2
0

doh.c 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006
  1. /***************************************************************************
  2. * _ _ ____ _
  3. * Project ___| | | | _ \| |
  4. * / __| | | | |_) | |
  5. * | (__| |_| | _ <| |___
  6. * \___|\___/|_| \_\_____|
  7. *
  8. * Copyright (C) Daniel Stenberg, <daniel@haxx.se>, et al.
  9. *
  10. * This software is licensed as described in the file COPYING, which
  11. * you should have received as part of this distribution. The terms
  12. * are also available at https://curl.se/docs/copyright.html.
  13. *
  14. * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  15. * copies of the Software, and permit persons to whom the Software is
  16. * furnished to do so, under the terms of the COPYING file.
  17. *
  18. * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  19. * KIND, either express or implied.
  20. *
  21. * SPDX-License-Identifier: curl
  22. *
  23. ***************************************************************************/
  24. #include "curl_setup.h"
  25. #ifndef CURL_DISABLE_DOH
  26. #include "urldata.h"
  27. #include "curl_addrinfo.h"
  28. #include "doh.h"
  29. #include "sendf.h"
  30. #include "multiif.h"
  31. #include "url.h"
  32. #include "share.h"
  33. #include "curl_base64.h"
  34. #include "connect.h"
  35. #include "strdup.h"
  36. #include "dynbuf.h"
  37. /* The last 3 #include files should be in this order */
  38. #include "curl_printf.h"
  39. #include "curl_memory.h"
  40. #include "memdebug.h"
  41. #define DNS_CLASS_IN 0x01
  42. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  43. static const char * const errors[]={
  44. "",
  45. "Bad label",
  46. "Out of range",
  47. "Label loop",
  48. "Too small",
  49. "Out of memory",
  50. "RDATA length",
  51. "Malformat",
  52. "Bad RCODE",
  53. "Unexpected TYPE",
  54. "Unexpected CLASS",
  55. "No content",
  56. "Bad ID",
  57. "Name too long"
  58. };
  59. static const char *doh_strerror(DOHcode code)
  60. {
  61. if((code >= DOH_OK) && (code <= DOH_DNS_NAME_TOO_LONG))
  62. return errors[code];
  63. return "bad error code";
  64. }
  65. struct curl_trc_feat Curl_doh_trc = {
  66. "DoH",
  67. CURL_LOG_LVL_NONE,
  68. };
  69. #endif /* !CURL_DISABLE_VERBOSE_STRINGS */
  70. /* @unittest 1655
  71. */
  72. UNITTEST DOHcode doh_encode(const char *host,
  73. DNStype dnstype,
  74. unsigned char *dnsp, /* buffer */
  75. size_t len, /* buffer size */
  76. size_t *olen) /* output length */
  77. {
  78. const size_t hostlen = strlen(host);
  79. unsigned char *orig = dnsp;
  80. const char *hostp = host;
  81. /* The expected output length is 16 bytes more than the length of
  82. * the QNAME-encoding of the host name.
  83. *
  84. * A valid DNS name may not contain a zero-length label, except at
  85. * the end. For this reason, a name beginning with a dot, or
  86. * containing a sequence of two or more consecutive dots, is invalid
  87. * and cannot be encoded as a QNAME.
  88. *
  89. * If the host name ends with a trailing dot, the corresponding
  90. * QNAME-encoding is one byte longer than the host name. If (as is
  91. * also valid) the hostname is shortened by the omission of the
  92. * trailing dot, then its QNAME-encoding will be two bytes longer
  93. * than the host name.
  94. *
  95. * Each [ label, dot ] pair is encoded as [ length, label ],
  96. * preserving overall length. A final [ label ] without a dot is
  97. * also encoded as [ length, label ], increasing overall length
  98. * by one. The encoding is completed by appending a zero byte,
  99. * representing the zero-length root label, again increasing
  100. * the overall length by one.
  101. */
  102. size_t expected_len;
  103. DEBUGASSERT(hostlen);
  104. expected_len = 12 + 1 + hostlen + 4;
  105. if(host[hostlen-1]!='.')
  106. expected_len++;
  107. if(expected_len > (256 + 16)) /* RFCs 1034, 1035 */
  108. return DOH_DNS_NAME_TOO_LONG;
  109. if(len < expected_len)
  110. return DOH_TOO_SMALL_BUFFER;
  111. *dnsp++ = 0; /* 16 bit id */
  112. *dnsp++ = 0;
  113. *dnsp++ = 0x01; /* |QR| Opcode |AA|TC|RD| Set the RD bit */
  114. *dnsp++ = '\0'; /* |RA| Z | RCODE | */
  115. *dnsp++ = '\0';
  116. *dnsp++ = 1; /* QDCOUNT (number of entries in the question section) */
  117. *dnsp++ = '\0';
  118. *dnsp++ = '\0'; /* ANCOUNT */
  119. *dnsp++ = '\0';
  120. *dnsp++ = '\0'; /* NSCOUNT */
  121. *dnsp++ = '\0';
  122. *dnsp++ = '\0'; /* ARCOUNT */
  123. /* encode each label and store it in the QNAME */
  124. while(*hostp) {
  125. size_t labellen;
  126. char *dot = strchr(hostp, '.');
  127. if(dot)
  128. labellen = dot - hostp;
  129. else
  130. labellen = strlen(hostp);
  131. if((labellen > 63) || (!labellen)) {
  132. /* label is too long or too short, error out */
  133. *olen = 0;
  134. return DOH_DNS_BAD_LABEL;
  135. }
  136. /* label is non-empty, process it */
  137. *dnsp++ = (unsigned char)labellen;
  138. memcpy(dnsp, hostp, labellen);
  139. dnsp += labellen;
  140. hostp += labellen;
  141. /* advance past dot, but only if there is one */
  142. if(dot)
  143. hostp++;
  144. } /* next label */
  145. *dnsp++ = 0; /* append zero-length label for root */
  146. /* There are assigned TYPE codes beyond 255: use range [1..65535] */
  147. *dnsp++ = (unsigned char)(255 & (dnstype>>8)); /* upper 8 bit TYPE */
  148. *dnsp++ = (unsigned char)(255 & dnstype); /* lower 8 bit TYPE */
  149. *dnsp++ = '\0'; /* upper 8 bit CLASS */
  150. *dnsp++ = DNS_CLASS_IN; /* IN - "the Internet" */
  151. *olen = dnsp - orig;
  152. /* verify that our estimation of length is valid, since
  153. * this has led to buffer overflows in this function */
  154. DEBUGASSERT(*olen == expected_len);
  155. return DOH_OK;
  156. }
  157. static size_t
  158. doh_write_cb(const void *contents, size_t size, size_t nmemb, void *userp)
  159. {
  160. size_t realsize = size * nmemb;
  161. struct dynbuf *mem = (struct dynbuf *)userp;
  162. if(Curl_dyn_addn(mem, contents, realsize))
  163. return 0;
  164. return realsize;
  165. }
  166. /* called from multi.c when this DoH transfer is complete */
  167. static int doh_done(struct Curl_easy *doh, CURLcode result)
  168. {
  169. struct Curl_easy *data = doh->set.dohfor;
  170. struct dohdata *dohp = data->req.doh;
  171. /* so one of the DoH request done for the 'data' transfer is now complete! */
  172. dohp->pending--;
  173. infof(doh, "a DoH request is completed, %u to go", dohp->pending);
  174. if(result)
  175. infof(doh, "DoH request %s", curl_easy_strerror(result));
  176. if(!dohp->pending) {
  177. /* DoH completed */
  178. curl_slist_free_all(dohp->headers);
  179. dohp->headers = NULL;
  180. Curl_expire(data, 0, EXPIRE_RUN_NOW);
  181. }
  182. return 0;
  183. }
  184. #define ERROR_CHECK_SETOPT(x,y) \
  185. do { \
  186. result = curl_easy_setopt(doh, x, y); \
  187. if(result && \
  188. result != CURLE_NOT_BUILT_IN && \
  189. result != CURLE_UNKNOWN_OPTION) \
  190. goto error; \
  191. } while(0)
  192. static CURLcode dohprobe(struct Curl_easy *data,
  193. struct dnsprobe *p, DNStype dnstype,
  194. const char *host,
  195. const char *url, CURLM *multi,
  196. struct curl_slist *headers)
  197. {
  198. struct Curl_easy *doh = NULL;
  199. CURLcode result = CURLE_OK;
  200. timediff_t timeout_ms;
  201. DOHcode d = doh_encode(host, dnstype, p->dohbuffer, sizeof(p->dohbuffer),
  202. &p->dohlen);
  203. if(d) {
  204. failf(data, "Failed to encode DoH packet [%d]", d);
  205. return CURLE_OUT_OF_MEMORY;
  206. }
  207. p->dnstype = dnstype;
  208. Curl_dyn_init(&p->serverdoh, DYN_DOH_RESPONSE);
  209. timeout_ms = Curl_timeleft(data, NULL, TRUE);
  210. if(timeout_ms <= 0) {
  211. result = CURLE_OPERATION_TIMEDOUT;
  212. goto error;
  213. }
  214. /* Curl_open() is the internal version of curl_easy_init() */
  215. result = Curl_open(&doh);
  216. if(!result) {
  217. /* pass in the struct pointer via a local variable to please coverity and
  218. the gcc typecheck helpers */
  219. struct dynbuf *resp = &p->serverdoh;
  220. doh->state.internal = true;
  221. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  222. doh->state.feat = &Curl_doh_trc;
  223. #endif
  224. ERROR_CHECK_SETOPT(CURLOPT_URL, url);
  225. ERROR_CHECK_SETOPT(CURLOPT_DEFAULT_PROTOCOL, "https");
  226. ERROR_CHECK_SETOPT(CURLOPT_WRITEFUNCTION, doh_write_cb);
  227. ERROR_CHECK_SETOPT(CURLOPT_WRITEDATA, resp);
  228. ERROR_CHECK_SETOPT(CURLOPT_POSTFIELDS, p->dohbuffer);
  229. ERROR_CHECK_SETOPT(CURLOPT_POSTFIELDSIZE, (long)p->dohlen);
  230. ERROR_CHECK_SETOPT(CURLOPT_HTTPHEADER, headers);
  231. #ifdef USE_HTTP2
  232. ERROR_CHECK_SETOPT(CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2TLS);
  233. ERROR_CHECK_SETOPT(CURLOPT_PIPEWAIT, 1L);
  234. #endif
  235. #ifndef CURLDEBUG
  236. /* enforce HTTPS if not debug */
  237. ERROR_CHECK_SETOPT(CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);
  238. #else
  239. /* in debug mode, also allow http */
  240. ERROR_CHECK_SETOPT(CURLOPT_PROTOCOLS, CURLPROTO_HTTP|CURLPROTO_HTTPS);
  241. #endif
  242. ERROR_CHECK_SETOPT(CURLOPT_TIMEOUT_MS, (long)timeout_ms);
  243. ERROR_CHECK_SETOPT(CURLOPT_SHARE, data->share);
  244. if(data->set.err && data->set.err != stderr)
  245. ERROR_CHECK_SETOPT(CURLOPT_STDERR, data->set.err);
  246. if(Curl_trc_ft_is_verbose(data, &Curl_doh_trc))
  247. ERROR_CHECK_SETOPT(CURLOPT_VERBOSE, 1L);
  248. if(data->set.no_signal)
  249. ERROR_CHECK_SETOPT(CURLOPT_NOSIGNAL, 1L);
  250. ERROR_CHECK_SETOPT(CURLOPT_SSL_VERIFYHOST,
  251. data->set.doh_verifyhost ? 2L : 0L);
  252. ERROR_CHECK_SETOPT(CURLOPT_SSL_VERIFYPEER,
  253. data->set.doh_verifypeer ? 1L : 0L);
  254. ERROR_CHECK_SETOPT(CURLOPT_SSL_VERIFYSTATUS,
  255. data->set.doh_verifystatus ? 1L : 0L);
  256. /* Inherit *some* SSL options from the user's transfer. This is a
  257. best-guess as to which options are needed for compatibility. #3661
  258. Note DoH does not inherit the user's proxy server so proxy SSL settings
  259. have no effect and are not inherited. If that changes then two new
  260. options should be added to check doh proxy insecure separately,
  261. CURLOPT_DOH_PROXY_SSL_VERIFYHOST and CURLOPT_DOH_PROXY_SSL_VERIFYPEER.
  262. */
  263. if(data->set.ssl.falsestart)
  264. ERROR_CHECK_SETOPT(CURLOPT_SSL_FALSESTART, 1L);
  265. if(data->set.str[STRING_SSL_CAFILE]) {
  266. ERROR_CHECK_SETOPT(CURLOPT_CAINFO,
  267. data->set.str[STRING_SSL_CAFILE]);
  268. }
  269. if(data->set.blobs[BLOB_CAINFO]) {
  270. ERROR_CHECK_SETOPT(CURLOPT_CAINFO_BLOB,
  271. data->set.blobs[BLOB_CAINFO]);
  272. }
  273. if(data->set.str[STRING_SSL_CAPATH]) {
  274. ERROR_CHECK_SETOPT(CURLOPT_CAPATH,
  275. data->set.str[STRING_SSL_CAPATH]);
  276. }
  277. if(data->set.str[STRING_SSL_CRLFILE]) {
  278. ERROR_CHECK_SETOPT(CURLOPT_CRLFILE,
  279. data->set.str[STRING_SSL_CRLFILE]);
  280. }
  281. if(data->set.ssl.certinfo)
  282. ERROR_CHECK_SETOPT(CURLOPT_CERTINFO, 1L);
  283. if(data->set.ssl.fsslctx)
  284. ERROR_CHECK_SETOPT(CURLOPT_SSL_CTX_FUNCTION, data->set.ssl.fsslctx);
  285. if(data->set.ssl.fsslctxp)
  286. ERROR_CHECK_SETOPT(CURLOPT_SSL_CTX_DATA, data->set.ssl.fsslctxp);
  287. if(data->set.fdebug)
  288. ERROR_CHECK_SETOPT(CURLOPT_DEBUGFUNCTION, data->set.fdebug);
  289. if(data->set.debugdata)
  290. ERROR_CHECK_SETOPT(CURLOPT_DEBUGDATA, data->set.debugdata);
  291. if(data->set.str[STRING_SSL_EC_CURVES]) {
  292. ERROR_CHECK_SETOPT(CURLOPT_SSL_EC_CURVES,
  293. data->set.str[STRING_SSL_EC_CURVES]);
  294. }
  295. {
  296. long mask =
  297. (data->set.ssl.enable_beast ?
  298. CURLSSLOPT_ALLOW_BEAST : 0) |
  299. (data->set.ssl.no_revoke ?
  300. CURLSSLOPT_NO_REVOKE : 0) |
  301. (data->set.ssl.no_partialchain ?
  302. CURLSSLOPT_NO_PARTIALCHAIN : 0) |
  303. (data->set.ssl.revoke_best_effort ?
  304. CURLSSLOPT_REVOKE_BEST_EFFORT : 0) |
  305. (data->set.ssl.native_ca_store ?
  306. CURLSSLOPT_NATIVE_CA : 0) |
  307. (data->set.ssl.auto_client_cert ?
  308. CURLSSLOPT_AUTO_CLIENT_CERT : 0);
  309. (void)curl_easy_setopt(doh, CURLOPT_SSL_OPTIONS, mask);
  310. }
  311. doh->set.fmultidone = doh_done;
  312. doh->set.dohfor = data; /* identify for which transfer this is done */
  313. p->easy = doh;
  314. /* DoH handles must not inherit private_data. The handles may be passed to
  315. the user via callbacks and the user will be able to identify them as
  316. internal handles because private data is not set. The user can then set
  317. private_data via CURLOPT_PRIVATE if they so choose. */
  318. DEBUGASSERT(!doh->set.private_data);
  319. if(curl_multi_add_handle(multi, doh))
  320. goto error;
  321. }
  322. else
  323. goto error;
  324. return CURLE_OK;
  325. error:
  326. Curl_close(&doh);
  327. return result;
  328. }
  329. /*
  330. * Curl_doh() resolves a name using DoH. It resolves a name and returns a
  331. * 'Curl_addrinfo *' with the address information.
  332. */
  333. struct Curl_addrinfo *Curl_doh(struct Curl_easy *data,
  334. const char *hostname,
  335. int port,
  336. int *waitp)
  337. {
  338. CURLcode result = CURLE_OK;
  339. int slot;
  340. struct dohdata *dohp;
  341. struct connectdata *conn = data->conn;
  342. *waitp = FALSE;
  343. (void)hostname;
  344. (void)port;
  345. DEBUGASSERT(!data->req.doh);
  346. DEBUGASSERT(conn);
  347. /* start clean, consider allocating this struct on demand */
  348. dohp = data->req.doh = calloc(1, sizeof(struct dohdata));
  349. if(!dohp)
  350. return NULL;
  351. conn->bits.doh = TRUE;
  352. dohp->host = hostname;
  353. dohp->port = port;
  354. dohp->headers =
  355. curl_slist_append(NULL,
  356. "Content-Type: application/dns-message");
  357. if(!dohp->headers)
  358. goto error;
  359. /* create IPv4 DoH request */
  360. result = dohprobe(data, &dohp->probe[DOH_PROBE_SLOT_IPADDR_V4],
  361. DNS_TYPE_A, hostname, data->set.str[STRING_DOH],
  362. data->multi, dohp->headers);
  363. if(result)
  364. goto error;
  365. dohp->pending++;
  366. #ifdef ENABLE_IPV6
  367. if((conn->ip_version != CURL_IPRESOLVE_V4) && Curl_ipv6works(data)) {
  368. /* create IPv6 DoH request */
  369. result = dohprobe(data, &dohp->probe[DOH_PROBE_SLOT_IPADDR_V6],
  370. DNS_TYPE_AAAA, hostname, data->set.str[STRING_DOH],
  371. data->multi, dohp->headers);
  372. if(result)
  373. goto error;
  374. dohp->pending++;
  375. }
  376. #endif
  377. *waitp = TRUE; /* this never returns synchronously */
  378. return NULL;
  379. error:
  380. curl_slist_free_all(dohp->headers);
  381. data->req.doh->headers = NULL;
  382. for(slot = 0; slot < DOH_PROBE_SLOTS; slot++) {
  383. (void)curl_multi_remove_handle(data->multi, dohp->probe[slot].easy);
  384. Curl_close(&dohp->probe[slot].easy);
  385. }
  386. Curl_safefree(data->req.doh);
  387. return NULL;
  388. }
  389. static DOHcode skipqname(const unsigned char *doh, size_t dohlen,
  390. unsigned int *indexp)
  391. {
  392. unsigned char length;
  393. do {
  394. if(dohlen < (*indexp + 1))
  395. return DOH_DNS_OUT_OF_RANGE;
  396. length = doh[*indexp];
  397. if((length & 0xc0) == 0xc0) {
  398. /* name pointer, advance over it and be done */
  399. if(dohlen < (*indexp + 2))
  400. return DOH_DNS_OUT_OF_RANGE;
  401. *indexp += 2;
  402. break;
  403. }
  404. if(length & 0xc0)
  405. return DOH_DNS_BAD_LABEL;
  406. if(dohlen < (*indexp + 1 + length))
  407. return DOH_DNS_OUT_OF_RANGE;
  408. *indexp += (unsigned int)(1 + length);
  409. } while(length);
  410. return DOH_OK;
  411. }
  412. static unsigned short get16bit(const unsigned char *doh, int index)
  413. {
  414. return (unsigned short)((doh[index] << 8) | doh[index + 1]);
  415. }
  416. static unsigned int get32bit(const unsigned char *doh, int index)
  417. {
  418. /* make clang and gcc optimize this to bswap by incrementing
  419. the pointer first. */
  420. doh += index;
  421. /* avoid undefined behavior by casting to unsigned before shifting
  422. 24 bits, possibly into the sign bit. codegen is same, but
  423. ub sanitizer won't be upset */
  424. return ((unsigned)doh[0] << 24) | ((unsigned)doh[1] << 16) |
  425. ((unsigned)doh[2] << 8) | doh[3];
  426. }
  427. static DOHcode store_a(const unsigned char *doh, int index, struct dohentry *d)
  428. {
  429. /* silently ignore addresses over the limit */
  430. if(d->numaddr < DOH_MAX_ADDR) {
  431. struct dohaddr *a = &d->addr[d->numaddr];
  432. a->type = DNS_TYPE_A;
  433. memcpy(&a->ip.v4, &doh[index], 4);
  434. d->numaddr++;
  435. }
  436. return DOH_OK;
  437. }
  438. static DOHcode store_aaaa(const unsigned char *doh,
  439. int index,
  440. struct dohentry *d)
  441. {
  442. /* silently ignore addresses over the limit */
  443. if(d->numaddr < DOH_MAX_ADDR) {
  444. struct dohaddr *a = &d->addr[d->numaddr];
  445. a->type = DNS_TYPE_AAAA;
  446. memcpy(&a->ip.v6, &doh[index], 16);
  447. d->numaddr++;
  448. }
  449. return DOH_OK;
  450. }
  451. static DOHcode store_cname(const unsigned char *doh,
  452. size_t dohlen,
  453. unsigned int index,
  454. struct dohentry *d)
  455. {
  456. struct dynbuf *c;
  457. unsigned int loop = 128; /* a valid DNS name can never loop this much */
  458. unsigned char length;
  459. if(d->numcname == DOH_MAX_CNAME)
  460. return DOH_OK; /* skip! */
  461. c = &d->cname[d->numcname++];
  462. do {
  463. if(index >= dohlen)
  464. return DOH_DNS_OUT_OF_RANGE;
  465. length = doh[index];
  466. if((length & 0xc0) == 0xc0) {
  467. int newpos;
  468. /* name pointer, get the new offset (14 bits) */
  469. if((index + 1) >= dohlen)
  470. return DOH_DNS_OUT_OF_RANGE;
  471. /* move to the new index */
  472. newpos = (length & 0x3f) << 8 | doh[index + 1];
  473. index = newpos;
  474. continue;
  475. }
  476. else if(length & 0xc0)
  477. return DOH_DNS_BAD_LABEL; /* bad input */
  478. else
  479. index++;
  480. if(length) {
  481. if(Curl_dyn_len(c)) {
  482. if(Curl_dyn_addn(c, STRCONST(".")))
  483. return DOH_OUT_OF_MEM;
  484. }
  485. if((index + length) > dohlen)
  486. return DOH_DNS_BAD_LABEL;
  487. if(Curl_dyn_addn(c, &doh[index], length))
  488. return DOH_OUT_OF_MEM;
  489. index += length;
  490. }
  491. } while(length && --loop);
  492. if(!loop)
  493. return DOH_DNS_LABEL_LOOP;
  494. return DOH_OK;
  495. }
  496. static DOHcode rdata(const unsigned char *doh,
  497. size_t dohlen,
  498. unsigned short rdlength,
  499. unsigned short type,
  500. int index,
  501. struct dohentry *d)
  502. {
  503. /* RDATA
  504. - A (TYPE 1): 4 bytes
  505. - AAAA (TYPE 28): 16 bytes
  506. - NS (TYPE 2): N bytes */
  507. DOHcode rc;
  508. switch(type) {
  509. case DNS_TYPE_A:
  510. if(rdlength != 4)
  511. return DOH_DNS_RDATA_LEN;
  512. rc = store_a(doh, index, d);
  513. if(rc)
  514. return rc;
  515. break;
  516. case DNS_TYPE_AAAA:
  517. if(rdlength != 16)
  518. return DOH_DNS_RDATA_LEN;
  519. rc = store_aaaa(doh, index, d);
  520. if(rc)
  521. return rc;
  522. break;
  523. case DNS_TYPE_CNAME:
  524. rc = store_cname(doh, dohlen, index, d);
  525. if(rc)
  526. return rc;
  527. break;
  528. case DNS_TYPE_DNAME:
  529. /* explicit for clarity; just skip; rely on synthesized CNAME */
  530. break;
  531. default:
  532. /* unsupported type, just skip it */
  533. break;
  534. }
  535. return DOH_OK;
  536. }
  537. UNITTEST void de_init(struct dohentry *de)
  538. {
  539. int i;
  540. memset(de, 0, sizeof(*de));
  541. de->ttl = INT_MAX;
  542. for(i = 0; i < DOH_MAX_CNAME; i++)
  543. Curl_dyn_init(&de->cname[i], DYN_DOH_CNAME);
  544. }
  545. UNITTEST DOHcode doh_decode(const unsigned char *doh,
  546. size_t dohlen,
  547. DNStype dnstype,
  548. struct dohentry *d)
  549. {
  550. unsigned char rcode;
  551. unsigned short qdcount;
  552. unsigned short ancount;
  553. unsigned short type = 0;
  554. unsigned short rdlength;
  555. unsigned short nscount;
  556. unsigned short arcount;
  557. unsigned int index = 12;
  558. DOHcode rc;
  559. if(dohlen < 12)
  560. return DOH_TOO_SMALL_BUFFER; /* too small */
  561. if(!doh || doh[0] || doh[1])
  562. return DOH_DNS_BAD_ID; /* bad ID */
  563. rcode = doh[3] & 0x0f;
  564. if(rcode)
  565. return DOH_DNS_BAD_RCODE; /* bad rcode */
  566. qdcount = get16bit(doh, 4);
  567. while(qdcount) {
  568. rc = skipqname(doh, dohlen, &index);
  569. if(rc)
  570. return rc; /* bad qname */
  571. if(dohlen < (index + 4))
  572. return DOH_DNS_OUT_OF_RANGE;
  573. index += 4; /* skip question's type and class */
  574. qdcount--;
  575. }
  576. ancount = get16bit(doh, 6);
  577. while(ancount) {
  578. unsigned short class;
  579. unsigned int ttl;
  580. rc = skipqname(doh, dohlen, &index);
  581. if(rc)
  582. return rc; /* bad qname */
  583. if(dohlen < (index + 2))
  584. return DOH_DNS_OUT_OF_RANGE;
  585. type = get16bit(doh, index);
  586. if((type != DNS_TYPE_CNAME) /* may be synthesized from DNAME */
  587. && (type != DNS_TYPE_DNAME) /* if present, accept and ignore */
  588. && (type != dnstype))
  589. /* Not the same type as was asked for nor CNAME nor DNAME */
  590. return DOH_DNS_UNEXPECTED_TYPE;
  591. index += 2;
  592. if(dohlen < (index + 2))
  593. return DOH_DNS_OUT_OF_RANGE;
  594. class = get16bit(doh, index);
  595. if(DNS_CLASS_IN != class)
  596. return DOH_DNS_UNEXPECTED_CLASS; /* unsupported */
  597. index += 2;
  598. if(dohlen < (index + 4))
  599. return DOH_DNS_OUT_OF_RANGE;
  600. ttl = get32bit(doh, index);
  601. if(ttl < d->ttl)
  602. d->ttl = ttl;
  603. index += 4;
  604. if(dohlen < (index + 2))
  605. return DOH_DNS_OUT_OF_RANGE;
  606. rdlength = get16bit(doh, index);
  607. index += 2;
  608. if(dohlen < (index + rdlength))
  609. return DOH_DNS_OUT_OF_RANGE;
  610. rc = rdata(doh, dohlen, rdlength, type, index, d);
  611. if(rc)
  612. return rc; /* bad rdata */
  613. index += rdlength;
  614. ancount--;
  615. }
  616. nscount = get16bit(doh, 8);
  617. while(nscount) {
  618. rc = skipqname(doh, dohlen, &index);
  619. if(rc)
  620. return rc; /* bad qname */
  621. if(dohlen < (index + 8))
  622. return DOH_DNS_OUT_OF_RANGE;
  623. index += 2 + 2 + 4; /* type, class and ttl */
  624. if(dohlen < (index + 2))
  625. return DOH_DNS_OUT_OF_RANGE;
  626. rdlength = get16bit(doh, index);
  627. index += 2;
  628. if(dohlen < (index + rdlength))
  629. return DOH_DNS_OUT_OF_RANGE;
  630. index += rdlength;
  631. nscount--;
  632. }
  633. arcount = get16bit(doh, 10);
  634. while(arcount) {
  635. rc = skipqname(doh, dohlen, &index);
  636. if(rc)
  637. return rc; /* bad qname */
  638. if(dohlen < (index + 8))
  639. return DOH_DNS_OUT_OF_RANGE;
  640. index += 2 + 2 + 4; /* type, class and ttl */
  641. if(dohlen < (index + 2))
  642. return DOH_DNS_OUT_OF_RANGE;
  643. rdlength = get16bit(doh, index);
  644. index += 2;
  645. if(dohlen < (index + rdlength))
  646. return DOH_DNS_OUT_OF_RANGE;
  647. index += rdlength;
  648. arcount--;
  649. }
  650. if(index != dohlen)
  651. return DOH_DNS_MALFORMAT; /* something is wrong */
  652. if((type != DNS_TYPE_NS) && !d->numcname && !d->numaddr)
  653. /* nothing stored! */
  654. return DOH_NO_CONTENT;
  655. return DOH_OK; /* ok */
  656. }
  657. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  658. static void showdoh(struct Curl_easy *data,
  659. const struct dohentry *d)
  660. {
  661. int i;
  662. infof(data, "[DoH] TTL: %u seconds", d->ttl);
  663. for(i = 0; i < d->numaddr; i++) {
  664. const struct dohaddr *a = &d->addr[i];
  665. if(a->type == DNS_TYPE_A) {
  666. infof(data, "[DoH] A: %u.%u.%u.%u",
  667. a->ip.v4[0], a->ip.v4[1],
  668. a->ip.v4[2], a->ip.v4[3]);
  669. }
  670. else if(a->type == DNS_TYPE_AAAA) {
  671. int j;
  672. char buffer[128];
  673. char *ptr;
  674. size_t len;
  675. len = msnprintf(buffer, 128, "[DoH] AAAA: ");
  676. ptr = &buffer[len];
  677. len = sizeof(buffer) - len;
  678. for(j = 0; j < 16; j += 2) {
  679. size_t l;
  680. msnprintf(ptr, len, "%s%02x%02x", j?":":"", d->addr[i].ip.v6[j],
  681. d->addr[i].ip.v6[j + 1]);
  682. l = strlen(ptr);
  683. len -= l;
  684. ptr += l;
  685. }
  686. infof(data, "%s", buffer);
  687. }
  688. }
  689. for(i = 0; i < d->numcname; i++) {
  690. infof(data, "CNAME: %s", Curl_dyn_ptr(&d->cname[i]));
  691. }
  692. }
  693. #else
  694. #define showdoh(x,y)
  695. #endif
  696. /*
  697. * doh2ai()
  698. *
  699. * This function returns a pointer to the first element of a newly allocated
  700. * Curl_addrinfo struct linked list filled with the data from a set of DoH
  701. * lookups. Curl_addrinfo is meant to work like the addrinfo struct does for
  702. * a IPv6 stack, but usable also for IPv4, all hosts and environments.
  703. *
  704. * The memory allocated by this function *MUST* be free'd later on calling
  705. * Curl_freeaddrinfo(). For each successful call to this function there
  706. * must be an associated call later to Curl_freeaddrinfo().
  707. */
  708. static CURLcode doh2ai(const struct dohentry *de, const char *hostname,
  709. int port, struct Curl_addrinfo **aip)
  710. {
  711. struct Curl_addrinfo *ai;
  712. struct Curl_addrinfo *prevai = NULL;
  713. struct Curl_addrinfo *firstai = NULL;
  714. struct sockaddr_in *addr;
  715. #ifdef ENABLE_IPV6
  716. struct sockaddr_in6 *addr6;
  717. #endif
  718. CURLcode result = CURLE_OK;
  719. int i;
  720. size_t hostlen = strlen(hostname) + 1; /* include null-terminator */
  721. DEBUGASSERT(de);
  722. if(!de->numaddr)
  723. return CURLE_COULDNT_RESOLVE_HOST;
  724. for(i = 0; i < de->numaddr; i++) {
  725. size_t ss_size;
  726. CURL_SA_FAMILY_T addrtype;
  727. if(de->addr[i].type == DNS_TYPE_AAAA) {
  728. #ifndef ENABLE_IPV6
  729. /* we can't handle IPv6 addresses */
  730. continue;
  731. #else
  732. ss_size = sizeof(struct sockaddr_in6);
  733. addrtype = AF_INET6;
  734. #endif
  735. }
  736. else {
  737. ss_size = sizeof(struct sockaddr_in);
  738. addrtype = AF_INET;
  739. }
  740. ai = calloc(1, sizeof(struct Curl_addrinfo) + ss_size + hostlen);
  741. if(!ai) {
  742. result = CURLE_OUT_OF_MEMORY;
  743. break;
  744. }
  745. ai->ai_addr = (void *)((char *)ai + sizeof(struct Curl_addrinfo));
  746. ai->ai_canonname = (void *)((char *)ai->ai_addr + ss_size);
  747. memcpy(ai->ai_canonname, hostname, hostlen);
  748. if(!firstai)
  749. /* store the pointer we want to return from this function */
  750. firstai = ai;
  751. if(prevai)
  752. /* make the previous entry point to this */
  753. prevai->ai_next = ai;
  754. ai->ai_family = addrtype;
  755. /* we return all names as STREAM, so when using this address for TFTP
  756. the type must be ignored and conn->socktype be used instead! */
  757. ai->ai_socktype = SOCK_STREAM;
  758. ai->ai_addrlen = (curl_socklen_t)ss_size;
  759. /* leave the rest of the struct filled with zero */
  760. switch(ai->ai_family) {
  761. case AF_INET:
  762. addr = (void *)ai->ai_addr; /* storage area for this info */
  763. DEBUGASSERT(sizeof(struct in_addr) == sizeof(de->addr[i].ip.v4));
  764. memcpy(&addr->sin_addr, &de->addr[i].ip.v4, sizeof(struct in_addr));
  765. addr->sin_family = addrtype;
  766. addr->sin_port = htons((unsigned short)port);
  767. break;
  768. #ifdef ENABLE_IPV6
  769. case AF_INET6:
  770. addr6 = (void *)ai->ai_addr; /* storage area for this info */
  771. DEBUGASSERT(sizeof(struct in6_addr) == sizeof(de->addr[i].ip.v6));
  772. memcpy(&addr6->sin6_addr, &de->addr[i].ip.v6, sizeof(struct in6_addr));
  773. addr6->sin6_family = addrtype;
  774. addr6->sin6_port = htons((unsigned short)port);
  775. break;
  776. #endif
  777. }
  778. prevai = ai;
  779. }
  780. if(result) {
  781. Curl_freeaddrinfo(firstai);
  782. firstai = NULL;
  783. }
  784. *aip = firstai;
  785. return result;
  786. }
  787. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  788. static const char *type2name(DNStype dnstype)
  789. {
  790. return (dnstype == DNS_TYPE_A)?"A":"AAAA";
  791. }
  792. #endif
  793. UNITTEST void de_cleanup(struct dohentry *d)
  794. {
  795. int i = 0;
  796. for(i = 0; i < d->numcname; i++) {
  797. Curl_dyn_free(&d->cname[i]);
  798. }
  799. }
  800. CURLcode Curl_doh_is_resolved(struct Curl_easy *data,
  801. struct Curl_dns_entry **dnsp)
  802. {
  803. CURLcode result;
  804. struct dohdata *dohp = data->req.doh;
  805. *dnsp = NULL; /* defaults to no response */
  806. if(!dohp)
  807. return CURLE_OUT_OF_MEMORY;
  808. if(!dohp->probe[DOH_PROBE_SLOT_IPADDR_V4].easy &&
  809. !dohp->probe[DOH_PROBE_SLOT_IPADDR_V6].easy) {
  810. failf(data, "Could not DoH-resolve: %s", data->state.async.hostname);
  811. return CONN_IS_PROXIED(data->conn)?CURLE_COULDNT_RESOLVE_PROXY:
  812. CURLE_COULDNT_RESOLVE_HOST;
  813. }
  814. else if(!dohp->pending) {
  815. DOHcode rc[DOH_PROBE_SLOTS] = {
  816. DOH_OK, DOH_OK
  817. };
  818. struct dohentry de;
  819. int slot;
  820. /* remove DoH handles from multi handle and close them */
  821. for(slot = 0; slot < DOH_PROBE_SLOTS; slot++) {
  822. curl_multi_remove_handle(data->multi, dohp->probe[slot].easy);
  823. Curl_close(&dohp->probe[slot].easy);
  824. }
  825. /* parse the responses, create the struct and return it! */
  826. de_init(&de);
  827. for(slot = 0; slot < DOH_PROBE_SLOTS; slot++) {
  828. struct dnsprobe *p = &dohp->probe[slot];
  829. if(!p->dnstype)
  830. continue;
  831. rc[slot] = doh_decode(Curl_dyn_uptr(&p->serverdoh),
  832. Curl_dyn_len(&p->serverdoh),
  833. p->dnstype,
  834. &de);
  835. Curl_dyn_free(&p->serverdoh);
  836. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  837. if(rc[slot]) {
  838. infof(data, "DoH: %s type %s for %s", doh_strerror(rc[slot]),
  839. type2name(p->dnstype), dohp->host);
  840. }
  841. #endif
  842. } /* next slot */
  843. result = CURLE_COULDNT_RESOLVE_HOST; /* until we know better */
  844. if(!rc[DOH_PROBE_SLOT_IPADDR_V4] || !rc[DOH_PROBE_SLOT_IPADDR_V6]) {
  845. /* we have an address, of one kind or other */
  846. struct Curl_dns_entry *dns;
  847. struct Curl_addrinfo *ai;
  848. if(Curl_trc_ft_is_verbose(data, &Curl_doh_trc)) {
  849. infof(data, "[DoH] Host name: %s", dohp->host);
  850. showdoh(data, &de);
  851. }
  852. result = doh2ai(&de, dohp->host, dohp->port, &ai);
  853. if(result) {
  854. de_cleanup(&de);
  855. return result;
  856. }
  857. if(data->share)
  858. Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
  859. /* we got a response, store it in the cache */
  860. dns = Curl_cache_addr(data, ai, dohp->host, 0, dohp->port);
  861. if(data->share)
  862. Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
  863. if(!dns) {
  864. /* returned failure, bail out nicely */
  865. Curl_freeaddrinfo(ai);
  866. }
  867. else {
  868. data->state.async.dns = dns;
  869. *dnsp = dns;
  870. result = CURLE_OK; /* address resolution OK */
  871. }
  872. } /* address processing done */
  873. /* Now process any build-specific attributes retrieved from DNS */
  874. /* All done */
  875. de_cleanup(&de);
  876. Curl_safefree(data->req.doh);
  877. return result;
  878. } /* !dohp->pending */
  879. /* else wait for pending DoH transactions to complete */
  880. return CURLE_OK;
  881. }
  882. #endif /* CURL_DISABLE_DOH */