GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: lib/libcrypto/crypto/../../libssl/src/crypto/pem/pem_lib.c Lines: 173 458 37.8 %
Date: 2016-12-06 Branches: 78 290 26.9 %

Line Branch Exec Source
1
/* $OpenBSD: pem_lib.c,v 1.42 2015/09/10 15:56:25 jsing Exp $ */
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 <ctype.h>
60
#include <stdio.h>
61
#include <stdlib.h>
62
#include <string.h>
63
64
#include <openssl/opensslconf.h>
65
66
#include <openssl/buffer.h>
67
#include <openssl/err.h>
68
#include <openssl/evp.h>
69
#include <openssl/objects.h>
70
#include <openssl/pem.h>
71
#include <openssl/pkcs12.h>
72
#include <openssl/x509.h>
73
74
#ifndef OPENSSL_NO_DES
75
#include <openssl/des.h>
76
#endif
77
#ifndef OPENSSL_NO_ENGINE
78
#include <openssl/engine.h>
79
#endif
80
81
#include "asn1_locl.h"
82
83
#define MIN_LENGTH	4
84
85
static int load_iv(char **fromp, unsigned char *to, int num);
86
static int check_pem(const char *nm, const char *name);
87
int pem_check_suffix(const char *pem_str, const char *suffix);
88
89
/* XXX LSSL ABI XXX return value and `num' ought to be size_t */
90
int
91
PEM_def_callback(char *buf, int num, int w, void *key)
92
{
93
	size_t l;
94
	int i;
95
	const char *prompt;
96
97
	if (num < 0)
98
		return -1;
99
100
	if (key) {
101
		l = strlen(key);
102
		if (l > (size_t)num)
103
			l = (size_t)num;
104
		memcpy(buf, key, l);
105
		return (int)l;
106
	}
107
108
	prompt = EVP_get_pw_prompt();
109
	if (prompt == NULL)
110
		prompt = "Enter PEM pass phrase:";
111
112
	for (;;) {
113
		i = EVP_read_pw_string_min(buf, MIN_LENGTH, num, prompt, w);
114
		if (i != 0) {
115
			PEMerr(PEM_F_PEM_DEF_CALLBACK,
116
			    PEM_R_PROBLEMS_GETTING_PASSWORD);
117
			memset(buf, 0, num);
118
			return (-1);
119
		}
120
		l = strlen(buf);
121
		if (l < MIN_LENGTH) {
122
			fprintf(stderr, "phrase is too short, "
123
			    "needs to be at least %zu chars\n",
124
			    (size_t)MIN_LENGTH);
125
		} else
126
			break;
127
	}
128
	return (int)l;
129
}
130
131
void
132
PEM_proc_type(char *buf, int type)
133
{
134
	const char *str;
135
136
	if (type == PEM_TYPE_ENCRYPTED)
137
		str = "ENCRYPTED";
138
	else if (type == PEM_TYPE_MIC_CLEAR)
139
		str = "MIC-CLEAR";
140
	else if (type == PEM_TYPE_MIC_ONLY)
141
		str = "MIC-ONLY";
142
	else
143
		str = "BAD-TYPE";
144
145
	strlcat(buf, "Proc-Type: 4,", PEM_BUFSIZE);
146
	strlcat(buf, str, PEM_BUFSIZE);
147
	strlcat(buf, "\n", PEM_BUFSIZE);
148
}
149
150
void
151
PEM_dek_info(char *buf, const char *type, int len, char *str)
152
{
153
	static const unsigned char map[17] = "0123456789ABCDEF";
154
	long i;
155
	int j;
156
157
	strlcat(buf, "DEK-Info: ", PEM_BUFSIZE);
158
	strlcat(buf, type, PEM_BUFSIZE);
159
	strlcat(buf, ",", PEM_BUFSIZE);
160
	j = strlen(buf);
161
	if (j + (len * 2) + 1 > PEM_BUFSIZE)
162
		return;
163
	for (i = 0; i < len; i++) {
164
		buf[j + i * 2] = map[(str[i] >> 4) & 0x0f];
165
		buf[j + i * 2 + 1] = map[(str[i]) & 0x0f];
166
	}
167
	buf[j + i * 2] = '\n';
168
	buf[j + i * 2 + 1] = '\0';
169
}
170
171
void *
172
PEM_ASN1_read(d2i_of_void *d2i, const char *name, FILE *fp, void **x,
173
    pem_password_cb *cb, void *u)
