Coverage Report

Created: 2025-12-31 06:58

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl30/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
static void pem_free(void *p, unsigned int flags, size_t num)
222
1.46M
{
223
1.46M
    if (flags & PEM_FLAG_SECURE)
224
6.62k
        OPENSSL_secure_clear_free(p, num);
225
1.46M
    else
226
1.46M
        OPENSSL_free(p);
227
1.46M
}
228
229
static void *pem_malloc(int num, unsigned int flags)
230
1.31M
{
231
1.31M
    return (flags & PEM_FLAG_SECURE) ? OPENSSL_secure_malloc(num)
232
1.31M
                                     : OPENSSL_malloc(num);
233
1.31M
}
234
235
static int pem_bytes_read_bio_flags(unsigned char **pdata, long *plen,
236
    char **pnm, const char *name, BIO *bp,
237
    pem_password_cb *cb, void *u,
238
    unsigned int flags)
239
124k
{
240
124k
    EVP_CIPHER_INFO cipher;
241
124k
    char *nm = NULL, *header = NULL;
242
124k
    unsigned char *data = NULL;
243
124k
    long len = 0;
244
124k
    int ret = 0;
245
246
124k
    do {
247
124k
        pem_free(nm, flags, 0);
248
124k
        pem_free(header, flags, 0);
249
124k
        pem_free(data, flags, len);
250
124k
        if (!PEM_read_bio_ex(bp, &nm, &header, &data, &len, flags)) {
251
0
            if (ERR_GET_REASON(ERR_peek_error()) == PEM_R_NO_START_LINE)
252
0
                ERR_add_error_data(2, "Expecting: ", name);
253
0
            return 0;
254
0
        }
255
124k
    } while (!check_pem(nm, name));
256
124k
    if (!PEM_get_EVP_CIPHER_INFO(header, &cipher))
257
0
        goto err;
258
124k
    if (!PEM_do_header(&cipher, data, &len, cb, u))
259
0
        goto err;
260
261
124k
    *pdata = data;
262
124k
    *plen = len;
263
264
124k
    if (pnm != NULL)
265
0
        *pnm = nm;
266
267
124k
    ret = 1;
268
269
124k
err:
270
124k
    if (!ret || pnm == NULL)
271
124k
        pem_free(nm, flags, 0);
272
124k
    pem_free(header, flags, 0);
273
124k
    if (!ret)
274
0
        pem_free(data, flags, len);
275
124k
    return ret;
276
124k
}
277
278
int PEM_bytes_read_bio(unsigned char **pdata, long *plen, char **pnm,
279
    const char *name, BIO *bp, pem_password_cb *cb,
280
    void *u)
281
124k
{
282
124k
    return pem_bytes_read_bio_flags(pdata, plen, pnm, name, bp, cb, u,
283
124k
        PEM_FLAG_EAY_COMPATIBLE);
284
124k
}
285
286
int PEM_bytes_read_bio_secmem(unsigned char **pdata, long *plen, char **pnm,
287
    const char *name, BIO *bp, pem_password_cb *cb,
288
    void *u)
289
0
{
290
0
    return pem_bytes_read_bio_flags(pdata, plen, pnm, name, bp, cb, u,
291
0
        PEM_FLAG_SECURE | PEM_FLAG_EAY_COMPATIBLE);
292
0
}
293
294
#ifndef OPENSSL_NO_STDIO
295
int PEM_ASN1_write(i2d_of_void *i2d, const char *name, FILE *fp,
296
    const void *x, const EVP_CIPHER *enc,
297
    const unsigned char *kstr, int klen,
298
    pem_password_cb *callback, void *u)
299
0
{
300
0
    BIO *b;
301
0
    int ret;
302
303
0
    if ((b = BIO_new(BIO_s_file())) == NULL) {
304
0
        ERR_raise(ERR_LIB_PEM, ERR_R_BUF_LIB);
305
0
        return 0;
306
0
    }
307
0
    BIO_set_fp(b, fp, BIO_NOCLOSE);
308
0
    ret = PEM_ASN1_write_bio(i2d, name, b, x, enc, kstr, klen, callback, u);
309
0
    BIO_free(b);
310
0
    return ret;
311
0
}
312
#endif
313
314
int PEM_ASN1_write_bio(i2d_of_void *i2d, const char *name, BIO *bp,
315
    const void *x, const EVP_CIPHER *enc,
316
    const unsigned char *kstr, int klen,
317
    pem_password_cb *callback, void *u)
