1 /*
2  * Copyright 2016-2025 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 /* This file has quite some overlap with providers/implementations/storemgmt/file_store.c */
13 
14 /*
15  * We need to use some asn1_meth deprecated APIs
16  */
17 #define OPENSSL_SUPPRESS_DEPRECATED
18 
19 #include "internal/e_os.h" /* for stat */
20 #include <string.h>
21 #include <sys/stat.h>
22 #include <ctype.h>
23 #include <assert.h>
24 
25 #include <openssl/bio.h>
26 #include <openssl/dsa.h>         /* For d2i_DSAPrivateKey */
27 #include <openssl/err.h>
28 #include <openssl/evp.h>
29 #include <openssl/pem.h>
30 #include <openssl/pkcs12.h>      /* For the PKCS8 stuff o.O */
31 #include <openssl/rsa.h>         /* For d2i_RSAPrivateKey */
32 #include <openssl/safestack.h>
33 #include <openssl/store.h>
34 #include <openssl/ui.h>
35 #include <openssl/engine.h>
36 #include <openssl/x509.h>        /* For the PKCS8 stuff o.O */
37 #include "internal/asn1.h"       /* For asn1_d2i_read_bio */
38 #include "internal/o_dir.h"
39 #include "internal/cryptlib.h"
40 #include "crypto/ctype.h"        /* For ossl_isdigit */
41 #include "crypto/pem.h"          /* For PVK and "blob" PEM headers */
42 
43 #include "e_loader_attic_err.c"
44 
DEFINE_STACK_OF(OSSL_STORE_INFO)45 DEFINE_STACK_OF(OSSL_STORE_INFO)
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_UI_LIB);
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_UI_LIB);
74         pass = NULL;
75     } else if (UI_add_input_string(ui, prompt, UI_INPUT_FLAG_DEFAULT_PWD,
76                                     pass, 0, (int)(maxsize - 1)) <= 0) {
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 
file_fill_pem_pass_data(struct pem_pass_data * pass_data,const char * desc,const char * info,const UI_METHOD * ui_method,void * ui_data)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 */
file_get_pem_pass(char * buf,int num,int w,void * data)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 : (int)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  */
check_suffix(const char * str,const char * suffix)136 static int check_suffix(const char *str, const char *suffix)
137 {
138     int str_len = (int)strlen(str);
139     int suffix_len = (int)(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 (int)(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 */
get0_EMBEDDED(OSSL_STORE_INFO * info)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 
store_info_free(OSSL_STORE_INFO * info)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 
new_EMBEDDED(const char * new_pem_name,BUF_MEM * embedded)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         return NULL;
197     if ((info = OSSL_STORE_INFO_new(STORE_INFO_EMBEDDED, data)) == NULL) {
198         ATTICerr(0, ERR_R_OSSL_STORE_LIB);
199         OPENSSL_free(data);
200         return NULL;
201     }
202 
203     data->blob = embedded;
204     data->pem_name =
205         new_pem_name == NULL ? NULL : OPENSSL_strdup(new_pem_name);
206 
207     if (new_pem_name != NULL && data->pem_name == NULL) {
208         store_info_free(info);
209         info = NULL;
210     }
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 an 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  *    an 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  */
try_decode_PKCS12(const char * pem_name,const char * pem_header,const unsigned char * blob,size_t len,void ** pctx,int * matchcount,const UI_METHOD * ui_method,void * ui_data,const char * uri,OSSL_LIB_CTX * libctx,const char * propq)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 || len > LONG_MAX)
313             /* No match, there is no PEM PKCS12 tag */
314             return NULL;
315 
316         if ((p12 = d2i_PKCS12(NULL, &blob, (long)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_mac_present(p12)
326                 || 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", 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, (int)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                 OSSL_STACK_OF_X509_free(chain);
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 
eof_PKCS12(void * ctx_)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 
destroy_ctx_PKCS12(void ** pctx)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  */
try_decode_PKCS8Encrypted(const char * pem_name,const char * pem_header,const unsigned char * blob,size_t len,void ** pctx,int * matchcount,const UI_METHOD * ui_method,void * ui_data,const char * uri,OSSL_LIB_CTX * libctx,const char * propq)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                                                   OSSL_LIB_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 (len > LONG_MAX || (p8 = d2i_X509_SIG(NULL, &blob, (long)len)) == NULL)
458         return NULL;
459 
460     *matchcount = 1;
461 
462     if ((mem = BUF_MEM_new()) == NULL) {
463         ATTICerr(0, ERR_R_BUF_LIB);
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, (int)strlen(pass),
476                           doct->data, doct->length,
477                           &new_data, &new_data_len, 0))
478         goto nop8;
479 
480     mem->data = (char *)new_data;
481     mem->max = mem->length = (size_t)new_data_len;
482     X509_SIG_free(p8);
483     p8 = NULL;
484 
485     store_info = new_EMBEDDED(PEM_STRING_PKCS8INF, mem);
486     if (store_info == NULL) {
487         ATTICerr(0, ERR_R_OSSL_STORE_LIB);
488         goto nop8;
489     }
490 
491     return store_info;
492  nop8:
493     X509_SIG_free(p8);
494     BUF_MEM_free(mem);
495     return NULL;
496 }
497 
498 static FILE_HANDLER PKCS8Encrypted_handler = {
499     "PKCS8Encrypted",
500     try_decode_PKCS8Encrypted
501 };
502 
503 /*
504  * Private key decoder.  Decodes all sorts of private keys, both PKCS#8
505  * encoded ones and old style PEM ones (with the key type is encoded into
506  * the PEM name).
507  */
try_decode_PrivateKey(const char * pem_name,const char * pem_header,const unsigned char * blob,size_t len,void ** pctx,int * matchcount,const UI_METHOD * ui_method,void * ui_data,const char * uri,OSSL_LIB_CTX * libctx,const char * propq)508 static OSSL_STORE_INFO *try_decode_PrivateKey(const char *pem_name,
509                                               const char *pem_header,
510                                               const unsigned char *blob,
511                                               size_t len, void **pctx,
512                                               int *matchcount,
513                                               const UI_METHOD *ui_method,
514                                               void *ui_data, const char *uri,
515                                               OSSL_LIB_CTX *libctx,
516                                               const char *propq)
517 {
518     OSSL_STORE_INFO *store_info = NULL;
519     EVP_PKEY *pkey = NULL;
520     const EVP_PKEY_ASN1_METHOD *ameth = NULL;
521 
522     if (len > LONG_MAX)
523         return NULL;
524     if (pem_name != NULL) {
525         if (strcmp(pem_name, PEM_STRING_PKCS8INF) == 0) {
526             PKCS8_PRIV_KEY_INFO *p8inf =
527                 d2i_PKCS8_PRIV_KEY_INFO(NULL, &blob, (long)len);
528 
529             *matchcount = 1;
530             if (p8inf != NULL)
531                 pkey = EVP_PKCS82PKEY_ex(p8inf, libctx, propq);
532             PKCS8_PRIV_KEY_INFO_free(p8inf);
533         } else {
534             int slen;
535             int pkey_id;
536 
537             if ((slen = check_suffix(pem_name, "PRIVATE KEY")) > 0
538                 && (ameth = EVP_PKEY_asn1_find_str(NULL, pem_name,
539                                                    slen)) != NULL
540                 && EVP_PKEY_asn1_get0_info(&pkey_id, NULL, NULL, NULL, NULL,
541                                            ameth)) {
542                 *matchcount = 1;
543                 pkey = d2i_PrivateKey_ex(pkey_id, NULL, &blob, (long)len,
544                                          libctx, propq);
545             }
546         }
547     } else {
548         int i;
549 #ifndef OPENSSL_NO_ENGINE
550         ENGINE *curengine = ENGINE_get_first();
551 
552         while (curengine != NULL) {
553             ENGINE_PKEY_ASN1_METHS_PTR asn1meths =
554                 ENGINE_get_pkey_asn1_meths(curengine);
555 
556             if (asn1meths != NULL) {
557                 const int *nids = NULL;
558                 int nids_n = asn1meths(curengine, NULL, &nids, 0);
559 
560                 for (i = 0; i < nids_n; i++) {
561                     EVP_PKEY_ASN1_METHOD *ameth2 = NULL;
562                     EVP_PKEY *tmp_pkey = NULL;
563                     const unsigned char *tmp_blob = blob;
564                     int pkey_id, pkey_flags;
565 
566                     if (!asn1meths(curengine, &ameth2, NULL, nids[i])
567                         || !EVP_PKEY_asn1_get0_info(&pkey_id, NULL,
568                                                     &pkey_flags, NULL, NULL,
569                                                     ameth2)
570                         || (pkey_flags & ASN1_PKEY_ALIAS) != 0)
571                         continue;
572 
573                     ERR_set_mark(); /* prevent flooding error queue */
574                     tmp_pkey = d2i_PrivateKey_ex(pkey_id, NULL,
575                                                  &tmp_blob, (long)len,
576                                                  libctx, propq);
577                     if (tmp_pkey != NULL) {
578                         if (pkey != NULL)
579                             EVP_PKEY_free(tmp_pkey);
580                         else
581                             pkey = tmp_pkey;
582                         (*matchcount)++;
583                     }
584                     ERR_pop_to_mark();
585                 }
586             }
587             curengine = ENGINE_get_next(curengine);
588         }
589 #endif
590 
591         for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) {
592             EVP_PKEY *tmp_pkey = NULL;
593             const unsigned char *tmp_blob = blob;
594             int pkey_id, pkey_flags;
595 
596             ameth = EVP_PKEY_asn1_get0(i);
597             if (!EVP_PKEY_asn1_get0_info(&pkey_id, NULL, &pkey_flags, NULL,
598                                          NULL, ameth)
599                 || (pkey_flags & ASN1_PKEY_ALIAS) != 0)
600                 continue;
601 
602             ERR_set_mark(); /* prevent flooding error queue */
603             tmp_pkey = d2i_PrivateKey_ex(pkey_id, NULL, &tmp_blob, (long)len,
604                                          libctx, propq);
605             if (tmp_pkey != NULL) {
606                 if (pkey != NULL)
607                     EVP_PKEY_free(tmp_pkey);
608                 else
609                     pkey = tmp_pkey;
610                 (*matchcount)++;
611             }
612             ERR_pop_to_mark();
613         }
614 
615         if (*matchcount > 1) {
616             EVP_PKEY_free(pkey);
617             pkey = NULL;
618         }
619     }
620     if (pkey == NULL)
621         /* No match */
622         return NULL;
623 
624     store_info = OSSL_STORE_INFO_new_PKEY(pkey);
625     if (store_info == NULL)
626         EVP_PKEY_free(pkey);
627 
628     return store_info;
629 }
630 
631 static FILE_HANDLER PrivateKey_handler = {
632     "PrivateKey",
633     try_decode_PrivateKey
634 };
635 
636 /*
637  * Public key decoder.  Only supports SubjectPublicKeyInfo formatted keys.
638  */
try_decode_PUBKEY(const char * pem_name,const char * pem_header,const unsigned char * blob,size_t len,void ** pctx,int * matchcount,const UI_METHOD * ui_method,void * ui_data,const char * uri,OSSL_LIB_CTX * libctx,const char * propq)639 static OSSL_STORE_INFO *try_decode_PUBKEY(const char *pem_name,
640                                           const char *pem_header,
641                                           const unsigned char *blob,
642                                           size_t len, void **pctx,
643                                           int *matchcount,
644                                           const UI_METHOD *ui_method,
645                                           void *ui_data, const char *uri,
646                                           OSSL_LIB_CTX *libctx,
647                                           const char *propq)
648 {
649     OSSL_STORE_INFO *store_info = NULL;
650     EVP_PKEY *pkey = NULL;
651 
652     if (pem_name != NULL) {
653         if (strcmp(pem_name, PEM_STRING_PUBLIC) != 0)
654             /* No match */
655             return NULL;
656         *matchcount = 1;
657     }
658 
659     if (len > LONG_MAX || (pkey = d2i_PUBKEY(NULL, &blob, (long)len)) != NULL) {
660         *matchcount = 1;
661         store_info = OSSL_STORE_INFO_new_PUBKEY(pkey);
662     }
663 
664     return store_info;
665 }
666 
667 static FILE_HANDLER PUBKEY_handler = {
668     "PUBKEY",
669     try_decode_PUBKEY
670 };
671 
672 /*
673  * Key parameter decoder.
674  */
try_decode_params(const char * pem_name,const char * pem_header,const unsigned char * blob,size_t len,void ** pctx,int * matchcount,const UI_METHOD * ui_method,void * ui_data,const char * uri,OSSL_LIB_CTX * libctx,const char * propq)675 static OSSL_STORE_INFO *try_decode_params(const char *pem_name,
676                                           const char *pem_header,
677                                           const unsigned char *blob,
678                                           size_t len, void **pctx,
679                                           int *matchcount,
680                                           const UI_METHOD *ui_method,
681                                           void *ui_data, const char *uri,
682                                           OSSL_LIB_CTX *libctx,
683                                           const char *propq)
684 {
685     OSSL_STORE_INFO *store_info = NULL;
686     EVP_PKEY *pkey = NULL;
687     const EVP_PKEY_ASN1_METHOD *ameth = NULL;
688 
689     if (len > LONG_MAX)
690         return NULL;
691     if (pem_name != NULL) {
692         int slen;
693         int pkey_id;
694 
695         if ((slen = check_suffix(pem_name, "PARAMETERS")) > 0
696             && (ameth = EVP_PKEY_asn1_find_str(NULL, pem_name, slen)) != NULL
697             && EVP_PKEY_asn1_get0_info(&pkey_id, NULL, NULL, NULL, NULL,
698                                        ameth)) {
699             *matchcount = 1;
700             pkey = d2i_KeyParams(pkey_id, NULL, &blob, (long)len);
701         }
702     } else {
703         int i;
704 
705         for (i = 0; i < EVP_PKEY_asn1_get_count(); i++) {
706             EVP_PKEY *tmp_pkey = NULL;
707             const unsigned char *tmp_blob = blob;
708             int pkey_id, pkey_flags;
709 
710             ameth = EVP_PKEY_asn1_get0(i);
711             if (!EVP_PKEY_asn1_get0_info(&pkey_id, NULL, &pkey_flags, NULL,
712                                          NULL, ameth)
713                 || (pkey_flags & ASN1_PKEY_ALIAS) != 0)
714                 continue;
715 
716             ERR_set_mark(); /* prevent flooding error queue */
717 
718             tmp_pkey = d2i_KeyParams(pkey_id, NULL, &tmp_blob, (long)len);
719 
720             if (tmp_pkey != NULL) {
721                 if (pkey != NULL)
722                     EVP_PKEY_free(tmp_pkey);
723                 else
724                     pkey = tmp_pkey;
725                 (*matchcount)++;
726             }
727             ERR_pop_to_mark();
728         }
729 
730         if (*matchcount > 1) {
731             EVP_PKEY_free(pkey);
732             pkey = NULL;
733         }
734     }
735     if (pkey == NULL)
736         /* No match */
737         return NULL;
738 
739     store_info = OSSL_STORE_INFO_new_PARAMS(pkey);
740     if (store_info == NULL)
741         EVP_PKEY_free(pkey);
742 
743     return store_info;
744 }
745 
746 static FILE_HANDLER params_handler = {
747     "params",
748     try_decode_params
749 };
750 
751 /*
752  * X.509 certificate decoder.
753  */
try_decode_X509Certificate(const char * pem_name,const char * pem_header,const unsigned char * blob,size_t len,void ** pctx,int * matchcount,const UI_METHOD * ui_method,void * ui_data,const char * uri,OSSL_LIB_CTX * libctx,const char * propq)754 static OSSL_STORE_INFO *try_decode_X509Certificate(const char *pem_name,
755                                                    const char *pem_header,
756                                                    const unsigned char *blob,
757                                                    size_t len, void **pctx,
758                                                    int *matchcount,
759                                                    const UI_METHOD *ui_method,
760                                                    void *ui_data,
761                                                    const char *uri,
762                                                    OSSL_LIB_CTX *libctx,
763                                                    const char *propq)
764 {
765     OSSL_STORE_INFO *store_info = NULL;
766     X509 *cert = NULL;
767 
768     /*
769      * In most cases, we can try to interpret the serialized data as a trusted
770      * cert (X509 + X509_AUX) and fall back to reading it as a normal cert
771      * (just X509), but if the PEM name specifically declares it as a trusted
772      * cert, then no fallback should be engaged.  |ignore_trusted| tells if
773      * the fallback can be used (1) or not (0).
774      */
775     int ignore_trusted = 1;
776 
777     if (len > LONG_MAX)
778         return NULL;
779     if (pem_name != NULL) {
780         if (strcmp(pem_name, PEM_STRING_X509_TRUSTED) == 0)
781             ignore_trusted = 0;
782         else if (strcmp(pem_name, PEM_STRING_X509_OLD) != 0
783                  && strcmp(pem_name, PEM_STRING_X509) != 0)
784             /* No match */
785             return NULL;
786         *matchcount = 1;
787     }
788 
789     cert = X509_new_ex(libctx, propq);
790     if (cert == NULL)
791         return NULL;
792 
793     if ((d2i_X509_AUX(&cert, &blob, (long)len)) != NULL
794         || (ignore_trusted && (d2i_X509(&cert, &blob, (long)len)) != NULL)) {
795         *matchcount = 1;
796         store_info = OSSL_STORE_INFO_new_CERT(cert);
797     }
798 
799     if (store_info == NULL)
800         X509_free(cert);
801 
802     return store_info;
803 }
804 
805 static FILE_HANDLER X509Certificate_handler = {
806     "X509Certificate",
807     try_decode_X509Certificate
808 };
809 
810 /*
811  * X.509 CRL decoder.
812  */
try_decode_X509CRL(const char * pem_name,const char * pem_header,const unsigned char * blob,size_t len,void ** pctx,int * matchcount,const UI_METHOD * ui_method,void * ui_data,const char * uri,OSSL_LIB_CTX * libctx,const char * propq)813 static OSSL_STORE_INFO *try_decode_X509CRL(const char *pem_name,
814                                            const char *pem_header,
815                                            const unsigned char *blob,
816                                            size_t len, void **pctx,
817                                            int *matchcount,
818                                            const UI_METHOD *ui_method,
819                                            void *ui_data, const char *uri,
820                                            OSSL_LIB_CTX *libctx,
821                                            const char *propq)
822 {
823     OSSL_STORE_INFO *store_info = NULL;
824     X509_CRL *crl = NULL;
825 
826     if (len > LONG_MAX)
827         return NULL;
828     if (pem_name != NULL) {
829         if (strcmp(pem_name, PEM_STRING_X509_CRL) != 0)
830             /* No match */
831             return NULL;
832         *matchcount = 1;
833     }
834 
835     if ((crl = d2i_X509_CRL(NULL, &blob, (long)len)) != NULL) {
836         *matchcount = 1;
837         store_info = OSSL_STORE_INFO_new_CRL(crl);
838     }
839 
840     if (store_info == NULL)
841         X509_CRL_free(crl);
842 
843     return store_info;
844 }
845 
846 static FILE_HANDLER X509CRL_handler = {
847     "X509CRL",
848     try_decode_X509CRL
849 };
850 
851 /*
852  * To finish it all off, we collect all the handlers.
853  */
854 static const FILE_HANDLER *file_handlers[] = {
855     &PKCS12_handler,
856     &PKCS8Encrypted_handler,
857     &X509Certificate_handler,
858     &X509CRL_handler,
859     &params_handler,
860     &PUBKEY_handler,
861     &PrivateKey_handler,
862 };
863 
864 
865 /*-
866  *  The loader itself
867  *  -----------------
868  */
869 
870 struct ossl_store_loader_ctx_st {
871     char *uri;                   /* The URI we currently try to load */
872     enum {
873         is_raw = 0,
874         is_pem,
875         is_dir
876     } type;
877     int errcnt;
878 #define FILE_FLAG_SECMEM         (1<<0)
879 #define FILE_FLAG_ATTACHED       (1<<1)
880     unsigned int flags;
881     union {
882         struct { /* Used with is_raw and is_pem */
883             BIO *file;
884 
885             /*
886              * The following are used when the handler is marked as
887              * repeatable
888              */
889             const FILE_HANDLER *last_handler;
890             void *last_handler_ctx;
891         } file;
892         struct { /* Used with is_dir */
893             OPENSSL_DIR_CTX *ctx;
894             int end_reached;
895 
896             /*
897              * When a search expression is given, these are filled in.
898              * |search_name| contains the file basename to look for.
899              * The string is exactly 8 characters long.
900              */
901             char search_name[9];
902 
903             /*
904              * The directory reading utility we have combines opening with
905              * reading the first name.  To make sure we can detect the end
906              * at the right time, we read early and cache the name.
907              */
908             const char *last_entry;
909             int last_errno;
910         } dir;
911     } _;
912 
913     /* Expected object type.  May be unspecified */
914     int expected_type;
915 
916     OSSL_LIB_CTX *libctx;
917     char *propq;
918 };
919 
OSSL_STORE_LOADER_CTX_free(OSSL_STORE_LOADER_CTX * ctx)920 static void OSSL_STORE_LOADER_CTX_free(OSSL_STORE_LOADER_CTX *ctx)
921 {
922     if (ctx == NULL)
923         return;
924 
925     OPENSSL_free(ctx->propq);
926     OPENSSL_free(ctx->uri);
927     if (ctx->type != is_dir) {
928         if (ctx->_.file.last_handler != NULL) {
929             ctx->_.file.last_handler->destroy_ctx(&ctx->_.file.last_handler_ctx);
930             ctx->_.file.last_handler_ctx = NULL;
931             ctx->_.file.last_handler = NULL;
932         }
933     }
934     OPENSSL_free(ctx);
935 }
936 
file_find_type(OSSL_STORE_LOADER_CTX * ctx)937 static int file_find_type(OSSL_STORE_LOADER_CTX *ctx)
938 {
939     BIO *buff = NULL;
940     char peekbuf[4096] = { 0, };
941 
942     if ((buff = BIO_new(BIO_f_buffer())) == NULL)
943         return 0;
944 
945     ctx->_.file.file = BIO_push(buff, ctx->_.file.file);
946     if (BIO_buffer_peek(ctx->_.file.file, peekbuf, sizeof(peekbuf) - 1) > 0) {
947         peekbuf[sizeof(peekbuf) - 1] = '\0';
948         if (strstr(peekbuf, "-----BEGIN ") != NULL)
949             ctx->type = is_pem;
950     }
951     return 1;
952 }
953 
file_open_ex(const OSSL_STORE_LOADER * loader,const char * uri,OSSL_LIB_CTX * libctx,const char * propq,const UI_METHOD * ui_method,void * ui_data)954 static OSSL_STORE_LOADER_CTX *file_open_ex
955     (const OSSL_STORE_LOADER *loader, const char *uri,
956      OSSL_LIB_CTX *libctx, const char *propq,
957      const UI_METHOD *ui_method, void *ui_data)
958 {
959     OSSL_STORE_LOADER_CTX *ctx = NULL;
960     struct stat st;
961     const char *path_data[2];
962     size_t path_data_n = 0, i;
963     const char *path, *p = uri, *q;
964 
965     /*
966      * First step, just take the URI as is.
967      */
968     path_data[path_data_n++] = uri;
969 
970     /*
971      * Second step, if the URI appears to start with the "file" scheme,
972      * extract the path and make that the second path to check.
973      * There's a special case if the URI also contains an authority, then
974      * the full URI shouldn't be used as a path anywhere.
975      */
976     if (CHECK_AND_SKIP_CASE_PREFIX(p, "file:")) {
977         q = p;
978         if (CHECK_AND_SKIP_PREFIX(q, "//")) {
979             path_data_n--;           /* Invalidate using the full URI */
980             if (CHECK_AND_SKIP_CASE_PREFIX(q, "localhost/")
981                 || CHECK_AND_SKIP_PREFIX(q, "/")) {
982                 /*
983                  * In this case, we step back on char to ensure that the
984                  * first slash is preserved, making the path always absolute
985                  */
986                 p = q - 1;
987             } else {
988                 ATTICerr(0, ATTIC_R_URI_AUTHORITY_UNSUPPORTED);
989                 return NULL;
990             }
991         }
992 #ifdef _WIN32
993         /* Windows "file:" URIs with a drive letter start with a '/' */
994         if (p[0] == '/' && p[2] == ':' && p[3] == '/') {
995             char c = tolower((unsigned char)p[1]);
996 
997             if (c >= 'a' && c <= 'z') {
998                 /* Skip past the slash, making the path a normal Windows path */
999                 p++;
1000             }
1001         }
1002 #endif
1003         path_data[path_data_n++] = p;
1004     }
1005 
1006 
1007     for (i = 0, path = NULL; path == NULL && i < path_data_n; i++) {
1008         if (stat(path_data[i], &st) < 0) {
1009             ERR_raise_data(ERR_LIB_SYS, errno,
1010                            "calling stat(%s)",
1011                            path_data[i]);
1012         } else {
1013             path = path_data[i];
1014         }
1015     }
1016     if (path == NULL) {
1017         return NULL;
1018     }
1019 
1020     /* Successfully found a working path */
1021 
1022     ctx = OPENSSL_zalloc(sizeof(*ctx));
1023     if (ctx == NULL)
1024         return NULL;
1025     ctx->uri = OPENSSL_strdup(uri);
1026     if (ctx->uri == NULL)
1027         goto err;
1028 
1029     if (S_ISDIR(st.st_mode)) {
1030         ctx->type = is_dir;
1031         ctx->_.dir.last_entry = OPENSSL_DIR_read(&ctx->_.dir.ctx, path);
1032         ctx->_.dir.last_errno = errno;
1033         if (ctx->_.dir.last_entry == NULL) {
1034             if (ctx->_.dir.last_errno != 0) {
1035                 ERR_raise(ERR_LIB_SYS, ctx->_.dir.last_errno);
1036                 goto err;
1037             }
1038             ctx->_.dir.end_reached = 1;
1039         }
1040     } else if ((ctx->_.file.file = BIO_new_file(path, "rb")) == NULL
1041                || !file_find_type(ctx)) {
1042         BIO_free_all(ctx->_.file.file);
1043         goto err;
1044     }
1045     if (propq != NULL) {
1046         ctx->propq = OPENSSL_strdup(propq);
1047         if (ctx->propq == NULL)
1048             goto err;
1049     }
1050     ctx->libctx = libctx;
1051 
1052     return ctx;
1053  err:
1054     OSSL_STORE_LOADER_CTX_free(ctx);
1055     return NULL;
1056 }
1057 
file_open(const OSSL_STORE_LOADER * loader,const char * uri,const UI_METHOD * ui_method,void * ui_data)1058 static OSSL_STORE_LOADER_CTX *file_open
1059     (const OSSL_STORE_LOADER *loader, const char *uri,
1060      const UI_METHOD *ui_method, void *ui_data)
1061 {
1062     return file_open_ex(loader, uri, NULL, NULL, ui_method, ui_data);
1063 }
1064 
file_attach(const OSSL_STORE_LOADER * loader,BIO * bp,OSSL_LIB_CTX * libctx,const char * propq,const UI_METHOD * ui_method,void * ui_data)1065 static OSSL_STORE_LOADER_CTX *file_attach
1066     (const OSSL_STORE_LOADER *loader, BIO *bp,
1067      OSSL_LIB_CTX *libctx, const char *propq,
1068      const UI_METHOD *ui_method, void *ui_data)
1069 {
1070     OSSL_STORE_LOADER_CTX *ctx = NULL;
1071 
1072     if ((ctx = OPENSSL_zalloc(sizeof(*ctx))) == NULL
1073         || (propq != NULL && (ctx->propq = OPENSSL_strdup(propq)) == NULL)) {
1074         OSSL_STORE_LOADER_CTX_free(ctx);
1075         return NULL;
1076     }
1077     ctx->libctx = libctx;
1078     ctx->flags |= FILE_FLAG_ATTACHED;
1079     ctx->_.file.file = bp;
1080     if (!file_find_type(ctx)) {
1081         /* Safety measure */
1082         ctx->_.file.file = NULL;
1083         goto err;
1084     }
1085     return ctx;
1086 err:
1087     OSSL_STORE_LOADER_CTX_free(ctx);
1088     return NULL;
1089 }
1090 
file_ctrl(OSSL_STORE_LOADER_CTX * ctx,int cmd,va_list args)1091 static int file_ctrl(OSSL_STORE_LOADER_CTX *ctx, int cmd, va_list args)
1092 {
1093     int ret = 1;
1094 
1095     switch (cmd) {
1096     case OSSL_STORE_C_USE_SECMEM:
1097         {
1098             int on = *(va_arg(args, int *));
1099 
1100             switch (on) {
1101             case 0:
1102                 ctx->flags &= ~FILE_FLAG_SECMEM;
1103                 break;
1104             case 1:
1105                 ctx->flags |= FILE_FLAG_SECMEM;
1106                 break;
1107             default:
1108                 ATTICerr(0, ERR_R_PASSED_INVALID_ARGUMENT);
1109                 ret = 0;
1110                 break;
1111             }
1112         }
1113         break;
1114     default:
1115         break;
1116     }
1117 
1118     return ret;
1119 }
1120 
file_expect(OSSL_STORE_LOADER_CTX * ctx,int expected)1121 static int file_expect(OSSL_STORE_LOADER_CTX *ctx, int expected)
1122 {
1123     ctx->expected_type = expected;
1124     return 1;
1125 }
1126 
file_find(OSSL_STORE_LOADER_CTX * ctx,const OSSL_STORE_SEARCH * search)1127 static int file_find(OSSL_STORE_LOADER_CTX *ctx,
1128                      const OSSL_STORE_SEARCH *search)
1129 {
1130     /*
1131      * If ctx == NULL, the library is looking to know if this loader supports
1132      * the given search type.
1133      */
1134 
1135     if (OSSL_STORE_SEARCH_get_type(search) == OSSL_STORE_SEARCH_BY_NAME) {
1136         unsigned long hash = 0;
1137 
1138         if (ctx == NULL)
1139             return 1;
1140 
1141         if (ctx->type != is_dir) {
1142             ATTICerr(0, ATTIC_R_SEARCH_ONLY_SUPPORTED_FOR_DIRECTORIES);
1143             return 0;
1144         }
1145 
1146         hash = X509_NAME_hash_ex(OSSL_STORE_SEARCH_get0_name(search),
1147                                  NULL, NULL, NULL);
1148         BIO_snprintf(ctx->_.dir.search_name, sizeof(ctx->_.dir.search_name),
1149                      "%08lx", hash);
1150         return 1;
1151     }
1152 
1153     if (ctx != NULL)
1154         ATTICerr(0, ATTIC_R_UNSUPPORTED_SEARCH_TYPE);
1155     return 0;
1156 }
1157 
file_load_try_decode(OSSL_STORE_LOADER_CTX * ctx,const char * pem_name,const char * pem_header,unsigned char * data,size_t len,const UI_METHOD * ui_method,void * ui_data,int * matchcount)1158 static OSSL_STORE_INFO *file_load_try_decode(OSSL_STORE_LOADER_CTX *ctx,
1159                                              const char *pem_name,
1160                                              const char *pem_header,
1161                                              unsigned char *data, size_t len,
1162                                              const UI_METHOD *ui_method,
1163                                              void *ui_data, int *matchcount)
1164 {
1165     OSSL_STORE_INFO *result = NULL;
1166     BUF_MEM *new_mem = NULL;
1167     char *new_pem_name = NULL;
1168     int t = 0;
1169 
1170  again:
1171     {
1172         size_t i = 0;
1173         void *handler_ctx = NULL;
1174         const FILE_HANDLER **matching_handlers =
1175             OPENSSL_zalloc(sizeof(*matching_handlers)
1176                            * OSSL_NELEM(file_handlers));
1177 
1178         if (matching_handlers == NULL)
1179             goto err;
1180 
1181         *matchcount = 0;
1182         for (i = 0; i < OSSL_NELEM(file_handlers); i++) {
1183             const FILE_HANDLER *handler = file_handlers[i];
1184             int try_matchcount = 0;
1185             void *tmp_handler_ctx = NULL;
1186             OSSL_STORE_INFO *tmp_result;
1187             unsigned long err;
1188 
1189             ERR_set_mark();
1190             tmp_result =
1191                 handler->try_decode(pem_name, pem_header, data, len,
1192                                     &tmp_handler_ctx, &try_matchcount,
1193                                     ui_method, ui_data, ctx->uri,
1194                                     ctx->libctx, ctx->propq);
1195             /* avoid flooding error queue with low-level ASN.1 parse errors */
1196             err = ERR_peek_last_error();
1197             if (ERR_GET_LIB(err) == ERR_LIB_ASN1
1198                     && ERR_GET_REASON(err) == ERR_R_NESTED_ASN1_ERROR)
1199                 ERR_pop_to_mark();
1200             else
1201                 ERR_clear_last_mark();
1202 
1203             if (try_matchcount > 0) {
1204 
1205                 matching_handlers[*matchcount] = handler;
1206 
1207                 if (handler_ctx)
1208                     handler->destroy_ctx(&handler_ctx);
1209                 handler_ctx = tmp_handler_ctx;
1210 
1211                 if ((*matchcount += try_matchcount) > 1) {
1212                     /* more than one match => ambiguous, kill any result */
1213                     store_info_free(result);
1214                     store_info_free(tmp_result);
1215                     if (handler->destroy_ctx != NULL)
1216                         handler->destroy_ctx(&handler_ctx);
1217                     handler_ctx = NULL;
1218                     tmp_result = NULL;
1219                     result = NULL;
1220                 }
1221                 if (result == NULL)
1222                     result = tmp_result;
1223                 if (result == NULL) /* e.g., PKCS#12 file decryption error */
1224                     break;
1225             }
1226         }
1227 
1228         if (result != NULL
1229                 && *matchcount == 1 && matching_handlers[0]->repeatable) {
1230             ctx->_.file.last_handler = matching_handlers[0];
1231             ctx->_.file.last_handler_ctx = handler_ctx;
1232         }
1233 
1234         OPENSSL_free(matching_handlers);
1235     }
1236 
1237  err:
1238     OPENSSL_free(new_pem_name);
1239     BUF_MEM_free(new_mem);
1240 
1241     if (result != NULL
1242         && (t = OSSL_STORE_INFO_get_type(result)) == STORE_INFO_EMBEDDED) {
1243         struct embedded_st *embedded = get0_EMBEDDED(result);
1244 
1245         /* "steal" the embedded data */
1246         pem_name = new_pem_name = embedded->pem_name;
1247         new_mem = embedded->blob;
1248         data = (unsigned char *)new_mem->data;
1249         len = new_mem->length;
1250         embedded->pem_name = NULL;
1251         embedded->blob = NULL;
1252 
1253         store_info_free(result);
1254         result = NULL;
1255         goto again;
1256     }
1257 
1258     return result;
1259 }
1260 
file_load_try_repeat(OSSL_STORE_LOADER_CTX * ctx,const UI_METHOD * ui_method,void * ui_data)1261 static OSSL_STORE_INFO *file_load_try_repeat(OSSL_STORE_LOADER_CTX *ctx,
1262                                              const UI_METHOD *ui_method,
1263                                              void *ui_data)
1264 {
1265     OSSL_STORE_INFO *result = NULL;
1266     int try_matchcount = 0;
1267 
1268     if (ctx->_.file.last_handler != NULL) {
1269         result =
1270             ctx->_.file.last_handler->try_decode(NULL, NULL, NULL, 0,
1271                                                  &ctx->_.file.last_handler_ctx,
1272                                                  &try_matchcount,
1273                                                  ui_method, ui_data, ctx->uri,
1274                                                  ctx->libctx, ctx->propq);
1275 
1276         if (result == NULL) {
1277             ctx->_.file.last_handler->destroy_ctx(&ctx->_.file.last_handler_ctx);
1278             ctx->_.file.last_handler_ctx = NULL;
1279             ctx->_.file.last_handler = NULL;
1280         }
1281     }
1282     return result;
1283 }
1284 
pem_free_flag(void * pem_data,int secure,size_t num)1285 static void pem_free_flag(void *pem_data, int secure, size_t num)
1286 {
1287     if (secure)
1288         OPENSSL_secure_clear_free(pem_data, num);
1289     else
1290         OPENSSL_free(pem_data);
1291 }
file_read_pem(BIO * bp,char ** pem_name,char ** pem_header,unsigned char ** data,long * len,const UI_METHOD * ui_method,void * ui_data,const char * uri,int secure)1292 static int file_read_pem(BIO *bp, char **pem_name, char **pem_header,
1293                          unsigned char **data, long *len,
1294                          const UI_METHOD *ui_method, void *ui_data,
1295                          const char *uri, int secure)
1296 {
1297     int i = secure
1298         ? PEM_read_bio_ex(bp, pem_name, pem_header, data, len,
1299                           PEM_FLAG_SECURE | PEM_FLAG_EAY_COMPATIBLE)
1300         : PEM_read_bio(bp, pem_name, pem_header, data, len);
1301 
1302     if (i <= 0)
1303         return 0;
1304 
1305     /*
1306      * 10 is the number of characters in "Proc-Type:", which
1307      * PEM_get_EVP_CIPHER_INFO() requires to be present.
1308      * If the PEM header has less characters than that, it's
1309      * not worth spending cycles on it.
1310      */
1311     if (strlen(*pem_header) > 10) {
1312         EVP_CIPHER_INFO cipher;
1313         struct pem_pass_data pass_data;
1314 
1315         if (!PEM_get_EVP_CIPHER_INFO(*pem_header, &cipher)
1316             || !file_fill_pem_pass_data(&pass_data, "PEM pass phrase", uri,
1317                                         ui_method, ui_data)
1318             || !PEM_do_header(&cipher, *data, len, file_get_pem_pass,
1319                               &pass_data)) {
1320             return 0;
1321         }
1322     }
1323     return 1;
1324 }
1325 
file_try_read_msblob(BIO * bp,int * matchcount)1326 static OSSL_STORE_INFO *file_try_read_msblob(BIO *bp, int *matchcount)
1327 {
1328     OSSL_STORE_INFO *result = NULL;
1329     int ispub = -1;
1330 
1331     {
1332         unsigned int magic = 0, bitlen = 0;
1333         int isdss = 0;
1334         unsigned char peekbuf[16] = { 0, };
1335         const unsigned char *p = peekbuf;
1336 
1337         if (BIO_buffer_peek(bp, peekbuf, sizeof(peekbuf)) <= 0)
1338             return 0;
1339         if (ossl_do_blob_header(&p, sizeof(peekbuf), &magic, &bitlen,
1340                                  &isdss, &ispub) <= 0)
1341             return 0;
1342     }
1343 
1344     (*matchcount)++;
1345 
1346     {
1347         EVP_PKEY *tmp = ispub
1348             ? b2i_PublicKey_bio(bp)
1349             : b2i_PrivateKey_bio(bp);
1350 
1351         if (tmp == NULL
1352             || (result = OSSL_STORE_INFO_new_PKEY(tmp)) == NULL) {
1353             EVP_PKEY_free(tmp);
1354             return 0;
1355         }
1356     }
1357 
1358     return result;
1359 }
1360 
file_try_read_PVK(BIO * bp,const UI_METHOD * ui_method,void * ui_data,const char * uri,int * matchcount)1361 static OSSL_STORE_INFO *file_try_read_PVK(BIO *bp, const UI_METHOD *ui_method,
1362                                           void *ui_data, const char *uri,
1363                                           int *matchcount)
1364 {
1365     OSSL_STORE_INFO *result = NULL;
1366 
1367     {
1368         unsigned int saltlen = 0, keylen = 0;
1369         int isdss = -1;
1370         unsigned char peekbuf[24] = { 0, };
1371         const unsigned char *p = peekbuf;
1372 
1373         if (BIO_buffer_peek(bp, peekbuf, sizeof(peekbuf)) <= 0)
1374             return 0;
1375         if (!ossl_do_PVK_header(&p, sizeof(peekbuf), 0, &isdss, &saltlen, &keylen))
1376             return 0;
1377     }
1378 
1379     (*matchcount)++;
1380 
1381     {
1382         EVP_PKEY *tmp = NULL;
1383         struct pem_pass_data pass_data;
1384 
1385         if (!file_fill_pem_pass_data(&pass_data, "PVK pass phrase", uri,
1386                                      ui_method, ui_data)
1387             || (tmp = b2i_PVK_bio(bp, file_get_pem_pass, &pass_data)) == NULL
1388             || (result = OSSL_STORE_INFO_new_PKEY(tmp)) == NULL) {
1389             EVP_PKEY_free(tmp);
1390             return 0;
1391         }
1392     }
1393 
1394     return result;
1395 }
1396 
file_read_asn1(BIO * bp,unsigned char ** data,long * len)1397 static int file_read_asn1(BIO *bp, unsigned char **data, long *len)
1398 {
1399     BUF_MEM *mem = NULL;
1400 
1401     if (asn1_d2i_read_bio(bp, &mem) < 0)
1402         return 0;
1403 
1404     *data = (unsigned char *)mem->data;
1405     *len = (long)mem->length;
1406     OPENSSL_free(mem);
1407 
1408     return 1;
1409 }
1410 
file_name_to_uri(OSSL_STORE_LOADER_CTX * ctx,const char * name,char ** data)1411 static int file_name_to_uri(OSSL_STORE_LOADER_CTX *ctx, const char *name,
1412                             char **data)
1413 {
1414     assert(name != NULL);
1415     assert(data != NULL);
1416     {
1417         const char *pathsep = ossl_ends_with_dirsep(ctx->uri) ? "" : "/";
1418         long calculated_length = (long)(strlen(ctx->uri) + strlen(pathsep)
1419             + strlen(name) + 1 /* \0 */);
1420 
1421         *data = OPENSSL_zalloc(calculated_length);
1422         if (*data == NULL)
1423             return 0;
1424 
1425         OPENSSL_strlcat(*data, ctx->uri, calculated_length);
1426         OPENSSL_strlcat(*data, pathsep, calculated_length);
1427         OPENSSL_strlcat(*data, name, calculated_length);
1428     }
1429     return 1;
1430 }
1431 
file_name_check(OSSL_STORE_LOADER_CTX * ctx,const char * name)1432 static int file_name_check(OSSL_STORE_LOADER_CTX *ctx, const char *name)
1433 {
1434     const char *p = NULL;
1435     size_t len = strlen(ctx->_.dir.search_name);
1436 
1437     /* If there are no search criteria, all names are accepted */
1438     if (ctx->_.dir.search_name[0] == '\0')
1439         return 1;
1440 
1441     /* If the expected type isn't supported, no name is accepted */
1442     if (ctx->expected_type != 0
1443         && ctx->expected_type != OSSL_STORE_INFO_CERT
1444         && ctx->expected_type != OSSL_STORE_INFO_CRL)
1445         return 0;
1446 
1447     /*
1448      * First, check the basename
1449      */
1450     if (OPENSSL_strncasecmp(name, ctx->_.dir.search_name, len) != 0
1451         || name[len] != '.')
1452         return 0;
1453     p = &name[len + 1];
1454 
1455     /*
1456      * Then, if the expected type is a CRL, check that the extension starts
1457      * with 'r'
1458      */
1459     if (*p == 'r') {
1460         p++;
1461         if (ctx->expected_type != 0
1462             && ctx->expected_type != OSSL_STORE_INFO_CRL)
1463             return 0;
1464     } else if (ctx->expected_type == OSSL_STORE_INFO_CRL) {
1465         return 0;
1466     }
1467 
1468     /*
1469      * Last, check that the rest of the extension is a decimal number, at
1470      * least one digit long.
1471      */
1472     if (!isdigit((unsigned char)*p))
1473         return 0;
1474     while (isdigit((unsigned char)*p))
1475         p++;
1476 
1477 #ifdef __VMS
1478     /*
1479      * One extra step here, check for a possible generation number.
1480      */
1481     if (*p == ';')
1482         for (p++; *p != '\0'; p++)
1483             if (!ossl_isdigit(*p))
1484                 break;
1485 #endif
1486 
1487     /*
1488      * If we've reached the end of the string at this point, we've successfully
1489      * found a fitting file name.
1490      */
1491     return *p == '\0';
1492 }
1493 
1494 static int file_eof(OSSL_STORE_LOADER_CTX *ctx);
1495 static int file_error(OSSL_STORE_LOADER_CTX *ctx);
file_load(OSSL_STORE_LOADER_CTX * ctx,const UI_METHOD * ui_method,void * ui_data)1496 static OSSL_STORE_INFO *file_load(OSSL_STORE_LOADER_CTX *ctx,
1497                                   const UI_METHOD *ui_method,
1498                                   void *ui_data)
1499 {
1500     OSSL_STORE_INFO *result = NULL;
1501 
1502     ctx->errcnt = 0;
1503 
1504     if (ctx->type == is_dir) {
1505         do {
1506             char *newname = NULL;
1507 
1508             if (ctx->_.dir.last_entry == NULL) {
1509                 if (!ctx->_.dir.end_reached) {
1510                     assert(ctx->_.dir.last_errno != 0);
1511                     ERR_raise(ERR_LIB_SYS, ctx->_.dir.last_errno);
1512                     ctx->errcnt++;
1513                 }
1514                 return NULL;
1515             }
1516 
1517             if (ctx->_.dir.last_entry[0] != '.'
1518                 && file_name_check(ctx, ctx->_.dir.last_entry)
1519                 && !file_name_to_uri(ctx, ctx->_.dir.last_entry, &newname))
1520                 return NULL;
1521 
1522             /*
1523              * On the first call (with a NULL context), OPENSSL_DIR_read()
1524              * cares about the second argument.  On the following calls, it
1525              * only cares that it isn't NULL.  Therefore, we can safely give
1526              * it our URI here.
1527              */
1528             ctx->_.dir.last_entry = OPENSSL_DIR_read(&ctx->_.dir.ctx, ctx->uri);
1529             ctx->_.dir.last_errno = errno;
1530             if (ctx->_.dir.last_entry == NULL && ctx->_.dir.last_errno == 0)
1531                 ctx->_.dir.end_reached = 1;
1532 
1533             if (newname != NULL
1534                 && (result = OSSL_STORE_INFO_new_NAME(newname)) == NULL) {
1535                 OPENSSL_free(newname);
1536                 ATTICerr(0, ERR_R_OSSL_STORE_LIB);
1537                 return NULL;
1538             }
1539         } while (result == NULL && !file_eof(ctx));
1540     } else {
1541         int matchcount = -1;
1542 
1543      again:
1544         result = file_load_try_repeat(ctx, ui_method, ui_data);
1545         if (result != NULL)
1546             return result;
1547 
1548         if (file_eof(ctx))
1549             return NULL;
1550 
1551         do {
1552             char *pem_name = NULL;      /* PEM record name */
1553             char *pem_header = NULL;    /* PEM record header */
1554             unsigned char *data = NULL; /* DER encoded data */
1555             long len = 0;               /* DER encoded data length */
1556 
1557             matchcount = -1;
1558             if (ctx->type == is_pem) {
1559                 if (!file_read_pem(ctx->_.file.file, &pem_name, &pem_header,
1560                                    &data, &len, ui_method, ui_data, ctx->uri,
1561                                    (ctx->flags & FILE_FLAG_SECMEM) != 0)) {
1562                     ctx->errcnt++;
1563                     goto endloop;
1564                 }
1565             } else {
1566                 if ((result = file_try_read_msblob(ctx->_.file.file,
1567                                                    &matchcount)) != NULL
1568                     || (result = file_try_read_PVK(ctx->_.file.file,
1569                                                    ui_method, ui_data, ctx->uri,
1570                                                    &matchcount)) != NULL)
1571                     goto endloop;
1572 
1573                 if (!file_read_asn1(ctx->_.file.file, &data, &len)) {
1574                     ctx->errcnt++;
1575                     goto endloop;
1576                 }
1577             }
1578 
1579             result = file_load_try_decode(ctx, pem_name, pem_header, data, len,
1580                                           ui_method, ui_data, &matchcount);
1581 
1582             if (result != NULL)
1583                 goto endloop;
1584 
1585             /*
1586              * If a PEM name matches more than one handler, the handlers are
1587              * badly coded.
1588              */
1589             if (!ossl_assert(pem_name == NULL || matchcount <= 1)) {
1590                 ctx->errcnt++;
1591                 goto endloop;
1592             }
1593 
1594             if (matchcount > 1) {
1595                 ATTICerr(0, ATTIC_R_AMBIGUOUS_CONTENT_TYPE);
1596             } else if (matchcount == 1) {
1597                 /*
1598                  * If there are other errors on the stack, they already show
1599                  * what the problem is.
1600                  */
1601                 if (ERR_peek_error() == 0) {
1602                     ATTICerr(0, ATTIC_R_UNSUPPORTED_CONTENT_TYPE);
1603                     if (pem_name != NULL)
1604                         ERR_add_error_data(3, "PEM type is '", pem_name, "'");
1605                 }
1606             }
1607             if (matchcount > 0)
1608                 ctx->errcnt++;
1609 
1610          endloop:
1611             pem_free_flag(pem_name, (ctx->flags & FILE_FLAG_SECMEM) != 0, 0);
1612             pem_free_flag(pem_header, (ctx->flags & FILE_FLAG_SECMEM) != 0, 0);
1613             pem_free_flag(data, (ctx->flags & FILE_FLAG_SECMEM) != 0, len);
1614         } while (matchcount == 0 && !file_eof(ctx) && !file_error(ctx));
1615 
1616         /* We bail out on ambiguity */
1617         if (matchcount > 1) {
1618             store_info_free(result);
1619             return NULL;
1620         }
1621 
1622         if (result != NULL
1623             && ctx->expected_type != 0
1624             && ctx->expected_type != OSSL_STORE_INFO_get_type(result)) {
1625             store_info_free(result);
1626             goto again;
1627         }
1628     }
1629 
1630     return result;
1631 }
1632 
file_error(OSSL_STORE_LOADER_CTX * ctx)1633 static int file_error(OSSL_STORE_LOADER_CTX *ctx)
1634 {
1635     return ctx->errcnt > 0;
1636 }
1637 
file_eof(OSSL_STORE_LOADER_CTX * ctx)1638 static int file_eof(OSSL_STORE_LOADER_CTX *ctx)
1639 {
1640     if (ctx->type == is_dir)
1641         return ctx->_.dir.end_reached;
1642 
1643     if (ctx->_.file.last_handler != NULL
1644         && !ctx->_.file.last_handler->eof(ctx->_.file.last_handler_ctx))
1645         return 0;
1646     return BIO_eof(ctx->_.file.file);
1647 }
1648 
file_close(OSSL_STORE_LOADER_CTX * ctx)1649 static int file_close(OSSL_STORE_LOADER_CTX *ctx)
1650 {
1651     if ((ctx->flags & FILE_FLAG_ATTACHED) == 0) {
1652         if (ctx->type == is_dir)
1653             OPENSSL_DIR_end(&ctx->_.dir.ctx);
1654         else
1655             BIO_free_all(ctx->_.file.file);
1656     } else {
1657         /*
1658          * Because file_attach() called file_find_type(), we know that a
1659          * BIO_f_buffer() has been pushed on top of the regular BIO.
1660          */
1661         BIO *buff = ctx->_.file.file;
1662 
1663         /* Detach buff */
1664         (void)BIO_pop(ctx->_.file.file);
1665         /* Safety measure */
1666         ctx->_.file.file = NULL;
1667 
1668         BIO_free(buff);
1669     }
1670     OSSL_STORE_LOADER_CTX_free(ctx);
1671     return 1;
1672 }
1673 
1674 /*-
1675  * ENGINE management
1676  */
1677 
1678 static const char *loader_attic_id = "loader_attic";
1679 static const char *loader_attic_name = "'file:' loader";
1680 
1681 static OSSL_STORE_LOADER *loader_attic = NULL;
1682 
loader_attic_init(ENGINE * e)1683 static int loader_attic_init(ENGINE *e)
1684 {
1685     return 1;
1686 }
1687 
1688 
loader_attic_finish(ENGINE * e)1689 static int loader_attic_finish(ENGINE *e)
1690 {
1691     return 1;
1692 }
1693 
1694 
loader_attic_destroy(ENGINE * e)1695 static int loader_attic_destroy(ENGINE *e)
1696 {
1697     OSSL_STORE_LOADER *loader = OSSL_STORE_unregister_loader("file");
1698 
1699     if (loader == NULL)
1700         return 0;
1701 
1702     ERR_unload_ATTIC_strings();
1703     OSSL_STORE_LOADER_free(loader);
1704     return 1;
1705 }
1706 
bind_loader_attic(ENGINE * e)1707 static int bind_loader_attic(ENGINE *e)
1708 {
1709 
1710     /* Ensure the ATTIC error handling is set up on best effort basis */
1711     ERR_load_ATTIC_strings();
1712 
1713     if (/* Create the OSSL_STORE_LOADER */
1714         (loader_attic = OSSL_STORE_LOADER_new(e, "file")) == NULL
1715         || !OSSL_STORE_LOADER_set_open_ex(loader_attic, file_open_ex)
1716         || !OSSL_STORE_LOADER_set_open(loader_attic, file_open)
1717         || !OSSL_STORE_LOADER_set_attach(loader_attic, file_attach)
1718         || !OSSL_STORE_LOADER_set_ctrl(loader_attic, file_ctrl)
1719         || !OSSL_STORE_LOADER_set_expect(loader_attic, file_expect)
1720         || !OSSL_STORE_LOADER_set_find(loader_attic, file_find)
1721         || !OSSL_STORE_LOADER_set_load(loader_attic, file_load)
1722         || !OSSL_STORE_LOADER_set_eof(loader_attic, file_eof)
1723         || !OSSL_STORE_LOADER_set_error(loader_attic, file_error)
1724         || !OSSL_STORE_LOADER_set_close(loader_attic, file_close)
1725         /* Init the engine itself */
1726         || !ENGINE_set_id(e, loader_attic_id)
1727         || !ENGINE_set_name(e, loader_attic_name)
1728         || !ENGINE_set_destroy_function(e, loader_attic_destroy)
1729         || !ENGINE_set_init_function(e, loader_attic_init)
1730         || !ENGINE_set_finish_function(e, loader_attic_finish)
1731         /* Finally, register the method with libcrypto */
1732         || !OSSL_STORE_register_loader(loader_attic)) {
1733         OSSL_STORE_LOADER_free(loader_attic);
1734         loader_attic = NULL;
1735         ATTICerr(0, ATTIC_R_INIT_FAILED);
1736         return 0;
1737     }
1738 
1739     return 1;
1740 }
1741 
1742 #ifdef OPENSSL_NO_DYNAMIC_ENGINE
1743 # error "Only allowed as dynamically shared object"
1744 #endif
1745 
bind_helper(ENGINE * e,const char * id)1746 static int bind_helper(ENGINE *e, const char *id)
1747 {
1748     if (id && (strcmp(id, loader_attic_id) != 0))
1749         return 0;
1750     if (!bind_loader_attic(e))
1751         return 0;
1752     return 1;
1753 }
1754 
1755 IMPLEMENT_DYNAMIC_CHECK_FN()
1756     IMPLEMENT_DYNAMIC_BIND_FN(bind_helper)
1757