Coverage Report

Created: 2025-12-31 06:58

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl36/crypto/pem/pem_lib.c
Line
Count
Source
1
/*
2
 * Copyright 1995-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
/*
11
 * We need to use some engine deprecated APIs
12
 */
13
#include "internal/deprecated.h"
14
15
#include <stdio.h>
16
#include "crypto/ctype.h"
17
#include <string.h>
18
#include "internal/cryptlib.h"
19
#include <openssl/buffer.h>
20
#include <openssl/objects.h>
21
#include <openssl/evp.h>
22
#include <openssl/rand.h>
23
#include <openssl/x509.h>
24
#include <openssl/pem.h>
25
#include <openssl/pkcs12.h>
26
#include "crypto/asn1.h"
27
#include <openssl/des.h>
28
#include <openssl/engine.h>
29
30
0
#define MIN_LENGTH 4
31
32
static int load_iv(char **fromp, unsigned char *to, int num);
33
static int check_pem(const char *nm, const char *name);
34
int ossl_pem_check_suffix(const char *pem_str, const char *suffix);
35
36
int PEM_def_callback(char *buf, int num, int rwflag, void *userdata)
37
0
{
38
0
    int i, min_len;
39
0
    const char *prompt;
40
41
    /* We assume that the user passes a default password as userdata */
42
0
    if (userdata) {
43
0
        i = (int)strlen(userdata);
44
0
        i = (i > num) ? num : i;
45
0
        memcpy(buf, userdata, i);
46
0
        return i;
47
0
    }
48
49
0
    prompt = EVP_get_pw_prompt();
50
0
    if (prompt == NULL)
51
0
        prompt = "Enter PEM pass phrase:";
52
53
    /*
54
     * rwflag == 0 means decryption
55
     * rwflag == 1 means encryption
56
     *
57
     * We assume that for encryption, we want a minimum length, while for
58
     * decryption, we cannot know any minimum length, so we assume zero.
59
     */
60
0
    min_len = rwflag ? MIN_LENGTH : 0;
61
62
0
    i = EVP_read_pw_string_min(buf, min_len, num, prompt, rwflag);
63
0
    if (i != 0) {
64
0
        ERR_raise(ERR_LIB_PEM, PEM_R_PROBLEMS_GETTING_PASSWORD);
65
0
        memset(buf, 0, (unsigned int)num);
66
0
        return -1;
67
0
    }
68
0
    return (int)strlen(buf);
69
0
}
70
71
void PEM_proc_type(char *buf, int type)
72
0
{
73
0
    const char *str;
74
0
    char *p = buf + strlen(buf);
75
76
0
    if (type == PEM_TYPE_ENCRYPTED)
77
0
        str = "ENCRYPTED";
78
0
    else if (type == PEM_TYPE_MIC_CLEAR)
79
0
        str = "MIC-CLEAR";
80
0
    else if (type == PEM_TYPE_MIC_ONLY)
81
0
        str = "MIC-ONLY";
82
0
    else
83
0
        str = "BAD-TYPE";
84
85
0
    BIO_snprintf(p, PEM_BUFSIZE - (size_t)(p - buf), "Proc-Type: 4,%s\n", str);
86
0
}
87
88
void PEM_dek_info(char *buf, const char *type, int len, const char *str)
89
0
{
90
0
    long i;
91
0
    char *p = buf + strlen(buf);
92
0
    int j = PEM_BUFSIZE - (int)(p - buf), n;
93
94
0
    n = BIO_snprintf(p, j, "DEK-Info: %s,", type);
95
0
    if (n > 0) {
96
0
        j -= n;
97
0
        p += n;
98
0
        for (i = 0; i < len; i++) {
99
0
            n = BIO_snprintf(p, j, "%02X", 0xff & str[i]);
100
0
            if (n <= 0)
101
0
                return;
102
0
            j -= n;
103
0
            p += n;
104
0
        }
105
0
        if (j > 1)
106
0
            strcpy(p, "\n");
107
0
    }
108
0
}
109
110
#ifndef OPENSSL_NO_STDIO
111
void *PEM_ASN1_read(d2i_of_void *d2i, const char *name, FILE *fp, void **x,
112
    pem_password_cb *cb, void *u)