318
0
{
319
0
    EVP_CIPHER_CTX *ctx = NULL;
320
0
    int dsize = 0, i = 0, j = 0, ret = 0;
321
0
    unsigned char *p, *data = NULL;
322
0
    const char *objstr = NULL;
323
0
    char buf[PEM_BUFSIZE];
324
0
    unsigned char key[EVP_MAX_KEY_LENGTH];
325
0
    unsigned char iv[EVP_MAX_IV_LENGTH];
326
327
0
    if (enc != NULL) {
328
0
        objstr = EVP_CIPHER_get0_name(enc);
329
0
        if (objstr == NULL || EVP_CIPHER_get_iv_length(enc) == 0
330
0
            || EVP_CIPHER_get_iv_length(enc) > (int)sizeof(iv)
331
            /*
332
             * Check "Proc-Type: 4,Encrypted\nDEK-Info: objstr,hex-iv\n"
333
             * fits into buf
334
             */
335
0
            || strlen(objstr) + 23 + 2 * EVP_CIPHER_get_iv_length(enc) + 13
336
0
                > sizeof(buf)) {
337
0
            ERR_raise(ERR_LIB_PEM, PEM_R_UNSUPPORTED_CIPHER);
338
0
            goto err;
339
0
        }
340
0
    }
341
342
0
    if ((dsize = i2d(x, NULL)) <= 0) {
343
0
        ERR_raise(ERR_LIB_PEM, ERR_R_ASN1_LIB);
344
0
        dsize = 0;
345
0
        goto err;
346
0
    }
347
    /* dsize + 8 bytes are needed */
348
    /* actually it needs the cipher block size extra... */
349
0
    data = OPENSSL_malloc((unsigned int)dsize + 20);
350
0
    if (data == NULL) {
351
0
        ERR_raise(ERR_LIB_PEM, ERR_R_MALLOC_FAILURE);
352
0
        goto err;
353
0
    }
354
0
    p = data;
355
0
    i = i2d(x, &p);
356
357
0
    if (enc != NULL) {
358
0
        if (kstr == NULL) {
359
0
            if (callback == NULL)
360
0
                klen = PEM_def_callback(buf, PEM_BUFSIZE, 1, u);
361
0
            else
362
0
                klen = (*callback)(buf, PEM_BUFSIZE, 1, u);
363
0
            if (klen <= 0) {
364
0
                ERR_raise(ERR_LIB_PEM, PEM_R_READ_KEY);
365
0
                goto err;
366
0
            }
367
#ifdef CHARSET_EBCDIC
368
            /* Convert the pass phrase from EBCDIC */
369
            ebcdic2ascii(buf, buf, klen);
370
#endif
371
0
            kstr = (unsigned char *)buf;
372
0
        }
373
        /* Generate a salt */
374
0
        if (RAND_bytes(iv, EVP_CIPHER_get_iv_length(enc)) <= 0)
375
0
            goto err;
376
        /*
377
         * The 'iv' is used as the iv and as a salt.  It is NOT taken from
378
         * the BytesToKey function
379
         */
380
0
        if (!EVP_BytesToKey(enc, EVP_md5(), iv, kstr, klen, 1, key, NULL))
381
0
            goto err;
382
383
0
        if (kstr == (unsigned char *)buf)
384
0
            OPENSSL_cleanse(buf, PEM_BUFSIZE);
385
386
0
        buf[0] = '\0';
387
0
        PEM_proc_type(buf, PEM_TYPE_ENCRYPTED);
388
0
        PEM_dek_info(buf, objstr, EVP_CIPHER_get_iv_length(enc), (char *)iv);
389
        /* k=strlen(buf); */
390
391
0
        ret = 1;
392
0
        if ((ctx = EVP_CIPHER_CTX_new()) == NULL
393
0
            || !EVP_EncryptInit_ex(ctx, enc, NULL, key, iv)
394
0
            || !EVP_EncryptUpdate(ctx, data, &j, data, i)
395
0
            || !EVP_EncryptFinal_ex(ctx, &(data[j]), &i))
396
0
            ret = 0;
397
0
        if (ret == 0)
398
0
            goto err;
399
0
        i += j;
400
0
    } else {
401
0
        ret = 1;
402
0
        buf[0] = '\0';
403
0
    }
404
0
    i = PEM_write_bio(bp, name, buf, data, i);
405
0
    if (i <= 0)
406
0
        ret = 0;
407
0
err:
408
0
    OPENSSL_cleanse(key, sizeof(key));
409
0
    OPENSSL_cleanse(iv, sizeof(iv));
410
0
    EVP_CIPHER_CTX_free(ctx);
411
0
    OPENSSL_cleanse(buf, PEM_BUFSIZE);
412
0
    OPENSSL_clear_free(data, (unsigned int)dsize);
413
0
    return ret;
414
0
}
415
416
int PEM_do_header(EVP_CIPHER_INFO *cipher, unsigned char *data, long *plen,
417
    pem_password_cb *callback, void *u)
