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