xref: /freebsd/contrib/unbound/validator/val_secalgo.c (revision 4543ef516683042d46f3bd3bb8a4f3f746e00499)
1 /*
2  * validator/val_secalgo.c - validator security algorithm functions.
3  *
4  * Copyright (c) 2012, 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  * These functions take raw data buffers, formatted for crypto verification,
41  * and do the library calls (for the crypto library in use).
42  */
43 #include "config.h"
44 /* packed_rrset on top to define enum types (forced by c99 standard) */
45 #include "util/data/packed_rrset.h"
46 #include "validator/val_secalgo.h"
47 #include "validator/val_nsec3.h"
48 #include "util/log.h"
49 #include "sldns/rrdef.h"
50 #include "sldns/keyraw.h"
51 #include "sldns/sbuffer.h"
52 
53 #if !defined(HAVE_SSL) && !defined(HAVE_NSS) && !defined(HAVE_NETTLE)
54 #error "Need crypto library to do digital signature cryptography"
55 #endif
56 
57 /** fake DSA support for unit tests */
58 int fake_dsa = 0;
59 /** fake SHA1 support for unit tests */
60 int fake_sha1 = 0;
61 
62 /* OpenSSL implementation */
63 #ifdef HAVE_SSL
64 #ifdef HAVE_OPENSSL_ERR_H
65 #include <openssl/err.h>
66 #endif
67 
68 #ifdef HAVE_OPENSSL_RAND_H
69 #include <openssl/rand.h>
70 #endif
71 
72 #ifdef HAVE_OPENSSL_CONF_H
73 #include <openssl/conf.h>
74 #endif
75 
76 #ifdef HAVE_OPENSSL_ENGINE_H
77 #include <openssl/engine.h>
78 #endif
79 
80 #if defined(HAVE_OPENSSL_DSA_H) && defined(USE_DSA)
81 #include <openssl/dsa.h>
82 #endif
83 
84 /**
85  * Output a libcrypto openssl error to the logfile.
86  * @param str: string to add to it.
87  * @param e: the error to output, error number from ERR_get_error().
88  */
89 static void
90 log_crypto_error(const char* str, unsigned long e)
91 {
92 	char buf[128];
93 	/* or use ERR_error_string if ERR_error_string_n is not avail TODO */
94 	ERR_error_string_n(e, buf, sizeof(buf));
95 	/* buf now contains */
96 	/* error:[error code]:[library name]:[function name]:[reason string] */
97 	log_err("%s crypto %s", str, buf);
98 }
99 
100 /**
101  * Output a libcrypto openssl error to the logfile as a debug message.
102  * @param level: debug level to use in verbose() call
103  * @param str: string to add to it.
104  * @param e: the error to output, error number from ERR_get_error().
105  */
106 static void
107 log_crypto_verbose(enum verbosity_value level, const char* str, unsigned long e)
108 {
109 	char buf[128];
110 	/* or use ERR_error_string if ERR_error_string_n is not avail TODO */
111 	ERR_error_string_n(e, buf, sizeof(buf));
112 	/* buf now contains */
113 	/* error:[error code]:[library name]:[function name]:[reason string] */
114 	verbose(level, "%s crypto %s", str, buf);
115 }
116 
117 /* return size of digest if supported, or 0 otherwise */
118 size_t
119 nsec3_hash_algo_size_supported(int id)
120 {
121 	switch(id) {
122 	case NSEC3_HASH_SHA1:
123 		return SHA_DIGEST_LENGTH;
124 	default:
125 		return 0;
126 	}
127 }
128 
129 /* perform nsec3 hash. return false on failure */
130 int
131 secalgo_nsec3_hash(int algo, unsigned char* buf, size_t len,
132         unsigned char* res)
133 {
134 	switch(algo) {
135 	case NSEC3_HASH_SHA1:
136 #ifdef OPENSSL_FIPS
137 		if(!sldns_digest_evp(buf, len, res, EVP_sha1()))
138 			log_crypto_error("could not digest with EVP_sha1",
139 				ERR_get_error());
140 #else
141 		(void)SHA1(buf, len, res);
142 #endif
143 		return 1;
144 	default:
145 		return 0;
146 	}
147 }
148 
149 void
150 secalgo_hash_sha256(unsigned char* buf, size_t len, unsigned char* res)
151 {
152 #ifdef OPENSSL_FIPS
153 	if(!sldns_digest_evp(buf, len, res, EVP_sha256()))
154 		log_crypto_error("could not digest with EVP_sha256",
155 			ERR_get_error());
156 #else
157 	(void)SHA256(buf, len, res);
158 #endif
159 }
160 
161 /** hash structure for keeping track of running hashes */
162 struct secalgo_hash {
163 	/** the openssl message digest context */
164 	EVP_MD_CTX* ctx;
165 };
166 
167 /** create secalgo hash with hash type */
168 static struct secalgo_hash* secalgo_hash_create_md(const EVP_MD* md)
169 {
170 	struct secalgo_hash* h;
171 	if(!md)
172 		return NULL;
173 	h = calloc(1, sizeof(*h));
174 	if(!h)
175 		return NULL;
176 	h->ctx = EVP_MD_CTX_create();
177 	if(!h->ctx) {
178 		free(h);
179 		return NULL;
180 	}
181 	if(!EVP_DigestInit_ex(h->ctx, md, NULL)) {
182 		EVP_MD_CTX_destroy(h->ctx);
183 		free(h);
184 		return NULL;
185 	}
186 	return h;
187 }
188 
189 struct secalgo_hash* secalgo_hash_create_sha384(void)
190 {
191 	return secalgo_hash_create_md(EVP_sha384());
192 }
193 
194 struct secalgo_hash* secalgo_hash_create_sha512(void)
195 {
196 	return secalgo_hash_create_md(EVP_sha512());
197 }
198 
199 int secalgo_hash_update(struct secalgo_hash* hash, uint8_t* data, size_t len)
200 {
201 	return EVP_DigestUpdate(hash->ctx, (unsigned char*)data,
202 		(unsigned int)len);
203 }
204 
205 int secalgo_hash_final(struct secalgo_hash* hash, uint8_t* result,
206         size_t maxlen, size_t* resultlen)
207 {
208 	if(EVP_MD_CTX_size(hash->ctx) > (int)maxlen) {
209 		*resultlen = 0;
210 		log_err("secalgo_hash_final: hash buffer too small");
211 		return 0;
212 	}
213 	*resultlen = EVP_MD_CTX_size(hash->ctx);
214 	return EVP_DigestFinal_ex(hash->ctx, result, NULL);
215 }
216 
217 void secalgo_hash_delete(struct secalgo_hash* hash)
218 {
219 	if(!hash) return;
220 	EVP_MD_CTX_destroy(hash->ctx);
221 	free(hash);
222 }
223 
224 /**
225  * Return size of DS digest according to its hash algorithm.
226  * @param algo: DS digest algo.
227  * @return size in bytes of digest, or 0 if not supported.
228  */
229 size_t
230 ds_digest_size_supported(int algo)
231 {
232 	switch(algo) {
233 		case LDNS_SHA1:
234 #if defined(HAVE_EVP_SHA1) && defined(USE_SHA1)
235 #ifdef HAVE_EVP_DEFAULT_PROPERTIES_IS_FIPS_ENABLED
236 			if (EVP_default_properties_is_fips_enabled(NULL))
237 				return 0;
238 #endif
239 			return SHA_DIGEST_LENGTH;
240 #else
241 			if(fake_sha1) return 20;
242 			return 0;
243 #endif
244 #ifdef HAVE_EVP_SHA256
245 		case LDNS_SHA256:
246 			return SHA256_DIGEST_LENGTH;
247 #endif
248 #ifdef USE_GOST
249 		case LDNS_HASH_GOST:
250 			/* we support GOST if it can be loaded */
251 			(void)sldns_key_EVP_load_gost_id();
252 			if(EVP_get_digestbyname("md_gost94"))
253 				return 32;
254 			else	return 0;
255 #endif
256 #ifdef USE_ECDSA
257 		case LDNS_SHA384:
258 			return SHA384_DIGEST_LENGTH;
259 #endif
260 		default: break;
261 	}
262 	return 0;
263 }
264 
265 #ifdef USE_GOST
266 /** Perform GOST hash */
267 static int
268 do_gost94(unsigned char* data, size_t len, unsigned char* dest)
269 {
270 	const EVP_MD* md = EVP_get_digestbyname("md_gost94");
271 	if(!md)
272 		return 0;
273 	return sldns_digest_evp(data, (unsigned int)len, dest, md);
274 }
275 #endif
276 
277 int
278 secalgo_ds_digest(int algo, unsigned char* buf, size_t len,
279 	unsigned char* res)
280 {
281 	switch(algo) {
282 #if defined(HAVE_EVP_SHA1) && defined(USE_SHA1)
283 		case LDNS_SHA1:
284 #ifdef OPENSSL_FIPS
285 			if(!sldns_digest_evp(buf, len, res, EVP_sha1()))
286 				log_crypto_error("could not digest with EVP_sha1",
287 					ERR_get_error());
288 #else
289 			(void)SHA1(buf, len, res);
290 #endif
291 			return 1;
292 #endif
293 #ifdef HAVE_EVP_SHA256
294 		case LDNS_SHA256:
295 #ifdef OPENSSL_FIPS
296 			if(!sldns_digest_evp(buf, len, res, EVP_sha256()))
297 				log_crypto_error("could not digest with EVP_sha256",
298 					ERR_get_error());
299 #else
300 			(void)SHA256(buf, len, res);
301 #endif
302 			return 1;
303 #endif
304 #ifdef USE_GOST
305 		case LDNS_HASH_GOST:
306 			if(do_gost94(buf, len, res))
307 				return 1;
308 			break;
309 #endif
310 #ifdef USE_ECDSA
311 		case LDNS_SHA384:
312 #ifdef OPENSSL_FIPS
313 			if(!sldns_digest_evp(buf, len, res, EVP_sha384()))
314 				log_crypto_error("could not digest with EVP_sha384",
315 					ERR_get_error());
316 #else
317 			(void)SHA384(buf, len, res);
318 #endif
319 			return 1;
320 #endif
321 		default:
322 			verbose(VERB_QUERY, "unknown DS digest algorithm %d",
323 				algo);
324 			break;
325 	}
326 	return 0;
327 }
328 
329 /** return true if DNSKEY algorithm id is supported */
330 int
331 dnskey_algo_id_is_supported(int id)
332 {
333 	switch(id) {
334 	case LDNS_RSAMD5:
335 		/* RFC 6725 deprecates RSAMD5 */
336 		return 0;
337 	case LDNS_DSA:
338 	case LDNS_DSA_NSEC3:
339 #if defined(USE_DSA) && defined(USE_SHA1)
340 		return 1;
341 #else
342 		if(fake_dsa || fake_sha1) return 1;
343 		return 0;
344 #endif
345 
346 	case LDNS_RSASHA1:
347 	case LDNS_RSASHA1_NSEC3:
348 #ifdef USE_SHA1
349 #ifdef HAVE_EVP_DEFAULT_PROPERTIES_IS_FIPS_ENABLED
350 		return !EVP_default_properties_is_fips_enabled(NULL);
351 #else
352 		return 1;
353 #endif
354 #else
355 		if(fake_sha1) return 1;
356 		return 0;
357 #endif
358 
359 #if defined(HAVE_EVP_SHA256) && defined(USE_SHA2)
360 	case LDNS_RSASHA256:
361 #endif
362 #if defined(HAVE_EVP_SHA512) && defined(USE_SHA2)
363 	case LDNS_RSASHA512:
364 #endif
365 #ifdef USE_ECDSA
366 	case LDNS_ECDSAP256SHA256:
367 	case LDNS_ECDSAP384SHA384:
368 #endif
369 #if (defined(HAVE_EVP_SHA256) && defined(USE_SHA2)) || (defined(HAVE_EVP_SHA512) && defined(USE_SHA2)) || defined(USE_ECDSA)
370 		return 1;
371 #endif
372 #ifdef USE_ED25519
373 	case LDNS_ED25519:
374 #endif
375 #ifdef USE_ED448
376 	case LDNS_ED448:
377 #endif
378 #if defined(USE_ED25519) || defined(USE_ED448)
379 #ifdef HAVE_EVP_DEFAULT_PROPERTIES_IS_FIPS_ENABLED
380 		return !EVP_default_properties_is_fips_enabled(NULL);
381 #else
382 		return 1;
383 #endif
384 #endif
385 
386 #ifdef USE_GOST
387 	case LDNS_ECC_GOST:
388 		/* we support GOST if it can be loaded */
389 		return sldns_key_EVP_load_gost_id();
390 #endif
391 	default:
392 		return 0;
393 	}
394 }
395 
396 #ifdef USE_DSA
397 /**
398  * Setup DSA key digest in DER encoding ...
399  * @param sig: input is signature output alloced ptr (unless failure).
400  * 	caller must free alloced ptr if this routine returns true.
401  * @param len: input is initial siglen, output is output len.
402  * @return false on failure.
403  */
404 static int
405 setup_dsa_sig(unsigned char** sig, unsigned int* len)
406 {
407 	unsigned char* orig = *sig;
408 	unsigned int origlen = *len;
409 	int newlen;
410 	BIGNUM *R, *S;
411 	DSA_SIG *dsasig;
412 
413 	/* extract the R and S field from the sig buffer */
414 	if(origlen < 1 + 2*SHA_DIGEST_LENGTH)
415 		return 0;
416 	R = BN_new();
417 	if(!R) return 0;
418 	(void) BN_bin2bn(orig + 1, SHA_DIGEST_LENGTH, R);
419 	S = BN_new();
420 	if(!S) return 0;
421 	(void) BN_bin2bn(orig + 21, SHA_DIGEST_LENGTH, S);
422 	dsasig = DSA_SIG_new();
423 	if(!dsasig) return 0;
424 
425 #ifdef HAVE_DSA_SIG_SET0
426 	if(!DSA_SIG_set0(dsasig, R, S)) return 0;
427 #else
428 #  ifndef S_SPLINT_S
429 	dsasig->r = R;
430 	dsasig->s = S;
431 #  endif /* S_SPLINT_S */
432 #endif
433 	*sig = NULL;
434 	newlen = i2d_DSA_SIG(dsasig, sig);
435 	if(newlen < 0) {
436 		DSA_SIG_free(dsasig);
437 		free(*sig);
438 		return 0;
439 	}
440 	*len = (unsigned int)newlen;
441 	DSA_SIG_free(dsasig);
442 	return 1;
443 }
444 #endif /* USE_DSA */
445 
446 #ifdef USE_ECDSA
447 /**
448  * Setup the ECDSA signature in its encoding that the library wants.
449  * Converts from plain numbers to ASN formatted.
450  * @param sig: input is signature, output alloced ptr (unless failure).
451  * 	caller must free alloced ptr if this routine returns true.
452  * @param len: input is initial siglen, output is output len.
453  * @return false on failure.
454  */
455 static int
456 setup_ecdsa_sig(unsigned char** sig, unsigned int* len)
457 {
458         /* convert from two BIGNUMs in the rdata buffer, to ASN notation.
459 	 * ASN preamble: 30440220 <R 32bytefor256> 0220 <S 32bytefor256>
460 	 * the '20' is the length of that field (=bnsize).
461 i	 * the '44' is the total remaining length.
462 	 * if negative, start with leading zero.
463 	 * if starts with 00s, remove them from the number.
464 	 */
465         uint8_t pre[] = {0x30, 0x44, 0x02, 0x20};
466         int pre_len = 4;
467         uint8_t mid[] = {0x02, 0x20};
468         int mid_len = 2;
469         int raw_sig_len, r_high, s_high, r_rem=0, s_rem=0;
470 	int bnsize = (int)((*len)/2);
471         unsigned char* d = *sig;
472 	uint8_t* p;
473 	/* if too short or not even length, fails */
474 	if(*len < 16 || bnsize*2 != (int)*len)
475 		return 0;
476 
477         /* strip leading zeroes from r (but not last one) */
478         while(r_rem < bnsize-1 && d[r_rem] == 0)
479                 r_rem++;
480         /* strip leading zeroes from s (but not last one) */
481         while(s_rem < bnsize-1 && d[bnsize+s_rem] == 0)
482                 s_rem++;
483 
484         r_high = ((d[0+r_rem]&0x80)?1:0);
485         s_high = ((d[bnsize+s_rem]&0x80)?1:0);
486         raw_sig_len = pre_len + r_high + bnsize - r_rem + mid_len +
487                 s_high + bnsize - s_rem;
488 	*sig = (unsigned char*)malloc((size_t)raw_sig_len);
489 	if(!*sig)
490 		return 0;
491 	p = (uint8_t*)*sig;
492 	p[0] = pre[0];
493 	p[1] = (uint8_t)(raw_sig_len-2);
494 	p[2] = pre[2];
495 	p[3] = (uint8_t)(bnsize + r_high - r_rem);
496 	p += 4;
497 	if(r_high) {
498 		*p = 0;
499 		p += 1;
500 	}
501 	memmove(p, d+r_rem, (size_t)bnsize-r_rem);
502 	p += bnsize-r_rem;
503 	memmove(p, mid, (size_t)mid_len-1);
504 	p += mid_len-1;
505 	*p = (uint8_t)(bnsize + s_high - s_rem);
506 	p += 1;
507         if(s_high) {
508 		*p = 0;
509 		p += 1;
510 	}
511 	memmove(p, d+bnsize+s_rem, (size_t)bnsize-s_rem);
512 	*len = (unsigned int)raw_sig_len;
513 	return 1;
514 }
515 #endif /* USE_ECDSA */
516 
517 #ifdef USE_ECDSA_EVP_WORKAROUND
518 static EVP_MD ecdsa_evp_256_md;
519 static EVP_MD ecdsa_evp_384_md;
520 void ecdsa_evp_workaround_init(void)
521 {
522 	/* openssl before 1.0.0 fixes RSA with the SHA256
523 	 * hash in EVP.  We create one for ecdsa_sha256 */
524 	ecdsa_evp_256_md = *EVP_sha256();
525 	ecdsa_evp_256_md.required_pkey_type[0] = EVP_PKEY_EC;
526 	ecdsa_evp_256_md.verify = (void*)ECDSA_verify;
527 
528 	ecdsa_evp_384_md = *EVP_sha384();
529 	ecdsa_evp_384_md.required_pkey_type[0] = EVP_PKEY_EC;
530 	ecdsa_evp_384_md.verify = (void*)ECDSA_verify;
531 }
532 #endif /* USE_ECDSA_EVP_WORKAROUND */
533 
534 /**
535  * Setup key and digest for verification. Adjust sig if necessary.
536  *
537  * @param algo: key algorithm
538  * @param evp_key: EVP PKEY public key to create.
539  * @param digest_type: digest type to use
540  * @param key: key to setup for.
541  * @param keylen: length of key.
542  * @return false on failure.
543  */
544 static int
545 setup_key_digest(int algo, EVP_PKEY** evp_key, const EVP_MD** digest_type,
546 	unsigned char* key, size_t keylen)
547 {
548 	switch(algo) {
549 #if defined(USE_DSA) && defined(USE_SHA1)
550 		case LDNS_DSA:
551 		case LDNS_DSA_NSEC3:
552 			*evp_key = sldns_key_dsa2pkey_raw(key, keylen);
553 			if(!*evp_key) {
554 				verbose(VERB_QUERY, "verify: sldns_key_dsa2pkey failed");
555 				return 0;
556 			}
557 #ifdef HAVE_EVP_DSS1
558 			*digest_type = EVP_dss1();
559 #else
560 			*digest_type = EVP_sha1();
561 #endif
562 
563 			break;
564 #endif /* USE_DSA && USE_SHA1 */
565 
566 #if defined(USE_SHA1) || (defined(HAVE_EVP_SHA256) && defined(USE_SHA2)) || (defined(HAVE_EVP_SHA512) && defined(USE_SHA2))
567 #ifdef USE_SHA1
568 		case LDNS_RSASHA1:
569 		case LDNS_RSASHA1_NSEC3:
570 #endif
571 #if defined(HAVE_EVP_SHA256) && defined(USE_SHA2)
572 		case LDNS_RSASHA256:
573 #endif
574 #if defined(HAVE_EVP_SHA512) && defined(USE_SHA2)
575 		case LDNS_RSASHA512:
576 #endif
577 			*evp_key = sldns_key_rsa2pkey_raw(key, keylen);
578 			if(!*evp_key) {
579 				verbose(VERB_QUERY, "verify: sldns_key_rsa2pkey SHA failed");
580 				return 0;
581 			}
582 
583 			/* select SHA version */
584 #if defined(HAVE_EVP_SHA256) && defined(USE_SHA2)
585 			if(algo == LDNS_RSASHA256)
586 				*digest_type = EVP_sha256();
587 			else
588 #endif
589 #if defined(HAVE_EVP_SHA512) && defined(USE_SHA2)
590 				if(algo == LDNS_RSASHA512)
591 				*digest_type = EVP_sha512();
592 			else
593 #endif
594 #ifdef USE_SHA1
595 				*digest_type = EVP_sha1();
596 #else
597 				{ verbose(VERB_QUERY, "no digest available"); return 0; }
598 #endif
599 			break;
600 #endif /* defined(USE_SHA1) || (defined(HAVE_EVP_SHA256) && defined(USE_SHA2)) || (defined(HAVE_EVP_SHA512) && defined(USE_SHA2)) */
601 
602 		case LDNS_RSAMD5:
603 			*evp_key = sldns_key_rsa2pkey_raw(key, keylen);
604 			if(!*evp_key) {
605 				verbose(VERB_QUERY, "verify: sldns_key_rsa2pkey MD5 failed");
606 				return 0;
607 			}
608 			*digest_type = EVP_md5();
609 
610 			break;
611 #ifdef USE_GOST
612 		case LDNS_ECC_GOST:
613 			*evp_key = sldns_gost2pkey_raw(key, keylen);
614 			if(!*evp_key) {
615 				verbose(VERB_QUERY, "verify: "
616 					"sldns_gost2pkey_raw failed");
617 				return 0;
618 			}
619 			*digest_type = EVP_get_digestbyname("md_gost94");
620 			if(!*digest_type) {
621 				verbose(VERB_QUERY, "verify: "
622 					"EVP_getdigest md_gost94 failed");
623 				return 0;
624 			}
625 			break;
626 #endif
627 #ifdef USE_ECDSA
628 		case LDNS_ECDSAP256SHA256:
629 			*evp_key = sldns_ecdsa2pkey_raw(key, keylen,
630 				LDNS_ECDSAP256SHA256);
631 			if(!*evp_key) {
632 				verbose(VERB_QUERY, "verify: "
633 					"sldns_ecdsa2pkey_raw failed");
634 				return 0;
635 			}
636 #ifdef USE_ECDSA_EVP_WORKAROUND
637 			*digest_type = &ecdsa_evp_256_md;
638 #else
639 			*digest_type = EVP_sha256();
640 #endif
641 			break;
642 		case LDNS_ECDSAP384SHA384:
643 			*evp_key = sldns_ecdsa2pkey_raw(key, keylen,
644 				LDNS_ECDSAP384SHA384);
645 			if(!*evp_key) {
646 				verbose(VERB_QUERY, "verify: "
647 					"sldns_ecdsa2pkey_raw failed");
648 				return 0;
649 			}
650 #ifdef USE_ECDSA_EVP_WORKAROUND
651 			*digest_type = &ecdsa_evp_384_md;
652 #else
653 			*digest_type = EVP_sha384();
654 #endif
655 			break;
656 #endif /* USE_ECDSA */
657 #ifdef USE_ED25519
658 		case LDNS_ED25519:
659 			*evp_key = sldns_ed255192pkey_raw(key, keylen);
660 			if(!*evp_key) {
661 				verbose(VERB_QUERY, "verify: "
662 					"sldns_ed255192pkey_raw failed");
663 				return 0;
664 			}
665 			*digest_type = NULL;
666 			break;
667 #endif /* USE_ED25519 */
668 #ifdef USE_ED448
669 		case LDNS_ED448:
670 			*evp_key = sldns_ed4482pkey_raw(key, keylen);
671 			if(!*evp_key) {
672 				verbose(VERB_QUERY, "verify: "
673 					"sldns_ed4482pkey_raw failed");
674 				return 0;
675 			}
676 			*digest_type = NULL;
677 			break;
678 #endif /* USE_ED448 */
679 		default:
680 			verbose(VERB_QUERY, "verify: unknown algorithm %d",
681 				algo);
682 			return 0;
683 	}
684 	return 1;
685 }
686 
687 static void
688 digest_ctx_free(EVP_MD_CTX* ctx, EVP_PKEY *evp_key,
689 	unsigned char* sigblock, int dofree, int docrypto_free)
690 {
691 #ifdef HAVE_EVP_MD_CTX_NEW
692 	EVP_MD_CTX_destroy(ctx);
693 #else
694 	EVP_MD_CTX_cleanup(ctx);
695 	free(ctx);
696 #endif
697 	EVP_PKEY_free(evp_key);
698 	if(dofree) free(sigblock);
699 	else if(docrypto_free) OPENSSL_free(sigblock);
700 }
701 
702 static enum sec_status
703 digest_error_status(const char *str)
704 {
705 	unsigned long e = ERR_get_error();
706 #ifdef EVP_R_INVALID_DIGEST
707 	if (ERR_GET_LIB(e) == ERR_LIB_EVP &&
708 		ERR_GET_REASON(e) == EVP_R_INVALID_DIGEST) {
709 		log_crypto_verbose(VERB_ALGO, str, e);
710 		return sec_status_indeterminate;
711 	}
712 #endif
713 	log_crypto_verbose(VERB_QUERY, str, e);
714 	return sec_status_unchecked;
715 }
716 
717 /**
718  * Check a canonical sig+rrset and signature against a dnskey
719  * @param buf: buffer with data to verify, the first rrsig part and the
720  *	canonicalized rrset.
721  * @param algo: DNSKEY algorithm.
722  * @param sigblock: signature rdata field from RRSIG
723  * @param sigblock_len: length of sigblock data.
724  * @param key: public key data from DNSKEY RR.
725  * @param keylen: length of keydata.
726  * @param reason: bogus reason in more detail.
727  * @return secure if verification succeeded, bogus on crypto failure,
728  *	unchecked on format errors and alloc failures, indeterminate
729  *	if digest is not supported by the crypto library (openssl3+ only).
730  */
731 enum sec_status
732 verify_canonrrset(sldns_buffer* buf, int algo, unsigned char* sigblock,
733 	unsigned int sigblock_len, unsigned char* key, unsigned int keylen,
734 	char** reason)
735 {
736 	const EVP_MD *digest_type;
737 	EVP_MD_CTX* ctx;
738 	int res, dofree = 0, docrypto_free = 0;
739 	EVP_PKEY *evp_key = NULL;
740 
741 #ifndef USE_DSA
742 	if((algo == LDNS_DSA || algo == LDNS_DSA_NSEC3) &&(fake_dsa||fake_sha1))
743 		return sec_status_secure;
744 #endif
745 #ifndef USE_SHA1
746 	if(fake_sha1 && (algo == LDNS_DSA || algo == LDNS_DSA_NSEC3 || algo == LDNS_RSASHA1 || algo == LDNS_RSASHA1_NSEC3))
747 		return sec_status_secure;
748 #endif
749 
750 	if(!setup_key_digest(algo, &evp_key, &digest_type, key, keylen)) {
751 		verbose(VERB_QUERY, "verify: failed to setup key");
752 		*reason = "use of key for crypto failed";
753 		EVP_PKEY_free(evp_key);
754 		return sec_status_bogus;
755 	}
756 #ifdef USE_DSA
757 	/* if it is a DSA signature in bind format, convert to DER format */
758 	if((algo == LDNS_DSA || algo == LDNS_DSA_NSEC3) &&
759 		sigblock_len == 1+2*SHA_DIGEST_LENGTH) {
760 		if(!setup_dsa_sig(&sigblock, &sigblock_len)) {
761 			verbose(VERB_QUERY, "verify: failed to setup DSA sig");
762 			*reason = "use of key for DSA crypto failed";
763 			EVP_PKEY_free(evp_key);
764 			return sec_status_bogus;
765 		}
766 		docrypto_free = 1;
767 	}
768 #endif
769 #if defined(USE_ECDSA) && defined(USE_DSA)
770 	else
771 #endif
772 #ifdef USE_ECDSA
773 	if(algo == LDNS_ECDSAP256SHA256 || algo == LDNS_ECDSAP384SHA384) {
774 		/* EVP uses ASN prefix on sig, which is not in the wire data */
775 		if(!setup_ecdsa_sig(&sigblock, &sigblock_len)) {
776 			verbose(VERB_QUERY, "verify: failed to setup ECDSA sig");
777 			*reason = "use of signature for ECDSA crypto failed";
778 			EVP_PKEY_free(evp_key);
779 			return sec_status_bogus;
780 		}
781 		dofree = 1;
782 	}
783 #endif /* USE_ECDSA */
784 
785 	/* do the signature cryptography work */
786 #ifdef HAVE_EVP_MD_CTX_NEW
787 	ctx = EVP_MD_CTX_new();
788 #else
789 	ctx = (EVP_MD_CTX*)malloc(sizeof(*ctx));
790 	if(ctx) EVP_MD_CTX_init(ctx);
791 #endif
792 	if(!ctx) {
793 		log_err("EVP_MD_CTX_new: malloc failure");
794 		EVP_PKEY_free(evp_key);
795 		if(dofree) free(sigblock);
796 		else if(docrypto_free) OPENSSL_free(sigblock);
797 		return sec_status_unchecked;
798 	}
799 #ifndef HAVE_EVP_DIGESTVERIFY
800 	if(EVP_DigestInit(ctx, digest_type) == 0) {
801 		enum sec_status sec;
802 		sec = digest_error_status("verify: EVP_DigestInit failed");
803 		digest_ctx_free(ctx, evp_key, sigblock,
804 			dofree, docrypto_free);
805 		return sec;
806 	}
807 	if(EVP_DigestUpdate(ctx, (unsigned char*)sldns_buffer_begin(buf),
808 		(unsigned int)sldns_buffer_limit(buf)) == 0) {
809 		log_crypto_verbose(VERB_QUERY, "verify: EVP_DigestUpdate failed",
810 			ERR_get_error());
811 		digest_ctx_free(ctx, evp_key, sigblock,
812 			dofree, docrypto_free);
813 		return sec_status_unchecked;
814 	}
815 
816 	res = EVP_VerifyFinal(ctx, sigblock, sigblock_len, evp_key);
817 #else /* HAVE_EVP_DIGESTVERIFY */
818 	if(EVP_DigestVerifyInit(ctx, NULL, digest_type, NULL, evp_key) == 0) {
819 		enum sec_status sec;
820 		sec = digest_error_status("verify: EVP_DigestVerifyInit failed");
821 		digest_ctx_free(ctx, evp_key, sigblock,
822 			dofree, docrypto_free);
823 		return sec;
824 	}
825 	res = EVP_DigestVerify(ctx, sigblock, sigblock_len,
826 		(unsigned char*)sldns_buffer_begin(buf),
827 		sldns_buffer_limit(buf));
828 #endif
829 	digest_ctx_free(ctx, evp_key, sigblock,
830 		dofree, docrypto_free);
831 
832 	if(res == 1) {
833 		return sec_status_secure;
834 	} else if(res == 0) {
835 		verbose(VERB_QUERY, "verify: signature mismatch");
836 		*reason = "signature crypto failed";
837 		return sec_status_bogus;
838 	}
839 
840 	log_crypto_error("verify:", ERR_get_error());
841 	return sec_status_unchecked;
842 }
843 
844 /**************************************************/
845 #elif defined(HAVE_NSS)
846 /* libnss implementation */
847 /* nss3 */
848 #include "sechash.h"
849 #include "pk11pub.h"
850 #include "keyhi.h"
851 #include "secerr.h"
852 #include "cryptohi.h"
853 /* nspr4 */
854 #include "prerror.h"
855 
856 /* return size of digest if supported, or 0 otherwise */
857 size_t
858 nsec3_hash_algo_size_supported(int id)
859 {
860 	switch(id) {
861 	case NSEC3_HASH_SHA1:
862 		return SHA1_LENGTH;
863 	default:
864 		return 0;
865 	}
866 }
867 
868 /* perform nsec3 hash. return false on failure */
869 int
870 secalgo_nsec3_hash(int algo, unsigned char* buf, size_t len,
871         unsigned char* res)
872 {
873 	switch(algo) {
874 	case NSEC3_HASH_SHA1:
875 		(void)HASH_HashBuf(HASH_AlgSHA1, res, buf, (unsigned long)len);
876 		return 1;
877 	default:
878 		return 0;
879 	}
880 }
881 
882 void
883 secalgo_hash_sha256(unsigned char* buf, size_t len, unsigned char* res)
884 {
885 	(void)HASH_HashBuf(HASH_AlgSHA256, res, buf, (unsigned long)len);
886 }
887 
888 /** the secalgo hash structure */
889 struct secalgo_hash {
890 	/** hash context */
891 	HASHContext* ctx;
892 };
893 
894 /** create hash struct of type */
895 static struct secalgo_hash* secalgo_hash_create_type(HASH_HashType tp)
896 {
897 	struct secalgo_hash* h = calloc(1, sizeof(*h));
898 	if(!h)
899 		return NULL;
900 	h->ctx = HASH_Create(tp);
901 	if(!h->ctx) {
902 		free(h);
903 		return NULL;
904 	}
905 	return h;
906 }
907 
908 struct secalgo_hash* secalgo_hash_create_sha384(void)
909 {
910 	return secalgo_hash_create_type(HASH_AlgSHA384);
911 }
912 
913 struct secalgo_hash* secalgo_hash_create_sha512(void)
914 {
915 	return secalgo_hash_create_type(HASH_AlgSHA512);
916 }
917 
918 int secalgo_hash_update(struct secalgo_hash* hash, uint8_t* data, size_t len)
919 {
920 	HASH_Update(hash->ctx, (unsigned char*)data, (unsigned int)len);
921 	return 1;
922 }
923 
924 int secalgo_hash_final(struct secalgo_hash* hash, uint8_t* result,
925         size_t maxlen, size_t* resultlen)
926 {
927 	unsigned int reslen = 0;
928 	if(HASH_ResultLenContext(hash->ctx) > (unsigned int)maxlen) {
929 		*resultlen = 0;
930 		log_err("secalgo_hash_final: hash buffer too small");
931 		return 0;
932 	}
933 	HASH_End(hash->ctx, (unsigned char*)result, &reslen,
934 		(unsigned int)maxlen);
935 	*resultlen = (size_t)reslen;
936 	return 1;
937 }
938 
939 void secalgo_hash_delete(struct secalgo_hash* hash)
940 {
941 	if(!hash) return;
942 	HASH_Destroy(hash->ctx);
943 	free(hash);
944 }
945 
946 size_t
947 ds_digest_size_supported(int algo)
948 {
949 	/* uses libNSS */
950 	switch(algo) {
951 #ifdef USE_SHA1
952 		case LDNS_SHA1:
953 			return SHA1_LENGTH;
954 #endif
955 #ifdef USE_SHA2
956 		case LDNS_SHA256:
957 			return SHA256_LENGTH;
958 #endif
959 #ifdef USE_ECDSA
960 		case LDNS_SHA384:
961 			return SHA384_LENGTH;
962 #endif
963 		/* GOST not supported in NSS */
964 		case LDNS_HASH_GOST:
965 		default: break;
966 	}
967 	return 0;
968 }
969 
970 int
971 secalgo_ds_digest(int algo, unsigned char* buf, size_t len,
972 	unsigned char* res)
973 {
974 	/* uses libNSS */
975 	switch(algo) {
976 #ifdef USE_SHA1
977 		case LDNS_SHA1:
978 			return HASH_HashBuf(HASH_AlgSHA1, res, buf, len)
979 				== SECSuccess;
980 #endif
981 #if defined(USE_SHA2)
982 		case LDNS_SHA256:
983 			return HASH_HashBuf(HASH_AlgSHA256, res, buf, len)
984 				== SECSuccess;
985 #endif
986 #ifdef USE_ECDSA
987 		case LDNS_SHA384:
988 			return HASH_HashBuf(HASH_AlgSHA384, res, buf, len)
989 				== SECSuccess;
990 #endif
991 		case LDNS_HASH_GOST:
992 		default:
993 			verbose(VERB_QUERY, "unknown DS digest algorithm %d",
994 				algo);
995 			break;
996 	}
997 	return 0;
998 }
999 
1000 int
1001 dnskey_algo_id_is_supported(int id)
1002 {
1003 	/* uses libNSS */
1004 	switch(id) {
1005 	case LDNS_RSAMD5:
1006 		/* RFC 6725 deprecates RSAMD5 */
1007 		return 0;
1008 #if defined(USE_SHA1) || defined(USE_SHA2)
1009 #if defined(USE_DSA) && defined(USE_SHA1)
1010 	case LDNS_DSA:
1011 	case LDNS_DSA_NSEC3:
1012 #endif
1013 #ifdef USE_SHA1
1014 	case LDNS_RSASHA1:
1015 	case LDNS_RSASHA1_NSEC3:
1016 #endif
1017 #ifdef USE_SHA2
1018 	case LDNS_RSASHA256:
1019 #endif
1020 #ifdef USE_SHA2
1021 	case LDNS_RSASHA512:
1022 #endif
1023 		return 1;
1024 #endif /* SHA1 or SHA2 */
1025 
1026 #ifdef USE_ECDSA
1027 	case LDNS_ECDSAP256SHA256:
1028 	case LDNS_ECDSAP384SHA384:
1029 		return PK11_TokenExists(CKM_ECDSA);
1030 #endif
1031 	case LDNS_ECC_GOST:
1032 	default:
1033 		return 0;
1034 	}
1035 }
1036 
1037 /* return a new public key for NSS */
1038 static SECKEYPublicKey* nss_key_create(KeyType ktype)
1039 {
1040 	SECKEYPublicKey* key;
1041 	PLArenaPool* arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
1042 	if(!arena) {
1043 		log_err("out of memory, PORT_NewArena failed");
1044 		return NULL;
1045 	}
1046 	key = PORT_ArenaZNew(arena, SECKEYPublicKey);
1047 	if(!key) {
1048 		log_err("out of memory, PORT_ArenaZNew failed");
1049 		PORT_FreeArena(arena, PR_FALSE);
1050 		return NULL;
1051 	}
1052 	key->arena = arena;
1053 	key->keyType = ktype;
1054 	key->pkcs11Slot = NULL;
1055 	key->pkcs11ID = CK_INVALID_HANDLE;
1056 	return key;
1057 }
1058 
1059 static SECKEYPublicKey* nss_buf2ecdsa(unsigned char* key, size_t len, int algo)
1060 {
1061 	SECKEYPublicKey* pk;
1062 	SECItem pub = {siBuffer, NULL, 0};
1063 	SECItem params = {siBuffer, NULL, 0};
1064 	static unsigned char param256[] = {
1065 		/* OBJECTIDENTIFIER 1.2.840.10045.3.1.7 (P-256)
1066 		 * {iso(1) member-body(2) us(840) ansi-x962(10045) curves(3) prime(1) prime256v1(7)} */
1067 		0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07
1068 	};
1069 	static unsigned char param384[] = {
1070 		/* OBJECTIDENTIFIER 1.3.132.0.34 (P-384)
1071 		 * {iso(1) identified-organization(3) certicom(132) curve(0) ansip384r1(34)} */
1072 		0x06, 0x05, 0x2b, 0x81, 0x04, 0x00, 0x22
1073 	};
1074 	unsigned char buf[256+2]; /* sufficient for 2*384/8+1 */
1075 
1076 	/* check length, which uncompressed must be 2 bignums */
1077 	if(algo == LDNS_ECDSAP256SHA256) {
1078 		if(len != 2*256/8) return NULL;
1079 		/* ECCurve_X9_62_PRIME_256V1 */
1080 	} else if(algo == LDNS_ECDSAP384SHA384) {
1081 		if(len != 2*384/8) return NULL;
1082 		/* ECCurve_X9_62_PRIME_384R1 */
1083 	} else    return NULL;
1084 
1085 	buf[0] = 0x04; /* POINT_FORM_UNCOMPRESSED */
1086 	memmove(buf+1, key, len);
1087 	pub.data = buf;
1088 	pub.len = len+1;
1089 	if(algo == LDNS_ECDSAP256SHA256) {
1090 		params.data = param256;
1091 		params.len = sizeof(param256);
1092 	} else {
1093 		params.data = param384;
1094 		params.len = sizeof(param384);
1095 	}
1096 
1097 	pk = nss_key_create(ecKey);
1098 	if(!pk)
1099 		return NULL;
1100 	pk->u.ec.size = (len/2)*8;
1101 	if(SECITEM_CopyItem(pk->arena, &pk->u.ec.publicValue, &pub)) {
1102 		SECKEY_DestroyPublicKey(pk);
1103 		return NULL;
1104 	}
1105 	if(SECITEM_CopyItem(pk->arena, &pk->u.ec.DEREncodedParams, &params)) {
1106 		SECKEY_DestroyPublicKey(pk);
1107 		return NULL;
1108 	}
1109 
1110 	return pk;
1111 }
1112 
1113 #if defined(USE_DSA) && defined(USE_SHA1)
1114 static SECKEYPublicKey* nss_buf2dsa(unsigned char* key, size_t len)
1115 {
1116 	SECKEYPublicKey* pk;
1117 	uint8_t T;
1118 	uint16_t length;
1119 	uint16_t offset;
1120 	SECItem Q = {siBuffer, NULL, 0};
1121 	SECItem P = {siBuffer, NULL, 0};
1122 	SECItem G = {siBuffer, NULL, 0};
1123 	SECItem Y = {siBuffer, NULL, 0};
1124 
1125 	if(len == 0)
1126 		return NULL;
1127 	T = (uint8_t)key[0];
1128 	length = (64 + T * 8);
1129 	offset = 1;
1130 
1131 	if (T > 8) {
1132 		return NULL;
1133 	}
1134 	if(len < (size_t)1 + SHA1_LENGTH + 3*length)
1135 		return NULL;
1136 
1137 	Q.data = key+offset;
1138 	Q.len = SHA1_LENGTH;
1139 	offset += SHA1_LENGTH;
1140 
1141 	P.data = key+offset;
1142 	P.len = length;
1143 	offset += length;
1144 
1145 	G.data = key+offset;
1146 	G.len = length;
1147 	offset += length;
1148 
1149 	Y.data = key+offset;
1150 	Y.len = length;
1151 	offset += length;
1152 
1153 	pk = nss_key_create(dsaKey);
1154 	if(!pk)
1155 		return NULL;
1156 	if(SECITEM_CopyItem(pk->arena, &pk->u.dsa.params.prime, &P)) {
1157 		SECKEY_DestroyPublicKey(pk);
1158 		return NULL;
1159 	}
1160 	if(SECITEM_CopyItem(pk->arena, &pk->u.dsa.params.subPrime, &Q)) {
1161 		SECKEY_DestroyPublicKey(pk);
1162 		return NULL;
1163 	}
1164 	if(SECITEM_CopyItem(pk->arena, &pk->u.dsa.params.base, &G)) {
1165 		SECKEY_DestroyPublicKey(pk);
1166 		return NULL;
1167 	}
1168 	if(SECITEM_CopyItem(pk->arena, &pk->u.dsa.publicValue, &Y)) {
1169 		SECKEY_DestroyPublicKey(pk);
1170 		return NULL;
1171 	}
1172 	return pk;
1173 }
1174 #endif /* USE_DSA && USE_SHA1 */
1175 
1176 static SECKEYPublicKey* nss_buf2rsa(unsigned char* key, size_t len)
1177 {
1178 	SECKEYPublicKey* pk;
1179 	uint16_t exp;
1180 	uint16_t offset;
1181 	uint16_t int16;
1182 	SECItem modulus = {siBuffer, NULL, 0};
1183 	SECItem exponent = {siBuffer, NULL, 0};
1184 	if(len == 0)
1185 		return NULL;
1186 	if(key[0] == 0) {
1187 		if(len < 3)
1188 			return NULL;
1189 		/* the exponent is too large so it's places further */
1190 		memmove(&int16, key+1, 2);
1191 		exp = ntohs(int16);
1192 		offset = 3;
1193 	} else {
1194 		exp = key[0];
1195 		offset = 1;
1196 	}
1197 
1198 	/* key length at least one */
1199 	if(len < (size_t)offset + exp + 1)
1200 		return NULL;
1201 
1202 	exponent.data = key+offset;
1203 	exponent.len = exp;
1204 	offset += exp;
1205 	modulus.data = key+offset;
1206 	modulus.len = (len - offset);
1207 
1208 	pk = nss_key_create(rsaKey);
1209 	if(!pk)
1210 		return NULL;
1211 	if(SECITEM_CopyItem(pk->arena, &pk->u.rsa.modulus, &modulus)) {
1212 		SECKEY_DestroyPublicKey(pk);
1213 		return NULL;
1214 	}
1215 	if(SECITEM_CopyItem(pk->arena, &pk->u.rsa.publicExponent, &exponent)) {
1216 		SECKEY_DestroyPublicKey(pk);
1217 		return NULL;
1218 	}
1219 	return pk;
1220 }
1221 
1222 /**
1223  * Setup key and digest for verification. Adjust sig if necessary.
1224  *
1225  * @param algo: key algorithm
1226  * @param evp_key: EVP PKEY public key to create.
1227  * @param digest_type: digest type to use
1228  * @param key: key to setup for.
1229  * @param keylen: length of key.
1230  * @param prefix: if returned, the ASN prefix for the hashblob.
1231  * @param prefixlen: length of the prefix.
1232  * @return false on failure.
1233  */
1234 static int
1235 nss_setup_key_digest(int algo, SECKEYPublicKey** pubkey, HASH_HashType* htype,
1236 	unsigned char* key, size_t keylen, unsigned char** prefix,
1237 	size_t* prefixlen)
1238 {
1239 	/* uses libNSS */
1240 
1241 	/* hash prefix for md5, RFC2537 */
1242 	static unsigned char p_md5[] = {0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a,
1243 	0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, 0x10};
1244 	/* hash prefix to prepend to hash output, from RFC3110 */
1245 	static unsigned char p_sha1[] = {0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2B,
1246 		0x0E, 0x03, 0x02, 0x1A, 0x05, 0x00, 0x04, 0x14};
1247 	/* from RFC5702 */
1248 	static unsigned char p_sha256[] = {0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60,
1249 	0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20};
1250 	static unsigned char p_sha512[] = {0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60,
1251 	0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, 0x00, 0x04, 0x40};
1252 	/* from RFC6234 */
1253 	/* for future RSASHA384 ..
1254 	static unsigned char p_sha384[] = {0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60,
1255 	0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, 0x04, 0x30};
1256 	*/
1257 
1258 	switch(algo) {
1259 
1260 #if defined(USE_SHA1) || defined(USE_SHA2)
1261 #if defined(USE_DSA) && defined(USE_SHA1)
1262 		case LDNS_DSA:
1263 		case LDNS_DSA_NSEC3:
1264 			*pubkey = nss_buf2dsa(key, keylen);
1265 			if(!*pubkey) {
1266 				log_err("verify: malloc failure in crypto");
1267 				return 0;
1268 			}
1269 			*htype = HASH_AlgSHA1;
1270 			/* no prefix for DSA verification */
1271 			break;
1272 #endif
1273 #ifdef USE_SHA1
1274 		case LDNS_RSASHA1:
1275 		case LDNS_RSASHA1_NSEC3:
1276 #endif
1277 #ifdef USE_SHA2
1278 		case LDNS_RSASHA256:
1279 #endif
1280 #ifdef USE_SHA2
1281 		case LDNS_RSASHA512:
1282 #endif
1283 			*pubkey = nss_buf2rsa(key, keylen);
1284 			if(!*pubkey) {
1285 				log_err("verify: malloc failure in crypto");
1286 				return 0;
1287 			}
1288 			/* select SHA version */
1289 #ifdef USE_SHA2
1290 			if(algo == LDNS_RSASHA256) {
1291 				*htype = HASH_AlgSHA256;
1292 				*prefix = p_sha256;
1293 				*prefixlen = sizeof(p_sha256);
1294 			} else
1295 #endif
1296 #ifdef USE_SHA2
1297 				if(algo == LDNS_RSASHA512) {
1298 				*htype = HASH_AlgSHA512;
1299 				*prefix = p_sha512;
1300 				*prefixlen = sizeof(p_sha512);
1301 			} else
1302 #endif
1303 #ifdef USE_SHA1
1304 			{
1305 				*htype = HASH_AlgSHA1;
1306 				*prefix = p_sha1;
1307 				*prefixlen = sizeof(p_sha1);
1308 			}
1309 #else
1310 			{
1311 				verbose(VERB_QUERY, "verify: no digest algo");
1312 				return 0;
1313 			}
1314 #endif
1315 
1316 			break;
1317 #endif /* SHA1 or SHA2 */
1318 
1319 		case LDNS_RSAMD5:
1320 			*pubkey = nss_buf2rsa(key, keylen);
1321 			if(!*pubkey) {
1322 				log_err("verify: malloc failure in crypto");
1323 				return 0;
1324 			}
1325 			*htype = HASH_AlgMD5;
1326 			*prefix = p_md5;
1327 			*prefixlen = sizeof(p_md5);
1328 
1329 			break;
1330 #ifdef USE_ECDSA
1331 		case LDNS_ECDSAP256SHA256:
1332 			*pubkey = nss_buf2ecdsa(key, keylen,
1333 				LDNS_ECDSAP256SHA256);
1334 			if(!*pubkey) {
1335 				log_err("verify: malloc failure in crypto");
1336 				return 0;
1337 			}
1338 			*htype = HASH_AlgSHA256;
1339 			/* no prefix for DSA verification */
1340 			break;
1341 		case LDNS_ECDSAP384SHA384:
1342 			*pubkey = nss_buf2ecdsa(key, keylen,
1343 				LDNS_ECDSAP384SHA384);
1344 			if(!*pubkey) {
1345 				log_err("verify: malloc failure in crypto");
1346 				return 0;
1347 			}
1348 			*htype = HASH_AlgSHA384;
1349 			/* no prefix for DSA verification */
1350 			break;
1351 #endif /* USE_ECDSA */
1352 		case LDNS_ECC_GOST:
1353 		default:
1354 			verbose(VERB_QUERY, "verify: unknown algorithm %d",
1355 				algo);
1356 			return 0;
1357 	}
1358 	return 1;
1359 }
1360 
1361 /**
1362  * Check a canonical sig+rrset and signature against a dnskey
1363  * @param buf: buffer with data to verify, the first rrsig part and the
1364  *	canonicalized rrset.
1365  * @param algo: DNSKEY algorithm.
1366  * @param sigblock: signature rdata field from RRSIG
1367  * @param sigblock_len: length of sigblock data.
1368  * @param key: public key data from DNSKEY RR.
1369  * @param keylen: length of keydata.
1370  * @param reason: bogus reason in more detail.
1371  * @return secure if verification succeeded, bogus on crypto failure,
1372  *	unchecked on format errors and alloc failures.
1373  */
1374 enum sec_status
1375 verify_canonrrset(sldns_buffer* buf, int algo, unsigned char* sigblock,
1376 	unsigned int sigblock_len, unsigned char* key, unsigned int keylen,
1377 	char** reason)
1378 {
1379 	/* uses libNSS */
1380 	/* large enough for the different hashes */
1381 	unsigned char hash[HASH_LENGTH_MAX];
1382 	unsigned char hash2[HASH_LENGTH_MAX*2];
1383 	HASH_HashType htype = 0;
1384 	SECKEYPublicKey* pubkey = NULL;
1385 	SECItem secsig = {siBuffer, sigblock, sigblock_len};
1386 	SECItem sechash = {siBuffer, hash, 0};
1387 	SECStatus res;
1388 	unsigned char* prefix = NULL; /* prefix for hash, RFC3110, RFC5702 */
1389 	size_t prefixlen = 0;
1390 	int err;
1391 
1392 	if(!nss_setup_key_digest(algo, &pubkey, &htype, key, keylen,
1393 		&prefix, &prefixlen)) {
1394 		verbose(VERB_QUERY, "verify: failed to setup key");
1395 		*reason = "use of key for crypto failed";
1396 		SECKEY_DestroyPublicKey(pubkey);
1397 		return sec_status_bogus;
1398 	}
1399 
1400 #if defined(USE_DSA) && defined(USE_SHA1)
1401 	/* need to convert DSA, ECDSA signatures? */
1402 	if((algo == LDNS_DSA || algo == LDNS_DSA_NSEC3)) {
1403 		if(sigblock_len == 1+2*SHA1_LENGTH) {
1404 			secsig.data ++;
1405 			secsig.len --;
1406 		} else {
1407 			SECItem* p = DSAU_DecodeDerSig(&secsig);
1408 			if(!p) {
1409 				verbose(VERB_QUERY, "verify: failed DER decode");
1410 				*reason = "signature DER decode failed";
1411 				SECKEY_DestroyPublicKey(pubkey);
1412 				return sec_status_bogus;
1413 			}
1414 			if(SECITEM_CopyItem(pubkey->arena, &secsig, p)) {
1415 				log_err("alloc failure in DER decode");
1416 				SECKEY_DestroyPublicKey(pubkey);
1417 				SECITEM_FreeItem(p, PR_TRUE);
1418 				return sec_status_unchecked;
1419 			}
1420 			SECITEM_FreeItem(p, PR_TRUE);
1421 		}
1422 	}
1423 #endif /* USE_DSA */
1424 
1425 	/* do the signature cryptography work */
1426 	/* hash the data */
1427 	sechash.len = HASH_ResultLen(htype);
1428 	if(sechash.len > sizeof(hash)) {
1429 		verbose(VERB_QUERY, "verify: hash too large for buffer");
1430 		SECKEY_DestroyPublicKey(pubkey);
1431 		return sec_status_unchecked;
1432 	}
1433 	if(HASH_HashBuf(htype, hash, (unsigned char*)sldns_buffer_begin(buf),
1434 		(unsigned int)sldns_buffer_limit(buf)) != SECSuccess) {
1435 		verbose(VERB_QUERY, "verify: HASH_HashBuf failed");
1436 		SECKEY_DestroyPublicKey(pubkey);
1437 		return sec_status_unchecked;
1438 	}
1439 	if(prefix) {
1440 		int hashlen = sechash.len;
1441 		if(prefixlen+hashlen > sizeof(hash2)) {
1442 			verbose(VERB_QUERY, "verify: hashprefix too large");
1443 			SECKEY_DestroyPublicKey(pubkey);
1444 			return sec_status_unchecked;
1445 		}
1446 		sechash.data = hash2;
1447 		sechash.len = prefixlen+hashlen;
1448 		memcpy(sechash.data, prefix, prefixlen);
1449 		memmove(sechash.data+prefixlen, hash, hashlen);
1450 	}
1451 
1452 	/* verify the signature */
1453 	res = PK11_Verify(pubkey, &secsig, &sechash, NULL /*wincx*/);
1454 	SECKEY_DestroyPublicKey(pubkey);
1455 
1456 	if(res == SECSuccess) {
1457 		return sec_status_secure;
1458 	}
1459 	err = PORT_GetError();
1460 	if(err != SEC_ERROR_BAD_SIGNATURE) {
1461 		/* failed to verify */
1462 		verbose(VERB_QUERY, "verify: PK11_Verify failed: %s",
1463 			PORT_ErrorToString(err));
1464 		/* if it is not supported, like ECC is removed, we get,
1465 		 * SEC_ERROR_NO_MODULE */
1466 		if(err == SEC_ERROR_NO_MODULE)
1467 			return sec_status_unchecked;
1468 		/* but other errors are commonly returned
1469 		 * for a bad signature from NSS.  Thus we return bogus,
1470 		 * not unchecked */
1471 		*reason = "signature crypto failed";
1472 		return sec_status_bogus;
1473 	}
1474 	verbose(VERB_QUERY, "verify: signature mismatch: %s",
1475 		PORT_ErrorToString(err));
1476 	*reason = "signature crypto failed";
1477 	return sec_status_bogus;
1478 }
1479 
1480 #elif defined(HAVE_NETTLE)
1481 
1482 #include "sha.h"
1483 #include "bignum.h"
1484 #include "macros.h"
1485 #include "rsa.h"
1486 #include "dsa.h"
1487 #ifdef HAVE_NETTLE_DSA_COMPAT_H
1488 #include "dsa-compat.h"
1489 #endif
1490 #include "asn1.h"
1491 #ifdef USE_ECDSA
1492 #include "ecdsa.h"
1493 #include "ecc-curve.h"
1494 #endif
1495 #ifdef HAVE_NETTLE_EDDSA_H
1496 #include "eddsa.h"
1497 #endif
1498 
1499 static int
1500 _digest_nettle(int algo, uint8_t* buf, size_t len,
1501 	unsigned char* res)
1502 {
1503 	switch(algo) {
1504 		case SHA1_DIGEST_SIZE:
1505 		{
1506 			struct sha1_ctx ctx;
1507 			sha1_init(&ctx);
1508 			sha1_update(&ctx, len, buf);
1509 			sha1_digest(&ctx, SHA1_DIGEST_SIZE, res);
1510 			return 1;
1511 		}
1512 		case SHA256_DIGEST_SIZE:
1513 		{
1514 			struct sha256_ctx ctx;
1515 			sha256_init(&ctx);
1516 			sha256_update(&ctx, len, buf);
1517 			sha256_digest(&ctx, SHA256_DIGEST_SIZE, res);
1518 			return 1;
1519 		}
1520 		case SHA384_DIGEST_SIZE:
1521 		{
1522 			struct sha384_ctx ctx;
1523 			sha384_init(&ctx);
1524 			sha384_update(&ctx, len, buf);
1525 			sha384_digest(&ctx, SHA384_DIGEST_SIZE, res);
1526 			return 1;
1527 		}
1528 		case SHA512_DIGEST_SIZE:
1529 		{
1530 			struct sha512_ctx ctx;
1531 			sha512_init(&ctx);
1532 			sha512_update(&ctx, len, buf);
1533 			sha512_digest(&ctx, SHA512_DIGEST_SIZE, res);
1534 			return 1;
1535 		}
1536 		default:
1537 			break;
1538 	}
1539 	return 0;
1540 }
1541 
1542 /* return size of digest if supported, or 0 otherwise */
1543 size_t
1544 nsec3_hash_algo_size_supported(int id)
1545 {
1546 	switch(id) {
1547 	case NSEC3_HASH_SHA1:
1548 		return SHA1_DIGEST_SIZE;
1549 	default:
1550 		return 0;
1551 	}
1552 }
1553 
1554 /* perform nsec3 hash. return false on failure */
1555 int
1556 secalgo_nsec3_hash(int algo, unsigned char* buf, size_t len,
1557         unsigned char* res)
1558 {
1559 	switch(algo) {
1560 	case NSEC3_HASH_SHA1:
1561 		return _digest_nettle(SHA1_DIGEST_SIZE, (uint8_t*)buf, len,
1562 			res);
1563 	default:
1564 		return 0;
1565 	}
1566 }
1567 
1568 void
1569 secalgo_hash_sha256(unsigned char* buf, size_t len, unsigned char* res)
1570 {
1571 	_digest_nettle(SHA256_DIGEST_SIZE, (uint8_t*)buf, len, res);
1572 }
1573 
1574 /** secalgo hash structure */
1575 struct secalgo_hash {
1576 	/** if it is 384 or 512 */
1577 	int active;
1578 	/** context for sha384 */
1579 	struct sha384_ctx ctx384;
1580 	/** context for sha512 */
1581 	struct sha512_ctx ctx512;
1582 };
1583 
1584 struct secalgo_hash* secalgo_hash_create_sha384(void)
1585 {
1586 	struct secalgo_hash* h = calloc(1, sizeof(*h));
1587 	if(!h)
1588 		return NULL;
1589 	h->active = 384;
1590 	sha384_init(&h->ctx384);
1591 	return h;
1592 }
1593 
1594 struct secalgo_hash* secalgo_hash_create_sha512(void)
1595 {
1596 	struct secalgo_hash* h = calloc(1, sizeof(*h));
1597 	if(!h)
1598 		return NULL;
1599 	h->active = 512;
1600 	sha512_init(&h->ctx512);
1601 	return h;
1602 }
1603 
1604 int secalgo_hash_update(struct secalgo_hash* hash, uint8_t* data, size_t len)
1605 {
1606 	if(hash->active == 384) {
1607 		sha384_update(&hash->ctx384, len, data);
1608 	} else if(hash->active == 512) {
1609 		sha512_update(&hash->ctx512, len, data);
1610 	} else {
1611 		return 0;
1612 	}
1613 	return 1;
1614 }
1615 
1616 int secalgo_hash_final(struct secalgo_hash* hash, uint8_t* result,
1617         size_t maxlen, size_t* resultlen)
1618 {
1619 	if(hash->active == 384) {
1620 		if(SHA384_DIGEST_SIZE > maxlen) {
1621 			*resultlen = 0;
1622 			log_err("secalgo_hash_final: hash buffer too small");
1623 			return 0;
1624 		}
1625 		*resultlen = SHA384_DIGEST_SIZE;
1626 		sha384_digest(&hash->ctx384, SHA384_DIGEST_SIZE,
1627 			(unsigned char*)result);
1628 	} else if(hash->active == 512) {
1629 		if(SHA512_DIGEST_SIZE > maxlen) {
1630 			*resultlen = 0;
1631 			log_err("secalgo_hash_final: hash buffer too small");
1632 			return 0;
1633 		}
1634 		*resultlen = SHA512_DIGEST_SIZE;
1635 		sha512_digest(&hash->ctx512, SHA512_DIGEST_SIZE,
1636 			(unsigned char*)result);
1637 	} else {
1638 		*resultlen = 0;
1639 		return 0;
1640 	}
1641 	return 1;
1642 }
1643 
1644 void secalgo_hash_delete(struct secalgo_hash* hash)
1645 {
1646 	if(!hash) return;
1647 	free(hash);
1648 }
1649 
1650 /**
1651  * Return size of DS digest according to its hash algorithm.
1652  * @param algo: DS digest algo.
1653  * @return size in bytes of digest, or 0 if not supported.
1654  */
1655 size_t
1656 ds_digest_size_supported(int algo)
1657 {
1658 	switch(algo) {
1659 		case LDNS_SHA1:
1660 #ifdef USE_SHA1
1661 			return SHA1_DIGEST_SIZE;
1662 #else
1663 			if(fake_sha1) return 20;
1664 			return 0;
1665 #endif
1666 #ifdef USE_SHA2
1667 		case LDNS_SHA256:
1668 			return SHA256_DIGEST_SIZE;
1669 #endif
1670 #ifdef USE_ECDSA
1671 		case LDNS_SHA384:
1672 			return SHA384_DIGEST_SIZE;
1673 #endif
1674 		/* GOST not supported */
1675 		case LDNS_HASH_GOST:
1676 		default:
1677 			break;
1678 	}
1679 	return 0;
1680 }
1681 
1682 int
1683 secalgo_ds_digest(int algo, unsigned char* buf, size_t len,
1684 	unsigned char* res)
1685 {
1686 	switch(algo) {
1687 #ifdef USE_SHA1
1688 		case LDNS_SHA1:
1689 			return _digest_nettle(SHA1_DIGEST_SIZE, buf, len, res);
1690 #endif
1691 #if defined(USE_SHA2)
1692 		case LDNS_SHA256:
1693 			return _digest_nettle(SHA256_DIGEST_SIZE, buf, len, res);
1694 #endif
1695 #ifdef USE_ECDSA
1696 		case LDNS_SHA384:
1697 			return _digest_nettle(SHA384_DIGEST_SIZE, buf, len, res);
1698 
1699 #endif
1700 		case LDNS_HASH_GOST:
1701 		default:
1702 			verbose(VERB_QUERY, "unknown DS digest algorithm %d",
1703 				algo);
1704 			break;
1705 	}
1706 	return 0;
1707 }
1708 
1709 int
1710 dnskey_algo_id_is_supported(int id)
1711 {
1712 	/* uses libnettle */
1713 	switch(id) {
1714 	case LDNS_DSA:
1715 	case LDNS_DSA_NSEC3:
1716 #if defined(USE_DSA) && defined(USE_SHA1)
1717 		return 1;
1718 #else
1719 		if(fake_dsa || fake_sha1) return 1;
1720 		return 0;
1721 #endif
1722 	case LDNS_RSASHA1:
1723 	case LDNS_RSASHA1_NSEC3:
1724 #ifdef USE_SHA1
1725 		return 1;
1726 #else
1727 		if(fake_sha1) return 1;
1728 		return 0;
1729 #endif
1730 #ifdef USE_SHA2
1731 	case LDNS_RSASHA256:
1732 	case LDNS_RSASHA512:
1733 #endif
1734 #ifdef USE_ECDSA
1735 	case LDNS_ECDSAP256SHA256:
1736 	case LDNS_ECDSAP384SHA384:
1737 #endif
1738 		return 1;
1739 #ifdef USE_ED25519
1740 	case LDNS_ED25519:
1741 		return 1;
1742 #endif
1743 	case LDNS_RSAMD5: /* RFC 6725 deprecates RSAMD5 */
1744 	case LDNS_ECC_GOST:
1745 	default:
1746 		return 0;
1747 	}
1748 }
1749 
1750 #if defined(USE_DSA) && defined(USE_SHA1)
1751 static char *
1752 _verify_nettle_dsa(sldns_buffer* buf, unsigned char* sigblock,
1753 	unsigned int sigblock_len, unsigned char* key, unsigned int keylen)
1754 {
1755 	uint8_t digest[SHA1_DIGEST_SIZE];
1756 	uint8_t key_t_value;
1757 	int res = 0;
1758 	size_t offset;
1759 	struct dsa_public_key pubkey;
1760 	struct dsa_signature signature;
1761 	unsigned int expected_len;
1762 
1763 	/* Extract DSA signature from the record */
1764 	nettle_dsa_signature_init(&signature);
1765 	/* Signature length: 41 bytes - RFC 2536 sec. 3 */
1766 	if(sigblock_len == 41) {
1767 		if(key[0] != sigblock[0])
1768 			return "invalid T value in DSA signature or pubkey";
1769 		nettle_mpz_set_str_256_u(signature.r, 20, sigblock+1);
1770 		nettle_mpz_set_str_256_u(signature.s, 20, sigblock+1+20);
1771 	} else {
1772 		/* DER encoded, decode the ASN1 notated R and S bignums */
1773 		/* SEQUENCE { r INTEGER, s INTEGER } */
1774 		struct asn1_der_iterator i, seq;
1775 		if(asn1_der_iterator_first(&i, sigblock_len,
1776 			(uint8_t*)sigblock) != ASN1_ITERATOR_CONSTRUCTED
1777 			|| i.type != ASN1_SEQUENCE)
1778 			return "malformed DER encoded DSA signature";
1779 		/* decode this element of i using the seq iterator */
1780 		if(asn1_der_decode_constructed(&i, &seq) !=
1781 			ASN1_ITERATOR_PRIMITIVE || seq.type != ASN1_INTEGER)
1782 			return "malformed DER encoded DSA signature";
1783 		if(!asn1_der_get_bignum(&seq, signature.r, 20*8))
1784 			return "malformed DER encoded DSA signature";
1785 		if(asn1_der_iterator_next(&seq) != ASN1_ITERATOR_PRIMITIVE
1786 			|| seq.type != ASN1_INTEGER)
1787 			return "malformed DER encoded DSA signature";
1788 		if(!asn1_der_get_bignum(&seq, signature.s, 20*8))
1789 			return "malformed DER encoded DSA signature";
1790 		if(asn1_der_iterator_next(&i) != ASN1_ITERATOR_END)
1791 			return "malformed DER encoded DSA signature";
1792 	}
1793 
1794 	/* Validate T values constraints - RFC 2536 sec. 2 & sec. 3 */
1795 	key_t_value = key[0];
1796 	if (key_t_value > 8) {
1797 		return "invalid T value in DSA pubkey";
1798 	}
1799 
1800 	/* Pubkey minimum length: 21 bytes - RFC 2536 sec. 2 */
1801 	if (keylen < 21) {
1802 		return "DSA pubkey too short";
1803 	}
1804 
1805 	expected_len =   1 +		/* T */
1806 		        20 +		/* Q */
1807 		       (64 + key_t_value*8) +	/* P */
1808 		       (64 + key_t_value*8) +	/* G */
1809 		       (64 + key_t_value*8);	/* Y */
1810 	if (keylen != expected_len ) {
1811 		return "invalid DSA pubkey length";
1812 	}
1813 
1814 	/* Extract DSA pubkey from the record */
1815 	nettle_dsa_public_key_init(&pubkey);
1816 	offset = 1;
1817 	nettle_mpz_set_str_256_u(pubkey.q, 20, key+offset);
1818 	offset += 20;
1819 	nettle_mpz_set_str_256_u(pubkey.p, (64 + key_t_value*8), key+offset);
1820 	offset += (64 + key_t_value*8);
1821 	nettle_mpz_set_str_256_u(pubkey.g, (64 + key_t_value*8), key+offset);
1822 	offset += (64 + key_t_value*8);
1823 	nettle_mpz_set_str_256_u(pubkey.y, (64 + key_t_value*8), key+offset);
1824 
1825 	/* Digest content of "buf" and verify its DSA signature in "sigblock"*/
1826 	res = _digest_nettle(SHA1_DIGEST_SIZE, (unsigned char*)sldns_buffer_begin(buf),
1827 						(unsigned int)sldns_buffer_limit(buf), (unsigned char*)digest);
1828 	res &= dsa_sha1_verify_digest(&pubkey, digest, &signature);
1829 
1830 	/* Clear and return */
1831 	nettle_dsa_signature_clear(&signature);
1832 	nettle_dsa_public_key_clear(&pubkey);
1833 	if (!res)
1834 		return "DSA signature verification failed";
1835 	else
1836 		return NULL;
1837 }
1838 #endif /* USE_DSA */
1839 
1840 static char *
1841 _verify_nettle_rsa(sldns_buffer* buf, unsigned int digest_size, char* sigblock,
1842 	unsigned int sigblock_len, uint8_t* key, unsigned int keylen)
1843 {
1844 	uint16_t exp_len = 0;
1845 	size_t exp_offset = 0, mod_offset = 0;
1846 	struct rsa_public_key pubkey;
1847 	mpz_t signature;
1848 	int res = 0;
1849 
1850 	/* RSA pubkey parsing as per RFC 3110 sec. 2 */
1851 	if( keylen <= 1) {
1852 		return "null RSA key";
1853 	}
1854 	if (key[0] != 0) {
1855 		/* 1-byte length */
1856 		exp_len = key[0];
1857 		exp_offset = 1;
1858 	} else {
1859 		/* 1-byte NUL + 2-bytes exponent length */
1860 		if (keylen < 3) {
1861 			return "incorrect RSA key length";
1862 		}
1863 		exp_len = READ_UINT16(key+1);
1864 		if (exp_len == 0)
1865 			return "null RSA exponent length";
1866 		exp_offset = 3;
1867 	}
1868 	/* Check that we are not over-running input length */
1869 	if (keylen < exp_offset + exp_len + 1) {
1870 		return "RSA key content shorter than expected";
1871 	}
1872 	mod_offset = exp_offset + exp_len;
1873 	nettle_rsa_public_key_init(&pubkey);
1874 	pubkey.size = keylen - mod_offset;
1875 	nettle_mpz_set_str_256_u(pubkey.e, exp_len, &key[exp_offset]);
1876 	nettle_mpz_set_str_256_u(pubkey.n, pubkey.size, &key[mod_offset]);
1877 
1878 	/* Digest content of "buf" and verify its RSA signature in "sigblock"*/
1879 	nettle_mpz_init_set_str_256_u(signature, sigblock_len, (uint8_t*)sigblock);
1880 	switch (digest_size) {
1881 		case SHA1_DIGEST_SIZE:
1882 		{
1883 			uint8_t digest[SHA1_DIGEST_SIZE];
1884 			res = _digest_nettle(SHA1_DIGEST_SIZE, (unsigned char*)sldns_buffer_begin(buf),
1885 						(unsigned int)sldns_buffer_limit(buf), (unsigned char*)digest);
1886 			res &= rsa_sha1_verify_digest(&pubkey, digest, signature);
1887 			break;
1888 		}
1889 		case SHA256_DIGEST_SIZE:
1890 		{
1891 			uint8_t digest[SHA256_DIGEST_SIZE];
1892 			res = _digest_nettle(SHA256_DIGEST_SIZE, (unsigned char*)sldns_buffer_begin(buf),
1893 						(unsigned int)sldns_buffer_limit(buf), (unsigned char*)digest);
1894 			res &= rsa_sha256_verify_digest(&pubkey, digest, signature);
1895 			break;
1896 		}
1897 		case SHA512_DIGEST_SIZE:
1898 		{
1899 			uint8_t digest[SHA512_DIGEST_SIZE];
1900 			res = _digest_nettle(SHA512_DIGEST_SIZE, (unsigned char*)sldns_buffer_begin(buf),
1901 						(unsigned int)sldns_buffer_limit(buf), (unsigned char*)digest);
1902 			res &= rsa_sha512_verify_digest(&pubkey, digest, signature);
1903 			break;
1904 		}
1905 		default:
1906 			break;
1907 	}
1908 
1909 	/* Clear and return */
1910 	nettle_rsa_public_key_clear(&pubkey);
1911 	mpz_clear(signature);
1912 	if (!res) {
1913 		return "RSA signature verification failed";
1914 	} else {
1915 		return NULL;
1916 	}
1917 }
1918 
1919 #ifdef USE_ECDSA
1920 static char *
1921 _verify_nettle_ecdsa(sldns_buffer* buf, unsigned int digest_size, unsigned char* sigblock,
1922 	unsigned int sigblock_len, unsigned char* key, unsigned int keylen)
1923 {
1924 	int res = 0;
1925 	struct ecc_point pubkey;
1926 	struct dsa_signature signature;
1927 
1928 	/* Always matched strength, as per RFC 6605 sec. 1 */
1929 	if (sigblock_len != 2*digest_size || keylen != 2*digest_size) {
1930 		return "wrong ECDSA signature length";
1931 	}
1932 
1933 	/* Parse ECDSA signature as per RFC 6605 sec. 4 */
1934 	nettle_dsa_signature_init(&signature);
1935 	switch (digest_size) {
1936 		case SHA256_DIGEST_SIZE:
1937 		{
1938 			uint8_t digest[SHA256_DIGEST_SIZE];
1939 			mpz_t x, y;
1940 			nettle_ecc_point_init(&pubkey, nettle_get_secp_256r1());
1941 			nettle_mpz_init_set_str_256_u(x, SHA256_DIGEST_SIZE, key);
1942 			nettle_mpz_init_set_str_256_u(y, SHA256_DIGEST_SIZE, key+SHA256_DIGEST_SIZE);
1943 			nettle_mpz_set_str_256_u(signature.r, SHA256_DIGEST_SIZE, sigblock);
1944 			nettle_mpz_set_str_256_u(signature.s, SHA256_DIGEST_SIZE, sigblock+SHA256_DIGEST_SIZE);
1945 			res = _digest_nettle(SHA256_DIGEST_SIZE, (unsigned char*)sldns_buffer_begin(buf),
1946 						(unsigned int)sldns_buffer_limit(buf), (unsigned char*)digest);
1947 			res &= nettle_ecc_point_set(&pubkey, x, y);
1948 			res &= nettle_ecdsa_verify (&pubkey, SHA256_DIGEST_SIZE, digest, &signature);
1949 			mpz_clear(x);
1950 			mpz_clear(y);
1951 			nettle_ecc_point_clear(&pubkey);
1952 			break;
1953 		}
1954 		case SHA384_DIGEST_SIZE:
1955 		{
1956 			uint8_t digest[SHA384_DIGEST_SIZE];
1957 			mpz_t x, y;
1958 			nettle_ecc_point_init(&pubkey, nettle_get_secp_384r1());
1959 			nettle_mpz_init_set_str_256_u(x, SHA384_DIGEST_SIZE, key);
1960 			nettle_mpz_init_set_str_256_u(y, SHA384_DIGEST_SIZE, key+SHA384_DIGEST_SIZE);
1961 			nettle_mpz_set_str_256_u(signature.r, SHA384_DIGEST_SIZE, sigblock);
1962 			nettle_mpz_set_str_256_u(signature.s, SHA384_DIGEST_SIZE, sigblock+SHA384_DIGEST_SIZE);
1963 			res = _digest_nettle(SHA384_DIGEST_SIZE, (unsigned char*)sldns_buffer_begin(buf),
1964 						(unsigned int)sldns_buffer_limit(buf), (unsigned char*)digest);
1965 			res &= nettle_ecc_point_set(&pubkey, x, y);
1966 			res &= nettle_ecdsa_verify (&pubkey, SHA384_DIGEST_SIZE, digest, &signature);
1967 			mpz_clear(x);
1968 			mpz_clear(y);
1969 			nettle_ecc_point_clear(&pubkey);
1970 			break;
1971 		}
1972 		default:
1973 			return "unknown ECDSA algorithm";
1974 	}
1975 
1976 	/* Clear and return */
1977 	nettle_dsa_signature_clear(&signature);
1978 	if (!res)
1979 		return "ECDSA signature verification failed";
1980 	else
1981 		return NULL;
1982 }
1983 #endif
1984 
1985 #ifdef USE_ED25519
1986 static char *
1987 _verify_nettle_ed25519(sldns_buffer* buf, unsigned char* sigblock,
1988 	unsigned int sigblock_len, unsigned char* key, unsigned int keylen)
1989 {
1990 	int res = 0;
1991 
1992 	if(sigblock_len != ED25519_SIGNATURE_SIZE) {
1993 		return "wrong ED25519 signature length";
1994 	}
1995 	if(keylen != ED25519_KEY_SIZE) {
1996 		return "wrong ED25519 key length";
1997 	}
1998 
1999 	res = ed25519_sha512_verify((uint8_t*)key, sldns_buffer_limit(buf),
2000 		sldns_buffer_begin(buf), (uint8_t*)sigblock);
2001 
2002 	if (!res)
2003 		return "ED25519 signature verification failed";
2004 	else
2005 		return NULL;
2006 }
2007 #endif
2008 
2009 /**
2010  * Check a canonical sig+rrset and signature against a dnskey
2011  * @param buf: buffer with data to verify, the first rrsig part and the
2012  *	canonicalized rrset.
2013  * @param algo: DNSKEY algorithm.
2014  * @param sigblock: signature rdata field from RRSIG
2015  * @param sigblock_len: length of sigblock data.
2016  * @param key: public key data from DNSKEY RR.
2017  * @param keylen: length of keydata.
2018  * @param reason: bogus reason in more detail.
2019  * @return secure if verification succeeded, bogus on crypto failure,
2020  *	unchecked on format errors and alloc failures.
2021  */
2022 enum sec_status
2023 verify_canonrrset(sldns_buffer* buf, int algo, unsigned char* sigblock,
2024 	unsigned int sigblock_len, unsigned char* key, unsigned int keylen,
2025 	char** reason)
2026 {
2027 	unsigned int digest_size = 0;
2028 
2029 	if (sigblock_len == 0 || keylen == 0) {
2030 		*reason = "null signature";
2031 		return sec_status_bogus;
2032 	}
2033 
2034 #ifndef USE_DSA
2035 	if((algo == LDNS_DSA || algo == LDNS_DSA_NSEC3) &&(fake_dsa||fake_sha1))
2036 		return sec_status_secure;
2037 #endif
2038 #ifndef USE_SHA1
2039 	if(fake_sha1 && (algo == LDNS_DSA || algo == LDNS_DSA_NSEC3 || algo == LDNS_RSASHA1 || algo == LDNS_RSASHA1_NSEC3))
2040 		return sec_status_secure;
2041 #endif
2042 
2043 	switch(algo) {
2044 #if defined(USE_DSA) && defined(USE_SHA1)
2045 	case LDNS_DSA:
2046 	case LDNS_DSA_NSEC3:
2047 		*reason = _verify_nettle_dsa(buf, sigblock, sigblock_len, key, keylen);
2048 		if (*reason != NULL)
2049 			return sec_status_bogus;
2050 		else
2051 			return sec_status_secure;
2052 #endif /* USE_DSA */
2053 
2054 #ifdef USE_SHA1
2055 	case LDNS_RSASHA1:
2056 	case LDNS_RSASHA1_NSEC3:
2057 		digest_size = (digest_size ? digest_size : SHA1_DIGEST_SIZE);
2058 #endif
2059 		/* double fallthrough annotation to please gcc parser */
2060 		/* fallthrough */
2061 #ifdef USE_SHA2
2062 		/* fallthrough */
2063 	case LDNS_RSASHA256:
2064 		digest_size = (digest_size ? digest_size : SHA256_DIGEST_SIZE);
2065 		/* fallthrough */
2066 	case LDNS_RSASHA512:
2067 		digest_size = (digest_size ? digest_size : SHA512_DIGEST_SIZE);
2068 
2069 #endif
2070 		*reason = _verify_nettle_rsa(buf, digest_size, (char*)sigblock,
2071 						sigblock_len, key, keylen);
2072 		if (*reason != NULL)
2073 			return sec_status_bogus;
2074 		else
2075 			return sec_status_secure;
2076 
2077 #ifdef USE_ECDSA
2078 	case LDNS_ECDSAP256SHA256:
2079 		digest_size = (digest_size ? digest_size : SHA256_DIGEST_SIZE);
2080 		/* fallthrough */
2081 	case LDNS_ECDSAP384SHA384:
2082 		digest_size = (digest_size ? digest_size : SHA384_DIGEST_SIZE);
2083 		*reason = _verify_nettle_ecdsa(buf, digest_size, sigblock,
2084 						sigblock_len, key, keylen);
2085 		if (*reason != NULL)
2086 			return sec_status_bogus;
2087 		else
2088 			return sec_status_secure;
2089 #endif
2090 #ifdef USE_ED25519
2091 	case LDNS_ED25519:
2092 		*reason = _verify_nettle_ed25519(buf, sigblock, sigblock_len,
2093 			key, keylen);
2094 		if (*reason != NULL)
2095 			return sec_status_bogus;
2096 		else
2097 			return sec_status_secure;
2098 #endif
2099 	case LDNS_RSAMD5:
2100 	case LDNS_ECC_GOST:
2101 	default:
2102 		*reason = "unable to verify signature, unknown algorithm";
2103 		return sec_status_bogus;
2104 	}
2105 }
2106 
2107 #endif /* HAVE_SSL or HAVE_NSS or HAVE_NETTLE */
2108