418
124k
{
419
124k
    int ok;
420
124k
    int keylen;
421
124k
    long len = *plen;
422
124k
    int ilen = (int)len; /* EVP_DecryptUpdate etc. take int lengths */
423
124k
    EVP_CIPHER_CTX *ctx;
424
124k
    unsigned char key[EVP_MAX_KEY_LENGTH];
425
124k
    char buf[PEM_BUFSIZE];
426
427
124k
#if LONG_MAX > INT_MAX
428
    /* Check that we did not truncate the length */
429
124k
    if (len > INT_MAX) {
430
0
        ERR_raise(ERR_LIB_PEM, PEM_R_HEADER_TOO_LONG);
431
0
        return 0;
432
0
    }
433
124k
#endif
434
435
124k
    if (cipher->cipher == NULL)
436
124k
        return 1;
437
2
    if (callback == NULL)
438
0
        keylen = PEM_def_callback(buf, PEM_BUFSIZE, 0, u);
439
2
    else
440
2
        keylen = callback(buf, PEM_BUFSIZE, 0, u);
441
2
    if (keylen < 0) {
442
2
        ERR_raise(ERR_LIB_PEM, PEM_R_BAD_PASSWORD_READ);
443
2
        return 0;
444
2
    }
445
#ifdef CHARSET_EBCDIC
446
    /* Convert the pass phrase from EBCDIC */
447
    ebcdic2ascii(buf, buf, keylen);
448
#endif
449
450
0
    if (!EVP_BytesToKey(cipher->cipher, EVP_md5(), &(cipher->iv[0]),
451
0
            (unsigned char *)buf, keylen, 1, key, NULL))
452
0
        return 0;
453
454
0
    ctx = EVP_CIPHER_CTX_new();
455
0
    if (ctx == NULL)
456
0
        return 0;
457
458
0
    ok = EVP_DecryptInit_ex(ctx, cipher->cipher, NULL, key, &(cipher->iv[0]));
459
0
    if (ok)
460
0
        ok = EVP_DecryptUpdate(ctx, data, &ilen, data, ilen);
461
0
    if (ok) {
462
        /* Squirrel away the length of data decrypted so far. */
463
0
        *plen = ilen;
464
0
        ok = EVP_DecryptFinal_ex(ctx, &(data[ilen]), &ilen);
465
0
    }
466
0
    if (ok)
467
0
        *plen += ilen;
468
0
    else
469
0
        ERR_raise(ERR_LIB_PEM, PEM_R_BAD_DECRYPT);
470
471
0
    EVP_CIPHER_CTX_free(ctx);
472
0
    OPENSSL_cleanse((char *)buf, sizeof(buf));
473
0
    OPENSSL_cleanse((char *)key, sizeof(key));
474
0
    return ok;
475
0
}
476
477
/*
478
 * This implements a very limited PEM header parser that does not support the
479
 * full grammar of rfc1421.  In particular, folded headers are not supported,
480
 * nor is additional whitespace.
481
 *
482
 * A robust implementation would make use of a library that turns the headers
483
 * into a BIO from which one folded line is read at a time, and is then split
484
 * into a header label and content.  We would then parse the content of the
485
 * headers we care about.  This is overkill for just this limited use-case, but
486
 * presumably we also parse rfc822-style headers for S/MIME, so a common
487
 * abstraction might well be more generally useful.
488
 */
