]> git.ipfire.org Git - thirdparty/openssl.git/blob - crypto/pem/pem_lib.c
Identify and move common internal libcrypto header files
[thirdparty/openssl.git] / crypto / pem / pem_lib.c
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 "internal/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 "internal/asn1_int.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 #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 {
87 #ifdef OPENSSL_NO_STDIO
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 int i, j;
95 const char *prompt;
96 if (key) {
97 i = strlen(key);
98 i = (i > num) ? num : i;
99 memcpy(buf, key, i);
100 return (i);
101 }
102
103 prompt = EVP_get_pw_prompt();
104 if (prompt == NULL)
105 prompt = "Enter PEM pass phrase:";
106
107 for (;;) {
108 i = EVP_read_pw_string_min(buf, MIN_LENGTH, num, prompt, w);
109 if (i != 0) {
110 PEMerr(PEM_F_PEM_DEF_CALLBACK, PEM_R_PROBLEMS_GETTING_PASSWORD);
111 memset(buf, 0, (unsigned int)num);
112 return (-1);
113 }
114 j = strlen(buf);
115 if (j < MIN_LENGTH) {
116 fprintf(stderr,
117 "phrase is too short, needs to be at least %d chars\n",
118 MIN_LENGTH);
119 } else
120 break;
121 }
122 return (j);
123 #endif
124 }
125
126 void PEM_proc_type(char *buf, int type)
127 {
128 const char *str;
129
130 if (type == PEM_TYPE_ENCRYPTED)
131 str = "ENCRYPTED";
132 else if (type == PEM_TYPE_MIC_CLEAR)
133 str = "MIC-CLEAR";
134 else if (type == PEM_TYPE_MIC_ONLY)
135 str = "MIC-ONLY";
136 else
137 str = "BAD-TYPE";
138
139 BUF_strlcat(buf, "Proc-Type: 4,", PEM_BUFSIZE);
140 BUF_strlcat(buf, str, PEM_BUFSIZE);
141 BUF_strlcat(buf, "\n", PEM_BUFSIZE);
142 }
143
144 void PEM_dek_info(char *buf, const char *type, int len, char *str)
145 {
146 static const unsigned char map[17] = "0123456789ABCDEF";
147 long i;
148 int j;
149
150 BUF_strlcat(buf, "DEK-Info: ", PEM_BUFSIZE);
151 BUF_strlcat(buf, type, PEM_BUFSIZE);
152 BUF_strlcat(buf, ",", PEM_BUFSIZE);
153 j = strlen(buf);
154 if (j + (len * 2) + 1 > PEM_BUFSIZE)
155 return;
156 for (i = 0; i < len; i++) {
157 buf[j + i * 2] = map[(str[i] >> 4) & 0x0f];
158 buf[j + i * 2 + 1] = map[(str[i]) & 0x0f];
159 }
160 buf[j + i * 2] = '\n';
161 buf[j + i * 2 + 1] = '\0';
162 }
163
164 #ifndef OPENSSL_NO_STDIO
165 void *PEM_ASN1_read(d2i_of_void *d2i, const char *name, FILE *fp, void **x,
166 pem_password_cb *cb, void *u)
167 {
168 BIO *b;
169 void *ret;
170
171 if ((b = BIO_new(BIO_s_file())) == NULL) {
172 PEMerr(PEM_F_PEM_ASN1_READ, ERR_R_BUF_LIB);
173 return (0);
174 }
175 BIO_set_fp(b, fp, BIO_NOCLOSE);
176 ret = PEM_ASN1_read_bio(d2i, name, b, x, cb, u);
177 BIO_free(b);
178 return (ret);
179 }
180 #endif
181
182 static int check_pem(const char *nm, const char *name)
183 {
184 /* Normal matching nm and name */
185 if (strcmp(nm, name) == 0)
186 return 1;
187
188 /* Make PEM_STRING_EVP_PKEY match any private key */
189
190 if (strcmp(name, PEM_STRING_EVP_PKEY) == 0) {
191 int slen;
192 const EVP_PKEY_ASN1_METHOD *ameth;
193 if (strcmp(nm, PEM_STRING_PKCS8) == 0)
194 return 1;
195 if (strcmp(nm, PEM_STRING_PKCS8INF) == 0)
196 return 1;
197 slen = pem_check_suffix(nm, "PRIVATE KEY");
198 if (slen > 0) {
199 /*
200 * NB: ENGINE implementations wont contain a deprecated old
201 * private key decode function so don't look for them.
202 */
203 ameth = EVP_PKEY_asn1_find_str(NULL, nm, slen);
204 if (ameth && ameth->old_priv_decode)
205 return 1;
206 }
207 return 0;
208 }
209
210 if (strcmp(name, PEM_STRING_PARAMETERS) == 0) {
211 int slen;
212 const EVP_PKEY_ASN1_METHOD *ameth;
213 slen = pem_check_suffix(nm, "PARAMETERS");
214 if (slen > 0) {
215 ENGINE *e;
216 ameth = EVP_PKEY_asn1_find_str(&e, nm, slen);
217 if (ameth) {
218 int r;
219 if (ameth->param_decode)
220 r = 1;
221 else
222 r = 0;
223 #ifndef OPENSSL_NO_ENGINE
224 if (e)
225 ENGINE_finish(e);
226 #endif
227 return r;
228 }
229 }
230 return 0;
231 }
232 /* If reading DH parameters handle X9.42 DH format too */
233 if (strcmp(nm, PEM_STRING_DHXPARAMS) == 0
234 && strcmp(name, PEM_STRING_DHPARAMS) == 0)
235 return 1;
236
237 /* Permit older strings */
238
239 if (strcmp(nm, PEM_STRING_X509_OLD) == 0
240 && strcmp(name, PEM_STRING_X509) == 0)
241 return 1;
242
243 if (strcmp(nm, PEM_STRING_X509_REQ_OLD) == 0
244 && strcmp(name, PEM_STRING_X509_REQ) == 0)
245 return 1;
246
247 /* Allow normal certs to be read as trusted certs */
248 if (strcmp(nm, PEM_STRING_X509) == 0
249 && strcmp(name, PEM_STRING_X509_TRUSTED) == 0)
250 return 1;
251
252 if (strcmp(nm, PEM_STRING_X509_OLD) == 0
253 && strcmp(name, PEM_STRING_X509_TRUSTED) == 0)
254 return 1;
255
256 /* Some CAs use PKCS#7 with CERTIFICATE headers */
257 if (strcmp(nm, PEM_STRING_X509) == 0
258 && strcmp(name, PEM_STRING_PKCS7) == 0)
259 return 1;
260
261 if (strcmp(nm, PEM_STRING_PKCS7_SIGNED) == 0
262 && strcmp(name, PEM_STRING_PKCS7) == 0)
263 return 1;
264
265 #ifndef OPENSSL_NO_CMS
266 if (strcmp(nm, PEM_STRING_X509) == 0
267 && strcmp(name, PEM_STRING_CMS) == 0)
268 return 1;
269 /* Allow CMS to be read from PKCS#7 headers */
270 if (strcmp(nm, PEM_STRING_PKCS7) == 0
271 && strcmp(name, PEM_STRING_CMS) == 0)
272 return 1;
273 #endif
274
275 return 0;
276 }
277
278 int PEM_bytes_read_bio(unsigned char **pdata, long *plen, char **pnm,
279 const char *name, BIO *bp, pem_password_cb *cb,
280 void *u)
281 {
282 EVP_CIPHER_INFO cipher;
283 char *nm = NULL, *header = NULL;
284 unsigned char *data = NULL;
285 long len;
286 int ret = 0;
287
288 for (;;) {
289 if (!PEM_read_bio(bp, &nm, &header, &data, &len)) {
290 if (ERR_GET_REASON(ERR_peek_error()) == PEM_R_NO_START_LINE)
291 ERR_add_error_data(2, "Expecting: ", name);
292 return 0;
293 }
294 if (check_pem(nm, name))
295 break;
296 OPENSSL_free(nm);
297 OPENSSL_free(header);
298 OPENSSL_free(data);
299 }
300 if (!PEM_get_EVP_CIPHER_INFO(header, &cipher))
301 goto err;
302 if (!PEM_do_header(&cipher, data, &len, cb, u))
303 goto err;
304
305 *pdata = data;
306 *plen = len;
307
308 if (pnm)
309 *pnm = nm;
310
311 ret = 1;
312
313 err:
314 if (!ret || !pnm)
315 OPENSSL_free(nm);
316 OPENSSL_free(header);
317 if (!ret)
318 OPENSSL_free(data);
319 return ret;
320 }
321
322 #ifndef OPENSSL_NO_STDIO
323 int PEM_ASN1_write(i2d_of_void *i2d, const char *name, FILE *fp,
324 void *x, const EVP_CIPHER *enc, unsigned char *kstr,
325 int klen, pem_password_cb *callback, void *u)
326 {
327 BIO *b;
328 int ret;
329
330 if ((b = BIO_new(BIO_s_file())) == NULL) {
331 PEMerr(PEM_F_PEM_ASN1_WRITE, ERR_R_BUF_LIB);
332 return (0);
333 }
334 BIO_set_fp(b, fp, BIO_NOCLOSE);
335 ret = PEM_ASN1_write_bio(i2d, name, b, x, enc, kstr, klen, callback, u);
336 BIO_free(b);
337 return (ret);
338 }
339 #endif
340
341 int PEM_ASN1_write_bio(i2d_of_void *i2d, const char *name, BIO *bp,
342 void *x, const EVP_CIPHER *enc, unsigned char *kstr,
343 int klen, pem_password_cb *callback, void *u)
344 {
345 EVP_CIPHER_CTX ctx;
346 int dsize = 0, i = 0, j = 0, ret = 0;
347 unsigned char *p, *data = NULL;
348 const char *objstr = NULL;
349 char buf[PEM_BUFSIZE];
350 unsigned char key[EVP_MAX_KEY_LENGTH];
351 unsigned char iv[EVP_MAX_IV_LENGTH];
352
353 if (enc != NULL) {
354 objstr = OBJ_nid2sn(EVP_CIPHER_nid(enc));
355 if (objstr == NULL) {
356 PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, PEM_R_UNSUPPORTED_CIPHER);
357 goto err;
358 }
359 }
360
361 if ((dsize = i2d(x, NULL)) < 0) {
362 PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, ERR_R_ASN1_LIB);
363 dsize = 0;
364 goto err;
365 }
366 /* dzise + 8 bytes are needed */
367 /* actually it needs the cipher block size extra... */
368 data = OPENSSL_malloc((unsigned int)dsize + 20);
369 if (data == NULL) {
370 PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, ERR_R_MALLOC_FAILURE);
371 goto err;
372 }
373 p = data;
374 i = i2d(x, &p);
375
376 if (enc != NULL) {
377 if (kstr == NULL) {
378 if (callback == NULL)
379 klen = PEM_def_callback(buf, PEM_BUFSIZE, 1, u);
380 else
381 klen = (*callback) (buf, PEM_BUFSIZE, 1, u);
382 if (klen <= 0) {
383 PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, PEM_R_READ_KEY);
384 goto err;
385 }
386 #ifdef CHARSET_EBCDIC
387 /* Convert the pass phrase from EBCDIC */
388 ebcdic2ascii(buf, buf, klen);
389 #endif
390 kstr = (unsigned char *)buf;
391 }
392 RAND_add(data, i, 0); /* put in the RSA key. */
393 OPENSSL_assert(enc->iv_len <= (int)sizeof(iv));
394 if (RAND_bytes(iv, enc->iv_len) <= 0) /* Generate a salt */
395 goto err;
396 /*
397 * The 'iv' is used as the iv and as a salt. It is NOT taken from
398 * the BytesToKey function
399 */
400 if (!EVP_BytesToKey(enc, EVP_md5(), iv, kstr, klen, 1, key, NULL))
401 goto err;
402
403 if (kstr == (unsigned char *)buf)
404 OPENSSL_cleanse(buf, PEM_BUFSIZE);
405
406 OPENSSL_assert(strlen(objstr) + 23 + 2 * enc->iv_len + 13 <=
407 sizeof buf);
408
409 buf[0] = '\0';
410 PEM_proc_type(buf, PEM_TYPE_ENCRYPTED);
411 PEM_dek_info(buf, objstr, enc->iv_len, (char *)iv);
412 /* k=strlen(buf); */
413
414 EVP_CIPHER_CTX_init(&ctx);
415 ret = 1;
416 if (!EVP_EncryptInit_ex(&ctx, enc, NULL, key, iv)
417 || !EVP_EncryptUpdate(&ctx, data, &j, data, i)
418 || !EVP_EncryptFinal_ex(&ctx, &(data[j]), &i))
419 ret = 0;
420 EVP_CIPHER_CTX_cleanup(&ctx);
421 if (ret == 0)
422 goto err;
423 i += j;
424 } else {
425 ret = 1;
426 buf[0] = '\0';
427 }
428 i = PEM_write_bio(bp, name, buf, data, i);
429 if (i <= 0)
430 ret = 0;
431 err:
432 OPENSSL_cleanse(key, sizeof(key));
433 OPENSSL_cleanse(iv, sizeof(iv));
434 OPENSSL_cleanse((char *)&ctx, sizeof(ctx));
435 OPENSSL_cleanse(buf, PEM_BUFSIZE);
436 OPENSSL_clear_free(data, (unsigned int)dsize);
437 return (ret);
438 }
439
440 int PEM_do_header(EVP_CIPHER_INFO *cipher, unsigned char *data, long *plen,
441 pem_password_cb *callback, void *u)
442 {
443 int i = 0, j, o, klen;
444 long len;
445 EVP_CIPHER_CTX ctx;
446 unsigned char key[EVP_MAX_KEY_LENGTH];
447 char buf[PEM_BUFSIZE];
448
449 len = *plen;
450
451 if (cipher->cipher == NULL)
452 return (1);
453 if (callback == NULL)
454 klen = PEM_def_callback(buf, PEM_BUFSIZE, 0, u);
455 else
456 klen = callback(buf, PEM_BUFSIZE, 0, u);
457 if (klen <= 0) {
458 PEMerr(PEM_F_PEM_DO_HEADER, PEM_R_BAD_PASSWORD_READ);
459 return (0);
460 }
461 #ifdef CHARSET_EBCDIC
462 /* Convert the pass phrase from EBCDIC */
463 ebcdic2ascii(buf, buf, klen);
464 #endif
465
466 if (!EVP_BytesToKey(cipher->cipher, EVP_md5(), &(cipher->iv[0]),
467 (unsigned char *)buf, klen, 1, key, NULL))
468 return 0;
469
470 j = (int)len;
471 EVP_CIPHER_CTX_init(&ctx);
472 o = EVP_DecryptInit_ex(&ctx, cipher->cipher, NULL, key, &(cipher->iv[0]));
473 if (o)
474 o = EVP_DecryptUpdate(&ctx, data, &i, data, j);
475 if (o)
476 o = EVP_DecryptFinal_ex(&ctx, &(data[i]), &j);
477 EVP_CIPHER_CTX_cleanup(&ctx);
478 OPENSSL_cleanse((char *)buf, sizeof(buf));
479 OPENSSL_cleanse((char *)key, sizeof(key));
480 if (o)
481 j += i;
482 else {
483 PEMerr(PEM_F_PEM_DO_HEADER, PEM_R_BAD_DECRYPT);
484 return (0);
485 }
486 *plen = j;
487 return (1);
488 }
489
490 int PEM_get_EVP_CIPHER_INFO(char *header, EVP_CIPHER_INFO *cipher)
491 {
492 const EVP_CIPHER *enc = NULL;
493 char *p, c;
494 char **header_pp = &header;
495
496 cipher->cipher = NULL;
497 if ((header == NULL) || (*header == '\0') || (*header == '\n'))
498 return (1);
499 if (strncmp(header, "Proc-Type: ", 11) != 0) {
500 PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_NOT_PROC_TYPE);
501 return (0);
502 }
503 header += 11;
504 if (*header != '4')
505 return (0);
506 header++;
507 if (*header != ',')
508 return (0);
509 header++;
510 if (strncmp(header, "ENCRYPTED", 9) != 0) {
511 PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_NOT_ENCRYPTED);
512 return (0);
513 }
514 for (; (*header != '\n') && (*header != '\0'); header++) ;
515 if (*header == '\0') {
516 PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_SHORT_HEADER);
517 return (0);
518 }
519 header++;
520 if (strncmp(header, "DEK-Info: ", 10) != 0) {
521 PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_NOT_DEK_INFO);
522 return (0);
523 }
524 header += 10;
525
526 p = header;
527 for (;;) {
528 c = *header;
529 #ifndef CHARSET_EBCDIC
530 if (!(((c >= 'A') && (c <= 'Z')) || (c == '-') ||
531 ((c >= '0') && (c <= '9'))))
532 break;
533 #else
534 if (!(isupper(c) || (c == '-') || isdigit(c)))
535 break;
536 #endif
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, PEM_R_UNSUPPORTED_ENCRYPTION);
546 return (0);
547 }
548 if (!load_iv(header_pp, &(cipher->iv[0]), enc->iv_len))
549 return (0);
550
551 return (1);
552 }
553
554 static int load_iv(char **fromp, unsigned char *to, int num)
555 {
556 int v, i;
557 char *from;
558
559 from = *fromp;
560 for (i = 0; i < num; i++)
561 to[i] = 0;
562 num *= 2;
563 for (i = 0; i < num; i++) {
564 if ((*from >= '0') && (*from <= '9'))
565 v = *from - '0';
566 else if ((*from >= 'A') && (*from <= 'F'))
567 v = *from - 'A' + 10;
568 else if ((*from >= 'a') && (*from <= 'f'))
569 v = *from - 'a' + 10;
570 else {
571 PEMerr(PEM_F_LOAD_IV, PEM_R_BAD_IV_CHARS);
572 return (0);
573 }
574 from++;
575 to[i / 2] |= v << (long)((!(i & 1)) * 4);
576 }
577
578 *fromp = from;
579 return (1);
580 }
581
582 #ifndef OPENSSL_NO_STDIO
583 int PEM_write(FILE *fp, const char *name, const char *header,
584 const unsigned char *data, long len)
585 {
586 BIO *b;
587 int ret;
588
589 if ((b = BIO_new(BIO_s_file())) == NULL) {
590 PEMerr(PEM_F_PEM_WRITE, ERR_R_BUF_LIB);
591 return (0);
592 }
593 BIO_set_fp(b, fp, BIO_NOCLOSE);
594 ret = PEM_write_bio(b, name, header, data, len);
595 BIO_free(b);
596 return (ret);
597 }
598 #endif
599
600 int PEM_write_bio(BIO *bp, const char *name, const char *header,
601 const unsigned char *data, long len)
602 {
603 int nlen, n, i, j, outl;
604 unsigned char *buf = NULL;
605 EVP_ENCODE_CTX ctx;
606 int reason = ERR_R_BUF_LIB;
607
608 EVP_EncodeInit(&ctx);
609 nlen = strlen(name);
610
611 if ((BIO_write(bp, "-----BEGIN ", 11) != 11) ||
612 (BIO_write(bp, name, nlen) != nlen) ||
613 (BIO_write(bp, "-----\n", 6) != 6))
614 goto err;
615
616 i = strlen(header);
617 if (i > 0) {
618 if ((BIO_write(bp, header, i) != i) || (BIO_write(bp, "\n", 1) != 1))
619 goto err;
620 }
621
622 buf = OPENSSL_malloc(PEM_BUFSIZE * 8);
623 if (buf == NULL) {
624 reason = ERR_R_MALLOC_FAILURE;
625 goto err;
626 }
627
628 i = j = 0;
629 while (len > 0) {
630 n = (int)((len > (PEM_BUFSIZE * 5)) ? (PEM_BUFSIZE * 5) : len);
631 EVP_EncodeUpdate(&ctx, buf, &outl, &(data[j]), n);
632 if ((outl) && (BIO_write(bp, (char *)buf, outl) != outl))
633 goto err;
634 i += outl;
635 len -= n;
636 j += n;
637 }
638 EVP_EncodeFinal(&ctx, buf, &outl);
639 if ((outl > 0) && (BIO_write(bp, (char *)buf, outl) != outl))
640 goto err;
641 OPENSSL_clear_free(buf, PEM_BUFSIZE * 8);
642 buf = NULL;
643 if ((BIO_write(bp, "-----END ", 9) != 9) ||
644 (BIO_write(bp, name, nlen) != nlen) ||
645 (BIO_write(bp, "-----\n", 6) != 6))
646 goto err;
647 return (i + outl);
648 err:
649 OPENSSL_clear_free(buf, PEM_BUFSIZE * 8);
650 PEMerr(PEM_F_PEM_WRITE_BIO, reason);
651 return (0);
652 }
653
654 #ifndef OPENSSL_NO_STDIO
655 int PEM_read(FILE *fp, char **name, char **header, unsigned char **data,
656 long *len)
657 {
658 BIO *b;
659 int ret;
660
661 if ((b = BIO_new(BIO_s_file())) == NULL) {
662 PEMerr(PEM_F_PEM_READ, ERR_R_BUF_LIB);
663 return (0);
664 }
665 BIO_set_fp(b, fp, BIO_NOCLOSE);
666 ret = PEM_read_bio(b, name, header, data, len);
667 BIO_free(b);
668 return (ret);
669 }
670 #endif
671
672 int PEM_read_bio(BIO *bp, char **name, char **header, unsigned char **data,
673 long *len)
674 {
675 EVP_ENCODE_CTX ctx;
676 int end = 0, i, k, bl = 0, hl = 0, nohead = 0;
677 char buf[256];
678 BUF_MEM *nameB;
679 BUF_MEM *headerB;
680 BUF_MEM *dataB, *tmpB;
681
682 nameB = BUF_MEM_new();
683 headerB = BUF_MEM_new();
684 dataB = BUF_MEM_new();
685 if ((nameB == NULL) || (headerB == NULL) || (dataB == NULL)) {
686 BUF_MEM_free(nameB);
687 BUF_MEM_free(headerB);
688 BUF_MEM_free(dataB);
689 PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
690 return (0);
691 }
692
693 buf[254] = '\0';
694 for (;;) {
695 i = BIO_gets(bp, buf, 254);
696
697 if (i <= 0) {
698 PEMerr(PEM_F_PEM_READ_BIO, PEM_R_NO_START_LINE);
699 goto err;
700 }
701
702 while ((i >= 0) && (buf[i] <= ' '))
703 i--;
704 buf[++i] = '\n';
705 buf[++i] = '\0';
706
707 if (strncmp(buf, "-----BEGIN ", 11) == 0) {
708 i = strlen(&(buf[11]));
709
710 if (strncmp(&(buf[11 + i - 6]), "-----\n", 6) != 0)
711 continue;
712 if (!BUF_MEM_grow(nameB, i + 9)) {
713 PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
714 goto err;
715 }
716 memcpy(nameB->data, &(buf[11]), i - 6);
717 nameB->data[i - 6] = '\0';
718 break;
719 }
720 }
721 hl = 0;
722 if (!BUF_MEM_grow(headerB, 256)) {
723 PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
724 goto err;
725 }
726 headerB->data[0] = '\0';
727 for (;;) {
728 i = BIO_gets(bp, buf, 254);
729 if (i <= 0)
730 break;
731
732 while ((i >= 0) && (buf[i] <= ' '))
733 i--;
734 buf[++i] = '\n';
735 buf[++i] = '\0';
736
737 if (buf[0] == '\n')
738 break;
739 if (!BUF_MEM_grow(headerB, hl + i + 9)) {
740 PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
741 goto err;
742 }
743 if (strncmp(buf, "-----END ", 9) == 0) {
744 nohead = 1;
745 break;
746 }
747 memcpy(&(headerB->data[hl]), buf, i);
748 headerB->data[hl + i] = '\0';
749 hl += i;
750 }
751
752 bl = 0;
753 if (!BUF_MEM_grow(dataB, 1024)) {
754 PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
755 goto err;
756 }
757 dataB->data[0] = '\0';
758 if (!nohead) {
759 for (;;) {
760 i = BIO_gets(bp, buf, 254);
761 if (i <= 0)
762 break;
763
764 while ((i >= 0) && (buf[i] <= ' '))
765 i--;
766 buf[++i] = '\n';
767 buf[++i] = '\0';
768
769 if (i != 65)
770 end = 1;
771 if (strncmp(buf, "-----END ", 9) == 0)
772 break;
773 if (i > 65)
774 break;
775 if (!BUF_MEM_grow_clean(dataB, i + bl + 9)) {
776 PEMerr(PEM_F_PEM_READ_BIO, ERR_R_MALLOC_FAILURE);
777 goto err;
778 }
779 memcpy(&(dataB->data[bl]), buf, i);
780 dataB->data[bl + i] = '\0';
781 bl += i;
782 if (end) {
783 buf[0] = '\0';
784 i = BIO_gets(bp, buf, 254);
785 if (i <= 0)
786 break;
787
788 while ((i >= 0) && (buf[i] <= ' '))
789 i--;
790 buf[++i] = '\n';
791 buf[++i] = '\0';
792
793 break;
794 }
795 }
796 } else {
797 tmpB = headerB;
798 headerB = dataB;
799 dataB = tmpB;
800 bl = hl;
801 }
802 i = strlen(nameB->data);
803 if ((strncmp(buf, "-----END ", 9) != 0) ||
804 (strncmp(nameB->data, &(buf[9]), i) != 0) ||
805 (strncmp(&(buf[9 + i]), "-----\n", 6) != 0)) {
806 PEMerr(PEM_F_PEM_READ_BIO, PEM_R_BAD_END_LINE);
807 goto err;
808 }
809
810 EVP_DecodeInit(&ctx);
811 i = EVP_DecodeUpdate(&ctx,
812 (unsigned char *)dataB->data, &bl,
813 (unsigned char *)dataB->data, bl);
814 if (i < 0) {
815 PEMerr(PEM_F_PEM_READ_BIO, PEM_R_BAD_BASE64_DECODE);
816 goto err;
817 }
818 i = EVP_DecodeFinal(&ctx, (unsigned char *)&(dataB->data[bl]), &k);
819 if (i < 0) {
820 PEMerr(PEM_F_PEM_READ_BIO, PEM_R_BAD_BASE64_DECODE);
821 goto err;
822 }
823 bl += k;
824
825 if (bl == 0)
826 goto err;
827 *name = nameB->data;
828 *header = headerB->data;
829 *data = (unsigned char *)dataB->data;
830 *len = bl;
831 OPENSSL_free(nameB);
832 OPENSSL_free(headerB);
833 OPENSSL_free(dataB);
834 return (1);
835 err:
836 BUF_MEM_free(nameB);
837 BUF_MEM_free(headerB);
838 BUF_MEM_free(dataB);
839 return (0);
840 }
841
842 /*
843 * Check pem string and return prefix length. If for example the pem_str ==
844 * "RSA PRIVATE KEY" and suffix = "PRIVATE KEY" the return value is 3 for the
845 * string "RSA".
846 */
847
848 int pem_check_suffix(const char *pem_str, const char *suffix)
849 {
850 int pem_len = strlen(pem_str);
851 int suffix_len = strlen(suffix);
852 const char *p;
853 if (suffix_len + 1 >= pem_len)
854 return 0;
855 p = pem_str + pem_len - suffix_len;
856 if (strcmp(p, suffix))
857 return 0;
858 p--;
859 if (*p != ' ')
860 return 0;
861 return p - pem_str;
862 }