update libressl to 2.8.2
[unleashed.git] / lib / libcrypto / pem / pem_lib.c
blob6661a222f0086de94fa8fde2e76d3d088724e381
1 /* $OpenBSD: pem_lib.c,v 1.48 2018/08/24 19:48:39 tb Exp $ */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3 * All rights reserved.
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.
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).
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.
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)"
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.
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.]
59 #include <ctype.h>
60 #include <stdio.h>
61 #include <stdlib.h>
62 #include <string.h>
64 #include <openssl/opensslconf.h>
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>
74 #ifndef OPENSSL_NO_DES
75 #include <openssl/des.h>
76 #endif
77 #ifndef OPENSSL_NO_ENGINE
78 #include <openssl/engine.h>
79 #endif
81 #include "asn1_locl.h"
83 #define MIN_LENGTH 4
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);
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)
93 size_t l;
94 int i;
95 const char *prompt;
97 if (num < 0)
98 return -1;
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;
108 prompt = EVP_get_pw_prompt();
109 if (prompt == NULL)
110 prompt = "Enter PEM pass phrase:";
112 for (;;) {
113 i = EVP_read_pw_string_min(buf, MIN_LENGTH, num, prompt, w);
114 if (i != 0) {
115 PEMerror(PEM_R_PROBLEMS_GETTING_PASSWORD);
116 memset(buf, 0, num);
117 return (-1);
119 l = strlen(buf);
120 if (l < MIN_LENGTH) {
121 fprintf(stderr, "phrase is too short, "
122 "needs to be at least %zu chars\n",
123 (size_t)MIN_LENGTH);
124 } else
125 break;
127 return (int)l;
130 void
131 PEM_proc_type(char *buf, int type)
133 const char *str;
135 if (type == PEM_TYPE_ENCRYPTED)
136 str = "ENCRYPTED";
137 else if (type == PEM_TYPE_MIC_CLEAR)
138 str = "MIC-CLEAR";
139 else if (type == PEM_TYPE_MIC_ONLY)
140 str = "MIC-ONLY";
141 else
142 str = "BAD-TYPE";
144 strlcat(buf, "Proc-Type: 4,", PEM_BUFSIZE);
145 strlcat(buf, str, PEM_BUFSIZE);
146 strlcat(buf, "\n", PEM_BUFSIZE);
149 void
150 PEM_dek_info(char *buf, const char *type, int len, char *str)
152 static const unsigned char map[17] = "0123456789ABCDEF";
153 long i;
154 int j;
156 strlcat(buf, "DEK-Info: ", PEM_BUFSIZE);
157 strlcat(buf, type, PEM_BUFSIZE);
158 strlcat(buf, ",", PEM_BUFSIZE);
159 j = strlen(buf);
160 if (j + (len * 2) + 1 > PEM_BUFSIZE)
161 return;
162 for (i = 0; i < len; i++) {
163 buf[j + i * 2] = map[(str[i] >> 4) & 0x0f];
164 buf[j + i * 2 + 1] = map[(str[i]) & 0x0f];
166 buf[j + i * 2] = '\n';
167 buf[j + i * 2 + 1] = '\0';
170 void *
171 PEM_ASN1_read(d2i_of_void *d2i, const char *name, FILE *fp, void **x,
172 pem_password_cb *cb, void *u)
174 BIO *b;
175 void *ret;
177 if ((b = BIO_new(BIO_s_file())) == NULL) {
178 PEMerror(ERR_R_BUF_LIB);
179 return (0);
181 BIO_set_fp(b, fp, BIO_NOCLOSE);
182 ret = PEM_ASN1_read_bio(d2i, name, b, x, cb, u);
183 BIO_free(b);
184 return (ret);
187 static int
188 check_pem(const char *nm, const char *name)
190 /* Normal matching nm and name */
191 if (!strcmp(nm, name))
192 return 1;
194 /* Make PEM_STRING_EVP_PKEY match any private key */
196 if (!strcmp(name, PEM_STRING_EVP_PKEY)) {
197 int slen;
198 const EVP_PKEY_ASN1_METHOD *ameth;
199 if (!strcmp(nm, PEM_STRING_PKCS8))
200 return 1;
201 if (!strcmp(nm, PEM_STRING_PKCS8INF))
202 return 1;
203 slen = pem_check_suffix(nm, "PRIVATE KEY");
204 if (slen > 0) {
205 /* NB: ENGINE implementations wont contain
206 * a deprecated old private key decode function
207 * so don't look for them.
209 ameth = EVP_PKEY_asn1_find_str(NULL, nm, slen);
210 if (ameth && ameth->old_priv_decode)
211 return 1;
213 return 0;
216 if (!strcmp(name, PEM_STRING_PARAMETERS)) {
217 int slen;
218 const EVP_PKEY_ASN1_METHOD *ameth;
219 slen = pem_check_suffix(nm, "PARAMETERS");
220 if (slen > 0) {
221 ENGINE *e;
222 ameth = EVP_PKEY_asn1_find_str(&e, nm, slen);
223 if (ameth) {
224 int r;
225 if (ameth->param_decode)
226 r = 1;
227 else
228 r = 0;
229 #ifndef OPENSSL_NO_ENGINE
230 ENGINE_finish(e);
231 #endif
232 return r;
235 return 0;
238 /* Permit older strings */
240 if (!strcmp(nm, PEM_STRING_X509_OLD) &&
241 !strcmp(name, PEM_STRING_X509))
242 return 1;
244 if (!strcmp(nm, PEM_STRING_X509_REQ_OLD) &&
245 !strcmp(name, PEM_STRING_X509_REQ))
246 return 1;
248 /* Allow normal certs to be read as trusted certs */
249 if (!strcmp(nm, PEM_STRING_X509) &&
250 !strcmp(name, PEM_STRING_X509_TRUSTED))
251 return 1;
253 if (!strcmp(nm, PEM_STRING_X509_OLD) &&
254 !strcmp(name, PEM_STRING_X509_TRUSTED))
255 return 1;
257 /* Some CAs use PKCS#7 with CERTIFICATE headers */
258 if (!strcmp(nm, PEM_STRING_X509) &&
259 !strcmp(name, PEM_STRING_PKCS7))
260 return 1;
262 if (!strcmp(nm, PEM_STRING_PKCS7_SIGNED) &&
263 !strcmp(name, PEM_STRING_PKCS7))
264 return 1;
267 return 0;
271 PEM_bytes_read_bio(unsigned char **pdata, long *plen, char **pnm,
272 const char *name, BIO *bp, pem_password_cb *cb, void *u)
274 EVP_CIPHER_INFO cipher;
275 char *nm = NULL, *header = NULL;
276 unsigned char *data = NULL;
277 long len;
278 int ret = 0;
280 for (;;) {
281 if (!PEM_read_bio(bp, &nm, &header, &data, &len)) {
282 if (ERR_GET_REASON(ERR_peek_error()) ==
283 PEM_R_NO_START_LINE)
284 ERR_asprintf_error_data("Expecting: %s", name);
285 return 0;
287 if (check_pem(nm, name))
288 break;
289 free(nm);
290 free(header);
291 free(data);
293 if (!PEM_get_EVP_CIPHER_INFO(header, &cipher))
294 goto err;
295 if (!PEM_do_header(&cipher, data, &len, cb, u))
296 goto err;
298 *pdata = data;
299 *plen = len;
301 if (pnm)
302 *pnm = nm;
304 ret = 1;
306 err:
307 if (!ret || !pnm)
308 free(nm);
309 free(header);
310 if (!ret)
311 free(data);
312 return ret;
316 PEM_ASN1_write(i2d_of_void *i2d, const char *name, FILE *fp, void *x,
317 const EVP_CIPHER *enc, unsigned char *kstr, int klen,
318 pem_password_cb *callback, void *u)
320 BIO *b;
321 int ret;
323 if ((b = BIO_new(BIO_s_file())) == NULL) {
324 PEMerror(ERR_R_BUF_LIB);
325 return (0);
327 BIO_set_fp(b, fp, BIO_NOCLOSE);
328 ret = PEM_ASN1_write_bio(i2d, name, b, x, enc, kstr, klen, callback, u);
329 BIO_free(b);
330 return (ret);
334 PEM_ASN1_write_bio(i2d_of_void *i2d, const char *name, BIO *bp, void *x,
335 const EVP_CIPHER *enc, unsigned char *kstr, int klen,
336 pem_password_cb *callback, void *u)
338 EVP_CIPHER_CTX ctx;
339 int dsize = 0, i, j, ret = 0;
340 unsigned char *p, *data = NULL;
341 const char *objstr = NULL;
342 char buf[PEM_BUFSIZE];
343 unsigned char key[EVP_MAX_KEY_LENGTH];
344 unsigned char iv[EVP_MAX_IV_LENGTH];
346 if (enc != NULL) {
347 objstr = OBJ_nid2sn(EVP_CIPHER_nid(enc));
348 if (objstr == NULL) {
349 PEMerror(PEM_R_UNSUPPORTED_CIPHER);
350 goto err;
354 if ((dsize = i2d(x, NULL)) < 0) {
355 PEMerror(ERR_R_ASN1_LIB);
356 dsize = 0;
357 goto err;
359 /* dzise + 8 bytes are needed */
360 /* actually it needs the cipher block size extra... */
361 data = malloc(dsize + 20);
362 if (data == NULL) {
363 PEMerror(ERR_R_MALLOC_FAILURE);
364 goto err;
366 p = data;
367 i = i2d(x, &p);
369 if (enc != NULL) {
370 if (kstr == NULL) {
371 if (callback == NULL)
372 klen = PEM_def_callback(buf, PEM_BUFSIZE, 1, u);
373 else
374 klen = (*callback)(buf, PEM_BUFSIZE, 1, u);
375 if (klen <= 0) {
376 PEMerror(PEM_R_READ_KEY);
377 goto err;
379 kstr = (unsigned char *)buf;
381 if ((size_t)enc->iv_len > sizeof(iv)) {
382 PEMerror(EVP_R_IV_TOO_LARGE);
383 goto err;
385 arc4random_buf(iv, enc->iv_len); /* Generate a salt */
386 /* The 'iv' is used as the iv and as a salt. It is
387 * NOT taken from the BytesToKey function */
388 if (!EVP_BytesToKey(enc, EVP_md5(), iv, kstr, klen, 1,
389 key, NULL))
390 goto err;
392 if (kstr == (unsigned char *)buf)
393 explicit_bzero(buf, PEM_BUFSIZE);
395 if (strlen(objstr) + 23 + 2 * enc->iv_len + 13 > sizeof buf) {
396 PEMerror(ASN1_R_BUFFER_TOO_SMALL);
397 goto err;
400 buf[0] = '\0';
401 PEM_proc_type(buf, PEM_TYPE_ENCRYPTED);
402 PEM_dek_info(buf, objstr, enc->iv_len, (char *)iv);
403 /* k=strlen(buf); */
405 EVP_CIPHER_CTX_init(&ctx);
406 ret = 1;
407 if (!EVP_EncryptInit_ex(&ctx, enc, NULL, key, iv) ||
408 !EVP_EncryptUpdate(&ctx, data, &j, data, i) ||
409 !EVP_EncryptFinal_ex(&ctx, &(data[j]), &i))
410 ret = 0;
411 EVP_CIPHER_CTX_cleanup(&ctx);
412 if (ret == 0)
413 goto err;
414 i += j;
415 } else {
416 ret = 1;
417 buf[0] = '\0';
419 i = PEM_write_bio(bp, name, buf, data, i);
420 if (i <= 0)
421 ret = 0;
422 err:
423 explicit_bzero(key, sizeof(key));
424 explicit_bzero(iv, sizeof(iv));
425 explicit_bzero((char *)&ctx, sizeof(ctx));
426 explicit_bzero(buf, PEM_BUFSIZE);
427 freezero(data, (unsigned int)dsize);
428 return (ret);
432 PEM_do_header(EVP_CIPHER_INFO *cipher, unsigned char *data, long *plen,
433 pem_password_cb *callback, void *u)
435 int i, j, o, klen;
436 long len;
437 EVP_CIPHER_CTX ctx;
438 unsigned char key[EVP_MAX_KEY_LENGTH];
439 char buf[PEM_BUFSIZE];
441 len = *plen;
443 if (cipher->cipher == NULL)
444 return (1);
445 if (callback == NULL)
446 klen = PEM_def_callback(buf, PEM_BUFSIZE, 0, u);
447 else
448 klen = callback(buf, PEM_BUFSIZE, 0, u);
449 if (klen <= 0) {
450 PEMerror(PEM_R_BAD_PASSWORD_READ);
451 return (0);
453 if (!EVP_BytesToKey(cipher->cipher, EVP_md5(), &(cipher->iv[0]),
454 (unsigned char *)buf, klen, 1, key, NULL))
455 return 0;
457 j = (int)len;
458 EVP_CIPHER_CTX_init(&ctx);
459 o = EVP_DecryptInit_ex(&ctx, cipher->cipher, NULL, key,
460 &(cipher->iv[0]));
461 if (o)
462 o = EVP_DecryptUpdate(&ctx, data, &i, data, j);
463 if (o)
464 o = EVP_DecryptFinal_ex(&ctx, &(data[i]), &j);
465 EVP_CIPHER_CTX_cleanup(&ctx);
466 explicit_bzero((char *)buf, sizeof(buf));
467 explicit_bzero((char *)key, sizeof(key));
468 if (!o) {
469 PEMerror(PEM_R_BAD_DECRYPT);
470 return (0);
472 *plen = j + i;
473 return (1);
477 PEM_get_EVP_CIPHER_INFO(char *header, EVP_CIPHER_INFO *cipher)
479 const EVP_CIPHER *enc = NULL;
480 char *p, c;
481 char **header_pp = &header;
483 cipher->cipher = NULL;
484 if ((header == NULL) || (*header == '\0') || (*header == '\n'))
485 return (1);
486 if (strncmp(header, "Proc-Type: ", 11) != 0) {
487 PEMerror(PEM_R_NOT_PROC_TYPE);
488 return (0);
490 header += 11;
491 if (*header != '4')
492 return (0);
493 header++;
494 if (*header != ',')
495 return (0);
496 header++;
497 if (strncmp(header, "ENCRYPTED", 9) != 0) {
498 PEMerror(PEM_R_NOT_ENCRYPTED);
499 return (0);
501 for (; (*header != '\n') && (*header != '\0'); header++)
503 if (*header == '\0') {
504 PEMerror(PEM_R_SHORT_HEADER);
505 return (0);
507 header++;
508 if (strncmp(header, "DEK-Info: ", 10) != 0) {
509 PEMerror(PEM_R_NOT_DEK_INFO);
510 return (0);
512 header += 10;
514 p = header;
515 for (;;) {
516 c= *header;
517 if (!( ((c >= 'A') && (c <= 'Z')) || (c == '-') ||
518 ((c >= '0') && (c <= '9'))))
519 break;
520 header++;
522 *header = '\0';
523 cipher->cipher = enc = EVP_get_cipherbyname(p);
524 *header = c;
525 header++;
527 if (enc == NULL) {
528 PEMerror(PEM_R_UNSUPPORTED_ENCRYPTION);
529 return (0);
531 if (!load_iv(header_pp, &(cipher->iv[0]), enc->iv_len))
532 return (0);
534 return (1);
537 static int
538 load_iv(char **fromp, unsigned char *to, int num)
540 int v, i;
541 char *from;
543 from= *fromp;
544 for (i = 0; i < num; i++)
545 to[i] = 0;
546 num *= 2;
547 for (i = 0; i < num; i++) {
548 if ((*from >= '0') && (*from <= '9'))
549 v = *from - '0';
550 else if ((*from >= 'A') && (*from <= 'F'))
551 v = *from - 'A' + 10;
552 else if ((*from >= 'a') && (*from <= 'f'))
553 v = *from - 'a' + 10;
554 else {
555 PEMerror(PEM_R_BAD_IV_CHARS);
556 return (0);
558 from++;
559 to[i / 2] |= v << (long)((!(i & 1)) * 4);
562 *fromp = from;
563 return (1);
567 PEM_write(FILE *fp, const char *name, const char *header,
568 const unsigned char *data, long len)
570 BIO *b;
571 int ret;
573 if ((b = BIO_new(BIO_s_file())) == NULL) {
574 PEMerror(ERR_R_BUF_LIB);
575 return (0);
577 BIO_set_fp(b, fp, BIO_NOCLOSE);
578 ret = PEM_write_bio(b, name, header, data, len);
579 BIO_free(b);
580 return (ret);
584 PEM_write_bio(BIO *bp, const char *name, const char *header,
585 const unsigned char *data, long len)
587 int nlen, n, i, j, outl;
588 unsigned char *buf = NULL;
589 EVP_ENCODE_CTX ctx;
590 int reason = ERR_R_BUF_LIB;
592 EVP_EncodeInit(&ctx);
593 nlen = strlen(name);
595 if ((BIO_write(bp, "-----BEGIN ", 11) != 11) ||
596 (BIO_write(bp, name, nlen) != nlen) ||
597 (BIO_write(bp, "-----\n", 6) != 6))
598 goto err;
600 i = strlen(header);
601 if (i > 0) {
602 if ((BIO_write(bp, header, i) != i) ||
603 (BIO_write(bp, "\n", 1) != 1))
604 goto err;
607 buf = reallocarray(NULL, PEM_BUFSIZE, 8);
608 if (buf == NULL) {
609 reason = ERR_R_MALLOC_FAILURE;
610 goto err;
613 i = j = 0;
614 while (len > 0) {
615 n = (int)((len > (PEM_BUFSIZE * 5)) ? (PEM_BUFSIZE * 5) : len);
616 if (!EVP_EncodeUpdate(&ctx, buf, &outl, &(data[j]), n))
617 goto err;
618 if ((outl) && (BIO_write(bp, (char *)buf, outl) != outl))
619 goto err;
620 i += outl;
621 len -= n;
622 j += n;
624 EVP_EncodeFinal(&ctx, buf, &outl);
625 if ((outl > 0) && (BIO_write(bp, (char *)buf, outl) != outl))
626 goto err;
627 freezero(buf, PEM_BUFSIZE * 8);
628 buf = NULL;
629 if ((BIO_write(bp, "-----END ", 9) != 9) ||
630 (BIO_write(bp, name, nlen) != nlen) ||
631 (BIO_write(bp, "-----\n", 6) != 6))
632 goto err;
633 return (i + outl);
635 err:
636 freezero(buf, PEM_BUFSIZE * 8);
637 PEMerror(reason);
638 return (0);
642 PEM_read(FILE *fp, char **name, char **header, unsigned char **data, long *len)
644 BIO *b;
645 int ret;
647 if ((b = BIO_new(BIO_s_file())) == NULL) {
648 PEMerror(ERR_R_BUF_LIB);
649 return (0);
651 BIO_set_fp(b, fp, BIO_NOCLOSE);
652 ret = PEM_read_bio(b, name, header, data, len);
653 BIO_free(b);
654 return (ret);
658 PEM_read_bio(BIO *bp, char **name, char **header, unsigned char **data,
659 long *len)
661 EVP_ENCODE_CTX ctx;
662 int end = 0, i, k, bl = 0, hl = 0, nohead = 0;
663 char buf[256];
664 BUF_MEM *nameB;
665 BUF_MEM *headerB;
666 BUF_MEM *dataB, *tmpB;
668 nameB = BUF_MEM_new();
669 headerB = BUF_MEM_new();
670 dataB = BUF_MEM_new();
671 if ((nameB == NULL) || (headerB == NULL) || (dataB == NULL)) {
672 BUF_MEM_free(nameB);
673 BUF_MEM_free(headerB);
674 BUF_MEM_free(dataB);
675 PEMerror(ERR_R_MALLOC_FAILURE);
676 return (0);
679 buf[254] = '\0';
680 for (;;) {
681 i = BIO_gets(bp, buf, 254);
683 if (i <= 0) {
684 PEMerror(PEM_R_NO_START_LINE);
685 goto err;
688 while ((i >= 0) && (buf[i] <= ' '))
689 i--;
690 buf[++i] = '\n';
691 buf[++i] = '\0';
693 if (strncmp(buf, "-----BEGIN ", 11) == 0) {
694 i = strlen(&(buf[11]));
696 if (strncmp(&(buf[11 + i - 6]), "-----\n", 6) != 0)
697 continue;
698 if (!BUF_MEM_grow(nameB, i + 9)) {
699 PEMerror(ERR_R_MALLOC_FAILURE);
700 goto err;
702 memcpy(nameB->data, &(buf[11]), i - 6);
703 nameB->data[i - 6] = '\0';
704 break;
707 hl = 0;
708 if (!BUF_MEM_grow(headerB, 256)) {
709 PEMerror(ERR_R_MALLOC_FAILURE);
710 goto err;
712 headerB->data[0] = '\0';
713 for (;;) {
714 i = BIO_gets(bp, buf, 254);
715 if (i <= 0)
716 break;
718 while ((i >= 0) && (buf[i] <= ' '))
719 i--;
720 buf[++i] = '\n';
721 buf[++i] = '\0';
723 if (buf[0] == '\n')
724 break;
725 if (!BUF_MEM_grow(headerB, hl + i + 9)) {
726 PEMerror(ERR_R_MALLOC_FAILURE);
727 goto err;
729 if (strncmp(buf, "-----END ", 9) == 0) {
730 nohead = 1;
731 break;
733 memcpy(&(headerB->data[hl]), buf, i);
734 headerB->data[hl + i] = '\0';
735 hl += i;
738 bl = 0;
739 if (!BUF_MEM_grow(dataB, 1024)) {
740 PEMerror(ERR_R_MALLOC_FAILURE);
741 goto err;
743 dataB->data[0] = '\0';
744 if (!nohead) {
745 for (;;) {
746 i = BIO_gets(bp, buf, 254);
747 if (i <= 0)
748 break;
750 while ((i >= 0) && (buf[i] <= ' '))
751 i--;
752 buf[++i] = '\n';
753 buf[++i] = '\0';
755 if (i != 65)
756 end = 1;
757 if (strncmp(buf, "-----END ", 9) == 0)
758 break;
759 if (i > 65)
760 break;
761 if (!BUF_MEM_grow_clean(dataB, i + bl + 9)) {
762 PEMerror(ERR_R_MALLOC_FAILURE);
763 goto err;
765 memcpy(&(dataB->data[bl]), buf, i);
766 dataB->data[bl + i] = '\0';
767 bl += i;
768 if (end) {
769 buf[0] = '\0';
770 i = BIO_gets(bp, buf, 254);
771 if (i <= 0)
772 break;
774 while ((i >= 0) && (buf[i] <= ' '))
775 i--;
776 buf[++i] = '\n';
777 buf[++i] = '\0';
779 break;
782 } else {
783 tmpB = headerB;
784 headerB = dataB;
785 dataB = tmpB;
786 bl = hl;
788 i = strlen(nameB->data);
789 if ((strncmp(buf, "-----END ", 9) != 0) ||
790 (strncmp(nameB->data, &(buf[9]), i) != 0) ||
791 (strncmp(&(buf[9 + i]), "-----\n", 6) != 0)) {
792 PEMerror(PEM_R_BAD_END_LINE);
793 goto err;
796 EVP_DecodeInit(&ctx);
797 i = EVP_DecodeUpdate(&ctx,
798 (unsigned char *)dataB->data, &bl,
799 (unsigned char *)dataB->data, bl);
800 if (i < 0) {
801 PEMerror(PEM_R_BAD_BASE64_DECODE);
802 goto err;
804 i = EVP_DecodeFinal(&ctx, (unsigned char *)&(dataB->data[bl]), &k);
805 if (i < 0) {
806 PEMerror(PEM_R_BAD_BASE64_DECODE);
807 goto err;
809 bl += k;
811 if (bl == 0)
812 goto err;
813 *name = nameB->data;
814 *header = headerB->data;
815 *data = (unsigned char *)dataB->data;
816 *len = bl;
817 free(nameB);
818 free(headerB);
819 free(dataB);
820 return (1);
822 err:
823 BUF_MEM_free(nameB);
824 BUF_MEM_free(headerB);
825 BUF_MEM_free(dataB);
826 return (0);
829 /* Check pem string and return prefix length.
830 * If for example the pem_str == "RSA PRIVATE KEY" and suffix = "PRIVATE KEY"
831 * the return value is 3 for the string "RSA".
835 pem_check_suffix(const char *pem_str, const char *suffix)
837 int pem_len = strlen(pem_str);
838 int suffix_len = strlen(suffix);
839 const char *p;
841 if (suffix_len + 1 >= pem_len)
842 return 0;
843 p = pem_str + pem_len - suffix_len;
844 if (strcmp(p, suffix))
845 return 0;
846 p--;
847 if (*p != ' ')
848 return 0;
849 return p - pem_str;