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