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