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