]> git.ipfire.org Git - people/ms/dnsmasq.git/blob - src/dnssec.c
DNSSEC fix: correct logic for signed records in unsigned DNS space.
[people/ms/dnsmasq.git] / src / dnssec.c
1 /* dnssec.c is Copyright (c) 2012 Giovanni Bajo <rasky@develer.com>
2 and Copyright (c) 2012-2015 Simon Kelley
3
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; version 2 dated June, 1991, or
7 (at your option) version 3 dated 29 June, 2007.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18 #include "dnsmasq.h"
19
20 #ifdef HAVE_DNSSEC
21
22 #include <nettle/rsa.h>
23 #include <nettle/dsa.h>
24 #ifndef NO_NETTLE_ECC
25 # include <nettle/ecdsa.h>
26 # include <nettle/ecc-curve.h>
27 #endif
28 #include <nettle/nettle-meta.h>
29 #include <nettle/bignum.h>
30
31 /* Nettle-3.0 moved to a new API for DSA. We use a name that's defined in the new API
32 to detect Nettle-3, and invoke the backwards compatibility mode. */
33 #ifdef dsa_params_init
34 #include <nettle/dsa-compat.h>
35 #endif
36
37 #include <utime.h>
38
39 #define SERIAL_UNDEF -100
40 #define SERIAL_EQ 0
41 #define SERIAL_LT -1
42 #define SERIAL_GT 1
43
44 /* http://www.iana.org/assignments/ds-rr-types/ds-rr-types.xhtml */
45 static char *ds_digest_name(int digest)
46 {
47 switch (digest)
48 {
49 case 1: return "sha1";
50 case 2: return "sha256";
51 case 3: return "gosthash94";
52 case 4: return "sha384";
53 default: return NULL;
54 }
55 }
56
57 /* http://www.iana.org/assignments/dns-sec-alg-numbers/dns-sec-alg-numbers.xhtml */
58 static char *algo_digest_name(int algo)
59 {
60 switch (algo)
61 {
62 case 1: return "md5";
63 case 3: return "sha1";
64 case 5: return "sha1";
65 case 6: return "sha1";
66 case 7: return "sha1";
67 case 8: return "sha256";
68 case 10: return "sha512";
69 case 12: return "gosthash94";
70 case 13: return "sha256";
71 case 14: return "sha384";
72 default: return NULL;
73 }
74 }
75
76 /* Find pointer to correct hash function in nettle library */
77 static const struct nettle_hash *hash_find(char *name)
78 {
79 int i;
80
81 if (!name)
82 return NULL;
83
84 for (i = 0; nettle_hashes[i]; i++)
85 {
86 if (strcmp(nettle_hashes[i]->name, name) == 0)
87 return nettle_hashes[i];
88 }
89
90 return NULL;
91 }
92
93 /* expand ctx and digest memory allocations if necessary and init hash function */
94 static int hash_init(const struct nettle_hash *hash, void **ctxp, unsigned char **digestp)
95 {
96 static void *ctx = NULL;
97 static unsigned char *digest = NULL;
98 static unsigned int ctx_sz = 0;
99 static unsigned int digest_sz = 0;
100
101 void *new;
102
103 if (ctx_sz < hash->context_size)
104 {
105 if (!(new = whine_malloc(hash->context_size)))
106 return 0;
107 if (ctx)
108 free(ctx);
109 ctx = new;
110 ctx_sz = hash->context_size;
111 }
112
113 if (digest_sz < hash->digest_size)
114 {
115 if (!(new = whine_malloc(hash->digest_size)))
116 return 0;
117 if (digest)
118 free(digest);
119 digest = new;
120 digest_sz = hash->digest_size;
121 }
122
123 *ctxp = ctx;
124 *digestp = digest;
125
126 hash->init(ctx);
127
128 return 1;
129 }
130
131 static int dnsmasq_rsa_verify(struct blockdata *key_data, unsigned int key_len, unsigned char *sig, size_t sig_len,
132 unsigned char *digest, int algo)
133 {
134 unsigned char *p;
135 size_t exp_len;
136
137 static struct rsa_public_key *key = NULL;
138 static mpz_t sig_mpz;
139
140 if (key == NULL)
141 {
142 if (!(key = whine_malloc(sizeof(struct rsa_public_key))))
143 return 0;
144
145 nettle_rsa_public_key_init(key);
146 mpz_init(sig_mpz);
147 }
148
149 if ((key_len < 3) || !(p = blockdata_retrieve(key_data, key_len, NULL)))
150 return 0;
151
152 key_len--;
153 if ((exp_len = *p++) == 0)
154 {
155 GETSHORT(exp_len, p);
156 key_len -= 2;
157 }
158
159 if (exp_len >= key_len)
160 return 0;
161
162 key->size = key_len - exp_len;
163 mpz_import(key->e, exp_len, 1, 1, 0, 0, p);
164 mpz_import(key->n, key->size, 1, 1, 0, 0, p + exp_len);
165
166 mpz_import(sig_mpz, sig_len, 1, 1, 0, 0, sig);
167
168 switch (algo)
169 {
170 case 1:
171 return nettle_rsa_md5_verify_digest(key, digest, sig_mpz);
172 case 5: case 7:
173 return nettle_rsa_sha1_verify_digest(key, digest, sig_mpz);
174 case 8:
175 return nettle_rsa_sha256_verify_digest(key, digest, sig_mpz);
176 case 10:
177 return nettle_rsa_sha512_verify_digest(key, digest, sig_mpz);
178 }
179
180 return 0;
181 }
182
183 static int dnsmasq_dsa_verify(struct blockdata *key_data, unsigned int key_len, unsigned char *sig, size_t sig_len,
184 unsigned char *digest, int algo)
185 {
186 unsigned char *p;
187 unsigned int t;
188
189 static struct dsa_public_key *key = NULL;
190 static struct dsa_signature *sig_struct;
191
192 if (key == NULL)
193 {
194 if (!(sig_struct = whine_malloc(sizeof(struct dsa_signature))) ||
195 !(key = whine_malloc(sizeof(struct dsa_public_key))))
196 return 0;
197
198 nettle_dsa_public_key_init(key);
199 nettle_dsa_signature_init(sig_struct);
200 }
201
202 if ((sig_len < 41) || !(p = blockdata_retrieve(key_data, key_len, NULL)))
203 return 0;
204
205 t = *p++;
206
207 if (key_len < (213 + (t * 24)))
208 return 0;
209
210 mpz_import(key->q, 20, 1, 1, 0, 0, p); p += 20;
211 mpz_import(key->p, 64 + (t*8), 1, 1, 0, 0, p); p += 64 + (t*8);
212 mpz_import(key->g, 64 + (t*8), 1, 1, 0, 0, p); p += 64 + (t*8);
213 mpz_import(key->y, 64 + (t*8), 1, 1, 0, 0, p); p += 64 + (t*8);
214
215 mpz_import(sig_struct->r, 20, 1, 1, 0, 0, sig+1);
216 mpz_import(sig_struct->s, 20, 1, 1, 0, 0, sig+21);
217
218 (void)algo;
219
220 return nettle_dsa_sha1_verify_digest(key, digest, sig_struct);
221 }
222
223 #ifndef NO_NETTLE_ECC
224 static int dnsmasq_ecdsa_verify(struct blockdata *key_data, unsigned int key_len,
225 unsigned char *sig, size_t sig_len,
226 unsigned char *digest, size_t digest_len, int algo)
227 {
228 unsigned char *p;
229 unsigned int t;
230 struct ecc_point *key;
231
232 static struct ecc_point *key_256 = NULL, *key_384 = NULL;
233 static mpz_t x, y;
234 static struct dsa_signature *sig_struct;
235
236 if (!sig_struct)
237 {
238 if (!(sig_struct = whine_malloc(sizeof(struct dsa_signature))))
239 return 0;
240
241 nettle_dsa_signature_init(sig_struct);
242 mpz_init(x);
243 mpz_init(y);
244 }
245
246 switch (algo)
247 {
248 case 13:
249 if (!key_256)
250 {
251 if (!(key_256 = whine_malloc(sizeof(struct ecc_point))))
252 return 0;
253
254 nettle_ecc_point_init(key_256, &nettle_secp_256r1);
255 }
256
257 key = key_256;
258 t = 32;
259 break;
260
261 case 14:
262 if (!key_384)
263 {
264 if (!(key_384 = whine_malloc(sizeof(struct ecc_point))))
265 return 0;
266
267 nettle_ecc_point_init(key_384, &nettle_secp_384r1);
268 }
269
270 key = key_384;
271 t = 48;
272 break;
273
274 default:
275 return 0;
276 }
277
278 if (sig_len != 2*t || key_len != 2*t ||
279 !(p = blockdata_retrieve(key_data, key_len, NULL)))
280 return 0;
281
282 mpz_import(x, t , 1, 1, 0, 0, p);
283 mpz_import(y, t , 1, 1, 0, 0, p + t);
284
285 if (!ecc_point_set(key, x, y))
286 return 0;
287
288 mpz_import(sig_struct->r, t, 1, 1, 0, 0, sig);
289 mpz_import(sig_struct->s, t, 1, 1, 0, 0, sig + t);
290
291 return nettle_ecdsa_verify(key, digest_len, digest, sig_struct);
292 }
293 #endif
294
295 static int verify(struct blockdata *key_data, unsigned int key_len, unsigned char *sig, size_t sig_len,
296 unsigned char *digest, size_t digest_len, int algo)
297 {
298 (void)digest_len;
299
300 switch (algo)
301 {
302 case 1: case 5: case 7: case 8: case 10:
303 return dnsmasq_rsa_verify(key_data, key_len, sig, sig_len, digest, algo);
304
305 case 3: case 6:
306 return dnsmasq_dsa_verify(key_data, key_len, sig, sig_len, digest, algo);
307
308 #ifndef NO_NETTLE_ECC
309 case 13: case 14:
310 return dnsmasq_ecdsa_verify(key_data, key_len, sig, sig_len, digest, digest_len, algo);
311 #endif
312 }
313
314 return 0;
315 }
316
317 /* Convert from presentation format to wire format, in place.
318 Also map UC -> LC.
319 Note that using extract_name to get presentation format
320 then calling to_wire() removes compression and maps case,
321 thus generating names in canonical form.
322 Calling to_wire followed by from_wire is almost an identity,
323 except that the UC remains mapped to LC.
324
325 Note that both /000 and '.' are allowed within labels. These get
326 represented in presentation format using NAME_ESCAPE as an escape
327 character. In theory, if all the characters in a name were /000 or
328 '.' or NAME_ESCAPE then all would have to be escaped, so the
329 presentation format would be twice as long as the spec (1024).
330 The buffers are all delcared as 2049 (allowing for the trailing zero)
331 for this reason.
332 */
333 static int to_wire(char *name)
334 {
335 unsigned char *l, *p, *q, term;
336 int len;
337
338 for (l = (unsigned char*)name; *l != 0; l = p)
339 {
340 for (p = l; *p != '.' && *p != 0; p++)
341 if (*p >= 'A' && *p <= 'Z')
342 *p = *p - 'A' + 'a';
343 else if (*p == NAME_ESCAPE)
344 {
345 for (q = p; *q; q++)
346 *q = *(q+1);
347 (*p)--;
348 }
349 term = *p;
350
351 if ((len = p - l) != 0)
352 memmove(l+1, l, len);
353 *l = len;
354
355 p++;
356
357 if (term == 0)
358 *p = 0;
359 }
360
361 return l + 1 - (unsigned char *)name;
362 }
363
364 /* Note: no compression allowed in input. */
365 static void from_wire(char *name)
366 {
367 unsigned char *l, *p, *last;
368 int len;
369
370 for (last = (unsigned char *)name; *last != 0; last += *last+1);
371
372 for (l = (unsigned char *)name; *l != 0; l += len+1)
373 {
374 len = *l;
375 memmove(l, l+1, len);
376 for (p = l; p < l + len; p++)
377 if (*p == '.' || *p == 0 || *p == NAME_ESCAPE)
378 {
379 memmove(p+1, p, 1 + last - p);
380 len++;
381 *p++ = NAME_ESCAPE;
382 (*p)++;
383 }
384
385 l[len] = '.';
386 }
387
388 if ((char *)l != name)
389 *(l-1) = 0;
390 }
391
392 /* Input in presentation format */
393 static int count_labels(char *name)
394 {
395 int i;
396
397 if (*name == 0)
398 return 0;
399
400 for (i = 0; *name; name++)
401 if (*name == '.')
402 i++;
403
404 return i+1;
405 }
406
407 /* Implement RFC1982 wrapped compare for 32-bit numbers */
408 static int serial_compare_32(unsigned long s1, unsigned long s2)
409 {
410 if (s1 == s2)
411 return SERIAL_EQ;
412
413 if ((s1 < s2 && (s2 - s1) < (1UL<<31)) ||
414 (s1 > s2 && (s1 - s2) > (1UL<<31)))
415 return SERIAL_LT;
416 if ((s1 < s2 && (s2 - s1) > (1UL<<31)) ||
417 (s1 > s2 && (s1 - s2) < (1UL<<31)))
418 return SERIAL_GT;
419 return SERIAL_UNDEF;
420 }
421
422 /* Called at startup. If the timestamp file is configured and exists, put its mtime on
423 timestamp_time. If it doesn't exist, create it, and set the mtime to 1-1-2015.
424 return -1 -> Cannot create file.
425 0 -> not using timestamp, or timestamp exists and is in past.
426 1 -> timestamp exists and is in future.
427 */
428
429 static time_t timestamp_time;
430 static int back_to_the_future;
431
432 int setup_timestamp(void)
433 {
434 struct stat statbuf;
435
436 back_to_the_future = 0;
437
438 if (!daemon->timestamp_file)
439 return 0;
440
441 if (stat(daemon->timestamp_file, &statbuf) != -1)
442 {
443 timestamp_time = statbuf.st_mtime;
444 check_and_exit:
445 if (difftime(timestamp_time, time(0)) <= 0)
446 {
447 /* time already OK, update timestamp, and do key checking from the start. */
448 if (utime(daemon->timestamp_file, NULL) == -1)
449 my_syslog(LOG_ERR, _("failed to update mtime on %s: %s"), daemon->timestamp_file, strerror(errno));
450 back_to_the_future = 1;
451 return 0;
452 }
453 return 1;
454 }
455
456 if (errno == ENOENT)
457 {
458 /* NB. for explanation of O_EXCL flag, see comment on pidfile in dnsmasq.c */
459 int fd = open(daemon->timestamp_file, O_WRONLY | O_CREAT | O_NONBLOCK | O_EXCL, 0666);
460 if (fd != -1)
461 {
462 struct utimbuf timbuf;
463
464 close(fd);
465
466 timestamp_time = timbuf.actime = timbuf.modtime = 1420070400; /* 1-1-2015 */
467 if (utime(daemon->timestamp_file, &timbuf) == 0)
468 goto check_and_exit;
469 }
470 }
471
472 return -1;
473 }
474
475 /* Check whether today/now is between date_start and date_end */
476 static int check_date_range(unsigned long date_start, unsigned long date_end)
477 {
478 unsigned long curtime = time(0);
479
480 /* Checking timestamps may be temporarily disabled */
481
482 /* If the current time if _before_ the timestamp
483 on our persistent timestamp file, then assume the
484 time if not yet correct, and don't check the
485 key timestamps. As soon as the current time is
486 later then the timestamp, update the timestamp
487 and start checking keys */
488 if (daemon->timestamp_file)
489 {
490 if (back_to_the_future == 0 && difftime(timestamp_time, curtime) <= 0)
491 {
492 if (utime(daemon->timestamp_file, NULL) != 0)
493 my_syslog(LOG_ERR, _("failed to update mtime on %s: %s"), daemon->timestamp_file, strerror(errno));
494
495 back_to_the_future = 1;
496 set_option_bool(OPT_DNSSEC_TIME);
497 queue_event(EVENT_RELOAD); /* purge cache */
498 }
499
500 if (back_to_the_future == 0)
501 return 1;
502 }
503 else if (option_bool(OPT_DNSSEC_TIME))
504 return 1;
505
506 /* We must explicitly check against wanted values, because of SERIAL_UNDEF */
507 return serial_compare_32(curtime, date_start) == SERIAL_GT
508 && serial_compare_32(curtime, date_end) == SERIAL_LT;
509 }
510
511 static u16 *get_desc(int type)
512 {
513 /* List of RRtypes which include domains in the data.
514 0 -> domain
515 integer -> no of plain bytes
516 -1 -> end
517
518 zero is not a valid RRtype, so the final entry is returned for
519 anything which needs no mangling.
520 */
521
522 static u16 rr_desc[] =
523 {
524 T_NS, 0, -1,
525 T_MD, 0, -1,
526 T_MF, 0, -1,
527 T_CNAME, 0, -1,
528 T_SOA, 0, 0, -1,
529 T_MB, 0, -1,
530 T_MG, 0, -1,
531 T_MR, 0, -1,
532 T_PTR, 0, -1,
533 T_MINFO, 0, 0, -1,
534 T_MX, 2, 0, -1,
535 T_RP, 0, 0, -1,
536 T_AFSDB, 2, 0, -1,
537 T_RT, 2, 0, -1,
538 T_SIG, 18, 0, -1,
539 T_PX, 2, 0, 0, -1,
540 T_NXT, 0, -1,
541 T_KX, 2, 0, -1,
542 T_SRV, 6, 0, -1,
543 T_DNAME, 0, -1,
544 0, -1 /* wildcard/catchall */
545 };
546
547 u16 *p = rr_desc;
548
549 while (*p != type && *p != 0)
550 while (*p++ != (u16)-1);
551
552 return p+1;
553 }
554
555 /* Return bytes of canonicalised rdata, when the return value is zero, the remaining
556 data, pointed to by *p, should be used raw. */
557 static int get_rdata(struct dns_header *header, size_t plen, unsigned char *end, char *buff, int bufflen,
558 unsigned char **p, u16 **desc)
559 {
560 int d = **desc;
561
562 /* No more data needs mangling */
563 if (d == (u16)-1)
564 {
565 /* If there's more data than we have space for, just return what fits,
566 we'll get called again for more chunks */
567 if (end - *p > bufflen)
568 {
569 memcpy(buff, *p, bufflen);
570 *p += bufflen;
571 return bufflen;
572 }
573
574 return 0;
575 }
576
577 (*desc)++;
578
579 if (d == 0 && extract_name(header, plen, p, buff, 1, 0))
580 /* domain-name, canonicalise */
581 return to_wire(buff);
582 else
583 {
584 /* plain data preceding a domain-name, don't run off the end of the data */
585 if ((end - *p) < d)
586 d = end - *p;
587
588 if (d != 0)
589 {
590 memcpy(buff, *p, d);
591 *p += d;
592 }
593
594 return d;
595 }
596 }
597
598 static int expand_workspace(unsigned char ***wkspc, int *sz, int new)
599 {
600 unsigned char **p;
601 int new_sz = *sz;
602
603 if (new_sz > new)
604 return 1;
605
606 if (new >= 100)
607 return 0;
608
609 new_sz += 5;
610
611 if (!(p = whine_malloc((new_sz) * sizeof(unsigned char **))))
612 return 0;
613
614 if (*wkspc)
615 {
616 memcpy(p, *wkspc, *sz * sizeof(unsigned char **));
617 free(*wkspc);
618 }
619
620 *wkspc = p;
621 *sz = new_sz;
622
623 return 1;
624 }
625
626 /* Bubble sort the RRset into the canonical order.
627 Note that the byte-streams from two RRs may get unsynced: consider
628 RRs which have two domain-names at the start and then other data.
629 The domain-names may have different lengths in each RR, but sort equal
630
631 ------------
632 |abcde|fghi|
633 ------------
634 |abcd|efghi|
635 ------------
636
637 leaving the following bytes as deciding the order. Hence the nasty left1 and left2 variables.
638 */
639
640 static void sort_rrset(struct dns_header *header, size_t plen, u16 *rr_desc, int rrsetidx,
641 unsigned char **rrset, char *buff1, char *buff2)
642 {
643 int swap, quit, i;
644
645 do
646 {
647 for (swap = 0, i = 0; i < rrsetidx-1; i++)
648 {
649 int rdlen1, rdlen2, left1, left2, len1, len2, len, rc;
650 u16 *dp1, *dp2;
651 unsigned char *end1, *end2;
652 /* Note that these have been determined to be OK previously,
653 so we don't need to check for NULL return here. */
654 unsigned char *p1 = skip_name(rrset[i], header, plen, 10);
655 unsigned char *p2 = skip_name(rrset[i+1], header, plen, 10);
656
657 p1 += 8; /* skip class, type, ttl */
658 GETSHORT(rdlen1, p1);
659 end1 = p1 + rdlen1;
660
661 p2 += 8; /* skip class, type, ttl */
662 GETSHORT(rdlen2, p2);
663 end2 = p2 + rdlen2;
664
665 dp1 = dp2 = rr_desc;
666
667 for (quit = 0, left1 = 0, left2 = 0, len1 = 0, len2 = 0; !quit;)
668 {
669 if (left1 != 0)
670 memmove(buff1, buff1 + len1 - left1, left1);
671
672 if ((len1 = get_rdata(header, plen, end1, buff1 + left1, (MAXDNAME * 2) - left1, &p1, &dp1)) == 0)
673 {
674 quit = 1;
675 len1 = end1 - p1;
676 memcpy(buff1 + left1, p1, len1);
677 }
678 len1 += left1;
679
680 if (left2 != 0)
681 memmove(buff2, buff2 + len2 - left2, left2);
682
683 if ((len2 = get_rdata(header, plen, end2, buff2 + left2, (MAXDNAME *2) - left2, &p2, &dp2)) == 0)
684 {
685 quit = 1;
686 len2 = end2 - p2;
687 memcpy(buff2 + left2, p2, len2);
688 }
689 len2 += left2;
690
691 if (len1 > len2)
692 left1 = len1 - len2, left2 = 0, len = len2;
693 else
694 left2 = len2 - len1, left1 = 0, len = len1;
695
696 rc = (len == 0) ? 0 : memcmp(buff1, buff2, len);
697
698 if (rc > 0 || (rc == 0 && quit && len1 > len2))
699 {
700 unsigned char *tmp = rrset[i+1];
701 rrset[i+1] = rrset[i];
702 rrset[i] = tmp;
703 swap = quit = 1;
704 }
705 else if (rc < 0)
706 quit = 1;
707 }
708 }
709 } while (swap);
710 }
711
712 /* Validate a single RRset (class, type, name) in the supplied DNS reply
713 Return code:
714 STAT_SECURE if it validates.
715 STAT_SECURE_WILDCARD if it validates and is the result of wildcard expansion.
716 (In this case *wildcard_out points to the "body" of the wildcard within name.)
717 STAT_NO_SIG no RRsigs found.
718 STAT_INSECURE RRset empty.
719 STAT_BOGUS signature is wrong, bad packet.
720 STAT_NEED_KEY need DNSKEY to complete validation (name is returned in keyname)
721
722 if key is non-NULL, use that key, which has the algo and tag given in the params of those names,
723 otherwise find the key in the cache.
724
725 name is unchanged on exit. keyname is used as workspace and trashed.
726 */
727 static int validate_rrset(time_t now, struct dns_header *header, size_t plen, int class, int type,
728 char *name, char *keyname, char **wildcard_out, struct blockdata *key, int keylen, int algo_in, int keytag_in)
729 {
730 static unsigned char **rrset = NULL, **sigs = NULL;
731 static int rrset_sz = 0, sig_sz = 0;
732
733 unsigned char *p;
734 int rrsetidx, sigidx, res, rdlen, j, name_labels;
735 struct crec *crecp = NULL;
736 int type_covered, algo, labels, orig_ttl, sig_expiration, sig_inception, key_tag;
737 u16 *rr_desc = get_desc(type);
738
739 if (wildcard_out)
740 *wildcard_out = NULL;
741
742 if (!(p = skip_questions(header, plen)))
743 return STAT_BOGUS;
744
745 name_labels = count_labels(name); /* For 4035 5.3.2 check */
746
747 /* look for RRSIGs for this RRset and get pointers to each RR in the set. */
748 for (rrsetidx = 0, sigidx = 0, j = ntohs(header->ancount) + ntohs(header->nscount);
749 j != 0; j--)
750 {
751 unsigned char *pstart, *pdata;
752 int stype, sclass;
753
754 pstart = p;
755
756 if (!(res = extract_name(header, plen, &p, name, 0, 10)))
757 return STAT_BOGUS; /* bad packet */
758
759 GETSHORT(stype, p);
760 GETSHORT(sclass, p);
761 p += 4; /* TTL */
762
763 pdata = p;
764
765 GETSHORT(rdlen, p);
766
767 if (!CHECK_LEN(header, p, plen, rdlen))
768 return STAT_BOGUS;
769
770 if (res == 1 && sclass == class)
771 {
772 if (stype == type)
773 {
774 if (!expand_workspace(&rrset, &rrset_sz, rrsetidx))
775 return STAT_BOGUS;
776
777 rrset[rrsetidx++] = pstart;
778 }
779
780 if (stype == T_RRSIG)
781 {
782 if (rdlen < 18)
783 return STAT_BOGUS; /* bad packet */
784
785 GETSHORT(type_covered, p);
786
787 if (type_covered == type)
788 {
789 if (!expand_workspace(&sigs, &sig_sz, sigidx))
790 return STAT_BOGUS;
791
792 sigs[sigidx++] = pdata;
793 }
794
795 p = pdata + 2; /* restore for ADD_RDLEN */
796 }
797 }
798
799 if (!ADD_RDLEN(header, p, plen, rdlen))
800 return STAT_BOGUS;
801 }
802
803 /* RRset empty */
804 if (rrsetidx == 0)
805 return STAT_INSECURE;
806
807 /* no RRSIGs */
808 if (sigidx == 0)
809 return STAT_NO_SIG;
810
811 /* Sort RRset records into canonical order.
812 Note that at this point keyname and daemon->workspacename buffs are
813 unused, and used as workspace by the sort. */
814 sort_rrset(header, plen, rr_desc, rrsetidx, rrset, daemon->workspacename, keyname);
815
816 /* Now try all the sigs to try and find one which validates */
817 for (j = 0; j <sigidx; j++)
818 {
819 unsigned char *psav, *sig, *digest;
820 int i, wire_len, sig_len;
821 const struct nettle_hash *hash;
822 void *ctx;
823 char *name_start;
824 u32 nsigttl;
825
826 p = sigs[j];
827 GETSHORT(rdlen, p); /* rdlen >= 18 checked previously */
828 psav = p;
829
830 p += 2; /* type_covered - already checked */
831 algo = *p++;
832 labels = *p++;
833 GETLONG(orig_ttl, p);
834 GETLONG(sig_expiration, p);
835 GETLONG(sig_inception, p);
836 GETSHORT(key_tag, p);
837
838 if (!extract_name(header, plen, &p, keyname, 1, 0))
839 return STAT_BOGUS;
840
841 /* RFC 4035 5.3.1 says that the Signer's Name field MUST equal
842 the name of the zone containing the RRset. We can't tell that
843 for certain, but we can check that the RRset name is equal to
844 or encloses the signers name, which should be enough to stop
845 an attacker using signatures made with the key of an unrelated
846 zone he controls. Note that the root key is always allowed. */
847 if (*keyname != 0)
848 {
849 int failed = 0;
850
851 for (name_start = name; !hostname_isequal(name_start, keyname); )
852 if ((name_start = strchr(name_start, '.')))
853 name_start++; /* chop a label off and try again */
854 else
855 {
856 failed = 1;
857 break;
858 }
859
860 /* Bad sig, try another */
861 if (failed)
862 continue;
863 }
864
865 /* Other 5.3.1 checks */
866 if (!check_date_range(sig_inception, sig_expiration) ||
867 labels > name_labels ||
868 !(hash = hash_find(algo_digest_name(algo))) ||
869 !hash_init(hash, &ctx, &digest))
870 continue;
871
872 /* OK, we have the signature record, see if the relevant DNSKEY is in the cache. */
873 if (!key && !(crecp = cache_find_by_name(NULL, keyname, now, F_DNSKEY)))
874 return STAT_NEED_KEY;
875
876 sig = p;
877 sig_len = rdlen - (p - psav);
878
879 nsigttl = htonl(orig_ttl);
880
881 hash->update(ctx, 18, psav);
882 wire_len = to_wire(keyname);
883 hash->update(ctx, (unsigned int)wire_len, (unsigned char*)keyname);
884 from_wire(keyname);
885
886 for (i = 0; i < rrsetidx; ++i)
887 {
888 int seg;
889 unsigned char *end, *cp;
890 u16 len, *dp;
891
892 p = rrset[i];
893 if (!extract_name(header, plen, &p, name, 1, 10))
894 return STAT_BOGUS;
895
896 name_start = name;
897
898 /* if more labels than in RRsig name, hash *.<no labels in rrsig labels field> 4035 5.3.2 */
899 if (labels < name_labels)
900 {
901 int k;
902 for (k = name_labels - labels; k != 0; k--)
903 {
904 while (*name_start != '.' && *name_start != 0)
905 name_start++;
906 if (k != 1 && *name_start == '.')
907 name_start++;
908 }
909
910 if (wildcard_out)
911 *wildcard_out = name_start+1;
912
913 name_start--;
914 *name_start = '*';
915 }
916
917 wire_len = to_wire(name_start);
918 hash->update(ctx, (unsigned int)wire_len, (unsigned char *)name_start);
919 hash->update(ctx, 4, p); /* class and type */
920 hash->update(ctx, 4, (unsigned char *)&nsigttl);
921
922 p += 8; /* skip class, type, ttl */
923 GETSHORT(rdlen, p);
924 if (!CHECK_LEN(header, p, plen, rdlen))
925 return STAT_BOGUS;
926
927 end = p + rdlen;
928
929 /* canonicalise rdata and calculate length of same, use name buffer as workspace.
930 Note that name buffer is twice MAXDNAME long in DNSSEC mode. */
931 cp = p;
932 dp = rr_desc;
933 for (len = 0; (seg = get_rdata(header, plen, end, name, MAXDNAME * 2, &cp, &dp)) != 0; len += seg);
934 len += end - cp;
935 len = htons(len);
936 hash->update(ctx, 2, (unsigned char *)&len);
937
938 /* Now canonicalise again and digest. */
939 cp = p;
940 dp = rr_desc;
941 while ((seg = get_rdata(header, plen, end, name, MAXDNAME * 2, &cp, &dp)))
942 hash->update(ctx, seg, (unsigned char *)name);
943 if (cp != end)
944 hash->update(ctx, end - cp, cp);
945 }
946
947 hash->digest(ctx, hash->digest_size, digest);
948
949 /* namebuff used for workspace above, restore to leave unchanged on exit */
950 p = (unsigned char*)(rrset[0]);
951 extract_name(header, plen, &p, name, 1, 0);
952
953 if (key)
954 {
955 if (algo_in == algo && keytag_in == key_tag &&
956 verify(key, keylen, sig, sig_len, digest, hash->digest_size, algo))
957 return STAT_SECURE;
958 }
959 else
960 {
961 /* iterate through all possible keys 4035 5.3.1 */
962 for (; crecp; crecp = cache_find_by_name(crecp, keyname, now, F_DNSKEY))
963 if (crecp->addr.key.algo == algo &&
964 crecp->addr.key.keytag == key_tag &&
965 crecp->uid == (unsigned int)class &&
966 verify(crecp->addr.key.keydata, crecp->addr.key.keylen, sig, sig_len, digest, hash->digest_size, algo))
967 return (labels < name_labels) ? STAT_SECURE_WILDCARD : STAT_SECURE;
968 }
969 }
970
971 return STAT_BOGUS;
972 }
973
974 /* The DNS packet is expected to contain the answer to a DNSKEY query.
975 Put all DNSKEYs in the answer which are valid into the cache.
976 return codes:
977 STAT_SECURE At least one valid DNSKEY found and in cache.
978 STAT_BOGUS No DNSKEYs found, which can be validated with DS,
979 or self-sign for DNSKEY RRset is not valid, bad packet.
980 STAT_NEED_DS DS records to validate a key not found, name in keyname
981 */
982 int dnssec_validate_by_ds(time_t now, struct dns_header *header, size_t plen, char *name, char *keyname, int class)
983 {
984 unsigned char *psave, *p = (unsigned char *)(header+1);
985 struct crec *crecp, *recp1;
986 int rc, j, qtype, qclass, ttl, rdlen, flags, algo, valid, keytag, type_covered;
987 struct blockdata *key;
988 struct all_addr a;
989
990 if (ntohs(header->qdcount) != 1 ||
991 !extract_name(header, plen, &p, name, 1, 4))
992 return STAT_BOGUS;
993
994 GETSHORT(qtype, p);
995 GETSHORT(qclass, p);
996
997 if (qtype != T_DNSKEY || qclass != class || ntohs(header->ancount) == 0)
998 return STAT_BOGUS;
999
1000 /* See if we have cached a DS record which validates this key */
1001 if (!(crecp = cache_find_by_name(NULL, name, now, F_DS)))
1002 {
1003 strcpy(keyname, name);
1004 return STAT_NEED_DS;
1005 }
1006
1007 /* If we've cached that DS provably doesn't exist, result must be INSECURE */
1008 if (crecp->flags & F_NEG)
1009 return STAT_INSECURE_DS;
1010
1011 /* NOTE, we need to find ONE DNSKEY which matches the DS */
1012 for (valid = 0, j = ntohs(header->ancount); j != 0 && !valid; j--)
1013 {
1014 /* Ensure we have type, class TTL and length */
1015 if (!(rc = extract_name(header, plen, &p, name, 0, 10)))
1016 return STAT_BOGUS; /* bad packet */
1017
1018 GETSHORT(qtype, p);
1019 GETSHORT(qclass, p);
1020 GETLONG(ttl, p);
1021 GETSHORT(rdlen, p);
1022
1023 if (!CHECK_LEN(header, p, plen, rdlen) || rdlen < 4)
1024 return STAT_BOGUS; /* bad packet */
1025
1026 if (qclass != class || qtype != T_DNSKEY || rc == 2)
1027 {
1028 p += rdlen;
1029 continue;
1030 }
1031
1032 psave = p;
1033
1034 GETSHORT(flags, p);
1035 if (*p++ != 3)
1036 return STAT_BOGUS;
1037 algo = *p++;
1038 keytag = dnskey_keytag(algo, flags, p, rdlen - 4);
1039 key = NULL;
1040
1041 /* key must have zone key flag set */
1042 if (flags & 0x100)
1043 key = blockdata_alloc((char*)p, rdlen - 4);
1044
1045 p = psave;
1046
1047 if (!ADD_RDLEN(header, p, plen, rdlen))
1048 {
1049 if (key)
1050 blockdata_free(key);
1051 return STAT_BOGUS; /* bad packet */
1052 }
1053
1054 /* No zone key flag or malloc failure */
1055 if (!key)
1056 continue;
1057
1058 for (recp1 = crecp; recp1; recp1 = cache_find_by_name(recp1, name, now, F_DS))
1059 {
1060 void *ctx;
1061 unsigned char *digest, *ds_digest;
1062 const struct nettle_hash *hash;
1063
1064 if (recp1->addr.ds.algo == algo &&
1065 recp1->addr.ds.keytag == keytag &&
1066 recp1->uid == (unsigned int)class &&
1067 (hash = hash_find(ds_digest_name(recp1->addr.ds.digest))) &&
1068 hash_init(hash, &ctx, &digest))
1069
1070 {
1071 int wire_len = to_wire(name);
1072
1073 /* Note that digest may be different between DSs, so
1074 we can't move this outside the loop. */
1075 hash->update(ctx, (unsigned int)wire_len, (unsigned char *)name);
1076 hash->update(ctx, (unsigned int)rdlen, psave);
1077 hash->digest(ctx, hash->digest_size, digest);
1078
1079 from_wire(name);
1080
1081 if (recp1->addr.ds.keylen == (int)hash->digest_size &&
1082 (ds_digest = blockdata_retrieve(recp1->addr.key.keydata, recp1->addr.ds.keylen, NULL)) &&
1083 memcmp(ds_digest, digest, recp1->addr.ds.keylen) == 0 &&
1084 validate_rrset(now, header, plen, class, T_DNSKEY, name, keyname, NULL, key, rdlen - 4, algo, keytag) == STAT_SECURE)
1085 {
1086 valid = 1;
1087 break;
1088 }
1089 }
1090 }
1091 blockdata_free(key);
1092 }
1093
1094 if (valid)
1095 {
1096 /* DNSKEY RRset determined to be OK, now cache it and the RRsigs that sign it. */
1097 cache_start_insert();
1098
1099 p = skip_questions(header, plen);
1100
1101 for (j = ntohs(header->ancount); j != 0; j--)
1102 {
1103 /* Ensure we have type, class TTL and length */
1104 if (!(rc = extract_name(header, plen, &p, name, 0, 10)))
1105 return STAT_INSECURE; /* bad packet */
1106
1107 GETSHORT(qtype, p);
1108 GETSHORT(qclass, p);
1109 GETLONG(ttl, p);
1110 GETSHORT(rdlen, p);
1111
1112 if (!CHECK_LEN(header, p, plen, rdlen))
1113 return STAT_BOGUS; /* bad packet */
1114
1115 if (qclass == class && rc == 1)
1116 {
1117 psave = p;
1118
1119 if (qtype == T_DNSKEY)
1120 {
1121 if (rdlen < 4)
1122 return STAT_BOGUS; /* bad packet */
1123
1124 GETSHORT(flags, p);
1125 if (*p++ != 3)
1126 return STAT_BOGUS;
1127 algo = *p++;
1128 keytag = dnskey_keytag(algo, flags, p, rdlen - 4);
1129
1130 /* Cache needs to known class for DNSSEC stuff */
1131 a.addr.dnssec.class = class;
1132
1133 if ((key = blockdata_alloc((char*)p, rdlen - 4)))
1134 {
1135 if (!(recp1 = cache_insert(name, &a, now, ttl, F_FORWARD | F_DNSKEY | F_DNSSECOK)))
1136 blockdata_free(key);
1137 else
1138 {
1139 a.addr.keytag = keytag;
1140 log_query(F_NOEXTRA | F_KEYTAG | F_UPSTREAM, name, &a, "DNSKEY keytag %u");
1141
1142 recp1->addr.key.keylen = rdlen - 4;
1143 recp1->addr.key.keydata = key;
1144 recp1->addr.key.algo = algo;
1145 recp1->addr.key.keytag = keytag;
1146 recp1->addr.key.flags = flags;
1147 }
1148 }
1149 }
1150 else if (qtype == T_RRSIG)
1151 {
1152 /* RRSIG, cache if covers DNSKEY RRset */
1153 if (rdlen < 18)
1154 return STAT_BOGUS; /* bad packet */
1155
1156 GETSHORT(type_covered, p);
1157
1158 if (type_covered == T_DNSKEY)
1159 {
1160 a.addr.dnssec.class = class;
1161 a.addr.dnssec.type = type_covered;
1162
1163 algo = *p++;
1164 p += 13; /* labels, orig_ttl, expiration, inception */
1165 GETSHORT(keytag, p);
1166 if ((key = blockdata_alloc((char*)psave, rdlen)))
1167 {
1168 if (!(crecp = cache_insert(name, &a, now, ttl, F_FORWARD | F_DNSKEY | F_DS)))
1169 blockdata_free(key);
1170 else
1171 {
1172 crecp->addr.sig.keydata = key;
1173 crecp->addr.sig.keylen = rdlen;
1174 crecp->addr.sig.keytag = keytag;
1175 crecp->addr.sig.type_covered = type_covered;
1176 crecp->addr.sig.algo = algo;
1177 }
1178 }
1179 }
1180 }
1181
1182 p = psave;
1183 }
1184
1185 if (!ADD_RDLEN(header, p, plen, rdlen))
1186 return STAT_BOGUS; /* bad packet */
1187 }
1188
1189 /* commit cache insert. */
1190 cache_end_insert();
1191 return STAT_SECURE;
1192 }
1193
1194 log_query(F_NOEXTRA | F_UPSTREAM, name, NULL, "BOGUS DNSKEY");
1195 return STAT_BOGUS;
1196 }
1197
1198 /* The DNS packet is expected to contain the answer to a DS query
1199 Put all DSs in the answer which are valid into the cache.
1200 return codes:
1201 STAT_SECURE At least one valid DS found and in cache.
1202 STAT_NO_DS It's proved there's no DS here.
1203 STAT_NO_NS It's proved there's no DS _or_ NS here.
1204 STAT_BOGUS no DS in reply or not signed, fails validation, bad packet.
1205 STAT_NEED_KEY DNSKEY records to validate a DS not found, name in keyname
1206 */
1207
1208 int dnssec_validate_ds(time_t now, struct dns_header *header, size_t plen, char *name, char *keyname, int class)
1209 {
1210 unsigned char *p = (unsigned char *)(header+1);
1211 int qtype, qclass, val, i, neganswer, nons;
1212
1213 if (ntohs(header->qdcount) != 1 ||
1214 !(p = skip_name(p, header, plen, 4)))
1215 return STAT_BOGUS;
1216
1217 GETSHORT(qtype, p);
1218 GETSHORT(qclass, p);
1219
1220 if (qtype != T_DS || qclass != class)
1221 val = STAT_BOGUS;
1222 else
1223 val = dnssec_validate_reply(now, header, plen, name, keyname, NULL, &neganswer, &nons);
1224 /* Note dnssec_validate_reply() will have cached positive answers */
1225
1226 if (val == STAT_INSECURE)
1227 val = STAT_BOGUS;
1228
1229 p = (unsigned char *)(header+1);
1230 extract_name(header, plen, &p, name, 1, 4);
1231 p += 4; /* qtype, qclass */
1232
1233 if (!(p = skip_section(p, ntohs(header->ancount), header, plen)))
1234 val = STAT_BOGUS;
1235
1236 /* If we return STAT_NO_SIG, name contains the name of the DS query */
1237 if (val == STAT_NO_SIG)
1238 {
1239 *keyname = 0;
1240 return val;
1241 }
1242
1243 /* If the key needed to validate the DS is on the same domain as the DS, we'll
1244 loop getting nowhere. Stop that now. This can happen of the DS answer comes
1245 from the DS's zone, and not the parent zone. */
1246 if (val == STAT_BOGUS || (val == STAT_NEED_KEY && hostname_isequal(name, keyname)))
1247 {
1248 log_query(F_NOEXTRA | F_UPSTREAM, name, NULL, "BOGUS DS");
1249 return STAT_BOGUS;
1250 }
1251
1252 /* By here, the answer is proved secure, and a positive answer has been cached. */
1253 if (val == STAT_SECURE && neganswer)
1254 {
1255 int rdlen, flags = F_FORWARD | F_DS | F_NEG | F_DNSSECOK;
1256 unsigned long ttl, minttl = ULONG_MAX;
1257 struct all_addr a;
1258
1259 if (RCODE(header) == NXDOMAIN)
1260 flags |= F_NXDOMAIN;
1261
1262 /* We only cache validated DS records, DNSSECOK flag hijacked
1263 to store presence/absence of NS. */
1264 if (nons)
1265 flags &= ~F_DNSSECOK;
1266
1267 for (i = ntohs(header->nscount); i != 0; i--)
1268 {
1269 if (!(p = skip_name(p, header, plen, 0)))
1270 return STAT_BOGUS;
1271
1272 GETSHORT(qtype, p);
1273 GETSHORT(qclass, p);
1274 GETLONG(ttl, p);
1275 GETSHORT(rdlen, p);
1276
1277 if (!CHECK_LEN(header, p, plen, rdlen))
1278 return STAT_BOGUS; /* bad packet */
1279
1280 if (qclass != class || qtype != T_SOA)
1281 {
1282 p += rdlen;
1283 continue;
1284 }
1285
1286 if (ttl < minttl)
1287 minttl = ttl;
1288
1289 /* MNAME */
1290 if (!(p = skip_name(p, header, plen, 0)))
1291 return STAT_BOGUS;
1292 /* RNAME */
1293 if (!(p = skip_name(p, header, plen, 20)))
1294 return STAT_BOGUS;
1295 p += 16; /* SERIAL REFRESH RETRY EXPIRE */
1296
1297 GETLONG(ttl, p); /* minTTL */
1298 if (ttl < minttl)
1299 minttl = ttl;
1300
1301 break;
1302 }
1303
1304 if (i != 0)
1305 {
1306 cache_start_insert();
1307
1308 a.addr.dnssec.class = class;
1309 cache_insert(name, &a, now, ttl, flags);
1310
1311 cache_end_insert();
1312
1313 log_query(F_NOEXTRA | F_UPSTREAM, name, NULL, nons ? "no delegation" : "no DS");
1314 }
1315
1316 return nons ? STAT_NO_NS : STAT_NO_DS;
1317 }
1318
1319 return val;
1320 }
1321
1322 /* 4034 6.1 */
1323 static int hostname_cmp(const char *a, const char *b)
1324 {
1325 char *sa, *ea, *ca, *sb, *eb, *cb;
1326 unsigned char ac, bc;
1327
1328 sa = ea = (char *)a + strlen(a);
1329 sb = eb = (char *)b + strlen(b);
1330
1331 while (1)
1332 {
1333 while (sa != a && *(sa-1) != '.')
1334 sa--;
1335
1336 while (sb != b && *(sb-1) != '.')
1337 sb--;
1338
1339 ca = sa;
1340 cb = sb;
1341
1342 while (1)
1343 {
1344 if (ca == ea)
1345 {
1346 if (cb == eb)
1347 break;
1348
1349 return -1;
1350 }
1351
1352 if (cb == eb)
1353 return 1;
1354
1355 ac = (unsigned char) *ca++;
1356 bc = (unsigned char) *cb++;
1357
1358 if (ac >= 'A' && ac <= 'Z')
1359 ac += 'a' - 'A';
1360 if (bc >= 'A' && bc <= 'Z')
1361 bc += 'a' - 'A';
1362
1363 if (ac < bc)
1364 return -1;
1365 else if (ac != bc)
1366 return 1;
1367 }
1368
1369
1370 if (sa == a)
1371 {
1372 if (sb == b)
1373 return 0;
1374
1375 return -1;
1376 }
1377
1378 if (sb == b)
1379 return 1;
1380
1381 ea = sa--;
1382 eb = sb--;
1383 }
1384 }
1385
1386 /* Find all the NSEC or NSEC3 records in a reply.
1387 return an array of pointers to them. */
1388 static int find_nsec_records(struct dns_header *header, size_t plen, unsigned char ***nsecsetp, int *nsecsetl, int class_reqd)
1389 {
1390 static unsigned char **nsecset = NULL;
1391 static int nsecset_sz = 0;
1392
1393 int type_found = 0;
1394 unsigned char *p = skip_questions(header, plen);
1395 int type, class, rdlen, i, nsecs_found;
1396
1397 /* Move to NS section */
1398 if (!p || !(p = skip_section(p, ntohs(header->ancount), header, plen)))
1399 return 0;
1400
1401 for (nsecs_found = 0, i = ntohs(header->nscount); i != 0; i--)
1402 {
1403 unsigned char *pstart = p;
1404
1405 if (!(p = skip_name(p, header, plen, 10)))
1406 return 0;
1407
1408 GETSHORT(type, p);
1409 GETSHORT(class, p);
1410 p += 4; /* TTL */
1411 GETSHORT(rdlen, p);
1412
1413 if (class == class_reqd && (type == T_NSEC || type == T_NSEC3))
1414 {
1415 /* No mixed NSECing 'round here, thankyouverymuch */
1416 if (type_found == T_NSEC && type == T_NSEC3)
1417 return 0;
1418 if (type_found == T_NSEC3 && type == T_NSEC)
1419 return 0;
1420
1421 type_found = type;
1422
1423 if (!expand_workspace(&nsecset, &nsecset_sz, nsecs_found))
1424 return 0;
1425
1426 nsecset[nsecs_found++] = pstart;
1427 }
1428
1429 if (!ADD_RDLEN(header, p, plen, rdlen))
1430 return 0;
1431 }
1432
1433 *nsecsetp = nsecset;
1434 *nsecsetl = nsecs_found;
1435
1436 return type_found;
1437 }
1438
1439 static int prove_non_existence_nsec(struct dns_header *header, size_t plen, unsigned char **nsecs, int nsec_count,
1440 char *workspace1, char *workspace2, char *name, int type, int *nons)
1441 {
1442 int i, rc, rdlen;
1443 unsigned char *p, *psave;
1444 int offset = (type & 0xff) >> 3;
1445 int mask = 0x80 >> (type & 0x07);
1446
1447 if (nons)
1448 *nons = 0;
1449
1450 /* Find NSEC record that proves name doesn't exist */
1451 for (i = 0; i < nsec_count; i++)
1452 {
1453 p = nsecs[i];
1454 if (!extract_name(header, plen, &p, workspace1, 1, 10))
1455 return STAT_BOGUS;
1456 p += 8; /* class, type, TTL */
1457 GETSHORT(rdlen, p);
1458 psave = p;
1459 if (!extract_name(header, plen, &p, workspace2, 1, 10))
1460 return STAT_BOGUS;
1461
1462 rc = hostname_cmp(workspace1, name);
1463
1464 if (rc == 0)
1465 {
1466 /* 4035 para 5.4. Last sentence */
1467 if (type == T_NSEC || type == T_RRSIG)
1468 return STAT_SECURE;
1469
1470 /* NSEC with the same name as the RR we're testing, check
1471 that the type in question doesn't appear in the type map */
1472 rdlen -= p - psave;
1473 /* rdlen is now length of type map, and p points to it */
1474
1475 /* If we can prove that there's no NS record, return that information. */
1476 if (nons && rdlen >= 2 && p[0] == 0 && (p[2] & (0x80 >> T_NS)) == 0)
1477 *nons = 1;
1478
1479 while (rdlen >= 2)
1480 {
1481 if (!CHECK_LEN(header, p, plen, rdlen))
1482 return STAT_BOGUS;
1483
1484 if (p[0] == type >> 8)
1485 {
1486 /* Does the NSEC say our type exists? */
1487 if (offset < p[1] && (p[offset+2] & mask) != 0)
1488 return STAT_BOGUS;
1489
1490 break; /* finshed checking */
1491 }
1492
1493 rdlen -= p[1];
1494 p += p[1];
1495 }
1496
1497 return STAT_SECURE;
1498 }
1499 else if (rc == -1)
1500 {
1501 /* Normal case, name falls between NSEC name and next domain name,
1502 wrap around case, name falls between NSEC name (rc == -1) and end */
1503 if (hostname_cmp(workspace2, name) >= 0 || hostname_cmp(workspace1, workspace2) >= 0)
1504 return STAT_SECURE;
1505 }
1506 else
1507 {
1508 /* wrap around case, name falls between start and next domain name */
1509 if (hostname_cmp(workspace1, workspace2) >= 0 && hostname_cmp(workspace2, name) >=0 )
1510 return STAT_SECURE;
1511 }
1512 }
1513
1514 return STAT_BOGUS;
1515 }
1516
1517 /* return digest length, or zero on error */
1518 static int hash_name(char *in, unsigned char **out, struct nettle_hash const *hash,
1519 unsigned char *salt, int salt_len, int iterations)
1520 {
1521 void *ctx;
1522 unsigned char *digest;
1523 int i;
1524
1525 if (!hash_init(hash, &ctx, &digest))
1526 return 0;
1527
1528 hash->update(ctx, to_wire(in), (unsigned char *)in);
1529 hash->update(ctx, salt_len, salt);
1530 hash->digest(ctx, hash->digest_size, digest);
1531
1532 for(i = 0; i < iterations; i++)
1533 {
1534 hash->update(ctx, hash->digest_size, digest);
1535 hash->update(ctx, salt_len, salt);
1536 hash->digest(ctx, hash->digest_size, digest);
1537 }
1538
1539 from_wire(in);
1540
1541 *out = digest;
1542 return hash->digest_size;
1543 }
1544
1545 /* Decode base32 to first "." or end of string */
1546 static int base32_decode(char *in, unsigned char *out)
1547 {
1548 int oc, on, c, mask, i;
1549 unsigned char *p = out;
1550
1551 for (c = *in, oc = 0, on = 0; c != 0 && c != '.'; c = *++in)
1552 {
1553 if (c >= '0' && c <= '9')
1554 c -= '0';
1555 else if (c >= 'a' && c <= 'v')
1556 c -= 'a', c += 10;
1557 else if (c >= 'A' && c <= 'V')
1558 c -= 'A', c += 10;
1559 else
1560 return 0;
1561
1562 for (mask = 0x10, i = 0; i < 5; i++)
1563 {
1564 if (c & mask)
1565 oc |= 1;
1566 mask = mask >> 1;
1567 if (((++on) & 7) == 0)
1568 *p++ = oc;
1569 oc = oc << 1;
1570 }
1571 }
1572
1573 if ((on & 7) != 0)
1574 return 0;
1575
1576 return p - out;
1577 }
1578
1579 static int check_nsec3_coverage(struct dns_header *header, size_t plen, int digest_len, unsigned char *digest, int type,
1580 char *workspace1, char *workspace2, unsigned char **nsecs, int nsec_count, int *nons)
1581 {
1582 int i, hash_len, salt_len, base32_len, rdlen;
1583 unsigned char *p, *psave;
1584
1585 for (i = 0; i < nsec_count; i++)
1586 if ((p = nsecs[i]))
1587 {
1588 if (!extract_name(header, plen, &p, workspace1, 1, 0) ||
1589 !(base32_len = base32_decode(workspace1, (unsigned char *)workspace2)))
1590 return 0;
1591
1592 p += 8; /* class, type, TTL */
1593 GETSHORT(rdlen, p);
1594 psave = p;
1595 p += 4; /* algo, flags, iterations */
1596 salt_len = *p++; /* salt_len */
1597 p += salt_len; /* salt */
1598 hash_len = *p++; /* p now points to next hashed name */
1599
1600 if (!CHECK_LEN(header, p, plen, hash_len))
1601 return 0;
1602
1603 if (digest_len == base32_len && hash_len == base32_len)
1604 {
1605 int rc = memcmp(workspace2, digest, digest_len);
1606
1607 if (rc == 0)
1608 {
1609 /* We found an NSEC3 whose hashed name exactly matches the query, so
1610 we just need to check the type map. p points to the RR data for the record. */
1611
1612 int offset = (type & 0xff) >> 3;
1613 int mask = 0x80 >> (type & 0x07);
1614
1615 p += hash_len; /* skip next-domain hash */
1616 rdlen -= p - psave;
1617
1618 if (!CHECK_LEN(header, p, plen, rdlen))
1619 return 0;
1620
1621 /* If we can prove that there's no NS record, return that information. */
1622 if (nons && rdlen >= 2 && p[0] == 0 && (p[2] & (0x80 >> T_NS)) == 0)
1623 *nons = 1;
1624
1625 while (rdlen >= 2)
1626 {
1627 if (p[0] == type >> 8)
1628 {
1629 /* Does the NSEC3 say our type exists? */
1630 if (offset < p[1] && (p[offset+2] & mask) != 0)
1631 return STAT_BOGUS;
1632
1633 break; /* finshed checking */
1634 }
1635
1636 rdlen -= p[1];
1637 p += p[1];
1638 }
1639
1640 return 1;
1641 }
1642 else if (rc < 0)
1643 {
1644 /* Normal case, hash falls between NSEC3 name-hash and next domain name-hash,
1645 wrap around case, name-hash falls between NSEC3 name-hash and end */
1646 if (memcmp(p, digest, digest_len) >= 0 || memcmp(workspace2, p, digest_len) >= 0)
1647 return 1;
1648 }
1649 else
1650 {
1651 /* wrap around case, name falls between start and next domain name */
1652 if (memcmp(workspace2, p, digest_len) >= 0 && memcmp(p, digest, digest_len) >= 0)
1653 return 1;
1654 }
1655 }
1656 }
1657 return 0;
1658 }
1659
1660 static int prove_non_existence_nsec3(struct dns_header *header, size_t plen, unsigned char **nsecs, int nsec_count,
1661 char *workspace1, char *workspace2, char *name, int type, char *wildname, int *nons)
1662 {
1663 unsigned char *salt, *p, *digest;
1664 int digest_len, i, iterations, salt_len, base32_len, algo = 0;
1665 struct nettle_hash const *hash;
1666 char *closest_encloser, *next_closest, *wildcard;
1667
1668 if (nons)
1669 *nons = 0;
1670
1671 /* Look though the NSEC3 records to find the first one with
1672 an algorithm we support (currently only algo == 1).
1673
1674 Take the algo, iterations, and salt of that record
1675 as the ones we're going to use, and prune any
1676 that don't match. */
1677
1678 for (i = 0; i < nsec_count; i++)
1679 {
1680 if (!(p = skip_name(nsecs[i], header, plen, 15)))
1681 return STAT_BOGUS; /* bad packet */
1682
1683 p += 10; /* type, class, TTL, rdlen */
1684 algo = *p++;
1685
1686 if (algo == 1)
1687 break; /* known algo */
1688 }
1689
1690 /* No usable NSEC3s */
1691 if (i == nsec_count)
1692 return STAT_BOGUS;
1693
1694 p++; /* flags */
1695 GETSHORT (iterations, p);
1696 salt_len = *p++;
1697 salt = p;
1698 if (!CHECK_LEN(header, salt, plen, salt_len))
1699 return STAT_BOGUS; /* bad packet */
1700
1701 /* Now prune so we only have NSEC3 records with same iterations, salt and algo */
1702 for (i = 0; i < nsec_count; i++)
1703 {
1704 unsigned char *nsec3p = nsecs[i];
1705 int this_iter;
1706
1707 nsecs[i] = NULL; /* Speculative, will be restored if OK. */
1708
1709 if (!(p = skip_name(nsec3p, header, plen, 15)))
1710 return STAT_BOGUS; /* bad packet */
1711
1712 p += 10; /* type, class, TTL, rdlen */
1713
1714 if (*p++ != algo)
1715 continue;
1716
1717 p++; /* flags */
1718
1719 GETSHORT(this_iter, p);
1720 if (this_iter != iterations)
1721 continue;
1722
1723 if (salt_len != *p++)
1724 continue;
1725
1726 if (!CHECK_LEN(header, p, plen, salt_len))
1727 return STAT_BOGUS; /* bad packet */
1728
1729 if (memcmp(p, salt, salt_len) != 0)
1730 continue;
1731
1732 /* All match, put the pointer back */
1733 nsecs[i] = nsec3p;
1734 }
1735
1736 /* Algo is checked as 1 above */
1737 if (!(hash = hash_find("sha1")))
1738 return STAT_BOGUS;
1739
1740 if ((digest_len = hash_name(name, &digest, hash, salt, salt_len, iterations)) == 0)
1741 return STAT_BOGUS;
1742
1743 if (check_nsec3_coverage(header, plen, digest_len, digest, type, workspace1, workspace2, nsecs, nsec_count, nons))
1744 return STAT_SECURE;
1745
1746 /* Can't find an NSEC3 which covers the name directly, we need the "closest encloser NSEC3"
1747 or an answer inferred from a wildcard record. */
1748 closest_encloser = name;
1749 next_closest = NULL;
1750
1751 do
1752 {
1753 if (*closest_encloser == '.')
1754 closest_encloser++;
1755
1756 if (wildname && hostname_isequal(closest_encloser, wildname))
1757 break;
1758
1759 if ((digest_len = hash_name(closest_encloser, &digest, hash, salt, salt_len, iterations)) == 0)
1760 return STAT_BOGUS;
1761
1762 for (i = 0; i < nsec_count; i++)
1763 if ((p = nsecs[i]))
1764 {
1765 if (!extract_name(header, plen, &p, workspace1, 1, 0) ||
1766 !(base32_len = base32_decode(workspace1, (unsigned char *)workspace2)))
1767 return STAT_BOGUS;
1768
1769 if (digest_len == base32_len &&
1770 memcmp(digest, workspace2, digest_len) == 0)
1771 break; /* Gotit */
1772 }
1773
1774 if (i != nsec_count)
1775 break;
1776
1777 next_closest = closest_encloser;
1778 }
1779 while ((closest_encloser = strchr(closest_encloser, '.')));
1780
1781 if (!closest_encloser)
1782 return STAT_BOGUS;
1783
1784 /* Look for NSEC3 that proves the non-existence of the next-closest encloser */
1785 if ((digest_len = hash_name(next_closest, &digest, hash, salt, salt_len, iterations)) == 0)
1786 return STAT_BOGUS;
1787
1788 if (!check_nsec3_coverage(header, plen, digest_len, digest, type, workspace1, workspace2, nsecs, nsec_count, NULL))
1789 return STAT_BOGUS;
1790
1791 /* Finally, check that there's no seat of wildcard synthesis */
1792 if (!wildname)
1793 {
1794 if (!(wildcard = strchr(next_closest, '.')) || wildcard == next_closest)
1795 return STAT_BOGUS;
1796
1797 wildcard--;
1798 *wildcard = '*';
1799
1800 if ((digest_len = hash_name(wildcard, &digest, hash, salt, salt_len, iterations)) == 0)
1801 return STAT_BOGUS;
1802
1803 if (!check_nsec3_coverage(header, plen, digest_len, digest, type, workspace1, workspace2, nsecs, nsec_count, NULL))
1804 return STAT_BOGUS;
1805 }
1806
1807 return STAT_SECURE;
1808 }
1809
1810 /* Validate all the RRsets in the answer and authority sections of the reply (4035:3.2.3) */
1811 /* Returns are the same as validate_rrset, plus the class if the missing key is in *class */
1812 int dnssec_validate_reply(time_t now, struct dns_header *header, size_t plen, char *name, char *keyname,
1813 int *class, int *neganswer, int *nons)
1814 {
1815 unsigned char *ans_start, *qname, *p1, *p2, **nsecs;
1816 int type1, class1, rdlen1, type2, class2, rdlen2, qclass, qtype;
1817 int i, j, rc, nsec_count, cname_count = CNAME_CHAIN;
1818 int nsec_type = 0, have_answer = 0;
1819
1820 if (neganswer)
1821 *neganswer = 0;
1822
1823 if (RCODE(header) == SERVFAIL || ntohs(header->qdcount) != 1)
1824 return STAT_BOGUS;
1825
1826 if (RCODE(header) != NXDOMAIN && RCODE(header) != NOERROR)
1827 return STAT_INSECURE;
1828
1829 qname = p1 = (unsigned char *)(header+1);
1830
1831 if (!extract_name(header, plen, &p1, name, 1, 4))
1832 return STAT_BOGUS;
1833
1834 GETSHORT(qtype, p1);
1835 GETSHORT(qclass, p1);
1836 ans_start = p1;
1837
1838 if (qtype == T_ANY)
1839 have_answer = 1;
1840
1841 /* Can't validate an RRISG query */
1842 if (qtype == T_RRSIG)
1843 return STAT_INSECURE;
1844
1845 cname_loop:
1846 for (j = ntohs(header->ancount); j != 0; j--)
1847 {
1848 /* leave pointer to missing name in qname */
1849
1850 if (!(rc = extract_name(header, plen, &p1, name, 0, 10)))
1851 return STAT_BOGUS; /* bad packet */
1852
1853 GETSHORT(type2, p1);
1854 GETSHORT(class2, p1);
1855 p1 += 4; /* TTL */
1856 GETSHORT(rdlen2, p1);
1857
1858 if (rc == 1 && qclass == class2)
1859 {
1860 /* Do we have an answer for the question? */
1861 if (type2 == qtype)
1862 {
1863 have_answer = 1;
1864 break;
1865 }
1866 else if (type2 == T_CNAME)
1867 {
1868 qname = p1;
1869
1870 /* looped CNAMES */
1871 if (!cname_count-- || !extract_name(header, plen, &p1, name, 1, 0))
1872 return STAT_BOGUS;
1873
1874 p1 = ans_start;
1875 goto cname_loop;
1876 }
1877 }
1878
1879 if (!ADD_RDLEN(header, p1, plen, rdlen2))
1880 return STAT_BOGUS;
1881 }
1882
1883 if (neganswer && !have_answer)
1884 *neganswer = 1;
1885
1886 /* No data, therefore no sigs */
1887 if (ntohs(header->ancount) + ntohs(header->nscount) == 0)
1888 {
1889 *keyname = 0;
1890 return STAT_NO_SIG;
1891 }
1892
1893 for (p1 = ans_start, i = 0; i < ntohs(header->ancount) + ntohs(header->nscount); i++)
1894 {
1895 if (!extract_name(header, plen, &p1, name, 1, 10))
1896 return STAT_BOGUS; /* bad packet */
1897
1898 GETSHORT(type1, p1);
1899 GETSHORT(class1, p1);
1900 p1 += 4; /* TTL */
1901 GETSHORT(rdlen1, p1);
1902
1903 /* Don't try and validate RRSIGs! */
1904 if (type1 != T_RRSIG)
1905 {
1906 /* Check if we've done this RRset already */
1907 for (p2 = ans_start, j = 0; j < i; j++)
1908 {
1909 if (!(rc = extract_name(header, plen, &p2, name, 0, 10)))
1910 return STAT_BOGUS; /* bad packet */
1911
1912 GETSHORT(type2, p2);
1913 GETSHORT(class2, p2);
1914 p2 += 4; /* TTL */
1915 GETSHORT(rdlen2, p2);
1916
1917 if (type2 == type1 && class2 == class1 && rc == 1)
1918 break; /* Done it before: name, type, class all match. */
1919
1920 if (!ADD_RDLEN(header, p2, plen, rdlen2))
1921 return STAT_BOGUS;
1922 }
1923
1924 /* Not done, validate now */
1925 if (j == i)
1926 {
1927 int ttl, keytag, algo, digest, type_covered;
1928 unsigned char *psave;
1929 struct all_addr a;
1930 struct blockdata *key;
1931 struct crec *crecp;
1932 char *wildname;
1933 int have_wildcard = 0;
1934
1935 rc = validate_rrset(now, header, plen, class1, type1, name, keyname, &wildname, NULL, 0, 0, 0);
1936
1937 if (rc == STAT_SECURE_WILDCARD)
1938 {
1939 have_wildcard = 1;
1940
1941 /* An attacker replay a wildcard answer with a different
1942 answer and overlay a genuine RR. To prove this
1943 hasn't happened, the answer must prove that
1944 the gennuine record doesn't exist. Check that here. */
1945 if (!nsec_type && !(nsec_type = find_nsec_records(header, plen, &nsecs, &nsec_count, class1)))
1946 return STAT_BOGUS; /* No NSECs or bad packet */
1947
1948 if (nsec_type == T_NSEC)
1949 rc = prove_non_existence_nsec(header, plen, nsecs, nsec_count, daemon->workspacename, keyname, name, type1, NULL);
1950 else
1951 rc = prove_non_existence_nsec3(header, plen, nsecs, nsec_count, daemon->workspacename,
1952 keyname, name, type1, wildname, NULL);
1953
1954 if (rc != STAT_SECURE)
1955 return rc;
1956 }
1957 else if (rc != STAT_SECURE)
1958 {
1959 if (class)
1960 *class = class1; /* Class for DS or DNSKEY */
1961
1962 if (rc == STAT_NO_SIG)
1963 {
1964 /* If we dropped off the end of a CNAME chain, return
1965 STAT_NO_SIG and the last name is keyname. This is used for proving non-existence
1966 if DS records in CNAME chains. */
1967 if (cname_count == CNAME_CHAIN || i < ntohs(header->ancount))
1968 /* No CNAME chain, or no sig in answer section, return empty name. */
1969 *keyname = 0;
1970 else if (!extract_name(header, plen, &qname, keyname, 1, 0))
1971 return STAT_BOGUS;
1972 }
1973
1974 return rc;
1975 }
1976
1977 /* Cache RRsigs in answer section, and if we just validated a DS RRset, cache it */
1978 cache_start_insert();
1979
1980 for (p2 = ans_start, j = 0; j < ntohs(header->ancount); j++)
1981 {
1982 if (!(rc = extract_name(header, plen, &p2, name, 0, 10)))
1983 return STAT_BOGUS; /* bad packet */
1984
1985 GETSHORT(type2, p2);
1986 GETSHORT(class2, p2);
1987 GETLONG(ttl, p2);
1988 GETSHORT(rdlen2, p2);
1989
1990 if (!CHECK_LEN(header, p2, plen, rdlen2))
1991 return STAT_BOGUS; /* bad packet */
1992
1993 if (class2 == class1 && rc == 1)
1994 {
1995 psave = p2;
1996
1997 if (type1 == T_DS && type2 == T_DS)
1998 {
1999 if (rdlen2 < 4)
2000 return STAT_BOGUS; /* bad packet */
2001
2002 GETSHORT(keytag, p2);
2003 algo = *p2++;
2004 digest = *p2++;
2005
2006 /* Cache needs to known class for DNSSEC stuff */
2007 a.addr.dnssec.class = class2;
2008
2009 if ((key = blockdata_alloc((char*)p2, rdlen2 - 4)))
2010 {
2011 if (!(crecp = cache_insert(name, &a, now, ttl, F_FORWARD | F_DS | F_DNSSECOK)))
2012 blockdata_free(key);
2013 else
2014 {
2015 a.addr.keytag = keytag;
2016 log_query(F_NOEXTRA | F_KEYTAG | F_UPSTREAM, name, &a, "DS keytag %u");
2017 crecp->addr.ds.digest = digest;
2018 crecp->addr.ds.keydata = key;
2019 crecp->addr.ds.algo = algo;
2020 crecp->addr.ds.keytag = keytag;
2021 crecp->addr.ds.keylen = rdlen2 - 4;
2022 }
2023 }
2024 }
2025 else if (type2 == T_RRSIG)
2026 {
2027 if (rdlen2 < 18)
2028 return STAT_BOGUS; /* bad packet */
2029
2030 GETSHORT(type_covered, p2);
2031
2032 if (type_covered == type1 &&
2033 (type_covered == T_A || type_covered == T_AAAA ||
2034 type_covered == T_CNAME || type_covered == T_DS ||
2035 type_covered == T_DNSKEY || type_covered == T_PTR))
2036 {
2037 a.addr.dnssec.type = type_covered;
2038 a.addr.dnssec.class = class1;
2039
2040 algo = *p2++;
2041 p2 += 13; /* labels, orig_ttl, expiration, inception */
2042 GETSHORT(keytag, p2);
2043
2044 /* We don't cache sigs for wildcard answers, because to reproduce the
2045 answer from the cache will require one or more NSEC/NSEC3 records
2046 which we don't cache. The lack of the RRSIG ensures that a query for
2047 this RRset asking for a secure answer will always be forwarded. */
2048 if (!have_wildcard && (key = blockdata_alloc((char*)psave, rdlen2)))
2049 {
2050 if (!(crecp = cache_insert(name, &a, now, ttl, F_FORWARD | F_DNSKEY | F_DS)))
2051 blockdata_free(key);
2052 else
2053 {
2054 crecp->addr.sig.keydata = key;
2055 crecp->addr.sig.keylen = rdlen2;
2056 crecp->addr.sig.keytag = keytag;
2057 crecp->addr.sig.type_covered = type_covered;
2058 crecp->addr.sig.algo = algo;
2059 }
2060 }
2061 }
2062 }
2063
2064 p2 = psave;
2065 }
2066
2067 if (!ADD_RDLEN(header, p2, plen, rdlen2))
2068 return STAT_BOGUS; /* bad packet */
2069 }
2070
2071 cache_end_insert();
2072 }
2073 }
2074
2075 if (!ADD_RDLEN(header, p1, plen, rdlen1))
2076 return STAT_BOGUS;
2077 }
2078
2079 /* OK, all the RRsets validate, now see if we have a NODATA or NXDOMAIN reply */
2080 if (have_answer)
2081 return STAT_SECURE;
2082
2083 /* NXDOMAIN or NODATA reply, prove that (name, class1, type1) can't exist */
2084 /* First marshall the NSEC records, if we've not done it previously */
2085 if (!nsec_type && !(nsec_type = find_nsec_records(header, plen, &nsecs, &nsec_count, qclass)))
2086 {
2087 /* No NSEC records. If we dropped off the end of a CNAME chain, return
2088 STAT_NO_SIG and the last name is keyname. This is used for proving non-existence
2089 if DS records in CNAME chains. */
2090 if (cname_count == CNAME_CHAIN) /* No CNAME chain, return empty name. */
2091 *keyname = 0;
2092 else if (!extract_name(header, plen, &qname, keyname, 1, 0))
2093 return STAT_BOGUS;
2094 return STAT_NO_SIG; /* No NSECs, this is probably a dangling CNAME pointing into
2095 an unsigned zone. Return STAT_NO_SIG to cause this to be proved. */
2096 }
2097
2098 /* Get name of missing answer */
2099 if (!extract_name(header, plen, &qname, name, 1, 0))
2100 return STAT_BOGUS;
2101
2102 if (nsec_type == T_NSEC)
2103 return prove_non_existence_nsec(header, plen, nsecs, nsec_count, daemon->workspacename, keyname, name, qtype, nons);
2104 else
2105 return prove_non_existence_nsec3(header, plen, nsecs, nsec_count, daemon->workspacename, keyname, name, qtype, NULL, nons);
2106 }
2107
2108 /* Chase the CNAME chain in the packet until the first record which _doesn't validate.
2109 Needed for proving answer in unsigned space.
2110 Return STAT_NEED_*
2111 STAT_BOGUS - error
2112 STAT_INSECURE - name of first non-secure record in name
2113 */
2114 int dnssec_chase_cname(time_t now, struct dns_header *header, size_t plen, char *name, char *keyname)
2115 {
2116 unsigned char *p = (unsigned char *)(header+1);
2117 int type, class, qclass, rdlen, j, rc;
2118 int cname_count = CNAME_CHAIN;
2119 char *wildname;
2120
2121 /* Get question */
2122 if (!extract_name(header, plen, &p, name, 1, 4))
2123 return STAT_BOGUS;
2124
2125 p +=2; /* type */
2126 GETSHORT(qclass, p);
2127
2128 while (1)
2129 {
2130 for (j = ntohs(header->ancount); j != 0; j--)
2131 {
2132 if (!(rc = extract_name(header, plen, &p, name, 0, 10)))
2133 return STAT_BOGUS; /* bad packet */
2134
2135 GETSHORT(type, p);
2136 GETSHORT(class, p);
2137 p += 4; /* TTL */
2138 GETSHORT(rdlen, p);
2139
2140 /* Not target, loop */
2141 if (rc == 2 || qclass != class)
2142 {
2143 if (!ADD_RDLEN(header, p, plen, rdlen))
2144 return STAT_BOGUS;
2145 continue;
2146 }
2147
2148 /* Got to end of CNAME chain. */
2149 if (type != T_CNAME)
2150 return STAT_INSECURE;
2151
2152 /* validate CNAME chain, return if insecure or need more data */
2153 rc = validate_rrset(now, header, plen, class, type, name, keyname, &wildname, NULL, 0, 0, 0);
2154
2155 if (rc == STAT_SECURE_WILDCARD)
2156 {
2157 int nsec_type, nsec_count, i;
2158 unsigned char **nsecs;
2159
2160 /* An attacker can replay a wildcard answer with a different
2161 answer and overlay a genuine RR. To prove this
2162 hasn't happened, the answer must prove that
2163 the genuine record doesn't exist. Check that here. */
2164 if (!(nsec_type = find_nsec_records(header, plen, &nsecs, &nsec_count, class)))
2165 return STAT_BOGUS; /* No NSECs or bad packet */
2166
2167 /* Note that we're called here because something didn't validate in validate_reply,
2168 so we can't assume that any NSEC records have been validated. We do them by steam here */
2169
2170 for (i = 0; i < nsec_count; i++)
2171 {
2172 unsigned char *p1 = nsecs[i];
2173
2174 if (!extract_name(header, plen, &p1, daemon->workspacename, 1, 0))
2175 return STAT_BOGUS;
2176
2177 rc = validate_rrset(now, header, plen, class, nsec_type, daemon->workspacename, keyname, NULL, NULL, 0, 0, 0);
2178
2179 /* NSECs can't be wildcards. */
2180 if (rc == STAT_SECURE_WILDCARD)
2181 rc = STAT_BOGUS;
2182
2183 if (rc != STAT_SECURE)
2184 return rc;
2185 }
2186
2187 if (nsec_type == T_NSEC)
2188 rc = prove_non_existence_nsec(header, plen, nsecs, nsec_count, daemon->workspacename, keyname, name, type, NULL);
2189 else
2190 rc = prove_non_existence_nsec3(header, plen, nsecs, nsec_count, daemon->workspacename,
2191 keyname, name, type, wildname, NULL);
2192
2193 if (rc != STAT_SECURE)
2194 return rc;
2195 }
2196
2197 if (rc != STAT_SECURE)
2198 {
2199 if (rc == STAT_NO_SIG)
2200 rc = STAT_INSECURE;
2201 return rc;
2202 }
2203
2204 /* Loop down CNAME chain/ */
2205 if (!cname_count-- ||
2206 !extract_name(header, plen, &p, name, 1, 0) ||
2207 !(p = skip_questions(header, plen)))
2208 return STAT_BOGUS;
2209
2210 break;
2211 }
2212
2213 /* End of CNAME chain */
2214 return STAT_INSECURE;
2215 }
2216 }
2217
2218
2219 /* Compute keytag (checksum to quickly index a key). See RFC4034 */
2220 int dnskey_keytag(int alg, int flags, unsigned char *key, int keylen)
2221 {
2222 if (alg == 1)
2223 {
2224 /* Algorithm 1 (RSAMD5) has a different (older) keytag calculation algorithm.
2225 See RFC4034, Appendix B.1 */
2226 return key[keylen-4] * 256 + key[keylen-3];
2227 }
2228 else
2229 {
2230 unsigned long ac = flags + 0x300 + alg;
2231 int i;
2232
2233 for (i = 0; i < keylen; ++i)
2234 ac += (i & 1) ? key[i] : key[i] << 8;
2235
2236 ac += (ac >> 16) & 0xffff;
2237 return ac & 0xffff;
2238 }
2239 }
2240
2241 size_t dnssec_generate_query(struct dns_header *header, char *end, char *name, int class,
2242 int type, union mysockaddr *addr, int edns_pktsz)
2243 {
2244 unsigned char *p;
2245 char *types = querystr("dnssec-query", type);
2246 size_t ret;
2247
2248 if (addr->sa.sa_family == AF_INET)
2249 log_query(F_NOEXTRA | F_DNSSEC | F_IPV4, name, (struct all_addr *)&addr->in.sin_addr, types);
2250 #ifdef HAVE_IPV6
2251 else
2252 log_query(F_NOEXTRA | F_DNSSEC | F_IPV6, name, (struct all_addr *)&addr->in6.sin6_addr, types);
2253 #endif
2254
2255 header->qdcount = htons(1);
2256 header->ancount = htons(0);
2257 header->nscount = htons(0);
2258 header->arcount = htons(0);
2259
2260 header->hb3 = HB3_RD;
2261 SET_OPCODE(header, QUERY);
2262 /* For debugging, set Checking Disabled, otherwise, have the upstream check too,
2263 this allows it to select auth servers when one is returning bad data. */
2264 header->hb4 = option_bool(OPT_DNSSEC_DEBUG) ? HB4_CD : 0;
2265
2266 /* ID filled in later */
2267
2268 p = (unsigned char *)(header+1);
2269
2270 p = do_rfc1035_name(p, name);
2271 *p++ = 0;
2272 PUTSHORT(type, p);
2273 PUTSHORT(class, p);
2274
2275 ret = add_do_bit(header, p - (unsigned char *)header, end);
2276
2277 if (find_pseudoheader(header, ret, NULL, &p, NULL))
2278 PUTSHORT(edns_pktsz, p);
2279
2280 return ret;
2281 }
2282
2283 /* Go through a domain name, find "pointers" and fix them up based on how many bytes
2284 we've chopped out of the packet, or check they don't point into an elided part. */
2285 static int check_name(unsigned char **namep, struct dns_header *header, size_t plen, int fixup, unsigned char **rrs, int rr_count)
2286 {
2287 unsigned char *ansp = *namep;
2288
2289 while(1)
2290 {
2291 unsigned int label_type;
2292
2293 if (!CHECK_LEN(header, ansp, plen, 1))
2294 return 0;
2295
2296 label_type = (*ansp) & 0xc0;
2297
2298 if (label_type == 0xc0)
2299 {
2300 /* pointer for compression. */
2301 unsigned int offset;
2302 int i;
2303 unsigned char *p;
2304
2305 if (!CHECK_LEN(header, ansp, plen, 2))
2306 return 0;
2307
2308 offset = ((*ansp++) & 0x3f) << 8;
2309 offset |= *ansp++;
2310
2311 p = offset + (unsigned char *)header;
2312
2313 for (i = 0; i < rr_count; i++)
2314 if (p < rrs[i])
2315 break;
2316 else
2317 if (i & 1)
2318 offset -= rrs[i] - rrs[i-1];
2319
2320 /* does the pointer end up in an elided RR? */
2321 if (i & 1)
2322 return 0;
2323
2324 /* No, scale the pointer */
2325 if (fixup)
2326 {
2327 ansp -= 2;
2328 *ansp++ = (offset >> 8) | 0xc0;
2329 *ansp++ = offset & 0xff;
2330 }
2331 break;
2332 }
2333 else if (label_type == 0x80)
2334 return 0; /* reserved */
2335 else if (label_type == 0x40)
2336 {
2337 /* Extended label type */
2338 unsigned int count;
2339
2340 if (!CHECK_LEN(header, ansp, plen, 2))
2341 return 0;
2342
2343 if (((*ansp++) & 0x3f) != 1)
2344 return 0; /* we only understand bitstrings */
2345
2346 count = *(ansp++); /* Bits in bitstring */
2347
2348 if (count == 0) /* count == 0 means 256 bits */
2349 ansp += 32;
2350 else
2351 ansp += ((count-1)>>3)+1;
2352 }
2353 else
2354 { /* label type == 0 Bottom six bits is length */
2355 unsigned int len = (*ansp++) & 0x3f;
2356
2357 if (!ADD_RDLEN(header, ansp, plen, len))
2358 return 0;
2359
2360 if (len == 0)
2361 break; /* zero length label marks the end. */
2362 }
2363 }
2364
2365 *namep = ansp;
2366
2367 return 1;
2368 }
2369
2370 /* Go through RRs and check or fixup the domain names contained within */
2371 static int check_rrs(unsigned char *p, struct dns_header *header, size_t plen, int fixup, unsigned char **rrs, int rr_count)
2372 {
2373 int i, type, class, rdlen;
2374 unsigned char *pp;
2375
2376 for (i = 0; i < ntohs(header->ancount) + ntohs(header->nscount) + ntohs(header->arcount); i++)
2377 {
2378 pp = p;
2379
2380 if (!(p = skip_name(p, header, plen, 10)))
2381 return 0;
2382
2383 GETSHORT(type, p);
2384 GETSHORT(class, p);
2385 p += 4; /* TTL */
2386 GETSHORT(rdlen, p);
2387
2388 if (type != T_NSEC && type != T_NSEC3 && type != T_RRSIG)
2389 {
2390 /* fixup name of RR */
2391 if (!check_name(&pp, header, plen, fixup, rrs, rr_count))
2392 return 0;
2393
2394 if (class == C_IN)
2395 {
2396 u16 *d;
2397
2398 for (pp = p, d = get_desc(type); *d != (u16)-1; d++)
2399 {
2400 if (*d != 0)
2401 pp += *d;
2402 else if (!check_name(&pp, header, plen, fixup, rrs, rr_count))
2403 return 0;
2404 }
2405 }
2406 }
2407
2408 if (!ADD_RDLEN(header, p, plen, rdlen))
2409 return 0;
2410 }
2411
2412 return 1;
2413 }
2414
2415
2416 size_t filter_rrsigs(struct dns_header *header, size_t plen)
2417 {
2418 static unsigned char **rrs;
2419 static int rr_sz = 0;
2420
2421 unsigned char *p = (unsigned char *)(header+1);
2422 int i, rdlen, qtype, qclass, rr_found, chop_an, chop_ns, chop_ar;
2423
2424 if (ntohs(header->qdcount) != 1 ||
2425 !(p = skip_name(p, header, plen, 4)))
2426 return plen;
2427
2428 GETSHORT(qtype, p);
2429 GETSHORT(qclass, p);
2430
2431 /* First pass, find pointers to start and end of all the records we wish to elide:
2432 records added for DNSSEC, unless explicity queried for */
2433 for (rr_found = 0, chop_ns = 0, chop_an = 0, chop_ar = 0, i = 0;
2434 i < ntohs(header->ancount) + ntohs(header->nscount) + ntohs(header->arcount);
2435 i++)
2436 {
2437 unsigned char *pstart = p;
2438 int type, class;
2439
2440 if (!(p = skip_name(p, header, plen, 10)))
2441 return plen;
2442
2443 GETSHORT(type, p);
2444 GETSHORT(class, p);
2445 p += 4; /* TTL */
2446 GETSHORT(rdlen, p);
2447
2448 if ((type == T_NSEC || type == T_NSEC3 || type == T_RRSIG) &&
2449 (type != qtype || class != qclass))
2450 {
2451 if (!expand_workspace(&rrs, &rr_sz, rr_found + 1))
2452 return plen;
2453
2454 rrs[rr_found++] = pstart;
2455
2456 if (!ADD_RDLEN(header, p, plen, rdlen))
2457 return plen;
2458
2459 rrs[rr_found++] = p;
2460
2461 if (i < ntohs(header->ancount))
2462 chop_an++;
2463 else if (i < (ntohs(header->nscount) + ntohs(header->ancount)))
2464 chop_ns++;
2465 else
2466 chop_ar++;
2467 }
2468 else if (!ADD_RDLEN(header, p, plen, rdlen))
2469 return plen;
2470 }
2471
2472 /* Nothing to do. */
2473 if (rr_found == 0)
2474 return plen;
2475
2476 /* Second pass, look for pointers in names in the records we're keeping and make sure they don't
2477 point to records we're going to elide. This is theoretically possible, but unlikely. If
2478 it happens, we give up and leave the answer unchanged. */
2479 p = (unsigned char *)(header+1);
2480
2481 /* question first */
2482 if (!check_name(&p, header, plen, 0, rrs, rr_found))
2483 return plen;
2484 p += 4; /* qclass, qtype */
2485
2486 /* Now answers and NS */
2487 if (!check_rrs(p, header, plen, 0, rrs, rr_found))
2488 return plen;
2489
2490 /* Third pass, elide records */
2491 for (p = rrs[0], i = 1; i < rr_found; i += 2)
2492 {
2493 unsigned char *start = rrs[i];
2494 unsigned char *end = (i != rr_found - 1) ? rrs[i+1] : ((unsigned char *)(header+1)) + plen;
2495
2496 memmove(p, start, end-start);
2497 p += end-start;
2498 }
2499
2500 plen = p - (unsigned char *)header;
2501 header->ancount = htons(ntohs(header->ancount) - chop_an);
2502 header->nscount = htons(ntohs(header->nscount) - chop_ns);
2503 header->arcount = htons(ntohs(header->arcount) - chop_ar);
2504
2505 /* Fourth pass, fix up pointers in the remaining records */
2506 p = (unsigned char *)(header+1);
2507
2508 check_name(&p, header, plen, 1, rrs, rr_found);
2509 p += 4; /* qclass, qtype */
2510
2511 check_rrs(p, header, plen, 1, rrs, rr_found);
2512
2513 return plen;
2514 }
2515
2516 unsigned char* hash_questions(struct dns_header *header, size_t plen, char *name)
2517 {
2518 int q;
2519 unsigned int len;
2520 unsigned char *p = (unsigned char *)(header+1);
2521 const struct nettle_hash *hash;
2522 void *ctx;
2523 unsigned char *digest;
2524
2525 if (!(hash = hash_find("sha1")) || !hash_init(hash, &ctx, &digest))
2526 return NULL;
2527
2528 for (q = ntohs(header->qdcount); q != 0; q--)
2529 {
2530 if (!extract_name(header, plen, &p, name, 1, 4))
2531 break; /* bad packet */
2532
2533 len = to_wire(name);
2534 hash->update(ctx, len, (unsigned char *)name);
2535 /* CRC the class and type as well */
2536 hash->update(ctx, 4, p);
2537
2538 p += 4;
2539 if (!CHECK_LEN(header, p, plen, 0))
2540 break; /* bad packet */
2541 }
2542
2543 hash->digest(ctx, hash->digest_size, digest);
2544 return digest;
2545 }
2546
2547 #endif /* HAVE_DNSSEC */