Coverage Report

Created: 2025-12-08 06:22

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
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
0
                       void *u) {
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
0
                              void *u) {
292
0
    return pem_bytes_read_bio_flags(pdata, plen, pnm, name, bp, cb, u,
293
0
                                    PEM_FLAG_SECURE | PEM_FLAG_EAY_COMPATIBLE);
294
0
}
295
296
#ifndef OPENSSL_NO_STDIO
297
int PEM_ASN1_write(i2d_of_void *i2d, const char *name, FILE *fp,
298
                   const void *x, const EVP_CIPHER *enc,
299
                   const unsigned char *kstr, int klen,
300
                   pem_password_cb *callback, void *u)
301
0
{
302
0
    BIO *b;
303
0
    int ret;
304
305
0
    if ((b = BIO_new(BIO_s_file())) == NULL) {
306
0
        ERR_raise(ERR_LIB_PEM, ERR_R_BUF_LIB);
307
0
        return 0;
308
0
    }
309
0
    BIO_set_fp(b, fp, BIO_NOCLOSE);
310
0
    ret = PEM_ASN1_write_bio(i2d, name, b, x, enc, kstr, klen, callback, u);
311
0
    BIO_free(b);
312
0
    return ret;
313
0
}
314
#endif
315
316
static int
317
PEM_ASN1_write_bio_internal(
318
    i2d_of_void *i2d, OSSL_i2d_of_void_ctx *i2d_ctx, void *vctx,
319
    const char *name, BIO *bp, const void *x, const EVP_CIPHER *enc,
320
    const unsigned char *kstr, int klen, pem_password_cb *callback, void *u)
