Coverage Report

Created: 2026-02-22 06:11

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