Coverage Report

Created: 2025-12-10 06:24

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