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