2
0

doh.c 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984
  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. #ifdef ENABLE_IPV6
  356. if((conn->ip_version != CURL_IPRESOLVE_V4) && Curl_ipv6works(data)) {
  357. /* create IPv6 DoH request */
  358. result = dohprobe(data, &dohp->probe[DOH_PROBE_SLOT_IPADDR_V6],
  359. DNS_TYPE_AAAA, hostname, data->set.str[STRING_DOH],
  360. data->multi, dohp->headers);
  361. if(result)
  362. goto error;
  363. dohp->pending++;
  364. }
  365. #endif
  366. return NULL;
  367. error:
  368. curl_slist_free_all(dohp->headers);
  369. data->req.doh->headers = NULL;
  370. for(slot = 0; slot < DOH_PROBE_SLOTS; slot++) {
  371. Curl_close(&dohp->probe[slot].easy);
  372. }
  373. Curl_safefree(data->req.doh);
  374. return NULL;
  375. }
  376. static DOHcode skipqname(const unsigned char *doh, size_t dohlen,
  377. unsigned int *indexp)
  378. {
  379. unsigned char length;
  380. do {
  381. if(dohlen < (*indexp + 1))
  382. return DOH_DNS_OUT_OF_RANGE;
  383. length = doh[*indexp];
  384. if((length & 0xc0) == 0xc0) {
  385. /* name pointer, advance over it and be done */
  386. if(dohlen < (*indexp + 2))
  387. return DOH_DNS_OUT_OF_RANGE;
  388. *indexp += 2;
  389. break;
  390. }
  391. if(length & 0xc0)
  392. return DOH_DNS_BAD_LABEL;
  393. if(dohlen < (*indexp + 1 + length))
  394. return DOH_DNS_OUT_OF_RANGE;
  395. *indexp += 1 + length;
  396. } while(length);
  397. return DOH_OK;
  398. }
  399. static unsigned short get16bit(const unsigned char *doh, int index)
  400. {
  401. return (unsigned short)((doh[index] << 8) | doh[index + 1]);
  402. }
  403. static unsigned int get32bit(const unsigned char *doh, int index)
  404. {
  405. /* make clang and gcc optimize this to bswap by incrementing
  406. the pointer first. */
  407. doh += index;
  408. /* avoid undefined behavior by casting to unsigned before shifting
  409. 24 bits, possibly into the sign bit. codegen is same, but
  410. ub sanitizer won't be upset */
  411. return ( (unsigned)doh[0] << 24) | (doh[1] << 16) |(doh[2] << 8) | doh[3];
  412. }
  413. static DOHcode store_a(const unsigned char *doh, int index, struct dohentry *d)
  414. {
  415. /* silently ignore addresses over the limit */
  416. if(d->numaddr < DOH_MAX_ADDR) {
  417. struct dohaddr *a = &d->addr[d->numaddr];
  418. a->type = DNS_TYPE_A;
  419. memcpy(&a->ip.v4, &doh[index], 4);
  420. d->numaddr++;
  421. }
  422. return DOH_OK;
  423. }
  424. static DOHcode store_aaaa(const unsigned char *doh,
  425. int index,
  426. struct dohentry *d)
  427. {
  428. /* silently ignore addresses over the limit */
  429. if(d->numaddr < DOH_MAX_ADDR) {
  430. struct dohaddr *a = &d->addr[d->numaddr];
  431. a->type = DNS_TYPE_AAAA;
  432. memcpy(&a->ip.v6, &doh[index], 16);
  433. d->numaddr++;
  434. }
  435. return DOH_OK;
  436. }
  437. static DOHcode store_cname(const unsigned char *doh,
  438. size_t dohlen,
  439. unsigned int index,
  440. struct dohentry *d)
  441. {
  442. struct dynbuf *c;
  443. unsigned int loop = 128; /* a valid DNS name can never loop this much */
  444. unsigned char length;
  445. if(d->numcname == DOH_MAX_CNAME)
  446. return DOH_OK; /* skip! */
  447. c = &d->cname[d->numcname++];
  448. do {
  449. if(index >= dohlen)
  450. return DOH_DNS_OUT_OF_RANGE;
  451. length = doh[index];
  452. if((length & 0xc0) == 0xc0) {
  453. int newpos;
  454. /* name pointer, get the new offset (14 bits) */
  455. if((index + 1) >= dohlen)
  456. return DOH_DNS_OUT_OF_RANGE;
  457. /* move to the new index */
  458. newpos = (length & 0x3f) << 8 | doh[index + 1];
  459. index = newpos;
  460. continue;
  461. }
  462. else if(length & 0xc0)
  463. return DOH_DNS_BAD_LABEL; /* bad input */
  464. else
  465. index++;
  466. if(length) {
  467. if(Curl_dyn_len(c)) {
  468. if(Curl_dyn_addn(c, STRCONST(".")))
  469. return DOH_OUT_OF_MEM;
  470. }
  471. if((index + length) > dohlen)
  472. return DOH_DNS_BAD_LABEL;
  473. if(Curl_dyn_addn(c, &doh[index], length))
  474. return DOH_OUT_OF_MEM;
  475. index += length;
  476. }
  477. } while(length && --loop);
  478. if(!loop)
  479. return DOH_DNS_LABEL_LOOP;
  480. return DOH_OK;
  481. }
  482. static DOHcode rdata(const unsigned char *doh,
  483. size_t dohlen,
  484. unsigned short rdlength,
  485. unsigned short type,
  486. int index,
  487. struct dohentry *d)
  488. {
  489. /* RDATA
  490. - A (TYPE 1): 4 bytes
  491. - AAAA (TYPE 28): 16 bytes
  492. - NS (TYPE 2): N bytes */
  493. DOHcode rc;
  494. switch(type) {
  495. case DNS_TYPE_A:
  496. if(rdlength != 4)
  497. return DOH_DNS_RDATA_LEN;
  498. rc = store_a(doh, index, d);
  499. if(rc)
  500. return rc;
  501. break;
  502. case DNS_TYPE_AAAA:
  503. if(rdlength != 16)
  504. return DOH_DNS_RDATA_LEN;
  505. rc = store_aaaa(doh, index, d);
  506. if(rc)
  507. return rc;
  508. break;
  509. case DNS_TYPE_CNAME:
  510. rc = store_cname(doh, dohlen, index, d);
  511. if(rc)
  512. return rc;
  513. break;
  514. case DNS_TYPE_DNAME:
  515. /* explicit for clarity; just skip; rely on synthesized CNAME */
  516. break;
  517. default:
  518. /* unsupported type, just skip it */
  519. break;
  520. }
  521. return DOH_OK;
  522. }
  523. UNITTEST void de_init(struct dohentry *de)
  524. {
  525. int i;
  526. memset(de, 0, sizeof(*de));
  527. de->ttl = INT_MAX;
  528. for(i = 0; i < DOH_MAX_CNAME; i++)
  529. Curl_dyn_init(&de->cname[i], DYN_DOH_CNAME);
  530. }
  531. UNITTEST DOHcode doh_decode(const unsigned char *doh,
  532. size_t dohlen,
  533. DNStype dnstype,
  534. struct dohentry *d)
  535. {
  536. unsigned char rcode;
  537. unsigned short qdcount;
  538. unsigned short ancount;
  539. unsigned short type = 0;
  540. unsigned short rdlength;
  541. unsigned short nscount;
  542. unsigned short arcount;
  543. unsigned int index = 12;
  544. DOHcode rc;
  545. if(dohlen < 12)
  546. return DOH_TOO_SMALL_BUFFER; /* too small */
  547. if(!doh || doh[0] || doh[1])
  548. return DOH_DNS_BAD_ID; /* bad ID */
  549. rcode = doh[3] & 0x0f;
  550. if(rcode)
  551. return DOH_DNS_BAD_RCODE; /* bad rcode */
  552. qdcount = get16bit(doh, 4);
  553. while(qdcount) {
  554. rc = skipqname(doh, dohlen, &index);
  555. if(rc)
  556. return rc; /* bad qname */
  557. if(dohlen < (index + 4))
  558. return DOH_DNS_OUT_OF_RANGE;
  559. index += 4; /* skip question's type and class */
  560. qdcount--;
  561. }
  562. ancount = get16bit(doh, 6);
  563. while(ancount) {
  564. unsigned short class;
  565. unsigned int ttl;
  566. rc = skipqname(doh, dohlen, &index);
  567. if(rc)
  568. return rc; /* bad qname */
  569. if(dohlen < (index + 2))
  570. return DOH_DNS_OUT_OF_RANGE;
  571. type = get16bit(doh, index);
  572. if((type != DNS_TYPE_CNAME) /* may be synthesized from DNAME */
  573. && (type != DNS_TYPE_DNAME) /* if present, accept and ignore */
  574. && (type != dnstype))
  575. /* Not the same type as was asked for nor CNAME nor DNAME */
  576. return DOH_DNS_UNEXPECTED_TYPE;
  577. index += 2;
  578. if(dohlen < (index + 2))
  579. return DOH_DNS_OUT_OF_RANGE;
  580. class = get16bit(doh, index);
  581. if(DNS_CLASS_IN != class)
  582. return DOH_DNS_UNEXPECTED_CLASS; /* unsupported */
  583. index += 2;
  584. if(dohlen < (index + 4))
  585. return DOH_DNS_OUT_OF_RANGE;
  586. ttl = get32bit(doh, index);
  587. if(ttl < d->ttl)
  588. d->ttl = ttl;
  589. index += 4;
  590. if(dohlen < (index + 2))
  591. return DOH_DNS_OUT_OF_RANGE;
  592. rdlength = get16bit(doh, index);
  593. index += 2;
  594. if(dohlen < (index + rdlength))
  595. return DOH_DNS_OUT_OF_RANGE;
  596. rc = rdata(doh, dohlen, rdlength, type, index, d);
  597. if(rc)
  598. return rc; /* bad rdata */
  599. index += rdlength;
  600. ancount--;
  601. }
  602. nscount = get16bit(doh, 8);
  603. while(nscount) {
  604. rc = skipqname(doh, dohlen, &index);
  605. if(rc)
  606. return rc; /* bad qname */
  607. if(dohlen < (index + 8))
  608. return DOH_DNS_OUT_OF_RANGE;
  609. index += 2 + 2 + 4; /* type, class and ttl */
  610. if(dohlen < (index + 2))
  611. return DOH_DNS_OUT_OF_RANGE;
  612. rdlength = get16bit(doh, index);
  613. index += 2;
  614. if(dohlen < (index + rdlength))
  615. return DOH_DNS_OUT_OF_RANGE;
  616. index += rdlength;
  617. nscount--;
  618. }
  619. arcount = get16bit(doh, 10);
  620. while(arcount) {
  621. rc = skipqname(doh, dohlen, &index);
  622. if(rc)
  623. return rc; /* bad qname */
  624. if(dohlen < (index + 8))
  625. return DOH_DNS_OUT_OF_RANGE;
  626. index += 2 + 2 + 4; /* type, class and ttl */
  627. if(dohlen < (index + 2))
  628. return DOH_DNS_OUT_OF_RANGE;
  629. rdlength = get16bit(doh, index);
  630. index += 2;
  631. if(dohlen < (index + rdlength))
  632. return DOH_DNS_OUT_OF_RANGE;
  633. index += rdlength;
  634. arcount--;
  635. }
  636. if(index != dohlen)
  637. return DOH_DNS_MALFORMAT; /* something is wrong */
  638. if((type != DNS_TYPE_NS) && !d->numcname && !d->numaddr)
  639. /* nothing stored! */
  640. return DOH_NO_CONTENT;
  641. return DOH_OK; /* ok */
  642. }
  643. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  644. static void showdoh(struct Curl_easy *data,
  645. const struct dohentry *d)
  646. {
  647. int i;
  648. infof(data, "TTL: %u seconds", d->ttl);
  649. for(i = 0; i < d->numaddr; i++) {
  650. const struct dohaddr *a = &d->addr[i];
  651. if(a->type == DNS_TYPE_A) {
  652. infof(data, "DoH A: %u.%u.%u.%u",
  653. a->ip.v4[0], a->ip.v4[1],
  654. a->ip.v4[2], a->ip.v4[3]);
  655. }
  656. else if(a->type == DNS_TYPE_AAAA) {
  657. int j;
  658. char buffer[128];
  659. char *ptr;
  660. size_t len;
  661. msnprintf(buffer, 128, "DoH AAAA: ");
  662. ptr = &buffer[10];
  663. len = 118;
  664. for(j = 0; j < 16; j += 2) {
  665. size_t l;
  666. msnprintf(ptr, len, "%s%02x%02x", j?":":"", d->addr[i].ip.v6[j],
  667. d->addr[i].ip.v6[j + 1]);
  668. l = strlen(ptr);
  669. len -= l;
  670. ptr += l;
  671. }
  672. infof(data, "%s", buffer);
  673. }
  674. }
  675. for(i = 0; i < d->numcname; i++) {
  676. infof(data, "CNAME: %s", Curl_dyn_ptr(&d->cname[i]));
  677. }
  678. }
  679. #else
  680. #define showdoh(x,y)
  681. #endif
  682. /*
  683. * doh2ai()
  684. *
  685. * This function returns a pointer to the first element of a newly allocated
  686. * Curl_addrinfo struct linked list filled with the data from a set of DoH
  687. * lookups. Curl_addrinfo is meant to work like the addrinfo struct does for
  688. * a IPv6 stack, but usable also for IPv4, all hosts and environments.
  689. *
  690. * The memory allocated by this function *MUST* be free'd later on calling
  691. * Curl_freeaddrinfo(). For each successful call to this function there
  692. * must be an associated call later to Curl_freeaddrinfo().
  693. */
  694. static struct Curl_addrinfo *
  695. doh2ai(const struct dohentry *de, const char *hostname, int port)
  696. {
  697. struct Curl_addrinfo *ai;
  698. struct Curl_addrinfo *prevai = NULL;
  699. struct Curl_addrinfo *firstai = NULL;
  700. struct sockaddr_in *addr;
  701. #ifdef ENABLE_IPV6
  702. struct sockaddr_in6 *addr6;
  703. #endif
  704. CURLcode result = CURLE_OK;
  705. int i;
  706. size_t hostlen = strlen(hostname) + 1; /* include null-terminator */
  707. if(!de)
  708. /* no input == no output! */
  709. return NULL;
  710. for(i = 0; i < de->numaddr; i++) {
  711. size_t ss_size;
  712. CURL_SA_FAMILY_T addrtype;
  713. if(de->addr[i].type == DNS_TYPE_AAAA) {
  714. #ifndef ENABLE_IPV6
  715. /* we can't handle IPv6 addresses */
  716. continue;
  717. #else
  718. ss_size = sizeof(struct sockaddr_in6);
  719. addrtype = AF_INET6;
  720. #endif
  721. }
  722. else {
  723. ss_size = sizeof(struct sockaddr_in);
  724. addrtype = AF_INET;
  725. }
  726. ai = calloc(1, sizeof(struct Curl_addrinfo) + ss_size + hostlen);
  727. if(!ai) {
  728. result = CURLE_OUT_OF_MEMORY;
  729. break;
  730. }
  731. ai->ai_addr = (void *)((char *)ai + sizeof(struct Curl_addrinfo));
  732. ai->ai_canonname = (void *)((char *)ai->ai_addr + ss_size);
  733. memcpy(ai->ai_canonname, hostname, hostlen);
  734. if(!firstai)
  735. /* store the pointer we want to return from this function */
  736. firstai = ai;
  737. if(prevai)
  738. /* make the previous entry point to this */
  739. prevai->ai_next = ai;
  740. ai->ai_family = addrtype;
  741. /* we return all names as STREAM, so when using this address for TFTP
  742. the type must be ignored and conn->socktype be used instead! */
  743. ai->ai_socktype = SOCK_STREAM;
  744. ai->ai_addrlen = (curl_socklen_t)ss_size;
  745. /* leave the rest of the struct filled with zero */
  746. switch(ai->ai_family) {
  747. case AF_INET:
  748. addr = (void *)ai->ai_addr; /* storage area for this info */
  749. DEBUGASSERT(sizeof(struct in_addr) == sizeof(de->addr[i].ip.v4));
  750. memcpy(&addr->sin_addr, &de->addr[i].ip.v4, sizeof(struct in_addr));
  751. addr->sin_family = addrtype;
  752. addr->sin_port = htons((unsigned short)port);
  753. break;
  754. #ifdef ENABLE_IPV6
  755. case AF_INET6:
  756. addr6 = (void *)ai->ai_addr; /* storage area for this info */
  757. DEBUGASSERT(sizeof(struct in6_addr) == sizeof(de->addr[i].ip.v6));
  758. memcpy(&addr6->sin6_addr, &de->addr[i].ip.v6, sizeof(struct in6_addr));
  759. addr6->sin6_family = addrtype;
  760. addr6->sin6_port = htons((unsigned short)port);
  761. break;
  762. #endif
  763. }
  764. prevai = ai;
  765. }
  766. if(result) {
  767. Curl_freeaddrinfo(firstai);
  768. firstai = NULL;
  769. }
  770. return firstai;
  771. }
  772. #ifndef CURL_DISABLE_VERBOSE_STRINGS
  773. static const char *type2name(DNStype dnstype)
  774. {
  775. return (dnstype == DNS_TYPE_A)?"A":"AAAA";
  776. }
  777. #endif
  778. UNITTEST void de_cleanup(struct dohentry *d)
  779. {
  780. int i = 0;
  781. for(i = 0; i < d->numcname; i++) {
  782. Curl_dyn_free(&d->cname[i]);
  783. }
  784. }
  785. CURLcode Curl_doh_is_resolved(struct Curl_easy *data,
  786. struct Curl_dns_entry **dnsp)
  787. {
  788. CURLcode result;
  789. struct dohdata *dohp = data->req.doh;
  790. *dnsp = NULL; /* defaults to no response */
  791. if(!dohp)
  792. return CURLE_OUT_OF_MEMORY;
  793. if(!dohp->probe[DOH_PROBE_SLOT_IPADDR_V4].easy &&
  794. !dohp->probe[DOH_PROBE_SLOT_IPADDR_V6].easy) {
  795. failf(data, "Could not DoH-resolve: %s", data->state.async.hostname);
  796. return CONN_IS_PROXIED(data->conn)?CURLE_COULDNT_RESOLVE_PROXY:
  797. CURLE_COULDNT_RESOLVE_HOST;
  798. }
  799. else if(!dohp->pending) {
  800. DOHcode rc[DOH_PROBE_SLOTS] = {
  801. DOH_OK, DOH_OK
  802. };
  803. struct dohentry de;
  804. int slot;
  805. /* remove DoH handles from multi handle and close them */
  806. for(slot = 0; slot < DOH_PROBE_SLOTS; slot++) {
  807. curl_multi_remove_handle(data->multi, dohp->probe[slot].easy);
  808. Curl_close(&dohp->probe[slot].easy);
  809. }
  810. /* parse the responses, create the struct and return it! */
  811. de_init(&de);
  812. for(slot = 0; slot < DOH_PROBE_SLOTS; slot++) {
  813. struct dnsprobe *p = &dohp->probe[slot];
  814. if(!p->dnstype)
  815. continue;
  816. rc[slot] = doh_decode(Curl_dyn_uptr(&p->serverdoh),
  817. Curl_dyn_len(&p->serverdoh),
  818. p->dnstype,
  819. &de);
  820. Curl_dyn_free(&p->serverdoh);
  821. if(rc[slot]) {
  822. infof(data, "DoH: %s type %s for %s", doh_strerror(rc[slot]),
  823. type2name(p->dnstype), dohp->host);
  824. }
  825. } /* next slot */
  826. result = CURLE_COULDNT_RESOLVE_HOST; /* until we know better */
  827. if(!rc[DOH_PROBE_SLOT_IPADDR_V4] || !rc[DOH_PROBE_SLOT_IPADDR_V6]) {
  828. /* we have an address, of one kind or other */
  829. struct Curl_dns_entry *dns;
  830. struct Curl_addrinfo *ai;
  831. infof(data, "DoH Host name: %s", dohp->host);
  832. showdoh(data, &de);
  833. ai = doh2ai(&de, dohp->host, dohp->port);
  834. if(!ai) {
  835. de_cleanup(&de);
  836. return CURLE_OUT_OF_MEMORY;
  837. }
  838. if(data->share)
  839. Curl_share_lock(data, CURL_LOCK_DATA_DNS, CURL_LOCK_ACCESS_SINGLE);
  840. /* we got a response, store it in the cache */
  841. dns = Curl_cache_addr(data, ai, dohp->host, 0, dohp->port);
  842. if(data->share)
  843. Curl_share_unlock(data, CURL_LOCK_DATA_DNS);
  844. if(!dns) {
  845. /* returned failure, bail out nicely */
  846. Curl_freeaddrinfo(ai);
  847. }
  848. else {
  849. data->state.async.dns = dns;
  850. *dnsp = dns;
  851. result = CURLE_OK; /* address resolution OK */
  852. }
  853. } /* address processing done */
  854. /* Now process any build-specific attributes retrieved from DNS */
  855. /* All done */
  856. de_cleanup(&de);
  857. Curl_safefree(data->req.doh);
  858. return result;
  859. } /* !dohp->pending */
  860. /* else wait for pending DoH transactions to complete */
  861. return CURLE_OK;
  862. }
  863. #endif /* CURL_DISABLE_DOH */