1/*
2 * Copyright 2016-2020 The OpenSSL Project Authors. All Rights Reserved.
3 *
4 * Licensed under the OpenSSL license (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#include <sys/stat.h>
13#include <ctype.h>
14#include <assert.h>
15
16#include <openssl/bio.h>
17#include <openssl/dsa.h>         /* For d2i_DSAPrivateKey */
18#include <openssl/err.h>
19#include <openssl/evp.h>
20#include <openssl/pem.h>
21#include <openssl/pkcs12.h>      /* For the PKCS8 stuff o.O */
22#include <openssl/rsa.h>         /* For d2i_RSAPrivateKey */
23#include <openssl/safestack.h>
24#include <openssl/store.h>
25#include <openssl/ui.h>
26#include <openssl/x509.h>        /* For the PKCS8 stuff o.O */
27#include "crypto/asn1.h"
28#include "crypto/ctype.h"
29#include "internal/o_dir.h"
30#include "internal/cryptlib.h"
31#include "crypto/store.h"
32#include "store_local.h"
33
34#ifdef _WIN32
35# define stat    _stat
36#endif
37
38#ifndef S_ISDIR
39# define S_ISDIR(a) (((a) & S_IFMT) == S_IFDIR)
40#endif
41
42/*-
43 *  Password prompting
44 *  ------------------
45 */
46
47static char *file_get_pass(const UI_METHOD *ui_method, char *pass,
48                           size_t maxsize, const char *prompt_info, void *data)
49{
50    UI *ui = UI_new();
51    char *prompt = NULL;
52
53    if (ui == NULL) {
54        OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, ERR_R_MALLOC_FAILURE);
55        return NULL;
56    }
57
58    if (ui_method != NULL)
59        UI_set_method(ui, ui_method);
60    UI_add_user_data(ui, data);
61
62    if ((prompt = UI_construct_prompt(ui, "pass phrase",
63                                      prompt_info)) == NULL) {
64        OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, ERR_R_MALLOC_FAILURE);
65        pass = NULL;
66    } else if (!UI_add_input_string(ui, prompt, UI_INPUT_FLAG_DEFAULT_PWD,
67                                    pass, 0, maxsize - 1)) {
68        OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, ERR_R_UI_LIB);
69        pass = NULL;
70    } else {
71        switch (UI_process(ui)) {
72        case -2:
73            OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS,
74                          OSSL_STORE_R_UI_PROCESS_INTERRUPTED_OR_CANCELLED);
75            pass = NULL;
76            break;
77        case -1:
78            OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, ERR_R_UI_LIB);
79            pass = NULL;
80            break;
81        default:
82            break;
83        }
84    }
85
86    OPENSSL_free(prompt);
87    UI_free(ui);
88    return pass;
89}
90
91struct pem_pass_data {
92    const UI_METHOD *ui_method;
93    void *data;
94    const char *prompt_info;
95};
96
97static int file_fill_pem_pass_data(struct pem_pass_data *pass_data,
98                                   const char *prompt_info,
99                                   const UI_METHOD *ui_method, void *ui_data)
100{
101    if (pass_data == NULL)
102        return 0;
103    pass_data->ui_method = ui_method;
104    pass_data->data = ui_data;
105    pass_data->prompt_info = prompt_info;
106    return 1;
107}
108
109/* This is used anywhere a pem_password_cb is needed */
110static int file_get_pem_pass(char *buf, int num, int w, void *data)
111{
112    struct pem_pass_data *pass_data = data;
113    char *pass = file_get_pass(pass_data->ui_method, buf, num,
114                               pass_data->prompt_info, pass_data->data);
115
116    return pass == NULL ? 0 : strlen(pass);
117}
118
119/*-
120 *  The file scheme decoders
121 *  ------------------------
122 *
123 *  Each possible data type has its own decoder, which either operates
124 *  through a given PEM name, or attempts to decode to see if the blob
125 *  it's given is decodable for its data type.  The assumption is that
126 *  only the correct data type will match the content.
127 */
128
129/*-
130 * The try_decode function is called to check if the blob of data can
131 * be used by this handler, and if it can, decodes it into a supported
132 * OpenSSL type and returns a OSSL_STORE_INFO with the decoded data.
133 * Input:
134 *    pem_name:     If this blob comes from a PEM file, this holds
135 *                  the PEM name.  If it comes from another type of
136 *                  file, this is NULL.
137 *    pem_header:   If this blob comes from a PEM file, this holds
138 *                  the PEM headers.  If it comes from another type of
139 *                  file, this is NULL.
140 *    blob:         The blob of data to match with what this handler
141 *                  can use.
142 *    len:          The length of the blob.
143 *    handler_ctx:  For a handler marked repeatable, this pointer can
144 *                  be used to create a context for the handler.  IT IS
145 *                  THE HANDLER'S RESPONSIBILITY TO CREATE AND DESTROY
146 *                  THIS CONTEXT APPROPRIATELY, i.e. create on first call
147 *                  and destroy when about to return NULL.
148 *    matchcount:   A pointer to an int to count matches for this data.
149 *                  Usually becomes 0 (no match) or 1 (match!), but may
150 *                  be higher in the (unlikely) event that the data matches
151 *                  more than one possibility.  The int will always be
152 *                  zero when the function is called.
153 *    ui_method:    Application UI method for getting a password, pin
154 *                  or any other interactive data.
155 *    ui_data:      Application data to be passed to ui_method when
156 *                  it's called.
157 * Output:
158 *    a OSSL_STORE_INFO
159 */
160typedef OSSL_STORE_INFO *(*file_try_decode_fn)(const char *pem_name,
161                                               const char *pem_header,
162                                               const unsigned char *blob,
163                                               size_t len, void **handler_ctx,
164                                               int *matchcount,
165                                               const UI_METHOD *ui_method,
166                                               void *ui_data);
167/*
168 * The eof function should return 1 if there's no more data to be found
169 * with the handler_ctx, otherwise 0.  This is only used when the handler is
170 * marked repeatable.
171 */
172typedef int (*file_eof_fn)(void *handler_ctx);
173/*
174 * The destroy_ctx function is used to destroy the handler_ctx that was
175 * initiated by a repeatable try_decode function.  This is only used when
176 * the handler is marked repeatable.
177 */
178typedef void (*file_destroy_ctx_fn)(void **handler_ctx);
179
180typedef struct file_handler_st {
181    const char *name;
182    file_try_decode_fn try_decode;
183    file_eof_fn eof;
184    file_destroy_ctx_fn destroy_ctx;
185
186    /* flags */
187    int repeatable;
188} FILE_HANDLER;
189
190/*
191 * PKCS#12 decoder.  It operates by decoding all of the blob content,
192 * extracting all the interesting data from it and storing them internally,
193 * then serving them one piece at a time.
194 */
195static OSSL_STORE_INFO *try_decode_PKCS12(const char *pem_name,
196                                          const char *pem_header,
197                                          const unsigned char *blob,
198                                          size_t len, void **pctx,
199                                          int *matchcount,
200                                          const UI_METHOD *ui_method,
201                                          void *ui_data)
202{
203    OSSL_STORE_INFO *store_info = NULL;
204    STACK_OF(OSSL_STORE_INFO) *ctx = *pctx;
205
206    if (ctx == NULL) {
207        /* Initial parsing */
208        PKCS12 *p12;
209        int ok = 0;
210
211        if (pem_name != NULL)
212            /* No match, there is no PEM PKCS12 tag */
213            return NULL;
214
215        if ((p12 = d2i_PKCS12(NULL, &blob, len)) != NULL) {
216            char *pass = NULL;
217            char tpass[PEM_BUFSIZE];
218            EVP_PKEY *pkey = NULL;
219            X509 *cert = NULL;
220            STACK_OF(X509) *chain = NULL;
221
222            *matchcount = 1;
223
224            if (PKCS12_verify_mac(p12, "", 0)
225                || PKCS12_verify_mac(p12, NULL, 0)) {
226                pass = "";
227            } else {
228                if ((pass = file_get_pass(ui_method, tpass, PEM_BUFSIZE,
229                                          "PKCS12 import password",
230                                          ui_data)) == NULL) {
231                    OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS12,
232                                  OSSL_STORE_R_PASSPHRASE_CALLBACK_ERROR);
233                    goto p12_end;
234                }
235                if (!PKCS12_verify_mac(p12, pass, strlen(pass))) {
236                    OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS12,
237                                  OSSL_STORE_R_ERROR_VERIFYING_PKCS12_MAC);
238                    goto p12_end;
239                }
240            }
241
242            if (PKCS12_parse(p12, pass, &pkey, &cert, &chain)) {
243                OSSL_STORE_INFO *osi_pkey = NULL;
244                OSSL_STORE_INFO *osi_cert = NULL;
245                OSSL_STORE_INFO *osi_ca = NULL;
246
247                if ((ctx = sk_OSSL_STORE_INFO_new_null()) != NULL
248                    && (osi_pkey = OSSL_STORE_INFO_new_PKEY(pkey)) != NULL
249                    && sk_OSSL_STORE_INFO_push(ctx, osi_pkey) != 0
250                    && (osi_cert = OSSL_STORE_INFO_new_CERT(cert)) != NULL
251                    && sk_OSSL_STORE_INFO_push(ctx, osi_cert) != 0) {
252                    ok = 1;
253                    osi_pkey = NULL;
254                    osi_cert = NULL;
255
256                    while(sk_X509_num(chain) > 0) {
257                        X509 *ca = sk_X509_value(chain, 0);
258
259                        if ((osi_ca = OSSL_STORE_INFO_new_CERT(ca)) == NULL
260                            || sk_OSSL_STORE_INFO_push(ctx, osi_ca) == 0) {
261                            ok = 0;
262                            break;
263                        }
264                        osi_ca = NULL;
265                        (void)sk_X509_shift(chain);
266                    }
267                }
268                if (!ok) {
269                    OSSL_STORE_INFO_free(osi_ca);
270                    OSSL_STORE_INFO_free(osi_cert);
271                    OSSL_STORE_INFO_free(osi_pkey);
272                    sk_OSSL_STORE_INFO_pop_free(ctx, OSSL_STORE_INFO_free);
273                    EVP_PKEY_free(pkey);
274                    X509_free(cert);
275                    sk_X509_pop_free(chain, X509_free);
276                    ctx = NULL;
277                }
278                *pctx = ctx;
279            }
280        }
281     p12_end:
282        PKCS12_free(p12);
283        if (!ok)
284            return NULL;
285    }
286
287    if (ctx != NULL) {
288        *matchcount = 1;
289        store_info = sk_OSSL_STORE_INFO_shift(ctx);
290    }
291
292    return store_info;
293}
294
295static int eof_PKCS12(void *ctx_)
296{
297    STACK_OF(OSSL_STORE_INFO) *ctx = ctx_;
298
299    return ctx == NULL || sk_OSSL_STORE_INFO_num(ctx) == 0;
300}
301
302static void destroy_ctx_PKCS12(void **pctx)
303{
304    STACK_OF(OSSL_STORE_INFO) *ctx = *pctx;
305
306    sk_OSSL_STORE_INFO_pop_free(ctx, OSSL_STORE_INFO_free);
307    *pctx = NULL;
308}
309
310static FILE_HANDLER PKCS12_handler = {
311    "PKCS12",
312    try_decode_PKCS12,
313    eof_PKCS12,
314    destroy_ctx_PKCS12,
315    1                            /* repeatable */
316};
317
318/*
319 * Encrypted PKCS#8 decoder.  It operates by just decrypting the given blob
320 * into a new blob, which is returned as an EMBEDDED STORE_INFO.  The whole
321 * decoding process will then start over with the new blob.
322 */
323static OSSL_STORE_INFO *try_decode_PKCS8Encrypted(const char *pem_name,
324                                                  const char *pem_header,
325                                                  const unsigned char *blob,
326                                                  size_t len, void **pctx,
327                                                  int *matchcount,
328                                                  const UI_METHOD *ui_method,
329                                                  void *ui_data)
330{
331    X509_SIG *p8 = NULL;
332    char kbuf[PEM_BUFSIZE];
333    char *pass = NULL;
334    const X509_ALGOR *dalg = NULL;
335    const ASN1_OCTET_STRING *doct = NULL;
336    OSSL_STORE_INFO *store_info = NULL;
337    BUF_MEM *mem = NULL;
338    unsigned char *new_data = NULL;
339    int new_data_len;
340
341    if (pem_name != NULL) {
342        if (strcmp(pem_name, PEM_STRING_PKCS8) != 0)
343            return NULL;
344        *matchcount = 1;
345    }
346
347    if ((p8 = d2i_X509_SIG(NULL, &blob, len)) == NULL)
348        return NULL;
349
350    *matchcount = 1;
351
352    if ((mem = BUF_MEM_new()) == NULL) {
353        OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS8ENCRYPTED,
354                      ERR_R_MALLOC_FAILURE);
355        goto nop8;
356    }
357
358    if ((pass = file_get_pass(ui_method, kbuf, PEM_BUFSIZE,
359                              "PKCS8 decrypt password", ui_data)) == NULL) {
360        OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS8ENCRYPTED,
361                      OSSL_STORE_R_BAD_PASSWORD_READ);
362        goto nop8;
363    }
364
365    X509_SIG_get0(p8, &dalg, &doct);
366    if (!PKCS12_pbe_crypt(dalg, pass, strlen(pass), doct->data, doct->length,
367                          &new_data, &new_data_len, 0))
368        goto nop8;
369
370    mem->data = (char *)new_data;
371    mem->max = mem->length = (size_t)new_data_len;
372    X509_SIG_free(p8);
373
374    store_info = ossl_store_info_new_EMBEDDED(PEM_STRING_PKCS8INF, mem);
375    if (store_info == NULL) {
376        OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS8ENCRYPTED,
377                      ERR_R_MALLOC_FAILURE);
378        goto nop8;
379    }
380
381    return store_info;
382 nop8:
383    X509_SIG_free(p8);
384    BUF_MEM_free(mem);
385    return NULL;
386}
387
388static FILE_HANDLER PKCS8Encrypted_handler = {
389    "PKCS8Encrypted",
390    try_decode_PKCS8Encrypted
391};
392
393/*
394 * Private key decoder.  Decodes all sorts of private keys, both PKCS#8
395 * encoded ones and old style PEM ones (with the key type is encoded into
396 * the PEM name).
397 */
398int pem_check_suffix(const char *pem_str, const char *suffix);
399static OSSL_STORE_INFO *try_decode_PrivateKey(const char *pem_name,
400                                              const char *pem_header,
401                                              const unsigned char *blob,
402                                              size_t len, void **pctx,
403                                              int *matchcount,
404                                              const UI_METHOD *ui_method,
405                                              void *ui_data)
406{
407    OSSL_STORE_INFO *store_info = NULL;
408    EVP_PKEY *pkey = NULL;
409    const EVP_PKEY_ASN1_METHOD *ameth = NULL;
410
411    if (pem_name != NULL) {
412        if (strcmp(pem_name, PEM_STRING_PKCS8INF) == 0) {
413            PKCS8_PRIV_KEY_INFO *p8inf =
414                d2i_PKCS8_PRIV_KEY_INFO(NULL, &blob, len);
415
416            *matchcount = 1;
417            if (p8inf != NULL)
418                pkey = EVP_PKCS82PKEY(p8inf);
419            PKCS8_PRIV_KEY_INFO_free(p8inf);
420        } else {
421            int slen;
422
423            if ((slen = pem_check_suffix(pem_name, "PRIVATE KEY")) > 0
424                && (ameth = EVP_PKEY_asn1_find_str(NULL, pem_name,
425                                                   slen)) != NULL) {
426                *matchcount = 1;
427                pkey = d2i_PrivateKey(ameth->pkey_id, NULL, &blob, len);
428            }
429        }
430    } else {
431        int i;
432#ifndef OPENSSL_NO_ENGINE
433        ENGINE *curengine = ENGINE_get_first();
434
435        while (curengine != NULL) {
436            ENGINE_PKEY_ASN1_METHS_PTR asn1meths =
437                ENGINE_get_pkey_asn1_meths(curengine);
438
439            if (asn1meths != NULL) {
440                const int *nids = NULL;
441                int nids_n = asn1meths(curengine, NULL, &nids, 0);
442
443                for (i = 0; i < nids_n; i++) {
444                    EVP_PKEY_ASN1_METHOD *ameth2 = NULL;
445                    EVP_PKEY *tmp_pkey = NULL;
446                    const unsigned char *tmp_blob = blob;
447
448                    if (!asn1meths(curengine, &ameth2, NULL, nids[i]))
449                        continue;
450                    if (ameth2 == NULL
451                        || ameth2->pkey_flags & ASN1_PKEY_ALIAS)
452                        continue;
453
454                    tmp_pkey = d2i_PrivateKey(ameth2->pkey_id, NULL,
455                                              &tmp_blob, len);
456                    if (tmp_pkey != NULL) {
457                        if (pkey != NULL)
458                            EVP_PKEY_free(tmp_pkey);
459                        else
460                            pkey = tmp_pkey;
461                        (*matchcount)++;
462                    }
463                }
464            }
465            curengine = ENGINE_get_next(curengine);
466        }
467#endif
468
469        for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) {
470            EVP_PKEY *tmp_pkey = NULL;
471            const unsigned char *tmp_blob = blob;
472
473            ameth = EVP_PKEY_asn1_get0(i);
474            if (ameth->pkey_flags & ASN1_PKEY_ALIAS)
475                continue;
476
477            tmp_pkey = d2i_PrivateKey(ameth->pkey_id, NULL, &tmp_blob, len);
478            if (tmp_pkey != NULL) {
479                if (pkey != NULL)
480                    EVP_PKEY_free(tmp_pkey);
481                else
482                    pkey = tmp_pkey;
483                (*matchcount)++;
484            }
485        }
486
487        if (*matchcount > 1) {
488            EVP_PKEY_free(pkey);
489            pkey = NULL;
490        }
491    }
492    if (pkey == NULL)
493        /* No match */
494        return NULL;
495
496    store_info = OSSL_STORE_INFO_new_PKEY(pkey);
497    if (store_info == NULL)
498        EVP_PKEY_free(pkey);
499
500    return store_info;
501}
502
503static FILE_HANDLER PrivateKey_handler = {
504    "PrivateKey",
505    try_decode_PrivateKey
506};
507
508/*
509 * Public key decoder.  Only supports SubjectPublicKeyInfo formatted keys.
510 */
511static OSSL_STORE_INFO *try_decode_PUBKEY(const char *pem_name,
512                                          const char *pem_header,
513                                          const unsigned char *blob,
514                                          size_t len, void **pctx,
515                                          int *matchcount,
516                                          const UI_METHOD *ui_method,
517                                          void *ui_data)
518{
519    OSSL_STORE_INFO *store_info = NULL;
520    EVP_PKEY *pkey = NULL;
521
522    if (pem_name != NULL) {
523        if (strcmp(pem_name, PEM_STRING_PUBLIC) != 0)
524            /* No match */
525            return NULL;
526        *matchcount = 1;
527    }
528
529    if ((pkey = d2i_PUBKEY(NULL, &blob, len)) != NULL) {
530        *matchcount = 1;
531        store_info = OSSL_STORE_INFO_new_PKEY(pkey);
532    }
533
534    return store_info;
535}
536
537static FILE_HANDLER PUBKEY_handler = {
538    "PUBKEY",
539    try_decode_PUBKEY
540};
541
542/*
543 * Key parameter decoder.
544 */
545static OSSL_STORE_INFO *try_decode_params(const char *pem_name,
546                                          const char *pem_header,
547                                          const unsigned char *blob,
548                                          size_t len, void **pctx,
549                                          int *matchcount,
550                                          const UI_METHOD *ui_method,
551                                          void *ui_data)
552{
553    OSSL_STORE_INFO *store_info = NULL;
554    int slen = 0;
555    EVP_PKEY *pkey = NULL;
556    const EVP_PKEY_ASN1_METHOD *ameth = NULL;
557    int ok = 0;
558
559    if (pem_name != NULL) {
560        if ((slen = pem_check_suffix(pem_name, "PARAMETERS")) == 0)
561            return NULL;
562        *matchcount = 1;
563    }
564
565    if (slen > 0) {
566        if ((pkey = EVP_PKEY_new()) == NULL) {
567            OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PARAMS, ERR_R_EVP_LIB);
568            return NULL;
569        }
570
571
572        if (EVP_PKEY_set_type_str(pkey, pem_name, slen)
573            && (ameth = EVP_PKEY_get0_asn1(pkey)) != NULL
574            && ameth->param_decode != NULL
575            && ameth->param_decode(pkey, &blob, len))
576            ok = 1;
577    } else {
578        int i;
579        EVP_PKEY *tmp_pkey = NULL;
580
581        for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) {
582            const unsigned char *tmp_blob = blob;
583
584            if (tmp_pkey == NULL && (tmp_pkey = EVP_PKEY_new()) == NULL) {
585                OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PARAMS, ERR_R_EVP_LIB);
586                break;
587            }
588
589            ameth = EVP_PKEY_asn1_get0(i);
590            if (ameth->pkey_flags & ASN1_PKEY_ALIAS)
591                continue;
592
593            if (EVP_PKEY_set_type(tmp_pkey, ameth->pkey_id)
594                && (ameth = EVP_PKEY_get0_asn1(tmp_pkey)) != NULL
595                && ameth->param_decode != NULL
596                && ameth->param_decode(tmp_pkey, &tmp_blob, len)) {
597                if (pkey != NULL)
598                    EVP_PKEY_free(tmp_pkey);
599                else
600                    pkey = tmp_pkey;
601                tmp_pkey = NULL;
602                (*matchcount)++;
603            }
604        }
605
606        EVP_PKEY_free(tmp_pkey);
607        if (*matchcount == 1) {
608            ok = 1;
609        }
610    }
611
612    if (ok)
613        store_info = OSSL_STORE_INFO_new_PARAMS(pkey);
614    if (store_info == NULL)
615        EVP_PKEY_free(pkey);
616
617    return store_info;
618}
619
620static FILE_HANDLER params_handler = {
621    "params",
622    try_decode_params
623};
624
625/*
626 * X.509 certificate decoder.
627 */
628static OSSL_STORE_INFO *try_decode_X509Certificate(const char *pem_name,
629                                                   const char *pem_header,
630                                                   const unsigned char *blob,
631                                                   size_t len, void **pctx,
632                                                   int *matchcount,
633                                                   const UI_METHOD *ui_method,
634                                                   void *ui_data)
635{
636    OSSL_STORE_INFO *store_info = NULL;
637    X509 *cert = NULL;
638
639    /*
640     * In most cases, we can try to interpret the serialized data as a trusted
641     * cert (X509 + X509_AUX) and fall back to reading it as a normal cert
642     * (just X509), but if the PEM name specifically declares it as a trusted
643     * cert, then no fallback should be engaged.  |ignore_trusted| tells if
644     * the fallback can be used (1) or not (0).
645     */
646    int ignore_trusted = 1;
647
648    if (pem_name != NULL) {
649        if (strcmp(pem_name, PEM_STRING_X509_TRUSTED) == 0)
650            ignore_trusted = 0;
651        else if (strcmp(pem_name, PEM_STRING_X509_OLD) != 0
652                 && strcmp(pem_name, PEM_STRING_X509) != 0)
653            /* No match */
654            return NULL;
655        *matchcount = 1;
656    }
657
658    if ((cert = d2i_X509_AUX(NULL, &blob, len)) != NULL
659        || (ignore_trusted && (cert = d2i_X509(NULL, &blob, len)) != NULL)) {
660        *matchcount = 1;
661        store_info = OSSL_STORE_INFO_new_CERT(cert);
662    }
663
664    if (store_info == NULL)
665        X509_free(cert);
666
667    return store_info;
668}
669
670static FILE_HANDLER X509Certificate_handler = {
671    "X509Certificate",
672    try_decode_X509Certificate
673};
674
675/*
676 * X.509 CRL decoder.
677 */
678static OSSL_STORE_INFO *try_decode_X509CRL(const char *pem_name,
679                                           const char *pem_header,
680                                           const unsigned char *blob,
681                                           size_t len, void **pctx,
682                                           int *matchcount,
683                                           const UI_METHOD *ui_method,
684                                           void *ui_data)
685{
686    OSSL_STORE_INFO *store_info = NULL;
687    X509_CRL *crl = NULL;
688
689    if (pem_name != NULL) {
690        if (strcmp(pem_name, PEM_STRING_X509_CRL) != 0)
691            /* No match */
692            return NULL;
693        *matchcount = 1;
694    }
695
696    if ((crl = d2i_X509_CRL(NULL, &blob, len)) != NULL) {
697        *matchcount = 1;
698        store_info = OSSL_STORE_INFO_new_CRL(crl);
699    }
700
701    if (store_info == NULL)
702        X509_CRL_free(crl);
703
704    return store_info;
705}
706
707static FILE_HANDLER X509CRL_handler = {
708    "X509CRL",
709    try_decode_X509CRL
710};
711
712/*
713 * To finish it all off, we collect all the handlers.
714 */
715static const FILE_HANDLER *file_handlers[] = {
716    &PKCS12_handler,
717    &PKCS8Encrypted_handler,
718    &X509Certificate_handler,
719    &X509CRL_handler,
720    &params_handler,
721    &PUBKEY_handler,
722    &PrivateKey_handler,
723};
724
725
726/*-
727 *  The loader itself
728 *  -----------------
729 */
730
731struct ossl_store_loader_ctx_st {
732    enum {
733        is_raw = 0,
734        is_pem,
735        is_dir
736    } type;
737    int errcnt;
738#define FILE_FLAG_SECMEM         (1<<0)
739    unsigned int flags;
740    union {
741        struct {                 /* Used with is_raw and is_pem */
742            BIO *file;
743
744            /*
745             * The following are used when the handler is marked as
746             * repeatable
747             */
748            const FILE_HANDLER *last_handler;
749            void *last_handler_ctx;
750        } file;
751        struct {                 /* Used with is_dir */
752            OPENSSL_DIR_CTX *ctx;
753            int end_reached;
754            char *uri;
755
756            /*
757             * When a search expression is given, these are filled in.
758             * |search_name| contains the file basename to look for.
759             * The string is exactly 8 characters long.
760             */
761            char search_name[9];
762
763            /*
764             * The directory reading utility we have combines opening with
765             * reading the first name.  To make sure we can detect the end
766             * at the right time, we read early and cache the name.
767             */
768            const char *last_entry;
769            int last_errno;
770        } dir;
771    } _;
772
773    /* Expected object type.  May be unspecified */
774    int expected_type;
775};
776
777static void OSSL_STORE_LOADER_CTX_free(OSSL_STORE_LOADER_CTX *ctx)
778{
779    if (ctx->type == is_dir) {
780        OPENSSL_free(ctx->_.dir.uri);
781    } else {
782        if (ctx->_.file.last_handler != NULL) {
783            ctx->_.file.last_handler->destroy_ctx(&ctx->_.file.last_handler_ctx);
784            ctx->_.file.last_handler_ctx = NULL;
785            ctx->_.file.last_handler = NULL;
786        }
787    }
788    OPENSSL_free(ctx);
789}
790
791static OSSL_STORE_LOADER_CTX *file_open(const OSSL_STORE_LOADER *loader,
792                                        const char *uri,
793                                        const UI_METHOD *ui_method,
794                                        void *ui_data)
795{
796    OSSL_STORE_LOADER_CTX *ctx = NULL;
797    struct stat st;
798    struct {
799        const char *path;
800        unsigned int check_absolute:1;
801    } path_data[2];
802    size_t path_data_n = 0, i;
803    const char *path;
804
805    /*
806     * First step, just take the URI as is.
807     */
808    path_data[path_data_n].check_absolute = 0;
809    path_data[path_data_n++].path = uri;
810
811    /*
812     * Second step, if the URI appears to start with the 'file' scheme,
813     * extract the path and make that the second path to check.
814     * There's a special case if the URI also contains an authority, then
815     * the full URI shouldn't be used as a path anywhere.
816     */
817    if (strncasecmp(uri, "file:", 5) == 0) {
818        const char *p = &uri[5];
819
820        if (strncmp(&uri[5], "//", 2) == 0) {
821            path_data_n--;           /* Invalidate using the full URI */
822            if (strncasecmp(&uri[7], "localhost/", 10) == 0) {
823                p = &uri[16];
824            } else if (uri[7] == '/') {
825                p = &uri[7];
826            } else {
827                OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN,
828                              OSSL_STORE_R_URI_AUTHORITY_UNSUPPORTED);
829                return NULL;
830            }
831        }
832
833        path_data[path_data_n].check_absolute = 1;
834#ifdef _WIN32
835        /* Windows file: URIs with a drive letter start with a / */
836        if (p[0] == '/' && p[2] == ':' && p[3] == '/') {
837            char c = ossl_tolower(p[1]);
838
839            if (c >= 'a' && c <= 'z') {
840                p++;
841                /* We know it's absolute, so no need to check */
842                path_data[path_data_n].check_absolute = 0;
843            }
844        }
845#endif
846        path_data[path_data_n++].path = p;
847    }
848
849
850    for (i = 0, path = NULL; path == NULL && i < path_data_n; i++) {
851        /*
852         * If the scheme "file" was an explicit part of the URI, the path must
853         * be absolute.  So says RFC 8089
854         */
855        if (path_data[i].check_absolute && path_data[i].path[0] != '/') {
856            OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN,
857                          OSSL_STORE_R_PATH_MUST_BE_ABSOLUTE);
858            ERR_add_error_data(1, path_data[i].path);
859            return NULL;
860        }
861
862        if (stat(path_data[i].path, &st) < 0) {
863            SYSerr(SYS_F_STAT, errno);
864            ERR_add_error_data(1, path_data[i].path);
865        } else {
866            path = path_data[i].path;
867        }
868    }
869    if (path == NULL) {
870        return NULL;
871    }
872
873    /* Successfully found a working path, clear possible collected errors */
874    ERR_clear_error();
875
876    ctx = OPENSSL_zalloc(sizeof(*ctx));
877    if (ctx == NULL) {
878        OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN, ERR_R_MALLOC_FAILURE);
879        return NULL;
880    }
881
882    if (S_ISDIR(st.st_mode)) {
883        /*
884         * Try to copy everything, even if we know that some of them must be
885         * NULL for the moment.  This prevents errors in the future, when more
886         * components may be used.
887         */
888        ctx->_.dir.uri = OPENSSL_strdup(uri);
889        ctx->type = is_dir;
890
891        if (ctx->_.dir.uri == NULL)
892            goto err;
893
894        ctx->_.dir.last_entry = OPENSSL_DIR_read(&ctx->_.dir.ctx, path);
895        ctx->_.dir.last_errno = errno;
896        if (ctx->_.dir.last_entry == NULL) {
897            if (ctx->_.dir.last_errno != 0) {
898                char errbuf[256];
899                OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN, ERR_R_SYS_LIB);
900                errno = ctx->_.dir.last_errno;
901                if (openssl_strerror_r(errno, errbuf, sizeof(errbuf)))
902                    ERR_add_error_data(1, errbuf);
903                goto err;
904            }
905            ctx->_.dir.end_reached = 1;
906        }
907    } else {
908        BIO *buff = NULL;
909        char peekbuf[4096] = { 0, };
910
911        if ((buff = BIO_new(BIO_f_buffer())) == NULL
912            || (ctx->_.file.file = BIO_new_file(path, "rb")) == NULL) {
913            BIO_free_all(buff);
914            goto err;
915        }
916
917        ctx->_.file.file = BIO_push(buff, ctx->_.file.file);
918        if (BIO_buffer_peek(ctx->_.file.file, peekbuf, sizeof(peekbuf) - 1) > 0) {
919            peekbuf[sizeof(peekbuf) - 1] = '\0';
920            if (strstr(peekbuf, "-----BEGIN ") != NULL)
921                ctx->type = is_pem;
922        }
923    }
924
925    return ctx;
926 err:
927    OSSL_STORE_LOADER_CTX_free(ctx);
928    return NULL;
929}
930
931static int file_ctrl(OSSL_STORE_LOADER_CTX *ctx, int cmd, va_list args)
932{
933    int ret = 1;
934
935    switch (cmd) {
936    case OSSL_STORE_C_USE_SECMEM:
937        {
938            int on = *(va_arg(args, int *));
939
940            switch (on) {
941            case 0:
942                ctx->flags &= ~FILE_FLAG_SECMEM;
943                break;
944            case 1:
945                ctx->flags |= FILE_FLAG_SECMEM;
946                break;
947            default:
948                OSSL_STOREerr(OSSL_STORE_F_FILE_CTRL,
949                              ERR_R_PASSED_INVALID_ARGUMENT);
950                ret = 0;
951                break;
952            }
953        }
954        break;
955    default:
956        break;
957    }
958
959    return ret;
960}
961
962static int file_expect(OSSL_STORE_LOADER_CTX *ctx, int expected)
963{
964    ctx->expected_type = expected;
965    return 1;
966}
967
968static int file_find(OSSL_STORE_LOADER_CTX *ctx, OSSL_STORE_SEARCH *search)
969{
970    /*
971     * If ctx == NULL, the library is looking to know if this loader supports
972     * the given search type.
973     */
974
975    if (OSSL_STORE_SEARCH_get_type(search) == OSSL_STORE_SEARCH_BY_NAME) {
976        unsigned long hash = 0;
977
978        if (ctx == NULL)
979            return 1;
980
981        if (ctx->type != is_dir) {
982            OSSL_STOREerr(OSSL_STORE_F_FILE_FIND,
983                          OSSL_STORE_R_SEARCH_ONLY_SUPPORTED_FOR_DIRECTORIES);
984            return 0;
985        }
986
987        hash = X509_NAME_hash(OSSL_STORE_SEARCH_get0_name(search));
988        BIO_snprintf(ctx->_.dir.search_name, sizeof(ctx->_.dir.search_name),
989                     "%08lx", hash);
990        return 1;
991    }
992
993    if (ctx != NULL)
994        OSSL_STOREerr(OSSL_STORE_F_FILE_FIND,
995                      OSSL_STORE_R_UNSUPPORTED_SEARCH_TYPE);
996    return 0;
997}
998
999/* Internal function to decode an already opened PEM file */
1000OSSL_STORE_LOADER_CTX *ossl_store_file_attach_pem_bio_int(BIO *bp)
1001{
1002    OSSL_STORE_LOADER_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx));
1003
1004    if (ctx == NULL) {
1005        OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_FILE_ATTACH_PEM_BIO_INT,
1006                      ERR_R_MALLOC_FAILURE);
1007        return NULL;
1008    }
1009
1010    ctx->_.file.file = bp;
1011    ctx->type = is_pem;
1012
1013    return ctx;
1014}
1015
1016static OSSL_STORE_INFO *file_load_try_decode(OSSL_STORE_LOADER_CTX *ctx,
1017                                             const char *pem_name,
1018                                             const char *pem_header,
1019                                             unsigned char *data, size_t len,
1020                                             const UI_METHOD *ui_method,
1021                                             void *ui_data, int *matchcount)
1022{
1023    OSSL_STORE_INFO *result = NULL;
1024    BUF_MEM *new_mem = NULL;
1025    char *new_pem_name = NULL;
1026    int t = 0;
1027
1028 again:
1029    {
1030        size_t i = 0;
1031        void *handler_ctx = NULL;
1032        const FILE_HANDLER **matching_handlers =
1033            OPENSSL_zalloc(sizeof(*matching_handlers)
1034                           * OSSL_NELEM(file_handlers));
1035
1036        if (matching_handlers == NULL) {
1037            OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD_TRY_DECODE,
1038                          ERR_R_MALLOC_FAILURE);
1039            goto err;
1040        }
1041
1042        *matchcount = 0;
1043        for (i = 0; i < OSSL_NELEM(file_handlers); i++) {
1044            const FILE_HANDLER *handler = file_handlers[i];
1045            int try_matchcount = 0;
1046            void *tmp_handler_ctx = NULL;
1047            OSSL_STORE_INFO *tmp_result =
1048                handler->try_decode(pem_name, pem_header, data, len,
1049                                    &tmp_handler_ctx, &try_matchcount,
1050                                    ui_method, ui_data);
1051
1052            if (try_matchcount > 0) {
1053
1054                matching_handlers[*matchcount] = handler;
1055
1056                if (handler_ctx)
1057                    handler->destroy_ctx(&handler_ctx);
1058                handler_ctx = tmp_handler_ctx;
1059
1060                if ((*matchcount += try_matchcount) > 1) {
1061                    /* more than one match => ambiguous, kill any result */
1062                    OSSL_STORE_INFO_free(result);
1063                    OSSL_STORE_INFO_free(tmp_result);
1064                    if (handler->destroy_ctx != NULL)
1065                        handler->destroy_ctx(&handler_ctx);
1066                    handler_ctx = NULL;
1067                    tmp_result = NULL;
1068                    result = NULL;
1069                }
1070                if (result == NULL)
1071                    result = tmp_result;
1072            }
1073        }
1074
1075        if (*matchcount == 1 && matching_handlers[0]->repeatable) {
1076            ctx->_.file.last_handler = matching_handlers[0];
1077            ctx->_.file.last_handler_ctx = handler_ctx;
1078        }
1079
1080        OPENSSL_free(matching_handlers);
1081    }
1082
1083 err:
1084    OPENSSL_free(new_pem_name);
1085    BUF_MEM_free(new_mem);
1086
1087    if (result != NULL
1088        && (t = OSSL_STORE_INFO_get_type(result)) == OSSL_STORE_INFO_EMBEDDED) {
1089        pem_name = new_pem_name =
1090            ossl_store_info_get0_EMBEDDED_pem_name(result);
1091        new_mem = ossl_store_info_get0_EMBEDDED_buffer(result);
1092        data = (unsigned char *)new_mem->data;
1093        len = new_mem->length;
1094        OPENSSL_free(result);
1095        result = NULL;
1096        goto again;
1097    }
1098
1099    if (result != NULL)
1100        ERR_clear_error();
1101
1102    return result;
1103}
1104
1105static OSSL_STORE_INFO *file_load_try_repeat(OSSL_STORE_LOADER_CTX *ctx,
1106                                             const UI_METHOD *ui_method,
1107                                             void *ui_data)
1108{
1109    OSSL_STORE_INFO *result = NULL;
1110    int try_matchcount = 0;
1111
1112    if (ctx->_.file.last_handler != NULL) {
1113        result =
1114            ctx->_.file.last_handler->try_decode(NULL, NULL, NULL, 0,
1115                                                 &ctx->_.file.last_handler_ctx,
1116                                                 &try_matchcount,
1117                                                 ui_method, ui_data);
1118
1119        if (result == NULL) {
1120            ctx->_.file.last_handler->destroy_ctx(&ctx->_.file.last_handler_ctx);
1121            ctx->_.file.last_handler_ctx = NULL;
1122            ctx->_.file.last_handler = NULL;
1123        }
1124    }
1125    return result;
1126}
1127
1128static void pem_free_flag(void *pem_data, int secure, size_t num)
1129{
1130    if (secure)
1131        OPENSSL_secure_clear_free(pem_data, num);
1132    else
1133        OPENSSL_free(pem_data);
1134}
1135static int file_read_pem(BIO *bp, char **pem_name, char **pem_header,
1136                         unsigned char **data, long *len,
1137                         const UI_METHOD *ui_method,
1138                         void *ui_data, int secure)
1139{
1140    int i = secure
1141        ? PEM_read_bio_ex(bp, pem_name, pem_header, data, len,
1142                          PEM_FLAG_SECURE | PEM_FLAG_EAY_COMPATIBLE)
1143        : PEM_read_bio(bp, pem_name, pem_header, data, len);
1144
1145    if (i <= 0)
1146        return 0;
1147
1148    /*
1149     * 10 is the number of characters in "Proc-Type:", which
1150     * PEM_get_EVP_CIPHER_INFO() requires to be present.
1151     * If the PEM header has less characters than that, it's
1152     * not worth spending cycles on it.
1153     */
1154    if (strlen(*pem_header) > 10) {
1155        EVP_CIPHER_INFO cipher;
1156        struct pem_pass_data pass_data;
1157
1158        if (!PEM_get_EVP_CIPHER_INFO(*pem_header, &cipher)
1159            || !file_fill_pem_pass_data(&pass_data, "PEM", ui_method, ui_data)
1160            || !PEM_do_header(&cipher, *data, len, file_get_pem_pass,
1161                              &pass_data)) {
1162            return 0;
1163        }
1164    }
1165    return 1;
1166}
1167
1168static int file_read_asn1(BIO *bp, unsigned char **data, long *len)
1169{
1170    BUF_MEM *mem = NULL;
1171
1172    if (asn1_d2i_read_bio(bp, &mem) < 0)
1173        return 0;
1174
1175    *data = (unsigned char *)mem->data;
1176    *len = (long)mem->length;
1177    OPENSSL_free(mem);
1178
1179    return 1;
1180}
1181
1182static int ends_with_dirsep(const char *uri)
1183{
1184    if (*uri != '\0')
1185        uri += strlen(uri) - 1;
1186#if defined __VMS
1187    if (*uri == ']' || *uri == '>' || *uri == ':')
1188        return 1;
1189#elif defined _WIN32
1190    if (*uri == '\\')
1191        return 1;
1192#endif
1193    return *uri == '/';
1194}
1195
1196static int file_name_to_uri(OSSL_STORE_LOADER_CTX *ctx, const char *name,
1197                            char **data)
1198{
1199    assert(name != NULL);
1200    assert(data != NULL);
1201    {
1202        const char *pathsep = ends_with_dirsep(ctx->_.dir.uri) ? "" : "/";
1203        long calculated_length = strlen(ctx->_.dir.uri) + strlen(pathsep)
1204            + strlen(name) + 1 /* \0 */;
1205
1206        *data = OPENSSL_zalloc(calculated_length);
1207        if (*data == NULL) {
1208            OSSL_STOREerr(OSSL_STORE_F_FILE_NAME_TO_URI, ERR_R_MALLOC_FAILURE);
1209            return 0;
1210        }
1211
1212        OPENSSL_strlcat(*data, ctx->_.dir.uri, calculated_length);
1213        OPENSSL_strlcat(*data, pathsep, calculated_length);
1214        OPENSSL_strlcat(*data, name, calculated_length);
1215    }
1216    return 1;
1217}
1218
1219static int file_name_check(OSSL_STORE_LOADER_CTX *ctx, const char *name)
1220{
1221    const char *p = NULL;
1222
1223    /* If there are no search criteria, all names are accepted */
1224    if (ctx->_.dir.search_name[0] == '\0')
1225        return 1;
1226
1227    /* If the expected type isn't supported, no name is accepted */
1228    if (ctx->expected_type != 0
1229        && ctx->expected_type != OSSL_STORE_INFO_CERT
1230        && ctx->expected_type != OSSL_STORE_INFO_CRL)
1231        return 0;
1232
1233    /*
1234     * First, check the basename
1235     */
1236    if (strncasecmp(name, ctx->_.dir.search_name,
1237                    sizeof(ctx->_.dir.search_name) - 1) != 0
1238        || name[sizeof(ctx->_.dir.search_name) - 1] != '.')
1239        return 0;
1240    p = &name[sizeof(ctx->_.dir.search_name)];
1241
1242    /*
1243     * Then, if the expected type is a CRL, check that the extension starts
1244     * with 'r'
1245     */
1246    if (*p == 'r') {
1247        p++;
1248        if (ctx->expected_type != 0
1249            && ctx->expected_type != OSSL_STORE_INFO_CRL)
1250            return 0;
1251    } else if (ctx->expected_type == OSSL_STORE_INFO_CRL) {
1252        return 0;
1253    }
1254
1255    /*
1256     * Last, check that the rest of the extension is a decimal number, at
1257     * least one digit long.
1258     */
1259    if (!ossl_isdigit(*p))
1260        return 0;
1261    while (ossl_isdigit(*p))
1262        p++;
1263
1264# ifdef __VMS
1265    /*
1266     * One extra step here, check for a possible generation number.
1267     */
1268    if (*p == ';')
1269        for (p++; *p != '\0'; p++)
1270            if (!ossl_isdigit(*p))
1271                break;
1272# endif
1273
1274    /*
1275     * If we've reached the end of the string at this point, we've successfully
1276     * found a fitting file name.
1277     */
1278    return *p == '\0';
1279}
1280
1281static int file_eof(OSSL_STORE_LOADER_CTX *ctx);
1282static int file_error(OSSL_STORE_LOADER_CTX *ctx);
1283static OSSL_STORE_INFO *file_load(OSSL_STORE_LOADER_CTX *ctx,
1284                                  const UI_METHOD *ui_method, void *ui_data)
1285{
1286    OSSL_STORE_INFO *result = NULL;
1287
1288    ctx->errcnt = 0;
1289    ERR_clear_error();
1290
1291    if (ctx->type == is_dir) {
1292        do {
1293            char *newname = NULL;
1294
1295            if (ctx->_.dir.last_entry == NULL) {
1296                if (!ctx->_.dir.end_reached) {
1297                    char errbuf[256];
1298                    assert(ctx->_.dir.last_errno != 0);
1299                    OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD, ERR_R_SYS_LIB);
1300                    errno = ctx->_.dir.last_errno;
1301                    ctx->errcnt++;
1302                    if (openssl_strerror_r(errno, errbuf, sizeof(errbuf)))
1303                        ERR_add_error_data(1, errbuf);
1304                }
1305                return NULL;
1306            }
1307
1308            if (ctx->_.dir.last_entry[0] != '.'
1309                && file_name_check(ctx, ctx->_.dir.last_entry)
1310                && !file_name_to_uri(ctx, ctx->_.dir.last_entry, &newname))
1311                return NULL;
1312
1313            /*
1314             * On the first call (with a NULL context), OPENSSL_DIR_read()
1315             * cares about the second argument.  On the following calls, it
1316             * only cares that it isn't NULL.  Therefore, we can safely give
1317             * it our URI here.
1318             */
1319            ctx->_.dir.last_entry = OPENSSL_DIR_read(&ctx->_.dir.ctx,
1320                                                     ctx->_.dir.uri);
1321            ctx->_.dir.last_errno = errno;
1322            if (ctx->_.dir.last_entry == NULL && ctx->_.dir.last_errno == 0)
1323                ctx->_.dir.end_reached = 1;
1324
1325            if (newname != NULL
1326                && (result = OSSL_STORE_INFO_new_NAME(newname)) == NULL) {
1327                OPENSSL_free(newname);
1328                OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD, ERR_R_OSSL_STORE_LIB);
1329                return NULL;
1330            }
1331        } while (result == NULL && !file_eof(ctx));
1332    } else {
1333        int matchcount = -1;
1334
1335     again:
1336        result = file_load_try_repeat(ctx, ui_method, ui_data);
1337        if (result != NULL)
1338            return result;
1339
1340        if (file_eof(ctx))
1341            return NULL;
1342
1343        do {
1344            char *pem_name = NULL;      /* PEM record name */
1345            char *pem_header = NULL;    /* PEM record header */
1346            unsigned char *data = NULL; /* DER encoded data */
1347            long len = 0;               /* DER encoded data length */
1348
1349            matchcount = -1;
1350            if (ctx->type == is_pem) {
1351                if (!file_read_pem(ctx->_.file.file, &pem_name, &pem_header,
1352                                   &data, &len, ui_method, ui_data,
1353                                   (ctx->flags & FILE_FLAG_SECMEM) != 0)) {
1354                    ctx->errcnt++;
1355                    goto endloop;
1356                }
1357            } else {
1358                if (!file_read_asn1(ctx->_.file.file, &data, &len)) {
1359                    ctx->errcnt++;
1360                    goto endloop;
1361                }
1362            }
1363
1364            result = file_load_try_decode(ctx, pem_name, pem_header, data, len,
1365                                          ui_method, ui_data, &matchcount);
1366
1367            if (result != NULL)
1368                goto endloop;
1369
1370            /*
1371             * If a PEM name matches more than one handler, the handlers are
1372             * badly coded.
1373             */
1374            if (!ossl_assert(pem_name == NULL || matchcount <= 1)) {
1375                ctx->errcnt++;
1376                goto endloop;
1377            }
1378
1379            if (matchcount > 1) {
1380                OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD,
1381                              OSSL_STORE_R_AMBIGUOUS_CONTENT_TYPE);
1382            } else if (matchcount == 1) {
1383                /*
1384                 * If there are other errors on the stack, they already show
1385                 * what the problem is.
1386                 */
1387                if (ERR_peek_error() == 0) {
1388                    OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD,
1389                                  OSSL_STORE_R_UNSUPPORTED_CONTENT_TYPE);
1390                    if (pem_name != NULL)
1391                        ERR_add_error_data(3, "PEM type is '", pem_name, "'");
1392                }
1393            }
1394            if (matchcount > 0)
1395                ctx->errcnt++;
1396
1397         endloop:
1398            pem_free_flag(pem_name, (ctx->flags & FILE_FLAG_SECMEM) != 0, 0);
1399            pem_free_flag(pem_header, (ctx->flags & FILE_FLAG_SECMEM) != 0, 0);
1400            pem_free_flag(data, (ctx->flags & FILE_FLAG_SECMEM) != 0, len);
1401        } while (matchcount == 0 && !file_eof(ctx) && !file_error(ctx));
1402
1403        /* We bail out on ambiguity */
1404        if (matchcount > 1)
1405            return NULL;
1406
1407        if (result != NULL
1408            && ctx->expected_type != 0
1409            && ctx->expected_type != OSSL_STORE_INFO_get_type(result)) {
1410            OSSL_STORE_INFO_free(result);
1411            goto again;
1412        }
1413    }
1414
1415    return result;
1416}
1417
1418static int file_error(OSSL_STORE_LOADER_CTX *ctx)
1419{
1420    return ctx->errcnt > 0;
1421}
1422
1423static int file_eof(OSSL_STORE_LOADER_CTX *ctx)
1424{
1425    if (ctx->type == is_dir)
1426        return ctx->_.dir.end_reached;
1427
1428    if (ctx->_.file.last_handler != NULL
1429        && !ctx->_.file.last_handler->eof(ctx->_.file.last_handler_ctx))
1430        return 0;
1431    return BIO_eof(ctx->_.file.file);
1432}
1433
1434static int file_close(OSSL_STORE_LOADER_CTX *ctx)
1435{
1436    if (ctx->type == is_dir) {
1437        OPENSSL_DIR_end(&ctx->_.dir.ctx);
1438    } else {
1439        BIO_free_all(ctx->_.file.file);
1440    }
1441    OSSL_STORE_LOADER_CTX_free(ctx);
1442    return 1;
1443}
1444
1445int ossl_store_file_detach_pem_bio_int(OSSL_STORE_LOADER_CTX *ctx)
1446{
1447    OSSL_STORE_LOADER_CTX_free(ctx);
1448    return 1;
1449}
1450
1451static OSSL_STORE_LOADER file_loader =
1452    {
1453        "file",
1454        NULL,
1455        file_open,
1456        file_ctrl,
1457        file_expect,
1458        file_find,
1459        file_load,
1460        file_eof,
1461        file_error,
1462        file_close
1463    };
1464
1465static void store_file_loader_deinit(void)
1466{
1467    ossl_store_unregister_loader_int(file_loader.scheme);
1468}
1469
1470int ossl_store_file_loader_init(void)
1471{
1472    int ret = ossl_store_register_loader_int(&file_loader);
1473
1474    OPENSSL_atexit(store_file_loader_deinit);
1475    return ret;
1476}
1477