prov: prefix all OSSL_DISPATCH tables names with ossl_
[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 err, ok = 0;
169
170     ERR_set_mark();
171     if (!read_der(ctx->provctx, cin, &der, &der_len))
172         goto err;
173
174     /*
175      * Opportunistic attempt to decrypt.  If it doesn't work, we try to
176      * decode our input unencrypted.
177      */
178     if (der_from_p8(&new_der, &new_der_len, der, der_len, pw_cb, pw_cbarg)) {
179         OPENSSL_free(der);
180         der = new_der;
181         der_len = new_der_len;
182     }
183
184     derp = der;
185     pkey = d2i_PrivateKey_ex(ctx->desc->type, NULL, &derp, der_len,
186                              libctx, NULL);
187     if (pkey == NULL) {
188         derp = der;
189         pkey = d2i_PUBKEY_ex(NULL, &derp, der_len, libctx, NULL);
190     }
191
192     if (pkey == NULL) {
193         derp = der;
194         pkey = d2i_KeyParams(ctx->desc->type, NULL, &derp, der_len);
195     }
196  err:
197     /*
198      * Prune low-level ASN.1 parse errors from error queue, assuming that
199      * this is called by decoder_process() in a loop trying several formats.
200      */
201     err = ERR_peek_last_error();
202     if (ERR_GET_LIB(err) == ERR_LIB_ASN1
203             && (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG
204                 || ERR_GET_REASON(err) == ERR_R_NESTED_ASN1_ERROR))
205         ERR_pop_to_mark();
206     else
207         ERR_clear_last_mark();
208
209     if (pkey != NULL) {
210         /*
211          * Tear out the low-level key pointer from the pkey,
212          * but only if it matches the expected key type.
213          *
214          * TODO(3.0): The check should be done with EVP_PKEY_is_a(), but
215          * as long as we still have #legacy internal keys, it's safer to
216          * use the type numbers inside the provider.
217          */
218         if (EVP_PKEY_id(pkey) == ctx->desc->type)
219             key = ctx->desc->extract_key(pkey);
220
221         /*
222          * ctx->desc->extract_key() is expected to have incremented |key|'s
223          * reference count, so it should be safe to free |pkey| now.
224          */
225         EVP_PKEY_free(pkey);
226     }
227
228     OPENSSL_free(der);
229
230     if (key != NULL) {
231         OSSL_PARAM params[4];
232         int object_type = OSSL_OBJECT_PKEY;
233
234         params[0] =
235             OSSL_PARAM_construct_int(OSSL_OBJECT_PARAM_TYPE, &object_type);
236         params[1] =
237             OSSL_PARAM_construct_utf8_string(OSSL_OBJECT_PARAM_DATA_TYPE,
238                                              (char *)ctx->desc->name, 0);
239         /* The address of the key becomes the octet string */
240         params[2] =
241             OSSL_PARAM_construct_octet_string(OSSL_OBJECT_PARAM_REFERENCE,
242                                               &key, sizeof(key));
243         params[3] = OSSL_PARAM_construct_end();
244
245         ok = data_cb(params, data_cbarg);
246     }
247     ctx->desc->free_key(key);
248
249     return ok;
250 }
251
252 static int der2key_export_object(void *vctx,
253                                  const void *reference, size_t reference_sz,
254                                  OSSL_CALLBACK *export_cb, void *export_cbarg)
255 {
256     struct der2key_ctx_st *ctx = vctx;
257     OSSL_FUNC_keymgmt_export_fn *export =
258         ossl_prov_get_keymgmt_export(ctx->desc->fns);
259     void *keydata;
260
261     if (reference_sz == sizeof(keydata) && export != NULL) {
262         /* The contents of the reference is the address to our object */
263         keydata = *(void **)reference;
264
265         return export(keydata, OSSL_KEYMGMT_SELECT_ALL,
266                       export_cb, export_cbarg);
267     }
268     return 0;
269 }
270
271 #define IMPLEMENT_NEWCTX(KEYTYPEstr, KEYTYPE, keytype, extract, free)   \
272     static const struct keytype_desc_st keytype##_desc =                \
273         { EVP_PKEY_##KEYTYPE, KEYTYPEstr,                               \
274           ossl_##keytype##_keymgmt_functions,                           \
275           (extract_key_fn *)extract,                                    \
276           (free_key_fn *)free };                                        \
277     static OSSL_FUNC_decoder_newctx_fn der2##keytype##_newctx;          \
278     static void *der2##keytype##_newctx(void *provctx)                  \
279     {                                                                   \
280         return der2key_newctx(provctx, &keytype##_desc);                \
281     }                                                                   \
282     const OSSL_DISPATCH ossl_der_to_##keytype##_decoder_functions[] = { \
283         { OSSL_FUNC_DECODER_NEWCTX,                                     \
284           (void (*)(void))der2##keytype##_newctx },                     \
285         { OSSL_FUNC_DECODER_FREECTX,                                    \
286           (void (*)(void))der2key_freectx },                            \
287         { OSSL_FUNC_DECODER_GETTABLE_PARAMS,                            \
288           (void (*)(void))der2key_gettable_params },                    \
289         { OSSL_FUNC_DECODER_GET_PARAMS,                                 \
290           (void (*)(void))der2key_get_params },                         \
291         { OSSL_FUNC_DECODER_DECODE,                                     \
292           (void (*)(void))der2key_decode },                             \
293         { OSSL_FUNC_DECODER_EXPORT_OBJECT,                              \
294           (void (*)(void))der2key_export_object },                      \
295         { 0, NULL }                                                     \
296     }
297
298 #ifndef OPENSSL_NO_DH
299 IMPLEMENT_NEWCTX("DH", DH, dh, EVP_PKEY_get1_DH, DH_free);
300 IMPLEMENT_NEWCTX("DHX", DHX, dhx, EVP_PKEY_get1_DH, DH_free);
301 #endif
302 #ifndef OPENSSL_NO_DSA
303 IMPLEMENT_NEWCTX("DSA", DSA, dsa, EVP_PKEY_get1_DSA, DSA_free);
304 #endif
305 #ifndef OPENSSL_NO_EC
306 IMPLEMENT_NEWCTX("EC", EC, ec, EVP_PKEY_get1_EC_KEY, EC_KEY_free);
307 IMPLEMENT_NEWCTX("X25519", X25519, x25519,
308                  evp_pkey_get1_X25519, ecx_key_free);
309 IMPLEMENT_NEWCTX("X448", X448, x448,
310                  evp_pkey_get1_X448, ecx_key_free);
311 IMPLEMENT_NEWCTX("ED25519", ED25519, ed25519,
312                  evp_pkey_get1_ED25519, ecx_key_free);
313 IMPLEMENT_NEWCTX("ED448", ED448, ed448, evp_pkey_get1_ED448, ecx_key_free);
314 #endif
315 IMPLEMENT_NEWCTX("RSA", RSA, rsa, EVP_PKEY_get1_RSA, RSA_free);
316 IMPLEMENT_NEWCTX("RSA-PSS", RSA_PSS, rsapss, EVP_PKEY_get1_RSA, RSA_free);