pem_lib.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988
  1. /*
  2. * Copyright 1995-2018 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. #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. memset(cipher->iv, 0, sizeof(cipher->iv));
  436. if ((header == NULL) || (*header == '\0') || (*header == '\n'))
  437. return 1;
  438. if (strncmp(header, ProcType, sizeof(ProcType)-1) != 0) {
  439. PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_NOT_PROC_TYPE);
  440. return 0;
  441. }
  442. header += sizeof(ProcType)-1;
  443. header += strspn(header, " \t");
  444. if (*header++ != '4' || *header++ != ',')
  445. return 0;
  446. header += strspn(header, " \t");
  447. /* We expect "ENCRYPTED" followed by optional white-space + line break */
  448. if (strncmp(header, ENCRYPTED, sizeof(ENCRYPTED)-1) != 0 ||
  449. strspn(header+sizeof(ENCRYPTED)-1, " \t\r\n") == 0) {
  450. PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_NOT_ENCRYPTED);
  451. return 0;
  452. }
  453. header += sizeof(ENCRYPTED)-1;
  454. header += strspn(header, " \t\r");
  455. if (*header++ != '\n') {
  456. PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_SHORT_HEADER);
  457. return 0;
  458. }
  459. /*-
  460. * https://tools.ietf.org/html/rfc1421#section-4.6.1.3
  461. * We expect "DEK-Info: algo[,hex-parameters]"
  462. */
  463. if (strncmp(header, DEKInfo, sizeof(DEKInfo)-1) != 0) {
  464. PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_NOT_DEK_INFO);
  465. return 0;
  466. }
  467. header += sizeof(DEKInfo)-1;
  468. header += strspn(header, " \t");
  469. /*
  470. * DEK-INFO is a comma-separated combination of algorithm name and optional
  471. * parameters.
  472. */
  473. dekinfostart = header;
  474. header += strcspn(header, " \t,");
  475. c = *header;
  476. *header = '\0';
  477. cipher->cipher = enc = EVP_get_cipherbyname(dekinfostart);
  478. *header = c;
  479. header += strspn(header, " \t");
  480. if (enc == NULL) {
  481. PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_UNSUPPORTED_ENCRYPTION);
  482. return 0;
  483. }
  484. ivlen = EVP_CIPHER_iv_length(enc);
  485. if (ivlen > 0 && *header++ != ',') {
  486. PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_MISSING_DEK_IV);
  487. return 0;
  488. } else if (ivlen == 0 && *header == ',') {
  489. PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_UNEXPECTED_DEK_IV);
  490. return 0;
  491. }
  492. if (!load_iv(&header, cipher->iv, EVP_CIPHER_iv_length(enc)))
  493. return 0;
  494. return 1;
  495. }
  496. static int load_iv(char **fromp, unsigned char *to, int num)
  497. {
  498. int v, i;
  499. char *from;
  500. from = *fromp;
  501. for (i = 0; i < num; i++)
  502. to[i] = 0;
  503. num *= 2;
  504. for (i = 0; i < num; i++) {
  505. v = OPENSSL_hexchar2int(*from);
  506. if (v < 0) {
  507. PEMerr(PEM_F_LOAD_IV, PEM_R_BAD_IV_CHARS);
  508. return 0;
  509. }
  510. from++;
  511. to[i / 2] |= v << (long)((!(i & 1)) * 4);
  512. }
  513. *fromp = from;
  514. return 1;
  515. }
  516. #ifndef OPENSSL_NO_STDIO
  517. int PEM_write(FILE *fp, const char *name, const char *header,
  518. const unsigned char *data, long len)
  519. {
  520. BIO *b;
  521. int ret;
  522. if ((b = BIO_new(BIO_s_file())) == NULL) {
  523. PEMerr(PEM_F_PEM_WRITE, ERR_R_BUF_LIB);
  524. return 0;
  525. }
  526. BIO_set_fp(b, fp, BIO_NOCLOSE);
  527. ret = PEM_write_bio(b, name, header, data, len);
  528. BIO_free(b);
  529. return ret;
  530. }
  531. #endif
  532. int PEM_write_bio(BIO *bp, const char *name, const char *header,
  533. const unsigned char *data, long len)
  534. {
  535. int nlen, n, i, j, outl;
  536. unsigned char *buf = NULL;
  537. EVP_ENCODE_CTX *ctx = EVP_ENCODE_CTX_new();
  538. int reason = ERR_R_BUF_LIB;
  539. int retval = 0;
  540. if (ctx == NULL) {
  541. reason = ERR_R_MALLOC_FAILURE;
  542. goto err;
  543. }
  544. EVP_EncodeInit(ctx);
  545. nlen = strlen(name);
  546. if ((BIO_write(bp, "-----BEGIN ", 11) != 11) ||
  547. (BIO_write(bp, name, nlen) != nlen) ||
  548. (BIO_write(bp, "-----\n", 6) != 6))
  549. goto err;
  550. i = strlen(header);
  551. if (i > 0) {
  552. if ((BIO_write(bp, header, i) != i) || (BIO_write(bp, "\n", 1) != 1))
  553. goto err;
  554. }
  555. buf = OPENSSL_malloc(PEM_BUFSIZE * 8);
  556. if (buf == NULL) {
  557. reason = ERR_R_MALLOC_FAILURE;
  558. goto err;
  559. }
  560. i = j = 0;
  561. while (len > 0) {
  562. n = (int)((len > (PEM_BUFSIZE * 5)) ? (PEM_BUFSIZE * 5) : len);
  563. if (!EVP_EncodeUpdate(ctx, buf, &outl, &(data[j]), n))
  564. goto err;
  565. if ((outl) && (BIO_write(bp, (char *)buf, outl) != outl))
  566. goto err;
  567. i += outl;
  568. len -= n;
  569. j += n;
  570. }
  571. EVP_EncodeFinal(ctx, buf, &outl);
  572. if ((outl > 0) && (BIO_write(bp, (char *)buf, outl) != outl))
  573. goto err;
  574. if ((BIO_write(bp, "-----END ", 9) != 9) ||
  575. (BIO_write(bp, name, nlen) != nlen) ||
  576. (BIO_write(bp, "-----\n", 6) != 6))
  577. goto err;
  578. retval = i + outl;
  579. err:
  580. if (retval == 0)
  581. PEMerr(PEM_F_PEM_WRITE_BIO, reason);
  582. EVP_ENCODE_CTX_free(ctx);
  583. OPENSSL_clear_free(buf, PEM_BUFSIZE * 8);
  584. return retval;
  585. }
  586. #ifndef OPENSSL_NO_STDIO
  587. int PEM_read(FILE *fp, char **name, char **header, unsigned char **data,
  588. long *len)
  589. {
  590. BIO *b;
  591. int ret;
  592. if ((b = BIO_new(BIO_s_file())) == NULL) {
  593. PEMerr(PEM_F_PEM_READ, ERR_R_BUF_LIB);
  594. return 0;
  595. }
  596. BIO_set_fp(b, fp, BIO_NOCLOSE);
  597. ret = PEM_read_bio(b, name, header, data, len);
  598. BIO_free(b);
  599. return ret;
  600. }
  601. #endif
  602. /* Some helpers for PEM_read_bio_ex(). */
  603. static int sanitize_line(char *linebuf, int len, unsigned int flags)
  604. {
  605. int i;
  606. if (flags & PEM_FLAG_EAY_COMPATIBLE) {
  607. /* Strip trailing whitespace */
  608. while ((len >= 0) && (linebuf[len] <= ' '))
  609. len--;
  610. /* Go back to whitespace before applying uniform line ending. */
  611. len++;
  612. } else if (flags & PEM_FLAG_ONLY_B64) {
  613. for (i = 0; i < len; ++i) {
  614. if (!ossl_isbase64(linebuf[i]) || linebuf[i] == '\n'
  615. || linebuf[i] == '\r')
  616. break;
  617. }
  618. len = i;
  619. } else {
  620. /* EVP_DecodeBlock strips leading and trailing whitespace, so just strip
  621. * control characters in-place and let everything through. */
  622. for (i = 0; i < len; ++i) {
  623. if (linebuf[i] == '\n' || linebuf[i] == '\r')
  624. break;
  625. if (ossl_iscntrl(linebuf[i]))
  626. linebuf[i] = ' ';
  627. }
  628. len = i;
  629. }
  630. /* The caller allocated LINESIZE+1, so this is safe. */
  631. linebuf[len++] = '\n';
  632. linebuf[len] = '\0';
  633. return len;
  634. }
  635. #define LINESIZE 255
  636. /* Note trailing spaces for begin and end. */
  637. static const char beginstr[] = "-----BEGIN ";
  638. static const char endstr[] = "-----END ";
  639. static const char tailstr[] = "-----\n";
  640. #define BEGINLEN ((int)(sizeof(beginstr) - 1))
  641. #define ENDLEN ((int)(sizeof(endstr) - 1))
  642. #define TAILLEN ((int)(sizeof(tailstr) - 1))
  643. static int get_name(BIO *bp, char **name, unsigned int flags)
  644. {
  645. char *linebuf;
  646. int ret = 0;
  647. int len;
  648. /*
  649. * Need to hold trailing NUL (accounted for by BIO_gets() and the newline
  650. * that will be added by sanitize_line() (the extra '1').
  651. */
  652. linebuf = pem_malloc(LINESIZE + 1, flags);
  653. if (linebuf == NULL) {
  654. PEMerr(PEM_F_GET_NAME, ERR_R_MALLOC_FAILURE);
  655. return 0;
  656. }
  657. do {
  658. len = BIO_gets(bp, linebuf, LINESIZE);
  659. if (len <= 0) {
  660. PEMerr(PEM_F_GET_NAME, PEM_R_NO_START_LINE);
  661. goto err;
  662. }
  663. /* Strip trailing garbage and standardize ending. */
  664. len = sanitize_line(linebuf, len, flags & ~PEM_FLAG_ONLY_B64);
  665. /* Allow leading empty or non-matching lines. */
  666. } while (strncmp(linebuf, beginstr, BEGINLEN) != 0
  667. || len < TAILLEN
  668. || strncmp(linebuf + len - TAILLEN, tailstr, TAILLEN) != 0);
  669. linebuf[len - TAILLEN] = '\0';
  670. len = len - BEGINLEN - TAILLEN + 1;
  671. *name = pem_malloc(len, flags);
  672. if (*name == NULL) {
  673. PEMerr(PEM_F_GET_NAME, ERR_R_MALLOC_FAILURE);
  674. goto err;
  675. }
  676. memcpy(*name, linebuf + BEGINLEN, len);
  677. ret = 1;
  678. err:
  679. pem_free(linebuf, flags, LINESIZE + 1);
  680. return ret;
  681. }
  682. /* Keep track of how much of a header we've seen. */
  683. enum header_status {
  684. MAYBE_HEADER,
  685. IN_HEADER,
  686. POST_HEADER
  687. };
  688. /**
  689. * Extract the optional PEM header, with details on the type of content and
  690. * any encryption used on the contents, and the bulk of the data from the bio.
  691. * The end of the header is marked by a blank line; if the end-of-input marker
  692. * is reached prior to a blank line, there is no header.
  693. *
  694. * The header and data arguments are BIO** since we may have to swap them
  695. * if there is no header, for efficiency.
  696. *
  697. * We need the name of the PEM-encoded type to verify the end string.
  698. */
  699. static int get_header_and_data(BIO *bp, BIO **header, BIO **data, char *name,
  700. unsigned int flags)
  701. {
  702. BIO *tmp = *header;
  703. char *linebuf, *p;
  704. int len, line, ret = 0, end = 0;
  705. /* 0 if not seen (yet), 1 if reading header, 2 if finished header */
  706. enum header_status got_header = MAYBE_HEADER;
  707. unsigned int flags_mask;
  708. size_t namelen;
  709. /* Need to hold trailing NUL (accounted for by BIO_gets() and the newline
  710. * that will be added by sanitize_line() (the extra '1'). */
  711. linebuf = pem_malloc(LINESIZE + 1, flags);
  712. if (linebuf == NULL) {
  713. PEMerr(PEM_F_GET_HEADER_AND_DATA, ERR_R_MALLOC_FAILURE);
  714. return 0;
  715. }
  716. for (line = 0; ; line++) {
  717. flags_mask = ~0u;
  718. len = BIO_gets(bp, linebuf, LINESIZE);
  719. if (len <= 0) {
  720. PEMerr(PEM_F_GET_HEADER_AND_DATA, PEM_R_SHORT_HEADER);
  721. goto err;
  722. }
  723. if (got_header == MAYBE_HEADER) {
  724. if (memchr(linebuf, ':', len) != NULL)
  725. got_header = IN_HEADER;
  726. }
  727. if (!strncmp(linebuf, endstr, ENDLEN) || got_header == IN_HEADER)
  728. flags_mask &= ~PEM_FLAG_ONLY_B64;
  729. len = sanitize_line(linebuf, len, flags & flags_mask);
  730. /* Check for end of header. */
  731. if (linebuf[0] == '\n') {
  732. if (got_header == POST_HEADER) {
  733. /* Another blank line is an error. */
  734. PEMerr(PEM_F_GET_HEADER_AND_DATA, PEM_R_BAD_END_LINE);
  735. goto err;
  736. }
  737. got_header = POST_HEADER;
  738. tmp = *data;
  739. continue;
  740. }
  741. /* Check for end of stream (which means there is no header). */
  742. if (strncmp(linebuf, endstr, ENDLEN) == 0) {
  743. p = linebuf + ENDLEN;
  744. namelen = strlen(name);
  745. if (strncmp(p, name, namelen) != 0 ||
  746. strncmp(p + namelen, tailstr, TAILLEN) != 0) {
  747. PEMerr(PEM_F_GET_HEADER_AND_DATA, PEM_R_BAD_END_LINE);
  748. goto err;
  749. }
  750. if (got_header == MAYBE_HEADER) {
  751. *header = *data;
  752. *data = tmp;
  753. }
  754. break;
  755. } else if (end) {
  756. /* Malformed input; short line not at end of data. */
  757. PEMerr(PEM_F_GET_HEADER_AND_DATA, PEM_R_BAD_END_LINE);
  758. goto err;
  759. }
  760. /*
  761. * Else, a line of text -- could be header or data; we don't
  762. * know yet. Just pass it through.
  763. */
  764. if (BIO_puts(tmp, linebuf) < 0)
  765. goto err;
  766. /*
  767. * Only encrypted files need the line length check applied.
  768. */
  769. if (got_header == POST_HEADER) {
  770. /* 65 includes the trailing newline */
  771. if (len > 65)
  772. goto err;
  773. if (len < 65)
  774. end = 1;
  775. }
  776. }
  777. ret = 1;
  778. err:
  779. pem_free(linebuf, flags, LINESIZE + 1);
  780. return ret;
  781. }
  782. /**
  783. * Read in PEM-formatted data from the given BIO.
  784. *
  785. * By nature of the PEM format, all content must be printable ASCII (except
  786. * for line endings). Other 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. }