STORE 'file' scheme loader: fix try_decode_params() to check ambiguity
[openssl.git] / crypto / store / loader_file.c
1 /*
2  * Copyright 2016-2017 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (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 <string.h>
11 #include <sys/stat.h>
12 #include <assert.h>
13
14 #include <openssl/bio.h>
15 #include <openssl/dsa.h>         /* For d2i_DSAPrivateKey */
16 #include <openssl/err.h>
17 #include <openssl/evp.h>
18 #include <openssl/pem.h>
19 #include <openssl/pkcs12.h>      /* For the PKCS8 stuff o.O */
20 #include <openssl/rsa.h>         /* For d2i_RSAPrivateKey */
21 #include <openssl/safestack.h>
22 #include <openssl/store.h>
23 #include <openssl/ui.h>
24 #include <openssl/x509.h>        /* For the PKCS8 stuff o.O */
25 #include "internal/asn1_int.h"
26 #include "internal/o_dir.h"
27 #include "internal/cryptlib.h"
28 #include "internal/store_int.h"
29 #include "store_locl.h"
30
31 #include "e_os.h"
32
33 /*
34  *  Password prompting
35  */
36
37 static char *file_get_pass(const UI_METHOD *ui_method, char *pass,
38                            size_t maxsize, const char *prompt_info, void *data)
39 {
40     UI *ui = UI_new();
41     char *prompt = NULL;
42
43     if (ui == NULL) {
44         OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, ERR_R_MALLOC_FAILURE);
45         return NULL;
46     }
47
48     if (ui_method != NULL)
49         UI_set_method(ui, ui_method);
50     UI_add_user_data(ui, data);
51
52     if ((prompt = UI_construct_prompt(ui, "pass phrase",
53                                       prompt_info)) == NULL) {
54         OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, ERR_R_MALLOC_FAILURE);
55         pass = NULL;
56     } else if (!UI_add_input_string(ui, prompt, UI_INPUT_FLAG_DEFAULT_PWD,
57                                     pass, 0, maxsize - 1)) {
58         OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, ERR_R_UI_LIB);
59         pass = NULL;
60     } else {
61         switch (UI_process(ui)) {
62         case -2:
63             OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS,
64                           OSSL_STORE_R_UI_PROCESS_INTERRUPTED_OR_CANCELLED);
65             pass = NULL;
66             break;
67         case -1:
68             OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, ERR_R_UI_LIB);
69             pass = NULL;
70             break;
71         default:
72             break;
73         }
74     }
75
76     OPENSSL_free(prompt);
77     UI_free(ui);
78     return pass;
79 }
80
81 struct pem_pass_data {
82     const UI_METHOD *ui_method;
83     void *data;
84     const char *prompt_info;
85 };
86 static int file_fill_pem_pass_data(struct pem_pass_data *pass_data,
87                                    const char *prompt_info,
88                                    const UI_METHOD *ui_method, void *ui_data)
89 {
90     if (pass_data == NULL)
91         return 0;
92     pass_data->ui_method = ui_method;
93     pass_data->data = ui_data;
94     pass_data->prompt_info = prompt_info;
95     return 1;
96 }
97 static int file_get_pem_pass(char *buf, int num, int w, void *data)
98 {
99     struct pem_pass_data *pass_data = data;
100     char *pass = file_get_pass(pass_data->ui_method, buf, num,
101                                pass_data->prompt_info, pass_data->data);
102
103     return pass == NULL ? 0 : strlen(pass);
104 }
105
106 /*
107  *  The file scheme handlers
108  */
109
110 /*-
111  * The try_decode function is called to check if the blob of data can
112  * be used by this handler, and if it can, decodes it into a supported
113  * OpenSSL type and returns a OSSL_STORE_INFO with the decoded data.
114  * Input:
115  *    pem_name:     If this blob comes from a PEM file, this holds
116  *                  the PEM name.  If it comes from another type of
117  *                  file, this is NULL.
118  *    pem_header:   If this blob comes from a PEM file, this holds
119  *                  the PEM headers.  If it comes from another type of
120  *                  file, this is NULL.
121  *    blob:         The blob of data to match with what this handler
122  *                  can use.
123  *    len:          The length of the blob.
124  *    handler_ctx:  For a handler marked repeatable, this pointer can
125  *                  be used to create a context for the handler.  IT IS
126  *                  THE HANDLER'S RESPONSIBILITY TO CREATE AND DESTROY
127  *                  THIS CONTEXT APPROPRIATELY, i.e. create on first call
128  *                  and destroy when about to return NULL.
129  *    matchcount:   A pointer to an int to count matches for this data.
130  *                  Usually becomes 0 (no match) or 1 (match!), but may
131  *                  be higher in the (unlikely) event that the data matches
132  *                  more than one possibility.  The int will always be
133  *                  zero when the function is called.
134  *    ui_method:    Application UI method for getting a password, pin
135  *                  or any other interactive data.
136  *    ui_data:      Application data to be passed to ui_method when
137  *                  it's called.
138  * Output:
139  *    a OSSL_STORE_INFO
140  */
141 typedef OSSL_STORE_INFO *(*file_try_decode_fn)(const char *pem_name,
142                                                const char *pem_header,
143                                                const unsigned char *blob,
144                                                size_t len, void **handler_ctx,
145                                                int *matchcount,
146                                                const UI_METHOD *ui_method,
147                                                void *ui_data);
148 /*
149  * The eof function should return 1 if there's no more data to be found
150  * with the handler_ctx, otherwise 0.  This is only used when the handler is
151  * marked repeatable.
152  */
153 typedef int (*file_eof_fn)(void *handler_ctx);
154 /*
155  * The destroy_ctx function is used to destroy the handler_ctx that was
156  * intiated by a repeatable try_decode fuction.  This is only used when
157  * the handler is marked repeatable.
158  */
159 typedef void (*file_destroy_ctx_fn)(void **handler_ctx);
160
161 typedef struct file_handler_st {
162     const char *name;
163     file_try_decode_fn try_decode;
164     file_eof_fn eof;
165     file_destroy_ctx_fn destroy_ctx;
166
167     /* flags */
168     int repeatable;
169 } FILE_HANDLER;
170
171 static OSSL_STORE_INFO *try_decode_PKCS12(const char *pem_name,
172                                           const char *pem_header,
173                                           const unsigned char *blob,
174                                           size_t len, void **pctx,
175                                           int *matchcount,
176                                           const UI_METHOD *ui_method,
177                                           void *ui_data)
178 {
179     OSSL_STORE_INFO *store_info = NULL;
180     STACK_OF(OSSL_STORE_INFO) *ctx = *pctx;
181
182     if (ctx == NULL) {
183         /* Initial parsing */
184         PKCS12 *p12;
185         int ok = 0;
186
187         if (pem_name != NULL)
188             /* No match, there is no PEM PKCS12 tag */
189             return NULL;
190
191         if ((p12 = d2i_PKCS12(NULL, &blob, len)) != NULL) {
192             char *pass = NULL;
193             char tpass[PEM_BUFSIZE];
194             EVP_PKEY *pkey = NULL;
195             X509 *cert = NULL;
196             STACK_OF(X509) *chain = NULL;
197
198             *matchcount = 1;
199
200             if (PKCS12_verify_mac(p12, "", 0)
201                 || PKCS12_verify_mac(p12, NULL, 0)) {
202                 pass = "";
203             } else {
204                 if ((pass = file_get_pass(ui_method, tpass, PEM_BUFSIZE,
205                                           "PKCS12 import password",
206                                           ui_data)) == NULL) {
207                     OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS12,
208                                   OSSL_STORE_R_PASSPHRASE_CALLBACK_ERROR);
209                     goto p12_end;
210                 }
211                 if (!PKCS12_verify_mac(p12, pass, strlen(pass))) {
212                     OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS12,
213                                   OSSL_STORE_R_ERROR_VERIFYING_PKCS12_MAC);
214                     goto p12_end;
215                 }
216             }
217
218             if (PKCS12_parse(p12, pass, &pkey, &cert, &chain)) {
219                 OSSL_STORE_INFO *si_pkey = NULL;
220                 OSSL_STORE_INFO *si_cert = NULL;
221                 OSSL_STORE_INFO *si_ca = NULL;
222
223                 if ((ctx = sk_OSSL_STORE_INFO_new_null()) != NULL
224                     && (si_pkey = OSSL_STORE_INFO_new_PKEY(pkey)) != NULL
225                     && sk_OSSL_STORE_INFO_push(ctx, si_pkey) != 0
226                     && (si_cert = OSSL_STORE_INFO_new_CERT(cert)) != NULL
227                     && sk_OSSL_STORE_INFO_push(ctx, si_cert) != 0) {
228                     ok = 1;
229                     si_pkey = NULL;
230                     si_cert = NULL;
231
232                     while(sk_X509_num(chain) > 0) {
233                         X509 *ca = sk_X509_value(chain, 0);
234
235                         if ((si_ca = OSSL_STORE_INFO_new_CERT(ca)) == NULL
236                             || sk_OSSL_STORE_INFO_push(ctx, si_ca) == 0) {
237                             ok = 0;
238                             break;
239                         }
240                         si_ca = NULL;
241                         (void)sk_X509_shift(chain);
242                     }
243                 }
244                 if (!ok) {
245                     OSSL_STORE_INFO_free(si_ca);
246                     OSSL_STORE_INFO_free(si_cert);
247                     OSSL_STORE_INFO_free(si_pkey);
248                     sk_OSSL_STORE_INFO_pop_free(ctx, OSSL_STORE_INFO_free);
249                     EVP_PKEY_free(pkey);
250                     X509_free(cert);
251                     sk_X509_pop_free(chain, X509_free);
252                     ctx = NULL;
253                 }
254                 *pctx = ctx;
255             }
256         }
257      p12_end:
258         PKCS12_free(p12);
259         if (!ok)
260             return NULL;
261     }
262
263     if (ctx != NULL) {
264         *matchcount = 1;
265         store_info = sk_OSSL_STORE_INFO_shift(ctx);
266     }
267
268     return store_info;
269 }
270 static int eof_PKCS12(void *ctx_)
271 {
272     STACK_OF(OSSL_STORE_INFO) *ctx = ctx_;
273
274     return ctx == NULL || sk_OSSL_STORE_INFO_num(ctx) == 0;
275 }
276 static void destroy_ctx_PKCS12(void **pctx)
277 {
278     STACK_OF(OSSL_STORE_INFO) *ctx = *pctx;
279
280     sk_OSSL_STORE_INFO_pop_free(ctx, OSSL_STORE_INFO_free);
281     *pctx = NULL;
282 }
283 static FILE_HANDLER PKCS12_handler = {
284     "PKCS12",
285     try_decode_PKCS12,
286     eof_PKCS12,
287     destroy_ctx_PKCS12,
288     1                            /* repeatable */
289 };
290
291 static OSSL_STORE_INFO *try_decode_PKCS8Encrypted(const char *pem_name,
292                                                   const char *pem_header,
293                                                   const unsigned char *blob,
294                                                   size_t len, void **pctx,
295                                                   int *matchcount,
296                                                   const UI_METHOD *ui_method,
297                                                   void *ui_data)
298 {
299     X509_SIG *p8 = NULL;
300     char kbuf[PEM_BUFSIZE];
301     char *pass = NULL;
302     const X509_ALGOR *dalg = NULL;
303     const ASN1_OCTET_STRING *doct = NULL;
304     OSSL_STORE_INFO *store_info = NULL;
305     BUF_MEM *mem = NULL;
306     unsigned char *new_data = NULL;
307     int new_data_len;
308
309     if (pem_name != NULL) {
310         if (strcmp(pem_name, PEM_STRING_PKCS8) != 0)
311             return NULL;
312         *matchcount = 1;
313     }
314
315     if ((p8 = d2i_X509_SIG(NULL, &blob, len)) == NULL)
316         return NULL;
317
318     *matchcount = 1;
319
320     if ((mem = BUF_MEM_new()) == NULL) {
321         OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS8ENCRYPTED,
322                       ERR_R_MALLOC_FAILURE);
323         goto nop8;
324     }
325
326     if ((pass = file_get_pass(ui_method, kbuf, PEM_BUFSIZE,
327                               "PKCS8 decrypt password", ui_data)) == NULL) {
328         OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS8ENCRYPTED,
329                       OSSL_STORE_R_BAD_PASSWORD_READ);
330         goto nop8;
331     }
332
333     X509_SIG_get0(p8, &dalg, &doct);
334     if (!PKCS12_pbe_crypt(dalg, pass, strlen(pass), doct->data, doct->length,
335                           &new_data, &new_data_len, 0))
336         goto nop8;
337
338     mem->data = (char *)new_data;
339     mem->max = mem->length = (size_t)new_data_len;
340     X509_SIG_free(p8);
341
342     store_info = ossl_store_info_new_EMBEDDED(PEM_STRING_PKCS8INF, mem);
343     if (store_info == NULL) {
344         OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS8ENCRYPTED,
345                       ERR_R_MALLOC_FAILURE);
346         goto nop8;
347     }
348
349     return store_info;
350  nop8:
351     X509_SIG_free(p8);
352     BUF_MEM_free(mem);
353     return NULL;
354 }
355 static FILE_HANDLER PKCS8Encrypted_handler = {
356     "PKCS8Encrypted",
357     try_decode_PKCS8Encrypted
358 };
359
360 int pem_check_suffix(const char *pem_str, const char *suffix);
361 static OSSL_STORE_INFO *try_decode_PrivateKey(const char *pem_name,
362                                               const char *pem_header,
363                                               const unsigned char *blob,
364                                               size_t len, void **pctx,
365                                               int *matchcount,
366                                               const UI_METHOD *ui_method,
367                                               void *ui_data)
368 {
369     OSSL_STORE_INFO *store_info = NULL;
370     EVP_PKEY *pkey = NULL;
371     const EVP_PKEY_ASN1_METHOD *ameth = NULL;
372
373     if (pem_name != NULL) {
374         if (strcmp(pem_name, PEM_STRING_PKCS8INF) == 0) {
375             PKCS8_PRIV_KEY_INFO *p8inf =
376                 d2i_PKCS8_PRIV_KEY_INFO(NULL, &blob, len);
377
378             *matchcount = 1;
379             if (p8inf != NULL)
380                 pkey = EVP_PKCS82PKEY(p8inf);
381             PKCS8_PRIV_KEY_INFO_free(p8inf);
382         } else {
383             int slen;
384
385             if ((slen = pem_check_suffix(pem_name, "PRIVATE KEY")) > 0
386                 && (ameth = EVP_PKEY_asn1_find_str(NULL, pem_name,
387                                                    slen)) != NULL) {
388                 *matchcount = 1;
389                 pkey = d2i_PrivateKey(ameth->pkey_id, NULL, &blob, len);
390             }
391         }
392     } else {
393         int i;
394
395         for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) {
396             EVP_PKEY *tmp_pkey = NULL;
397             const unsigned char *tmp_blob = blob;
398
399             ameth = EVP_PKEY_asn1_get0(i);
400             if (ameth->pkey_flags & ASN1_PKEY_ALIAS)
401                 continue;
402
403             tmp_pkey = d2i_PrivateKey(ameth->pkey_id, NULL, &tmp_blob, len);
404             if (tmp_pkey != NULL) {
405                 if (pkey != NULL)
406                     EVP_PKEY_free(tmp_pkey);
407                 else
408                     pkey = tmp_pkey;
409                 (*matchcount)++;
410             }
411         }
412
413         if (*matchcount > 1) {
414             EVP_PKEY_free(pkey);
415             pkey = NULL;
416         }
417     }
418     if (pkey == NULL)
419         /* No match */
420         return NULL;
421
422     store_info = OSSL_STORE_INFO_new_PKEY(pkey);
423     if (store_info == NULL)
424         EVP_PKEY_free(pkey);
425
426     return store_info;
427 }
428 static FILE_HANDLER PrivateKey_handler = {
429     "PrivateKey",
430     try_decode_PrivateKey
431 };
432
433 static OSSL_STORE_INFO *try_decode_PUBKEY(const char *pem_name,
434                                           const char *pem_header,
435                                           const unsigned char *blob,
436                                           size_t len, void **pctx,
437                                           int *matchcount,
438                                           const UI_METHOD *ui_method,
439                                           void *ui_data)
440 {
441     OSSL_STORE_INFO *store_info = NULL;
442     EVP_PKEY *pkey = NULL;
443
444     if (pem_name != NULL) {
445         if (strcmp(pem_name, PEM_STRING_PUBLIC) != 0)
446             /* No match */
447             return NULL;
448         *matchcount = 1;
449     }
450
451     if ((pkey = d2i_PUBKEY(NULL, &blob, len)) != NULL) {
452         *matchcount = 1;
453         store_info = OSSL_STORE_INFO_new_PKEY(pkey);
454     }
455
456     return store_info;
457 }
458 static FILE_HANDLER PUBKEY_handler = {
459     "PUBKEY",
460     try_decode_PUBKEY
461 };
462
463 static OSSL_STORE_INFO *try_decode_params(const char *pem_name,
464                                           const char *pem_header,
465                                           const unsigned char *blob,
466                                           size_t len, void **pctx,
467                                           int *matchcount,
468                                           const UI_METHOD *ui_method,
469                                           void *ui_data)
470 {
471     OSSL_STORE_INFO *store_info = NULL;
472     int slen = 0;
473     EVP_PKEY *pkey = NULL;
474     const EVP_PKEY_ASN1_METHOD *ameth = NULL;
475     int ok = 0;
476
477     if (pem_name != NULL) {
478         if ((slen = pem_check_suffix(pem_name, "PARAMETERS")) == 0)
479             return NULL;
480         *matchcount = 1;
481     }
482
483     if (slen > 0) {
484         if ((pkey = EVP_PKEY_new()) == NULL) {
485             OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PARAMS, ERR_R_EVP_LIB);
486             return NULL;
487         }
488
489
490         if (EVP_PKEY_set_type_str(pkey, pem_name, slen)
491             && (ameth = EVP_PKEY_get0_asn1(pkey)) != NULL
492             && ameth->param_decode != NULL
493             && ameth->param_decode(pkey, &blob, len))
494             ok = 1;
495     } else {
496         int i;
497         EVP_PKEY *tmp_pkey = NULL;
498
499         for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) {
500             const unsigned char *tmp_blob = blob;
501
502             if (tmp_pkey == NULL && (tmp_pkey = EVP_PKEY_new()) == NULL) {
503                 OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PARAMS, ERR_R_EVP_LIB);
504                 break;
505             }
506
507             ameth = EVP_PKEY_asn1_get0(i);
508             if (ameth->pkey_flags & ASN1_PKEY_ALIAS)
509                 continue;
510
511             if (EVP_PKEY_set_type(tmp_pkey, ameth->pkey_id)
512                 && (ameth = EVP_PKEY_get0_asn1(tmp_pkey)) != NULL
513                 && ameth->param_decode != NULL
514                 && ameth->param_decode(tmp_pkey, &tmp_blob, len)) {
515                 if (pkey != NULL)
516                     EVP_PKEY_free(tmp_pkey);
517                 else
518                     pkey = tmp_pkey;
519                 tmp_pkey = NULL;
520                 (*matchcount)++;
521             }
522         }
523
524         EVP_PKEY_free(tmp_pkey);
525         if (*matchcount == 1) {
526             ok = 1;
527         }
528     }
529
530     if (ok)
531         store_info = OSSL_STORE_INFO_new_PARAMS(pkey);
532     if (store_info == NULL)
533         EVP_PKEY_free(pkey);
534
535     return store_info;
536 }
537 static FILE_HANDLER params_handler = {
538     "params",
539     try_decode_params
540 };
541
542 static OSSL_STORE_INFO *try_decode_X509Certificate(const char *pem_name,
543                                                    const char *pem_header,
544                                                    const unsigned char *blob,
545                                                    size_t len, void **pctx,
546                                                    int *matchcount,
547                                                    const UI_METHOD *ui_method,
548                                                    void *ui_data)
549 {
550     OSSL_STORE_INFO *store_info = NULL;
551     X509 *cert = NULL;
552
553     /*
554      * In most cases, we can try to interpret the serialized data as a trusted
555      * cert (X509 + X509_AUX) and fall back to reading it as a normal cert
556      * (just X509), but if the PEM name specifically declares it as a trusted
557      * cert, then no fallback should be engaged.  |ignore_trusted| tells if
558      * the fallback can be used (1) or not (0).
559      */
560     int ignore_trusted = 1;
561
562     if (pem_name != NULL) {
563         if (strcmp(pem_name, PEM_STRING_X509_TRUSTED) == 0)
564             ignore_trusted = 0;
565         else if (strcmp(pem_name, PEM_STRING_X509_OLD) != 0
566                  && strcmp(pem_name, PEM_STRING_X509) != 0)
567             /* No match */
568             return NULL;
569         *matchcount = 1;
570     }
571
572     if ((cert = d2i_X509_AUX(NULL, &blob, len)) != NULL
573         || (ignore_trusted && (cert = d2i_X509(NULL, &blob, len)) != NULL)) {
574         *matchcount = 1;
575         store_info = OSSL_STORE_INFO_new_CERT(cert);
576     }
577
578     if (store_info == NULL)
579         X509_free(cert);
580
581     return store_info;
582 }
583 static FILE_HANDLER X509Certificate_handler = {
584     "X509Certificate",
585     try_decode_X509Certificate
586 };
587
588 static OSSL_STORE_INFO *try_decode_X509CRL(const char *pem_name,
589                                            const char *pem_header,
590                                            const unsigned char *blob,
591                                            size_t len, void **pctx,
592                                            int *matchcount,
593                                            const UI_METHOD *ui_method,
594                                            void *ui_data)
595 {
596     OSSL_STORE_INFO *store_info = NULL;
597     X509_CRL *crl = NULL;
598
599     if (pem_name != NULL) {
600         if (strcmp(pem_name, PEM_STRING_X509_CRL) != 0)
601             /* No match */
602             return NULL;
603         *matchcount = 1;
604     }
605
606     if ((crl = d2i_X509_CRL(NULL, &blob, len)) != NULL) {
607         *matchcount = 1;
608         store_info = OSSL_STORE_INFO_new_CRL(crl);
609     }
610
611     if (store_info == NULL)
612         X509_CRL_free(crl);
613
614     return store_info;
615 }
616 static FILE_HANDLER X509CRL_handler = {
617     "X509CRL",
618     try_decode_X509CRL
619 };
620
621 static const FILE_HANDLER *file_handlers[] = {
622     &PKCS12_handler,
623     &PKCS8Encrypted_handler,
624     &X509Certificate_handler,
625     &X509CRL_handler,
626     &params_handler,
627     &PUBKEY_handler,
628     &PrivateKey_handler,
629 };
630
631
632 /*
633  *  The loader itself
634  */
635
636 struct ossl_store_loader_ctx_st {
637     enum {
638         is_raw = 0,
639         is_pem,
640         is_dir
641     } type;
642     int errcnt;
643 #define FILE_FLAG_SECMEM         (1<<0)
644     unsigned int flags;
645     union {
646         struct {                 /* Used with is_raw and is_pem */
647             BIO *file;
648
649             /*
650              * The following are used when the handler is marked as
651              * repeatable
652              */
653             const FILE_HANDLER *last_handler;
654             void *last_handler_ctx;
655         } file;
656         struct {                 /* Used with is_dir */
657             OPENSSL_DIR_CTX *ctx;
658             int end_reached;
659             char *uri;
660
661             /*
662              * The directory reading utility we have combines opening with
663              * reading the first name.  To make sure we can detect the end
664              * at the right time, we read early and cache the name.
665              */
666             const char *last_entry;
667             int last_errno;
668         } dir;
669     } _;
670 };
671
672 static void OSSL_STORE_LOADER_CTX_free(OSSL_STORE_LOADER_CTX *ctx)
673 {
674     if (ctx->type == is_dir) {
675         OPENSSL_free(ctx->_.dir.uri);
676     } else {
677         if (ctx->_.file.last_handler != NULL) {
678             ctx->_.file.last_handler->destroy_ctx(&ctx->_.file.last_handler_ctx);
679             ctx->_.file.last_handler_ctx = NULL;
680             ctx->_.file.last_handler = NULL;
681         }
682     }
683     OPENSSL_free(ctx);
684 }
685
686 static OSSL_STORE_LOADER_CTX *file_open(const OSSL_STORE_LOADER *loader,
687                                         const char *uri,
688                                         const UI_METHOD *ui_method,
689                                         void *ui_data)
690 {
691     OSSL_STORE_LOADER_CTX *ctx = NULL;
692     struct stat st;
693     const char *path = NULL;
694
695     if (strncasecmp(uri, "file:", 5) == 0) {
696         if (strncasecmp(&uri[5], "//localhost/", 12) == 0) {
697             path = &uri[16];
698         } else if (strncmp(&uri[5], "///", 3) == 0) {
699             path = &uri[7];
700         } else if (strncmp(&uri[5], "//", 2) != 0) {
701             path = &uri[5];
702         } else {
703             OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN,
704                           OSSL_STORE_R_URI_AUTHORITY_UNSUPPORED);
705             return NULL;
706         }
707
708         /*
709          * If the scheme "file" was an explicit part of the URI, the path must
710          * be absolute.  So says RFC 8089
711          */
712         if (path[0] != '/') {
713             OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN,
714                           OSSL_STORE_R_PATH_MUST_BE_ABSOLUTE);
715             return NULL;
716         }
717
718 #ifdef _WIN32
719         /* Windows file: URIs with a drive letter start with a / */
720         if (path[0] == '/' && path[2] == ':' && path[3] == '/')
721             path++;
722 #endif
723     } else {
724         path = uri;
725     }
726
727
728     if (stat(path, &st) < 0) {
729         SYSerr(SYS_F_STAT, errno);
730         ERR_add_error_data(1, path);
731         return NULL;
732     }
733
734     ctx = OPENSSL_zalloc(sizeof(*ctx));
735     if (ctx == NULL) {
736         OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN, ERR_R_MALLOC_FAILURE);
737         return NULL;
738     }
739
740     if ((st.st_mode & S_IFDIR) == S_IFDIR) {
741         /*
742          * Try to copy everything, even if we know that some of them must be
743          * NULL for the moment.  This prevents errors in the future, when more
744          * components may be used.
745          */
746         ctx->_.dir.uri = OPENSSL_strdup(uri);
747         ctx->type = is_dir;
748
749         if (ctx->_.dir.uri == NULL)
750             goto err;
751
752         ctx->_.dir.last_entry = OPENSSL_DIR_read(&ctx->_.dir.ctx, path);
753         ctx->_.dir.last_errno = errno;
754         if (ctx->_.dir.last_entry == NULL) {
755             if (ctx->_.dir.last_errno != 0) {
756                 char errbuf[256];
757                 errno = ctx->_.dir.last_errno;
758                 openssl_strerror_r(errno, errbuf, sizeof(errbuf));
759                 OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN, ERR_R_SYS_LIB);
760                 ERR_add_error_data(1, errbuf);
761                 goto err;
762             }
763             ctx->_.dir.end_reached = 1;
764         }
765     } else {
766         BIO *buff = NULL;
767         char peekbuf[4096];
768
769         if ((buff = BIO_new(BIO_f_buffer())) == NULL
770             || (ctx->_.file.file = BIO_new_file(path, "rb")) == NULL) {
771             BIO_free_all(buff);
772             goto err;
773         }
774
775         ctx->_.file.file = BIO_push(buff, ctx->_.file.file);
776         if (BIO_buffer_peek(ctx->_.file.file, peekbuf, sizeof(peekbuf)-1) > 0) {
777             peekbuf[sizeof(peekbuf)-1] = '\0';
778             if (strstr(peekbuf, "-----BEGIN ") != NULL)
779                 ctx->type = is_pem;
780         }
781     }
782
783     return ctx;
784  err:
785     OSSL_STORE_LOADER_CTX_free(ctx);
786     return NULL;
787 }
788
789 static int file_ctrl(OSSL_STORE_LOADER_CTX *ctx, int cmd, va_list args)
790 {
791     int ret = 1;
792
793     switch (cmd) {
794     case OSSL_STORE_C_USE_SECMEM:
795         {
796             int on = *(va_arg(args, int *));
797
798             switch (on) {
799             case 0:
800                 ctx->flags &= ~FILE_FLAG_SECMEM;
801                 break;
802             case 1:
803                 ctx->flags |= FILE_FLAG_SECMEM;
804                 break;
805             default:
806                 OSSL_STOREerr(OSSL_STORE_F_FILE_CTRL,
807                               ERR_R_PASSED_INVALID_ARGUMENT);
808                 ret = 0;
809                 break;
810             }
811         }
812         break;
813     default:
814         break;
815     }
816
817     return ret;
818 }
819
820 /* Internal function to decode an already opened PEM file */
821 OSSL_STORE_LOADER_CTX *ossl_store_file_attach_pem_bio_int(BIO *bp)
822 {
823     OSSL_STORE_LOADER_CTX *ctx = OPENSSL_zalloc(sizeof(*ctx));
824
825     if (ctx == NULL) {
826         OSSL_STOREerr(OSSL_STORE_F_OSSL_STORE_FILE_ATTACH_PEM_BIO_INT,
827                       ERR_R_MALLOC_FAILURE);
828         return NULL;
829     }
830
831     ctx->_.file.file = bp;
832     ctx->type = is_pem;
833
834     return ctx;
835 }
836
837 static OSSL_STORE_INFO *file_load_try_decode(OSSL_STORE_LOADER_CTX *ctx,
838                                              const char *pem_name,
839                                              const char *pem_header,
840                                              unsigned char *data, size_t len,
841                                              const UI_METHOD *ui_method,
842                                              void *ui_data, int *matchcount)
843 {
844     OSSL_STORE_INFO *result = NULL;
845     BUF_MEM *new_mem = NULL;
846     char *new_pem_name = NULL;
847     int t = 0;
848
849  again:
850     {
851         size_t i = 0;
852         void *handler_ctx = NULL;
853         const FILE_HANDLER **matching_handlers =
854             OPENSSL_zalloc(sizeof(*matching_handlers)
855                            * OSSL_NELEM(file_handlers));
856
857         if (matching_handlers == NULL) {
858             OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD_TRY_DECODE,
859                           ERR_R_MALLOC_FAILURE);
860             goto err;
861         }
862
863         *matchcount = 0;
864         for (i = 0; i < OSSL_NELEM(file_handlers); i++) {
865             const FILE_HANDLER *handler = file_handlers[i];
866             int try_matchcount = 0;
867             void *tmp_handler_ctx = NULL;
868             OSSL_STORE_INFO *tmp_result =
869                 handler->try_decode(pem_name, pem_header, data, len,
870                                     &tmp_handler_ctx, &try_matchcount,
871                                     ui_method, ui_data);
872
873             if (try_matchcount > 0) {
874                 if (matching_handlers)
875                     matching_handlers[*matchcount] = handler;
876
877                 if (handler_ctx)
878                     handler->destroy_ctx(&handler_ctx);
879                 handler_ctx = tmp_handler_ctx;
880
881                 if ((*matchcount += try_matchcount) > 1) {
882                     /* more than one match => ambiguous, kill any result */
883                     OSSL_STORE_INFO_free(result);
884                     OSSL_STORE_INFO_free(tmp_result);
885                     if (handler->destroy_ctx != NULL)
886                         handler->destroy_ctx(&handler_ctx);
887                     handler_ctx = NULL;
888                     tmp_result = NULL;
889                     result = NULL;
890                 }
891                 if (result == NULL)
892                     result = tmp_result;
893             }
894         }
895
896         if (*matchcount == 1 && matching_handlers[0]->repeatable) {
897             ctx->_.file.last_handler = matching_handlers[0];
898             ctx->_.file.last_handler_ctx = handler_ctx;
899         }
900
901         OPENSSL_free(matching_handlers);
902     }
903
904  err:
905     OPENSSL_free(new_pem_name);
906     BUF_MEM_free(new_mem);
907
908     if (result != NULL
909         && (t = OSSL_STORE_INFO_get_type(result)) == OSSL_STORE_INFO_EMBEDDED) {
910         pem_name = new_pem_name =
911             ossl_store_info_get0_EMBEDDED_pem_name(result);
912         new_mem = ossl_store_info_get0_EMBEDDED_buffer(result);
913         data = (unsigned char *)new_mem->data;
914         len = new_mem->length;
915         OPENSSL_free(result);
916         result = NULL;
917         goto again;
918     }
919
920     if (result != NULL)
921         ERR_clear_error();
922
923     return result;
924 }
925
926 static OSSL_STORE_INFO *file_load_try_repeat(OSSL_STORE_LOADER_CTX *ctx,
927                                              const UI_METHOD *ui_method,
928                                              void *ui_data)
929 {
930     OSSL_STORE_INFO *result = NULL;
931     int try_matchcount = 0;
932
933     if (ctx->_.file.last_handler != NULL) {
934         result =
935             ctx->_.file.last_handler->try_decode(NULL, NULL, NULL, 0,
936                                                  &ctx->_.file.last_handler_ctx,
937                                                  &try_matchcount,
938                                                  ui_method, ui_data);
939
940         if (result == NULL) {
941             ctx->_.file.last_handler->destroy_ctx(&ctx->_.file.last_handler_ctx);
942             ctx->_.file.last_handler_ctx = NULL;
943             ctx->_.file.last_handler = NULL;
944         }
945     }
946     return result;
947 }
948
949 static void pem_free_flag(void *pem_data, int secure)
950 {
951     if (secure)
952         OPENSSL_secure_free(pem_data);
953     else
954         OPENSSL_free(pem_data);
955 }
956 static int file_read_pem(BIO *bp, char **pem_name, char **pem_header,
957                          unsigned char **data, long *len,
958                          const UI_METHOD *ui_method,
959                          void *ui_data, int secure)
960 {
961     int i = secure
962         ? PEM_read_bio_ex(bp, pem_name, pem_header, data, len,
963                           PEM_FLAG_SECURE | PEM_FLAG_EAY_COMPATIBLE)
964         : PEM_read_bio(bp, pem_name, pem_header, data, len);
965
966     if (i <= 0)
967         return 0;
968
969     /*
970      * 10 is the number of characters in "Proc-Type:", which
971      * PEM_get_EVP_CIPHER_INFO() requires to be present.
972      * If the PEM header has less characters than that, it's
973      * not worth spending cycles on it.
974      */
975     if (strlen(*pem_header) > 10) {
976         EVP_CIPHER_INFO cipher;
977         struct pem_pass_data pass_data;
978
979         if (!PEM_get_EVP_CIPHER_INFO(*pem_header, &cipher)
980             || !file_fill_pem_pass_data(&pass_data, "PEM", ui_method, ui_data)
981             || !PEM_do_header(&cipher, *data, len, file_get_pem_pass,
982                               &pass_data)) {
983             return 0;
984         }
985     }
986     return 1;
987 }
988
989 static int file_read_asn1(BIO *bp, unsigned char **data, long *len)
990 {
991     BUF_MEM *mem = NULL;
992
993     if (asn1_d2i_read_bio(bp, &mem) < 0)
994         return 0;
995
996     *data = (unsigned char *)mem->data;
997     *len = (long)mem->length;
998     OPENSSL_free(mem);
999
1000     return 1;
1001 }
1002
1003 static int ends_with_dirsep(const char *uri)
1004 {
1005     if (*uri != '\0')
1006         uri += strlen(uri) - 1;
1007 #if defined __VMS
1008     if (*uri == ']' || *uri == '>' || *uri == ':')
1009         return 1;
1010 #elif defined _WIN32
1011     if (*uri == '\\')
1012         return 1;
1013 #endif
1014     return *uri == '/';
1015 }
1016
1017 static int file_name_to_uri(OSSL_STORE_LOADER_CTX *ctx, const char *name,
1018                             char **data)
1019 {
1020     assert(name != NULL);
1021     assert(data != NULL);
1022     {
1023         const char *pathsep = ends_with_dirsep(ctx->_.dir.uri) ? "" : "/";
1024         long calculated_length = strlen(ctx->_.dir.uri) + strlen(pathsep)
1025             + strlen(name) + 1 /* \0 */;
1026
1027         *data = OPENSSL_zalloc(calculated_length);
1028         if (*data == NULL) {
1029             OSSL_STOREerr(OSSL_STORE_F_FILE_NAME_TO_URI, ERR_R_MALLOC_FAILURE);
1030             return 0;
1031         }
1032
1033         OPENSSL_strlcat(*data, ctx->_.dir.uri, calculated_length);
1034         OPENSSL_strlcat(*data, pathsep, calculated_length);
1035         OPENSSL_strlcat(*data, name, calculated_length);
1036     }
1037     return 1;
1038 }
1039
1040 static int file_eof(OSSL_STORE_LOADER_CTX *ctx);
1041 static int file_error(OSSL_STORE_LOADER_CTX *ctx);
1042 static OSSL_STORE_INFO *file_load(OSSL_STORE_LOADER_CTX *ctx,
1043                                   const UI_METHOD *ui_method, void *ui_data)
1044 {
1045     OSSL_STORE_INFO *result = NULL;
1046
1047     ctx->errcnt = 0;
1048     ERR_clear_error();
1049
1050     if (ctx->type == is_dir) {
1051         do {
1052             char *newname = NULL;
1053
1054             if (ctx->_.dir.last_entry == NULL) {
1055                 if (!ctx->_.dir.end_reached) {
1056                     char errbuf[256];
1057                     assert(ctx->_.dir.last_errno != 0);
1058                     errno = ctx->_.dir.last_errno;
1059                     ctx->errcnt++;
1060                     openssl_strerror_r(errno, errbuf, sizeof(errbuf));
1061                     OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD, ERR_R_SYS_LIB);
1062                     ERR_add_error_data(1, errbuf);
1063                 }
1064                 return NULL;
1065             }
1066
1067             if (ctx->_.dir.last_entry[0] != '.'
1068                 && !file_name_to_uri(ctx, ctx->_.dir.last_entry, &newname))
1069                 return NULL;
1070
1071             /*
1072              * On the first call (with a NULL context), OPENSSL_DIR_read()
1073              * cares about the second argument.  On the following calls, it
1074              * only cares that it isn't NULL.  Therefore, we can safely give
1075              * it our URI here.
1076              */
1077             ctx->_.dir.last_entry = OPENSSL_DIR_read(&ctx->_.dir.ctx,
1078                                                      ctx->_.dir.uri);
1079             ctx->_.dir.last_errno = errno;
1080             if (ctx->_.dir.last_entry == NULL && ctx->_.dir.last_errno == 0)
1081                 ctx->_.dir.end_reached = 1;
1082
1083             if (newname != NULL
1084                 && (result = OSSL_STORE_INFO_new_NAME(newname)) == NULL) {
1085                 OPENSSL_free(newname);
1086                 OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD, ERR_R_OSSL_STORE_LIB);
1087                 return NULL;
1088             }
1089         } while (result == NULL && !file_eof(ctx));
1090     } else {
1091         int matchcount = -1;
1092
1093         result = file_load_try_repeat(ctx, ui_method, ui_data);
1094         if (result != NULL)
1095             return result;
1096
1097         if (file_eof(ctx))
1098             return NULL;
1099
1100         do {
1101             char *pem_name = NULL;      /* PEM record name */
1102             char *pem_header = NULL;    /* PEM record header */
1103             unsigned char *data = NULL; /* DER encoded data */
1104             long len = 0;               /* DER encoded data length */
1105
1106             matchcount = -1;
1107             if (ctx->type == is_pem) {
1108                 if (!file_read_pem(ctx->_.file.file, &pem_name, &pem_header,
1109                                    &data, &len, ui_method, ui_data,
1110                                    (ctx->flags & FILE_FLAG_SECMEM) != 0)) {
1111                     ctx->errcnt++;
1112                     goto endloop;
1113                 }
1114             } else {
1115                 if (!file_read_asn1(ctx->_.file.file, &data, &len)) {
1116                     ctx->errcnt++;
1117                     goto endloop;
1118                 }
1119             }
1120
1121             result = file_load_try_decode(ctx, pem_name, pem_header, data, len,
1122                                           ui_method, ui_data, &matchcount);
1123
1124             if (result != NULL)
1125                 goto endloop;
1126
1127             /*
1128              * If a PEM name matches more than one handler, the handlers are
1129              * badly coded.
1130              */
1131             if (!ossl_assert(pem_name == NULL || matchcount <= 1)) {
1132                 ctx->errcnt++;
1133                 goto endloop;
1134             }
1135
1136             if (matchcount > 1) {
1137                 OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD,
1138                               OSSL_STORE_R_AMBIGUOUS_CONTENT_TYPE);
1139             } else if (matchcount == 1) {
1140                 /*
1141                  * If there are other errors on the stack, they already show
1142                  * what the problem is.
1143                  */
1144                 if (ERR_peek_error() == 0) {
1145                     OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD,
1146                                   OSSL_STORE_R_UNSUPPORTED_CONTENT_TYPE);
1147                     if (pem_name != NULL)
1148                         ERR_add_error_data(3, "PEM type is '", pem_name, "'");
1149                 }
1150             }
1151             if (matchcount > 0)
1152                 ctx->errcnt++;
1153
1154          endloop:
1155             pem_free_flag(pem_name, (ctx->flags & FILE_FLAG_SECMEM) != 0);
1156             pem_free_flag(pem_header, (ctx->flags & FILE_FLAG_SECMEM) != 0);
1157             pem_free_flag(data, (ctx->flags & FILE_FLAG_SECMEM) != 0);
1158         } while (matchcount == 0 && !file_eof(ctx) && !file_error(ctx));
1159
1160         /* We bail out on ambiguity */
1161         if (matchcount > 1)
1162             return NULL;
1163     }
1164
1165     return result;
1166 }
1167
1168 static int file_error(OSSL_STORE_LOADER_CTX *ctx)
1169 {
1170     return ctx->errcnt > 0;
1171 }
1172
1173 static int file_eof(OSSL_STORE_LOADER_CTX *ctx)
1174 {
1175     if (ctx->type == is_dir)
1176         return ctx->_.dir.end_reached;
1177
1178     if (ctx->_.file.last_handler != NULL
1179         && !ctx->_.file.last_handler->eof(ctx->_.file.last_handler_ctx))
1180         return 0;
1181     return BIO_eof(ctx->_.file.file);
1182 }
1183
1184 static int file_close(OSSL_STORE_LOADER_CTX *ctx)
1185 {
1186     if (ctx->type == is_dir) {
1187         OPENSSL_DIR_end(&ctx->_.dir.ctx);
1188     } else {
1189         BIO_free_all(ctx->_.file.file);
1190     }
1191     OSSL_STORE_LOADER_CTX_free(ctx);
1192     return 1;
1193 }
1194
1195 int ossl_store_file_detach_pem_bio_int(OSSL_STORE_LOADER_CTX *ctx)
1196 {
1197     OSSL_STORE_LOADER_CTX_free(ctx);
1198     return 1;
1199 }
1200
1201 static OSSL_STORE_LOADER file_loader =
1202     {
1203         "file",
1204         NULL,
1205         file_open,
1206         file_ctrl,
1207         file_load,
1208         file_eof,
1209         file_error,
1210         file_close
1211     };
1212
1213 static void store_file_loader_deinit(void)
1214 {
1215     ossl_store_unregister_loader_int(file_loader.scheme);
1216 }
1217
1218 int ossl_store_file_loader_init(void)
1219 {
1220     int ret = ossl_store_register_loader_int(&file_loader);
1221
1222     OPENSSL_atexit(store_file_loader_deinit);
1223     return ret;
1224 }