1/*
2 * Copyright (c) 2011 Apple Inc. All Rights Reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24
25#include "ossl-config.h"
26
27#include <stdio.h>
28#include <stdlib.h>
29#include <string.h>
30#include <assert.h>
31
32#include "ossl-bn.h"
33#include "ossl-rand.h"
34#include "ossl-rsa.h"
35
36#ifdef HAVE_COMMONCRYPTO_COMMONRSACRYPTOR_H
37
38#include <CommonCrypto/CommonRSACryptor.h>
39
40static int cc_rsa_public_encrypt(int, const unsigned char *, unsigned char *, RSA *, int);
41static int cc_rsa_private_decrypt(int, const unsigned char *, unsigned char *, RSA *, int);
42
43static int cc_rsa_private_encrypt(int flen, const unsigned char *from,
44				    unsigned char *to, RSA *rsa, int padding);
45static int cc_rsa_public_decrypt(int flen, const unsigned char *from,
46				    unsigned char *to, RSA *rsa, int padding);
47
48static int cc_rsa_mod_exp(BIGNUM *r0, const BIGNUM *i, RSA *rsa, BN_CTX *ctx);
49
50static int cc_rsa_init(RSA *rsa);
51static int cc_rsa_finish(RSA *rsa);
52
53static int cc_rsa_sign(int, const unsigned char *, unsigned int, unsigned char *,
54			    unsigned int *, const RSA *);
55static int cc_rsa_verify(int, const unsigned char *, unsigned int, unsigned char *,
56			    unsigned int, const RSA *);
57
58static int cc_rsa_generate_key(RSA *rsa, int bits, BIGNUM *e_value, BN_GENCB *cb);
59
60static int
61cc_rsa_init(RSA *rsa __unused)
62{
63	/* XXX set any flags needed */
64	return (1);
65}
66
67
68static int
69cc_rsa_finish(RSA *rsa __unused)
70{
71	/* XXX free resources */
72	return (1);
73}
74
75
76static int
77cc_status_to_openssl_err(CCCryptorStatus status)
78{
79	switch (status) {
80	case kCCSuccess:
81		return (0);
82
83	case -1:
84		/* XXX RSAerr( , UNKNOWN_NEG1); */
85		fprintf(stderr, "unknown (-1) error");
86		return (-1);
87
88	case kCCParamError:
89		/* XXX RSAerr( , PARAM_ERROR ); */
90		fprintf(stderr, "parameter error");
91		return (1);
92
93	case kCCBufferTooSmall:
94		/* XXX RSAerr( , BUFFER_OVERFLOW ); */
95		fprintf(stderr, "buffer overflow error");
96		return (2);
97
98	case kCCMemoryFailure:
99		/* XXX RSAerr(  , ERR_R_MALLOC_FAILURE); */
100		fprintf(stderr, "memory failure");
101		return (3);
102
103	case kCCDecodeError:
104		/* XXX RSAerr( , PK_INVALID_SIZE); */
105		fprintf(stderr, "der_encode_int_error");
106		return (4);
107
108	default:
109		/* XXX RSAerr( , UNKNOWN); */
110		fprintf(stderr, "unknown error");
111		return (666);
112	}
113}
114
115
116/* DER encoding for importing keys to CommonCrypto.  */
117static unsigned long
118der_length_seq_hdr(unsigned long blksz)
119{
120	unsigned long len = 0;
121
122	if (blksz < 128UL) {
123		/* 0x30 LL */
124		len = 2UL;
125	} else if (blksz < 256UL) {
126		/* 0x30 0x81 LL */
127		len = 3UL;
128	} else if (blksz < 65536UL) {
129		/* 0x30 0x81 LL LL */
130		len = 4UL;
131	} else if (blksz < 16777216UL) {
132		/*  0x30 0x83 LL LL LL */
133		len = 5UL;
134	} else {
135		fprintf(stderr, "Invalid DER Sequence size.");
136		abort();
137	}
138
139	return (len);
140}
141
142
143static int
144der_encode_seq_hdr(unsigned long blksz, unsigned char *out, unsigned long *outlen)
145{
146	*out++ = 0x30;
147	if (blksz < 128UL) {
148		/* 0x30 LL */
149		*out++ = (unsigned char)(blksz & 0xFF);
150		*outlen = 2UL;
151	} else if (blksz < 256) {
152		/* 0x30 0x81 LL */
153		*out++ = 0x81;
154		*out++ = (unsigned char)(blksz & 0xFF);
155		*outlen = 3UL;
156	} else if (blksz < 65536UL) {
157		/* 0x30 0x81 LL LL */
158		*out++ = 0x82;
159		*out++ = (unsigned char)((blksz >> 8UL) & 0xFF);
160		*out++ = (unsigned char)(blksz & 0xFF);
161		*outlen = 4UL;
162	} else if (blksz < 16777216UL) {
163		/*  0x30 0x83 LL LL LL */
164		*out++ = 0x83;
165		*out++ = (unsigned char)((blksz >> 16UL) & 0xFF);
166		*out++ = (unsigned char)((blksz >> 8UL) & 0xFF);
167		*out++ = (unsigned char)(blksz & 0xFF);
168		*outlen = 5UL;
169	} else {
170		*outlen = 0UL;
171		return (-1);
172	}
173
174	return (0);
175}
176
177
178static unsigned long
179der_length_int(const BIGNUM *num)
180{
181	unsigned long len, z;
182	int leading_zero;
183
184	if (((BN_num_bits(num) & 0x7) == 0) || BN_is_zero(num)) {
185		leading_zero = 1;
186	} else{
187		leading_zero = 0;
188	}
189
190	z = len = leading_zero + BN_num_bytes(num);
191
192	if (z < 128) {
193		/* short form */
194		++len;
195	} else {
196		/* long form (z != 0), len bytes < 128 */
197		++len;
198		while (z) {
199			++len;
200			z >>= 8;
201		}
202	}
203	/* add the 0x02 header byte */
204	++len;
205
206	return (len);
207}
208
209
210static int
211der_encode_int(const BIGNUM *num, unsigned char *out, unsigned long *outlen)
212{
213	unsigned long tmplen, y;
214	int err, leading_zero;
215
216	if ((tmplen = der_length_int(num)) > *outlen) {
217		return (-1);
218	}
219
220	if (BN_is_negative(num)) {
221		return (-2);
222	}
223
224	/* We only need a leading zero if the msb of the first byte is one */
225	if (((BN_num_bits(num) & 0x7) == 0) || BN_is_zero(num)) {
226		leading_zero = 1;
227	} else{
228		leading_zero = 0;
229	}
230
231	y = BN_num_bytes(num) + leading_zero;
232
233	/* header info */
234	*out++ = 0x02;
235	if (y < 128) {
236		/* short form */
237		*out++ = (unsigned char)y;
238	} else if (y < 256) {
239		*out++ = 0x81;
240		*out++ = (unsigned char)y;
241	} else if (y < 65536UL) {
242		*out++ = 0x82;
243		*out++ = (unsigned char)((y >> 8) & 0xFF);
244		*out++ = (unsigned char)y;
245	} else if (y < 16777216UL) {
246		*out++ = 0x83;
247		*out++ = (unsigned char)((y >> 16) & 0xFF);
248		*out++ = (unsigned char)((y >> 8) & 0xFF);
249		*out++ = (unsigned char)y;
250	} else {
251		return (-3);
252	}
253
254	/* now store msbyte of zero if num is non-zero */
255	if (leading_zero) {
256		*out++ = 0x00;
257	}
258
259	(void)BN_bn2bin(num, out);
260
261	*outlen = tmplen;
262
263	return (0);
264}
265
266
267/* keytype = { ccRSAKeyPublic or ccRSAKeyPrivate } */
268static CCRSACryptorRef
269get_CCRSACryptorRef(CCRSAKeyType keytype, const RSA *rsakey)
270{
271	CCCryptorStatus status = kCCDecodeError;
272	CCRSACryptorRef ref = NULL;
273	unsigned long length, offset, outlen, blksz;
274	unsigned char *derbuf = NULL;
275	BIGNUM *zero = BN_new();
276
277	BN_clear(zero);
278
279	switch (keytype) {
280	case ccRSAKeyPublic:
281		blksz = der_length_int(rsakey->n) + der_length_int(rsakey->e);
282		length = der_length_seq_hdr(blksz) + blksz;
283		derbuf = malloc(length);
284		offset = 0L;
285		outlen = length;
286
287		/* Add sequence header first */
288		if (der_encode_seq_hdr(blksz, derbuf + offset, &outlen) != 0) {
289			goto outerr;
290		}
291		offset += outlen;
292		outlen = length - offset;
293		/* And then integers */
294		if (der_encode_int(rsakey->n, derbuf + offset, &outlen) != 0) {
295			goto outerr;
296		}
297		offset += outlen;
298		outlen = length - offset;
299		if (der_encode_int(rsakey->e, derbuf + offset, &outlen) != 0) {
300			goto outerr;
301		}
302
303		break;
304
305	case ccRSAKeyPrivate:
306		blksz = der_length_int(zero) + der_length_int(rsakey->n) +
307		    der_length_int(rsakey->e) + der_length_int(rsakey->d) +
308		    der_length_int(rsakey->p) + der_length_int(rsakey->q) +
309		    der_length_int(rsakey->dmp1) + der_length_int(rsakey->dmq1) +
310		    der_length_int(rsakey->iqmp);
311		length = der_length_seq_hdr(blksz) + blksz;
312		derbuf = malloc(length);
313		offset = 0L;
314		outlen = length;
315
316		/* Add sequence header first */
317		if (der_encode_seq_hdr(blksz, derbuf + offset, &outlen) != 0) {
318			goto outerr;
319		}
320		offset += outlen;
321		outlen = length - offset;
322		/* And then integers */
323		if (der_encode_int(zero, derbuf + offset, &outlen) != 0) {
324			goto outerr;
325		}
326		offset += outlen;
327		outlen = length - offset;
328		if (der_encode_int(rsakey->n, derbuf + offset, &outlen) != 0) {
329			goto outerr;
330		}
331		offset += outlen;
332		outlen = length - offset;
333		if (der_encode_int(rsakey->e, derbuf + offset, &outlen) != 0) {
334			goto outerr;
335		}
336		offset += outlen;
337		outlen = length - offset;
338		if (der_encode_int(rsakey->d, derbuf + offset, &outlen) != 0) {
339			goto outerr;
340		}
341		offset += outlen;
342		outlen = length - offset;
343		if (der_encode_int(rsakey->p, derbuf + offset, &outlen) != 0) {
344			goto outerr;
345		}
346		offset += outlen;
347		outlen = length - offset;
348		if (der_encode_int(rsakey->q, derbuf + offset, &outlen) != 0) {
349			goto outerr;
350		}
351		offset += outlen;
352		outlen = length - offset;
353		if (der_encode_int(rsakey->dmp1, derbuf + offset, &outlen) != 0) {
354			goto outerr;
355		}
356		offset += outlen;
357		outlen = length - offset;
358		if (der_encode_int(rsakey->dmq1, derbuf + offset, &outlen) != 0) {
359			goto outerr;
360		}
361		offset += outlen;
362		outlen = length - offset;
363		if (der_encode_int(rsakey->iqmp, derbuf + offset, &outlen) != 0) {
364			goto outerr;
365		}
366
367		break;
368
369	default:
370		goto outerr;
371	}
372
373	status = CCRSACryptorImport(derbuf, length, &ref);
374
375outerr:
376
377	BN_free(zero);
378	if (derbuf != NULL) {
379		free(derbuf);
380	}
381
382	if (cc_status_to_openssl_err(status) == 0) {
383		return (ref);
384	} else{
385		return (NULL);
386	}
387}
388
389
390/* RSASSA-PKCS1-v1_5 (PKCS #1 v2.0 signature) with SHA1 (default) or MD5 */
391static int
392cc_rsa_sign(int nid, const unsigned char *digest, unsigned int dlen,
393    unsigned char *sig, unsigned int *len, const RSA *rsa)
394{
395	CCRSACryptorRef cc_key = get_CCRSACryptorRef(ccRSAKeyPrivate, rsa);
396	CCCryptorStatus status;
397
398	if (NULL == cc_key) {
399		/* XXX RSAerr( , ); */
400		return (0);
401	}
402
403	status = CCRSACryptorSign(cc_key, ccPKCS1Padding, (const void *)digest,
404		(size_t)dlen, (nid == NID_md5) ? kCCDigestMD5 : kCCDigestSHA1,
405		0, (void *)sig, (size_t *)len);
406
407	CCRSACryptorRelease(cc_key);
408
409	return (cc_status_to_openssl_err(status) == 0);
410}
411
412
413/* RSASSA-PKCS1-v1_5 (PKCS #1 v2.0 signature verify) with SHA1 (default) or MD5 */
414static int
415cc_rsa_verify(int nid, const unsigned char *digest, unsigned int dlen,
416    unsigned char *sigblob, unsigned int len, const RSA *rsa)
417{
418	CCRSACryptorRef cc_key = get_CCRSACryptorRef(ccRSAKeyPublic, rsa);
419	CCCryptorStatus status;
420
421	if (NULL == cc_key) {
422		/* XXX RSAerr( , ); */
423		return (0);
424	}
425
426	status = CCRSACryptorVerify(cc_key, ccPKCS1Padding, (const void *)digest, (size_t)dlen,
427		(nid == NID_md5) ? kCCDigestMD5 : kCCDigestSHA1, 0, (const void *)sigblob,
428		(size_t)len);
429	CCRSACryptorRelease(cc_key);
430
431	return (cc_status_to_openssl_err(status) == 0);
432}
433
434
435int RSA_public_encrypt(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding);
436
437static int
438openssl_to_cc_padding(int padding)
439{
440	switch (padding) {
441	case RSA_PKCS1_PADDING:
442		return (ccPKCS1Padding);
443
444	case RSA_PKCS1_OAEP_PADDING:
445		return (ccOAEPPadding);
446
447#if 0
448	case RSA_X931_PADDING:
449		return (ccX931Padding);
450
451	case RSA_NO_PADDING:
452		return (ccPaddingNone);
453#endif
454	default:
455		/* XXX RSAerr( , ); */
456		return (-1);
457	}
458}
459
460
461static int
462cc_rsa_public_encrypt(int ilen, const unsigned char *inbuf, unsigned char *outbuf,
463    RSA *key, int padding)
464{
465	CCRSACryptorRef cc_key = get_CCRSACryptorRef(ccRSAKeyPublic, key);
466	CCCryptorStatus status;
467	size_t olen = (size_t)BN_num_bytes(key->n);
468	int cc_padding;
469
470	if ((cc_padding = openssl_to_cc_padding(padding)) == -1) {
471		return (-1);
472	}
473
474
475	if (NULL == cc_key) {
476		/* XXX RSAerr( , ); */
477		return (-1);
478	}
479
480	status = CCRSACryptorEncrypt(cc_key, cc_padding, (const void *)inbuf,
481		(size_t)ilen, (void *)outbuf, (size_t *)&olen, NULL, 0, kCCDigestSHA1);
482
483	CCRSACryptorRelease(cc_key);
484	/* See if CCRSACryptorEncrypt() returns the undocumented -1 error. */
485	if (-1 == status) {
486		/* couldn't open /dev/random?  Use OpenSSL's RSA encrypt for now. */
487		olen = RSA_public_encrypt(ilen, inbuf, outbuf, key, padding);
488		return ((int)olen);
489	}
490
491	if (cc_status_to_openssl_err(status) != 0) {
492		return (-1);
493	} else {
494		return ((int)olen);
495	}
496}
497
498
499#include "tommath.h"
500#include "rk-roken.h"
501typedef struct Rsa_key {
502	/** Type of key, PK_PRIVATE or PK_PUBLIC */
503	int	type;
504	/** The public exponent */
505	void *	e;
506	/** The private exponent */
507	void *	d;
508	/** The modulus */
509	void *	N;
510	/** The p factor of N */
511	void *	p;
512	/** The q factor of N */
513	void *	q;
514	/** The 1/q mod p CRT param */
515	void *	qP;
516	/** The d mod (p - 1) CRT param */
517	void *	dP;
518	/** The d mod (q - 1) CRT param */
519	void *	dQ;
520} rsa_key;
521typedef struct _CCRSACryptor {
522	rsa_key		key;
523	CCRSAKeyType	keyType;
524} CCRSACryptor;
525
526static int
527cc_rsa_private_decrypt(int ilen, const unsigned char *inbuf, unsigned char *outbuf,
528    RSA *key, int padding)
529{
530	CCRSACryptorRef cc_key = get_CCRSACryptorRef(ccRSAKeyPrivate, key);
531	CCCryptorStatus status;
532	size_t olen = (size_t)BN_num_bytes(key->n);
533	int cc_padding;
534
535	if ((cc_padding = openssl_to_cc_padding(padding)) == -1) {
536		return (-1);
537	}
538
539	if (NULL == cc_key) {
540		/* XXX RSAerr( , ); */
541		return (-1);
542	}
543
544	status = CCRSACryptorDecrypt(cc_key, cc_padding, (const void *)inbuf, (size_t)ilen,
545		(void *)outbuf, (size_t * )&olen, NULL, 0, kCCDigestSHA1);
546	CCRSACryptorRelease(cc_key);
547
548	if (cc_status_to_openssl_err(status) != 0) {
549		return (-1);
550	} else {
551		return ((int)olen);
552	}
553}
554
555
556#ifndef PR_10783242_FIXED
557
558/*
559 * XXX The following code is needed because CommonCrypto doesn't provide RSA private key
560 * encryption and RSA public key decryption.  See <rdar://problem/10783242>
561 */
562
563#ifndef RSA_MAX_MODULUS_BITS
564# define RSA_MAX_MODULUS_BITS		16384
565#endif
566#ifndef RSA_SMALL_MODULUS_BITS
567# define RSA_SMALL_MODULUS_BITS		3072
568#endif
569#ifndef RSA_MAX_PUBEXP_BITS
570# define RSA_MAX_PUBEXP_BITS		64 /* exponent limit enforced for "large" modulus only */
571#endif
572
573static int
574RSA_padding_add_PKCS1_type_1(unsigned char *to, int tlen,
575    const unsigned char *from, int flen)
576{
577	int j;
578	unsigned char *p;
579
580	if (flen > (tlen - RSA_PKCS1_PADDING_SIZE)) {
581		/* RSAerr(RSA_F_RSA_PADDING_ADD_PKCS1_TYPE_1,RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE); */
582		return (0);
583	}
584
585	p = (unsigned char *)to;
586
587	*(p++) = 0;
588	*(p++) = 1; /* Private Key BT (Block Type) */
589
590	/* pad out with 0xff data */
591	j = tlen - 3 - flen;
592	memset(p, 0xff, j);
593	p += j;
594	*(p++) = '\0';
595	memcpy(p, from, (unsigned int)flen);
596	return (1);
597}
598
599
600static int
601RSA_padding_check_PKCS1_type_1(unsigned char *to, int tlen,
602    const unsigned char *from, int flen, int num)
603{
604	int i, j;
605	const unsigned char *p;
606
607	p = from;
608	if ((num != (flen+1)) || (*(p++) != 01)) {
609		/* RSAerr(RSA_F_RSA_PADDING_CHECK_PKCS1_TYPE_1,RSA_R_BLOCK_TYPE_IS_NOT_01); */
610		return (-1);
611	}
612
613	/* scan over padding data */
614	j = flen - 1; /* one for type. */
615	for (i = 0; i < j; i++) {
616		if (*p != 0xff) {
617			/* should decrypt to 0xff */
618			if (*p == 0) {
619				p++;
620				break;
621			} else {
622				/* RSAerr(RSA_F_RSA_PADDING_CHECK_PKCS1_TYPE_1,RSA_R_BAD_FIXED_HEADER_DECRYPT); */
623				return (-1);
624			}
625		}
626		p++;
627	}
628
629	if (i == j) {
630		/* RSAerr(RSA_F_RSA_PADDING_CHECK_PKCS1_TYPE_1,RSA_R_NULL_BEFORE_BLOCK_MISSING); */
631		return (-1);
632	}
633
634	if (i < 8) {
635		/* RSAerr(RSA_F_RSA_PADDING_CHECK_PKCS1_TYPE_1,RSA_R_BAD_PAD_BYTE_COUNT); */
636		return (-1);
637	}
638	i++; /* Skip over the '\0' */
639	j -= i;
640	if (j > tlen) {
641		/* RSAerr(RSA_F_RSA_PADDING_CHECK_PKCS1_TYPE_1,RSA_R_DATA_TOO_LARGE); */
642		return (-1);
643	}
644	memcpy(to, p, (unsigned int)j);
645
646	return (j);
647}
648
649
650static int
651RSA_padding_add_PKCS1_type_2(unsigned char *to, int tlen,
652    const unsigned char *from, int flen)
653{
654	int i, j;
655	unsigned char *p;
656
657	if (flen > (tlen-11)) {
658		/* RSAerr(RSA_F_RSA_PADDING_ADD_PKCS1_TYPE_2,RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE); */
659		return (0);
660	}
661
662	p = (unsigned char *)to;
663
664	*(p++) = 0;
665	*(p++) = 2; /* Public Key BT (Block Type) */
666
667	/* pad out with non-zero random data */
668	j = tlen - 3 - flen;
669
670	if (RAND_bytes(p, j) <= 0) {
671		return (0);
672	}
673	for (i = 0; i < j; i++) {
674		if (*p == '\0') {
675			do {
676				if (RAND_bytes(p, 1) <= 0) {
677					return (0);
678				}
679			} while (*p == '\0');
680		}
681		p++;
682	}
683
684	*(p++) = '\0';
685
686	memcpy(p, from, (unsigned int)flen);
687
688	return (1);
689}
690
691
692static int
693RSA_padding_check_PKCS1_type_2(unsigned char *to, int tlen,
694    const unsigned char *from, int flen, int num)
695{
696	int i, j;
697	const unsigned char *p;
698
699	p = from;
700	if ((num != (flen+1)) || (*(p++) != 02)) {
701		/* RSAerr(RSA_F_RSA_PADDING_CHECK_PKCS1_TYPE_2,RSA_R_BLOCK_TYPE_IS_NOT_02); */
702		return (-1);
703	}
704#ifdef PKCS1_CHECK
705	return (num - 11);
706#endif
707
708	/* scan over padding data */
709	j = flen - 1; /* one for type. */
710	for (i = 0; i < j; i++) {
711		if (*(p++) == 0) {
712			break;
713		}
714	}
715
716	if (i == j) {
717		/* RSAerr(RSA_F_RSA_PADDING_CHECK_PKCS1_TYPE_2,RSA_R_NULL_BEFORE_BLOCK_MISSING); */
718		return (-1);
719	}
720
721	if (i < 8) {
722		/* RSAerr(RSA_F_RSA_PADDING_CHECK_PKCS1_TYPE_2,RSA_R_BAD_PAD_BYTE_COUNT); */
723		return (-1);
724	}
725	i++; /* Skip over the '\0' */
726	j -= i;
727	if (j > tlen) {
728		/* RSAerr(RSA_F_RSA_PADDING_CHECK_PKCS1_TYPE_2,RSA_R_DATA_TOO_LARGE); */
729		return (-1);
730	}
731	memcpy(to, p, (unsigned int)j);
732
733	return (j);
734}
735
736
737/* signing */
738static int
739cc_rsa_private_encrypt(int flen, const unsigned char *from,
740    unsigned char *to, RSA *rsa, int padding)
741{
742	BIGNUM *f, *ret, *br, *res;
743	int i, j, k, num = 0, r = -1;
744	unsigned char *buf = NULL;
745	BN_CTX *ctx = NULL;
746
747#if 0
748	int local_blinding = 0;
749	BN_BLINDING *blinding = NULL;
750#endif
751
752	if ((ctx = BN_CTX_new()) == NULL) {
753		goto err;
754	}
755	BN_CTX_start(ctx);
756	f = BN_CTX_get(ctx);
757	br = BN_CTX_get(ctx);
758	ret = BN_CTX_get(ctx);
759	num = BN_num_bytes(rsa->n);
760	buf = malloc(num);
761	if (!f || !ret || !buf) {
762		/* RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,ERR_R_MALLOC_FAILURE); */
763		goto err;
764	}
765
766	switch (padding) {
767	case RSA_PKCS1_PADDING:
768		i = RSA_padding_add_PKCS1_type_1(buf, num, from, flen);
769		break;
770
771#if 0
772	case RSA_X931_PADDING:
773		i = RSA_padding_add_X931(buf, num, from, flen);
774		break;
775
776	case RSA_NO_PADDING:
777		i = RSA_padding_add_none(buf, num, from, flen);
778		break;
779
780	case RSA_SSLV23_PADDING:
781#endif
782	default:
783		/* RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,RSA_R_UNKNOWN_PADDING_TYPE); */
784		goto err;
785	}
786	if (i <= 0) {
787		goto err;
788	}
789
790	if (BN_bin2bn(buf, num, f) == NULL) {
791		goto err;
792	}
793
794	if (BN_ucmp(f, rsa->n) >= 0) {
795		/* usually the padding functions would catch this */
796		/* RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,RSA_R_DATA_TOO_LARGE_FOR_MODULUS); */
797		goto err;
798	}
799
800#if 0
801	if (!(rsa->flags & RSA_FLAG_NO_BLINDING)) {
802		blinding = rsa_get_blinding(rsa, &local_blinding, ctx);
803		if (blinding == NULL) {
804			/* RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT, ERR_R_INTERNAL_ERROR); */
805			goto err;
806		}
807	}
808
809	if (blinding != NULL) {
810		if (!rsa_blinding_convert(blinding, local_blinding, f, br, ctx)) {
811			goto err;
812		}
813	}
814#endif
815
816	if ((rsa->flags & RSA_FLAG_EXT_PKEY) ||
817	    ((rsa->p != NULL) &&
818	    (rsa->q != NULL) &&
819	    (rsa->dmp1 != NULL) &&
820	    (rsa->dmq1 != NULL) &&
821	    (rsa->iqmp != NULL))) {
822		if (!rsa->meth->rsa_mod_exp(ret, f, rsa, ctx)) {
823			goto err;
824		}
825	} else {
826		BIGNUM local_d;
827		BIGNUM *d = NULL;
828
829		if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
830			BN_init(&local_d);
831			d = &local_d;
832			BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME);
833		} else{
834			d = rsa->d;
835		}
836
837#if 0
838		if (rsa->flags & RSA_FLAG_CACHE_PUBLIC) {
839			if (!BN_MONT_CTX_set_locked(&rsa->_method_mod_n, CRYPTO_LOCK_RSA, rsa->n, ctx)) {
840				goto err;
841			}
842		}
843#endif
844
845		if (!rsa->meth->bn_mod_exp(ret, f, d, rsa->n, ctx, rsa->_method_mod_n)) {
846			goto err;
847		}
848	}
849
850#if 0
851	if (blinding) {
852		if (!rsa_blinding_invert(blinding, local_blinding, ret, br, ctx)) {
853			goto err;
854		}
855	}
856#endif
857
858#if 0
859	if (padding == RSA_X931_PADDING) {
860		BN_sub(f, rsa->n, ret);
861		if (BN_cmp(ret, f)) {
862			res = f;
863		} else{
864			res = ret;
865		}
866	} else
867#endif
868	res = ret;
869
870	/* put in leading 0 bytes if the number is less than the
871	 * length of the modulus */
872	j = BN_num_bytes(res);
873	i = BN_bn2bin(res, &(to[num-j]));
874	for (k = 0; k < (num-i); k++) {
875		to[k] = 0;
876	}
877
878	r = num;
879err:
880	if (ctx != NULL) {
881		BN_CTX_end(ctx);
882		BN_CTX_free(ctx);
883	}
884	if (buf != NULL) {
885		memset(buf, 0, num);
886		free(buf);
887	}
888	return (r);
889}
890
891
892/* signature verification */
893static int
894cc_rsa_public_decrypt(int flen, const unsigned char *from,
895    unsigned char *to, RSA *rsa, int padding)
896{
897	BIGNUM *f, *ret;
898	int i, num = 0, r = -1;
899	unsigned char *p;
900	unsigned char *buf = NULL;
901	BN_CTX *ctx = NULL;
902
903	if (BN_num_bits(rsa->n) > RSA_MAX_MODULUS_BITS) {
904		/* RSAerr(RSA_F_RSA_EAY_PUBLIC_DECRYPT, RSA_R_MODULUS_TOO_LARGE); */
905		return (-1);
906	}
907
908	if (BN_ucmp(rsa->n, rsa->e) <= 0) {
909		/* RSAerr(RSA_F_RSA_EAY_PUBLIC_DECRYPT, RSA_R_BAD_E_VALUE); */
910		return (-1);
911	}
912
913	/* for large moduli, enforce exponent limit */
914	if (BN_num_bits(rsa->n) > RSA_SMALL_MODULUS_BITS) {
915		if (BN_num_bits(rsa->e) > RSA_MAX_PUBEXP_BITS) {
916			/* RSAerr(RSA_F_RSA_EAY_PUBLIC_DECRYPT, RSA_R_BAD_E_VALUE); */
917			return (-1);
918		}
919	}
920
921	if ((ctx = BN_CTX_new()) == NULL) {
922		goto err;
923	}
924	BN_CTX_start(ctx);
925	f = BN_CTX_get(ctx);
926	ret = BN_CTX_get(ctx);
927	num = BN_num_bytes(rsa->n);
928	buf = malloc(num);
929	if (!f || !ret || !buf) {
930		/* RSAerr(RSA_F_RSA_EAY_PUBLIC_DECRYPT,ERR_R_MALLOC_FAILURE); */
931		goto err;
932	}
933
934	/* This check was for equality but PGP does evil things
935	 * and chops off the top '0' bytes */
936	if (flen > num) {
937		/* RSAerr(RSA_F_RSA_EAY_PUBLIC_DECRYPT,RSA_R_DATA_GREATER_THAN_MOD_LEN); */
938		goto err;
939	}
940
941	if (BN_bin2bn(from, flen, f) == NULL) {
942		goto err;
943	}
944
945	if (BN_ucmp(f, rsa->n) >= 0) {
946		/* RSAerr(RSA_F_RSA_EAY_PUBLIC_DECRYPT,RSA_R_DATA_TOO_LARGE_FOR_MODULUS); */
947		goto err;
948	}
949
950#if 0
951	if (rsa->flags & RSA_FLAG_CACHE_PUBLIC) {
952		if (!BN_MONT_CTX_set_locked(&rsa->_method_mod_n, CRYPTO_LOCK_RSA, rsa->n, ctx)) {
953			goto err;
954		}
955	}
956#endif
957
958	if (!rsa->meth->bn_mod_exp(ret, f, rsa->e, rsa->n, ctx, rsa->_method_mod_n)) {
959		goto err;
960	}
961
962#if 0
963	if ((padding == RSA_X931_PADDING) && ((ret->d[0] & 0xf) != 12)) {
964		if (!BN_sub(ret, rsa->n, ret)) {
965			goto err;
966		}
967	}
968#endif
969
970	p = buf;
971	i = BN_bn2bin(ret, p);
972
973	switch (padding) {
974	case RSA_PKCS1_PADDING:
975		r = RSA_padding_check_PKCS1_type_1(to, num, buf, i, num);
976		break;
977
978#if 0
979	case RSA_X931_PADDING:
980		r = RSA_padding_check_X931(to, num, buf, i, num);
981		break;
982
983	case RSA_NO_PADDING:
984		r = RSA_padding_check_none(to, num, buf, i, num);
985		break;
986#endif
987	default:
988		/* RSAerr(RSA_F_RSA_EAY_PUBLIC_DECRYPT,RSA_R_UNKNOWN_PADDING_TYPE); */
989		goto err;
990	}
991
992	/*
993	 * if (r < 0)
994	 *      RSAerr(RSA_F_RSA_EAY_PUBLIC_DECRYPT,RSA_R_PADDING_CHECK_FAILED);
995	 */
996
997err:
998	if (ctx != NULL) {
999		BN_CTX_end(ctx);
1000		BN_CTX_free(ctx);
1001	}
1002	if (buf != NULL) {
1003		memset(buf, 0, num);
1004		free(buf);
1005	}
1006
1007	return (r);
1008}
1009
1010
1011static int
1012cc_rsa_mod_exp(BIGNUM *r0, const BIGNUM *I, RSA *rsa, BN_CTX *ctx)
1013{
1014	BIGNUM *r1, *m1, *vrfy;
1015	BIGNUM local_dmp1, local_dmq1, local_c, local_r1;
1016	BIGNUM *dmp1, *dmq1, *c, *pr1;
1017	int ret = 0;
1018
1019	BN_CTX_start(ctx);
1020	r1 = BN_CTX_get(ctx);
1021	m1 = BN_CTX_get(ctx);
1022	vrfy = BN_CTX_get(ctx);
1023
1024	{
1025		BIGNUM local_p, local_q;
1026		BIGNUM *p = NULL, *q = NULL;
1027
1028		/* Make sure BN_mod_inverse in Montgomery intialization uses the
1029		 * BN_FLG_CONSTTIME flag (unless RSA_FLAG_NO_CONSTTIME is set)
1030		 */
1031		if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
1032			BN_init(&local_p);
1033			p = &local_p;
1034			BN_with_flags(p, rsa->p, BN_FLG_CONSTTIME);
1035
1036			BN_init(&local_q);
1037			q = &local_q;
1038			BN_with_flags(q, rsa->q, BN_FLG_CONSTTIME);
1039		} else {
1040			p = rsa->p;
1041			q = rsa->q;
1042		}
1043
1044#if 0
1045		if (rsa->flags & RSA_FLAG_CACHE_PRIVATE) {
1046			if (!BN_MONT_CTX_set_locked(&rsa->_method_mod_p, CRYPTO_LOCK_RSA, p, ctx)) {
1047				goto err;
1048			}
1049			if (!BN_MONT_CTX_set_locked(&rsa->_method_mod_q, CRYPTO_LOCK_RSA, q, ctx)) {
1050				goto err;
1051			}
1052		}
1053#endif
1054	}
1055
1056#if 0
1057	if (rsa->flags & RSA_FLAG_CACHE_PUBLIC) {
1058		if (!BN_MONT_CTX_set_locked(&rsa->_method_mod_n, CRYPTO_LOCK_RSA, rsa->n, ctx)) {
1059			goto err;
1060		}
1061	}
1062#endif
1063
1064	/* compute I mod q */
1065	if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
1066		c = &local_c;
1067		BN_with_flags(c, I, BN_FLG_CONSTTIME);
1068		if (!BN_mod(r1, c, rsa->q, ctx)) {
1069			goto err;
1070		}
1071	} else {
1072		if (!BN_mod(r1, I, rsa->q, ctx)) {
1073			goto err;
1074		}
1075	}
1076
1077	/* compute r1^dmq1 mod q */
1078	if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
1079		dmq1 = &local_dmq1;
1080		BN_with_flags(dmq1, rsa->dmq1, BN_FLG_CONSTTIME);
1081	} else{
1082		dmq1 = rsa->dmq1;
1083	}
1084
1085	if (!rsa->meth->bn_mod_exp(m1, r1, dmq1, rsa->q, ctx, rsa->_method_mod_q)) {
1086		goto err;
1087	}
1088
1089	/* compute I mod p */
1090	if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
1091		c = &local_c;
1092		BN_with_flags(c, I, BN_FLG_CONSTTIME);
1093		if (!BN_mod(r1, c, rsa->p, ctx)) {
1094			goto err;
1095		}
1096	} else {
1097		if (!BN_mod(r1, I, rsa->p, ctx)) {
1098			goto err;
1099		}
1100	}
1101
1102	/* compute r1^dmp1 mod p */
1103	if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
1104		dmp1 = &local_dmp1;
1105		BN_with_flags(dmp1, rsa->dmp1, BN_FLG_CONSTTIME);
1106	} else{
1107		dmp1 = rsa->dmp1;
1108	}
1109	if (!rsa->meth->bn_mod_exp(r0, r1, dmp1, rsa->p, ctx, rsa->_method_mod_p)) {
1110		goto err;
1111	}
1112
1113	if (!BN_sub(r0, r0, m1)) {
1114		goto err;
1115	}
1116
1117	/* This will help stop the size of r0 increasing, which does
1118	 * affect the multiply if it optimised for a power of 2 size */
1119	if (BN_is_negative(r0)) {
1120		if (!BN_add(r0, r0, rsa->p)) {
1121			goto err;
1122		}
1123	}
1124
1125	if (!BN_mul(r1, r0, rsa->iqmp, ctx)) {
1126		goto err;
1127	}
1128
1129	/* Turn BN_FLG_CONSTTIME flag on before division operation */
1130	if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
1131		pr1 = &local_r1;
1132		BN_with_flags(pr1, r1, BN_FLG_CONSTTIME);
1133	} else{
1134		pr1 = r1;
1135	}
1136	if (!BN_mod(r0, pr1, rsa->p, ctx)) {
1137		goto err;
1138	}
1139
1140	/* If p < q it is occasionally possible for the correction of
1141	 * adding 'p' if r0 is negative above to leave the result still
1142	 * negative. This can break the private key operations: the following
1143	 * second correction should *always* correct this rare occurrence.
1144	 * This will *never* happen with OpenSSL generated keys because
1145	 * they ensure p > q [steve]
1146	 */
1147	if (BN_is_negative(r0)) {
1148		if (!BN_add(r0, r0, rsa->p)) {
1149			goto err;
1150		}
1151	}
1152	if (!BN_mul(r1, r0, rsa->q, ctx)) {
1153		goto err;
1154	}
1155	if (!BN_add(r0, r1, m1)) {
1156		goto err;
1157	}
1158
1159	if (rsa->e && rsa->n) {
1160		if (!rsa->meth->bn_mod_exp(vrfy, r0, rsa->e, rsa->n, ctx,
1161		    rsa->_method_mod_n)) {
1162			goto err;
1163		}
1164
1165		/* If 'I' was greater than (or equal to) rsa->n, the operation
1166		 * will be equivalent to using 'I mod n'. However, the result of
1167		 * the verify will *always* be less than 'n' so we don't check
1168		 * for absolute equality, just congruency. */
1169		if (!BN_sub(vrfy, vrfy, I)) {
1170			goto err;
1171		}
1172		if (!BN_mod(vrfy, vrfy, rsa->n, ctx)) {
1173			goto err;
1174		}
1175		if (BN_is_negative(vrfy)) {
1176			if (!BN_add(vrfy, vrfy, rsa->n)) {
1177				goto err;
1178			}
1179		}
1180		if (!BN_is_zero(vrfy)) {
1181			/* 'I' and 'vrfy' aren't congruent mod n. Don't leak
1182			 * miscalculated CRT output, just do a raw (slower)
1183			 * mod_exp and return that instead. */
1184
1185			BIGNUM local_d;
1186			BIGNUM *d = NULL;
1187
1188			if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
1189				d = &local_d;
1190				BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME);
1191			} else{
1192				d = rsa->d;
1193			}
1194			if (!rsa->meth->bn_mod_exp(r0, I, d, rsa->n, ctx,
1195			    rsa->_method_mod_n)) {
1196				goto err;
1197			}
1198		}
1199	}
1200	ret = 1;
1201err:
1202	BN_CTX_end(ctx);
1203	return (ret);
1204}
1205
1206
1207#endif /* ! PR_10783242_FIXED */
1208
1209/*
1210 * RSA key generation.
1211 */
1212#if 0
1213int
1214CC_RSA_generate_key_ex(RSA *rsa, int keybits, BIGNUM *bn_e, void *cb)
1215{
1216	CCCryptorStatus status;
1217	unsigned long eword = BN_get_word(bn_e);
1218	CCRSACryptorRef public = NULL, private = NULL;
1219	uint8_t *npublic = NULL, *nprivate = NULL, *e = NULL, *d = NULL, *p = NULL, *q = NULL;
1220	size_t npubliclen, nprivatelen, elen, dlen, plen, qlen;
1221	size_t keybytes = ((keybits + 7) / 8) + 1;
1222
1223	if (0xffffffffL == eword) {
1224		/* XXX Need to set OpenSSL error code here on failure. */
1225		return (0);
1226	}
1227
1228	status = CCRSACryptorGeneratePair((size_t)keybits, (uint32_t)eword, &public, &private);
1229	if (kCCSuccess != status) {
1230		/* XXX Need to set OpenSSL error code here on failure. */
1231		return (0);
1232	}
1233
1234	if ((npublic = malloc(keybytes)) == NULL) {
1235		goto outerr;
1236	}
1237	if ((nprivate = malloc(keybytes)) == NULL) {
1238		goto outerr;
1239	}
1240	if ((e = malloc(keybytes)) == NULL) {
1241		goto outerr;
1242	}
1243	if ((d = malloc(keybytes)) == NULL) {
1244		goto outerr;
1245	}
1246	if ((p = malloc(keybytes)) == NULL) {
1247		goto outerr;
1248	}
1249	if ((q = malloc(keybytes)) == NULL) {
1250		goto outerr;
1251	}
1252
1253	npubliclen = elen = keybytes;
1254	dlen = plen = qlen = 0;
1255	status = CCRSAGetKeyComponents(public, npublic, &npubliclen, e, &elen, p, &plen, q, &qlen);
1256	if (kCCSuccess != status) {
1257		/* XXX Need to set OpenSSL error code here on failure. */
1258		return (0);
1259	}
1260	if ((rsa->n = BN_bin2bn((const unsigned char *)npublic, (int)npubliclen, NULL)) == NULL) {
1261		goto outerr;
1262	}
1263	if ((rsa->e = BN_bin2bn((const unsigned char *)e, (int)elen, NULL)) == NULL) {
1264		goto outerr;
1265	}
1266
1267	/* NOTE: d is returned in the exponent (e) for the private key */
1268	nprivatelen = dlen = plen = qlen = keybytes;
1269	status = CCRSAGetKeyComponents(private, nprivate, &nprivatelen, d, &dlen, p, &plen, q, &qlen);
1270	if (kCCSuccess != status) {
1271		/* XXX Need to set OpenSSL error code here on failure. */
1272		return (0);
1273	}
1274
1275	if ((npubliclen != nprivatelen) || (memcmp(npublic, nprivate, nprivatelen) != 0)) {
1276		goto outerr;
1277	}
1278
1279	/* We need the RSA components non-NULL */
1280	if (!rsa->n && ((rsa->n = BN_new()) == NULL)) {
1281		goto outerr;
1282	}
1283	if (!rsa->d && ((rsa->d = BN_new()) == NULL)) {
1284		goto outerr;
1285	}
1286	if (!rsa->e && ((rsa->e = BN_new()) == NULL)) {
1287		goto outerr;
1288	}
1289	if (!rsa->p && ((rsa->p = BN_new()) == NULL)) {
1290		goto outerr;
1291	}
1292	if (!rsa->q && ((rsa->q = BN_new()) == NULL)) {
1293		goto outerr;
1294	}
1295	if (!rsa->dmp1 && ((rsa->dmp1 = BN_new()) == NULL)) {
1296		goto outerr;
1297	}
1298	if (!rsa->dmq1 && ((rsa->dmq1 = BN_new()) == NULL)) {
1299		goto outerr;
1300	}
1301	if (!rsa->iqmp && ((rsa->iqmp = BN_new()) == NULL)) {
1302		goto outerr;
1303	}
1304
1305	if (BN_bin2bn((const unsigned char *)npublic, (int)npubliclen, rsa->n) == NULL) {
1306		goto outerr;
1307	}
1308	if (BN_bin2bn((const unsigned char *)e, (int)elen, rsa->e) == NULL) {
1309		goto outerr;
1310	}
1311	if (BN_bin2bn((const unsigned char *)d, (int)dlen, rsa->d) == NULL) {
1312		goto outerr;
1313	}
1314	if (BN_bin2bn((const unsigned char *)p, (int)plen, rsa->p) == NULL) {
1315		goto outerr;
1316	}
1317	if (BN_bin2bn((const unsigned char *)q, (int)qlen, rsa->q) == NULL) {
1318		goto outerr;
1319	}
1320
1321	if (RSA_check_key(rsa) != 1) {
1322		char buf[1024];
1323		unsigned long err = ERR_get_error();
1324		ERR_error_string_n(err, buf, 1024);
1325		printf("RSA is invalid!! %s\n", buf);
1326		return (0);
1327	}
1328
1329	BIGNUM local_d, local_p;
1330	BIGNUM *dbn, *pbn;
1331	BIGNUM *r1 = NULL, *r2 = NULL;
1332	BN_CTX *ctx = NULL;
1333
1334	ctx = BN_CTX_new();
1335	if (ctx == NULL) {
1336		goto outerr;
1337	}
1338	BN_CTX_start(ctx);
1339	if ((r1 = BN_CTX_get(ctx)) == NULL) {
1340		goto outerr;
1341	}
1342	if ((r2 = BN_CTX_get(ctx)) == NULL) {
1343		goto outerr;
1344	}
1345
1346	/* set up d for correct BN_FLG_CONSTTIME flag */
1347	if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
1348		dbn = &local_d;
1349		BN_with_flags(dbn, rsa->d, BN_FLG_CONSTTIME);
1350	}else          {
1351		dbn = rsa->d;
1352	}
1353
1354	/* calculate d mod (p-1) */
1355	if (!BN_sub(r1, rsa->p, BN_value_one())) {
1356		goto outerr;                                    /* p-1 */
1357	}
1358	if (!BN_mod(rsa->dmp1, dbn, r1, ctx)) {
1359		goto outerr;
1360	}
1361
1362	/* calculate d mod (q-1) */
1363	if (!BN_sub(r2, rsa->q, BN_value_one())) {
1364		goto outerr;                                    /* q-1 */
1365	}
1366	if (!BN_mod(rsa->dmq1, dbn, r2, ctx)) {
1367		goto outerr;
1368	}
1369
1370	/* calculate inverse of q mod p */
1371	if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
1372		pbn = &local_p;
1373		BN_with_flags(pbn, rsa->p, BN_FLG_CONSTTIME);
1374	}else          {
1375		pbn = rsa->p;
1376	}
1377	if (!BN_mod_inverse(rsa->iqmp, rsa->q, pbn, ctx)) {
1378		goto outerr;
1379	}
1380
1381	CCRSACryptorRelease(public);
1382	CCRSACryptorRelease(private);
1383	free(npublic);
1384	free(nprivate);
1385	free(e);
1386	free(d);
1387	free(p);
1388	free(q);
1389	BN_CTX_end(ctx);
1390	BN_CTX_free(ctx);
1391
1392	return (1);
1393
1394outerr:
1395	if (ctx != NULL) {
1396		BN_CTX_end(ctx);
1397		BN_CTX_free(ctx);
1398	}
1399	if (public != NULL) {
1400		CCRSACryptorRelease(public);
1401	}
1402	if (private != NULL) {
1403		CCRSACryptorRelease(private);
1404	}
1405
1406	if (rsa->n != NULL) {
1407		BN_clear_free(rsa->n);
1408	}
1409	if (rsa->e != NULL) {
1410		BN_clear_free(rsa->e);
1411	}
1412	if (rsa->d != NULL) {
1413		BN_clear_free(rsa->d);
1414	}
1415	if (rsa->p != NULL) {
1416		BN_clear_free(rsa->p);
1417	}
1418	if (rsa->q != NULL) {
1419		BN_clear_free(rsa->q);
1420	}
1421	if (rsa->dmp1 != NULL) {
1422		BN_clear_free(rsa->dmp1);
1423	}
1424	if (rsa->dmq1 != NULL) {
1425		BN_clear_free(rsa->dmq1);
1426	}
1427	if (rsa->iqmp != NULL) {
1428		BN_clear_free(rsa->iqmp);
1429	}
1430
1431	if (NULL == npublic) {
1432		free(npublic);
1433	}
1434	if (NULL == npublic) {
1435		free(nprivate);
1436	}
1437	if (NULL == e) {
1438		free(e);
1439	}
1440	if (NULL == d) {
1441		free(d);
1442	}
1443	if (NULL == p) {
1444		free(p);
1445	}
1446	if (NULL == q) {
1447		free(q);
1448	}
1449
1450	/* XXX Need to set OpenSSL error code here on failure. */
1451	return (0);
1452}
1453
1454
1455#else
1456
1457static int
1458cc_rsa_builtin_keygen(RSA *rsa, int bits, BIGNUM *e_value, void *cb)
1459{
1460	BIGNUM *r0 = NULL, *r1 = NULL, *r2 = NULL, *r3 = NULL, *tmp;
1461	BIGNUM local_r0, local_d, local_p;
1462	BIGNUM *pr0, *d, *p;
1463	int bitsp, bitsq, ok = -1, n = 0;
1464	BN_CTX *ctx = NULL;
1465
1466	ctx = BN_CTX_new();
1467	if (ctx == NULL) {
1468		goto err;
1469	}
1470	BN_CTX_start(ctx);
1471	r0 = BN_CTX_get(ctx);
1472	r1 = BN_CTX_get(ctx);
1473	r2 = BN_CTX_get(ctx);
1474	r3 = BN_CTX_get(ctx);
1475	if (r3 == NULL) {
1476		goto err;
1477	}
1478
1479	bitsp = (bits + 1) / 2;
1480	bitsq = bits - bitsp;
1481
1482	/* We need the RSA components to be non-NULL */
1483	if (!rsa->n && ((rsa->n = BN_new()) == NULL)) {
1484		goto err;
1485	}
1486	if (!rsa->d && ((rsa->d = BN_new()) == NULL)) {
1487		goto err;
1488	}
1489	if (!rsa->e && ((rsa->e = BN_new()) == NULL)) {
1490		goto err;
1491	}
1492	if (!rsa->p && ((rsa->p = BN_new()) == NULL)) {
1493		goto err;
1494	}
1495	if (!rsa->q && ((rsa->q = BN_new()) == NULL)) {
1496		goto err;
1497	}
1498	if (!rsa->dmp1 && ((rsa->dmp1 = BN_new()) == NULL)) {
1499		goto err;
1500	}
1501	if (!rsa->dmq1 && ((rsa->dmq1 = BN_new()) == NULL)) {
1502		goto err;
1503	}
1504	if (!rsa->iqmp && ((rsa->iqmp = BN_new()) == NULL)) {
1505		goto err;
1506	}
1507
1508	BN_copy(rsa->e, e_value);
1509
1510	/* generate p and q */
1511	for ( ; ; ) {
1512		if (!BN_generate_prime_ex(rsa->p, bitsp, 0, NULL, NULL, NULL)) {
1513			goto err;
1514		}
1515		if (!BN_sub(r2, rsa->p, BN_value_one())) {
1516			goto err;
1517		}
1518		if (!BN_gcd(r1, r2, rsa->e, ctx)) {
1519			goto err;
1520		}
1521		if (BN_is_one(r1)) {
1522			break;
1523		}
1524	}
1525	for ( ; ; ) {
1526		/* When generating ridiculously small keys, we can get stuck
1527		 * continually regenerating the same prime values. Check for
1528		 * this and bail if it happens 3 times. */
1529		unsigned int degenerate = 0;
1530		do {
1531			if (!BN_generate_prime_ex(rsa->q, bitsq, 0, NULL, NULL, NULL)) {
1532				goto err;
1533			}
1534		} while ((BN_cmp(rsa->p, rsa->q) == 0) && (++degenerate < 3));
1535		if (degenerate == 3) {
1536			ok = 0; /* we set our own err */
1537			/* RSAerr(RSA_F_RSA_BUILTIN_KEYGEN,RSA_R_KEY_SIZE_TOO_SMALL); */
1538			goto err;
1539		}
1540		if (!BN_sub(r2, rsa->q, BN_value_one())) {
1541			goto err;
1542		}
1543		if (!BN_gcd(r1, r2, rsa->e, ctx)) {
1544			goto err;
1545		}
1546		if (BN_is_one(r1)) {
1547			break;
1548		}
1549	}
1550	if (BN_cmp(rsa->p, rsa->q) < 0) {
1551		tmp = rsa->p;
1552		rsa->p = rsa->q;
1553		rsa->q = tmp;
1554	}
1555
1556	/* calculate n */
1557	if (!BN_mul(rsa->n, rsa->p, rsa->q, ctx)) {
1558		goto err;
1559	}
1560
1561	/* calculate d */
1562	if (!BN_sub(r1, rsa->p, BN_value_one())) {
1563		goto err;                                       /* p-1 */
1564	}
1565	if (!BN_sub(r2, rsa->q, BN_value_one())) {
1566		goto err;                                       /* q-1 */
1567	}
1568	if (!BN_mul(r0, r1, r2, ctx)) {
1569		goto err;                       /* (p-1)(q-1) */
1570	}
1571	if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
1572		pr0 = &local_r0;
1573		BN_with_flags(pr0, r0, BN_FLG_CONSTTIME);
1574	} else{
1575		pr0 = r0;
1576	}
1577
1578	if (!BN_mod_inverse(rsa->d, rsa->e, pr0, ctx)) {
1579		goto err;                                               /* d */
1580	}
1581	/* set up d for correct BN_FLG_CONSTTIME flag */
1582	if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
1583		d = &local_d;
1584		BN_with_flags(d, rsa->d, BN_FLG_CONSTTIME);
1585	} else{
1586		d = rsa->d;
1587	}
1588
1589	/* calculate d mod (p-1) */
1590	if (!BN_mod(rsa->dmp1, d, r1, ctx)) {
1591		goto err;
1592	}
1593
1594	/* calculate d mod (q-1) */
1595	if (!BN_mod(rsa->dmq1, d, r2, ctx)) {
1596		goto err;
1597	}
1598
1599	/* calculate inverse of q mod p */
1600	if (!(rsa->flags & RSA_FLAG_NO_CONSTTIME)) {
1601		p = &local_p;
1602		BN_with_flags(p, rsa->p, BN_FLG_CONSTTIME);
1603	} else{
1604		p = rsa->p;
1605	}
1606	if (!BN_mod_inverse(rsa->iqmp, rsa->q, p, ctx)) {
1607		goto err;
1608	}
1609
1610	ok = 1;
1611err:
1612	if (ok == -1) {
1613		/* RSAerr(RSA_F_RSA_BUILTIN_KEYGEN,ERR_LIB_BN); */
1614		ok = 0;
1615	}
1616	if (ctx != NULL) {
1617		BN_CTX_end(ctx);
1618		BN_CTX_free(ctx);
1619	}
1620
1621	return (ok);
1622}
1623
1624
1625#endif /* ! #if 0 */
1626
1627
1628static int cc_rsa_generate_key(RSA *rsa, int bits, BIGNUM *e_value, BN_GENCB *cb)
1629{
1630	return (cc_rsa_builtin_keygen(rsa, bits, e_value, cb));
1631}
1632
1633
1634const RSA_METHOD _ossl_rsa_cc_method =
1635{
1636	.name		= "CommonCrypto RSA",
1637	.rsa_pub_enc	= cc_rsa_public_encrypt,
1638	.rsa_pub_dec	= cc_rsa_public_decrypt,
1639	.rsa_priv_enc	= cc_rsa_private_encrypt,
1640	.rsa_priv_dec	= cc_rsa_private_decrypt,
1641	.rsa_mod_exp	= cc_rsa_mod_exp,
1642	.bn_mod_exp	= BN_mod_exp_mont,
1643	.init		= cc_rsa_init,
1644	.finish		= cc_rsa_finish,
1645	.flags		=		     0,
1646	.app_data	= NULL,
1647	.rsa_sign	= cc_rsa_sign,
1648	.rsa_verify	= cc_rsa_verify,
1649	.rsa_keygen	= cc_rsa_generate_key
1650};
1651#endif /* HAVE_COMMONCRYPTO_COMMONRSACRYPTOR_H */
1652
1653const RSA_METHOD *
1654RSA_cc_method(void)
1655{
1656#ifdef HAVE_COMMONCRYPTO_COMMONRSACRYPTOR_H
1657	return (&_ossl_rsa_cc_method);
1658
1659#else
1660	return (NULL);
1661#endif
1662}
1663