xref: /freebsd/crypto/openssl/engines/e_loader_attic.c (revision ba3c1f5972d7b90feb6e6da47905ff2757e0fe57)
1 /*
2  * Copyright 2016-2022 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 /* THIS ENGINE IS FOR TESTING PURPOSES ONLY. */
11 
12 /* This file has quite some overlap with providers/implementations/storemgmt/file_store.c */
13 
14 /* We need to use some engine deprecated APIs */
15 #define OPENSSL_SUPPRESS_DEPRECATED
16 
17 #include <string.h>
18 #include <sys/stat.h>
19 #include <ctype.h>
20 #include <assert.h>
21 
22 #include <openssl/bio.h>
23 #include <openssl/dsa.h>         /* For d2i_DSAPrivateKey */
24 #include <openssl/err.h>
25 #include <openssl/evp.h>
26 #include <openssl/pem.h>
27 #include <openssl/pkcs12.h>      /* For the PKCS8 stuff o.O */
28 #include <openssl/rsa.h>         /* For d2i_RSAPrivateKey */
29 #include <openssl/safestack.h>
30 #include <openssl/store.h>
31 #include <openssl/ui.h>
32 #include <openssl/engine.h>
33 #include <openssl/x509.h>        /* For the PKCS8 stuff o.O */
34 #include "internal/asn1.h"       /* For asn1_d2i_read_bio */
35 #include "internal/o_dir.h"
36 #include "internal/cryptlib.h"
37 #include "crypto/ctype.h"        /* For ossl_isdigit */
38 #include "crypto/pem.h"          /* For PVK and "blob" PEM headers */
39 
40 #include "e_loader_attic_err.c"
41 
42 DEFINE_STACK_OF(OSSL_STORE_INFO)
43 
44 #ifdef _WIN32
45 # define stat _stat
46 #endif
47 
48 #ifndef S_ISDIR
49 # define S_ISDIR(a) (((a) & S_IFMT) == S_IFDIR)
50 #endif
51 
52 /*-
53  *  Password prompting
54  *  ------------------
55  */
56 
57 static char *file_get_pass(const UI_METHOD *ui_method, char *pass,
58                            size_t maxsize, const char *desc, const char *info,
59                            void *data)
60 {
61     UI *ui = UI_new();
62     char *prompt = NULL;
63 
64     if (ui == NULL) {
65         ATTICerr(0, ERR_R_MALLOC_FAILURE);
66         return NULL;
67     }
68 
69     if (ui_method != NULL)
70         UI_set_method(ui, ui_method);
71     UI_add_user_data(ui, data);
72 
73     if ((prompt = UI_construct_prompt(ui, desc, info)) == NULL) {
74         ATTICerr(0, ERR_R_MALLOC_FAILURE);
75         pass = NULL;
76     } else if (UI_add_input_string(ui, prompt, UI_INPUT_FLAG_DEFAULT_PWD,
77                                     pass, 0, maxsize - 1) <= 0) {
78         ATTICerr(0, ERR_R_UI_LIB);
79         pass = NULL;
80     } else {
81         switch (UI_process(ui)) {
82         case -2:
83             ATTICerr(0, ATTIC_R_UI_PROCESS_INTERRUPTED_OR_CANCELLED);
84             pass = NULL;
85             break;
86         case -1:
87             ATTICerr(0, ERR_R_UI_LIB);
88             pass = NULL;
89             break;
90         default:
91             break;
92         }
93     }
94 
95     OPENSSL_free(prompt);
96     UI_free(ui);
97     return pass;
98 }
99 
100 struct pem_pass_data {
101     const UI_METHOD *ui_method;
102     void *data;
103     const char *prompt_desc;
104     const char *prompt_info;
105 };
106 
107 static int file_fill_pem_pass_data(struct pem_pass_data *pass_data,
108                                    const char *desc, const char *info,
109                                    const UI_METHOD *ui_method, void *ui_data)
110 {
111     if (pass_data == NULL)
112         return 0;
113     pass_data->ui_method = ui_method;
114     pass_data->data = ui_data;
115     pass_data->prompt_desc = desc;
116     pass_data->prompt_info = info;
117     return 1;
118 }
119 
120 /* This is used anywhere a pem_password_cb is needed */
121 static int file_get_pem_pass(char *buf, int num, int w, void *data)
122 {
123     struct pem_pass_data *pass_data = data;
124     char *pass = file_get_pass(pass_data->ui_method, buf, num,
125                                pass_data->prompt_desc, pass_data->prompt_info,
126                                pass_data->data);
127 
128     return pass == NULL ? 0 : strlen(pass);
129 }
130 
131 /*
132  * Check if |str| ends with |suffix| preceded by a space, and if it does,
133  * return the index of that space.  If there is no such suffix in |str|,
134  * return -1.
135  * For |str| == "FOO BAR" and |suffix| == "BAR", the returned value is 3.
136  */
137 static int check_suffix(const char *str, const char *suffix)
138 {
139     int str_len = strlen(str);
140     int suffix_len = strlen(suffix) + 1;
141     const char *p = NULL;
142 
143     if (suffix_len >= str_len)
144         return -1;
145     p = str + str_len - suffix_len;
146     if (*p != ' '
147         || strcmp(p + 1, suffix) != 0)
148         return -1;
149     return p - str;
150 }
151 
152 /*
153  * EMBEDDED is a special type of OSSL_STORE_INFO, specially for the file
154  * handlers, so we define it internally.  This uses the possibility to
155  * create an OSSL_STORE_INFO with a generic data pointer and arbitrary
156  * type number.
157  *
158  * This is used by a FILE_HANDLER's try_decode function to signal that it
159  * has decoded the incoming blob into a new blob, and that the attempted
160  * decoding should be immediately restarted with the new blob, using the
161  * new PEM name.
162  */
163 /* Negative numbers are never used for public OSSL_STORE_INFO types */
164 #define STORE_INFO_EMBEDDED       -1
165 
166 /* This is the embedded data */
167 struct embedded_st {
168     BUF_MEM *blob;
169     char *pem_name;
170 };
171 
172 /* Helper functions */
173 static struct embedded_st *get0_EMBEDDED(OSSL_STORE_INFO *info)
174 {
175     return OSSL_STORE_INFO_get0_data(STORE_INFO_EMBEDDED, info);
176 }
177 
178 static void store_info_free(OSSL_STORE_INFO *info)
179 {
180     struct embedded_st *data;
181 
182     if (info != NULL && (data = get0_EMBEDDED(info)) != NULL) {
183         BUF_MEM_free(data->blob);
184         OPENSSL_free(data->pem_name);
185         OPENSSL_free(data);
186     }
187     OSSL_STORE_INFO_free(info);
188 }
189 
190 static OSSL_STORE_INFO *new_EMBEDDED(const char *new_pem_name,
191                                      BUF_MEM *embedded)
192 {
193     OSSL_STORE_INFO *info = NULL;
194     struct embedded_st *data = NULL;
195 
196     if ((data = OPENSSL_zalloc(sizeof(*data))) == NULL
197         || (info = OSSL_STORE_INFO_new(STORE_INFO_EMBEDDED, data)) == NULL) {
198         ATTICerr(0, ERR_R_MALLOC_FAILURE);
199         OPENSSL_free(data);
200         return NULL;
201     }
202 
203     data->blob = embedded;
204     data->pem_name =
205         new_pem_name == NULL ? NULL : OPENSSL_strdup(new_pem_name);
206 
207     if (new_pem_name != NULL && data->pem_name == NULL) {
208         ATTICerr(0, ERR_R_MALLOC_FAILURE);
209         store_info_free(info);
210         info = NULL;
211     }
212 
213     return info;
214 }
215 
216 /*-
217  *  The file scheme decoders
218  *  ------------------------
219  *
220  *  Each possible data type has its own decoder, which either operates
221  *  through a given PEM name, or attempts to decode to see if the blob
222  *  it's given is decodable for its data type.  The assumption is that
223  *  only the correct data type will match the content.
224  */
225 
226 /*-
227  * The try_decode function is called to check if the blob of data can
228  * be used by this handler, and if it can, decodes it into a supported
229  * OpenSSL type and returns a OSSL_STORE_INFO with the decoded data.
230  * Input:
231  *    pem_name:     If this blob comes from a PEM file, this holds
232  *                  the PEM name.  If it comes from another type of
233  *                  file, this is NULL.
234  *    pem_header:   If this blob comes from a PEM file, this holds
235  *                  the PEM headers.  If it comes from another type of
236  *                  file, this is NULL.
237  *    blob:         The blob of data to match with what this handler
238  *                  can use.
239  *    len:          The length of the blob.
240  *    handler_ctx:  For a handler marked repeatable, this pointer can
241  *                  be used to create a context for the handler.  IT IS
242  *                  THE HANDLER'S RESPONSIBILITY TO CREATE AND DESTROY
243  *                  THIS CONTEXT APPROPRIATELY, i.e. create on first call
244  *                  and destroy when about to return NULL.
245  *    matchcount:   A pointer to an int to count matches for this data.
246  *                  Usually becomes 0 (no match) or 1 (match!), but may
247  *                  be higher in the (unlikely) event that the data matches
248  *                  more than one possibility.  The int will always be
249  *                  zero when the function is called.
250  *    ui_method:    Application UI method for getting a password, pin
251  *                  or any other interactive data.
252  *    ui_data:      Application data to be passed to ui_method when
253  *                  it's called.
254  *    libctx:       The library context to be used if applicable
255  *    propq:        The property query string for any algorithm fetches
256  * Output:
257  *    a OSSL_STORE_INFO
258  */
259 typedef OSSL_STORE_INFO *(*file_try_decode_fn)(const char *pem_name,
260                                                const char *pem_header,
261                                                const unsigned char *blob,
262                                                size_t len, void **handler_ctx,
263                                                int *matchcount,
264                                                const UI_METHOD *ui_method,
265                                                void *ui_data, const char *uri,
266                                                OSSL_LIB_CTX *libctx,
267                                                const char *propq);
268 /*
269  * The eof function should return 1 if there's no more data to be found
270  * with the handler_ctx, otherwise 0.  This is only used when the handler is
271  * marked repeatable.
272  */
273 typedef int (*file_eof_fn)(void *handler_ctx);
274 /*
275  * The destroy_ctx function is used to destroy the handler_ctx that was
276  * initiated by a repeatable try_decode function.  This is only used when
277  * the handler is marked repeatable.
278  */
279 typedef void (*file_destroy_ctx_fn)(void **handler_ctx);
280 
281 typedef struct file_handler_st {
282     const char *name;
283     file_try_decode_fn try_decode;
284     file_eof_fn eof;
285     file_destroy_ctx_fn destroy_ctx;
286 
287     /* flags */
288     int repeatable;
289 } FILE_HANDLER;
290 
291 /*
292  * PKCS#12 decoder.  It operates by decoding all of the blob content,
293  * extracting all the interesting data from it and storing them internally,
294  * then serving them one piece at a time.
295  */
296 static OSSL_STORE_INFO *try_decode_PKCS12(const char *pem_name,
297                                           const char *pem_header,
298                                           const unsigned char *blob,
299                                           size_t len, void **pctx,
300                                           int *matchcount,
301                                           const UI_METHOD *ui_method,
302                                           void *ui_data, const char *uri,
303                                           OSSL_LIB_CTX *libctx,
304                                           const char *propq)
305 {
306     OSSL_STORE_INFO *store_info = NULL;
307     STACK_OF(OSSL_STORE_INFO) *ctx = *pctx;
308 
309     if (ctx == NULL) {
310         /* Initial parsing */
311         PKCS12 *p12;
312 
313         if (pem_name != NULL)
314             /* No match, there is no PEM PKCS12 tag */
315             return NULL;
316 
317         if ((p12 = d2i_PKCS12(NULL, &blob, len)) != NULL) {
318             char *pass = NULL;
319             char tpass[PEM_BUFSIZE];
320             EVP_PKEY *pkey = NULL;
321             X509 *cert = NULL;
322             STACK_OF(X509) *chain = NULL;
323 
324             *matchcount = 1;
325 
326             if (!PKCS12_mac_present(p12)
327                 || PKCS12_verify_mac(p12, "", 0)
328                 || PKCS12_verify_mac(p12, NULL, 0)) {
329                 pass = "";
330             } else {
331                 if ((pass = file_get_pass(ui_method, tpass, PEM_BUFSIZE,
332                                           "PKCS12 import", uri,
333                                           ui_data)) == NULL) {
334                     ATTICerr(0, ATTIC_R_PASSPHRASE_CALLBACK_ERROR);
335                     goto p12_end;
336                 }
337                 if (!PKCS12_verify_mac(p12, pass, strlen(pass))) {
338                     ATTICerr(0, ATTIC_R_ERROR_VERIFYING_PKCS12_MAC);
339                     goto p12_end;
340                 }
341             }
342 
343             if (PKCS12_parse(p12, pass, &pkey, &cert, &chain)) {
344                 OSSL_STORE_INFO *osi_pkey = NULL;
345                 OSSL_STORE_INFO *osi_cert = NULL;
346                 OSSL_STORE_INFO *osi_ca = NULL;
347                 int ok = 1;
348 
349                 if ((ctx = sk_OSSL_STORE_INFO_new_null()) != NULL) {
350                     if (pkey != NULL) {
351                         if ((osi_pkey = OSSL_STORE_INFO_new_PKEY(pkey)) != NULL
352                             /* clearing pkey here avoids case distinctions */
353                             && (pkey = NULL) == NULL
354                             && sk_OSSL_STORE_INFO_push(ctx, osi_pkey) != 0)
355                             osi_pkey = NULL;
356                         else
357                             ok = 0;
358                     }
359                     if (ok && cert != NULL) {
360                         if ((osi_cert = OSSL_STORE_INFO_new_CERT(cert)) != NULL
361                             /* clearing cert here avoids case distinctions */
362                             && (cert = NULL) == NULL
363                             && sk_OSSL_STORE_INFO_push(ctx, osi_cert) != 0)
364                             osi_cert = NULL;
365                         else
366                             ok = 0;
367                     }
368                     while (ok && sk_X509_num(chain) > 0) {
369                         X509 *ca = sk_X509_value(chain, 0);
370 
371                         if ((osi_ca = OSSL_STORE_INFO_new_CERT(ca)) != NULL
372                             && sk_X509_shift(chain) != NULL
373                             && sk_OSSL_STORE_INFO_push(ctx, osi_ca) != 0)
374                             osi_ca = NULL;
375                         else
376                             ok = 0;
377                     }
378                 }
379                 EVP_PKEY_free(pkey);
380                 X509_free(cert);
381                 sk_X509_pop_free(chain, X509_free);
382                 store_info_free(osi_pkey);
383                 store_info_free(osi_cert);
384                 store_info_free(osi_ca);
385                 if (!ok) {
386                     sk_OSSL_STORE_INFO_pop_free(ctx, store_info_free);
387                     ctx = NULL;
388                 }
389                 *pctx = ctx;
390             }
391         }
392      p12_end:
393         PKCS12_free(p12);
394         if (ctx == NULL)
395             return NULL;
396     }
397 
398     *matchcount = 1;
399     store_info = sk_OSSL_STORE_INFO_shift(ctx);
400     return store_info;
401 }
402 
403 static int eof_PKCS12(void *ctx_)
404 {
405     STACK_OF(OSSL_STORE_INFO) *ctx = ctx_;
406 
407     return ctx == NULL || sk_OSSL_STORE_INFO_num(ctx) == 0;
408 }
409 
410 static void destroy_ctx_PKCS12(void **pctx)
411 {
412     STACK_OF(OSSL_STORE_INFO) *ctx = *pctx;
413 
414     sk_OSSL_STORE_INFO_pop_free(ctx, store_info_free);
415     *pctx = NULL;
416 }
417 
418 static FILE_HANDLER PKCS12_handler = {
419     "PKCS12",
420     try_decode_PKCS12,
421     eof_PKCS12,
422     destroy_ctx_PKCS12,
423     1 /* repeatable */
424 };
425 
426 /*
427  * Encrypted PKCS#8 decoder.  It operates by just decrypting the given blob
428  * into a new blob, which is returned as an EMBEDDED STORE_INFO.  The whole
429  * decoding process will then start over with the new blob.
430  */
431 static OSSL_STORE_INFO *try_decode_PKCS8Encrypted(const char *pem_name,
432                                                   const char *pem_header,
433                                                   const unsigned char *blob,
434                                                   size_t len, void **pctx,
435                                                   int *matchcount,
436                                                   const UI_METHOD *ui_method,
437                                                   void *ui_data,
438                                                   const char *uri,
439                                                   OSSL_LIB_CTX *libctx,
440                                                   const char *propq)
441 {
442     X509_SIG *p8 = NULL;
443     char kbuf[PEM_BUFSIZE];
444     char *pass = NULL;
445     const X509_ALGOR *dalg = NULL;
446     const ASN1_OCTET_STRING *doct = NULL;
447     OSSL_STORE_INFO *store_info = NULL;
448     BUF_MEM *mem = NULL;
449     unsigned char *new_data = NULL;
450     int new_data_len;
451 
452     if (pem_name != NULL) {
453         if (strcmp(pem_name, PEM_STRING_PKCS8) != 0)
454             return NULL;
455         *matchcount = 1;
456     }
457 
458     if ((p8 = d2i_X509_SIG(NULL, &blob, len)) == NULL)
459         return NULL;
460 
461     *matchcount = 1;
462 
463     if ((mem = BUF_MEM_new()) == NULL) {
464         ATTICerr(0, ERR_R_MALLOC_FAILURE);
465         goto nop8;
466     }
467 
468     if ((pass = file_get_pass(ui_method, kbuf, PEM_BUFSIZE,
469                               "PKCS8 decrypt pass phrase", uri,
470                               ui_data)) == NULL) {
471         ATTICerr(0, ATTIC_R_BAD_PASSWORD_READ);
472         goto nop8;
473     }
474 
475     X509_SIG_get0(p8, &dalg, &doct);
476     if (!PKCS12_pbe_crypt(dalg, pass, strlen(pass), doct->data, doct->length,
477                           &new_data, &new_data_len, 0))
478         goto nop8;
479 
480     mem->data = (char *)new_data;
481     mem->max = mem->length = (size_t)new_data_len;
482     X509_SIG_free(p8);
483     p8 = NULL;
484 
485     store_info = new_EMBEDDED(PEM_STRING_PKCS8INF, mem);
486     if (store_info == NULL) {
487         ATTICerr(0, ERR_R_MALLOC_FAILURE);
488         goto nop8;
489     }
490 
491     return store_info;
492  nop8:
493     X509_SIG_free(p8);
494     BUF_MEM_free(mem);
495     return NULL;
496 }
497 
498 static FILE_HANDLER PKCS8Encrypted_handler = {
499     "PKCS8Encrypted",
500     try_decode_PKCS8Encrypted
501 };
502 
503 /*
504  * Private key decoder.  Decodes all sorts of private keys, both PKCS#8
505  * encoded ones and old style PEM ones (with the key type is encoded into
506  * the PEM name).
507  */
508 static OSSL_STORE_INFO *try_decode_PrivateKey(const char *pem_name,
509                                               const char *pem_header,
510                                               const unsigned char *blob,
511                                               size_t len, void **pctx,
512                                               int *matchcount,
513                                               const UI_METHOD *ui_method,
514                                               void *ui_data, const char *uri,
515                                               OSSL_LIB_CTX *libctx,
516                                               const char *propq)
517 {
518     OSSL_STORE_INFO *store_info = NULL;
519     EVP_PKEY *pkey = NULL;
520     const EVP_PKEY_ASN1_METHOD *ameth = NULL;
521 
522     if (pem_name != NULL) {
523         if (strcmp(pem_name, PEM_STRING_PKCS8INF) == 0) {
524             PKCS8_PRIV_KEY_INFO *p8inf =
525                 d2i_PKCS8_PRIV_KEY_INFO(NULL, &blob, len);
526 
527             *matchcount = 1;
528             if (p8inf != NULL)
529                 pkey = EVP_PKCS82PKEY_ex(p8inf, libctx, propq);
530             PKCS8_PRIV_KEY_INFO_free(p8inf);
531         } else {
532             int slen;
533             int pkey_id;
534 
535             if ((slen = check_suffix(pem_name, "PRIVATE KEY")) > 0
536                 && (ameth = EVP_PKEY_asn1_find_str(NULL, pem_name,
537                                                    slen)) != NULL
538                 && EVP_PKEY_asn1_get0_info(&pkey_id, NULL, NULL, NULL, NULL,
539                                            ameth)) {
540                 *matchcount = 1;
541                 pkey = d2i_PrivateKey_ex(pkey_id, NULL, &blob, len,
542                                          libctx, propq);
543             }
544         }
545     } else {
546         int i;
547 #ifndef OPENSSL_NO_ENGINE
548         ENGINE *curengine = ENGINE_get_first();
549 
550         while (curengine != NULL) {
551             ENGINE_PKEY_ASN1_METHS_PTR asn1meths =
552                 ENGINE_get_pkey_asn1_meths(curengine);
553 
554             if (asn1meths != NULL) {
555                 const int *nids = NULL;
556                 int nids_n = asn1meths(curengine, NULL, &nids, 0);
557 
558                 for (i = 0; i < nids_n; i++) {
559                     EVP_PKEY_ASN1_METHOD *ameth2 = NULL;
560                     EVP_PKEY *tmp_pkey = NULL;
561                     const unsigned char *tmp_blob = blob;
562                     int pkey_id, pkey_flags;
563 
564                     if (!asn1meths(curengine, &ameth2, NULL, nids[i])
565                         || !EVP_PKEY_asn1_get0_info(&pkey_id, NULL,
566                                                     &pkey_flags, NULL, NULL,
567                                                     ameth2)
568                         || (pkey_flags & ASN1_PKEY_ALIAS) != 0)
569                         continue;
570 
571                     ERR_set_mark(); /* prevent flooding error queue */
572                     tmp_pkey = d2i_PrivateKey_ex(pkey_id, NULL,
573                                                  &tmp_blob, len,
574                                                  libctx, propq);
575                     if (tmp_pkey != NULL) {
576                         if (pkey != NULL)
577                             EVP_PKEY_free(tmp_pkey);
578                         else
579                             pkey = tmp_pkey;
580                         (*matchcount)++;
581                     }
582                     ERR_pop_to_mark();
583                 }
584             }
585             curengine = ENGINE_get_next(curengine);
586         }
587 #endif
588 
589         for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) {
590             EVP_PKEY *tmp_pkey = NULL;
591             const unsigned char *tmp_blob = blob;
592             int pkey_id, pkey_flags;
593 
594             ameth = EVP_PKEY_asn1_get0(i);
595             if (!EVP_PKEY_asn1_get0_info(&pkey_id, NULL, &pkey_flags, NULL,
596                                          NULL, ameth)
597                 || (pkey_flags & ASN1_PKEY_ALIAS) != 0)
598                 continue;
599 
600             ERR_set_mark(); /* prevent flooding error queue */
601             tmp_pkey = d2i_PrivateKey_ex(pkey_id, NULL, &tmp_blob, len,
602                                          libctx, propq);
603             if (tmp_pkey != NULL) {
604                 if (pkey != NULL)
605                     EVP_PKEY_free(tmp_pkey);
606                 else
607                     pkey = tmp_pkey;
608                 (*matchcount)++;
609             }
610             ERR_pop_to_mark();
611         }
612 
613         if (*matchcount > 1) {
614             EVP_PKEY_free(pkey);
615             pkey = NULL;
616         }
617     }
618     if (pkey == NULL)
619         /* No match */
620         return NULL;
621 
622     store_info = OSSL_STORE_INFO_new_PKEY(pkey);
623     if (store_info == NULL)
624         EVP_PKEY_free(pkey);
625 
626     return store_info;
627 }
628 
629 static FILE_HANDLER PrivateKey_handler = {
630     "PrivateKey",
631     try_decode_PrivateKey
632 };
633 
634 /*
635  * Public key decoder.  Only supports SubjectPublicKeyInfo formatted keys.
636  */
637 static OSSL_STORE_INFO *try_decode_PUBKEY(const char *pem_name,
638                                           const char *pem_header,
639                                           const unsigned char *blob,
640                                           size_t len, void **pctx,
641                                           int *matchcount,
642                                           const UI_METHOD *ui_method,
643                                           void *ui_data, const char *uri,
644                                           OSSL_LIB_CTX *libctx,
645                                           const char *propq)
646 {
647     OSSL_STORE_INFO *store_info = NULL;
648     EVP_PKEY *pkey = NULL;
649 
650     if (pem_name != NULL) {
651         if (strcmp(pem_name, PEM_STRING_PUBLIC) != 0)
652             /* No match */
653             return NULL;
654         *matchcount = 1;
655     }
656 
657     if ((pkey = d2i_PUBKEY(NULL, &blob, len)) != NULL) {
658         *matchcount = 1;
659         store_info = OSSL_STORE_INFO_new_PUBKEY(pkey);
660     }
661 
662     return store_info;
663 }
664 
665 static FILE_HANDLER PUBKEY_handler = {
666     "PUBKEY",
667     try_decode_PUBKEY
668 };
669 
670 /*
671  * Key parameter decoder.
672  */
673 static OSSL_STORE_INFO *try_decode_params(const char *pem_name,
674                                           const char *pem_header,
675                                           const unsigned char *blob,
676                                           size_t len, void **pctx,
677                                           int *matchcount,
678                                           const UI_METHOD *ui_method,
679                                           void *ui_data, const char *uri,
680                                           OSSL_LIB_CTX *libctx,
681                                           const char *propq)
682 {
683     OSSL_STORE_INFO *store_info = NULL;
684     EVP_PKEY *pkey = NULL;
685     const EVP_PKEY_ASN1_METHOD *ameth = NULL;
686 
687     if (pem_name != NULL) {
688         int slen;
689         int pkey_id;
690 
691         if ((slen = check_suffix(pem_name, "PARAMETERS")) > 0
692             && (ameth = EVP_PKEY_asn1_find_str(NULL, pem_name, slen)) != NULL
693             && EVP_PKEY_asn1_get0_info(&pkey_id, NULL, NULL, NULL, NULL,
694                                        ameth)) {
695             *matchcount = 1;
696             pkey = d2i_KeyParams(pkey_id, NULL, &blob, len);
697         }
698     } else {
699         int i;
700 
701         for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) {
702             EVP_PKEY *tmp_pkey = NULL;
703             const unsigned char *tmp_blob = blob;
704             int pkey_id, pkey_flags;
705 
706             ameth = EVP_PKEY_asn1_get0(i);
707             if (!EVP_PKEY_asn1_get0_info(&pkey_id, NULL, &pkey_flags, NULL,
708                                          NULL, ameth)
709                 || (pkey_flags & ASN1_PKEY_ALIAS) != 0)
710                 continue;
711 
712             ERR_set_mark(); /* prevent flooding error queue */
713 
714             tmp_pkey = d2i_KeyParams(pkey_id, NULL, &tmp_blob, len);
715 
716             if (tmp_pkey != NULL) {
717                 if (pkey != NULL)
718                     EVP_PKEY_free(tmp_pkey);
719                 else
720                     pkey = tmp_pkey;
721                 (*matchcount)++;
722             }
723             ERR_pop_to_mark();
724         }
725 
726         if (*matchcount > 1) {
727             EVP_PKEY_free(pkey);
728             pkey = NULL;
729         }
730     }
731     if (pkey == NULL)
732         /* No match */
733         return NULL;
734 
735     store_info = OSSL_STORE_INFO_new_PARAMS(pkey);
736     if (store_info == NULL)
737         EVP_PKEY_free(pkey);
738 
739     return store_info;
740 }
741 
742 static FILE_HANDLER params_handler = {
743     "params",
744     try_decode_params
745 };
746 
747 /*
748  * X.509 certificate decoder.
749  */
750 static OSSL_STORE_INFO *try_decode_X509Certificate(const char *pem_name,
751                                                    const char *pem_header,
752                                                    const unsigned char *blob,
753                                                    size_t len, void **pctx,
754                                                    int *matchcount,
755                                                    const UI_METHOD *ui_method,
756                                                    void *ui_data,
757                                                    const char *uri,
758                                                    OSSL_LIB_CTX *libctx,
759                                                    const char *propq)
760 {
761     OSSL_STORE_INFO *store_info = NULL;
762     X509 *cert = NULL;
763 
764     /*
765      * In most cases, we can try to interpret the serialized data as a trusted
766      * cert (X509 + X509_AUX) and fall back to reading it as a normal cert
767      * (just X509), but if the PEM name specifically declares it as a trusted
768      * cert, then no fallback should be engaged.  |ignore_trusted| tells if
769      * the fallback can be used (1) or not (0).
770      */
771     int ignore_trusted = 1;
772 
773     if (pem_name != NULL) {
774         if (strcmp(pem_name, PEM_STRING_X509_TRUSTED) == 0)
775             ignore_trusted = 0;
776         else if (strcmp(pem_name, PEM_STRING_X509_OLD) != 0
777                  && strcmp(pem_name, PEM_STRING_X509) != 0)
778             /* No match */
779             return NULL;
780         *matchcount = 1;
781     }
782 
783     cert = X509_new_ex(libctx, propq);
784     if (cert == NULL)
785         return NULL;
786 
787     if ((d2i_X509_AUX(&cert, &blob, len)) != NULL
788         || (ignore_trusted && (d2i_X509(&cert, &blob, len)) != NULL)) {
789         *matchcount = 1;
790         store_info = OSSL_STORE_INFO_new_CERT(cert);
791     }
792 
793     if (store_info == NULL)
794         X509_free(cert);
795 
796     return store_info;
797 }
798 
799 static FILE_HANDLER X509Certificate_handler = {
800     "X509Certificate",
801     try_decode_X509Certificate
802 };
803 
804 /*
805  * X.509 CRL decoder.
806  */
807 static OSSL_STORE_INFO *try_decode_X509CRL(const char *pem_name,
808                                            const char *pem_header,
809                                            const unsigned char *blob,
810                                            size_t len, void **pctx,
811                                            int *matchcount,
812                                            const UI_METHOD *ui_method,
813                                            void *ui_data, const char *uri,
814                                            OSSL_LIB_CTX *libctx,
815                                            const char *propq)
816 {
817     OSSL_STORE_INFO *store_info = NULL;
818     X509_CRL *crl = NULL;
819 
820     if (pem_name != NULL) {
821         if (strcmp(pem_name, PEM_STRING_X509_CRL) != 0)
822             /* No match */
823             return NULL;
824         *matchcount = 1;
825     }
826 
827     if ((crl = d2i_X509_CRL(NULL, &blob, len)) != NULL) {
828         *matchcount = 1;
829         store_info = OSSL_STORE_INFO_new_CRL(crl);
830     }
831 
832     if (store_info == NULL)
833         X509_CRL_free(crl);
834 
835     return store_info;
836 }
837 
838 static FILE_HANDLER X509CRL_handler = {
839     "X509CRL",
840     try_decode_X509CRL
841 };
842 
843 /*
844  * To finish it all off, we collect all the handlers.
845  */
846 static const FILE_HANDLER *file_handlers[] = {
847     &PKCS12_handler,
848     &PKCS8Encrypted_handler,
849     &X509Certificate_handler,
850     &X509CRL_handler,
851     &params_handler,
852     &PUBKEY_handler,
853     &PrivateKey_handler,
854 };
855 
856 
857 /*-
858  *  The loader itself
859  *  -----------------
860  */
861 
862 struct ossl_store_loader_ctx_st {
863     char *uri;                   /* The URI we currently try to load */
864     enum {
865         is_raw = 0,
866         is_pem,
867         is_dir
868     } type;
869     int errcnt;
870 #define FILE_FLAG_SECMEM         (1<<0)
871 #define FILE_FLAG_ATTACHED       (1<<1)
872     unsigned int flags;
873     union {
874         struct { /* Used with is_raw and is_pem */
875             BIO *file;
876 
877             /*
878              * The following are used when the handler is marked as
879              * repeatable
880              */
881             const FILE_HANDLER *last_handler;
882             void *last_handler_ctx;
883         } file;
884         struct { /* Used with is_dir */
885             OPENSSL_DIR_CTX *ctx;
886             int end_reached;
887 
888             /*
889              * When a search expression is given, these are filled in.
890              * |search_name| contains the file basename to look for.
891              * The string is exactly 8 characters long.
892              */
893             char search_name[9];
894 
895             /*
896              * The directory reading utility we have combines opening with
897              * reading the first name.  To make sure we can detect the end
898              * at the right time, we read early and cache the name.
899              */
900             const char *last_entry;
901             int last_errno;
902         } dir;
903     } _;
904 
905     /* Expected object type.  May be unspecified */
906     int expected_type;
907 
908     OSSL_LIB_CTX *libctx;
909     char *propq;
910 };
911 
912 static void OSSL_STORE_LOADER_CTX_free(OSSL_STORE_LOADER_CTX *ctx)
913 {
914     if (ctx == NULL)
915         return;
916 
917     OPENSSL_free(ctx->propq);
918     OPENSSL_free(ctx->uri);
919     if (ctx->type != is_dir) {
920         if (ctx->_.file.last_handler != NULL) {
921             ctx->_.file.last_handler->destroy_ctx(&ctx->_.file.last_handler_ctx);
922             ctx->_.file.last_handler_ctx = NULL;
923             ctx->_.file.last_handler = NULL;
924         }
925     }
926     OPENSSL_free(ctx);
927 }
928 
929 static int file_find_type(OSSL_STORE_LOADER_CTX *ctx)
930 {
931     BIO *buff = NULL;
932     char peekbuf[4096] = { 0, };
933 
934     if ((buff = BIO_new(BIO_f_buffer())) == NULL)
935         return 0;
936 
937     ctx->_.file.file = BIO_push(buff, ctx->_.file.file);
938     if (BIO_buffer_peek(ctx->_.file.file, peekbuf, sizeof(peekbuf) - 1) > 0) {
939         peekbuf[sizeof(peekbuf) - 1] = '\0';
940         if (strstr(peekbuf, "-----BEGIN ") != NULL)
941             ctx->type = is_pem;
942     }
943     return 1;
944 }
945 
946 static OSSL_STORE_LOADER_CTX *file_open_ex
947     (const OSSL_STORE_LOADER *loader, const char *uri,
948      OSSL_LIB_CTX *libctx, const char *propq,
949      const UI_METHOD *ui_method, void *ui_data)
950 {
951     OSSL_STORE_LOADER_CTX *ctx = NULL;
952     struct stat st;
953     struct {
954         const char *path;
955         unsigned int check_absolute:1;
956     } path_data[2];
957     size_t path_data_n = 0, i;
958     const char *path;
959 
960     /*
961      * First step, just take the URI as is.
962      */
963     path_data[path_data_n].check_absolute = 0;
964     path_data[path_data_n++].path = uri;
965 
966     /*
967      * Second step, if the URI appears to start with the 'file' scheme,
968      * extract the path and make that the second path to check.
969      * There's a special case if the URI also contains an authority, then
970      * the full URI shouldn't be used as a path anywhere.
971      */
972     if (OPENSSL_strncasecmp(uri, "file:", 5) == 0) {
973         const char *p = &uri[5];
974 
975         if (strncmp(&uri[5], "//", 2) == 0) {
976             path_data_n--;           /* Invalidate using the full URI */
977             if (OPENSSL_strncasecmp(&uri[7], "localhost/", 10) == 0) {
978                 p = &uri[16];
979             } else if (uri[7] == '/') {
980                 p = &uri[7];
981             } else {
982                 ATTICerr(0, ATTIC_R_URI_AUTHORITY_UNSUPPORTED);
983                 return NULL;
984             }
985         }
986 
987         path_data[path_data_n].check_absolute = 1;
988 #ifdef _WIN32
989         /* Windows file: URIs with a drive letter start with a / */
990         if (p[0] == '/' && p[2] == ':' && p[3] == '/') {
991             char c = tolower(p[1]);
992 
993             if (c >= 'a' && c <= 'z') {
994                 p++;
995                 /* We know it's absolute, so no need to check */
996                 path_data[path_data_n].check_absolute = 0;
997             }
998         }
999 #endif
1000         path_data[path_data_n++].path = p;
1001     }
1002 
1003 
1004     for (i = 0, path = NULL; path == NULL && i < path_data_n; i++) {
1005         /*
1006          * If the scheme "file" was an explicit part of the URI, the path must
1007          * be absolute.  So says RFC 8089
1008          */
1009         if (path_data[i].check_absolute && path_data[i].path[0] != '/') {
1010             ATTICerr(0, ATTIC_R_PATH_MUST_BE_ABSOLUTE);
1011             ERR_add_error_data(1, path_data[i].path);
1012             return NULL;
1013         }
1014 
1015         if (stat(path_data[i].path, &st) < 0) {
1016             ERR_raise_data(ERR_LIB_SYS, errno,
1017                            "calling stat(%s)",
1018                            path_data[i].path);
1019         } else {
1020             path = path_data[i].path;
1021         }
1022     }
1023     if (path == NULL) {
1024         return NULL;
1025     }
1026 
1027     /* Successfully found a working path */
1028 
1029     ctx = OPENSSL_zalloc(sizeof(*ctx));
1030     if (ctx == NULL) {
1031         ATTICerr(0, ERR_R_MALLOC_FAILURE);
1032         return NULL;
1033     }
1034     ctx->uri = OPENSSL_strdup(uri);
1035     if (ctx->uri == NULL) {
1036         ATTICerr(0, ERR_R_MALLOC_FAILURE);
1037         goto err;
1038     }
1039 
1040     if (S_ISDIR(st.st_mode)) {
1041         ctx->type = is_dir;
1042         ctx->_.dir.last_entry = OPENSSL_DIR_read(&ctx->_.dir.ctx, path);
1043         ctx->_.dir.last_errno = errno;
1044         if (ctx->_.dir.last_entry == NULL) {
1045             if (ctx->_.dir.last_errno != 0) {
1046                 ERR_raise(ERR_LIB_SYS, ctx->_.dir.last_errno);
1047                 goto err;
1048             }
1049             ctx->_.dir.end_reached = 1;
1050         }
1051     } else if ((ctx->_.file.file = BIO_new_file(path, "rb")) == NULL
1052                || !file_find_type(ctx)) {
1053         BIO_free_all(ctx->_.file.file);
1054         goto err;
1055     }
1056     if (propq != NULL) {
1057         ctx->propq = OPENSSL_strdup(propq);
1058         if (ctx->propq == NULL) {
1059             ATTICerr(0, ERR_R_MALLOC_FAILURE);
1060             goto err;
1061         }
1062     }
1063     ctx->libctx = libctx;
1064 
1065     return ctx;
1066  err:
1067     OSSL_STORE_LOADER_CTX_free(ctx);
1068     return NULL;
1069 }
1070 
1071 static OSSL_STORE_LOADER_CTX *file_open
1072     (const OSSL_STORE_LOADER *loader, const char *uri,
1073      const UI_METHOD *ui_method, void *ui_data)
1074 {
1075     return file_open_ex(loader, uri, NULL, NULL, ui_method, ui_data);
1076 }
1077 
1078 static OSSL_STORE_LOADER_CTX *file_attach
1079     (const OSSL_STORE_LOADER *loader, BIO *bp,
1080      OSSL_LIB_CTX *libctx, const char *propq,
1081      const UI_METHOD *ui_method, void *ui_data)
1082 {
1083     OSSL_STORE_LOADER_CTX *ctx = NULL;
1084 
1085     if ((ctx = OPENSSL_zalloc(sizeof(*ctx))) == NULL
1086         || (propq != NULL && (ctx->propq = OPENSSL_strdup(propq)) == NULL)) {
1087         ATTICerr(0, ERR_R_MALLOC_FAILURE);
1088         OSSL_STORE_LOADER_CTX_free(ctx);
1089         return NULL;
1090     }
1091     ctx->libctx = libctx;
1092     ctx->flags |= FILE_FLAG_ATTACHED;
1093     ctx->_.file.file = bp;
1094     if (!file_find_type(ctx)) {
1095         /* Safety measure */
1096         ctx->_.file.file = NULL;
1097         goto err;
1098     }
1099     return ctx;
1100 err:
1101     OSSL_STORE_LOADER_CTX_free(ctx);
1102     return NULL;
1103 }
1104 
1105 static int file_ctrl(OSSL_STORE_LOADER_CTX *ctx, int cmd, va_list args)
1106 {
1107     int ret = 1;
1108 
1109     switch (cmd) {
1110     case OSSL_STORE_C_USE_SECMEM:
1111         {
1112             int on = *(va_arg(args, int *));
1113 
1114             switch (on) {
1115             case 0:
1116                 ctx->flags &= ~FILE_FLAG_SECMEM;
1117                 break;
1118             case 1:
1119                 ctx->flags |= FILE_FLAG_SECMEM;
1120                 break;
1121             default:
1122                 ATTICerr(0, ERR_R_PASSED_INVALID_ARGUMENT);
1123                 ret = 0;
1124                 break;
1125             }
1126         }
1127         break;
1128     default:
1129         break;
1130     }
1131 
1132     return ret;
1133 }
1134 
1135 static int file_expect(OSSL_STORE_LOADER_CTX *ctx, int expected)
1136 {
1137     ctx->expected_type = expected;
1138     return 1;
1139 }
1140 
1141 static int file_find(OSSL_STORE_LOADER_CTX *ctx,
1142                      const OSSL_STORE_SEARCH *search)
1143 {
1144     /*
1145      * If ctx == NULL, the library is looking to know if this loader supports
1146      * the given search type.
1147      */
1148 
1149     if (OSSL_STORE_SEARCH_get_type(search) == OSSL_STORE_SEARCH_BY_NAME) {
1150         unsigned long hash = 0;
1151 
1152         if (ctx == NULL)
1153             return 1;
1154 
1155         if (ctx->type != is_dir) {
1156             ATTICerr(0, ATTIC_R_SEARCH_ONLY_SUPPORTED_FOR_DIRECTORIES);
1157             return 0;
1158         }
1159 
1160         hash = X509_NAME_hash_ex(OSSL_STORE_SEARCH_get0_name(search),
1161                                  NULL, NULL, NULL);
1162         BIO_snprintf(ctx->_.dir.search_name, sizeof(ctx->_.dir.search_name),
1163                      "%08lx", hash);
1164         return 1;
1165     }
1166 
1167     if (ctx != NULL)
1168         ATTICerr(0, ATTIC_R_UNSUPPORTED_SEARCH_TYPE);
1169     return 0;
1170 }
1171 
1172 static OSSL_STORE_INFO *file_load_try_decode(OSSL_STORE_LOADER_CTX *ctx,
1173                                              const char *pem_name,
1174                                              const char *pem_header,
1175                                              unsigned char *data, size_t len,
1176                                              const UI_METHOD *ui_method,
1177                                              void *ui_data, int *matchcount)
1178 {
1179     OSSL_STORE_INFO *result = NULL;
1180     BUF_MEM *new_mem = NULL;
1181     char *new_pem_name = NULL;
1182     int t = 0;
1183 
1184  again:
1185     {
1186         size_t i = 0;
1187         void *handler_ctx = NULL;
1188         const FILE_HANDLER **matching_handlers =
1189             OPENSSL_zalloc(sizeof(*matching_handlers)
1190                            * OSSL_NELEM(file_handlers));
1191 
1192         if (matching_handlers == NULL) {
1193             ATTICerr(0, ERR_R_MALLOC_FAILURE);
1194             goto err;
1195         }
1196 
1197         *matchcount = 0;
1198         for (i = 0; i < OSSL_NELEM(file_handlers); i++) {
1199             const FILE_HANDLER *handler = file_handlers[i];
1200             int try_matchcount = 0;
1201             void *tmp_handler_ctx = NULL;
1202             OSSL_STORE_INFO *tmp_result;
1203             unsigned long err;
1204 
1205             ERR_set_mark();
1206             tmp_result =
1207                 handler->try_decode(pem_name, pem_header, data, len,
1208                                     &tmp_handler_ctx, &try_matchcount,
1209                                     ui_method, ui_data, ctx->uri,
1210                                     ctx->libctx, ctx->propq);
1211             /* avoid flooding error queue with low-level ASN.1 parse errors */
1212             err = ERR_peek_last_error();
1213             if (ERR_GET_LIB(err) == ERR_LIB_ASN1
1214                     && ERR_GET_REASON(err) == ERR_R_NESTED_ASN1_ERROR)
1215                 ERR_pop_to_mark();
1216             else
1217                 ERR_clear_last_mark();
1218 
1219             if (try_matchcount > 0) {
1220 
1221                 matching_handlers[*matchcount] = handler;
1222 
1223                 if (handler_ctx)
1224                     handler->destroy_ctx(&handler_ctx);
1225                 handler_ctx = tmp_handler_ctx;
1226 
1227                 if ((*matchcount += try_matchcount) > 1) {
1228                     /* more than one match => ambiguous, kill any result */
1229                     store_info_free(result);
1230                     store_info_free(tmp_result);
1231                     if (handler->destroy_ctx != NULL)
1232                         handler->destroy_ctx(&handler_ctx);
1233                     handler_ctx = NULL;
1234                     tmp_result = NULL;
1235                     result = NULL;
1236                 }
1237                 if (result == NULL)
1238                     result = tmp_result;
1239                 if (result == NULL) /* e.g., PKCS#12 file decryption error */
1240                     break;
1241             }
1242         }
1243 
1244         if (result != NULL
1245                 && *matchcount == 1 && matching_handlers[0]->repeatable) {
1246             ctx->_.file.last_handler = matching_handlers[0];
1247             ctx->_.file.last_handler_ctx = handler_ctx;
1248         }
1249 
1250         OPENSSL_free(matching_handlers);
1251     }
1252 
1253  err:
1254     OPENSSL_free(new_pem_name);
1255     BUF_MEM_free(new_mem);
1256 
1257     if (result != NULL
1258         && (t = OSSL_STORE_INFO_get_type(result)) == STORE_INFO_EMBEDDED) {
1259         struct embedded_st *embedded = get0_EMBEDDED(result);
1260 
1261         /* "steal" the embedded data */
1262         pem_name = new_pem_name = embedded->pem_name;
1263         new_mem = embedded->blob;
1264         data = (unsigned char *)new_mem->data;
1265         len = new_mem->length;
1266         embedded->pem_name = NULL;
1267         embedded->blob = NULL;
1268 
1269         store_info_free(result);
1270         result = NULL;
1271         goto again;
1272     }
1273 
1274     return result;
1275 }
1276 
1277 static OSSL_STORE_INFO *file_load_try_repeat(OSSL_STORE_LOADER_CTX *ctx,
1278                                              const UI_METHOD *ui_method,
1279                                              void *ui_data)
1280 {
1281     OSSL_STORE_INFO *result = NULL;
1282     int try_matchcount = 0;
1283 
1284     if (ctx->_.file.last_handler != NULL) {
1285         result =
1286             ctx->_.file.last_handler->try_decode(NULL, NULL, NULL, 0,
1287                                                  &ctx->_.file.last_handler_ctx,
1288                                                  &try_matchcount,
1289                                                  ui_method, ui_data, ctx->uri,
1290                                                  ctx->libctx, ctx->propq);
1291 
1292         if (result == NULL) {
1293             ctx->_.file.last_handler->destroy_ctx(&ctx->_.file.last_handler_ctx);
1294             ctx->_.file.last_handler_ctx = NULL;
1295             ctx->_.file.last_handler = NULL;
1296         }
1297     }
1298     return result;
1299 }
1300 
1301 static void pem_free_flag(void *pem_data, int secure, size_t num)
1302 {
1303     if (secure)
1304         OPENSSL_secure_clear_free(pem_data, num);
1305     else
1306         OPENSSL_free(pem_data);
1307 }
1308 static int file_read_pem(BIO *bp, char **pem_name, char **pem_header,
1309                          unsigned char **data, long *len,
1310                          const UI_METHOD *ui_method, void *ui_data,
1311                          const char *uri, int secure)
1312 {
1313     int i = secure
1314         ? PEM_read_bio_ex(bp, pem_name, pem_header, data, len,
1315                           PEM_FLAG_SECURE | PEM_FLAG_EAY_COMPATIBLE)
1316         : PEM_read_bio(bp, pem_name, pem_header, data, len);
1317 
1318     if (i <= 0)
1319         return 0;
1320 
1321     /*
1322      * 10 is the number of characters in "Proc-Type:", which
1323      * PEM_get_EVP_CIPHER_INFO() requires to be present.
1324      * If the PEM header has less characters than that, it's
1325      * not worth spending cycles on it.
1326      */
1327     if (strlen(*pem_header) > 10) {
1328         EVP_CIPHER_INFO cipher;
1329         struct pem_pass_data pass_data;
1330 
1331         if (!PEM_get_EVP_CIPHER_INFO(*pem_header, &cipher)
1332             || !file_fill_pem_pass_data(&pass_data, "PEM pass phrase", uri,
1333                                         ui_method, ui_data)
1334             || !PEM_do_header(&cipher, *data, len, file_get_pem_pass,
1335                               &pass_data)) {
1336             return 0;
1337         }
1338     }
1339     return 1;
1340 }
1341 
1342 static OSSL_STORE_INFO *file_try_read_msblob(BIO *bp, int *matchcount)
1343 {
1344     OSSL_STORE_INFO *result = NULL;
1345     int ispub = -1;
1346 
1347     {
1348         unsigned int magic = 0, bitlen = 0;
1349         int isdss = 0;
1350         unsigned char peekbuf[16] = { 0, };
1351         const unsigned char *p = peekbuf;
1352 
1353         if (BIO_buffer_peek(bp, peekbuf, sizeof(peekbuf)) <= 0)
1354             return 0;
1355         if (ossl_do_blob_header(&p, sizeof(peekbuf), &magic, &bitlen,
1356                                  &isdss, &ispub) <= 0)
1357             return 0;
1358     }
1359 
1360     (*matchcount)++;
1361 
1362     {
1363         EVP_PKEY *tmp = ispub
1364             ? b2i_PublicKey_bio(bp)
1365             : b2i_PrivateKey_bio(bp);
1366 
1367         if (tmp == NULL
1368             || (result = OSSL_STORE_INFO_new_PKEY(tmp)) == NULL) {
1369             EVP_PKEY_free(tmp);
1370             return 0;
1371         }
1372     }
1373 
1374     return result;
1375 }
1376 
1377 static OSSL_STORE_INFO *file_try_read_PVK(BIO *bp, const UI_METHOD *ui_method,
1378                                           void *ui_data, const char *uri,
1379                                           int *matchcount)
1380 {
1381     OSSL_STORE_INFO *result = NULL;
1382 
1383     {
1384         unsigned int saltlen = 0, keylen = 0;
1385         unsigned char peekbuf[24] = { 0, };
1386         const unsigned char *p = peekbuf;
1387 
1388         if (BIO_buffer_peek(bp, peekbuf, sizeof(peekbuf)) <= 0)
1389             return 0;
1390         if (!ossl_do_PVK_header(&p, sizeof(peekbuf), 0, &saltlen, &keylen))
1391             return 0;
1392     }
1393 
1394     (*matchcount)++;
1395 
1396     {
1397         EVP_PKEY *tmp = NULL;
1398         struct pem_pass_data pass_data;
1399 
1400         if (!file_fill_pem_pass_data(&pass_data, "PVK pass phrase", uri,
1401                                      ui_method, ui_data)
1402             || (tmp = b2i_PVK_bio(bp, file_get_pem_pass, &pass_data)) == NULL
1403             || (result = OSSL_STORE_INFO_new_PKEY(tmp)) == NULL) {
1404             EVP_PKEY_free(tmp);
1405             return 0;
1406         }
1407     }
1408 
1409     return result;
1410 }
1411 
1412 static int file_read_asn1(BIO *bp, unsigned char **data, long *len)
1413 {
1414     BUF_MEM *mem = NULL;
1415 
1416     if (asn1_d2i_read_bio(bp, &mem) < 0)
1417         return 0;
1418 
1419     *data = (unsigned char *)mem->data;
1420     *len = (long)mem->length;
1421     OPENSSL_free(mem);
1422 
1423     return 1;
1424 }
1425 
1426 static int file_name_to_uri(OSSL_STORE_LOADER_CTX *ctx, const char *name,
1427                             char **data)
1428 {
1429     assert(name != NULL);
1430     assert(data != NULL);
1431     {
1432         const char *pathsep = ossl_ends_with_dirsep(ctx->uri) ? "" : "/";
1433         long calculated_length = strlen(ctx->uri) + strlen(pathsep)
1434             + strlen(name) + 1 /* \0 */;
1435 
1436         *data = OPENSSL_zalloc(calculated_length);
1437         if (*data == NULL) {
1438             ATTICerr(0, ERR_R_MALLOC_FAILURE);
1439             return 0;
1440         }
1441 
1442         OPENSSL_strlcat(*data, ctx->uri, calculated_length);
1443         OPENSSL_strlcat(*data, pathsep, calculated_length);
1444         OPENSSL_strlcat(*data, name, calculated_length);
1445     }
1446     return 1;
1447 }
1448 
1449 static int file_name_check(OSSL_STORE_LOADER_CTX *ctx, const char *name)
1450 {
1451     const char *p = NULL;
1452     size_t len = strlen(ctx->_.dir.search_name);
1453 
1454     /* If there are no search criteria, all names are accepted */
1455     if (ctx->_.dir.search_name[0] == '\0')
1456         return 1;
1457 
1458     /* If the expected type isn't supported, no name is accepted */
1459     if (ctx->expected_type != 0
1460         && ctx->expected_type != OSSL_STORE_INFO_CERT
1461         && ctx->expected_type != OSSL_STORE_INFO_CRL)
1462         return 0;
1463 
1464     /*
1465      * First, check the basename
1466      */
1467     if (OPENSSL_strncasecmp(name, ctx->_.dir.search_name, len) != 0
1468         || name[len] != '.')
1469         return 0;
1470     p = &name[len + 1];
1471 
1472     /*
1473      * Then, if the expected type is a CRL, check that the extension starts
1474      * with 'r'
1475      */
1476     if (*p == 'r') {
1477         p++;
1478         if (ctx->expected_type != 0
1479             && ctx->expected_type != OSSL_STORE_INFO_CRL)
1480             return 0;
1481     } else if (ctx->expected_type == OSSL_STORE_INFO_CRL) {
1482         return 0;
1483     }
1484 
1485     /*
1486      * Last, check that the rest of the extension is a decimal number, at
1487      * least one digit long.
1488      */
1489     if (!isdigit(*p))
1490         return 0;
1491     while (isdigit(*p))
1492         p++;
1493 
1494 #ifdef __VMS
1495     /*
1496      * One extra step here, check for a possible generation number.
1497      */
1498     if (*p == ';')
1499         for (p++; *p != '\0'; p++)
1500             if (!ossl_isdigit(*p))
1501                 break;
1502 #endif
1503 
1504     /*
1505      * If we've reached the end of the string at this point, we've successfully
1506      * found a fitting file name.
1507      */
1508     return *p == '\0';
1509 }
1510 
1511 static int file_eof(OSSL_STORE_LOADER_CTX *ctx);
1512 static int file_error(OSSL_STORE_LOADER_CTX *ctx);
1513 static OSSL_STORE_INFO *file_load(OSSL_STORE_LOADER_CTX *ctx,
1514                                   const UI_METHOD *ui_method,
1515                                   void *ui_data)
1516 {
1517     OSSL_STORE_INFO *result = NULL;
1518 
1519     ctx->errcnt = 0;
1520 
1521     if (ctx->type == is_dir) {
1522         do {
1523             char *newname = NULL;
1524 
1525             if (ctx->_.dir.last_entry == NULL) {
1526                 if (!ctx->_.dir.end_reached) {
1527                     assert(ctx->_.dir.last_errno != 0);
1528                     ERR_raise(ERR_LIB_SYS, ctx->_.dir.last_errno);
1529                     ctx->errcnt++;
1530                 }
1531                 return NULL;
1532             }
1533 
1534             if (ctx->_.dir.last_entry[0] != '.'
1535                 && file_name_check(ctx, ctx->_.dir.last_entry)
1536                 && !file_name_to_uri(ctx, ctx->_.dir.last_entry, &newname))
1537                 return NULL;
1538 
1539             /*
1540              * On the first call (with a NULL context), OPENSSL_DIR_read()
1541              * cares about the second argument.  On the following calls, it
1542              * only cares that it isn't NULL.  Therefore, we can safely give
1543              * it our URI here.
1544              */
1545             ctx->_.dir.last_entry = OPENSSL_DIR_read(&ctx->_.dir.ctx, ctx->uri);
1546             ctx->_.dir.last_errno = errno;
1547             if (ctx->_.dir.last_entry == NULL && ctx->_.dir.last_errno == 0)
1548                 ctx->_.dir.end_reached = 1;
1549 
1550             if (newname != NULL
1551                 && (result = OSSL_STORE_INFO_new_NAME(newname)) == NULL) {
1552                 OPENSSL_free(newname);
1553                 ATTICerr(0, ERR_R_OSSL_STORE_LIB);
1554                 return NULL;
1555             }
1556         } while (result == NULL && !file_eof(ctx));
1557     } else {
1558         int matchcount = -1;
1559 
1560      again:
1561         result = file_load_try_repeat(ctx, ui_method, ui_data);
1562         if (result != NULL)
1563             return result;
1564 
1565         if (file_eof(ctx))
1566             return NULL;
1567 
1568         do {
1569             char *pem_name = NULL;      /* PEM record name */
1570             char *pem_header = NULL;    /* PEM record header */
1571             unsigned char *data = NULL; /* DER encoded data */
1572             long len = 0;               /* DER encoded data length */
1573 
1574             matchcount = -1;
1575             if (ctx->type == is_pem) {
1576                 if (!file_read_pem(ctx->_.file.file, &pem_name, &pem_header,
1577                                    &data, &len, ui_method, ui_data, ctx->uri,
1578                                    (ctx->flags & FILE_FLAG_SECMEM) != 0)) {
1579                     ctx->errcnt++;
1580                     goto endloop;
1581                 }
1582             } else {
1583                 if ((result = file_try_read_msblob(ctx->_.file.file,
1584                                                    &matchcount)) != NULL
1585                     || (result = file_try_read_PVK(ctx->_.file.file,
1586                                                    ui_method, ui_data, ctx->uri,
1587                                                    &matchcount)) != NULL)
1588                     goto endloop;
1589 
1590                 if (!file_read_asn1(ctx->_.file.file, &data, &len)) {
1591                     ctx->errcnt++;
1592                     goto endloop;
1593                 }
1594             }
1595 
1596             result = file_load_try_decode(ctx, pem_name, pem_header, data, len,
1597                                           ui_method, ui_data, &matchcount);
1598 
1599             if (result != NULL)
1600                 goto endloop;
1601 
1602             /*
1603              * If a PEM name matches more than one handler, the handlers are
1604              * badly coded.
1605              */
1606             if (!ossl_assert(pem_name == NULL || matchcount <= 1)) {
1607                 ctx->errcnt++;
1608                 goto endloop;
1609             }
1610 
1611             if (matchcount > 1) {
1612                 ATTICerr(0, ATTIC_R_AMBIGUOUS_CONTENT_TYPE);
1613             } else if (matchcount == 1) {
1614                 /*
1615                  * If there are other errors on the stack, they already show
1616                  * what the problem is.
1617                  */
1618                 if (ERR_peek_error() == 0) {
1619                     ATTICerr(0, ATTIC_R_UNSUPPORTED_CONTENT_TYPE);
1620                     if (pem_name != NULL)
1621                         ERR_add_error_data(3, "PEM type is '", pem_name, "'");
1622                 }
1623             }
1624             if (matchcount > 0)
1625                 ctx->errcnt++;
1626 
1627          endloop:
1628             pem_free_flag(pem_name, (ctx->flags & FILE_FLAG_SECMEM) != 0, 0);
1629             pem_free_flag(pem_header, (ctx->flags & FILE_FLAG_SECMEM) != 0, 0);
1630             pem_free_flag(data, (ctx->flags & FILE_FLAG_SECMEM) != 0, len);
1631         } while (matchcount == 0 && !file_eof(ctx) && !file_error(ctx));
1632 
1633         /* We bail out on ambiguity */
1634         if (matchcount > 1) {
1635             store_info_free(result);
1636             return NULL;
1637         }
1638 
1639         if (result != NULL
1640             && ctx->expected_type != 0
1641             && ctx->expected_type != OSSL_STORE_INFO_get_type(result)) {
1642             store_info_free(result);
1643             goto again;
1644         }
1645     }
1646 
1647     return result;
1648 }
1649 
1650 static int file_error(OSSL_STORE_LOADER_CTX *ctx)
1651 {
1652     return ctx->errcnt > 0;
1653 }
1654 
1655 static int file_eof(OSSL_STORE_LOADER_CTX *ctx)
1656 {
1657     if (ctx->type == is_dir)
1658         return ctx->_.dir.end_reached;
1659 
1660     if (ctx->_.file.last_handler != NULL
1661         && !ctx->_.file.last_handler->eof(ctx->_.file.last_handler_ctx))
1662         return 0;
1663     return BIO_eof(ctx->_.file.file);
1664 }
1665 
1666 static int file_close(OSSL_STORE_LOADER_CTX *ctx)
1667 {
1668     if ((ctx->flags & FILE_FLAG_ATTACHED) == 0) {
1669         if (ctx->type == is_dir)
1670             OPENSSL_DIR_end(&ctx->_.dir.ctx);
1671         else
1672             BIO_free_all(ctx->_.file.file);
1673     } else {
1674         /*
1675          * Because file_attach() called file_find_type(), we know that a
1676          * BIO_f_buffer() has been pushed on top of the regular BIO.
1677          */
1678         BIO *buff = ctx->_.file.file;
1679 
1680         /* Detach buff */
1681         (void)BIO_pop(ctx->_.file.file);
1682         /* Safety measure */
1683         ctx->_.file.file = NULL;
1684 
1685         BIO_free(buff);
1686     }
1687     OSSL_STORE_LOADER_CTX_free(ctx);
1688     return 1;
1689 }
1690 
1691 /*-
1692  * ENGINE management
1693  */
1694 
1695 static const char *loader_attic_id = "loader_attic";
1696 static const char *loader_attic_name = "'file:' loader";
1697 
1698 static OSSL_STORE_LOADER *loader_attic = NULL;
1699 
1700 static int loader_attic_init(ENGINE *e)
1701 {
1702     return 1;
1703 }
1704 
1705 
1706 static int loader_attic_finish(ENGINE *e)
1707 {
1708     return 1;
1709 }
1710 
1711 
1712 static int loader_attic_destroy(ENGINE *e)
1713 {
1714     OSSL_STORE_LOADER *loader = OSSL_STORE_unregister_loader("file");
1715 
1716     if (loader == NULL)
1717         return 0;
1718 
1719     ERR_unload_ATTIC_strings();
1720     OSSL_STORE_LOADER_free(loader);
1721     return 1;
1722 }
1723 
1724 static int bind_loader_attic(ENGINE *e)
1725 {
1726 
1727     /* Ensure the ATTIC error handling is set up on best effort basis */
1728     ERR_load_ATTIC_strings();
1729 
1730     if (/* Create the OSSL_STORE_LOADER */
1731         (loader_attic = OSSL_STORE_LOADER_new(e, "file")) == NULL
1732         || !OSSL_STORE_LOADER_set_open_ex(loader_attic, file_open_ex)
1733         || !OSSL_STORE_LOADER_set_open(loader_attic, file_open)
1734         || !OSSL_STORE_LOADER_set_attach(loader_attic, file_attach)
1735         || !OSSL_STORE_LOADER_set_ctrl(loader_attic, file_ctrl)
1736         || !OSSL_STORE_LOADER_set_expect(loader_attic, file_expect)
1737         || !OSSL_STORE_LOADER_set_find(loader_attic, file_find)
1738         || !OSSL_STORE_LOADER_set_load(loader_attic, file_load)
1739         || !OSSL_STORE_LOADER_set_eof(loader_attic, file_eof)
1740         || !OSSL_STORE_LOADER_set_error(loader_attic, file_error)
1741         || !OSSL_STORE_LOADER_set_close(loader_attic, file_close)
1742         /* Init the engine itself */
1743         || !ENGINE_set_id(e, loader_attic_id)
1744         || !ENGINE_set_name(e, loader_attic_name)
1745         || !ENGINE_set_destroy_function(e, loader_attic_destroy)
1746         || !ENGINE_set_init_function(e, loader_attic_init)
1747         || !ENGINE_set_finish_function(e, loader_attic_finish)
1748         /* Finally, register the method with libcrypto */
1749         || !OSSL_STORE_register_loader(loader_attic)) {
1750         OSSL_STORE_LOADER_free(loader_attic);
1751         loader_attic = NULL;
1752         ATTICerr(0, ATTIC_R_INIT_FAILED);
1753         return 0;
1754     }
1755 
1756     return 1;
1757 }
1758 
1759 #ifdef OPENSSL_NO_DYNAMIC_ENGINE
1760 # error "Only allowed as dynamically shared object"
1761 #endif
1762 
1763 static int bind_helper(ENGINE *e, const char *id)
1764 {
1765     if (id && (strcmp(id, loader_attic_id) != 0))
1766         return 0;
1767     if (!bind_loader_attic(e))
1768         return 0;
1769     return 1;
1770 }
1771 
1772 IMPLEMENT_DYNAMIC_CHECK_FN()
1773     IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
1774