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