113
0
{
114
0
    BIO *b;
115
0
    void *ret;
116
117
0
    if ((b = BIO_new(BIO_s_file())) == NULL) {
118
0
        ERR_raise(ERR_LIB_PEM, ERR_R_BUF_LIB);
119
0
        return 0;
120
0
    }
121
0
    BIO_set_fp(b, fp, BIO_NOCLOSE);
122
0
    ret = PEM_ASN1_read_bio(d2i, name, b, x, cb, u);
123
0
    BIO_free(b);
124
0
    return ret;
125
0
}
126
#endif
127
128
static int check_pem(const char *nm, const char *name)
129
124k
{
130
    /* Normal matching nm and name */
131
124k
    if (strcmp(nm, name) == 0)
132
124k
        return 1;
133
134
    /* Make PEM_STRING_EVP_PKEY match any private key */
135
136
0
    if (strcmp(name, PEM_STRING_EVP_PKEY) == 0) {
137
0
        int slen;
138
0
        const EVP_PKEY_ASN1_METHOD *ameth;
139
0
        if (strcmp(nm, PEM_STRING_PKCS8) == 0)
140
0
            return 1;
141
0
        if (strcmp(nm, PEM_STRING_PKCS8INF) == 0)
142
0
            return 1;
143
0
        slen = ossl_pem_check_suffix(nm, "PRIVATE KEY");
144
0
        if (slen > 0) {
145
            /*
146
             * NB: ENGINE implementations won't contain a deprecated old
147
             * private key decode function so don't look for them.
148
             */
149
0
            ameth = EVP_PKEY_asn1_find_str(NULL, nm, slen);
150
0
            if (ameth && ameth->old_priv_decode)
151
0
                return 1;
152
0
        }
153
0
        return 0;
154
0
    }
155
156
0
    if (strcmp(name, PEM_STRING_PARAMETERS) == 0) {
157
0
        int slen;
158
0
        const EVP_PKEY_ASN1_METHOD *ameth;
159
0
        slen = ossl_pem_check_suffix(nm, "PARAMETERS");
160
0
        if (slen > 0) {
161
0
            ENGINE *e;
162
0
            ameth = EVP_PKEY_asn1_find_str(&e, nm, slen);
163
0
            if (ameth) {
164
0
                int r;
165
0
                if (ameth->param_decode)
166
0
                    r = 1;
167
0
                else
168
0
                    r = 0;
169
0
#ifndef OPENSSL_NO_ENGINE
170
0
                ENGINE_finish(e);
171
0
#endif
172
0
                return r;
173
0
            }
174
0
        }
175
0
        return 0;
176
0
    }
177
    /* If reading DH parameters handle X9.42 DH format too */
178
0
    if (strcmp(nm, PEM_STRING_DHXPARAMS) == 0
179
0
        && strcmp(name, PEM_STRING_DHPARAMS) == 0)
180
0
        return 1;
181
182
    /* Permit older strings */
183
184
0
    if (strcmp(nm, PEM_STRING_X509_OLD) == 0
185
0
        && strcmp(name, PEM_STRING_X509) == 0)
186
0
        return 1;
187
188
0
    if (strcmp(nm, PEM_STRING_X509_REQ_OLD) == 0
189
0
        && strcmp(name, PEM_STRING_X509_REQ) == 0)
190
0
        return 1;
191
192
    /* Allow normal certs to be read as trusted certs */
193
0
    if (strcmp(nm, PEM_STRING_X509) == 0
194
0
        && strcmp(name, PEM_STRING_X509_TRUSTED) == 0)
195
0
        return 1;
196
197
0
    if (strcmp(nm, PEM_STRING_X509_OLD) == 0
198
0
        && strcmp(name, PEM_STRING_X509_TRUSTED) == 0)
199
0
        return 1;
200
201
    /* Some CAs use PKCS#7 with CERTIFICATE headers */
202
0
    if (strcmp(nm, PEM_STRING_X509) == 0
203
0
        && strcmp(name, PEM_STRING_PKCS7) == 0)
204
0
        return 1;
205
206
0
    if (strcmp(nm, PEM_STRING_PKCS7_SIGNED) == 0
207
0
        && strcmp(name, PEM_STRING_PKCS7) == 0)
208
0
        return 1;
209
210
0
#ifndef OPENSSL_NO_CMS
211
0
    if (strcmp(nm, PEM_STRING_X509) == 0
212
0
        && strcmp(name, PEM_STRING_CMS) == 0)
213
0
        return 1;
214
    /* Allow CMS to be read from PKCS#7 headers */
215
0
    if (strcmp(nm, PEM_STRING_PKCS7) == 0
216
0
        && strcmp(name, PEM_STRING_CMS) == 0)
217
0
        return 1;
218
0
#endif
219
220
0
    return 0;
221
0
}
222
223
#define PEM_FREE(p, flags, num) \
224
1.24M
    pem_free((p), (flags), (num), OPENSSL_FILE, OPENSSL_LINE)
225
static void pem_free(void *p, unsigned int flags, size_t num,
226
    const char *file, int line)
227
1.46M
{
228
1.46M
    if (flags & PEM_FLAG_SECURE)
229
6.62k
        CRYPTO_secure_clear_free(p, num, file, line);
230
1.46M
    else
231
1.46M
        CRYPTO_free(p, file, line);
232
1.46M
}
233
234
#define PEM_MALLOC(num, flags) \
235
935k
    pem_malloc((num), (flags), OPENSSL_FILE, OPENSSL_LINE)
236
static void *pem_malloc(int num, unsigned int flags,
237
    const char *file, int line)
238
1.31M
{
239
1.31M
    return (flags & PEM_FLAG_SECURE) ? CRYPTO_secure_malloc(num, file, line)
240
1.31M
                                     : CRYPTO_malloc(num, file, line);
241
1.31M
}
242
243
static int pem_bytes_read_bio_flags(unsigned char **pdata, long *plen,
244
    char **pnm, const char *name, BIO *bp,
245
    pem_password_cb *cb, void *u,
246
    unsigned int flags)
247
124k
{
248
124k
    EVP_CIPHER_INFO cipher;
249
124k
    char *nm = NULL, *header = NULL;
250
124k
    unsigned char *data = NULL;
251
124k
    long len = 0;
252
124k
    int ret = 0;
253
254
124k
    do {
255
124k
        PEM_FREE(nm, flags, 0);
256
124k
        PEM_FREE(header, flags, 0);
257
124k
        PEM_FREE(data, flags, len);
258
124k
        if (!PEM_read_bio_ex(bp, &nm, &header, &data, &len, flags)) {
259
0
            if (ERR_GET_REASON(ERR_peek_error()) == PEM_R_NO_START_LINE)
260
0
                ERR_add_error_data(2, "Expecting: ", name);
261
0
            return 0;
262
0
        }
263
124k
    } while (!check_pem(nm, name));
264
124k
    if (!PEM_get_EVP_CIPHER_INFO(header, &cipher))
265
0
        goto err;
266
124k
    if (!PEM_do_header(&cipher, data, &len, cb, u))
267
0
        goto err;
268
269
124k
    *pdata = data;
270
124k
    *plen = len;
271
272
124k
    if (pnm != NULL)
273
0
        *pnm = nm;
274
275
124k
    ret = 1;
276
277
124k
err:
278
124k
    if (!ret || pnm == NULL)
279
124k
        PEM_FREE(nm, flags, 0);
280
124k
    PEM_FREE(header, flags, 0);
281
124k
    if (!ret)
282
0
        PEM_FREE(data, flags, len);
283
124k
    return ret;
284
124k
}
285
286
int PEM_bytes_read_bio(unsigned char **pdata, long *plen, char **pnm,
287
    const char *name, BIO *bp, pem_password_cb *cb,
288
    void *u)