174
{
175
	BIO *b;
176
	void *ret;
177
178
	if ((b = BIO_new(BIO_s_file())) == NULL) {
179
		PEMerr(PEM_F_PEM_ASN1_READ, ERR_R_BUF_LIB);
180
		return (0);
181
	}
182
	BIO_set_fp(b, fp, BIO_NOCLOSE);
183
	ret = PEM_ASN1_read_bio(d2i, name, b, x, cb, u);
184
	BIO_free(b);
185
	return (ret);
186
}
187
188
static int
189
check_pem(const char *nm, const char *name)
190
5
{
191
	/* Normal matching nm and name */
192
5
	if (!strcmp(nm, name))
193
3
		return 1;
194
195
	/* Make PEM_STRING_EVP_PKEY match any private key */
196
197
2
	if (!strcmp(name, PEM_STRING_EVP_PKEY)) {
198
		int slen;
199
		const EVP_PKEY_ASN1_METHOD *ameth;
200
1
		if (!strcmp(nm, PEM_STRING_PKCS8))
201
			return 1;
202
1
		if (!strcmp(nm, PEM_STRING_PKCS8INF))
203
			return 1;
204
1
		slen = pem_check_suffix(nm, "PRIVATE KEY");
205
1
		if (slen > 0) {
206
			/* NB: ENGINE implementations wont contain
207
			 * a deprecated old private key decode function
208
			 * so don't look for them.
209
			 */
210
1
			ameth = EVP_PKEY_asn1_find_str(NULL, nm, slen);
211

1
			if (ameth && ameth->old_priv_decode)
212
1
				return 1;
213
		}
214
		return 0;
215
	}
216
217
1
	if (!strcmp(name, PEM_STRING_PARAMETERS)) {
218
		int slen;
219
		const EVP_PKEY_ASN1_METHOD *ameth;
220
		slen = pem_check_suffix(nm, "PARAMETERS");
221
		if (slen > 0) {
222
			ENGINE *e;
223
			ameth = EVP_PKEY_asn1_find_str(&e, nm, slen);
224
			if (ameth) {
225
				int r;
226
				if (ameth->param_decode)
227
					r = 1;
228
				else
229
					r = 0;
230
#ifndef OPENSSL_NO_ENGINE
231
				if (e)
232
					ENGINE_finish(e);
233
#endif
234
				return r;
235
			}
236
		}
237
		return 0;
238
	}
239
240
	/* Permit older strings */
241
242

1
	if (!strcmp(nm, PEM_STRING_X509_OLD) &&
243
	    !strcmp(name, PEM_STRING_X509))
244
		return 1;
245
246

1
	if (!strcmp(nm, PEM_STRING_X509_REQ_OLD) &&
247
	    !strcmp(name, PEM_STRING_X509_REQ))
248
		return 1;
249
250
	/* Allow normal certs to be read as trusted certs */
251

1
	if (!strcmp(nm, PEM_STRING_X509) &&
252
	    !strcmp(name, PEM_STRING_X509_TRUSTED))
253
1
		return 1;
254
255
	if (!strcmp(nm, PEM_STRING_X509_OLD) &&
256
	    !strcmp(name, PEM_STRING_X509_TRUSTED))
257
		return 1;
258
259
	/* Some CAs use PKCS#7 with CERTIFICATE headers */
260
	if (!strcmp(nm, PEM_STRING_X509) &&
261
	    !strcmp(name, PEM_STRING_PKCS7))
262
		return 1;
263
264
	if (!strcmp(nm, PEM_STRING_PKCS7_SIGNED) &&
265
	    !strcmp(name, PEM_STRING_PKCS7))
266
		return 1;
267
268
#ifndef OPENSSL_NO_CMS
269
	if (!strcmp(nm, PEM_STRING_X509) &&
270
	    !strcmp(name, PEM_STRING_CMS))
271
		return 1;
272
	/* Allow CMS to be read from PKCS#7 headers */
273
	if (!strcmp(nm, PEM_STRING_PKCS7) &&
274
	    !strcmp(name, PEM_STRING_CMS))
275
		return 1;
276
#endif
277
278
	return 0;
279
}
280
281
int
282
PEM_bytes_read_bio(unsigned char **pdata, long *plen, char **pnm,
283
    const char *name, BIO *bp, pem_password_cb *cb, void *u)
