c693ca7e212edacd97c2466c7119c2b1475326be
[openssl.git] / crypto / rsa / rsa_ameth.c
1 /*
2  * Copyright 2006-2020 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 /*
11  * RSA low level APIs are deprecated for public use, but still ok for
12  * internal use.
13  */
14 #include "internal/deprecated.h"
15
16 #include <stdio.h>
17 #include "internal/cryptlib.h"
18 #include <openssl/asn1t.h>
19 #include <openssl/x509.h>
20 #include <openssl/bn.h>
21 #include <openssl/core_names.h>
22 #include <openssl/param_build.h>
23 #include "crypto/asn1.h"
24 #include "crypto/evp.h"
25 #include "crypto/rsa.h"
26 #include "rsa_local.h"
27
28 static RSA_PSS_PARAMS *rsa_pss_decode(const X509_ALGOR *alg);
29 static int rsa_sync_to_pss_params_30(RSA *rsa);
30
31 /* Set any parameters associated with pkey */
32 static int rsa_param_encode(const EVP_PKEY *pkey,
33                             ASN1_STRING **pstr, int *pstrtype)
34 {
35     const RSA *rsa = pkey->pkey.rsa;
36
37     *pstr = NULL;
38     /* If RSA it's just NULL type */
39     if (RSA_test_flags(rsa, RSA_FLAG_TYPE_MASK) != RSA_FLAG_TYPE_RSASSAPSS) {
40         *pstrtype = V_ASN1_NULL;
41         return 1;
42     }
43     /* If no PSS parameters we omit parameters entirely */
44     if (rsa->pss == NULL) {
45         *pstrtype = V_ASN1_UNDEF;
46         return 1;
47     }
48     /* Encode PSS parameters */
49     if (ASN1_item_pack(rsa->pss, ASN1_ITEM_rptr(RSA_PSS_PARAMS), pstr) == NULL)
50         return 0;
51
52     *pstrtype = V_ASN1_SEQUENCE;
53     return 1;
54 }
55 /* Decode any parameters and set them in RSA structure */
56 static int rsa_param_decode(RSA *rsa, const X509_ALGOR *alg)
57 {
58     const ASN1_OBJECT *algoid;
59     const void *algp;
60     int algptype;
61
62     X509_ALGOR_get0(&algoid, &algptype, &algp, alg);
63     if (OBJ_obj2nid(algoid) != EVP_PKEY_RSA_PSS)
64         return 1;
65     if (algptype == V_ASN1_UNDEF)
66         return 1;
67     if (algptype != V_ASN1_SEQUENCE) {
68         RSAerr(RSA_F_RSA_PARAM_DECODE, RSA_R_INVALID_PSS_PARAMETERS);
69         return 0;
70     }
71     rsa->pss = rsa_pss_decode(alg);
72     if (rsa->pss == NULL)
73         return 0;
74     if (!rsa_sync_to_pss_params_30(rsa))
75         return 0;
76     return 1;
77 }
78
79 static int rsa_pub_encode(X509_PUBKEY *pk, const EVP_PKEY *pkey)
80 {
81     unsigned char *penc = NULL;
82     int penclen;
83     ASN1_STRING *str;
84     int strtype;
85
86     if (!rsa_param_encode(pkey, &str, &strtype))
87         return 0;
88     penclen = i2d_RSAPublicKey(pkey->pkey.rsa, &penc);
89     if (penclen <= 0)
90         return 0;
91     if (X509_PUBKEY_set0_param(pk, OBJ_nid2obj(pkey->ameth->pkey_id),
92                                strtype, str, penc, penclen))
93         return 1;
94
95     OPENSSL_free(penc);
96     return 0;
97 }
98
99 static int rsa_pub_decode(EVP_PKEY *pkey, const X509_PUBKEY *pubkey)
100 {
101     const unsigned char *p;
102     int pklen;
103     X509_ALGOR *alg;
104     RSA *rsa = NULL;
105
106     if (!X509_PUBKEY_get0_param(NULL, &p, &pklen, &alg, pubkey))
107         return 0;
108     if ((rsa = d2i_RSAPublicKey(NULL, &p, pklen)) == NULL)
109         return 0;
110     if (!rsa_param_decode(rsa, alg)) {
111         RSA_free(rsa);
112         return 0;
113     }
114
115     RSA_clear_flags(rsa, RSA_FLAG_TYPE_MASK);
116     switch (pkey->ameth->pkey_id) {
117     case EVP_PKEY_RSA:
118         RSA_set_flags(rsa, RSA_FLAG_TYPE_RSA);
119         break;
120     case EVP_PKEY_RSA_PSS:
121         RSA_set_flags(rsa, RSA_FLAG_TYPE_RSASSAPSS);
122         break;
123     default:
124         /* Leave the type bits zero */
125         break;
126     }
127
128     if (!EVP_PKEY_assign(pkey, pkey->ameth->pkey_id, rsa)) {
129         RSA_free(rsa);
130         return 0;
131     }
132     return 1;
133 }
134
135 static int rsa_pub_cmp(const EVP_PKEY *a, const EVP_PKEY *b)
136 {
137     /*
138      * Don't check the public/private key, this is mostly for smart
139      * cards.
140      */
141     if (((RSA_flags(a->pkey.rsa) & RSA_METHOD_FLAG_NO_CHECK))
142             || (RSA_flags(b->pkey.rsa) & RSA_METHOD_FLAG_NO_CHECK)) {
143         return 1;
144     }
145
146     if (BN_cmp(b->pkey.rsa->n, a->pkey.rsa->n) != 0
147         || BN_cmp(b->pkey.rsa->e, a->pkey.rsa->e) != 0)
148         return 0;
149     return 1;
150 }
151
152 static int old_rsa_priv_decode(EVP_PKEY *pkey,
153                                const unsigned char **pder, int derlen)
154 {
155     RSA *rsa;
156
157     if ((rsa = d2i_RSAPrivateKey(NULL, pder, derlen)) == NULL)
158         return 0;
159     EVP_PKEY_assign(pkey, pkey->ameth->pkey_id, rsa);
160     return 1;
161 }
162
163 static int old_rsa_priv_encode(const EVP_PKEY *pkey, unsigned char **pder)
164 {
165     return i2d_RSAPrivateKey(pkey->pkey.rsa, pder);
166 }
167
168 static int rsa_priv_encode(PKCS8_PRIV_KEY_INFO *p8, const EVP_PKEY *pkey)
169 {
170     unsigned char *rk = NULL;
171     int rklen;
172     ASN1_STRING *str;
173     int strtype;
174
175     if (!rsa_param_encode(pkey, &str, &strtype))
176         return 0;
177     rklen = i2d_RSAPrivateKey(pkey->pkey.rsa, &rk);
178
179     if (rklen <= 0) {
180         RSAerr(RSA_F_RSA_PRIV_ENCODE, ERR_R_MALLOC_FAILURE);
181         ASN1_STRING_free(str);
182         return 0;
183     }
184
185     if (!PKCS8_pkey_set0(p8, OBJ_nid2obj(pkey->ameth->pkey_id), 0,
186                          strtype, str, rk, rklen)) {
187         RSAerr(RSA_F_RSA_PRIV_ENCODE, ERR_R_MALLOC_FAILURE);
188         ASN1_STRING_free(str);
189         return 0;
190     }
191
192     return 1;
193 }
194
195 static int rsa_priv_decode(EVP_PKEY *pkey, const PKCS8_PRIV_KEY_INFO *p8)
196 {
197     const unsigned char *p;
198     RSA *rsa;
199     int pklen;
200     const X509_ALGOR *alg;
201
202     if (!PKCS8_pkey_get0(NULL, &p, &pklen, &alg, p8))
203         return 0;
204     rsa = d2i_RSAPrivateKey(NULL, &p, pklen);
205     if (rsa == NULL) {
206         RSAerr(RSA_F_RSA_PRIV_DECODE, ERR_R_RSA_LIB);
207         return 0;
208     }
209     if (!rsa_param_decode(rsa, alg)) {
210         RSA_free(rsa);
211         return 0;
212     }
213
214     RSA_clear_flags(rsa, RSA_FLAG_TYPE_MASK);
215     switch (pkey->ameth->pkey_id) {
216     case EVP_PKEY_RSA:
217         RSA_set_flags(rsa, RSA_FLAG_TYPE_RSA);
218         break;
219     case EVP_PKEY_RSA_PSS:
220         RSA_set_flags(rsa, RSA_FLAG_TYPE_RSASSAPSS);
221         break;
222     default:
223         /* Leave the type bits zero */
224         break;
225     }
226
227     EVP_PKEY_assign(pkey, pkey->ameth->pkey_id, rsa);
228     return 1;
229 }
230
231 static int int_rsa_size(const EVP_PKEY *pkey)
232 {
233     return RSA_size(pkey->pkey.rsa);
234 }
235
236 static int rsa_bits(const EVP_PKEY *pkey)
237 {
238     return BN_num_bits(pkey->pkey.rsa->n);
239 }
240
241 static int rsa_security_bits(const EVP_PKEY *pkey)
242 {
243     return RSA_security_bits(pkey->pkey.rsa);
244 }
245
246 static void int_rsa_free(EVP_PKEY *pkey)
247 {
248     RSA_free(pkey->pkey.rsa);
249 }
250
251 static int rsa_pss_param_print(BIO *bp, int pss_key, RSA_PSS_PARAMS *pss,
252                                int indent)
253 {
254     int rv = 0;
255     X509_ALGOR *maskHash = NULL;
256
257     if (!BIO_indent(bp, indent, 128))
258         goto err;
259     if (pss_key) {
260         if (pss == NULL) {
261             if (BIO_puts(bp, "No PSS parameter restrictions\n") <= 0)
262                 return 0;
263             return 1;
264         } else {
265             if (BIO_puts(bp, "PSS parameter restrictions:") <= 0)
266                 return 0;
267         }
268     } else if (pss == NULL) {
269         if (BIO_puts(bp,"(INVALID PSS PARAMETERS)\n") <= 0)
270             return 0;
271         return 1;
272     }
273     if (BIO_puts(bp, "\n") <= 0)
274         goto err;
275     if (pss_key)
276         indent += 2;
277     if (!BIO_indent(bp, indent, 128))
278         goto err;
279     if (BIO_puts(bp, "Hash Algorithm: ") <= 0)
280         goto err;
281
282     if (pss->hashAlgorithm) {
283         if (i2a_ASN1_OBJECT(bp, pss->hashAlgorithm->algorithm) <= 0)
284             goto err;
285     } else if (BIO_puts(bp, "sha1 (default)") <= 0) {
286         goto err;
287     }
288
289     if (BIO_puts(bp, "\n") <= 0)
290         goto err;
291
292     if (!BIO_indent(bp, indent, 128))
293         goto err;
294
295     if (BIO_puts(bp, "Mask Algorithm: ") <= 0)
296         goto err;
297     if (pss->maskGenAlgorithm) {
298         if (i2a_ASN1_OBJECT(bp, pss->maskGenAlgorithm->algorithm) <= 0)
299             goto err;
300         if (BIO_puts(bp, " with ") <= 0)
301             goto err;
302         maskHash = x509_algor_mgf1_decode(pss->maskGenAlgorithm);
303         if (maskHash != NULL) {
304             if (i2a_ASN1_OBJECT(bp, maskHash->algorithm) <= 0)
305                 goto err;
306         } else if (BIO_puts(bp, "INVALID") <= 0) {
307             goto err;
308         }
309     } else if (BIO_puts(bp, "mgf1 with sha1 (default)") <= 0) {
310         goto err;
311     }
312     BIO_puts(bp, "\n");
313
314     if (!BIO_indent(bp, indent, 128))
315         goto err;
316     if (BIO_printf(bp, "%s Salt Length: 0x", pss_key ? "Minimum" : "") <= 0)
317         goto err;
318     if (pss->saltLength) {
319         if (i2a_ASN1_INTEGER(bp, pss->saltLength) <= 0)
320             goto err;
321     } else if (BIO_puts(bp, "14 (default)") <= 0) {
322         goto err;
323     }
324     BIO_puts(bp, "\n");
325
326     if (!BIO_indent(bp, indent, 128))
327         goto err;
328     if (BIO_puts(bp, "Trailer Field: 0x") <= 0)
329         goto err;
330     if (pss->trailerField) {
331         if (i2a_ASN1_INTEGER(bp, pss->trailerField) <= 0)
332             goto err;
333     } else if (BIO_puts(bp, "BC (default)") <= 0) {
334         goto err;
335     }
336     BIO_puts(bp, "\n");
337
338     rv = 1;
339
340  err:
341     X509_ALGOR_free(maskHash);
342     return rv;
343
344 }
345
346 static int pkey_rsa_print(BIO *bp, const EVP_PKEY *pkey, int off, int priv)
347 {
348     const RSA *x = pkey->pkey.rsa;
349     char *str;
350     const char *s;
351     int ret = 0, mod_len = 0, ex_primes;
352
353     if (x->n != NULL)
354         mod_len = BN_num_bits(x->n);
355     ex_primes = sk_RSA_PRIME_INFO_num(x->prime_infos);
356
357     if (!BIO_indent(bp, off, 128))
358         goto err;
359
360     if (BIO_printf(bp, "%s ", pkey_is_pss(pkey) ?  "RSA-PSS" : "RSA") <= 0)
361         goto err;
362
363     if (priv && x->d) {
364         if (BIO_printf(bp, "Private-Key: (%d bit, %d primes)\n",
365                        mod_len, ex_primes <= 0 ? 2 : ex_primes + 2) <= 0)
366             goto err;
367         str = "modulus:";
368         s = "publicExponent:";
369     } else {
370         if (BIO_printf(bp, "Public-Key: (%d bit)\n", mod_len) <= 0)
371             goto err;
372         str = "Modulus:";
373         s = "Exponent:";
374     }
375     if (!ASN1_bn_print(bp, str, x->n, NULL, off))
376         goto err;
377     if (!ASN1_bn_print(bp, s, x->e, NULL, off))
378         goto err;
379     if (priv) {
380         int i;
381
382         if (!ASN1_bn_print(bp, "privateExponent:", x->d, NULL, off))
383             goto err;
384         if (!ASN1_bn_print(bp, "prime1:", x->p, NULL, off))
385             goto err;
386         if (!ASN1_bn_print(bp, "prime2:", x->q, NULL, off))
387             goto err;
388         if (!ASN1_bn_print(bp, "exponent1:", x->dmp1, NULL, off))
389             goto err;
390         if (!ASN1_bn_print(bp, "exponent2:", x->dmq1, NULL, off))
391             goto err;
392         if (!ASN1_bn_print(bp, "coefficient:", x->iqmp, NULL, off))
393             goto err;
394         for (i = 0; i < sk_RSA_PRIME_INFO_num(x->prime_infos); i++) {
395             /* print multi-prime info */
396             BIGNUM *bn = NULL;
397             RSA_PRIME_INFO *pinfo;
398             int j;
399
400             pinfo = sk_RSA_PRIME_INFO_value(x->prime_infos, i);
401             for (j = 0; j < 3; j++) {
402                 if (!BIO_indent(bp, off, 128))
403                     goto err;
404                 switch (j) {
405                 case 0:
406                     if (BIO_printf(bp, "prime%d:", i + 3) <= 0)
407                         goto err;
408                     bn = pinfo->r;
409                     break;
410                 case 1:
411                     if (BIO_printf(bp, "exponent%d:", i + 3) <= 0)
412                         goto err;
413                     bn = pinfo->d;
414                     break;
415                 case 2:
416                     if (BIO_printf(bp, "coefficient%d:", i + 3) <= 0)
417                         goto err;
418                     bn = pinfo->t;
419                     break;
420                 default:
421                     break;
422                 }
423                 if (!ASN1_bn_print(bp, "", bn, NULL, off))
424                     goto err;
425             }
426         }
427     }
428     if (pkey_is_pss(pkey) && !rsa_pss_param_print(bp, 1, x->pss, off))
429         goto err;
430     ret = 1;
431  err:
432     return ret;
433 }
434
435 static int rsa_pub_print(BIO *bp, const EVP_PKEY *pkey, int indent,
436                          ASN1_PCTX *ctx)
437 {
438     return pkey_rsa_print(bp, pkey, indent, 0);
439 }
440
441 static int rsa_priv_print(BIO *bp, const EVP_PKEY *pkey, int indent,
442                           ASN1_PCTX *ctx)
443 {
444     return pkey_rsa_print(bp, pkey, indent, 1);
445 }
446
447 static RSA_PSS_PARAMS *rsa_pss_decode(const X509_ALGOR *alg)
448 {
449     RSA_PSS_PARAMS *pss;
450
451     pss = ASN1_TYPE_unpack_sequence(ASN1_ITEM_rptr(RSA_PSS_PARAMS),
452                                     alg->parameter);
453
454     if (pss == NULL)
455         return NULL;
456
457     if (pss->maskGenAlgorithm != NULL) {
458         pss->maskHash = x509_algor_mgf1_decode(pss->maskGenAlgorithm);
459         if (pss->maskHash == NULL) {
460             RSA_PSS_PARAMS_free(pss);
461             return NULL;
462         }
463     }
464
465     return pss;
466 }
467
468 static int rsa_sig_print(BIO *bp, const X509_ALGOR *sigalg,
469                          const ASN1_STRING *sig, int indent, ASN1_PCTX *pctx)
470 {
471     if (OBJ_obj2nid(sigalg->algorithm) == EVP_PKEY_RSA_PSS) {
472         int rv;
473         RSA_PSS_PARAMS *pss = rsa_pss_decode(sigalg);
474
475         rv = rsa_pss_param_print(bp, 0, pss, indent);
476         RSA_PSS_PARAMS_free(pss);
477         if (!rv)
478             return 0;
479     } else if (BIO_puts(bp, "\n") <= 0) {
480         return 0;
481     }
482     if (sig)
483         return X509_signature_dump(bp, sig, indent);
484     return 1;
485 }
486
487 static int rsa_pkey_ctrl(EVP_PKEY *pkey, int op, long arg1, void *arg2)
488 {
489     X509_ALGOR *alg = NULL;
490     const EVP_MD *md;
491     const EVP_MD *mgf1md;
492     int min_saltlen;
493
494     switch (op) {
495
496     case ASN1_PKEY_CTRL_PKCS7_SIGN:
497         if (arg1 == 0)
498             PKCS7_SIGNER_INFO_get0_algs(arg2, NULL, NULL, &alg);
499         break;
500
501     case ASN1_PKEY_CTRL_PKCS7_ENCRYPT:
502         if (pkey_is_pss(pkey))
503             return -2;
504         if (arg1 == 0)
505             PKCS7_RECIP_INFO_get0_alg(arg2, &alg);
506         break;
507
508     case ASN1_PKEY_CTRL_DEFAULT_MD_NID:
509         if (pkey->pkey.rsa->pss != NULL) {
510             if (!rsa_pss_get_param(pkey->pkey.rsa->pss, &md, &mgf1md,
511                                    &min_saltlen)) {
512                 RSAerr(0, ERR_R_INTERNAL_ERROR);
513                 return 0;
514             }
515             *(int *)arg2 = EVP_MD_type(md);
516             /* Return of 2 indicates this MD is mandatory */
517             return 2;
518         }
519         *(int *)arg2 = NID_sha256;
520         return 1;
521
522     default:
523         return -2;
524
525     }
526
527     if (alg)
528         X509_ALGOR_set0(alg, OBJ_nid2obj(NID_rsaEncryption), V_ASN1_NULL, 0);
529
530     return 1;
531
532 }
533
534 /*
535  * Convert EVP_PKEY_CTX in PSS mode into corresponding algorithm parameter,
536  * suitable for setting an AlgorithmIdentifier.
537  */
538
539 static RSA_PSS_PARAMS *rsa_ctx_to_pss(EVP_PKEY_CTX *pkctx)
540 {
541     const EVP_MD *sigmd, *mgf1md;
542     EVP_PKEY *pk = EVP_PKEY_CTX_get0_pkey(pkctx);
543     int saltlen;
544
545     if (EVP_PKEY_CTX_get_signature_md(pkctx, &sigmd) <= 0)
546         return NULL;
547     if (EVP_PKEY_CTX_get_rsa_mgf1_md(pkctx, &mgf1md) <= 0)
548         return NULL;
549     if (!EVP_PKEY_CTX_get_rsa_pss_saltlen(pkctx, &saltlen))
550         return NULL;
551     if (saltlen == -1) {
552         saltlen = EVP_MD_size(sigmd);
553     } else if (saltlen == -2 || saltlen == -3) {
554         saltlen = EVP_PKEY_size(pk) - EVP_MD_size(sigmd) - 2;
555         if ((EVP_PKEY_bits(pk) & 0x7) == 1)
556             saltlen--;
557         if (saltlen < 0)
558             return NULL;
559     }
560
561     return rsa_pss_params_create(sigmd, mgf1md, saltlen);
562 }
563
564 RSA_PSS_PARAMS *rsa_pss_params_create(const EVP_MD *sigmd,
565                                       const EVP_MD *mgf1md, int saltlen)
566 {
567     RSA_PSS_PARAMS *pss = RSA_PSS_PARAMS_new();
568
569     if (pss == NULL)
570         goto err;
571     if (saltlen != 20) {
572         pss->saltLength = ASN1_INTEGER_new();
573         if (pss->saltLength == NULL)
574             goto err;
575         if (!ASN1_INTEGER_set(pss->saltLength, saltlen))
576             goto err;
577     }
578     if (!x509_algor_new_from_md(&pss->hashAlgorithm, sigmd))
579         goto err;
580     if (mgf1md == NULL)
581         mgf1md = sigmd;
582     if (!x509_algor_md_to_mgf1(&pss->maskGenAlgorithm, mgf1md))
583         goto err;
584     if (!x509_algor_new_from_md(&pss->maskHash, mgf1md))
585         goto err;
586     return pss;
587  err:
588     RSA_PSS_PARAMS_free(pss);
589     return NULL;
590 }
591
592 ASN1_STRING *ossl_rsa_ctx_to_pss_string(EVP_PKEY_CTX *pkctx)
593 {
594     RSA_PSS_PARAMS *pss = rsa_ctx_to_pss(pkctx);
595     ASN1_STRING *os;
596
597     if (pss == NULL)
598         return NULL;
599
600     os = ASN1_item_pack(pss, ASN1_ITEM_rptr(RSA_PSS_PARAMS), NULL);
601     RSA_PSS_PARAMS_free(pss);
602     return os;
603 }
604
605 /*
606  * From PSS AlgorithmIdentifier set public key parameters. If pkey isn't NULL
607  * then the EVP_MD_CTX is setup and initialised. If it is NULL parameters are
608  * passed to pkctx instead.
609  */
610
611 int ossl_rsa_pss_to_ctx(EVP_MD_CTX *ctx, EVP_PKEY_CTX *pkctx,
612                         const X509_ALGOR *sigalg, EVP_PKEY *pkey)
613 {
614     int rv = -1;
615     int saltlen;
616     const EVP_MD *mgf1md = NULL, *md = NULL;
617     RSA_PSS_PARAMS *pss;
618
619     /* Sanity check: make sure it is PSS */
620     if (OBJ_obj2nid(sigalg->algorithm) != EVP_PKEY_RSA_PSS) {
621         RSAerr(0, RSA_R_UNSUPPORTED_SIGNATURE_TYPE);
622         return -1;
623     }
624     /* Decode PSS parameters */
625     pss = rsa_pss_decode(sigalg);
626
627     if (!rsa_pss_get_param(pss, &md, &mgf1md, &saltlen)) {
628         RSAerr(0, RSA_R_INVALID_PSS_PARAMETERS);
629         goto err;
630     }
631
632     /* We have all parameters now set up context */
633     if (pkey) {
634         if (!EVP_DigestVerifyInit(ctx, &pkctx, md, NULL, pkey))
635             goto err;
636     } else {
637         const EVP_MD *checkmd;
638         if (EVP_PKEY_CTX_get_signature_md(pkctx, &checkmd) <= 0)
639             goto err;
640         if (EVP_MD_type(md) != EVP_MD_type(checkmd)) {
641             RSAerr(0, RSA_R_DIGEST_DOES_NOT_MATCH);
642             goto err;
643         }
644     }
645
646     if (EVP_PKEY_CTX_set_rsa_padding(pkctx, RSA_PKCS1_PSS_PADDING) <= 0)
647         goto err;
648
649     if (EVP_PKEY_CTX_set_rsa_pss_saltlen(pkctx, saltlen) <= 0)
650         goto err;
651
652     if (EVP_PKEY_CTX_set_rsa_mgf1_md(pkctx, mgf1md) <= 0)
653         goto err;
654     /* Carry on */
655     rv = 1;
656
657  err:
658     RSA_PSS_PARAMS_free(pss);
659     return rv;
660 }
661
662 static int rsa_pss_verify_param(const EVP_MD **pmd, const EVP_MD **pmgf1md,
663                                 int *psaltlen, int *ptrailerField)
664 {
665     if (psaltlen != NULL && *psaltlen < 0) {
666         ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_SALT_LENGTH);
667         return 0;
668     }
669     /*
670      * low-level routines support only trailer field 0xbc (value 1) and
671      * PKCS#1 says we should reject any other value anyway.
672      */
673     if (ptrailerField != NULL && *ptrailerField != 1) {
674         ERR_raise(ERR_LIB_RSA, RSA_R_INVALID_TRAILER);
675         return 0;
676     }
677     return 1;
678 }
679
680 static int rsa_pss_get_param_unverified(const RSA_PSS_PARAMS *pss,
681                                         const EVP_MD **pmd,
682                                         const EVP_MD **pmgf1md,
683                                         int *psaltlen, int *ptrailerField)
684 {
685     RSA_PSS_PARAMS_30 pss_params;
686
687     /* Get the defaults from the ONE place */
688     (void)ossl_rsa_pss_params_30_set_defaults(&pss_params);
689
690     if (pss == NULL)
691         return 0;
692     *pmd = x509_algor_get_md(pss->hashAlgorithm);
693     if (*pmd == NULL)
694         return 0;
695     *pmgf1md = x509_algor_get_md(pss->maskHash);
696     if (*pmgf1md == NULL)
697         return 0;
698     if (pss->saltLength)
699         *psaltlen = ASN1_INTEGER_get(pss->saltLength);
700     else
701         *psaltlen = ossl_rsa_pss_params_30_saltlen(&pss_params);
702     if (pss->trailerField)
703         *ptrailerField = ASN1_INTEGER_get(pss->trailerField);
704     else
705         *ptrailerField = ossl_rsa_pss_params_30_trailerfield(&pss_params);;
706
707     return 1;
708 }
709
710 int rsa_pss_get_param(const RSA_PSS_PARAMS *pss, const EVP_MD **pmd,
711                       const EVP_MD **pmgf1md, int *psaltlen)
712 {
713     /*
714      * Callers do not care about the trailer field, and yet, we must
715      * pass it from get_param to verify_param, since the latter checks
716      * its value.
717      *
718      * When callers start caring, it's a simple thing to add another
719      * argument to this function.
720      */
721     int trailerField = 0;
722
723     return rsa_pss_get_param_unverified(pss, pmd, pmgf1md, psaltlen,
724                                         &trailerField)
725         && rsa_pss_verify_param(pmd, pmgf1md, psaltlen, &trailerField);
726 }
727
728 static int rsa_sync_to_pss_params_30(RSA *rsa)
729 {
730     if (rsa != NULL && rsa->pss != NULL) {
731         const EVP_MD *md = NULL, *mgf1md = NULL;
732         int md_nid, mgf1md_nid, saltlen, trailerField;
733         RSA_PSS_PARAMS_30 pss_params;
734
735         /*
736          * We don't care about the validity of the fields here, we just
737          * want to synchronise values.  Verifying here makes it impossible
738          * to even read a key with invalid values, making it hard to test
739          * a bad situation.
740          *
741          * Other routines use rsa_pss_get_param(), so the values will be
742          * checked, eventually.
743          */
744         if (!rsa_pss_get_param_unverified(rsa->pss, &md, &mgf1md,
745                                           &saltlen, &trailerField))
746             return 0;
747         md_nid = EVP_MD_type(md);
748         mgf1md_nid = EVP_MD_type(mgf1md);
749         if (!ossl_rsa_pss_params_30_set_defaults(&pss_params)
750             || !ossl_rsa_pss_params_30_set_hashalg(&pss_params, md_nid)
751             || !ossl_rsa_pss_params_30_set_maskgenhashalg(&pss_params,
752                                                           mgf1md_nid)
753             || !ossl_rsa_pss_params_30_set_saltlen(&pss_params, saltlen)
754             || !ossl_rsa_pss_params_30_set_trailerfield(&pss_params,
755                                                         trailerField))
756             return 0;
757         rsa->pss_params = pss_params;
758     }
759     return 1;
760 }
761
762 /*
763  * Customised RSA item verification routine. This is called when a signature
764  * is encountered requiring special handling. We currently only handle PSS.
765  */
766
767 static int rsa_item_verify(EVP_MD_CTX *ctx, const ASN1_ITEM *it,
768                            const void *asn, const X509_ALGOR *sigalg,
769                            const ASN1_BIT_STRING *sig, EVP_PKEY *pkey)
770 {
771     /* Sanity check: make sure it is PSS */
772     if (OBJ_obj2nid(sigalg->algorithm) != EVP_PKEY_RSA_PSS) {
773         RSAerr(RSA_F_RSA_ITEM_VERIFY, RSA_R_UNSUPPORTED_SIGNATURE_TYPE);
774         return -1;
775     }
776     if (ossl_rsa_pss_to_ctx(ctx, NULL, sigalg, pkey) > 0) {
777         /* Carry on */
778         return 2;
779     }
780     return -1;
781 }
782
783 static int rsa_item_sign(EVP_MD_CTX *ctx, const ASN1_ITEM *it, const void *asn,
784                          X509_ALGOR *alg1, X509_ALGOR *alg2,
785                          ASN1_BIT_STRING *sig)
786 {
787     int pad_mode;
788     EVP_PKEY_CTX *pkctx = EVP_MD_CTX_pkey_ctx(ctx);
789
790     if (EVP_PKEY_CTX_get_rsa_padding(pkctx, &pad_mode) <= 0)
791         return 0;
792     if (pad_mode == RSA_PKCS1_PADDING)
793         return 2;
794     if (pad_mode == RSA_PKCS1_PSS_PADDING) {
795         ASN1_STRING *os1 = NULL;
796         os1 = ossl_rsa_ctx_to_pss_string(pkctx);
797         if (!os1)
798             return 0;
799         /* Duplicate parameters if we have to */
800         if (alg2) {
801             ASN1_STRING *os2 = ASN1_STRING_dup(os1);
802             if (!os2) {
803                 ASN1_STRING_free(os1);
804                 return 0;
805             }
806             X509_ALGOR_set0(alg2, OBJ_nid2obj(EVP_PKEY_RSA_PSS),
807                             V_ASN1_SEQUENCE, os2);
808         }
809         X509_ALGOR_set0(alg1, OBJ_nid2obj(EVP_PKEY_RSA_PSS),
810                         V_ASN1_SEQUENCE, os1);
811         return 3;
812     }
813     return 2;
814 }
815
816 static int rsa_sig_info_set(X509_SIG_INFO *siginf, const X509_ALGOR *sigalg,
817                             const ASN1_STRING *sig)
818 {
819     int rv = 0;
820     int mdnid, saltlen;
821     uint32_t flags;
822     const EVP_MD *mgf1md = NULL, *md = NULL;
823     RSA_PSS_PARAMS *pss;
824     int secbits;
825
826     /* Sanity check: make sure it is PSS */
827     if (OBJ_obj2nid(sigalg->algorithm) != EVP_PKEY_RSA_PSS)
828         return 0;
829     /* Decode PSS parameters */
830     pss = rsa_pss_decode(sigalg);
831     if (!rsa_pss_get_param(pss, &md, &mgf1md, &saltlen))
832         goto err;
833     mdnid = EVP_MD_type(md);
834     /*
835      * For TLS need SHA256, SHA384 or SHA512, digest and MGF1 digest must
836      * match and salt length must equal digest size
837      */
838     if ((mdnid == NID_sha256 || mdnid == NID_sha384 || mdnid == NID_sha512)
839             && mdnid == EVP_MD_type(mgf1md) && saltlen == EVP_MD_size(md))
840         flags = X509_SIG_INFO_TLS;
841     else
842         flags = 0;
843     /* Note: security bits half number of digest bits */
844     secbits = EVP_MD_size(md) * 4;
845     /*
846      * SHA1 and MD5 are known to be broken. Reduce security bits so that
847      * they're no longer accepted at security level 1. The real values don't
848      * really matter as long as they're lower than 80, which is our security
849      * level 1.
850      * https://eprint.iacr.org/2020/014 puts a chosen-prefix attack for SHA1 at
851      * 2^63.4
852      * https://documents.epfl.ch/users/l/le/lenstra/public/papers/lat.pdf
853      * puts a chosen-prefix attack for MD5 at 2^39.
854      */
855     if (mdnid == NID_sha1)
856         secbits = 64;
857     else if (mdnid == NID_md5_sha1)
858         secbits = 68;
859     else if (mdnid == NID_md5)
860         secbits = 39;
861     X509_SIG_INFO_set(siginf, mdnid, EVP_PKEY_RSA_PSS, secbits,
862                       flags);
863     rv = 1;
864     err:
865     RSA_PSS_PARAMS_free(pss);
866     return rv;
867 }
868
869 static int rsa_pkey_check(const EVP_PKEY *pkey)
870 {
871     return RSA_check_key_ex(pkey->pkey.rsa, NULL);
872 }
873
874 static size_t rsa_pkey_dirty_cnt(const EVP_PKEY *pkey)
875 {
876     return pkey->pkey.rsa->dirty_cnt;
877 }
878
879 /*
880  * For the moment, we trust the call path, where keys going through
881  * rsa_pkey_export_to() match a KEYMGMT for the "RSA" keytype, while
882  * keys going through rsa_pss_pkey_export_to() match a KEYMGMT for the
883  * "RSA-PSS" keytype.
884  * TODO(3.0) Investigate whether we should simply continue to trust the
885  * call path, or if we should strengthen this function by checking that
886  * |rsa_type| matches the RSA key subtype.  The latter requires ensuring
887  * that the type flag for the RSA key is properly set by other functions
888  * in this file.
889  */
890 static int rsa_int_export_to(const EVP_PKEY *from, int rsa_type,
891                              void *to_keydata, EVP_KEYMGMT *to_keymgmt,
892                              OPENSSL_CTX *libctx, const char *propq)
893 {
894     RSA *rsa = from->pkey.rsa;
895     OSSL_PARAM_BLD *tmpl = OSSL_PARAM_BLD_new();
896     OSSL_PARAM *params = NULL;
897     int selection = 0;
898     int rv = 0;
899
900     if (tmpl == NULL)
901         return 0;
902     /*
903      * If the RSA method is foreign, then we can't be sure of anything, and
904      * can therefore not export or pretend to export.
905      */
906     if (RSA_get_method(rsa) != RSA_PKCS1_OpenSSL())
907         goto err;
908
909     /* Public parameters must always be present */
910     if (RSA_get0_n(rsa) == NULL || RSA_get0_e(rsa) == NULL)
911         goto err;
912
913     if (!ossl_rsa_todata(rsa, tmpl, NULL))
914         goto err;
915
916     selection |= OSSL_KEYMGMT_SELECT_PUBLIC_KEY;
917     if (RSA_get0_d(rsa) != NULL)
918         selection |= OSSL_KEYMGMT_SELECT_PRIVATE_KEY;
919
920     if (rsa->pss != NULL) {
921         const EVP_MD *md = NULL, *mgf1md = NULL;
922         int md_nid, mgf1md_nid, saltlen, trailerfield;
923         RSA_PSS_PARAMS_30 pss_params;
924
925         if (!rsa_pss_get_param_unverified(rsa->pss, &md, &mgf1md,
926                                           &saltlen, &trailerfield))
927             goto err;
928         md_nid = EVP_MD_type(md);
929         mgf1md_nid = EVP_MD_type(mgf1md);
930         if (!ossl_rsa_pss_params_30_set_defaults(&pss_params)
931             || !ossl_rsa_pss_params_30_set_hashalg(&pss_params, md_nid)
932             || !ossl_rsa_pss_params_30_set_maskgenhashalg(&pss_params,
933                                                           mgf1md_nid)
934             || !ossl_rsa_pss_params_30_set_saltlen(&pss_params, saltlen)
935             || !ossl_rsa_pss_params_30_todata(&pss_params, tmpl, NULL))
936             goto err;
937         selection |= OSSL_KEYMGMT_SELECT_OTHER_PARAMETERS;
938     }
939
940     if ((params = OSSL_PARAM_BLD_to_param(tmpl)) == NULL)
941         goto err;
942
943     /* We export, the provider imports */
944     rv = evp_keymgmt_import(to_keymgmt, to_keydata, selection, params);
945
946  err:
947     OSSL_PARAM_BLD_free_params(params);
948     OSSL_PARAM_BLD_free(tmpl);
949     return rv;
950 }
951
952 static int rsa_int_import_from(const OSSL_PARAM params[], void *vpctx,
953                                int rsa_type)
954 {
955     EVP_PKEY_CTX *pctx = vpctx;
956     EVP_PKEY *pkey = EVP_PKEY_CTX_get0_pkey(pctx);
957     RSA *rsa = ossl_rsa_new_with_ctx(pctx->libctx);
958     RSA_PSS_PARAMS_30 rsa_pss_params = { 0, };
959     int ok = 0;
960
961     if (rsa == NULL) {
962         ERR_raise(ERR_LIB_DH, ERR_R_MALLOC_FAILURE);
963         return 0;
964     }
965
966     RSA_clear_flags(rsa, RSA_FLAG_TYPE_MASK);
967     RSA_set_flags(rsa, rsa_type);
968
969     if (!ossl_rsa_pss_params_30_fromdata(&rsa_pss_params, params, pctx->libctx))
970         goto err;
971
972     switch (rsa_type) {
973     case RSA_FLAG_TYPE_RSA:
974         /*
975          * Were PSS parameters filled in?
976          * In that case, something's wrong
977          */
978         if (!ossl_rsa_pss_params_30_is_unrestricted(&rsa_pss_params))
979             goto err;
980         break;
981     case RSA_FLAG_TYPE_RSASSAPSS:
982         /*
983          * Were PSS parameters filled in?  In that case, create the old
984          * RSA_PSS_PARAMS structure.  Otherwise, this is an unrestricted key.
985          */
986         if (!ossl_rsa_pss_params_30_is_unrestricted(&rsa_pss_params)) {
987             /* Create the older RSA_PSS_PARAMS from RSA_PSS_PARAMS_30 data */
988             int mdnid = ossl_rsa_pss_params_30_hashalg(&rsa_pss_params);
989             int mgf1mdnid = ossl_rsa_pss_params_30_maskgenhashalg(&rsa_pss_params);
990             int saltlen = ossl_rsa_pss_params_30_saltlen(&rsa_pss_params);
991             const EVP_MD *md = EVP_get_digestbynid(mdnid);
992             const EVP_MD *mgf1md = EVP_get_digestbynid(mgf1mdnid);
993
994             if ((rsa->pss = rsa_pss_params_create(md, mgf1md, saltlen)) == NULL)
995                 goto err;
996         }
997         break;
998     default:
999         /* RSA key sub-types we don't know how to handle yet */
1000         goto err;
1001     }
1002
1003     if (!ossl_rsa_fromdata(rsa, params))
1004         goto err;
1005
1006     switch (rsa_type) {
1007     case RSA_FLAG_TYPE_RSA:
1008         ok = EVP_PKEY_assign_RSA(pkey, rsa);
1009         break;
1010     case RSA_FLAG_TYPE_RSASSAPSS:
1011         ok = EVP_PKEY_assign(pkey, EVP_PKEY_RSA_PSS, rsa);
1012         break;
1013     }
1014
1015  err:
1016     if (!ok)
1017         RSA_free(rsa);
1018     return ok;
1019 }
1020
1021 static int rsa_pkey_export_to(const EVP_PKEY *from, void *to_keydata,
1022                               EVP_KEYMGMT *to_keymgmt, OPENSSL_CTX *libctx,
1023                               const char *propq)
1024 {
1025     return rsa_int_export_to(from, RSA_FLAG_TYPE_RSA, to_keydata,
1026                              to_keymgmt, libctx, propq);
1027 }
1028
1029 static int rsa_pss_pkey_export_to(const EVP_PKEY *from, void *to_keydata,
1030                                   EVP_KEYMGMT *to_keymgmt, OPENSSL_CTX *libctx,
1031                                   const char *propq)
1032 {
1033     return rsa_int_export_to(from, RSA_FLAG_TYPE_RSASSAPSS, to_keydata,
1034                              to_keymgmt, libctx, propq);
1035 }
1036
1037 static int rsa_pkey_import_from(const OSSL_PARAM params[], void *vpctx)
1038 {
1039     return rsa_int_import_from(params, vpctx, RSA_FLAG_TYPE_RSA);
1040 }
1041
1042 static int rsa_pss_pkey_import_from(const OSSL_PARAM params[], void *vpctx)
1043 {
1044     return rsa_int_import_from(params, vpctx, RSA_FLAG_TYPE_RSASSAPSS);
1045 }
1046
1047 const EVP_PKEY_ASN1_METHOD rsa_asn1_meths[2] = {
1048     {
1049      EVP_PKEY_RSA,
1050      EVP_PKEY_RSA,
1051      ASN1_PKEY_SIGPARAM_NULL,
1052
1053      "RSA",
1054      "OpenSSL RSA method",
1055
1056      rsa_pub_decode,
1057      rsa_pub_encode,
1058      rsa_pub_cmp,
1059      rsa_pub_print,
1060
1061      rsa_priv_decode,
1062      rsa_priv_encode,
1063      rsa_priv_print,
1064
1065      int_rsa_size,
1066      rsa_bits,
1067      rsa_security_bits,
1068
1069      0, 0, 0, 0, 0, 0,
1070
1071      rsa_sig_print,
1072      int_rsa_free,
1073      rsa_pkey_ctrl,
1074      old_rsa_priv_decode,
1075      old_rsa_priv_encode,
1076      rsa_item_verify,
1077      rsa_item_sign,
1078      rsa_sig_info_set,
1079      rsa_pkey_check,
1080
1081      0, 0,
1082      0, 0, 0, 0,
1083
1084      rsa_pkey_dirty_cnt,
1085      rsa_pkey_export_to,
1086      rsa_pkey_import_from
1087     },
1088
1089     {
1090      EVP_PKEY_RSA2,
1091      EVP_PKEY_RSA,
1092      ASN1_PKEY_ALIAS}
1093 };
1094
1095 const EVP_PKEY_ASN1_METHOD rsa_pss_asn1_meth = {
1096      EVP_PKEY_RSA_PSS,
1097      EVP_PKEY_RSA_PSS,
1098      ASN1_PKEY_SIGPARAM_NULL,
1099
1100      "RSA-PSS",
1101      "OpenSSL RSA-PSS method",
1102
1103      rsa_pub_decode,
1104      rsa_pub_encode,
1105      rsa_pub_cmp,
1106      rsa_pub_print,
1107
1108      rsa_priv_decode,
1109      rsa_priv_encode,
1110      rsa_priv_print,
1111
1112      int_rsa_size,
1113      rsa_bits,
1114      rsa_security_bits,
1115
1116      0, 0, 0, 0, 0, 0,
1117
1118      rsa_sig_print,
1119      int_rsa_free,
1120      rsa_pkey_ctrl,
1121      0, 0,
1122      rsa_item_verify,
1123      rsa_item_sign,
1124      0,
1125      rsa_pkey_check,
1126
1127      0, 0,
1128      0, 0, 0, 0,
1129
1130      rsa_pkey_dirty_cnt,
1131      rsa_pss_pkey_export_to,
1132      rsa_pss_pkey_import_from
1133 };