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