284
5
{
285
	EVP_CIPHER_INFO cipher;
286
5
	char *nm = NULL, *header = NULL;
287
5
	unsigned char *data = NULL;
288
	long len;
289
5
	int ret = 0;
290
291
	for (;;) {
292
5
		if (!PEM_read_bio(bp, &nm, &header, &data, &len)) {
293
			if (ERR_GET_REASON(ERR_peek_error()) ==
294
			    PEM_R_NO_START_LINE)
295
				ERR_asprintf_error_data("Expecting: %s", name);
296
			return 0;
297
		}
298
5
		if (check_pem(nm, name))
299
5
			break;
300
		free(nm);
301
		free(header);
302
		free(data);
303
	}
304
5
	if (!PEM_get_EVP_CIPHER_INFO(header, &cipher))
305
		goto err;
306
5
	if (!PEM_do_header(&cipher, data, &len, cb, u))
307
		goto err;
308
309
5
	*pdata = data;
310
5
	*plen = len;
311
312
5
	if (pnm)
313
1
		*pnm = nm;
314
315
5
	ret = 1;
316
317
5
err:
318
5
	if (!ret || !pnm)
319
4
		free(nm);
320
5
	free(header);
321
5
	if (!ret)
322
		free(data);
323
5
	return ret;
324
}
325
326
int
327
PEM_ASN1_write(i2d_of_void *i2d, const char *name, FILE *fp, void *x,
328
    const EVP_CIPHER *enc, unsigned char *kstr, int klen,
329
    pem_password_cb *callback, void *u)
330
{
331
	BIO *b;
332
	int ret;
333
334
	if ((b = BIO_new(BIO_s_file())) == NULL) {
335
		PEMerr(PEM_F_PEM_ASN1_WRITE, ERR_R_BUF_LIB);
336
		return (0);
337
	}
338
	BIO_set_fp(b, fp, BIO_NOCLOSE);
339
	ret = PEM_ASN1_write_bio(i2d, name, b, x, enc, kstr, klen, callback, u);
340
	BIO_free(b);
341
	return (ret);
342
}
343
344
int
345
PEM_ASN1_write_bio(i2d_of_void *i2d, const char *name, BIO *bp, void *x,
346
    const EVP_CIPHER *enc, unsigned char *kstr, int klen,
347
    pem_password_cb *callback, void *u)
348
3
{
349
	EVP_CIPHER_CTX ctx;
350
3
	int dsize = 0, i, j, ret = 0;
351
3
	unsigned char *p, *data = NULL;
352
3
	const char *objstr = NULL;
353
	char buf[PEM_BUFSIZE];
354
	unsigned char key[EVP_MAX_KEY_LENGTH];
355
	unsigned char iv[EVP_MAX_IV_LENGTH];
356
357
3
	if (enc != NULL) {
358
		objstr = OBJ_nid2sn(EVP_CIPHER_nid(enc));
359
		if (objstr == NULL) {
360
			PEMerr(PEM_F_PEM_ASN1_WRITE_BIO,
361
			    PEM_R_UNSUPPORTED_CIPHER);
362
			goto err;
363
		}
364
	}
365
366
3
	if ((dsize = i2d(x, NULL)) < 0) {
367
		PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, ERR_R_ASN1_LIB);
368
		dsize = 0;
369
		goto err;
370
	}