489
int PEM_get_EVP_CIPHER_INFO(char *header, EVP_CIPHER_INFO *cipher)
490
9.54k
{
491
9.54k
    static const char ProcType[] = "Proc-Type:";
492
9.54k
    static const char ENCRYPTED[] = "ENCRYPTED";
493
9.54k
    static const char DEKInfo[] = "DEK-Info:";
494
9.54k
    const EVP_CIPHER *enc = NULL;
495
9.54k
    int ivlen;
496
9.54k
    char *dekinfostart, c;
497
498
9.54k
    cipher->cipher = NULL;
499
9.54k
    memset(cipher->iv, 0, sizeof(cipher->iv));
500
9.54k
    if ((header == NULL) || (*header == '\0') || (*header == '\n'))
501
9.54k
        return 1;
502
503
0
    if (strncmp(header, ProcType, sizeof(ProcType) - 1) != 0) {
504
0
        ERR_raise(ERR_LIB_PEM, PEM_R_NOT_PROC_TYPE);
505
0
        return 0;
506
0
    }
507
0
    header += sizeof(ProcType) - 1;
508
0
    header += strspn(header, " \t");
509
510
0
    if (*header++ != '4' || *header++ != ',')
511
0
        return 0;
512
0
    header += strspn(header, " \t");
513
514
    /* We expect "ENCRYPTED" followed by optional white-space + line break */
515
0
    if (strncmp(header, ENCRYPTED, sizeof(ENCRYPTED) - 1) != 0 || strspn(header + sizeof(ENCRYPTED) - 1, " \t\r\n") == 0) {
516
0
        ERR_raise(ERR_LIB_PEM, PEM_R_NOT_ENCRYPTED);
517
0
        return 0;
518
0
    }
519
0
    header += sizeof(ENCRYPTED) - 1;
520
0
    header += strspn(header, " \t\r");
521
0
    if (*header++ != '\n') {
522
0
        ERR_raise(ERR_LIB_PEM, PEM_R_SHORT_HEADER);
523
0
        return 0;
524
0
    }
525
526
    /*-
527
     * https://tools.ietf.org/html/rfc1421#section-4.6.1.3
528
     * We expect "DEK-Info: algo[,hex-parameters]"
529
     */
530
0
    if (strncmp(header, DEKInfo, sizeof(DEKInfo) - 1) != 0) {
531
0
        ERR_raise(ERR_LIB_PEM, PEM_R_NOT_DEK_INFO);
532
0
        return 0;
533
0
    }
534
0
    header += sizeof(DEKInfo) - 1;
535
0
    header += strspn(header, " \t");
536
537
    /*
538
     * DEK-INFO is a comma-separated combination of algorithm name and optional
539
     * parameters.
540
     */
541
0
    dekinfostart = header;
542
0
    header += strcspn(header, " \t,");
543
0
    c = *header;
544
0
    *header = '\0';
545
0
    cipher->cipher = enc = EVP_get_cipherbyname(dekinfostart);
546
0
    *header = c;
547
0
    header += strspn(header, " \t");
548
549
0
    if (enc == NULL) {
550
0
        ERR_raise(ERR_LIB_PEM, PEM_R_UNSUPPORTED_ENCRYPTION);
551
0
        return 0;
552
0
    }
553
0
    ivlen = EVP_CIPHER_get_iv_length(enc);
554
0
    if (ivlen > 0 && *header++ != ',') {
555
0
        ERR_raise(ERR_LIB_PEM, PEM_R_MISSING_DEK_IV);
556
0
        return 0;
557
0
    } else if (ivlen == 0 && *header == ',') {
558
0
        ERR_raise(ERR_LIB_PEM, PEM_R_UNEXPECTED_DEK_IV);
559
0
        return 0;
560
0
    }
561
562
0
    if (!load_iv(&header, cipher->iv, EVP_CIPHER_get_iv_length(enc)))
563
0
        return 0;
564
565
0
    return 1;
566
0
}
567
568
static int load_iv(char **fromp, unsigned char *to, int num)
569
21
{
570
21
    int v, i;
571
21
    char *from;
572
573
21
    from = *fromp;
574
189
    for (i = 0; i < num; i++)
575
168
        to[i] = 0;
576
21
    num *= 2;
577
148
    for (i = 0; i < num; i++) {
578
146
        v = OPENSSL_hexchar2int(*from);
579
146
        if (v < 0) {
580
19
            ERR_raise(ERR_LIB_PEM, PEM_R_BAD_IV_CHARS);
581
19
            return 0;
582
19
        }
583
127
        from++;
584
127
        to[i / 2] |= v << (long)((!(i & 1)) * 4);
585
127
    }
586
587
2
    *fromp = from;
588
2
    return 1;
589
21
}
590
591
#ifndef OPENSSL_NO_STDIO
592
int PEM_write(FILE *fp, const char *name, const char *header,
593
    const unsigned char *data, long len)
594
0
{
595
0
    BIO *b;
596
0
    int ret;
597
598
0
    if ((b = BIO_new(BIO_s_file())) == NULL) {
599
0
        ERR_raise(ERR_LIB_PEM, ERR_R_BUF_LIB);
600
0
        return 0;
601
0
    }
602
0
    BIO_set_fp(b, fp, BIO_NOCLOSE);
603
0
    ret = PEM_write_bio(b, name, header, data, len);
604
0
    BIO_free(b);
605
0
    return ret;
606
0
}
607
#endif
608
609
int PEM_write_bio(BIO *bp, const char *name, const char *header,
610
    const unsigned char *data, long len)
