pem_lib.c 30 KB

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