Coverage Report

Created: 2023-03-26 06:11

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