289
124k
{
290
124k
    return pem_bytes_read_bio_flags(pdata, plen, pnm, name, bp, cb, u,
291
124k
        PEM_FLAG_EAY_COMPATIBLE);
292
124k
}
293
294
int PEM_bytes_read_bio_secmem(unsigned char **pdata, long *plen, char **pnm,
295
    const char *name, BIO *bp, pem_password_cb *cb,
296
    void *u)
297
0
{
298
0
    return pem_bytes_read_bio_flags(pdata, plen, pnm, name, bp, cb, u,
299
0
        PEM_FLAG_SECURE | PEM_FLAG_EAY_COMPATIBLE);
300
0
}
301
302
#ifndef OPENSSL_NO_STDIO
303
int PEM_ASN1_write(i2d_of_void *i2d, const char *name, FILE *fp,
304
    const void *x, const EVP_CIPHER *enc,
305
    const unsigned char *kstr, int klen,
306
    pem_password_cb *callback, void *u)
307
0
{
308
0
    BIO *b;
309
0
    int ret;
310
311
0
    if ((b = BIO_new(BIO_s_file())) == NULL) {
312
0
        ERR_raise(ERR_LIB_PEM, ERR_R_BUF_LIB);
313
0
        return 0;
314
0
    }
315
0
    BIO_set_fp(b, fp, BIO_NOCLOSE);
316
0
    ret = PEM_ASN1_write_bio(i2d, name, b, x, enc, kstr, klen, callback, u);
317
0
    BIO_free(b);
318
0
    return ret;
319
0
}
320
#endif
321
322
static int
323
PEM_ASN1_write_bio_internal(
324
    i2d_of_void *i2d, OSSL_i2d_of_void_ctx *i2d_ctx, void *vctx,
325
    const char *name, BIO *bp, const void *x, const EVP_CIPHER *enc,
326
    const unsigned char *kstr, int klen, pem_password_cb *callback, void *u)
327
0
{
328
0
    EVP_CIPHER_CTX *ctx = NULL;
329
0
    int dsize = 0, i = 0, j = 0, ret = 0;
330
0
    unsigned char *p, *data = NULL;
331
0
    const char *objstr = NULL;
332
0
    char buf[PEM_BUFSIZE];
333
0
    unsigned char key[EVP_MAX_KEY_LENGTH];
334
0
    unsigned char iv[EVP_MAX_IV_LENGTH];
335
336
0
    if (enc != NULL) {
337
0
        objstr = EVP_CIPHER_get0_name(enc);
338
0
        if (objstr == NULL || EVP_CIPHER_get_iv_length(enc) == 0
339
0
            || EVP_CIPHER_get_iv_length(enc) > (int)sizeof(iv)
340
            /*
341
             * Check "Proc-Type: 4,Encrypted\nDEK-Info: objstr,hex-iv\n"
342
             * fits into buf
343
             */
344
0
            || strlen(objstr) + 23 + 2 * EVP_CIPHER_get_iv_length(enc) + 13
345
0
                > sizeof(buf)) {
346
0
            ERR_raise(ERR_LIB_PEM, PEM_R_UNSUPPORTED_CIPHER);
347
0
            goto err;
348
0
        }
349
0
    }
350
351
0
    if (i2d == NULL && i2d_ctx == NULL) {
352
0
        ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_INVALID_NULL_ARGUMENT);
353
0
        dsize = 0;
354
0
        goto err;
355
0
    }
356
0
    dsize = i2d != NULL ? i2d(x, NULL) : i2d_ctx(x, NULL, vctx);
357
0
    if (dsize <= 0) {
358
0
        ERR_raise(ERR_LIB_PEM, ERR_R_ASN1_LIB);
359
0
        dsize = 0;
360
0
        goto err;
361
0
    }
362
    /* Allocate enough space for one extra cipher block */
363
0
    data = OPENSSL_malloc((unsigned int)dsize + EVP_MAX_BLOCK_LENGTH);
364
0
    if (data == NULL)
365
0
        goto err;
366
0
    p = data;
367
0
    i = i2d != NULL ? i2d(x, &p) : i2d_ctx(x, &p, vctx);
368
369
0
    if (enc != NULL) {
370
0
        if (kstr == NULL) {
371
0
            if (callback == NULL)
372
0
                klen = PEM_def_callback(buf, PEM_BUFSIZE, 1, u);
373
0
            else
374
0
                klen = (*callback)(buf, PEM_BUFSIZE, 1, u);
375
0
            if (klen <= 0) {
376
0
                ERR_raise(ERR_LIB_PEM, PEM_R_READ_KEY);
377
0
                goto err;
378
0
            }
379
#ifdef CHARSET_EBCDIC
380
            /* Convert the pass phrase from EBCDIC */
381
            ebcdic2ascii(buf, buf, klen);
382
#endif
383
0
            kstr = (unsigned char *)buf;
384
0
        }
385
        /* Generate a salt */
386
0
        if (RAND_bytes(iv, EVP_CIPHER_get_iv_length(enc)) <= 0)
387
0
            goto err;
388
        /*
389
         * The 'iv' is used as the iv and as a salt.  It is NOT taken from
390
         * the BytesToKey function
391
         */
392
0
        if (!EVP_BytesToKey(enc, EVP_md5(), iv, kstr, klen, 1, key, NULL))
393
0
            goto err;
394
395
0
        if (kstr == (unsigned char *)buf)
396
0
            OPENSSL_cleanse(buf, PEM_BUFSIZE);
397
398
0
        buf[0] = '\0';
399
0
        PEM_proc_type(buf, PEM_TYPE_ENCRYPTED);
400
0
        PEM_dek_info(buf, objstr, EVP_CIPHER_get_iv_length(enc), (char *)iv);
401
        /* k=strlen(buf); */
402
403
0
        ret = 1;
404
0
        if ((ctx = EVP_CIPHER_CTX_new()) == NULL
405
0
            || !EVP_EncryptInit_ex(ctx, enc, NULL, key, iv)
406
0
            || !EVP_EncryptUpdate(ctx, data, &j, data, i)
407
0
            || !EVP_EncryptFinal_ex(ctx, &(data[j]), &i))
408
0
            ret = 0;
409
0
        if (ret == 0)
410
0
            goto err;
411
0
        i += j;
412
0
    } else {
413
0
        ret = 1;
414
0
        buf[0] = '\0';
415
0
    }