371
	/* dzise + 8 bytes are needed */
372
	/* actually it needs the cipher block size extra... */
373
3
	data = malloc(dsize + 20);
374
3
	if (data == NULL) {
375
		PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, ERR_R_MALLOC_FAILURE);
376
		goto err;
377
	}
378
3
	p = data;
379
3
	i = i2d(x, &p);
380
381
3
	if (enc != NULL) {
382
		if (kstr == NULL) {
383
			if (callback == NULL)
384
				klen = PEM_def_callback(buf, PEM_BUFSIZE, 1, u);
385
			else
386
				klen = (*callback)(buf, PEM_BUFSIZE, 1, u);
387
			if (klen <= 0) {
388
				PEMerr(PEM_F_PEM_ASN1_WRITE_BIO,
389
				    PEM_R_READ_KEY);
390
				goto err;
391
			}
392
			kstr = (unsigned char *)buf;
393
		}
394
		if ((size_t)enc->iv_len > sizeof(iv)) {
395
			PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, EVP_R_IV_TOO_LARGE);
396
			goto err;
397
		}
398
		arc4random_buf(iv, enc->iv_len); /* Generate a salt */
399
		/* The 'iv' is used as the iv and as a salt.  It is
400
		 * NOT taken from the BytesToKey function */
401
		if (!EVP_BytesToKey(enc, EVP_md5(), iv, kstr, klen, 1,
402
		    key, NULL))
403
			goto err;
404
405
		if (kstr == (unsigned char *)buf)
406
			explicit_bzero(buf, PEM_BUFSIZE);
407
408
		if (strlen(objstr) + 23 + 2 * enc->iv_len + 13 > sizeof buf) {
409
			PEMerr(PEM_F_PEM_ASN1_WRITE_BIO,
410
			    ASN1_R_BUFFER_TOO_SMALL);
411
			goto err;
412
		}
413
414
		buf[0] = '\0';
415
		PEM_proc_type(buf, PEM_TYPE_ENCRYPTED);
416
		PEM_dek_info(buf, objstr, enc->iv_len, (char *)iv);
417
		/* k=strlen(buf); */
418
419
		EVP_CIPHER_CTX_init(&ctx);
420
		ret = 1;
421
		if (!EVP_EncryptInit_ex(&ctx, enc, NULL, key, iv) ||
422
		    !EVP_EncryptUpdate(&ctx, data, &j, data, i) ||
423
		    !EVP_EncryptFinal_ex(&ctx, &(data[j]), &i))
424
			ret = 0;
425
		EVP_CIPHER_CTX_cleanup(&ctx);
426
		if (ret == 0)
427
			goto err;
428
		i += j;
429
	} else {
430
3
		ret = 1;
431
3
		buf[0] = '\0';
432
	}
433
3
	i = PEM_write_bio(bp, name, buf, data, i);
434
3
	if (i <= 0)
435
		ret = 0;
436
3
err:
437
3
	explicit_bzero(key, sizeof(key));
438
3
	explicit_bzero(iv, sizeof(iv));
439
3
	explicit_bzero((char *)&ctx, sizeof(ctx));
440
3
	explicit_bzero(buf, PEM_BUFSIZE);
441
3
	if (data != NULL) {
442
3
		explicit_bzero(data, (unsigned int)dsize);
443
3
		free(data);
444
	}
445
3
	return (ret);
446
}
447
448
int
449
PEM_do_header(EVP_CIPHER_INFO *cipher, unsigned char *data, long *plen,
450
    pem_password_cb *callback, void *u)
