Rename some occurrences of 'library_context' and 'lib_ctx' to 'libctx'
[openssl.git] / providers / implementations / encode_decode / encode_key2any.c
1 /*
2  * Copyright 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  * Low level APIs are deprecated for public use, but still ok for internal use.
12  */
13 #include "internal/deprecated.h"
14
15 #include <openssl/core.h>
16 #include <openssl/core_dispatch.h>
17 #include <openssl/core_names.h>
18 #include <openssl/crypto.h>
19 #include <openssl/params.h>
20 #include <openssl/asn1.h>
21 #include <openssl/err.h>
22 #include <openssl/pem.h>
23 #include <openssl/x509.h>
24 #include <openssl/pkcs12.h>      /* PKCS8_encrypt() */
25 #include <openssl/dh.h>
26 #include <openssl/dsa.h>
27 #include <openssl/ec.h>
28 #include "internal/passphrase.h"
29 #include "internal/cryptlib.h"
30 #include "crypto/ecx.h"
31 #include "crypto/rsa.h"
32 #include "prov/implementations.h"
33 #include "prov/providercommonerr.h"
34 #include "prov/bio.h"
35 #include "prov/provider_ctx.h"
36 #include "prov/der_rsa.h"
37 #include "endecoder_local.h"
38
39 struct key2any_ctx_st {
40     PROV_CTX *provctx;
41
42     /* Set to 1 if intending to encrypt/decrypt, otherwise 0 */
43     int cipher_intent;
44
45     EVP_CIPHER *cipher;
46
47     struct ossl_passphrase_data_st pwdata;
48 };
49
50 typedef int check_key_type_fn(const void *key, int nid);
51 typedef int key_to_paramstring_fn(const void *key, int nid,
52                                   void **str, int *strtype);
53 typedef int key_to_der_fn(BIO *out, const void *key, int key_nid,
54                           key_to_paramstring_fn *p2s, i2d_of_void *k2d,
55                           struct key2any_ctx_st *ctx);
56 typedef int write_bio_of_void_fn(BIO *bp, const void *x);
57
58 static PKCS8_PRIV_KEY_INFO *key_to_p8info(const void *key, int key_nid,
59                                           void *params, int params_type,
60                                           i2d_of_void *k2d)
61 {
62     /* der, derlen store the key DER output and its length */
63     unsigned char *der = NULL;
64     int derlen;
65     /* The final PKCS#8 info */
66     PKCS8_PRIV_KEY_INFO *p8info = NULL;
67
68
69     if ((p8info = PKCS8_PRIV_KEY_INFO_new()) == NULL
70         || (derlen = k2d(key, &der)) <= 0
71         || !PKCS8_pkey_set0(p8info, OBJ_nid2obj(key_nid), 0,
72                             params_type, params, der, derlen)) {
73         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
74         PKCS8_PRIV_KEY_INFO_free(p8info);
75         OPENSSL_free(der);
76         p8info = NULL;
77     }
78
79     return p8info;
80 }
81
82 static X509_SIG *p8info_to_encp8(PKCS8_PRIV_KEY_INFO *p8info,
83                                  struct key2any_ctx_st *ctx)
84 {
85     X509_SIG *p8 = NULL;
86     char kstr[PEM_BUFSIZE];
87     size_t klen = 0;
88
89     if (ctx->cipher == NULL)
90         return NULL;
91
92     if (!ossl_pw_get_passphrase(kstr, sizeof(kstr), &klen, NULL, 1,
93                                 &ctx->pwdata)) {
94         ERR_raise(ERR_LIB_PROV, PROV_R_READ_KEY);
95         return NULL;
96     }
97     /* First argument == -1 means "standard" */
98     p8 = PKCS8_encrypt(-1, ctx->cipher, kstr, klen, NULL, 0, 0, p8info);
99     OPENSSL_cleanse(kstr, klen);
100     return p8;
101 }
102
103 static X509_SIG *key_to_encp8(const void *key, int key_nid,
104                               void *params, int params_type,
105                               i2d_of_void *k2d, struct key2any_ctx_st *ctx)
106 {
107     PKCS8_PRIV_KEY_INFO *p8info =
108         key_to_p8info(key, key_nid, params, params_type, k2d);
109     X509_SIG *p8 = p8info_to_encp8(p8info, ctx);
110
111     PKCS8_PRIV_KEY_INFO_free(p8info);
112     return p8;
113 }
114
115 static X509_PUBKEY *key_to_pubkey(const void *key, int key_nid,
116                                   void *params, int params_type,
117                                   i2d_of_void k2d)
118 {
119     /* der, derlen store the key DER output and its length */
120     unsigned char *der = NULL;
121     int derlen;
122     /* The final X509_PUBKEY */
123     X509_PUBKEY *xpk = NULL;
124
125
126     if ((xpk = X509_PUBKEY_new()) == NULL
127         || (derlen = k2d(key, &der)) <= 0
128         || !X509_PUBKEY_set0_param(xpk, OBJ_nid2obj(key_nid),
129                                    params_type, params, der, derlen)) {
130         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
131         X509_PUBKEY_free(xpk);
132         OPENSSL_free(der);
133         xpk = NULL;
134     }
135
136     return xpk;
137 }
138
139 static int key_to_der_pkcs8_bio(BIO *out, const void *key, int key_nid,
140                                 key_to_paramstring_fn *p2s, i2d_of_void *k2d,
141                                 struct key2any_ctx_st *ctx)
142 {
143     int ret = 0;
144     void *str = NULL;
145     int strtype = V_ASN1_UNDEF;
146
147     if (p2s != NULL && !p2s(key, key_nid, &str, &strtype))
148         return 0;
149
150     if (ctx->cipher_intent) {
151         X509_SIG *p8 = key_to_encp8(key, key_nid, str, strtype, k2d, ctx);
152
153         if (p8 != NULL)
154             ret = i2d_PKCS8_bio(out, p8);
155
156         X509_SIG_free(p8);
157     } else {
158         PKCS8_PRIV_KEY_INFO *p8info =
159             key_to_p8info(key, key_nid, str, strtype, k2d);
160
161         if (p8info != NULL)
162             ret = i2d_PKCS8_PRIV_KEY_INFO_bio(out, p8info);
163
164         PKCS8_PRIV_KEY_INFO_free(p8info);
165     }
166
167     return ret;
168 }
169
170 static int key_to_pem_pkcs8_bio(BIO *out, const void *key, int key_nid,
171                                 key_to_paramstring_fn *p2s, i2d_of_void *k2d,
172                                 struct key2any_ctx_st *ctx)
173 {
174     int ret = 0;
175     void *str = NULL;
176     int strtype = V_ASN1_UNDEF;
177
178     if (p2s != NULL && !p2s(key, key_nid, &str, &strtype))
179         return 0;
180
181     if (ctx->cipher_intent) {
182         X509_SIG *p8 = key_to_encp8(key, key_nid, str, strtype, k2d, ctx);
183
184         if (p8 != NULL)
185             ret = PEM_write_bio_PKCS8(out, p8);
186
187         X509_SIG_free(p8);
188     } else {
189         PKCS8_PRIV_KEY_INFO *p8info =
190             key_to_p8info(key, key_nid, str, strtype, k2d);
191
192         if (p8info != NULL)
193             ret = PEM_write_bio_PKCS8_PRIV_KEY_INFO(out, p8info);
194
195         PKCS8_PRIV_KEY_INFO_free(p8info);
196     }
197
198     return ret;
199 }
200
201 static int key_to_der_pubkey_bio(BIO *out, const void *key, int key_nid,
202                                  key_to_paramstring_fn *p2s, i2d_of_void *k2d,
203                                  struct key2any_ctx_st *ctx)
204 {
205     int ret = 0;
206     void *str = NULL;
207     int strtype = V_ASN1_UNDEF;
208     X509_PUBKEY *xpk = NULL;
209
210     if (p2s != NULL && !p2s(key, key_nid, &str, &strtype))
211         return 0;
212
213     xpk = key_to_pubkey(key, key_nid, str, strtype, k2d);
214
215     if (xpk != NULL)
216         ret = i2d_X509_PUBKEY_bio(out, xpk);
217
218     /* Also frees |str| */
219     X509_PUBKEY_free(xpk);
220     return ret;
221 }
222
223 static int key_to_pem_pubkey_bio(BIO *out, const void *key, int key_nid,
224                                  key_to_paramstring_fn *p2s, i2d_of_void *k2d,
225                                  struct key2any_ctx_st *ctx)
226 {
227     int ret = 0;
228     void *str = NULL;
229     int strtype = V_ASN1_UNDEF;
230     X509_PUBKEY *xpk = NULL;
231
232     if (p2s != NULL && !p2s(key, key_nid, &str, &strtype))
233         return 0;
234
235     xpk = key_to_pubkey(key, key_nid, str, strtype, k2d);
236
237     if (xpk != NULL)
238         ret = PEM_write_bio_X509_PUBKEY(out, xpk);
239
240     /* Also frees |str| */
241     X509_PUBKEY_free(xpk);
242     return ret;
243 }
244
245 #define der_output_type         "DER"
246 #define pem_output_type         "PEM"
247
248 /* ---------------------------------------------------------------------- */
249
250 #ifndef OPENSSL_NO_DH
251 static int prepare_dh_params(const void *dh, int nid,
252                              void **pstr, int *pstrtype)
253 {
254     ASN1_STRING *params = ASN1_STRING_new();
255
256     if (params == NULL) {
257         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
258         return 0;
259     }
260
261     if (nid == EVP_PKEY_DHX)
262         params->length = i2d_DHxparams(dh, &params->data);
263     else
264         params->length = i2d_DHparams(dh, &params->data);
265
266     if (params->length <= 0) {
267         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
268         ASN1_STRING_free(params);
269         return 0;
270     }
271     params->type = V_ASN1_SEQUENCE;
272
273     *pstr = params;
274     *pstrtype = V_ASN1_SEQUENCE;
275     return 1;
276 }
277
278 static int dh_pub_to_der(const void *dh, unsigned char **pder)
279 {
280     const BIGNUM *bn = NULL;
281     ASN1_INTEGER *pub_key = NULL;
282     int ret;
283
284     if ((bn = DH_get0_pub_key(dh)) == NULL) {
285         ERR_raise(ERR_LIB_PROV, PROV_R_NOT_A_PUBLIC_KEY);
286         return 0;
287     }
288     if ((pub_key = BN_to_ASN1_INTEGER(bn, NULL)) == NULL) {
289         ERR_raise(ERR_LIB_PROV, PROV_R_BN_ERROR);
290         return 0;
291     }
292
293     ret = i2d_ASN1_INTEGER(pub_key, pder);
294
295     ASN1_STRING_clear_free(pub_key);
296     return ret;
297 }
298
299 static int dh_priv_to_der(const void *dh, unsigned char **pder)
300 {
301     const BIGNUM *bn = NULL;
302     ASN1_INTEGER *priv_key = NULL;
303     int ret;
304
305     if ((bn = DH_get0_priv_key(dh)) == NULL) {
306         ERR_raise(ERR_LIB_PROV, PROV_R_NOT_A_PRIVATE_KEY);
307         return 0;
308     }
309     if ((priv_key = BN_to_ASN1_INTEGER(bn, NULL)) == NULL) {
310         ERR_raise(ERR_LIB_PROV, PROV_R_BN_ERROR);
311         return 0;
312     }
313
314     ret = i2d_ASN1_INTEGER(priv_key, pder);
315
316     ASN1_STRING_clear_free(priv_key);
317     return ret;
318 }
319
320 static int dh_params_to_der_bio(BIO *out, const void *key)
321 {
322     int type =
323         DH_test_flags(key, DH_FLAG_TYPE_DHX) ? EVP_PKEY_DHX : EVP_PKEY_DH;
324
325     if (type == EVP_PKEY_DH)
326         return i2d_DHparams_bio(out, key);
327     return i2d_DHxparams_bio(out, key);
328 }
329
330 static int dh_params_to_pem_bio(BIO *out, const void *key)
331 {
332     int type =
333         DH_test_flags(key, DH_FLAG_TYPE_DHX) ? EVP_PKEY_DHX : EVP_PKEY_DH;
334
335     if (type == EVP_PKEY_DH)
336         return PEM_write_bio_DHparams(out, key);
337
338     return PEM_write_bio_DHxparams(out, key);
339 }
340
341 static int dh_check_key_type(const void *key, int expected_type)
342 {
343     int type =
344         DH_test_flags(key, DH_FLAG_TYPE_DHX) ? EVP_PKEY_DHX : EVP_PKEY_DH;
345
346     return type == expected_type;
347 }
348
349 # define dh_evp_type            EVP_PKEY_DH
350 # define dhx_evp_type           EVP_PKEY_DHX
351 # define dh_input_type          "DH"
352 # define dhx_input_type         "DHX"
353 #endif
354
355 /* ---------------------------------------------------------------------- */
356
357 #ifndef OPENSSL_NO_DSA
358 static int prepare_some_dsa_params(const void *dsa, int nid,
359                                    void **pstr, int *pstrtype)
360 {
361     ASN1_STRING *params = ASN1_STRING_new();
362
363     if (params == NULL) {
364         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
365         return 0;
366     }
367
368     params->length = i2d_DSAparams(dsa, &params->data);
369
370     if (params->length <= 0) {
371         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
372         ASN1_STRING_free(params);
373         return 0;
374     }
375
376     *pstrtype = V_ASN1_SEQUENCE;
377     *pstr = params;
378     return 1;
379 }
380
381 static int prepare_all_dsa_params(const void *dsa, int nid,
382                                   void **pstr, int *pstrtype)
383 {
384     const BIGNUM *p = DSA_get0_p(dsa);
385     const BIGNUM *q = DSA_get0_q(dsa);
386     const BIGNUM *g = DSA_get0_g(dsa);
387
388     if (p != NULL && q != NULL && g != NULL)
389         return prepare_some_dsa_params(dsa, nid, pstr, pstrtype);
390
391     *pstr = NULL;
392     *pstrtype = V_ASN1_UNDEF;
393     return 1;
394 }
395
396 static int prepare_dsa_params(const void *dsa, int nid,
397                               void **pstr, int *pstrtype)
398 {
399     /*
400      * TODO(v3.0) implement setting save_parameters, see dsa_pub_encode()
401      * in crypto/dsa/dsa_ameth.c
402      */
403     int save_parameters = 1;
404
405     return save_parameters
406         ?  prepare_all_dsa_params(dsa, nid, pstr, pstrtype)
407         :  prepare_some_dsa_params(dsa, nid, pstr, pstrtype);
408 }
409
410 static int dsa_pub_to_der(const void *dsa, unsigned char **pder)
411 {
412     const BIGNUM *bn = NULL;
413     ASN1_INTEGER *pub_key = NULL;
414     int ret;
415
416     if ((bn = DSA_get0_pub_key(dsa)) == NULL) {
417         ERR_raise(ERR_LIB_PROV, PROV_R_NOT_A_PUBLIC_KEY);
418         return 0;
419     }
420     if ((pub_key = BN_to_ASN1_INTEGER(bn, NULL)) == NULL) {
421         ERR_raise(ERR_LIB_PROV, PROV_R_BN_ERROR);
422         return 0;
423     }
424
425     ret = i2d_ASN1_INTEGER(pub_key, pder);
426
427     ASN1_STRING_clear_free(pub_key);
428     return ret;
429 }
430
431 static int dsa_priv_to_der(const void *dsa, unsigned char **pder)
432 {
433     const BIGNUM *bn = NULL;
434     ASN1_INTEGER *priv_key = NULL;
435     int ret;
436
437     if ((bn = DSA_get0_priv_key(dsa)) == NULL) {
438         ERR_raise(ERR_LIB_PROV, PROV_R_NOT_A_PRIVATE_KEY);
439         return 0;
440     }
441     if ((priv_key = BN_to_ASN1_INTEGER(bn, NULL)) == NULL) {
442         ERR_raise(ERR_LIB_PROV, PROV_R_BN_ERROR);
443         return 0;
444     }
445
446     ret = i2d_ASN1_INTEGER(priv_key, pder);
447
448     ASN1_STRING_clear_free(priv_key);
449     return ret;
450 }
451
452 static int dsa_params_to_der_bio(BIO *out, const void *key)
453 {
454     return i2d_DSAparams_bio(out, key);
455 }
456
457 static int dsa_params_to_pem_bio(BIO *out, const void *key)
458 {
459     return PEM_write_bio_DSAparams(out, key);
460 }
461
462 # define dsa_check_key_type     NULL
463 # define dsa_evp_type           EVP_PKEY_DSA
464 # define dsa_input_type         "DSA"
465 #endif
466
467 /* ---------------------------------------------------------------------- */
468
469 #ifndef OPENSSL_NO_EC
470 static int prepare_ec_explicit_params(const void *eckey,
471                                       void **pstr, int *pstrtype)
472 {
473     ASN1_STRING *params = ASN1_STRING_new();
474
475     if (params == NULL) {
476         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
477         return 0;
478     }
479
480     params->length = i2d_ECParameters(eckey, &params->data);
481     if (params->length <= 0) {
482         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
483         ASN1_STRING_free(params);
484         return 0;
485     }
486
487     *pstrtype = V_ASN1_SEQUENCE;
488     *pstr = params;
489     return 1;
490 }
491
492 static int prepare_ec_params(const void *eckey, int nid,
493                              void **pstr, int *pstrtype)
494 {
495     int curve_nid;
496     const EC_GROUP *group = EC_KEY_get0_group(eckey);
497     ASN1_OBJECT *params = NULL;
498
499     if (group == NULL)
500         return 0;
501     curve_nid = EC_GROUP_get_curve_name(group);
502     if (curve_nid != NID_undef) {
503         params = OBJ_nid2obj(curve_nid);
504         if (params == NULL)
505             return 0;
506     }
507
508     if (curve_nid != NID_undef
509         && (EC_GROUP_get_asn1_flag(group) & OPENSSL_EC_NAMED_CURVE)) {
510         if (OBJ_length(params) == 0) {
511             /* Some curves might not have an associated OID */
512             ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_OID);
513             ASN1_OBJECT_free(params);
514             return 0;
515         }
516         *pstr = params;
517         *pstrtype = V_ASN1_OBJECT;
518         return 1;
519     } else {
520         return prepare_ec_explicit_params(eckey, pstr, pstrtype);
521     }
522 }
523
524 static int ec_params_to_der_bio(BIO *out, const void *eckey)
525 {
526     return i2d_ECPKParameters_bio(out, EC_KEY_get0_group(eckey));
527 }
528
529 static int ec_params_to_pem_bio(BIO *out, const void *eckey)
530 {
531     return PEM_write_bio_ECPKParameters(out, EC_KEY_get0_group(eckey));
532 }
533
534 static int ec_pub_to_der(const void *eckey, unsigned char **pder)
535 {
536     return i2o_ECPublicKey(eckey, pder);
537 }
538
539 static int ec_priv_to_der(const void *veckey, unsigned char **pder)
540 {
541     EC_KEY *eckey = (EC_KEY *)veckey;
542     unsigned int old_flags;
543     int ret = 0;
544
545     /*
546      * For PKCS8 the curve name appears in the PKCS8_PRIV_KEY_INFO object
547      * as the pkeyalg->parameter field. (For a named curve this is an OID)
548      * The pkey field is an octet string that holds the encoded
549      * ECPrivateKey SEQUENCE with the optional parameters field omitted.
550      * We omit this by setting the EC_PKEY_NO_PARAMETERS flag.
551      */
552     old_flags = EC_KEY_get_enc_flags(eckey); /* save old flags */
553     EC_KEY_set_enc_flags(eckey, old_flags | EC_PKEY_NO_PARAMETERS);
554     ret = i2d_ECPrivateKey(eckey, pder);
555     EC_KEY_set_enc_flags(eckey, old_flags); /* restore old flags */
556     return ret; /* return the length of the der encoded data */
557 }
558
559 # define ec_check_key_type      NULL
560 # define ec_evp_type            EVP_PKEY_EC
561 # define ec_input_type          "EC"
562 #endif
563
564 /* ---------------------------------------------------------------------- */
565
566 #ifndef OPENSSL_NO_EC
567 # define prepare_ecx_params NULL
568
569 static int ecx_pub_to_der(const void *vecxkey, unsigned char **pder)
570 {
571     const ECX_KEY *ecxkey = vecxkey;
572     unsigned char *keyblob;
573
574     if (ecxkey == NULL) {
575         ERR_raise(ERR_LIB_PROV, ERR_R_PASSED_NULL_PARAMETER);
576         return 0;
577     }
578
579     keyblob = OPENSSL_memdup(ecxkey->pubkey, ecxkey->keylen);
580     if (keyblob == NULL) {
581         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
582         return 0;
583     }
584
585     *pder = keyblob;
586     return ecxkey->keylen;
587 }
588
589 static int ecx_priv_to_der(const void *vecxkey, unsigned char **pder)
590 {
591     const ECX_KEY *ecxkey = vecxkey;
592     ASN1_OCTET_STRING oct;
593     int keybloblen;
594
595     if (ecxkey == NULL || ecxkey->privkey == NULL) {
596         ERR_raise(ERR_LIB_PROV, ERR_R_PASSED_NULL_PARAMETER);
597         return 0;
598     }
599
600     oct.data = ecxkey->privkey;
601     oct.length = ecxkey->keylen;
602     oct.flags = 0;
603
604     keybloblen = i2d_ASN1_OCTET_STRING(&oct, pder);
605     if (keybloblen < 0) {
606         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
607         return 0;
608     }
609
610     return keybloblen;
611 }
612
613 # define ecx_params_to_der_bio  NULL
614 # define ecx_params_to_pem_bio  NULL
615 # define ecx_check_key_type     NULL
616
617 # define ed25519_evp_type       EVP_PKEY_ED25519
618 # define ed448_evp_type         EVP_PKEY_ED448
619 # define x25519_evp_type        EVP_PKEY_X25519
620 # define x448_evp_type          EVP_PKEY_X448
621 # define ed25519_input_type     "ED25519"
622 # define ed448_input_type       "ED448"
623 # define x25519_input_type      "X25519"
624 # define x448_input_type        "X448"
625 #endif
626
627 /* ---------------------------------------------------------------------- */
628
629 /*
630  * Helper functions to prepare RSA-PSS params for encoding.  We would
631  * have simply written the whole AlgorithmIdentifier, but existing libcrypto
632  * functionality doesn't allow that.
633  */
634
635 static int prepare_rsa_params(const void *rsa, int nid,
636                               void **pstr, int *pstrtype)
637 {
638     const RSA_PSS_PARAMS_30 *pss = ossl_rsa_get0_pss_params_30((RSA *)rsa);
639
640     *pstr = NULL;
641
642     switch (RSA_test_flags(rsa, RSA_FLAG_TYPE_MASK)) {
643     case RSA_FLAG_TYPE_RSA:
644         /* If plain RSA, the parameters shall be NULL */
645         *pstrtype = V_ASN1_NULL;
646         return 1;
647     case RSA_FLAG_TYPE_RSASSAPSS:
648         if (ossl_rsa_pss_params_30_is_unrestricted(pss)) {
649             *pstrtype = V_ASN1_UNDEF;
650             return 1;
651         } else {
652             ASN1_STRING *astr = NULL;
653             WPACKET pkt;
654             unsigned char *str = NULL;
655             size_t str_sz = 0;
656             int i;
657
658             for (i = 0; i < 2; i++) {
659                 switch (i) {
660                 case 0:
661                     if (!WPACKET_init_null_der(&pkt))
662                         goto err;
663                     break;
664                 case 1:
665                     if ((str = OPENSSL_malloc(str_sz)) == NULL
666                         || !WPACKET_init_der(&pkt, str, str_sz)) {
667                         goto err;
668                     }
669                     break;
670                 }
671                 if (!ossl_DER_w_RSASSA_PSS_params(&pkt, -1, pss)
672                     || !WPACKET_finish(&pkt)
673                     || !WPACKET_get_total_written(&pkt, &str_sz))
674                     goto err;
675                 WPACKET_cleanup(&pkt);
676
677                 /*
678                  * If no PSS parameters are going to be written, there's no
679                  * point going for another iteration.
680                  * This saves us from getting |str| allocated just to have it
681                  * immediately de-allocated.
682                  */
683                 if (str_sz == 0)
684                     break;
685             }
686
687             if ((astr = ASN1_STRING_new()) == NULL)
688                 goto err;
689             *pstrtype = V_ASN1_SEQUENCE;
690             ASN1_STRING_set0(astr, str, (int)str_sz);
691             *pstr = astr;
692
693             return 1;
694          err:
695             OPENSSL_free(str);
696             return 0;
697         }
698     }
699
700     /* Currently unsupported RSA key type */
701     return 0;
702 }
703
704 #define rsa_params_to_der_bio   NULL
705 #define rsa_params_to_pem_bio   NULL
706 #define rsa_priv_to_der         (i2d_of_void *)i2d_RSAPrivateKey
707 #define rsa_pub_to_der          (i2d_of_void *)i2d_RSAPublicKey
708
709 static int rsa_check_key_type(const void *rsa, int expected_type)
710 {
711     switch (RSA_test_flags(rsa, RSA_FLAG_TYPE_MASK)) {
712     case RSA_FLAG_TYPE_RSA:
713         return expected_type == EVP_PKEY_RSA;
714     case RSA_FLAG_TYPE_RSASSAPSS:
715         return expected_type == EVP_PKEY_RSA_PSS;
716     }
717
718     /* Currently unsupported RSA key type */
719     return EVP_PKEY_NONE;
720 }
721
722 #define rsa_evp_type            EVP_PKEY_RSA
723 #define rsapss_evp_type         EVP_PKEY_RSA_PSS
724 #define rsa_input_type          "RSA"
725 #define rsapss_input_type       "RSA-PSS"
726
727 /* ---------------------------------------------------------------------- */
728
729 static OSSL_FUNC_decoder_newctx_fn key2any_newctx;
730 static OSSL_FUNC_decoder_freectx_fn key2any_freectx;
731 static OSSL_FUNC_decoder_gettable_params_fn key2any_gettable_params;
732
733 static void *key2any_newctx(void *provctx)
734 {
735     struct key2any_ctx_st *ctx = OPENSSL_zalloc(sizeof(*ctx));
736
737     if (ctx != NULL)
738         ctx->provctx = provctx;
739
740     return ctx;
741 }
742
743 static void key2any_freectx(void *vctx)
744 {
745     struct key2any_ctx_st *ctx = vctx;
746
747     ossl_pw_clear_passphrase_data(&ctx->pwdata);
748     EVP_CIPHER_free(ctx->cipher);
749     OPENSSL_free(ctx);
750 }
751
752 static const OSSL_PARAM *key2any_gettable_params(void *provctx)
753 {
754     static const OSSL_PARAM gettables[] = {
755         { OSSL_ENCODER_PARAM_OUTPUT_TYPE, OSSL_PARAM_UTF8_PTR, NULL, 0, 0 },
756         OSSL_PARAM_END,
757     };
758
759     return gettables;
760 }
761
762 static int key2any_get_params(OSSL_PARAM params[], const char *input_type,
763                               const char *output_type)
764 {
765     OSSL_PARAM *p;
766
767     p = OSSL_PARAM_locate(params, OSSL_ENCODER_PARAM_INPUT_TYPE);
768     if (p != NULL && !OSSL_PARAM_set_utf8_ptr(p, input_type))
769         return 0;
770
771     p = OSSL_PARAM_locate(params, OSSL_ENCODER_PARAM_OUTPUT_TYPE);
772     if (p != NULL && !OSSL_PARAM_set_utf8_ptr(p, output_type))
773         return 0;
774
775     return 1;
776 }
777
778 static const OSSL_PARAM *key2any_settable_ctx_params(ossl_unused void *provctx)
779 {
780     static const OSSL_PARAM settables[] = {
781         OSSL_PARAM_utf8_string(OSSL_ENCODER_PARAM_CIPHER, NULL, 0),
782         OSSL_PARAM_utf8_string(OSSL_ENCODER_PARAM_PROPERTIES, NULL, 0),
783         OSSL_PARAM_END,
784     };
785
786     return settables;
787 }
788
789 static int key2any_set_ctx_params(void *vctx, const OSSL_PARAM params[])
790 {
791     struct key2any_ctx_st *ctx = vctx;
792     OSSL_LIB_CTX *libctx = ossl_prov_ctx_get0_libctx(ctx->provctx);
793     const OSSL_PARAM *cipherp =
794         OSSL_PARAM_locate_const(params, OSSL_ENCODER_PARAM_CIPHER);
795     const OSSL_PARAM *propsp =
796         OSSL_PARAM_locate_const(params, OSSL_ENCODER_PARAM_PROPERTIES);
797
798     if (cipherp != NULL) {
799         const char *ciphername = NULL;
800         const char *props = NULL;
801
802         if (!OSSL_PARAM_get_utf8_string_ptr(cipherp, &ciphername))
803             return 0;
804         if (propsp != NULL && !OSSL_PARAM_get_utf8_string_ptr(propsp, &props))
805             return 0;
806
807         EVP_CIPHER_free(ctx->cipher);
808         ctx->cipher_intent = ciphername != NULL;
809         if (ciphername != NULL
810             && ((ctx->cipher =
811                  EVP_CIPHER_fetch(libctx, ciphername, props)) == NULL))
812             return 0;
813     }
814     return 1;
815 }
816
817 static int key2any_encode(struct key2any_ctx_st *ctx, OSSL_CORE_BIO *cout,
818                           const void *key, int type,
819                           check_key_type_fn *checker,
820                           key_to_der_fn *writer,
821                           OSSL_PASSPHRASE_CALLBACK *cb, void *cbarg,
822                           key_to_paramstring_fn *key2paramstring,
823                           i2d_of_void *key2der)
824 {
825     int ret = 0;
826
827     if (key == NULL) {
828         ERR_raise(ERR_LIB_PROV, ERR_R_PASSED_NULL_PARAMETER);
829     } else if (checker == NULL || checker(key, type)) {
830         BIO *out = bio_new_from_core_bio(ctx->provctx, cout);
831
832         if (out != NULL
833             && writer != NULL
834             && ossl_pw_set_ossl_passphrase_cb(&ctx->pwdata, cb, cbarg))
835             ret = writer(out, key, type, key2paramstring, key2der, ctx);
836
837         BIO_free(out);
838     } else {
839         ERR_raise(ERR_LIB_PROV, ERR_R_PASSED_INVALID_ARGUMENT);
840     }
841     return ret;
842 }
843
844 static int key2any_encode_params(struct key2any_ctx_st *ctx,
845                                  OSSL_CORE_BIO *cout,
846                                  const void *key, int type,
847                                  check_key_type_fn *checker,
848                                  write_bio_of_void_fn *writer)
849 {
850     int ret = 0;
851
852     if (key == NULL) {
853         ERR_raise(ERR_LIB_PROV, ERR_R_PASSED_NULL_PARAMETER);
854     } else if (checker == NULL || checker(key, type)) {
855         BIO *out = bio_new_from_core_bio(ctx->provctx, cout);
856
857         if (out != NULL && writer != NULL)
858             ret = writer(out, key);
859
860         BIO_free(out);
861     } else {
862         ERR_raise(ERR_LIB_PROV, ERR_R_PASSED_INVALID_ARGUMENT);
863     }
864
865     return ret;
866 }
867
868 #define MAKE_ENCODER(impl, type, evp_type, output)                          \
869     static OSSL_FUNC_encoder_get_params_fn                                  \
870     impl##2##output##_get_params;                                           \
871     static OSSL_FUNC_encoder_import_object_fn                               \
872     impl##2##output##_import_object;                                        \
873     static OSSL_FUNC_encoder_free_object_fn                                 \
874     impl##2##output##_free_object;                                          \
875     static OSSL_FUNC_encoder_encode_fn impl##2##output##_encode;            \
876                                                                             \
877     static int impl##2##output##_get_params(OSSL_PARAM params[])            \
878     {                                                                       \
879         return key2any_get_params(params, impl##_input_type,                \
880                                   output##_output_type);                    \
881     }                                                                       \
882     static void *                                                           \
883     impl##2##output##_import_object(void *vctx, int selection,              \
884                                     const OSSL_PARAM params[])              \
885     {                                                                       \
886         struct key2any_ctx_st *ctx = vctx;                                  \
887         return ossl_prov_import_key(ossl_##impl##_keymgmt_functions,        \
888                                     ctx->provctx, selection, params);       \
889     }                                                                       \
890     static void impl##2##output##_free_object(void *key)                    \
891     {                                                                       \
892         ossl_prov_free_key(ossl_##impl##_keymgmt_functions, key);           \
893     }                                                                       \
894     static int                                                              \
895     impl##2##output##_encode(void *ctx, OSSL_CORE_BIO *cout,                \
896                              const void *key,                               \
897                              const OSSL_PARAM key_abstract[],               \
898                              int selection,                                 \
899                              OSSL_PASSPHRASE_CALLBACK *cb, void *cbarg)     \
900     {                                                                       \
901         /* We don't deal with abstract objects */                           \
902         if (key_abstract != NULL) {                                         \
903             ERR_raise(ERR_LIB_PROV, ERR_R_PASSED_INVALID_ARGUMENT);         \
904             return 0;                                                       \
905         }                                                                   \
906         if ((selection & OSSL_KEYMGMT_SELECT_PRIVATE_KEY) != 0)             \
907             return key2any_encode(ctx, cout, key, impl##_evp_type,          \
908                                   type##_check_key_type,                    \
909                                   key_to_##output##_pkcs8_bio,              \
910                                   cb, cbarg,                                \
911                                   prepare_##type##_params,                  \
912                                   type##_priv_to_der);                      \
913         if ((selection & OSSL_KEYMGMT_SELECT_PUBLIC_KEY) != 0)              \
914             return key2any_encode(ctx, cout, key, impl##_evp_type,          \
915                                   type##_check_key_type,                    \
916                                   key_to_##output##_pubkey_bio,             \
917                                   cb, cbarg,                                \
918                                   prepare_##type##_params,                  \
919                                   type##_pub_to_der);                       \
920         if ((selection & OSSL_KEYMGMT_SELECT_ALL_PARAMETERS) != 0)          \
921             return key2any_encode_params(ctx, cout, key,                    \
922                                          impl##_evp_type,                   \
923                                          type##_check_key_type,             \
924                                          type##_params_to_##output##_bio);  \
925                                                                             \
926         ERR_raise(ERR_LIB_PROV, ERR_R_PASSED_INVALID_ARGUMENT);             \
927         return 0;                                                           \
928     }                                                                       \
929     const OSSL_DISPATCH ossl_##impl##_to_##output##_encoder_functions[] = { \
930         { OSSL_FUNC_ENCODER_NEWCTX,                                         \
931           (void (*)(void))key2any_newctx },                                 \
932         { OSSL_FUNC_ENCODER_FREECTX,                                        \
933           (void (*)(void))key2any_freectx },                                \
934         { OSSL_FUNC_ENCODER_GETTABLE_PARAMS,                                \
935           (void (*)(void))key2any_gettable_params },                        \
936         { OSSL_FUNC_ENCODER_GET_PARAMS,                                     \
937           (void (*)(void))impl##2##output##_get_params },                   \
938         { OSSL_FUNC_ENCODER_SETTABLE_CTX_PARAMS,                            \
939           (void (*)(void))key2any_settable_ctx_params },                    \
940         { OSSL_FUNC_ENCODER_SET_CTX_PARAMS,                                 \
941           (void (*)(void))key2any_set_ctx_params },                         \
942         { OSSL_FUNC_ENCODER_IMPORT_OBJECT,                                  \
943           (void (*)(void))impl##2##output##_import_object },                \
944         { OSSL_FUNC_ENCODER_FREE_OBJECT,                                    \
945           (void (*)(void))impl##2##output##_free_object },                  \
946         { OSSL_FUNC_ENCODER_ENCODE,                                         \
947           (void (*)(void))impl##2##output##_encode },                       \
948         { 0, NULL }                                                         \
949     }
950
951 #ifndef OPENSSL_NO_DH
952 MAKE_ENCODER(dh, dh, EVP_PKEY_DH, der);
953 MAKE_ENCODER(dh, dh, EVP_PKEY_DH, pem);
954 MAKE_ENCODER(dhx, dh, EVP_PKEY_DHX, der);
955 MAKE_ENCODER(dhx, dh, EVP_PKEY_DHX, pem);
956 #endif
957 #ifndef OPENSSL_NO_DSA
958 MAKE_ENCODER(dsa, dsa, EVP_PKEY_DSA, der);
959 MAKE_ENCODER(dsa, dsa, EVP_PKEY_DSA, pem);
960 #endif
961 #ifndef OPENSSL_NO_EC
962 MAKE_ENCODER(ec, ec, EVP_PKEY_EC, der);
963 MAKE_ENCODER(ec, ec, EVP_PKEY_EC, pem);
964 MAKE_ENCODER(ed25519, ecx, EVP_PKEY_ED25519, der);
965 MAKE_ENCODER(ed25519, ecx, EVP_PKEY_ED25519, pem);
966 MAKE_ENCODER(ed448, ecx, EVP_PKEY_ED448, der);
967 MAKE_ENCODER(ed448, ecx, EVP_PKEY_ED448, pem);
968 MAKE_ENCODER(x25519, ecx, EVP_PKEY_X25519, der);
969 MAKE_ENCODER(x25519, ecx, EVP_PKEY_X25519, pem);
970 MAKE_ENCODER(x448, ecx, EVP_PKEY_ED448, der);
971 MAKE_ENCODER(x448, ecx, EVP_PKEY_ED448, pem);
972 #endif
973 MAKE_ENCODER(rsa, rsa, EVP_PKEY_RSA, der);
974 MAKE_ENCODER(rsa, rsa, EVP_PKEY_RSA, pem);
975 MAKE_ENCODER(rsapss, rsa, EVP_PKEY_RSA, der);
976 MAKE_ENCODER(rsapss, rsa, EVP_PKEY_RSA, pem);