d2f976f6814a33f8e2313f77f9081b450060a0a6
[openssl.git] / crypto / rsa / rsa_ameth.c
1 /*
2  * Copyright 2006-2018 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <stdio.h>
11 #include "internal/cryptlib.h"
12 #include <openssl/asn1t.h>
13 #include <openssl/x509.h>
14 #include <openssl/bn.h>
15 #include <openssl/cms.h>
16 #include <openssl/core_names.h>
17 #include "internal/param_build.h"
18 #include "crypto/asn1.h"
19 #include "crypto/evp.h"
20 #include "crypto/rsa.h"
21 #include "rsa_local.h"
22
23 #ifndef OPENSSL_NO_CMS
24 static int rsa_cms_sign(CMS_SignerInfo *si);
25 static int rsa_cms_verify(CMS_SignerInfo *si);
26 static int rsa_cms_decrypt(CMS_RecipientInfo *ri);
27 static int rsa_cms_encrypt(CMS_RecipientInfo *ri);
28 #endif
29
30 static RSA_PSS_PARAMS *rsa_pss_decode(const X509_ALGOR *alg);
31
32 /* Set any parameters associated with pkey */
33 static int rsa_param_encode(const EVP_PKEY *pkey,
34                             ASN1_STRING **pstr, int *pstrtype)
35 {
36     const RSA *rsa = pkey->pkey.rsa;
37
38     *pstr = NULL;
39     /* If RSA it's just NULL type */
40     if (pkey->ameth->pkey_id != EVP_PKEY_RSA_PSS) {
41         *pstrtype = V_ASN1_NULL;
42         return 1;
43     }
44     /* If no PSS parameters we omit parameters entirely */
45     if (rsa->pss == NULL) {
46         *pstrtype = V_ASN1_UNDEF;
47         return 1;
48     }
49     /* Encode PSS parameters */
50     if (ASN1_item_pack(rsa->pss, ASN1_ITEM_rptr(RSA_PSS_PARAMS), pstr) == NULL)
51         return 0;
52
53     *pstrtype = V_ASN1_SEQUENCE;
54     return 1;
55 }
56 /* Decode any parameters and set them in RSA structure */
57 static int rsa_param_decode(RSA *rsa, const X509_ALGOR *alg)
58 {
59     const ASN1_OBJECT *algoid;
60     const void *algp;
61     int algptype;
62
63     X509_ALGOR_get0(&algoid, &algptype, &algp, alg);
64     if (OBJ_obj2nid(algoid) != EVP_PKEY_RSA_PSS)
65         return 1;
66     if (algptype == V_ASN1_UNDEF)
67         return 1;
68     if (algptype != V_ASN1_SEQUENCE) {
69         RSAerr(RSA_F_RSA_PARAM_DECODE, RSA_R_INVALID_PSS_PARAMETERS);
70         return 0;
71     }
72     rsa->pss = rsa_pss_decode(alg);
73     if (rsa->pss == NULL)
74         return 0;
75     return 1;
76 }
77
78 static int rsa_pub_encode(X509_PUBKEY *pk, const EVP_PKEY *pkey)
79 {
80     unsigned char *penc = NULL;
81     int penclen;
82     ASN1_STRING *str;
83     int strtype;
84
85     if (!rsa_param_encode(pkey, &str, &strtype))
86         return 0;
87     penclen = i2d_RSAPublicKey(pkey->pkey.rsa, &penc);
88     if (penclen <= 0)
89         return 0;
90     if (X509_PUBKEY_set0_param(pk, OBJ_nid2obj(pkey->ameth->pkey_id),
91                                strtype, str, penc, penclen))
92         return 1;
93
94     OPENSSL_free(penc);
95     return 0;
96 }
97
98 static int rsa_pub_decode(EVP_PKEY *pkey, X509_PUBKEY *pubkey)
99 {
100     const unsigned char *p;
101     int pklen;
102     X509_ALGOR *alg;
103     RSA *rsa = NULL;
104
105     if (!X509_PUBKEY_get0_param(NULL, &p, &pklen, &alg, pubkey))
106         return 0;
107     if ((rsa = d2i_RSAPublicKey(NULL, &p, pklen)) == NULL) {
108         RSAerr(RSA_F_RSA_PUB_DECODE, ERR_R_RSA_LIB);
109         return 0;
110     }
111     if (!rsa_param_decode(rsa, alg)) {
112         RSA_free(rsa);
113         return 0;
114     }
115     if (!EVP_PKEY_assign(pkey, pkey->ameth->pkey_id, rsa)) {
116         RSA_free(rsa);
117         return 0;
118     }
119     return 1;
120 }
121
122 static int rsa_pub_cmp(const EVP_PKEY *a, const EVP_PKEY *b)
123 {
124     if (BN_cmp(b->pkey.rsa->n, a->pkey.rsa->n) != 0
125         || BN_cmp(b->pkey.rsa->e, a->pkey.rsa->e) != 0)
126         return 0;
127     return 1;
128 }
129
130 static int old_rsa_priv_decode(EVP_PKEY *pkey,
131                                const unsigned char **pder, int derlen)
132 {
133     RSA *rsa;
134
135     if ((rsa = d2i_RSAPrivateKey(NULL, pder, derlen)) == NULL) {
136         RSAerr(RSA_F_OLD_RSA_PRIV_DECODE, ERR_R_RSA_LIB);
137         return 0;
138     }
139     EVP_PKEY_assign(pkey, pkey->ameth->pkey_id, rsa);
140     return 1;
141 }
142
143 static int old_rsa_priv_encode(const EVP_PKEY *pkey, unsigned char **pder)
144 {
145     return i2d_RSAPrivateKey(pkey->pkey.rsa, pder);
146 }
147
148 static int rsa_priv_encode(PKCS8_PRIV_KEY_INFO *p8, const EVP_PKEY *pkey)
149 {
150     unsigned char *rk = NULL;
151     int rklen;
152     ASN1_STRING *str;
153     int strtype;
154
155     if (!rsa_param_encode(pkey, &str, &strtype))
156         return 0;
157     rklen = i2d_RSAPrivateKey(pkey->pkey.rsa, &rk);
158
159     if (rklen <= 0) {
160         RSAerr(RSA_F_RSA_PRIV_ENCODE, ERR_R_MALLOC_FAILURE);
161         ASN1_STRING_free(str);
162         return 0;
163     }
164
165     if (!PKCS8_pkey_set0(p8, OBJ_nid2obj(pkey->ameth->pkey_id), 0,
166                          strtype, str, rk, rklen)) {
167         RSAerr(RSA_F_RSA_PRIV_ENCODE, ERR_R_MALLOC_FAILURE);
168         ASN1_STRING_free(str);
169         return 0;
170     }
171
172     return 1;
173 }
174
175 static int rsa_priv_decode(EVP_PKEY *pkey, const PKCS8_PRIV_KEY_INFO *p8)
176 {
177     const unsigned char *p;
178     RSA *rsa;
179     int pklen;
180     const X509_ALGOR *alg;
181
182     if (!PKCS8_pkey_get0(NULL, &p, &pklen, &alg, p8))
183         return 0;
184     rsa = d2i_RSAPrivateKey(NULL, &p, pklen);
185     if (rsa == NULL) {
186         RSAerr(RSA_F_RSA_PRIV_DECODE, ERR_R_RSA_LIB);
187         return 0;
188     }
189     if (!rsa_param_decode(rsa, alg)) {
190         RSA_free(rsa);
191         return 0;
192     }
193     EVP_PKEY_assign(pkey, pkey->ameth->pkey_id, rsa);
194     return 1;
195 }
196
197 static int int_rsa_size(const EVP_PKEY *pkey)
198 {
199     return RSA_size(pkey->pkey.rsa);
200 }
201
202 static int rsa_bits(const EVP_PKEY *pkey)
203 {
204     return BN_num_bits(pkey->pkey.rsa->n);
205 }
206
207 static int rsa_security_bits(const EVP_PKEY *pkey)
208 {
209     return RSA_security_bits(pkey->pkey.rsa);
210 }
211
212 static void int_rsa_free(EVP_PKEY *pkey)
213 {
214     RSA_free(pkey->pkey.rsa);
215 }
216
217 static X509_ALGOR *rsa_mgf1_decode(X509_ALGOR *alg)
218 {
219     if (OBJ_obj2nid(alg->algorithm) != NID_mgf1)
220         return NULL;
221     return ASN1_TYPE_unpack_sequence(ASN1_ITEM_rptr(X509_ALGOR),
222                                      alg->parameter);
223 }
224
225 static int rsa_pss_param_print(BIO *bp, int pss_key, RSA_PSS_PARAMS *pss,
226                                int indent)
227 {
228     int rv = 0;
229     X509_ALGOR *maskHash = NULL;
230
231     if (!BIO_indent(bp, indent, 128))
232         goto err;
233     if (pss_key) {
234         if (pss == NULL) {
235             if (BIO_puts(bp, "No PSS parameter restrictions\n") <= 0)
236                 return 0;
237             return 1;
238         } else {
239             if (BIO_puts(bp, "PSS parameter restrictions:") <= 0)
240                 return 0;
241         }
242     } else if (pss == NULL) {
243         if (BIO_puts(bp,"(INVALID PSS PARAMETERS)\n") <= 0)
244             return 0;
245         return 1;
246     }
247     if (BIO_puts(bp, "\n") <= 0)
248         goto err;
249     if (pss_key)
250         indent += 2;
251     if (!BIO_indent(bp, indent, 128))
252         goto err;
253     if (BIO_puts(bp, "Hash Algorithm: ") <= 0)
254         goto err;
255
256     if (pss->hashAlgorithm) {
257         if (i2a_ASN1_OBJECT(bp, pss->hashAlgorithm->algorithm) <= 0)
258             goto err;
259     } else if (BIO_puts(bp, "sha1 (default)") <= 0) {
260         goto err;
261     }
262
263     if (BIO_puts(bp, "\n") <= 0)
264         goto err;
265
266     if (!BIO_indent(bp, indent, 128))
267         goto err;
268
269     if (BIO_puts(bp, "Mask Algorithm: ") <= 0)
270         goto err;
271     if (pss->maskGenAlgorithm) {
272         if (i2a_ASN1_OBJECT(bp, pss->maskGenAlgorithm->algorithm) <= 0)
273             goto err;
274         if (BIO_puts(bp, " with ") <= 0)
275             goto err;
276         maskHash = rsa_mgf1_decode(pss->maskGenAlgorithm);
277         if (maskHash != NULL) {
278             if (i2a_ASN1_OBJECT(bp, maskHash->algorithm) <= 0)
279                 goto err;
280         } else if (BIO_puts(bp, "INVALID") <= 0) {
281             goto err;
282         }
283     } else if (BIO_puts(bp, "mgf1 with sha1 (default)") <= 0) {
284         goto err;
285     }
286     BIO_puts(bp, "\n");
287
288     if (!BIO_indent(bp, indent, 128))
289         goto err;
290     if (BIO_printf(bp, "%s Salt Length: 0x", pss_key ? "Minimum" : "") <= 0)
291         goto err;
292     if (pss->saltLength) {
293         if (i2a_ASN1_INTEGER(bp, pss->saltLength) <= 0)
294             goto err;
295     } else if (BIO_puts(bp, "14 (default)") <= 0) {
296         goto err;
297     }
298     BIO_puts(bp, "\n");
299
300     if (!BIO_indent(bp, indent, 128))
301         goto err;
302     if (BIO_puts(bp, "Trailer Field: 0x") <= 0)
303         goto err;
304     if (pss->trailerField) {
305         if (i2a_ASN1_INTEGER(bp, pss->trailerField) <= 0)
306             goto err;
307     } else if (BIO_puts(bp, "BC (default)") <= 0) {
308         goto err;
309     }
310     BIO_puts(bp, "\n");
311
312     rv = 1;
313
314  err:
315     X509_ALGOR_free(maskHash);
316     return rv;
317
318 }
319
320 static int pkey_rsa_print(BIO *bp, const EVP_PKEY *pkey, int off, int priv)
321 {
322     const RSA *x = pkey->pkey.rsa;
323     char *str;
324     const char *s;
325     int ret = 0, mod_len = 0, ex_primes;
326
327     if (x->n != NULL)
328         mod_len = BN_num_bits(x->n);
329     ex_primes = sk_RSA_PRIME_INFO_num(x->prime_infos);
330
331     if (!BIO_indent(bp, off, 128))
332         goto err;
333
334     if (BIO_printf(bp, "%s ", pkey_is_pss(pkey) ?  "RSA-PSS" : "RSA") <= 0)
335         goto err;
336
337     if (priv && x->d) {
338         if (BIO_printf(bp, "Private-Key: (%d bit, %d primes)\n",
339                        mod_len, ex_primes <= 0 ? 2 : ex_primes + 2) <= 0)
340             goto err;
341         str = "modulus:";
342         s = "publicExponent:";
343     } else {
344         if (BIO_printf(bp, "Public-Key: (%d bit)\n", mod_len) <= 0)
345             goto err;
346         str = "Modulus:";
347         s = "Exponent:";
348     }
349     if (!ASN1_bn_print(bp, str, x->n, NULL, off))
350         goto err;
351     if (!ASN1_bn_print(bp, s, x->e, NULL, off))
352         goto err;
353     if (priv) {
354         int i;
355
356         if (!ASN1_bn_print(bp, "privateExponent:", x->d, NULL, off))
357             goto err;
358         if (!ASN1_bn_print(bp, "prime1:", x->p, NULL, off))
359             goto err;
360         if (!ASN1_bn_print(bp, "prime2:", x->q, NULL, off))
361             goto err;
362         if (!ASN1_bn_print(bp, "exponent1:", x->dmp1, NULL, off))
363             goto err;
364         if (!ASN1_bn_print(bp, "exponent2:", x->dmq1, NULL, off))
365             goto err;
366         if (!ASN1_bn_print(bp, "coefficient:", x->iqmp, NULL, off))
367             goto err;
368         for (i = 0; i < sk_RSA_PRIME_INFO_num(x->prime_infos); i++) {
369             /* print multi-prime info */
370             BIGNUM *bn = NULL;
371             RSA_PRIME_INFO *pinfo;
372             int j;
373
374             pinfo = sk_RSA_PRIME_INFO_value(x->prime_infos, i);
375             for (j = 0; j < 3; j++) {
376                 if (!BIO_indent(bp, off, 128))
377                     goto err;
378                 switch (j) {
379                 case 0:
380                     if (BIO_printf(bp, "prime%d:", i + 3) <= 0)
381                         goto err;
382                     bn = pinfo->r;
383                     break;
384                 case 1:
385                     if (BIO_printf(bp, "exponent%d:", i + 3) <= 0)
386                         goto err;
387                     bn = pinfo->d;
388                     break;
389                 case 2:
390                     if (BIO_printf(bp, "coefficient%d:", i + 3) <= 0)
391                         goto err;
392                     bn = pinfo->t;
393                     break;
394                 default:
395                     break;
396                 }
397                 if (!ASN1_bn_print(bp, "", bn, NULL, off))
398                     goto err;
399             }
400         }
401     }
402     if (pkey_is_pss(pkey) && !rsa_pss_param_print(bp, 1, x->pss, off))
403         goto err;
404     ret = 1;
405  err:
406     return ret;
407 }
408
409 static int rsa_pub_print(BIO *bp, const EVP_PKEY *pkey, int indent,
410                          ASN1_PCTX *ctx)
411 {
412     return pkey_rsa_print(bp, pkey, indent, 0);
413 }
414
415 static int rsa_priv_print(BIO *bp, const EVP_PKEY *pkey, int indent,
416                           ASN1_PCTX *ctx)
417 {
418     return pkey_rsa_print(bp, pkey, indent, 1);
419 }
420
421 static RSA_PSS_PARAMS *rsa_pss_decode(const X509_ALGOR *alg)
422 {
423     RSA_PSS_PARAMS *pss;
424
425     pss = ASN1_TYPE_unpack_sequence(ASN1_ITEM_rptr(RSA_PSS_PARAMS),
426                                     alg->parameter);
427
428     if (pss == NULL)
429         return NULL;
430
431     if (pss->maskGenAlgorithm != NULL) {
432         pss->maskHash = rsa_mgf1_decode(pss->maskGenAlgorithm);
433         if (pss->maskHash == NULL) {
434             RSA_PSS_PARAMS_free(pss);
435             return NULL;
436         }
437     }
438
439     return pss;
440 }
441
442 static int rsa_sig_print(BIO *bp, const X509_ALGOR *sigalg,
443                          const ASN1_STRING *sig, int indent, ASN1_PCTX *pctx)
444 {
445     if (OBJ_obj2nid(sigalg->algorithm) == EVP_PKEY_RSA_PSS) {
446         int rv;
447         RSA_PSS_PARAMS *pss = rsa_pss_decode(sigalg);
448
449         rv = rsa_pss_param_print(bp, 0, pss, indent);
450         RSA_PSS_PARAMS_free(pss);
451         if (!rv)
452             return 0;
453     } else if (BIO_puts(bp, "\n") <= 0) {
454         return 0;
455     }
456     if (sig)
457         return X509_signature_dump(bp, sig, indent);
458     return 1;
459 }
460
461 static int rsa_pkey_ctrl(EVP_PKEY *pkey, int op, long arg1, void *arg2)
462 {
463     X509_ALGOR *alg = NULL;
464     const EVP_MD *md;
465     const EVP_MD *mgf1md;
466     int min_saltlen;
467
468     switch (op) {
469
470     case ASN1_PKEY_CTRL_PKCS7_SIGN:
471         if (arg1 == 0)
472             PKCS7_SIGNER_INFO_get0_algs(arg2, NULL, NULL, &alg);
473         break;
474
475     case ASN1_PKEY_CTRL_PKCS7_ENCRYPT:
476         if (pkey_is_pss(pkey))
477             return -2;
478         if (arg1 == 0)
479             PKCS7_RECIP_INFO_get0_alg(arg2, &alg);
480         break;
481 #ifndef OPENSSL_NO_CMS
482     case ASN1_PKEY_CTRL_CMS_SIGN:
483         if (arg1 == 0)
484             return rsa_cms_sign(arg2);
485         else if (arg1 == 1)
486             return rsa_cms_verify(arg2);
487         break;
488
489     case ASN1_PKEY_CTRL_CMS_ENVELOPE:
490         if (pkey_is_pss(pkey))
491             return -2;
492         if (arg1 == 0)
493             return rsa_cms_encrypt(arg2);
494         else if (arg1 == 1)
495             return rsa_cms_decrypt(arg2);
496         break;
497
498     case ASN1_PKEY_CTRL_CMS_RI_TYPE:
499         if (pkey_is_pss(pkey))
500             return -2;
501         *(int *)arg2 = CMS_RECIPINFO_TRANS;
502         return 1;
503 #endif
504
505     case ASN1_PKEY_CTRL_DEFAULT_MD_NID:
506         if (pkey->pkey.rsa->pss != NULL) {
507             if (!rsa_pss_get_param(pkey->pkey.rsa->pss, &md, &mgf1md,
508                                    &min_saltlen)) {
509                 RSAerr(0, ERR_R_INTERNAL_ERROR);
510                 return 0;
511             }
512             *(int *)arg2 = EVP_MD_type(md);
513             /* Return of 2 indicates this MD is mandatory */
514             return 2;
515         }
516         *(int *)arg2 = NID_sha256;
517         return 1;
518
519     default:
520         return -2;
521
522     }
523
524     if (alg)
525         X509_ALGOR_set0(alg, OBJ_nid2obj(NID_rsaEncryption), V_ASN1_NULL, 0);
526
527     return 1;
528
529 }
530
531 /* allocate and set algorithm ID from EVP_MD, default SHA1 */
532 static int rsa_md_to_algor(X509_ALGOR **palg, const EVP_MD *md)
533 {
534     if (md == NULL || EVP_MD_type(md) == NID_sha1)
535         return 1;
536     *palg = X509_ALGOR_new();
537     if (*palg == NULL)
538         return 0;
539     X509_ALGOR_set_md(*palg, md);
540     return 1;
541 }
542
543 /* Allocate and set MGF1 algorithm ID from EVP_MD */
544 static int rsa_md_to_mgf1(X509_ALGOR **palg, const EVP_MD *mgf1md)
545 {
546     X509_ALGOR *algtmp = NULL;
547     ASN1_STRING *stmp = NULL;
548
549     *palg = NULL;
550     if (mgf1md == NULL || EVP_MD_type(mgf1md) == NID_sha1)
551         return 1;
552     /* need to embed algorithm ID inside another */
553     if (!rsa_md_to_algor(&algtmp, mgf1md))
554         goto err;
555     if (ASN1_item_pack(algtmp, ASN1_ITEM_rptr(X509_ALGOR), &stmp) == NULL)
556          goto err;
557     *palg = X509_ALGOR_new();
558     if (*palg == NULL)
559         goto err;
560     X509_ALGOR_set0(*palg, OBJ_nid2obj(NID_mgf1), V_ASN1_SEQUENCE, stmp);
561     stmp = NULL;
562  err:
563     ASN1_STRING_free(stmp);
564     X509_ALGOR_free(algtmp);
565     if (*palg)
566         return 1;
567     return 0;
568 }
569
570 /* convert algorithm ID to EVP_MD, default SHA1 */
571 static const EVP_MD *rsa_algor_to_md(X509_ALGOR *alg)
572 {
573     const EVP_MD *md;
574
575     if (!alg)
576         return EVP_sha1();
577     md = EVP_get_digestbyobj(alg->algorithm);
578     if (md == NULL)
579         RSAerr(RSA_F_RSA_ALGOR_TO_MD, RSA_R_UNKNOWN_DIGEST);
580     return md;
581 }
582
583 /*
584  * Convert EVP_PKEY_CTX in PSS mode into corresponding algorithm parameter,
585  * suitable for setting an AlgorithmIdentifier.
586  */
587
588 static RSA_PSS_PARAMS *rsa_ctx_to_pss(EVP_PKEY_CTX *pkctx)
589 {
590     const EVP_MD *sigmd, *mgf1md;
591     EVP_PKEY *pk = EVP_PKEY_CTX_get0_pkey(pkctx);
592     int saltlen;
593
594     if (EVP_PKEY_CTX_get_signature_md(pkctx, &sigmd) <= 0)
595         return NULL;
596     if (EVP_PKEY_CTX_get_rsa_mgf1_md(pkctx, &mgf1md) <= 0)
597         return NULL;
598     if (!EVP_PKEY_CTX_get_rsa_pss_saltlen(pkctx, &saltlen))
599         return NULL;
600     if (saltlen == -1) {
601         saltlen = EVP_MD_size(sigmd);
602     } else if (saltlen == -2 || saltlen == -3) {
603         saltlen = EVP_PKEY_size(pk) - EVP_MD_size(sigmd) - 2;
604         if ((EVP_PKEY_bits(pk) & 0x7) == 1)
605             saltlen--;
606         if (saltlen < 0)
607             return NULL;
608     }
609
610     return rsa_pss_params_create(sigmd, mgf1md, saltlen);
611 }
612
613 RSA_PSS_PARAMS *rsa_pss_params_create(const EVP_MD *sigmd,
614                                       const EVP_MD *mgf1md, int saltlen)
615 {
616     RSA_PSS_PARAMS *pss = RSA_PSS_PARAMS_new();
617
618     if (pss == NULL)
619         goto err;
620     if (saltlen != 20) {
621         pss->saltLength = ASN1_INTEGER_new();
622         if (pss->saltLength == NULL)
623             goto err;
624         if (!ASN1_INTEGER_set(pss->saltLength, saltlen))
625             goto err;
626     }
627     if (!rsa_md_to_algor(&pss->hashAlgorithm, sigmd))
628         goto err;
629     if (mgf1md == NULL)
630         mgf1md = sigmd;
631     if (!rsa_md_to_mgf1(&pss->maskGenAlgorithm, mgf1md))
632         goto err;
633     if (!rsa_md_to_algor(&pss->maskHash, mgf1md))
634         goto err;
635     return pss;
636  err:
637     RSA_PSS_PARAMS_free(pss);
638     return NULL;
639 }
640
641 static ASN1_STRING *rsa_ctx_to_pss_string(EVP_PKEY_CTX *pkctx)
642 {
643     RSA_PSS_PARAMS *pss = rsa_ctx_to_pss(pkctx);
644     ASN1_STRING *os;
645
646     if (pss == NULL)
647         return NULL;
648
649     os = ASN1_item_pack(pss, ASN1_ITEM_rptr(RSA_PSS_PARAMS), NULL);
650     RSA_PSS_PARAMS_free(pss);
651     return os;
652 }
653
654 /*
655  * From PSS AlgorithmIdentifier set public key parameters. If pkey isn't NULL
656  * then the EVP_MD_CTX is setup and initialised. If it is NULL parameters are
657  * passed to pkctx instead.
658  */
659
660 static int rsa_pss_to_ctx(EVP_MD_CTX *ctx, EVP_PKEY_CTX *pkctx,
661                           X509_ALGOR *sigalg, EVP_PKEY *pkey)
662 {
663     int rv = -1;
664     int saltlen;
665     const EVP_MD *mgf1md = NULL, *md = NULL;
666     RSA_PSS_PARAMS *pss;
667
668     /* Sanity check: make sure it is PSS */
669     if (OBJ_obj2nid(sigalg->algorithm) != EVP_PKEY_RSA_PSS) {
670         RSAerr(RSA_F_RSA_PSS_TO_CTX, RSA_R_UNSUPPORTED_SIGNATURE_TYPE);
671         return -1;
672     }
673     /* Decode PSS parameters */
674     pss = rsa_pss_decode(sigalg);
675
676     if (!rsa_pss_get_param(pss, &md, &mgf1md, &saltlen)) {
677         RSAerr(RSA_F_RSA_PSS_TO_CTX, RSA_R_INVALID_PSS_PARAMETERS);
678         goto err;
679     }
680
681     /* We have all parameters now set up context */
682     if (pkey) {
683         if (!EVP_DigestVerifyInit(ctx, &pkctx, md, NULL, pkey))
684             goto err;
685     } else {
686         const EVP_MD *checkmd;
687         if (EVP_PKEY_CTX_get_signature_md(pkctx, &checkmd) <= 0)
688             goto err;
689         if (EVP_MD_type(md) != EVP_MD_type(checkmd)) {
690             RSAerr(RSA_F_RSA_PSS_TO_CTX, RSA_R_DIGEST_DOES_NOT_MATCH);
691             goto err;
692         }
693     }
694
695     if (EVP_PKEY_CTX_set_rsa_padding(pkctx, RSA_PKCS1_PSS_PADDING) <= 0)
696         goto err;
697
698     if (EVP_PKEY_CTX_set_rsa_pss_saltlen(pkctx, saltlen) <= 0)
699         goto err;
700
701     if (EVP_PKEY_CTX_set_rsa_mgf1_md(pkctx, mgf1md) <= 0)
702         goto err;
703     /* Carry on */
704     rv = 1;
705
706  err:
707     RSA_PSS_PARAMS_free(pss);
708     return rv;
709 }
710
711 int rsa_pss_get_param(const RSA_PSS_PARAMS *pss, const EVP_MD **pmd,
712                       const EVP_MD **pmgf1md, int *psaltlen)
713 {
714     if (pss == NULL)
715         return 0;
716     *pmd = rsa_algor_to_md(pss->hashAlgorithm);
717     if (*pmd == NULL)
718         return 0;
719     *pmgf1md = rsa_algor_to_md(pss->maskHash);
720     if (*pmgf1md == NULL)
721         return 0;
722     if (pss->saltLength) {
723         *psaltlen = ASN1_INTEGER_get(pss->saltLength);
724         if (*psaltlen < 0) {
725             RSAerr(RSA_F_RSA_PSS_GET_PARAM, RSA_R_INVALID_SALT_LENGTH);
726             return 0;
727         }
728     } else {
729         *psaltlen = 20;
730     }
731
732     /*
733      * low-level routines support only trailer field 0xbc (value 1) and
734      * PKCS#1 says we should reject any other value anyway.
735      */
736     if (pss->trailerField && ASN1_INTEGER_get(pss->trailerField) != 1) {
737         RSAerr(RSA_F_RSA_PSS_GET_PARAM, RSA_R_INVALID_TRAILER);
738         return 0;
739     }
740
741     return 1;
742 }
743
744 #ifndef OPENSSL_NO_CMS
745 static int rsa_cms_verify(CMS_SignerInfo *si)
746 {
747     int nid, nid2;
748     X509_ALGOR *alg;
749     EVP_PKEY_CTX *pkctx = CMS_SignerInfo_get0_pkey_ctx(si);
750
751     CMS_SignerInfo_get0_algs(si, NULL, NULL, NULL, &alg);
752     nid = OBJ_obj2nid(alg->algorithm);
753     if (nid == EVP_PKEY_RSA_PSS)
754         return rsa_pss_to_ctx(NULL, pkctx, alg, NULL);
755     /* Only PSS allowed for PSS keys */
756     if (pkey_ctx_is_pss(pkctx)) {
757         RSAerr(RSA_F_RSA_CMS_VERIFY, RSA_R_ILLEGAL_OR_UNSUPPORTED_PADDING_MODE);
758         return 0;
759     }
760     if (nid == NID_rsaEncryption)
761         return 1;
762     /* Workaround for some implementation that use a signature OID */
763     if (OBJ_find_sigid_algs(nid, NULL, &nid2)) {
764         if (nid2 == NID_rsaEncryption)
765             return 1;
766     }
767     return 0;
768 }
769 #endif
770
771 /*
772  * Customised RSA item verification routine. This is called when a signature
773  * is encountered requiring special handling. We currently only handle PSS.
774  */
775
776 static int rsa_item_verify(EVP_MD_CTX *ctx, const ASN1_ITEM *it, void *asn,
777                            X509_ALGOR *sigalg, ASN1_BIT_STRING *sig,
778                            EVP_PKEY *pkey)
779 {
780     /* Sanity check: make sure it is PSS */
781     if (OBJ_obj2nid(sigalg->algorithm) != EVP_PKEY_RSA_PSS) {
782         RSAerr(RSA_F_RSA_ITEM_VERIFY, RSA_R_UNSUPPORTED_SIGNATURE_TYPE);
783         return -1;
784     }
785     if (rsa_pss_to_ctx(ctx, NULL, sigalg, pkey) > 0) {
786         /* Carry on */
787         return 2;
788     }
789     return -1;
790 }
791
792 #ifndef OPENSSL_NO_CMS
793 static int rsa_cms_sign(CMS_SignerInfo *si)
794 {
795     int pad_mode = RSA_PKCS1_PADDING;
796     X509_ALGOR *alg;
797     EVP_PKEY_CTX *pkctx = CMS_SignerInfo_get0_pkey_ctx(si);
798     ASN1_STRING *os = NULL;
799
800     CMS_SignerInfo_get0_algs(si, NULL, NULL, NULL, &alg);
801     if (pkctx) {
802         if (EVP_PKEY_CTX_get_rsa_padding(pkctx, &pad_mode) <= 0)
803             return 0;
804     }
805     if (pad_mode == RSA_PKCS1_PADDING) {
806         X509_ALGOR_set0(alg, OBJ_nid2obj(NID_rsaEncryption), V_ASN1_NULL, 0);
807         return 1;
808     }
809     /* We don't support it */
810     if (pad_mode != RSA_PKCS1_PSS_PADDING)
811         return 0;
812     os = rsa_ctx_to_pss_string(pkctx);
813     if (!os)
814         return 0;
815     X509_ALGOR_set0(alg, OBJ_nid2obj(EVP_PKEY_RSA_PSS), V_ASN1_SEQUENCE, os);
816     return 1;
817 }
818 #endif
819
820 static int rsa_item_sign(EVP_MD_CTX *ctx, const ASN1_ITEM *it, void *asn,
821                          X509_ALGOR *alg1, X509_ALGOR *alg2,
822                          ASN1_BIT_STRING *sig)
823 {
824     int pad_mode;
825     EVP_PKEY_CTX *pkctx = EVP_MD_CTX_pkey_ctx(ctx);
826
827     if (EVP_PKEY_CTX_get_rsa_padding(pkctx, &pad_mode) <= 0)
828         return 0;
829     if (pad_mode == RSA_PKCS1_PADDING)
830         return 2;
831     if (pad_mode == RSA_PKCS1_PSS_PADDING) {
832         ASN1_STRING *os1 = NULL;
833         os1 = rsa_ctx_to_pss_string(pkctx);
834         if (!os1)
835             return 0;
836         /* Duplicate parameters if we have to */
837         if (alg2) {
838             ASN1_STRING *os2 = ASN1_STRING_dup(os1);
839             if (!os2) {
840                 ASN1_STRING_free(os1);
841                 return 0;
842             }
843             X509_ALGOR_set0(alg2, OBJ_nid2obj(EVP_PKEY_RSA_PSS),
844                             V_ASN1_SEQUENCE, os2);
845         }
846         X509_ALGOR_set0(alg1, OBJ_nid2obj(EVP_PKEY_RSA_PSS),
847                         V_ASN1_SEQUENCE, os1);
848         return 3;
849     }
850     return 2;
851 }
852
853 static int rsa_sig_info_set(X509_SIG_INFO *siginf, const X509_ALGOR *sigalg,
854                             const ASN1_STRING *sig)
855 {
856     int rv = 0;
857     int mdnid, saltlen;
858     uint32_t flags;
859     const EVP_MD *mgf1md = NULL, *md = NULL;
860     RSA_PSS_PARAMS *pss;
861
862     /* Sanity check: make sure it is PSS */
863     if (OBJ_obj2nid(sigalg->algorithm) != EVP_PKEY_RSA_PSS)
864         return 0;
865     /* Decode PSS parameters */
866     pss = rsa_pss_decode(sigalg);
867     if (!rsa_pss_get_param(pss, &md, &mgf1md, &saltlen))
868         goto err;
869     mdnid = EVP_MD_type(md);
870     /*
871      * For TLS need SHA256, SHA384 or SHA512, digest and MGF1 digest must
872      * match and salt length must equal digest size
873      */
874     if ((mdnid == NID_sha256 || mdnid == NID_sha384 || mdnid == NID_sha512)
875             && mdnid == EVP_MD_type(mgf1md) && saltlen == EVP_MD_size(md))
876         flags = X509_SIG_INFO_TLS;
877     else
878         flags = 0;
879     /* Note: security bits half number of digest bits */
880     X509_SIG_INFO_set(siginf, mdnid, EVP_PKEY_RSA_PSS, EVP_MD_size(md) * 4,
881                       flags);
882     rv = 1;
883     err:
884     RSA_PSS_PARAMS_free(pss);
885     return rv;
886 }
887
888 #ifndef OPENSSL_NO_CMS
889 static RSA_OAEP_PARAMS *rsa_oaep_decode(const X509_ALGOR *alg)
890 {
891     RSA_OAEP_PARAMS *oaep;
892
893     oaep = ASN1_TYPE_unpack_sequence(ASN1_ITEM_rptr(RSA_OAEP_PARAMS),
894                                      alg->parameter);
895
896     if (oaep == NULL)
897         return NULL;
898
899     if (oaep->maskGenFunc != NULL) {
900         oaep->maskHash = rsa_mgf1_decode(oaep->maskGenFunc);
901         if (oaep->maskHash == NULL) {
902             RSA_OAEP_PARAMS_free(oaep);
903             return NULL;
904         }
905     }
906     return oaep;
907 }
908
909 static int rsa_cms_decrypt(CMS_RecipientInfo *ri)
910 {
911     EVP_PKEY_CTX *pkctx;
912     X509_ALGOR *cmsalg;
913     int nid;
914     int rv = -1;
915     unsigned char *label = NULL;
916     int labellen = 0;
917     const EVP_MD *mgf1md = NULL, *md = NULL;
918     RSA_OAEP_PARAMS *oaep;
919
920     pkctx = CMS_RecipientInfo_get0_pkey_ctx(ri);
921     if (pkctx == NULL)
922         return 0;
923     if (!CMS_RecipientInfo_ktri_get0_algs(ri, NULL, NULL, &cmsalg))
924         return -1;
925     nid = OBJ_obj2nid(cmsalg->algorithm);
926     if (nid == NID_rsaEncryption)
927         return 1;
928     if (nid != NID_rsaesOaep) {
929         RSAerr(RSA_F_RSA_CMS_DECRYPT, RSA_R_UNSUPPORTED_ENCRYPTION_TYPE);
930         return -1;
931     }
932     /* Decode OAEP parameters */
933     oaep = rsa_oaep_decode(cmsalg);
934
935     if (oaep == NULL) {
936         RSAerr(RSA_F_RSA_CMS_DECRYPT, RSA_R_INVALID_OAEP_PARAMETERS);
937         goto err;
938     }
939
940     mgf1md = rsa_algor_to_md(oaep->maskHash);
941     if (mgf1md == NULL)
942         goto err;
943     md = rsa_algor_to_md(oaep->hashFunc);
944     if (md == NULL)
945         goto err;
946
947     if (oaep->pSourceFunc != NULL) {
948         X509_ALGOR *plab = oaep->pSourceFunc;
949
950         if (OBJ_obj2nid(plab->algorithm) != NID_pSpecified) {
951             RSAerr(RSA_F_RSA_CMS_DECRYPT, RSA_R_UNSUPPORTED_LABEL_SOURCE);
952             goto err;
953         }
954         if (plab->parameter->type != V_ASN1_OCTET_STRING) {
955             RSAerr(RSA_F_RSA_CMS_DECRYPT, RSA_R_INVALID_LABEL);
956             goto err;
957         }
958
959         label = plab->parameter->value.octet_string->data;
960         /* Stop label being freed when OAEP parameters are freed */
961         plab->parameter->value.octet_string->data = NULL;
962         labellen = plab->parameter->value.octet_string->length;
963     }
964
965     if (EVP_PKEY_CTX_set_rsa_padding(pkctx, RSA_PKCS1_OAEP_PADDING) <= 0)
966         goto err;
967     if (EVP_PKEY_CTX_set_rsa_oaep_md(pkctx, md) <= 0)
968         goto err;
969     if (EVP_PKEY_CTX_set_rsa_mgf1_md(pkctx, mgf1md) <= 0)
970         goto err;
971     if (EVP_PKEY_CTX_set0_rsa_oaep_label(pkctx, label, labellen) <= 0)
972         goto err;
973     /* Carry on */
974     rv = 1;
975
976  err:
977     RSA_OAEP_PARAMS_free(oaep);
978     return rv;
979 }
980
981 static int rsa_cms_encrypt(CMS_RecipientInfo *ri)
982 {
983     const EVP_MD *md, *mgf1md;
984     RSA_OAEP_PARAMS *oaep = NULL;
985     ASN1_STRING *os = NULL;
986     X509_ALGOR *alg;
987     EVP_PKEY_CTX *pkctx = CMS_RecipientInfo_get0_pkey_ctx(ri);
988     int pad_mode = RSA_PKCS1_PADDING, rv = 0, labellen;
989     unsigned char *label;
990
991     if (CMS_RecipientInfo_ktri_get0_algs(ri, NULL, NULL, &alg) <= 0)
992         return 0;
993     if (pkctx) {
994         if (EVP_PKEY_CTX_get_rsa_padding(pkctx, &pad_mode) <= 0)
995             return 0;
996     }
997     if (pad_mode == RSA_PKCS1_PADDING) {
998         X509_ALGOR_set0(alg, OBJ_nid2obj(NID_rsaEncryption), V_ASN1_NULL, 0);
999         return 1;
1000     }
1001     /* Not supported */
1002     if (pad_mode != RSA_PKCS1_OAEP_PADDING)
1003         return 0;
1004     if (EVP_PKEY_CTX_get_rsa_oaep_md(pkctx, &md) <= 0)
1005         goto err;
1006     if (EVP_PKEY_CTX_get_rsa_mgf1_md(pkctx, &mgf1md) <= 0)
1007         goto err;
1008     labellen = EVP_PKEY_CTX_get0_rsa_oaep_label(pkctx, &label);
1009     if (labellen < 0)
1010         goto err;
1011     oaep = RSA_OAEP_PARAMS_new();
1012     if (oaep == NULL)
1013         goto err;
1014     if (!rsa_md_to_algor(&oaep->hashFunc, md))
1015         goto err;
1016     if (!rsa_md_to_mgf1(&oaep->maskGenFunc, mgf1md))
1017         goto err;
1018     if (labellen > 0) {
1019         ASN1_OCTET_STRING *los;
1020         oaep->pSourceFunc = X509_ALGOR_new();
1021         if (oaep->pSourceFunc == NULL)
1022             goto err;
1023         los = ASN1_OCTET_STRING_new();
1024         if (los == NULL)
1025             goto err;
1026         if (!ASN1_OCTET_STRING_set(los, label, labellen)) {
1027             ASN1_OCTET_STRING_free(los);
1028             goto err;
1029         }
1030         X509_ALGOR_set0(oaep->pSourceFunc, OBJ_nid2obj(NID_pSpecified),
1031                         V_ASN1_OCTET_STRING, los);
1032     }
1033     /* create string with pss parameter encoding. */
1034     if (!ASN1_item_pack(oaep, ASN1_ITEM_rptr(RSA_OAEP_PARAMS), &os))
1035          goto err;
1036     X509_ALGOR_set0(alg, OBJ_nid2obj(NID_rsaesOaep), V_ASN1_SEQUENCE, os);
1037     os = NULL;
1038     rv = 1;
1039  err:
1040     RSA_OAEP_PARAMS_free(oaep);
1041     ASN1_STRING_free(os);
1042     return rv;
1043 }
1044 #endif
1045
1046 static int rsa_pkey_check(const EVP_PKEY *pkey)
1047 {
1048     return RSA_check_key_ex(pkey->pkey.rsa, NULL);
1049 }
1050
1051 static size_t rsa_pkey_dirty_cnt(const EVP_PKEY *pkey)
1052 {
1053     return pkey->pkey.rsa->dirty_cnt;
1054 }
1055
1056 DEFINE_SPECIAL_STACK_OF_CONST(BIGNUM_const, BIGNUM)
1057
1058 static void *rsa_pkey_export_to(const EVP_PKEY *pk, EVP_KEYMGMT *keymgmt,
1059                                 int want_domainparams)
1060 {
1061     RSA *rsa = pk->pkey.rsa;
1062     OSSL_PARAM_BLD tmpl;
1063     const BIGNUM *n = RSA_get0_n(rsa), *e = RSA_get0_e(rsa);
1064     const BIGNUM *d = RSA_get0_d(rsa);
1065     STACK_OF(BIGNUM_const) *primes = NULL, *exps = NULL, *coeffs = NULL;
1066     int numprimes = 0, numexps = 0, numcoeffs = 0;
1067     OSSL_PARAM *params = NULL;
1068     void *provkey = NULL;
1069
1070     /*
1071      * There are no domain parameters for RSA keys, or rather, they are
1072      * included in the key data itself.
1073      */
1074     if (want_domainparams)
1075         goto err;
1076
1077     /* Get all the primes and CRT params */
1078     if ((primes = sk_BIGNUM_const_new_null()) == NULL
1079         || (exps = sk_BIGNUM_const_new_null()) == NULL
1080         || (coeffs = sk_BIGNUM_const_new_null()) == NULL)
1081         goto err;
1082
1083     if (!rsa_get0_all_params(rsa, primes, exps, coeffs))
1084         goto err;
1085
1086     /* Public parameters must always be present */
1087     if (n == NULL || e == NULL)
1088         goto err;
1089
1090     if (d != NULL) {
1091         /* It's a private key, so we should have everything else too */
1092         numprimes = sk_BIGNUM_const_num(primes);
1093         numexps = sk_BIGNUM_const_num(exps);
1094         numcoeffs = sk_BIGNUM_const_num(coeffs);
1095
1096         if (numprimes < 2 || numexps < 2 || numcoeffs < 1)
1097             goto err;
1098
1099         /*
1100          * assert that an OSSL_PARAM_BLD has enough space.
1101          * (the current 10 places doesn't have space for multi-primes)
1102          */
1103         if (!ossl_assert(/* n, e */ 2 + /* d */ 1 + /* numprimes */ 1
1104                          + numprimes + numexps + numcoeffs
1105                          <= OSSL_PARAM_BLD_MAX))
1106             goto err;
1107     }
1108
1109     ossl_param_bld_init(&tmpl);
1110     if (!ossl_param_bld_push_BN(&tmpl, OSSL_PKEY_PARAM_RSA_N, n)
1111         || !ossl_param_bld_push_BN(&tmpl, OSSL_PKEY_PARAM_RSA_E, e))
1112         goto err;
1113
1114     if (d != NULL) {
1115         int i;
1116
1117         if (!ossl_param_bld_push_BN(&tmpl, OSSL_PKEY_PARAM_RSA_D, d))
1118             goto err;
1119
1120         for (i = 0; i < numprimes; i++) {
1121             const BIGNUM *num = sk_BIGNUM_const_value(primes, i);
1122
1123             if (!ossl_param_bld_push_BN(&tmpl, OSSL_PKEY_PARAM_RSA_FACTOR,
1124                                         num))
1125                 goto err;
1126         }
1127
1128         for (i = 0; i < numexps; i++) {
1129             const BIGNUM *num = sk_BIGNUM_const_value(exps, i);
1130
1131             if (!ossl_param_bld_push_BN(&tmpl, OSSL_PKEY_PARAM_RSA_EXPONENT,
1132                                         num))
1133                 goto err;
1134         }
1135
1136         for (i = 0; i < numcoeffs; i++) {
1137             const BIGNUM *num = sk_BIGNUM_const_value(coeffs, i);
1138
1139             if (!ossl_param_bld_push_BN(&tmpl, OSSL_PKEY_PARAM_RSA_COEFFICIENT,
1140                                         num))
1141                 goto err;
1142         }
1143     }
1144
1145     if ((params = ossl_param_bld_to_param(&tmpl)) == NULL)
1146         goto err;
1147
1148     /* We export, the provider imports */
1149     provkey = evp_keymgmt_importkey(keymgmt, params);
1150
1151  err:
1152     sk_BIGNUM_const_free(primes);
1153     sk_BIGNUM_const_free(exps);
1154     sk_BIGNUM_const_free(coeffs);
1155     ossl_param_bld_free(params);
1156     return provkey;
1157 }
1158
1159 const EVP_PKEY_ASN1_METHOD rsa_asn1_meths[2] = {
1160     {
1161      EVP_PKEY_RSA,
1162      EVP_PKEY_RSA,
1163      ASN1_PKEY_SIGPARAM_NULL,
1164
1165      "RSA",
1166      "OpenSSL RSA method",
1167
1168      rsa_pub_decode,
1169      rsa_pub_encode,
1170      rsa_pub_cmp,
1171      rsa_pub_print,
1172
1173      rsa_priv_decode,
1174      rsa_priv_encode,
1175      rsa_priv_print,
1176
1177      int_rsa_size,
1178      rsa_bits,
1179      rsa_security_bits,
1180
1181      0, 0, 0, 0, 0, 0,
1182
1183      rsa_sig_print,
1184      int_rsa_free,
1185      rsa_pkey_ctrl,
1186      old_rsa_priv_decode,
1187      old_rsa_priv_encode,
1188      rsa_item_verify,
1189      rsa_item_sign,
1190      rsa_sig_info_set,
1191      rsa_pkey_check,
1192
1193      0, 0,
1194      0, 0, 0, 0,
1195
1196      rsa_pkey_dirty_cnt,
1197      rsa_pkey_export_to
1198     },
1199
1200     {
1201      EVP_PKEY_RSA2,
1202      EVP_PKEY_RSA,
1203      ASN1_PKEY_ALIAS}
1204 };
1205
1206 const EVP_PKEY_ASN1_METHOD rsa_pss_asn1_meth = {
1207      EVP_PKEY_RSA_PSS,
1208      EVP_PKEY_RSA_PSS,
1209      ASN1_PKEY_SIGPARAM_NULL,
1210
1211      "RSA-PSS",
1212      "OpenSSL RSA-PSS method",
1213
1214      rsa_pub_decode,
1215      rsa_pub_encode,
1216      rsa_pub_cmp,
1217      rsa_pub_print,
1218
1219      rsa_priv_decode,
1220      rsa_priv_encode,
1221      rsa_priv_print,
1222
1223      int_rsa_size,
1224      rsa_bits,
1225      rsa_security_bits,
1226
1227      0, 0, 0, 0, 0, 0,
1228
1229      rsa_sig_print,
1230      int_rsa_free,
1231      rsa_pkey_ctrl,
1232      0, 0,
1233      rsa_item_verify,
1234      rsa_item_sign,
1235      0,
1236      rsa_pkey_check,
1237
1238      0, 0,
1239      0, 0, 0, 0,
1240
1241      rsa_pkey_dirty_cnt,
1242      rsa_pkey_export_to
1243 };