416
0
    i = PEM_write_bio(bp, name, buf, data, i);
417
0
    if (i <= 0)
418
0
        ret = 0;
419
0
err:
420
0
    OPENSSL_cleanse(key, sizeof(key));
421
0
    OPENSSL_cleanse(iv, sizeof(iv));
422
0
    EVP_CIPHER_CTX_free(ctx);
423
0
    OPENSSL_cleanse(buf, PEM_BUFSIZE);
424
0
    OPENSSL_clear_free(data, (unsigned int)dsize);
425
0
    return ret;
426
0
}
427
428
int PEM_ASN1_write_bio(i2d_of_void *i2d, const char *name, BIO *bp, const void *x,
429
    const EVP_CIPHER *enc, const unsigned char *kstr, int klen,
430
    pem_password_cb *callback, void *u)
431
0
{
432
0
    return PEM_ASN1_write_bio_internal(i2d, NULL, NULL, name, bp, x, enc,
433
0
        kstr, klen, callback, u);
434
0
}
435
436
int PEM_ASN1_write_bio_ctx(OSSL_i2d_of_void_ctx *i2d, void *vctx,
437
    const char *name, BIO *bp, const void *x,
438
    const EVP_CIPHER *enc, const unsigned char *kstr,
439
    int klen, pem_password_cb *callback, void *u)
440
0
{
441
0
    return PEM_ASN1_write_bio_internal(NULL, i2d, vctx, name, bp, x, enc,
442
0
        kstr, klen, callback, u);
443
0
}
444
445
int PEM_do_header(EVP_CIPHER_INFO *cipher, unsigned char *data, long *plen,
446
    pem_password_cb *callback, void *u)
447
124k
{
448
124k
    int ok;
449
124k
    int keylen;
450
124k
    long len = *plen;
451
124k
    int ilen = (int)len; /* EVP_DecryptUpdate etc. take int lengths */
452
124k
    EVP_CIPHER_CTX *ctx;
453
124k
    unsigned char key[EVP_MAX_KEY_LENGTH];
454
124k
    char buf[PEM_BUFSIZE];
455
456
124k
#if LONG_MAX > INT_MAX
457
    /* Check that we did not truncate the length */
458
124k
    if (len > INT_MAX) {
459
0
        ERR_raise(ERR_LIB_PEM, PEM_R_HEADER_TOO_LONG);
460
0
        return 0;
461
0
    }
462
124k
#endif
463
464
124k
    if (cipher->cipher == NULL)
465
124k
        return 1;
466
2
    if (callback == NULL)
467
0
        keylen = PEM_def_callback(buf, PEM_BUFSIZE, 0, u);
468
2
    else
469
2
        keylen = callback(buf, PEM_BUFSIZE, 0, u);
470
2
    if (keylen < 0) {
471
2
        ERR_raise(ERR_LIB_PEM, PEM_R_BAD_PASSWORD_READ);
472
2
        return 0;
473
2
    }
474
#ifdef CHARSET_EBCDIC
475
    /* Convert the pass phrase from EBCDIC */
476
    ebcdic2ascii(buf, buf, keylen);
477
#endif
478
479
0
    if (!EVP_BytesToKey(cipher->cipher, EVP_md5(), &(cipher->iv[0]),
480
0
            (unsigned char *)buf, keylen, 1, key, NULL))
481
0
        return 0;
482
483
0
    ctx = EVP_CIPHER_CTX_new();
484
0
    if (ctx == NULL)
485
0
        return 0;
486
487
0
    ok = EVP_DecryptInit_ex(ctx, cipher->cipher, NULL, key, &(cipher->iv[0]));
488
0
    if (ok)
489
0
        ok = EVP_DecryptUpdate(ctx, data, &ilen, data, ilen);
490
0
    if (ok) {
491
        /* Squirrel away the length of data decrypted so far. */
492
0
        *plen = ilen;
493
0
        ok = EVP_DecryptFinal_ex(ctx, &(data[ilen]), &ilen);
494
0
    }
495
0
    if (ok)
496
0
        *plen += ilen;
497
0
    else
498
0
        ERR_raise(ERR_LIB_PEM, PEM_R_BAD_DECRYPT);
499
500
0
    EVP_CIPHER_CTX_free(ctx);
501
0
    OPENSSL_cleanse((char *)buf, sizeof(buf));
502
0
    OPENSSL_cleanse((char *)key, sizeof(key));
503
0
    return ok;
504
0
}
505
506
/*
507
 * This implements a very limited PEM header parser that does not support the
508
 * full grammar of rfc1421.  In particular, folded headers are not supported,
509
 * nor is additional whitespace.
510
 *
511
 * A robust implementation would make use of a library that turns the headers
512
 * into a BIO from which one folded line is read at a time, and is then split
513
 * into a header label and content.  We would then parse the content of the
514
 * headers we care about.  This is overkill for just this limited use-case, but
515
 * presumably we also parse rfc822-style headers for S/MIME, so a common
516
 * abstraction might well be more generally useful.
517
 */
