Coverage Report

Created: 2022-11-30 06:20

/src/openssl/crypto/pem/pem_lib.c
Line
Count
Source (jump to first uncovered line)
1
/* crypto/pem/pem_lib.c */
2
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3
 * All rights reserved.
4
 *
5
 * This package is an SSL implementation written
6
 * by Eric Young (eay@cryptsoft.com).
7
 * The implementation was written so as to conform with Netscapes SSL.
8
 *
9
 * This library is free for commercial and non-commercial use as long as
10
 * the following conditions are aheared to.  The following conditions
11
 * apply to all code found in this distribution, be it the RC4, RSA,
12
 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13
 * included with this distribution is covered by the same copyright terms
14
 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15
 *
16
 * Copyright remains Eric Young's, and as such any Copyright notices in
17
 * the code are not to be removed.
18
 * If this package is used in a product, Eric Young should be given attribution
19
 * as the author of the parts of the library used.
20
 * This can be in the form of a textual message at program startup or
21
 * in documentation (online or textual) provided with the package.
22
 *
23
 * Redistribution and use in source and binary forms, with or without
24
 * modification, are permitted provided that the following conditions
25
 * are met:
26
 * 1. Redistributions of source code must retain the copyright
27
 *    notice, this list of conditions and the following disclaimer.
28
 * 2. Redistributions in binary form must reproduce the above copyright
29
 *    notice, this list of conditions and the following disclaimer in the
30
 *    documentation and/or other materials provided with the distribution.
31
 * 3. All advertising materials mentioning features or use of this software
32
 *    must display the following acknowledgement:
33
 *    "This product includes cryptographic software written by
34
 *     Eric Young (eay@cryptsoft.com)"
35
 *    The word 'cryptographic' can be left out if the rouines from the library
36
 *    being used are not cryptographic related :-).
37
 * 4. If you include any Windows specific code (or a derivative thereof) from
38
 *    the apps directory (application code) you must include an acknowledgement:
39
 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40
 *
41
 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51
 * SUCH DAMAGE.
52
 *
53
 * The licence and distribution terms for any publically available version or
54
 * derivative of this code cannot be changed.  i.e. this code cannot simply be
55
 * copied and put under another distribution licence
56
 * [including the GNU Public Licence.]
57
 */
