0ec264bf1612e583b66ff6ca0a8b04415aa9c6c4
[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
12 #include <openssl/bio.h>
13 #include <openssl/dsa.h>         /* For d2i_DSAPrivateKey */
14 #include <openssl/err.h>
15 #include <openssl/evp.h>
16 #include <openssl/pem.h>
17 #include <openssl/pkcs12.h>      /* For the PKCS8 stuff o.O */
18 #include <openssl/rsa.h>         /* For d2i_RSAPrivateKey */
19 #include <openssl/safestack.h>
20 #include <openssl/store.h>
21 #include <openssl/ui.h>
22 #include <openssl/x509.h>        /* For the PKCS8 stuff o.O */
23 #include "internal/asn1_int.h"
24 #include "store_locl.h"
25
26 #include "e_os.h"
27
28 /*
29  *  Password prompting
30  */
31
32 static char *file_get_pass(const UI_METHOD *ui_method, char *pass,
33                            size_t maxsize, const char *prompt_info, void *data)
34 {
35     UI *ui = UI_new();
36     char *prompt = NULL;
37
38     if (ui == NULL) {
39         OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, ERR_R_MALLOC_FAILURE);
40         return NULL;
41     }
42
43     if (ui_method != NULL)
44         UI_set_method(ui, ui_method);
45     UI_add_user_data(ui, data);
46
47     if ((prompt = UI_construct_prompt(ui, "pass phrase",
48                                       prompt_info)) == NULL) {
49         OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, ERR_R_MALLOC_FAILURE);
50         pass = NULL;
51     } else if (!UI_add_input_string(ui, prompt, UI_INPUT_FLAG_DEFAULT_PWD,
52                                     pass, 0, maxsize - 1)) {
53         OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, ERR_R_UI_LIB);
54         pass = NULL;
55     } else {
56         switch (UI_process(ui)) {
57         case -2:
58             OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS,
59                           OSSL_STORE_R_UI_PROCESS_INTERRUPTED_OR_CANCELLED);
60             pass = NULL;
61             break;
62         case -1:
63             OSSL_STOREerr(OSSL_STORE_F_FILE_GET_PASS, ERR_R_UI_LIB);
64             pass = NULL;
65             break;
66         default:
67             break;
68         }
69     }
70
71     OPENSSL_free(prompt);
72     UI_free(ui);
73     return pass;
74 }
75
76 struct pem_pass_data {
77     const UI_METHOD *ui_method;
78     void *data;
79     const char *prompt_info;
80 };
81 static int file_fill_pem_pass_data(struct pem_pass_data *pass_data,
82                                    const char *prompt_info,
83                                    const UI_METHOD *ui_method, void *ui_data)
84 {
85     if (pass_data == NULL)
86         return 0;
87     pass_data->ui_method = ui_method;
88     pass_data->data = ui_data;
89     pass_data->prompt_info = prompt_info;
90     return 1;
91 }
92 static int file_get_pem_pass(char *buf, int num, int w, void *data)
93 {
94     struct pem_pass_data *pass_data = data;
95     char *pass = file_get_pass(pass_data->ui_method, buf, num,
96                                pass_data->prompt_info, pass_data->data);
97
98     return pass == NULL ? 0 : strlen(pass);
99 }
100
101 /*
102  *  The file scheme handlers
103  */
104
105 /*-
106  * The try_decode function is called to check if the blob of data can
107  * be used by this handler, and if it can, decodes it into a supported
108  * OpenSSL type and returns a OSSL_STORE_INFO with the decoded data.
109  * Input:
110  *    pem_name:     If this blob comes from a PEM file, this holds
111  *                  the PEM name.  If it comes from another type of
112  *                  file, this is NULL.
113  *    pem_header:   If this blob comes from a PEM file, this holds
114  *                  the PEM headers.  If it comes from another type of
115  *                  file, this is NULL.
116  *    blob:         The blob of data to match with what this handler
117  *                  can use.
118  *    len:          The length of the blob.
119  *    handler_ctx:  For a handler marked repeatable, this pointer can
120  *                  be used to create a context for the handler.  IT IS
121  *                  THE HANDLER'S RESPONSIBILITY TO CREATE AND DESTROY
122  *                  THIS CONTEXT APPROPRIATELY, i.e. create on first call
123  *                  and destroy when about to return NULL.
124  *    ui_method:    Application UI method for getting a password, pin
125  *                  or any other interactive data.
126  *    ui_data:      Application data to be passed to ui_method when
127  *                  it's called.
128  * Output:
129  *    a OSSL_STORE_INFO
130  */
131 typedef OSSL_STORE_INFO *(*file_try_decode_fn)(const char *pem_name,
132                                                const char *pem_header,
133                                                const unsigned char *blob,
134                                                size_t len, void **handler_ctx,
135                                                const UI_METHOD *ui_method,
136                                                void *ui_data);
137 /*
138  * The eof function should return 1 if there's no more data to be found
139  * with the handler_ctx, otherwise 0.  This is only used when the handler is
140  * marked repeatable.
141  */
142 typedef int (*file_eof_fn)(void *handler_ctx);
143 /*
144  * The destroy_ctx function is used to destroy the handler_ctx that was
145  * intiated by a repeatable try_decode fuction.  This is only used when
146  * the handler is marked repeatable.
147  */
148 typedef void (*file_destroy_ctx_fn)(void **handler_ctx);
149
150 typedef struct file_handler_st {
151     const char *name;
152     file_try_decode_fn try_decode;
153     file_eof_fn eof;
154     file_destroy_ctx_fn destroy_ctx;
155
156     /* flags */
157     int repeatable;
158 } FILE_HANDLER;
159
160 static OSSL_STORE_INFO *try_decode_PKCS12(const char *pem_name,
161                                           const char *pem_header,
162                                           const unsigned char *blob,
163                                           size_t len, void **pctx,
164                                           const UI_METHOD *ui_method,
165                                           void *ui_data)
166 {
167     OSSL_STORE_INFO *store_info = NULL;
168     STACK_OF(OSSL_STORE_INFO) *ctx = *pctx;
169
170     if (ctx == NULL) {
171         /* Initial parsing */
172         PKCS12 *p12;
173         int ok = 0;
174
175         if (pem_name != NULL)
176             /* No match, there is no PEM PKCS12 tag */
177             return NULL;
178
179         if ((p12 = d2i_PKCS12(NULL, &blob, len)) != NULL) {
180             char *pass = NULL;
181             char tpass[PEM_BUFSIZE];
182             EVP_PKEY *pkey = NULL;
183             X509 *cert = NULL;
184             STACK_OF(X509) *chain = NULL;
185
186             if (PKCS12_verify_mac(p12, "", 0)
187                 || PKCS12_verify_mac(p12, NULL, 0)) {
188                 pass = "";
189             } else {
190                 if ((pass = file_get_pass(ui_method, tpass, PEM_BUFSIZE,
191                                           "PKCS12 import password",
192                                           ui_data)) == NULL) {
193                     OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS12,
194                                   OSSL_STORE_R_PASSPHRASE_CALLBACK_ERROR);
195                     goto p12_end;
196                 }
197                 if (!PKCS12_verify_mac(p12, pass, strlen(pass))) {
198                     OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS12,
199                                   OSSL_STORE_R_ERROR_VERIFYING_PKCS12_MAC);
200                     goto p12_end;
201                 }
202             }
203
204             if (PKCS12_parse(p12, pass, &pkey, &cert, &chain)) {
205                 OSSL_STORE_INFO *si_pkey = NULL;
206                 OSSL_STORE_INFO *si_cert = NULL;
207                 OSSL_STORE_INFO *si_ca = NULL;
208
209                 if ((ctx = sk_OSSL_STORE_INFO_new_null()) != NULL
210                     && (si_pkey = OSSL_STORE_INFO_new_PKEY(pkey)) != NULL
211                     && sk_OSSL_STORE_INFO_push(ctx, si_pkey) != 0
212                     && (si_cert = OSSL_STORE_INFO_new_CERT(cert)) != NULL
213                     && sk_OSSL_STORE_INFO_push(ctx, si_cert) != 0) {
214                     ok = 1;
215                     si_pkey = NULL;
216                     si_cert = NULL;
217
218                     while(sk_X509_num(chain) > 0) {
219                         X509 *ca = sk_X509_value(chain, 0);
220
221                         if ((si_ca = OSSL_STORE_INFO_new_CERT(ca)) == NULL
222                             || sk_OSSL_STORE_INFO_push(ctx, si_ca) == 0) {
223                             ok = 0;
224                             break;
225                         }
226                         si_ca = NULL;
227                         (void)sk_X509_shift(chain);
228                     }
229                 }
230                 if (!ok) {
231                     OSSL_STORE_INFO_free(si_ca);
232                     OSSL_STORE_INFO_free(si_cert);
233                     OSSL_STORE_INFO_free(si_pkey);
234                     sk_OSSL_STORE_INFO_pop_free(ctx, OSSL_STORE_INFO_free);
235                     EVP_PKEY_free(pkey);
236                     X509_free(cert);
237                     sk_X509_pop_free(chain, X509_free);
238                     ctx = NULL;
239                 }
240                 *pctx = ctx;
241             }
242         }
243      p12_end:
244         PKCS12_free(p12);
245         if (!ok)
246             return NULL;
247     }
248
249     if (ctx != NULL)
250         store_info = sk_OSSL_STORE_INFO_shift(ctx);
251
252     return store_info;
253 }
254 static int eof_PKCS12(void *ctx_)
255 {
256     STACK_OF(OSSL_STORE_INFO) *ctx = ctx_;
257
258     return ctx == NULL || sk_OSSL_STORE_INFO_num(ctx) == 0;
259 }
260 static void destroy_ctx_PKCS12(void **pctx)
261 {
262     STACK_OF(OSSL_STORE_INFO) *ctx = *pctx;
263
264     sk_OSSL_STORE_INFO_pop_free(ctx, OSSL_STORE_INFO_free);
265     *pctx = NULL;
266 }
267 static FILE_HANDLER PKCS12_handler = {
268     "PKCS12",
269     try_decode_PKCS12,
270     eof_PKCS12,
271     destroy_ctx_PKCS12,
272     1                            /* repeatable */
273 };
274
275 static OSSL_STORE_INFO *try_decode_PKCS8Encrypted(const char *pem_name,
276                                                   const char *pem_header,
277                                                   const unsigned char *blob,
278                                                   size_t len, void **pctx,
279                                                   const UI_METHOD *ui_method,
280                                                   void *ui_data)
281 {
282     X509_SIG *p8 = NULL;
283     char kbuf[PEM_BUFSIZE];
284     char *pass = NULL;
285     const X509_ALGOR *dalg = NULL;
286     const ASN1_OCTET_STRING *doct = NULL;
287     OSSL_STORE_INFO *store_info = NULL;
288     BUF_MEM *mem = NULL;
289     unsigned char *new_data = NULL;
290     int new_data_len;
291
292     if (pem_name != NULL && strcmp(pem_name, PEM_STRING_PKCS8) != 0)
293         return NULL;
294
295     if ((p8 = d2i_X509_SIG(NULL, &blob, len)) == NULL)
296         return NULL;
297
298     if ((mem = BUF_MEM_new()) == NULL) {
299         OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS8ENCRYPTED,
300                       ERR_R_MALLOC_FAILURE);
301         goto nop8;
302     }
303
304     if ((pass = file_get_pass(ui_method, kbuf, PEM_BUFSIZE,
305                               "PKCS8 decrypt password", ui_data)) == NULL) {
306         OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS8ENCRYPTED,
307                       OSSL_STORE_R_BAD_PASSWORD_READ);
308         goto nop8;
309     }
310
311     X509_SIG_get0(p8, &dalg, &doct);
312     if (!PKCS12_pbe_crypt(dalg, pass, strlen(pass), doct->data, doct->length,
313                           &new_data, &new_data_len, 0))
314         goto nop8;
315
316     mem->data = (char *)new_data;
317     mem->max = mem->length = (size_t)new_data_len;
318     X509_SIG_free(p8);
319
320     store_info = ossl_store_info_new_EMBEDDED(PEM_STRING_PKCS8INF, mem);
321     if (store_info == NULL) {
322         OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PKCS8ENCRYPTED,
323                       ERR_R_MALLOC_FAILURE);
324         goto nop8;
325     }
326
327     return store_info;
328  nop8:
329     X509_SIG_free(p8);
330     BUF_MEM_free(mem);
331     return NULL;
332 }
333 static FILE_HANDLER PKCS8Encrypted_handler = {
334     "PKCS8Encrypted",
335     try_decode_PKCS8Encrypted
336 };
337
338 int pem_check_suffix(const char *pem_str, const char *suffix);
339 static OSSL_STORE_INFO *try_decode_PrivateKey(const char *pem_name,
340                                               const char *pem_header,
341                                               const unsigned char *blob,
342                                               size_t len, void **pctx,
343                                               const UI_METHOD *ui_method,
344                                               void *ui_data)
345 {
346     OSSL_STORE_INFO *store_info = NULL;
347     EVP_PKEY *pkey = NULL;
348     const EVP_PKEY_ASN1_METHOD *ameth = NULL;
349
350     if (pem_name != NULL) {
351         if (strcmp(pem_name, PEM_STRING_PKCS8INF) == 0) {
352             PKCS8_PRIV_KEY_INFO *p8inf =
353                 d2i_PKCS8_PRIV_KEY_INFO(NULL, &blob, len);
354
355             if (p8inf != NULL)
356                 pkey = EVP_PKCS82PKEY(p8inf);
357             PKCS8_PRIV_KEY_INFO_free(p8inf);
358         } else {
359             int slen;
360
361             if ((slen = pem_check_suffix(pem_name, "PRIVATE KEY")) > 0
362                 && (ameth = EVP_PKEY_asn1_find_str(NULL, pem_name,
363                                                    slen)) != NULL)
364                 pkey = d2i_PrivateKey(ameth->pkey_id, NULL, &blob, len);
365         }
366     } else {
367         int i;
368
369         for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) {
370             ameth = EVP_PKEY_asn1_get0(i);
371             if (ameth->pkey_flags & ASN1_PKEY_ALIAS)
372                 continue;
373             pkey = d2i_PrivateKey(ameth->pkey_id, NULL, &blob, len);
374             if (pkey != NULL)
375                 break;
376         }
377     }
378     if (pkey == NULL)
379         /* No match */
380         return NULL;
381
382     store_info = OSSL_STORE_INFO_new_PKEY(pkey);
383     if (store_info == NULL)
384         EVP_PKEY_free(pkey);
385
386     return store_info;
387 }
388 static FILE_HANDLER PrivateKey_handler = {
389     "PrivateKey",
390     try_decode_PrivateKey
391 };
392
393 static OSSL_STORE_INFO *try_decode_PUBKEY(const char *pem_name,
394                                           const char *pem_header,
395                                           const unsigned char *blob,
396                                           size_t len, void **pctx,
397                                           const UI_METHOD *ui_method,
398                                           void *ui_data)
399 {
400     OSSL_STORE_INFO *store_info = NULL;
401     EVP_PKEY *pkey = NULL;
402
403     if (pem_name != NULL && strcmp(pem_name, PEM_STRING_PUBLIC) != 0)
404         /* No match */
405         return NULL;
406
407     if ((pkey = d2i_PUBKEY(NULL, &blob, len)) != NULL)
408         store_info = OSSL_STORE_INFO_new_PKEY(pkey);
409
410     return store_info;
411 }
412 static FILE_HANDLER PUBKEY_handler = {
413     "PUBKEY",
414     try_decode_PUBKEY
415 };
416
417 static OSSL_STORE_INFO *try_decode_params(const char *pem_name,
418                                           const char *pem_header,
419                                           const unsigned char *blob,
420                                           size_t len, void **pctx,
421                                           const UI_METHOD *ui_method,
422                                           void *ui_data)
423 {
424     OSSL_STORE_INFO *store_info = NULL;
425     EVP_PKEY *pkey = EVP_PKEY_new();
426     const EVP_PKEY_ASN1_METHOD *ameth = NULL;
427     int ok = 0;
428
429     if (pkey == NULL) {
430         OSSL_STOREerr(OSSL_STORE_F_TRY_DECODE_PARAMS, ERR_R_EVP_LIB);
431         return NULL;
432     }
433
434     if (pem_name != NULL) {
435         int slen;
436
437         if ((slen = pem_check_suffix(pem_name, "PARAMETERS")) > 0
438             && EVP_PKEY_set_type_str(pkey, pem_name, slen)
439             && (ameth = EVP_PKEY_get0_asn1(pkey)) != NULL
440             && ameth->param_decode != NULL
441             && ameth->param_decode(pkey, &blob, len))
442             ok = 1;
443     } else {
444         int i;
445
446         for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) {
447             ameth = EVP_PKEY_asn1_get0(i);
448             if (ameth->pkey_flags & ASN1_PKEY_ALIAS)
449                 continue;
450             if (EVP_PKEY_set_type(pkey, ameth->pkey_id)
451                 && (ameth = EVP_PKEY_get0_asn1(pkey)) != NULL
452                 && ameth->param_decode != NULL
453                 && ameth->param_decode(pkey, &blob, len)) {
454                 ok = 1;
455                 break;
456             }
457         }
458     }
459
460     if (ok)
461         store_info = OSSL_STORE_INFO_new_PARAMS(pkey);
462     if (store_info == NULL)
463         EVP_PKEY_free(pkey);
464
465     return store_info;
466 }
467 static FILE_HANDLER params_handler = {
468     "params",
469     try_decode_params
470 };
471
472 static OSSL_STORE_INFO *try_decode_X509Certificate(const char *pem_name,
473                                                    const char *pem_header,
474                                                    const unsigned char *blob,
475                                                    size_t len, void **pctx,
476                                                    const UI_METHOD *ui_method,
477                                                    void *ui_data)
478 {
479     OSSL_STORE_INFO *store_info = NULL;
480     X509 *cert = NULL;
481
482     /*
483      * In most cases, we can try to interpret the serialized data as a trusted
484      * cert (X509 + X509_AUX) and fall back to reading it as a normal cert
485      * (just X509), but if the PEM name specifically declares it as a trusted
486      * cert, then no fallback should be engaged.  |ignore_trusted| tells if
487      * the fallback can be used (1) or not (0).
488      */
489     int ignore_trusted = 1;
490
491     if (pem_name != NULL) {
492         if (strcmp(pem_name, PEM_STRING_X509_TRUSTED) == 0)
493             ignore_trusted = 0;
494         else if (strcmp(pem_name, PEM_STRING_X509_OLD) != 0
495                  && strcmp(pem_name, PEM_STRING_X509) != 0)
496             /* No match */
497             return NULL;
498     }
499
500     if ((cert = d2i_X509_AUX(NULL, &blob, len)) != NULL
501         || (ignore_trusted && (cert = d2i_X509(NULL, &blob, len)) != NULL))
502         store_info = OSSL_STORE_INFO_new_CERT(cert);
503
504     if (store_info == NULL)
505         X509_free(cert);
506
507     return store_info;
508 }
509 static FILE_HANDLER X509Certificate_handler = {
510     "X509Certificate",
511     try_decode_X509Certificate
512 };
513
514 static OSSL_STORE_INFO *try_decode_X509CRL(const char *pem_name,
515                                            const char *pem_header,
516                                            const unsigned char *blob,
517                                            size_t len, void **pctx,
518                                            const UI_METHOD *ui_method,
519                                            void *ui_data)
520 {
521     OSSL_STORE_INFO *store_info = NULL;
522     X509_CRL *crl = NULL;
523
524     if (pem_name != NULL
525         && strcmp(pem_name, PEM_STRING_X509_CRL) != 0)
526         /* No match */
527         return NULL;
528
529     if ((crl = d2i_X509_CRL(NULL, &blob, len)) != NULL)
530         store_info = OSSL_STORE_INFO_new_CRL(crl);
531
532     if (store_info == NULL)
533         X509_CRL_free(crl);
534
535     return store_info;
536 }
537 static FILE_HANDLER X509CRL_handler = {
538     "X509CRL",
539     try_decode_X509CRL
540 };
541
542 static const FILE_HANDLER *file_handlers[] = {
543     &PKCS12_handler,
544     &PKCS8Encrypted_handler,
545     &X509Certificate_handler,
546     &X509CRL_handler,
547     &params_handler,
548     &PUBKEY_handler,
549     &PrivateKey_handler,
550 };
551
552
553 /*
554  *  The loader itself
555  */
556
557 struct ossl_store_loader_ctx_st {
558     BIO *file;
559     int is_pem;
560     int errcnt;
561
562     /* The following are used when the handler is marked as repeatable */
563     const FILE_HANDLER *last_handler;
564     void *last_handler_ctx;
565 };
566
567 static OSSL_STORE_LOADER_CTX *file_open(const OSSL_STORE_LOADER *loader,
568                                         const char *uri,
569                                         const UI_METHOD *ui_method,
570                                         void *ui_data)
571 {
572     BIO *buff = NULL;
573     char peekbuf[4096];
574     OSSL_STORE_LOADER_CTX *ctx = NULL;
575     const char *path = NULL;
576
577     if (strncasecmp(uri, "file:", 5) == 0) {
578         if (strncmp(&uri[5], "//localhost/", 12) == 0) {
579             path = &uri[16];
580         } else if (strncmp(&uri[5], "///", 3) == 0) {
581             path = &uri[7];
582         } else if (strncmp(&uri[5], "//", 2) != 0) {
583             path = &uri[5];
584         } else {
585             OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN,
586                           OSSL_STORE_R_URI_AUTHORITY_UNSUPPORED);
587             return NULL;
588         }
589
590         /*
591          * If the scheme "file" was an explicit part of the URI, the path must
592          * be absolute.  So says RFC 8089
593          */
594         if (path[0] != '/') {
595             OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN,
596                           OSSL_STORE_R_PATH_MUST_BE_ABSOLUTE);
597             return NULL;
598         }
599
600 #ifdef _WIN32
601         /* Windows file: URIs with a drive letter start with a / */
602         if (path[0] == '/' && path[2] == ':' && path[3] == '/')
603             path++;
604 #endif
605     } else {
606         path = uri;
607     }
608
609
610     ctx = OPENSSL_zalloc(sizeof(*ctx));
611     if (ctx == NULL) {
612         OSSL_STOREerr(OSSL_STORE_F_FILE_OPEN, ERR_R_MALLOC_FAILURE);
613         return NULL;
614     }
615
616     if ((buff = BIO_new(BIO_f_buffer())) == NULL)
617         goto err;
618     if ((ctx->file = BIO_new_file(path, "rb")) == NULL) {
619         goto err;
620     }
621     ctx->file = BIO_push(buff, ctx->file);
622     if (BIO_buffer_peek(ctx->file, peekbuf, sizeof(peekbuf)-1) > 0) {
623         peekbuf[sizeof(peekbuf)-1] = '\0';
624         if (strstr(peekbuf, "-----BEGIN ") != NULL)
625             ctx->is_pem = 1;
626     }
627
628     return ctx;
629  err:
630     if (buff != NULL)
631         BIO_free(buff);
632     OPENSSL_free(ctx);
633     return NULL;
634 }
635
636 static OSSL_STORE_INFO *file_load_try_decode(OSSL_STORE_LOADER_CTX *ctx,
637                                              const char *pem_name,
638                                              const char *pem_header,
639                                              unsigned char *data, size_t len,
640                                              const UI_METHOD *ui_method,
641                                              void *ui_data, int *matchcount)
642 {
643     OSSL_STORE_INFO *result = NULL;
644     BUF_MEM *new_mem = NULL;
645     char *new_pem_name = NULL;
646     int t = 0;
647
648  again:
649     {
650         size_t i = 0;
651         void *handler_ctx = NULL;
652         const FILE_HANDLER **matching_handlers =
653             OPENSSL_zalloc(sizeof(*matching_handlers)
654                            * OSSL_NELEM(file_handlers));
655
656         if (matching_handlers == NULL) {
657             OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD_TRY_DECODE,
658                           ERR_R_MALLOC_FAILURE);
659             goto err;
660         }
661
662         *matchcount = 0;
663         for (i = 0; i < OSSL_NELEM(file_handlers); i++) {
664             const FILE_HANDLER *handler = file_handlers[i];
665             void *tmp_handler_ctx = NULL;
666             OSSL_STORE_INFO *tmp_result =
667                 handler->try_decode(pem_name, pem_header, data, len,
668                                     &tmp_handler_ctx, ui_method, ui_data);
669
670             if (tmp_result == NULL) {
671                 OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD_TRY_DECODE,
672                               OSSL_STORE_R_IS_NOT_A);
673                 ERR_add_error_data(1, handler->name);
674             } else {
675                 if (matching_handlers)
676                     matching_handlers[*matchcount] = handler;
677
678                 if (handler_ctx)
679                     handler->destroy_ctx(&handler_ctx);
680                 handler_ctx = tmp_handler_ctx;
681
682                 if (++*matchcount == 1) {
683                     result = tmp_result;
684                     tmp_result = NULL;
685                 } else {
686                     /* more than one match => ambiguous, kill any result */
687                     OSSL_STORE_INFO_free(result);
688                     OSSL_STORE_INFO_free(tmp_result);
689                     if (handler->destroy_ctx != NULL)
690                         handler->destroy_ctx(&handler_ctx);
691                     handler_ctx = NULL;
692                     result = NULL;
693                 }
694             }
695         }
696
697         if (*matchcount > 1)
698             OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD_TRY_DECODE,
699                           OSSL_STORE_R_AMBIGUOUS_CONTENT_TYPE);
700         if (*matchcount == 0)
701             OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD_TRY_DECODE,
702                           OSSL_STORE_R_UNSUPPORTED_CONTENT_TYPE);
703         else if (matching_handlers[0]->repeatable) {
704             if (ctx == NULL) {
705                 OSSL_STOREerr(OSSL_STORE_F_FILE_LOAD_TRY_DECODE,
706                               OSSL_STORE_R_UNSUPPORTED_CONTENT_TYPE);
707                 OSSL_STORE_INFO_free(result);
708                 result = NULL;
709             } else {
710                 ctx->last_handler = matching_handlers[0];
711                 ctx->last_handler_ctx = handler_ctx;
712             }
713         }
714
715         OPENSSL_free(matching_handlers);
716     }
717
718  err:
719     OPENSSL_free(new_pem_name);
720     BUF_MEM_free(new_mem);
721
722     if (result != NULL
723         && (t = OSSL_STORE_INFO_get_type(result)) == OSSL_STORE_INFO_EMBEDDED) {
724         pem_name = new_pem_name =
725             ossl_store_info_get0_EMBEDDED_pem_name(result);
726         new_mem = ossl_store_info_get0_EMBEDDED_buffer(result);
727         data = (unsigned char *)new_mem->data;
728         len = new_mem->length;
729         OPENSSL_free(result);
730         result = NULL;
731         goto again;
732     }
733
734     if (result != NULL)
735         ERR_clear_error();
736
737     return result;
738 }
739
740 static OSSL_STORE_INFO *file_load_try_repeat(OSSL_STORE_LOADER_CTX *ctx,
741                                              const UI_METHOD *ui_method,
742                                              void *ui_data)
743 {
744     OSSL_STORE_INFO *result = NULL;
745
746     if (ctx->last_handler != NULL) {
747         result = ctx->last_handler->try_decode(NULL, NULL, NULL, 0,
748                                                &ctx->last_handler_ctx,
749                                                ui_method, ui_data);
750
751         if (result == NULL) {
752             ctx->last_handler->destroy_ctx(&ctx->last_handler_ctx);
753             ctx->last_handler_ctx = NULL;
754             ctx->last_handler = NULL;
755         }
756     }
757     return result;
758 }
759
760 static int file_read_pem(BIO *bp, char **pem_name, char **pem_header,
761                          unsigned char **data, long *len,
762                          const UI_METHOD *ui_method,
763                          void *ui_data)
764 {
765     int i = PEM_read_bio(bp, pem_name, pem_header, data, len);
766
767     if (i <= 0)
768         return 0;
769
770     /*
771      * 10 is the number of characters in "Proc-Type:", which
772      * PEM_get_EVP_CIPHER_INFO() requires to be present.
773      * If the PEM header has less characters than that, it's
774      * not worth spending cycles on it.
775      */
776     if (strlen(*pem_header) > 10) {
777         EVP_CIPHER_INFO cipher;
778         struct pem_pass_data pass_data;
779
780         if (!PEM_get_EVP_CIPHER_INFO(*pem_header, &cipher)
781             || !file_fill_pem_pass_data(&pass_data, "PEM", ui_method, ui_data)
782             || !PEM_do_header(&cipher, *data, len, file_get_pem_pass,
783                               &pass_data)) {
784             return 0;
785         }
786     }
787     return 1;
788 }
789
790 static int file_read_asn1(BIO *bp, unsigned char **data, long *len)
791 {
792     BUF_MEM *mem = NULL;
793
794     if (asn1_d2i_read_bio(bp, &mem) < 0)
795         return 0;
796
797     *data = (unsigned char *)mem->data;
798     *len = (long)mem->length;
799     OPENSSL_free(mem);
800
801     return 1;
802 }
803
804 static int file_eof(OSSL_STORE_LOADER_CTX *ctx);
805 static int file_error(OSSL_STORE_LOADER_CTX *ctx);
806 static OSSL_STORE_INFO *file_load(OSSL_STORE_LOADER_CTX *ctx,
807                                   const UI_METHOD *ui_method, void *ui_data)
808 {
809     OSSL_STORE_INFO *result = NULL;
810     int matchcount = -1;
811
812     result = file_load_try_repeat(ctx, ui_method, ui_data);
813     if (result != NULL)
814         return result;
815
816     if (file_error(ctx))
817         return NULL;
818
819     do {
820         char *pem_name = NULL;      /* PEM record name */
821         char *pem_header = NULL;    /* PEM record header */
822         unsigned char *data = NULL; /* DER encoded data */
823         long len = 0;               /* DER encoded data length */
824
825         if (ctx->is_pem) {
826             if (!file_read_pem(ctx->file, &pem_name, &pem_header, &data, &len,
827                                ui_method, ui_data)) {
828                 if (!file_eof(ctx))
829                     ctx->errcnt++;
830                 goto err;
831             }
832         } else {
833             if (!file_read_asn1(ctx->file, &data, &len)) {
834                 if (!file_eof(ctx))
835                     ctx->errcnt++;
836                 goto err;
837             }
838         }
839
840         matchcount = -1;
841         result = file_load_try_decode(ctx, pem_name, pem_header, data, len,
842                                       ui_method, ui_data, &matchcount);
843
844      err:
845         OPENSSL_free(pem_name);
846         OPENSSL_free(pem_header);
847         OPENSSL_free(data);
848     } while (matchcount == 0 && !file_eof(ctx) && !file_error(ctx));
849
850     /* We bail out on ambiguity */
851     if (matchcount > 1)
852         return NULL;
853
854     return result;
855 }
856
857 static int file_error(OSSL_STORE_LOADER_CTX *ctx)
858 {
859     return ctx->errcnt > 0;
860 }
861
862 static int file_eof(OSSL_STORE_LOADER_CTX *ctx)
863 {
864     if (ctx->last_handler != NULL
865         && !ctx->last_handler->eof(ctx->last_handler_ctx))
866         return 0;
867     return BIO_eof(ctx->file);
868 }
869
870 static int file_close(OSSL_STORE_LOADER_CTX *ctx)
871 {
872     if (ctx->last_handler != NULL) {
873         ctx->last_handler->destroy_ctx(&ctx->last_handler_ctx);
874         ctx->last_handler_ctx = NULL;
875         ctx->last_handler = NULL;
876     }
877     BIO_free_all(ctx->file);
878     OPENSSL_free(ctx);
879     return 1;
880 }
881
882 static OSSL_STORE_LOADER file_loader =
883     {
884         "file",
885         file_open,
886         NULL,
887         file_load,
888         file_eof,
889         file_error,
890         file_close
891     };
892
893 static void store_file_loader_deinit(void)
894 {
895     ossl_store_unregister_loader_int(file_loader.scheme);
896 }
897
898 int ossl_store_file_loader_init(void)
899 {
900     int ret = ossl_store_register_loader_int(&file_loader);
901
902     OPENSSL_atexit(store_file_loader_deinit);
903     return ret;
904 }