518
#define PROC_TYPE "Proc-Type:"
519
#define ENCRYPTED "ENCRYPTED"
520
#define DEK_INFO "DEK-Info:"
521
int PEM_get_EVP_CIPHER_INFO(char *header, EVP_CIPHER_INFO *cipher)
522
115k
{
523
115k
    const EVP_CIPHER *enc = NULL;
524
115k
    int ivlen;
525
115k
    char *dekinfostart, c;
526
527
115k
    cipher->cipher = NULL;
528
115k
    memset(cipher->iv, 0, sizeof(cipher->iv));
529
115k
    if ((header == NULL) || (*header == '\0') || (*header == '\n'))
530
115k
        return 1;
531
532
793
    if (!CHECK_AND_SKIP_PREFIX(header, PROC_TYPE)) {
533
355
        ERR_raise(ERR_LIB_PEM, PEM_R_NOT_PROC_TYPE);
534
355
        return 0;
535
355
    }
536
438
    header += strspn(header, " \t");
537
538
438
    if (*header++ != '4' || *header++ != ',')
539
34
        return 0;
540
404
    header += strspn(header, " \t");
541
542
    /* We expect "ENCRYPTED" followed by optional white-space + line break */
543
404
    if (!CHECK_AND_SKIP_PREFIX(header, ENCRYPTED) || strspn(header, " \t\r\n") == 0) {
544
150
        ERR_raise(ERR_LIB_PEM, PEM_R_NOT_ENCRYPTED);
545
150
        return 0;
546
150
    }
547
254
    header += strspn(header, " \t\r");
548
254
    if (*header++ != '\n') {
549
3
        ERR_raise(ERR_LIB_PEM, PEM_R_SHORT_HEADER);
550
3
        return 0;
551
3
    }
552
553
    /*-
554
     * https://tools.ietf.org/html/rfc1421#section-4.6.1.3
555
     * We expect "DEK-Info: algo[,hex-parameters]"
556
     */
557
251
    if (!CHECK_AND_SKIP_PREFIX(header, DEK_INFO)) {
558
114
        ERR_raise(ERR_LIB_PEM, PEM_R_NOT_DEK_INFO);
559
114
        return 0;
560
114
    }
561
137
    header += strspn(header, " \t");
562
563
    /*
564
     * DEK-INFO is a comma-separated combination of algorithm name and optional
565
     * parameters.
566
     */
567
137
    dekinfostart = header;
568
137
    header += strcspn(header, " \t,");
569
137
    c = *header;
570
137
    *header = '\0';
571
137
    cipher->cipher = enc = EVP_get_cipherbyname(dekinfostart);
572
137
    *header = c;
573
137
    header += strspn(header, " \t");
574
575
137
    if (enc == NULL) {
576
114
        ERR_raise(ERR_LIB_PEM, PEM_R_UNSUPPORTED_ENCRYPTION);
577
114
        return 0;
578
114
    }
579
23
    ivlen = EVP_CIPHER_get_iv_length(enc);
580
23
    if (ivlen > 0 && *header++ != ',') {
581
2
        ERR_raise(ERR_LIB_PEM, PEM_R_MISSING_DEK_IV);
582
2
        return 0;
583
21
    } else if (ivlen == 0 && *header == ',') {
584
0
        ERR_raise(ERR_LIB_PEM, PEM_R_UNEXPECTED_DEK_IV);
585
0
        return 0;
586
0
    }
587
588
21
    if (!load_iv(&header, cipher->iv, EVP_CIPHER_get_iv_length(enc)))
589
19
        return 0;
590
591
2
    return 1;
592
21
}
593
594
static int load_iv(char **fromp, unsigned char *to, int num)
595
21
{
596
21
    int v, i;
597
21
    char *from;
598
599
21
    from = *fromp;
600
189
    for (i = 0; i < num; i++)
601
168
        to[i] = 0;
602
21
    num *= 2;
603
148
    for (i = 0; i < num; i++) {
604
146
        v = OPENSSL_hexchar2int(*from);
605
146
        if (v < 0) {
606
19
            ERR_raise(ERR_LIB_PEM, PEM_R_BAD_IV_CHARS);
607
19
            return 0;
608
19
        }
609
127
        from++;
610
127
        to[i / 2] |= v << (long)((!(i & 1)) * 4);
611
127
    }
612
613
2
    *fromp = from;
614
2
    return 1;
615
21
}
616
617
#ifndef OPENSSL_NO_STDIO
618
int PEM_write(FILE *fp, const char *name, const char *header,
619
    const unsigned char *data, long len)
620
0
{
621
0
    BIO *b;
622
0
    int ret;
623
624
0
    if ((b = BIO_new(BIO_s_file())) == NULL) {
625
0
        ERR_raise(ERR_LIB_PEM, ERR_R_BUF_LIB);
626
0
        return 0;
627
0
    }
628
0
    BIO_set_fp(b, fp, BIO_NOCLOSE);
629
0
    ret = PEM_write_bio(b, name, header, data, len);
630
0
    BIO_free(b);
631
0
    return ret;
632
0
}
633
#endif
634
635
int PEM_write_bio(BIO *bp, const char *name, const char *header,
636
    const unsigned char *data, long len)
