ENCODER: Refactor our provider encoder implementations
[openssl.git] / providers / implementations / encode_decode / decode_der2key.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
12  * internal use.
13  */
14 #include "internal/deprecated.h"
15
16 #include <openssl/core_dispatch.h>
17 #include <openssl/core_names.h>
18 #include <openssl/core_object.h>
19 #include <openssl/crypto.h>
20 #include <openssl/err.h>
21 #include <openssl/params.h>
22 #include <openssl/pem.h>         /* PEM_BUFSIZE and public PEM functions */
23 #include <openssl/pkcs12.h>
24 #include <openssl/x509.h>
25 #include "internal/cryptlib.h"   /* ossl_assert() */
26 #include "internal/asn1.h"
27 #include "crypto/ecx.h"
28 #include "prov/bio.h"
29 #include "prov/implementations.h"
30 #include "prov/providercommonerr.h"
31 #include "endecoder_local.h"
32
33 static int read_der(PROV_CTX *provctx, OSSL_CORE_BIO *cin,
34                     unsigned char **data, long *len)
35 {
36     BUF_MEM *mem = NULL;
37     BIO *in = bio_new_from_core_bio(provctx, cin);
38     int ok = (asn1_d2i_read_bio(in, &mem) >= 0);
39
40     if (ok) {
41         *data = (unsigned char *)mem->data;
42         *len = (long)mem->length;
43         OPENSSL_free(mem);
44     }
45     BIO_free(in);
46     return ok;
47 }
48
49 static int der_from_p8(unsigned char **new_der, long *new_der_len,
50                        unsigned char *input_der, long input_der_len,
51                        OSSL_PASSPHRASE_CALLBACK *pw_cb, void *pw_cbarg)
52 {
53     const unsigned char *derp;
54     X509_SIG *p8 = NULL;
55     int ok = 0;
56
57     if (!ossl_assert(new_der != NULL && *new_der == NULL)
58         || !ossl_assert(new_der_len != NULL))
59         return 0;
60
61     derp = input_der;
62     if ((p8 = d2i_X509_SIG(NULL, &derp, input_der_len)) != NULL) {
63         char pbuf[PEM_BUFSIZE];
64         size_t plen = 0;
65
66         if (!pw_cb(pbuf, sizeof(pbuf), &plen, NULL, pw_cbarg)) {
67             ERR_raise(ERR_LIB_PROV, PROV_R_READ_KEY);
68         } else {
69             const X509_ALGOR *alg = NULL;
70             const ASN1_OCTET_STRING *oct = NULL;
71             int len = 0;
72
73             X509_SIG_get0(p8, &alg, &oct);
74             if (PKCS12_pbe_crypt(alg, pbuf, plen, oct->data, oct->length,
75                                  new_der, &len, 0) != NULL)
76                 ok = 1;
77             *new_der_len = len;
78         }
79     }
80     X509_SIG_free(p8);
81     return ok;
82 }
83
84 /* ---------------------------------------------------------------------- */
85
86 static OSSL_FUNC_decoder_freectx_fn der2key_freectx;
87 static OSSL_FUNC_decoder_gettable_params_fn der2key_gettable_params;
88 static OSSL_FUNC_decoder_get_params_fn der2key_get_params;
89 static OSSL_FUNC_decoder_decode_fn der2key_decode;
90 static OSSL_FUNC_decoder_export_object_fn der2key_export_object;
91
92 typedef void *(extract_key_fn)(EVP_PKEY *);
93 typedef void (free_key_fn)(void *);
94 struct keytype_desc_st {
95     int type;                 /* EVP key type */
96     const char *name;         /* Keytype */
97     const OSSL_DISPATCH *fns; /* Keymgmt (to pilfer functions from) */
98
99     /*
100      * These must be the correct EVP_PKEY_get1_{TYPE}() and {TYPE}_free()
101      * function for the key.
102      */
103     extract_key_fn *extract_key;
104     free_key_fn *free_key;
105 };
106
107 /*
108  * Context used for DER to key decoding.
109  */
110 struct der2key_ctx_st {
111     PROV_CTX *provctx;
112     const struct keytype_desc_st *desc;
113 };
114
115 static struct der2key_ctx_st *
116 der2key_newctx(void *provctx, const struct keytype_desc_st *desc)
117 {
118     struct der2key_ctx_st *ctx = OPENSSL_zalloc(sizeof(*ctx));
119
120     if (ctx != NULL) {
121         ctx->provctx = provctx;
122         ctx->desc = desc;
123     }
124     return ctx;
125 }
126
127 static void der2key_freectx(void *vctx)
128 {
129     struct der2key_ctx_st *ctx = vctx;
130
131     OPENSSL_free(ctx);
132 }
133
134 static const OSSL_PARAM *der2key_gettable_params(void *provctx)
135 {
136     static const OSSL_PARAM gettables[] = {
137         { OSSL_DECODER_PARAM_INPUT_TYPE, OSSL_PARAM_UTF8_PTR, NULL, 0, 0 },
138         OSSL_PARAM_END,
139     };
140
141     return gettables;
142 }
143
144 static int der2key_get_params(OSSL_PARAM params[])
145 {
146     OSSL_PARAM *p;
147
148     p = OSSL_PARAM_locate(params, OSSL_DECODER_PARAM_INPUT_TYPE);
149     if (p != NULL && !OSSL_PARAM_set_utf8_ptr(p, "DER"))
150         return 0;
151
152     return 1;
153 }
154
155 static int der2key_decode(void *vctx, OSSL_CORE_BIO *cin,
156                           OSSL_CALLBACK *data_cb, void *data_cbarg,
157                           OSSL_PASSPHRASE_CALLBACK *pw_cb, void *pw_cbarg)
158 {
159     struct der2key_ctx_st *ctx = vctx;
160     void *libctx = PROV_LIBRARY_CONTEXT_OF(ctx->provctx);
161     unsigned char *der = NULL;
162     const unsigned char *derp;
163     long der_len = 0;
164     unsigned char *new_der = NULL;
165     long new_der_len;
166     EVP_PKEY *pkey = NULL;
167     void *key = NULL;
168     int ok = 0;
169
170     if (!read_der(ctx->provctx, cin, &der, &der_len))
171         return 0;
172
173     /*
174      * Opportunistic attempt to decrypt.  If it doesn't work, we try to
175      * decode our input unencrypted.
176      */
177     if (der_from_p8(&new_der, &new_der_len, der, der_len, pw_cb, pw_cbarg)) {
178         OPENSSL_free(der);
179         der = new_der;
180         der_len = new_der_len;
181     }
182
183     derp = der;
184     pkey = d2i_PrivateKey_ex(ctx->desc->type, NULL, &derp, der_len,
185                              libctx, NULL);
186     if (pkey == NULL) {
187         derp = der;
188         pkey = d2i_PUBKEY_ex(NULL, &derp, der_len, libctx, NULL);
189     }
190
191     if (pkey == NULL) {
192         derp = der;
193         pkey = d2i_KeyParams(ctx->desc->type, NULL, &derp, der_len);
194     }
195
196     if (pkey != NULL) {
197         /*
198          * Tear out the low-level key pointer from the pkey,
199          * but only if it matches the expected key type.
200          *
201          * TODO(3.0): The check should be done with EVP_PKEY_is_a(), but
202          * as long as we still have #legacy internal keys, it's safer to
203          * use the type numbers inside the provider.
204          */
205         if (EVP_PKEY_id(pkey) == ctx->desc->type)
206             key = ctx->desc->extract_key(pkey);
207
208         /*
209          * ctx->desc->extract_key() is expected to have incremented |key|'s
210          * reference count, so it should be safe to free |pkey| now.
211          */
212         EVP_PKEY_free(pkey);
213     }
214
215     OPENSSL_free(der);
216
217     if (key != NULL) {
218         OSSL_PARAM params[4];
219         int object_type = OSSL_OBJECT_PKEY;
220
221         params[0] =
222             OSSL_PARAM_construct_int(OSSL_OBJECT_PARAM_TYPE, &object_type);
223         params[1] =
224             OSSL_PARAM_construct_utf8_string(OSSL_OBJECT_PARAM_DATA_TYPE,
225                                              (char *)ctx->desc->name, 0);
226         /* The address of the key becomes the octet string */
227         params[2] =
228             OSSL_PARAM_construct_octet_string(OSSL_OBJECT_PARAM_REFERENCE,
229                                               &key, sizeof(key));
230         params[3] = OSSL_PARAM_construct_end();
231
232         ok = data_cb(params, data_cbarg);
233     }
234     ctx->desc->free_key(key);
235
236     return ok;
237 }
238
239 static int der2key_export_object(void *vctx,
240                                  const void *reference, size_t reference_sz,
241                                  OSSL_CALLBACK *export_cb, void *export_cbarg)
242 {
243     struct der2key_ctx_st *ctx = vctx;
244     OSSL_FUNC_keymgmt_export_fn *export =
245         ossl_prov_get_keymgmt_export(ctx->desc->fns);
246     void *keydata;
247
248     if (reference_sz == sizeof(keydata) && export != NULL) {
249         /* The contents of the reference is the address to our object */
250         keydata = *(void **)reference;
251
252         return export(keydata, OSSL_KEYMGMT_SELECT_ALL,
253                       export_cb, export_cbarg);
254     }
255     return 0;
256 }
257
258 #define IMPLEMENT_NEWCTX(KEYTYPEstr, KEYTYPE, keytype, extract, free)   \
259     static const struct keytype_desc_st keytype##_desc =                \
260         { EVP_PKEY_##KEYTYPE, KEYTYPEstr, keytype##_keymgmt_functions,  \
261           (extract_key_fn *)extract,                                    \
262           (free_key_fn *)free };                                        \
263     static OSSL_FUNC_decoder_newctx_fn der2##keytype##_newctx;          \
264     static void *der2##keytype##_newctx(void *provctx)                  \
265     {                                                                   \
266         return der2key_newctx(provctx, &keytype##_desc);                \
267     }                                                                   \
268     const OSSL_DISPATCH der_to_##keytype##_decoder_functions[] = {      \
269         { OSSL_FUNC_DECODER_NEWCTX,                                     \
270           (void (*)(void))der2##keytype##_newctx },                     \
271         { OSSL_FUNC_DECODER_FREECTX,                                    \
272           (void (*)(void))der2key_freectx },                            \
273         { OSSL_FUNC_DECODER_GETTABLE_PARAMS,                            \
274           (void (*)(void))der2key_gettable_params },                    \
275         { OSSL_FUNC_DECODER_GET_PARAMS,                                 \
276           (void (*)(void))der2key_get_params },                         \
277         { OSSL_FUNC_DECODER_DECODE,                                     \
278           (void (*)(void))der2key_decode },                             \
279         { OSSL_FUNC_DECODER_EXPORT_OBJECT,                              \
280           (void (*)(void))der2key_export_object },                      \
281         { 0, NULL }                                                     \
282     }
283
284 #ifndef OPENSSL_NO_DH
285 IMPLEMENT_NEWCTX("DH", DH, dh, EVP_PKEY_get1_DH, DH_free);
286 IMPLEMENT_NEWCTX("DHX", DHX, dhx, EVP_PKEY_get1_DH, DH_free);
287 #endif
288 #ifndef OPENSSL_NO_DSA
289 IMPLEMENT_NEWCTX("DSA", DSA, dsa, EVP_PKEY_get1_DSA, DSA_free);
290 #endif
291 #ifndef OPENSSL_NO_EC
292 IMPLEMENT_NEWCTX("EC", EC, ec, EVP_PKEY_get1_EC_KEY, EC_KEY_free);
293 IMPLEMENT_NEWCTX("X25519", X25519, x25519,
294                  EVP_PKEY_get1_X25519, ecx_key_free);
295 IMPLEMENT_NEWCTX("X448", X448, x448,
296                  EVP_PKEY_get1_X448, ecx_key_free);
297 IMPLEMENT_NEWCTX("ED25519", ED25519, ed25519,
298                  EVP_PKEY_get1_ED25519, ecx_key_free);
299 IMPLEMENT_NEWCTX("ED448", ED448, ed448, EVP_PKEY_get1_ED448, ecx_key_free);
300 #endif
301 IMPLEMENT_NEWCTX("RSA", RSA, rsa, EVP_PKEY_get1_RSA, RSA_free);
302 IMPLEMENT_NEWCTX("RSA-PSS", RSA_PSS, rsapss, EVP_PKEY_get1_RSA, RSA_free);