1
0

pem.c 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044
  1. /* pem.c
  2. *
  3. * Copyright (C) 2006-2023 wolfSSL Inc.
  4. *
  5. * This file is part of wolfSSL.
  6. *
  7. * wolfSSL is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * wolfSSL is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
  20. */
  21. #ifdef HAVE_CONFIG_H
  22. #include <config.h>
  23. #endif
  24. #ifndef WOLFSSL_USER_SETTINGS
  25. #include <wolfssl/options.h>
  26. #endif
  27. #include <wolfssl/wolfcrypt/settings.h>
  28. #include <wolfssl/wolfcrypt/asn_public.h>
  29. #include <wolfssl/wolfcrypt/coding.h>
  30. #include <wolfssl/wolfcrypt/error-crypt.h>
  31. #include <wolfssl/wolfcrypt/random.h>
  32. #include <wolfssl/wolfcrypt/wc_encrypt.h>
  33. #ifdef DEBUG_WOLFSSL
  34. #include <wolfssl/wolfcrypt/logging.h>
  35. #endif
  36. #include <stdio.h>
  37. #if defined(WOLFSSL_PEM_TO_DER) && !defined(NO_FILESYSTEM)
  38. /* Increment allocated data by this much. */
  39. #define DATA_INC_LEN 256
  40. /* Maximum block size of a cipher. */
  41. #define BLOCK_SIZE_MAX 16
  42. /* Maximum PEM type string length. */
  43. #define PEM_TYPE_MAX_LEN 32
  44. /* Maximum salt length. */
  45. #define SALT_MAX_LEN 64
  46. /* Default PBE iterations. */
  47. #define DEFAULT_ITERATIONS 100000
  48. /* Maps a string to a value. */
  49. typedef struct Str2Val {
  50. /* String to be matched. */
  51. const char* string;
  52. /* Corresponding value. */
  53. int val;
  54. } String2Val;
  55. /* Get the value corresponding to the string.
  56. *
  57. * @param [in] map Map of strings to values.
  58. * @param [in] len Number of entries in map.
  59. * @param [in] str String to look-up.
  60. * @param [out] val Value corresponding to string.
  61. * @return 0 on success.
  62. * @return 1 on failure.
  63. */
  64. static int StringToVal(const String2Val* map, int len, const char* str,
  65. int* val)
  66. {
  67. int ret = 1;
  68. int i;
  69. for (i = 0; i < len; i++) {
  70. if (strcmp(str, map[i].string) == 0) {
  71. *val = map[i].val;
  72. ret = 0;
  73. break;
  74. }
  75. }
  76. return ret;
  77. }
  78. /* Read the contents of a file into a dynamically allocated buffer.
  79. *
  80. * Uses realloc as input may be stdin.
  81. *
  82. * @param [in] fp File pointer to read from.
  83. * @param [out] pdata Pointer to data.
  84. * @param [out] plen Pointer to length.
  85. * @return 0 on success.
  86. * @return 1 on failure.
  87. */
  88. static int pemApp_ReadFile(FILE* fp, unsigned char** pdata, word32* plen)
  89. {
  90. int ret = 0;
  91. word32 len = 0;
  92. size_t read_len;
  93. /* Allocate a minimum amount. */
  94. unsigned char* data = (unsigned char*)malloc(DATA_INC_LEN + BLOCK_SIZE_MAX);
  95. if (data != NULL) {
  96. /* Read more data. */
  97. while ((read_len = fread(data + len, 1, DATA_INC_LEN, fp)) != 0) {
  98. unsigned char* p;
  99. /* Add read data amount to length. */
  100. len += (word32)read_len;
  101. /* Stop if we are at end-of-file. */
  102. if (feof(fp)) {
  103. break;
  104. }
  105. /* Make space for more data to be added to buffer. */
  106. p = (unsigned char*)realloc(data, len + DATA_INC_LEN +
  107. BLOCK_SIZE_MAX);
  108. if (p == NULL) {
  109. /* Reallocation failed - free current buffer. */
  110. free(data);
  111. data = NULL;
  112. break;
  113. }
  114. /* Set data to new pointer. */
  115. data = p;
  116. }
  117. /* Done with file. */
  118. fclose(fp);
  119. }
  120. if (data != NULL) {
  121. /* Return data and length. */
  122. *pdata = data;
  123. *plen = len;
  124. }
  125. else {
  126. /* Failed to allocate data. */
  127. ret = MEMORY_E;
  128. }
  129. return ret;
  130. }
  131. /* Write the data to the file.
  132. *
  133. * @param [in] fp File pointer to write to.
  134. * @param [in] data Data to write.
  135. * @param [in] len Length of data to write in bytes.
  136. * @return 0 on success.
  137. * @return 1 on failure.
  138. */
  139. static int WriteFile(FILE* fp, const char* data, word32 len)
  140. {
  141. int ret = 0;
  142. /* Write data to file. */
  143. if (fwrite(data, 1, len, fp) != len) {
  144. /* Not all data was written. */
  145. fprintf(stderr, "Failed to write\n");
  146. ret = 1;
  147. }
  148. /* Close file. */
  149. fclose(fp);
  150. return ret;
  151. }
  152. /* List of known PEM types. */
  153. static const String2Val type_map[] = {
  154. { "CERTIFICATE" , CERT_TYPE },
  155. #ifdef WOLFSSL_CERT_REQ
  156. { "CERTIFICATE REQUEST" , CERTREQ_TYPE },
  157. #endif
  158. #ifndef NO_DH
  159. { "DH PARAMETERS" , DH_PARAM_TYPE },
  160. { "X9.42 DH PARAMETERS" , X942_PARAM_TYPE },
  161. #endif
  162. #ifndef NO_DSA
  163. { "DSA PARAMETERS" , DSA_PARAM_TYPE },
  164. #endif
  165. #ifdef HAVE_CRL
  166. { "X509 CRL" , CRL_TYPE },
  167. #endif
  168. { "RSA PRIVATE KEY" , RSA_TYPE },
  169. { "RSA PUBLIC KEY" , RSA_PUBLICKEY_TYPE },
  170. { "PRIVATE KEY" , PKCS8_PRIVATEKEY_TYPE },
  171. { "ENCRYPTED PRIVATE KEY", PKCS8_ENC_PRIVATEKEY_TYPE },
  172. #ifdef HAVE_ECC
  173. { "EC PRIVATE KEY" , ECC_PRIVATEKEY_TYPE },
  174. #ifdef OPENSSL_EXTRA
  175. { "EC PARAMETERS" , ECC_PARAM_TYPE },
  176. #endif /* OPENSSL_EXTRA */
  177. #endif /* HAVE_ECC */
  178. #ifndef NO_DSA
  179. { "DSA PRIVATE KEY" , DSA_PRIVATEKEY_TYPE },
  180. #endif
  181. { "PUBLIC KEY" , ECC_PUBLICKEY_TYPE },
  182. #if defined(HAVE_ED25519) || defined(HAVE_ED448)
  183. { "EDDSA PRIVATE KEY" , EDDSA_PRIVATEKEY_TYPE },
  184. #endif
  185. };
  186. /* Number of entries in PEM type map. */
  187. #define TYPE_MAP_LEN ((int)(sizeof(type_map) / sizeof(*type_map)))
  188. /* Convert string to PEM type value.
  189. *
  190. * @param [in] str PEM type as a string.
  191. * @param [out] type PEM type as a value.
  192. * @return 0 on success.
  193. * @return 1 on failure.
  194. */
  195. static int StringToType(const char* str, int* type)
  196. {
  197. int ret = StringToVal(type_map, TYPE_MAP_LEN, str, type);
  198. if (ret == 1) {
  199. fprintf(stderr, "String doesn't match known PEM types: %s\n", str);
  200. }
  201. return ret;
  202. }
  203. #if defined(WOLFSSL_ENCRYPTED_KEYS) && !defined(NO_PWDBASED)
  204. /* Password callback for returning the password set in the user data.
  205. *
  206. * @param [out] passwd Password buffer.
  207. * @param [in] sz Size of password buffer.
  208. * @param [in] rw Ignored.
  209. * @param [in] userdata Data associated with callback in EncryptedInfo.
  210. * @return Length of password.
  211. */
  212. static int password_from_userdata(char* passwd, int sz, int rw, void* userdata)
  213. {
  214. (void)rw;
  215. /* Copy user data into buffer. */
  216. strncpy(passwd, (const char*)userdata, (size_t)sz);
  217. passwd[sz - 1] = '\0';
  218. /* Return length of password returned. */
  219. return (int)XSTRLEN((const char*)passwd);
  220. }
  221. #endif
  222. /* Find needle in haystack.
  223. *
  224. * @param [in] haystack String to find needle in.
  225. * @param [in] offset Offset into haystack to start looking.
  226. * @param [in] len Length of haystack.
  227. * @param [in] needle String to find in haystack.
  228. * @param [in] needle_len Length of string to find.
  229. * @param [out] needle_offset Offset into haystack at which needle was found.
  230. * @return 0 on success.
  231. * @return 1 on failure.
  232. */
  233. static int FindStr(char* haystack, word32 offset, word32 len,
  234. const char* needle, word32 needle_len, word32* needle_offset)
  235. {
  236. /* Assume failure. */
  237. int ret = 1;
  238. word32 i;
  239. /* Ensure there is enough space for needle. */
  240. if (len >= needle_len) {
  241. /* Look through haystack starting at offset until not enough space for
  242. * needle. */
  243. for (i = offset; i <= len - needle_len; i++) {
  244. /* Check if needle found. */
  245. if ((haystack[i] == needle[0]) &&
  246. (strncmp(haystack + i, needle, needle_len) == 0)) {
  247. /* Return offset at which needle found. */
  248. *needle_offset = i;
  249. /* Return success. */
  250. ret = 0;
  251. /* Stop looking. */
  252. break;
  253. }
  254. }
  255. }
  256. return ret;
  257. }
  258. /* Find the next PEM block.
  259. *
  260. * @param [in] data PEM data.
  261. * @param [in] offset Offset into data to start looking.
  262. * @param [in] len Length of PEM data.
  263. * @param [out] start Start of Base64 encoding.
  264. * @param [out] end End of Base64 encoding.
  265. * @param [out] type PEM type.
  266. * @return 0 on success.
  267. * @return 1 on failure.
  268. */
  269. static int FindPem(char* data, word32 offset, word32 len, word32* start,
  270. word32* end, int* type)
  271. {
  272. int ret = 0;
  273. word32 i = 0;
  274. word32 type_off = 0;
  275. char str[PEM_TYPE_MAX_LEN];
  276. /* Find header. */
  277. ret = FindStr(data, offset, len, "-----BEGIN ", 11, &i);
  278. if (ret == 1) {
  279. /* Got to end without finding PEM header. */
  280. fprintf(stderr, "No PEM header found\n");
  281. }
  282. if (ret == 0) {
  283. /* Return start of PEM. */
  284. *start = i;
  285. /* Get start of type. */
  286. type_off = i + 11;
  287. /* Confirm header. */
  288. ret = FindStr(data, i + 11, len, "-----", 5, &i);
  289. if (ret == 1) {
  290. /* Got to end without finding rest of PEM header. */
  291. fprintf(stderr, "Invalid PEM header\n");
  292. }
  293. }
  294. if (ret == 0) {
  295. /* Found end of header - convert type string to value. */
  296. word32 type_len = i - type_off;
  297. if (type_len >= PEM_TYPE_MAX_LEN) {
  298. ret = 1;
  299. }
  300. if (ret == 0) {
  301. if (type_len > 0)
  302. memcpy(str, data + type_off, type_len);
  303. str[type_len] = '\0';
  304. ret = StringToType(str, type);
  305. }
  306. }
  307. if (ret == 0) {
  308. /* Find footer. */
  309. ret = FindStr(data, i + 5, len, "-----END ", 9, &i);
  310. if (ret == 1) {
  311. /* Got to end without finding PEM footer. */
  312. fprintf(stderr, "No PEM footer found\n");
  313. }
  314. }
  315. if (ret == 0) {
  316. /* Confirm header. */
  317. ret = FindStr(data, i + 9, len, "-----", 5, &i);
  318. if (ret == 1) {
  319. /* Got to end without finding rest of PEM footer. */
  320. fprintf(stderr, "Invalid PEM footer\n");
  321. }
  322. }
  323. if (ret == 0) {
  324. /* Return end of */
  325. *end = i + 6;
  326. }
  327. return ret;
  328. }
  329. /* Convert PEM to DER and write to file.
  330. *
  331. * @param [in] in Array of characters that is the PEM data.
  332. * @param [in] offset Offset into array to start looking for PEM block.
  333. * @param [in] len Length of data in array in bytes.
  334. * @param [out] der Buffer holding DER encoded data.
  335. * @param [in] type PEM type. -1 indicates to determine from array.
  336. * @param [in] info Encryption information.
  337. * @return 0 on success.
  338. * @return Not 0 on failure.
  339. */
  340. static int ConvPemToDer(char* in, word32 offset, word32 len, DerBuffer** der,
  341. int type, EncryptedInfo* info, int padding)
  342. {
  343. int ret = 0;
  344. word32 start = 0;
  345. word32 end = 0;
  346. /* Set point to start looking and length. */
  347. char* pem = in + offset;
  348. word32 pem_len = len - offset;
  349. /* Check if we need to discover PEM type. */
  350. if ((ret == 0) && (type == -1)) {
  351. /* Find PEM block and type. */
  352. ret = FindPem(pem, 0, pem_len, &start, &end, &type);
  353. if (ret != 0) {
  354. fprintf(stderr, "Could not find PEM header\n");
  355. }
  356. /* Update start pointer and length. */
  357. pem += start;
  358. pem_len = end - start;
  359. }
  360. if (ret == 0) {
  361. /* Convert to DER. */
  362. ret = wc_PemToDer((unsigned char*)pem, pem_len, type, der, NULL, info,
  363. NULL);
  364. if (ret != 0) {
  365. fprintf(stderr, "Could not convert PEM to DER\n");
  366. }
  367. }
  368. /* Remove padding from encryption if requested. */
  369. if ((ret == 0) && padding) {
  370. unsigned char pad = (*der)->buffer[(*der)->length - 1];
  371. word32 i;
  372. /* Simple padding validation. */
  373. if ((pad == 0) || (pad > (*der)->length)) {
  374. fprintf(stderr, "Invalid padding: %02x\n", pad);
  375. ret = 1;
  376. }
  377. else {
  378. /* Check padding is valid. */
  379. for (i = 1; i < pad; i++) {
  380. if ((*der)->buffer[(*der)->length - 1 - i] != pad) {
  381. fprintf(stderr, "Invalid padding: %d\n", pad);
  382. ret = 1;
  383. break;
  384. }
  385. }
  386. if (ret == 0) {
  387. /* Don't write out padding. */
  388. (*der)->length -= pad;
  389. }
  390. }
  391. }
  392. return ret;
  393. }
  394. #ifdef WOLFSSL_DER_TO_PEM
  395. #if defined(WOLFSSL_ENCRYPTED_KEYS) && !defined(NO_PWDBASED)
  396. /* List of known PBE algorithms. */
  397. static const String2Val pbe_map[] = {
  398. #ifndef NO_SHA
  399. #ifndef NO_RC4
  400. { "SHA1_RC4_128" , ENC_PKCS8_PBE_SHA1_RC4_128 },
  401. #endif
  402. #ifndef NO_DES
  403. { "SHA1_DES3" , ENC_PKCS8_PBE_SHA1_DES3 },
  404. { "PBES1_SHA1_DES", ENC_PKCS8_PBES1_SHA1_DES },
  405. #endif
  406. #ifdef WC_RC2
  407. { "SHA1_40RC2_CBC", ENC_PKCS8_PBE_SHA1_40RC2_CBC },
  408. #endif
  409. #endif
  410. #ifndef NO_MD5
  411. #ifndef NO_DES
  412. { "PBES1_MD5_DES" , ENC_PKCS8_PBES1_MD5_DES },
  413. #endif
  414. #endif
  415. { "PBES2" , ENC_PKCS8_PBES2 },
  416. };
  417. /* Number of entries in PBE map. */
  418. #define PBE_MAP_LEN ((int)(sizeof(pbe_map) / sizeof(*pbe_map)))
  419. /* Convert string to PBE value.
  420. *
  421. * @param [in] str PBE as a string.
  422. * @param [out] pbe PBE as a value.
  423. * @return 0 on success.
  424. * @return 1 on failure.
  425. */
  426. static int StringToPbe(char* str, int* pbe)
  427. {
  428. int ret = StringToVal(pbe_map, PBE_MAP_LEN, str, pbe);
  429. if (ret == 1) {
  430. fprintf(stderr, "String doesn't match known PBE algorithms: %s\n", str);
  431. }
  432. return ret;
  433. }
  434. /* List of known PBE versions. */
  435. static const String2Val pbe_ver_map[] = {
  436. { "PKCS12" , ENC_PKCS8_VER_PKCS12 },
  437. { "PKCS12v1", ENC_PKCS8_VER_PKCS12 },
  438. { "PKCS5" , ENC_PKCS8_VER_PKCS5 },
  439. };
  440. /* Number of entries in PBE versions map. */
  441. #define PBE_VER_MAP_LEN ((int)(sizeof(pbe_ver_map) / sizeof(*pbe_ver_map)))
  442. /* Convert string to PBE version value.
  443. *
  444. * @param [in] str PBE version as a string.
  445. * @param [out] pbe_ver PBE version as a value.
  446. * @return 0 on success.
  447. * @return 1 on failure.
  448. */
  449. static int StringToPbeVer(char* str, int* pbe_ver)
  450. {
  451. int ret = StringToVal(pbe_ver_map, PBE_VER_MAP_LEN, str, pbe_ver);
  452. if (ret == 1) {
  453. fprintf(stderr, "String doesn't match known PBE versions: %s\n", str);
  454. }
  455. return ret;
  456. }
  457. /* List of known PKCS#5v2 PBE encryption algorithms. */
  458. static const String2Val pbe_alg_map[] = {
  459. { "AES-128-CBC", ENC_PKCS8_ALG_AES128CBC },
  460. { "AES-256-CBC", ENC_PKCS8_ALG_AES256CBC },
  461. { "DES" , ENC_PKCS8_ALG_DES },
  462. { "DES3" , ENC_PKCS8_ALG_DES3 },
  463. };
  464. /* Number of entries in PBE algorithm map. */
  465. #define PBE_ALG_MAP_LEN ((int)(sizeof(pbe_alg_map) / sizeof(*pbe_alg_map)))
  466. /* Convert string to PBE algorithm value.
  467. *
  468. * @param [in] str PBE algorithm as a string.
  469. * @param [out] pbe_alg PBE algorithm as a value.
  470. * @return 0 on success.
  471. * @return 1 on failure.
  472. */
  473. static int StringToPbeAlg(char* str, int* pbe_alg)
  474. {
  475. int ret = StringToVal(pbe_alg_map, PBE_ALG_MAP_LEN, str, pbe_alg);
  476. if (ret == 1) {
  477. fprintf(stderr, "String doesn't match known PBE algorithms: %s\n", str);
  478. }
  479. return ret;
  480. }
  481. /* Encrypt the DER data.
  482. *
  483. * @param [in] in DER data to encrypt.
  484. * @param [in] in_len Length of DER data.
  485. * @param [in] password Password to use to derive key for encryption.
  486. * @param [in] iterations Number of iterations in PBE.
  487. * @param [in] salt_sz Size of salt to use in bytes.
  488. * @param [in] pbe PBE algorithm to use.
  489. * @param [in] pbe_ver Version of PBE algorithm to use.
  490. * @param [in] enc_alg_id Encryption algorithm id for when using PBES2.
  491. * @param [out] enc DER encrypted data.
  492. * @param [out] enc_len Length of DER encrypted data.
  493. * @return 0 on success.
  494. * @return 1 on failure.
  495. */
  496. static int EncryptDer(unsigned char* in, word32 in_len, char* password,
  497. unsigned int iterations, unsigned int salt_sz, int pbe, int pbe_ver,
  498. int enc_alg_id, unsigned char** enc, word32* enc_len)
  499. {
  500. int ret;
  501. WC_RNG rng;
  502. unsigned char salt[SALT_MAX_LEN];
  503. if (password == NULL)
  504. return 1;
  505. XMEMSET(&rng, 0, sizeof(rng));
  506. /* Create a random number generator. */
  507. ret = wc_InitRng(&rng);
  508. if (ret == 0) {
  509. /* Get salt from random number generator. */
  510. ret = wc_RNG_GenerateBlock(&rng, salt, salt_sz);
  511. }
  512. if (ret == 0) {
  513. /* Get length of encrypted DER data. */
  514. ret = wc_CreateEncryptedPKCS8Key(in, in_len, NULL, enc_len, password,
  515. (int)strlen(password), pbe_ver, pbe, enc_alg_id, salt, salt_sz,
  516. (int)iterations, &rng, NULL);
  517. if (ret == LENGTH_ONLY_E) {
  518. ret = 0;
  519. }
  520. else if (ret == 0) {
  521. ret = 1;
  522. }
  523. }
  524. if (ret == 0) {
  525. /* Allocate memory for encrypted DER data. */
  526. *enc = (unsigned char*)malloc(*enc_len);
  527. if (*enc == NULL) {
  528. ret = 1;
  529. }
  530. }
  531. if (ret == 0) {
  532. /* Encrypt DER data. */
  533. ret = wc_CreateEncryptedPKCS8Key(in, in_len, *enc, enc_len, password,
  534. (int)strlen(password), pbe_ver, pbe, enc_alg_id, salt, salt_sz,
  535. (int)iterations, &rng, NULL);
  536. if (ret > 0) {
  537. ret = 0;
  538. }
  539. }
  540. wc_FreeRng(&rng);
  541. return ret;
  542. }
  543. #endif
  544. /* Convert DER to PEM and write to file.
  545. *
  546. * @param [in] in Array of bytes holding the DER encoding.
  547. * @param [in] offset Offset into array of data to convert to PEM.
  548. * @param [in] len Length of data in array in bytes.
  549. * @param [out] out Allocated buffer holding PEM encoding.
  550. * @param [out] out_len Length of PEM encoding in bytes.
  551. * @param [in] type PEM type.
  552. * @param [in] cipher_str String to write into encrypted key.
  553. * @return 0 on success.
  554. * @return Not 0 on failure.
  555. */
  556. static int ConvDerToPem(unsigned char* in, word32 offset, word32 len,
  557. unsigned char** out, word32* out_len, int type, const char* cipher_str)
  558. {
  559. int ret = 0;
  560. unsigned char* pem = NULL;
  561. unsigned int pem_len = 0;
  562. /* Set point to start looking and length. */
  563. unsigned char* der = in + offset;
  564. word32 der_len = len - offset;
  565. /* Get length of PEM based on DER. */
  566. ret = wc_DerToPemEx(der, der_len, NULL, 0, (byte*)cipher_str, type);
  567. if (ret <= 0) {
  568. fprintf(stderr, "Could not determine length of PEM\n");
  569. }
  570. pem_len = (unsigned int)ret;
  571. if (ret > 0) {
  572. ret = 0;
  573. }
  574. if ((ret == 0) && (pem_len > 0)) {
  575. /* Allocate memory to hold PEM encoding. */
  576. pem = (unsigned char*)malloc(pem_len);
  577. if (pem == NULL) {
  578. ret = 1;
  579. }
  580. }
  581. if (ret == 0) {
  582. /* Convert DER to PEM. */
  583. ret = wc_DerToPemEx(der, der_len, pem, pem_len, (byte*)cipher_str,
  584. type);
  585. if (ret <= 0) {
  586. fprintf(stderr, "Could not convert DER to PEM\n");
  587. free(pem);
  588. }
  589. if (ret > 0) {
  590. *out = pem;
  591. *out_len = (word32)ret;
  592. ret = 0;
  593. }
  594. }
  595. return ret;
  596. }
  597. #endif
  598. /* Usage lines to show. */
  599. const char* usage[] = {
  600. "pem [OPTION]...",
  601. "Convert to/from PEM and DER.",
  602. "",
  603. "Options:",
  604. " -?, --help display this help and exit",
  605. " -t --type string representing type of data",
  606. " -in name of file to read (uses stdin otherwise)",
  607. " -out name of file to write to (uses stdout otherwise)",
  608. " -o --offset offset into file where data to convert starts",
  609. #if defined(WOLFSSL_ENCRYPTED_KEYS) && !defined(NO_PWDBASED)
  610. " -p --pass password to use with encrypted keys",
  611. #endif
  612. #ifdef WOLFSSL_DER_TO_PEM
  613. " -d --der input is DER and output is PEM",
  614. #if defined(WOLFSSL_ENCRYPTED_KEYS) && !defined(NO_PWDBASED)
  615. " --padding Remove padding on decrypted data",
  616. " -e --encrypt DER key is to be encrypted",
  617. " -v --pbe-ver PBE version to use when encrypting key (see below)",
  618. " -p --pbe PBE to use when encrypting key (see below)",
  619. " -a --pbe-alg PBES2 algorithm to use when encrypting key (see below)",
  620. " -i --iter number of iterations of PBE - default: 100000",
  621. " -s --salt-sz length, in bytes, of salt to generate - 0-64",
  622. #endif
  623. #endif
  624. #ifdef DEBUG_WOLFSSL
  625. " -l --log turn on wolfSSL logging",
  626. #endif
  627. "",
  628. };
  629. /* Number of usage lines. */
  630. #define USAGE_SZ ((int)(sizeof(usage) / sizeof(*usage)))
  631. const struct string_usage_st {
  632. const char* str;
  633. const String2Val* map;
  634. int len;
  635. } known_strings[] = {
  636. { "Known PEM header/trailer strings:", type_map , TYPE_MAP_LEN },
  637. #if defined(WOLFSSL_DER_TO_PEM) && defined(WOLFSSL_ENCRYPTED_KEYS) && \
  638. !defined(NO_PWDBASED)
  639. { "Known PBE version strings:" , pbe_ver_map, PBE_VER_MAP_LEN },
  640. { "Known PBE strings:" , pbe_map , PBE_MAP_LEN },
  641. { "Known PBES2 algorithm strings:" , pbe_alg_map, PBE_ALG_MAP_LEN },
  642. #endif
  643. };
  644. /* Number of usage lines. */
  645. #define KNOWN_STRINGS_SZ \
  646. ((int)(sizeof(known_strings) / sizeof(*known_strings)))
  647. /* Print out usage lines.
  648. */
  649. static void Usage(void)
  650. {
  651. int i;
  652. int j;
  653. /* Usage lines. */
  654. for (i = 0; i < USAGE_SZ; i++) {
  655. printf("%s\n", usage[i]);
  656. }
  657. /* Known strings for options. */
  658. for (j = 0; j < KNOWN_STRINGS_SZ; j++) {
  659. printf("%s\n", known_strings[j].str);
  660. for (i = 0; i < known_strings[j].len; i++) {
  661. printf(" %s\n", known_strings[j].map[i].string);
  662. }
  663. }
  664. }
  665. /* Main entry of ASN.1 printing program.
  666. *
  667. * @param [in] argc Count of command line arguments.
  668. * @param [in] argv Command line arguments.
  669. * @return 0 on success.
  670. * @return 1 on failure.
  671. */
  672. int main(int argc, char* argv[])
  673. {
  674. int ret = 0;
  675. /* Default to reading STDIN. */
  676. FILE* in_file = stdin;
  677. /* Default to writing to STDOUT. */
  678. FILE* out_file = stdout;
  679. const char* out_name = NULL;
  680. unsigned char* in = NULL;
  681. word32 in_len = 0;
  682. word32 offset = 0;
  683. unsigned char* out = NULL;
  684. word32 out_len = 0;
  685. int pem = 1;
  686. const char* type_str = NULL;
  687. int type = -1;
  688. DerBuffer* der = NULL;
  689. EncryptedInfo info;
  690. int padding = 0;
  691. #if defined(WOLFSSL_DER_TO_PEM) && defined(WOLFSSL_ENCRYPTED_KEYS) && \
  692. !defined(NO_PWDBASED)
  693. int enc_der = 0;
  694. unsigned char* enc = NULL;
  695. word32 enc_len = 0;
  696. unsigned int iterations = DEFAULT_ITERATIONS;
  697. unsigned int salt_sz = 8;
  698. int pbe_ver = ENC_PKCS8_VER_PKCS5;
  699. int pbe = ENC_PKCS8_PBES2;
  700. int pbe_alg = ENC_PKCS8_ALG_AES256CBC;
  701. #endif
  702. #ifdef DEBUG_WOLFSSL
  703. int log = 0;
  704. #endif
  705. memset(&info, 0, sizeof(info));
  706. /* Skip over program name. */
  707. argc--;
  708. argv++;
  709. while (argc > 0) {
  710. /* PEM header type. */
  711. if ((strcmp(argv[0], "-t") == 0) ||
  712. (strcmp(argv[0], "--type") == 0)) {
  713. argc--;
  714. argv++;
  715. if (argc == 0) {
  716. fprintf(stderr, "No type string provided\n");
  717. return 1;
  718. }
  719. type_str = argv[0];
  720. }
  721. /* Name of input file. */
  722. else if (strcmp(argv[0], "-in") == 0) {
  723. argc--;
  724. argv++;
  725. if (argc == 0) {
  726. fprintf(stderr, "No filename provided\n");
  727. return 1;
  728. }
  729. in_file = fopen(argv[0], "r");
  730. if (in_file == NULL) {
  731. fprintf(stderr, "File not able to be read: %s\n", argv[0]);
  732. return 1;
  733. }
  734. }
  735. /* Name of output file. */
  736. else if (strcmp(argv[0], "-out") == 0) {
  737. argc--;
  738. argv++;
  739. if (argc == 0) {
  740. fprintf(stderr, "No filename provided\n");
  741. return 1;
  742. }
  743. out_name = argv[0];
  744. }
  745. /* Offset into input data to start from. */
  746. else if ((strcmp(argv[0], "-o") == 0) ||
  747. (strcmp(argv[0], "--offset") == 0)) {
  748. argc--;
  749. argv++;
  750. if (argc == 0) {
  751. fprintf(stderr, "No filename provided\n");
  752. return 1;
  753. }
  754. offset = (word32)strtoul(argv[0], NULL, 10);
  755. }
  756. #if defined(WOLFSSL_ENCRYPTED_KEYS) && !defined(NO_PWDBASED)
  757. /* Password to use when encrypting or decrypting keys with PEM. */
  758. else if ((strcmp(argv[0], "-p") == 0) ||
  759. (strcmp(argv[0], "--pass") == 0)) {
  760. argc--;
  761. argv++;
  762. if (argc == 0) {
  763. fprintf(stderr, "No password provided\n");
  764. return 1;
  765. }
  766. info.passwd_cb = password_from_userdata;
  767. info.passwd_userdata = argv[0];
  768. }
  769. #endif
  770. #ifdef WOLFSSL_DER_TO_PEM
  771. /* Input is DER and we are converting to PEM. */
  772. else if ((strcmp(argv[0], "-d") == 0) ||
  773. (strcmp(argv[0], "--der") == 0)) {
  774. pem = 0;
  775. }
  776. #if defined(WOLFSSL_ENCRYPTED_KEYS) && !defined(NO_PWDBASED)
  777. /* Remove padding leftover from decryption. */
  778. else if (strcmp(argv[0], "--padding") == 0) {
  779. padding = 1;
  780. }
  781. /* Encrypting the DER data. */
  782. else if ((strcmp(argv[0], "-e") == 0) ||
  783. (strcmp(argv[0], "--encrypt") == 0)) {
  784. enc_der = 1;
  785. }
  786. /* PBE version. */
  787. else if ((strcmp(argv[0], "-v") == 0) ||
  788. (strcmp(argv[0], "--pbe-ver") == 0)) {
  789. argc--;
  790. argv++;
  791. if (argc == 0) {
  792. fprintf(stderr, "No PBE version provided\n");
  793. return 1;
  794. }
  795. if (StringToPbeVer(argv[0], &pbe_ver) != 0) {
  796. return 1;
  797. }
  798. }
  799. /* PBE algorithm. */
  800. else if ((strcmp(argv[0], "-p") == 0) ||
  801. (strcmp(argv[0], "--pbe") == 0)) {
  802. argc--;
  803. argv++;
  804. if (argc == 0) {
  805. fprintf(stderr, "No PBE provided\n");
  806. return 1;
  807. }
  808. if (StringToPbe(argv[0], &pbe) != 0) {
  809. return 1;
  810. }
  811. }
  812. /* PBES2 algorithm. */
  813. else if ((strcmp(argv[0], "-a") == 0) ||
  814. (strcmp(argv[0], "--pbe-alg") == 0)) {
  815. argc--;
  816. argv++;
  817. if (argc == 0) {
  818. fprintf(stderr, "No PBE algorithm provided\n");
  819. return 1;
  820. }
  821. if (StringToPbeAlg(argv[0], &pbe_alg) != 0) {
  822. return 1;
  823. }
  824. }
  825. /* Number of PBE iterations. */
  826. else if ((strcmp(argv[0], "-i") == 0) ||
  827. (strcmp(argv[0], "--iter") == 0)) {
  828. argc--;
  829. argv++;
  830. if (argc == 0) {
  831. fprintf(stderr, "No filename provided\n");
  832. return 1;
  833. }
  834. iterations = (unsigned int)strtoul(argv[0], NULL, 10);
  835. }
  836. /* Size of salt to be generated. */
  837. else if ((strcmp(argv[0], "-s") == 0) ||
  838. (strcmp(argv[0], "--salt-sz") == 0)) {
  839. argc--;
  840. argv++;
  841. if (argc == 0) {
  842. fprintf(stderr, "No salt size provided\n");
  843. return 1;
  844. }
  845. salt_sz = (unsigned int)strtoul(argv[0], NULL, 10);
  846. if (salt_sz > SALT_MAX_LEN) {
  847. fprintf(stderr, "Salt size must be no bigger than %d: %d\n",
  848. SALT_MAX_LEN, salt_sz);
  849. return 1;
  850. }
  851. }
  852. #endif /* WOLFSSL_ENCRYPTED_KEYS !NO_PWDBASED */
  853. #endif /* WOLFSSL_DER_TO_PEM */
  854. #ifdef DEBUG_WOLFSSL
  855. /* Turn on logging. */
  856. else if ((strcmp(argv[0], "-l") == 0) ||
  857. (strcmp(argv[0], "--log") == 0)) {
  858. log = 1;
  859. }
  860. #endif
  861. /* Display help/usage. */
  862. else if ((strcmp(argv[0], "-?") == 0) ||
  863. (strcmp(argv[0], "--help") == 0)) {
  864. Usage();
  865. return 0;
  866. }
  867. else {
  868. fprintf(stderr, "Bad option: %s\n", argv[0]);
  869. Usage();
  870. return 1;
  871. }
  872. /* Move on to next command line argument. */
  873. argc--;
  874. argv++;
  875. }
  876. #ifdef DEBUG_WOLFSSL
  877. if (log) {
  878. wolfSSL_Debugging_ON();
  879. }
  880. #endif
  881. /* Convert PEM type string to value. */
  882. if (type_str != NULL) {
  883. ret = StringToType(type_str, &type);
  884. }
  885. #if defined(WOLFSSL_DER_TO_PEM) && defined(WOLFSSL_ENCRYPTED_KEYS) && \
  886. !defined(NO_PWDBASED)
  887. /* Check whether we are encrypting DER. */
  888. if ((!pem) && (type == PKCS8_ENC_PRIVATEKEY_TYPE)) {
  889. enc_der = 1;
  890. }
  891. #endif
  892. /* Read all of PEM file. */
  893. if ((ret == 0) && (pemApp_ReadFile(in_file, &in, &in_len) != 0)) {
  894. fprintf(stderr, "Reading file failed\n");
  895. ret = 1;
  896. }
  897. if ((ret == 0) && pem) {
  898. /* Convert PEM to DER. */
  899. ret = ConvPemToDer((char*)in, offset, in_len, &der, type, &info,
  900. padding);
  901. if (ret == 0) {
  902. out = der->buffer;
  903. out_len = der->length;
  904. }
  905. }
  906. else {
  907. #ifdef WOLFSSL_DER_TO_PEM
  908. #if defined(WOLFSSL_ENCRYPTED_KEYS) && !defined(NO_PWDBASED)
  909. if (enc_der) {
  910. /* Encrypt DER first. */
  911. ret = EncryptDer(in + offset, in_len - offset,
  912. (char*)info.passwd_userdata, iterations, salt_sz, pbe, pbe_ver,
  913. pbe_alg, &enc, &enc_len);
  914. if (ret == 0) {
  915. /* Convert encrypted DER data to PEM. */
  916. ret = ConvDerToPem(enc, 0, enc_len, &out, &out_len, type,
  917. NULL);
  918. }
  919. }
  920. else
  921. #endif /* WOLFSSL_ENCRYPTED_KEYS && !NO_PWDBASED */
  922. {
  923. /* Convert DER data to PEM. */
  924. ret = ConvDerToPem(in, offset, in_len, &out, &out_len, type, NULL);
  925. }
  926. #else
  927. fprintf(stderr, "DER to PEM not supported by wolfSSL\n");
  928. ret = 1;
  929. #endif
  930. }
  931. if ((ret == 0) && (out_name != NULL)) {
  932. /*Open write named file to write to. */
  933. out_file = fopen(out_name, "w");
  934. if (out_file == NULL) {
  935. fprintf(stderr, "File not able to be written: %s\n", out_name);
  936. ret = 1;
  937. }
  938. }
  939. if (ret == 0) {
  940. /* Write out PEM. */
  941. ret = WriteFile(out_file, out ? (const char *)out : "", out_len);
  942. if (ret != 0) {
  943. fprintf(stderr, "Could not write file\n");
  944. }
  945. }
  946. /* Dispose of allocated data. */
  947. if (der != NULL) {
  948. wc_FreeDer(&der);
  949. }
  950. else if (out != NULL) {
  951. free(out);
  952. }
  953. #if defined(WOLFSSL_DER_TO_PEM) && defined(WOLFSSL_ENCRYPTED_KEYS) && \
  954. !defined(NO_PWDBASED)
  955. if (enc != NULL) {
  956. free(enc);
  957. }
  958. #endif
  959. if (in != NULL) {
  960. free(in);
  961. }
  962. if (ret < 0) {
  963. fprintf(stderr, "%s\n", wc_GetErrorString(ret));
  964. }
  965. return (ret == 0) ? 0 : 1;
  966. }
  967. #else
  968. /* Main entry of ASN.1 printing program.
  969. *
  970. * @param [in] argc Count of command line arguments.
  971. * @param [in] argv Command line arguments.
  972. * @return 0 on success.
  973. * @return 1 on failure.
  974. */
  975. int main(int argc, char* argv[])
  976. {
  977. (void)argc;
  978. (void)argv;
  979. fprintf(stderr, "PEM to DER conversion of file system support not compiled"
  980. " in.\n");
  981. return 0;
  982. }
  983. #endif /* WOLFSSL_PEM_TO_DER && !NO_FILESYSTEM */