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