pem.c 32 KB

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