611
0
{
612
0
    int nlen, n, i, j, outl;
613
0
    unsigned char *buf = NULL;
614
0
    EVP_ENCODE_CTX *ctx = EVP_ENCODE_CTX_new();
615
0
    int reason = ERR_R_BUF_LIB;
616
0
    int retval = 0;
617
618
0
    if (ctx == NULL) {
619
0
        reason = ERR_R_MALLOC_FAILURE;
620
0
        goto err;
621
0
    }
622
623
0
    EVP_EncodeInit(ctx);
624
0
    nlen = strlen(name);
625
626
0
    if ((BIO_write(bp, "-----BEGIN ", 11) != 11) || (BIO_write(bp, name, nlen) != nlen) || (BIO_write(bp, "-----\n", 6) != 6))
627
0
        goto err;
628
629
0
    i = header != NULL ? strlen(header) : 0;
630
0
    if (i > 0) {
631
0
        if ((BIO_write(bp, header, i) != i) || (BIO_write(bp, "\n", 1) != 1))
632
0
            goto err;
633
0
    }
634
635
0
    buf = OPENSSL_malloc(PEM_BUFSIZE * 8);
636
0
    if (buf == NULL) {
637
0
        reason = ERR_R_MALLOC_FAILURE;
638
0
        goto err;
639
0
    }
640
641
0
    i = j = 0;
642
0
    while (len > 0) {
643
0
        n = (int)((len > (PEM_BUFSIZE * 5)) ? (PEM_BUFSIZE * 5) : len);
644
0
        if (!EVP_EncodeUpdate(ctx, buf, &outl, &(data[j]), n))
645
0
            goto err;
646
0
        if ((outl) && (BIO_write(bp, (char *)buf, outl) != outl))
647
0
            goto err;
648
0
        i += outl;
649
0
        len -= n;
650
0
        j += n;
651
0
    }
652
0
    EVP_EncodeFinal(ctx, buf, &outl);
653
0
    if ((outl > 0) && (BIO_write(bp, (char *)buf, outl) != outl))
654
0
        goto err;
655
0
    if ((BIO_write(bp, "-----END ", 9) != 9) || (BIO_write(bp, name, nlen) != nlen) || (BIO_write(bp, "-----\n", 6) != 6))
656
0
        goto err;
657
0
    retval = i + outl;
658
659
0
err:
660
0
    if (retval == 0)
661
0
        ERR_raise(ERR_LIB_PEM, reason);
662
0
    EVP_ENCODE_CTX_free(ctx);
663
0
    OPENSSL_clear_free(buf, PEM_BUFSIZE * 8);
664
0
    return retval;
665
0
}
666
667
#ifndef OPENSSL_NO_STDIO
668
int PEM_read(FILE *fp, char **name, char **header, unsigned char **data,
669
    long *len)
