pem_lib.c 29 KB

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