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