58
59
#include <stdio.h>
60
#include <ctype.h>
61
#include "cryptlib.h"
62
#include <openssl/buffer.h>
63
#include <openssl/objects.h>
64
#include <openssl/evp.h>
65
#include <openssl/rand.h>
66
#include <openssl/x509.h>
67
#include <openssl/pem.h>
68
#include <openssl/pkcs12.h>
69
#include "asn1_locl.h"
70
#ifndef OPENSSL_NO_DES
71
# include <openssl/des.h>
72
#endif
73
#ifndef OPENSSL_NO_ENGINE
74
# include <openssl/engine.h>
75
#endif
76
77
const char PEM_version[] = "PEM" OPENSSL_VERSION_PTEXT;
78
79
0
#define MIN_LENGTH      4
80
81
static int load_iv(char **fromp, unsigned char *to, int num);
82
static int check_pem(const char *nm, const char *name);
83
int pem_check_suffix(const char *pem_str, const char *suffix);
84
85
int PEM_def_callback(char *buf, int num, int w, void *key)
86
0
{
87
#ifdef OPENSSL_NO_FP_API
88
    /*
89
     * We should not ever call the default callback routine from windows.
90
     */
91
    PEMerr(PEM_F_PEM_DEF_CALLBACK, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
92
    return (-1);
93
#else
94
0
    int i, j;
95
0
    const char *prompt;
96
0
    if (key) {
97
0
        i = strlen(key);
98
0
        i = (i > num) ? num : i;
99
0
        memcpy(buf, key, i);
100
0
        return (i);
101
0
    }
102
103
0
    prompt = EVP_get_pw_prompt();
104
0
    if (prompt == NULL)
105
0
        prompt = "Enter PEM pass phrase:";
106
107
0
    for (;;) {
108
        /*
109
         * We assume that w == 0 means decryption,
110
         * while w == 1 means encryption
111
         */
112
0
        int min_len = w ? MIN_LENGTH : 0;
113
114
0
        i = EVP_read_pw_string_min(buf, min_len, num, prompt, w);
115
0
        if (i != 0) {
116
0
            PEMerr(PEM_F_PEM_DEF_CALLBACK, PEM_R_PROBLEMS_GETTING_PASSWORD);
117
0
            memset(buf, 0, (unsigned int)num);
118
0
            return (-1);
119
0
        }
120
0
        j = strlen(buf);
121
0
        if (min_len && j < min_len) {
122
0
            fprintf(stderr,
123
0
                    "phrase is too short, needs to be at least %d chars\n",
124
0
                    min_len);
125
0
        } else
126
0
            break;
127
0
    }
128
0
    return (j);
129
0
#endif
130
0
}
131
132
void PEM_proc_type(char *buf, int type)
133
0
{
134
0
    const char *str;
135
136
0
    if (type == PEM_TYPE_ENCRYPTED)
137
0
        str = "ENCRYPTED";
138
0
    else if (type == PEM_TYPE_MIC_CLEAR)
139
0
        str = "MIC-CLEAR";
140
0
    else if (type == PEM_TYPE_MIC_ONLY)
141
0
        str = "MIC-ONLY";
142
0
    else
143
0
        str = "BAD-TYPE";
144
145
0
    BUF_strlcat(buf, "Proc-Type: 4,", PEM_BUFSIZE);
146
0
    BUF_strlcat(buf, str, PEM_BUFSIZE);
147
0
    BUF_strlcat(buf, "\n", PEM_BUFSIZE);
148
0
}
149
150
void PEM_dek_info(char *buf, const char *type, int len, char *str)
151
0
{
152
0
    static const unsigned char map[17] = "0123456789ABCDEF";
153
0
    long i;
154
0
    int j;
155
156
0
    BUF_strlcat(buf, "DEK-Info: ", PEM_BUFSIZE);
157
0
    BUF_strlcat(buf, type, PEM_BUFSIZE);
158
0
    BUF_strlcat(buf, ",", PEM_BUFSIZE);
159
0
    j = strlen(buf);
160
0
    if (j + (len * 2) + 1 > PEM_BUFSIZE)
161
0
        return;
162
0
    for (i = 0; i < len; i++) {
163
0
        buf[j + i * 2] = map[(str[i] >> 4) & 0x0f];
164
0
        buf[j + i * 2 + 1] = map[(str[i]) & 0x0f];
165
0
    }
166
0
    buf[j + i * 2] = '\n';
167
0
    buf[j + i * 2 + 1] = '\0';
168
0
}
169
170
#ifndef OPENSSL_NO_FP_API
171
void *PEM_ASN1_read(d2i_of_void *d2i, const char *name, FILE *fp, void **x,
172
                    pem_password_cb *cb, void *u)
173
0
{
174
0
    BIO *b;
175
0
    void *ret;
176
177
0
    if ((b = BIO_new(BIO_s_file())) == NULL) {
178
0
        PEMerr(PEM_F_PEM_ASN1_READ, ERR_R_BUF_LIB);
179
0
        return (0);
180
0
    }
181
0
    BIO_set_fp(b, fp, BIO_NOCLOSE);
182
0
    ret = PEM_ASN1_read_bio(d2i, name, b, x, cb, u);
183
0
    BIO_free(b);
184
0
    return (ret);
185
0
}
186
#endif
187
188
static int check_pem(const char *nm, const char *name)
189
0
{
190
    /* Normal matching nm and name */
191
0
    if (!strcmp(nm, name))
192
0
        return 1;
193
194
    /* Make PEM_STRING_EVP_PKEY match any private key */
195
196
0
    if (!strcmp(name, PEM_STRING_EVP_PKEY)) {
197
0
        int slen;
198
0
        const EVP_PKEY_ASN1_METHOD *ameth;
199
0
        if (!strcmp(nm, PEM_STRING_PKCS8))
200
0
            return 1;
201
0
        if (!strcmp(nm, PEM_STRING_PKCS8INF))
202
0
            return 1;
203
0
        slen = pem_check_suffix(nm, "PRIVATE KEY");
204
0
        if (slen > 0) {
205
            /*
206
             * NB: ENGINE implementations wont contain a deprecated old
207
             * private key decode function so don't look for them.
208
             */
209
0
            ameth = EVP_PKEY_asn1_find_str(NULL, nm, slen);
210
0
            if (ameth && ameth->old_priv_decode)
211
0
                return 1;
212
0
        }
213
0
        return 0;
214
0
    }
215
216
0
    if (!strcmp(name, PEM_STRING_PARAMETERS)) {
217
0
        int slen;
218
0
        const EVP_PKEY_ASN1_METHOD *ameth;
219
0
        slen = pem_check_suffix(nm, "PARAMETERS");
220
0
        if (slen > 0) {
221
0
            ENGINE *e;
222
0
            ameth = EVP_PKEY_asn1_find_str(&e, nm, slen);
223
0
            if (ameth) {
224
0
                int r;
225
0
                if (ameth->param_decode)
226
0
                    r = 1;
227
0
                else
228
0
                    r = 0;
229
0
#ifndef OPENSSL_NO_ENGINE
230
0
                if (e)
231
0
                    ENGINE_finish(e);
232
0
#endif
233
0
                return r;
234
0
            }
235
0
        }
236
0
        return 0;
237
0
    }
238
    /* If reading DH parameters handle X9.42 DH format too */
239
0
    if (!strcmp(nm, PEM_STRING_DHXPARAMS) &&
240
0
        !strcmp(name, PEM_STRING_DHPARAMS))
241
0
        return 1;
242
243
    /* Permit older strings */
244
245
0
    if (!strcmp(nm, PEM_STRING_X509_OLD) && !strcmp(name, PEM_STRING_X509))
246
0
        return 1;
247
248
0
    if (!strcmp(nm, PEM_STRING_X509_REQ_OLD) &&
249
0
        !strcmp(name, PEM_STRING_X509_REQ))
250
0
        return 1;
251
252
    /* Allow normal certs to be read as trusted certs */
253
0
    if (!strcmp(nm, PEM_STRING_X509) &&
254
0
        !strcmp(name, PEM_STRING_X509_TRUSTED))
255
0
        return 1;
256
257
0
    if (!strcmp(nm, PEM_STRING_X509_OLD) &&
258
0
        !strcmp(name, PEM_STRING_X509_TRUSTED))
259
0
        return 1;
260
261
    /* Some CAs use PKCS#7 with CERTIFICATE headers */
262
0
    if (!strcmp(nm, PEM_STRING_X509) && !strcmp(name, PEM_STRING_PKCS7))
263
0
        return 1;
264
265
0
    if (!strcmp(nm, PEM_STRING_PKCS7_SIGNED) &&
266
0
        !strcmp(name, PEM_STRING_PKCS7))
267
0
        return 1;
268
269
0
#ifndef OPENSSL_NO_CMS
270
0
    if (!strcmp(nm, PEM_STRING_X509) && !strcmp(name, PEM_STRING_CMS))
271
0
        return 1;
272
    /* Allow CMS to be read from PKCS#7 headers */
273
0
    if (!strcmp(nm, PEM_STRING_PKCS7) && !strcmp(name, PEM_STRING_CMS))
274
0
        return 1;
275
0
#endif
276
277
0
    return 0;
278
0
}
279
280
int PEM_bytes_read_bio(unsigned char **pdata, long *plen, char **pnm,
281
                       const char *name, BIO *bp, pem_password_cb *cb,
282
                       void *u)
283
1.24k
{
284
1.24k
    EVP_CIPHER_INFO cipher;
285
1.24k
    char *nm = NULL, *header = NULL;
286
1.24k
    unsigned char *data = NULL;
287
1.24k
    long len;
288
1.24k
    int ret = 0;
289
290
1.24k
    for (;;) {
291
1.24k
        if (!PEM_read_bio(bp, &nm, &header, &data, &len)) {
292
1.24k
            if (ERR_GET_REASON(ERR_peek_error()) == PEM_R_NO_START_LINE)
293
1.24k
                ERR_add_error_data(2, "Expecting: ", name);
294
1.24k
            return 0;
295
1.24k
        }
296
0
        if (check_pem(nm, name))
297
0
            break;
298
0
        OPENSSL_free(nm);
299
0
        OPENSSL_free(header);
300
0
        OPENSSL_free(data);
301
0
    }
302
0
    if (!PEM_get_EVP_CIPHER_INFO(header, &cipher))
303
0
        goto err;
304
0
    if (!PEM_do_header(&cipher, data, &len, cb, u))
305
0
        goto err;
306
307
0
    *pdata = data;
308
0
    *plen = len;
309
310
0
    if (pnm)
311
0
        *pnm = nm;
312
313
0
    ret = 1;
314
315
0
 err:
316
0
    if (!ret || !pnm)
317
0
        OPENSSL_free(nm);
318
0
    OPENSSL_free(header);
319
0
    if (!ret)
320
0
        OPENSSL_free(data);
321
0
    return ret;
322
0
}
323
324
#ifndef OPENSSL_NO_FP_API
325
int PEM_ASN1_write(i2d_of_void *i2d, const char *name, FILE *fp,
326
                   void *x, const EVP_CIPHER *enc, unsigned char *kstr,
327
                   int klen, pem_password_cb *callback, void *u)
328
0
{
329
0
    BIO *b;
330
0
    int ret;
331
332
0
    if ((b = BIO_new(BIO_s_file())) == NULL) {
333
0
        PEMerr(PEM_F_PEM_ASN1_WRITE, ERR_R_BUF_LIB);
334
0
        return (0);
335
0
    }
336
0
    BIO_set_fp(b, fp, BIO_NOCLOSE);
337
0
    ret = PEM_ASN1_write_bio(i2d, name, b, x, enc, kstr, klen, callback, u);
338
0
    BIO_free(b);
339
0
    return (ret);
340
0
}
341
#endif
342
343
int PEM_ASN1_write_bio(i2d_of_void *i2d, const char *name, BIO *bp,
344
                       void *x, const EVP_CIPHER *enc, unsigned char *kstr,
345
                       int klen, pem_password_cb *callback, void *u)
346
0
{
347
0
    EVP_CIPHER_CTX ctx;
348
0
    int dsize = 0, i, j, ret = 0;
349
0
    unsigned char *p, *data = NULL;
350
0
    const char *objstr = NULL;
351
0
    char buf[PEM_BUFSIZE];
352
0
    unsigned char key[EVP_MAX_KEY_LENGTH];
353
0
    unsigned char iv[EVP_MAX_IV_LENGTH];
354
355
0
    if (enc != NULL) {
356
0
        objstr = OBJ_nid2sn(EVP_CIPHER_nid(enc));
357
0
        if (objstr == NULL || EVP_CIPHER_iv_length(enc) == 0) {
358
0
            PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, PEM_R_UNSUPPORTED_CIPHER);
359
0
            goto err;
360
0
        }
361
0
    }
362
363
0
    if ((dsize = i2d(x, NULL)) < 0) {
364
0
        PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, ERR_R_ASN1_LIB);
365
0
        dsize = 0;
366
0
        goto err;
367
0
    }
