sign_tool.cpp 36 KB

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