Debian Codegraph @

src/dnssec.c

raw
1 /* dnssec.c is Copyright (c) 2012 Giovanni Bajo <[email protected]>
2 and Copyright (c) 2012-2026 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 #define SERIAL_UNDEF -100
23 #define SERIAL_EQ 0
24 #define SERIAL_LT -1
25 #define SERIAL_GT 1
26
27 /* Input in presentation format */
28 static int count_labels(char *name)
29 {
30 int i;
31 char *p;
32
33 if (*name == 0)
34 return 0;
35
36 for (p = name, i = 0; *p; p++)
37 if (*p == '.')
38 i++;
39
40 /* Don't count empty first label. */
41 return *name == '.' ? i : i+1;
42 }
43
44 /* Implement RFC1982 wrapped compare for 32-bit numbers */
45 static int serial_compare_32(u32 s1, u32 s2)
46 {
47 if (s1 == s2)
48 return SERIAL_EQ;
49
50 if ((s1 < s2 && (s2 - s1) < (1UL<<31)) ||
51 (s1 > s2 && (s1 - s2) > (1UL<<31)))
52 return SERIAL_LT;
53 if ((s1 < s2 && (s2 - s1) > (1UL<<31)) ||
54 (s1 > s2 && (s1 - s2) < (1UL<<31)))
55 return SERIAL_GT;
56 return SERIAL_UNDEF;
57 }
58
59 /* Called at startup. If the timestamp file is configured and exists, put its mtime on
60 timestamp_time. If it doesn't exist, create it, and set the mtime to 1-1-2015.
61 return -1 -> Cannot create file.
62 0 -> not using timestamp, or timestamp exists and is in past.
63 1 -> timestamp exists and is in future.
64 */
65
66 static time_t timestamp_time;
67
68 int setup_timestamp(void)
69 {
70 struct stat statbuf;
71
72 daemon->back_to_the_future = 0;
73
74 if (!daemon->timestamp_file)
75 return 0;
76
77 if (stat(daemon->timestamp_file, &statbuf) != -1)
78 {
79 timestamp_time = statbuf.st_mtime;
80 check_and_exit:
81 if (difftime(timestamp_time, time(0)) <= 0)
82 {
83 /* time already OK, update timestamp, and do key checking from the start. */
84 if (utimes(daemon->timestamp_file, NULL) == -1)
85 my_syslog(LOG_ERR, _("failed to update mtime on %s: %s"), daemon->timestamp_file, strerror(errno));
86 daemon->back_to_the_future = 1;
87 return 0;
88 }
89 return 1;
90 }
91
92 if (errno == ENOENT)
93 {
94 /* NB. for explanation of O_EXCL flag, see comment on pidfile in dnsmasq.c */
95 int fd = open(daemon->timestamp_file, O_WRONLY | O_CREAT | O_NONBLOCK | O_EXCL, 0666);
96 if (fd != -1)
97 {
98 struct timeval tv[2];
99
100 close(fd);
101
102 timestamp_time = 1420070400; /* 1-1-2015 */
103 tv[0].tv_sec = tv[1].tv_sec = timestamp_time;
104 tv[0].tv_usec = tv[1].tv_usec = 0;
105 if (utimes(daemon->timestamp_file, tv) == 0)
106 goto check_and_exit;
107 }
108 }
109
110 return -1;
111 }
112
113 /* Check whether today/now is between date_start and date_end */
114 static int is_check_date(unsigned long curtime)
115 {
116 /* Checking timestamps may be temporarily disabled */
117
118 /* If the current time if _before_ the timestamp
119 on our persistent timestamp file, then assume the
120 time if not yet correct, and don't check the
121 key timestamps. As soon as the current time is
122 later then the timestamp, update the timestamp
123 and start checking keys */
124 if (daemon->timestamp_file)
125 {
126 if (daemon->back_to_the_future == 0 && difftime(timestamp_time, curtime) <= 0)
127 {
128 if (utimes(daemon->timestamp_file, NULL) != 0)
129 my_syslog(LOG_ERR, _("failed to update mtime on %s: %s"), daemon->timestamp_file, strerror(errno));
130
131 my_syslog(LOG_INFO, _("system time considered valid, now checking DNSSEC signature timestamps."));
132 daemon->back_to_the_future = 1;
133 daemon->dnssec_no_time_check = 0;
134 queue_event(EVENT_RELOAD); /* purge cache */
135 }
136
137 return daemon->back_to_the_future;
138 }
139 else
140 return !daemon->dnssec_no_time_check;
141 }
142
143 /* Return bytes of canonicalised rrdata one by one.
144 Init state->ip with the RR, and state->end with the end of same.
145 Init state->op to NULL.
146 Init state->desc to RR descriptor.
147 Init state->buff with a MAXDNAMESTR+1 buffer.
148
149 After each call which returns 1, state->op points to the next byte of data.
150 On returning 0, the end has been reached.
151 */
152 struct rdata_state {
153 short *desc;
154 size_t c;
155 unsigned char *end, *ip, *op;
156 char *buff;
157 };
158
159 static int get_rdata(struct dns_header *header, size_t plen, struct rdata_state *state)
160 {
161 int d;
162
163 if (state->op && state->c != 1)
164 {
165 state->op++;
166 state->c--;
167 return 1;
168 }
169
170 while (1)
171 {
172 d = *(state->desc);
173
174 if (d == -1)
175 {
176 /* all the bytes to the end. */
177 if ((state->c = state->end - state->ip) != 0)
178 {
179 state->op = state->ip;
180 state->ip = state->end;
181 }
182 else
183 return 0;
184 }
185 else
186 {
187 state->desc++;
188
189 if (d == (u16)0)
190 {
191 /* domain-name, canonicalise */
192
193 /* If the name is malformed, or runs beyond the end of the RR, abort.
194 under no circumstances should state->ip be beyond state->end since
195 that will cause the run-out code above to turn the negative
196 calculted length into a very large postive value for state->c
197 and overrun the buffer. */
198 if (!extract_name(header, plen, &state->ip, state->buff, EXTR_NAME_EXTRACT, 0) ||
199 state->ip > state->end)
200 return 0;
201
202 /* to_wire() always returns length > 0 */
203 state->c = to_wire(state->buff);
204 state->op = (unsigned char *)state->buff;
205 }
206 else
207 {
208 /* Plain data preceding a domain-name.
209 Handle short RR, if there are no bytes left, return finished. */
210 if ((state->end - state->ip) < d &&
211 (d = state->end - state->ip) == 0)
212 return 0;
213
214 state->op = state->ip;
215 state->c = d;
216 state->ip += d;
217 }
218 }
219
220 return 1;
221 }
222 }
223
224 /* Bubble sort the RRset into the canonical order. */
225
226 static int sort_rrset(struct dns_header *header, size_t plen, short *rr_desc, int rrsetidx,
227 unsigned char **rrset, char *buff1, char *buff2)
228 {
229 int swap, i, j;
230
231 do
232 {
233 for (swap = 0, i = 0; i < rrsetidx-1; i++)
234 {
235 int rdlen1, rdlen2;
236 struct rdata_state state1, state2;
237
238 /* Note that these have been determined to be OK previously,
239 so we don't need to check for NULL return here. */
240 state1.ip = skip_name(rrset[i], header, plen, 10);
241 state2.ip = skip_name(rrset[i+1], header, plen, 10);
242 state1.op = state2.op = NULL;
243 state1.buff = buff1;
244 state2.buff = buff2;
245 state1.desc = state2.desc = rr_desc;
246
247 state1.ip += 8; /* skip class, type, ttl */
248 GETSHORT(rdlen1, state1.ip);
249 if (!CHECK_LEN(header, state1.ip, plen, rdlen1))
250 return rrsetidx; /* short packet */
251 state1.end = state1.ip + rdlen1;
252
253 state2.ip += 8; /* skip class, type, ttl */
254 GETSHORT(rdlen2, state2.ip);
255 if (!CHECK_LEN(header, state2.ip, plen, rdlen2))
256 return rrsetidx; /* short packet */
257 state2.end = state2.ip + rdlen2;
258
259 /* If the RR has no names in it then canonicalisation
260 is the identity function and we can compare
261 the RRs directly. If not we compare the
262 canonicalised RRs one byte at a time. */
263 if (*rr_desc == -1)
264 {
265 int rdmin = rdlen1 > rdlen2 ? rdlen2 : rdlen1;
266 int cmp = memcmp(state1.ip, state2.ip, rdmin);
267
268 if (cmp > 0 || (cmp == 0 && rdlen1 > rdmin))
269 {
270 unsigned char *tmp = rrset[i+1];
271 rrset[i+1] = rrset[i];
272 rrset[i] = tmp;
273 swap = 1;
274 }
275 else if (cmp == 0 && (rdlen1 == rdlen2))
276 {
277 /* Two RRs are equal, remove one copy. RFC 4034, para 6.3 */
278 for (j = i+1; j < rrsetidx-1; j++)
279 rrset[j] = rrset[j+1];
280 rrsetidx--;
281 i--;
282 }
283 }
284 else
285 /* Comparing canonicalised RRs, byte-at-a-time. */
286 while (1)
287 {
288 int ok1, ok2;
289
290 ok1 = get_rdata(header, plen, &state1);
291 ok2 = get_rdata(header, plen, &state2);
292
293 if (!ok1 && !ok2)
294 {
295 /* Two RRs are equal, remove one copy. RFC 4034, para 6.3 */
296 for (j = i+1; j < rrsetidx-1; j++)
297 rrset[j] = rrset[j+1];
298 rrsetidx--;
299 i--;
300 break;
301 }
302 else if (ok1 && (!ok2 || *state1.op > *state2.op))
303 {
304 unsigned char *tmp = rrset[i+1];
305 rrset[i+1] = rrset[i];
306 rrset[i] = tmp;
307 swap = 1;
308 break;
309 }
310 else if (ok2 && (!ok1 || *state2.op > *state1.op))
311 break;
312
313 /* arrive here when bytes are equal, go round the loop again
314 and compare the next ones. */
315 }
316 }
317 } while (swap);
318
319 return rrsetidx;
320 }
321
322 static unsigned char **rrset = NULL, **sigs = NULL;
323
324 /* Get pointers to RRset members and signature(s) for same.
325 Check signatures, and return keyname associated in keyname. */
326 static int explore_rrset(struct dns_header *header, size_t plen, int class, int type,
327 char *name, char *keyname, int *sigcnt, int *rrcnt)
328 {
329 static int rrset_sz = 0, sig_sz = 0;
330 unsigned char *p;
331 int rrsetidx, sigidx, j, rdlen, res;
332 int gotkey = 0;
333
334 if (!(p = skip_questions(header, plen)))
335 return 0;
336
337 /* look for RRSIGs for this RRset and get pointers to each RR in the set. */
338 for (rrsetidx = 0, sigidx = 0, j = ntohs(header->ancount) + ntohs(header->nscount);
339 j != 0; j--)
340 {
341 unsigned char *pstart, *pdata;
342 int stype, sclass, type_covered;
343
344 pstart = p;
345
346 if (!(res = extract_name(header, plen, &p, name, EXTR_NAME_COMPARE, 10)))
347 return 0; /* bad packet */
348
349 GETSHORT(stype, p);
350 GETSHORT(sclass, p);
351
352 pdata = p;
353
354 p += 4; /* TTL */
355 GETSHORT(rdlen, p);
356
357 if (!CHECK_LEN(header, p, plen, rdlen))
358 return 0;
359
360 if (res == 1 && sclass == class)
361 {
362 if (stype == type)
363 {
364 if (!expand_workspace(&rrset, &rrset_sz, rrsetidx))
365 return 0;
366
367 rrset[rrsetidx++] = pstart;
368 }
369
370 if (stype == T_RRSIG)
371 {
372 if (rdlen < 18)
373 return 0; /* bad packet */
374
375 GETSHORT(type_covered, p);
376 p += 16; /* algo, labels, orig_ttl, sig_expiration, sig_inception, key_tag */
377
378 if (type_covered == type)
379 {
380 if (!extract_name(header, plen, &p, daemon->workspacename, EXTR_NAME_EXTRACT, 0))
381 return 0;
382
383 /* RFC 4035 5.3.1 says that the Signer's Name field MUST equal
384 the name of the zone containing the RRset. We can't tell that
385 for certain, but we can check that the RRset name is equal to
386 or encloses the signers name, which should be enough to stop
387 an attacker using signatures made with the key of an unrelated
388 zone he controls. Note that the root key is always allowed.
389 Ignore sigs which aren't valid */
390 if (*daemon->workspacename == 0 || hostname_issubdomain(daemon->workspacename, name) != 0)
391 {
392 if (gotkey)
393 {
394 /* If there's more than one valid SIG, they must all have same keyname */
395 if (!hostname_isequal(keyname, daemon->workspacename))
396 return 0;
397 }
398 else
399 {
400 strcpy(keyname, daemon->workspacename);
401 gotkey = 1;
402 }
403
404 if (gotkey)
405 {
406 if (!expand_workspace(&sigs, &sig_sz, sigidx))
407 return 0;
408
409 sigs[sigidx++] = pdata;
410 }
411 }
412 }
413
414 p = pdata + 6; /* restore for ADD_RDLEN */
415 }
416 }
417
418 if (!ADD_RDLEN(header, p, plen, rdlen))
419 return 0;
420 }
421
422 *sigcnt = sigidx;
423 *rrcnt = rrsetidx;
424
425 return 1;
426 }
427
428 int dec_counter(int *counter, char *message)
429 {
430 if ((*counter)-- == 0)
431 {
432 my_syslog(LOG_WARNING, "limit exceeded: %s", message ? message : _("per-query crypto work"));
433 return 1;
434 }
435
436 return 0;
437 }
438
439 /* Validate a single RRset (class, type, name) in the supplied DNS reply
440 Return code:
441 STAT_SECURE if it validates.
442 STAT_BOGUS signature is wrong, bad packet.
443 STAT_ABANDONED validation abandoned do to excess resource usage.
444 STAT_NEED_KEY need DNSKEY to complete validation (name is returned in keyname)
445 STAT_NEED_DS need DS to complete validation (name is returned in keyname)
446
447 If key is non-NULL, use that key, which has the algo and tag given in the params of those names,
448 otherwise find the key in the cache.
449
450 Name is unchanged on exit. keyname is used as workspace and trashed.
451
452 Call explore_rrset first to find and count RRs and sigs.
453
454 ttl_out is the floor on TTL, based on TTL and orig_ttl and expiration of sig used to validate.
455 */
456 static int validate_rrset(time_t now, struct dns_header *header, size_t plen, int class, int type, int sigidx, int rrsetidx,
457 char *name, char *keyname, int *wildcard_offset_out, struct blockdata *key, int keylen,
458 int algo_in, int keytag_in, unsigned long *ttl_out, int *validate_counter)
459 {
460 unsigned char *p;
461 int rdlen, j, name_labels, algo, labels, key_tag, sig_fail_cnt;
462 struct crec *crecp = NULL;
463 short *rr_desc = rrfilter_desc(type);
464 u32 sig_expiration, sig_inception;
465 unsigned long curtime = time(0);
466 int time_check = is_check_date(curtime);
467 int failflags = DNSSEC_FAIL_NOSIG;
468
469 if (sigidx != 0)
470 failflags |= DNSSEC_FAIL_NYV | DNSSEC_FAIL_EXP | DNSSEC_FAIL_NOKEYSUP;
471
472 if (wildcard_offset_out)
473 *wildcard_offset_out = 0;
474
475 name_labels = count_labels(name); /* For 4035 5.3.2 check */
476
477 /* Sort RRset records into canonical order.
478 Note that at this point keyname and daemon->workspacename buffs are
479 unused, and used as workspace by the sort. */
480 rrsetidx = sort_rrset(header, plen, rr_desc, rrsetidx, rrset, daemon->workspacename, keyname);
481
482 /* Now try all the sigs to try and find one which validates */
483 for (sig_fail_cnt = daemon->limit[LIMIT_SIG_FAIL], j = 0; j <sigidx; j++)
484 {
485 unsigned char *psav, *sig, *digest;
486 int i, wire_len, sig_len;
487 const struct nettle_hash *hash;
488 void *ctx;
489 char *name_start;
490 u32 nsigttl, ttl, orig_ttl;
491
492 failflags &= ~DNSSEC_FAIL_NOSIG;
493
494 p = sigs[j];
495 GETLONG(ttl, p);
496 GETSHORT(rdlen, p); /* rdlen >= 18 checked previously */
497 psav = p;
498
499 p += 2; /* type_covered - already checked */
500 algo = *p++;
501 labels = *p++;
502 GETLONG(orig_ttl, p);
503 GETLONG(sig_expiration, p);
504 GETLONG(sig_inception, p);
505 GETSHORT(key_tag, p);
506
507 if (!extract_name(header, plen, &p, keyname, EXTR_NAME_EXTRACT, 0))
508 return STAT_BOGUS;
509
510 if (!time_check)
511 failflags &= ~(DNSSEC_FAIL_NYV | DNSSEC_FAIL_EXP);
512 else
513 {
514 /* We must explicitly check against wanted values, because of SERIAL_UNDEF */
515 if (serial_compare_32(curtime, sig_inception) == SERIAL_LT)
516 continue;
517 else
518 failflags &= ~DNSSEC_FAIL_NYV;
519
520 if (serial_compare_32(curtime, sig_expiration) == SERIAL_GT)
521 continue;
522 else
523 failflags &= ~DNSSEC_FAIL_EXP;
524 }
525
526 if (!(hash = hash_find(algo_digest_name(algo))))
527 continue;
528 else
529 failflags &= ~DNSSEC_FAIL_NOKEYSUP;
530
531 if (labels > name_labels ||
532 !hash_init(hash, &ctx, &digest))
533 continue;
534
535 /* OK, we have the signature record, see if the relevant DNSKEY is in the cache. */
536 if (!key && !(crecp = cache_find_by_name(NULL, keyname, now, F_DNSKEY)))
537 return STAT_NEED_KEY;
538
539 if (ttl_out)
540 {
541 /* 4035 5.3.3 rules on TTLs */
542 if (orig_ttl < ttl)
543 ttl = orig_ttl;
544
545 if (time_check && difftime(sig_expiration, curtime) < ttl)
546 ttl = difftime(sig_expiration, curtime);
547
548 *ttl_out = ttl;
549 }
550
551 /* Don't trust rdlen not to be too small and give us a negative sig_len
552 It has already been checked that it doesn't run us off the end
553 of the packet. */
554 if ((sig_len = rdlen - (p - psav)) <= 0)
555 return STAT_BOGUS;
556
557 sig = p;
558 nsigttl = htonl(orig_ttl);
559
560 hash->update(ctx, 18, psav);
561 wire_len = to_wire(keyname);
562 hash->update(ctx, (unsigned int)wire_len, (unsigned char*)keyname);
563 from_wire(keyname);
564
565 #define RRBUFLEN 128 /* Most RRs are smaller than this. */
566
567 for (i = 0; i < rrsetidx; ++i)
568 {
569 int j;
570 struct rdata_state state;
571 u16 len;
572 unsigned char rrbuf[RRBUFLEN];
573
574 p = rrset[i];
575
576 if (!extract_name(header, plen, &p, name, EXTR_NAME_EXTRACT, 10))
577 return STAT_BOGUS;
578
579 name_start = name;
580
581 /* if more labels than in RRsig name, hash *.<no labels in rrsig labels field> 4035 5.3.2 */
582 /* If the name is already the wildcard, we're not going to change it. */
583 if (labels < name_labels &&
584 !(name_labels - labels == 1 && name_start[0] == '*' && name_start[1] == '.'))
585 {
586 for (j = name_labels - labels; j != 0; j--)
587 {
588 while (*name_start != '.' && *name_start != 0)
589 name_start++;
590 if (j != 1 && *name_start == '.')
591 name_start++;
592 }
593
594 if (wildcard_offset_out)
595 *wildcard_offset_out = name_start - name + 1;
596
597 name_start--;
598 *name_start = '*';
599 }
600
601 wire_len = to_wire(name_start);
602 hash->update(ctx, (unsigned int)wire_len, (unsigned char *)name_start);
603 hash->update(ctx, 4, p); /* class and type */
604 hash->update(ctx, 4, (unsigned char *)&nsigttl);
605
606 p += 8; /* skip type, class, ttl */
607 GETSHORT(rdlen, p);
608 if (!CHECK_LEN(header, p, plen, rdlen))
609 return STAT_BOGUS;
610
611 /* Optimisation for RR types which need no cannonicalisation.
612 This includes DNSKEY DS NSEC and NSEC3, which are also long, so
613 it saves lots of calls to get_rdata, and avoids the pessimal
614 segmented insertion, even with a small rrbuf[].
615
616 If canonicalisation is not needed, a simple insertion into the hash works.
617 */
618 if (*rr_desc == -1)
619 {
620 len = htons(rdlen);
621 hash->update(ctx, 2, (unsigned char *)&len);
622 hash->update(ctx, rdlen, p);
623 }
624 else
625 {
626 /* canonicalise rdata and calculate length of same, use
627 name buffer as workspace for get_rdata. */
628 state.ip = p;
629 state.op = NULL;
630 state.desc = rr_desc;
631 state.buff = name;
632 state.end = p + rdlen;
633
634 for (j = 0; get_rdata(header, plen, &state); j++)
635 if (j < RRBUFLEN)
636 rrbuf[j] = *state.op;
637
638 len = htons((u16)j);
639 hash->update(ctx, 2, (unsigned char *)&len);
640
641 /* If the RR is shorter than RRBUFLEN (most of them, in practice)
642 then we can just digest it now. If it exceeds RRBUFLEN we have to
643 go back to the start and do it in chunks. */
644 if (j >= RRBUFLEN)
645 {
646 state.ip = p;
647 state.op = NULL;
648 state.desc = rr_desc;
649
650 for (j = 0; get_rdata(header, plen, &state); j++)
651 {
652 rrbuf[j] = *state.op;
653
654 if (j == RRBUFLEN - 1)
655 {
656 hash->update(ctx, RRBUFLEN, rrbuf);
657 j = -1;
658 }
659 }
660 }
661
662 if (j != 0)
663 hash->update(ctx, j, rrbuf);
664 }
665 }
666
667 nettle_digest_wrapper(hash, ctx, hash->digest_size, digest);
668
669 /* namebuff used for workspace above, restore to leave unchanged on exit */
670 p = (unsigned char*)(rrset[0]);
671 if (!extract_name(header, plen, &p, name, EXTR_NAME_EXTRACT, 0))
672 return STAT_BOGUS;
673
674 if (key)
675 {
676 if (algo_in == algo && keytag_in == key_tag)
677 {
678 if (dec_counter(validate_counter, NULL))
679 return STAT_ABANDONED;
680
681 if (verify(key, keylen, sig, sig_len, digest, hash->digest_size, algo))
682 return STAT_SECURE;
683 }
684 }
685 else
686 {
687 /* iterate through all possible keys 4035 5.3.1 */
688 for (; crecp; crecp = cache_find_by_name(crecp, keyname, now, F_DNSKEY))
689 if (crecp->addr.key.algo == algo &&
690 crecp->addr.key.keytag == key_tag &&
691 crecp->uid == (unsigned int)class)
692 {
693 if (dec_counter(validate_counter, NULL))
694 return STAT_ABANDONED;
695
696 if (verify(crecp->addr.key.keydata, crecp->addr.key.keylen, sig, sig_len, digest, hash->digest_size, algo))
697 return STAT_SECURE;
698
699 /* An attacker can waste a lot of our CPU by setting up a giant DNSKEY RRSET full of failing
700 keys, all of which we have to try. Since many failing keys is not likely for
701 a legitimate domain, set a limit on how many can fail. */
702 if ((daemon->limit[LIMIT_SIG_FAIL] - (sig_fail_cnt + 1)) > (int)daemon->metrics[METRIC_SIG_FAIL_HWM])
703 daemon->metrics[METRIC_SIG_FAIL_HWM] = daemon->limit[LIMIT_SIG_FAIL] - (sig_fail_cnt + 1);
704 if (dec_counter(&sig_fail_cnt, _("per-RRSet signature fails")))
705 return STAT_ABANDONED;
706 }
707 }
708 }
709
710 /* If we reach this point, no verifying key was found */
711 return STAT_BOGUS | failflags | DNSSEC_FAIL_NOKEY;
712 }
713
714
715 /* The DNS packet is expected to contain the answer to a DNSKEY query.
716 Put all DNSKEYs in the answer which are valid into the cache.
717 return codes:
718 STAT_OK Done, key(s) in cache.
719 STAT_BOGUS No DNSKEYs found, which can be validated with DS,
720 or self-sign for DNSKEY RRset is not valid, bad packet.
721 STAT_ABANDONED resource exhaustion.
722 STAT_NEED_DS DS records to validate a key not found, name in keyname
723 */
724 int dnssec_validate_by_ds(time_t now, struct dns_header *header, size_t plen, char *name,
725 char *keyname, int class, int *validate_counter)
726 {
727 unsigned char *psave, *p = (unsigned char *)(header+1), *keyaddr;
728 struct crec *crecp, *recp1;
729 int rc, j, qtype, qclass, rdlen, flags, algo, keytag, sigcnt, rrcnt;
730 unsigned long ttl, sig_ttl;
731 union all_addr a;
732 int failflags = DNSSEC_FAIL_NODSSUP | DNSSEC_FAIL_NOZONE;
733 char valid_digest[255];
734 static unsigned char **cached_digest;
735 static size_t cached_digest_size = 0;
736
737 if (ntohs(header->qdcount) != 1 || RCODE(header) != NOERROR || !extract_name(header, plen, &p, name, EXTR_NAME_EXTRACT, 4))
738 return STAT_BOGUS | DNSSEC_FAIL_NOKEY;
739
740 GETSHORT(qtype, p);
741 GETSHORT(qclass, p);
742
743 if (qtype != T_DNSKEY || qclass != class ||
744 !explore_rrset(header, plen, class, T_DNSKEY, name, keyname, &sigcnt, &rrcnt) ||
745 rrcnt == 0)
746 return STAT_BOGUS | DNSSEC_FAIL_NOKEY;
747
748 if (sigcnt == 0)
749 return STAT_BOGUS | DNSSEC_FAIL_NOSIG;
750
751 /* See if we have cached a DS record which validates this key */
752 if (!(crecp = cache_find_by_name(NULL, name, now, F_DS)))
753 {
754 strcpy(keyname, name);
755 return STAT_NEED_DS;
756 }
757
758 /* NOTE, we need to find ONE DNSKEY which matches the DS */
759 for (j = ntohs(header->ancount); j != 0; j--)
760 {
761 /* Ensure we have type, class TTL and length */
762 if (!(rc = extract_name(header, plen, &p, name, EXTR_NAME_COMPARE, 10)))
763 return STAT_BOGUS; /* bad packet */
764
765 GETSHORT(qtype, p);
766 GETSHORT(qclass, p);
767 GETLONG(ttl, p);
768 GETSHORT(rdlen, p);
769
770 if (!CHECK_LEN(header, p, plen, rdlen))
771 return STAT_BOGUS; /* bad packet */
772
773 if (qclass != class || qtype != T_DNSKEY || rc == 2)
774 {
775 p += rdlen;
776 continue;
777 }
778
779 if (rdlen < 5)
780 return STAT_BOGUS; /* min 1 byte key! */
781
782 psave = p;
783
784 GETSHORT(flags, p);
785 if (*p++ != 3)
786 {
787 p = psave + rdlen;
788 continue;
789 }
790 algo = *p++;
791 keyaddr = p;
792 keytag = dnskey_keytag(algo, flags, keyaddr, rdlen - 4);
793
794 p = psave + rdlen;
795
796 /* key must have zone key flag set */
797 if (!(flags & 0x100))
798 continue;
799
800 failflags &= ~DNSSEC_FAIL_NOZONE;
801
802 /* clear digest cache. */
803 memset(valid_digest, 0, sizeof(valid_digest));
804
805 for (recp1 = crecp; recp1; recp1 = cache_find_by_name(recp1, name, now, F_DS))
806 {
807 void *ctx;
808 unsigned char *digest, *ds_digest;
809 const struct nettle_hash *hash;
810 int wire_len;
811
812 if ((recp1->flags & F_NEG) ||
813 recp1->addr.ds.algo != algo ||
814 recp1->addr.ds.keytag != keytag ||
815 recp1->uid != (unsigned int)class)
816 continue;
817
818 if (!(hash = hash_find(ds_digest_name(recp1->addr.ds.digest))))
819 continue;
820
821 failflags &= ~DNSSEC_FAIL_NODSSUP;
822
823 if (recp1->addr.ds.keylen != (int)hash->digest_size ||
824 !(ds_digest = blockdata_retrieve(recp1->addr.ds.keydata, recp1->addr.ds.keylen, NULL)))
825 continue;
826
827 if (valid_digest[recp1->addr.ds.digest])
828 digest = cached_digest[recp1->addr.ds.digest];
829 else
830 {
831 /* computing a hash is a unit of crypto work. */
832 if (dec_counter(validate_counter, NULL))
833 return STAT_ABANDONED;
834
835 if (!hash_init(hash, &ctx, &digest))
836 continue;
837
838 wire_len = to_wire(name);
839
840 /* Note that digest may be different between DSs, so
841 we can't move this outside the loop. We keep
842 copies of each digest we make for this key,
843 so maximum digest work is O(keys x digests_types)
844 rather then O(keys x DSs) */
845 hash->update(ctx, (unsigned int)wire_len, (unsigned char *)name);
846 hash->update(ctx, (unsigned int)rdlen, psave);
847 nettle_digest_wrapper(hash, ctx, hash->digest_size, digest);
848
849 from_wire(name);
850
851 if (recp1->addr.ds.digest >= cached_digest_size)
852 {
853 unsigned char **new;
854
855 /* whine_malloc zeros memory */
856 if ((new = whine_malloc((recp1->addr.ds.digest + 5) * sizeof(unsigned char *))))
857 {
858 if (cached_digest_size != 0)
859 {
860 memcpy(new, cached_digest, cached_digest_size * sizeof(unsigned char *));
861 free(cached_digest);
862 }
863
864 cached_digest_size = recp1->addr.ds.digest + 5;
865 cached_digest = new;
866 }
867 }
868
869 if (recp1->addr.ds.digest < cached_digest_size)
870 {
871 if (!cached_digest[recp1->addr.ds.digest])
872 cached_digest[recp1->addr.ds.digest] = whine_malloc(recp1->addr.ds.keylen);
873
874 if (cached_digest[recp1->addr.ds.digest])
875 {
876 memcpy(cached_digest[recp1->addr.ds.digest], digest, recp1->addr.ds.keylen);
877 valid_digest[recp1->addr.ds.digest] = 1;
878 }
879 }
880 }
881
882 if (memcmp(ds_digest, digest, recp1->addr.ds.keylen) == 0)
883 {
884 /* Found the key validated by a DS record.
885 Now check the self-sig for the entire key RRset using that key.
886 Note that validate_rrset() will never return STAT_NEED_KEY here,
887 since we supply the key it will use as an argument. */
888 struct blockdata *key;
889
890 if (!(key = blockdata_alloc((char *)keyaddr, rdlen - 4)))
891 break;
892
893 rc = validate_rrset(now, header, plen, class, T_DNSKEY, sigcnt, rrcnt, name, keyname,
894 NULL, key, rdlen - 4, algo, keytag, &sig_ttl, validate_counter);
895
896 blockdata_free(key);
897
898 if (STAT_ISEQUAL(rc, STAT_ABANDONED))
899 return rc;
900
901 /* can't validate KEY RRset with this key, see if there's another that
902 will, which is validated by another DS. */
903 if (!STAT_ISEQUAL(rc, STAT_SECURE))
904 break;
905
906 /* DNSKEY RRset determined to be OK, now cache it. */
907 cache_start_insert();
908
909 p = skip_questions(header, plen);
910
911 for (j = ntohs(header->ancount); j != 0; j--)
912 {
913 /* Ensure we have type, class TTL and length */
914 if (!(rc = extract_name(header, plen, &p, name, EXTR_NAME_COMPARE, 10)))
915 return STAT_BOGUS; /* bad packet */
916
917 GETSHORT(qtype, p);
918 GETSHORT(qclass, p);
919 GETLONG(ttl, p);
920 GETSHORT(rdlen, p);
921
922 /* TTL may be limited by sig. */
923 if (sig_ttl < ttl)
924 ttl = sig_ttl;
925
926 if (!CHECK_LEN(header, p, plen, rdlen))
927 return STAT_BOGUS; /* bad packet */
928
929 psave = p;
930
931 if (qclass == class && rc == 1 && qtype == T_DNSKEY)
932 {
933 if (rdlen < 4)
934 return STAT_BOGUS; /* min 1 byte key! */
935
936 GETSHORT(flags, p);
937 if (*p++ == 3)
938 {
939 algo = *p++;
940 keytag = dnskey_keytag(algo, flags, p, rdlen - 4);
941
942 if (!(key = blockdata_alloc((char*)p, rdlen - 4)))
943 return STAT_BOGUS;
944
945 a.key.keylen = rdlen - 4;
946 a.key.keydata = key;
947 a.key.algo = algo;
948 a.key.keytag = keytag;
949 a.key.flags = flags;
950
951 if (!cache_insert(name, &a, class, now, ttl, F_FORWARD | F_DNSKEY | F_DNSSECOK))
952 {
953 /* cache_insert fails when the cache is too small, so error with STAT_ABANDONED which
954 will log this as a resource exhaustion problem, which it is. */
955 blockdata_free(key);
956 return STAT_ABANDONED;
957 }
958
959 a.log.keytag = keytag;
960 a.log.algo = algo;
961 log_query(F_NOEXTRA | F_KEYTAG | F_UPSTREAM, name, &a, "DNSKEY keytag %hu, algo %hu", !algo_digest_name(algo));
962 }
963 }
964
965 p = psave + rdlen;
966 }
967
968 /* commit cache insert. */
969 cache_end_insert();
970 return STAT_OK;
971 }
972 }
973 }
974
975 log_query(F_NOEXTRA | F_UPSTREAM, name, NULL, "BOGUS DNSKEY", 0);
976 return STAT_BOGUS | failflags;
977 }
978
979 /* The DNS packet is expected to contain the answer to a DS query
980 Put all DSs in the answer which are valid and have hash and signature algos
981 we support into the cache.
982 Also handles replies which prove that there's no DS at this location,
983 either because the zone is unsigned or this isn't a zone cut. These are
984 cached too.
985 If none of the DS's are for supported algos, treat the answer as if
986 it's a proof of no DS at this location. RFC4035 para 5.2.
987 return codes:
988 STAT_OK At least one valid DS found and in cache.
989 STAT_BOGUS no DS in reply or not signed, fails validation, bad packet.
990 STAT_NEED_KEY DNSKEY records to validate a DS not found, name in keyname
991 STAT_NEED_DS DS record needed.
992 STAT_ABANDONED resource exhaustion.
993 */
994
995 int dnssec_validate_ds(time_t now, struct dns_header *header, size_t plen, char *name,
996 char *keyname, int class, int *validate_counter)
997 {
998 unsigned char *p = (unsigned char *)(header+1);
999 int qtype, qclass, rc, i, neganswer = 0, prim_ok = 0, nons = 0, servfail = 0, neg_ttl = 0, found_supported = 0;
1000 int aclass, atype, rdlen, flags;
1001 unsigned long ttl;
1002 union all_addr a;
1003
1004 /* A SERVFAIL answer has been seen to a DS query not at start of authority,
1005 so treat it as such and continue to search for a DS or proof of no existence
1006 further down the tree. */
1007 if (RCODE(header) == SERVFAIL)
1008 servfail = neganswer = nons = 1;
1009 else
1010 rc = dnssec_validate_reply(now, header, plen, name, keyname, NULL, 0, &neganswer, &prim_ok, &nons, &neg_ttl, validate_counter);
1011
1012 p = (unsigned char *)(header+1);
1013 if (ntohs(header->qdcount) != 1 ||
1014 !extract_name(header, plen, &p, name, EXTR_NAME_EXTRACT, 4))
1015 return STAT_BOGUS;
1016
1017 GETSHORT(qtype, p);
1018 GETSHORT(qclass, p);
1019
1020 if (qtype != T_DS || qclass != class)
1021 return STAT_BOGUS;
1022
1023 if (!servfail)
1024 {
1025 if (STAT_ISEQUAL(rc, STAT_INSECURE))
1026 {
1027 /* A INSECURE DS answer is OK if it's negative and there's a CNAME answer to the DS answer which is
1028 signed, since that's enough to prove that the DS record doesn't exist. */
1029 if (!neganswer || !prim_ok)
1030 {
1031 if (option_bool(OPT_BOGUSPRIV) &&
1032 (flags = in_arpa_name_2_addr(name, &a)) &&
1033 ((flags == F_IPV6 && private_net6(&a.addr6, 0)) || (flags == F_IPV4 && private_net(a.addr4, 0))))
1034 {
1035 my_syslog(LOG_INFO, _("insecure reply received for DS %s, assuming that's OK for a RFC-1918 address"), name);
1036 neganswer = 1;
1037 nons = 0; /* If we're faking a DS, fake one with an NS. */
1038 neg_ttl = DNSSEC_ASSUMED_DS_TTL;
1039 }
1040 else if (lookup_domain(name, F_DOMAINSRV, NULL, NULL))
1041 {
1042 my_syslog(LOG_INFO, _("insecure reply received for DS %s, assuming non-DNSSEC domain-specific server"), name);
1043 neganswer = 1;
1044 nons = 0; /* If we're faking a DS, fake one with an NS. */
1045 neg_ttl = DNSSEC_ASSUMED_DS_TTL;
1046 }
1047 else
1048 {
1049 my_syslog(LOG_WARNING, _("insecure DS reply received for %s, check domain configuration and upstream DNS server DNSSEC support"), name);
1050 log_query(F_NOEXTRA | F_UPSTREAM, name, NULL, "BOGUS DS - not secure", 0);
1051 return STAT_BOGUS | DNSSEC_FAIL_INDET;
1052 }
1053 }
1054 }
1055 else
1056 {
1057 if (STAT_ISEQUAL(rc, STAT_NEED_KEY) && hostname_isequal(name, keyname))
1058 {
1059 /* If the key needed to validate the DS is on the same domain as the DS, we'll
1060 loop getting nowhere. Stop that now. This can happen of the DS answer comes
1061 from the DS's zone, and not the parent zone. */
1062 log_query(F_NOEXTRA | F_UPSTREAM, name, NULL, "BOGUS DS", 0);
1063 return STAT_BOGUS;
1064 }
1065
1066 if (!STAT_ISEQUAL(rc, STAT_SECURE))
1067 return rc;
1068 }
1069 }
1070
1071 if (!neganswer)
1072 {
1073 cache_start_insert();
1074
1075 for (i = 0; i < ntohs(header->ancount); i++)
1076 {
1077 unsigned char *psave;
1078
1079 if (!(rc = extract_name(header, plen, &p, name, EXTR_NAME_COMPARE, 10)))
1080 return STAT_BOGUS; /* bad packet */
1081
1082 GETSHORT(atype, p);
1083 GETSHORT(aclass, 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 psave = p;
1091
1092 if (aclass == class && atype == T_DS && rc == 1)
1093 {
1094 int algo, digest, keytag;
1095 struct blockdata *key;
1096
1097 if (rdlen < 5)
1098 return STAT_BOGUS; /* min 1 byte digest! */
1099
1100 GETSHORT(keytag, p);
1101 algo = *p++;
1102 digest = *p++;
1103
1104 if (!ds_digest_name(digest) || !algo_digest_name(algo))
1105 {
1106 a.log.keytag = keytag;
1107 a.log.algo = algo;
1108 a.log.digest = digest;
1109 log_query(F_NOEXTRA | F_KEYTAG | F_UPSTREAM, name, &a, "DS for keytag %hu, algo %hu, digest %hu", 1);
1110 neg_ttl = ttl;
1111 }
1112 else if ((key = blockdata_alloc((char*)p, rdlen - 4)))
1113 {
1114 a.ds.digest = digest;
1115 a.ds.keydata = key;
1116 a.ds.algo = algo;
1117 a.ds.keytag = keytag;
1118 a.ds.keylen = rdlen - 4;
1119
1120 if (!cache_insert(name, &a, class, now, ttl, F_FORWARD | F_DS | F_DNSSECOK))
1121 {
1122 /* cache_insert fails when the cache is too small, so error with STAT_ABANDONED which
1123 will log this as a resource exhaustion problem, which it is. */
1124 blockdata_free(key);
1125 return STAT_ABANDONED;
1126 }
1127 else
1128 {
1129 a.log.keytag = keytag;
1130 a.log.algo = algo;
1131 a.log.digest = digest;
1132 log_query(F_NOEXTRA | F_KEYTAG | F_UPSTREAM, name, &a, "DS for keytag %hu, algo %hu, digest %hu", 0);
1133 found_supported = 1;
1134 }
1135 }
1136 }
1137
1138 p = psave + rdlen;
1139 }
1140
1141 cache_end_insert();
1142
1143 /* Fall through if no supported algo DS found. */
1144 if (found_supported)
1145 return STAT_OK;
1146 }
1147
1148 flags = F_FORWARD | F_DS | F_NEG | F_DNSSECOK;
1149
1150 if (neganswer)
1151 {
1152 if (RCODE(header) == NXDOMAIN)
1153 flags |= F_NXDOMAIN;
1154
1155 if (nons)
1156 {
1157 if (lookup_domain(name, F_DOMAINSRV, NULL, NULL))
1158 {
1159 my_syslog(LOG_WARNING, _("negative DS reply without NS record received for %s, assuming non-DNSSEC domain-specific server"), name);
1160 nons = 0;
1161 neg_ttl = DNSSEC_ASSUMED_DS_TTL;
1162 }
1163 else
1164 /* We only cache validated DS records, DNSSECOK flag hijacked
1165 to store presence/absence of NS. */
1166 flags &= ~F_DNSSECOK;
1167 }
1168
1169 log_query(F_NOEXTRA | F_UPSTREAM, name, NULL,
1170 servfail ? "SERVFAIL" : (nons ? "no DS/cut" : "no DS"), 0);
1171 }
1172
1173 return cache_neg_ds(name, flags, class, now, neg_ttl);
1174
1175 }
1176
1177 int cache_neg_ds(char *name, int flags, int class, time_t now, int ttl)
1178 {
1179 cache_start_insert();
1180
1181 /* Use TTL from NSEC for negative cache entries */
1182 if (!cache_insert(name, NULL, class, now, ttl, flags))
1183 return STAT_ABANDONED;
1184
1185 cache_end_insert();
1186
1187 return STAT_OK;
1188 }
1189
1190 /* 4034 6.1 */
1191 static int hostname_cmp(const char *a, const char *b)
1192 {
1193 char *sa, *ea, *ca, *sb, *eb, *cb;
1194 unsigned char ac, bc;
1195
1196 sa = ea = (char *)a + strlen(a);
1197 sb = eb = (char *)b + strlen(b);
1198
1199 while (1)
1200 {
1201 while (sa != a && *(sa-1) != '.')
1202 sa--;
1203
1204 while (sb != b && *(sb-1) != '.')
1205 sb--;
1206
1207 ca = sa;
1208 cb = sb;
1209
1210 while (1)
1211 {
1212 if (ca == ea)
1213 {
1214 if (cb == eb)
1215 break;
1216
1217 return -1;
1218 }
1219
1220 if (cb == eb)
1221 return 1;
1222
1223 ac = (unsigned char) *ca++;
1224 bc = (unsigned char) *cb++;
1225
1226 if (ac >= 'A' && ac <= 'Z')
1227 ac += 'a' - 'A';
1228 if (bc >= 'A' && bc <= 'Z')
1229 bc += 'a' - 'A';
1230
1231 if (ac < bc)
1232 return -1;
1233 else if (ac != bc)
1234 return 1;
1235 }
1236
1237
1238 if (sa == a)
1239 {
1240 if (sb == b)
1241 return 0;
1242
1243 return -1;
1244 }
1245
1246 if (sb == b)
1247 return 1;
1248
1249 ea = --sa;
1250 eb = --sb;
1251 }
1252 }
1253
1254 static int check_type_bitmap(unsigned char *p, int type)
1255 {
1256 int offset = (type & 0xff) >> 3;
1257
1258 if (p[0] == type >> 8 && p[1] > offset && (p[offset + 2] & (0x80 >> (type & 0x07))))
1259 return 1;
1260
1261 return 0;
1262 }
1263
1264 /* returns 0 on success, or DNSSEC_FAIL_* value on failure. */
1265 static int prove_non_existence_nsec(struct dns_header *header, size_t plen, unsigned char **nsecs, unsigned char **labels, int nsec_count,
1266 char *workspace1_in, char *workspace2, char *name, int type, int *nons)
1267 {
1268 int i, rc, rdlen;
1269 unsigned char *p, *psave;
1270
1271 if (nons)
1272 *nons = 1;
1273
1274 /* Find NSEC record that proves name doesn't exist */
1275 for (i = 0; i < nsec_count; i++)
1276 {
1277 char *workspace1 = workspace1_in;
1278 int sig_labels, name_labels;
1279
1280 p = nsecs[i];
1281 if (!extract_name(header, plen, &p, workspace1, EXTR_NAME_EXTRACT, 10))
1282 return DNSSEC_FAIL_BADPACKET;
1283 p += 8; /* class, type, TTL */
1284 GETSHORT(rdlen, p);
1285 psave = p;
1286
1287 if (!extract_name(header, plen, &p, workspace2, EXTR_NAME_EXTRACT, 0))
1288 return DNSSEC_FAIL_BADPACKET;
1289
1290 /* If NSEC comes from wildcard expansion, use original wildcard
1291 as name for computation. */
1292 sig_labels = *labels[i];
1293 name_labels = count_labels(workspace1);
1294
1295 if (sig_labels < name_labels)
1296 {
1297 int k;
1298 for (k = name_labels - sig_labels; k != 0; k--)
1299 {
1300 while (*workspace1 != '.' && *workspace1 != 0)
1301 workspace1++;
1302 if (k != 1 && *workspace1 == '.')
1303 workspace1++;
1304 }
1305
1306 workspace1--;
1307 *workspace1 = '*';
1308 }
1309
1310 rdlen -= p - psave;
1311 /* rdlen is now length of type map, and p points to it
1312 packet checked to be as long as rdlen implies in prove_non_existence() */
1313
1314 rc = hostname_cmp(workspace1, name);
1315
1316 if (rc == 0)
1317 {
1318 /* 4035 para 5.4. Last sentence */
1319 if (type == T_NSEC || type == T_RRSIG)
1320 return 0;
1321
1322 while (rdlen > 0)
1323 {
1324 if (rdlen < 2 || rdlen < p[1] + 2)
1325 return DNSSEC_FAIL_BADPACKET;
1326
1327 /* If we can prove that there's no NS record, return that information. */
1328 if (nons && check_type_bitmap(p, T_NS))
1329 *nons = 0;
1330
1331 /* NSEC with the same name as the RR we're testing, check
1332 that the type in question doesn't appear in the type map */
1333 if (check_type_bitmap(p, type))
1334 return DNSSEC_FAIL_NONSEC;
1335
1336 /* A CNAME answer would also be valid, so if there's a CNAME it should
1337 have been returned. */
1338 if (check_type_bitmap(p, T_CNAME))
1339 return DNSSEC_FAIL_NONSEC;
1340
1341 /* If the SOA bit is set for a DS record, then we have the
1342 DS from the wrong side of the delegation. For the root DS,
1343 this is expected. */
1344 if (name_labels != 0 && type == T_DS && check_type_bitmap(p, T_SOA))
1345 return DNSSEC_FAIL_NONSEC;
1346
1347 /* RFC 6672 5.3.4.1. */
1348 if (check_type_bitmap(p, T_DNAME) && hostname_issubdomain(name, workspace1) == 1)
1349 return DNSSEC_FAIL_NONSEC;
1350
1351 rdlen -= p[1] + 2;
1352 p += p[1] + 2;
1353 }
1354
1355 return 0;
1356 }
1357 else if (rc == -1)
1358 {
1359 /* Normal case, name falls between NSEC name and next domain name,
1360 wrap around case, name falls between NSEC name (rc == -1) and end */
1361 if (hostname_cmp(workspace2, name) >= 0 || hostname_cmp(workspace1, workspace2) >= 0)
1362 return 0;
1363 }
1364 else
1365 {
1366 /* wrap around case, name falls between start and next domain name */
1367 if (hostname_cmp(workspace1, workspace2) >= 0 && hostname_cmp(workspace2, name) >=0 )
1368 return 0;
1369 }
1370 }
1371
1372 return DNSSEC_FAIL_NONSEC;
1373 }
1374
1375 /* return digest length, or zero on error */
1376 static int hash_name(char *in, unsigned char **out, struct nettle_hash const *hash,
1377 unsigned char *salt, int salt_len, int iterations)
1378 {
1379 void *ctx;
1380 unsigned char *digest;
1381 int i;
1382
1383 if (!hash_init(hash, &ctx, &digest))
1384 return 0;
1385
1386 hash->update(ctx, to_wire(in), (unsigned char *)in);
1387 hash->update(ctx, salt_len, salt);
1388 nettle_digest_wrapper(hash, ctx, hash->digest_size, digest);
1389
1390 for(i = 0; i < iterations; i++)
1391 {
1392 hash->update(ctx, hash->digest_size, digest);
1393 hash->update(ctx, salt_len, salt);
1394 nettle_digest_wrapper(hash, ctx, hash->digest_size, digest);
1395 }
1396
1397 from_wire(in);
1398
1399 *out = digest;
1400 return hash->digest_size;
1401 }
1402
1403 /* Decode base32 to first "." or end of string */
1404 static int base32_decode(char *in, unsigned char *out)
1405 {
1406 int oc, on, c, mask, i;
1407 unsigned char *p = out;
1408
1409 for (c = *in, oc = 0, on = 0; c != 0 && c != '.'; c = *++in)
1410 {
1411 if (c >= '0' && c <= '9')
1412 c -= '0';
1413 else if (c >= 'a' && c <= 'v')
1414 c -= 'a', c += 10;
1415 else if (c >= 'A' && c <= 'V')
1416 c -= 'A', c += 10;
1417 else
1418 return 0;
1419
1420 for (mask = 0x10, i = 0; i < 5; i++)
1421 {
1422 if (c & mask)
1423 oc |= 1;
1424 mask = mask >> 1;
1425 if (((++on) & 7) == 0)
1426 {
1427 *p++ = oc;
1428 oc = 0;
1429 }
1430 oc = oc << 1;
1431 }
1432 }
1433
1434 if ((on & 7) != 0)
1435 return 0;
1436
1437 return p - out;
1438 }
1439
1440 /* return 1 if we can prove record _doesn't_ exist */
1441 static int check_nsec3_coverage(struct dns_header *header, size_t plen, int digest_len, unsigned char *digest, int type,
1442 char *workspace1, char *workspace2, unsigned char **nsecs, int nsec_count, int *nons, int name_labels)
1443 {
1444 int i, hash_len, salt_len, base32_len, rdlen, flags;
1445 unsigned char *p, *psave;
1446
1447 for (i = 0; i < nsec_count; i++)
1448 if ((p = nsecs[i]))
1449 {
1450 if (!extract_name(header, plen, &p, workspace1, EXTR_NAME_EXTRACT, 10) ||
1451 !(base32_len = base32_decode(workspace1, (unsigned char *)workspace2)))
1452 return 0;
1453
1454 p += 8; /* class, type, TTL */
1455 GETSHORT(rdlen, p);
1456
1457 psave = p;
1458
1459 /* packet checked to be as long as implied by rdlen, salt_len and hash_len in prove_non_existence() */
1460 p++; /* algo */
1461 flags = *p++; /* flags */
1462 p += 2; /* iterations */
1463 salt_len = *p++; /* salt_len */
1464 p += salt_len; /* salt */
1465 hash_len = *p++; /* p now points to next hashed name */
1466
1467 if (digest_len == base32_len && hash_len == base32_len)
1468 {
1469 int rc = memcmp(workspace2, digest, digest_len);
1470
1471 if (rc == 0)
1472 {
1473 /* We found an NSEC3 whose hashed name exactly matches the query, so
1474 we just need to check the type map. p points to the RR data for the record.
1475 Note we have packet length up to rdlen bytes checked. */
1476
1477 p += hash_len; /* skip next-domain hash */
1478 rdlen -= p - psave;
1479
1480 while (rdlen > 0)
1481 {
1482 if (rdlen < 2 || rdlen < p[1] + 2)
1483 return 0;
1484
1485 /* If we can prove that there's no NS record, return that information. */
1486 if (nons && check_type_bitmap(p, T_NS))
1487 *nons = 0;
1488
1489 /* Does the NSEC3 say our type exists? */
1490 if (check_type_bitmap(p, type))
1491 return 0;
1492
1493 /* A CNAME answer would also be valid, so if there's a CNAME it should
1494 have been returned. */
1495 if (check_type_bitmap(p, T_CNAME))
1496 return 0;
1497
1498 /* If the SOA bit is set for a DS record, then we have the
1499 DS from the wrong side of the delegation. For the root DS,
1500 this is expected. */
1501 if (name_labels != 0 && type == T_DS && check_type_bitmap(p, T_SOA))
1502 return 0;
1503
1504 rdlen -= p[1] + 2;
1505 p += p[1] + 2;
1506 }
1507
1508 return 1;
1509 }
1510 else if (rc < 0)
1511 {
1512 /* Normal case, hash falls between NSEC3 name-hash and next domain name-hash,
1513 wrap around case, name-hash falls between NSEC3 name-hash and end */
1514 if (memcmp(p, digest, digest_len) >= 0 || memcmp(workspace2, p, digest_len) >= 0)
1515 {
1516 if ((flags & 0x01) && nons) /* opt out */
1517 *nons = 0;
1518
1519 return 1;
1520 }
1521 }
1522 else
1523 {
1524 /* wrap around case, name falls between start and next domain name */
1525 if (memcmp(workspace2, p, digest_len) >= 0 && memcmp(p, digest, digest_len) >= 0)
1526 {
1527 if ((flags & 0x01) && nons) /* opt out */
1528 *nons = 0;
1529
1530 return 1;
1531 }
1532 }
1533 }
1534 }
1535
1536 return 0;
1537 }
1538
1539 /* returns 0 on success, or DNSSEC_FAIL_* value on failure. */
1540 static int prove_non_existence_nsec3(struct dns_header *header, size_t plen, unsigned char **nsecs, int nsec_count, char *workspace1,
1541 char *workspace2, char *name, int type, int wild_offset, int *nons, int *validate_counter)
1542 {
1543 unsigned char *salt, *p, *digest;
1544 int digest_len, i, iterations, salt_len, base32_len, algo = 0;
1545 struct nettle_hash const *hash = NULL;
1546 char *closest_encloser, *next_closest, *wildcard;
1547
1548 if (nons)
1549 *nons = 1;
1550
1551 /* Look though the NSEC3 records to find the first one with
1552 an algorithm we support.
1553
1554 Take the algo, iterations, and salt of that record
1555 as the ones we're going to use, and prune any
1556 that don't match. */
1557
1558 for (i = 0; i < nsec_count; i++)
1559 {
1560 if (!(p = skip_name(nsecs[i], header, plen, 15)))
1561 return DNSSEC_FAIL_BADPACKET; /* bad packet */
1562
1563 p += 10; /* type, class, TTL, rdlen */
1564 algo = *p++;
1565
1566 if ((hash = hash_find(nsec3_digest_name(algo))))
1567 break; /* known algo */
1568 }
1569
1570 /* No usable NSEC3s */
1571 if (i == nsec_count)
1572 return DNSSEC_FAIL_NONSEC;
1573
1574 p++; /* flags */
1575
1576 GETSHORT (iterations, p);
1577 /* Upper-bound iterations, to avoid DoS. RFC 9276 refers. */
1578 if (iterations > daemon->limit[LIMIT_NSEC3_ITERS])
1579 return DNSSEC_FAIL_NSEC3_ITERS;
1580
1581 salt_len = *p++;
1582 salt = p;
1583
1584 /* Now prune so we only have NSEC3 records with same iterations, salt and algo */
1585 for (i = 0; i < nsec_count; i++)
1586 {
1587 unsigned char *nsec3p = nsecs[i];
1588 int this_iter, flags;
1589
1590 nsecs[i] = NULL; /* Speculative, will be restored if OK. */
1591
1592 if (!(p = skip_name(nsec3p, header, plen, 15)))
1593 return DNSSEC_FAIL_BADPACKET; /* bad packet */
1594
1595 p += 10; /* type, class, TTL, rdlen */
1596
1597 if (*p++ != algo)
1598 continue;
1599
1600 flags = *p++; /* flags */
1601
1602 /* 5155 8.2 */
1603 if (flags != 0 && flags != 1)
1604 continue;
1605
1606 GETSHORT(this_iter, p);
1607 if (this_iter != iterations)
1608 continue;
1609
1610 if (salt_len != *p++)
1611 continue;
1612
1613 if (memcmp(p, salt, salt_len) != 0)
1614 continue;
1615
1616 /* All match, put the pointer back */
1617 nsecs[i] = nsec3p;
1618 }
1619
1620 if (dec_counter(validate_counter, NULL))
1621 return DNSSEC_FAIL_WORK;
1622
1623 if ((digest_len = hash_name(name, &digest, hash, salt, salt_len, iterations)) == 0)
1624 return DNSSEC_FAIL_NONSEC;
1625
1626 if (check_nsec3_coverage(header, plen, digest_len, digest, type, workspace1, workspace2, nsecs, nsec_count, nons, count_labels(name)))
1627 return 0;
1628
1629 /* Can't find an NSEC3 which covers the name directly, we need the "closest encloser NSEC3"
1630 or an answer inferred from a wildcard record. */
1631 closest_encloser = name;
1632 next_closest = NULL;
1633
1634 do
1635 {
1636 if (*closest_encloser == '.')
1637 closest_encloser++;
1638
1639 if (wild_offset != 0 && name - closest_encloser == wild_offset)
1640 break;
1641
1642 if (dec_counter(validate_counter, NULL))
1643 return DNSSEC_FAIL_WORK;
1644
1645 if ((digest_len = hash_name(closest_encloser, &digest, hash, salt, salt_len, iterations)) == 0)
1646 return DNSSEC_FAIL_NONSEC;
1647
1648 for (i = 0; i < nsec_count; i++)
1649 if ((p = nsecs[i]))
1650 {
1651 if (!extract_name(header, plen, &p, workspace1, EXTR_NAME_EXTRACT, 0))
1652 return DNSSEC_FAIL_BADPACKET;
1653
1654 if (!(base32_len = base32_decode(workspace1, (unsigned char *)workspace2)))
1655 return DNSSEC_FAIL_NONSEC;
1656
1657 if (digest_len == base32_len &&
1658 memcmp(digest, workspace2, digest_len) == 0)
1659 break; /* Gotit */
1660 }
1661
1662 if (i != nsec_count)
1663 break;
1664
1665 next_closest = closest_encloser;
1666 }
1667 while ((closest_encloser = strchr(closest_encloser, '.')));
1668
1669 if (!closest_encloser || !next_closest)
1670 return DNSSEC_FAIL_NONSEC;
1671
1672 /* Look for NSEC3 that proves the non-existence of the next-closest encloser */
1673 if (dec_counter(validate_counter, NULL))
1674 return DNSSEC_FAIL_WORK;
1675
1676 if ((digest_len = hash_name(next_closest, &digest, hash, salt, salt_len, iterations)) == 0)
1677 return DNSSEC_FAIL_NONSEC;
1678
1679 if (!check_nsec3_coverage(header, plen, digest_len, digest, type, workspace1, workspace2, nsecs, nsec_count, NULL, 1))
1680 return DNSSEC_FAIL_NONSEC;
1681
1682 /* Finally, check that there's no seat of wildcard synthesis */
1683 if (wild_offset == 0)
1684 {
1685 if (!(wildcard = strchr(next_closest, '.')) || wildcard == next_closest)
1686 return DNSSEC_FAIL_NONSEC;
1687
1688 wildcard--;
1689 *wildcard = '*';
1690
1691 if (dec_counter(validate_counter, NULL))
1692 return DNSSEC_FAIL_WORK;
1693
1694 if ((digest_len = hash_name(wildcard, &digest, hash, salt, salt_len, iterations)) == 0)
1695 return DNSSEC_FAIL_NONSEC;
1696
1697 if (!check_nsec3_coverage(header, plen, digest_len, digest, type, workspace1, workspace2, nsecs, nsec_count, NULL, 1))
1698 return DNSSEC_FAIL_NONSEC;
1699 }
1700
1701 return 0;
1702 }
1703
1704 /* returns 0 on success, or DNSSEC_FAIL_* value on failure. */
1705 static int prove_non_existence(struct dns_header *header, size_t plen, char *keyname, char *name, int qtype, int qclass,
1706 int wild_offset, int *nons, int *nsec_ttl, int *validate_counter)
1707 {
1708 static unsigned char **nsecset = NULL, **rrsig_labels = NULL;
1709 static int nsecset_sz = 0, rrsig_labels_sz = 0;
1710
1711 int type_found = 0;
1712 unsigned char *auth_start, *p = skip_questions(header, plen);
1713 int type, class, rdlen, i, nsecs_found;
1714 unsigned long ttl;
1715
1716 /* Move to NS section */
1717 if (!p || !(p = skip_section(p, ntohs(header->ancount), header, plen)))
1718 return DNSSEC_FAIL_BADPACKET;
1719
1720 auth_start = p;
1721
1722 for (nsecs_found = 0, i = 0; i < ntohs(header->nscount); i++)
1723 {
1724 unsigned char *pstart = p;
1725
1726 if (!extract_name(header, plen, &p, daemon->workspacename, EXTR_NAME_EXTRACT, 10))
1727 return DNSSEC_FAIL_BADPACKET;
1728
1729 GETSHORT(type, p);
1730 GETSHORT(class, p);
1731 GETLONG(ttl, p);
1732 GETSHORT(rdlen, p);
1733
1734 if (!CHECK_LEN(header, p, plen, rdlen))
1735 return DNSSEC_FAIL_BADPACKET;
1736
1737 if (class == qclass && (type == T_NSEC || type == T_NSEC3))
1738 {
1739 if (nsec_ttl)
1740 {
1741 /* Limit TTL with sig TTL */
1742 if (daemon->rr_status[ntohs(header->ancount) + i] < ttl)
1743 ttl = daemon->rr_status[ntohs(header->ancount) + i];
1744 *nsec_ttl = ttl;
1745 }
1746
1747 /* No mixed NSECing 'round here, thankyouverymuch */
1748 if (type_found != 0 && type_found != type)
1749 return DNSSEC_FAIL_NONSEC;
1750
1751 type_found = type;
1752
1753 if (!expand_workspace(&nsecset, &nsecset_sz, nsecs_found))
1754 return DNSSEC_FAIL_BADPACKET;
1755
1756 if (type == T_NSEC)
1757 {
1758 /* If we're looking for NSECs, find the corresponding SIGs, to
1759 extract the labels value, which we need in case the NSECs
1760 are the result of wildcard expansion.
1761 Note that the NSEC may not have been validated yet
1762 so if there are multiple SIGs, make sure the label value
1763 is the same in all, to avoid be duped by a rogue one.
1764 If there are no SIGs, that's an error */
1765 unsigned char *p1 = auth_start;
1766 int res, j, rdlen1, type1, class1;
1767
1768 if (!expand_workspace(&rrsig_labels, &rrsig_labels_sz, nsecs_found))
1769 return DNSSEC_FAIL_BADPACKET;
1770
1771 rrsig_labels[nsecs_found] = NULL;
1772
1773 for (j = ntohs(header->nscount); j != 0; j--)
1774 {
1775 unsigned char *psav;
1776
1777 if (!(res = extract_name(header, plen, &p1, daemon->workspacename, EXTR_NAME_COMPARE, 10)))
1778 return DNSSEC_FAIL_BADPACKET;
1779
1780 GETSHORT(type1, p1);
1781 GETSHORT(class1, p1);
1782 p1 += 4; /* TTL */
1783 GETSHORT(rdlen1, p1);
1784
1785 psav = p1;
1786
1787 if (!CHECK_LEN(header, p1, plen, rdlen1))
1788 return DNSSEC_FAIL_BADPACKET;
1789
1790 if (res == 1 && class1 == qclass && type1 == T_RRSIG)
1791 {
1792 int type_covered;
1793
1794 if (rdlen1 < 18)
1795 return DNSSEC_FAIL_BADPACKET; /* bad packet */
1796
1797 GETSHORT(type_covered, p1);
1798
1799 if (type_covered == T_NSEC)
1800 {
1801 p1++; /* algo */
1802
1803 /* labels field must be the same in every SIG we find. */
1804 if (!rrsig_labels[nsecs_found])
1805 rrsig_labels[nsecs_found] = p1;
1806 else if (*rrsig_labels[nsecs_found] != *p1) /* algo */
1807 return DNSSEC_FAIL_NONSEC;
1808 }
1809 }
1810
1811 p1 = psav + rdlen1;
1812 }
1813
1814 /* Must have found at least one sig. */
1815 if (!rrsig_labels[nsecs_found])
1816 return DNSSEC_FAIL_NONSEC;
1817 }
1818 else if (type == T_NSEC3)
1819 {
1820 /* Decode the packet structure enough to check that rdlen is big enough
1821 to contain everything other than the type bitmap.
1822 (packet checked to be long enough to contain rdlen above)
1823 We don't need to do any further length checks in check_nes3_coverage()
1824 or prove_non_existence_nsec3() */
1825
1826 int salt_len, hash_len;
1827 unsigned char *psav = p;
1828
1829 if (rdlen < 5)
1830 return DNSSEC_FAIL_BADPACKET;
1831
1832 p += 4; /* algo, flags, iterations */
1833 salt_len = *p++; /* salt_len */
1834 if (rdlen < (6 + salt_len))
1835 return DNSSEC_FAIL_BADPACKET; /* check up to hash_length */
1836
1837 p += salt_len; /* salt */
1838 hash_len = *p++;
1839 if (rdlen < (6 + salt_len + hash_len))
1840 return DNSSEC_FAIL_BADPACKET; /* check to end of next hashed name */
1841
1842 p = psav;
1843 }
1844
1845 nsecset[nsecs_found++] = pstart;
1846 }
1847
1848 p += rdlen;
1849 }
1850
1851 if (type_found == T_NSEC)
1852 return prove_non_existence_nsec(header, plen, nsecset, rrsig_labels, nsecs_found, daemon->workspacename, keyname, name, qtype, nons);
1853 else if (type_found == T_NSEC3)
1854 return prove_non_existence_nsec3(header, plen, nsecset, nsecs_found, daemon->workspacename, keyname, name, qtype, wild_offset, nons, validate_counter);
1855 else
1856 return DNSSEC_FAIL_NONSEC;
1857 }
1858
1859 /* Check signing status of name.
1860 returns:
1861 STAT_SECURE zone is signed.
1862 STAT_INSECURE zone proved unsigned.
1863 STAT_NEED_DS require DS record of name returned in keyname.
1864 STAT_NEED_KEY require DNSKEY record of name returned in keyname.
1865 name returned unaltered.
1866 */
1867 static int zone_status(char *name, int class, char *keyname, time_t now)
1868 {
1869 int name_start = strlen(name); /* for when TA is root */
1870 struct crec *crecp;
1871 char *p;
1872
1873 /* First, work towards the root, looking for a trust anchor.
1874 This can either be one configured, or one previously cached.
1875 We can assume, if we don't find one first, that there is
1876 a trust anchor at the root. */
1877 for (p = name; p; p = strchr(p, '.'))
1878 {
1879 if (*p == '.')
1880 p++;
1881
1882 if (cache_find_by_name(NULL, p, now, F_DS))
1883 {
1884 name_start = p - name;
1885 break;
1886 }
1887 }
1888
1889 /* Now work away from the trust anchor */
1890 while (1)
1891 {
1892 strcpy(keyname, &name[name_start]);
1893
1894 if (!(crecp = cache_find_by_name(NULL, keyname, now, F_DS)))
1895 return STAT_NEED_DS;
1896
1897 /* F_DNSSECOK misused in DS cache records to non-existence of NS record.
1898 F_NEG && !F_DNSSECOK implies that we've proved there's no DS record here,
1899 but that's because there's no NS record either, ie this isn't the start
1900 of a zone. We only prove that the DNS tree below a node is unsigned when
1901 we prove that we're at a zone cut AND there's no DS record. */
1902 if (crecp->flags & F_NEG)
1903 {
1904 if (crecp->flags & F_DNSSECOK)
1905 return STAT_INSECURE; /* proved no DS here */
1906 }
1907 else
1908 {
1909 /* If all the DS records have digest and/or sig algos we don't support,
1910 then the zone is insecure. Note that if an algo
1911 appears in the DS, then RRSIGs for that algo MUST
1912 exist for each RRset: 4035 para 2.2 So if we find
1913 a DS here with digest and sig we can do, we're entitled
1914 to assume we can validate the zone and if we can't later,
1915 because an RRSIG is missing we return BOGUS.
1916 */
1917 do
1918 {
1919 if (crecp->uid == (unsigned int)class &&
1920 ds_digest_name(crecp->addr.ds.digest) &&
1921 algo_digest_name(crecp->addr.ds.algo))
1922 break;
1923 }
1924 while ((crecp = cache_find_by_name(crecp, keyname, now, F_DS)));
1925
1926 if (!crecp)
1927 return STAT_INSECURE;
1928 }
1929
1930 if (name_start == 0)
1931 break;
1932
1933 for (p = &name[name_start-2]; (*p != '.') && (p != name); p--);
1934
1935 if (p != name)
1936 p++;
1937
1938 name_start = p - name;
1939 }
1940
1941 return STAT_SECURE;
1942 }
1943
1944 /* Validate all the RRsets in the answer and authority sections of the reply (4035:3.2.3)
1945 Return code:
1946 STAT_SECURE if it validates.
1947 STAT_INSECURE at least one RRset not validated, because in unsigned zone.
1948 STAT_BOGUS signature is wrong, bad packet, no validation where there should be.
1949 STAT_NEED_KEY need DNSKEY to complete validation (name is returned in keyname, class in *class)
1950 STAT_NEED_DS need DS to complete validation (name is returned in keyname)
1951 STAT_ABANDONED resource exhaustion.
1952
1953 daemon->rr_status points to a char array which corressponds to the RRs in the
1954 answer and auth sections. This is set to >1 for each RR which is validated, and 0 for any which aren't.
1955
1956 When validating replies to DS records, we're only interested in the NSEC{3} RRs in the auth section.
1957 Other RRs in that section missing sigs will not cause am INSECURE reply. We determine this mode
1958 if the nons argument is non-NULL.
1959 */
1960 int dnssec_validate_reply(time_t now, struct dns_header *header, size_t plen, char *name, char *keyname,
1961 int *class, int check_unsigned, int *neganswer, int *prim_ok, int *nons, int *nsec_ttl, int *validate_counter)
1962 {
1963 static unsigned char **targets = NULL;
1964 static int target_sz = 0;
1965
1966 unsigned char *ans_start, *p1, *p2, *p3;
1967 int type1, class1, rdlen1 = 0, type2, class2, rdlen2, qclass, qtype, targetidx, gotdname;
1968 int i, j, k, rc = STAT_INSECURE;
1969 int secure = STAT_SECURE;
1970 int rc_nsec;
1971 unsigned long ttl;
1972
1973 /* extend rr_status if necessary */
1974 if (daemon->rr_status_sz < ntohs(header->ancount) + ntohs(header->nscount))
1975 {
1976 unsigned long *new = whine_malloc(sizeof(*daemon->rr_status) * (ntohs(header->ancount) + ntohs(header->nscount) + 64));
1977
1978 if (!new)
1979 return STAT_BOGUS;
1980
1981 free(daemon->rr_status);
1982 daemon->rr_status = new;
1983 daemon->rr_status_sz = ntohs(header->ancount) + ntohs(header->nscount) + 64;
1984 }
1985
1986 memset(daemon->rr_status, 0, sizeof(*daemon->rr_status) * daemon->rr_status_sz);
1987
1988 if (neganswer)
1989 *neganswer = 0;
1990
1991 if (RCODE(header) == SERVFAIL)
1992 return STAT_BOGUS | DNSSEC_FAIL_UPSTREAM;
1993
1994 if (ntohs(header->qdcount) != 1)
1995 return STAT_BOGUS;
1996
1997 if (RCODE(header) != NXDOMAIN && RCODE(header) != NOERROR)
1998 return STAT_INSECURE;
1999
2000 p1 = (unsigned char *)(header+1);
2001
2002 /* Find all the targets we're looking for answers to.
2003 The zeroth array element is for the query, subsequent ones
2004 for CNAME targets, unless the query is for a CNAME or ANY. */
2005
2006 if (!expand_workspace(&targets, &target_sz, 0))
2007 return STAT_BOGUS;
2008
2009 targets[0] = p1;
2010 targetidx = 1;
2011
2012 if (!extract_name(header, plen, &p1, name, EXTR_NAME_EXTRACT, 4))
2013 return STAT_BOGUS;
2014
2015 GETSHORT(qtype, p1);
2016 GETSHORT(qclass, p1);
2017 ans_start = p1;
2018
2019 /* Can't validate an RRSIG query */
2020 if (qtype == T_RRSIG)
2021 return STAT_INSECURE;
2022
2023 /* Find CNAME targets. */
2024 for (gotdname = i = 0; i < ntohs(header->ancount); i++)
2025 {
2026 if (!(p1 = skip_name(p1, header, plen, 10)))
2027 return STAT_BOGUS; /* bad packet */
2028
2029 GETSHORT(type1, p1);
2030 GETSHORT(class1, p1);
2031 p1 += 4; /* TTL */
2032 GETSHORT(rdlen1, p1);
2033
2034 if (type1 == T_DNAME)
2035 gotdname = 1;
2036
2037 if (qtype != T_CNAME && qtype != T_ANY && type1 == T_CNAME && class1 == qclass)
2038 {
2039 if (!expand_workspace(&targets, &target_sz, targetidx))
2040 return STAT_BOGUS;
2041
2042 targets[targetidx++] = p1; /* pointer to target name */
2043 }
2044
2045 if (!ADD_RDLEN(header, p1, plen, rdlen1))
2046 return STAT_BOGUS;
2047 }
2048
2049 /* A DNAME capable of sythesising a CNAME means we don't need to validate the CNAME,
2050 we can just assume that it's valid. RFC 4035 3.2.3 */
2051 if (gotdname)
2052 for (p1 = ans_start, i = 0; i < ntohs(header->ancount); i++)
2053 {
2054 if (!extract_name(header, plen, &p1, name, EXTR_NAME_EXTRACT, 10))
2055 return STAT_BOGUS; /* bad packet */
2056
2057 GETSHORT(type1, p1);
2058 GETSHORT(class1, p1);
2059 p1 += 4; /* TTL */
2060 GETSHORT(rdlen1, p1);
2061
2062 if (type1 != T_DNAME)
2063 {
2064 if (!ADD_RDLEN(header, p1, plen, rdlen1))
2065 return STAT_BOGUS;
2066 }
2067 else
2068 {
2069 if (!extract_name(header, plen, &p1, keyname, EXTR_NAME_EXTRACT, 0))
2070 return STAT_BOGUS; /* bad packet */
2071
2072 /* We now have the name of the DNAME in name, and the target in keyname.
2073 Look for any CNAMEs which could have been synthesised from this DNAME
2074 and pre-qualify them. */
2075 for (p2 = ans_start, j = 0; j < ntohs(header->ancount); j++)
2076 {
2077 if (!extract_name(header, plen, &p2, daemon->cname, EXTR_NAME_EXTRACT, 10))
2078 return STAT_BOGUS; /* bad packet */
2079
2080 GETSHORT(type2, p2);
2081 GETSHORT(class2, p2);
2082 GETLONG(ttl, p2);
2083 GETSHORT(rdlen2, p2);
2084
2085 if (type2 != T_CNAME || class2 != class1)
2086 {
2087 if (!ADD_RDLEN(header, p2, plen, rdlen2))
2088 return STAT_BOGUS;
2089 }
2090 else
2091 {
2092 size_t name_prefix_len = strlen(daemon->cname) - strlen(name);
2093
2094 if (!extract_name(header, plen, &p2, daemon->workspacename, EXTR_NAME_EXTRACT, 0))
2095 return STAT_BOGUS; /* bad packet */
2096
2097 /* We have the name of the CNAME in daemon->cname, and the target in daemon->workspacename.
2098 See if the CNAME was sythesised from the DNAME.
2099 CNAME must be <subdomain>.<dname>
2100 CNAME target must be <subdomain>.<dname_target>
2101 <subdomain>s must match for name and target. */
2102 if (hostname_issubdomain(name, daemon->cname) == 1 &&
2103 hostname_issubdomain(keyname, daemon->workspacename) == 1 &&
2104 name_prefix_len == strlen(daemon->workspacename) - strlen(keyname))
2105 {
2106 char save = daemon->cname[name_prefix_len];
2107 daemon->cname[name_prefix_len] = 0;
2108 daemon->workspacename[name_prefix_len] = 0;
2109
2110 if (hostname_isequal(daemon->cname, daemon->workspacename))
2111 {
2112 /* pre-qualify this as validated */
2113 daemon->rr_status[j] = ttl > 0 ? ttl : 1;
2114
2115 /* and remove it from the targets we need to have validated answers to. */
2116 if (class2 == qclass)
2117 {
2118 daemon->cname[name_prefix_len] = save;
2119 for (k = 0; k <targetidx; k++)
2120 if ((p3 = targets[k]))
2121 {
2122 int rc1;
2123 if (!(rc1 = extract_name(header, plen, &p3, daemon->cname, EXTR_NAME_COMPARE, 0)))
2124 return STAT_BOGUS; /* bad packet */
2125
2126 if (rc1 == 1)
2127 targets[k] = NULL;
2128 }
2129 }
2130 }
2131 }
2132 }
2133 }
2134 }
2135 }
2136
2137 for (p1 = ans_start, i = 0; i < ntohs(header->ancount) + ntohs(header->nscount); i++)
2138 {
2139 if (i != 0 && !ADD_RDLEN(header, p1, plen, rdlen1))
2140 return STAT_BOGUS;
2141
2142 if (!extract_name(header, plen, &p1, name, EXTR_NAME_EXTRACT, 10))
2143 return STAT_BOGUS; /* bad packet */
2144
2145 GETSHORT(type1, p1);
2146 GETSHORT(class1, p1);
2147 p1 += 4; /* TTL */
2148 GETSHORT(rdlen1, p1);
2149
2150 /* Don't try and validate RRSIGs! */
2151 if (type1 == T_RRSIG)
2152 continue;
2153
2154 /* Pre-validated by DNAME above don't validate. */
2155 if (daemon->rr_status[i] != 0)
2156 continue;
2157
2158 /* Check if we've done this RRset already */
2159 for (p2 = ans_start, j = 0; j < i; j++)
2160 {
2161 if (!(rc = extract_name(header, plen, &p2, name, EXTR_NAME_COMPARE, 10)))
2162 return STAT_BOGUS; /* bad packet */
2163
2164 GETSHORT(type2, p2);
2165 GETSHORT(class2, p2);
2166 p2 += 4; /* TTL */
2167 GETSHORT(rdlen2, p2);
2168
2169 if (type2 == type1 && class2 == class1 && rc == 1)
2170 break; /* Done it before: name, type, class all match. */
2171
2172 if (!ADD_RDLEN(header, p2, plen, rdlen2))
2173 return STAT_BOGUS;
2174 }
2175
2176 /* Done already: copy the validation status */
2177 if (j != i)
2178 daemon->rr_status[i] = daemon->rr_status[j];
2179 else
2180 {
2181 /* Not done, validate now */
2182 int sigcnt, rrcnt, wild_offset;
2183
2184 if (!explore_rrset(header, plen, class1, type1, name, keyname, &sigcnt, &rrcnt))
2185 return STAT_BOGUS;
2186
2187 /* NSEC and NSEC3 records must be signed. We make this assumption elsewhere. */
2188 if (sigcnt == 0 && (type1 == T_NSEC || type1 == T_NSEC3))
2189 return STAT_BOGUS | DNSSEC_FAIL_NOSIG;
2190 else if (sigcnt == 0 && nons && i >= ntohs(header->ancount))
2191 /* If we're validating a DS reply, rather than looking for the value of AD bit,
2192 we only care that NSEC and NSEC3 RRs in the auth section are signed.
2193 Return SECURE even if others (SOA....) are not. */
2194 rc = STAT_SECURE;
2195 else if (sigcnt == 0 && (!check_unsigned || i >= ntohs(header->ancount)))
2196 /* unsigned RRsets in auth section are not BOGUS, but do make reply insecure. */
2197 rc = STAT_INSECURE;
2198 else
2199 {
2200 /* explore_rrset() gives us zone name from sigs in keyname, if
2201 it didn't find a key, use the name we're validating.
2202 Can't overwrite name here. */
2203 if (sigcnt == 0)
2204 strcpy(daemon->workspacename, name);
2205 else
2206 strcpy(daemon->workspacename, keyname);
2207
2208 rc = zone_status(daemon->workspacename, class1, keyname, now);
2209
2210 if (STAT_ISEQUAL(rc, STAT_BOGUS) || STAT_ISEQUAL(rc, STAT_NEED_KEY) || STAT_ISEQUAL(rc, STAT_NEED_DS))
2211 {
2212 if (class)
2213 *class = class1; /* Class for NEED_DS or NEED_KEY */
2214 return rc;
2215 }
2216
2217 /* If zone is insecure, don't need to validate RRset, and rc remains as STAT_INSECURE*/
2218 if (STAT_ISEQUAL(rc, STAT_SECURE))
2219 {
2220 unsigned long sig_ttl;
2221 rc = validate_rrset(now, header, plen, class1, type1, sigcnt,
2222 rrcnt, name, keyname, &wild_offset, NULL, 0, 0, 0, &sig_ttl, validate_counter);
2223
2224 if (STAT_ISEQUAL(rc, STAT_BOGUS) || STAT_ISEQUAL(rc, STAT_NEED_KEY) || STAT_ISEQUAL(rc, STAT_NEED_DS) || STAT_ISEQUAL(rc, STAT_ABANDONED))
2225 {
2226 if (class)
2227 *class = class1; /* Class for DS or DNSKEY */
2228 return rc;
2229 }
2230
2231 /* rc is now STAT_SECURE */
2232
2233 /* Note that RR is validated */
2234 daemon->rr_status[i] = sig_ttl;
2235
2236 /* Note if we've validated either the answer to the question
2237 or the target of a CNAME. Any not noted will need NSEC or
2238 to be in unsigned space. */
2239 for (j = 0; j <targetidx; j++)
2240 if ((p2 = targets[j]))
2241 {
2242 int rc1;
2243 if (!(rc1 = extract_name(header, plen, &p2, name, EXTR_NAME_COMPARE, 10)))
2244 return STAT_BOGUS; /* bad packet */
2245
2246 if (class1 == qclass && rc1 == 1 && (type1 == T_CNAME || type1 == qtype || qtype == T_ANY ))
2247 targets[j] = NULL;
2248 }
2249
2250 /* An attacker replay a wildcard answer with a different
2251 answer and overlay a genuine RR. To prove this
2252 hasn't happened, the answer must prove that
2253 the genuine record doesn't exist. Check that here.
2254 Note that we may not yet have validated the NSEC/NSEC3 RRsets.
2255 That's not a problem since if the RRsets later fail
2256 we'll return BOGUS then. */
2257 if (wild_offset != 0 &&
2258 ((rc_nsec = prove_non_existence(header, plen, keyname, name, type1, class1, wild_offset, NULL, NULL, validate_counter))) != 0)
2259 return (rc_nsec & DNSSEC_FAIL_WORK) ? STAT_ABANDONED : (STAT_BOGUS | rc_nsec);
2260
2261 rc = STAT_SECURE;
2262 }
2263 }
2264 }
2265
2266 if (STAT_ISEQUAL(rc, STAT_INSECURE))
2267 secure = STAT_INSECURE;
2268 }
2269
2270
2271 /* For a DS record, we are interested also in if the answer to the DS query was
2272 a CNAME RRset which validated. That's proof that the DS doesn't exist,
2273 even if it's a CNAME which is not signed, and therefore we have no proof
2274 of what it actually _is_. This return tells us that the answer to
2275 primary query is secure, even is the whole answer is insecure, because
2276 something down the CNAME list doesn't validate or doesn't exist.
2277 Note that prim_ok is only valid when neganswer is true, ie either
2278 the answer is the requested record or it's a CNAME that ends
2279 in a missing answer or an unsigned zone.
2280 */
2281 if (prim_ok)
2282 *prim_ok = !targets[0];
2283
2284 /* OK, all the RRsets validate, now see if we have a missing answer or CNAME target. */
2285 for (j = 0; j <targetidx; j++)
2286 if ((p2 = targets[j]))
2287 {
2288 if (neganswer)
2289 *neganswer = 1;
2290
2291 if (!extract_name(header, plen, &p2, name, EXTR_NAME_EXTRACT, 10))
2292 return STAT_BOGUS; /* bad packet */
2293
2294 /* NXDOMAIN or NODATA reply, unanswered question is (name, qclass, qtype)
2295 This situation is OK if either the answer is in an unsigned zone, or there's NSEC records. */
2296 if ((rc_nsec = prove_non_existence(header, plen, keyname, name, qtype, qclass, 0, nons, nsec_ttl, validate_counter)) != 0)
2297 {
2298 if (rc_nsec & DNSSEC_FAIL_WORK)
2299 return STAT_ABANDONED;
2300
2301 if ((rc_nsec & (DNSSEC_FAIL_NONSEC | DNSSEC_FAIL_NSEC3_ITERS)) &&
2302 !STAT_ISEQUAL((rc = zone_status(name, qclass, keyname, now)), STAT_SECURE))
2303 {
2304 if (class)
2305 *class = qclass; /* Class for NEED_DS or NEED_KEY */
2306 return rc;
2307 }
2308
2309 return STAT_BOGUS | rc_nsec; /* signed zone, no NSECs */
2310 }
2311 }
2312
2313 return secure;
2314 }
2315
2316
2317 /* Compute keytag (checksum to quickly index a key). See RFC4034 */
2318 int dnskey_keytag(int alg, int flags, unsigned char *key, int keylen)
2319 {
2320 if (alg == 1)
2321 {
2322 /* Algorithm 1 (RSAMD5) has a different (older) keytag calculation algorithm.
2323 See RFC4034, Appendix B.1 */
2324 return key[keylen-4] * 256 + key[keylen-3];
2325 }
2326 else
2327 {
2328 unsigned long ac = flags + 0x300 + alg;
2329 int i;
2330
2331 for (i = 0; i < keylen; ++i)
2332 ac += (i & 1) ? key[i] : key[i] << 8;
2333
2334 ac += (ac >> 16) & 0xffff;
2335 return ac & 0xffff;
2336 }
2337 }
2338
2339 size_t dnssec_generate_query(struct dns_header *header, size_t outlen, char *name,
2340 int class, int id, int type)
2341 {
2342 unsigned char *p;
2343
2344 header->qdcount = htons(1);
2345 header->ancount = htons(0);
2346 header->nscount = htons(0);
2347 header->arcount = htons(0);
2348 header->id = htons(id);
2349
2350 header->hb3 = HB3_RD;
2351 SET_OPCODE(header, QUERY);
2352 /* For debugging, set Checking Disabled, otherwise, have the upstream check too,
2353 this allows it to select auth servers when one is returning bad data. */
2354 header->hb4 = option_bool(OPT_DNSSEC_DEBUG) ? HB4_CD : 0;
2355
2356 p = (unsigned char *)(header+1);
2357
2358 p = do_rfc1035_name(p, name, NULL);
2359 *p++ = 0;
2360 PUTSHORT(type, p);
2361 PUTSHORT(class, p);
2362
2363 return add_do_bit(header, p - (unsigned char *)header, outlen);
2364 }
2365
2366 int errflags_to_ede(int status)
2367 {
2368 /* We can end up with more than one flag set for some errors,
2369 so this encodes a rough priority so the (eg) No sig is reported
2370 before no-unexpired-sig. */
2371 if (status & DNSSEC_FAIL_UPSTREAM)
2372 return EDE_US_SERVFAIL;
2373 else if (status & DNSSEC_FAIL_NYV)
2374 return EDE_SIG_NYV;
2375 else if (status & DNSSEC_FAIL_EXP)
2376 return EDE_SIG_EXP;
2377 else if (status & DNSSEC_FAIL_NOKEYSUP)
2378 return EDE_USUPDNSKEY;
2379 else if (status & DNSSEC_FAIL_NOZONE)
2380 return EDE_NO_ZONEKEY;
2381 else if (status & DNSSEC_FAIL_NOKEY)
2382 return EDE_NO_DNSKEY;
2383 else if (status & DNSSEC_FAIL_NODSSUP)
2384 return EDE_USUPDS;
2385 else if (status & DNSSEC_FAIL_NSEC3_ITERS)
2386 return EDE_UNS_NS3_ITER;
2387 else if (status & DNSSEC_FAIL_NONSEC)
2388 return EDE_NO_NSEC;
2389 else if (status & DNSSEC_FAIL_INDET)
2390 return EDE_DNSSEC_IND;
2391 else if (status & DNSSEC_FAIL_NOSIG)
2392 return EDE_NO_RRSIG;
2393 else
2394 return EDE_UNSET;
2395 }
2396 #endif /* HAVE_DNSSEC */