670
0
{
671
0
    BIO *b;
672
0
    int ret;
673
674
0
    if ((b = BIO_new(BIO_s_file())) == NULL) {
675
0
        ERR_raise(ERR_LIB_PEM, ERR_R_BUF_LIB);
676
0
        return 0;
677
0
    }
678
0
    BIO_set_fp(b, fp, BIO_NOCLOSE);
679
0
    ret = PEM_read_bio(b, name, header, data, len);
680
0
    BIO_free(b);
681
0
    return ret;
682
0
}
683
#endif
684
685
/* Some helpers for PEM_read_bio_ex(). */
686
static int sanitize_line(char *linebuf, int len, unsigned int flags, int first_call)
687
16.5M
{
688
16.5M
    int i;
689
16.5M
    if (first_call) {
690
        /* Other BOMs imply unsupported multibyte encoding,
691
         * so don't strip them and let the error raise */
692
294k
        const unsigned char utf8_bom[3] = { 0xEF, 0xBB, 0xBF };
693
694
294k
        if (len > 3 && memcmp(linebuf, utf8_bom, 3) == 0) {
695
17
            memmove(linebuf, linebuf + 3, len - 3);
696
17
            linebuf[len - 3] = 0;
697
17
            len -= 3;
698
17
        }
699
294k
    }
700
701
16.5M
    if (flags & PEM_FLAG_EAY_COMPATIBLE) {
702
        /* Strip trailing whitespace */
703
140M
        while ((len >= 0) && (linebuf[len] <= ' '))
704
124M
            len--;
705
        /* Go back to whitespace before applying uniform line ending. */
706
15.1M
        len++;
707
15.1M
    } else if (flags & PEM_FLAG_ONLY_B64) {
708
4.02M
        for (i = 0; i < len; ++i) {
709
4.01M
            if (!ossl_isbase64(linebuf[i]) || linebuf[i] == '\n'
710
4.00M
                || linebuf[i] == '\r')
711
7.81k
                break;
712
4.01M
        }
713
22.7k
        len = i;
714
1.40M
    } else {
715
        /* EVP_DecodeBlock strips leading and trailing whitespace, so just strip
716
         * control characters in-place and let everything through. */
717
172M
        for (i = 0; i < len; ++i) {
718
171M
            if (linebuf[i] == '\n' || linebuf[i] == '\r')
719
827k
                break;
720
171M
            if (ossl_iscntrl(linebuf[i]))
721
69.9M
                linebuf[i] = ' ';
722
171M
        }
723
1.40M
        len = i;
724
1.40M
    }
725
    /* The caller allocated LINESIZE+1, so this is safe. */
726
16.5M
    linebuf[len++] = '\n';
727
16.5M
    linebuf[len] = '\0';
728
16.5M
    return len;
729
16.5M
}
730
731
477k
#define LINESIZE 255
732
/* Note trailing spaces for begin and end. */
733
static const char beginstr[] = "-----BEGIN ";
734
static const char endstr[] = "-----END ";
735
static const char tailstr[] = "-----\n";
736
57.2k
#define BEGINLEN ((int)(sizeof(beginstr) - 1))
737
400k
#define ENDLEN ((int)(sizeof(endstr) - 1))
738
133k
#define TAILLEN ((int)(sizeof(tailstr) - 1))
739
static int get_name(BIO *bp, char **name, unsigned int flags)
740
19.0k
{
741
19.0k
    char *linebuf;
742
19.0k
    int ret = 0;
743
19.0k
    int len;
744
19.0k
    int first_call = 1;
745
746
    /*
747
     * Need to hold trailing NUL (accounted for by BIO_gets() and the newline
748
     * that will be added by sanitize_line() (the extra '1').
749
     */
750
19.0k
    linebuf = pem_malloc(LINESIZE + 1, flags);
751
19.0k
    if (linebuf == NULL) {
752
0
        ERR_raise(ERR_LIB_PEM, ERR_R_MALLOC_FAILURE);
753
0
        return 0;
754
0
    }
755
756
19.0k
    do {
757
19.0k
        len = BIO_gets(bp, linebuf, LINESIZE);
758
759
19.0k
        if (len <= 0) {
760
0
            ERR_raise(ERR_LIB_PEM, PEM_R_NO_START_LINE);
761
0
            goto err;
762
0
        }
763
764
        /* Strip trailing garbage and standardize ending. */
765
19.0k
        len = sanitize_line(linebuf, len, flags & ~PEM_FLAG_ONLY_B64, first_call);
766
19.0k
        first_call = 0;
767
768
        /* Allow leading empty or non-matching lines. */
769
19.0k
    } while (strncmp(linebuf, beginstr, BEGINLEN) != 0
770
19.0k
        || len < TAILLEN
771
19.0k
        || strncmp(linebuf + len - TAILLEN, tailstr, TAILLEN) != 0);
772
19.0k
    linebuf[len - TAILLEN] = '\0';
773
19.0k
    len = len - BEGINLEN - TAILLEN + 1;
774
19.0k
    *name = pem_malloc(len, flags);
775
19.0k
    if (*name == NULL) {
776
0
        ERR_raise(ERR_LIB_PEM, ERR_R_MALLOC_FAILURE);
777
0
        goto err;
778
0
    }
779
19.0k
    memcpy(*name, linebuf + BEGINLEN, len);
780
19.0k
    ret = 1;
781
782
19.0k
err:
783
19.0k
    pem_free(linebuf, flags, LINESIZE + 1);
784
19.0k
    return ret;
785
19.0k
}
786
787
/* Keep track of how much of a header we've seen. */
788
enum header_status {
789
    MAYBE_HEADER,
790
    IN_HEADER,
791
    POST_HEADER
792
};
793
794
/**
795
 * Extract the optional PEM header, with details on the type of content and
796
 * any encryption used on the contents, and the bulk of the data from the bio.
797
 * The end of the header is marked by a blank line; if the end-of-input marker
798
 * is reached prior to a blank line, there is no header.
799
 *
800
 * The header and data arguments are BIO** since we may have to swap them
801
 * if there is no header, for efficiency.
802
 *
803
 * We need the name of the PEM-encoded type to verify the end string.
804
 */
805
static int get_header_and_data(BIO *bp, BIO **header, BIO **data, char *name,
806
    unsigned int flags)