368
    /* dzise + 8 bytes are needed */
369
    /* actually it needs the cipher block size extra... */
370
0
    data = (unsigned char *)OPENSSL_malloc((unsigned int)dsize + 20);
371
0
    if (data == NULL) {
372
0
        PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, ERR_R_MALLOC_FAILURE);
373
0
        goto err;
374
0
    }
375
0
    p = data;
376
0
    i = i2d(x, &p);
377
378
0
    if (enc != NULL) {
379
0
        if (kstr == NULL) {
380
0
            if (callback == NULL)
381
0
                klen = PEM_def_callback(buf, PEM_BUFSIZE, 1, u);
382
0
            else
383
0
                klen = (*callback) (buf, PEM_BUFSIZE, 1, u);
384
0
            if (klen <= 0) {
385
0
                PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, PEM_R_READ_KEY);
386
0
                goto err;
387
0
            }
388
#ifdef CHARSET_EBCDIC
389
            /* Convert the pass phrase from EBCDIC */
390
            ebcdic2ascii(buf, buf, klen);
391
#endif
392
0
            kstr = (unsigned char *)buf;
393
0
        }
394
0
        RAND_add(data, i, 0);   /* put in the RSA key. */
395
0
        OPENSSL_assert(enc->iv_len <= (int)sizeof(iv));
