Coverage Report

Created: 2025-12-31 06:58

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl33/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
124k
{
128
    /* Normal matching nm and name */
129
124k
    if (strcmp(nm, name) == 0)
130
124k
        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.32M
    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.46M
{
226
1.46M
    if (flags & PEM_FLAG_SECURE)
227
6.62k
        CRYPTO_secure_clear_free(p, num, file, line);
228
1.46M
    else
229
1.46M
        CRYPTO_free(p, file, line);
230
1.46M
}
231
232
#define PEM_MALLOC(num, flags) \
233
1.06M
    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.31M
{
237
1.31M
    return (flags & PEM_FLAG_SECURE) ? CRYPTO_secure_malloc(num, file, line)
238
1.31M
                                     : CRYPTO_malloc(num, file, line);
239
1.31M
}
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
124k
{
246
124k
    EVP_CIPHER_INFO cipher;
247
124k
    char *nm = NULL, *header = NULL;
248
124k
    unsigned char *data = NULL;
249
124k
    long len = 0;
250
124k
    int ret = 0;
251
252
124k
    do {
253
124k
        PEM_FREE(nm, flags, 0);
254
124k
        PEM_FREE(header, flags, 0);
255
124k
        PEM_FREE(data, flags, len);
256
124k
        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
124k
    } while (!check_pem(nm, name));
262
124k
    if (!PEM_get_EVP_CIPHER_INFO(header, &cipher))
263
0
        goto err;
264
124k
    if (!PEM_do_header(&cipher, data, &len, cb, u))
265
0
        goto err;
266
267
124k
    *pdata = data;
268
124k
    *plen = len;
269
270
124k
    if (pnm != NULL)
271
0
        *pnm = nm;
272
273
124k
    ret = 1;
274
275
124k
err:
276
124k
    if (!ret || pnm == NULL)
277
124k
        PEM_FREE(nm, flags, 0);
278
124k
    PEM_FREE(header, flags, 0);
279
124k
    if (!ret)
280
0
        PEM_FREE(data, flags, len);
281
124k
    return ret;
282
124k
}
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
124k
{
288
124k
    return pem_bytes_read_bio_flags(pdata, plen, pnm, name, bp, cb, u,
289
124k
        PEM_FLAG_EAY_COMPATIBLE);
290
124k
}
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
124k
{
423
124k
    int ok;
424
124k
    int keylen;
425
124k
    long len = *plen;
426
124k
    int ilen = (int)len; /* EVP_DecryptUpdate etc. take int lengths */
427
124k
    EVP_CIPHER_CTX *ctx;
428
124k
    unsigned char key[EVP_MAX_KEY_LENGTH];
429
124k
    char buf[PEM_BUFSIZE];
430
431
124k
#if LONG_MAX > INT_MAX
432
    /* Check that we did not truncate the length */
433
124k
    if (len > INT_MAX) {
434
0
        ERR_raise(ERR_LIB_PEM, PEM_R_HEADER_TOO_LONG);
435
0
        return 0;
436
0
    }
437
124k
#endif
438
439
124k
    if (cipher->cipher == NULL)
440
124k
        return 1;
441
2
    if (callback == NULL)
442
0
        keylen = PEM_def_callback(buf, PEM_BUFSIZE, 0, u);
443
2
    else
444
2
        keylen = callback(buf, PEM_BUFSIZE, 0, u);
445
2
    if (keylen < 0) {
446
2
        ERR_raise(ERR_LIB_PEM, PEM_R_BAD_PASSWORD_READ);
447
2
        return 0;
448
2
    }
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
115k
{
498
115k
    const EVP_CIPHER *enc = NULL;
499
115k
    int ivlen;
500
115k
    char *dekinfostart, c;
501
502
115k
    cipher->cipher = NULL;
503
115k
    memset(cipher->iv, 0, sizeof(cipher->iv));
504
115k
    if ((header == NULL) || (*header == '\0') || (*header == '\n'))
505
115k
        return 1;
506
507
793
    if (!CHECK_AND_SKIP_PREFIX(header, PROC_TYPE)) {
508
355
        ERR_raise(ERR_LIB_PEM, PEM_R_NOT_PROC_TYPE);
509
355
        return 0;
510
355
    }
511
438
    header += strspn(header, " \t");
512
513
438
    if (*header++ != '4' || *header++ != ',')
514
34
        return 0;
515
404
    header += strspn(header, " \t");
516
517
    /* We expect "ENCRYPTED" followed by optional white-space + line break */
518
404
    if (!CHECK_AND_SKIP_PREFIX(header, ENCRYPTED) || strspn(header, " \t\r\n") == 0) {
519
150
        ERR_raise(ERR_LIB_PEM, PEM_R_NOT_ENCRYPTED);
520
150
        return 0;
521
150
    }
522
254
    header += strspn(header, " \t\r");
523
254
    if (*header++ != '\n') {
524
3
        ERR_raise(ERR_LIB_PEM, PEM_R_SHORT_HEADER);
525
3
        return 0;
526
3
    }
527
528
    /*-
529
     * https://tools.ietf.org/html/rfc1421#section-4.6.1.3
530
     * We expect "DEK-Info: algo[,hex-parameters]"
531
     */
532
251
    if (!CHECK_AND_SKIP_PREFIX(header, DEK_INFO)) {
533
114
        ERR_raise(ERR_LIB_PEM, PEM_R_NOT_DEK_INFO);
534
114
        return 0;
535
114
    }
536
137
    header += strspn(header, " \t");
537
538
    /*
539
     * DEK-INFO is a comma-separated combination of algorithm name and optional
540
     * parameters.
541
     */
542
137
    dekinfostart = header;
543
137
    header += strcspn(header, " \t,");
544
137
    c = *header;
545
137
    *header = '\0';
546
137
    cipher->cipher = enc = EVP_get_cipherbyname(dekinfostart);
547
137
    *header = c;
548
137
    header += strspn(header, " \t");
549
550
137
    if (enc == NULL) {
551
114
        ERR_raise(ERR_LIB_PEM, PEM_R_UNSUPPORTED_ENCRYPTION);
552
114
        return 0;
553
114
    }
554
23
    ivlen = EVP_CIPHER_get_iv_length(enc);
555
23
    if (ivlen > 0 && *header++ != ',') {
556
2
        ERR_raise(ERR_LIB_PEM, PEM_R_MISSING_DEK_IV);
557
2
        return 0;
558
21
    } 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
21
    if (!load_iv(&header, cipher->iv, EVP_CIPHER_get_iv_length(enc)))
564
19
        return 0;
565
566
2
    return 1;
567
21
}
568
569
static int load_iv(char **fromp, unsigned char *to, int num)
570
21
{
571
21
    int v, i;
572
21
    char *from;
573
574
21
    from = *fromp;
575
189
    for (i = 0; i < num; i++)
576
168
        to[i] = 0;
577
21
    num *= 2;
578
148
    for (i = 0; i < num; i++) {
579
146
        v = OPENSSL_hexchar2int(*from);
580
146
        if (v < 0) {
581
19
            ERR_raise(ERR_LIB_PEM, PEM_R_BAD_IV_CHARS);
582
19
            return 0;
583
19
        }
584
127
        from++;
585
127
        to[i / 2] |= v << (long)((!(i & 1)) * 4);
586
127
    }
587
588
2
    *fromp = from;
589
2
    return 1;
590
21
}
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.5M
{
699
16.5M
    int i;
700
16.5M
    if (first_call) {
701
        /* Other BOMs imply unsupported multibyte encoding,
702
         * so don't strip them and let the error raise */
703
294k
        const unsigned char utf8_bom[3] = { 0xEF, 0xBB, 0xBF };
704
705
294k
        if (len > 3 && memcmp(linebuf, utf8_bom, 3) == 0) {
706
17
            memmove(linebuf, linebuf + 3, len - 3);
707
17
            linebuf[len - 3] = 0;
708
17
            len -= 3;
709
17
        }
710
294k
    }
711
712
16.5M
    if (flags & PEM_FLAG_EAY_COMPATIBLE) {
713
        /* Strip trailing whitespace */
714
140M
        while ((len >= 0) && (linebuf[len] <= ' '))
715
124M
            len--;
716
        /* Go back to whitespace before applying uniform line ending. */
717
15.1M
        len++;
718
15.1M
    } else if (flags & PEM_FLAG_ONLY_B64) {
719
4.02M
        for (i = 0; i < len; ++i) {
720
4.01M
            if (!ossl_isbase64(linebuf[i]) || linebuf[i] == '\n'
721
4.00M
                || linebuf[i] == '\r')
722
7.81k
                break;
723
4.01M
        }
724
22.7k
        len = i;
725
1.40M
    } else {
726
        /* EVP_DecodeBlock strips leading and trailing whitespace, so just strip
727
         * control characters in-place and let everything through. */
728
172M
        for (i = 0; i < len; ++i) {
729
171M
            if (linebuf[i] == '\n' || linebuf[i] == '\r')
730
827k
                break;
731
171M
            if (ossl_iscntrl(linebuf[i]))
732
69.9M
                linebuf[i] = ' ';
733
171M
        }
734
1.40M
        len = i;
735
1.40M
    }
736
    /* The caller allocated LINESIZE+1, so this is safe. */
737
16.5M
    linebuf[len++] = '\n';
738
16.5M
    linebuf[len] = '\0';
739
16.5M
    return len;
740
16.5M
}
741
742
21.5M
#define LINESIZE 255
743
/* Note trailing spaces for begin and end. */
744
475k
#define BEGINSTR "-----BEGIN "
745
#define ENDSTR "-----END "
746
716k
#define TAILSTR "-----\n"
747
475k
#define BEGINLEN ((int)(sizeof(BEGINSTR) - 1))
748
#define ENDLEN ((int)(sizeof(ENDSTR) - 1))
749
12.6M
#define TAILLEN ((int)(sizeof(TAILSTR) - 1))
750
static int get_name(BIO *bp, char **name, unsigned int flags)
751
275k
{
752
275k
    char *linebuf;
753
275k
    int ret = 0;
754
275k
    int len;
755
275k
    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
275k
    linebuf = PEM_MALLOC(LINESIZE + 1, flags);
762
275k
    if (linebuf == NULL)
763
0
        return 0;
764
765
11.9M
    do {
766
11.9M
        len = BIO_gets(bp, linebuf, LINESIZE);
767
768
11.9M
        if (len <= 0) {
769
38.3k
            ERR_raise(ERR_LIB_PEM, PEM_R_NO_START_LINE);
770
38.3k
            goto err;
771
38.3k
        }
772
773
        /* Strip trailing garbage and standardize ending. */
774
11.9M
        len = sanitize_line(linebuf, len, flags & ~PEM_FLAG_ONLY_B64, first_call);
775
11.9M
        first_call = 0;
776
777
        /* Allow leading empty or non-matching lines. */
778
11.9M
    } while (!HAS_PREFIX(linebuf, BEGINSTR)
779
240k
        || len < TAILLEN
780
240k
        || !HAS_PREFIX(linebuf + len - TAILLEN, TAILSTR));
781
237k
    linebuf[len - TAILLEN] = '\0';
782
237k
    len = len - BEGINLEN - TAILLEN + 1;
783
237k
    *name = PEM_MALLOC(len, flags);
784
237k
    if (*name == NULL)
785
0
        goto err;
786
237k
    memcpy(*name, linebuf + BEGINLEN, len);
787
237k
    ret = 1;
788
789
275k
err:
790
275k
    PEM_FREE(linebuf, flags, LINESIZE + 1);
791
275k
    return ret;
792
237k
}
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
237k
{
815
237k
    BIO *tmp = *header;
816
237k
    char *linebuf, *p;
817
237k
    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
237k
    enum header_status got_header = MAYBE_HEADER;
820
237k
    unsigned int flags_mask;
821
237k
    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
237k
    linebuf = PEM_MALLOC(LINESIZE + 1, flags);
826
237k
    if (linebuf == NULL)
827
0
        return 0;
828
829
4.47M
    while (1) {
830
4.47M
        flags_mask = ~0u;
831
4.47M
        len = BIO_gets(bp, linebuf, LINESIZE);
832
4.47M
        if (len <= 0) {
833
2.73k
            ERR_raise(ERR_LIB_PEM, PEM_R_BAD_END_LINE);
834
2.73k
            goto err;
835
2.73k
        }
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.46M
        prev_partial_line_read = partial_line_read;
843
4.46M
        partial_line_read = len == LINESIZE - 1 && linebuf[LINESIZE - 2] != '\n';
844
845
4.46M
        if (got_header == MAYBE_HEADER) {
846
3.94M
            if (memchr(linebuf, ':', len) != NULL)
847
1.39k
                got_header = IN_HEADER;
848
3.94M
        }
849
4.46M
        if (HAS_PREFIX(linebuf, ENDSTR) || got_header == IN_HEADER)
850
757k
            flags_mask &= ~PEM_FLAG_ONLY_B64;
851
4.46M
        len = sanitize_line(linebuf, len, flags & flags_mask, 0);
852
853
        /* Check for end of header. */
854
4.46M
        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
9.54k
            if (!prev_partial_line_read) {
860
2.07k
                if (got_header == POST_HEADER) {
861
                    /* Another blank line is an error. */
862
148
                    ERR_raise(ERR_LIB_PEM, PEM_R_BAD_END_LINE);
863
148
                    goto err;
864
148
                }
865
1.92k
                got_header = POST_HEADER;
866
1.92k
                tmp = *data;
867
1.92k
            }
868
9.39k
            continue;
869
9.54k
        }
870
871
        /* Check for end of stream (which means there is no header). */
872
4.45M
        p = linebuf;
873
4.45M
        if (CHECK_AND_SKIP_PREFIX(p, ENDSTR)) {
874
234k
            namelen = strlen(name);
875
234k
            if (strncmp(p, name, namelen) != 0 || !HAS_PREFIX(p + namelen, TAILSTR)) {
876
1.85k
                ERR_raise(ERR_LIB_PEM, PEM_R_BAD_END_LINE);
877
1.85k
                goto err;
878
1.85k
            }
879
232k
            if (got_header == MAYBE_HEADER) {
880
231k
                *header = *data;
881
231k
                *data = tmp;
882
231k
            }
883
232k
            break;
884
4.22M
        } else if (end) {
885
            /* Malformed input; short line not at end of data. */
886
76
            ERR_raise(ERR_LIB_PEM, PEM_R_BAD_END_LINE);
887
76
            goto err;
888
76
        }
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.22M
        if (BIO_puts(tmp, linebuf) < 0)
894
0
            goto err;
895
        /*
896
         * Only encrypted files need the line length check applied.
897
         */
898
4.22M
        if (got_header == POST_HEADER) {
899
            /* 65 includes the trailing newline */
900
4.25k
            if (len > 65)
901
58
                goto err;
902
4.19k
            if (len < 65)
903
1.52k
                end = 1;
904
4.19k
        }
905
4.22M
    }
906
907
232k
    ret = 1;
908
237k
err:
909
237k
    PEM_FREE(linebuf, flags, LINESIZE + 1);
910
237k
    return ret;
911
232k
}
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
185k
{
922
185k
    EVP_ENCODE_CTX *ctx = NULL;
923
185k
    const BIO_METHOD *bmeth;
924
185k
    BIO *headerB = NULL, *dataB = NULL;
925
185k
    char *name = NULL;
926
185k
    int len, taillen, headerlen, ret = 0;
927
185k
    BUF_MEM *buf_mem;
928
929
185k
    *len_out = 0;
930
185k
    *name_out = *header = NULL;
931
185k
    *data = NULL;
932
185k
    if ((flags & PEM_FLAG_EAY_COMPATIBLE) && (flags & PEM_FLAG_ONLY_B64)) {
933
        /* These two are mutually incompatible; bail out. */
934
4
        ERR_raise(ERR_LIB_PEM, ERR_R_PASSED_INVALID_ARGUMENT);
935
4
        goto end;
936
4
    }
937
185k
    bmeth = (flags & PEM_FLAG_SECURE) ? BIO_s_secmem() : BIO_s_mem();
938
939
185k
    headerB = BIO_new(bmeth);
940
185k
    dataB = BIO_new(bmeth);
941
185k
    if (headerB == NULL || dataB == NULL) {
942
0
        ERR_raise(ERR_LIB_PEM, ERR_R_BIO_LIB);
943
0
        goto end;
944
0
    }
945
946
185k
    if (!get_name(bp, &name, flags))
947
23.4k
        goto end;
948
162k
    if (!get_header_and_data(bp, &headerB, &dataB, name, flags))
949
2.89k
        goto end;
950
951
159k
    BIO_get_mem_ptr(dataB, &buf_mem);
952
159k
    len = buf_mem->length;
953
954
    /* There was no data in the PEM file */
955
159k
    if (len == 0)
956
21
        goto end;
957
958
159k
    ctx = EVP_ENCODE_CTX_new();
959
159k
    if (ctx == NULL) {
960
0
        ERR_raise(ERR_LIB_PEM, ERR_R_EVP_LIB);
961
0
        goto end;
962
0
    }
963
964
159k
    EVP_DecodeInit(ctx);
965
159k
    if (EVP_DecodeUpdate(ctx, (unsigned char *)buf_mem->data, &len,
966
159k
            (unsigned char *)buf_mem->data, len)
967
159k
            < 0
968
158k
        || EVP_DecodeFinal(ctx, (unsigned char *)&(buf_mem->data[len]),
969
158k
               &taillen)
970
158k
            < 0) {
971
357
        ERR_raise(ERR_LIB_PEM, PEM_R_BAD_BASE64_DECODE);
972
357
        goto end;
973
357
    }
974
158k
    len += taillen;
975
158k
    buf_mem->length = len;
976
977
158k
    headerlen = BIO_get_mem_data(headerB, NULL);
978
158k
    *header = PEM_MALLOC(headerlen + 1, flags);
979
158k
    *data = PEM_MALLOC(len, flags);
980
158k
    if (*header == NULL || *data == NULL)
981
39
        goto out_free;
982
158k
    if (headerlen != 0 && BIO_read(headerB, *header, headerlen) != headerlen)
983
0
        goto out_free;
984
158k
    (*header)[headerlen] = '\0';
985
158k
    if (BIO_read(dataB, *data, len) != len)
986
0
        goto out_free;
987
158k
    *len_out = len;
988
158k
    *name_out = name;
989
158k
    name = NULL;
990
158k
    ret = 1;
991
158k
    goto end;
992
993
39
out_free:
994
39
    PEM_FREE(*header, flags, 0);
995
39
    *header = NULL;
996
39
    PEM_FREE(*data, flags, 0);
997
39
    *data = NULL;
998
185k
end:
999
185k
    EVP_ENCODE_CTX_free(ctx);
1000
185k
    PEM_FREE(name, flags, 0);
1001
185k
    BIO_free(headerB);
1002
185k
    BIO_free(dataB);
1003
185k
    return ret;
1004
39
}
1005
1006
int PEM_read_bio(BIO *bp, char **name, char **header, unsigned char **data,
1007
    long *len)
1008
164k
{
1009
164k
    return PEM_read_bio_ex(bp, name, header, data, len, PEM_FLAG_EAY_COMPATIBLE);
1010
164k
}
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
}