doh.c 28 KB

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