doh.c 28 KB

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