pem_lib.c 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  1. /*
  2. * Copyright 1995-2023 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 "crypto/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 "crypto/asn1.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 = header != NULL ? strlen(header) : 0;
  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, ret = 0, end = 0, prev_partial_line_read = 0, partial_line_read = 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 (;;) {
  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_BAD_END_LINE);
  721. goto err;
  722. }
  723. /*
  724. * Check if line has been read completely or if only part of the line
  725. * has been read. Keep the previous value to ignore newlines that
  726. * appear due to reading a line up until the char before the newline.
  727. */
  728. prev_partial_line_read = partial_line_read;
  729. partial_line_read = len == LINESIZE-1 && linebuf[LINESIZE-2] != '\n';
  730. if (got_header == MAYBE_HEADER) {
  731. if (memchr(linebuf, ':', len) != NULL)
  732. got_header = IN_HEADER;
  733. }
  734. if (!strncmp(linebuf, endstr, ENDLEN) || got_header == IN_HEADER)
  735. flags_mask &= ~PEM_FLAG_ONLY_B64;
  736. len = sanitize_line(linebuf, len, flags & flags_mask);
  737. /* Check for end of header. */
  738. if (linebuf[0] == '\n') {
  739. /*
  740. * If previous line has been read only partially this newline is a
  741. * regular newline at the end of a line and not an empty line.
  742. */
  743. if (!prev_partial_line_read) {
  744. if (got_header == POST_HEADER) {
  745. /* Another blank line is an error. */
  746. PEMerr(PEM_F_GET_HEADER_AND_DATA, PEM_R_BAD_END_LINE);
  747. goto err;
  748. }
  749. got_header = POST_HEADER;
  750. tmp = *data;
  751. }
  752. continue;
  753. }
  754. /* Check for end of stream (which means there is no header). */
  755. if (strncmp(linebuf, endstr, ENDLEN) == 0) {
  756. p = linebuf + ENDLEN;
  757. namelen = strlen(name);
  758. if (strncmp(p, name, namelen) != 0 ||
  759. strncmp(p + namelen, tailstr, TAILLEN) != 0) {
  760. PEMerr(PEM_F_GET_HEADER_AND_DATA, PEM_R_BAD_END_LINE);
  761. goto err;
  762. }
  763. if (got_header == MAYBE_HEADER) {
  764. *header = *data;
  765. *data = tmp;
  766. }
  767. break;
  768. } else if (end) {
  769. /* Malformed input; short line not at end of data. */
  770. PEMerr(PEM_F_GET_HEADER_AND_DATA, PEM_R_BAD_END_LINE);
  771. goto err;
  772. }
  773. /*
  774. * Else, a line of text -- could be header or data; we don't
  775. * know yet. Just pass it through.
  776. */
  777. if (BIO_puts(tmp, linebuf) < 0)
  778. goto err;
  779. /*
  780. * Only encrypted files need the line length check applied.
  781. */
  782. if (got_header == POST_HEADER) {
  783. /* 65 includes the trailing newline */
  784. if (len > 65)
  785. goto err;
  786. if (len < 65)
  787. end = 1;
  788. }
  789. }
  790. ret = 1;
  791. err:
  792. pem_free(linebuf, flags, LINESIZE + 1);
  793. return ret;
  794. }
  795. /**
  796. * Read in PEM-formatted data from the given BIO.
  797. *
  798. * By nature of the PEM format, all content must be printable ASCII (except
  799. * for line endings). Other characters are malformed input and will be rejected.
  800. */
  801. int PEM_read_bio_ex(BIO *bp, char **name_out, char **header,
  802. unsigned char **data, long *len_out, unsigned int flags)
  803. {
  804. EVP_ENCODE_CTX *ctx = NULL;
  805. const BIO_METHOD *bmeth;
  806. BIO *headerB = NULL, *dataB = NULL;
  807. char *name = NULL;
  808. int len, taillen, headerlen, ret = 0;
  809. BUF_MEM * buf_mem;
  810. *len_out = 0;
  811. *name_out = *header = NULL;
  812. *data = NULL;
  813. if ((flags & PEM_FLAG_EAY_COMPATIBLE) && (flags & PEM_FLAG_ONLY_B64)) {
  814. /* These two are mutually incompatible; bail out. */
  815. PEMerr(PEM_F_PEM_READ_BIO_EX, ERR_R_PASSED_INVALID_ARGUMENT);
  816. goto end;
  817. }
  818. bmeth = (flags & PEM_FLAG_SECURE) ? BIO_s_secmem() : BIO_s_mem();
  819. headerB = BIO_new(bmeth);
  820. dataB = BIO_new(bmeth);
  821. if (headerB == NULL || dataB == NULL) {
  822. PEMerr(PEM_F_PEM_READ_BIO_EX, ERR_R_MALLOC_FAILURE);
  823. goto end;
  824. }
  825. if (!get_name(bp, &name, flags))
  826. goto end;
  827. if (!get_header_and_data(bp, &headerB, &dataB, name, flags))
  828. goto end;
  829. BIO_get_mem_ptr(dataB, &buf_mem);
  830. len = buf_mem->length;
  831. /* There was no data in the PEM file */
  832. if (len == 0)
  833. goto end;
  834. ctx = EVP_ENCODE_CTX_new();
  835. if (ctx == NULL) {
  836. PEMerr(PEM_F_PEM_READ_BIO_EX, ERR_R_MALLOC_FAILURE);
  837. goto end;
  838. }
  839. EVP_DecodeInit(ctx);
  840. if (EVP_DecodeUpdate(ctx, (unsigned char*)buf_mem->data, &len,
  841. (unsigned char*)buf_mem->data, len) < 0
  842. || EVP_DecodeFinal(ctx, (unsigned char*)&(buf_mem->data[len]),
  843. &taillen) < 0) {
  844. PEMerr(PEM_F_PEM_READ_BIO_EX, PEM_R_BAD_BASE64_DECODE);
  845. goto end;
  846. }
  847. len += taillen;
  848. buf_mem->length = len;
  849. headerlen = BIO_get_mem_data(headerB, NULL);
  850. *header = pem_malloc(headerlen + 1, flags);
  851. *data = pem_malloc(len, flags);
  852. if (*header == NULL || *data == NULL) {
  853. pem_free(*header, flags, 0);
  854. *header = NULL;
  855. pem_free(*data, flags, 0);
  856. *data = NULL;
  857. goto end;
  858. }
  859. BIO_read(headerB, *header, headerlen);
  860. (*header)[headerlen] = '\0';
  861. BIO_read(dataB, *data, len);
  862. *len_out = len;
  863. *name_out = name;
  864. name = NULL;
  865. ret = 1;
  866. end:
  867. EVP_ENCODE_CTX_free(ctx);
  868. pem_free(name, flags, 0);
  869. BIO_free(headerB);
  870. BIO_free(dataB);
  871. return ret;
  872. }
  873. int PEM_read_bio(BIO *bp, char **name, char **header, unsigned char **data,
  874. long *len)
  875. {
  876. return PEM_read_bio_ex(bp, name, header, data, len, PEM_FLAG_EAY_COMPATIBLE);
  877. }
  878. /*
  879. * Check pem string and return prefix length. If for example the pem_str ==
  880. * "RSA PRIVATE KEY" and suffix = "PRIVATE KEY" the return value is 3 for the
  881. * string "RSA".
  882. */
  883. int pem_check_suffix(const char *pem_str, const char *suffix)
  884. {
  885. int pem_len = strlen(pem_str);
  886. int suffix_len = strlen(suffix);
  887. const char *p;
  888. if (suffix_len + 1 >= pem_len)
  889. return 0;
  890. p = pem_str + pem_len - suffix_len;
  891. if (strcmp(p, suffix))
  892. return 0;
  893. p--;
  894. if (*p != ' ')
  895. return 0;
  896. return p - pem_str;
  897. }