396
0
        if (RAND_bytes(iv, enc->iv_len) <= 0) /* Generate a salt */
397
0
            goto err;
398
        /*
399
         * The 'iv' is used as the iv and as a salt.  It is NOT taken from
400
         * the BytesToKey function
401
         */
402
0
        if (!EVP_BytesToKey(enc, EVP_md5(), iv, kstr, klen, 1, key, NULL))
403
0
            goto err;
404
405
0
        if (kstr == (unsigned char *)buf)
406
0
            OPENSSL_cleanse(buf, PEM_BUFSIZE);
407
408
0
        OPENSSL_assert(strlen(objstr) + 23 + 2 * enc->iv_len + 13 <=
409
0
                       sizeof buf);
410
411
0
        buf[0] = '\0';
412
0
        PEM_proc_type(buf, PEM_TYPE_ENCRYPTED);
413
0
        PEM_dek_info(buf, objstr, enc->iv_len, (char *)iv);
414
        /* k=strlen(buf); */
415
416
0
        EVP_CIPHER_CTX_init(&ctx);
417
0
        ret = 1;
418
0
        if (!EVP_EncryptInit_ex(&ctx, enc, NULL, key, iv)
419
0
            || !EVP_EncryptUpdate(&ctx, data, &j, data, i)
420
0
            || !EVP_EncryptFinal_ex(&ctx, &(data[j]), &i))
