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