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