Continue standardising malloc style for libcrypto
[openssl.git] / crypto / rsa / rsa_ameth.c
1 /* crypto/rsa/rsa_ameth.c */
2 /*
3  * Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL project
4  * 2006.
5  */
6 /* ====================================================================
7  * Copyright (c) 2006 The OpenSSL Project.  All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in
18  *    the documentation and/or other materials provided with the
19  *    distribution.
20  *
21  * 3. All advertising materials mentioning features or use of this
22  *    software must display the following acknowledgment:
23  *    "This product includes software developed by the OpenSSL Project
24  *    for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
25  *
26  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
27  *    endorse or promote products derived from this software without
28  *    prior written permission. For written permission, please contact
29  *    licensing@OpenSSL.org.
30  *
31  * 5. Products derived from this software may not be called "OpenSSL"
32  *    nor may "OpenSSL" appear in their names without prior written
33  *    permission of the OpenSSL Project.
34  *
35  * 6. Redistributions of any form whatsoever must retain the following
36  *    acknowledgment:
37  *    "This product includes software developed by the OpenSSL Project
38  *    for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
41  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
43  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
44  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
45  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
46  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
47  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
49  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
50  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
51  * OF THE POSSIBILITY OF SUCH DAMAGE.
52  * ====================================================================
53  *
54  * This product includes cryptographic software written by Eric Young
55  * (eay@cryptsoft.com).  This product includes software written by Tim
56  * Hudson (tjh@cryptsoft.com).
57  *
58  */
59
60 #include <stdio.h>
61 #include "internal/cryptlib.h"
62 #include <openssl/asn1t.h>
63 #include <openssl/x509.h>
64 #include <openssl/rsa.h>
65 #include <openssl/bn.h>
66 #ifndef OPENSSL_NO_CMS
67 # include <openssl/cms.h>
68 #endif
69 #include "internal/asn1_int.h"
70
71 #ifndef OPENSSL_NO_CMS
72 static int rsa_cms_sign(CMS_SignerInfo *si);
73 static int rsa_cms_verify(CMS_SignerInfo *si);
74 static int rsa_cms_decrypt(CMS_RecipientInfo *ri);
75 static int rsa_cms_encrypt(CMS_RecipientInfo *ri);
76 #endif
77
78 static int rsa_pub_encode(X509_PUBKEY *pk, const EVP_PKEY *pkey)
79 {
80     unsigned char *penc = NULL;
81     int penclen;
82     penclen = i2d_RSAPublicKey(pkey->pkey.rsa, &penc);
83     if (penclen <= 0)
84         return 0;
85     if (X509_PUBKEY_set0_param(pk, OBJ_nid2obj(EVP_PKEY_RSA),
86                                V_ASN1_NULL, NULL, penc, penclen))
87         return 1;
88
89     OPENSSL_free(penc);
90     return 0;
91 }
92
93 static int rsa_pub_decode(EVP_PKEY *pkey, X509_PUBKEY *pubkey)
94 {
95     const unsigned char *p;
96     int pklen;
97     RSA *rsa = NULL;
98
99     if (!X509_PUBKEY_get0_param(NULL, &p, &pklen, NULL, pubkey))
100         return 0;
101     if ((rsa = d2i_RSAPublicKey(NULL, &p, pklen)) == NULL) {
102         RSAerr(RSA_F_RSA_PUB_DECODE, ERR_R_RSA_LIB);
103         return 0;
104     }
105     EVP_PKEY_assign_RSA(pkey, rsa);
106     return 1;
107 }
108
109 static int rsa_pub_cmp(const EVP_PKEY *a, const EVP_PKEY *b)
110 {
111     if (BN_cmp(b->pkey.rsa->n, a->pkey.rsa->n) != 0
112         || BN_cmp(b->pkey.rsa->e, a->pkey.rsa->e) != 0)
113         return 0;
114     return 1;
115 }
116
117 static int old_rsa_priv_decode(EVP_PKEY *pkey,
118                                const unsigned char **pder, int derlen)
119 {
120     RSA *rsa;
121
122     if ((rsa = d2i_RSAPrivateKey(NULL, pder, derlen)) == NULL) {
123         RSAerr(RSA_F_OLD_RSA_PRIV_DECODE, ERR_R_RSA_LIB);
124         return 0;
125     }
126     EVP_PKEY_assign_RSA(pkey, rsa);
127     return 1;
128 }
129
130 static int old_rsa_priv_encode(const EVP_PKEY *pkey, unsigned char **pder)
131 {
132     return i2d_RSAPrivateKey(pkey->pkey.rsa, pder);
133 }
134
135 static int rsa_priv_encode(PKCS8_PRIV_KEY_INFO *p8, const EVP_PKEY *pkey)
136 {
137     unsigned char *rk = NULL;
138     int rklen;
139     rklen = i2d_RSAPrivateKey(pkey->pkey.rsa, &rk);
140
141     if (rklen <= 0) {
142         RSAerr(RSA_F_RSA_PRIV_ENCODE, ERR_R_MALLOC_FAILURE);
143         return 0;
144     }
145
146     if (!PKCS8_pkey_set0(p8, OBJ_nid2obj(NID_rsaEncryption), 0,
147                          V_ASN1_NULL, NULL, rk, rklen)) {
148         RSAerr(RSA_F_RSA_PRIV_ENCODE, ERR_R_MALLOC_FAILURE);
149         return 0;
150     }
151
152     return 1;
153 }
154
155 static int rsa_priv_decode(EVP_PKEY *pkey, PKCS8_PRIV_KEY_INFO *p8)
156 {
157     const unsigned char *p;
158     int pklen;
159     if (!PKCS8_pkey_get0(NULL, &p, &pklen, NULL, p8))
160         return 0;
161     return old_rsa_priv_decode(pkey, &p, pklen);
162 }
163
164 static int int_rsa_size(const EVP_PKEY *pkey)
165 {
166     return RSA_size(pkey->pkey.rsa);
167 }
168
169 static int rsa_bits(const EVP_PKEY *pkey)
170 {
171     return BN_num_bits(pkey->pkey.rsa->n);
172 }
173
174 static int rsa_security_bits(const EVP_PKEY *pkey)
175 {
176     return RSA_security_bits(pkey->pkey.rsa);
177 }
178
179 static void int_rsa_free(EVP_PKEY *pkey)
180 {
181     RSA_free(pkey->pkey.rsa);
182 }
183
184 static void update_buflen(const BIGNUM *b, size_t *pbuflen)
185 {
186     size_t i;
187     if (!b)
188         return;
189     if (*pbuflen < (i = (size_t)BN_num_bytes(b)))
190         *pbuflen = i;
191 }
192
193 static int do_rsa_print(BIO *bp, const RSA *x, int off, int priv)
194 {
195     char *str;
196     const char *s;
197     unsigned char *m = NULL;
198     int ret = 0, mod_len = 0;
199     size_t buf_len = 0;
200
201     update_buflen(x->n, &buf_len);
202     update_buflen(x->e, &buf_len);
203
204     if (priv) {
205         update_buflen(x->d, &buf_len);
206         update_buflen(x->p, &buf_len);
207         update_buflen(x->q, &buf_len);
208         update_buflen(x->dmp1, &buf_len);
209         update_buflen(x->dmq1, &buf_len);
210         update_buflen(x->iqmp, &buf_len);
211     }
212
213     m = OPENSSL_malloc(buf_len + 10);
214     if (m == NULL) {
215         RSAerr(RSA_F_DO_RSA_PRINT, ERR_R_MALLOC_FAILURE);
216         goto err;
217     }
218
219     if (x->n != NULL)
220         mod_len = BN_num_bits(x->n);
221
222     if (!BIO_indent(bp, off, 128))
223         goto err;
224
225     if (priv && x->d) {
226         if (BIO_printf(bp, "Private-Key: (%d bit)\n", mod_len)
227             <= 0)
228             goto err;
229         str = "modulus:";
230         s = "publicExponent:";
231     } else {
232         if (BIO_printf(bp, "Public-Key: (%d bit)\n", mod_len)
233             <= 0)
234             goto err;
235         str = "Modulus:";
236         s = "Exponent:";
237     }
238     if (!ASN1_bn_print(bp, str, x->n, m, off))
239         goto err;
240     if (!ASN1_bn_print(bp, s, x->e, m, off))
241         goto err;
242     if (priv) {
243         if (!ASN1_bn_print(bp, "privateExponent:", x->d, m, off))
244             goto err;
245         if (!ASN1_bn_print(bp, "prime1:", x->p, m, off))
246             goto err;
247         if (!ASN1_bn_print(bp, "prime2:", x->q, m, off))
248             goto err;
249         if (!ASN1_bn_print(bp, "exponent1:", x->dmp1, m, off))
250             goto err;
251         if (!ASN1_bn_print(bp, "exponent2:", x->dmq1, m, off))
252             goto err;
253         if (!ASN1_bn_print(bp, "coefficient:", x->iqmp, m, off))
254             goto err;
255     }
256     ret = 1;
257  err:
258     OPENSSL_free(m);
259     return (ret);
260 }
261
262 static int rsa_pub_print(BIO *bp, const EVP_PKEY *pkey, int indent,
263                          ASN1_PCTX *ctx)
264 {
265     return do_rsa_print(bp, pkey->pkey.rsa, indent, 0);
266 }
267
268 static int rsa_priv_print(BIO *bp, const EVP_PKEY *pkey, int indent,
269                           ASN1_PCTX *ctx)
270 {
271     return do_rsa_print(bp, pkey->pkey.rsa, indent, 1);
272 }
273
274 /* Given an MGF1 Algorithm ID decode to an Algorithm Identifier */
275 static X509_ALGOR *rsa_mgf1_decode(X509_ALGOR *alg)
276 {
277     if (alg == NULL)
278         return NULL;
279     if (OBJ_obj2nid(alg->algorithm) != NID_mgf1)
280         return NULL;
281     return ASN1_TYPE_unpack_sequence(ASN1_ITEM_rptr(X509_ALGOR),
282                                      alg->parameter);
283 }
284
285 static RSA_PSS_PARAMS *rsa_pss_decode(const X509_ALGOR *alg,
286                                       X509_ALGOR **pmaskHash)
287 {
288     RSA_PSS_PARAMS *pss;
289
290     *pmaskHash = NULL;
291
292     pss = ASN1_TYPE_unpack_sequence(ASN1_ITEM_rptr(RSA_PSS_PARAMS),
293                                     alg->parameter);
294
295     if (!pss)
296         return NULL;
297
298     *pmaskHash = rsa_mgf1_decode(pss->maskGenAlgorithm);
299
300     return pss;
301 }
302
303 static int rsa_pss_param_print(BIO *bp, RSA_PSS_PARAMS *pss,
304                                X509_ALGOR *maskHash, int indent)
305 {
306     int rv = 0;
307     if (!pss) {
308         if (BIO_puts(bp, " (INVALID PSS PARAMETERS)\n") <= 0)
309             return 0;
310         return 1;
311     }
312     if (BIO_puts(bp, "\n") <= 0)
313         goto err;
314     if (!BIO_indent(bp, indent, 128))
315         goto err;
316     if (BIO_puts(bp, "Hash Algorithm: ") <= 0)
317         goto err;
318
319     if (pss->hashAlgorithm) {
320         if (i2a_ASN1_OBJECT(bp, pss->hashAlgorithm->algorithm) <= 0)
321             goto err;
322     } else if (BIO_puts(bp, "sha1 (default)") <= 0)
323         goto err;
324
325     if (BIO_puts(bp, "\n") <= 0)
326         goto err;
327
328     if (!BIO_indent(bp, indent, 128))
329         goto err;
330
331     if (BIO_puts(bp, "Mask Algorithm: ") <= 0)
332         goto err;
333     if (pss->maskGenAlgorithm) {
334         if (i2a_ASN1_OBJECT(bp, pss->maskGenAlgorithm->algorithm) <= 0)
335             goto err;
336         if (BIO_puts(bp, " with ") <= 0)
337             goto err;
338         if (maskHash) {
339             if (i2a_ASN1_OBJECT(bp, maskHash->algorithm) <= 0)
340                 goto err;
341         } else if (BIO_puts(bp, "INVALID") <= 0)
342             goto err;
343     } else if (BIO_puts(bp, "mgf1 with sha1 (default)") <= 0)
344         goto err;
345     BIO_puts(bp, "\n");
346
347     if (!BIO_indent(bp, indent, 128))
348         goto err;
349     if (BIO_puts(bp, "Salt Length: 0x") <= 0)
350         goto err;
351     if (pss->saltLength) {
352         if (i2a_ASN1_INTEGER(bp, pss->saltLength) <= 0)
353             goto err;
354     } else if (BIO_puts(bp, "14 (default)") <= 0)
355         goto err;
356     BIO_puts(bp, "\n");
357
358     if (!BIO_indent(bp, indent, 128))
359         goto err;
360     if (BIO_puts(bp, "Trailer Field: 0x") <= 0)
361         goto err;
362     if (pss->trailerField) {
363         if (i2a_ASN1_INTEGER(bp, pss->trailerField) <= 0)
364             goto err;
365     } else if (BIO_puts(bp, "BC (default)") <= 0)
366         goto err;
367     BIO_puts(bp, "\n");
368
369     rv = 1;
370
371  err:
372     return rv;
373
374 }
375
376 static int rsa_sig_print(BIO *bp, const X509_ALGOR *sigalg,
377                          const ASN1_STRING *sig, int indent, ASN1_PCTX *pctx)
378 {
379     if (OBJ_obj2nid(sigalg->algorithm) == NID_rsassaPss) {
380         int rv;
381         RSA_PSS_PARAMS *pss;
382         X509_ALGOR *maskHash;
383         pss = rsa_pss_decode(sigalg, &maskHash);
384         rv = rsa_pss_param_print(bp, pss, maskHash, indent);
385         RSA_PSS_PARAMS_free(pss);
386         X509_ALGOR_free(maskHash);
387         if (!rv)
388             return 0;
389     } else if (!sig && BIO_puts(bp, "\n") <= 0)
390         return 0;
391     if (sig)
392         return X509_signature_dump(bp, sig, indent);
393     return 1;
394 }
395
396 static int rsa_pkey_ctrl(EVP_PKEY *pkey, int op, long arg1, void *arg2)
397 {
398     X509_ALGOR *alg = NULL;
399     switch (op) {
400
401     case ASN1_PKEY_CTRL_PKCS7_SIGN:
402         if (arg1 == 0)
403             PKCS7_SIGNER_INFO_get0_algs(arg2, NULL, NULL, &alg);
404         break;
405
406     case ASN1_PKEY_CTRL_PKCS7_ENCRYPT:
407         if (arg1 == 0)
408             PKCS7_RECIP_INFO_get0_alg(arg2, &alg);
409         break;
410 #ifndef OPENSSL_NO_CMS
411     case ASN1_PKEY_CTRL_CMS_SIGN:
412         if (arg1 == 0)
413             return rsa_cms_sign(arg2);
414         else if (arg1 == 1)
415             return rsa_cms_verify(arg2);
416         break;
417
418     case ASN1_PKEY_CTRL_CMS_ENVELOPE:
419         if (arg1 == 0)
420             return rsa_cms_encrypt(arg2);
421         else if (arg1 == 1)
422             return rsa_cms_decrypt(arg2);
423         break;
424
425     case ASN1_PKEY_CTRL_CMS_RI_TYPE:
426         *(int *)arg2 = CMS_RECIPINFO_TRANS;
427         return 1;
428 #endif
429
430     case ASN1_PKEY_CTRL_DEFAULT_MD_NID:
431         *(int *)arg2 = NID_sha256;
432         return 1;
433
434     default:
435         return -2;
436
437     }
438
439     if (alg)
440         X509_ALGOR_set0(alg, OBJ_nid2obj(NID_rsaEncryption), V_ASN1_NULL, 0);
441
442     return 1;
443
444 }
445
446 /* allocate and set algorithm ID from EVP_MD, default SHA1 */
447 static int rsa_md_to_algor(X509_ALGOR **palg, const EVP_MD *md)
448 {
449     if (EVP_MD_type(md) == NID_sha1)
450         return 1;
451     *palg = X509_ALGOR_new();
452     if (*palg == NULL)
453         return 0;
454     X509_ALGOR_set_md(*palg, md);
455     return 1;
456 }
457
458 /* Allocate and set MGF1 algorithm ID from EVP_MD */
459 static int rsa_md_to_mgf1(X509_ALGOR **palg, const EVP_MD *mgf1md)
460 {
461     X509_ALGOR *algtmp = NULL;
462     ASN1_STRING *stmp = NULL;
463     *palg = NULL;
464     if (EVP_MD_type(mgf1md) == NID_sha1)
465         return 1;
466     /* need to embed algorithm ID inside another */
467     if (!rsa_md_to_algor(&algtmp, mgf1md))
468         goto err;
469     if (!ASN1_item_pack(algtmp, ASN1_ITEM_rptr(X509_ALGOR), &stmp))
470          goto err;
471     *palg = X509_ALGOR_new();
472     if (*palg == NULL)
473         goto err;
474     X509_ALGOR_set0(*palg, OBJ_nid2obj(NID_mgf1), V_ASN1_SEQUENCE, stmp);
475     stmp = NULL;
476  err:
477     ASN1_STRING_free(stmp);
478     X509_ALGOR_free(algtmp);
479     if (*palg)
480         return 1;
481     return 0;
482 }
483
484 /* convert algorithm ID to EVP_MD, default SHA1 */
485 static const EVP_MD *rsa_algor_to_md(X509_ALGOR *alg)
486 {
487     const EVP_MD *md;
488     if (!alg)
489         return EVP_sha1();
490     md = EVP_get_digestbyobj(alg->algorithm);
491     if (md == NULL)
492         RSAerr(RSA_F_RSA_ALGOR_TO_MD, RSA_R_UNKNOWN_DIGEST);
493     return md;
494 }
495
496 /* convert MGF1 algorithm ID to EVP_MD, default SHA1 */
497 static const EVP_MD *rsa_mgf1_to_md(X509_ALGOR *alg, X509_ALGOR *maskHash)
498 {
499     const EVP_MD *md;
500     if (!alg)
501         return EVP_sha1();
502     /* Check mask and lookup mask hash algorithm */
503     if (OBJ_obj2nid(alg->algorithm) != NID_mgf1) {
504         RSAerr(RSA_F_RSA_MGF1_TO_MD, RSA_R_UNSUPPORTED_MASK_ALGORITHM);
505         return NULL;
506     }
507     if (!maskHash) {
508         RSAerr(RSA_F_RSA_MGF1_TO_MD, RSA_R_UNSUPPORTED_MASK_PARAMETER);
509         return NULL;
510     }
511     md = EVP_get_digestbyobj(maskHash->algorithm);
512     if (md == NULL) {
513         RSAerr(RSA_F_RSA_MGF1_TO_MD, RSA_R_UNKNOWN_MASK_DIGEST);
514         return NULL;
515     }
516     return md;
517 }
518
519 /*
520  * Convert EVP_PKEY_CTX is PSS mode into corresponding algorithm parameter,
521  * suitable for setting an AlgorithmIdentifier.
522  */
523
524 static ASN1_STRING *rsa_ctx_to_pss(EVP_PKEY_CTX *pkctx)
525 {
526     const EVP_MD *sigmd, *mgf1md;
527     RSA_PSS_PARAMS *pss = NULL;
528     ASN1_STRING *os = NULL;
529     EVP_PKEY *pk = EVP_PKEY_CTX_get0_pkey(pkctx);
530     int saltlen, rv = 0;
531     if (EVP_PKEY_CTX_get_signature_md(pkctx, &sigmd) <= 0)
532         goto err;
533     if (EVP_PKEY_CTX_get_rsa_mgf1_md(pkctx, &mgf1md) <= 0)
534         goto err;
535     if (!EVP_PKEY_CTX_get_rsa_pss_saltlen(pkctx, &saltlen))
536         goto err;
537     if (saltlen == -1)
538         saltlen = EVP_MD_size(sigmd);
539     else if (saltlen == -2) {
540         saltlen = EVP_PKEY_size(pk) - EVP_MD_size(sigmd) - 2;
541         if (((EVP_PKEY_bits(pk) - 1) & 0x7) == 0)
542             saltlen--;
543     }
544     pss = RSA_PSS_PARAMS_new();
545     if (pss == NULL)
546         goto err;
547     if (saltlen != 20) {
548         pss->saltLength = ASN1_INTEGER_new();
549         if (pss->saltLength == NULL)
550             goto err;
551         if (!ASN1_INTEGER_set(pss->saltLength, saltlen))
552             goto err;
553     }
554     if (!rsa_md_to_algor(&pss->hashAlgorithm, sigmd))
555         goto err;
556     if (!rsa_md_to_mgf1(&pss->maskGenAlgorithm, mgf1md))
557         goto err;
558     /* Finally create string with pss parameter encoding. */
559     if (!ASN1_item_pack(pss, ASN1_ITEM_rptr(RSA_PSS_PARAMS), &os))
560          goto err;
561     rv = 1;
562  err:
563     RSA_PSS_PARAMS_free(pss);
564     if (rv)
565         return os;
566     ASN1_STRING_free(os);
567     return NULL;
568 }
569
570 /*
571  * From PSS AlgorithmIdentifier set public key parameters. If pkey isn't NULL
572  * then the EVP_MD_CTX is setup and initalised. If it is NULL parameters are
573  * passed to pkctx instead.
574  */
575
576 static int rsa_pss_to_ctx(EVP_MD_CTX *ctx, EVP_PKEY_CTX *pkctx,
577                           X509_ALGOR *sigalg, EVP_PKEY *pkey)
578 {
579     int rv = -1;
580     int saltlen;
581     const EVP_MD *mgf1md = NULL, *md = NULL;
582     RSA_PSS_PARAMS *pss;
583     X509_ALGOR *maskHash;
584     /* Sanity check: make sure it is PSS */
585     if (OBJ_obj2nid(sigalg->algorithm) != NID_rsassaPss) {
586         RSAerr(RSA_F_RSA_PSS_TO_CTX, RSA_R_UNSUPPORTED_SIGNATURE_TYPE);
587         return -1;
588     }
589     /* Decode PSS parameters */
590     pss = rsa_pss_decode(sigalg, &maskHash);
591
592     if (pss == NULL) {
593         RSAerr(RSA_F_RSA_PSS_TO_CTX, RSA_R_INVALID_PSS_PARAMETERS);
594         goto err;
595     }
596     mgf1md = rsa_mgf1_to_md(pss->maskGenAlgorithm, maskHash);
597     if (!mgf1md)
598         goto err;
599     md = rsa_algor_to_md(pss->hashAlgorithm);
600     if (!md)
601         goto err;
602
603     if (pss->saltLength) {
604         saltlen = ASN1_INTEGER_get(pss->saltLength);
605
606         /*
607          * Could perform more salt length sanity checks but the main RSA
608          * routines will trap other invalid values anyway.
609          */
610         if (saltlen < 0) {
611             RSAerr(RSA_F_RSA_PSS_TO_CTX, RSA_R_INVALID_SALT_LENGTH);
612             goto err;
613         }
614     } else
615         saltlen = 20;
616
617     /*
618      * low-level routines support only trailer field 0xbc (value 1) and
619      * PKCS#1 says we should reject any other value anyway.
620      */
621     if (pss->trailerField && ASN1_INTEGER_get(pss->trailerField) != 1) {
622         RSAerr(RSA_F_RSA_PSS_TO_CTX, RSA_R_INVALID_TRAILER);
623         goto err;
624     }
625
626     /* We have all parameters now set up context */
627
628     if (pkey) {
629         if (!EVP_DigestVerifyInit(ctx, &pkctx, md, NULL, pkey))
630             goto err;
631     } else {
632         const EVP_MD *checkmd;
633         if (EVP_PKEY_CTX_get_signature_md(pkctx, &checkmd) <= 0)
634             goto err;
635         if (EVP_MD_type(md) != EVP_MD_type(checkmd)) {
636             RSAerr(RSA_F_RSA_PSS_TO_CTX, RSA_R_DIGEST_DOES_NOT_MATCH);
637             goto err;
638         }
639     }
640
641     if (EVP_PKEY_CTX_set_rsa_padding(pkctx, RSA_PKCS1_PSS_PADDING) <= 0)
642         goto err;
643
644     if (EVP_PKEY_CTX_set_rsa_pss_saltlen(pkctx, saltlen) <= 0)
645         goto err;
646
647     if (EVP_PKEY_CTX_set_rsa_mgf1_md(pkctx, mgf1md) <= 0)
648         goto err;
649     /* Carry on */
650     rv = 1;
651
652  err:
653     RSA_PSS_PARAMS_free(pss);
654     X509_ALGOR_free(maskHash);
655     return rv;
656 }
657
658 #ifndef OPENSSL_NO_CMS
659 static int rsa_cms_verify(CMS_SignerInfo *si)
660 {
661     int nid, nid2;
662     X509_ALGOR *alg;
663     EVP_PKEY_CTX *pkctx = CMS_SignerInfo_get0_pkey_ctx(si);
664     CMS_SignerInfo_get0_algs(si, NULL, NULL, NULL, &alg);
665     nid = OBJ_obj2nid(alg->algorithm);
666     if (nid == NID_rsaEncryption)
667         return 1;
668     if (nid == NID_rsassaPss)
669         return rsa_pss_to_ctx(NULL, pkctx, alg, NULL);
670     /* Workaround for some implementation that use a signature OID */
671     if (OBJ_find_sigid_algs(nid, NULL, &nid2)) {
672         if (nid2 == NID_rsaEncryption)
673             return 1;
674     }
675     return 0;
676 }
677 #endif
678
679 /*
680  * Customised RSA item verification routine. This is called when a signature
681  * is encountered requiring special handling. We currently only handle PSS.
682  */
683
684 static int rsa_item_verify(EVP_MD_CTX *ctx, const ASN1_ITEM *it, void *asn,
685                            X509_ALGOR *sigalg, ASN1_BIT_STRING *sig,
686                            EVP_PKEY *pkey)
687 {
688     /* Sanity check: make sure it is PSS */
689     if (OBJ_obj2nid(sigalg->algorithm) != NID_rsassaPss) {
690         RSAerr(RSA_F_RSA_ITEM_VERIFY, RSA_R_UNSUPPORTED_SIGNATURE_TYPE);
691         return -1;
692     }
693     if (rsa_pss_to_ctx(ctx, NULL, sigalg, pkey) > 0) {
694         /* Carry on */
695         return 2;
696     }
697     return -1;
698 }
699
700 #ifndef OPENSSL_NO_CMS
701 static int rsa_cms_sign(CMS_SignerInfo *si)
702 {
703     int pad_mode = RSA_PKCS1_PADDING;
704     X509_ALGOR *alg;
705     EVP_PKEY_CTX *pkctx = CMS_SignerInfo_get0_pkey_ctx(si);
706     ASN1_STRING *os = NULL;
707     CMS_SignerInfo_get0_algs(si, NULL, NULL, NULL, &alg);
708     if (pkctx) {
709         if (EVP_PKEY_CTX_get_rsa_padding(pkctx, &pad_mode) <= 0)
710             return 0;
711     }
712     if (pad_mode == RSA_PKCS1_PADDING) {
713         X509_ALGOR_set0(alg, OBJ_nid2obj(NID_rsaEncryption), V_ASN1_NULL, 0);
714         return 1;
715     }
716     /* We don't support it */
717     if (pad_mode != RSA_PKCS1_PSS_PADDING)
718         return 0;
719     os = rsa_ctx_to_pss(pkctx);
720     if (!os)
721         return 0;
722     X509_ALGOR_set0(alg, OBJ_nid2obj(NID_rsassaPss), V_ASN1_SEQUENCE, os);
723     return 1;
724 }
725 #endif
726
727 static int rsa_item_sign(EVP_MD_CTX *ctx, const ASN1_ITEM *it, void *asn,
728                          X509_ALGOR *alg1, X509_ALGOR *alg2,
729                          ASN1_BIT_STRING *sig)
730 {
731     int pad_mode;
732     EVP_PKEY_CTX *pkctx = ctx->pctx;
733     if (EVP_PKEY_CTX_get_rsa_padding(pkctx, &pad_mode) <= 0)
734         return 0;
735     if (pad_mode == RSA_PKCS1_PADDING)
736         return 2;
737     if (pad_mode == RSA_PKCS1_PSS_PADDING) {
738         ASN1_STRING *os1 = NULL;
739         os1 = rsa_ctx_to_pss(pkctx);
740         if (!os1)
741             return 0;
742         /* Duplicate parameters if we have to */
743         if (alg2) {
744             ASN1_STRING *os2 = ASN1_STRING_dup(os1);
745             if (!os2) {
746                 ASN1_STRING_free(os1);
747                 return 0;
748             }
749             X509_ALGOR_set0(alg2, OBJ_nid2obj(NID_rsassaPss),
750                             V_ASN1_SEQUENCE, os2);
751         }
752         X509_ALGOR_set0(alg1, OBJ_nid2obj(NID_rsassaPss),
753                         V_ASN1_SEQUENCE, os1);
754         return 3;
755     }
756     return 2;
757 }
758
759 #ifndef OPENSSL_NO_CMS
760 static RSA_OAEP_PARAMS *rsa_oaep_decode(const X509_ALGOR *alg,
761                                         X509_ALGOR **pmaskHash)
762 {
763     RSA_OAEP_PARAMS *pss;
764
765     *pmaskHash = NULL;
766
767     pss = ASN1_TYPE_unpack_sequence(ASN1_ITEM_rptr(RSA_OAEP_PARAMS),
768                                     alg->parameter);
769
770     if (!pss)
771         return NULL;
772
773     *pmaskHash = rsa_mgf1_decode(pss->maskGenFunc);
774
775     return pss;
776 }
777
778 static int rsa_cms_decrypt(CMS_RecipientInfo *ri)
779 {
780     EVP_PKEY_CTX *pkctx;
781     X509_ALGOR *cmsalg;
782     int nid;
783     int rv = -1;
784     unsigned char *label = NULL;
785     int labellen = 0;
786     const EVP_MD *mgf1md = NULL, *md = NULL;
787     RSA_OAEP_PARAMS *oaep;
788     X509_ALGOR *maskHash;
789     pkctx = CMS_RecipientInfo_get0_pkey_ctx(ri);
790     if (!pkctx)
791         return 0;
792     if (!CMS_RecipientInfo_ktri_get0_algs(ri, NULL, NULL, &cmsalg))
793         return -1;
794     nid = OBJ_obj2nid(cmsalg->algorithm);
795     if (nid == NID_rsaEncryption)
796         return 1;
797     if (nid != NID_rsaesOaep) {
798         RSAerr(RSA_F_RSA_CMS_DECRYPT, RSA_R_UNSUPPORTED_ENCRYPTION_TYPE);
799         return -1;
800     }
801     /* Decode OAEP parameters */
802     oaep = rsa_oaep_decode(cmsalg, &maskHash);
803
804     if (oaep == NULL) {
805         RSAerr(RSA_F_RSA_CMS_DECRYPT, RSA_R_INVALID_OAEP_PARAMETERS);
806         goto err;
807     }
808
809     mgf1md = rsa_mgf1_to_md(oaep->maskGenFunc, maskHash);
810     if (!mgf1md)
811         goto err;
812     md = rsa_algor_to_md(oaep->hashFunc);
813     if (!md)
814         goto err;
815
816     if (oaep->pSourceFunc) {
817         X509_ALGOR *plab = oaep->pSourceFunc;
818         if (OBJ_obj2nid(plab->algorithm) != NID_pSpecified) {
819             RSAerr(RSA_F_RSA_CMS_DECRYPT, RSA_R_UNSUPPORTED_LABEL_SOURCE);
820             goto err;
821         }
822         if (plab->parameter->type != V_ASN1_OCTET_STRING) {
823             RSAerr(RSA_F_RSA_CMS_DECRYPT, RSA_R_INVALID_LABEL);
824             goto err;
825         }
826
827         label = plab->parameter->value.octet_string->data;
828         /* Stop label being freed when OAEP parameters are freed */
829         plab->parameter->value.octet_string->data = NULL;
830         labellen = plab->parameter->value.octet_string->length;
831     }
832
833     if (EVP_PKEY_CTX_set_rsa_padding(pkctx, RSA_PKCS1_OAEP_PADDING) <= 0)
834         goto err;
835     if (EVP_PKEY_CTX_set_rsa_oaep_md(pkctx, md) <= 0)
836         goto err;
837     if (EVP_PKEY_CTX_set_rsa_mgf1_md(pkctx, mgf1md) <= 0)
838         goto err;
839     if (EVP_PKEY_CTX_set0_rsa_oaep_label(pkctx, label, labellen) <= 0)
840         goto err;
841     /* Carry on */
842     rv = 1;
843
844  err:
845     RSA_OAEP_PARAMS_free(oaep);
846     X509_ALGOR_free(maskHash);
847     return rv;
848 }
849
850 static int rsa_cms_encrypt(CMS_RecipientInfo *ri)
851 {
852     const EVP_MD *md, *mgf1md;
853     RSA_OAEP_PARAMS *oaep = NULL;
854     ASN1_STRING *os = NULL;
855     X509_ALGOR *alg;
856     EVP_PKEY_CTX *pkctx = CMS_RecipientInfo_get0_pkey_ctx(ri);
857     int pad_mode = RSA_PKCS1_PADDING, rv = 0, labellen;
858     unsigned char *label;
859     CMS_RecipientInfo_ktri_get0_algs(ri, NULL, NULL, &alg);
860     if (pkctx) {
861         if (EVP_PKEY_CTX_get_rsa_padding(pkctx, &pad_mode) <= 0)
862             return 0;
863     }
864     if (pad_mode == RSA_PKCS1_PADDING) {
865         X509_ALGOR_set0(alg, OBJ_nid2obj(NID_rsaEncryption), V_ASN1_NULL, 0);
866         return 1;
867     }
868     /* Not supported */
869     if (pad_mode != RSA_PKCS1_OAEP_PADDING)
870         return 0;
871     if (EVP_PKEY_CTX_get_rsa_oaep_md(pkctx, &md) <= 0)
872         goto err;
873     if (EVP_PKEY_CTX_get_rsa_mgf1_md(pkctx, &mgf1md) <= 0)
874         goto err;
875     labellen = EVP_PKEY_CTX_get0_rsa_oaep_label(pkctx, &label);
876     if (labellen < 0)
877         goto err;
878     oaep = RSA_OAEP_PARAMS_new();
879     if (oaep == NULL)
880         goto err;
881     if (!rsa_md_to_algor(&oaep->hashFunc, md))
882         goto err;
883     if (!rsa_md_to_mgf1(&oaep->maskGenFunc, mgf1md))
884         goto err;
885     if (labellen > 0) {
886         ASN1_OCTET_STRING *los = ASN1_OCTET_STRING_new();
887         oaep->pSourceFunc = X509_ALGOR_new();
888         if (oaep->pSourceFunc == NULL)
889             goto err;
890         if (los == NULL)
891             goto err;
892         if (!ASN1_OCTET_STRING_set(los, label, labellen)) {
893             ASN1_OCTET_STRING_free(los);
894             goto err;
895         }
896         X509_ALGOR_set0(oaep->pSourceFunc, OBJ_nid2obj(NID_pSpecified),
897                         V_ASN1_OCTET_STRING, los);
898     }
899     /* create string with pss parameter encoding. */
900     if (!ASN1_item_pack(oaep, ASN1_ITEM_rptr(RSA_OAEP_PARAMS), &os))
901          goto err;
902     X509_ALGOR_set0(alg, OBJ_nid2obj(NID_rsaesOaep), V_ASN1_SEQUENCE, os);
903     os = NULL;
904     rv = 1;
905  err:
906     RSA_OAEP_PARAMS_free(oaep);
907     ASN1_STRING_free(os);
908     return rv;
909 }
910 #endif
911
912 const EVP_PKEY_ASN1_METHOD rsa_asn1_meths[] = {
913     {
914      EVP_PKEY_RSA,
915      EVP_PKEY_RSA,
916      ASN1_PKEY_SIGPARAM_NULL,
917
918      "RSA",
919      "OpenSSL RSA method",
920
921      rsa_pub_decode,
922      rsa_pub_encode,
923      rsa_pub_cmp,
924      rsa_pub_print,
925
926      rsa_priv_decode,
927      rsa_priv_encode,
928      rsa_priv_print,
929
930      int_rsa_size,
931      rsa_bits,
932      rsa_security_bits,
933
934      0, 0, 0, 0, 0, 0,
935
936      rsa_sig_print,
937      int_rsa_free,
938      rsa_pkey_ctrl,
939      old_rsa_priv_decode,
940      old_rsa_priv_encode,
941      rsa_item_verify,
942      rsa_item_sign},
943
944     {
945      EVP_PKEY_RSA2,
946      EVP_PKEY_RSA,
947      ASN1_PKEY_ALIAS}
948 };