421
0
            ret = 0;
422
0
        EVP_CIPHER_CTX_cleanup(&ctx);
423
0
        if (ret == 0)
424
0
            goto err;
425
0
        i += j;
426
0
    } else {
427
0
        ret = 1;
428
0
        buf[0] = '\0';
429
0
    }
430
0
    i = PEM_write_bio(bp, name, buf, data, i);
431
0
    if (i <= 0)
432
0
        ret = 0;
433
0
 err:
434
0
    OPENSSL_cleanse(key, sizeof(key));
435
0
    OPENSSL_cleanse(iv, sizeof(iv));
436
0
    OPENSSL_cleanse((char *)&ctx, sizeof(ctx));
437
0
    OPENSSL_cleanse(buf, PEM_BUFSIZE);
438
0
    if (data != NULL) {
439
0
        OPENSSL_cleanse(data, (unsigned int)dsize);
440
0
        OPENSSL_free(data);
441
0
    }
442
0
    return (ret);
443
0
}
444
445
int PEM_do_header(EVP_CIPHER_INFO *cipher, unsigned char *data, long *plen,
446
                  pem_password_cb *callback, void *u)
447
157k
{
448
157k
    int i = 0, j, o, klen;
449
157k
    long len;
450
157k
    EVP_CIPHER_CTX ctx;
451
157k
    unsigned char key[EVP_MAX_KEY_LENGTH];
452
157k
    char buf[PEM_BUFSIZE];
453
454
157k
    len = *plen;
455
456
157k
    if (cipher->cipher == NULL)
457
157k
        return (1);
458
0
    if (callback == NULL)
459
0
        klen = PEM_def_callback(buf, PEM_BUFSIZE, 0, u);
460
0
    else
461
0
        klen = callback(buf, PEM_BUFSIZE, 0, u);
462
0
    if (klen <= 0) {
463
0
        PEMerr(PEM_F_PEM_DO_HEADER, PEM_R_BAD_PASSWORD_READ);
464
0
        return (0);
465
0
    }
466
#ifdef CHARSET_EBCDIC
467
    /* Convert the pass phrase from EBCDIC */
468
    ebcdic2ascii(buf, buf, klen);
469
#endif
470
471
0
    if (!EVP_BytesToKey(cipher->cipher, EVP_md5(), &(cipher->iv[0]),
472
0
                        (unsigned char *)buf, klen, 1, key, NULL))
473
0
        return 0;
474
475
0
    j = (int)len;
476
0
    EVP_CIPHER_CTX_init(&ctx);
477
0
    o = EVP_DecryptInit_ex(&ctx, cipher->cipher, NULL, key, &(cipher->iv[0]));
478
0
    if (o)
479
0
        o = EVP_DecryptUpdate(&ctx, data, &i, data, j);
480
0
    if (o)
481
0
        o = EVP_DecryptFinal_ex(&ctx, &(data[i]), &j);
482
0
    EVP_CIPHER_CTX_cleanup(&ctx);
483
0
    OPENSSL_cleanse((char *)buf, sizeof(buf));
484
0
    OPENSSL_cleanse((char *)key, sizeof(key));
485
0
    if (o)
486
0
        j += i;
487
0
    else {
488
0
        PEMerr(PEM_F_PEM_DO_HEADER, PEM_R_BAD_DECRYPT);
489
0
        return (0);
490
0
    }
491
0
    *plen = j;
492
0
    return (1);
493
0
}
494
495
int PEM_get_EVP_CIPHER_INFO(char *header, EVP_CIPHER_INFO *cipher)
496
157k
{
497
157k
    const EVP_CIPHER *enc = NULL;
498
157k
    char *p, c;
499
157k
    char **header_pp = &header;
500
501
157k
    cipher->cipher = NULL;
502
157k
    if ((header == NULL) || (*header == '\0') || (*header == '\n'))
503
157k
        return (1);
504
0
    if (strncmp(header, "Proc-Type: ", 11) != 0) {
505
0
        PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_NOT_PROC_TYPE);
506
0
        return (0);
507
0
    }
508
0
    header += 11;
509
0
    if (*header != '4')
510
0
        return (0);
511
0
    header++;
512
0
    if (*header != ',')
513
0
        return (0);
514
0
    header++;
515
0
    if (strncmp(header, "ENCRYPTED", 9) != 0) {
516
0
        PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_NOT_ENCRYPTED);
517
0
        return (0);
518
0
    }