637
0
{
638
0
    int nlen, n, i, j, outl;
639
0
    unsigned char *buf = NULL;
640
0
    EVP_ENCODE_CTX *ctx = EVP_ENCODE_CTX_new();
641
0
    int reason = 0;
642
0
    int retval = 0;
643
644
0
    if (ctx == NULL) {
645
0
        reason = ERR_R_EVP_LIB;
646
0
        goto err;
647
0
    }
648
649
0
    EVP_EncodeInit(ctx);
650
0
    nlen = (int)strlen(name);
651
652
0
    if ((BIO_write(bp, "-----BEGIN ", 11) != 11) || (BIO_write(bp, name, nlen) != nlen) || (BIO_write(bp, "-----\n", 6) != 6)) {
653
0
        reason = ERR_R_BIO_LIB;
654
0
        goto err;
655
0
    }
656
657
0
    i = header != NULL ? (int)strlen(header) : 0;
658
0
    if (i > 0) {
659
0
        if ((BIO_write(bp, header, i) != i) || (BIO_write(bp, "\n", 1) != 1)) {
660
0
            reason = ERR_R_BIO_LIB;
661
0
            goto err;
662
0
        }
663
0
    }
664
665
0
    buf = OPENSSL_malloc_array(PEM_BUFSIZE, 8);
666
0
    if (buf == NULL)
667
0
        goto err;
668
669
0
    i = j = 0;
670
0
    while (len > 0) {
671
0
        n = (int)((len > (PEM_BUFSIZE * 5)) ? (PEM_BUFSIZE * 5) : len);
672
0
        if (!EVP_EncodeUpdate(ctx, buf, &outl, &(data[j]), n)) {
673
0
            reason = ERR_R_EVP_LIB;
674
0
            goto err;
675
0
        }
676
0
        if ((outl) && (BIO_write(bp, (char *)buf, outl) != outl)) {
677
0
            reason = ERR_R_BIO_LIB;
678
0
            goto err;
679
0
        }
680
0
        i += outl;
681
0
        len -= n;
682
0
        j += n;
683
0
    }
684
0
    EVP_EncodeFinal(ctx, buf, &outl);
685
0
    if ((outl > 0) && (BIO_write(bp, (char *)buf, outl) != outl)) {
686
0
        reason = ERR_R_BIO_LIB;
687
0
        goto err;
688
0
    }
689
0
    if ((BIO_write(bp, "-----END ", 9) != 9) || (BIO_write(bp, name, nlen) != nlen) || (BIO_write(bp, "-----\n", 6) != 6)) {
690
0
        reason = ERR_R_BIO_LIB;
691
0
        goto err;
692
0
    }
693
0
    retval = i + outl;
694
695
0
err:
696
0
    if (retval == 0 && reason != 0)
697
0
        ERR_raise(ERR_LIB_PEM, reason);
698
0
    EVP_ENCODE_CTX_free(ctx);
699
0
    OPENSSL_clear_free(buf, PEM_BUFSIZE * 8);
700
0
    return retval;
701
0
}
702
703
#ifndef OPENSSL_NO_STDIO
704
int PEM_read(FILE *fp, char **name, char **header, unsigned char **data,
705
    long *len)
706
0
{
707
0
    BIO *b;
708
0
    int ret;
709
710
0
    if ((b = BIO_new(BIO_s_file())) == NULL) {
711
0
        ERR_raise(ERR_LIB_PEM, ERR_R_BUF_LIB);
712
0
        return 0;
713
0
    }
714
0
    BIO_set_fp(b, fp, BIO_NOCLOSE);
715
0
    ret = PEM_read_bio(b, name, header, data, len);
716
0
    BIO_free(b);
717
0
    return ret;
718
0
}
719
#endif
720
721
/* Some helpers for PEM_read_bio_ex(). */
722
static int sanitize_line(char *linebuf, int len, unsigned int flags, int first_call)
723
16.5M
{
724
16.5M
    int i;
725
16.5M
    if (first_call) {
726
        /* Other BOMs imply unsupported multibyte encoding,
727
         * so don't strip them and let the error raise */
728
294k
        const unsigned char utf8_bom[3] = { 0xEF, 0xBB, 0xBF };
729
730
294k
        if (len > 3 && memcmp(linebuf, utf8_bom, 3) == 0) {
731
17
            memmove(linebuf, linebuf + 3, len - 3);
732
17
            linebuf[len - 3] = 0;
733
17
            len -= 3;
734
17
        }
735
294k
    }
736
737
16.5M
    if (flags & PEM_FLAG_EAY_COMPATIBLE) {
738
        /* Strip trailing whitespace */
739
140M
        while ((len >= 0) && (linebuf[len] <= ' '))
740
124M
            len--;
741
        /* Go back to whitespace before applying uniform line ending. */
742
15.1M
        len++;
743
15.1M
    } else if (flags & PEM_FLAG_ONLY_B64) {
744
4.02M
        for (i = 0; i < len; ++i) {
745
4.01M
            if (!ossl_isbase64(linebuf[i]) || linebuf[i] == '\n'
746
4.00M
                || linebuf[i] == '\r')
747
7.81k
                break;
748
4.01M
        }
749
22.7k
        len = i;
750
1.40M
    } else {
751
        /* EVP_DecodeBlock strips leading and trailing whitespace, so just strip
752
         * control characters in-place and let everything through. */
753
172M
        for (i = 0; i < len; ++i) {
754
171M
            if (linebuf[i] == '\n' || linebuf[i] == '\r')
755
827k
                break;
756
171M
            if (ossl_iscntrl(linebuf[i]))
757
69.9M
                linebuf[i] = ' ';
758
171M
        }
759
1.40M
        len = i;
760
1.40M
    }
761
    /* The caller allocated LINESIZE+1, so this is safe. */
762
16.5M
    linebuf[len++] = '\n';
763
16.5M
    linebuf[len] = '\0';
764
16.5M
    return len;
765
16.5M
}
766
767
21.5M
#define LINESIZE 255
768
/* Note trailing spaces for begin and end. */
769
475k
#define BEGINSTR "-----BEGIN "
770
#define ENDSTR "-----END "
771
716k
#define TAILSTR "-----\n"
772
475k
#define BEGINLEN ((int)(sizeof(BEGINSTR) - 1))
773
#define ENDLEN ((int)(sizeof(ENDSTR) - 1))
774
12.6M
#define TAILLEN ((int)(sizeof(TAILSTR) - 1))
775
static int get_name(BIO *bp, char **name, unsigned int flags)
776
275k
{
777
275k
    char *linebuf;
778
275k
    int ret = 0;
779
275k
    int len;
780
275k
    int first_call = 1;
781
782
    /*
783
     * Need to hold trailing NUL (accounted for by BIO_gets() and the newline
784
     * that will be added by sanitize_line() (the extra '1').
785
     */
786
275k
    linebuf = PEM_MALLOC(LINESIZE + 1, flags);
787
275k
    if (linebuf == NULL)
788
0
        return 0;
789
790
11.9M
    do {
791
11.9M
        len = BIO_gets(bp, linebuf, LINESIZE);
792
793
11.9M
        if (len <= 0) {
794
38.3k
            ERR_raise(ERR_LIB_PEM, PEM_R_NO_START_LINE);
795
38.3k
            goto err;
796
38.3k
        }
797
798
        /* Strip trailing garbage and standardize ending. */
799
11.9M
        len = sanitize_line(linebuf, len, flags & ~PEM_FLAG_ONLY_B64, first_call);
800
11.9M
        first_call = 0;
801
802
        /* Allow leading empty or non-matching lines. */
803
11.9M
    } while (!HAS_PREFIX(linebuf, BEGINSTR)
804
240k
        || len < TAILLEN
805
240k
        || !HAS_PREFIX(linebuf + len - TAILLEN, TAILSTR));
806
237k
    linebuf[len - TAILLEN] = '\0';
807
237k
    len = len - BEGINLEN - TAILLEN + 1;
808
237k
    *name = PEM_MALLOC(len, flags);
809
237k
    if (*name == NULL)
810
0
        goto err;
811
237k
    memcpy(*name, linebuf + BEGINLEN, len);
812
237k
    ret = 1;
813
814
275k
err:
815
275k
    PEM_FREE(linebuf, flags, LINESIZE + 1);
816
275k
    return ret;
817
237k
}
818
819
/* Keep track of how much of a header we've seen. */
820
enum header_status {
821
    MAYBE_HEADER,
822
    IN_HEADER,
823
    POST_HEADER
824
};
825
826
/**
827
 * Extract the optional PEM header, with details on the type of content and
828
 * any encryption used on the contents, and the bulk of the data from the bio.
829
 * The end of the header is marked by a blank line; if the end-of-input marker
830
 * is reached prior to a blank line, there is no header.
831
 *
832
 * The header and data arguments are BIO** since we may have to swap them
833
 * if there is no header, for efficiency.
834
 *
835
 * We need the name of the PEM-encoded type to verify the end string.
836
 */