451
157
{
452
	int i, j, o, klen;
453
	long len;
454
	EVP_CIPHER_CTX ctx;
455
	unsigned char key[EVP_MAX_KEY_LENGTH];
456
	char buf[PEM_BUFSIZE];
457
458
157
	len = *plen;
459
460
157
	if (cipher->cipher == NULL)
461
157
		return (1);
462
	if (callback == NULL)
463
		klen = PEM_def_callback(buf, PEM_BUFSIZE, 0, u);
464
	else
465
		klen = callback(buf, PEM_BUFSIZE, 0, u);
466
	if (klen <= 0) {
467
		PEMerr(PEM_F_PEM_DO_HEADER, PEM_R_BAD_PASSWORD_READ);
468
		return (0);
469
	}
470
	if (!EVP_BytesToKey(cipher->cipher, EVP_md5(), &(cipher->iv[0]),
471
	    (unsigned char *)buf, klen, 1, key, NULL))
472
		return 0;
473
474
	j = (int)len;
475
	EVP_CIPHER_CTX_init(&ctx);
476
	o = EVP_DecryptInit_ex(&ctx, cipher->cipher, NULL, key,
477
	    &(cipher->iv[0]));
478
	if (o)
479
		o = EVP_DecryptUpdate(&ctx, data, &i, data, j);
480
	if (o)
481
		o = EVP_DecryptFinal_ex(&ctx, &(data[i]), &j);
482
	EVP_CIPHER_CTX_cleanup(&ctx);
483
	explicit_bzero((char *)buf, sizeof(buf));
484
	explicit_bzero((char *)key, sizeof(key));
485
	if (!o) {
486
		PEMerr(PEM_F_PEM_DO_HEADER, PEM_R_BAD_DECRYPT);
487
		return (0);
488
	}
489
	*plen = j + i;
490
	return (1);
491
}
492
493
int
494
PEM_get_EVP_CIPHER_INFO(char *header, EVP_CIPHER_INFO *cipher)
495
157
{
496
157
	const EVP_CIPHER *enc = NULL;
497
	char *p, c;
498
157
	char **header_pp = &header;
499
500
157
	cipher->cipher = NULL;
501

157
	if ((header == NULL) || (*header == '\0') || (*header == '\n'))
502
157
		return (1);
503
	if (strncmp(header, "Proc-Type: ", 11) != 0) {
504
		PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_NOT_PROC_TYPE);
505
		return (0);
506
	}
507
	header += 11;
508
	if (*header != '4')
509
		return (0);
510
	header++;
511
	if (*header != ',')
512
		return (0);
513
	header++;
514
	if (strncmp(header, "ENCRYPTED", 9) != 0) {
515
		PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_NOT_ENCRYPTED);
516
		return (0);
517
	}
518
	for (; (*header != '\n') && (*header != '\0'); header++)
519
		;
520
	if (*header == '\0') {
521
		PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_SHORT_HEADER);
522
		return (0);
523
	}
524
	header++;
525
	if (strncmp(header, "DEK-Info: ", 10) != 0) {
526
		PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_NOT_DEK_INFO);
527
		return (0);
528
	}
529
	header += 10;
530
531
	p = header;
532
	for (;;) {
533
		c= *header;
534
		if (!(	((c >= 'A') && (c <= 'Z')) || (c == '-') ||
535
		    ((c >= '0') && (c <= '9'))))
536
			break;
537
		header++;
538
	}
539
	*header = '\0';
540
	cipher->cipher = enc = EVP_get_cipherbyname(p);
541
	*header = c;
542
	header++;
543
544
	if (enc == NULL) {
545
		PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO,
546
		    PEM_R_UNSUPPORTED_ENCRYPTION);
547
		return (0);
548
	}
549
	if (!load_iv(header_pp, &(cipher->iv[0]), enc->iv_len))
550
		return (0);
551
552
	return (1);
