Coverage Report

Created: 2025-07-23 06:08

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