519
0
    for (; (*header != '\n') && (*header != '\0'); header++) ;
520
0
    if (*header == '\0') {
521
0
        PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_SHORT_HEADER);
522
0
        return (0);
523
0
    }
524
0
    header++;
525
0
    if (strncmp(header, "DEK-Info: ", 10) != 0) {
526
0
        PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_NOT_DEK_INFO);
527
0
        return (0);
528
0
    }
529
0
    header += 10;
530
531
0
    p = header;
532
0
    for (;;) {
533
0
        c = *header;
534
0
#ifndef CHARSET_EBCDIC
535
0
        if (!(((c >= 'A') && (c <= 'Z')) || (c == '-') ||
536
0
              ((c >= '0') && (c <= '9'))))
537
0
            break;
538
#else
539
        if (!(isupper((unsigned char)c) || (c == '-')
540
            || isdigit((unsigned char)c)))
541
            break;
542
#endif
543
0
        header++;
544
0
    }
545
0
    *header = '\0';
546
0
    cipher->cipher = enc = EVP_get_cipherbyname(p);
547
0
    *header = c;
548
0
    header++;
549
550
0
    if (enc == NULL) {
551
0
        PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_UNSUPPORTED_ENCRYPTION);
552
0
        return (0);
553
0
    }
554
0
    if (!load_iv(header_pp, &(cipher->iv[0]), enc->iv_len))
555
0
        return (0);
556
557
0
    return (1);
558
0
}
559
560
static int load_iv(char **fromp, unsigned char *to, int num)
561
0
{
562
0
    int v, i;
563
0
    char *from;
564
565
0
    from = *fromp;
566
0
    for (i = 0; i < num; i++)
567
0
        to[i] = 0;
568
0
    num *= 2;
569
0
    for (i = 0; i < num; i++) {
570
0
        if ((*from >= '0') && (*from <= '9'))
571
0
            v = *from - '0';
572
0
        else if ((*from >= 'A') && (*from <= 'F'))
573
0
            v = *from - 'A' + 10;
574
0
        else if ((*from >= 'a') && (*from <= 'f'))
575
0
            v = *from - 'a' + 10;
576
0
        else {
577
0
            PEMerr(PEM_F_LOAD_IV, PEM_R_BAD_IV_CHARS);
578
0
            return (0);
579
0
        }
580
0
        from++;
581
0
        to[i / 2] |= v << (long)((!(i & 1)) * 4);
582
0
    }
583
584
0
    *fromp = from;
585
0
    return (1);
586
0
}
587
588
#ifndef OPENSSL_NO_FP_API
589
int PEM_write(FILE *fp, const char *name, const char *header,
590
              const unsigned char *data, long len)
591
0
{
592
0
    BIO *b;
593
0
    int ret;
594
595
0
    if ((b = BIO_new(BIO_s_file())) == NULL) {
596
0
        PEMerr(PEM_F_PEM_WRITE, ERR_R_BUF_LIB);
597
0
        return (0);
598
0
    }
599
0
    BIO_set_fp(b, fp, BIO_NOCLOSE);
600
0
    ret = PEM_write_bio(b, name, header, data, len);
601
0
    BIO_free(b);
602
0
    return (ret);
603
0
}
604
#endif
605
606
int PEM_write_bio(BIO *bp, const char *name, const char *header,
607
                  const unsigned char *data, long len)