807
19.0k
{
808
19.0k
    BIO *tmp = *header;
809
19.0k
    char *linebuf, *p;
810
19.0k
    int len, ret = 0, end = 0, prev_partial_line_read = 0, partial_line_read = 0;
811
    /* 0 if not seen (yet), 1 if reading header, 2 if finished header */
812
19.0k
    enum header_status got_header = MAYBE_HEADER;
813
19.0k
    unsigned int flags_mask;
814
19.0k
    size_t namelen;
815
816
    /* Need to hold trailing NUL (accounted for by BIO_gets() and the newline
817
     * that will be added by sanitize_line() (the extra '1'). */
818
19.0k
    linebuf = pem_malloc(LINESIZE + 1, flags);
819
19.0k
    if (linebuf == NULL) {
820
0
        ERR_raise(ERR_LIB_PEM, ERR_R_MALLOC_FAILURE);
821
0
        return 0;
822
0
    }
823
824
190k
    while (1) {
825
190k
        flags_mask = ~0u;
826
190k
        len = BIO_gets(bp, linebuf, LINESIZE);
827
190k
        if (len <= 0) {
828
0
            ERR_raise(ERR_LIB_PEM, PEM_R_BAD_END_LINE);
829
0
            goto err;
830
0
        }
831
832
        /*
833
         * Check if line has been read completely or if only part of the line
834
         * has been read. Keep the previous value to ignore newlines that
835
         * appear due to reading a line up until the char before the newline.
836
         */
837
190k
        prev_partial_line_read = partial_line_read;
838
190k
        partial_line_read = len == LINESIZE - 1 && linebuf[LINESIZE - 2] != '\n';
839
840
190k
        if (got_header == MAYBE_HEADER) {
841
190k
            if (memchr(linebuf, ':', len) != NULL)
842
0
                got_header = IN_HEADER;
843
190k
        }
844
190k
        if (!strncmp(linebuf, endstr, ENDLEN) || got_header == IN_HEADER)
845
19.0k
            flags_mask &= ~PEM_FLAG_ONLY_B64;
846
190k
        len = sanitize_line(linebuf, len, flags & flags_mask, 0);
847
848
        /* Check for end of header. */
849
190k
        if (linebuf[0] == '\n') {
850
            /*
851
             * If previous line has been read only partially this newline is a
852
             * regular newline at the end of a line and not an empty line.
853
             */
854
0
            if (!prev_partial_line_read) {
855
0
                if (got_header == POST_HEADER) {
856
                    /* Another blank line is an error. */
857
0
                    ERR_raise(ERR_LIB_PEM, PEM_R_BAD_END_LINE);
858
0
                    goto err;
859
0
                }
860
0
                got_header = POST_HEADER;
861
0
                tmp = *data;
862
0
            }
863
0
            continue;
864
0
        }
865
866
        /* Check for end of stream (which means there is no header). */
867
190k
        if (strncmp(linebuf, endstr, ENDLEN) == 0) {
868
19.0k
            p = linebuf + ENDLEN;
869
19.0k
            namelen = strlen(name);
870
19.0k
            if (strncmp(p, name, namelen) != 0 || strncmp(p + namelen, tailstr, TAILLEN) != 0) {
871
0
                ERR_raise(ERR_LIB_PEM, PEM_R_BAD_END_LINE);
872
0
                goto err;
873
0
            }
874
19.0k
            if (got_header == MAYBE_HEADER) {
875
19.0k
                *header = *data;
876
19.0k
                *data = tmp;
877
19.0k
            }
878
19.0k
            break;
879
171k
        } else if (end) {
880
            /* Malformed input; short line not at end of data. */
881
0
            ERR_raise(ERR_LIB_PEM, PEM_R_BAD_END_LINE);
882
0
            goto err;
883
0
        }
884
        /*
885
         * Else, a line of text -- could be header or data; we don't
886
         * know yet.  Just pass it through.
887
         */
888
171k
        if (BIO_puts(tmp, linebuf) < 0)
889
0
            goto err;
890
        /*
891
         * Only encrypted files need the line length check applied.
892
         */
893
171k
        if (got_header == POST_HEADER) {
894
            /* 65 includes the trailing newline */
895
0
            if (len > 65)
896
0
                goto err;
897
0
            if (len < 65)
898
0
                end = 1;
899
0
        }
900
171k
    }
901
902
19.0k
    ret = 1;
903
19.0k
err:
904
19.0k
    pem_free(linebuf, flags, LINESIZE + 1);
905
19.0k
    return ret;
906
19.0k
}
907
908
/**
909
 * Read in PEM-formatted data from the given BIO.
910
 *
911
 * By nature of the PEM format, all content must be printable ASCII (except
912
 * for line endings).  Other characters are malformed input and will be rejected.
913
 */
914
int PEM_read_bio_ex(BIO *bp, char **name_out, char **header,
915
    unsigned char **data, long *len_out, unsigned int flags)
