sign_tool.cpp 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123
  1. /*
  2. * Copyright (C) 2011-2017 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. // SignTool.cpp : Defines the entry point for the console application.
  32. //
  33. /**
  34. * File:
  35. * sign_tool.cpp
  36. *Description:
  37. * Defines the entry point for the application.
  38. *
  39. */
  40. #include <openssl/bio.h>
  41. #include <openssl/bn.h>
  42. #include <openssl/sha.h>
  43. #include <openssl/rsa.h>
  44. #include <openssl/evp.h>
  45. #include <openssl/err.h>
  46. #include "metadata.h"
  47. #include "manage_metadata.h"
  48. #include "parse_key_file.h"
  49. #include "enclave_creator_sign.h"
  50. #include "util_st.h"
  51. #include "se_trace.h"
  52. #include "sgx_error.h"
  53. #include "se_map.h"
  54. #include "loader.h"
  55. #include "parserfactory.h"
  56. #include "elf_helper.h"
  57. #include "crypto_wrapper.h"
  58. #include <unistd.h>
  59. #include <stdio.h>
  60. #include <stdlib.h>
  61. #include <assert.h>
  62. #include <string>
  63. #include <memory>
  64. #include <sstream>
  65. #define SIGNATURE_SIZE 384
  66. typedef enum _file_path_t
  67. {
  68. DLL = 0,
  69. XML = 1,
  70. KEY,
  71. OUTPUT,
  72. SIG,
  73. UNSIGNED,
  74. DUMPFILE
  75. } file_path_t;
  76. static int load_enclave(BinParser *parser, metadata_t *metadata)
  77. {
  78. std::unique_ptr<CLoader> ploader(new CLoader(const_cast<uint8_t *>(parser->get_start_addr()), *parser));
  79. return ploader->load_enclave_ex(NULL, 0, metadata, NULL);
  80. }
  81. #define THE_INVALID_HANDLE (-1)
  82. static int open_file(const char* dllpath)
  83. {
  84. FILE *fp = fopen(dllpath, "rb");
  85. if (fp == NULL)
  86. return THE_INVALID_HANDLE;
  87. return fileno(fp);
  88. }
  89. static void close_handle(int fd)
  90. {
  91. close(fd);
  92. }
  93. static bool get_enclave_info(BinParser *parser, bin_fmt_t *bf, uint64_t * meta_offset, bool is_dump_mode = false)
  94. {
  95. uint64_t meta_rva = parser->get_metadata_offset();
  96. const uint8_t *base_addr = parser->get_start_addr();
  97. metadata_t *metadata = GET_PTR(metadata_t, base_addr, meta_rva);
  98. if(metadata->magic_num == METADATA_MAGIC && is_dump_mode == false)
  99. {
  100. se_trace(SE_TRACE_ERROR, ENCLAVE_ALREADY_SIGNED_ERROR);
  101. return false;
  102. }
  103. *bf = parser->get_bin_format();
  104. *meta_offset = meta_rva;
  105. return true;
  106. }
  107. // measure_enclave():
  108. // 1. Get the enclave hash by loading enclave
  109. // 2. Get the enclave info - metadata offset and enclave file format
  110. static bool measure_enclave(uint8_t *hash, const char *dllpath, const xml_parameter_t *parameter, bool ignore_rel_error, metadata_t *metadata, uint64_t *meta_offset)
  111. {
  112. assert(hash && dllpath && metadata && meta_offset);
  113. bool res = false;
  114. uint32_t file_size = 0;
  115. uint64_t quota = 0;
  116. bin_fmt_t bin_fmt = BF_UNKNOWN;
  117. se_file_handle_t fh = open_file(dllpath);
  118. if (fh == THE_INVALID_HANDLE)
  119. {
  120. se_trace(SE_TRACE_ERROR, OPEN_FILE_ERROR, dllpath);
  121. return false;
  122. }
  123. // Probably we can use `decltype' if all major supported compilers support that.
  124. std::unique_ptr<map_handle_t, void (*)(map_handle_t*)> mh(map_file(fh, &file_size), unmap_file);
  125. if (!mh)
  126. {
  127. close_handle(fh);
  128. return false;
  129. }
  130. // Parse enclave
  131. std::unique_ptr<BinParser> parser(binparser::get_parser(mh->base_addr, (size_t)file_size));
  132. assert(parser != NULL);
  133. sgx_status_t status = parser->run_parser();
  134. if (status != SGX_SUCCESS)
  135. {
  136. se_trace(SE_TRACE_ERROR, INVALID_ENCLAVE_ERROR);
  137. close_handle(fh);
  138. return false;
  139. }
  140. // generate metadata
  141. CMetadata meta(metadata, parser.get());
  142. if(meta.build_metadata(parameter) == false)
  143. {
  144. close_handle(fh);
  145. return false;
  146. }
  147. // Collect enclave info
  148. if(get_enclave_info(parser.get(), &bin_fmt, meta_offset) == false)
  149. {
  150. close_handle(fh);
  151. return false;
  152. }
  153. bool no_rel = false;
  154. if (bin_fmt == BF_ELF64)
  155. {
  156. no_rel = ElfHelper<64>::dump_textrels(parser.get());
  157. }
  158. else
  159. {
  160. no_rel = ElfHelper<32>::dump_textrels(parser.get());
  161. }
  162. if(no_rel == false && ignore_rel_error == false)
  163. {
  164. close_handle(fh);
  165. se_trace(SE_TRACE_ERROR, TEXT_REL_ERROR);
  166. return false;
  167. }
  168. // Load enclave to get enclave hash
  169. int ret = load_enclave(parser.release(), metadata);
  170. close_handle(fh);
  171. switch(ret)
  172. {
  173. case SGX_ERROR_INVALID_METADATA:
  174. se_trace(SE_TRACE_ERROR, OUT_OF_EPC_ERROR);
  175. res = false;
  176. break;
  177. case SGX_ERROR_INVALID_VERSION:
  178. se_trace(SE_TRACE_ERROR, META_VERSION_ERROR);
  179. res = false;
  180. break;
  181. case SGX_ERROR_INVALID_ENCLAVE:
  182. se_trace(SE_TRACE_ERROR, INVALID_ENCLAVE_ERROR);
  183. res = false;
  184. break;
  185. case SGX_SUCCESS:
  186. ret = dynamic_cast<EnclaveCreatorST*>(get_enclave_creator())->get_enclave_info(hash, SGX_HASH_SIZE, &quota);
  187. if(ret != SGX_SUCCESS)
  188. {
  189. res = false;
  190. break;
  191. }
  192. se_trace(SE_TRACE_ERROR, REQUIRED_ENCLAVE_SIZE, quota);
  193. res = true;
  194. break;
  195. default:
  196. res = false;
  197. break;
  198. }
  199. return res;
  200. }
  201. //fill_enclave_css()
  202. // fill the enclave_css_t structure with enclave_hash
  203. // If the 'rsa' is not null, fill the key part
  204. // If the path[UNSIGNED] != NULL, update the header.date(CATSIG mode)
  205. static bool fill_enclave_css(const RSA *rsa, const char **path,
  206. const uint8_t *enclave_hash, enclave_css_t *css)
  207. {
  208. assert(enclave_hash != NULL && path != NULL && css != NULL);
  209. //if rsa is not NULL, fill the public key part
  210. if(rsa)
  211. {
  212. int exponent_size = BN_num_bytes(rsa->e);
  213. int modulus_size = BN_num_bytes(rsa->n);
  214. if(modulus_size > SE_KEY_SIZE)
  215. return false;
  216. unsigned char *modulus = (unsigned char *)malloc(SE_KEY_SIZE);
  217. if(modulus == NULL)
  218. {
  219. return false;
  220. }
  221. memset(modulus, 0, SE_KEY_SIZE);
  222. exponent_size = (uint32_t)(ROUND_TO(exponent_size, sizeof(uint32_t)) / sizeof(uint32_t));
  223. modulus_size = (uint32_t)(ROUND_TO(modulus_size, sizeof(uint32_t)) / sizeof(uint32_t));
  224. if(BN_bn2bin(rsa->n, modulus) != SE_KEY_SIZE)
  225. {
  226. free(modulus);
  227. return false;
  228. }
  229. if(BN_bn2bin(rsa->e, (unsigned char *)&css->key.exponent) != 1)
  230. {
  231. free(modulus);
  232. return false;
  233. }
  234. for(unsigned int i = 0; i < SE_KEY_SIZE; i++)
  235. {
  236. css->key.modulus[i] = modulus[SE_KEY_SIZE -i - 1];
  237. }
  238. free(modulus);
  239. assert(css->key.exponent[0] == 0x03);
  240. assert(exponent_size == 0x1);
  241. assert(modulus_size == 0x60);
  242. }
  243. // fill the enclave hash
  244. memcpy_s(&css->body.enclave_hash, sizeof(css->body.enclave_hash), enclave_hash, SGX_HASH_SIZE);
  245. if(path[UNSIGNED] != NULL)
  246. {
  247. // In catsig mode, update the header.date as the time when the unsigned file is generated.
  248. enclave_css_t enclave_css;
  249. memset(&enclave_css, 0, sizeof(enclave_css));
  250. size_t fsize = get_file_size(path[UNSIGNED]);
  251. if(fsize != sizeof(enclave_css.header) + sizeof(enclave_css.body))
  252. {
  253. se_trace(SE_TRACE_ERROR, UNSIGNED_FILE_ERROR, path[UNSIGNED]);
  254. return false;
  255. }
  256. uint8_t *buf = new uint8_t[fsize];
  257. memset(buf, 0, fsize);
  258. if(read_file_to_buf(path[UNSIGNED], buf, fsize) == false)
  259. {
  260. se_trace(SE_TRACE_ERROR, READ_FILE_ERROR, path[UNSIGNED]);
  261. delete [] buf;
  262. return false;
  263. }
  264. memcpy_s(&enclave_css.header, sizeof(enclave_css.header), buf, sizeof(enclave_css.header));
  265. memcpy_s(&enclave_css.body, sizeof(enclave_css.body), buf + sizeof(enclave_css.header), fsize - sizeof(enclave_css.header));
  266. delete [] buf;
  267. css->header.date = enclave_css.header.date;
  268. // Verify the header and body read from the unsigned file to make sure it's the same as that generated from xml file
  269. if(memcmp(&enclave_css.header, &css->header, sizeof(enclave_css.header)) || memcmp(&enclave_css.body, &css->body, sizeof(enclave_css.body)))
  270. {
  271. se_trace(SE_TRACE_ERROR, UNSIGNED_FILE_XML_MISMATCH);
  272. return false;
  273. }
  274. }
  275. return true;
  276. }
  277. static bool calc_RSAq1q2(int length_s, const uint8_t *data_s, int length_m, const uint8_t *data_m,
  278. uint8_t *data_q1, uint8_t *data_q2)
  279. {
  280. assert(data_s && data_m && data_q1 && data_q2);
  281. bool ret = false;
  282. BIGNUM *ptemp1=NULL, *ptemp2=NULL, *pQ1=NULL, *pQ2=NULL, *pM=NULL, *pS = NULL;
  283. unsigned char *q1 = NULL, *q2= NULL;
  284. BN_CTX *ctx = NULL;
  285. do{
  286. if((ptemp1 = BN_new()) == NULL)
  287. break;
  288. if((ptemp2 = BN_new()) == NULL)
  289. break;
  290. if((pQ1 = BN_new()) == NULL)
  291. break;
  292. if((pQ2 = BN_new()) == NULL)
  293. break;
  294. if((pM = BN_new()) == NULL)
  295. break;
  296. if((pS = BN_new()) == NULL)
  297. break;
  298. if(BN_bin2bn((const unsigned char *)data_m, length_m, pM) == NULL)
  299. break;
  300. if(BN_bin2bn((const unsigned char *)data_s, length_s, pS) == NULL)
  301. break;
  302. if((ctx = BN_CTX_new()) == NULL)
  303. break;
  304. //q1 = floor(signature*signature/modulus)
  305. //q2 = floor((signature*signature.signature - q1*signature*Modulus)/Modulus)
  306. if(BN_mul(ptemp1, pS, pS, ctx) != 1)
  307. break;
  308. if(BN_div(pQ1, ptemp2, ptemp1, pM, ctx) !=1)
  309. break;
  310. if(BN_mul(ptemp1, pS, ptemp2, ctx) !=1)
  311. break;
  312. if(BN_div(pQ2, ptemp2, ptemp1, pM, ctx) !=1)
  313. break;
  314. int q1_len = BN_num_bytes(pQ1);
  315. int q2_len = BN_num_bytes(pQ2);
  316. if((q1 = (unsigned char *)malloc(q1_len)) == NULL)
  317. break;
  318. if((q2 = (unsigned char *)malloc(q2_len)) == NULL)
  319. break;
  320. if(q1_len != BN_bn2bin(pQ1, (unsigned char *)q1))
  321. break;
  322. if(q2_len != BN_bn2bin(pQ2, (unsigned char *)q2))
  323. break;
  324. int size_q1 = (q1_len < SE_KEY_SIZE) ? q1_len : SE_KEY_SIZE;
  325. int size_q2 = (q2_len < SE_KEY_SIZE) ? q2_len : SE_KEY_SIZE;
  326. for(int i = 0; i < size_q1; i++)
  327. {
  328. data_q1[i] = q1[size_q1 - i -1];
  329. }
  330. for(int i = 0; i < size_q2; i++)
  331. {
  332. data_q2[i] = q2[size_q2 - i -1];
  333. }
  334. ret = true;
  335. }while(0);
  336. if(q1)
  337. free(q1);
  338. if(q2)
  339. free(q2);
  340. if(ptemp1)
  341. BN_clear_free(ptemp1);
  342. if(ptemp2)
  343. BN_clear_free(ptemp2);
  344. if(pQ1)
  345. BN_clear_free(pQ1);
  346. if(pQ2)
  347. BN_clear_free(pQ2);
  348. if(pS)
  349. BN_clear_free(pS);
  350. if(pM)
  351. BN_clear_free(pM);
  352. if(ctx)
  353. BN_CTX_free(ctx);
  354. return ret;
  355. }
  356. static bool create_signature(const RSA *rsa, const char *sigpath, enclave_css_t *enclave_css)
  357. {
  358. assert(enclave_css != NULL);
  359. assert(!(rsa == NULL && sigpath == NULL) && !(rsa != NULL && sigpath != NULL));
  360. uint8_t signature[SIGNATURE_SIZE]; // keep the signature in big endian
  361. memset(signature, 0, SIGNATURE_SIZE);
  362. //**********get the signature*********
  363. if(sigpath != NULL)//CATSIG mode
  364. {
  365. if(get_file_size(sigpath) != SIGNATURE_SIZE)
  366. {
  367. se_trace(SE_TRACE_ERROR, SIG_FILE_ERROR, sigpath);
  368. return false;
  369. }
  370. if(read_file_to_buf(sigpath, signature, SIGNATURE_SIZE) == false)
  371. {
  372. se_trace(SE_TRACE_ERROR, READ_FILE_ERROR, sigpath);
  373. return false;
  374. }
  375. }
  376. else //SIGN mode
  377. {
  378. size_t buffer_size = sizeof(enclave_css->header) + sizeof(enclave_css->body);
  379. uint8_t * temp_buffer = (uint8_t *)malloc(buffer_size * sizeof(char));
  380. if(NULL == temp_buffer)
  381. {
  382. se_trace(SE_TRACE_ERROR, NO_MEMORY_ERROR);
  383. return false;
  384. }
  385. memcpy_s(temp_buffer, buffer_size, &enclave_css->header, sizeof(enclave_css->header));
  386. memcpy_s(temp_buffer + sizeof(enclave_css->header), buffer_size - sizeof(enclave_css->header),
  387. &enclave_css->body, sizeof(enclave_css->body));
  388. uint8_t hash[SGX_HASH_SIZE] = {0};
  389. unsigned int hash_size = SGX_HASH_SIZE;
  390. if(SGX_SUCCESS != sgx_EVP_Digest(EVP_sha256(), temp_buffer, (unsigned int)buffer_size, hash, &hash_size))
  391. {
  392. free(temp_buffer);
  393. return false;
  394. }
  395. size_t siglen;
  396. int ret = RSA_sign(NID_sha256, hash, hash_size, signature, (unsigned int *)&siglen, const_cast<RSA *>(rsa));
  397. free(temp_buffer);
  398. if(ret != 1)
  399. return false;
  400. }
  401. for(int i = 0; i<SIGNATURE_SIZE; i++)
  402. {
  403. (enclave_css->key.signature)[i] = signature[SIGNATURE_SIZE-1-i];
  404. }
  405. //************************calculate q1 and q2*********************
  406. uint8_t modulus[SE_KEY_SIZE];
  407. for(int i = 0; i<SE_KEY_SIZE; i++)
  408. {
  409. modulus[i] = enclave_css->key.modulus[SE_KEY_SIZE-1-i];
  410. }
  411. bool res = calc_RSAq1q2(sizeof(enclave_css->key.signature),
  412. (const uint8_t *)signature,
  413. sizeof(enclave_css->key.modulus),
  414. (const uint8_t *)modulus,
  415. (uint8_t *)enclave_css->buffer.q1,
  416. (uint8_t *)enclave_css->buffer.q2);
  417. return res;
  418. }
  419. static bool verify_signature(const RSA *rsa, const enclave_css_t *enclave_css)
  420. {
  421. assert(rsa != NULL && enclave_css != NULL);
  422. size_t buffer_size = sizeof(enclave_css->header) + sizeof(enclave_css->body);
  423. uint8_t *temp_buffer = (uint8_t *)malloc(buffer_size * sizeof(char));
  424. if(NULL == temp_buffer)
  425. {
  426. se_trace(SE_TRACE_ERROR, NO_MEMORY_ERROR);
  427. return false;
  428. }
  429. memcpy_s(temp_buffer, buffer_size, &enclave_css->header, sizeof(enclave_css->header));
  430. memcpy_s(temp_buffer + sizeof(enclave_css->header), buffer_size-sizeof(enclave_css->header),
  431. &enclave_css->body, sizeof(enclave_css->body));
  432. uint8_t hash[SGX_HASH_SIZE] = {0};
  433. unsigned int hash_size = SGX_HASH_SIZE;
  434. if(SGX_SUCCESS != sgx_EVP_Digest(EVP_sha256(), temp_buffer, (unsigned int)buffer_size, hash, &hash_size))
  435. {
  436. free(temp_buffer);
  437. return false;
  438. }
  439. free(temp_buffer);
  440. uint8_t signature[SIGNATURE_SIZE];
  441. for(int i=0; i<SIGNATURE_SIZE; i++)
  442. {
  443. signature[i] = enclave_css->key.signature[SIGNATURE_SIZE-1-i];
  444. }
  445. if(1 != RSA_verify(NID_sha256, hash, hash_size, signature, SIGNATURE_SIZE, const_cast<RSA *>(rsa)))
  446. {
  447. return false;
  448. }
  449. return true;
  450. }
  451. static bool gen_enclave_signing_file(const enclave_css_t *enclave_css, const char *outpath)
  452. {
  453. assert(enclave_css != NULL);
  454. size_t size = sizeof(enclave_css->header) + sizeof(enclave_css->body);
  455. uint8_t *buffer = (uint8_t *)malloc(size);
  456. if(buffer == NULL)
  457. {
  458. se_trace(SE_TRACE_ERROR, NO_MEMORY_ERROR);
  459. return false;
  460. }
  461. memcpy_s(buffer, sizeof(enclave_css->header), &enclave_css->header, sizeof(enclave_css->header));
  462. memcpy_s(buffer + sizeof(enclave_css->header), sizeof(enclave_css->body), &enclave_css->body, sizeof(enclave_css->body));
  463. if(write_data_to_file(outpath, std::ios::out|std::ios::binary, buffer, size) == false)
  464. {
  465. free(buffer);
  466. return false;
  467. }
  468. free(buffer);
  469. return true;
  470. }
  471. static bool cmdline_parse(unsigned int argc, char *argv[], int *mode, const char **path, bool *ignore_rel_error)
  472. {
  473. assert(mode!=NULL && path != NULL);
  474. if(argc<2)
  475. {
  476. se_trace(SE_TRACE_ERROR, LACK_PARA_ERROR);
  477. return false;
  478. }
  479. if(argc == 2 && !STRCMP(argv[1], "-help"))
  480. {
  481. se_trace(SE_TRACE_ERROR, USAGE_STRING);
  482. *mode = -1;
  483. return true;
  484. }
  485. enum { PAR_REQUIRED, PAR_OPTIONAL, PAR_INVALID };
  486. typedef struct _param_struct_{
  487. const char *name; //options
  488. char *value; //keep the path
  489. int flag; //indicate this parameter is required(0), optional(1) or invalid(2)
  490. }param_struct_t; //keep the parameter pairs
  491. param_struct_t params_sign[] = {
  492. {"-enclave", NULL, PAR_REQUIRED},
  493. {"-config", NULL, PAR_OPTIONAL},
  494. {"-key", NULL, PAR_REQUIRED},
  495. {"-out", NULL, PAR_REQUIRED},
  496. {"-sig", NULL, PAR_INVALID},
  497. {"-unsigned", NULL, PAR_INVALID},
  498. {"-review_enclave", NULL, PAR_INVALID},
  499. {"-dumpfile", NULL, PAR_OPTIONAL}};
  500. param_struct_t params_gendata[] = {
  501. {"-enclave", NULL, PAR_REQUIRED},
  502. {"-config", NULL, PAR_OPTIONAL},
  503. {"-key", NULL, PAR_INVALID},
  504. {"-out", NULL, PAR_REQUIRED},
  505. {"-sig", NULL, PAR_INVALID},
  506. {"-unsigned", NULL, PAR_INVALID},
  507. {"-review_enclave", NULL, PAR_INVALID},
  508. {"-dumpfile", NULL, PAR_INVALID}};
  509. param_struct_t params_catsig[] = {
  510. {"-enclave", NULL, PAR_REQUIRED},
  511. {"-config", NULL, PAR_OPTIONAL},
  512. {"-key", NULL, PAR_REQUIRED},
  513. {"-out", NULL, PAR_REQUIRED},
  514. {"-sig", NULL, PAR_REQUIRED},
  515. {"-unsigned", NULL, PAR_REQUIRED},
  516. {"-review_enclave", NULL, PAR_INVALID},
  517. {"-dumpfile", NULL, PAR_OPTIONAL}};
  518. param_struct_t params_dump[] = {
  519. {"-enclave", NULL, PAR_REQUIRED},
  520. {"-config", NULL, PAR_INVALID},
  521. {"-key", NULL, PAR_INVALID},
  522. {"-out", NULL, PAR_INVALID},
  523. {"-sig", NULL, PAR_INVALID},
  524. {"-unsigned", NULL, PAR_INVALID},
  525. {"-review_enclave", NULL, PAR_INVALID},
  526. {"-dumpfile", NULL, PAR_REQUIRED}};
  527. const char *mode_m[] ={"sign", "gendata","catsig", "dump"};
  528. param_struct_t *params[] = {params_sign, params_gendata, params_catsig, params_dump};
  529. unsigned int tempidx=0;
  530. for(; tempidx<sizeof(mode_m)/sizeof(mode_m[0]); tempidx++)
  531. {
  532. if(!STRCMP(mode_m[tempidx], argv[1]))//match
  533. {
  534. break;
  535. }
  536. }
  537. unsigned int tempmode = tempidx;
  538. if(tempmode>=sizeof(mode_m)/sizeof(mode_m[0]))
  539. {
  540. se_trace(SE_TRACE_ERROR, UNREC_CMD_ERROR, argv[1]);
  541. return false;
  542. }
  543. unsigned int err_idx = 2;
  544. for(; err_idx < argc; err_idx++)
  545. {
  546. if(!STRCMP(argv[err_idx], "-ignore-rel-error"))
  547. break;
  548. }
  549. unsigned int params_count = (unsigned)(sizeof(params_sign)/sizeof(params_sign[0]));
  550. unsigned int params_count_min = 0;
  551. unsigned int params_count_max =0;
  552. for(unsigned int i=0; i< params_count; i++)
  553. {
  554. params_count_max ++;
  555. if(params[tempmode][i].flag == PAR_REQUIRED)
  556. params_count_min ++;
  557. }
  558. unsigned int additional_param = 2;
  559. if(err_idx != argc)
  560. additional_param++;
  561. if(argc<params_count_min * 2 + additional_param)
  562. return false;
  563. if(argc>params_count_max * 2 + additional_param)
  564. return false;
  565. for(unsigned int i=2; i<argc; i=i+2)
  566. {
  567. if(i == err_idx)
  568. {
  569. i++;
  570. continue;
  571. }
  572. unsigned int j=0;
  573. for(; j<params_count; j++)
  574. {
  575. if(STRCMP(argv[i], params[tempmode][j].name)==0) //match
  576. {
  577. if((i<argc-1)&&(STRNCMP(argv[i+1],"-", 1))) // assuming pathname doesn't contain "-"
  578. {
  579. if(params[tempmode][j].value != NULL)
  580. {
  581. se_trace(SE_TRACE_ERROR, REPEAT_OPTION_ERROR, params[tempmode][j].name);
  582. return false;
  583. }
  584. params[tempmode][j].value = argv[i+1];
  585. break;
  586. }
  587. else //didn't match: 1) no path parameter behind option parameter 2) parameters format error.
  588. {
  589. se_trace(SE_TRACE_ERROR, INVALID_FILE_NAME_ERROR, params[tempmode][j].name);
  590. return false;
  591. }
  592. }
  593. }
  594. if(j>=params_count_max)
  595. {
  596. return false;
  597. }
  598. }
  599. for(unsigned int i = 0; i < params_count; i ++)
  600. {
  601. if(params[tempmode][i].flag == PAR_REQUIRED && params[tempmode][i].value == NULL)
  602. {
  603. se_trace(SE_TRACE_ERROR, LACK_REQUIRED_OPTION_ERROR, params[tempmode][i].name, mode_m[tempmode]);
  604. return false;
  605. }
  606. if(params[tempmode][i].flag == PAR_INVALID && params[tempmode][i].value != NULL)
  607. {
  608. se_trace(SE_TRACE_ERROR, GIVE_INVALID_OPTION_ERROR, params[tempmode][i].name, mode_m[tempmode]);
  609. return false;
  610. }
  611. }
  612. for(unsigned int i = 0; i < params_count; i++)
  613. {
  614. path[i] = params[tempmode][i].value;
  615. }
  616. *mode = tempmode;
  617. if(err_idx != argc)
  618. *ignore_rel_error = true;
  619. return true;
  620. }
  621. //generate_output:
  622. // To generate the final output file
  623. // SIGN- need to fill the enclave_css_t(key part included), sign the header and body and
  624. // update the metadata in the out file
  625. // GENDATA- need to fill the enclave_css_t(key part excluded), get the body and header,
  626. // and then write the whole out file with body+header+hash
  627. // CATSIG- need to fill the enclave_css_t(include key), read the signature from the sigpath,
  628. // and then update the metadata in the out file
  629. static bool generate_output(int mode, int ktype, const uint8_t *enclave_hash, const RSA *rsa, metadata_t *metadata,
  630. const char **path)
  631. {
  632. assert(enclave_hash != NULL && metadata != NULL && path != NULL);
  633. switch(mode)
  634. {
  635. case SIGN:
  636. {
  637. if(ktype != PRIVATE_KEY || !rsa)
  638. {
  639. se_trace(SE_TRACE_ERROR, LACK_PRI_KEY_ERROR);
  640. return false;
  641. }
  642. if(false == fill_enclave_css(rsa, path, enclave_hash, &(metadata->enclave_css)))
  643. {
  644. return false;
  645. }
  646. if(false == create_signature(rsa, NULL, &(metadata->enclave_css)))
  647. {
  648. return false;
  649. }
  650. break;
  651. }
  652. case GENDATA:
  653. {
  654. if(false == fill_enclave_css(NULL, path, enclave_hash, &(metadata->enclave_css)))
  655. {
  656. return false;
  657. }
  658. if(false == gen_enclave_signing_file(&(metadata->enclave_css), path[OUTPUT]))
  659. {
  660. return false;
  661. }
  662. break;
  663. }
  664. case CATSIG:
  665. {
  666. if(ktype != PUBLIC_KEY || !rsa)
  667. {
  668. se_trace(SE_TRACE_ERROR, LACK_PUB_KEY_ERROR);
  669. return false;
  670. }
  671. if(false == fill_enclave_css(rsa, path, enclave_hash, &(metadata->enclave_css)))
  672. {
  673. return false;
  674. }
  675. if(false == create_signature(NULL, path[SIG], &(metadata->enclave_css)))
  676. {
  677. return false;
  678. }
  679. break;
  680. }
  681. default:
  682. {
  683. return false;
  684. }
  685. }
  686. return true;
  687. }
  688. #include "se_page_attr.h"
  689. static void metadata_cleanup(metadata_t *metadata, uint32_t size_to_reduce)
  690. {
  691. metadata->dirs[DIR_LAYOUT].size -= size_to_reduce;
  692. metadata->size -= size_to_reduce;
  693. //if there exists LAYOUT_ID_HEAP_MAX, modify it so that it won't be included in the MRENCLAVE
  694. layout_t *start = GET_PTR(layout_t, metadata, metadata->dirs[DIR_LAYOUT].offset);
  695. layout_t *end = GET_PTR(layout_t, start, metadata->dirs[DIR_LAYOUT].size);
  696. for (layout_t *l = start; l < end; l++)
  697. {
  698. if (l->entry.id == LAYOUT_ID_HEAP_MAX)
  699. {
  700. l->entry.si_flags = SI_FLAG_NONE;
  701. l->entry.attributes &= (uint16_t)(~PAGE_ATTR_POST_ADD);
  702. break;
  703. }
  704. }
  705. //remove the PAGE_ATTR_POST_ADD attribute so that dynamic range won't be
  706. //created during enclave loading time
  707. for (layout_t *l = start; l < end; l++)
  708. {
  709. if (l->entry.id == LAYOUT_ID_HEAP_INIT)
  710. {
  711. l->entry.attributes &= (uint16_t)(~PAGE_ATTR_POST_ADD);
  712. break;
  713. }
  714. }
  715. }
  716. static bool append_compatible_metadata(metadata_t *compat_metadata, metadata_t *metadata)
  717. {
  718. metadata_t *dest_meta = metadata;
  719. uint32_t size = 0;
  720. do{
  721. if(dest_meta->magic_num != METADATA_MAGIC || dest_meta->size == 0)
  722. break;
  723. size += dest_meta->size;
  724. if(size < dest_meta->size)
  725. return false;
  726. dest_meta = (metadata_t *)((size_t)dest_meta + dest_meta->size);
  727. } while(size < METADATA_SIZE);
  728. if(size + compat_metadata->size < size ||
  729. size + compat_metadata->size < compat_metadata->size ||
  730. size + compat_metadata->size > METADATA_SIZE)
  731. return false;
  732. if(memcpy_s(dest_meta, METADATA_SIZE - size , compat_metadata, compat_metadata->size))
  733. return false;
  734. return true;
  735. }
  736. static bool generate_compatible_metadata(metadata_t *metadata)
  737. {
  738. metadata_t *metadata2 = (metadata_t *)malloc(metadata->size);
  739. if(!metadata2)
  740. {
  741. se_trace(SE_TRACE_ERROR, NO_MEMORY_ERROR);
  742. return false;
  743. }
  744. memcpy(metadata2, metadata, metadata->size);
  745. metadata2->version = META_DATA_MAKE_VERSION(SGX_1_9_MAJOR_VERSION,SGX_1_9_MINOR_VERSION );
  746. layout_t *start = GET_PTR(layout_t, metadata2, metadata2->dirs[DIR_LAYOUT].offset);
  747. layout_t *end = GET_PTR(layout_t, start, metadata2->dirs[DIR_LAYOUT].size);
  748. layout_t tmp_layout, *first_dyn_entry = NULL, *first = NULL, *utility_td = NULL;
  749. uint32_t size_to_reduce = 0;
  750. bool ret = false;
  751. for (layout_t *l = start; l < end; l++)
  752. {
  753. if ((l->entry.id == LAYOUT_ID_STACK_DYN_MAX) ||
  754. (l->entry.id == LAYOUT_ID_STACK_DYN_MIN))
  755. {
  756. first_dyn_entry = l;
  757. break;
  758. }
  759. }
  760. if (first_dyn_entry == NULL)
  761. {
  762. ret = append_compatible_metadata(metadata2, metadata);
  763. free(metadata2);
  764. return ret;
  765. }
  766. //sizeof(layout_t) for the guard page before LAYOUT_ID_STACK_DYN_MAX
  767. size_to_reduce = (uint32_t)((size_t)end - (size_t)first_dyn_entry + sizeof(layout_t));
  768. layout_t *last = &first_dyn_entry[-2];
  769. for (layout_t *l = start; l <= last; l++)
  770. {
  771. if (l->entry.id == LAYOUT_ID_TD)
  772. {
  773. utility_td = l;
  774. break;
  775. }
  776. }
  777. assert(utility_td != NULL);
  778. //Besides dynamic threads, there's only a single utility thread
  779. if (utility_td == last)
  780. {
  781. metadata_cleanup(metadata2, size_to_reduce);
  782. ret = append_compatible_metadata(metadata2, metadata);
  783. free(metadata2);
  784. return ret;
  785. }
  786. //We have some static threads
  787. first = &utility_td[1];
  788. //utility thread | thread group for min pool
  789. if (first == last)
  790. {
  791. metadata_cleanup(metadata2, size_to_reduce);
  792. ret = append_compatible_metadata(metadata2, metadata);
  793. free(metadata2);
  794. return ret;
  795. }
  796. if (first->group.id == LAYOUT_ID_THREAD_GROUP)
  797. {
  798. //utility thread | thread group for min pool | eremove thread | eremove thread group
  799. if (last->group.id == LAYOUT_ID_THREAD_GROUP)
  800. {
  801. first->group.load_times += last->group.load_times + 1;
  802. }
  803. //utility thread | thread group for min pool | eremove thread
  804. else
  805. {
  806. first->group.load_times += 1;
  807. }
  808. size_to_reduce += (uint32_t)((size_t)last - (size_t)first);
  809. }
  810. else
  811. {
  812. memset(&tmp_layout, 0, sizeof(tmp_layout));
  813. tmp_layout.group.id = LAYOUT_ID_THREAD_GROUP;
  814. //utility thread | eremove thread | eremove thread group
  815. if (last->group.id == LAYOUT_ID_THREAD_GROUP)
  816. {
  817. tmp_layout.group.entry_count = (uint16_t)(((size_t)last - (size_t)first) / sizeof(layout_t));
  818. tmp_layout.group.load_times = last->group.load_times + 1;
  819. }
  820. //utility thread | eremove thread
  821. else
  822. {
  823. tmp_layout.group.entry_count = (uint16_t)(((size_t)last - (size_t)first) / sizeof(layout_t) + 1);
  824. tmp_layout.group.load_times = 1;
  825. }
  826. for (uint32_t i = 0; i < tmp_layout.group.entry_count; i++)
  827. {
  828. tmp_layout.group.load_step += (((uint64_t)first[i].entry.page_count) << SE_PAGE_SHIFT);
  829. }
  830. memcpy_s(first, sizeof(layout_t), &tmp_layout, sizeof(layout_t));
  831. size_to_reduce += (uint32_t)((size_t)last - (size_t)first);
  832. }
  833. metadata_cleanup(metadata2, size_to_reduce);
  834. ret = append_compatible_metadata(metadata2, metadata);
  835. free(metadata2);
  836. return ret;
  837. }
  838. static bool dump_enclave_metadata(const char *enclave_path, const char *dumpfile_path)
  839. {
  840. assert(enclave_path != NULL && dumpfile_path != NULL);
  841. uint64_t meta_offset = 0;
  842. bin_fmt_t bin_fmt = BF_UNKNOWN;
  843. uint32_t file_size = 0;
  844. se_file_handle_t fh = open_file(enclave_path);
  845. if (fh == THE_INVALID_HANDLE)
  846. {
  847. se_trace(SE_TRACE_ERROR, OPEN_FILE_ERROR, enclave_path);
  848. return false;
  849. }
  850. std::unique_ptr<map_handle_t, void (*)(map_handle_t*)> mh(map_file(fh, &file_size), unmap_file);
  851. if (!mh)
  852. {
  853. close_handle(fh);
  854. return false;
  855. }
  856. // Parse enclave
  857. std::unique_ptr<BinParser> parser(binparser::get_parser(mh->base_addr, (size_t)file_size));
  858. assert(parser != NULL);
  859. sgx_status_t status = parser->run_parser();
  860. if (status != SGX_SUCCESS)
  861. {
  862. se_trace(SE_TRACE_ERROR, INVALID_ENCLAVE_ERROR);
  863. close_handle(fh);
  864. return false;
  865. }
  866. // Collect enclave info
  867. if(get_enclave_info(parser.get(), &bin_fmt, &meta_offset, true) == false)
  868. {
  869. close_handle(fh);
  870. return false;
  871. }
  872. const metadata_t *metadata = GET_PTR(metadata_t, mh->base_addr, meta_offset);
  873. if(print_metadata(dumpfile_path, metadata) == false)
  874. {
  875. close_handle(fh);
  876. remove(dumpfile_path);
  877. return false;
  878. }
  879. close_handle(fh);
  880. return true;
  881. }
  882. int main(int argc, char* argv[])
  883. {
  884. xml_parameter_t parameter[] = {{"ProdID", 0xFFFF, 0, 0, 0},
  885. {"ISVSVN", 0xFFFF, 0, 0, 0},
  886. {"ReleaseType", 1, 0, 0, 0},
  887. {"IntelSigned", 1, 0, 0, 0},
  888. {"ProvisionKey",1,0,0,0},
  889. {"LaunchKey",1,0,0,0},
  890. {"DisableDebug",1,0,0,0},
  891. {"HW", 0x10,0,0,0},
  892. {"TCSNum",0xFFFFFFFF,TCS_NUM_MIN,TCS_NUM_MIN,0},
  893. {"TCSMaxNum",0xFFFFFFFF,TCS_NUM_MIN,TCS_NUM_MIN,0},
  894. {"TCSMinPool",0xFFFFFFFF,0,TCS_NUM_MIN,0},
  895. {"TCSPolicy",TCS_POLICY_UNBIND,TCS_POLICY_BIND,TCS_POLICY_UNBIND,0},
  896. {"StackMaxSize",0x1FFFFFFFFF,STACK_SIZE_MIN,STACK_SIZE_MAX,0},
  897. {"StackMinSize",0x1FFFFFFFFF,STACK_SIZE_MIN,STACK_SIZE_MIN,0},
  898. {"HeapMaxSize",0x1FFFFFFFFF,0,HEAP_SIZE_MAX,0},
  899. {"HeapMinSize",0x1FFFFFFFFF,0,HEAP_SIZE_MIN,0},
  900. {"HeapInitSize",0x1FFFFFFFFF,0,HEAP_SIZE_MIN,0},
  901. {"MiscSelect", 0xFFFFFFFF, 0, DEFAULT_MISC_SELECT, 0},
  902. {"MiscMask", 0xFFFFFFFF, 0, DEFAULT_MISC_MASK, 0}};
  903. const char *path[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
  904. uint8_t enclave_hash[SGX_HASH_SIZE] = {0};
  905. uint8_t metadata_raw[METADATA_SIZE];
  906. metadata_t *metadata = (metadata_t*)metadata_raw;
  907. int res = -1, mode = -1;
  908. int key_type = UNIDENTIFIABLE_KEY; //indicate the type of the input key file
  909. size_t parameter_count = sizeof(parameter)/sizeof(parameter[0]);
  910. uint64_t meta_offset = 0;
  911. bool ignore_rel_error = false;
  912. RSA *rsa = NULL;
  913. memset(&metadata_raw, 0, sizeof(metadata_raw));
  914. OpenSSL_add_all_algorithms();
  915. ERR_load_crypto_strings();
  916. //Parse command line
  917. if(cmdline_parse(argc, argv, &mode, path, &ignore_rel_error) == false)
  918. {
  919. se_trace(SE_TRACE_ERROR, USAGE_STRING);
  920. goto clear_return;
  921. }
  922. if(mode == -1) // User only wants to get the help info
  923. {
  924. res = 0;
  925. goto clear_return;
  926. }
  927. else if(mode == DUMP)
  928. {
  929. // dump metadata info
  930. if(dump_enclave_metadata(path[DLL], path[DUMPFILE]) == false)
  931. {
  932. se_trace(SE_TRACE_ERROR, DUMP_METADATA_ERROR, path[DUMPFILE]);
  933. goto clear_return;
  934. }
  935. else
  936. {
  937. se_trace(SE_TRACE_ERROR, SUCCESS_EXIT);
  938. res = 0;
  939. goto clear_return;
  940. }
  941. }
  942. //Other modes
  943. //
  944. //Parse the xml file to get the metadata
  945. if(parse_metadata_file(path[XML], parameter, (int)parameter_count) == false)
  946. {
  947. goto clear_return;
  948. }
  949. //Parse the key file
  950. if(parse_key_file(mode, path[KEY], &rsa, &key_type) == false && key_type != NO_KEY)
  951. {
  952. goto clear_return;
  953. }
  954. if(copy_file(path[DLL], path[OUTPUT]) == false)
  955. {
  956. se_trace(SE_TRACE_ERROR, OVERALL_ERROR);
  957. goto clear_return;
  958. }
  959. ignore_rel_error = true;
  960. if(measure_enclave(enclave_hash, path[OUTPUT], parameter, ignore_rel_error, metadata, &meta_offset) == false)
  961. {
  962. se_trace(SE_TRACE_ERROR, OVERALL_ERROR);
  963. goto clear_return;
  964. }
  965. if((generate_output(mode, key_type, enclave_hash, rsa, metadata, path)) == false)
  966. {
  967. se_trace(SE_TRACE_ERROR, OVERALL_ERROR);
  968. goto clear_return;
  969. }
  970. //to verify
  971. if(mode == SIGN || mode == CATSIG)
  972. {
  973. if(verify_signature(rsa, &(metadata->enclave_css)) == false)
  974. {
  975. se_trace(SE_TRACE_ERROR, OVERALL_ERROR);
  976. goto clear_return;
  977. }
  978. if(false == generate_compatible_metadata(metadata))
  979. {
  980. se_trace(SE_TRACE_ERROR, OVERALL_ERROR);
  981. goto clear_return;
  982. }
  983. if(false == update_metadata(path[OUTPUT], metadata, meta_offset))
  984. {
  985. se_trace(SE_TRACE_ERROR, OVERALL_ERROR);
  986. goto clear_return;
  987. }
  988. }
  989. if(path[DUMPFILE] != NULL)
  990. {
  991. if(print_metadata(path[DUMPFILE], metadata) == false)
  992. {
  993. se_trace(SE_TRACE_ERROR, DUMP_METADATA_ERROR, path[DUMPFILE]);
  994. goto clear_return;
  995. }
  996. }
  997. se_trace(SE_TRACE_ERROR, SUCCESS_EXIT);
  998. res = 0;
  999. clear_return:
  1000. if(rsa)
  1001. RSA_free(rsa);
  1002. if(res == -1 && path[OUTPUT])
  1003. remove(path[OUTPUT]);
  1004. if(res == -1 && path[DUMPFILE])
  1005. remove(path[DUMPFILE]);
  1006. EVP_cleanup();
  1007. CRYPTO_cleanup_all_ex_data();
  1008. ERR_remove_thread_state(NULL);
  1009. ERR_free_strings();
  1010. return res;
  1011. }