Coverage Report

Created: 2025-06-22 06:56

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