Coverage Report

Created: 2018-08-29 13:53

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