837
static int get_header_and_data(BIO *bp, BIO **header, BIO **data, char *name,
838
    unsigned int flags)
839
237k
{
840
237k
    BIO *tmp = *header;
841
237k
    char *linebuf, *p;
842
237k
    int len, ret = 0, end = 0, prev_partial_line_read = 0, partial_line_read = 0;
843
    /* 0 if not seen (yet), 1 if reading header, 2 if finished header */
844
237k
    enum header_status got_header = MAYBE_HEADER;
845
237k
    unsigned int flags_mask;
846
237k
    size_t namelen;
847
848
    /* Need to hold trailing NUL (accounted for by BIO_gets() and the newline
849
     * that will be added by sanitize_line() (the extra '1'). */
850
237k
    linebuf = PEM_MALLOC(LINESIZE + 1, flags);
851
237k
    if (linebuf == NULL)
852
0
        return 0;
853
854
4.47M
    while (1) {
855
4.47M
        flags_mask = ~0u;
856
4.47M
        len = BIO_gets(bp, linebuf, LINESIZE);
857
4.47M
        if (len <= 0) {
858
2.73k
            ERR_raise(ERR_LIB_PEM, PEM_R_BAD_END_LINE);
859
2.73k
            goto err;
860
2.73k
        }
861
862
        /*
863
         * Check if line has been read completely or if only part of the line
864
         * has been read. Keep the previous value to ignore newlines that
865
         * appear due to reading a line up until the char before the newline.
866
         */
867
4.46M
        prev_partial_line_read = partial_line_read;
868
4.46M
        partial_line_read = len == LINESIZE - 1 && linebuf[LINESIZE - 2] != '\n';
869
870
4.46M
        if (got_header == MAYBE_HEADER) {
871
3.94M
            if (memchr(linebuf, ':', len) != NULL)
872
1.39k
                got_header = IN_HEADER;
873
3.94M
        }
874
4.46M
        if (HAS_PREFIX(linebuf, ENDSTR) || got_header == IN_HEADER)
875
757k
            flags_mask &= ~PEM_FLAG_ONLY_B64;
876
4.46M
        len = sanitize_line(linebuf, len, flags & flags_mask, 0);
877
878
        /* Check for end of header. */
879
4.46M
        if (linebuf[0] == '\n') {
880
            /*
881
             * If previous line has been read only partially this newline is a
882
             * regular newline at the end of a line and not an empty line.
883
             */
884
9.54k
            if (!prev_partial_line_read) {
885
2.07k
                if (got_header == POST_HEADER) {
886
                    /* Another blank line is an error. */
887
148
                    ERR_raise(ERR_LIB_PEM, PEM_R_BAD_END_LINE);
888
148
                    goto err;
889
148
                }
890
1.92k
                got_header = POST_HEADER;
891
1.92k
                tmp = *data;
892
1.92k
            }
893
9.39k
            continue;
894
9.54k
        }
895
896
        /* Check for end of stream (which means there is no header). */
897
4.45M
        p = linebuf;
898
4.45M
        if (CHECK_AND_SKIP_PREFIX(p, ENDSTR)) {
899
234k
            namelen = strlen(name);
900
234k
            if (strncmp(p, name, namelen) != 0 || !HAS_PREFIX(p + namelen, TAILSTR)) {
901
1.85k
                ERR_raise(ERR_LIB_PEM, PEM_R_BAD_END_LINE);
902
1.85k
                goto err;
903
1.85k
            }
904
232k
            if (got_header == MAYBE_HEADER) {
905
231k
                *header = *data;
906
231k
                *data = tmp;
907
231k
            }
908
232k
            break;
909
4.22M
        } else if (end) {
910
            /* Malformed input; short line not at end of data. */
911
76
            ERR_raise(ERR_LIB_PEM, PEM_R_BAD_END_LINE);
912
76
            goto err;
913
76
        }
914
        /*
915
         * Else, a line of text -- could be header or data; we don't
916
         * know yet.  Just pass it through.
917
         */
918
4.22M
        if (BIO_puts(tmp, linebuf) < 0)
919
0
            goto err;
920
        /*
921
         * Only encrypted files need the line length check applied.
922
         */
923
4.22M
        if (got_header == POST_HEADER) {
924
            /* 65 includes the trailing newline */
925
4.25k
            if (len > 65)
926
58
                goto err;
927
4.19k
            if (len < 65)
928
1.52k
                end = 1;
929
4.19k
        }
930
4.22M
    }
931
932
232k
    ret = 1;
933
237k
err:
934
237k
    PEM_FREE(linebuf, flags, LINESIZE + 1);
935
237k
    return ret;
936
232k
}
937
938
/**
939
 * Read in PEM-formatted data from the given BIO.
940
 *
941
 * By nature of the PEM format, all content must be printable ASCII (except
942
 * for line endings).  Other characters are malformed input and will be rejected.
943
 */
