Coverage Report

Created: 2023-09-25 06:45

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