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