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