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
rrset_get_count(struct ub_packed_rrset_key * rrset)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
rrset_get_sigcount(struct ub_packed_rrset_key * k)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
rrset_get_sig_keytag(struct ub_packed_rrset_key * k,size_t sig_idx)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
rrset_get_sig_algo(struct ub_packed_rrset_key * k,size_t sig_idx)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
rrset_get_rdata(struct ub_packed_rrset_key * k,size_t idx,uint8_t ** rdata,size_t * len)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
dnskey_get_flags(struct ub_packed_rrset_key * k,size_t idx)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
dnskey_get_protocol(struct ub_packed_rrset_key * k,size_t idx)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
dnskey_get_algo(struct ub_packed_rrset_key * k,size_t idx)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
dnskey_get_pubkey(struct ub_packed_rrset_key * k,size_t idx,unsigned char ** pk,unsigned int * pklen)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
ds_get_key_algo(struct ub_packed_rrset_key * k,size_t idx)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
ds_get_digest_algo(struct ub_packed_rrset_key * k,size_t idx)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
ds_get_keytag(struct ub_packed_rrset_key * ds_rrset,size_t ds_idx)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
ds_get_sigdata(struct ub_packed_rrset_key * k,size_t idx,uint8_t ** digest,size_t * len)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
ds_digest_size_algo(struct ub_packed_rrset_key * k,size_t idx)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
ds_create_dnskey_digest(struct module_env * env,struct ub_packed_rrset_key * dnskey_rrset,size_t dnskey_idx,struct ub_packed_rrset_key * ds_rrset,size_t ds_idx,uint8_t * digest)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 
ds_digest_match_dnskey(struct module_env * env,struct ub_packed_rrset_key * dnskey_rrset,size_t dnskey_idx,struct ub_packed_rrset_key * ds_rrset,size_t ds_idx)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
ds_digest_algo_is_supported(struct ub_packed_rrset_key * ds_rrset,size_t ds_idx)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
ds_key_algo_is_supported(struct ub_packed_rrset_key * ds_rrset,size_t ds_idx)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
dnskey_calc_keytag(struct ub_packed_rrset_key * dnskey_rrset,size_t dnskey_idx)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 
dnskey_algo_is_supported(struct ub_packed_rrset_key * dnskey_rrset,size_t dnskey_idx)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 
dnskey_size_is_supported(struct ub_packed_rrset_key * dnskey_rrset,size_t dnskey_idx)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 
dnskeyset_size_is_supported(struct ub_packed_rrset_key * dnskey_rrset)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 
algo_needs_init_dnskey_add(struct algo_needs * n,struct ub_packed_rrset_key * dnskey,uint8_t * sigalg)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 
algo_needs_init_list(struct algo_needs * n,uint8_t * sigalg)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 
algo_needs_init_ds(struct algo_needs * n,struct ub_packed_rrset_key * ds,int fav_ds_algo,uint8_t * sigalg)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 
algo_needs_set_secure(struct algo_needs * n,uint8_t algo)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 
algo_needs_set_bogus(struct algo_needs * n,uint8_t algo)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 
algo_needs_num_missing(struct algo_needs * n)509 size_t algo_needs_num_missing(struct algo_needs* n)
510 {
511 	return n->num;
512 }
513 
algo_needs_missing(struct algo_needs * n)514 int algo_needs_missing(struct algo_needs* n)
515 {
516 	int i;
517 	/* first check if a needed algo was bogus - report that */
518 	for(i=0; i<ALGO_NEEDS_MAX; i++)
519 		if(n->needs[i] == 2)
520 			return 0;
521 	/* now check which algo is missing */
522 	for(i=0; i<ALGO_NEEDS_MAX; i++)
523 		if(n->needs[i] == 1)
524 			return i;
525 	return 0;
526 }
527 
528 enum sec_status
dnskeyset_verify_rrset(struct module_env * env,struct val_env * ve,struct ub_packed_rrset_key * rrset,struct ub_packed_rrset_key * dnskey,uint8_t * sigalg,char ** reason,sldns_pkt_section section,struct module_qstate * qstate)529 dnskeyset_verify_rrset(struct module_env* env, struct val_env* ve,
530 	struct ub_packed_rrset_key* rrset, struct ub_packed_rrset_key* dnskey,
531 	uint8_t* sigalg, char** reason, sldns_pkt_section section,
532 	struct module_qstate* qstate)
533 {
534 	enum sec_status sec;
535 	size_t i, num;
536 	rbtree_type* sortree = NULL;
537 	/* make sure that for all DNSKEY algorithms there are valid sigs */
538 	struct algo_needs needs;
539 	int alg;
540 
541 	num = rrset_get_sigcount(rrset);
542 	if(num == 0) {
543 		verbose(VERB_QUERY, "rrset failed to verify due to a lack of "
544 			"signatures");
545 		*reason = "no signatures";
546 		return sec_status_bogus;
547 	}
548 
549 	if(sigalg) {
550 		algo_needs_init_list(&needs, sigalg);
551 		if(algo_needs_num_missing(&needs) == 0) {
552 			verbose(VERB_QUERY, "zone has no known algorithms");
553 			*reason = "zone has no known algorithms";
554 			return sec_status_insecure;
555 		}
556 	}
557 	for(i=0; i<num; i++) {
558 		sec = dnskeyset_verify_rrset_sig(env, ve, *env->now, rrset,
559 			dnskey, i, &sortree, reason, section, qstate);
560 		/* see which algorithm has been fixed up */
561 		if(sec == sec_status_secure) {
562 			if(!sigalg)
563 				return sec; /* done! */
564 			else if(algo_needs_set_secure(&needs,
565 				(uint8_t)rrset_get_sig_algo(rrset, i)))
566 				return sec; /* done! */
567 		} else if(sigalg && sec == sec_status_bogus) {
568 			algo_needs_set_bogus(&needs,
569 				(uint8_t)rrset_get_sig_algo(rrset, i));
570 		}
571 	}
572 	if(sigalg && (alg=algo_needs_missing(&needs)) != 0) {
573 		verbose(VERB_ALGO, "rrset failed to verify: "
574 			"no valid signatures for %d algorithms",
575 			(int)algo_needs_num_missing(&needs));
576 		algo_needs_reason(env, alg, reason, "no signatures");
577 	} else {
578 		verbose(VERB_ALGO, "rrset failed to verify: "
579 			"no valid signatures");
580 	}
581 	return sec_status_bogus;
582 }
583 
algo_needs_reason(struct module_env * env,int alg,char ** reason,char * s)584 void algo_needs_reason(struct module_env* env, int alg, char** reason, char* s)
585 {
586 	char buf[256];
587 	sldns_lookup_table *t = sldns_lookup_by_id(sldns_algorithms, alg);
588 	if(t&&t->name)
589 		snprintf(buf, sizeof(buf), "%s with algorithm %s", s, t->name);
590 	else	snprintf(buf, sizeof(buf), "%s with algorithm ALG%u", s,
591 			(unsigned)alg);
592 	*reason = regional_strdup(env->scratch, buf);
593 	if(!*reason)
594 		*reason = s;
595 }
596 
597 enum sec_status
dnskey_verify_rrset(struct module_env * env,struct val_env * ve,struct ub_packed_rrset_key * rrset,struct ub_packed_rrset_key * dnskey,size_t dnskey_idx,char ** reason,sldns_pkt_section section,struct module_qstate * qstate)598 dnskey_verify_rrset(struct module_env* env, struct val_env* ve,
599         struct ub_packed_rrset_key* rrset, struct ub_packed_rrset_key* dnskey,
600 	size_t dnskey_idx, char** reason, sldns_pkt_section section,
601 	struct module_qstate* qstate)
602 {
603 	enum sec_status sec;
604 	size_t i, num, numchecked = 0;
605 	rbtree_type* sortree = NULL;
606 	int buf_canon = 0;
607 	uint16_t tag = dnskey_calc_keytag(dnskey, dnskey_idx);
608 	int algo = dnskey_get_algo(dnskey, dnskey_idx);
609 
610 	num = rrset_get_sigcount(rrset);
611 	if(num == 0) {
612 		verbose(VERB_QUERY, "rrset failed to verify due to a lack of "
613 			"signatures");
614 		*reason = "no signatures";
615 		return sec_status_bogus;
616 	}
617 	for(i=0; i<num; i++) {
618 		/* see if sig matches keytag and algo */
619 		if(algo != rrset_get_sig_algo(rrset, i) ||
620 			tag != rrset_get_sig_keytag(rrset, i))
621 			continue;
622 		buf_canon = 0;
623 		sec = dnskey_verify_rrset_sig(env->scratch,
624 			env->scratch_buffer, ve, *env->now, rrset,
625 			dnskey, dnskey_idx, i, &sortree, &buf_canon, reason,
626 			section, qstate);
627 		if(sec == sec_status_secure)
628 			return sec;
629 		numchecked ++;
630 	}
631 	verbose(VERB_ALGO, "rrset failed to verify: all signatures are bogus");
632 	if(!numchecked) *reason = "signature missing";
633 	return sec_status_bogus;
634 }
635 
636 enum sec_status
dnskeyset_verify_rrset_sig(struct module_env * env,struct val_env * ve,time_t now,struct ub_packed_rrset_key * rrset,struct ub_packed_rrset_key * dnskey,size_t sig_idx,struct rbtree_type ** sortree,char ** reason,sldns_pkt_section section,struct module_qstate * qstate)637 dnskeyset_verify_rrset_sig(struct module_env* env, struct val_env* ve,
638 	time_t now, struct ub_packed_rrset_key* rrset,
639 	struct ub_packed_rrset_key* dnskey, size_t sig_idx,
640 	struct rbtree_type** sortree, char** reason, sldns_pkt_section section,
641 	struct module_qstate* qstate)
642 {
643 	/* find matching keys and check them */
644 	enum sec_status sec = sec_status_bogus;
645 	uint16_t tag = rrset_get_sig_keytag(rrset, sig_idx);
646 	int algo = rrset_get_sig_algo(rrset, sig_idx);
647 	size_t i, num = rrset_get_count(dnskey);
648 	size_t numchecked = 0;
649 	int buf_canon = 0;
650 	verbose(VERB_ALGO, "verify sig %d %d", (int)tag, algo);
651 	if(!dnskey_algo_id_is_supported(algo)) {
652 		verbose(VERB_QUERY, "verify sig: unknown algorithm");
653 		return sec_status_insecure;
654 	}
655 
656 	for(i=0; i<num; i++) {
657 		/* see if key matches keytag and algo */
658 		if(algo != dnskey_get_algo(dnskey, i) ||
659 			tag != dnskey_calc_keytag(dnskey, i))
660 			continue;
661 		numchecked ++;
662 
663 		/* see if key verifies */
664 		sec = dnskey_verify_rrset_sig(env->scratch,
665 			env->scratch_buffer, ve, now, rrset, dnskey, i,
666 			sig_idx, sortree, &buf_canon, reason, section, qstate);
667 		if(sec == sec_status_secure)
668 			return sec;
669 	}
670 	if(numchecked == 0) {
671 		*reason = "signatures from unknown keys";
672 		verbose(VERB_QUERY, "verify: could not find appropriate key");
673 		return sec_status_bogus;
674 	}
675 	return sec_status_bogus;
676 }
677 
678 /**
679  * RR entries in a canonical sorted tree of RRs
680  */
681 struct canon_rr {
682 	/** rbtree node, key is this structure */
683 	rbnode_type node;
684 	/** rrset the RR is in */
685 	struct ub_packed_rrset_key* rrset;
686 	/** which RR in the rrset */
687 	size_t rr_idx;
688 };
689 
690 /**
691  * Compare two RR for canonical order, in a field-style sweep.
692  * @param d: rrset data
693  * @param desc: ldns wireformat descriptor.
694  * @param i: first RR to compare
695  * @param j: first RR to compare
696  * @return comparison code.
697  */
698 static int
canonical_compare_byfield(struct packed_rrset_data * d,const sldns_rr_descriptor * desc,size_t i,size_t j)699 canonical_compare_byfield(struct packed_rrset_data* d,
700 	const sldns_rr_descriptor* desc, size_t i, size_t j)
701 {
702 	/* sweep across rdata, keep track of some state:
703 	 * 	which rr field, and bytes left in field.
704 	 * 	current position in rdata, length left.
705 	 * 	are we in a dname, length left in a label.
706 	 */
707 	int wfi = -1;	/* current wireformat rdata field (rdf) */
708 	int wfj = -1;
709 	uint8_t* di = d->rr_data[i]+2; /* ptr to current rdata byte */
710 	uint8_t* dj = d->rr_data[j]+2;
711 	size_t ilen = d->rr_len[i]-2; /* length left in rdata */
712 	size_t jlen = d->rr_len[j]-2;
713 	int dname_i = 0;  /* true if these bytes are part of a name */
714 	int dname_j = 0;
715 	size_t lablen_i = 0; /* 0 for label length byte,for first byte of rdf*/
716 	size_t lablen_j = 0; /* otherwise remaining length of rdf or label */
717 	int dname_num_i = (int)desc->_dname_count; /* decreased at root label */
718 	int dname_num_j = (int)desc->_dname_count;
719 
720 	/* loop while there are rdata bytes available for both rrs,
721 	 * and still some lowercasing needs to be done; either the dnames
722 	 * have not been reached yet, or they are currently being processed */
723 	while(ilen > 0 && jlen > 0 && (dname_num_i > 0 || dname_num_j > 0)) {
724 		/* compare these two bytes */
725 		/* lowercase if in a dname and not a label length byte */
726 		if( ((dname_i && lablen_i)?(uint8_t)tolower((int)*di):*di)
727 		 != ((dname_j && lablen_j)?(uint8_t)tolower((int)*dj):*dj)
728 		 ) {
729 		  if(((dname_i && lablen_i)?(uint8_t)tolower((int)*di):*di)
730 		  < ((dname_j && lablen_j)?(uint8_t)tolower((int)*dj):*dj))
731 		 	return -1;
732 		    return 1;
733 		}
734 		ilen--;
735 		jlen--;
736 		/* bytes are equal */
737 
738 		/* advance field i */
739 		/* lablen 0 means that this byte is the first byte of the
740 		 * next rdata field; inspect this rdata field and setup
741 		 * to process the rest of this rdata field.
742 		 * The reason to first read the byte, then setup the rdf,
743 		 * is that we are then sure the byte is available and short
744 		 * rdata is handled gracefully (even if it is a formerr). */
745 		if(lablen_i == 0) {
746 			if(dname_i) {
747 				/* scan this dname label */
748 				/* capture length to lowercase */
749 				lablen_i = (size_t)*di;
750 				if(lablen_i == 0) {
751 					/* end root label */
752 					dname_i = 0;
753 					dname_num_i--;
754 					/* if dname num is 0, then the
755 					 * remainder is binary only */
756 					if(dname_num_i == 0)
757 						lablen_i = ilen;
758 				}
759 			} else {
760 				/* scan this rdata field */
761 				wfi++;
762 				if(desc->_wireformat[wfi]
763 					== LDNS_RDF_TYPE_DNAME) {
764 					dname_i = 1;
765 					lablen_i = (size_t)*di;
766 					if(lablen_i == 0) {
767 						dname_i = 0;
768 						dname_num_i--;
769 						if(dname_num_i == 0)
770 							lablen_i = ilen;
771 					}
772 				} else if(desc->_wireformat[wfi]
773 					== LDNS_RDF_TYPE_STR)
774 					lablen_i = (size_t)*di;
775 				else	lablen_i = get_rdf_size(
776 					desc->_wireformat[wfi]) - 1;
777 			}
778 		} else	lablen_i--;
779 
780 		/* advance field j; same as for i */
781 		if(lablen_j == 0) {
782 			if(dname_j) {
783 				lablen_j = (size_t)*dj;
784 				if(lablen_j == 0) {
785 					dname_j = 0;
786 					dname_num_j--;
787 					if(dname_num_j == 0)
788 						lablen_j = jlen;
789 				}
790 			} else {
791 				wfj++;
792 				if(desc->_wireformat[wfj]
793 					== LDNS_RDF_TYPE_DNAME) {
794 					dname_j = 1;
795 					lablen_j = (size_t)*dj;
796 					if(lablen_j == 0) {
797 						dname_j = 0;
798 						dname_num_j--;
799 						if(dname_num_j == 0)
800 							lablen_j = jlen;
801 					}
802 				} else if(desc->_wireformat[wfj]
803 					== LDNS_RDF_TYPE_STR)
804 					lablen_j = (size_t)*dj;
805 				else	lablen_j = get_rdf_size(
806 					desc->_wireformat[wfj]) - 1;
807 			}
808 		} else	lablen_j--;
809 		di++;
810 		dj++;
811 	}
812 	/* end of the loop; because we advanced byte by byte; now we have
813 	 * that the rdata has ended, or that there is a binary remainder */
814 	/* shortest first */
815 	if(ilen == 0 && jlen == 0)
816 		return 0;
817 	if(ilen == 0)
818 		return -1;
819 	if(jlen == 0)
820 		return 1;
821 	/* binary remainder, capture comparison in wfi variable */
822 	if((wfi = memcmp(di, dj, (ilen<jlen)?ilen:jlen)) != 0)
823 		return wfi;
824 	if(ilen < jlen)
825 		return -1;
826 	if(jlen < ilen)
827 		return 1;
828 	return 0;
829 }
830 
831 /**
832  * Compare two RRs in the same RRset and determine their relative
833  * canonical order.
834  * @param rrset: the rrset in which to perform compares.
835  * @param i: first RR to compare
836  * @param j: first RR to compare
837  * @return 0 if RR i== RR j, -1 if <, +1 if >.
838  */
839 static int
canonical_compare(struct ub_packed_rrset_key * rrset,size_t i,size_t j)840 canonical_compare(struct ub_packed_rrset_key* rrset, size_t i, size_t j)
841 {
842 	struct packed_rrset_data* d = (struct packed_rrset_data*)
843 		rrset->entry.data;
844 	const sldns_rr_descriptor* desc;
845 	uint16_t type = ntohs(rrset->rk.type);
846 	size_t minlen;
847 	int c;
848 
849 	if(i==j)
850 		return 0;
851 
852 	switch(type) {
853 		/* These RR types have only a name as RDATA.
854 		 * This name has to be canonicalized.*/
855 		case LDNS_RR_TYPE_NS:
856 		case LDNS_RR_TYPE_MD:
857 		case LDNS_RR_TYPE_MF:
858 		case LDNS_RR_TYPE_CNAME:
859 		case LDNS_RR_TYPE_MB:
860 		case LDNS_RR_TYPE_MG:
861 		case LDNS_RR_TYPE_MR:
862 		case LDNS_RR_TYPE_PTR:
863 		case LDNS_RR_TYPE_DNAME:
864 			/* the wireread function has already checked these
865 			 * dname's for correctness, and this double checks */
866 			if(!dname_valid(d->rr_data[i]+2, d->rr_len[i]-2) ||
867 				!dname_valid(d->rr_data[j]+2, d->rr_len[j]-2))
868 				return 0;
869 			return query_dname_compare(d->rr_data[i]+2,
870 				d->rr_data[j]+2);
871 
872 		/* These RR types have STR and fixed size rdata fields
873 		 * before one or more name fields that need canonicalizing,
874 		 * and after that a byte-for byte remainder can be compared.
875 		 */
876 		/* type starts with the name; remainder is binary compared */
877 		case LDNS_RR_TYPE_NXT:
878 		/* use rdata field formats */
879 		case LDNS_RR_TYPE_MINFO:
880 		case LDNS_RR_TYPE_RP:
881 		case LDNS_RR_TYPE_SOA:
882 		case LDNS_RR_TYPE_RT:
883 		case LDNS_RR_TYPE_AFSDB:
884 		case LDNS_RR_TYPE_KX:
885 		case LDNS_RR_TYPE_MX:
886 		case LDNS_RR_TYPE_SIG:
887 		/* RRSIG signer name has to be downcased */
888 		case LDNS_RR_TYPE_RRSIG:
889 		case LDNS_RR_TYPE_PX:
890 		case LDNS_RR_TYPE_NAPTR:
891 		case LDNS_RR_TYPE_SRV:
892 			desc = sldns_rr_descript(type);
893 			log_assert(desc);
894 			/* this holds for the types that need canonicalizing */
895 			log_assert(desc->_minimum == desc->_maximum);
896 			return canonical_compare_byfield(d, desc, i, j);
897 
898 		case LDNS_RR_TYPE_HINFO: /* no longer downcased */
899 		case LDNS_RR_TYPE_NSEC:
900 	default:
901 		/* For unknown RR types, or types not listed above,
902 		 * no canonicalization is needed, do binary compare */
903 		/* byte for byte compare, equal means shortest first*/
904 		minlen = d->rr_len[i]-2;
905 		if(minlen > d->rr_len[j]-2)
906 			minlen = d->rr_len[j]-2;
907 		c = memcmp(d->rr_data[i]+2, d->rr_data[j]+2, minlen);
908 		if(c!=0)
909 			return c;
910 		/* rdata equal, shortest is first */
911 		if(d->rr_len[i] < d->rr_len[j])
912 			return -1;
913 		if(d->rr_len[i] > d->rr_len[j])
914 			return 1;
915 		/* rdata equal, length equal */
916 		break;
917 	}
918 	return 0;
919 }
920 
921 int
canonical_tree_compare(const void * k1,const void * k2)922 canonical_tree_compare(const void* k1, const void* k2)
923 {
924 	struct canon_rr* r1 = (struct canon_rr*)k1;
925 	struct canon_rr* r2 = (struct canon_rr*)k2;
926 	log_assert(r1->rrset == r2->rrset);
927 	return canonical_compare(r1->rrset, r1->rr_idx, r2->rr_idx);
928 }
929 
930 /**
931  * Sort RRs for rrset in canonical order.
932  * Does not actually canonicalize the RR rdatas.
933  * Does not touch rrsigs.
934  * @param rrset: to sort.
935  * @param d: rrset data.
936  * @param sortree: tree to sort into.
937  * @param rrs: rr storage.
938  */
939 static void
canonical_sort(struct ub_packed_rrset_key * rrset,struct packed_rrset_data * d,rbtree_type * sortree,struct canon_rr * rrs)940 canonical_sort(struct ub_packed_rrset_key* rrset, struct packed_rrset_data* d,
941 	rbtree_type* sortree, struct canon_rr* rrs)
942 {
943 	size_t i;
944 	/* insert into rbtree to sort and detect duplicates */
945 	for(i=0; i<d->count; i++) {
946 		rrs[i].node.key = &rrs[i];
947 		rrs[i].rrset = rrset;
948 		rrs[i].rr_idx = i;
949 		if(!rbtree_insert(sortree, &rrs[i].node)) {
950 			/* this was a duplicate */
951 		}
952 	}
953 }
954 
955 /**
956  * Insert canonical owner name into buffer.
957  * @param buf: buffer to insert into at current position.
958  * @param k: rrset with its owner name.
959  * @param sig: signature with signer name and label count.
960  * 	must be length checked, at least 18 bytes long.
961  * @param can_owner: position in buffer returned for future use.
962  * @param can_owner_len: length of canonical owner name.
963  */
964 static void
insert_can_owner(sldns_buffer * buf,struct ub_packed_rrset_key * k,uint8_t * sig,uint8_t ** can_owner,size_t * can_owner_len)965 insert_can_owner(sldns_buffer* buf, struct ub_packed_rrset_key* k,
966 	uint8_t* sig, uint8_t** can_owner, size_t* can_owner_len)
967 {
968 	int rrsig_labels = (int)sig[3];
969 	int fqdn_labels = dname_signame_label_count(k->rk.dname);
970 	*can_owner = sldns_buffer_current(buf);
971 	if(rrsig_labels == fqdn_labels) {
972 		/* no change */
973 		sldns_buffer_write(buf, k->rk.dname, k->rk.dname_len);
974 		query_dname_tolower(*can_owner);
975 		*can_owner_len = k->rk.dname_len;
976 		return;
977 	}
978 	log_assert(rrsig_labels < fqdn_labels);
979 	/* *. | fqdn(rightmost rrsig_labels) */
980 	if(rrsig_labels < fqdn_labels) {
981 		int i;
982 		uint8_t* nm = k->rk.dname;
983 		size_t len = k->rk.dname_len;
984 		/* so skip fqdn_labels-rrsig_labels */
985 		for(i=0; i<fqdn_labels-rrsig_labels; i++) {
986 			dname_remove_label(&nm, &len);
987 		}
988 		*can_owner_len = len+2;
989 		sldns_buffer_write(buf, (uint8_t*)"\001*", 2);
990 		sldns_buffer_write(buf, nm, len);
991 		query_dname_tolower(*can_owner);
992 	}
993 }
994 
995 /**
996  * Canonicalize Rdata in buffer.
997  * @param buf: buffer at position just after the rdata.
998  * @param rrset: rrset with type.
999  * @param len: length of the rdata (including rdatalen uint16).
1000  */
1001 static void
canonicalize_rdata(sldns_buffer * buf,struct ub_packed_rrset_key * rrset,size_t len)1002 canonicalize_rdata(sldns_buffer* buf, struct ub_packed_rrset_key* rrset,
1003 	size_t len)
1004 {
1005 	uint8_t* datstart = sldns_buffer_current(buf)-len+2;
1006 	switch(ntohs(rrset->rk.type)) {
1007 		case LDNS_RR_TYPE_NXT:
1008 		case LDNS_RR_TYPE_NS:
1009 		case LDNS_RR_TYPE_MD:
1010 		case LDNS_RR_TYPE_MF:
1011 		case LDNS_RR_TYPE_CNAME:
1012 		case LDNS_RR_TYPE_MB:
1013 		case LDNS_RR_TYPE_MG:
1014 		case LDNS_RR_TYPE_MR:
1015 		case LDNS_RR_TYPE_PTR:
1016 		case LDNS_RR_TYPE_DNAME:
1017 			/* type only has a single argument, the name */
1018 			query_dname_tolower(datstart);
1019 			return;
1020 		case LDNS_RR_TYPE_MINFO:
1021 		case LDNS_RR_TYPE_RP:
1022 		case LDNS_RR_TYPE_SOA:
1023 			/* two names after another */
1024 			query_dname_tolower(datstart);
1025 			query_dname_tolower(datstart +
1026 				dname_valid(datstart, len-2));
1027 			return;
1028 		case LDNS_RR_TYPE_RT:
1029 		case LDNS_RR_TYPE_AFSDB:
1030 		case LDNS_RR_TYPE_KX:
1031 		case LDNS_RR_TYPE_MX:
1032 			/* skip fixed part */
1033 			if(len < 2+2+1) /* rdlen, skiplen, 1byteroot */
1034 				return;
1035 			datstart += 2;
1036 			query_dname_tolower(datstart);
1037 			return;
1038 		case LDNS_RR_TYPE_SIG:
1039 		/* downcase the RRSIG, compat with BIND (kept it from SIG) */
1040 		case LDNS_RR_TYPE_RRSIG:
1041 			/* skip fixed part */
1042 			if(len < 2+18+1)
1043 				return;
1044 			datstart += 18;
1045 			query_dname_tolower(datstart);
1046 			return;
1047 		case LDNS_RR_TYPE_PX:
1048 			/* skip, then two names after another */
1049 			if(len < 2+2+1)
1050 				return;
1051 			datstart += 2;
1052 			query_dname_tolower(datstart);
1053 			query_dname_tolower(datstart +
1054 				dname_valid(datstart, len-2-2));
1055 			return;
1056 		case LDNS_RR_TYPE_NAPTR:
1057 			if(len < 2+4)
1058 				return;
1059 			len -= 2+4;
1060 			datstart += 4;
1061 			if(len < (size_t)datstart[0]+1) /* skip text field */
1062 				return;
1063 			len -= (size_t)datstart[0]+1;
1064 			datstart += (size_t)datstart[0]+1;
1065 			if(len < (size_t)datstart[0]+1) /* skip text field */
1066 				return;
1067 			len -= (size_t)datstart[0]+1;
1068 			datstart += (size_t)datstart[0]+1;
1069 			if(len < (size_t)datstart[0]+1) /* skip text field */
1070 				return;
1071 			len -= (size_t)datstart[0]+1;
1072 			datstart += (size_t)datstart[0]+1;
1073 			if(len < 1)	/* check name is at least 1 byte*/
1074 				return;
1075 			query_dname_tolower(datstart);
1076 			return;
1077 		case LDNS_RR_TYPE_SRV:
1078 			/* skip fixed part */
1079 			if(len < 2+6+1)
1080 				return;
1081 			datstart += 6;
1082 			query_dname_tolower(datstart);
1083 			return;
1084 
1085 		/* do not canonicalize NSEC rdata name, compat with
1086 		 * from bind 9.4 signer, where it does not do so */
1087 		case LDNS_RR_TYPE_NSEC: /* type starts with the name */
1088 		case LDNS_RR_TYPE_HINFO: /* not downcased */
1089 		/* A6 not supported */
1090 		default:
1091 			/* nothing to do for unknown types */
1092 			return;
1093 	}
1094 }
1095 
rrset_canonical_equal(struct regional * region,struct ub_packed_rrset_key * k1,struct ub_packed_rrset_key * k2)1096 int rrset_canonical_equal(struct regional* region,
1097 	struct ub_packed_rrset_key* k1, struct ub_packed_rrset_key* k2)
1098 {
1099 	struct rbtree_type sortree1, sortree2;
1100 	struct canon_rr *rrs1, *rrs2, *p1, *p2;
1101 	struct packed_rrset_data* d1=(struct packed_rrset_data*)k1->entry.data;
1102 	struct packed_rrset_data* d2=(struct packed_rrset_data*)k2->entry.data;
1103 	struct ub_packed_rrset_key fk;
1104 	struct packed_rrset_data fd;
1105 	size_t flen[2];
1106 	uint8_t* fdata[2];
1107 
1108 	/* basic compare */
1109 	if(k1->rk.dname_len != k2->rk.dname_len ||
1110 		k1->rk.flags != k2->rk.flags ||
1111 		k1->rk.type != k2->rk.type ||
1112 		k1->rk.rrset_class != k2->rk.rrset_class ||
1113 		query_dname_compare(k1->rk.dname, k2->rk.dname) != 0)
1114 		return 0;
1115 	if(d1->ttl != d2->ttl ||
1116 		d1->count != d2->count ||
1117 		d1->rrsig_count != d2->rrsig_count ||
1118 		d1->trust != d2->trust ||
1119 		d1->security != d2->security)
1120 		return 0;
1121 
1122 	/* init */
1123 	memset(&fk, 0, sizeof(fk));
1124 	memset(&fd, 0, sizeof(fd));
1125 	fk.entry.data = &fd;
1126 	fd.count = 2;
1127 	fd.rr_len = flen;
1128 	fd.rr_data = fdata;
1129 	rbtree_init(&sortree1, &canonical_tree_compare);
1130 	rbtree_init(&sortree2, &canonical_tree_compare);
1131 	if(d1->count > RR_COUNT_MAX || d2->count > RR_COUNT_MAX)
1132 		return 1; /* protection against integer overflow */
1133 	rrs1 = regional_alloc(region, sizeof(struct canon_rr)*d1->count);
1134 	rrs2 = regional_alloc(region, sizeof(struct canon_rr)*d2->count);
1135 	if(!rrs1 || !rrs2) return 1; /* alloc failure */
1136 
1137 	/* sort */
1138 	canonical_sort(k1, d1, &sortree1, rrs1);
1139 	canonical_sort(k2, d2, &sortree2, rrs2);
1140 
1141 	/* compare canonical-sorted RRs for canonical-equality */
1142 	if(sortree1.count != sortree2.count)
1143 		return 0;
1144 	p1 = (struct canon_rr*)rbtree_first(&sortree1);
1145 	p2 = (struct canon_rr*)rbtree_first(&sortree2);
1146 	while(p1 != (struct canon_rr*)RBTREE_NULL &&
1147 		p2 != (struct canon_rr*)RBTREE_NULL) {
1148 		flen[0] = d1->rr_len[p1->rr_idx];
1149 		flen[1] = d2->rr_len[p2->rr_idx];
1150 		fdata[0] = d1->rr_data[p1->rr_idx];
1151 		fdata[1] = d2->rr_data[p2->rr_idx];
1152 
1153 		if(canonical_compare(&fk, 0, 1) != 0)
1154 			return 0;
1155 		p1 = (struct canon_rr*)rbtree_next(&p1->node);
1156 		p2 = (struct canon_rr*)rbtree_next(&p2->node);
1157 	}
1158 	return 1;
1159 }
1160 
1161 /**
1162  * Create canonical form of rrset in the scratch buffer.
1163  * @param region: temporary region.
1164  * @param buf: the buffer to use.
1165  * @param k: the rrset to insert.
1166  * @param sig: RRSIG rdata to include.
1167  * @param siglen: RRSIG rdata len excluding signature field, but inclusive
1168  * 	signer name length.
1169  * @param sortree: if NULL is passed a new sorted rrset tree is built.
1170  * 	Otherwise it is reused.
1171  * @param section: section of packet where this rrset comes from.
1172  * @param qstate: qstate with region.
1173  * @return false on alloc error.
1174  */
1175 static int
rrset_canonical(struct regional * region,sldns_buffer * buf,struct ub_packed_rrset_key * k,uint8_t * sig,size_t siglen,struct rbtree_type ** sortree,sldns_pkt_section section,struct module_qstate * qstate)1176 rrset_canonical(struct regional* region, sldns_buffer* buf,
1177 	struct ub_packed_rrset_key* k, uint8_t* sig, size_t siglen,
1178 	struct rbtree_type** sortree, sldns_pkt_section section,
1179 	struct module_qstate* qstate)
1180 {
1181 	struct packed_rrset_data* d = (struct packed_rrset_data*)k->entry.data;
1182 	uint8_t* can_owner = NULL;
1183 	size_t can_owner_len = 0;
1184 	struct canon_rr* walk;
1185 	struct canon_rr* rrs;
1186 
1187 	if(!*sortree) {
1188 		*sortree = (struct rbtree_type*)regional_alloc(region,
1189 			sizeof(rbtree_type));
1190 		if(!*sortree)
1191 			return 0;
1192 		if(d->count > RR_COUNT_MAX)
1193 			return 0; /* integer overflow protection */
1194 		rrs = regional_alloc(region, sizeof(struct canon_rr)*d->count);
1195 		if(!rrs) {
1196 			*sortree = NULL;
1197 			return 0;
1198 		}
1199 		rbtree_init(*sortree, &canonical_tree_compare);
1200 		canonical_sort(k, d, *sortree, rrs);
1201 	}
1202 
1203 	sldns_buffer_clear(buf);
1204 	sldns_buffer_write(buf, sig, siglen);
1205 	/* canonicalize signer name */
1206 	query_dname_tolower(sldns_buffer_begin(buf)+18);
1207 	RBTREE_FOR(walk, struct canon_rr*, (*sortree)) {
1208 		/* see if there is enough space left in the buffer */
1209 		if(sldns_buffer_remaining(buf) < can_owner_len + 2 + 2 + 4
1210 			+ d->rr_len[walk->rr_idx]) {
1211 			log_err("verify: failed to canonicalize, "
1212 				"rrset too big");
1213 			return 0;
1214 		}
1215 		/* determine canonical owner name */
1216 		if(can_owner)
1217 			sldns_buffer_write(buf, can_owner, can_owner_len);
1218 		else	insert_can_owner(buf, k, sig, &can_owner,
1219 				&can_owner_len);
1220 		sldns_buffer_write(buf, &k->rk.type, 2);
1221 		sldns_buffer_write(buf, &k->rk.rrset_class, 2);
1222 		sldns_buffer_write(buf, sig+4, 4);
1223 		sldns_buffer_write(buf, d->rr_data[walk->rr_idx],
1224 			d->rr_len[walk->rr_idx]);
1225 		canonicalize_rdata(buf, k, d->rr_len[walk->rr_idx]);
1226 	}
1227 	sldns_buffer_flip(buf);
1228 
1229 	/* Replace RR owner with canonical owner for NSEC records in authority
1230 	 * section, to prevent that a wildcard synthesized NSEC can be used in
1231 	 * the non-existence proves. */
1232 	if(ntohs(k->rk.type) == LDNS_RR_TYPE_NSEC &&
1233 		section == LDNS_SECTION_AUTHORITY && qstate) {
1234 		k->rk.dname = regional_alloc_init(qstate->region, can_owner,
1235 			can_owner_len);
1236 		if(!k->rk.dname)
1237 			return 0;
1238 		k->rk.dname_len = can_owner_len;
1239 	}
1240 
1241 
1242 	return 1;
1243 }
1244 
1245 int
rrset_canonicalize_to_buffer(struct regional * region,sldns_buffer * buf,struct ub_packed_rrset_key * k)1246 rrset_canonicalize_to_buffer(struct regional* region, sldns_buffer* buf,
1247 	struct ub_packed_rrset_key* k)
1248 {
1249 	struct rbtree_type* sortree = NULL;
1250 	struct packed_rrset_data* d = (struct packed_rrset_data*)k->entry.data;
1251 	uint8_t* can_owner = NULL;
1252 	size_t can_owner_len = 0;
1253 	struct canon_rr* walk;
1254 	struct canon_rr* rrs;
1255 
1256 	sortree = (struct rbtree_type*)regional_alloc(region,
1257 		sizeof(rbtree_type));
1258 	if(!sortree)
1259 		return 0;
1260 	if(d->count > RR_COUNT_MAX)
1261 		return 0; /* integer overflow protection */
1262 	rrs = regional_alloc(region, sizeof(struct canon_rr)*d->count);
1263 	if(!rrs) {
1264 		return 0;
1265 	}
1266 	rbtree_init(sortree, &canonical_tree_compare);
1267 	canonical_sort(k, d, sortree, rrs);
1268 
1269 	sldns_buffer_clear(buf);
1270 	RBTREE_FOR(walk, struct canon_rr*, sortree) {
1271 		/* see if there is enough space left in the buffer */
1272 		if(sldns_buffer_remaining(buf) < can_owner_len + 2 + 2 + 4
1273 			+ d->rr_len[walk->rr_idx]) {
1274 			log_err("verify: failed to canonicalize, "
1275 				"rrset too big");
1276 			return 0;
1277 		}
1278 		/* determine canonical owner name */
1279 		if(can_owner)
1280 			sldns_buffer_write(buf, can_owner, can_owner_len);
1281 		else	{
1282 			can_owner = sldns_buffer_current(buf);
1283 			sldns_buffer_write(buf, k->rk.dname, k->rk.dname_len);
1284 			query_dname_tolower(can_owner);
1285 			can_owner_len = k->rk.dname_len;
1286 		}
1287 		sldns_buffer_write(buf, &k->rk.type, 2);
1288 		sldns_buffer_write(buf, &k->rk.rrset_class, 2);
1289 		sldns_buffer_write_u32(buf, d->rr_ttl[walk->rr_idx]);
1290 		sldns_buffer_write(buf, d->rr_data[walk->rr_idx],
1291 			d->rr_len[walk->rr_idx]);
1292 		canonicalize_rdata(buf, k, d->rr_len[walk->rr_idx]);
1293 	}
1294 	sldns_buffer_flip(buf);
1295 	return 1;
1296 }
1297 
1298 /** pretty print rrsig error with dates */
1299 static void
sigdate_error(const char * str,int32_t expi,int32_t incep,int32_t now)1300 sigdate_error(const char* str, int32_t expi, int32_t incep, int32_t now)
1301 {
1302 	struct tm tm;
1303 	char expi_buf[16];
1304 	char incep_buf[16];
1305 	char now_buf[16];
1306 	time_t te, ti, tn;
1307 
1308 	if(verbosity < VERB_QUERY)
1309 		return;
1310 	te = (time_t)expi;
1311 	ti = (time_t)incep;
1312 	tn = (time_t)now;
1313 	memset(&tm, 0, sizeof(tm));
1314 	if(gmtime_r(&te, &tm) && strftime(expi_buf, 15, "%Y%m%d%H%M%S", &tm)
1315 	 &&gmtime_r(&ti, &tm) && strftime(incep_buf, 15, "%Y%m%d%H%M%S", &tm)
1316 	 &&gmtime_r(&tn, &tm) && strftime(now_buf, 15, "%Y%m%d%H%M%S", &tm)) {
1317 		log_info("%s expi=%s incep=%s now=%s", str, expi_buf,
1318 			incep_buf, now_buf);
1319 	} else
1320 		log_info("%s expi=%u incep=%u now=%u", str, (unsigned)expi,
1321 			(unsigned)incep, (unsigned)now);
1322 }
1323 
1324 /** RFC 1982 comparison, uses unsigned integers, and tries to avoid
1325  * compiler optimization (eg. by avoiding a-b<0 comparisons),
1326  * this routine matches compare_serial(), for SOA serial number checks */
1327 static int
compare_1982(uint32_t a,uint32_t b)1328 compare_1982(uint32_t a, uint32_t b)
1329 {
1330 	/* for 32 bit values */
1331         const uint32_t cutoff = ((uint32_t) 1 << (32 - 1));
1332 
1333         if (a == b) {
1334                 return 0;
1335         } else if ((a < b && b - a < cutoff) || (a > b && a - b > cutoff)) {
1336                 return -1;
1337         } else {
1338                 return 1;
1339         }
1340 }
1341 
1342 /** if we know that b is larger than a, return the difference between them,
1343  * that is the distance between them. in RFC1982 arith */
1344 static uint32_t
subtract_1982(uint32_t a,uint32_t b)1345 subtract_1982(uint32_t a, uint32_t b)
1346 {
1347 	/* for 32 bit values */
1348         const uint32_t cutoff = ((uint32_t) 1 << (32 - 1));
1349 
1350 	if(a == b)
1351 		return 0;
1352 	if(a < b && b - a < cutoff) {
1353 		return b-a;
1354 	}
1355 	if(a > b && a - b > cutoff) {
1356 		return ((uint32_t)0xffffffff) - (a-b-1);
1357 	}
1358 	/* wrong case, b smaller than a */
1359 	return 0;
1360 }
1361 
1362 /** check rrsig dates */
1363 static int
check_dates(struct val_env * ve,uint32_t unow,uint8_t * expi_p,uint8_t * incep_p,char ** reason)1364 check_dates(struct val_env* ve, uint32_t unow,
1365 	uint8_t* expi_p, uint8_t* incep_p, char** reason)
1366 {
1367 	/* read out the dates */
1368 	uint32_t expi, incep, now;
1369 	memmove(&expi, expi_p, sizeof(expi));
1370 	memmove(&incep, incep_p, sizeof(incep));
1371 	expi = ntohl(expi);
1372 	incep = ntohl(incep);
1373 
1374 	/* get current date */
1375 	if(ve->date_override) {
1376 		if(ve->date_override == -1) {
1377 			verbose(VERB_ALGO, "date override: ignore date");
1378 			return 1;
1379 		}
1380 		now = ve->date_override;
1381 		verbose(VERB_ALGO, "date override option %d", (int)now);
1382 	} else	now = unow;
1383 
1384 	/* check them */
1385 	if(compare_1982(incep, expi) > 0) {
1386 		sigdate_error("verify: inception after expiration, "
1387 			"signature bad", expi, incep, now);
1388 		*reason = "signature inception after expiration";
1389 		return 0;
1390 	}
1391 	if(compare_1982(incep, now) > 0) {
1392 		/* within skew ? (calc here to avoid calculation normally) */
1393 		uint32_t skew = subtract_1982(incep, expi)/10;
1394 		if(skew < (uint32_t)ve->skew_min) skew = ve->skew_min;
1395 		if(skew > (uint32_t)ve->skew_max) skew = ve->skew_max;
1396 		if(subtract_1982(now, incep) > skew) {
1397 			sigdate_error("verify: signature bad, current time is"
1398 				" before inception date", expi, incep, now);
1399 			*reason = "signature before inception date";
1400 			return 0;
1401 		}
1402 		sigdate_error("verify warning suspicious signature inception "
1403 			" or bad local clock", expi, incep, now);
1404 	}
1405 	if(compare_1982(now, expi) > 0) {
1406 		uint32_t skew = subtract_1982(incep, expi)/10;
1407 		if(skew < (uint32_t)ve->skew_min) skew = ve->skew_min;
1408 		if(skew > (uint32_t)ve->skew_max) skew = ve->skew_max;
1409 		if(subtract_1982(expi, now) > skew) {
1410 			sigdate_error("verify: signature expired", expi,
1411 				incep, now);
1412 			*reason = "signature expired";
1413 			return 0;
1414 		}
1415 		sigdate_error("verify warning suspicious signature expiration "
1416 			" or bad local clock", expi, incep, now);
1417 	}
1418 	return 1;
1419 }
1420 
1421 /** adjust rrset TTL for verified rrset, compare to original TTL and expi */
1422 static void
adjust_ttl(struct val_env * ve,uint32_t unow,struct ub_packed_rrset_key * rrset,uint8_t * orig_p,uint8_t * expi_p,uint8_t * incep_p)1423 adjust_ttl(struct val_env* ve, uint32_t unow,
1424 	struct ub_packed_rrset_key* rrset, uint8_t* orig_p,
1425 	uint8_t* expi_p, uint8_t* incep_p)
1426 {
1427 	struct packed_rrset_data* d =
1428 		(struct packed_rrset_data*)rrset->entry.data;
1429 	/* read out the dates */
1430 	int32_t origttl, expittl, expi, incep, now;
1431 	memmove(&origttl, orig_p, sizeof(origttl));
1432 	memmove(&expi, expi_p, sizeof(expi));
1433 	memmove(&incep, incep_p, sizeof(incep));
1434 	expi = ntohl(expi);
1435 	incep = ntohl(incep);
1436 	origttl = ntohl(origttl);
1437 
1438 	/* get current date */
1439 	if(ve->date_override) {
1440 		now = ve->date_override;
1441 	} else	now = (int32_t)unow;
1442 	expittl = (int32_t)((uint32_t)expi - (uint32_t)now);
1443 
1444 	/* so now:
1445 	 * d->ttl: rrset ttl read from message or cache. May be reduced
1446 	 * origttl: original TTL from signature, authoritative TTL max.
1447 	 * MIN_TTL: minimum TTL from config.
1448 	 * expittl: TTL until the signature expires.
1449 	 *
1450 	 * Use the smallest of these, but don't let origttl set the TTL
1451 	 * below the minimum.
1452 	 */
1453 	if(MIN_TTL > (time_t)origttl && d->ttl > MIN_TTL) {
1454 		verbose(VERB_QUERY, "rrset TTL larger than original and minimum"
1455 			" TTL, adjusting TTL downwards to minimum ttl");
1456 		d->ttl = MIN_TTL;
1457 	}
1458 	else if(MIN_TTL <= origttl && d->ttl > (time_t)origttl) {
1459 		verbose(VERB_QUERY, "rrset TTL larger than original TTL, "
1460 		"adjusting TTL downwards to original ttl");
1461 		d->ttl = origttl;
1462 	}
1463 
1464 	if(expittl > 0 && d->ttl > (time_t)expittl) {
1465 		verbose(VERB_ALGO, "rrset TTL larger than sig expiration ttl,"
1466 			" adjusting TTL downwards");
1467 		d->ttl = expittl;
1468 	}
1469 }
1470 
1471 enum sec_status
dnskey_verify_rrset_sig(struct regional * region,sldns_buffer * buf,struct val_env * ve,time_t now,struct ub_packed_rrset_key * rrset,struct ub_packed_rrset_key * dnskey,size_t dnskey_idx,size_t sig_idx,struct rbtree_type ** sortree,int * buf_canon,char ** reason,sldns_pkt_section section,struct module_qstate * qstate)1472 dnskey_verify_rrset_sig(struct regional* region, sldns_buffer* buf,
1473 	struct val_env* ve, time_t now,
1474         struct ub_packed_rrset_key* rrset, struct ub_packed_rrset_key* dnskey,
1475         size_t dnskey_idx, size_t sig_idx,
1476 	struct rbtree_type** sortree, int* buf_canon, char** reason,
1477 	sldns_pkt_section section, struct module_qstate* qstate)
1478 {
1479 	enum sec_status sec;
1480 	uint8_t* sig;		/* RRSIG rdata */
1481 	size_t siglen;
1482 	size_t rrnum = rrset_get_count(rrset);
1483 	uint8_t* signer;	/* rrsig signer name */
1484 	size_t signer_len;
1485 	unsigned char* sigblock; /* signature rdata field */
1486 	unsigned int sigblock_len;
1487 	uint16_t ktag;		/* DNSKEY key tag */
1488 	unsigned char* key;	/* public key rdata field */
1489 	unsigned int keylen;
1490 	rrset_get_rdata(rrset, rrnum + sig_idx, &sig, &siglen);
1491 	/* min length of rdatalen, fixed rrsig, root signer, 1 byte sig */
1492 	if(siglen < 2+20) {
1493 		verbose(VERB_QUERY, "verify: signature too short");
1494 		*reason = "signature too short";
1495 		return sec_status_bogus;
1496 	}
1497 
1498 	if(!(dnskey_get_flags(dnskey, dnskey_idx) & DNSKEY_BIT_ZSK)) {
1499 		verbose(VERB_QUERY, "verify: dnskey without ZSK flag");
1500 		*reason = "dnskey without ZSK flag";
1501 		return sec_status_bogus;
1502 	}
1503 
1504 	if(dnskey_get_protocol(dnskey, dnskey_idx) != LDNS_DNSSEC_KEYPROTO) {
1505 		/* RFC 4034 says DNSKEY PROTOCOL MUST be 3 */
1506 		verbose(VERB_QUERY, "verify: dnskey has wrong key protocol");
1507 		*reason = "dnskey has wrong protocolnumber";
1508 		return sec_status_bogus;
1509 	}
1510 
1511 	/* verify as many fields in rrsig as possible */
1512 	signer = sig+2+18;
1513 	signer_len = dname_valid(signer, siglen-2-18);
1514 	if(!signer_len) {
1515 		verbose(VERB_QUERY, "verify: malformed signer name");
1516 		*reason = "signer name malformed";
1517 		return sec_status_bogus; /* signer name invalid */
1518 	}
1519 	if(!dname_subdomain_c(rrset->rk.dname, signer)) {
1520 		verbose(VERB_QUERY, "verify: signer name is off-tree");
1521 		*reason = "signer name off-tree";
1522 		return sec_status_bogus; /* signer name offtree */
1523 	}
1524 	sigblock = (unsigned char*)signer+signer_len;
1525 	if(siglen < 2+18+signer_len+1) {
1526 		verbose(VERB_QUERY, "verify: too short, no signature data");
1527 		*reason = "signature too short, no signature data";
1528 		return sec_status_bogus; /* sig rdf is < 1 byte */
1529 	}
1530 	sigblock_len = (unsigned int)(siglen - 2 - 18 - signer_len);
1531 
1532 	/* verify key dname == sig signer name */
1533 	if(query_dname_compare(signer, dnskey->rk.dname) != 0) {
1534 		verbose(VERB_QUERY, "verify: wrong key for rrsig");
1535 		log_nametypeclass(VERB_QUERY, "RRSIG signername is",
1536 			signer, 0, 0);
1537 		log_nametypeclass(VERB_QUERY, "the key name is",
1538 			dnskey->rk.dname, 0, 0);
1539 		*reason = "signer name mismatches key name";
1540 		return sec_status_bogus;
1541 	}
1542 
1543 	/* verify covered type */
1544 	/* memcmp works because type is in network format for rrset */
1545 	if(memcmp(sig+2, &rrset->rk.type, 2) != 0) {
1546 		verbose(VERB_QUERY, "verify: wrong type covered");
1547 		*reason = "signature covers wrong type";
1548 		return sec_status_bogus;
1549 	}
1550 	/* verify keytag and sig algo (possibly again) */
1551 	if((int)sig[2+2] != dnskey_get_algo(dnskey, dnskey_idx)) {
1552 		verbose(VERB_QUERY, "verify: wrong algorithm");
1553 		*reason = "signature has wrong algorithm";
1554 		return sec_status_bogus;
1555 	}
1556 	ktag = htons(dnskey_calc_keytag(dnskey, dnskey_idx));
1557 	if(memcmp(sig+2+16, &ktag, 2) != 0) {
1558 		verbose(VERB_QUERY, "verify: wrong keytag");
1559 		*reason = "signature has wrong keytag";
1560 		return sec_status_bogus;
1561 	}
1562 
1563 	/* verify labels is in a valid range */
1564 	if((int)sig[2+3] > dname_signame_label_count(rrset->rk.dname)) {
1565 		verbose(VERB_QUERY, "verify: labelcount out of range");
1566 		*reason = "signature labelcount out of range";
1567 		return sec_status_bogus;
1568 	}
1569 
1570 	/* original ttl, always ok */
1571 
1572 	if(!*buf_canon) {
1573 		/* create rrset canonical format in buffer, ready for
1574 		 * signature */
1575 		if(!rrset_canonical(region, buf, rrset, sig+2,
1576 			18 + signer_len, sortree, section, qstate)) {
1577 			log_err("verify: failed due to alloc error");
1578 			return sec_status_unchecked;
1579 		}
1580 		*buf_canon = 1;
1581 	}
1582 
1583 	/* check that dnskey is available */
1584 	dnskey_get_pubkey(dnskey, dnskey_idx, &key, &keylen);
1585 	if(!key) {
1586 		verbose(VERB_QUERY, "verify: short DNSKEY RR");
1587 		return sec_status_unchecked;
1588 	}
1589 
1590 	/* verify */
1591 	sec = verify_canonrrset(buf, (int)sig[2+2],
1592 		sigblock, sigblock_len, key, keylen, reason);
1593 
1594 	if(sec == sec_status_secure) {
1595 		/* check if TTL is too high - reduce if so */
1596 		adjust_ttl(ve, now, rrset, sig+2+4, sig+2+8, sig+2+12);
1597 
1598 		/* verify inception, expiration dates
1599 		 * Do this last so that if you ignore expired-sigs the
1600 		 * rest is sure to be OK. */
1601 		if(!check_dates(ve, now, sig+2+8, sig+2+12, reason)) {
1602 			return sec_status_bogus;
1603 		}
1604 	}
1605 
1606 	return sec;
1607 }
1608