doh.c 29 KB

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