608
0
{
609
0
    int nlen, n, i, j, outl;
610
0
    unsigned char *buf = NULL;
611
0
    EVP_ENCODE_CTX ctx;
612
0
    int reason = ERR_R_BUF_LIB;
613
614
0
    EVP_EncodeInit(&ctx);
615
0
    nlen = strlen(name);
616
617
0
    if ((BIO_write(bp, "-----BEGIN ", 11) != 11) ||
618
0
        (BIO_write(bp, name, nlen) != nlen) ||
619
0
        (BIO_write(bp, "-----\n", 6) != 6))
620
0
        goto err;
621
622
0
    i = strlen(header);
623
0
    if (i > 0) {
624
0
        if ((BIO_write(bp, header, i) != i) || (BIO_write(bp, "\n", 1) != 1))
625
0
            goto err;
626
0
    }
627
628
0
    buf = OPENSSL_malloc(PEM_BUFSIZE * 8);
629
0
    if (buf == NULL) {
630
0
        reason = ERR_R_MALLOC_FAILURE;
631
0
        goto err;
632
0
    }
633
634
0
    i = j = 0;
635
0
    while (len > 0) {
636
0
        n = (int)((len > (PEM_BUFSIZE * 5)) ? (PEM_BUFSIZE * 5) : len);
637
0
        EVP_EncodeUpdate(&ctx, buf, &outl, &(data[j]), n);
638
0
        if ((outl) && (BIO_write(bp, (char *)buf, outl) != outl))
639
0
            goto err;
640
0
        i += outl;
641
0
        len -= n;
642
0
        j += n;
643
0
    }
644
0
    EVP_EncodeFinal(&ctx, buf, &outl);
645
0
    if ((outl > 0) && (BIO_write(bp, (char *)buf, outl) != outl))
646
0
        goto err;
647
0
    OPENSSL_cleanse(buf, PEM_BUFSIZE * 8);
648
0
    OPENSSL_free(buf);
649
0
    buf = NULL;
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
    return (i + outl);
655
0
 err:
656
0
    if (buf) {
657
0
        OPENSSL_cleanse(buf, PEM_BUFSIZE * 8);
658
0
        OPENSSL_free(buf);
659
0
    }
660
0
    PEMerr(PEM_F_PEM_WRITE_BIO, reason);
661
0
    return (0);
662
0
}
663
664
#ifndef OPENSSL_NO_FP_API
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
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
int PEM_read_bio(BIO *bp, char **name, char **header, unsigned char **data,
683
                 long *len)