553
}
554
555
static int
556
load_iv(char **fromp, unsigned char *to, int num)
557
{
558
	int v, i;
559
	char *from;
560
561
	from= *fromp;
562
	for (i = 0; i < num; i++)
563
		to[i] = 0;
564
	num *= 2;
565
	for (i = 0; i < num; i++) {
566
		if ((*from >= '0') && (*from <= '9'))
567
			v = *from - '0';
568
		else if ((*from >= 'A') && (*from <= 'F'))
569
			v = *from - 'A' + 10;
570
		else if ((*from >= 'a') && (*from <= 'f'))
571
			v = *from - 'a' + 10;
572
		else {
573
			PEMerr(PEM_F_LOAD_IV, PEM_R_BAD_IV_CHARS);
574
			return (0);
575
		}
576
		from++;
577
		to[i / 2] |= v << (long)((!(i & 1)) * 4);
578
	}
579
580
	*fromp = from;
581
	return (1);
582
}
583
584
int
585
PEM_write(FILE *fp, char *name, char *header, unsigned char *data, long len)
586
{
587
	BIO *b;
588
	int ret;
589
590
	if ((b = BIO_new(BIO_s_file())) == NULL) {
591
		PEMerr(PEM_F_PEM_WRITE, ERR_R_BUF_LIB);
592
		return (0);
593
	}
594
	BIO_set_fp(b, fp, BIO_NOCLOSE);
595
	ret = PEM_write_bio(b, name, header, data, len);
596
	BIO_free(b);
597
	return (ret);
598
}
599
600
int
601
PEM_write_bio(BIO *bp, const char *name, char *header, unsigned char *data,
602
    long len)
603
3
{
604
	int nlen, n, i, j, outl;
605
3
	unsigned char *buf = NULL;
606
	EVP_ENCODE_CTX ctx;
607
3
	int reason = ERR_R_BUF_LIB;
608
609
3
	EVP_EncodeInit(&ctx);
610
3
	nlen = strlen(name);
611
612

3
	if ((BIO_write(bp, "-----BEGIN ", 11) != 11) ||
613
	    (BIO_write(bp, name, nlen) != nlen) ||
614
	    (BIO_write(bp, "-----\n", 6) != 6))
615
		goto err;
616
617
3
	i = strlen(header);
618
3
	if (i > 0) {
619
		if ((BIO_write(bp, header, i) != i) ||
620
		    (BIO_write(bp, "\n", 1) != 1))
621
			goto err;
622
	}
623
624
3
	buf = reallocarray(NULL, PEM_BUFSIZE, 8);
625
3
	if (buf == NULL) {
626
		reason = ERR_R_MALLOC_FAILURE;
627
		goto err;
628
	}
629
630
3
	i = j = 0;
631
9
	while (len > 0) {
632
3
		n = (int)((len > (PEM_BUFSIZE * 5)) ? (PEM_BUFSIZE * 5) : len);
633
3
		EVP_EncodeUpdate(&ctx, buf, &outl, &(data[j]), n);
634

3
		if ((outl) && (BIO_write(bp, (char *)buf, outl) != outl))
635
			goto err;
636
3
		i += outl;
637
3
		len -= n;
638
3
		j += n;
639
	}
640
3
	EVP_EncodeFinal(&ctx, buf, &outl);
641

3
	if ((outl > 0) && (BIO_write(bp, (char *)buf, outl) != outl))
642
		goto err;
643
3
	explicit_bzero(buf, PEM_BUFSIZE * 8);
644
3
	free(buf);
645
3
	buf = NULL;
646

3
	if ((BIO_write(bp, "-----END ", 9) != 9) ||
647
	    (BIO_write(bp, name, nlen) != nlen) ||
648
	    (BIO_write(bp, "-----\n", 6) != 6))
649
		goto err;
650
3
	return (i + outl);
651
652
err:
653
	if (buf) {
654
		explicit_bzero(buf, PEM_BUFSIZE * 8);
655
		free(buf);
656
	}
657
	PEMerr(PEM_F_PEM_WRITE_BIO, reason);
658
	return (0);
659
}
660
661
int
662
PEM_read(FILE *fp, char **name, char **header, unsigned char **data, long *len)
663
{
664
	BIO *b;
665
	int ret;
666
667
	if ((b = BIO_new(BIO_s_file())) == NULL) {
668
		PEMerr(PEM_F_PEM_READ, ERR_R_BUF_LIB);
669
		return (0);
670
	}
671
	BIO_set_fp(b, fp, BIO_NOCLOSE);
672
	ret = PEM_read_bio(b, name, header, data, len);
673
	BIO_free(b);
674
	return (ret);
675
}
676
677
int
678
PEM_read_bio(BIO *bp, char **name, char **header, unsigned char **data,
679
    long *len)
