Coverage Report

Created: 2026-05-24 07:14

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