doh.c 28 KB

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