doh.c 28 KB

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