xref: /netbsd-src/external/mpl/bind/dist/lib/dns/opensslrsa_link.c (revision cef8759bd76c1b621f8eab8faa6f208faabc2e15)
1 /*	$NetBSD: opensslrsa_link.c,v 1.7 2020/05/24 19:46:23 christos Exp $	*/
2 
3 /*
4  * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
5  *
6  * This Source Code Form is subject to the terms of the Mozilla Public
7  * License, v. 2.0. If a copy of the MPL was not distributed with this
8  * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9  *
10  * See the COPYRIGHT file distributed with this work for additional
11  * information regarding copyright ownership.
12  */
13 
14 #if !USE_PKCS11
15 
16 #include <inttypes.h>
17 #include <stdbool.h>
18 
19 #include <openssl/bn.h>
20 #include <openssl/err.h>
21 #include <openssl/objects.h>
22 #include <openssl/rsa.h>
23 
24 #include <isc/mem.h>
25 #include <isc/safe.h>
26 #include <isc/string.h>
27 #include <isc/util.h>
28 
29 #include <pk11/site.h>
30 
31 #include <dst/result.h>
32 
33 #include "dst_internal.h"
34 #include "dst_openssl.h"
35 #include "dst_parse.h"
36 #if !defined(OPENSSL_NO_ENGINE)
37 #include <openssl/engine.h>
38 #endif /* if !defined(OPENSSL_NO_ENGINE) */
39 
40 /*
41  * Limit the size of public exponents.
42  */
43 #ifndef RSA_MAX_PUBEXP_BITS
44 #define RSA_MAX_PUBEXP_BITS 35
45 #endif /* ifndef RSA_MAX_PUBEXP_BITS */
46 
47 /*
48  * We don't use configure for windows so enforce the OpenSSL version
49  * here.  Unlike with configure we don't support overriding this test.
50  */
51 #if defined(WIN32) && (OPENSSL_VERSION_NUMBER < 0x10000000L)
52 #error Please upgrade OpenSSL to 1.0.0 or greater.
53 #endif /* if defined(WIN32) && (OPENSSL_VERSION_NUMBER < 0x10000000L) */
54 
55 #define DST_RET(a)        \
56 	{                 \
57 		ret = a;  \
58 		goto err; \
59 	}
60 
61 #if !HAVE_RSA_SET0_KEY
62 /* From OpenSSL 1.1.0 */
63 static int
64 RSA_set0_key(RSA *r, BIGNUM *n, BIGNUM *e, BIGNUM *d) {
65 	/*
66 	 * If the fields n and e in r are NULL, the corresponding input
67 	 * parameters MUST be non-NULL for n and e.  d may be
68 	 * left NULL (in case only the public key is used).
69 	 */
70 	if ((r->n == NULL && n == NULL) || (r->e == NULL && e == NULL)) {
71 		return (0);
72 	}
73 
74 	if (n != NULL) {
75 		BN_free(r->n);
76 		r->n = n;
77 	}
78 	if (e != NULL) {
79 		BN_free(r->e);
80 		r->e = e;
81 	}
82 	if (d != NULL) {
83 		BN_free(r->d);
84 		r->d = d;
85 	}
86 
87 	return (1);
88 }
89 
90 static int
91 RSA_set0_factors(RSA *r, BIGNUM *p, BIGNUM *q) {
92 	/*
93 	 * If the fields p and q in r are NULL, the corresponding input
94 	 * parameters MUST be non-NULL.
95 	 */
96 	if ((r->p == NULL && p == NULL) || (r->q == NULL && q == NULL)) {
97 		return (0);
98 	}
99 
100 	if (p != NULL) {
101 		BN_free(r->p);
102 		r->p = p;
103 	}
104 	if (q != NULL) {
105 		BN_free(r->q);
106 		r->q = q;
107 	}
108 
109 	return (1);
110 }
111 
112 static int
113 RSA_set0_crt_params(RSA *r, BIGNUM *dmp1, BIGNUM *dmq1, BIGNUM *iqmp) {
114 	/*
115 	 * If the fields dmp1, dmq1 and iqmp in r are NULL, the
116 	 * corresponding input parameters MUST be non-NULL.
117 	 */
118 	if ((r->dmp1 == NULL && dmp1 == NULL) ||
119 	    (r->dmq1 == NULL && dmq1 == NULL) ||
120 	    (r->iqmp == NULL && iqmp == NULL))
121 	{
122 		return (0);
123 	}
124 
125 	if (dmp1 != NULL) {
126 		BN_free(r->dmp1);
127 		r->dmp1 = dmp1;
128 	}
129 	if (dmq1 != NULL) {
130 		BN_free(r->dmq1);
131 		r->dmq1 = dmq1;
132 	}
133 	if (iqmp != NULL) {
134 		BN_free(r->iqmp);
135 		r->iqmp = iqmp;
136 	}
137 
138 	return (1);
139 }
140 
141 static void
142 RSA_get0_key(const RSA *r, const BIGNUM **n, const BIGNUM **e,
143 	     const BIGNUM **d) {
144 	if (n != NULL) {
145 		*n = r->n;
146 	}
147 	if (e != NULL) {
148 		*e = r->e;
149 	}
150 	if (d != NULL) {
151 		*d = r->d;
152 	}
153 }
154 
155 static void
156 RSA_get0_factors(const RSA *r, const BIGNUM **p, const BIGNUM **q) {
157 	if (p != NULL) {
158 		*p = r->p;
159 	}
160 	if (q != NULL) {
161 		*q = r->q;
162 	}
163 }
164 
165 static void
166 RSA_get0_crt_params(const RSA *r, const BIGNUM **dmp1, const BIGNUM **dmq1,
167 		    const BIGNUM **iqmp) {
168 	if (dmp1 != NULL) {
169 		*dmp1 = r->dmp1;
170 	}
171 	if (dmq1 != NULL) {
172 		*dmq1 = r->dmq1;
173 	}
174 	if (iqmp != NULL) {
175 		*iqmp = r->iqmp;
176 	}
177 }
178 
179 static int
180 RSA_test_flags(const RSA *r, int flags) {
181 	return (r->flags & flags);
182 }
183 
184 #endif /* !HAVE_RSA_SET0_KEY */
185 
186 static isc_result_t
187 opensslrsa_createctx(dst_key_t *key, dst_context_t *dctx) {
188 	EVP_MD_CTX *evp_md_ctx;
189 	const EVP_MD *type = NULL;
190 
191 	UNUSED(key);
192 	REQUIRE(dctx->key->key_alg == DST_ALG_RSASHA1 ||
193 		dctx->key->key_alg == DST_ALG_NSEC3RSASHA1 ||
194 		dctx->key->key_alg == DST_ALG_RSASHA256 ||
195 		dctx->key->key_alg == DST_ALG_RSASHA512);
196 
197 	/*
198 	 * Reject incorrect RSA key lengths.
199 	 */
200 	switch (dctx->key->key_alg) {
201 	case DST_ALG_RSASHA1:
202 	case DST_ALG_NSEC3RSASHA1:
203 		/* From RFC 3110 */
204 		if (dctx->key->key_size > 4096) {
205 			return (ISC_R_FAILURE);
206 		}
207 		break;
208 	case DST_ALG_RSASHA256:
209 		/* From RFC 5702 */
210 		if ((dctx->key->key_size < 512) || (dctx->key->key_size > 4096))
211 		{
212 			return (ISC_R_FAILURE);
213 		}
214 		break;
215 	case DST_ALG_RSASHA512:
216 		/* From RFC 5702 */
217 		if ((dctx->key->key_size < 1024) ||
218 		    (dctx->key->key_size > 4096)) {
219 			return (ISC_R_FAILURE);
220 		}
221 		break;
222 	default:
223 		INSIST(0);
224 		ISC_UNREACHABLE();
225 	}
226 
227 	evp_md_ctx = EVP_MD_CTX_create();
228 	if (evp_md_ctx == NULL) {
229 		return (ISC_R_NOMEMORY);
230 	}
231 
232 	switch (dctx->key->key_alg) {
233 	case DST_ALG_RSASHA1:
234 	case DST_ALG_NSEC3RSASHA1:
235 		type = EVP_sha1(); /* SHA1 + RSA */
236 		break;
237 	case DST_ALG_RSASHA256:
238 		type = EVP_sha256(); /* SHA256 + RSA */
239 		break;
240 	case DST_ALG_RSASHA512:
241 		type = EVP_sha512();
242 		break;
243 	default:
244 		INSIST(0);
245 		ISC_UNREACHABLE();
246 	}
247 
248 	if (!EVP_DigestInit_ex(evp_md_ctx, type, NULL)) {
249 		EVP_MD_CTX_destroy(evp_md_ctx);
250 		return (dst__openssl_toresult3(
251 			dctx->category, "EVP_DigestInit_ex", ISC_R_FAILURE));
252 	}
253 	dctx->ctxdata.evp_md_ctx = evp_md_ctx;
254 
255 	return (ISC_R_SUCCESS);
256 }
257 
258 static void
259 opensslrsa_destroyctx(dst_context_t *dctx) {
260 	EVP_MD_CTX *evp_md_ctx = dctx->ctxdata.evp_md_ctx;
261 
262 	REQUIRE(dctx->key->key_alg == DST_ALG_RSASHA1 ||
263 		dctx->key->key_alg == DST_ALG_NSEC3RSASHA1 ||
264 		dctx->key->key_alg == DST_ALG_RSASHA256 ||
265 		dctx->key->key_alg == DST_ALG_RSASHA512);
266 
267 	if (evp_md_ctx != NULL) {
268 		EVP_MD_CTX_destroy(evp_md_ctx);
269 		dctx->ctxdata.evp_md_ctx = NULL;
270 	}
271 }
272 
273 static isc_result_t
274 opensslrsa_adddata(dst_context_t *dctx, const isc_region_t *data) {
275 	EVP_MD_CTX *evp_md_ctx = dctx->ctxdata.evp_md_ctx;
276 
277 	REQUIRE(dctx->key->key_alg == DST_ALG_RSASHA1 ||
278 		dctx->key->key_alg == DST_ALG_NSEC3RSASHA1 ||
279 		dctx->key->key_alg == DST_ALG_RSASHA256 ||
280 		dctx->key->key_alg == DST_ALG_RSASHA512);
281 
282 	if (!EVP_DigestUpdate(evp_md_ctx, data->base, data->length)) {
283 		return (dst__openssl_toresult3(
284 			dctx->category, "EVP_DigestUpdate", ISC_R_FAILURE));
285 	}
286 	return (ISC_R_SUCCESS);
287 }
288 
289 static isc_result_t
290 opensslrsa_sign(dst_context_t *dctx, isc_buffer_t *sig) {
291 	dst_key_t *key = dctx->key;
292 	isc_region_t r;
293 	unsigned int siglen = 0;
294 	EVP_MD_CTX *evp_md_ctx = dctx->ctxdata.evp_md_ctx;
295 	EVP_PKEY *pkey = key->keydata.pkey;
296 
297 	REQUIRE(dctx->key->key_alg == DST_ALG_RSASHA1 ||
298 		dctx->key->key_alg == DST_ALG_NSEC3RSASHA1 ||
299 		dctx->key->key_alg == DST_ALG_RSASHA256 ||
300 		dctx->key->key_alg == DST_ALG_RSASHA512);
301 
302 	isc_buffer_availableregion(sig, &r);
303 
304 	if (r.length < (unsigned int)EVP_PKEY_size(pkey)) {
305 		return (ISC_R_NOSPACE);
306 	}
307 
308 	if (!EVP_SignFinal(evp_md_ctx, r.base, &siglen, pkey)) {
309 		return (dst__openssl_toresult3(dctx->category, "EVP_SignFinal",
310 					       ISC_R_FAILURE));
311 	}
312 
313 	isc_buffer_add(sig, siglen);
314 
315 	return (ISC_R_SUCCESS);
316 }
317 
318 static isc_result_t
319 opensslrsa_verify2(dst_context_t *dctx, int maxbits, const isc_region_t *sig) {
320 	dst_key_t *key = dctx->key;
321 	int status = 0;
322 	const BIGNUM *e = NULL;
323 	EVP_MD_CTX *evp_md_ctx = dctx->ctxdata.evp_md_ctx;
324 	EVP_PKEY *pkey = key->keydata.pkey;
325 	RSA *rsa;
326 	int bits;
327 
328 	REQUIRE(dctx->key->key_alg == DST_ALG_RSASHA1 ||
329 		dctx->key->key_alg == DST_ALG_NSEC3RSASHA1 ||
330 		dctx->key->key_alg == DST_ALG_RSASHA256 ||
331 		dctx->key->key_alg == DST_ALG_RSASHA512);
332 
333 	rsa = EVP_PKEY_get1_RSA(pkey);
334 	if (rsa == NULL) {
335 		return (dst__openssl_toresult(DST_R_OPENSSLFAILURE));
336 	}
337 	RSA_get0_key(rsa, NULL, &e, NULL);
338 	bits = BN_num_bits(e);
339 	RSA_free(rsa);
340 	if (bits > maxbits && maxbits != 0) {
341 		return (DST_R_VERIFYFAILURE);
342 	}
343 
344 	status = EVP_VerifyFinal(evp_md_ctx, sig->base, sig->length, pkey);
345 	switch (status) {
346 	case 1:
347 		return (ISC_R_SUCCESS);
348 	case 0:
349 		return (dst__openssl_toresult(DST_R_VERIFYFAILURE));
350 	default:
351 		return (dst__openssl_toresult3(dctx->category,
352 					       "EVP_VerifyFinal",
353 					       DST_R_VERIFYFAILURE));
354 	}
355 }
356 
357 static isc_result_t
358 opensslrsa_verify(dst_context_t *dctx, const isc_region_t *sig) {
359 	return (opensslrsa_verify2(dctx, 0, sig));
360 }
361 
362 static bool
363 opensslrsa_compare(const dst_key_t *key1, const dst_key_t *key2) {
364 	int status;
365 	RSA *rsa1 = NULL, *rsa2 = NULL;
366 	const BIGNUM *n1 = NULL, *n2 = NULL;
367 	const BIGNUM *e1 = NULL, *e2 = NULL;
368 	const BIGNUM *d1 = NULL, *d2 = NULL;
369 	const BIGNUM *p1 = NULL, *p2 = NULL;
370 	const BIGNUM *q1 = NULL, *q2 = NULL;
371 	EVP_PKEY *pkey1, *pkey2;
372 
373 	pkey1 = key1->keydata.pkey;
374 	pkey2 = key2->keydata.pkey;
375 	/*
376 	 * The pkey reference will keep these around after
377 	 * the RSA_free() call.
378 	 */
379 	if (pkey1 != NULL) {
380 		rsa1 = EVP_PKEY_get1_RSA(pkey1);
381 		RSA_free(rsa1);
382 	}
383 	if (pkey2 != NULL) {
384 		rsa2 = EVP_PKEY_get1_RSA(pkey2);
385 		RSA_free(rsa2);
386 	}
387 
388 	if (rsa1 == NULL && rsa2 == NULL) {
389 		return (true);
390 	} else if (rsa1 == NULL || rsa2 == NULL) {
391 		return (false);
392 	}
393 
394 	RSA_get0_key(rsa1, &n1, &e1, &d1);
395 	RSA_get0_key(rsa2, &n2, &e2, &d2);
396 	status = BN_cmp(n1, n2) || BN_cmp(e1, e2);
397 
398 	if (status != 0) {
399 		return (false);
400 	}
401 
402 	if (RSA_test_flags(rsa1, RSA_FLAG_EXT_PKEY) != 0 ||
403 	    RSA_test_flags(rsa2, RSA_FLAG_EXT_PKEY) != 0)
404 	{
405 		if (RSA_test_flags(rsa1, RSA_FLAG_EXT_PKEY) == 0 ||
406 		    RSA_test_flags(rsa2, RSA_FLAG_EXT_PKEY) == 0)
407 		{
408 			return (false);
409 		}
410 		/*
411 		 * Can't compare private parameters, BTW does it make sense?
412 		 */
413 		return (true);
414 	}
415 
416 	if (d1 != NULL || d2 != NULL) {
417 		if (d1 == NULL || d2 == NULL) {
418 			return (false);
419 		}
420 		RSA_get0_factors(rsa1, &p1, &q1);
421 		RSA_get0_factors(rsa2, &p2, &q2);
422 		status = BN_cmp(d1, d2) || BN_cmp(p1, p1) || BN_cmp(q1, q2);
423 
424 		if (status != 0) {
425 			return (false);
426 		}
427 	}
428 	return (true);
429 }
430 
431 static int
432 progress_cb(int p, int n, BN_GENCB *cb) {
433 	union {
434 		void *dptr;
435 		void (*fptr)(int);
436 	} u;
437 
438 	UNUSED(n);
439 
440 	u.dptr = BN_GENCB_get_arg(cb);
441 	if (u.fptr != NULL) {
442 		u.fptr(p);
443 	}
444 	return (1);
445 }
446 
447 static isc_result_t
448 opensslrsa_generate(dst_key_t *key, int exp, void (*callback)(int)) {
449 	isc_result_t ret = DST_R_OPENSSLFAILURE;
450 	union {
451 		void *dptr;
452 		void (*fptr)(int);
453 	} u;
454 	RSA *rsa = RSA_new();
455 	BIGNUM *e = BN_new();
456 #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
457 	BN_GENCB _cb;
458 #endif /* if OPENSSL_VERSION_NUMBER < 0x10100000L || \
459 	* defined(LIBRESSL_VERSION_NUMBER) */
460 	BN_GENCB *cb = BN_GENCB_new();
461 	EVP_PKEY *pkey = EVP_PKEY_new();
462 
463 	/*
464 	 * Reject incorrect RSA key lengths.
465 	 */
466 	switch (key->key_alg) {
467 	case DST_ALG_RSASHA1:
468 	case DST_ALG_NSEC3RSASHA1:
469 		/* From RFC 3110 */
470 		if (key->key_size > 4096) {
471 			goto err;
472 		}
473 		break;
474 	case DST_ALG_RSASHA256:
475 		/* From RFC 5702 */
476 		if ((key->key_size < 512) || (key->key_size > 4096)) {
477 			goto err;
478 		}
479 		break;
480 	case DST_ALG_RSASHA512:
481 		/* From RFC 5702 */
482 		if ((key->key_size < 1024) || (key->key_size > 4096)) {
483 			goto err;
484 		}
485 		break;
486 	default:
487 		INSIST(0);
488 		ISC_UNREACHABLE();
489 	}
490 
491 	if (rsa == NULL || e == NULL || cb == NULL) {
492 		goto err;
493 	}
494 	if (pkey == NULL) {
495 		goto err;
496 	}
497 	if (!EVP_PKEY_set1_RSA(pkey, rsa)) {
498 		goto err;
499 	}
500 
501 	if (exp == 0) {
502 		/* RSA_F4 0x10001 */
503 		BN_set_bit(e, 0);
504 		BN_set_bit(e, 16);
505 	} else {
506 		/* (phased-out) F5 0x100000001 */
507 		BN_set_bit(e, 0);
508 		BN_set_bit(e, 32);
509 	}
510 
511 	if (callback == NULL) {
512 		BN_GENCB_set_old(cb, NULL, NULL);
513 	} else {
514 		u.fptr = callback;
515 		BN_GENCB_set(cb, progress_cb, u.dptr);
516 	}
517 
518 	if (RSA_generate_key_ex(rsa, key->key_size, e, cb)) {
519 		BN_free(e);
520 		BN_GENCB_free(cb);
521 		cb = NULL;
522 		key->keydata.pkey = pkey;
523 
524 		RSA_free(rsa);
525 		return (ISC_R_SUCCESS);
526 	}
527 	ret = dst__openssl_toresult2("RSA_generate_key_ex",
528 				     DST_R_OPENSSLFAILURE);
529 
530 err:
531 	if (pkey != NULL) {
532 		EVP_PKEY_free(pkey);
533 		pkey = NULL;
534 	}
535 	if (e != NULL) {
536 		BN_free(e);
537 		e = NULL;
538 	}
539 	if (rsa != NULL) {
540 		RSA_free(rsa);
541 		rsa = NULL;
542 	}
543 	if (cb != NULL) {
544 		BN_GENCB_free(cb);
545 		cb = NULL;
546 	}
547 	return (dst__openssl_toresult(ret));
548 }
549 
550 static bool
551 opensslrsa_isprivate(const dst_key_t *key) {
552 	const BIGNUM *d = NULL;
553 	RSA *rsa = EVP_PKEY_get1_RSA(key->keydata.pkey);
554 	INSIST(rsa != NULL);
555 	RSA_free(rsa);
556 	/* key->keydata.pkey still has a reference so rsa is still valid. */
557 	if (rsa != NULL && RSA_test_flags(rsa, RSA_FLAG_EXT_PKEY) != 0) {
558 		return (true);
559 	}
560 	RSA_get0_key(rsa, NULL, NULL, &d);
561 	return (rsa != NULL && d != NULL);
562 }
563 
564 static void
565 opensslrsa_destroy(dst_key_t *key) {
566 	EVP_PKEY *pkey = key->keydata.pkey;
567 	EVP_PKEY_free(pkey);
568 	key->keydata.pkey = NULL;
569 }
570 
571 static isc_result_t
572 opensslrsa_todns(const dst_key_t *key, isc_buffer_t *data) {
573 	isc_region_t r;
574 	unsigned int e_bytes;
575 	unsigned int mod_bytes;
576 	isc_result_t ret;
577 	RSA *rsa;
578 	EVP_PKEY *pkey;
579 	const BIGNUM *e = NULL, *n = NULL;
580 
581 	REQUIRE(key->keydata.pkey != NULL);
582 
583 	pkey = key->keydata.pkey;
584 	rsa = EVP_PKEY_get1_RSA(pkey);
585 	if (rsa == NULL) {
586 		return (dst__openssl_toresult(DST_R_OPENSSLFAILURE));
587 	}
588 
589 	isc_buffer_availableregion(data, &r);
590 
591 	RSA_get0_key(rsa, &n, &e, NULL);
592 	mod_bytes = BN_num_bytes(n);
593 	e_bytes = BN_num_bytes(e);
594 
595 	if (e_bytes < 256) { /*%< key exponent is <= 2040 bits */
596 		if (r.length < 1) {
597 			DST_RET(ISC_R_NOSPACE);
598 		}
599 		isc_buffer_putuint8(data, (uint8_t)e_bytes);
600 		isc_region_consume(&r, 1);
601 	} else {
602 		if (r.length < 3) {
603 			DST_RET(ISC_R_NOSPACE);
604 		}
605 		isc_buffer_putuint8(data, 0);
606 		isc_buffer_putuint16(data, (uint16_t)e_bytes);
607 		isc_region_consume(&r, 3);
608 	}
609 
610 	if (r.length < e_bytes + mod_bytes) {
611 		DST_RET(ISC_R_NOSPACE);
612 	}
613 
614 	RSA_get0_key(rsa, &n, &e, NULL);
615 	BN_bn2bin(e, r.base);
616 	isc_region_consume(&r, e_bytes);
617 	BN_bn2bin(n, r.base);
618 
619 	isc_buffer_add(data, e_bytes + mod_bytes);
620 
621 	ret = ISC_R_SUCCESS;
622 err:
623 	RSA_free(rsa);
624 	return (ret);
625 }
626 
627 static isc_result_t
628 opensslrsa_fromdns(dst_key_t *key, isc_buffer_t *data) {
629 	RSA *rsa;
630 	isc_region_t r;
631 	unsigned int e_bytes;
632 	unsigned int length;
633 	EVP_PKEY *pkey;
634 	BIGNUM *e = NULL, *n = NULL;
635 
636 	isc_buffer_remainingregion(data, &r);
637 	if (r.length == 0) {
638 		return (ISC_R_SUCCESS);
639 	}
640 	length = r.length;
641 
642 	rsa = RSA_new();
643 	if (rsa == NULL) {
644 		return (dst__openssl_toresult(ISC_R_NOMEMORY));
645 	}
646 
647 	if (r.length < 1) {
648 		RSA_free(rsa);
649 		return (DST_R_INVALIDPUBLICKEY);
650 	}
651 	e_bytes = *r.base;
652 	isc_region_consume(&r, 1);
653 
654 	if (e_bytes == 0) {
655 		if (r.length < 2) {
656 			RSA_free(rsa);
657 			return (DST_R_INVALIDPUBLICKEY);
658 		}
659 		e_bytes = (*r.base) << 8;
660 		isc_region_consume(&r, 1);
661 		e_bytes += *r.base;
662 		isc_region_consume(&r, 1);
663 	}
664 
665 	if (r.length < e_bytes) {
666 		RSA_free(rsa);
667 		return (DST_R_INVALIDPUBLICKEY);
668 	}
669 	e = BN_bin2bn(r.base, e_bytes, NULL);
670 	isc_region_consume(&r, e_bytes);
671 	n = BN_bin2bn(r.base, r.length, NULL);
672 	if (RSA_set0_key(rsa, n, e, NULL) == 0) {
673 		if (n != NULL) {
674 			BN_free(n);
675 		}
676 		if (e != NULL) {
677 			BN_free(e);
678 		}
679 		RSA_free(rsa);
680 		return (ISC_R_NOMEMORY);
681 	}
682 	key->key_size = BN_num_bits(n);
683 
684 	isc_buffer_forward(data, length);
685 
686 	pkey = EVP_PKEY_new();
687 	if (pkey == NULL) {
688 		RSA_free(rsa);
689 		return (ISC_R_NOMEMORY);
690 	}
691 	if (!EVP_PKEY_set1_RSA(pkey, rsa)) {
692 		EVP_PKEY_free(pkey);
693 		RSA_free(rsa);
694 		return (dst__openssl_toresult(DST_R_OPENSSLFAILURE));
695 	}
696 	key->keydata.pkey = pkey;
697 	RSA_free(rsa);
698 
699 	return (ISC_R_SUCCESS);
700 }
701 
702 static isc_result_t
703 opensslrsa_tofile(const dst_key_t *key, const char *directory) {
704 	int i;
705 	RSA *rsa;
706 	dst_private_t priv;
707 	unsigned char *bufs[8];
708 	isc_result_t result;
709 	const BIGNUM *n = NULL, *e = NULL, *d = NULL;
710 	const BIGNUM *p = NULL, *q = NULL;
711 	const BIGNUM *dmp1 = NULL, *dmq1 = NULL, *iqmp = NULL;
712 
713 	if (key->external) {
714 		priv.nelements = 0;
715 		return (dst__privstruct_writefile(key, &priv, directory));
716 	}
717 
718 	if (key->keydata.pkey == NULL) {
719 		return (DST_R_NULLKEY);
720 	}
721 	rsa = EVP_PKEY_get1_RSA(key->keydata.pkey);
722 	if (rsa == NULL) {
723 		return (dst__openssl_toresult(DST_R_OPENSSLFAILURE));
724 	}
725 	memset(bufs, 0, sizeof(bufs));
726 
727 	RSA_get0_key(rsa, &n, &e, &d);
728 	RSA_get0_factors(rsa, &p, &q);
729 	RSA_get0_crt_params(rsa, &dmp1, &dmq1, &iqmp);
730 
731 	for (i = 0; i < 8; i++) {
732 		bufs[i] = isc_mem_get(key->mctx, BN_num_bytes(n));
733 	}
734 
735 	i = 0;
736 
737 	priv.elements[i].tag = TAG_RSA_MODULUS;
738 	priv.elements[i].length = BN_num_bytes(n);
739 	BN_bn2bin(n, bufs[i]);
740 	priv.elements[i].data = bufs[i];
741 	i++;
742 
743 	priv.elements[i].tag = TAG_RSA_PUBLICEXPONENT;
744 	priv.elements[i].length = BN_num_bytes(e);
745 	BN_bn2bin(e, bufs[i]);
746 	priv.elements[i].data = bufs[i];
747 	i++;
748 
749 	if (d != NULL) {
750 		priv.elements[i].tag = TAG_RSA_PRIVATEEXPONENT;
751 		priv.elements[i].length = BN_num_bytes(d);
752 		BN_bn2bin(d, bufs[i]);
753 		priv.elements[i].data = bufs[i];
754 		i++;
755 	}
756 
757 	if (p != NULL) {
758 		priv.elements[i].tag = TAG_RSA_PRIME1;
759 		priv.elements[i].length = BN_num_bytes(p);
760 		BN_bn2bin(p, bufs[i]);
761 		priv.elements[i].data = bufs[i];
762 		i++;
763 	}
764 
765 	if (q != NULL) {
766 		priv.elements[i].tag = TAG_RSA_PRIME2;
767 		priv.elements[i].length = BN_num_bytes(q);
768 		BN_bn2bin(q, bufs[i]);
769 		priv.elements[i].data = bufs[i];
770 		i++;
771 	}
772 
773 	if (dmp1 != NULL) {
774 		priv.elements[i].tag = TAG_RSA_EXPONENT1;
775 		priv.elements[i].length = BN_num_bytes(dmp1);
776 		BN_bn2bin(dmp1, bufs[i]);
777 		priv.elements[i].data = bufs[i];
778 		i++;
779 	}
780 
781 	if (dmq1 != NULL) {
782 		priv.elements[i].tag = TAG_RSA_EXPONENT2;
783 		priv.elements[i].length = BN_num_bytes(dmq1);
784 		BN_bn2bin(dmq1, bufs[i]);
785 		priv.elements[i].data = bufs[i];
786 		i++;
787 	}
788 
789 	if (iqmp != NULL) {
790 		priv.elements[i].tag = TAG_RSA_COEFFICIENT;
791 		priv.elements[i].length = BN_num_bytes(iqmp);
792 		BN_bn2bin(iqmp, bufs[i]);
793 		priv.elements[i].data = bufs[i];
794 		i++;
795 	}
796 
797 	if (key->engine != NULL) {
798 		priv.elements[i].tag = TAG_RSA_ENGINE;
799 		priv.elements[i].length = (unsigned short)strlen(key->engine) +
800 					  1;
801 		priv.elements[i].data = (unsigned char *)key->engine;
802 		i++;
803 	}
804 
805 	if (key->label != NULL) {
806 		priv.elements[i].tag = TAG_RSA_LABEL;
807 		priv.elements[i].length = (unsigned short)strlen(key->label) +
808 					  1;
809 		priv.elements[i].data = (unsigned char *)key->label;
810 		i++;
811 	}
812 
813 	priv.nelements = i;
814 	result = dst__privstruct_writefile(key, &priv, directory);
815 
816 	RSA_free(rsa);
817 	for (i = 0; i < 8; i++) {
818 		if (bufs[i] == NULL) {
819 			break;
820 		}
821 		isc_mem_put(key->mctx, bufs[i], BN_num_bytes(n));
822 	}
823 	return (result);
824 }
825 
826 static isc_result_t
827 rsa_check(RSA *rsa, RSA *pub) {
828 	const BIGNUM *n1 = NULL, *n2 = NULL;
829 	const BIGNUM *e1 = NULL, *e2 = NULL;
830 	BIGNUM *n = NULL, *e = NULL;
831 
832 	/*
833 	 * Public parameters should be the same but if they are not set
834 	 * copy them from the public key.
835 	 */
836 	RSA_get0_key(rsa, &n1, &e1, NULL);
837 	if (pub != NULL) {
838 		RSA_get0_key(pub, &n2, &e2, NULL);
839 		if (n1 != NULL) {
840 			if (BN_cmp(n1, n2) != 0) {
841 				return (DST_R_INVALIDPRIVATEKEY);
842 			}
843 		} else {
844 			n = BN_dup(n2);
845 		}
846 		if (e1 != NULL) {
847 			if (BN_cmp(e1, e2) != 0) {
848 				return (DST_R_INVALIDPRIVATEKEY);
849 			}
850 		} else {
851 			e = BN_dup(e2);
852 		}
853 		if (RSA_set0_key(rsa, n, e, NULL) == 0) {
854 			if (n != NULL) {
855 				BN_free(n);
856 			}
857 			if (e != NULL) {
858 				BN_free(e);
859 			}
860 		}
861 	}
862 	RSA_get0_key(rsa, &n1, &e1, NULL);
863 	if (n1 == NULL || e1 == NULL) {
864 		return (DST_R_INVALIDPRIVATEKEY);
865 	}
866 	return (ISC_R_SUCCESS);
867 }
868 
869 static isc_result_t
870 opensslrsa_parse(dst_key_t *key, isc_lex_t *lexer, dst_key_t *pub) {
871 	dst_private_t priv;
872 	isc_result_t ret;
873 	int i;
874 	RSA *rsa = NULL, *pubrsa = NULL;
875 #if !defined(OPENSSL_NO_ENGINE)
876 	ENGINE *ep = NULL;
877 	const BIGNUM *ex = NULL;
878 #endif /* if !defined(OPENSSL_NO_ENGINE) */
879 	isc_mem_t *mctx = key->mctx;
880 	const char *engine = NULL, *label = NULL;
881 	EVP_PKEY *pkey = NULL;
882 	BIGNUM *n = NULL, *e = NULL, *d = NULL;
883 	BIGNUM *p = NULL, *q = NULL;
884 	BIGNUM *dmp1 = NULL, *dmq1 = NULL, *iqmp = NULL;
885 
886 	/* read private key file */
887 	ret = dst__privstruct_parse(key, DST_ALG_RSA, lexer, mctx, &priv);
888 	if (ret != ISC_R_SUCCESS) {
889 		goto err;
890 	}
891 
892 	if (key->external) {
893 		if (priv.nelements != 0) {
894 			DST_RET(DST_R_INVALIDPRIVATEKEY);
895 		}
896 		if (pub == NULL) {
897 			DST_RET(DST_R_INVALIDPRIVATEKEY);
898 		}
899 		key->keydata.pkey = pub->keydata.pkey;
900 		pub->keydata.pkey = NULL;
901 		key->key_size = pub->key_size;
902 		dst__privstruct_free(&priv, mctx);
903 		isc_safe_memwipe(&priv, sizeof(priv));
904 		return (ISC_R_SUCCESS);
905 	}
906 
907 	if (pub != NULL && pub->keydata.pkey != NULL) {
908 		pubrsa = EVP_PKEY_get1_RSA(pub->keydata.pkey);
909 	}
910 
911 	for (i = 0; i < priv.nelements; i++) {
912 		switch (priv.elements[i].tag) {
913 		case TAG_RSA_ENGINE:
914 			engine = (char *)priv.elements[i].data;
915 			break;
916 		case TAG_RSA_LABEL:
917 			label = (char *)priv.elements[i].data;
918 			break;
919 		default:
920 			break;
921 		}
922 	}
923 
924 	/*
925 	 * Is this key is stored in a HSM?
926 	 * See if we can fetch it.
927 	 */
928 	if (label != NULL) {
929 #if !defined(OPENSSL_NO_ENGINE)
930 		if (engine == NULL) {
931 			DST_RET(DST_R_NOENGINE);
932 		}
933 		ep = dst__openssl_getengine(engine);
934 		if (ep == NULL) {
935 			DST_RET(DST_R_NOENGINE);
936 		}
937 		pkey = ENGINE_load_private_key(ep, label, NULL, NULL);
938 		if (pkey == NULL) {
939 			DST_RET(dst__openssl_toresult2("ENGINE_load_private_"
940 						       "key",
941 						       ISC_R_NOTFOUND));
942 		}
943 		key->engine = isc_mem_strdup(key->mctx, engine);
944 		key->label = isc_mem_strdup(key->mctx, label);
945 		rsa = EVP_PKEY_get1_RSA(pkey);
946 		if (rsa == NULL) {
947 			DST_RET(dst__openssl_toresult(DST_R_OPENSSLFAILURE));
948 		}
949 		if (rsa_check(rsa, pubrsa) != ISC_R_SUCCESS) {
950 			DST_RET(DST_R_INVALIDPRIVATEKEY);
951 		}
952 		RSA_get0_key(rsa, NULL, &ex, NULL);
953 		if (BN_num_bits(ex) > RSA_MAX_PUBEXP_BITS) {
954 			DST_RET(ISC_R_RANGE);
955 		}
956 		if (pubrsa != NULL) {
957 			RSA_free(pubrsa);
958 		}
959 		key->key_size = EVP_PKEY_bits(pkey);
960 		key->keydata.pkey = pkey;
961 		RSA_free(rsa);
962 		dst__privstruct_free(&priv, mctx);
963 		isc_safe_memwipe(&priv, sizeof(priv));
964 		return (ISC_R_SUCCESS);
965 #else  /* if !defined(OPENSSL_NO_ENGINE) */
966 		DST_RET(DST_R_NOENGINE);
967 #endif /* if !defined(OPENSSL_NO_ENGINE) */
968 	}
969 
970 	rsa = RSA_new();
971 	if (rsa == NULL) {
972 		DST_RET(ISC_R_NOMEMORY);
973 	}
974 
975 	pkey = EVP_PKEY_new();
976 	if (pkey == NULL) {
977 		DST_RET(ISC_R_NOMEMORY);
978 	}
979 	if (!EVP_PKEY_set1_RSA(pkey, rsa)) {
980 		DST_RET(ISC_R_FAILURE);
981 	}
982 	key->keydata.pkey = pkey;
983 
984 	for (i = 0; i < priv.nelements; i++) {
985 		BIGNUM *bn;
986 		switch (priv.elements[i].tag) {
987 		case TAG_RSA_ENGINE:
988 			continue;
989 		case TAG_RSA_LABEL:
990 			continue;
991 		default:
992 			bn = BN_bin2bn(priv.elements[i].data,
993 				       priv.elements[i].length, NULL);
994 			if (bn == NULL) {
995 				DST_RET(ISC_R_NOMEMORY);
996 			}
997 			switch (priv.elements[i].tag) {
998 			case TAG_RSA_MODULUS:
999 				n = bn;
1000 				break;
1001 			case TAG_RSA_PUBLICEXPONENT:
1002 				e = bn;
1003 				break;
1004 			case TAG_RSA_PRIVATEEXPONENT:
1005 				d = bn;
1006 				break;
1007 			case TAG_RSA_PRIME1:
1008 				p = bn;
1009 				break;
1010 			case TAG_RSA_PRIME2:
1011 				q = bn;
1012 				break;
1013 			case TAG_RSA_EXPONENT1:
1014 				dmp1 = bn;
1015 				break;
1016 			case TAG_RSA_EXPONENT2:
1017 				dmq1 = bn;
1018 				break;
1019 			case TAG_RSA_COEFFICIENT:
1020 				iqmp = bn;
1021 				break;
1022 			}
1023 		}
1024 	}
1025 	dst__privstruct_free(&priv, mctx);
1026 	isc_safe_memwipe(&priv, sizeof(priv));
1027 
1028 	if (RSA_set0_key(rsa, n, e, d) == 0) {
1029 		if (n != NULL) {
1030 			BN_free(n);
1031 		}
1032 		if (e != NULL) {
1033 			BN_free(e);
1034 		}
1035 		if (d != NULL) {
1036 			BN_free(d);
1037 		}
1038 	}
1039 	if (RSA_set0_factors(rsa, p, q) == 0) {
1040 		if (p != NULL) {
1041 			BN_free(p);
1042 		}
1043 		if (q != NULL) {
1044 			BN_free(q);
1045 		}
1046 	}
1047 	if (RSA_set0_crt_params(rsa, dmp1, dmq1, iqmp) == 0) {
1048 		if (dmp1 != NULL) {
1049 			BN_free(dmp1);
1050 		}
1051 		if (dmq1 != NULL) {
1052 			BN_free(dmq1);
1053 		}
1054 		if (iqmp != NULL) {
1055 			BN_free(iqmp);
1056 		}
1057 	}
1058 
1059 	if (rsa_check(rsa, pubrsa) != ISC_R_SUCCESS) {
1060 		DST_RET(DST_R_INVALIDPRIVATEKEY);
1061 	}
1062 	if (BN_num_bits(e) > RSA_MAX_PUBEXP_BITS) {
1063 		DST_RET(ISC_R_RANGE);
1064 	}
1065 	key->key_size = BN_num_bits(n);
1066 	if (pubrsa != NULL) {
1067 		RSA_free(pubrsa);
1068 	}
1069 	RSA_free(rsa);
1070 
1071 	return (ISC_R_SUCCESS);
1072 
1073 err:
1074 	if (pkey != NULL) {
1075 		EVP_PKEY_free(pkey);
1076 	}
1077 	if (rsa != NULL) {
1078 		RSA_free(rsa);
1079 	}
1080 	if (pubrsa != NULL) {
1081 		RSA_free(pubrsa);
1082 	}
1083 	key->keydata.generic = NULL;
1084 	dst__privstruct_free(&priv, mctx);
1085 	isc_safe_memwipe(&priv, sizeof(priv));
1086 	return (ret);
1087 }
1088 
1089 static isc_result_t
1090 opensslrsa_fromlabel(dst_key_t *key, const char *engine, const char *label,
1091 		     const char *pin) {
1092 #if !defined(OPENSSL_NO_ENGINE)
1093 	ENGINE *e = NULL;
1094 	isc_result_t ret;
1095 	EVP_PKEY *pkey = NULL;
1096 	RSA *rsa = NULL, *pubrsa = NULL;
1097 	const BIGNUM *ex = NULL;
1098 
1099 	UNUSED(pin);
1100 
1101 	if (engine == NULL) {
1102 		DST_RET(DST_R_NOENGINE);
1103 	}
1104 	e = dst__openssl_getengine(engine);
1105 	if (e == NULL) {
1106 		DST_RET(DST_R_NOENGINE);
1107 	}
1108 	pkey = ENGINE_load_public_key(e, label, NULL, NULL);
1109 	if (pkey != NULL) {
1110 		pubrsa = EVP_PKEY_get1_RSA(pkey);
1111 		EVP_PKEY_free(pkey);
1112 		if (pubrsa == NULL) {
1113 			DST_RET(dst__openssl_toresult(DST_R_OPENSSLFAILURE));
1114 		}
1115 	}
1116 	pkey = ENGINE_load_private_key(e, label, NULL, NULL);
1117 	if (pkey == NULL) {
1118 		DST_RET(dst__openssl_toresult2("ENGINE_load_private_key",
1119 					       ISC_R_NOTFOUND));
1120 	}
1121 	key->engine = isc_mem_strdup(key->mctx, engine);
1122 	key->label = isc_mem_strdup(key->mctx, label);
1123 	rsa = EVP_PKEY_get1_RSA(pkey);
1124 	if (rsa == NULL) {
1125 		DST_RET(dst__openssl_toresult(DST_R_OPENSSLFAILURE));
1126 	}
1127 	if (rsa_check(rsa, pubrsa) != ISC_R_SUCCESS) {
1128 		DST_RET(DST_R_INVALIDPRIVATEKEY);
1129 	}
1130 	RSA_get0_key(rsa, NULL, &ex, NULL);
1131 	if (BN_num_bits(ex) > RSA_MAX_PUBEXP_BITS) {
1132 		DST_RET(ISC_R_RANGE);
1133 	}
1134 	if (pubrsa != NULL) {
1135 		RSA_free(pubrsa);
1136 	}
1137 	key->key_size = EVP_PKEY_bits(pkey);
1138 	key->keydata.pkey = pkey;
1139 	RSA_free(rsa);
1140 	return (ISC_R_SUCCESS);
1141 
1142 err:
1143 	if (rsa != NULL) {
1144 		RSA_free(rsa);
1145 	}
1146 	if (pubrsa != NULL) {
1147 		RSA_free(pubrsa);
1148 	}
1149 	if (pkey != NULL) {
1150 		EVP_PKEY_free(pkey);
1151 	}
1152 	return (ret);
1153 #else  /* if !defined(OPENSSL_NO_ENGINE) */
1154 	UNUSED(key);
1155 	UNUSED(engine);
1156 	UNUSED(label);
1157 	UNUSED(pin);
1158 	return (DST_R_NOENGINE);
1159 #endif /* if !defined(OPENSSL_NO_ENGINE) */
1160 }
1161 
1162 static dst_func_t opensslrsa_functions = {
1163 	opensslrsa_createctx,
1164 	NULL, /*%< createctx2 */
1165 	opensslrsa_destroyctx,
1166 	opensslrsa_adddata,
1167 	opensslrsa_sign,
1168 	opensslrsa_verify,
1169 	opensslrsa_verify2,
1170 	NULL, /*%< computesecret */
1171 	opensslrsa_compare,
1172 	NULL, /*%< paramcompare */
1173 	opensslrsa_generate,
1174 	opensslrsa_isprivate,
1175 	opensslrsa_destroy,
1176 	opensslrsa_todns,
1177 	opensslrsa_fromdns,
1178 	opensslrsa_tofile,
1179 	opensslrsa_parse,
1180 	NULL, /*%< cleanup */
1181 	opensslrsa_fromlabel,
1182 	NULL, /*%< dump */
1183 	NULL, /*%< restore */
1184 };
1185 
1186 isc_result_t
1187 dst__opensslrsa_init(dst_func_t **funcp, unsigned char algorithm) {
1188 	REQUIRE(funcp != NULL);
1189 
1190 	UNUSED(algorithm);
1191 
1192 	if (*funcp == NULL) {
1193 		*funcp = &opensslrsa_functions;
1194 	}
1195 	return (ISC_R_SUCCESS);
1196 }
1197 
1198 #endif /* !USE_PKCS11 */
1199 
1200 /*! \file */
1201