sign_tool.cpp 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141
  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. {"-review_enclave", NULL, PAR_INVALID},
  509. {"-dumpfile", NULL, PAR_OPTIONAL}};
  510. param_struct_t params_gendata[] = {
  511. {"-enclave", NULL, PAR_REQUIRED},
  512. {"-config", NULL, PAR_OPTIONAL},
  513. {"-key", NULL, PAR_INVALID},
  514. {"-out", NULL, PAR_REQUIRED},
  515. {"-sig", NULL, PAR_INVALID},
  516. {"-unsigned", NULL, PAR_INVALID},
  517. {"-review_enclave", NULL, PAR_INVALID},
  518. {"-dumpfile", NULL, PAR_INVALID}};
  519. param_struct_t params_catsig[] = {
  520. {"-enclave", NULL, PAR_REQUIRED},
  521. {"-config", NULL, PAR_OPTIONAL},
  522. {"-key", NULL, PAR_REQUIRED},
  523. {"-out", NULL, PAR_REQUIRED},
  524. {"-sig", NULL, PAR_REQUIRED},
  525. {"-unsigned", NULL, PAR_REQUIRED},
  526. {"-review_enclave", NULL, PAR_INVALID},
  527. {"-dumpfile", NULL, PAR_OPTIONAL}};
  528. param_struct_t params_dump[] = {
  529. {"-enclave", NULL, PAR_REQUIRED},
  530. {"-config", NULL, PAR_INVALID},
  531. {"-key", NULL, PAR_INVALID},
  532. {"-out", NULL, PAR_INVALID},
  533. {"-sig", NULL, PAR_INVALID},
  534. {"-unsigned", NULL, PAR_INVALID},
  535. {"-review_enclave", NULL, PAR_INVALID},
  536. {"-dumpfile", NULL, PAR_REQUIRED}};
  537. const char *mode_m[] ={"sign", "gendata","catsig", "dump"};
  538. param_struct_t *params[] = {params_sign, params_gendata, params_catsig, params_dump};
  539. unsigned int tempidx=0;
  540. for(; tempidx<sizeof(mode_m)/sizeof(mode_m[0]); tempidx++)
  541. {
  542. if(!STRCMP(mode_m[tempidx], argv[1]))//match
  543. {
  544. break;
  545. }
  546. }
  547. unsigned int tempmode = tempidx;
  548. if(tempmode>=sizeof(mode_m)/sizeof(mode_m[0]))
  549. {
  550. se_trace(SE_TRACE_ERROR, UNREC_CMD_ERROR, argv[1]);
  551. return false;
  552. }
  553. unsigned int err_idx = 2;
  554. for(; err_idx < argc; err_idx++)
  555. {
  556. if(!STRCMP(argv[err_idx], "-ignore-rel-error"))
  557. break;
  558. }
  559. unsigned int params_count = (unsigned)(sizeof(params_sign)/sizeof(params_sign[0]));
  560. unsigned int params_count_min = 0;
  561. unsigned int params_count_max =0;
  562. for(unsigned int i=0; i< params_count; i++)
  563. {
  564. params_count_max ++;
  565. if(params[tempmode][i].flag == PAR_REQUIRED)
  566. params_count_min ++;
  567. }
  568. unsigned int additional_param = 2;
  569. if(err_idx != argc)
  570. additional_param++;
  571. if(argc<params_count_min * 2 + additional_param)
  572. return false;
  573. if(argc>params_count_max * 2 + additional_param)
  574. return false;
  575. for(unsigned int i=2; i<argc; i=i+2)
  576. {
  577. if(i == err_idx)
  578. {
  579. i++;
  580. continue;
  581. }
  582. unsigned int j=0;
  583. for(; j<params_count; j++)
  584. {
  585. if(STRCMP(argv[i], params[tempmode][j].name)==0) //match
  586. {
  587. if((i<argc-1)&&(STRNCMP(argv[i+1],"-", 1))) // assuming pathname doesn't contain "-"
  588. {
  589. if(params[tempmode][j].value != NULL)
  590. {
  591. se_trace(SE_TRACE_ERROR, REPEAT_OPTION_ERROR, params[tempmode][j].name);
  592. return false;
  593. }
  594. params[tempmode][j].value = argv[i+1];
  595. break;
  596. }
  597. else //didn't match: 1) no path parameter behind option parameter 2) parameters format error.
  598. {
  599. se_trace(SE_TRACE_ERROR, INVALID_FILE_NAME_ERROR, params[tempmode][j].name);
  600. return false;
  601. }
  602. }
  603. }
  604. if(j>=params_count_max)
  605. {
  606. return false;
  607. }
  608. }
  609. for(unsigned int i = 0; i < params_count; i ++)
  610. {
  611. if(params[tempmode][i].flag == PAR_REQUIRED && params[tempmode][i].value == NULL)
  612. {
  613. se_trace(SE_TRACE_ERROR, LACK_REQUIRED_OPTION_ERROR, params[tempmode][i].name, mode_m[tempmode]);
  614. return false;
  615. }
  616. if(params[tempmode][i].flag == PAR_INVALID && params[tempmode][i].value != NULL)
  617. {
  618. se_trace(SE_TRACE_ERROR, GIVE_INVALID_OPTION_ERROR, params[tempmode][i].name, mode_m[tempmode]);
  619. return false;
  620. }
  621. }
  622. for(unsigned int i = 0; i < params_count; i++)
  623. {
  624. path[i] = params[tempmode][i].value;
  625. }
  626. *mode = tempmode;
  627. if(err_idx != argc)
  628. *ignore_rel_error = true;
  629. return true;
  630. }
  631. //generate_output:
  632. // To generate the final output file
  633. // SIGN- need to fill the enclave_css_t(key part included), sign the header and body and
  634. // update the metadata in the out file
  635. // GENDATA- need to fill the enclave_css_t(key part excluded), get the body and header,
  636. // and then write the whole out file with body+header+hash
  637. // CATSIG- need to fill the enclave_css_t(include key), read the signature from the sigpath,
  638. // and then update the metadata in the out file
  639. static bool generate_output(int mode, int ktype, const uint8_t *enclave_hash, const RSA *rsa, metadata_t *metadata,
  640. const char **path)
  641. {
  642. assert(enclave_hash != NULL && metadata != NULL && path != NULL);
  643. switch(mode)
  644. {
  645. case SIGN:
  646. {
  647. if(ktype != PRIVATE_KEY || !rsa)
  648. {
  649. se_trace(SE_TRACE_ERROR, LACK_PRI_KEY_ERROR);
  650. return false;
  651. }
  652. if(false == fill_enclave_css(rsa, path, enclave_hash, &(metadata->enclave_css)))
  653. {
  654. return false;
  655. }
  656. if(false == create_signature(rsa, NULL, &(metadata->enclave_css)))
  657. {
  658. return false;
  659. }
  660. break;
  661. }
  662. case GENDATA:
  663. {
  664. if(false == fill_enclave_css(NULL, path, enclave_hash, &(metadata->enclave_css)))
  665. {
  666. return false;
  667. }
  668. if(false == gen_enclave_signing_file(&(metadata->enclave_css), path[OUTPUT]))
  669. {
  670. return false;
  671. }
  672. break;
  673. }
  674. case CATSIG:
  675. {
  676. if(ktype != PUBLIC_KEY || !rsa)
  677. {
  678. se_trace(SE_TRACE_ERROR, LACK_PUB_KEY_ERROR);
  679. return false;
  680. }
  681. if(false == fill_enclave_css(rsa, path, enclave_hash, &(metadata->enclave_css)))
  682. {
  683. return false;
  684. }
  685. if(false == create_signature(NULL, path[SIG], &(metadata->enclave_css)))
  686. {
  687. return false;
  688. }
  689. break;
  690. }
  691. default:
  692. {
  693. return false;
  694. }
  695. }
  696. return true;
  697. }
  698. #include "se_page_attr.h"
  699. static void metadata_cleanup(metadata_t *metadata, uint32_t size_to_reduce)
  700. {
  701. metadata->dirs[DIR_LAYOUT].size -= size_to_reduce;
  702. metadata->size -= size_to_reduce;
  703. //if there exists LAYOUT_ID_HEAP_MAX, modify it so that it won't be included in the MRENCLAVE
  704. layout_t *start = GET_PTR(layout_t, metadata, metadata->dirs[DIR_LAYOUT].offset);
  705. layout_t *end = GET_PTR(layout_t, start, metadata->dirs[DIR_LAYOUT].size);
  706. for (layout_t *l = start; l < end; l++)
  707. {
  708. if (l->entry.id == LAYOUT_ID_HEAP_MAX)
  709. {
  710. l->entry.si_flags = SI_FLAG_NONE;
  711. l->entry.attributes &= (uint16_t)(~PAGE_ATTR_POST_ADD);
  712. break;
  713. }
  714. }
  715. //remove the PAGE_ATTR_POST_ADD attribute so that dynamic range won't be
  716. //created during enclave loading time
  717. for (layout_t *l = start; l < end; l++)
  718. {
  719. if (l->entry.id == LAYOUT_ID_HEAP_INIT)
  720. {
  721. l->entry.attributes &= (uint16_t)(~PAGE_ATTR_POST_ADD);
  722. break;
  723. }
  724. }
  725. }
  726. static bool append_compatible_metadata(metadata_t *compat_metadata, metadata_t *metadata)
  727. {
  728. metadata_t *dest_meta = metadata;
  729. uint32_t size = 0;
  730. do{
  731. if(dest_meta->magic_num != METADATA_MAGIC || dest_meta->size == 0)
  732. break;
  733. size += dest_meta->size;
  734. if(size < dest_meta->size)
  735. return false;
  736. dest_meta = (metadata_t *)((size_t)dest_meta + dest_meta->size);
  737. } while(size < METADATA_SIZE);
  738. if(size + compat_metadata->size < size ||
  739. size + compat_metadata->size < compat_metadata->size ||
  740. size + compat_metadata->size > METADATA_SIZE)
  741. return false;
  742. if(memcpy_s(dest_meta, METADATA_SIZE - size , compat_metadata, compat_metadata->size))
  743. return false;
  744. return true;
  745. }
  746. static bool generate_compatible_metadata(metadata_t *metadata)
  747. {
  748. metadata_t *metadata2 = (metadata_t *)malloc(metadata->size);
  749. if(!metadata2)
  750. {
  751. se_trace(SE_TRACE_ERROR, NO_MEMORY_ERROR);
  752. return false;
  753. }
  754. // append 2_0 metadata
  755. memcpy(metadata2, metadata, metadata->size);
  756. metadata2->version = META_DATA_MAKE_VERSION(SGX_2_0_MAJOR_VERSION,SGX_2_0_MINOR_VERSION);
  757. if (!append_compatible_metadata(metadata2, metadata))
  758. {
  759. free(metadata2);
  760. return false;
  761. }
  762. // append 1_9 metadata
  763. metadata2->version = META_DATA_MAKE_VERSION(SGX_1_9_MAJOR_VERSION,SGX_1_9_MINOR_VERSION);
  764. layout_t *start = GET_PTR(layout_t, metadata2, metadata2->dirs[DIR_LAYOUT].offset);
  765. layout_t *end = GET_PTR(layout_t, start, metadata2->dirs[DIR_LAYOUT].size);
  766. layout_t tmp_layout, *first_dyn_entry = NULL, *first = NULL, *utility_td = NULL;
  767. uint32_t size_to_reduce = 0;
  768. bool ret = false;
  769. for (layout_t *l = start; l < end; l++)
  770. {
  771. if ((l->entry.id == LAYOUT_ID_STACK_DYN_MAX) ||
  772. (l->entry.id == LAYOUT_ID_STACK_DYN_MIN))
  773. {
  774. first_dyn_entry = l;
  775. break;
  776. }
  777. }
  778. if (first_dyn_entry == NULL)
  779. {
  780. ret = append_compatible_metadata(metadata2, metadata);
  781. free(metadata2);
  782. return ret;
  783. }
  784. //sizeof(layout_t) for the guard page before LAYOUT_ID_STACK_DYN_MAX
  785. size_to_reduce = (uint32_t)((size_t)end - (size_t)first_dyn_entry + sizeof(layout_t));
  786. layout_t *last = &first_dyn_entry[-2];
  787. for (layout_t *l = start; l <= last; l++)
  788. {
  789. if (l->entry.id == LAYOUT_ID_TD)
  790. {
  791. utility_td = l;
  792. break;
  793. }
  794. }
  795. assert(utility_td != NULL);
  796. //Besides dynamic threads, there's only a single utility thread
  797. if (utility_td == last)
  798. {
  799. metadata_cleanup(metadata2, size_to_reduce);
  800. ret = append_compatible_metadata(metadata2, metadata);
  801. free(metadata2);
  802. return ret;
  803. }
  804. //We have some static threads
  805. first = &utility_td[1];
  806. if (first->group.id == LAYOUT_ID_THREAD_GROUP)
  807. {
  808. if (last->group.id == LAYOUT_ID_THREAD_GROUP)
  809. {
  810. //utility thread | thread group for min pool | eremove thread | eremove thread group
  811. if (first != last)
  812. first->group.load_times += last->group.load_times + 1;
  813. //utility thread | thread group for min pool
  814. }
  815. //utility thread | thread group for min pool | eremove thread
  816. else
  817. {
  818. first->group.load_times += 1;
  819. }
  820. size_to_reduce += (uint32_t)((size_t)last - (size_t)first);
  821. }
  822. else
  823. {
  824. memset(&tmp_layout, 0, sizeof(tmp_layout));
  825. tmp_layout.group.id = LAYOUT_ID_THREAD_GROUP;
  826. //utility thread | eremove thread | eremove thread group
  827. if (last->group.id == LAYOUT_ID_THREAD_GROUP)
  828. {
  829. tmp_layout.group.entry_count = (uint16_t)(((size_t)last - (size_t)first) / sizeof(layout_t));
  830. tmp_layout.group.load_times = last->group.load_times + 1;
  831. }
  832. //utility thread | eremove thread
  833. else
  834. {
  835. tmp_layout.group.entry_count = (uint16_t)(((size_t)last - (size_t)first) / sizeof(layout_t) + 1);
  836. tmp_layout.group.load_times = 1;
  837. }
  838. for (uint32_t i = 0; i < tmp_layout.group.entry_count; i++)
  839. {
  840. tmp_layout.group.load_step += (((uint64_t)first[i].entry.page_count) << SE_PAGE_SHIFT);
  841. }
  842. memcpy_s(first, sizeof(layout_t), &tmp_layout, sizeof(layout_t));
  843. size_to_reduce += (uint32_t)((size_t)last - (size_t)first);
  844. }
  845. metadata_cleanup(metadata2, size_to_reduce);
  846. ret = append_compatible_metadata(metadata2, metadata);
  847. free(metadata2);
  848. return ret;
  849. }
  850. static bool dump_enclave_metadata(const char *enclave_path, const char *dumpfile_path)
  851. {
  852. assert(enclave_path != NULL && dumpfile_path != NULL);
  853. uint64_t meta_offset = 0;
  854. bin_fmt_t bin_fmt = BF_UNKNOWN;
  855. uint32_t file_size = 0;
  856. se_file_handle_t fh = open_file(enclave_path);
  857. if (fh == THE_INVALID_HANDLE)
  858. {
  859. se_trace(SE_TRACE_ERROR, OPEN_FILE_ERROR, enclave_path);
  860. return false;
  861. }
  862. std::unique_ptr<map_handle_t, void (*)(map_handle_t*)> mh(map_file(fh, &file_size), unmap_file);
  863. if (!mh)
  864. {
  865. close_handle(fh);
  866. return false;
  867. }
  868. // Parse enclave
  869. std::unique_ptr<BinParser> parser(binparser::get_parser(mh->base_addr, (size_t)file_size));
  870. assert(parser != NULL);
  871. sgx_status_t status = parser->run_parser();
  872. if (status != SGX_SUCCESS)
  873. {
  874. se_trace(SE_TRACE_ERROR, INVALID_ENCLAVE_ERROR);
  875. close_handle(fh);
  876. return false;
  877. }
  878. // Collect enclave info
  879. if(get_enclave_info(parser.get(), &bin_fmt, &meta_offset, true) == false)
  880. {
  881. close_handle(fh);
  882. return false;
  883. }
  884. const metadata_t *metadata = GET_PTR(metadata_t, mh->base_addr, meta_offset);
  885. if(print_metadata(dumpfile_path, metadata) == false)
  886. {
  887. close_handle(fh);
  888. remove(dumpfile_path);
  889. return false;
  890. }
  891. close_handle(fh);
  892. return true;
  893. }
  894. int main(int argc, char* argv[])
  895. {
  896. xml_parameter_t parameter[] = {{"ProdID", 0xFFFF, 0, 0, 0},
  897. {"ISVSVN", 0xFFFF, 0, 0, 0},
  898. {"ReleaseType", 1, 0, 0, 0},
  899. {"IntelSigned", 1, 0, 0, 0},
  900. {"ProvisionKey",1,0,0,0},
  901. {"LaunchKey",1,0,0,0},
  902. {"DisableDebug",1,0,0,0},
  903. {"HW", 0x10,0,0,0},
  904. {"TCSNum",0xFFFFFFFF,TCS_NUM_MIN,TCS_NUM_MIN,0},
  905. {"TCSMaxNum",0xFFFFFFFF,TCS_NUM_MIN,TCS_NUM_MIN,0},
  906. {"TCSMinPool",0xFFFFFFFF,0,TCS_NUM_MIN,0},
  907. {"TCSPolicy",TCS_POLICY_UNBIND,TCS_POLICY_BIND,TCS_POLICY_UNBIND,0},
  908. {"StackMaxSize",0x1FFFFFFFFF,STACK_SIZE_MIN,STACK_SIZE_MAX,0},
  909. {"StackMinSize",0x1FFFFFFFFF,STACK_SIZE_MIN,STACK_SIZE_MIN,0},
  910. {"HeapMaxSize",0x1FFFFFFFFF,0,HEAP_SIZE_MAX,0},
  911. {"HeapMinSize",0x1FFFFFFFFF,0,HEAP_SIZE_MIN,0},
  912. {"HeapInitSize",0x1FFFFFFFFF,0,HEAP_SIZE_MIN,0},
  913. {"MiscSelect", 0xFFFFFFFF, 0, DEFAULT_MISC_SELECT, 0},
  914. {"MiscMask", 0xFFFFFFFF, 0, DEFAULT_MISC_MASK, 0}};
  915. const char *path[8] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
  916. uint8_t enclave_hash[SGX_HASH_SIZE] = {0};
  917. uint8_t metadata_raw[METADATA_SIZE];
  918. metadata_t *metadata = (metadata_t*)metadata_raw;
  919. int res = -1, mode = -1;
  920. int key_type = UNIDENTIFIABLE_KEY; //indicate the type of the input key file
  921. size_t parameter_count = sizeof(parameter)/sizeof(parameter[0]);
  922. uint64_t meta_offset = 0;
  923. bool ignore_rel_error = false;
  924. RSA *rsa = NULL;
  925. memset(&metadata_raw, 0, sizeof(metadata_raw));
  926. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  927. OpenSSL_add_all_algorithms();
  928. ERR_load_crypto_strings();
  929. #else
  930. OPENSSL_init_crypto(0, NULL);
  931. #endif
  932. //Parse command line
  933. if(cmdline_parse(argc, argv, &mode, path, &ignore_rel_error) == false)
  934. {
  935. se_trace(SE_TRACE_ERROR, USAGE_STRING);
  936. goto clear_return;
  937. }
  938. if(mode == -1) // User only wants to get the help info or version info
  939. {
  940. res = 0;
  941. goto clear_return;
  942. }
  943. else if(mode == DUMP)
  944. {
  945. // dump metadata info
  946. if(dump_enclave_metadata(path[DLL], path[DUMPFILE]) == false)
  947. {
  948. se_trace(SE_TRACE_ERROR, DUMP_METADATA_ERROR, path[DUMPFILE]);
  949. goto clear_return;
  950. }
  951. else
  952. {
  953. se_trace(SE_TRACE_ERROR, SUCCESS_EXIT);
  954. res = 0;
  955. goto clear_return;
  956. }
  957. }
  958. //Other modes
  959. //
  960. //Parse the xml file to get the metadata
  961. if(parse_metadata_file(path[XML], parameter, (int)parameter_count) == false)
  962. {
  963. goto clear_return;
  964. }
  965. //Parse the key file
  966. if(parse_key_file(mode, path[KEY], &rsa, &key_type) == false && key_type != NO_KEY)
  967. {
  968. goto clear_return;
  969. }
  970. if(copy_file(path[DLL], path[OUTPUT]) == false)
  971. {
  972. se_trace(SE_TRACE_ERROR, OVERALL_ERROR);
  973. goto clear_return;
  974. }
  975. ignore_rel_error = true;
  976. if(measure_enclave(enclave_hash, path[OUTPUT], parameter, ignore_rel_error, metadata, &meta_offset) == false)
  977. {
  978. se_trace(SE_TRACE_ERROR, OVERALL_ERROR);
  979. goto clear_return;
  980. }
  981. if((generate_output(mode, key_type, enclave_hash, rsa, metadata, path)) == false)
  982. {
  983. se_trace(SE_TRACE_ERROR, OVERALL_ERROR);
  984. goto clear_return;
  985. }
  986. //to verify
  987. if(mode == SIGN || mode == CATSIG)
  988. {
  989. if(verify_signature(rsa, &(metadata->enclave_css)) == false)
  990. {
  991. se_trace(SE_TRACE_ERROR, OVERALL_ERROR);
  992. goto clear_return;
  993. }
  994. if(false == generate_compatible_metadata(metadata))
  995. {
  996. se_trace(SE_TRACE_ERROR, OVERALL_ERROR);
  997. goto clear_return;
  998. }
  999. if(false == update_metadata(path[OUTPUT], metadata, meta_offset))
  1000. {
  1001. se_trace(SE_TRACE_ERROR, OVERALL_ERROR);
  1002. goto clear_return;
  1003. }
  1004. }
  1005. if(path[DUMPFILE] != NULL)
  1006. {
  1007. if(print_metadata(path[DUMPFILE], metadata) == false)
  1008. {
  1009. se_trace(SE_TRACE_ERROR, DUMP_METADATA_ERROR, path[DUMPFILE]);
  1010. goto clear_return;
  1011. }
  1012. }
  1013. se_trace(SE_TRACE_ERROR, SUCCESS_EXIT);
  1014. res = 0;
  1015. clear_return:
  1016. if(rsa)
  1017. RSA_free(rsa);
  1018. if(res == -1 && path[OUTPUT])
  1019. remove(path[OUTPUT]);
  1020. if(res == -1 && path[DUMPFILE])
  1021. remove(path[DUMPFILE]);
  1022. #if OPENSSL_VERSION_NUMBER < 0x10100000L
  1023. EVP_cleanup();
  1024. CRYPTO_cleanup_all_ex_data();
  1025. ERR_remove_thread_state(NULL);
  1026. ERR_free_strings();
  1027. #endif
  1028. return res;
  1029. }