321
0
{
322
0
    EVP_CIPHER_CTX *ctx = NULL;
323
0
    int dsize = 0, i = 0, j = 0, ret = 0;
324
0
    unsigned char *p, *data = NULL;
325
0
    const char *objstr = NULL;
326
0
    char buf[PEM_BUFSIZE];
327
0
    unsigned char key[EVP_MAX_KEY_LENGTH];
328
0
    unsigned char iv[EVP_MAX_IV_LENGTH];
329
330
0
    if (enc != NULL) {
331
0
        objstr = EVP_CIPHER_get0_name(enc);
332
0
        if (objstr == NULL || EVP_CIPHER_get_iv_length(enc) == 0
333
0
                || EVP_CIPHER_get_iv_length(enc) > (int)sizeof(iv)
334
                   /*
335
                    * Check "Proc-Type: 4,Encrypted\nDEK-Info: objstr,hex-iv\n"
336
                    * fits into buf
337
                    */
338
0
                || strlen(objstr) + 23 + 2 * EVP_CIPHER_get_iv_length(enc) + 13
339
0
                   > sizeof(buf)) {
340
0
            ERR_raise(ERR_LIB_PEM, PEM_R_UNSUPPORTED_CIPHER);
341
0
            goto err;
342
0
        }
343
0
    }
344
345
0
    if (i2d == NULL && i2d_ctx == NULL) {
346
0
        ERR_raise(ERR_LIB_CRYPTO, CRYPTO_R_INVALID_NULL_ARGUMENT);
347
0
        dsize = 0;
348
0
        goto err;
349
0
    }
350
0
    dsize = i2d != NULL ? i2d(x, NULL) : i2d_ctx(x, NULL, vctx);
351
0
    if (dsize <= 0) {
352
0
        ERR_raise(ERR_LIB_PEM, ERR_R_ASN1_LIB);
353
0
        dsize = 0;
354
0
        goto err;
355
0
    }
356
    /* Allocate enough space for one extra cipher block */
357
0
    data = OPENSSL_malloc((unsigned int)dsize + EVP_MAX_BLOCK_LENGTH);
358
0
    if (data == NULL)
359
0
        goto err;
360
0
    p = data;
361
0
    i = i2d != NULL ? i2d(x, &p) : i2d_ctx(x, &p, vctx);
362
363
0
    if (enc != NULL) {
364
0
        if (kstr == NULL) {
365
0
            if (callback == NULL)
366
0
                klen = PEM_def_callback(buf, PEM_BUFSIZE, 1, u);
367
0
            else
368
0
                klen = (*callback) (buf, PEM_BUFSIZE, 1, u);
369
0
            if (klen <= 0) {
370
0
                ERR_raise(ERR_LIB_PEM, PEM_R_READ_KEY);
371
0
                goto err;
372
0
            }
373
#ifdef CHARSET_EBCDIC
374
            /* Convert the pass phrase from EBCDIC */
375
            ebcdic2ascii(buf, buf, klen);
376
#endif
377
0
            kstr = (unsigned char *)buf;
378
0
        }
379
        /* Generate a salt */
380
0
        if (RAND_bytes(iv, EVP_CIPHER_get_iv_length(enc)) <= 0)
381
0
            goto err;
382
        /*
383
         * The 'iv' is used as the iv and as a salt.  It is NOT taken from
384
         * the BytesToKey function
385
         */
386
0
        if (!EVP_BytesToKey(enc, EVP_md5(), iv, kstr, klen, 1, key, NULL))
387
0
            goto err;
388
389
0
        if (kstr == (unsigned char *)buf)
390
0
            OPENSSL_cleanse(buf, PEM_BUFSIZE);
391
392
0
        buf[0] = '\0';
393
0
        PEM_proc_type(buf, PEM_TYPE_ENCRYPTED);
394
0
        PEM_dek_info(buf, objstr, EVP_CIPHER_get_iv_length(enc), (char *)iv);
395
        /* k=strlen(buf); */
396
397
0
        ret = 1;
398
0
        if ((ctx = EVP_CIPHER_CTX_new()) == NULL
399
0
            || !EVP_EncryptInit_ex(ctx, enc, NULL, key, iv)
400
0
            || !EVP_EncryptUpdate(ctx, data, &j, data, i)
401
0
            || !EVP_EncryptFinal_ex(ctx, &(data[j]), &i))
402
0
            ret = 0;
403
0
        if (ret == 0)
404
0
            goto err;
405
0
        i += j;
406
0
    } else {
407
0
        ret = 1;
408
0
        buf[0] = '\0';
409
0
    }
410
0
    i = PEM_write_bio(bp, name, buf, data, i);
411
0
    if (i <= 0)
412
0
        ret = 0;
413
0
 err:
414
0
    OPENSSL_cleanse(key, sizeof(key));
415
0
    OPENSSL_cleanse(iv, sizeof(iv));
416
0
    EVP_CIPHER_CTX_free(ctx);
417
0
    OPENSSL_cleanse(buf, PEM_BUFSIZE);
418
0
    OPENSSL_clear_free(data, (unsigned int)dsize);
419
0
    return ret;
420
0
}
421
422
int
423
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) ||
539
0
        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) ||
649
0
        (BIO_write(bp, name, nlen) != nlen) ||
650
0
        (BIO_write(bp, "-----\n", 6) != 6)) {
651
0
        reason = ERR_R_BIO_LIB;
652
0
        goto err;
653
0
    }
654
655
0
    i = header != NULL ? (int)strlen(header) : 0;
656
0
    if (i > 0) {
657
0
        if ((BIO_write(bp, header, i) != i) || (BIO_write(bp, "\n", 1) != 1)) {
658
0
            reason = ERR_R_BIO_LIB;
659
0
            goto err;
660
0
        }
661
0
    }
662
663
0
    buf = OPENSSL_malloc_array(PEM_BUFSIZE, 8);
664
0
    if (buf == NULL)
665
0
        goto err;
666
667
0
    i = j = 0;
668
0
    while (len > 0) {
669
0
        n = (int)((len > (PEM_BUFSIZE * 5)) ? (PEM_BUFSIZE * 5) : len);
670
0
        if (!EVP_EncodeUpdate(ctx, buf, &outl, &(data[j]), n)) {
671
0
            reason = ERR_R_EVP_LIB;
672
0
            goto err;
673
0
        }
674
0
        if ((outl) && (BIO_write(bp, (char *)buf, outl) != outl)) {
675
0
            reason = ERR_R_BIO_LIB;
676
0
            goto err;
677
0
        }
678
0
        i += outl;
679
0
        len -= n;
680
0
        j += n;
681
0
    }
682
0
    EVP_EncodeFinal(ctx, buf, &outl);
