2
0

pem_lib.c 30 KB

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