1/*
2 * Copyright (c) 2006 - 2008 Kungliga Tekniska Högskolan
3 * (Royal Institute of Technology, Stockholm, Sweden).
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 *
13 * 2. Redistributions in binary form must reproduce the above copyright
14 *    notice, this list of conditions and the following disclaimer in the
15 *    documentation and/or other materials provided with the distribution.
16 *
17 * 3. Neither the name of the Institute nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
34#include <config.h>
35
36#include <stdio.h>
37#include <stdlib.h>
38#include <krb5-types.h>
39#include <rfc2459_asn1.h>
40
41#include <der.h>
42
43#include <rsa.h>
44
45#include "common.h"
46
47#include <roken.h>
48
49/**
50 * @page page_rsa RSA - public-key cryptography
51 *
52 * RSA is named by its inventors (Ron Rivest, Adi Shamir, and Leonard
53 * Adleman) (published in 1977), patented expired in 21 September 2000.
54 *
55 *
56 * Speed for RSA in seconds
57 *   no key blinding
58 *   1000 iteration,
59 *   same rsa keys (1024 and 2048)
60 *   operation performed each eteration sign, verify, encrypt, decrypt on a random bit pattern
61 *
62 * name		1024	2048	4098
63 * =================================
64 * gmp: 	 0.73	  6.60	 44.80
65 * tfm: 	 2.45	    --	    --
66 * ltm:		 3.79	 20.74	105.41	(default in hcrypto)
67 * openssl:	 4.04	 11.90	 82.59
68 * cdsa:	15.89	102.89	721.40
69 * imath: 	40.62	    --	    --
70 *
71 * See the library functions here: @ref hcrypto_rsa
72 */
73
74/**
75 * Same as RSA_new_method() using NULL as engine.
76 *
77 * @return a newly allocated RSA object. Free with RSA_free().
78 *
79 * @ingroup hcrypto_rsa
80 */
81
82RSA *
83RSA_new(void)
84{
85    return RSA_new_method(NULL);
86}
87
88/**
89 * Allocate a new RSA object using the engine, if NULL is specified as
90 * the engine, use the default RSA engine as returned by
91 * ENGINE_get_default_RSA().
92 *
93 * @param engine Specific what ENGINE RSA provider should be used.
94 *
95 * @return a newly allocated RSA object. Free with RSA_free().
96 *
97 * @ingroup hcrypto_rsa
98 */
99
100RSA *
101RSA_new_method(ENGINE *engine)
102{
103    RSA *rsa;
104
105    rsa = calloc(1, sizeof(*rsa));
106    if (rsa == NULL)
107	return NULL;
108
109    rsa->references = 1;
110
111    if (engine) {
112	ENGINE_up_ref(engine);
113	rsa->engine = engine;
114    } else {
115	rsa->engine = ENGINE_get_default_RSA();
116    }
117
118    if (rsa->engine) {
119	rsa->meth = ENGINE_get_RSA(rsa->engine);
120	if (rsa->meth == NULL) {
121	    ENGINE_finish(engine);
122	    free(rsa);
123	    return 0;
124	}
125    }
126
127    if (rsa->meth == NULL)
128	rsa->meth = rk_UNCONST(RSA_get_default_method());
129
130    (*rsa->meth->init)(rsa);
131
132    return rsa;
133}
134
135/**
136 * Free an allocation RSA object.
137 *
138 * @param rsa the RSA object to free.
139 * @ingroup hcrypto_rsa
140 */
141
142void
143RSA_free(RSA *rsa)
144{
145    if (rsa->references <= 0)
146	abort();
147
148    if (--rsa->references > 0)
149	return;
150
151    (*rsa->meth->finish)(rsa);
152
153    if (rsa->engine)
154	ENGINE_finish(rsa->engine);
155
156#define free_if(f) if (f) { BN_free(f); }
157    free_if(rsa->n);
158    free_if(rsa->e);
159    free_if(rsa->d);
160    free_if(rsa->p);
161    free_if(rsa->q);
162    free_if(rsa->dmp1);
163    free_if(rsa->dmq1);
164    free_if(rsa->iqmp);
165#undef free_if
166
167    memset(rsa, 0, sizeof(*rsa));
168    free(rsa);
169}
170
171/**
172 * Add an extra reference to the RSA object. The object should be free
173 * with RSA_free() to drop the reference.
174 *
175 * @param rsa the object to add reference counting too.
176 *
177 * @return the current reference count, can't safely be used except
178 * for debug printing.
179 *
180 * @ingroup hcrypto_rsa
181 */
182
183int
184RSA_up_ref(RSA *rsa)
185{
186    return ++rsa->references;
187}
188
189/**
190 * Return the RSA_METHOD used for this RSA object.
191 *
192 * @param rsa the object to get the method from.
193 *
194 * @return the method used for this RSA object.
195 *
196 * @ingroup hcrypto_rsa
197 */
198
199const RSA_METHOD *
200RSA_get_method(const RSA *rsa)
201{
202    return rsa->meth;
203}
204
205/**
206 * Set a new method for the RSA keypair.
207 *
208 * @param rsa rsa parameter.
209 * @param method the new method for the RSA parameter.
210 *
211 * @return 1 on success.
212 *
213 * @ingroup hcrypto_rsa
214 */
215
216int
217RSA_set_method(RSA *rsa, const RSA_METHOD *method)
218{
219    (*rsa->meth->finish)(rsa);
220
221    if (rsa->engine) {
222	ENGINE_finish(rsa->engine);
223	rsa->engine = NULL;
224    }
225
226    rsa->meth = method;
227    (*rsa->meth->init)(rsa);
228    return 1;
229}
230
231/**
232 * Set the application data for the RSA object.
233 *
234 * @param rsa the rsa object to set the parameter for
235 * @param arg the data object to store
236 *
237 * @return 1 on success.
238 *
239 * @ingroup hcrypto_rsa
240 */
241
242int
243RSA_set_app_data(RSA *rsa, void *arg)
244{
245    rsa->ex_data.sk = arg;
246    return 1;
247}
248
249/**
250 * Get the application data for the RSA object.
251 *
252 * @param rsa the rsa object to get the parameter for
253 *
254 * @return the data object
255 *
256 * @ingroup hcrypto_rsa
257 */
258
259void *
260RSA_get_app_data(const RSA *rsa)
261{
262    return rsa->ex_data.sk;
263}
264
265int
266RSA_check_key(const RSA *key)
267{
268    static const unsigned char inbuf[] = "hello, world!";
269    RSA *rsa = rk_UNCONST(key);
270    void *buffer;
271    int ret;
272
273    /*
274     * XXX I have no clue how to implement this w/o a bignum library.
275     * Well, when we have a RSA key pair, we can try to encrypt/sign
276     * and then decrypt/verify.
277     */
278
279    if ((rsa->d == NULL || rsa->n == NULL) &&
280	(rsa->p == NULL || rsa->q || rsa->dmp1 == NULL || rsa->dmq1 == NULL || rsa->iqmp == NULL))
281	return 0;
282
283    buffer = malloc(RSA_size(rsa));
284    if (buffer == NULL)
285	return 0;
286
287    ret = RSA_private_encrypt(sizeof(inbuf), inbuf, buffer,
288			     rsa, RSA_PKCS1_PADDING);
289    if (ret == -1) {
290	free(buffer);
291	return 0;
292    }
293
294    ret = RSA_public_decrypt(ret, buffer, buffer,
295			      rsa, RSA_PKCS1_PADDING);
296    if (ret == -1) {
297	free(buffer);
298	return 0;
299    }
300
301    if (ret == sizeof(inbuf) && ct_memcmp(buffer, inbuf, sizeof(inbuf)) == 0) {
302	free(buffer);
303	return 1;
304    }
305    free(buffer);
306    return 0;
307}
308
309int
310RSA_size(const RSA *rsa)
311{
312    return BN_num_bytes(rsa->n);
313}
314
315#define RSAFUNC(name, body) \
316int \
317name(int flen,const unsigned char* f, unsigned char* t, RSA* r, int p){\
318    return body; \
319}
320
321RSAFUNC(RSA_public_encrypt, (r)->meth->rsa_pub_enc(flen, f, t, r, p))
322RSAFUNC(RSA_public_decrypt, (r)->meth->rsa_pub_dec(flen, f, t, r, p))
323RSAFUNC(RSA_private_encrypt, (r)->meth->rsa_priv_enc(flen, f, t, r, p))
324RSAFUNC(RSA_private_decrypt, (r)->meth->rsa_priv_dec(flen, f, t, r, p))
325
326static const heim_octet_string null_entry_oid = { 2, rk_UNCONST("\x05\x00") };
327
328static const unsigned sha1_oid_tree[] = { 1, 3, 14, 3, 2, 26 };
329static const AlgorithmIdentifier _signature_sha1_data = {
330    { 6, rk_UNCONST(sha1_oid_tree) }, rk_UNCONST(&null_entry_oid)
331};
332static const unsigned sha256_oid_tree[] = { 2, 16, 840, 1, 101, 3, 4, 2, 1 };
333static const AlgorithmIdentifier _signature_sha256_data = {
334    { 9, rk_UNCONST(sha256_oid_tree) }, rk_UNCONST(&null_entry_oid)
335};
336static const unsigned sha384_oid_tree[] = { 2, 16, 840, 1, 101, 3, 4, 2, 2 };
337const AlgorithmIdentifier _signature_sha384_data = {
338    { 9, rk_UNCONST(sha384_oid_tree) }, rk_UNCONST(&null_entry_oid)
339};
340static const unsigned sha512_oid_tree[] = { 2, 16, 840, 1, 101, 3, 4, 2, 3 };
341const AlgorithmIdentifier _signature_sha512_data = {
342    { 9, rk_UNCONST(sha512_oid_tree) }, rk_UNCONST(&null_entry_oid)
343};
344static const unsigned md5_oid_tree[] = { 1, 2, 840, 113549, 2, 5 };
345static const AlgorithmIdentifier _signature_md5_data = {
346    { 6, rk_UNCONST(md5_oid_tree) }, rk_UNCONST(&null_entry_oid)
347};
348
349
350int
351RSA_sign(int type, const unsigned char *from, unsigned int flen,
352	 unsigned char *to, unsigned int *tlen, RSA *rsa)
353{
354    if (rsa->meth->rsa_sign)
355	return rsa->meth->rsa_sign(type, from, flen, to, tlen, rsa);
356
357    if (rsa->meth->rsa_priv_enc) {
358	heim_octet_string indata;
359	DigestInfo di;
360	size_t size;
361	int ret;
362
363	memset(&di, 0, sizeof(di));
364
365	if (type == NID_sha1) {
366	    di.digestAlgorithm = _signature_sha1_data;
367	} else if (type == NID_md5) {
368	    di.digestAlgorithm = _signature_md5_data;
369	} else if (type == NID_sha256) {
370	    di.digestAlgorithm = _signature_sha256_data;
371	} else if (type == NID_sha384) {
372	    di.digestAlgorithm = _signature_sha384_data;
373	} else if (type == NID_sha512) {
374	    di.digestAlgorithm = _signature_sha512_data;
375	} else
376	    return -1;
377
378	di.digest.data = rk_UNCONST(from);
379	di.digest.length = flen;
380
381	ASN1_MALLOC_ENCODE(DigestInfo,
382			   indata.data,
383			   indata.length,
384			   &di,
385			   &size,
386			   ret);
387	if (ret)
388	    return ret;
389	if (indata.length != size)
390	    abort();
391
392	ret = rsa->meth->rsa_priv_enc(indata.length, indata.data, to,
393				      rsa, RSA_PKCS1_PADDING);
394	free(indata.data);
395	if (ret > 0) {
396	    *tlen = ret;
397	    ret = 1;
398	} else
399	    ret = 0;
400
401	return ret;
402    }
403
404    return 0;
405}
406
407int
408RSA_verify(int type, const unsigned char *from, unsigned int flen,
409	   unsigned char *sigbuf, unsigned int siglen, RSA *rsa)
410{
411    if (rsa->meth->rsa_verify)
412	return rsa->meth->rsa_verify(type, from, flen, sigbuf, siglen, rsa);
413
414    if (rsa->meth->rsa_pub_dec) {
415	const AlgorithmIdentifier *digest_alg;
416	void *data;
417	DigestInfo di;
418	size_t size;
419	int ret, ret2;
420
421	data = malloc(RSA_size(rsa));
422	if (data == NULL)
423	    return -1;
424
425	memset(&di, 0, sizeof(di));
426
427	ret = rsa->meth->rsa_pub_dec(siglen, sigbuf, data, rsa, RSA_PKCS1_PADDING);
428	if (ret <= 0) {
429	    free(data);
430	    return -2;
431	}
432
433	ret2 = decode_DigestInfo(data, ret, &di, &size);
434	free(data);
435	if (ret2 != 0)
436	    return -3;
437	if (ret != size) {
438	    free_DigestInfo(&di);
439	    return -4;
440	}
441
442	if (flen != di.digest.length || memcmp(di.digest.data, from, flen) != 0) {
443	    free_DigestInfo(&di);
444	    return -5;
445	}
446
447	if (type == NID_sha1) {
448	    digest_alg = &_signature_sha1_data;
449	} else if (type == NID_md5) {
450	    digest_alg = &_signature_md5_data;
451	} else if (type == NID_sha256) {
452	    digest_alg = &_signature_sha256_data;
453	} else {
454	    free_DigestInfo(&di);
455	    return -1;
456	}
457
458	ret = der_heim_oid_cmp(&digest_alg->algorithm,
459			       &di.digestAlgorithm.algorithm);
460	free_DigestInfo(&di);
461
462	if (ret != 0)
463	    return 0;
464	return 1;
465    }
466
467    return 0;
468}
469
470/*
471 * A NULL RSA_METHOD that returns failure for all operations. This is
472 * used as the default RSA method if we don't have any native
473 * support.
474 */
475
476static RSAFUNC(null_rsa_public_encrypt, -1)
477static RSAFUNC(null_rsa_public_decrypt, -1)
478static RSAFUNC(null_rsa_private_encrypt, -1)
479static RSAFUNC(null_rsa_private_decrypt, -1)
480
481/*
482 *
483 */
484
485int
486RSA_generate_key_ex(RSA *r, int bits, BIGNUM *e, BN_GENCB *cb)
487{
488    if (r->meth->rsa_keygen)
489	return (*r->meth->rsa_keygen)(r, bits, e, cb);
490    return 0;
491}
492
493
494/*
495 *
496 */
497
498static int
499null_rsa_init(RSA *rsa)
500{
501    return 1;
502}
503
504static int
505null_rsa_finish(RSA *rsa)
506{
507    return 1;
508}
509
510static const RSA_METHOD rsa_null_method = {
511    "hcrypto null RSA",
512    null_rsa_public_encrypt,
513    null_rsa_public_decrypt,
514    null_rsa_private_encrypt,
515    null_rsa_private_decrypt,
516    NULL,
517    NULL,
518    null_rsa_init,
519    null_rsa_finish,
520    0,
521    NULL,
522    NULL,
523    NULL
524};
525
526const RSA_METHOD *
527RSA_null_method(void)
528{
529    return &rsa_null_method;
530}
531
532#ifdef HAVE_CDSA
533extern const RSA_METHOD _hc_rsa_cdsa_method;
534static const RSA_METHOD *default_rsa_method = &_hc_rsa_cdsa_method;
535#elif defined(HEIM_HC_SF)
536extern const RSA_METHOD _hc_rsa_sf_method;
537static const RSA_METHOD *default_rsa_method = &_hc_rsa_sf_method;
538#elif defined(HAVE_GMP)
539extern const RSA_METHOD _hc_rsa_gmp_method;
540static const RSA_METHOD *default_rsa_method = &_hc_rsa_gmp_method;
541#elif defined(HEIM_HC_LTM)
542extern const RSA_METHOD _hc_rsa_ltm_method;
543static const RSA_METHOD *default_rsa_method = &_hc_rsa_ltm_method;
544#else
545static const RSA_METHOD *default_rsa_method = &rsa_null_method;
546#endif
547
548const RSA_METHOD *
549RSA_get_default_method(void)
550{
551    return default_rsa_method;
552}
553
554void
555RSA_set_default_method(const RSA_METHOD *meth)
556{
557    default_rsa_method = meth;
558}
559
560/*
561 *
562 */
563
564RSA *
565d2i_RSAPrivateKey(RSA *rsa, const unsigned char **pp, size_t len)
566{
567    RSAPrivateKey data;
568    RSA *k = rsa;
569    size_t size;
570    int ret;
571
572    ret = decode_RSAPrivateKey(*pp, len, &data, &size);
573    if (ret)
574	return NULL;
575
576    *pp += size;
577
578    if (k == NULL) {
579	k = RSA_new();
580	if (k == NULL) {
581	    free_RSAPrivateKey(&data);
582	    return NULL;
583	}
584    }
585
586    k->n = _hc_integer_to_BN(&data.modulus, NULL);
587    k->e = _hc_integer_to_BN(&data.publicExponent, NULL);
588    k->d = _hc_integer_to_BN(&data.privateExponent, NULL);
589    k->p = _hc_integer_to_BN(&data.prime1, NULL);
590    k->q = _hc_integer_to_BN(&data.prime2, NULL);
591    k->dmp1 = _hc_integer_to_BN(&data.exponent1, NULL);
592    k->dmq1 = _hc_integer_to_BN(&data.exponent2, NULL);
593    k->iqmp = _hc_integer_to_BN(&data.coefficient, NULL);
594    free_RSAPrivateKey(&data);
595
596    if (k->n == NULL || k->e == NULL || k->d == NULL || k->p == NULL ||
597	k->q == NULL || k->dmp1 == NULL || k->dmq1 == NULL || k->iqmp == NULL)
598    {
599	RSA_free(k);
600	return NULL;
601    }
602
603    return k;
604}
605
606int
607i2d_RSAPrivateKey(RSA *rsa, unsigned char **pp)
608{
609    RSAPrivateKey data;
610    size_t size;
611    int ret;
612
613    if (rsa->n == NULL || rsa->e == NULL || rsa->d == NULL || rsa->p == NULL ||
614	rsa->q == NULL || rsa->dmp1 == NULL || rsa->dmq1 == NULL ||
615	rsa->iqmp == NULL)
616	return -1;
617
618    memset(&data, 0, sizeof(data));
619
620    ret  = _hc_BN_to_integer(rsa->n, &data.modulus);
621    ret |= _hc_BN_to_integer(rsa->e, &data.publicExponent);
622    ret |= _hc_BN_to_integer(rsa->d, &data.privateExponent);
623    ret |= _hc_BN_to_integer(rsa->p, &data.prime1);
624    ret |= _hc_BN_to_integer(rsa->q, &data.prime2);
625    ret |= _hc_BN_to_integer(rsa->dmp1, &data.exponent1);
626    ret |= _hc_BN_to_integer(rsa->dmq1, &data.exponent2);
627    ret |= _hc_BN_to_integer(rsa->iqmp, &data.coefficient);
628    if (ret) {
629	free_RSAPrivateKey(&data);
630	return -1;
631    }
632
633    if (pp == NULL) {
634	size = length_RSAPrivateKey(&data);
635	free_RSAPrivateKey(&data);
636    } else {
637	void *p;
638	size_t len;
639
640	ASN1_MALLOC_ENCODE(RSAPrivateKey, p, len, &data, &size, ret);
641	free_RSAPrivateKey(&data);
642	if (ret)
643	    return -1;
644	if (len != size)
645	    abort();
646
647	memcpy(*pp, p, size);
648	free(p);
649
650	*pp += size;
651
652    }
653    return size;
654}
655
656int
657i2d_RSAPublicKey(RSA *rsa, unsigned char **pp)
658{
659    RSAPublicKey data;
660    size_t size;
661    int ret;
662
663    memset(&data, 0, sizeof(data));
664
665    if (_hc_BN_to_integer(rsa->n, &data.modulus) ||
666	_hc_BN_to_integer(rsa->e, &data.publicExponent))
667    {
668	free_RSAPublicKey(&data);
669	return -1;
670    }
671
672    if (pp == NULL) {
673	size = length_RSAPublicKey(&data);
674	free_RSAPublicKey(&data);
675    } else {
676	void *p;
677	size_t len;
678
679	ASN1_MALLOC_ENCODE(RSAPublicKey, p, len, &data, &size, ret);
680	free_RSAPublicKey(&data);
681	if (ret)
682	    return -1;
683	if (len != size)
684	    abort();
685
686	memcpy(*pp, p, size);
687	free(p);
688
689	*pp += size;
690    }
691
692    return size;
693}
694
695RSA *
696d2i_RSAPublicKey(RSA *rsa, const unsigned char **pp, size_t len)
697{
698    RSAPublicKey data;
699    RSA *k = rsa;
700    size_t size;
701    int ret;
702
703    ret = decode_RSAPublicKey(*pp, len, &data, &size);
704    if (ret)
705	return NULL;
706
707    *pp += size;
708
709    if (k == NULL) {
710	k = RSA_new();
711	if (k == NULL) {
712	    free_RSAPublicKey(&data);
713	    return NULL;
714	}
715    }
716
717    k->n = _hc_integer_to_BN(&data.modulus, NULL);
718    k->e = _hc_integer_to_BN(&data.publicExponent, NULL);
719
720    free_RSAPublicKey(&data);
721
722    if (k->n == NULL || k->e == NULL) {
723	RSA_free(k);
724	return NULL;
725    }
726
727    return k;
728}
729