Coverage Report

Created: 2024-07-24 06:31

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