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