680
159
{
681
	EVP_ENCODE_CTX ctx;
682
159
	int end = 0, i, k, bl = 0, hl = 0, nohead = 0;
683
	char buf[256];
684
	BUF_MEM *nameB;
685
	BUF_MEM *headerB;
686
	BUF_MEM *dataB, *tmpB;
687
688
159
	nameB = BUF_MEM_new();
689
159
	headerB = BUF_MEM_new();
690
159
	dataB = BUF_MEM_new();
691

159
	if ((nameB == NULL) || (headerB == NULL) || (dataB == NULL)) {
692
		BUF_MEM_free(nameB);
693
		BUF_MEM_free(headerB);
694
		BUF_MEM_free(dataB);
695
		PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
696
		return (0);
697
	}
698
699
159
	buf[254] = '\0';
700
	for (;;) {
701
3629
		i = BIO_gets(bp, buf, 254);
702
703
3629
		if (i <= 0) {
704
2
			PEMerr(PEM_F_PEM_READ_BIO, PEM_R_NO_START_LINE);
705
2
			goto err;
706
		}
707
708

11165
		while ((i >= 0) && (buf[i] <= ' '))
709
7538
			i--;
710
3627
		buf[++i] = '\n';
711
3627
		buf[++i] = '\0';
712
713
3627
		if (strncmp(buf, "-----BEGIN ", 11) == 0) {
714
157
			i = strlen(&(buf[11]));
715
716
157
			if (strncmp(&(buf[11 + i - 6]), "-----\n", 6) != 0)
717
				continue;
718
157
			if (!BUF_MEM_grow(nameB, i + 9)) {
719
				PEMerr(PEM_F_PEM_READ_BIO,
720
				    ERR_R_MALLOC_FAILURE);
721
				goto err;
722
			}
723
157
			memcpy(nameB->data, &(buf[11]), i - 6);
724
157
			nameB->data[i - 6] = '\0';
725
			break;
726
		}
727
	}
728
157
	hl = 0;
729
157
	if (!BUF_MEM_grow(headerB, 256)) {
730
		PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
731
		goto err;
732
	}
733
157
	headerB->data[0] = '\0';
734
	for (;;) {
735
3710
		i = BIO_gets(bp, buf, 254);
736
3710
		if (i <= 0)
737
			break;
738
739

11177
		while ((i >= 0) && (buf[i] <= ' '))
740
7467
			i--;
741
3710
		buf[++i] = '\n';
742
3710
		buf[++i] = '\0';
743
744
3710
		if (buf[0] == '\n')
745
			break;
746
3710
		if (!BUF_MEM_grow(headerB, hl + i + 9)) {
747
			PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
748
			goto err;
749
		}
750
3710
		if (strncmp(buf, "-----END ", 9) == 0) {
751
157
			nohead = 1;
752
157
			break;
753
		}
754
3553
		memcpy(&(headerB->data[hl]), buf, i);
755
3553
		headerB->data[hl + i] = '\0';
756
3553
		hl += i;
757
3553
	}
758
759
157
	bl = 0;
760
157
	if (!BUF_MEM_grow(dataB, 1024)) {
761
		PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
762
		goto err;
763
	}
764
157
	dataB->data[0] = '\0';
765
157
	if (!nohead) {
766
		for (;;) {
767
			i = BIO_gets(bp, buf, 254);
768
			if (i <= 0)
769
				break;
770
771
			while ((i >= 0) && (buf[i] <= ' '))
772
				i--;
773
			buf[++i] = '\n';
774
			buf[++i] = '\0';
775
776
			if (i != 65)
777
				end = 1;
778
			if (strncmp(buf, "-----END ", 9) == 0)
779
				break;
780
			if (i > 65)
781
				break;
782
			if (!BUF_MEM_grow_clean(dataB, i + bl + 9)) {
783
				PEMerr(PEM_F_PEM_READ_BIO,
784
				    ERR_R_MALLOC_FAILURE);
785
				goto err;
786
			}
787
			memcpy(&(dataB->data[bl]), buf, i);
788
			dataB->data[bl + i] = '\0';
789
			bl += i;
790
			if (end) {
791
				buf[0] = '\0';
792
				i = BIO_gets(bp, buf, 254);
793
				if (i <= 0)
794
					break;
795
796
				while ((i >= 0) && (buf[i] <= ' '))
797
					i--;
798
				buf[++i] = '\n';
799
				buf[++i] = '\0';
800
801
				break;
802
			}
803
		}
804
	} else {
805
157
		tmpB = headerB;
806
157
		headerB = dataB;
807
157
		dataB = tmpB;
808
157
		bl = hl;
809
	}
810
157
	i = strlen(nameB->data);
811

157
	if ((strncmp(buf, "-----END ", 9) != 0) ||
812
	    (strncmp(nameB->data, &(buf[9]), i) != 0) ||
813
	    (strncmp(&(buf[9 + i]), "-----\n", 6) != 0)) {
814
		PEMerr(PEM_F_PEM_READ_BIO, PEM_R_BAD_END_LINE);
815
		goto err;
816
	}
817
818
157
	EVP_DecodeInit(&ctx);
819
157
	i = EVP_DecodeUpdate(&ctx,
820
	    (unsigned char *)dataB->data, &bl,
821
	    (unsigned char *)dataB->data, bl);
822
157
	if (i < 0) {
823
		PEMerr(PEM_F_PEM_READ_BIO, PEM_R_BAD_BASE64_DECODE);
824
		goto err;
825
	}
826
157
	i = EVP_DecodeFinal(&ctx, (unsigned char *)&(dataB->data[bl]), &k);
827
157
	if (i < 0) {
828
		PEMerr(PEM_F_PEM_READ_BIO, PEM_R_BAD_BASE64_DECODE);
829
		goto err;
830
	}
831
157
	bl += k;
832
833
157
	if (bl == 0)
834
		goto err;
835
157
	*name = nameB->data;
836
157
	*header = headerB->data;
837
157
	*data = (unsigned char *)dataB->data;
838
157
	*len = bl;
839
157
	free(nameB);
840
157
	free(headerB);
841
157
	free(dataB);
842
157
	return (1);
843
844
2
err:
845
2
	BUF_MEM_free(nameB);
846
2
	BUF_MEM_free(headerB);
847
2
	BUF_MEM_free(dataB);
848
2
	return (0);
849
}
850
851
/* Check pem string and return prefix length.
852
 * If for example the pem_str == "RSA PRIVATE KEY" and suffix = "PRIVATE KEY"
853
 * the return value is 3 for the string "RSA".
854
 */
855
856
int
857
pem_check_suffix(const char *pem_str, const char *suffix)
858
2
{
859
2
	int pem_len = strlen(pem_str);
860
2
	int suffix_len = strlen(suffix);
861
	const char *p;
862
863
2
	if (suffix_len + 1 >= pem_len)
864
		return 0;
865
2
	p = pem_str + pem_len - suffix_len;
866
2
	if (strcmp(p, suffix))
867
		return 0;
868
2
	p--;
869
2
	if (*p != ' ')
870
		return 0;
871
2
	return p - pem_str;
872
}