683
0
    if ((outl > 0) && (BIO_write(bp, (char *)buf, outl) != outl)) {
684
0
        reason = ERR_R_BIO_LIB;
685
0
        goto err;
686
0
    }
687
0
    if ((BIO_write(bp, "-----END ", 9) != 9) ||
688
0
        (BIO_write(bp, name, nlen) != nlen) ||
689
0
        (BIO_write(bp, "-----\n", 6) != 6)) {
690
0
        reason = ERR_R_BIO_LIB;
691
0
        goto err;
692
0
    }
693
0
    retval = i + outl;
694
695
0
 err:
696
0
    if (retval == 0 && reason != 0)
697
0
        ERR_raise(ERR_LIB_PEM, reason);
698
0
    EVP_ENCODE_CTX_free(ctx);
699
0
    OPENSSL_clear_free(buf, PEM_BUFSIZE * 8);
700
0
    return retval;
701
0
}
702
703
#ifndef OPENSSL_NO_STDIO
704
int PEM_read(FILE *fp, char **name, char **header, unsigned char **data,
705
             long *len)
706
0
{
707
0
    BIO *b;
708
0
    int ret;
709
710
0
    if ((b = BIO_new(BIO_s_file())) == NULL) {
711
0
        ERR_raise(ERR_LIB_PEM, ERR_R_BUF_LIB);
712
0
        return 0;
713
0
    }
714
0
    BIO_set_fp(b, fp, BIO_NOCLOSE);
715
0
    ret = PEM_read_bio(b, name, header, data, len);
716
0
    BIO_free(b);
717
0
    return ret;
718
0
}
719
#endif
720
721
/* Some helpers for PEM_read_bio_ex(). */
722
static int sanitize_line(char *linebuf, int len, unsigned int flags, int first_call)
723
0
{
724
0
    int i;
725
0
    if (first_call) {
726
        /* Other BOMs imply unsupported multibyte encoding,
727
         * so don't strip them and let the error raise */
728
0
        const unsigned char utf8_bom[3] = {0xEF, 0xBB, 0xBF};
729
730
0
        if (len > 3 && memcmp(linebuf, utf8_bom, 3) == 0) {
731
0
            memmove(linebuf, linebuf + 3, len - 3);
732
0
            linebuf[len - 3] = 0;
733
0
            len -= 3;
734
0
        }
735
0
    }
736
737
0
    if (flags & PEM_FLAG_EAY_COMPATIBLE) {
738
        /* Strip trailing whitespace */
739
0
        while ((len >= 0) && (linebuf[len] <= ' '))
740
0
            len--;
741
        /* Go back to whitespace before applying uniform line ending. */
742
0
        len++;
743
0
    } else if (flags & PEM_FLAG_ONLY_B64) {
744
0
        for (i = 0; i < len; ++i) {
745
0
            if (!ossl_isbase64(linebuf[i]) || linebuf[i] == '\n'
746
0
                || linebuf[i] == '\r')
747
0
                break;
748
0
        }
749
0
        len = i;
750
0
    } else {
751
        /* EVP_DecodeBlock strips leading and trailing whitespace, so just strip
752
         * control characters in-place and let everything through. */
753
0
        for (i = 0; i < len; ++i) {
754
0
            if (linebuf[i] == '\n' || linebuf[i] == '\r')
755
0
                break;
756
0
            if (ossl_iscntrl(linebuf[i]))
757
0
                linebuf[i] = ' ';
758
0
        }
759
0
        len = i;
760
0
    }
761
    /* The caller allocated LINESIZE+1, so this is safe. */
762
0
    linebuf[len++] = '\n';
763
0
    linebuf[len] = '\0';
764
0
    return len;
765
0
}
766
767
0
#define LINESIZE 255
768
/* Note trailing spaces for begin and end. */
769
0
#define BEGINSTR "-----BEGIN "
770
#define ENDSTR "-----END "
771
0
#define TAILSTR "-----\n"
772
0
#define BEGINLEN ((int)(sizeof(BEGINSTR) - 1))
773
#define ENDLEN ((int)(sizeof(ENDSTR) - 1))
774
0
#define TAILLEN ((int)(sizeof(TAILSTR) - 1))
775
static int get_name(BIO *bp, char **name, unsigned int flags)
776
0
{
777
0
    char *linebuf;
778
0
    int ret = 0;
779
0
    int len;
780
0
    int first_call = 1;
781
782
    /*
783
     * Need to hold trailing NUL (accounted for by BIO_gets() and the newline
784
     * that will be added by sanitize_line() (the extra '1').
785
     */
786
0
    linebuf = PEM_MALLOC(LINESIZE + 1, flags);
787
0
    if (linebuf == NULL)
788
0
        return 0;
789
790
0
    do {
791
0
        len = BIO_gets(bp, linebuf, LINESIZE);
792
793
0
        if (len <= 0) {
794
0
            ERR_raise(ERR_LIB_PEM, PEM_R_NO_START_LINE);
795
0
            goto err;
796
0
        }
797
798
        /* Strip trailing garbage and standardize ending. */
799
0
        len = sanitize_line(linebuf, len, flags & ~PEM_FLAG_ONLY_B64, first_call);
800
0
        first_call = 0;
801
802
        /* Allow leading empty or non-matching lines. */
803
0
    } while (!HAS_PREFIX(linebuf, BEGINSTR)
804
0
             || len < TAILLEN
805
0
             || !HAS_PREFIX(linebuf + len - TAILLEN, TAILSTR));
806
0
    linebuf[len - TAILLEN] = '\0';
807
0
    len = len - BEGINLEN - TAILLEN + 1;
808
0
    *name = PEM_MALLOC(len, flags);
809
0
    if (*name == NULL)
810
0
        goto err;
811
0
    memcpy(*name, linebuf + BEGINLEN, len);
812
0
    ret = 1;
813
814
0
err:
815
0
    PEM_FREE(linebuf, flags, LINESIZE + 1);
816
0
    return ret;
817
0
}
818
819
/* Keep track of how much of a header we've seen. */
820
enum header_status {
821
    MAYBE_HEADER,
822
    IN_HEADER,
823
    POST_HEADER
824
};
825
826
/**
827
 * Extract the optional PEM header, with details on the type of content and
828
 * any encryption used on the contents, and the bulk of the data from the bio.
829
 * The end of the header is marked by a blank line; if the end-of-input marker
830
 * is reached prior to a blank line, there is no header.
831
 *
832
 * The header and data arguments are BIO** since we may have to swap them
833
 * if there is no header, for efficiency.
834
 *
835
 * We need the name of the PEM-encoded type to verify the end string.
836
 */