944
int PEM_read_bio_ex(BIO *bp, char **name_out, char **header,
945
    unsigned char **data, long *len_out, unsigned int flags)
946
109k
{
947
109k
    EVP_ENCODE_CTX *ctx = NULL;
948
109k
    const BIO_METHOD *bmeth;
949
109k
    BIO *headerB = NULL, *dataB = NULL;
950
109k
    char *name = NULL;
951
109k
    int len, taillen, headerlen, ret = 0;
952
109k
    BUF_MEM *buf_mem;
953
954
109k
    *len_out = 0;
955
109k
    *name_out = *header = NULL;
956
109k
    *data = NULL;
957
109k
    if ((flags & PEM_FLAG_EAY_COMPATIBLE) && (flags & PEM_FLAG_ONLY_B64)) {
958
        /* These two are mutually incompatible; bail out. */
959
2
        ERR_raise(ERR_LIB_PEM, ERR_R_PASSED_INVALID_ARGUMENT);
960
2
        goto end;
961
2
    }
962
109k
    bmeth = (flags & PEM_FLAG_SECURE) ? BIO_s_secmem() : BIO_s_mem();
963
964
109k
    headerB = BIO_new(bmeth);
965
109k
    dataB = BIO_new(bmeth);
966
109k
    if (headerB == NULL || dataB == NULL) {
967
0
        ERR_raise(ERR_LIB_PEM, ERR_R_BIO_LIB);
968
0
        goto end;
969
0
    }
970
971
109k
    if (!get_name(bp, &name, flags))
972
14.8k
        goto end;
973
94.6k
    if (!get_header_and_data(bp, &headerB, &dataB, name, flags))
974
1.97k
        goto end;
975
976
92.6k
    BIO_get_mem_ptr(dataB, &buf_mem);
977
92.6k
    if (buf_mem->length > INT_MAX) {
978
0
        ERR_raise(ERR_LIB_PEM, PEM_R_BAD_BASE64_DECODE);
979
0
        goto end;
980
0
    }
981
92.6k
    len = (int)buf_mem->length;
982
983
    /* There was no data in the PEM file */
984
92.6k
    if (len == 0)
985
11
        goto end;
986
987
92.6k
    ctx = EVP_ENCODE_CTX_new();
988
92.6k
    if (ctx == NULL) {
989
0
        ERR_raise(ERR_LIB_PEM, ERR_R_EVP_LIB);
990
0
        goto end;
991
0
    }
992
993
92.6k
    EVP_DecodeInit(ctx);
994
92.6k
    if (EVP_DecodeUpdate(ctx, (unsigned char *)buf_mem->data, &len,
995
92.6k
            (unsigned char *)buf_mem->data, len)
996
92.6k
            < 0
997
92.5k
        || EVP_DecodeFinal(ctx, (unsigned char *)&(buf_mem->data[len]),
998
92.5k
               &taillen)
999
92.5k
            < 0) {
1000
234
        ERR_raise(ERR_LIB_PEM, PEM_R_BAD_BASE64_DECODE);
1001
234
        goto end;
1002
234
    }
1003
92.4k
    len += taillen;
1004
92.4k
    buf_mem->length = len;
1005
1006
92.4k
    headerlen = BIO_get_mem_data(headerB, NULL);
1007
92.4k
    *header = PEM_MALLOC(headerlen + 1, flags);
1008
92.4k
    *data = PEM_MALLOC(len, flags);
1009
92.4k
    if (*header == NULL || *data == NULL)
1010
25
        goto out_free;
1011
92.3k
    if (headerlen != 0 && BIO_read(headerB, *header, headerlen) != headerlen)
1012
0
        goto out_free;
1013
92.3k
    (*header)[headerlen] = '\0';
1014
92.3k
    if (BIO_read(dataB, *data, len) != len)
1015
0
        goto out_free;
1016
92.3k
    *len_out = len;
1017
92.3k
    *name_out = name;
1018
92.3k
    name = NULL;
1019
92.3k
    ret = 1;
1020
92.3k
    goto end;
1021
1022
25
out_free:
1023
25
    PEM_FREE(*header, flags, 0);
1024
25
    *header = NULL;
1025
25
    PEM_FREE(*data, flags, 0);
1026
25
    *data = NULL;
1027
109k
end:
1028
109k
    EVP_ENCODE_CTX_free(ctx);
1029
109k
    PEM_FREE(name, flags, 0);
1030
109k
    BIO_free(headerB);
1031
109k
    BIO_free(dataB);
1032
109k
    return ret;
1033
25
}
1034
1035
int PEM_read_bio(BIO *bp, char **name, char **header, unsigned char **data,
1036
    long *len)
1037
164k
{
1038
164k
    return PEM_read_bio_ex(bp, name, header, data, len, PEM_FLAG_EAY_COMPATIBLE);
1039
164k
}
1040
1041
/*
1042
 * Check pem string and return prefix length. If for example the pem_str ==
1043
 * "RSA PRIVATE KEY" and suffix = "PRIVATE KEY" the return value is 3 for the
1044
 * string "RSA".
1045
 */
1046
1047
int ossl_pem_check_suffix(const char *pem_str, const char *suffix)
1048
0
{
1049
0
    int pem_len = (int)strlen(pem_str);
1050
0
    int suffix_len = (int)strlen(suffix);
1051
0
    const char *p;
1052
1053
0
    if (suffix_len + 1 >= pem_len)
1054
0
        return 0;
1055
0
    p = pem_str + pem_len - suffix_len;
1056
0
    if (strcmp(p, suffix))
1057
0
        return 0;
1058
0
    p--;
1059
0
    if (*p != ' ')
1060
0
        return 0;
1061
0
    return (int)(p - pem_str);
1062
0
}