916
185k
{
917
185k
    EVP_ENCODE_CTX *ctx = NULL;
918
185k
    const BIO_METHOD *bmeth;
919
185k
    BIO *headerB = NULL, *dataB = NULL;
920
185k
    char *name = NULL;
921
185k
    int len, taillen, headerlen, ret = 0;
922
185k
    BUF_MEM *buf_mem;
923
924
185k
    *len_out = 0;
925
185k
    *name_out = *header = NULL;
926
185k
    *data = NULL;
927
185k
    if ((flags & PEM_FLAG_EAY_COMPATIBLE) && (flags & PEM_FLAG_ONLY_B64)) {
928
        /* These two are mutually incompatible; bail out. */
929
4
        ERR_raise(ERR_LIB_PEM, ERR_R_PASSED_INVALID_ARGUMENT);
930
4
        goto end;
931
4
    }
932
185k
    bmeth = (flags & PEM_FLAG_SECURE) ? BIO_s_secmem() : BIO_s_mem();
933
934
185k
    headerB = BIO_new(bmeth);
935
185k
    dataB = BIO_new(bmeth);
936
185k
    if (headerB == NULL || dataB == NULL) {
937
0
        ERR_raise(ERR_LIB_PEM, ERR_R_MALLOC_FAILURE);
938
0
        goto end;
939
0
    }
940
941
185k
    if (!get_name(bp, &name, flags))
942
23.4k
        goto end;
943
162k
    if (!get_header_and_data(bp, &headerB, &dataB, name, flags))
944
2.89k
        goto end;
945
946
159k
    BIO_get_mem_ptr(dataB, &buf_mem);
947
159k
    len = buf_mem->length;
948
949
    /* There was no data in the PEM file */
950
159k
    if (len == 0)
951
21
        goto end;
952
953
159k
    ctx = EVP_ENCODE_CTX_new();
954
159k
    if (ctx == NULL) {
955
0
        ERR_raise(ERR_LIB_PEM, ERR_R_MALLOC_FAILURE);
956
0
        goto end;
957
0
    }
958
959
159k
    EVP_DecodeInit(ctx);
960
159k
    if (EVP_DecodeUpdate(ctx, (unsigned char *)buf_mem->data, &len,
961
159k
            (unsigned char *)buf_mem->data, len)
962
159k
            < 0
963
158k
        || EVP_DecodeFinal(ctx, (unsigned char *)&(buf_mem->data[len]),
964
158k
               &taillen)
965
158k
            < 0) {
966
357
        ERR_raise(ERR_LIB_PEM, PEM_R_BAD_BASE64_DECODE);
967
357
        goto end;
968
357
    }
969
158k
    len += taillen;
970
158k
    buf_mem->length = len;
971
972
158k
    headerlen = BIO_get_mem_data(headerB, NULL);
973
158k
    *header = pem_malloc(headerlen + 1, flags);
974
158k
    *data = pem_malloc(len, flags);
975
158k
    if (*header == NULL || *data == NULL)
976
39
        goto out_free;
977
158k
    if (headerlen != 0 && BIO_read(headerB, *header, headerlen) != headerlen)
978
0
        goto out_free;
979
158k
    (*header)[headerlen] = '\0';
980
158k
    if (BIO_read(dataB, *data, len) != len)
981
0
        goto out_free;
982
158k
    *len_out = len;
983
158k
    *name_out = name;
984
158k
    name = NULL;
985
158k
    ret = 1;
986
158k
    goto end;
987
988
39
out_free:
989
39
    pem_free(*header, flags, 0);
990
39
    *header = NULL;
991
39
    pem_free(*data, flags, 0);
992
39
    *data = NULL;
993
185k
end:
994
185k
    EVP_ENCODE_CTX_free(ctx);
995
185k
    pem_free(name, flags, 0);
996
185k
    BIO_free(headerB);
997
185k
    BIO_free(dataB);
998
185k
    return ret;
999
39
}
1000
1001
int PEM_read_bio(BIO *bp, char **name, char **header, unsigned char **data,
1002
    long *len)
1003
164k
{
1004
164k
    return PEM_read_bio_ex(bp, name, header, data, len, PEM_FLAG_EAY_COMPATIBLE);
1005
164k
}
1006
1007
/*
1008
 * Check pem string and return prefix length. If for example the pem_str ==
1009
 * "RSA PRIVATE KEY" and suffix = "PRIVATE KEY" the return value is 3 for the
1010
 * string "RSA".
1011
 */
1012
1013
int ossl_pem_check_suffix(const char *pem_str, const char *suffix)
1014
0
{
1015
0
    int pem_len = strlen(pem_str);
1016
0
    int suffix_len = strlen(suffix);
1017
0
    const char *p;
1018
0
    if (suffix_len + 1 >= pem_len)
1019
0
        return 0;
1020
0
    p = pem_str + pem_len - suffix_len;
1021
0
    if (strcmp(p, suffix))
1022
0
        return 0;
1023
0
    p--;
1024
0
    if (*p != ' ')
1025
0
        return 0;
1026
0
    return p - pem_str;
1027
0
}