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