837
static int get_header_and_data(BIO *bp, BIO **header, BIO **data, char *name,
838
                               unsigned int flags)
839
0
{
840
0
    BIO *tmp = *header;
841
0
    char *linebuf, *p;
842
0
    int len, ret = 0, end = 0, prev_partial_line_read = 0, partial_line_read = 0;
843
    /* 0 if not seen (yet), 1 if reading header, 2 if finished header */
844
0
    enum header_status got_header = MAYBE_HEADER;
845
0
    unsigned int flags_mask;
846
0
    size_t namelen;
847
848
    /* Need to hold trailing NUL (accounted for by BIO_gets() and the newline
849
     * that will be added by sanitize_line() (the extra '1'). */
850
0
    linebuf = PEM_MALLOC(LINESIZE + 1, flags);
851
0
    if (linebuf == NULL)
852
0
        return 0;
853
854
0
    while(1) {
855
0
        flags_mask = ~0u;
856
0
        len = BIO_gets(bp, linebuf, LINESIZE);
857
0
        if (len <= 0) {
858
0
            ERR_raise(ERR_LIB_PEM, PEM_R_BAD_END_LINE);
859
0
            goto err;
860
0
        }
861
862
        /*
863
         * Check if line has been read completely or if only part of the line
864
         * has been read. Keep the previous value to ignore newlines that
865
         * appear due to reading a line up until the char before the newline.
866
         */
867
0
        prev_partial_line_read = partial_line_read;
868
0
        partial_line_read = len == LINESIZE-1 && linebuf[LINESIZE-2] != '\n';
869
870
0
        if (got_header == MAYBE_HEADER) {
871
0
            if (memchr(linebuf, ':', len) != NULL)
872
0
                got_header = IN_HEADER;
873
0
        }
874
0
        if (HAS_PREFIX(linebuf, ENDSTR) || got_header == IN_HEADER)
875
0
            flags_mask &= ~PEM_FLAG_ONLY_B64;
876
0
        len = sanitize_line(linebuf, len, flags & flags_mask, 0);
877
878
        /* Check for end of header. */
879
0
        if (linebuf[0] == '\n') {
880
            /*
881
             * If previous line has been read only partially this newline is a
882
             * regular newline at the end of a line and not an empty line.
883
             */
884
0
            if (!prev_partial_line_read) {
885
0
                if (got_header == POST_HEADER) {
886
                    /* Another blank line is an error. */
887
0
                    ERR_raise(ERR_LIB_PEM, PEM_R_BAD_END_LINE);
888
0
                    goto err;
889
0
                }
890
0
                got_header = POST_HEADER;
891
0
                tmp = *data;
892
0
            }
893
0
            continue;
894
0
        }
895
896
        /* Check for end of stream (which means there is no header). */
897
0
        p = linebuf;
898
0
        if (CHECK_AND_SKIP_PREFIX(p, ENDSTR)) {
899
0
            namelen = strlen(name);
900
0
            if (strncmp(p, name, namelen) != 0 ||
901
0
                !HAS_PREFIX(p + namelen, TAILSTR)) {
902
0
                ERR_raise(ERR_LIB_PEM, PEM_R_BAD_END_LINE);
903
0
                goto err;
904
0
            }
905
0
            if (got_header == MAYBE_HEADER) {
906
0
                *header = *data;
907
0
                *data = tmp;
908
0
            }
909
0
            break;
910
0
        } else if (end) {
911
            /* Malformed input; short line not at end of data. */
912
0
            ERR_raise(ERR_LIB_PEM, PEM_R_BAD_END_LINE);
913
0
            goto err;
914
0
        }
915
        /*
916
         * Else, a line of text -- could be header or data; we don't
917
         * know yet.  Just pass it through.
918
         */
919
0
        if (BIO_puts(tmp, linebuf) < 0)
920
0
            goto err;
921
        /*
922
         * Only encrypted files need the line length check applied.
923
         */
924
0
        if (got_header == POST_HEADER) {
925
            /* 65 includes the trailing newline */
926
0
            if (len > 65)
927
0
                goto err;
928
0
            if (len < 65)
929
0
                end = 1;
930
0
        }
931
0
    }
932
933
0
    ret = 1;
934
0
err:
935
0
    PEM_FREE(linebuf, flags, LINESIZE + 1);
936
0
    return ret;
937
0
}
938
939
/**
940
 * Read in PEM-formatted data from the given BIO.
941
 *
942
 * By nature of the PEM format, all content must be printable ASCII (except
943
 * for line endings).  Other characters are malformed input and will be rejected.
944
 */
