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