xref: /freebsd/contrib/unbound/validator/val_sigcrypt.c (revision 96190b4fef3b4a0cc3ca0606b0c4e3e69a5e6717)
1 /*
2  * validator/val_sigcrypt.c - validator signature crypto functions.
3  *
4  * Copyright (c) 2007, NLnet Labs. All rights reserved.
5  *
6  * This software is open source.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * Redistributions of source code must retain the above copyright notice,
13  * this list of conditions and the following disclaimer.
14  *
15  * Redistributions in binary form must reproduce the above copyright notice,
16  * this list of conditions and the following disclaimer in the documentation
17  * and/or other materials provided with the distribution.
18  *
19  * Neither the name of the NLNET LABS nor the names of its contributors may
20  * be used to endorse or promote products derived from this software without
21  * specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27  * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
29  * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
30  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
32  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
33  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34  */
35 
36 /**
37  * \file
38  *
39  * This file contains helper functions for the validator module.
40  * The functions help with signature verification and checking, the
41  * bridging between RR wireformat data and crypto calls.
42  */
43 #include "config.h"
44 #include "validator/val_sigcrypt.h"
45 #include "validator/val_secalgo.h"
46 #include "validator/validator.h"
47 #include "util/data/msgreply.h"
48 #include "util/data/msgparse.h"
49 #include "util/data/dname.h"
50 #include "util/rbtree.h"
51 #include "util/rfc_1982.h"
52 #include "util/module.h"
53 #include "util/net_help.h"
54 #include "util/regional.h"
55 #include "util/config_file.h"
56 #include "sldns/keyraw.h"
57 #include "sldns/sbuffer.h"
58 #include "sldns/parseutil.h"
59 #include "sldns/wire2str.h"
60 
61 #include <ctype.h>
62 #if !defined(HAVE_SSL) && !defined(HAVE_NSS) && !defined(HAVE_NETTLE)
63 #error "Need crypto library to do digital signature cryptography"
64 #endif
65 
66 #ifdef HAVE_OPENSSL_ERR_H
67 #include <openssl/err.h>
68 #endif
69 
70 #ifdef HAVE_OPENSSL_RAND_H
71 #include <openssl/rand.h>
72 #endif
73 
74 #ifdef HAVE_OPENSSL_CONF_H
75 #include <openssl/conf.h>
76 #endif
77 
78 #ifdef HAVE_OPENSSL_ENGINE_H
79 #include <openssl/engine.h>
80 #endif
81 
82 /** Maximum number of RRSIG validations for an RRset. */
83 #define MAX_VALIDATE_RRSIGS 8
84 
85 /** return number of rrs in an rrset */
86 static size_t
87 rrset_get_count(struct ub_packed_rrset_key* rrset)
88 {
89 	struct packed_rrset_data* d = (struct packed_rrset_data*)
90 	rrset->entry.data;
91 	if(!d) return 0;
92 	return d->count;
93 }
94 
95 /**
96  * Get RR signature count
97  */
98 static size_t
99 rrset_get_sigcount(struct ub_packed_rrset_key* k)
100 {
101 	struct packed_rrset_data* d = (struct packed_rrset_data*)k->entry.data;
102 	return d->rrsig_count;
103 }
104 
105 /**
106  * Get signature keytag value
107  * @param k: rrset (with signatures)
108  * @param sig_idx: signature index.
109  * @return keytag or 0 if malformed rrsig.
110  */
111 static uint16_t
112 rrset_get_sig_keytag(struct ub_packed_rrset_key* k, size_t sig_idx)
113 {
114 	uint16_t t;
115 	struct packed_rrset_data* d = (struct packed_rrset_data*)k->entry.data;
116 	log_assert(sig_idx < d->rrsig_count);
117 	if(d->rr_len[d->count + sig_idx] < 2+18)
118 		return 0;
119 	memmove(&t, d->rr_data[d->count + sig_idx]+2+16, 2);
120 	return ntohs(t);
121 }
122 
123 /**
124  * Get signature signing algorithm value
125  * @param k: rrset (with signatures)
126  * @param sig_idx: signature index.
127  * @return algo or 0 if malformed rrsig.
128  */
129 static int
130 rrset_get_sig_algo(struct ub_packed_rrset_key* k, size_t sig_idx)
131 {
132 	struct packed_rrset_data* d = (struct packed_rrset_data*)k->entry.data;
133 	log_assert(sig_idx < d->rrsig_count);
134 	if(d->rr_len[d->count + sig_idx] < 2+3)
135 		return 0;
136 	return (int)d->rr_data[d->count + sig_idx][2+2];
137 }
138 
139 /** get rdata pointer and size */
140 static void
141 rrset_get_rdata(struct ub_packed_rrset_key* k, size_t idx, uint8_t** rdata,
142 	size_t* len)
143 {
144 	struct packed_rrset_data* d = (struct packed_rrset_data*)k->entry.data;
145 	log_assert(d && idx < (d->count + d->rrsig_count));
146 	*rdata = d->rr_data[idx];
147 	*len = d->rr_len[idx];
148 }
149 
150 uint16_t
151 dnskey_get_flags(struct ub_packed_rrset_key* k, size_t idx)
152 {
153 	uint8_t* rdata;
154 	size_t len;
155 	uint16_t f;
156 	rrset_get_rdata(k, idx, &rdata, &len);
157 	if(len < 2+2)
158 		return 0;
159 	memmove(&f, rdata+2, 2);
160 	f = ntohs(f);
161 	return f;
162 }
163 
164 /**
165  * Get DNSKEY protocol value from rdata
166  * @param k: DNSKEY rrset.
167  * @param idx: which key.
168  * @return protocol octet value
169  */
170 static int
171 dnskey_get_protocol(struct ub_packed_rrset_key* k, size_t idx)
172 {
173 	uint8_t* rdata;
174 	size_t len;
175 	rrset_get_rdata(k, idx, &rdata, &len);
176 	if(len < 2+4)
177 		return 0;
178 	return (int)rdata[2+2];
179 }
180 
181 int
182 dnskey_get_algo(struct ub_packed_rrset_key* k, size_t idx)
183 {
184 	uint8_t* rdata;
185 	size_t len;
186 	rrset_get_rdata(k, idx, &rdata, &len);
187 	if(len < 2+4)
188 		return 0;
189 	return (int)rdata[2+3];
190 }
191 
192 /** get public key rdata field from a dnskey RR and do some checks */
193 static void
194 dnskey_get_pubkey(struct ub_packed_rrset_key* k, size_t idx,
195 	unsigned char** pk, unsigned int* pklen)
196 {
197 	uint8_t* rdata;
198 	size_t len;
199 	rrset_get_rdata(k, idx, &rdata, &len);
200 	if(len < 2+5) {
201 		*pk = NULL;
202 		*pklen = 0;
203 		return;
204 	}
205 	*pk = (unsigned char*)rdata+2+4;
206 	*pklen = (unsigned)len-2-4;
207 }
208 
209 int
210 ds_get_key_algo(struct ub_packed_rrset_key* k, size_t idx)
211 {
212 	uint8_t* rdata;
213 	size_t len;
214 	rrset_get_rdata(k, idx, &rdata, &len);
215 	if(len < 2+3)
216 		return 0;
217 	return (int)rdata[2+2];
218 }
219 
220 int
221 ds_get_digest_algo(struct ub_packed_rrset_key* k, size_t idx)
222 {
223 	uint8_t* rdata;
224 	size_t len;
225 	rrset_get_rdata(k, idx, &rdata, &len);
226 	if(len < 2+4)
227 		return 0;
228 	return (int)rdata[2+3];
229 }
230 
231 uint16_t
232 ds_get_keytag(struct ub_packed_rrset_key* ds_rrset, size_t ds_idx)
233 {
234 	uint16_t t;
235 	uint8_t* rdata;
236 	size_t len;
237 	rrset_get_rdata(ds_rrset, ds_idx, &rdata, &len);
238 	if(len < 2+2)
239 		return 0;
240 	memmove(&t, rdata+2, 2);
241 	return ntohs(t);
242 }
243 
244 /**
245  * Return pointer to the digest in a DS RR.
246  * @param k: DS rrset.
247  * @param idx: which DS.
248  * @param digest: digest data is returned.
249  *	on error, this is NULL.
250  * @param len: length of digest is returned.
251  *	on error, the length is 0.
252  */
253 static void
254 ds_get_sigdata(struct ub_packed_rrset_key* k, size_t idx, uint8_t** digest,
255         size_t* len)
256 {
257 	uint8_t* rdata;
258 	size_t rdlen;
259 	rrset_get_rdata(k, idx, &rdata, &rdlen);
260 	if(rdlen < 2+5) {
261 		*digest = NULL;
262 		*len = 0;
263 		return;
264 	}
265 	*digest = rdata + 2 + 4;
266 	*len = rdlen - 2 - 4;
267 }
268 
269 /**
270  * Return size of DS digest according to its hash algorithm.
271  * @param k: DS rrset.
272  * @param idx: which DS.
273  * @return size in bytes of digest, or 0 if not supported.
274  */
275 static size_t
276 ds_digest_size_algo(struct ub_packed_rrset_key* k, size_t idx)
277 {
278 	return ds_digest_size_supported(ds_get_digest_algo(k, idx));
279 }
280 
281 /**
282  * Create a DS digest for a DNSKEY entry.
283  *
284  * @param env: module environment. Uses scratch space.
285  * @param dnskey_rrset: DNSKEY rrset.
286  * @param dnskey_idx: index of RR in rrset.
287  * @param ds_rrset: DS rrset
288  * @param ds_idx: index of RR in DS rrset.
289  * @param digest: digest is returned in here (must be correctly sized).
290  * @return false on error.
291  */
292 static int
293 ds_create_dnskey_digest(struct module_env* env,
294 	struct ub_packed_rrset_key* dnskey_rrset, size_t dnskey_idx,
295 	struct ub_packed_rrset_key* ds_rrset, size_t ds_idx,
296 	uint8_t* digest)
297 {
298 	sldns_buffer* b = env->scratch_buffer;
299 	uint8_t* dnskey_rdata;
300 	size_t dnskey_len;
301 	rrset_get_rdata(dnskey_rrset, dnskey_idx, &dnskey_rdata, &dnskey_len);
302 
303 	/* create digest source material in buffer
304 	 * digest = digest_algorithm( DNSKEY owner name | DNSKEY RDATA);
305 	 *	DNSKEY RDATA = Flags | Protocol | Algorithm | Public Key. */
306 	sldns_buffer_clear(b);
307 	sldns_buffer_write(b, dnskey_rrset->rk.dname,
308 		dnskey_rrset->rk.dname_len);
309 	query_dname_tolower(sldns_buffer_begin(b));
310 	sldns_buffer_write(b, dnskey_rdata+2, dnskey_len-2); /* skip rdatalen*/
311 	sldns_buffer_flip(b);
312 
313 	return secalgo_ds_digest(ds_get_digest_algo(ds_rrset, ds_idx),
314 		(unsigned char*)sldns_buffer_begin(b), sldns_buffer_limit(b),
315 		(unsigned char*)digest);
316 }
317 
318 int ds_digest_match_dnskey(struct module_env* env,
319 	struct ub_packed_rrset_key* dnskey_rrset, size_t dnskey_idx,
320 	struct ub_packed_rrset_key* ds_rrset, size_t ds_idx)
321 {
322 	uint8_t* ds;	/* DS digest */
323 	size_t dslen;
324 	uint8_t* digest; /* generated digest */
325 	size_t digestlen = ds_digest_size_algo(ds_rrset, ds_idx);
326 
327 	if(digestlen == 0) {
328 		verbose(VERB_QUERY, "DS fail: not supported, or DS RR "
329 			"format error");
330 		return 0; /* not supported, or DS RR format error */
331 	}
332 #ifndef USE_SHA1
333 	if(fake_sha1 && ds_get_digest_algo(ds_rrset, ds_idx)==LDNS_SHA1)
334 		return 1;
335 #endif
336 
337 	/* check digest length in DS with length from hash function */
338 	ds_get_sigdata(ds_rrset, ds_idx, &ds, &dslen);
339 	if(!ds || dslen != digestlen) {
340 		verbose(VERB_QUERY, "DS fail: DS RR algo and digest do not "
341 			"match each other");
342 		return 0; /* DS algorithm and digest do not match */
343 	}
344 
345 	digest = regional_alloc(env->scratch, digestlen);
346 	if(!digest) {
347 		verbose(VERB_QUERY, "DS fail: out of memory");
348 		return 0; /* mem error */
349 	}
350 	if(!ds_create_dnskey_digest(env, dnskey_rrset, dnskey_idx, ds_rrset,
351 		ds_idx, digest)) {
352 		verbose(VERB_QUERY, "DS fail: could not calc key digest");
353 		return 0; /* digest algo failed */
354 	}
355 	if(memcmp(digest, ds, dslen) != 0) {
356 		verbose(VERB_QUERY, "DS fail: digest is different");
357 		return 0; /* digest different */
358 	}
359 	return 1;
360 }
361 
362 int
363 ds_digest_algo_is_supported(struct ub_packed_rrset_key* ds_rrset,
364 	size_t ds_idx)
365 {
366 	return (ds_digest_size_algo(ds_rrset, ds_idx) != 0);
367 }
368 
369 int
370 ds_key_algo_is_supported(struct ub_packed_rrset_key* ds_rrset,
371 	size_t ds_idx)
372 {
373 	return dnskey_algo_id_is_supported(ds_get_key_algo(ds_rrset, ds_idx));
374 }
375 
376 uint16_t
377 dnskey_calc_keytag(struct ub_packed_rrset_key* dnskey_rrset, size_t dnskey_idx)
378 {
379 	uint8_t* data;
380 	size_t len;
381 	rrset_get_rdata(dnskey_rrset, dnskey_idx, &data, &len);
382 	/* do not pass rdatalen to ldns */
383 	return sldns_calc_keytag_raw(data+2, len-2);
384 }
385 
386 int dnskey_algo_is_supported(struct ub_packed_rrset_key* dnskey_rrset,
387         size_t dnskey_idx)
388 {
389 	return dnskey_algo_id_is_supported(dnskey_get_algo(dnskey_rrset,
390 		dnskey_idx));
391 }
392 
393 int dnskey_size_is_supported(struct ub_packed_rrset_key* dnskey_rrset,
394 	size_t dnskey_idx)
395 {
396 #ifdef DEPRECATE_RSA_1024
397 	uint8_t* rdata;
398 	size_t len;
399 	int alg = dnskey_get_algo(dnskey_rrset, dnskey_idx);
400 	size_t keysize;
401 
402 	rrset_get_rdata(dnskey_rrset, dnskey_idx, &rdata, &len);
403 	if(len < 2+4)
404 		return 0;
405 	keysize = sldns_rr_dnskey_key_size_raw(rdata+2+4, len-2-4, alg);
406 
407 	switch((sldns_algorithm)alg) {
408 	case LDNS_RSAMD5:
409 	case LDNS_RSASHA1:
410 	case LDNS_RSASHA1_NSEC3:
411 	case LDNS_RSASHA256:
412 	case LDNS_RSASHA512:
413 		/* reject RSA keys of 1024 bits and shorter */
414 		if(keysize <= 1024)
415 			return 0;
416 		break;
417 	default:
418 		break;
419 	}
420 #else
421 	(void)dnskey_rrset; (void)dnskey_idx;
422 #endif /* DEPRECATE_RSA_1024 */
423 	return 1;
424 }
425 
426 int dnskeyset_size_is_supported(struct ub_packed_rrset_key* dnskey_rrset)
427 {
428 	size_t i, num = rrset_get_count(dnskey_rrset);
429 	for(i=0; i<num; i++) {
430 		if(!dnskey_size_is_supported(dnskey_rrset, i))
431 			return 0;
432 	}
433 	return 1;
434 }
435 
436 void algo_needs_init_dnskey_add(struct algo_needs* n,
437         struct ub_packed_rrset_key* dnskey, uint8_t* sigalg)
438 {
439 	uint8_t algo;
440 	size_t i, total = n->num;
441 	size_t num = rrset_get_count(dnskey);
442 
443 	for(i=0; i<num; i++) {
444 		algo = (uint8_t)dnskey_get_algo(dnskey, i);
445 		if(!dnskey_algo_id_is_supported((int)algo))
446 			continue;
447 		if(n->needs[algo] == 0) {
448 			n->needs[algo] = 1;
449 			sigalg[total] = algo;
450 			total++;
451 		}
452 	}
453 	sigalg[total] = 0;
454 	n->num = total;
455 }
456 
457 void algo_needs_init_list(struct algo_needs* n, uint8_t* sigalg)
458 {
459 	uint8_t algo;
460 	size_t total = 0;
461 
462 	memset(n->needs, 0, sizeof(uint8_t)*ALGO_NEEDS_MAX);
463 	while( (algo=*sigalg++) != 0) {
464 		log_assert(dnskey_algo_id_is_supported((int)algo));
465 		log_assert(n->needs[algo] == 0);
466 		n->needs[algo] = 1;
467 		total++;
468 	}
469 	n->num = total;
470 }
471 
472 void algo_needs_init_ds(struct algo_needs* n, struct ub_packed_rrset_key* ds,
473 	int fav_ds_algo, uint8_t* sigalg)
474 {
475 	uint8_t algo;
476 	size_t i, total = 0;
477 	size_t num = rrset_get_count(ds);
478 
479 	memset(n->needs, 0, sizeof(uint8_t)*ALGO_NEEDS_MAX);
480 	for(i=0; i<num; i++) {
481 		if(ds_get_digest_algo(ds, i) != fav_ds_algo)
482 			continue;
483 		algo = (uint8_t)ds_get_key_algo(ds, i);
484 		if(!dnskey_algo_id_is_supported((int)algo))
485 			continue;
486 		log_assert(algo != 0); /* we do not support 0 and is EOS */
487 		if(n->needs[algo] == 0) {
488 			n->needs[algo] = 1;
489 			sigalg[total] = algo;
490 			total++;
491 		}
492 	}
493 	sigalg[total] = 0;
494 	n->num = total;
495 }
496 
497 int algo_needs_set_secure(struct algo_needs* n, uint8_t algo)
498 {
499 	if(n->needs[algo]) {
500 		n->needs[algo] = 0;
501 		n->num --;
502 		if(n->num == 0) /* done! */
503 			return 1;
504 	}
505 	return 0;
506 }
507 
508 void algo_needs_set_bogus(struct algo_needs* n, uint8_t algo)
509 {
510 	if(n->needs[algo]) n->needs[algo] = 2; /* need it, but bogus */
511 }
512 
513 size_t algo_needs_num_missing(struct algo_needs* n)
514 {
515 	return n->num;
516 }
517 
518 int algo_needs_missing(struct algo_needs* n)
519 {
520 	int i, miss = -1;
521 	/* check if a needed algo was bogus - report that;
522 	 * check the first missing algo - report that;
523 	 * or return 0 */
524 	for(i=0; i<ALGO_NEEDS_MAX; i++) {
525 		if(n->needs[i] == 2)
526 			return 0;
527 		if(n->needs[i] == 1 && miss == -1)
528 			miss = i;
529 	}
530 	if(miss != -1) return miss;
531 	return 0;
532 }
533 
534 /**
535  * verify rrset, with dnskey rrset, for a specific rrsig in rrset
536  * @param env: module environment, scratch space is used.
537  * @param ve: validator environment, date settings.
538  * @param now: current time for validation (can be overridden).
539  * @param rrset: to be validated.
540  * @param dnskey: DNSKEY rrset, keyset to try.
541  * @param sig_idx: which signature to try to validate.
542  * @param sortree: reused sorted order. Stored in region. Pass NULL at start,
543  * 	and for a new rrset.
544  * @param reason: if bogus, a string returned, fixed or alloced in scratch.
545  * @param reason_bogus: EDE (RFC8914) code paired with the reason of failure.
546  * @param section: section of packet where this rrset comes from.
547  * @param qstate: qstate with region.
548  * @param numverified: incremented when the number of RRSIG validations
549  * 	increases.
550  * @return secure if any key signs *this* signature. bogus if no key signs it,
551  *	unchecked on error, or indeterminate if all keys are not supported by
552  *	the crypto library (openssl3+ only).
553  */
554 static enum sec_status
555 dnskeyset_verify_rrset_sig(struct module_env* env, struct val_env* ve,
556 	time_t now, struct ub_packed_rrset_key* rrset,
557 	struct ub_packed_rrset_key* dnskey, size_t sig_idx,
558 	struct rbtree_type** sortree,
559 	char** reason, sldns_ede_code *reason_bogus,
560 	sldns_pkt_section section, struct module_qstate* qstate,
561 	int* numverified)
562 {
563 	/* find matching keys and check them */
564 	enum sec_status sec = sec_status_bogus;
565 	uint16_t tag = rrset_get_sig_keytag(rrset, sig_idx);
566 	int algo = rrset_get_sig_algo(rrset, sig_idx);
567 	size_t i, num = rrset_get_count(dnskey);
568 	size_t numchecked = 0;
569 	size_t numindeterminate = 0;
570 	int buf_canon = 0;
571 	verbose(VERB_ALGO, "verify sig %d %d", (int)tag, algo);
572 	if(!dnskey_algo_id_is_supported(algo)) {
573 		if(reason_bogus)
574 			*reason_bogus = LDNS_EDE_UNSUPPORTED_DNSKEY_ALG;
575 		verbose(VERB_QUERY, "verify sig: unknown algorithm");
576 		return sec_status_insecure;
577 	}
578 
579 	for(i=0; i<num; i++) {
580 		/* see if key matches keytag and algo */
581 		if(algo != dnskey_get_algo(dnskey, i) ||
582 			tag != dnskey_calc_keytag(dnskey, i))
583 			continue;
584 		numchecked ++;
585 		(*numverified)++;
586 
587 		/* see if key verifies */
588 		sec = dnskey_verify_rrset_sig(env->scratch,
589 			env->scratch_buffer, ve, now, rrset, dnskey, i,
590 			sig_idx, sortree, &buf_canon, reason, reason_bogus,
591 			section, qstate);
592 		if(sec == sec_status_secure)
593 			return sec;
594 		else if(sec == sec_status_indeterminate)
595 			numindeterminate ++;
596 		if(*numverified > MAX_VALIDATE_RRSIGS) {
597 			*reason = "too many RRSIG validations";
598 			if(reason_bogus)
599 				*reason_bogus = LDNS_EDE_DNSSEC_BOGUS;
600 			verbose(VERB_ALGO, "verify sig: too many RRSIG validations");
601 			return sec_status_bogus;
602 		}
603 	}
604 	if(numchecked == 0) {
605 		*reason = "signatures from unknown keys";
606 		if(reason_bogus)
607 			*reason_bogus = LDNS_EDE_DNSKEY_MISSING;
608 		verbose(VERB_QUERY, "verify: could not find appropriate key");
609 		return sec_status_bogus;
610 	}
611 	if(numindeterminate == numchecked) {
612 		*reason = "unsupported algorithm by crypto library";
613 		if(reason_bogus)
614 			*reason_bogus = LDNS_EDE_UNSUPPORTED_DNSKEY_ALG;
615 		verbose(VERB_ALGO, "verify sig: unsupported algorithm by "
616 			"crypto library");
617 		return sec_status_indeterminate;
618 	}
619 	return sec_status_bogus;
620 }
621 
622 enum sec_status
623 dnskeyset_verify_rrset(struct module_env* env, struct val_env* ve,
624 	struct ub_packed_rrset_key* rrset, struct ub_packed_rrset_key* dnskey,
625 	uint8_t* sigalg, char** reason, sldns_ede_code *reason_bogus,
626 	sldns_pkt_section section, struct module_qstate* qstate, int* verified,
627 	char* reasonbuf, size_t reasonlen)
628 {
629 	enum sec_status sec;
630 	size_t i, num;
631 	rbtree_type* sortree = NULL;
632 	/* make sure that for all DNSKEY algorithms there are valid sigs */
633 	struct algo_needs needs;
634 	int alg;
635 	*verified = 0;
636 
637 	num = rrset_get_sigcount(rrset);
638 	if(num == 0) {
639 		verbose(VERB_QUERY, "rrset failed to verify due to a lack of "
640 			"signatures");
641 		*reason = "no signatures";
642 		if(reason_bogus)
643 			*reason_bogus = LDNS_EDE_RRSIGS_MISSING;
644 		return sec_status_bogus;
645 	}
646 
647 	if(sigalg) {
648 		algo_needs_init_list(&needs, sigalg);
649 		if(algo_needs_num_missing(&needs) == 0) {
650 			verbose(VERB_QUERY, "zone has no known algorithms");
651 			*reason = "zone has no known algorithms";
652 			if(reason_bogus)
653 				*reason_bogus = LDNS_EDE_UNSUPPORTED_DNSKEY_ALG;
654 			return sec_status_insecure;
655 		}
656 	}
657 	for(i=0; i<num; i++) {
658 		sec = dnskeyset_verify_rrset_sig(env, ve, *env->now, rrset,
659 			dnskey, i, &sortree, reason, reason_bogus,
660 			section, qstate, verified);
661 		/* see which algorithm has been fixed up */
662 		if(sec == sec_status_secure) {
663 			if(!sigalg)
664 				return sec; /* done! */
665 			else if(algo_needs_set_secure(&needs,
666 				(uint8_t)rrset_get_sig_algo(rrset, i)))
667 				return sec; /* done! */
668 		} else if(sigalg && sec == sec_status_bogus) {
669 			algo_needs_set_bogus(&needs,
670 				(uint8_t)rrset_get_sig_algo(rrset, i));
671 		}
672 		if(*verified > MAX_VALIDATE_RRSIGS) {
673 			verbose(VERB_QUERY, "rrset failed to verify, too many RRSIG validations");
674 			*reason = "too many RRSIG validations";
675 			if(reason_bogus)
676 				*reason_bogus = LDNS_EDE_DNSSEC_BOGUS;
677 			return sec_status_bogus;
678 		}
679 	}
680 	if(sigalg && (alg=algo_needs_missing(&needs)) != 0) {
681 		verbose(VERB_ALGO, "rrset failed to verify: "
682 			"no valid signatures for %d algorithms",
683 			(int)algo_needs_num_missing(&needs));
684 		algo_needs_reason(alg, reason, "no signatures", reasonbuf,
685 			reasonlen);
686 	} else {
687 		verbose(VERB_ALGO, "rrset failed to verify: "
688 			"no valid signatures");
689 	}
690 	return sec_status_bogus;
691 }
692 
693 void algo_needs_reason(int alg, char** reason, char* s, char* reasonbuf,
694 	size_t reasonlen)
695 {
696 	sldns_lookup_table *t = sldns_lookup_by_id(sldns_algorithms, alg);
697 	if(t&&t->name)
698 		snprintf(reasonbuf, reasonlen, "%s with algorithm %s", s,
699 			t->name);
700 	else	snprintf(reasonbuf, reasonlen, "%s with algorithm ALG%u", s,
701 			(unsigned)alg);
702 	*reason = reasonbuf;
703 }
704 
705 enum sec_status
706 dnskey_verify_rrset(struct module_env* env, struct val_env* ve,
707         struct ub_packed_rrset_key* rrset, struct ub_packed_rrset_key* dnskey,
708 	size_t dnskey_idx, char** reason, sldns_ede_code *reason_bogus,
709 	sldns_pkt_section section, struct module_qstate* qstate)
710 {
711 	enum sec_status sec;
712 	size_t i, num, numchecked = 0, numindeterminate = 0;
713 	rbtree_type* sortree = NULL;
714 	int buf_canon = 0;
715 	uint16_t tag = dnskey_calc_keytag(dnskey, dnskey_idx);
716 	int algo = dnskey_get_algo(dnskey, dnskey_idx);
717 	int numverified = 0;
718 
719 	num = rrset_get_sigcount(rrset);
720 	if(num == 0) {
721 		verbose(VERB_QUERY, "rrset failed to verify due to a lack of "
722 			"signatures");
723 		*reason = "no signatures";
724 		if(reason_bogus)
725 			*reason_bogus = LDNS_EDE_RRSIGS_MISSING;
726 		return sec_status_bogus;
727 	}
728 	for(i=0; i<num; i++) {
729 		/* see if sig matches keytag and algo */
730 		if(algo != rrset_get_sig_algo(rrset, i) ||
731 			tag != rrset_get_sig_keytag(rrset, i))
732 			continue;
733 		buf_canon = 0;
734 		sec = dnskey_verify_rrset_sig(env->scratch,
735 			env->scratch_buffer, ve, *env->now, rrset,
736 			dnskey, dnskey_idx, i, &sortree, &buf_canon, reason,
737 			reason_bogus, section, qstate);
738 		if(sec == sec_status_secure)
739 			return sec;
740 		numchecked ++;
741 		numverified ++;
742 		if(sec == sec_status_indeterminate)
743 			numindeterminate ++;
744 		if(numverified > MAX_VALIDATE_RRSIGS) {
745 			verbose(VERB_QUERY, "rrset failed to verify, too many RRSIG validations");
746 			*reason = "too many RRSIG validations";
747 			if(reason_bogus)
748 				*reason_bogus = LDNS_EDE_DNSSEC_BOGUS;
749 			return sec_status_bogus;
750 		}
751 	}
752 	if(!numchecked) {
753 		*reason = "signature for expected key and algorithm missing";
754 		if(reason_bogus)
755 			*reason_bogus = LDNS_EDE_DNSSEC_BOGUS;
756 	} else if(numchecked == numindeterminate) {
757 		verbose(VERB_ALGO, "rrset failed to verify due to algorithm "
758 			"refusal by cryptolib");
759 		if(reason_bogus)
760 			*reason_bogus = LDNS_EDE_UNSUPPORTED_DNSKEY_ALG;
761 		*reason = "algorithm refused by cryptolib";
762 		return sec_status_indeterminate;
763 	}
764 	verbose(VERB_ALGO, "rrset failed to verify: all signatures are bogus");
765 	return sec_status_bogus;
766 }
767 
768 /**
769  * RR entries in a canonical sorted tree of RRs
770  */
771 struct canon_rr {
772 	/** rbtree node, key is this structure */
773 	rbnode_type node;
774 	/** rrset the RR is in */
775 	struct ub_packed_rrset_key* rrset;
776 	/** which RR in the rrset */
777 	size_t rr_idx;
778 };
779 
780 /**
781  * Compare two RR for canonical order, in a field-style sweep.
782  * @param d: rrset data
783  * @param desc: ldns wireformat descriptor.
784  * @param i: first RR to compare
785  * @param j: first RR to compare
786  * @return comparison code.
787  */
788 static int
789 canonical_compare_byfield(struct packed_rrset_data* d,
790 	const sldns_rr_descriptor* desc, size_t i, size_t j)
791 {
792 	/* sweep across rdata, keep track of some state:
793 	 * 	which rr field, and bytes left in field.
794 	 * 	current position in rdata, length left.
795 	 * 	are we in a dname, length left in a label.
796 	 */
797 	int wfi = -1;	/* current wireformat rdata field (rdf) */
798 	int wfj = -1;
799 	uint8_t* di = d->rr_data[i]+2; /* ptr to current rdata byte */
800 	uint8_t* dj = d->rr_data[j]+2;
801 	size_t ilen = d->rr_len[i]-2; /* length left in rdata */
802 	size_t jlen = d->rr_len[j]-2;
803 	int dname_i = 0;  /* true if these bytes are part of a name */
804 	int dname_j = 0;
805 	size_t lablen_i = 0; /* 0 for label length byte,for first byte of rdf*/
806 	size_t lablen_j = 0; /* otherwise remaining length of rdf or label */
807 	int dname_num_i = (int)desc->_dname_count; /* decreased at root label */
808 	int dname_num_j = (int)desc->_dname_count;
809 
810 	/* loop while there are rdata bytes available for both rrs,
811 	 * and still some lowercasing needs to be done; either the dnames
812 	 * have not been reached yet, or they are currently being processed */
813 	while(ilen > 0 && jlen > 0 && (dname_num_i > 0 || dname_num_j > 0)) {
814 		/* compare these two bytes */
815 		/* lowercase if in a dname and not a label length byte */
816 		if( ((dname_i && lablen_i)?(uint8_t)tolower((int)*di):*di)
817 		 != ((dname_j && lablen_j)?(uint8_t)tolower((int)*dj):*dj)
818 		 ) {
819 		  if(((dname_i && lablen_i)?(uint8_t)tolower((int)*di):*di)
820 		  < ((dname_j && lablen_j)?(uint8_t)tolower((int)*dj):*dj))
821 		 	return -1;
822 		    return 1;
823 		}
824 		ilen--;
825 		jlen--;
826 		/* bytes are equal */
827 
828 		/* advance field i */
829 		/* lablen 0 means that this byte is the first byte of the
830 		 * next rdata field; inspect this rdata field and setup
831 		 * to process the rest of this rdata field.
832 		 * The reason to first read the byte, then setup the rdf,
833 		 * is that we are then sure the byte is available and short
834 		 * rdata is handled gracefully (even if it is a formerr). */
835 		if(lablen_i == 0) {
836 			if(dname_i) {
837 				/* scan this dname label */
838 				/* capture length to lowercase */
839 				lablen_i = (size_t)*di;
840 				if(lablen_i == 0) {
841 					/* end root label */
842 					dname_i = 0;
843 					dname_num_i--;
844 					/* if dname num is 0, then the
845 					 * remainder is binary only */
846 					if(dname_num_i == 0)
847 						lablen_i = ilen;
848 				}
849 			} else {
850 				/* scan this rdata field */
851 				wfi++;
852 				if(desc->_wireformat[wfi]
853 					== LDNS_RDF_TYPE_DNAME) {
854 					dname_i = 1;
855 					lablen_i = (size_t)*di;
856 					if(lablen_i == 0) {
857 						dname_i = 0;
858 						dname_num_i--;
859 						if(dname_num_i == 0)
860 							lablen_i = ilen;
861 					}
862 				} else if(desc->_wireformat[wfi]
863 					== LDNS_RDF_TYPE_STR)
864 					lablen_i = (size_t)*di;
865 				else	lablen_i = get_rdf_size(
866 					desc->_wireformat[wfi]) - 1;
867 			}
868 		} else	lablen_i--;
869 
870 		/* advance field j; same as for i */
871 		if(lablen_j == 0) {
872 			if(dname_j) {
873 				lablen_j = (size_t)*dj;
874 				if(lablen_j == 0) {
875 					dname_j = 0;
876 					dname_num_j--;
877 					if(dname_num_j == 0)
878 						lablen_j = jlen;
879 				}
880 			} else {
881 				wfj++;
882 				if(desc->_wireformat[wfj]
883 					== LDNS_RDF_TYPE_DNAME) {
884 					dname_j = 1;
885 					lablen_j = (size_t)*dj;
886 					if(lablen_j == 0) {
887 						dname_j = 0;
888 						dname_num_j--;
889 						if(dname_num_j == 0)
890 							lablen_j = jlen;
891 					}
892 				} else if(desc->_wireformat[wfj]
893 					== LDNS_RDF_TYPE_STR)
894 					lablen_j = (size_t)*dj;
895 				else	lablen_j = get_rdf_size(
896 					desc->_wireformat[wfj]) - 1;
897 			}
898 		} else	lablen_j--;
899 		di++;
900 		dj++;
901 	}
902 	/* end of the loop; because we advanced byte by byte; now we have
903 	 * that the rdata has ended, or that there is a binary remainder */
904 	/* shortest first */
905 	if(ilen == 0 && jlen == 0)
906 		return 0;
907 	if(ilen == 0)
908 		return -1;
909 	if(jlen == 0)
910 		return 1;
911 	/* binary remainder, capture comparison in wfi variable */
912 	if((wfi = memcmp(di, dj, (ilen<jlen)?ilen:jlen)) != 0)
913 		return wfi;
914 	if(ilen < jlen)
915 		return -1;
916 	if(jlen < ilen)
917 		return 1;
918 	return 0;
919 }
920 
921 /**
922  * Compare two RRs in the same RRset and determine their relative
923  * canonical order.
924  * @param rrset: the rrset in which to perform compares.
925  * @param i: first RR to compare
926  * @param j: first RR to compare
927  * @return 0 if RR i== RR j, -1 if <, +1 if >.
928  */
929 static int
930 canonical_compare(struct ub_packed_rrset_key* rrset, size_t i, size_t j)
931 {
932 	struct packed_rrset_data* d = (struct packed_rrset_data*)
933 		rrset->entry.data;
934 	const sldns_rr_descriptor* desc;
935 	uint16_t type = ntohs(rrset->rk.type);
936 	size_t minlen;
937 	int c;
938 
939 	if(i==j)
940 		return 0;
941 
942 	switch(type) {
943 		/* These RR types have only a name as RDATA.
944 		 * This name has to be canonicalized.*/
945 		case LDNS_RR_TYPE_NS:
946 		case LDNS_RR_TYPE_MD:
947 		case LDNS_RR_TYPE_MF:
948 		case LDNS_RR_TYPE_CNAME:
949 		case LDNS_RR_TYPE_MB:
950 		case LDNS_RR_TYPE_MG:
951 		case LDNS_RR_TYPE_MR:
952 		case LDNS_RR_TYPE_PTR:
953 		case LDNS_RR_TYPE_DNAME:
954 			/* the wireread function has already checked these
955 			 * dname's for correctness, and this double checks */
956 			if(!dname_valid(d->rr_data[i]+2, d->rr_len[i]-2) ||
957 				!dname_valid(d->rr_data[j]+2, d->rr_len[j]-2))
958 				return 0;
959 			return query_dname_compare(d->rr_data[i]+2,
960 				d->rr_data[j]+2);
961 
962 		/* These RR types have STR and fixed size rdata fields
963 		 * before one or more name fields that need canonicalizing,
964 		 * and after that a byte-for byte remainder can be compared.
965 		 */
966 		/* type starts with the name; remainder is binary compared */
967 		case LDNS_RR_TYPE_NXT:
968 		/* use rdata field formats */
969 		case LDNS_RR_TYPE_MINFO:
970 		case LDNS_RR_TYPE_RP:
971 		case LDNS_RR_TYPE_SOA:
972 		case LDNS_RR_TYPE_RT:
973 		case LDNS_RR_TYPE_AFSDB:
974 		case LDNS_RR_TYPE_KX:
975 		case LDNS_RR_TYPE_MX:
976 		case LDNS_RR_TYPE_SIG:
977 		/* RRSIG signer name has to be downcased */
978 		case LDNS_RR_TYPE_RRSIG:
979 		case LDNS_RR_TYPE_PX:
980 		case LDNS_RR_TYPE_NAPTR:
981 		case LDNS_RR_TYPE_SRV:
982 			desc = sldns_rr_descript(type);
983 			log_assert(desc);
984 			/* this holds for the types that need canonicalizing */
985 			log_assert(desc->_minimum == desc->_maximum);
986 			return canonical_compare_byfield(d, desc, i, j);
987 
988 		case LDNS_RR_TYPE_HINFO: /* no longer downcased */
989 		case LDNS_RR_TYPE_NSEC:
990 	default:
991 		/* For unknown RR types, or types not listed above,
992 		 * no canonicalization is needed, do binary compare */
993 		/* byte for byte compare, equal means shortest first*/
994 		minlen = d->rr_len[i]-2;
995 		if(minlen > d->rr_len[j]-2)
996 			minlen = d->rr_len[j]-2;
997 		c = memcmp(d->rr_data[i]+2, d->rr_data[j]+2, minlen);
998 		if(c!=0)
999 			return c;
1000 		/* rdata equal, shortest is first */
1001 		if(d->rr_len[i] < d->rr_len[j])
1002 			return -1;
1003 		if(d->rr_len[i] > d->rr_len[j])
1004 			return 1;
1005 		/* rdata equal, length equal */
1006 		break;
1007 	}
1008 	return 0;
1009 }
1010 
1011 int
1012 canonical_tree_compare(const void* k1, const void* k2)
1013 {
1014 	struct canon_rr* r1 = (struct canon_rr*)k1;
1015 	struct canon_rr* r2 = (struct canon_rr*)k2;
1016 	log_assert(r1->rrset == r2->rrset);
1017 	return canonical_compare(r1->rrset, r1->rr_idx, r2->rr_idx);
1018 }
1019 
1020 /**
1021  * Sort RRs for rrset in canonical order.
1022  * Does not actually canonicalize the RR rdatas.
1023  * Does not touch rrsigs.
1024  * @param rrset: to sort.
1025  * @param d: rrset data.
1026  * @param sortree: tree to sort into.
1027  * @param rrs: rr storage.
1028  */
1029 static void
1030 canonical_sort(struct ub_packed_rrset_key* rrset, struct packed_rrset_data* d,
1031 	rbtree_type* sortree, struct canon_rr* rrs)
1032 {
1033 	size_t i;
1034 	/* insert into rbtree to sort and detect duplicates */
1035 	for(i=0; i<d->count; i++) {
1036 		rrs[i].node.key = &rrs[i];
1037 		rrs[i].rrset = rrset;
1038 		rrs[i].rr_idx = i;
1039 		if(!rbtree_insert(sortree, &rrs[i].node)) {
1040 			/* this was a duplicate */
1041 		}
1042 	}
1043 }
1044 
1045 /**
1046  * Insert canonical owner name into buffer.
1047  * @param buf: buffer to insert into at current position.
1048  * @param k: rrset with its owner name.
1049  * @param sig: signature with signer name and label count.
1050  * 	must be length checked, at least 18 bytes long.
1051  * @param can_owner: position in buffer returned for future use.
1052  * @param can_owner_len: length of canonical owner name.
1053  */
1054 static void
1055 insert_can_owner(sldns_buffer* buf, struct ub_packed_rrset_key* k,
1056 	uint8_t* sig, uint8_t** can_owner, size_t* can_owner_len)
1057 {
1058 	int rrsig_labels = (int)sig[3];
1059 	int fqdn_labels = dname_signame_label_count(k->rk.dname);
1060 	*can_owner = sldns_buffer_current(buf);
1061 	if(rrsig_labels == fqdn_labels) {
1062 		/* no change */
1063 		sldns_buffer_write(buf, k->rk.dname, k->rk.dname_len);
1064 		query_dname_tolower(*can_owner);
1065 		*can_owner_len = k->rk.dname_len;
1066 		return;
1067 	}
1068 	log_assert(rrsig_labels < fqdn_labels);
1069 	/* *. | fqdn(rightmost rrsig_labels) */
1070 	if(rrsig_labels < fqdn_labels) {
1071 		int i;
1072 		uint8_t* nm = k->rk.dname;
1073 		size_t len = k->rk.dname_len;
1074 		/* so skip fqdn_labels-rrsig_labels */
1075 		for(i=0; i<fqdn_labels-rrsig_labels; i++) {
1076 			dname_remove_label(&nm, &len);
1077 		}
1078 		*can_owner_len = len+2;
1079 		sldns_buffer_write(buf, (uint8_t*)"\001*", 2);
1080 		sldns_buffer_write(buf, nm, len);
1081 		query_dname_tolower(*can_owner);
1082 	}
1083 }
1084 
1085 /**
1086  * Canonicalize Rdata in buffer.
1087  * @param buf: buffer at position just after the rdata.
1088  * @param rrset: rrset with type.
1089  * @param len: length of the rdata (including rdatalen uint16).
1090  */
1091 static void
1092 canonicalize_rdata(sldns_buffer* buf, struct ub_packed_rrset_key* rrset,
1093 	size_t len)
1094 {
1095 	uint8_t* datstart = sldns_buffer_current(buf)-len+2;
1096 	switch(ntohs(rrset->rk.type)) {
1097 		case LDNS_RR_TYPE_NXT:
1098 		case LDNS_RR_TYPE_NS:
1099 		case LDNS_RR_TYPE_MD:
1100 		case LDNS_RR_TYPE_MF:
1101 		case LDNS_RR_TYPE_CNAME:
1102 		case LDNS_RR_TYPE_MB:
1103 		case LDNS_RR_TYPE_MG:
1104 		case LDNS_RR_TYPE_MR:
1105 		case LDNS_RR_TYPE_PTR:
1106 		case LDNS_RR_TYPE_DNAME:
1107 			/* type only has a single argument, the name */
1108 			query_dname_tolower(datstart);
1109 			return;
1110 		case LDNS_RR_TYPE_MINFO:
1111 		case LDNS_RR_TYPE_RP:
1112 		case LDNS_RR_TYPE_SOA:
1113 			/* two names after another */
1114 			query_dname_tolower(datstart);
1115 			query_dname_tolower(datstart +
1116 				dname_valid(datstart, len-2));
1117 			return;
1118 		case LDNS_RR_TYPE_RT:
1119 		case LDNS_RR_TYPE_AFSDB:
1120 		case LDNS_RR_TYPE_KX:
1121 		case LDNS_RR_TYPE_MX:
1122 			/* skip fixed part */
1123 			if(len < 2+2+1) /* rdlen, skiplen, 1byteroot */
1124 				return;
1125 			datstart += 2;
1126 			query_dname_tolower(datstart);
1127 			return;
1128 		case LDNS_RR_TYPE_SIG:
1129 		/* downcase the RRSIG, compat with BIND (kept it from SIG) */
1130 		case LDNS_RR_TYPE_RRSIG:
1131 			/* skip fixed part */
1132 			if(len < 2+18+1)
1133 				return;
1134 			datstart += 18;
1135 			query_dname_tolower(datstart);
1136 			return;
1137 		case LDNS_RR_TYPE_PX:
1138 			/* skip, then two names after another */
1139 			if(len < 2+2+1)
1140 				return;
1141 			datstart += 2;
1142 			query_dname_tolower(datstart);
1143 			query_dname_tolower(datstart +
1144 				dname_valid(datstart, len-2-2));
1145 			return;
1146 		case LDNS_RR_TYPE_NAPTR:
1147 			if(len < 2+4)
1148 				return;
1149 			len -= 2+4;
1150 			datstart += 4;
1151 			if(len < (size_t)datstart[0]+1) /* skip text field */
1152 				return;
1153 			len -= (size_t)datstart[0]+1;
1154 			datstart += (size_t)datstart[0]+1;
1155 			if(len < (size_t)datstart[0]+1) /* skip text field */
1156 				return;
1157 			len -= (size_t)datstart[0]+1;
1158 			datstart += (size_t)datstart[0]+1;
1159 			if(len < (size_t)datstart[0]+1) /* skip text field */
1160 				return;
1161 			len -= (size_t)datstart[0]+1;
1162 			datstart += (size_t)datstart[0]+1;
1163 			if(len < 1)	/* check name is at least 1 byte*/
1164 				return;
1165 			query_dname_tolower(datstart);
1166 			return;
1167 		case LDNS_RR_TYPE_SRV:
1168 			/* skip fixed part */
1169 			if(len < 2+6+1)
1170 				return;
1171 			datstart += 6;
1172 			query_dname_tolower(datstart);
1173 			return;
1174 
1175 		/* do not canonicalize NSEC rdata name, compat with
1176 		 * from bind 9.4 signer, where it does not do so */
1177 		case LDNS_RR_TYPE_NSEC: /* type starts with the name */
1178 		case LDNS_RR_TYPE_HINFO: /* not downcased */
1179 		/* A6 not supported */
1180 		default:
1181 			/* nothing to do for unknown types */
1182 			return;
1183 	}
1184 }
1185 
1186 int rrset_canonical_equal(struct regional* region,
1187 	struct ub_packed_rrset_key* k1, struct ub_packed_rrset_key* k2)
1188 {
1189 	struct rbtree_type sortree1, sortree2;
1190 	struct canon_rr *rrs1, *rrs2, *p1, *p2;
1191 	struct packed_rrset_data* d1=(struct packed_rrset_data*)k1->entry.data;
1192 	struct packed_rrset_data* d2=(struct packed_rrset_data*)k2->entry.data;
1193 	struct ub_packed_rrset_key fk;
1194 	struct packed_rrset_data fd;
1195 	size_t flen[2];
1196 	uint8_t* fdata[2];
1197 
1198 	/* basic compare */
1199 	if(k1->rk.dname_len != k2->rk.dname_len ||
1200 		k1->rk.flags != k2->rk.flags ||
1201 		k1->rk.type != k2->rk.type ||
1202 		k1->rk.rrset_class != k2->rk.rrset_class ||
1203 		query_dname_compare(k1->rk.dname, k2->rk.dname) != 0)
1204 		return 0;
1205 	if(d1->ttl != d2->ttl ||
1206 		d1->count != d2->count ||
1207 		d1->rrsig_count != d2->rrsig_count ||
1208 		d1->trust != d2->trust ||
1209 		d1->security != d2->security)
1210 		return 0;
1211 
1212 	/* init */
1213 	memset(&fk, 0, sizeof(fk));
1214 	memset(&fd, 0, sizeof(fd));
1215 	fk.entry.data = &fd;
1216 	fd.count = 2;
1217 	fd.rr_len = flen;
1218 	fd.rr_data = fdata;
1219 	rbtree_init(&sortree1, &canonical_tree_compare);
1220 	rbtree_init(&sortree2, &canonical_tree_compare);
1221 	if(d1->count > RR_COUNT_MAX || d2->count > RR_COUNT_MAX)
1222 		return 1; /* protection against integer overflow */
1223 	rrs1 = regional_alloc(region, sizeof(struct canon_rr)*d1->count);
1224 	rrs2 = regional_alloc(region, sizeof(struct canon_rr)*d2->count);
1225 	if(!rrs1 || !rrs2) return 1; /* alloc failure */
1226 
1227 	/* sort */
1228 	canonical_sort(k1, d1, &sortree1, rrs1);
1229 	canonical_sort(k2, d2, &sortree2, rrs2);
1230 
1231 	/* compare canonical-sorted RRs for canonical-equality */
1232 	if(sortree1.count != sortree2.count)
1233 		return 0;
1234 	p1 = (struct canon_rr*)rbtree_first(&sortree1);
1235 	p2 = (struct canon_rr*)rbtree_first(&sortree2);
1236 	while(p1 != (struct canon_rr*)RBTREE_NULL &&
1237 		p2 != (struct canon_rr*)RBTREE_NULL) {
1238 		flen[0] = d1->rr_len[p1->rr_idx];
1239 		flen[1] = d2->rr_len[p2->rr_idx];
1240 		fdata[0] = d1->rr_data[p1->rr_idx];
1241 		fdata[1] = d2->rr_data[p2->rr_idx];
1242 
1243 		if(canonical_compare(&fk, 0, 1) != 0)
1244 			return 0;
1245 		p1 = (struct canon_rr*)rbtree_next(&p1->node);
1246 		p2 = (struct canon_rr*)rbtree_next(&p2->node);
1247 	}
1248 	return 1;
1249 }
1250 
1251 /**
1252  * Create canonical form of rrset in the scratch buffer.
1253  * @param region: temporary region.
1254  * @param buf: the buffer to use.
1255  * @param k: the rrset to insert.
1256  * @param sig: RRSIG rdata to include.
1257  * @param siglen: RRSIG rdata len excluding signature field, but inclusive
1258  * 	signer name length.
1259  * @param sortree: if NULL is passed a new sorted rrset tree is built.
1260  * 	Otherwise it is reused.
1261  * @param section: section of packet where this rrset comes from.
1262  * @param qstate: qstate with region.
1263  * @return false on alloc error.
1264  */
1265 static int
1266 rrset_canonical(struct regional* region, sldns_buffer* buf,
1267 	struct ub_packed_rrset_key* k, uint8_t* sig, size_t siglen,
1268 	struct rbtree_type** sortree, sldns_pkt_section section,
1269 	struct module_qstate* qstate)
1270 {
1271 	struct packed_rrset_data* d = (struct packed_rrset_data*)k->entry.data;
1272 	uint8_t* can_owner = NULL;
1273 	size_t can_owner_len = 0;
1274 	struct canon_rr* walk;
1275 	struct canon_rr* rrs;
1276 
1277 	if(!*sortree) {
1278 		*sortree = (struct rbtree_type*)regional_alloc(region,
1279 			sizeof(rbtree_type));
1280 		if(!*sortree)
1281 			return 0;
1282 		if(d->count > RR_COUNT_MAX)
1283 			return 0; /* integer overflow protection */
1284 		rrs = regional_alloc(region, sizeof(struct canon_rr)*d->count);
1285 		if(!rrs) {
1286 			*sortree = NULL;
1287 			return 0;
1288 		}
1289 		rbtree_init(*sortree, &canonical_tree_compare);
1290 		canonical_sort(k, d, *sortree, rrs);
1291 	}
1292 
1293 	sldns_buffer_clear(buf);
1294 	sldns_buffer_write(buf, sig, siglen);
1295 	/* canonicalize signer name */
1296 	query_dname_tolower(sldns_buffer_begin(buf)+18);
1297 	RBTREE_FOR(walk, struct canon_rr*, (*sortree)) {
1298 		/* see if there is enough space left in the buffer */
1299 		if(sldns_buffer_remaining(buf) < can_owner_len + 2 + 2 + 4
1300 			+ d->rr_len[walk->rr_idx]) {
1301 			log_err("verify: failed to canonicalize, "
1302 				"rrset too big");
1303 			return 0;
1304 		}
1305 		/* determine canonical owner name */
1306 		if(can_owner)
1307 			sldns_buffer_write(buf, can_owner, can_owner_len);
1308 		else	insert_can_owner(buf, k, sig, &can_owner,
1309 				&can_owner_len);
1310 		sldns_buffer_write(buf, &k->rk.type, 2);
1311 		sldns_buffer_write(buf, &k->rk.rrset_class, 2);
1312 		sldns_buffer_write(buf, sig+4, 4);
1313 		sldns_buffer_write(buf, d->rr_data[walk->rr_idx],
1314 			d->rr_len[walk->rr_idx]);
1315 		canonicalize_rdata(buf, k, d->rr_len[walk->rr_idx]);
1316 	}
1317 	sldns_buffer_flip(buf);
1318 
1319 	/* Replace RR owner with canonical owner for NSEC records in authority
1320 	 * section, to prevent that a wildcard synthesized NSEC can be used in
1321 	 * the non-existence proves. */
1322 	if(ntohs(k->rk.type) == LDNS_RR_TYPE_NSEC &&
1323 		section == LDNS_SECTION_AUTHORITY && qstate) {
1324 		k->rk.dname = regional_alloc_init(qstate->region, can_owner,
1325 			can_owner_len);
1326 		if(!k->rk.dname)
1327 			return 0;
1328 		k->rk.dname_len = can_owner_len;
1329 	}
1330 
1331 
1332 	return 1;
1333 }
1334 
1335 int
1336 rrset_canonicalize_to_buffer(struct regional* region, sldns_buffer* buf,
1337 	struct ub_packed_rrset_key* k)
1338 {
1339 	struct rbtree_type* sortree = NULL;
1340 	struct packed_rrset_data* d = (struct packed_rrset_data*)k->entry.data;
1341 	uint8_t* can_owner = NULL;
1342 	size_t can_owner_len = 0;
1343 	struct canon_rr* walk;
1344 	struct canon_rr* rrs;
1345 
1346 	sortree = (struct rbtree_type*)regional_alloc(region,
1347 		sizeof(rbtree_type));
1348 	if(!sortree)
1349 		return 0;
1350 	if(d->count > RR_COUNT_MAX)
1351 		return 0; /* integer overflow protection */
1352 	rrs = regional_alloc(region, sizeof(struct canon_rr)*d->count);
1353 	if(!rrs) {
1354 		return 0;
1355 	}
1356 	rbtree_init(sortree, &canonical_tree_compare);
1357 	canonical_sort(k, d, sortree, rrs);
1358 
1359 	sldns_buffer_clear(buf);
1360 	RBTREE_FOR(walk, struct canon_rr*, sortree) {
1361 		/* see if there is enough space left in the buffer */
1362 		if(sldns_buffer_remaining(buf) < can_owner_len + 2 + 2 + 4
1363 			+ d->rr_len[walk->rr_idx]) {
1364 			log_err("verify: failed to canonicalize, "
1365 				"rrset too big");
1366 			return 0;
1367 		}
1368 		/* determine canonical owner name */
1369 		if(can_owner)
1370 			sldns_buffer_write(buf, can_owner, can_owner_len);
1371 		else	{
1372 			can_owner = sldns_buffer_current(buf);
1373 			sldns_buffer_write(buf, k->rk.dname, k->rk.dname_len);
1374 			query_dname_tolower(can_owner);
1375 			can_owner_len = k->rk.dname_len;
1376 		}
1377 		sldns_buffer_write(buf, &k->rk.type, 2);
1378 		sldns_buffer_write(buf, &k->rk.rrset_class, 2);
1379 		sldns_buffer_write_u32(buf, d->rr_ttl[walk->rr_idx]);
1380 		sldns_buffer_write(buf, d->rr_data[walk->rr_idx],
1381 			d->rr_len[walk->rr_idx]);
1382 		canonicalize_rdata(buf, k, d->rr_len[walk->rr_idx]);
1383 	}
1384 	sldns_buffer_flip(buf);
1385 	return 1;
1386 }
1387 
1388 /** pretty print rrsig error with dates */
1389 static void
1390 sigdate_error(const char* str, int32_t expi, int32_t incep, int32_t now)
1391 {
1392 	struct tm tm;
1393 	char expi_buf[16];
1394 	char incep_buf[16];
1395 	char now_buf[16];
1396 	time_t te, ti, tn;
1397 
1398 	if(verbosity < VERB_QUERY)
1399 		return;
1400 	te = (time_t)expi;
1401 	ti = (time_t)incep;
1402 	tn = (time_t)now;
1403 	memset(&tm, 0, sizeof(tm));
1404 	if(gmtime_r(&te, &tm) && strftime(expi_buf, 15, "%Y%m%d%H%M%S", &tm)
1405 	 &&gmtime_r(&ti, &tm) && strftime(incep_buf, 15, "%Y%m%d%H%M%S", &tm)
1406 	 &&gmtime_r(&tn, &tm) && strftime(now_buf, 15, "%Y%m%d%H%M%S", &tm)) {
1407 		log_info("%s expi=%s incep=%s now=%s", str, expi_buf,
1408 			incep_buf, now_buf);
1409 	} else
1410 		log_info("%s expi=%u incep=%u now=%u", str, (unsigned)expi,
1411 			(unsigned)incep, (unsigned)now);
1412 }
1413 
1414 /** check rrsig dates */
1415 static int
1416 check_dates(struct val_env* ve, uint32_t unow, uint8_t* expi_p,
1417 	uint8_t* incep_p, char** reason, sldns_ede_code *reason_bogus)
1418 {
1419 	/* read out the dates */
1420 	uint32_t expi, incep, now;
1421 	memmove(&expi, expi_p, sizeof(expi));
1422 	memmove(&incep, incep_p, sizeof(incep));
1423 	expi = ntohl(expi);
1424 	incep = ntohl(incep);
1425 
1426 	/* get current date */
1427 	if(ve->date_override) {
1428 		if(ve->date_override == -1) {
1429 			verbose(VERB_ALGO, "date override: ignore date");
1430 			return 1;
1431 		}
1432 		now = ve->date_override;
1433 		verbose(VERB_ALGO, "date override option %d", (int)now);
1434 	} else	now = unow;
1435 
1436 	/* check them */
1437 	if(compare_1982(incep, expi) > 0) {
1438 		sigdate_error("verify: inception after expiration, "
1439 			"signature bad", expi, incep, now);
1440 		*reason = "signature inception after expiration";
1441 		if(reason_bogus){
1442 			/* from RFC8914 on Signature Not Yet Valid: The resolver
1443 			 * attempted to perform DNSSEC validation, but no
1444 			 * signatures are presently valid and at least some are
1445 			 * not yet valid. */
1446 			*reason_bogus = LDNS_EDE_SIGNATURE_NOT_YET_VALID;
1447 		}
1448 
1449 		return 0;
1450 	}
1451 	if(compare_1982(incep, now) > 0) {
1452 		/* within skew ? (calc here to avoid calculation normally) */
1453 		uint32_t skew = subtract_1982(incep, expi)/10;
1454 		if(skew < (uint32_t)ve->skew_min) skew = ve->skew_min;
1455 		if(skew > (uint32_t)ve->skew_max) skew = ve->skew_max;
1456 		if(subtract_1982(now, incep) > skew) {
1457 			sigdate_error("verify: signature bad, current time is"
1458 				" before inception date", expi, incep, now);
1459 			*reason = "signature before inception date";
1460 			if(reason_bogus)
1461 				*reason_bogus = LDNS_EDE_SIGNATURE_NOT_YET_VALID;
1462 			return 0;
1463 		}
1464 		sigdate_error("verify warning suspicious signature inception "
1465 			" or bad local clock", expi, incep, now);
1466 	}
1467 	if(compare_1982(now, expi) > 0) {
1468 		uint32_t skew = subtract_1982(incep, expi)/10;
1469 		if(skew < (uint32_t)ve->skew_min) skew = ve->skew_min;
1470 		if(skew > (uint32_t)ve->skew_max) skew = ve->skew_max;
1471 		if(subtract_1982(expi, now) > skew) {
1472 			sigdate_error("verify: signature expired", expi,
1473 				incep, now);
1474 			*reason = "signature expired";
1475 			if(reason_bogus)
1476 				*reason_bogus = LDNS_EDE_SIGNATURE_EXPIRED;
1477 			return 0;
1478 		}
1479 		sigdate_error("verify warning suspicious signature expiration "
1480 			" or bad local clock", expi, incep, now);
1481 	}
1482 	return 1;
1483 }
1484 
1485 /** adjust rrset TTL for verified rrset, compare to original TTL and expi */
1486 static void
1487 adjust_ttl(struct val_env* ve, uint32_t unow,
1488 	struct ub_packed_rrset_key* rrset, uint8_t* orig_p,
1489 	uint8_t* expi_p, uint8_t* incep_p)
1490 {
1491 	struct packed_rrset_data* d =
1492 		(struct packed_rrset_data*)rrset->entry.data;
1493 	/* read out the dates */
1494 	int32_t origttl, expittl, expi, incep, now;
1495 	memmove(&origttl, orig_p, sizeof(origttl));
1496 	memmove(&expi, expi_p, sizeof(expi));
1497 	memmove(&incep, incep_p, sizeof(incep));
1498 	expi = ntohl(expi);
1499 	incep = ntohl(incep);
1500 	origttl = ntohl(origttl);
1501 
1502 	/* get current date */
1503 	if(ve->date_override) {
1504 		now = ve->date_override;
1505 	} else	now = (int32_t)unow;
1506 	expittl = (int32_t)((uint32_t)expi - (uint32_t)now);
1507 
1508 	/* so now:
1509 	 * d->ttl: rrset ttl read from message or cache. May be reduced
1510 	 * origttl: original TTL from signature, authoritative TTL max.
1511 	 * MIN_TTL: minimum TTL from config.
1512 	 * expittl: TTL until the signature expires.
1513 	 *
1514 	 * Use the smallest of these, but don't let origttl set the TTL
1515 	 * below the minimum.
1516 	 */
1517 	if(MIN_TTL > (time_t)origttl && d->ttl > MIN_TTL) {
1518 		verbose(VERB_QUERY, "rrset TTL larger than original and minimum"
1519 			" TTL, adjusting TTL downwards to minimum ttl");
1520 		d->ttl = MIN_TTL;
1521 	}
1522 	else if(MIN_TTL <= origttl && d->ttl > (time_t)origttl) {
1523 		verbose(VERB_QUERY, "rrset TTL larger than original TTL, "
1524 		"adjusting TTL downwards to original ttl");
1525 		d->ttl = origttl;
1526 	}
1527 
1528 	if(expittl > 0 && d->ttl > (time_t)expittl) {
1529 		verbose(VERB_ALGO, "rrset TTL larger than sig expiration ttl,"
1530 			" adjusting TTL downwards");
1531 		d->ttl = expittl;
1532 	}
1533 }
1534 
1535 enum sec_status
1536 dnskey_verify_rrset_sig(struct regional* region, sldns_buffer* buf,
1537 	struct val_env* ve, time_t now,
1538         struct ub_packed_rrset_key* rrset, struct ub_packed_rrset_key* dnskey,
1539         size_t dnskey_idx, size_t sig_idx,
1540 	struct rbtree_type** sortree, int* buf_canon,
1541 	char** reason, sldns_ede_code *reason_bogus,
1542 	sldns_pkt_section section, struct module_qstate* qstate)
1543 {
1544 	enum sec_status sec;
1545 	uint8_t* sig;		/* RRSIG rdata */
1546 	size_t siglen;
1547 	size_t rrnum = rrset_get_count(rrset);
1548 	uint8_t* signer;	/* rrsig signer name */
1549 	size_t signer_len;
1550 	unsigned char* sigblock; /* signature rdata field */
1551 	unsigned int sigblock_len;
1552 	uint16_t ktag;		/* DNSKEY key tag */
1553 	unsigned char* key;	/* public key rdata field */
1554 	unsigned int keylen;
1555 	rrset_get_rdata(rrset, rrnum + sig_idx, &sig, &siglen);
1556 	/* min length of rdatalen, fixed rrsig, root signer, 1 byte sig */
1557 	if(siglen < 2+20) {
1558 		verbose(VERB_QUERY, "verify: signature too short");
1559 		*reason = "signature too short";
1560 		if(reason_bogus)
1561 			*reason_bogus = LDNS_EDE_DNSSEC_BOGUS;
1562 		return sec_status_bogus;
1563 	}
1564 
1565 	if(!(dnskey_get_flags(dnskey, dnskey_idx) & DNSKEY_BIT_ZSK)) {
1566 		verbose(VERB_QUERY, "verify: dnskey without ZSK flag");
1567 		*reason = "dnskey without ZSK flag";
1568 		if(reason_bogus)
1569 			*reason_bogus = LDNS_EDE_NO_ZONE_KEY_BIT_SET;
1570 		return sec_status_bogus;
1571 	}
1572 
1573 	if(dnskey_get_protocol(dnskey, dnskey_idx) != LDNS_DNSSEC_KEYPROTO) {
1574 		/* RFC 4034 says DNSKEY PROTOCOL MUST be 3 */
1575 		verbose(VERB_QUERY, "verify: dnskey has wrong key protocol");
1576 		*reason = "dnskey has wrong protocolnumber";
1577 		if(reason_bogus)
1578 			*reason_bogus = LDNS_EDE_DNSSEC_BOGUS;
1579 		return sec_status_bogus;
1580 	}
1581 
1582 	/* verify as many fields in rrsig as possible */
1583 	signer = sig+2+18;
1584 	signer_len = dname_valid(signer, siglen-2-18);
1585 	if(!signer_len) {
1586 		verbose(VERB_QUERY, "verify: malformed signer name");
1587 		*reason = "signer name malformed";
1588 		if(reason_bogus)
1589 			*reason_bogus = LDNS_EDE_DNSSEC_BOGUS;
1590 		return sec_status_bogus; /* signer name invalid */
1591 	}
1592 	if(!dname_subdomain_c(rrset->rk.dname, signer)) {
1593 		verbose(VERB_QUERY, "verify: signer name is off-tree");
1594 		*reason = "signer name off-tree";
1595 		if(reason_bogus)
1596 			*reason_bogus = LDNS_EDE_DNSSEC_BOGUS;
1597 		return sec_status_bogus; /* signer name offtree */
1598 	}
1599 	sigblock = (unsigned char*)signer+signer_len;
1600 	if(siglen < 2+18+signer_len+1) {
1601 		verbose(VERB_QUERY, "verify: too short, no signature data");
1602 		*reason = "signature too short, no signature data";
1603 		if(reason_bogus)
1604 			*reason_bogus = LDNS_EDE_DNSSEC_BOGUS;
1605 		return sec_status_bogus; /* sig rdf is < 1 byte */
1606 	}
1607 	sigblock_len = (unsigned int)(siglen - 2 - 18 - signer_len);
1608 
1609 	/* verify key dname == sig signer name */
1610 	if(query_dname_compare(signer, dnskey->rk.dname) != 0) {
1611 		verbose(VERB_QUERY, "verify: wrong key for rrsig");
1612 		log_nametypeclass(VERB_QUERY, "RRSIG signername is",
1613 			signer, 0, 0);
1614 		log_nametypeclass(VERB_QUERY, "the key name is",
1615 			dnskey->rk.dname, 0, 0);
1616 		*reason = "signer name mismatches key name";
1617 		if(reason_bogus)
1618 			*reason_bogus = LDNS_EDE_DNSSEC_BOGUS;
1619 		return sec_status_bogus;
1620 	}
1621 
1622 	/* verify covered type */
1623 	/* memcmp works because type is in network format for rrset */
1624 	if(memcmp(sig+2, &rrset->rk.type, 2) != 0) {
1625 		verbose(VERB_QUERY, "verify: wrong type covered");
1626 		*reason = "signature covers wrong type";
1627 		if(reason_bogus)
1628 			*reason_bogus = LDNS_EDE_DNSSEC_BOGUS;
1629 		return sec_status_bogus;
1630 	}
1631 	/* verify keytag and sig algo (possibly again) */
1632 	if((int)sig[2+2] != dnskey_get_algo(dnskey, dnskey_idx)) {
1633 		verbose(VERB_QUERY, "verify: wrong algorithm");
1634 		*reason = "signature has wrong algorithm";
1635 		if(reason_bogus)
1636 			*reason_bogus = LDNS_EDE_DNSSEC_BOGUS;
1637 		return sec_status_bogus;
1638 	}
1639 	ktag = htons(dnskey_calc_keytag(dnskey, dnskey_idx));
1640 	if(memcmp(sig+2+16, &ktag, 2) != 0) {
1641 		verbose(VERB_QUERY, "verify: wrong keytag");
1642 		*reason = "signature has wrong keytag";
1643 		if(reason_bogus)
1644 			*reason_bogus = LDNS_EDE_DNSSEC_BOGUS;
1645 		return sec_status_bogus;
1646 	}
1647 
1648 	/* verify labels is in a valid range */
1649 	if((int)sig[2+3] > dname_signame_label_count(rrset->rk.dname)) {
1650 		verbose(VERB_QUERY, "verify: labelcount out of range");
1651 		*reason = "signature labelcount out of range";
1652 		if(reason_bogus)
1653 			*reason_bogus = LDNS_EDE_DNSSEC_BOGUS;
1654 		return sec_status_bogus;
1655 	}
1656 
1657 	/* original ttl, always ok */
1658 
1659 	if(!*buf_canon) {
1660 		/* create rrset canonical format in buffer, ready for
1661 		 * signature */
1662 		if(!rrset_canonical(region, buf, rrset, sig+2,
1663 			18 + signer_len, sortree, section, qstate)) {
1664 			log_err("verify: failed due to alloc error");
1665 			return sec_status_unchecked;
1666 		}
1667 		*buf_canon = 1;
1668 	}
1669 
1670 	/* check that dnskey is available */
1671 	dnskey_get_pubkey(dnskey, dnskey_idx, &key, &keylen);
1672 	if(!key) {
1673 		verbose(VERB_QUERY, "verify: short DNSKEY RR");
1674 		return sec_status_unchecked;
1675 	}
1676 
1677 	/* verify */
1678 	sec = verify_canonrrset(buf, (int)sig[2+2],
1679 		sigblock, sigblock_len, key, keylen, reason);
1680 
1681 	if(sec == sec_status_secure) {
1682 		/* check if TTL is too high - reduce if so */
1683 		adjust_ttl(ve, now, rrset, sig+2+4, sig+2+8, sig+2+12);
1684 
1685 		/* verify inception, expiration dates
1686 		 * Do this last so that if you ignore expired-sigs the
1687 		 * rest is sure to be OK. */
1688 		if(!check_dates(ve, now, sig+2+8, sig+2+12,
1689 			reason, reason_bogus)) {
1690 			return sec_status_bogus;
1691 		}
1692 	}
1693 
1694 	return sec;
1695 }
1696