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