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