encryptip.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897
  1. /*
  2. * Copyright (C) 2011-2018 Intel Corporation. All rights reserved.
  3. *
  4. * Redistribution and use in source and binary forms, with or without
  5. * modification, are permitted provided that the following conditions
  6. * are met:
  7. *
  8. * * Redistributions of source code must retain the above copyright
  9. * notice, this list of conditions and the following disclaimer.
  10. * * Redistributions in binary form must reproduce the above copyright
  11. * notice, this list of conditions and the following disclaimer in
  12. * the documentation and/or other materials provided with the
  13. * distribution.
  14. * * Neither the name of Intel Corporation nor the names of its
  15. * contributors may be used to endorse or promote products derived
  16. * from this software without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  19. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  20. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  21. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  22. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  23. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  24. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  25. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  26. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  27. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  28. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  29. *
  30. */
  31. #include <string.h>
  32. #include <stdio.h>
  33. #include <stdlib.h>
  34. #include <elf.h>
  35. #include <immintrin.h>
  36. #include <cpuid.h>
  37. #include <stdbool.h>
  38. #include "openssl/evp.h"
  39. #include "openssl/ossl_typ.h"
  40. #include "openssl/sha.h"
  41. #include <sgx_tseal.h>
  42. #include <sgx_tcrypto.h>
  43. #include "pcl_common.h"
  44. #include "encryptip.h"
  45. #include "sgx_pcl_guid.h"
  46. /*
  47. * @func main - tool entry point
  48. * 1. Parses arguments
  49. * 2. Read binary key file
  50. * 3. Read enclave so file
  51. * 4. Modify enclave binary
  52. * 5. Save enclave to file
  53. * @param int argc, number of command line parameters
  54. * @param IN char *argv[], array of command line parameters' strings
  55. * @return (int)(encip_ret_e)
  56. * Respective error values if either parse_args, read_file, encrypt_ip or write_file fail
  57. * ENCIP_ERROR_KEY_FILE_SIZE if size of binary key file is not 16 bytes
  58. * ENCIP_ERROR_ENCLAVE_SIZE if enclave size is 0
  59. * ENCIP_SUCCESS if success
  60. */
  61. int main(int argc, IN char *argv[])
  62. {
  63. char* keyfile_name = NULL;
  64. char* enclave_in_name = NULL;
  65. char* enclave_out_name = NULL;
  66. bool debug = false;
  67. uint8_t* enclave_buf = NULL;
  68. uint8_t* key_buf = NULL;
  69. size_t key_size = 0;
  70. size_t enclave_size = 0;
  71. // Parse the arguments:
  72. encip_ret_e ret = parse_args(argc, argv, &enclave_in_name, &enclave_out_name, &keyfile_name, &debug);
  73. if(ENCIP_ERROR(ret))
  74. return (int)ret;
  75. // Read enclave file into buffer:
  76. ret = read_file(enclave_in_name, &enclave_buf, &enclave_size);
  77. if(ENCIP_ERROR(ret))
  78. return (int)ret;
  79. if(0 == enclave_size)
  80. {
  81. ret = ENCIP_ERROR_ENCLAVE_SIZE;
  82. goto Label_free_enclave_buffer;
  83. }
  84. // Read key file into buffer:
  85. ret = read_file(keyfile_name, &key_buf, &key_size);
  86. if(ENCIP_ERROR(ret))
  87. goto Label_free_enclave_buffer;
  88. if(SGX_AESGCM_KEY_SIZE != key_size)
  89. {
  90. ret = ENCIP_ERROR_KEY_FILE_SIZE;
  91. goto Label_free_key_and_enclave_buffers;
  92. }
  93. // Modify enclave for PCL:
  94. ret = encrypt_ip(enclave_buf, enclave_size, key_buf, debug);
  95. if(ENCIP_ERROR(ret))
  96. goto Label_free_key_and_enclave_buffers;
  97. // Write the buffer into enclave file:
  98. ret = write_file(enclave_out_name, enclave_buf, enclave_size);
  99. if(ENCIP_ERROR(ret))
  100. goto Label_free_key_and_enclave_buffers;
  101. // Set success:
  102. ret = ENCIP_SUCCESS;
  103. Label_free_key_and_enclave_buffers:
  104. free(key_buf);
  105. Label_free_enclave_buffer:
  106. free(enclave_buf);
  107. return (int)ret;
  108. }
  109. /*
  110. * @func can_modify checks if section content can be modified without disrupting
  111. * enclave signing or loading flows
  112. * @param IN const char* const sec_name is a pointer to the section's name
  113. * @return true iff section content can be modified without disrupting
  114. * enclave signing or loading flows
  115. */
  116. static inline bool can_modify(IN const char* const sec_name, bool debug)
  117. {
  118. /*
  119. * non_ip_sec_names is an array of names of sections that must remain plain text
  120. * to enable enclave signing and loading flows
  121. */
  122. static char const* const non_ip_sec_names[NUM_NON_IP_OR_DEBUG_SEC_NAMES] =
  123. {
  124. ".shstrtab", // Sections' names string table. Pointed by e_shstrndx
  125. ".note.sgxmeta", // SGX enclave metadata
  126. ".bss", // Inited with zero - no IP. Section may overlap other sections
  127. ".tbss", // Inited with zero - no IP. Section may overlap other sections
  128. ".dynamic", // Required to construct dyn_info by function parse_dyn at elfparser.cpp
  129. ".dynsym", // Holds content pointed by entreis with index DT_SYMTAB in dyn_info
  130. ".dynstr", // Holds content pointed by entreis with index DT_STRTAB in dyn_info
  131. ".rela.dyn", // Holds content pointed by entreis with index DT_REL in dyn_info
  132. PCLTBL_SECTION_NAME, // PCL table
  133. PCL_TEXT_SECTION_NAME, // code use by PCL flow
  134. PCL_DATA_SECTION_NAME, // Data used by PCL flow
  135. PCL_RODATA_SECTION_NAME, // Read only data used by PCL flow
  136. ".comment", // Required for debugging
  137. ".debug_aranges", // Required for debugging
  138. ".debug_info", // Required for debugging
  139. ".debug_abbrev", // Required for debugging
  140. ".debug_line", // Required for debugging
  141. ".debug_str", // Required for debugging
  142. ".debug_loc", // Required for debugging
  143. ".debug_ranges", // Required for debugging
  144. ".gnu.version_d", // Required for debugging, allocables
  145. ".symtab", // Required for comfortable debugging
  146. ".strtab", // Required for comfortable debugging
  147. };
  148. if(NULL == sec_name)
  149. return false;
  150. uint32_t num_sec_names = debug ? NUM_NON_IP_OR_DEBUG_SEC_NAMES : NUM_NON_IP_SEC_NAMES;
  151. for(uint32_t secidx = 0; secidx < num_sec_names; secidx++)
  152. {
  153. if(!strcmp(non_ip_sec_names[secidx],sec_name))
  154. return false;
  155. }
  156. return true;
  157. }
  158. /*
  159. * @func parse_elf prases the ELF buffer and assigns dat astruct with:
  160. * 1. Pointer to elf sections array
  161. * 2. Index of sections names strings section
  162. * 3. Number of sections
  163. * 4. Pointer to sections names structure
  164. * 5. Pointer to elf segments array
  165. * 6. Number of segments
  166. * @param IN const void* const elf_buf_in is a pointer to the ELF binary in memory
  167. * @param size_t elf_size, ELF binary size in bytes
  168. * @param OUT pcl_data_t* dat is a pointer to the struct holding output
  169. * @return:
  170. * ENCIP_ERROR_PARSE_ELF_INVALID_PARAM if input parameters are NULL
  171. * ENCIP_ERROR_PARSE_ELF_INVALID_IMAGE if ELF image is not valid
  172. * ENCIP_SUCCESS if success
  173. */
  174. static encip_ret_e parse_elf(const void* const elf_buf_in, size_t elf_size, pcl_data_t* dat)
  175. {
  176. if(NULL == elf_buf_in || NULL == dat)
  177. return ENCIP_ERROR_PARSE_ELF_INVALID_PARAM;
  178. uint8_t* elf_buf = (uint8_t*)elf_buf_in;
  179. // Elf header is at the encalve input file start address:
  180. if(sizeof(Elf64_Ehdr) > elf_size)
  181. return ENCIP_ERROR_PARSE_ELF_INVALID_IMAGE;
  182. Elf64_Ehdr* elf_hdr = (Elf64_Ehdr*)(elf_buf);
  183. // Verify magic:
  184. if(ELFMAG0 != elf_hdr->e_ident[EI_MAG0] ||
  185. ELFMAG1 != elf_hdr->e_ident[EI_MAG1] ||
  186. ELFMAG2 != elf_hdr->e_ident[EI_MAG2] ||
  187. ELFMAG3 != elf_hdr->e_ident[EI_MAG3])
  188. return ENCIP_ERROR_PARSE_ELF_INVALID_IMAGE;
  189. // Find the number of sections:
  190. dat->nsections = elf_hdr->e_shnum;
  191. // Find the index of the section which contains the sections names strings:
  192. uint16_t shstrndx = elf_hdr->e_shstrndx;
  193. dat->shstrndx = shstrndx;
  194. if(dat->nsections <= shstrndx)
  195. return ENCIP_ERROR_PARSE_ELF_INVALID_IMAGE;
  196. // Find the array of the sections headers:
  197. if((elf_hdr->e_shoff >= elf_size) ||
  198. (elf_hdr->e_shoff + dat->nsections * sizeof(Elf64_Shdr) < elf_hdr->e_shoff) ||
  199. (elf_hdr->e_shoff + dat->nsections * sizeof(Elf64_Shdr) > elf_size))
  200. return ENCIP_ERROR_PARSE_ELF_INVALID_IMAGE;
  201. dat->elf_sec = (Elf64_Shdr*)(elf_buf + elf_hdr->e_shoff);
  202. // Find the begining of the section which contains the sections names strings
  203. if((dat->elf_sec[shstrndx].sh_offset >= elf_size) ||
  204. (dat->elf_sec[shstrndx].sh_offset + dat->elf_sec[shstrndx].sh_size < dat->elf_sec[shstrndx].sh_offset) ||
  205. (dat->elf_sec[shstrndx].sh_offset + dat->elf_sec[shstrndx].sh_size > elf_size))
  206. return ENCIP_ERROR_PARSE_ELF_INVALID_IMAGE;
  207. dat->sections_names = (char*)(elf_buf + dat->elf_sec[shstrndx].sh_offset);
  208. // Find number of segments:
  209. dat->nsegments = elf_hdr->e_phnum;
  210. if((elf_hdr->e_phoff >= elf_size) ||
  211. (elf_hdr->e_phoff + dat->nsegments * sizeof(Elf64_Phdr) < elf_hdr->e_phoff) ||
  212. (elf_hdr->e_phoff + dat->nsegments * sizeof(Elf64_Phdr) > elf_size))
  213. return ENCIP_ERROR_PARSE_ELF_INVALID_IMAGE;
  214. dat->phdr = (Elf64_Phdr*)(elf_buf + elf_hdr->e_phoff);
  215. return ENCIP_SUCCESS;
  216. }
  217. /*
  218. * @func get_pcl_tbl iterates over sections to find the PCL table
  219. * @param IN const void* const elf_buf_in is a pointer to the ELF binary in memory
  220. * @param size_t elf_size, ELF buffer size in bytes
  221. * @param IN const pcl_data_t* const dat is a pointer to the struct holding parsed elf content
  222. * @param OUT pcl_table_t** tbl_pp, address of pointer to table
  223. * @return encip_ret_e:
  224. * ENCIP_ERROR_GETTBL_INVALID_PARAM if input parameters are NULL
  225. * ENCIP_ERROR_TBL_NOT_ALIGNED if table not aligned to PCL_TABLE_ALLIGNMENT
  226. * ENCIP_ERROR_TBL_NOT_FOUND if table is not found in binary
  227. * ENCIP_ERROR_ALREADY_ENCRYPTED if pcl_state in PCL table equals PCL_CIPHER
  228. * ENCIP_ERROR_IMPROPER_STATE if pcl_state in PCL table does not equal PCL_PLAIN
  229. * ENCIP_ERROR_PARSE_ELF_INVALID_IMAGE if ELF image is invalid
  230. * ENCIP_SUCCESS if success
  231. */
  232. static encip_ret_e get_pcl_tbl(
  233. IN const void* const elf_buf_in,
  234. size_t elf_size,
  235. IN const pcl_data_t* const dat,
  236. OUT pcl_table_t** tbl_pp)
  237. {
  238. if(NULL == elf_buf_in || NULL == dat || NULL == tbl_pp)
  239. return ENCIP_ERROR_GETTBL_INVALID_PARAM;
  240. bool tbl_found = false;
  241. uint8_t* elf_buf = (uint8_t*)elf_buf_in;
  242. // Go over sections headers to find the table (skip first section):
  243. for(uint16_t secidx = 1; secidx < dat->nsections && !tbl_found; secidx++)
  244. {
  245. if(dat->elf_sec[secidx].sh_name >= dat->elf_sec[dat->shstrndx].sh_size)
  246. return ENCIP_ERROR_PARSE_ELF_INVALID_IMAGE;
  247. char* sec_name = dat->sections_names + dat->elf_sec[secidx].sh_name;
  248. /*
  249. * Verifying string starts before end of section. Assuming (but not checking)
  250. * that string ends before end of section. Additional check will complicate code.
  251. * Assuming the platform this application is running on is not compromized.
  252. */
  253. if((uint8_t*)sec_name >= elf_buf + elf_size)
  254. return ENCIP_ERROR_PARSE_ELF_INVALID_IMAGE;
  255. if(0 == strcmp(sec_name, PCLTBL_SECTION_NAME))
  256. {
  257. *tbl_pp = (pcl_table_t *)(elf_buf + dat->elf_sec[secidx].sh_offset);
  258. if((uint8_t*)(*tbl_pp) + sizeof(pcl_table_t) >= elf_buf + elf_size)
  259. return ENCIP_ERROR_PARSE_ELF_INVALID_IMAGE;
  260. // Verify table is aligned:
  261. if(0 != dat->elf_sec[secidx].sh_offset % PCL_TABLE_ALLIGNMENT)
  262. return ENCIP_ERROR_TBL_NOT_ALIGNED;
  263. tbl_found = true;
  264. }
  265. }
  266. if(!tbl_found)
  267. return ENCIP_ERROR_TBL_NOT_FOUND;
  268. return ENCIP_SUCCESS;
  269. }
  270. /*
  271. * @func rdrand_supported uses CPUID to check if platform supports RDRAND
  272. * @return true iff platform supports RDRAND
  273. */
  274. bool rdrand_supported()
  275. {
  276. int cpu_info[4] = {0, 0, 0, 0};
  277. __cpuid(cpu_info, 1);
  278. return (!!(cpu_info[2] & SUPPORT_RDRAND));
  279. }
  280. /*
  281. * @func init_random_iv initiates iv with a random number
  282. * @param OUT uint8_t* iv, pointer to output random IV
  283. * @return encip_ret_e:
  284. * ENCIP_ERROR_RANDIV_INVALID_PARAM if iv is NULL
  285. * ENCIP_ERROR_RDRAND_NOT_SUPPORTED if platform does not support RDRAND
  286. * ENCIP_ERROR_RDRAND_FAILED if random number gneration fails
  287. * ENCIP_SUCCESS if successfull
  288. */
  289. static encip_ret_e init_random_iv(OUT uint8_t* iv)
  290. {
  291. if(NULL == iv)
  292. return ENCIP_ERROR_RANDIV_INVALID_PARAM;
  293. if(rdrand_supported())
  294. {
  295. uint32_t* ivp = (uint32_t*)iv;
  296. // Get a random IV for encryption:
  297. for(uint32_t i=0;i < SGX_AESGCM_IV_SIZE / sizeof(uint32_t);i++)
  298. {
  299. uint32_t randval = 0;
  300. int rdrand32ret = _rdrand32_step(&randval);
  301. if(RDRAND_SUCCESS != rdrand32ret)
  302. return ENCIP_ERROR_RDRAND_FAILED;
  303. *ivp = randval;
  304. ivp++;
  305. }
  306. }
  307. else
  308. {
  309. return ENCIP_ERROR_RDRAND_NOT_SUPPORTED;
  310. }
  311. return ENCIP_SUCCESS;
  312. }
  313. /*
  314. * @func update_flags updates the flags of sections or segments that must become writable
  315. * @param uint16_t secidx, index of section for which the flags are currently updated
  316. * @param INOUT pcl_data_t* dat, ELF data
  317. * @return encip_ret_e, ENCIP_ERROR_UPDATEF_INVALID_PAR if dat is NULL, else ENCIP_SUCCESS
  318. */
  319. static inline encip_ret_e update_flags(uint16_t secidx, INOUT pcl_data_t* dat)
  320. {
  321. if(NULL == dat)
  322. return ENCIP_ERROR_UPDATEF_INVALID_PAR;
  323. // Mark section as writable:
  324. dat->elf_sec[secidx].sh_flags |= SHF_WRITE;
  325. Elf64_Addr secstart = dat->elf_sec[secidx].sh_addr;
  326. size_t secsize = dat->elf_sec[secidx].sh_size;
  327. /*
  328. * If section overlaps segment:
  329. * 1. Verify segment is readable
  330. * 2. Mark segment as writable
  331. */
  332. for(uint16_t segidx=0;segidx<dat->nsegments;segidx++)
  333. {
  334. Elf64_Addr segstart = dat->phdr[segidx].p_vaddr;
  335. size_t segsize = dat->phdr[segidx].p_memsz;
  336. if(((secstart < segstart + segsize) && (secstart >= segstart )) ||
  337. ((secstart + secsize > segstart ) && (secstart + secsize <= segstart + segsize)))
  338. {
  339. // Segment must be readible:
  340. if(!(dat->phdr[segidx].p_flags & (Elf64_Word)PF_R))
  341. {
  342. printf("\n\nError: segment %d ", segidx);
  343. if(dat->elf_sec[secidx].sh_name < dat->elf_sec[dat->shstrndx].sh_size)
  344. {
  345. char* sec_name = dat->sections_names + dat->elf_sec[secidx].sh_name;
  346. /*
  347. * Verifying string starts before end of section. Assuming (but not checking)
  348. * that string ends before end of section. Additional check will complicate code.
  349. * Assuming the platform this application is running on is not compromized.
  350. */
  351. printf("overlaps encrypted section \"%s\" and ", sec_name);
  352. }
  353. printf("is not readable. Exiting!!!\n\n\n");
  354. return ENCIP_ERROR_SEGMENT_NOT_READABLE;
  355. }
  356. // Mark segment as wirtable:
  357. dat->phdr[segidx].p_flags |= (Elf64_Word)PF_W;
  358. }
  359. }
  360. return ENCIP_SUCCESS;
  361. }
  362. /*
  363. * @func encrypt_or_clear_ip_sections modifies the content of some sections.
  364. * 1. If section content cannot be modified without disrupting enclave signing or loading flows
  365. * then section content is not modified
  366. * 2. Allocable sections (copied to application address space at shared object's load time)
  367. * are encrypted.
  368. * 3. The content of sections that are not allocable is zeroed
  369. * @param IN pcl_data_t* dat, ELF data
  370. * @param IN uint8_t* key, the AES key for GCM encrypt
  371. * @param INOUT uint8_t* elf_buf, base address of ELF binary buffer
  372. * @param OUT pcl_table_t* tbl, pointer to PCL table
  373. * @param OUT uint32_t* num_rvas_out, total number of sections that are encrypted
  374. * @param bool debug, true iff enclave is requried to support debug
  375. * @return encip_ret_e:
  376. * ENCIP_ERROR_ENCSECS_INVALID_PARAM any input parameter is NULL
  377. * PCL_MAX_NUM_ENCRYPTED_SECTIONS if out of entires in PCL table
  378. * Respective error results in case any of the functions encrypt or update_flags fail.
  379. * ENCIP_SUCCESS if success
  380. */
  381. static encip_ret_e encrypt_or_clear_ip_sections(
  382. IN pcl_data_t* dat,
  383. IN uint8_t* key,
  384. INOUT uint8_t* elf_buf,
  385. size_t elf_size,
  386. OUT pcl_table_t* tbl,
  387. OUT uint32_t* num_rvas_out,
  388. bool debug)
  389. {
  390. if(
  391. NULL == dat ||
  392. NULL == key ||
  393. NULL == elf_buf ||
  394. NULL == tbl ||
  395. NULL == num_rvas_out)
  396. return ENCIP_ERROR_ENCSECS_INVALID_PARAM;
  397. uint32_t num_rvas = 0;
  398. // Go over sections headers to find sections to encrypt or clear:
  399. char* sec_name = NULL;
  400. for(uint16_t secidx = 1; secidx < dat->nsections; secidx++)
  401. {
  402. if(dat->elf_sec[secidx].sh_name >= dat->elf_sec[dat->shstrndx].sh_size)
  403. return ENCIP_ERROR_PARSE_ELF_INVALID_IMAGE;
  404. sec_name = dat->sections_names + dat->elf_sec[secidx].sh_name;
  405. /*
  406. * Verifying string starts before end of section. Assuming (but not checking)
  407. * that string ends before end of section. Additional check will complicate code.
  408. * Assuming the platform this application is running on is not compromized.
  409. */
  410. if((uint8_t*)sec_name > elf_buf + elf_size)
  411. return ENCIP_ERROR_PARSE_ELF_INVALID_IMAGE;
  412. if(can_modify(sec_name, debug))
  413. {
  414. uint8_t* va = (uint8_t *)(elf_buf + dat->elf_sec[secidx].sh_offset);
  415. size_t size = dat->elf_sec[secidx].sh_size;
  416. if((va >= elf_buf + elf_size) ||
  417. (va + size < va) ||
  418. (va + size > elf_buf + elf_size))
  419. return ENCIP_ERROR_PARSE_ELF_INVALID_IMAGE;
  420. // If section is allocable (mapped into process's virtual memory), decrypt it:
  421. if(SHF_ALLOC & dat->elf_sec[secidx].sh_flags)
  422. {
  423. if(PCL_MAX_NUM_ENCRYPTED_SECTIONS <= num_rvas)
  424. {
  425. /*
  426. * No more empty entries in PCL table.
  427. * To fix - redefine PCL_MAX_NUM_ENCRYPTED_SECTIONS in pcl_common.h
  428. */
  429. printf("Error: No more empty entries in Intel(R) SGX PCL table\n");
  430. printf("To fix - redefine PCL_MAX_NUM_ENCRYPTED_SECTIONS in pcl_common.h\n");
  431. return ENCIP_ERROR_ENCSECS_RVAS_OVERFLOW;
  432. }
  433. if(PCL_GCM_NUM_BLOCKS(size) > PCL_GCM_MAX_NUM_BLOCKS)
  434. {
  435. /*
  436. * Size in 16-bytes-blocks exceeds (2^32 - 2).
  437. * Only happen if cipher-text size is ~64GB.
  438. */
  439. return ENCIP_ERROR_ENCSECS_COUNTER_OVERFLOW;
  440. }
  441. uint8_t* iv = (uint8_t*)&(tbl->rvas_sizes_tags_ivs[num_rvas].iv.val);
  442. encip_ret_e ret = init_random_iv(iv);
  443. if(ENCIP_ERROR(ret))
  444. return ret;
  445. uint8_t* tag = (uint8_t*)&(tbl->rvas_sizes_tags_ivs[num_rvas].tag);
  446. ret = gcm_encrypt(va, size, NULL, 0, (uint8_t *)key, iv, va, tag);
  447. if(ENCIP_ERROR(ret))
  448. {
  449. printf("Failed to gcm-encrypt section %s\n", sec_name);
  450. return ret;
  451. }
  452. // Insert entry to table:
  453. tbl->rvas_sizes_tags_ivs[num_rvas].rva = dat->elf_sec[secidx].sh_addr;
  454. tbl->rvas_sizes_tags_ivs[num_rvas].size = size;
  455. // Update flags to writable:
  456. ret = update_flags(secidx, dat);
  457. if(ENCIP_ERROR(ret))
  458. return ret;
  459. // Increment num_rvas:
  460. num_rvas++;
  461. }
  462. // Else (section is not allocable), zero it:
  463. else
  464. {
  465. memset(va, 0, size);
  466. }
  467. }
  468. }
  469. *num_rvas_out = num_rvas;
  470. return ENCIP_SUCCESS;
  471. }
  472. /*
  473. * @func encrypt_ip modifies the content of some sections.
  474. * @param INOUT uint8_t* elf_buf, buffer of ELF binary
  475. * @param size_t elf_size, size of ELF binary in bytes
  476. * @param IN uint8_t* key, AES-GCM-128 key
  477. * @param bool debug, true iff enclave is requried to support debug
  478. * @return encip_ret_e:
  479. * ENCIP_ERROR_ENCRYPTIP_INVALID_PARAM if any input parameter is NULL
  480. * Respective error results in case any of the following functions fail:
  481. * parse_elf, get_pcl_tbl init_random_iv, encrypt_or_clear_ip_sections or sha256
  482. * ENCIP_ERROR_MEM_ALLOC if memory allocation fails
  483. * ENCIP_ERROR_SEALED_BUF_SIZE if sealed buf size exceeds the size allocated for it in PCL table
  484. * ENCIP_SUCCESS if success
  485. */
  486. encip_ret_e encrypt_ip(INOUT uint8_t* elf_buf, size_t elf_size, IN uint8_t* key, bool debug)
  487. {
  488. if(NULL == elf_buf || NULL == key)
  489. return ENCIP_ERROR_ENCRYPTIP_INVALID_PARAM;
  490. encip_ret_e ret = ENCIP_ERROR_FAIL;
  491. pcl_data_t dat = {
  492. .elf_sec = 0,
  493. .shstrndx = 0,
  494. .sections_names = NULL,
  495. .phdr = NULL,
  496. .nsections = 0,
  497. .nsegments = 0,
  498. };
  499. pcl_table_t* tbl = NULL;
  500. ret = parse_elf(elf_buf, elf_size, &dat);
  501. if(ENCIP_ERROR(ret))
  502. return ret;
  503. ret = get_pcl_tbl(elf_buf, elf_size, &dat, &tbl);
  504. if(ENCIP_ERROR(ret))
  505. return ret;
  506. // Verify state of binary:
  507. if(PCL_CIPHER == tbl->pcl_state)
  508. return ENCIP_ERROR_ALREADY_ENCRYPTED;
  509. if(PCL_PLAIN != tbl->pcl_state)
  510. return ENCIP_ERROR_IMPROPER_STATE;
  511. // Encrypt or clear IP sections:
  512. uint32_t num_rvas = 0;
  513. ret = encrypt_or_clear_ip_sections(&dat, key, elf_buf, elf_size, tbl, &num_rvas, debug);
  514. if(ENCIP_ERROR(ret))
  515. return ret;
  516. // Set GUID:
  517. memcpy(tbl->pcl_guid, g_pcl_guid, sizeof(tbl->pcl_guid));
  518. // Set sealed blob size:
  519. tbl->sealed_blob_size = (size_t)sgx_calc_sealed_data_size(SGX_PCL_GUID_SIZE, SGX_AESGCM_KEY_SIZE);
  520. // Verify calculated size equals hard coded size of buffer in PCL table:
  521. if(PCL_SEALED_BLOB_SIZE != tbl->sealed_blob_size)
  522. return ENCIP_ERROR_SEALED_BUF_SIZE;
  523. // Set num RVAs:
  524. tbl->num_rvas = num_rvas;
  525. // Set decryption key sha256 hash result:
  526. ret = sha256(key, SGX_AESGCM_KEY_SIZE, tbl->decryption_key_hash);
  527. if(ENCIP_ERROR(ret))
  528. return ret;
  529. // Set PCL state
  530. tbl->pcl_state = PCL_CIPHER;
  531. return ENCIP_SUCCESS;
  532. }
  533. /*
  534. * @func print_usage prints sgx_encrypt usage instructions
  535. * @param IN char* encip_name is the name of the application
  536. */
  537. void print_usage(IN char* encip_name)
  538. {
  539. printf("\n");
  540. printf("\tUsage: \n");
  541. printf("\t %s -i <input enclave so file name> -o <output enclave so file name> -k <key file name> [-d]\n",
  542. encip_name);
  543. printf("\t -d (optional) prevents the tool from disabling the debug capabilities\n");
  544. printf("\n");
  545. }
  546. /*
  547. * @func parse_args parses the application's input argument.
  548. * @param int argc is the number of arguments
  549. * @param IN char* argv[] is the array of input arguments
  550. * @param OUT char** ifname points to the name of the original input enclave binary file
  551. * @param OUT char** ofname points to the name of the modified output enclave binary file
  552. * @param OUT char** kfname points to the name of the input key file
  553. * @param OUT bool* debug, true if enclave needs to support debug
  554. * the encrypted enclave binary.
  555. * @return encip_ret_e:
  556. * ENCIP_ERROR_PARSE_INVALID_PARAM if any of the input parameters is NULL
  557. * ENCIP_ERROR_PARSE_ARGS if input arguments are not supported
  558. * ENCIP_SUCCESS if success
  559. */
  560. encip_ret_e parse_args(
  561. int argc,
  562. IN char* argv[],
  563. OUT char** ifname,
  564. OUT char** ofname,
  565. OUT char** kfname,
  566. OUT bool* debug)
  567. {
  568. if(NULL == argv)
  569. return ENCIP_ERROR_PARSE_INVALID_PARAM;
  570. char* encip_name = argv[0];
  571. if((argc != 7 && argc != 8) ||
  572. NULL == ifname ||
  573. NULL == ofname ||
  574. NULL == kfname)
  575. {
  576. print_usage(encip_name);
  577. return ENCIP_ERROR_PARSE_INVALID_PARAM;
  578. }
  579. encip_ret_e ret = ENCIP_SUCCESS;
  580. for(int argidx = 1; argidx < argc; argidx++)
  581. {
  582. if(!strcmp(argv[argidx],"-d"))
  583. {
  584. *debug = true;
  585. }
  586. else if(!strcmp(argv[argidx],"-i") && argidx + 1 < argc)
  587. {
  588. argidx++;
  589. *ifname = argv[argidx];
  590. }
  591. else if(!strcmp(argv[argidx],"-o") && argidx + 1 < argc)
  592. {
  593. argidx++;
  594. *ofname = argv[argidx]; }
  595. else if(!strcmp(argv[argidx],"-k") && argidx + 1 < argc)
  596. {
  597. argidx++;
  598. *kfname = argv[argidx];
  599. }
  600. else
  601. {
  602. ret = ENCIP_ERROR_PARSE_ARGS;
  603. }
  604. }
  605. if((ENCIP_SUCCESS != ret) ||
  606. (NULL == *ifname) ||
  607. (NULL == *ofname) ||
  608. (NULL == *kfname))
  609. {
  610. print_usage(encip_name);
  611. ret = ENCIP_ERROR_PARSE_ARGS;
  612. }
  613. return ret;
  614. }
  615. /*
  616. * @func read_file reads file into buffer.
  617. * @param IN const char* const ifname is the input file name
  618. * @param OUT uint8_t** buf_pp points to the output buffer
  619. * @param OUT size_t* size_out points to the output data size
  620. * @return encip_ret_e:
  621. * ENCIP_ERROR_READF_INVALID_PARAM if any of the input parameters is NULL
  622. * ENCIP_ERROR_READF_OPEN if unable to open input file
  623. * ENCIP_ERROR_READF_ALLOC if unable to allocate output buffer
  624. * ENCIP_ERROR_READF_READ if unable to read file to buffer
  625. * ENCIP_SUCCESS if success
  626. */
  627. static encip_ret_e read_file(IN const char* const ifname, OUT uint8_t** buf_pp, OUT size_t* size_out)
  628. {
  629. if(NULL == ifname || NULL == buf_pp || NULL == size_out)
  630. return ENCIP_ERROR_READF_INVALID_PARAM;
  631. FILE* fin = fopen(ifname, "rb");
  632. if(NULL == fin)
  633. return ENCIP_ERROR_READF_OPEN;
  634. fseek(fin,0,SEEK_END);
  635. size_t const size = ftell(fin);
  636. fseek(fin, 0, SEEK_SET);
  637. *buf_pp = (uint8_t*)malloc(size);
  638. if(NULL == *buf_pp)
  639. {
  640. fclose(fin);
  641. return ENCIP_ERROR_MEM_ALLOC;
  642. }
  643. size_t const num_bytes = fread(*buf_pp, 1, size, fin);
  644. if(num_bytes != size)
  645. {
  646. fclose(fin);
  647. free (*buf_pp);
  648. return ENCIP_ERROR_READF_READ;
  649. }
  650. fclose(fin);
  651. *size_out = size;
  652. return ENCIP_SUCCESS;
  653. }
  654. /*
  655. * @func write_file writes buffer into file
  656. * @param IN char* ofname is the output file name
  657. * @param IN uint8_t* buf is the input buffer
  658. * @param size_t size is the size of the buffer
  659. * @return encip_ret_e:
  660. * ENCIP_ERROR_WRITEF_INVALID_PARAM if any of the input parameters is NULL
  661. * ENCIP_ERROR_WRITEF_OPEN if unable to open output file
  662. * ENCIP_ERROR_WRITEF_WRITE if unable to write buf to file
  663. * ENCIP_SUCCESS if success
  664. */
  665. static encip_ret_e write_file(IN const char* const ofname, IN uint8_t* buf, size_t size)
  666. {
  667. if(NULL == ofname || NULL == buf)
  668. return ENCIP_ERROR_WRITEF_INVALID_PARAM;
  669. FILE* fout = fopen(ofname, "wb");
  670. if(NULL == fout)
  671. return ENCIP_ERROR_WRITEF_OPEN;
  672. size_t num_bytes = fwrite(buf, 1, size, fout);
  673. if(num_bytes != size)
  674. {
  675. fclose(fout);
  676. return ENCIP_ERROR_WRITEF_WRITE;
  677. }
  678. fclose(fout);
  679. return ENCIP_SUCCESS;
  680. }
  681. /*
  682. * @func sha256 calculates SHA256
  683. * @param IN const void* const buf is the input payload
  684. * @param size_t buflen is the payload length in bytes
  685. * @param OUT uint8_t* hash is the resulting output hash
  686. * @return encip_ret_e:
  687. * ENCIP_ERROR_SHA_INVALID_PARAM if any of the input parameters is NULL
  688. * ENCIP_ERROR_SHA_ALLOC if EVP_MD_CTX_create is unable to allocate buffer
  689. * ENCIP_ERROR_SHA_INIT is EVP_DigestInit_ex fails
  690. * ENCIP_ERROR_SHA_UPDATE if EVP_DigestUpdate fails
  691. * ENCIP_ERROR_SHA_FINAL if EVP_DigestFinal_ex fails
  692. * ENCIP_SUCCESS if success
  693. */
  694. encip_ret_e sha256(IN const void* const buf, size_t buflen, OUT uint8_t* hash)
  695. {
  696. encip_ret_e ret = ENCIP_ERROR_FAIL;
  697. unsigned int digest_len = 0;
  698. if(NULL== buf || NULL== hash)
  699. return ENCIP_ERROR_SHA_INVALID_PARAM;
  700. EVP_MD_CTX *mdctx = EVP_MD_CTX_create();
  701. if(NULL == mdctx)
  702. return ENCIP_ERROR_SHA_ALLOC;
  703. if(EVP_SUCCESS != EVP_DigestInit_ex(mdctx, EVP_sha256(), NULL)){
  704. ret = ENCIP_ERROR_SHA_INIT;
  705. goto Label_free_context;
  706. }
  707. if(EVP_SUCCESS != EVP_DigestUpdate(mdctx, buf, buflen)){
  708. ret = ENCIP_ERROR_SHA_UPDATE;
  709. goto Label_free_context;
  710. }
  711. if((EVP_SUCCESS != EVP_DigestFinal_ex(mdctx, hash, &digest_len)) ||
  712. (SGX_SHA256_HASH_SIZE != digest_len)){
  713. ret = ENCIP_ERROR_SHA_FINAL;
  714. goto Label_free_context;
  715. }
  716. ret = ENCIP_SUCCESS;
  717. Label_free_context:
  718. EVP_MD_CTX_destroy(mdctx);
  719. return ret;
  720. }
  721. /*
  722. * @func gcm_encrypt calculates AES-GCM-128
  723. * @param IN unsigned char *plaintext, input plain text
  724. * @param int plaintext_len, size of plain text in bytes
  725. * @param IN unsigned char *aad, AAD
  726. * @param int aad_len, size of AAD in bytes
  727. * @param IN unsigned char *key, key
  728. * @param IN unsigned char *iv, iv
  729. * @param OUT unsigned char *ciphertext, output cipher text
  730. * @param OUT unsigned char *tag, GCM TAG result
  731. * @return encip_ret_e:
  732. * ENCIP_ERROR_GCM_ENCRYPT_INVALID_PARAM if any of the input parameters is NULL
  733. * ENCIP_ERROR_ENCRYPT_ALLOC if EVP_CIPHER_CTX_new is unable to allocate the requried buffer
  734. * ENCIP_ERROR_ENCRYPT_INIT_EX if initializing encryption function with EVP_EncryptInit_ex fails
  735. * ENCIP_ERROR_ENCRYPT_IV_LEN if setting IV length with EVP_CIPHER_CTX_ctrl fails
  736. * ENCIP_ERROR_ENCRYPT_INIT_KEY if setting key with EVP_EncryptInit_ex fails
  737. * ENCIP_ERROR_ENCRYPT_AAD if initializing AAD using EVP_EncryptUpdate fails
  738. * ENCIP_ERROR_ENCRYPT_UPDATE if encryption using EVP_EncryptUpdate fails
  739. * ENCIP_ERROR_ENCRYPT_FINAL if call to EVP_EncryptFinal_ex fails
  740. * ENCIP_ERROR_ENCRYPT_TAG if calculating TAG result using EVP_CIPHER_CTX_ctrl fails
  741. * ENCIP_SUCCESS if success
  742. */
  743. encip_ret_e gcm_encrypt(
  744. IN unsigned char *plaintext,
  745. size_t plaintext_len,
  746. IN unsigned char *aad,
  747. size_t aad_len,
  748. IN unsigned char *key,
  749. IN unsigned char *iv,
  750. OUT unsigned char *ciphertext,
  751. OUT unsigned char *tag)
  752. {
  753. EVP_CIPHER_CTX *ctx;
  754. int len;
  755. encip_ret_e ret = ENCIP_ERROR_GCM_ENCRYPT_INVALID_PARAM;
  756. if( NULL == plaintext ||
  757. NULL == key ||
  758. NULL == iv ||
  759. NULL == ciphertext ||
  760. NULL == tag)
  761. return ENCIP_ERROR_GCM_ENCRYPT_INVALID_PARAM;
  762. // Create and init context
  763. if(NULL == (ctx = EVP_CIPHER_CTX_new()))
  764. return ENCIP_ERROR_ENCRYPT_ALLOC;
  765. // Init the encryption function
  766. if(EVP_SUCCESS != EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, NULL, NULL))
  767. {
  768. ret = ENCIP_ERROR_ENCRYPT_INIT_EX;
  769. goto Label_gcm_cleanup;
  770. }
  771. // Set IV length to SGX_AESGCM_IV_SIZE
  772. if(EVP_SUCCESS != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, SGX_AESGCM_IV_SIZE, NULL))
  773. {
  774. ret = ENCIP_ERROR_ENCRYPT_IV_LEN;
  775. goto Label_gcm_cleanup;
  776. }
  777. // Init key and IV:
  778. if(EVP_SUCCESS != EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv))
  779. {
  780. ret = ENCIP_ERROR_ENCRYPT_INIT_KEY;
  781. goto Label_gcm_cleanup;
  782. }
  783. // Init AAD:
  784. if(NULL != aad)
  785. {
  786. if(EVP_SUCCESS != EVP_EncryptUpdate(ctx, NULL, &len, aad, (int)aad_len))
  787. {
  788. ret = ENCIP_ERROR_ENCRYPT_AAD;
  789. goto Label_gcm_cleanup;
  790. }
  791. }
  792. // Encrypt:
  793. if(EVP_SUCCESS != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, (int)plaintext_len))
  794. {
  795. ret = ENCIP_ERROR_ENCRYPT_UPDATE;
  796. goto Label_gcm_cleanup;
  797. }
  798. // Final:
  799. if(EVP_SUCCESS != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len))
  800. {
  801. ret = ENCIP_ERROR_ENCRYPT_FINAL;
  802. goto Label_gcm_cleanup;
  803. }
  804. // Get Tag:
  805. if(EVP_SUCCESS != EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, SGX_CMAC_MAC_SIZE, tag))
  806. {
  807. ret = ENCIP_ERROR_ENCRYPT_TAG;
  808. goto Label_gcm_cleanup;
  809. }
  810. ret = ENCIP_SUCCESS;
  811. // Cleanup:
  812. Label_gcm_cleanup:
  813. EVP_CIPHER_CTX_free(ctx);
  814. return ret;
  815. }