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