pem_lib.c 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003
  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 "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, const 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. const void *x, const EVP_CIPHER *enc,
  253. const unsigned char *kstr, int klen,
  254. pem_password_cb *callback, void *u)
  255. {
  256. BIO *b;
  257. int ret;
  258. if ((b = BIO_new(BIO_s_file())) == NULL) {
  259. PEMerr(PEM_F_PEM_ASN1_WRITE, ERR_R_BUF_LIB);
  260. return 0;
  261. }
  262. BIO_set_fp(b, fp, BIO_NOCLOSE);
  263. ret = PEM_ASN1_write_bio(i2d, name, b, x, enc, kstr, klen, callback, u);
  264. BIO_free(b);
  265. return ret;
  266. }
  267. #endif
  268. int PEM_ASN1_write_bio(i2d_of_void *i2d, const char *name, BIO *bp,
  269. const void *x, const EVP_CIPHER *enc,
  270. const unsigned char *kstr, int klen,
  271. pem_password_cb *callback, void *u)
  272. {
  273. EVP_CIPHER_CTX *ctx = NULL;
  274. int dsize = 0, i = 0, j = 0, ret = 0;
  275. unsigned char *p, *data = NULL;
  276. const char *objstr = NULL;
  277. char buf[PEM_BUFSIZE];
  278. unsigned char key[EVP_MAX_KEY_LENGTH];
  279. unsigned char iv[EVP_MAX_IV_LENGTH];
  280. if (enc != NULL) {
  281. objstr = OBJ_nid2sn(EVP_CIPHER_nid(enc));
  282. if (objstr == NULL || EVP_CIPHER_iv_length(enc) == 0
  283. || EVP_CIPHER_iv_length(enc) > (int)sizeof(iv)
  284. /*
  285. * Check "Proc-Type: 4,Encrypted\nDEK-Info: objstr,hex-iv\n"
  286. * fits into buf
  287. */
  288. || (strlen(objstr) + 23 + 2 * EVP_CIPHER_iv_length(enc) + 13)
  289. > sizeof(buf)) {
  290. PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, PEM_R_UNSUPPORTED_CIPHER);
  291. goto err;
  292. }
  293. }
  294. if ((dsize = i2d(x, NULL)) < 0) {
  295. PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, ERR_R_ASN1_LIB);
  296. dsize = 0;
  297. goto err;
  298. }
  299. /* dsize + 8 bytes are needed */
  300. /* actually it needs the cipher block size extra... */
  301. data = OPENSSL_malloc((unsigned int)dsize + 20);
  302. if (data == NULL) {
  303. PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, ERR_R_MALLOC_FAILURE);
  304. goto err;
  305. }
  306. p = data;
  307. i = i2d(x, &p);
  308. if (enc != NULL) {
  309. if (kstr == NULL) {
  310. if (callback == NULL)
  311. klen = PEM_def_callback(buf, PEM_BUFSIZE, 1, u);
  312. else
  313. klen = (*callback) (buf, PEM_BUFSIZE, 1, u);
  314. if (klen <= 0) {
  315. PEMerr(PEM_F_PEM_ASN1_WRITE_BIO, PEM_R_READ_KEY);
  316. goto err;
  317. }
  318. #ifdef CHARSET_EBCDIC
  319. /* Convert the pass phrase from EBCDIC */
  320. ebcdic2ascii(buf, buf, klen);
  321. #endif
  322. kstr = (unsigned char *)buf;
  323. }
  324. if (RAND_bytes(iv, EVP_CIPHER_iv_length(enc)) <= 0) /* Generate a salt */
  325. goto err;
  326. /*
  327. * The 'iv' is used as the iv and as a salt. It is NOT taken from
  328. * the BytesToKey function
  329. */
  330. if (!EVP_BytesToKey(enc, EVP_md5(), iv, kstr, klen, 1, key, NULL))
  331. goto err;
  332. if (kstr == (unsigned char *)buf)
  333. OPENSSL_cleanse(buf, PEM_BUFSIZE);
  334. buf[0] = '\0';
  335. PEM_proc_type(buf, PEM_TYPE_ENCRYPTED);
  336. PEM_dek_info(buf, objstr, EVP_CIPHER_iv_length(enc), (char *)iv);
  337. /* k=strlen(buf); */
  338. ret = 1;
  339. if ((ctx = EVP_CIPHER_CTX_new()) == NULL
  340. || !EVP_EncryptInit_ex(ctx, enc, NULL, key, iv)
  341. || !EVP_EncryptUpdate(ctx, data, &j, data, i)
  342. || !EVP_EncryptFinal_ex(ctx, &(data[j]), &i))
  343. ret = 0;
  344. if (ret == 0)
  345. goto err;
  346. i += j;
  347. } else {
  348. ret = 1;
  349. buf[0] = '\0';
  350. }
  351. i = PEM_write_bio(bp, name, buf, data, i);
  352. if (i <= 0)
  353. ret = 0;
  354. err:
  355. OPENSSL_cleanse(key, sizeof(key));
  356. OPENSSL_cleanse(iv, sizeof(iv));
  357. EVP_CIPHER_CTX_free(ctx);
  358. OPENSSL_cleanse(buf, PEM_BUFSIZE);
  359. OPENSSL_clear_free(data, (unsigned int)dsize);
  360. return ret;
  361. }
  362. int PEM_do_header(EVP_CIPHER_INFO *cipher, unsigned char *data, long *plen,
  363. pem_password_cb *callback, void *u)
  364. {
  365. int ok;
  366. int keylen;
  367. long len = *plen;
  368. int ilen = (int) len; /* EVP_DecryptUpdate etc. take int lengths */
  369. EVP_CIPHER_CTX *ctx;
  370. unsigned char key[EVP_MAX_KEY_LENGTH];
  371. char buf[PEM_BUFSIZE];
  372. #if LONG_MAX > INT_MAX
  373. /* Check that we did not truncate the length */
  374. if (len > INT_MAX) {
  375. PEMerr(PEM_F_PEM_DO_HEADER, PEM_R_HEADER_TOO_LONG);
  376. return 0;
  377. }
  378. #endif
  379. if (cipher->cipher == NULL)
  380. return 1;
  381. if (callback == NULL)
  382. keylen = PEM_def_callback(buf, PEM_BUFSIZE, 0, u);
  383. else
  384. keylen = callback(buf, PEM_BUFSIZE, 0, u);
  385. if (keylen < 0) {
  386. PEMerr(PEM_F_PEM_DO_HEADER, PEM_R_BAD_PASSWORD_READ);
  387. return 0;
  388. }
  389. #ifdef CHARSET_EBCDIC
  390. /* Convert the pass phrase from EBCDIC */
  391. ebcdic2ascii(buf, buf, keylen);
  392. #endif
  393. if (!EVP_BytesToKey(cipher->cipher, EVP_md5(), &(cipher->iv[0]),
  394. (unsigned char *)buf, keylen, 1, key, NULL))
  395. return 0;
  396. ctx = EVP_CIPHER_CTX_new();
  397. if (ctx == NULL)
  398. return 0;
  399. ok = EVP_DecryptInit_ex(ctx, cipher->cipher, NULL, key, &(cipher->iv[0]));
  400. if (ok)
  401. ok = EVP_DecryptUpdate(ctx, data, &ilen, data, ilen);
  402. if (ok) {
  403. /* Squirrel away the length of data decrypted so far. */
  404. *plen = ilen;
  405. ok = EVP_DecryptFinal_ex(ctx, &(data[ilen]), &ilen);
  406. }
  407. if (ok)
  408. *plen += ilen;
  409. else
  410. PEMerr(PEM_F_PEM_DO_HEADER, PEM_R_BAD_DECRYPT);
  411. EVP_CIPHER_CTX_free(ctx);
  412. OPENSSL_cleanse((char *)buf, sizeof(buf));
  413. OPENSSL_cleanse((char *)key, sizeof(key));
  414. return ok;
  415. }
  416. /*
  417. * This implements a very limited PEM header parser that does not support the
  418. * full grammar of rfc1421. In particular, folded headers are not supported,
  419. * nor is additional whitespace.
  420. *
  421. * A robust implementation would make use of a library that turns the headers
  422. * into a BIO from which one folded line is read at a time, and is then split
  423. * into a header label and content. We would then parse the content of the
  424. * headers we care about. This is overkill for just this limited use-case, but
  425. * presumably we also parse rfc822-style headers for S/MIME, so a common
  426. * abstraction might well be more generally useful.
  427. */
  428. int PEM_get_EVP_CIPHER_INFO(char *header, EVP_CIPHER_INFO *cipher)
  429. {
  430. static const char ProcType[] = "Proc-Type:";
  431. static const char ENCRYPTED[] = "ENCRYPTED";
  432. static const char DEKInfo[] = "DEK-Info:";
  433. const EVP_CIPHER *enc = NULL;
  434. int ivlen;
  435. char *dekinfostart, c;
  436. cipher->cipher = NULL;
  437. memset(cipher->iv, 0, sizeof(cipher->iv));
  438. if ((header == NULL) || (*header == '\0') || (*header == '\n'))
  439. return 1;
  440. if (strncmp(header, ProcType, sizeof(ProcType)-1) != 0) {
  441. PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_NOT_PROC_TYPE);
  442. return 0;
  443. }
  444. header += sizeof(ProcType)-1;
  445. header += strspn(header, " \t");
  446. if (*header++ != '4' || *header++ != ',')
  447. return 0;
  448. header += strspn(header, " \t");
  449. /* We expect "ENCRYPTED" followed by optional white-space + line break */
  450. if (strncmp(header, ENCRYPTED, sizeof(ENCRYPTED)-1) != 0 ||
  451. strspn(header+sizeof(ENCRYPTED)-1, " \t\r\n") == 0) {
  452. PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_NOT_ENCRYPTED);
  453. return 0;
  454. }
  455. header += sizeof(ENCRYPTED)-1;
  456. header += strspn(header, " \t\r");
  457. if (*header++ != '\n') {
  458. PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_SHORT_HEADER);
  459. return 0;
  460. }
  461. /*-
  462. * https://tools.ietf.org/html/rfc1421#section-4.6.1.3
  463. * We expect "DEK-Info: algo[,hex-parameters]"
  464. */
  465. if (strncmp(header, DEKInfo, sizeof(DEKInfo)-1) != 0) {
  466. PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_NOT_DEK_INFO);
  467. return 0;
  468. }
  469. header += sizeof(DEKInfo)-1;
  470. header += strspn(header, " \t");
  471. /*
  472. * DEK-INFO is a comma-separated combination of algorithm name and optional
  473. * parameters.
  474. */
  475. dekinfostart = header;
  476. header += strcspn(header, " \t,");
  477. c = *header;
  478. *header = '\0';
  479. cipher->cipher = enc = EVP_get_cipherbyname(dekinfostart);
  480. *header = c;
  481. header += strspn(header, " \t");
  482. if (enc == NULL) {
  483. PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_UNSUPPORTED_ENCRYPTION);
  484. return 0;
  485. }
  486. ivlen = EVP_CIPHER_iv_length(enc);
  487. if (ivlen > 0 && *header++ != ',') {
  488. PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_MISSING_DEK_IV);
  489. return 0;
  490. } else if (ivlen == 0 && *header == ',') {
  491. PEMerr(PEM_F_PEM_GET_EVP_CIPHER_INFO, PEM_R_UNEXPECTED_DEK_IV);
  492. return 0;
  493. }
  494. if (!load_iv(&header, cipher->iv, EVP_CIPHER_iv_length(enc)))
  495. return 0;
  496. return 1;
  497. }
  498. static int load_iv(char **fromp, unsigned char *to, int num)
  499. {
  500. int v, i;
  501. char *from;
  502. from = *fromp;
  503. for (i = 0; i < num; i++)
  504. to[i] = 0;
  505. num *= 2;
  506. for (i = 0; i < num; i++) {
  507. v = OPENSSL_hexchar2int(*from);
  508. if (v < 0) {
  509. PEMerr(PEM_F_LOAD_IV, PEM_R_BAD_IV_CHARS);
  510. return 0;
  511. }
  512. from++;
  513. to[i / 2] |= v << (long)((!(i & 1)) * 4);
  514. }
  515. *fromp = from;
  516. return 1;
  517. }
  518. #ifndef OPENSSL_NO_STDIO
  519. int PEM_write(FILE *fp, const char *name, const char *header,
  520. const unsigned char *data, long len)
  521. {
  522. BIO *b;
  523. int ret;
  524. if ((b = BIO_new(BIO_s_file())) == NULL) {
  525. PEMerr(PEM_F_PEM_WRITE, ERR_R_BUF_LIB);
  526. return 0;
  527. }
  528. BIO_set_fp(b, fp, BIO_NOCLOSE);
  529. ret = PEM_write_bio(b, name, header, data, len);
  530. BIO_free(b);
  531. return ret;
  532. }
  533. #endif
  534. int PEM_write_bio(BIO *bp, const char *name, const char *header,
  535. const unsigned char *data, long len)
  536. {
  537. int nlen, n, i, j, outl;
  538. unsigned char *buf = NULL;
  539. EVP_ENCODE_CTX *ctx = EVP_ENCODE_CTX_new();
  540. int reason = ERR_R_BUF_LIB;
  541. int retval = 0;
  542. if (ctx == NULL) {
  543. reason = ERR_R_MALLOC_FAILURE;
  544. goto err;
  545. }
  546. EVP_EncodeInit(ctx);
  547. nlen = strlen(name);
  548. if ((BIO_write(bp, "-----BEGIN ", 11) != 11) ||
  549. (BIO_write(bp, name, nlen) != nlen) ||
  550. (BIO_write(bp, "-----\n", 6) != 6))
  551. goto err;
  552. i = strlen(header);
  553. if (i > 0) {
  554. if ((BIO_write(bp, header, i) != i) || (BIO_write(bp, "\n", 1) != 1))
  555. goto err;
  556. }
  557. buf = OPENSSL_malloc(PEM_BUFSIZE * 8);
  558. if (buf == NULL) {
  559. reason = ERR_R_MALLOC_FAILURE;
  560. goto err;
  561. }
  562. i = j = 0;
  563. while (len > 0) {
  564. n = (int)((len > (PEM_BUFSIZE * 5)) ? (PEM_BUFSIZE * 5) : len);
  565. if (!EVP_EncodeUpdate(ctx, buf, &outl, &(data[j]), n))
  566. goto err;
  567. if ((outl) && (BIO_write(bp, (char *)buf, outl) != outl))
  568. goto err;
  569. i += outl;
  570. len -= n;
  571. j += n;
  572. }
  573. EVP_EncodeFinal(ctx, buf, &outl);
  574. if ((outl > 0) && (BIO_write(bp, (char *)buf, outl) != outl))
  575. goto err;
  576. if ((BIO_write(bp, "-----END ", 9) != 9) ||
  577. (BIO_write(bp, name, nlen) != nlen) ||
  578. (BIO_write(bp, "-----\n", 6) != 6))
  579. goto err;
  580. retval = i + outl;
  581. err:
  582. if (retval == 0)
  583. PEMerr(PEM_F_PEM_WRITE_BIO, reason);
  584. EVP_ENCODE_CTX_free(ctx);
  585. OPENSSL_clear_free(buf, PEM_BUFSIZE * 8);
  586. return retval;
  587. }
  588. #ifndef OPENSSL_NO_STDIO
  589. int PEM_read(FILE *fp, char **name, char **header, unsigned char **data,
  590. long *len)
  591. {
  592. BIO *b;
  593. int ret;
  594. if ((b = BIO_new(BIO_s_file())) == NULL) {
  595. PEMerr(PEM_F_PEM_READ, ERR_R_BUF_LIB);
  596. return 0;
  597. }
  598. BIO_set_fp(b, fp, BIO_NOCLOSE);
  599. ret = PEM_read_bio(b, name, header, data, len);
  600. BIO_free(b);
  601. return ret;
  602. }
  603. #endif
  604. /* Some helpers for PEM_read_bio_ex(). */
  605. static int sanitize_line(char *linebuf, int len, unsigned int flags, int first_call)
  606. {
  607. int i;
  608. if (first_call) {
  609. /* Other BOMs imply unsupported multibyte encoding,
  610. * so don't strip them and let the error raise */
  611. const unsigned char utf8_bom[3] = {0xEF, 0xBB, 0xBF};
  612. if (len > 3 && memcmp(linebuf, utf8_bom, 3) == 0) {
  613. memmove(linebuf, linebuf + 3, len - 3);
  614. linebuf[len - 3] = 0;
  615. len -= 3;
  616. }
  617. }
  618. if (flags & PEM_FLAG_EAY_COMPATIBLE) {
  619. /* Strip trailing whitespace */
  620. while ((len >= 0) && (linebuf[len] <= ' '))
  621. len--;
  622. /* Go back to whitespace before applying uniform line ending. */
  623. len++;
  624. } else if (flags & PEM_FLAG_ONLY_B64) {
  625. for (i = 0; i < len; ++i) {
  626. if (!ossl_isbase64(linebuf[i]) || linebuf[i] == '\n'
  627. || linebuf[i] == '\r')
  628. break;
  629. }
  630. len = i;
  631. } else {
  632. /* EVP_DecodeBlock strips leading and trailing whitespace, so just strip
  633. * control characters in-place and let everything through. */
  634. for (i = 0; i < len; ++i) {
  635. if (linebuf[i] == '\n' || linebuf[i] == '\r')
  636. break;
  637. if (ossl_iscntrl(linebuf[i]))
  638. linebuf[i] = ' ';
  639. }
  640. len = i;
  641. }
  642. /* The caller allocated LINESIZE+1, so this is safe. */
  643. linebuf[len++] = '\n';
  644. linebuf[len] = '\0';
  645. return len;
  646. }
  647. #define LINESIZE 255
  648. /* Note trailing spaces for begin and end. */
  649. static const char beginstr[] = "-----BEGIN ";
  650. static const char endstr[] = "-----END ";
  651. static const char tailstr[] = "-----\n";
  652. #define BEGINLEN ((int)(sizeof(beginstr) - 1))
  653. #define ENDLEN ((int)(sizeof(endstr) - 1))
  654. #define TAILLEN ((int)(sizeof(tailstr) - 1))
  655. static int get_name(BIO *bp, char **name, unsigned int flags)
  656. {
  657. char *linebuf;
  658. int ret = 0;
  659. int len;
  660. int first_call = 1;
  661. /*
  662. * Need to hold trailing NUL (accounted for by BIO_gets() and the newline
  663. * that will be added by sanitize_line() (the extra '1').
  664. */
  665. linebuf = pem_malloc(LINESIZE + 1, flags);
  666. if (linebuf == NULL) {
  667. PEMerr(PEM_F_GET_NAME, ERR_R_MALLOC_FAILURE);
  668. return 0;
  669. }
  670. do {
  671. len = BIO_gets(bp, linebuf, LINESIZE);
  672. if (len <= 0) {
  673. PEMerr(PEM_F_GET_NAME, PEM_R_NO_START_LINE);
  674. goto err;
  675. }
  676. /* Strip trailing garbage and standardize ending. */
  677. len = sanitize_line(linebuf, len, flags & ~PEM_FLAG_ONLY_B64, first_call);
  678. first_call = 0;
  679. /* Allow leading empty or non-matching lines. */
  680. } while (strncmp(linebuf, beginstr, BEGINLEN) != 0
  681. || len < TAILLEN
  682. || strncmp(linebuf + len - TAILLEN, tailstr, TAILLEN) != 0);
  683. linebuf[len - TAILLEN] = '\0';
  684. len = len - BEGINLEN - TAILLEN + 1;
  685. *name = pem_malloc(len, flags);
  686. if (*name == NULL) {
  687. PEMerr(PEM_F_GET_NAME, ERR_R_MALLOC_FAILURE);
  688. goto err;
  689. }
  690. memcpy(*name, linebuf + BEGINLEN, len);
  691. ret = 1;
  692. err:
  693. pem_free(linebuf, flags, LINESIZE + 1);
  694. return ret;
  695. }
  696. /* Keep track of how much of a header we've seen. */
  697. enum header_status {
  698. MAYBE_HEADER,
  699. IN_HEADER,
  700. POST_HEADER
  701. };
  702. /**
  703. * Extract the optional PEM header, with details on the type of content and
  704. * any encryption used on the contents, and the bulk of the data from the bio.
  705. * The end of the header is marked by a blank line; if the end-of-input marker
  706. * is reached prior to a blank line, there is no header.
  707. *
  708. * The header and data arguments are BIO** since we may have to swap them
  709. * if there is no header, for efficiency.
  710. *
  711. * We need the name of the PEM-encoded type to verify the end string.
  712. */
  713. static int get_header_and_data(BIO *bp, BIO **header, BIO **data, char *name,
  714. unsigned int flags)
  715. {
  716. BIO *tmp = *header;
  717. char *linebuf, *p;
  718. int len, line, ret = 0, end = 0;
  719. /* 0 if not seen (yet), 1 if reading header, 2 if finished header */
  720. enum header_status got_header = MAYBE_HEADER;
  721. unsigned int flags_mask;
  722. size_t namelen;
  723. /* Need to hold trailing NUL (accounted for by BIO_gets() and the newline
  724. * that will be added by sanitize_line() (the extra '1'). */
  725. linebuf = pem_malloc(LINESIZE + 1, flags);
  726. if (linebuf == NULL) {
  727. PEMerr(PEM_F_GET_HEADER_AND_DATA, ERR_R_MALLOC_FAILURE);
  728. return 0;
  729. }
  730. for (line = 0; ; line++) {
  731. flags_mask = ~0u;
  732. len = BIO_gets(bp, linebuf, LINESIZE);
  733. if (len <= 0) {
  734. PEMerr(PEM_F_GET_HEADER_AND_DATA, PEM_R_SHORT_HEADER);
  735. goto err;
  736. }
  737. if (got_header == MAYBE_HEADER) {
  738. if (memchr(linebuf, ':', len) != NULL)
  739. got_header = IN_HEADER;
  740. }
  741. if (!strncmp(linebuf, endstr, ENDLEN) || got_header == IN_HEADER)
  742. flags_mask &= ~PEM_FLAG_ONLY_B64;
  743. len = sanitize_line(linebuf, len, flags & flags_mask, 0);
  744. /* Check for end of header. */
  745. if (linebuf[0] == '\n') {
  746. if (got_header == POST_HEADER) {
  747. /* Another blank line is an error. */
  748. PEMerr(PEM_F_GET_HEADER_AND_DATA, PEM_R_BAD_END_LINE);
  749. goto err;
  750. }
  751. got_header = POST_HEADER;
  752. tmp = *data;
  753. continue;
  754. }
  755. /* Check for end of stream (which means there is no header). */
  756. if (strncmp(linebuf, endstr, ENDLEN) == 0) {
  757. p = linebuf + ENDLEN;
  758. namelen = strlen(name);
  759. if (strncmp(p, name, namelen) != 0 ||
  760. strncmp(p + namelen, tailstr, TAILLEN) != 0) {
  761. PEMerr(PEM_F_GET_HEADER_AND_DATA, PEM_R_BAD_END_LINE);
  762. goto err;
  763. }
  764. if (got_header == MAYBE_HEADER) {
  765. *header = *data;
  766. *data = tmp;
  767. }
  768. break;
  769. } else if (end) {
  770. /* Malformed input; short line not at end of data. */
  771. PEMerr(PEM_F_GET_HEADER_AND_DATA, PEM_R_BAD_END_LINE);
  772. goto err;
  773. }
  774. /*
  775. * Else, a line of text -- could be header or data; we don't
  776. * know yet. Just pass it through.
  777. */
  778. if (BIO_puts(tmp, linebuf) < 0)
  779. goto err;
  780. /*
  781. * Only encrypted files need the line length check applied.
  782. */
  783. if (got_header == POST_HEADER) {
  784. /* 65 includes the trailing newline */
  785. if (len > 65)
  786. goto err;
  787. if (len < 65)
  788. end = 1;
  789. }
  790. }
  791. ret = 1;
  792. err:
  793. pem_free(linebuf, flags, LINESIZE + 1);
  794. return ret;
  795. }
  796. /**
  797. * Read in PEM-formatted data from the given BIO.
  798. *
  799. * By nature of the PEM format, all content must be printable ASCII (except
  800. * for line endings). Other characters are malformed input and will be rejected.
  801. */
  802. int PEM_read_bio_ex(BIO *bp, char **name_out, char **header,
  803. unsigned char **data, long *len_out, unsigned int flags)
  804. {
  805. EVP_ENCODE_CTX *ctx = EVP_ENCODE_CTX_new();
  806. const BIO_METHOD *bmeth;
  807. BIO *headerB = NULL, *dataB = NULL;
  808. char *name = NULL;
  809. int len, taillen, headerlen, ret = 0;
  810. BUF_MEM * buf_mem;
  811. if (ctx == NULL) {
  812. PEMerr(PEM_F_PEM_READ_BIO_EX, ERR_R_MALLOC_FAILURE);
  813. return 0;
  814. }
  815. *len_out = 0;
  816. *name_out = *header = NULL;
  817. *data = NULL;
  818. if ((flags & PEM_FLAG_EAY_COMPATIBLE) && (flags & PEM_FLAG_ONLY_B64)) {
  819. /* These two are mutually incompatible; bail out. */
  820. PEMerr(PEM_F_PEM_READ_BIO_EX, ERR_R_PASSED_INVALID_ARGUMENT);
  821. goto end;
  822. }
  823. bmeth = (flags & PEM_FLAG_SECURE) ? BIO_s_secmem() : BIO_s_mem();
  824. headerB = BIO_new(bmeth);
  825. dataB = BIO_new(bmeth);
  826. if (headerB == NULL || dataB == NULL) {
  827. PEMerr(PEM_F_PEM_READ_BIO_EX, ERR_R_MALLOC_FAILURE);
  828. goto end;
  829. }
  830. if (!get_name(bp, &name, flags))
  831. goto end;
  832. if (!get_header_and_data(bp, &headerB, &dataB, name, flags))
  833. goto end;
  834. EVP_DecodeInit(ctx);
  835. BIO_get_mem_ptr(dataB, &buf_mem);
  836. len = buf_mem->length;
  837. if (EVP_DecodeUpdate(ctx, (unsigned char*)buf_mem->data, &len,
  838. (unsigned char*)buf_mem->data, len) < 0
  839. || EVP_DecodeFinal(ctx, (unsigned char*)&(buf_mem->data[len]),
  840. &taillen) < 0) {
  841. PEMerr(PEM_F_PEM_READ_BIO_EX, PEM_R_BAD_BASE64_DECODE);
  842. goto end;
  843. }
  844. len += taillen;
  845. buf_mem->length = len;
  846. /* There was no data in the PEM file; avoid malloc(0). */
  847. if (len == 0)
  848. goto end;
  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. pem_free(*data, flags, 0);
  855. goto end;
  856. }
  857. BIO_read(headerB, *header, headerlen);
  858. (*header)[headerlen] = '\0';
  859. BIO_read(dataB, *data, len);
  860. *len_out = len;
  861. *name_out = name;
  862. name = NULL;
  863. ret = 1;
  864. end:
  865. EVP_ENCODE_CTX_free(ctx);
  866. pem_free(name, flags, 0);
  867. BIO_free(headerB);
  868. BIO_free(dataB);
  869. return ret;
  870. }
  871. int PEM_read_bio(BIO *bp, char **name, char **header, unsigned char **data,
  872. long *len)
  873. {
  874. return PEM_read_bio_ex(bp, name, header, data, len, PEM_FLAG_EAY_COMPATIBLE);
  875. }
  876. /*
  877. * Check pem string and return prefix length. If for example the pem_str ==
  878. * "RSA PRIVATE KEY" and suffix = "PRIVATE KEY" the return value is 3 for the
  879. * string "RSA".
  880. */
  881. int pem_check_suffix(const char *pem_str, const char *suffix)
  882. {
  883. int pem_len = strlen(pem_str);
  884. int suffix_len = strlen(suffix);
  885. const char *p;
  886. if (suffix_len + 1 >= pem_len)
  887. return 0;
  888. p = pem_str + pem_len - suffix_len;
  889. if (strcmp(p, suffix))
  890. return 0;
  891. p--;
  892. if (*p != ' ')
  893. return 0;
  894. return p - pem_str;
  895. }