Debian Codegraph @

debian/rust-vendor/openssl-src/openssl/crypto/pem/pem_lib.c

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