2
0

pem.c 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048
  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*)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 == WC_NO_ERR_TRACE(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. if (in_file != stdin) {
  730. fprintf(stderr, "At most one input file can be supplied.\n");
  731. return 1;
  732. }
  733. in_file = fopen(argv[0], "r");
  734. if (in_file == NULL) {
  735. fprintf(stderr, "File not able to be read: %s\n", argv[0]);
  736. return 1;
  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. return 1;
  746. }
  747. out_name = argv[0];
  748. }
  749. /* Offset into input data to start from. */
  750. else if ((strcmp(argv[0], "-o") == 0) ||
  751. (strcmp(argv[0], "--offset") == 0)) {
  752. argc--;
  753. argv++;
  754. if (argc == 0) {
  755. fprintf(stderr, "No filename provided\n");
  756. return 1;
  757. }
  758. offset = (word32)strtoul(argv[0], NULL, 10);
  759. }
  760. #if defined(WOLFSSL_ENCRYPTED_KEYS) && !defined(NO_PWDBASED)
  761. /* Password to use when encrypting or decrypting keys with PEM. */
  762. else if ((strcmp(argv[0], "-p") == 0) ||
  763. (strcmp(argv[0], "--pass") == 0)) {
  764. argc--;
  765. argv++;
  766. if (argc == 0) {
  767. fprintf(stderr, "No password provided\n");
  768. return 1;
  769. }
  770. info.passwd_cb = password_from_userdata;
  771. info.passwd_userdata = argv[0];
  772. }
  773. #endif
  774. #ifdef WOLFSSL_DER_TO_PEM
  775. /* Input is DER and we are converting to PEM. */
  776. else if ((strcmp(argv[0], "-d") == 0) ||
  777. (strcmp(argv[0], "--der") == 0)) {
  778. pem = 0;
  779. }
  780. #if defined(WOLFSSL_ENCRYPTED_KEYS) && !defined(NO_PWDBASED)
  781. /* Remove padding leftover from decryption. */
  782. else if (strcmp(argv[0], "--padding") == 0) {
  783. padding = 1;
  784. }
  785. /* Encrypting the DER data. */
  786. else if ((strcmp(argv[0], "-e") == 0) ||
  787. (strcmp(argv[0], "--encrypt") == 0)) {
  788. enc_der = 1;
  789. }
  790. /* PBE version. */
  791. else if ((strcmp(argv[0], "-v") == 0) ||
  792. (strcmp(argv[0], "--pbe-ver") == 0)) {
  793. argc--;
  794. argv++;
  795. if (argc == 0) {
  796. fprintf(stderr, "No PBE version provided\n");
  797. return 1;
  798. }
  799. if (StringToPbeVer(argv[0], &pbe_ver) != 0) {
  800. return 1;
  801. }
  802. }
  803. /* PBE algorithm. */
  804. else if ((strcmp(argv[0], "-p") == 0) ||
  805. (strcmp(argv[0], "--pbe") == 0)) {
  806. argc--;
  807. argv++;
  808. if (argc == 0) {
  809. fprintf(stderr, "No PBE provided\n");
  810. return 1;
  811. }
  812. if (StringToPbe(argv[0], &pbe) != 0) {
  813. return 1;
  814. }
  815. }
  816. /* PBES2 algorithm. */
  817. else if ((strcmp(argv[0], "-a") == 0) ||
  818. (strcmp(argv[0], "--pbe-alg") == 0)) {
  819. argc--;
  820. argv++;
  821. if (argc == 0) {
  822. fprintf(stderr, "No PBE algorithm provided\n");
  823. return 1;
  824. }
  825. if (StringToPbeAlg(argv[0], &pbe_alg) != 0) {
  826. return 1;
  827. }
  828. }
  829. /* Number of PBE iterations. */
  830. else if ((strcmp(argv[0], "-i") == 0) ||
  831. (strcmp(argv[0], "--iter") == 0)) {
  832. argc--;
  833. argv++;
  834. if (argc == 0) {
  835. fprintf(stderr, "No filename provided\n");
  836. return 1;
  837. }
  838. iterations = (unsigned int)strtoul(argv[0], NULL, 10);
  839. }
  840. /* Size of salt to be generated. */
  841. else if ((strcmp(argv[0], "-s") == 0) ||
  842. (strcmp(argv[0], "--salt-sz") == 0)) {
  843. argc--;
  844. argv++;
  845. if (argc == 0) {
  846. fprintf(stderr, "No salt size provided\n");
  847. return 1;
  848. }
  849. salt_sz = (unsigned int)strtoul(argv[0], NULL, 10);
  850. if (salt_sz > SALT_MAX_LEN) {
  851. fprintf(stderr, "Salt size must be no bigger than %d: %d\n",
  852. SALT_MAX_LEN, salt_sz);
  853. return 1;
  854. }
  855. }
  856. #endif /* WOLFSSL_ENCRYPTED_KEYS !NO_PWDBASED */
  857. #endif /* WOLFSSL_DER_TO_PEM */
  858. #ifdef DEBUG_WOLFSSL
  859. /* Turn on logging. */
  860. else if ((strcmp(argv[0], "-l") == 0) ||
  861. (strcmp(argv[0], "--log") == 0)) {
  862. log = 1;
  863. }
  864. #endif
  865. /* Display help/usage. */
  866. else if ((strcmp(argv[0], "-?") == 0) ||
  867. (strcmp(argv[0], "--help") == 0)) {
  868. Usage();
  869. return 0;
  870. }
  871. else {
  872. fprintf(stderr, "Bad option: %s\n", argv[0]);
  873. Usage();
  874. return 1;
  875. }
  876. /* Move on to next command line argument. */
  877. argc--;
  878. argv++;
  879. }
  880. #ifdef DEBUG_WOLFSSL
  881. if (log) {
  882. wolfSSL_Debugging_ON();
  883. }
  884. #endif
  885. /* Convert PEM type string to value. */
  886. if (type_str != NULL) {
  887. ret = StringToType(type_str, &type);
  888. }
  889. #if defined(WOLFSSL_DER_TO_PEM) && defined(WOLFSSL_ENCRYPTED_KEYS) && \
  890. !defined(NO_PWDBASED)
  891. /* Check whether we are encrypting DER. */
  892. if ((!pem) && (type == PKCS8_ENC_PRIVATEKEY_TYPE)) {
  893. enc_der = 1;
  894. }
  895. #endif
  896. /* Read all of PEM file. */
  897. if ((ret == 0) && (pemApp_ReadFile(in_file, &in, &in_len) != 0)) {
  898. fprintf(stderr, "Reading file failed\n");
  899. ret = 1;
  900. }
  901. if ((ret == 0) && pem) {
  902. /* Convert PEM to DER. */
  903. ret = ConvPemToDer((char*)in, offset, in_len, &der, type, &info,
  904. padding);
  905. if (ret == 0) {
  906. out = der->buffer;
  907. out_len = der->length;
  908. }
  909. }
  910. else {
  911. #ifdef WOLFSSL_DER_TO_PEM
  912. #if defined(WOLFSSL_ENCRYPTED_KEYS) && !defined(NO_PWDBASED)
  913. if (enc_der) {
  914. /* Encrypt DER first. */
  915. ret = EncryptDer(in + offset, in_len - offset,
  916. (char*)info.passwd_userdata, iterations, salt_sz, pbe, pbe_ver,
  917. pbe_alg, &enc, &enc_len);
  918. if (ret == 0) {
  919. /* Convert encrypted DER data to PEM. */
  920. ret = ConvDerToPem(enc, 0, enc_len, &out, &out_len, type,
  921. NULL);
  922. }
  923. }
  924. else
  925. #endif /* WOLFSSL_ENCRYPTED_KEYS && !NO_PWDBASED */
  926. {
  927. /* Convert DER data to PEM. */
  928. ret = ConvDerToPem(in, offset, in_len, &out, &out_len, type, NULL);
  929. }
  930. #else
  931. fprintf(stderr, "DER to PEM not supported by wolfSSL\n");
  932. ret = 1;
  933. #endif
  934. }
  935. if ((ret == 0) && (out_name != NULL)) {
  936. /*Open write named file to write to. */
  937. out_file = fopen(out_name, "w");
  938. if (out_file == NULL) {
  939. fprintf(stderr, "File not able to be written: %s\n", out_name);
  940. ret = 1;
  941. }
  942. }
  943. if (ret == 0) {
  944. /* Write out PEM. */
  945. ret = WriteFile(out_file, out ? (const char *)out : "", out_len);
  946. if (ret != 0) {
  947. fprintf(stderr, "Could not write file\n");
  948. }
  949. }
  950. /* Dispose of allocated data. */
  951. if (der != NULL) {
  952. wc_FreeDer(&der);
  953. }
  954. else if (out != NULL) {
  955. free(out);
  956. }
  957. #if defined(WOLFSSL_DER_TO_PEM) && defined(WOLFSSL_ENCRYPTED_KEYS) && \
  958. !defined(NO_PWDBASED)
  959. if (enc != NULL) {
  960. free(enc);
  961. }
  962. #endif
  963. if (in != NULL) {
  964. free(in);
  965. }
  966. if (ret < 0) {
  967. fprintf(stderr, "%s\n", wc_GetErrorString(ret));
  968. }
  969. return (ret == 0) ? 0 : 1;
  970. }
  971. #else
  972. /* Main entry of ASN.1 printing program.
  973. *
  974. * @param [in] argc Count of command line arguments.
  975. * @param [in] argv Command line arguments.
  976. * @return 0 on success.
  977. * @return 1 on failure.
  978. */
  979. int main(int argc, char* argv[])
  980. {
  981. (void)argc;
  982. (void)argv;
  983. fprintf(stderr, "PEM to DER conversion of file system support not compiled"
  984. " in.\n");
  985. return 0;
  986. }
  987. #endif /* WOLFSSL_PEM_TO_DER && !NO_FILESYSTEM */