945
int PEM_read_bio_ex(BIO *bp, char **name_out, char **header,
946
                    unsigned char **data, long *len_out, unsigned int flags)
947
0
{
948
0
    EVP_ENCODE_CTX *ctx = NULL;
949
0
    const BIO_METHOD *bmeth;
950
0
    BIO *headerB = NULL, *dataB = NULL;
951
0
    char *name = NULL;
952
0
    int len, taillen, headerlen, ret = 0;
953
0
    BUF_MEM *buf_mem;
954
955
0
    *len_out = 0;
956
0
    *name_out = *header = NULL;
957
0
    *data = NULL;
958
0
    if ((flags & PEM_FLAG_EAY_COMPATIBLE) && (flags & PEM_FLAG_ONLY_B64)) {
959
        /* These two are mutually incompatible; bail out. */
960
0
        ERR_raise(ERR_LIB_PEM, ERR_R_PASSED_INVALID_ARGUMENT);
961
0
        goto end;
962
0
    }
963
0
    bmeth = (flags & PEM_FLAG_SECURE) ? BIO_s_secmem() : BIO_s_mem();
964
965
0
    headerB = BIO_new(bmeth);
966
0
    dataB = BIO_new(bmeth);
967
0
    if (headerB == NULL || dataB == NULL) {
968
0
        ERR_raise(ERR_LIB_PEM, ERR_R_BIO_LIB);
969
0
        goto end;
970
0
    }
971
972
0
    if (!get_name(bp, &name, flags))
973
0
        goto end;
974
0
    if (!get_header_and_data(bp, &headerB, &dataB, name, flags))
975
0
        goto end;
976
977
0
    BIO_get_mem_ptr(dataB, &buf_mem);
978
0
    if (buf_mem->length > INT_MAX) {
979
0
        ERR_raise(ERR_LIB_PEM, PEM_R_BAD_BASE64_DECODE);
980
0
        goto end;
981
0
    }
982
0
    len = (int)buf_mem->length;
983
984
    /* There was no data in the PEM file */
985
0
    if (len == 0)
986
0
        goto end;
987
988
0
    ctx = EVP_ENCODE_CTX_new();
989
0
    if (ctx == NULL) {
990
0
        ERR_raise(ERR_LIB_PEM, ERR_R_EVP_LIB);
991
0
        goto end;
992
0
    }
993
994
0
    EVP_DecodeInit(ctx);
995
0
    if (EVP_DecodeUpdate(ctx, (unsigned char*)buf_mem->data, &len,
996
0
                         (unsigned char*)buf_mem->data, len) < 0
997
0
            || EVP_DecodeFinal(ctx, (unsigned char*)&(buf_mem->data[len]),
998
0
                               &taillen) < 0) {
999
0
        ERR_raise(ERR_LIB_PEM, PEM_R_BAD_BASE64_DECODE);
1000
0
        goto end;
1001
0
    }
1002
0
    len += taillen;
1003
0
    buf_mem->length = len;
1004
1005
0
    headerlen = BIO_get_mem_data(headerB, NULL);
1006
0
    *header = PEM_MALLOC(headerlen + 1, flags);
1007
0
    *data = PEM_MALLOC(len, flags);
1008
0
    if (*header == NULL || *data == NULL)
1009
0
        goto out_free;
1010
0
    if (headerlen != 0 && BIO_read(headerB, *header, headerlen) != headerlen)
1011
0
        goto out_free;
1012
0
    (*header)[headerlen] = '\0';
1013
0
    if (BIO_read(dataB, *data, len) != len)
1014
0
        goto out_free;
1015
0
    *len_out = len;
1016
0
    *name_out = name;
1017
0
    name = NULL;
1018
0
    ret = 1;
1019
0
    goto end;
1020
1021
0
out_free:
1022
0
    PEM_FREE(*header, flags, 0);
1023
0
    *header = NULL;
1024
0
    PEM_FREE(*data, flags, 0);
1025
0
    *data = NULL;
1026
0
end:
1027
0
    EVP_ENCODE_CTX_free(ctx);
1028
0
    PEM_FREE(name, flags, 0);
1029
0
    BIO_free(headerB);
1030
0
    BIO_free(dataB);
1031
0
    return ret;
1032
0
}
1033
1034
int PEM_read_bio(BIO *bp, char **name, char **header, unsigned char **data,
1035
                 long *len)
1036
0
{
1037
0
    return PEM_read_bio_ex(bp, name, header, data, len, PEM_FLAG_EAY_COMPATIBLE);
1038
0
}
1039
1040
/*
1041
 * Check pem string and return prefix length. If for example the pem_str ==
1042
 * "RSA PRIVATE KEY" and suffix = "PRIVATE KEY" the return value is 3 for the
1043
 * string "RSA".
1044
 */
1045
1046
int ossl_pem_check_suffix(const char *pem_str, const char *suffix)
1047
0
{
1048
0
    int pem_len = (int)strlen(pem_str);
1049
0
    int suffix_len = (int)strlen(suffix);
1050
0
    const char *p;
1051
1052
0
    if (suffix_len + 1 >= pem_len)
1053
0
        return 0;
1054
0
    p = pem_str + pem_len - suffix_len;
1055
0
    if (strcmp(p, suffix))
1056
0
        return 0;
1057
0
    p--;
1058
0
    if (*p != ' ')
1059
0
        return 0;
1060
0
    return (int)(p - pem_str);
1061
0
}