9df29cec0aa118ce2cffbd83aec07086f19a7981
[openssl.git] / crypto / store / store_result.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 #include "e_os.h"
11 #include <string.h>
12
13 #include <openssl/core.h>
14 #include <openssl/core_names.h>
15 #include <openssl/core_object.h>
16 #include <openssl/err.h>
17 #include <openssl/pkcs12.h>
18 #include <openssl/provider.h>
19 #include <openssl/decoder.h>
20 #include <openssl/store.h>
21 #include "internal/provider.h"
22 #include "internal/passphrase.h"
23 #include "crypto/evp.h"
24 #include "crypto/x509.h"
25 #include "store_local.h"
26
27 #ifndef OSSL_OBJECT_PKCS12
28 /*
29  * The object abstraction doesn't know PKCS#12, but we want to indicate
30  * it anyway, so we create our own.  Since the public macros use positive
31  * numbers, negative ones should be fine.  They must never slip out from
32  * this translation unit anyway.
33  */
34 # define OSSL_OBJECT_PKCS12 -1
35 #endif
36
37 /*
38  * ossl_store_handle_load_result() is initially written to be a companion
39  * to our 'file:' scheme provider implementation, but has been made generic
40  * to serve others as well.
41  *
42  * This result handler takes any object abstraction (see provider-object(7))
43  * and does the best it can with it.  If the object is passed by value (not
44  * by reference), the contents are currently expected to be DER encoded.
45  * If an object type is specified, that will be respected; otherwise, this
46  * handler will guess the contents, by trying the following in order:
47  *
48  * 1.  Decode it into an EVP_PKEY, using OSSL_DECODER.
49  * 2.  Decode it into an X.509 certificate, using d2i_X509 / d2i_X509_AUX.
50  * 3.  Decode it into an X.509 CRL, using d2i_X509_CRL.
51  * 4.  Decode it into a PKCS#12 structure, using d2i_PKCS12 (*).
52  *
53  * For the 'file:' scheme implementation, this is division of labor.  Since
54  * the libcrypto <-> provider interface currently doesn't support certain
55  * structures as first class objects, they must be unpacked from DER here
56  * rather than in the provider.  The current exception is asymmetric keys,
57  * which can reside within the provider boundary, most of all thanks to
58  * OSSL_FUNC_keymgmt_load(), which allows loading the key material by
59  * reference.
60  */
61
62 DEFINE_STACK_OF(X509)
63
64 struct extracted_param_data_st {
65     int object_type;
66     const char *data_type;
67     const char *utf8_data;
68     const void *octet_data;
69     size_t octet_data_size;
70     const void *ref;
71     size_t ref_size;
72     const char *desc;
73 };
74
75 static int try_name(struct extracted_param_data_st *, OSSL_STORE_INFO **);
76 static int try_key(struct extracted_param_data_st *, OSSL_STORE_INFO **,
77                    OSSL_STORE_CTX *, const OSSL_PROVIDER *,
78                    OPENSSL_CTX *, const char *);
79 static int try_cert(struct extracted_param_data_st *, OSSL_STORE_INFO **,
80                     OPENSSL_CTX *, const char *);
81 static int try_crl(struct extracted_param_data_st *, OSSL_STORE_INFO **,
82                    OPENSSL_CTX *, const char *);
83 static int try_pkcs12(struct extracted_param_data_st *, OSSL_STORE_INFO **,
84                       OSSL_STORE_CTX *, OPENSSL_CTX *, const char *);
85
86 int ossl_store_handle_load_result(const OSSL_PARAM params[], void *arg)
87 {
88     struct ossl_load_result_data_st *cbdata = arg;
89     OSSL_STORE_INFO **v = &cbdata->v;
90     OSSL_STORE_CTX *ctx = cbdata->ctx;
91     const OSSL_PROVIDER *provider =
92         OSSL_STORE_LOADER_provider(ctx->fetched_loader);
93     OPENSSL_CTX *libctx = ossl_provider_library_context(provider);
94     const char *propq = ctx->properties;
95     const OSSL_PARAM *p;
96     struct extracted_param_data_st helper_data;
97
98     memset(&helper_data, 0, sizeof(helper_data));
99     helper_data.object_type = OSSL_OBJECT_UNKNOWN;
100
101     if ((p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_TYPE)) != NULL
102         && !OSSL_PARAM_get_int(p, &helper_data.object_type))
103         return 0;
104     p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_DATA_TYPE);
105     if (p != NULL
106         && !OSSL_PARAM_get_utf8_string_ptr(p, &helper_data.data_type))
107         return 0;
108     p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_DATA);
109     if (p != NULL
110         && !OSSL_PARAM_get_octet_string_ptr(p, &helper_data.octet_data,
111                                             &helper_data.octet_data_size)
112         && !OSSL_PARAM_get_utf8_string_ptr(p, &helper_data.utf8_data))
113         return 0;
114     p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_REFERENCE);
115     if (p != NULL && !OSSL_PARAM_get_octet_string_ptr(p, &helper_data.ref,
116                                                       &helper_data.ref_size))
117         return 0;
118     p = OSSL_PARAM_locate_const(params, OSSL_OBJECT_PARAM_DESC);
119     if (p != NULL && !OSSL_PARAM_get_utf8_string_ptr(p, &helper_data.desc))
120         return 0;
121
122     /*
123      * The helper functions return 0 on actual errors, otherwise 1, even if
124      * they didn't fill out |*v|.
125      */
126     if (!try_name(&helper_data, v)
127         || !try_key(&helper_data, v, ctx, provider, libctx, propq)
128         || !try_cert(&helper_data, v, libctx, propq)
129         || !try_crl(&helper_data, v, libctx, propq)
130         || !try_pkcs12(&helper_data, v, ctx, libctx, propq))
131         return 0;
132
133     return (*v != NULL);
134 }
135
136 static int try_name(struct extracted_param_data_st *data, OSSL_STORE_INFO **v)
137 {
138     if (data->object_type == OSSL_OBJECT_NAME) {
139         char *newname = NULL, *newdesc = NULL;
140
141         if (data->utf8_data == NULL)
142             return 0;
143         if ((newname = OPENSSL_strdup(data->utf8_data)) == NULL
144             || (data->desc != NULL
145                 && (newdesc = OPENSSL_strdup(data->desc)) == NULL)
146             || (*v = OSSL_STORE_INFO_new_NAME(newname)) == NULL) {
147             OPENSSL_free(newname);
148             OPENSSL_free(newdesc);
149             return 0;
150         }
151         OSSL_STORE_INFO_set0_NAME_description(*v, newdesc);
152     }
153     return 1;
154 }
155
156 /*
157  * For the rest of the object types, the provider code may not know what
158  * type of data it gave us, so we may need to figure that out on our own.
159  * Therefore, we do check for OSSL_OBJECT_UNKNOWN everywhere below, and
160  * only return 0 on error if the object type is known.
161  */
162
163 static EVP_PKEY *try_key_ref(struct extracted_param_data_st *data,
164                              OSSL_STORE_CTX *ctx,
165                              const OSSL_PROVIDER *provider,
166                              OPENSSL_CTX *libctx, const char *propq)
167 {
168     EVP_PKEY *pk = NULL;
169     EVP_KEYMGMT *keymgmt = NULL;
170     void *keydata = NULL;
171
172     /* If we have an object reference, we must have a data type */
173     if (data->data_type == NULL)
174         return 0;
175
176     keymgmt = EVP_KEYMGMT_fetch(libctx, data->data_type, propq);
177     if (keymgmt != NULL) {
178         /*
179          * There are two possible cases
180          *
181          * 1.  The keymgmt is from the same provider as the loader,
182          *     so we can use evp_keymgmt_load()
183          * 2.  The keymgmt is from another provider, then we must
184          *     do the export/import dance.
185          */
186         if (EVP_KEYMGMT_provider(keymgmt) == provider) {
187             keydata = evp_keymgmt_load(keymgmt, data->ref, data->ref_size);
188         } else {
189             struct evp_keymgmt_util_try_import_data_st import_data;
190             OSSL_FUNC_store_export_object_fn *export_object =
191                 ctx->fetched_loader->p_export_object;
192
193             import_data.keymgmt = keymgmt;
194             import_data.keydata = NULL;
195             import_data.selection = OSSL_KEYMGMT_SELECT_ALL;
196
197             if (export_object != NULL) {
198                 /*
199                  * No need to check for errors here, the value of
200                  * |import_data.keydata| is as much an indicator.
201                  */
202                 (void)export_object(ctx->loader_ctx,
203                                     data->ref, data->ref_size,
204                                     &evp_keymgmt_util_try_import,
205                                     &import_data);
206             }
207
208             keydata = import_data.keydata;
209         }
210     }
211     if (keydata != NULL)
212         pk = evp_keymgmt_util_make_pkey(keymgmt, keydata);
213     EVP_KEYMGMT_free(keymgmt);
214
215     return pk;
216 }
217
218 static EVP_PKEY *try_key_value(struct extracted_param_data_st *data,
219                                OSSL_STORE_CTX *ctx,
220                                OSSL_PASSPHRASE_CALLBACK *cb, void *cbarg,
221                                OPENSSL_CTX *libctx, const char *propq)
222 {
223     EVP_PKEY *pk = NULL;
224     OSSL_DECODER_CTX *decoderctx = NULL;
225     BIO *membio =
226         BIO_new_mem_buf(data->octet_data, (int)data->octet_data_size);
227
228     if (membio == NULL)
229         return 0;
230
231     decoderctx = OSSL_DECODER_CTX_new_by_EVP_PKEY(&pk, "DER", libctx, propq);
232     (void)OSSL_DECODER_CTX_set_passphrase_cb(decoderctx, cb, cbarg);
233
234     /* No error if this couldn't be decoded */
235     (void)OSSL_DECODER_from_bio(decoderctx, membio);
236
237     OSSL_DECODER_CTX_free(decoderctx);
238     BIO_free(membio);
239
240     return pk;
241 }
242
243 typedef OSSL_STORE_INFO *store_info_new_fn(EVP_PKEY *);
244
245 static EVP_PKEY *try_key_value_legacy(struct extracted_param_data_st *data,
246                                       store_info_new_fn **store_info_new,
247                                       OSSL_STORE_CTX *ctx,
248                                       OSSL_PASSPHRASE_CALLBACK *cb, void *cbarg,
249                                       OPENSSL_CTX *libctx, const char *propq)
250 {
251     EVP_PKEY *pk = NULL;
252     const unsigned char *der = data->octet_data, *derp;
253     long der_len = (long)data->octet_data_size;
254
255     /* Try PUBKEY first, that's a real easy target */
256     derp = der;
257     pk = d2i_PUBKEY_ex(NULL, &derp, der_len, libctx, propq);
258     if (pk != NULL)
259         *store_info_new = OSSL_STORE_INFO_new_PUBKEY;
260
261     /* Try private keys next */
262     if (pk == NULL) {
263         unsigned char *new_der = NULL;
264         X509_SIG *p8 = NULL;
265         PKCS8_PRIV_KEY_INFO *p8info = NULL;
266
267         /* See if it's an encrypted PKCS#8 and decrypt it */
268         derp = der;
269         if ((p8 = d2i_X509_SIG(NULL, &derp, der_len)) != NULL) {
270             char pbuf[PEM_BUFSIZE];
271             size_t plen = 0;
272
273             if (!cb(pbuf, sizeof(pbuf), &plen, NULL, cbarg)) {
274                 ERR_raise(ERR_LIB_OSSL_STORE,
275                           OSSL_STORE_R_BAD_PASSWORD_READ);
276             } else {
277                 const X509_ALGOR *alg = NULL;
278                 const ASN1_OCTET_STRING *oct = NULL;
279                 int len = 0;
280
281                 X509_SIG_get0(p8, &alg, &oct);
282
283                 /*
284                  * No need to check the returned value, |new_der|
285                  * will be NULL on error anyway.
286                  */
287                 PKCS12_pbe_crypt(alg, pbuf, plen,
288                                  oct->data, oct->length,
289                                  &new_der, &len, 0);
290                 der_len = len;
291                 der = new_der;
292             }
293             X509_SIG_free(p8);
294         }
295
296         /*
297          * If the encrypted PKCS#8 couldn't be decrypted,
298          * |der| is NULL
299          */
300         if (der != NULL) {
301             /* Try to unpack an unencrypted PKCS#8, that's easy */
302             derp = der;
303             p8info = d2i_PKCS8_PRIV_KEY_INFO(NULL, &derp, der_len);
304             if (p8info != NULL) {
305                 pk = EVP_PKCS82PKEY_with_libctx(p8info, libctx, propq);
306                 PKCS8_PRIV_KEY_INFO_free(p8info);
307             }
308
309             /*
310              * It wasn't PKCS#8, so we must try the hard way.
311              * However, we can cheat a little bit, because we know
312              * what's not yet fully supported in out decoders.
313              * TODO(3.0) Eliminate these when we have decoder support.
314              */
315             if (pk == NULL) {
316                 derp = der;
317                 pk = d2i_PrivateKey_ex(EVP_PKEY_SM2, NULL,
318                                        &derp, der_len,
319                                        libctx, NULL);
320             }
321         }
322
323         if (pk != NULL)
324             *store_info_new = OSSL_STORE_INFO_new_PKEY;
325
326         OPENSSL_free(new_der);
327         der = data->octet_data;
328         der_len = (long)data->octet_data_size;
329     }
330
331     /*
332      * Last, we try parameters.  We cheat the same way we do for
333      * private keys above.
334      * TODO(3.0) Eliminate these when we have decoder support.
335      */
336     if (pk == NULL) {
337         derp = der;
338         pk = d2i_KeyParams(EVP_PKEY_SM2, NULL, &derp, der_len);
339         if (pk != NULL)
340             *store_info_new = OSSL_STORE_INFO_new_PARAMS;
341     }
342
343     return pk;
344 }
345
346 static int try_key(struct extracted_param_data_st *data, OSSL_STORE_INFO **v,
347                    OSSL_STORE_CTX *ctx, const OSSL_PROVIDER *provider,
348                    OPENSSL_CTX *libctx, const char *propq)
349 {
350     store_info_new_fn *store_info_new = NULL;
351
352     if (data->object_type == OSSL_OBJECT_UNKNOWN
353         || data->object_type == OSSL_OBJECT_PKEY) {
354         EVP_PKEY *pk = NULL;
355
356         /* Prefer key by reference than key by value */
357         if (data->object_type == OSSL_OBJECT_PKEY && data->ref != NULL) {
358             pk = try_key_ref(data, ctx, provider, libctx, propq);
359
360             /*
361              * If for some reason we couldn't get a key, it's an error.
362              * It indicates that while decoders could make a key reference,
363              * the keymgmt somehow couldn't handle it, or doesn't have a
364              * OSSL_FUNC_keymgmt_load function.
365              */
366             if (pk == NULL)
367                 return 0;
368         } else if (data->octet_data != NULL) {
369             OSSL_PASSPHRASE_CALLBACK *cb = ossl_pw_passphrase_callback_dec;
370             void *cbarg = &ctx->pwdata;
371
372             pk = try_key_value(data, ctx, cb, cbarg, libctx, propq);
373
374             /*
375              * Desperate last maneuver, in case the decoders don't support
376              * the data we have, then we try on our own to at least get a
377              * legacy key.
378              * This is the same as der2key_decode() does, but in a limited
379              * way and within the walls of libcrypto.
380              *
381              * TODO Remove this when #legacy keys are gone
382              */
383             if (pk == NULL)
384                 pk = try_key_value_legacy(data, &store_info_new, ctx,
385                                           cb, cbarg, libctx, propq);
386         }
387
388         if (pk != NULL) {
389             data->object_type = OSSL_OBJECT_PKEY;
390
391             if (store_info_new == NULL) {
392                 /*
393                  * We determined the object type for OSSL_STORE_INFO, which
394                  * makes an explicit difference between an EVP_PKEY with just
395                  * (domain) parameters and an EVP_PKEY with actual key
396                  * material.
397                  * The logic is that an EVP_PKEY with actual key material
398                  * always has the public half.
399                  */
400                 if (evp_keymgmt_util_has(pk, OSSL_KEYMGMT_SELECT_PRIVATE_KEY))
401                     store_info_new = OSSL_STORE_INFO_new_PKEY;
402                 else if (evp_keymgmt_util_has(pk,
403                                               OSSL_KEYMGMT_SELECT_PUBLIC_KEY))
404                     store_info_new = OSSL_STORE_INFO_new_PUBKEY;
405                 else
406                     store_info_new = OSSL_STORE_INFO_new_PARAMS;
407             }
408             *v = store_info_new(pk);
409         }
410
411         if (*v == NULL)
412             EVP_PKEY_free(pk);
413     }
414
415     return 1;
416 }
417
418 static int try_cert(struct extracted_param_data_st *data, OSSL_STORE_INFO **v,
419                     OPENSSL_CTX *libctx, const char *propq)
420 {
421     if (data->object_type == OSSL_OBJECT_UNKNOWN
422         || data->object_type == OSSL_OBJECT_CERT) {
423         X509 *cert;
424
425         /*
426          * In most cases, we can try to interpret the serialized
427          * data as a trusted cert (X509 + X509_AUX) and fall back
428          * to reading it as a normal cert (just X509), but if
429          * |data_type| (the PEM name) specifically declares it as a
430          * trusted cert, then no fallback should be engaged.
431          * |ignore_trusted| tells if the fallback can be used (1)
432          * or not (0).
433          */
434         int ignore_trusted = 1;
435
436         /* If we have a data type, it should be a PEM name */
437         if (data->data_type != NULL
438             && (strcasecmp(data->data_type, PEM_STRING_X509_TRUSTED) == 0))
439             ignore_trusted = 0;
440
441         cert = d2i_X509_AUX(NULL, (const unsigned char **)&data->octet_data,
442                             data->octet_data_size);
443         if (cert == NULL && ignore_trusted)
444             cert = d2i_X509(NULL, (const unsigned char **)&data->octet_data,
445                             data->octet_data_size);
446
447         if (cert != NULL)
448             /* We determined the object type */
449             data->object_type = OSSL_OBJECT_CERT;
450
451         if (cert != NULL && !x509_set0_libctx(cert, libctx, propq)) {
452             X509_free(cert);
453             cert = NULL;
454         }
455
456         if (cert != NULL)
457             *v = OSSL_STORE_INFO_new_CERT(cert);
458         if (*v == NULL)
459             X509_free(cert);
460     }
461
462     return 1;
463 }
464
465 static int try_crl(struct extracted_param_data_st *data, OSSL_STORE_INFO **v,
466                    OPENSSL_CTX *libctx, const char *propq)
467 {
468     if (data->object_type == OSSL_OBJECT_UNKNOWN
469         || data->object_type == OSSL_OBJECT_CRL) {
470         X509_CRL *crl;
471
472         crl = d2i_X509_CRL(NULL, (const unsigned char **)&data->octet_data,
473                            data->octet_data_size);
474         if (crl != NULL)
475             /* We determined the object type */
476             data->object_type = OSSL_OBJECT_CRL;
477
478         if (crl != NULL && !x509_crl_set0_libctx(crl, libctx, propq)) {
479             X509_CRL_free(crl);
480             crl = NULL;
481         }
482
483         if (crl != NULL)
484             *v = OSSL_STORE_INFO_new_CRL(crl);
485         if (*v == NULL)
486             X509_CRL_free(crl);
487     }
488
489     return 1;
490 }
491
492 static int try_pkcs12(struct extracted_param_data_st *data, OSSL_STORE_INFO **v,
493                       OSSL_STORE_CTX *ctx,
494                       OPENSSL_CTX *libctx, const char *propq)
495 {
496     /* There is no specific object type for PKCS12 */
497     if (data->object_type == OSSL_OBJECT_UNKNOWN) {
498         /* Initial parsing */
499         PKCS12 *p12;
500
501         if ((p12 = d2i_PKCS12(NULL, (const unsigned char **)&data->octet_data,
502                               data->octet_data_size)) != NULL) {
503             char *pass = NULL;
504             char tpass[PEM_BUFSIZE];
505             size_t tpass_len;
506             EVP_PKEY *pkey = NULL;
507             X509 *cert = NULL;
508             STACK_OF(X509) *chain = NULL;
509
510             data->object_type = OSSL_OBJECT_PKCS12;
511
512             if (PKCS12_verify_mac(p12, "", 0)
513                 || PKCS12_verify_mac(p12, NULL, 0)) {
514                 pass = "";
515             } else {
516                 static char prompt_info[] = "PKCS12 import pass phrase";
517                 OSSL_PARAM pw_params[] = {
518                     OSSL_PARAM_utf8_string(OSSL_PASSPHRASE_PARAM_INFO,
519                                            prompt_info,
520                                            sizeof(prompt_info) - 1),
521                     OSSL_PARAM_END
522                 };
523
524                 if (!ossl_pw_get_passphrase(tpass, sizeof(tpass), &tpass_len,
525                                             pw_params, 0, &ctx->pwdata)) {
526                     ERR_raise(ERR_LIB_OSSL_STORE,
527                               OSSL_STORE_R_PASSPHRASE_CALLBACK_ERROR);
528                     goto p12_end;
529                 }
530                 pass = tpass;
531                 if (!PKCS12_verify_mac(p12, pass, strlen(pass))) {
532                     ERR_raise(ERR_LIB_OSSL_STORE,
533                               OSSL_STORE_R_ERROR_VERIFYING_PKCS12_MAC);
534                     goto p12_end;
535                 }
536             }
537
538             if (PKCS12_parse(p12, pass, &pkey, &cert, &chain)) {
539                 STACK_OF(OSSL_STORE_INFO) *infos = NULL;
540                 OSSL_STORE_INFO *osi_pkey = NULL;
541                 OSSL_STORE_INFO *osi_cert = NULL;
542                 OSSL_STORE_INFO *osi_ca = NULL;
543                 int ok = 1;
544
545                 if ((infos = sk_OSSL_STORE_INFO_new_null()) != NULL) {
546                     if (pkey != NULL) {
547                         if ((osi_pkey = OSSL_STORE_INFO_new_PKEY(pkey)) != NULL
548                             /* clearing pkey here avoids case distinctions */
549                             && (pkey = NULL) == NULL
550                             && sk_OSSL_STORE_INFO_push(infos, osi_pkey) != 0)
551                             osi_pkey = NULL;
552                         else
553                             ok = 0;
554                     }
555                     if (ok && cert != NULL) {
556                         if ((osi_cert = OSSL_STORE_INFO_new_CERT(cert)) != NULL
557                             /* clearing cert here avoids case distinctions */
558                             && (cert = NULL) == NULL
559                             && sk_OSSL_STORE_INFO_push(infos, osi_cert) != 0)
560                             osi_cert = NULL;
561                         else
562                             ok = 0;
563                     }
564                     while (ok && sk_X509_num(chain) > 0) {
565                         X509 *ca = sk_X509_value(chain, 0);
566
567                         if ((osi_ca = OSSL_STORE_INFO_new_CERT(ca)) != NULL
568                             && sk_X509_shift(chain) != NULL
569                             && sk_OSSL_STORE_INFO_push(infos, osi_ca) != 0)
570                             osi_ca = NULL;
571                         else
572                             ok = 0;
573                     }
574                 }
575                 EVP_PKEY_free(pkey);
576                 X509_free(cert);
577                 sk_X509_pop_free(chain, X509_free);
578                 OSSL_STORE_INFO_free(osi_pkey);
579                 OSSL_STORE_INFO_free(osi_cert);
580                 OSSL_STORE_INFO_free(osi_ca);
581                 if (!ok) {
582                     sk_OSSL_STORE_INFO_pop_free(infos, OSSL_STORE_INFO_free);
583                     infos = NULL;
584                 }
585                 ctx->cached_info = infos;
586             }
587         }
588      p12_end:
589         PKCS12_free(p12);
590         *v = sk_OSSL_STORE_INFO_shift(ctx->cached_info);
591     }
592
593     return 1;
594 }