doh.c 28 KB

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