pem_lib.c 29 KB

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