684
160k
{
685
160k
    EVP_ENCODE_CTX ctx;
686
160k
    int end = 0, i, k, bl = 0, hl = 0, nohead = 0;
687
160k
    char buf[256];
688
160k
    BUF_MEM *nameB;
689
160k
    BUF_MEM *headerB;
690
160k
    BUF_MEM *dataB, *tmpB;
691
692
160k
    nameB = BUF_MEM_new();
693
160k
    headerB = BUF_MEM_new();
694
160k
    dataB = BUF_MEM_new();
695
160k
    if ((nameB == NULL) || (headerB == NULL) || (dataB == NULL)) {
696
0
        BUF_MEM_free(nameB);
697
0
        BUF_MEM_free(headerB);
698
0
        BUF_MEM_free(dataB);
699
0
        PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
700
0
        return (0);
701
0
    }
702
703
160k
    buf[254] = '\0';
704
160k
    for (;;) {
705
160k
        i = BIO_gets(bp, buf, 254);
706
707
160k
        if (i <= 0) {
708
2.48k
            PEMerr(PEM_F_PEM_READ_BIO, PEM_R_NO_START_LINE);
709
2.48k
            goto err;
710
2.48k
        }
711
712
473k
        while ((i >= 0) && (buf[i] <= ' '))
713
315k
            i--;
714
157k
        buf[++i] = '\n';
715
157k
        buf[++i] = '\0';
716
717
157k
        if (strncmp(buf, "-----BEGIN ", 11) == 0) {
718
157k
            i = strlen(&(buf[11]));
719
720
157k
            if (strncmp(&(buf[11 + i - 6]), "-----\n", 6) != 0)
721
0
                continue;
722
157k
            if (!BUF_MEM_grow(nameB, i + 9)) {
723
0
                PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
724
0
                goto err;
725
0
            }
726
157k
            memcpy(nameB->data, &(buf[11]), i - 6);
727
157k
            nameB->data[i - 6] = '\0';
728
157k
            break;
729
157k
        }
730
157k
    }
731
157k
    hl = 0;
732
157k
    if (!BUF_MEM_grow(headerB, 256)) {
733
0
        PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
734
0
        goto err;
735
0
    }
736
157k
    headerB->data[0] = '\0';
737
3.83M
    for (;;) {
738
3.83M
        i = BIO_gets(bp, buf, 254);
739
3.83M
        if (i <= 0)
740
0
            break;
741
742
11.5M
        while ((i >= 0) && (buf[i] <= ' '))
743
7.67M
            i--;
744
3.83M
        buf[++i] = '\n';
745
3.83M
        buf[++i] = '\0';
746
747
3.83M
        if (buf[0] == '\n')
748
0
            break;
749
3.83M
        if (!BUF_MEM_grow(headerB, hl + i + 9)) {
750
0
            PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
751
0
            goto err;
752
0
        }
753
3.83M
        if (strncmp(buf, "-----END ", 9) == 0) {
754
157k
            nohead = 1;
755
157k
            break;
756
157k
        }
757
3.67M
        memcpy(&(headerB->data[hl]), buf, i);
758
3.67M
        headerB->data[hl + i] = '\0';
759
3.67M
        hl += i;
760
3.67M
    }
761
762
157k
    bl = 0;
763
157k
    if (!BUF_MEM_grow(dataB, 1024)) {
764
0
        PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
765
0
        goto err;
766
0
    }
767
157k
    dataB->data[0] = '\0';
768
157k
    if (!nohead) {
769
0
        for (;;) {
770
0
            i = BIO_gets(bp, buf, 254);
771
0
            if (i <= 0)
772
0
                break;
773
774
0
            while ((i >= 0) && (buf[i] <= ' '))
775
0
                i--;
776
0
            buf[++i] = '\n';
777
0
            buf[++i] = '\0';
778
779
0
            if (i != 65)
780
0
                end = 1;
781
0
            if (strncmp(buf, "-----END ", 9) == 0)
782
0
                break;
783
0
            if (i > 65)
784
0
                break;
785
0
            if (!BUF_MEM_grow_clean(dataB, i + bl + 9)) {
786
0
                PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
787
0
                goto err;
788
0
            }
789
0
            memcpy(&(dataB->data[bl]), buf, i);
790
0
            dataB->data[bl + i] = '\0';
791
0
            bl += i;
792
0
            if (end) {
793
0
                buf[0] = '\0';
794
0
                i = BIO_gets(bp, buf, 254);
795
0
                if (i <= 0)
796
0
                    break;
797
798
0
                while ((i >= 0) && (buf[i] <= ' '))
799
0
                    i--;
800
0
                buf[++i] = '\n';
801
0
                buf[++i] = '\0';
802
803
0
                break;
804
0
            }
805
0
        }
806
157k
    } else {
807
157k
        tmpB = headerB;
808
157k
        headerB = dataB;
809
157k
        dataB = tmpB;
810
157k
        bl = hl;
811
157k
    }
812
157k
    i = strlen(nameB->data);
813
157k
    if ((strncmp(buf, "-----END ", 9) != 0) ||
814
157k
        (strncmp(nameB->data, &(buf[9]), i) != 0) ||
815
157k
        (strncmp(&(buf[9 + i]), "-----\n", 6) != 0)) {
816
0
        PEMerr(PEM_F_PEM_READ_BIO, PEM_R_BAD_END_LINE);
817
0
        goto err;
818
0
    }
819
820
157k
    EVP_DecodeInit(&ctx);
821
157k
    i = EVP_DecodeUpdate(&ctx,
822
157k
                         (unsigned char *)dataB->data, &bl,
823
157k
                         (unsigned char *)dataB->data, bl);
824
157k
    if (i < 0) {
825
0
        PEMerr(PEM_F_PEM_READ_BIO, PEM_R_BAD_BASE64_DECODE);
826
0
        goto err;
827
0
    }
828
157k
    i = EVP_DecodeFinal(&ctx, (unsigned char *)&(dataB->data[bl]), &k);
829
157k
    if (i < 0) {
830
0
        PEMerr(PEM_F_PEM_READ_BIO, PEM_R_BAD_BASE64_DECODE);
831
0
        goto err;
832
0
    }
833
157k
    bl += k;
834
835
157k
    if (bl == 0)
836
0
        goto err;
837
157k
    *name = nameB->data;
838
157k
    *header = headerB->data;
839
157k
    *data = (unsigned char *)dataB->data;
840
157k
    *len = bl;
841
157k
    OPENSSL_free(nameB);
842
157k
    OPENSSL_free(headerB);
843
157k
    OPENSSL_free(dataB);
844
157k
    return (1);
845
2.48k
 err:
846
2.48k
    BUF_MEM_free(nameB);
847
2.48k
    BUF_MEM_free(headerB);
848
2.48k
    BUF_MEM_free(dataB);
849
2.48k
    return (0);
850
157k
}
851
852
/*
853
 * Check pem string and return prefix length. If for example the pem_str ==
854
 * "RSA PRIVATE KEY" and suffix = "PRIVATE KEY" the return value is 3 for the
855
 * string "RSA".
856
 */
857
858
int pem_check_suffix(const char *pem_str, const char *suffix)
859
0
{
860
0
    int pem_len = strlen(pem_str);
861
0
    int suffix_len = strlen(suffix);
862
0
    const char *p;
863
0
    if (suffix_len + 1 >= pem_len)
864
0
        return 0;
865
0
    p = pem_str + pem_len - suffix_len;
866
0
    if (strcmp(p, suffix))
867
0
        return 0;
868
0
    p--;
869
0
    if (*p != ' ')
870
0
        return 0;
871
0
    return p - pem_str;
872
0
}