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