enclave_framework.c 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392
  1. #include <pal_linux.h>
  2. #include <pal_linux_error.h>
  3. #include <pal_internal.h>
  4. #include <pal_debug.h>
  5. #include <pal_error.h>
  6. #include <pal_security.h>
  7. #include <pal_crypto.h>
  8. #include <api.h>
  9. #include <list.h>
  10. #include <stdbool.h>
  11. #include "enclave_pages.h"
  12. static const size_t URI_FILE_PREFIX_LEN = static_strlen("file:");
  13. __sgx_mem_aligned struct pal_enclave_state pal_enclave_state;
  14. void * enclave_base, * enclave_top;
  15. struct pal_enclave_config pal_enclave_config;
  16. static int register_trusted_file (const char * uri, const char * checksum_str);
  17. bool sgx_is_completely_within_enclave (const void * addr, uint64_t size)
  18. {
  19. if (((uint64_t) addr) > (UINT64_MAX - size)) {
  20. return false;
  21. }
  22. return enclave_base <= addr && addr + size <= enclave_top;
  23. }
  24. bool sgx_is_completely_outside_enclave(const void* addr, uint64_t size) {
  25. if (((uint64_t) addr) > (UINT64_MAX - size)) {
  26. return false;
  27. }
  28. return enclave_base >= addr + size || enclave_top <= addr;
  29. }
  30. void* sgx_alloc_on_ustack(uint64_t size) {
  31. void* ustack = GET_ENCLAVE_TLS(ustack) - size;
  32. if (!sgx_is_completely_outside_enclave(ustack, size)) {
  33. return NULL;
  34. }
  35. SET_ENCLAVE_TLS(ustack, ustack);
  36. return ustack;
  37. }
  38. void* sgx_copy_to_ustack(const void* ptr, uint64_t size) {
  39. if (!sgx_is_completely_within_enclave(ptr, size)) {
  40. return NULL;
  41. }
  42. void* uptr = sgx_alloc_on_ustack(size);
  43. if (uptr) {
  44. memcpy(uptr, ptr, size);
  45. }
  46. return uptr;
  47. }
  48. void sgx_reset_ustack(void) {
  49. SET_ENCLAVE_TLS(ustack, GET_ENCLAVE_TLS(ustack_top));
  50. }
  51. /* NOTE: Value from possibly untrusted uptr must be copied inside
  52. * CPU register or enclave stack (to prevent TOCTOU). Function call
  53. * achieves this. Attribute ensures no inline optimization. */
  54. __attribute__((noinline))
  55. bool sgx_copy_ptr_to_enclave(void** ptr, void* uptr, uint64_t size) {
  56. assert(ptr);
  57. if (!sgx_is_completely_outside_enclave(uptr, size)) {
  58. *ptr = NULL;
  59. return false;
  60. }
  61. *ptr = uptr;
  62. return true;
  63. }
  64. /* NOTE: Value from possibly untrusted uptr and usize must be copied
  65. * inside CPU registers or enclave stack (to prevent TOCTOU). Function
  66. * call achieves this. Attribute ensures no inline optimization. */
  67. __attribute__((noinline))
  68. uint64_t sgx_copy_to_enclave(const void* ptr, uint64_t maxsize, const void* uptr, uint64_t usize) {
  69. if (usize > maxsize ||
  70. !sgx_is_completely_outside_enclave(uptr, usize) ||
  71. !sgx_is_completely_within_enclave(ptr, usize)) {
  72. return 0;
  73. }
  74. memcpy((void*) ptr, uptr, usize);
  75. return usize;
  76. }
  77. static void print_report(sgx_report_t* r) {
  78. SGX_DBG(DBG_S, " cpu_svn: %s\n", ALLOCA_BYTES2HEXSTR(r->body.cpu_svn.svn));
  79. SGX_DBG(DBG_S, " mr_enclave: %s\n", ALLOCA_BYTES2HEXSTR(r->body.mr_enclave.m));
  80. SGX_DBG(DBG_S, " mr_signer: %s\n", ALLOCA_BYTES2HEXSTR(r->body.mr_signer.m));
  81. SGX_DBG(DBG_S, " attr.flags: %016lx\n", r->body.attributes.flags);
  82. SGX_DBG(DBG_S, " attr.xfrm: %016lx\n", r->body.attributes.xfrm);
  83. SGX_DBG(DBG_S, " isv_prod_id: %02x\n", r->body.isv_prod_id);
  84. SGX_DBG(DBG_S, " isv_svn: %02x\n", r->body.isv_svn);
  85. SGX_DBG(DBG_S, " report_data: %s\n", ALLOCA_BYTES2HEXSTR(r->body.report_data.d));
  86. SGX_DBG(DBG_S, " key_id: %s\n", ALLOCA_BYTES2HEXSTR(r->key_id.id));
  87. SGX_DBG(DBG_S, " mac: %s\n", ALLOCA_BYTES2HEXSTR(r->mac));
  88. }
  89. static sgx_key_128bit_t enclave_key;
  90. #define KEYBUF_SIZE ((sizeof(sgx_key_128bit_t) * 2) + 1)
  91. /*
  92. * sgx_get_report() obtains a CPU-signed report for local attestation
  93. * @target_info: the enclave target info
  94. * @data: the data to be included and signed in the report
  95. * @report: a buffer for storing the report
  96. */
  97. static int sgx_get_report(sgx_target_info_t* target_info, sgx_sign_data_t* data,
  98. sgx_report_t* report) {
  99. __sgx_mem_aligned struct pal_enclave_state state;
  100. memcpy(&state, &pal_enclave_state, sizeof(state));
  101. memcpy(&state.enclave_data, data, sizeof(*data));
  102. int ret = sgx_report(target_info, &state, report);
  103. if (ret) {
  104. SGX_DBG(DBG_E, "sgx_report failed: ret = %d)\n", ret);
  105. return -PAL_ERROR_DENIED;
  106. }
  107. print_report(report);
  108. return 0;
  109. }
  110. int sgx_verify_report (sgx_report_t* report)
  111. {
  112. __sgx_mem_aligned sgx_key_request_t keyrequest;
  113. memset(&keyrequest, 0, sizeof(sgx_key_request_t));
  114. keyrequest.key_name = REPORT_KEY;
  115. memcpy(&keyrequest.key_id, &report->key_id, sizeof(keyrequest.key_id));
  116. sgx_key_128bit_t report_key __attribute__((aligned(sizeof(sgx_key_128bit_t))));
  117. memset(&report_key, 0, sizeof(report_key));
  118. int ret = sgx_getkey(&keyrequest, &report_key);
  119. if (ret) {
  120. SGX_DBG(DBG_E, "Can't get report key\n");
  121. return -PAL_ERROR_DENIED;
  122. }
  123. SGX_DBG(DBG_S, "Get report key for verification: %s\n", ALLOCA_BYTES2HEXSTR(report_key));
  124. sgx_mac_t check_mac;
  125. memset(&check_mac, 0, sizeof(check_mac));
  126. // Generating the MAC with AES-CMAC using the report key. Only hash the part of the report
  127. // BEFORE the keyid field (hence the offsetof(...) trick). ENCLU[EREPORT] does not include
  128. // the MAC and the keyid fields when generating the MAC.
  129. lib_AESCMAC((uint8_t*)&report_key, sizeof(report_key),
  130. (uint8_t*)report, offsetof(sgx_report_t, key_id),
  131. (uint8_t*)&check_mac, sizeof(check_mac));
  132. // Clear the report key for security
  133. memset(&report_key, 0, sizeof(report_key));
  134. SGX_DBG(DBG_S, "Verify report:\n");
  135. print_report(report);
  136. SGX_DBG(DBG_S, " verify: %s\n", ALLOCA_BYTES2HEXSTR(check_mac));
  137. if (memcmp(&check_mac, &report->mac, sizeof(check_mac))) {
  138. SGX_DBG(DBG_E, "Report verification failed\n");
  139. return -PAL_ERROR_DENIED;
  140. }
  141. return 0;
  142. }
  143. int init_enclave_key (void)
  144. {
  145. __sgx_mem_aligned sgx_key_request_t keyrequest;
  146. memset(&keyrequest, 0, sizeof(sgx_key_request_t));
  147. keyrequest.key_name = SEAL_KEY;
  148. int ret = sgx_getkey(&keyrequest, &enclave_key);
  149. if (ret) {
  150. SGX_DBG(DBG_E, "Can't get seal key\n");
  151. return -PAL_ERROR_DENIED;
  152. }
  153. SGX_DBG(DBG_S, "Seal key: %s\n", ALLOCA_BYTES2HEXSTR(enclave_key));
  154. return 0;
  155. }
  156. /*
  157. * The file integrity check is designed as follow:
  158. *
  159. * For each file that requires authentication (specified in the manifest
  160. * as "sgx.trusted_files.xxx"), a SHA256 checksum is generated and stored
  161. * in the manifest, signed and verified as part of the enclave's crypto
  162. * measurement. When user requests for opening the file, Graphene loads
  163. * the whole file, generate the SHA256 checksum, and check with the known
  164. * checksums listed in the manifest. If the checksum does not match, and
  165. * neither does the file is allowed for unauthenticated access, the file
  166. * access will be rejected.
  167. *
  168. * During the generation of the SHA256 checksum, a 128-bit hash is also
  169. * generated for each chunk in the file. The per-chunk hashes are used
  170. * for partial verification in future reads, to avoid re-verifying the
  171. * whole file again or the need of caching file contents. The per-chunk
  172. * hashes are stored as "stubs" for each file. For a performance reason,
  173. * each per-chunk hash is a 128-bit AES-CMAC hash value, using a secret
  174. * key generated at the beginning of the enclave.
  175. */
  176. DEFINE_LIST(trusted_file);
  177. struct trusted_file {
  178. LIST_TYPE(trusted_file) list;
  179. int64_t index;
  180. uint64_t size;
  181. size_t uri_len;
  182. char uri[URI_MAX];
  183. sgx_checksum_t checksum;
  184. sgx_stub_t * stubs;
  185. };
  186. DEFINE_LISTP(trusted_file);
  187. static LISTP_TYPE(trusted_file) trusted_file_list = LISTP_INIT;
  188. static struct spinlock trusted_file_lock = LOCK_INIT;
  189. static int trusted_file_indexes = 0;
  190. static bool allow_file_creation = 0;
  191. static int file_check_policy = FILE_CHECK_POLICY_STRICT;
  192. /* Assumes `path` is normalized */
  193. static bool path_is_equal_or_subpath(const struct trusted_file* tf,
  194. const char* path,
  195. size_t path_len) {
  196. if (tf->uri_len > path_len || memcmp(tf->uri, path, tf->uri_len)) {
  197. /* tf->uri is not prefix of `path` */
  198. return false;
  199. }
  200. if (tf->uri_len == path_len) {
  201. /* Both are equal */
  202. return true;
  203. }
  204. if (tf->uri[tf->uri_len - 1] == '/' || path[tf->uri_len] == '/') {
  205. /* tf->uri is a subpath of `path` */
  206. return true;
  207. }
  208. if (tf->uri_len == URI_FILE_PREFIX_LEN && !memcmp(tf->uri, "file:", URI_FILE_PREFIX_LEN)) {
  209. /* Empty path is a prefix of everything */
  210. return true;
  211. }
  212. return false;
  213. }
  214. /*
  215. * 'load_trusted_file' checks if the file to be opened is trusted
  216. * or allowed for unauthenticated access, according to the manifest.
  217. *
  218. * file: file handle to be opened
  219. * stubptr: buffer for catching matched file stub.
  220. * sizeptr: size pointer
  221. * create: this file is newly created or not
  222. *
  223. * Returns 0 if succeeded, or an error code otherwise.
  224. */
  225. int load_trusted_file (PAL_HANDLE file, sgx_stub_t ** stubptr,
  226. uint64_t * sizeptr, int create)
  227. {
  228. struct trusted_file * tf = NULL, * tmp;
  229. char uri[URI_MAX];
  230. char normpath[URI_MAX];
  231. int ret, fd = file->file.fd;
  232. if (!(HANDLE_HDR(file)->flags & RFD(0)))
  233. return -PAL_ERROR_DENIED;
  234. ret = _DkStreamGetName(file, uri, URI_MAX);
  235. if (ret < 0) {
  236. return ret;
  237. }
  238. /* Allow to create the file when allow_file_creation is turned on;
  239. The created file is added to allowed_file list for later access */
  240. if (create && allow_file_creation) {
  241. register_trusted_file(uri, NULL);
  242. *stubptr = NULL;
  243. *sizeptr = 0;
  244. return 0;
  245. }
  246. /* Normalize the uri */
  247. if (!strstartswith_static(uri, "file:")) {
  248. SGX_DBG(DBG_E, "Invalid URI [%s]: Trusted files must start with 'file:'\n", uri);
  249. return -PAL_ERROR_INVAL;
  250. }
  251. assert(sizeof(normpath) > URI_FILE_PREFIX_LEN);
  252. normpath [0] = 'f';
  253. normpath [1] = 'i';
  254. normpath [2] = 'l';
  255. normpath [3] = 'e';
  256. normpath [4] = ':';
  257. size_t len = sizeof(normpath) - URI_FILE_PREFIX_LEN;
  258. ret = get_norm_path(uri + URI_FILE_PREFIX_LEN, normpath + URI_FILE_PREFIX_LEN, &len);
  259. if (ret < 0) {
  260. SGX_DBG(DBG_E,
  261. "Path (%s) normalization failed: %s\n",
  262. uri + URI_FILE_PREFIX_LEN,
  263. pal_strerror(ret));
  264. return ret;
  265. }
  266. len += URI_FILE_PREFIX_LEN;
  267. _DkSpinLock(&trusted_file_lock);
  268. LISTP_FOR_EACH_ENTRY(tmp, &trusted_file_list, list) {
  269. if (tmp->stubs) {
  270. /* trusted files: must be exactly the same URI */
  271. if (tmp->uri_len == len && !memcmp(tmp->uri, normpath, len + 1)) {
  272. tf = tmp;
  273. break;
  274. }
  275. } else {
  276. /* allowed files: must be a subfolder or file */
  277. if (path_is_equal_or_subpath(tmp, normpath, len)) {
  278. tf = tmp;
  279. break;
  280. }
  281. }
  282. }
  283. _DkSpinUnlock(&trusted_file_lock);
  284. if (!tf || !tf->index) {
  285. if (!tf) {
  286. if (get_file_check_policy() != FILE_CHECK_POLICY_ALLOW_ALL_BUT_LOG)
  287. return -PAL_ERROR_DENIED;
  288. pal_printf("Allowing access to an unknown file due to "
  289. "file_check_policy settings: %s\n", uri);
  290. }
  291. *stubptr = NULL;
  292. PAL_STREAM_ATTR attr;
  293. ret = _DkStreamAttributesQuery(normpath, &attr);
  294. if (!ret)
  295. *sizeptr = attr.pending_size;
  296. else
  297. *sizeptr = 0;
  298. return 0;
  299. }
  300. if (tf->index < 0)
  301. return tf->index;
  302. #if CACHE_FILE_STUBS == 1
  303. if (tf->stubs) {
  304. *stubptr = tf->stubs;
  305. *sizeptr = tf->size;
  306. return 0;
  307. }
  308. #endif
  309. int nstubs = tf->size / TRUSTED_STUB_SIZE +
  310. (tf->size % TRUSTED_STUB_SIZE ? 1 : 0);
  311. sgx_stub_t * stubs = malloc(sizeof(sgx_stub_t) * nstubs);
  312. if (!stubs)
  313. return -PAL_ERROR_NOMEM;
  314. sgx_stub_t * s = stubs; /* stubs is an array of 128bit values */
  315. uint64_t offset = 0;
  316. LIB_SHA256_CONTEXT sha;
  317. void * umem;
  318. ret = lib_SHA256Init(&sha);
  319. if (ret < 0)
  320. goto failed;
  321. for (; offset < tf->size ; offset += TRUSTED_STUB_SIZE, s++) {
  322. /* For each stub, generate a 128bit hash of a file chunk with
  323. * AES-CMAC, and then update the SHA256 digest. */
  324. uint64_t mapping_size = MIN(tf->size - offset, TRUSTED_STUB_SIZE);
  325. LIB_AESCMAC_CONTEXT aes_cmac;
  326. ret = lib_AESCMACInit(&aes_cmac, (uint8_t*)&enclave_key, sizeof(enclave_key));
  327. if (ret < 0)
  328. goto failed;
  329. ret = ocall_mmap_untrusted(fd, offset, mapping_size, PROT_READ, &umem);
  330. if (IS_ERR(ret)) {
  331. ret = unix_to_pal_error(ERRNO(ret));
  332. goto unmap;
  333. }
  334. /*
  335. * To prevent TOCTOU attack when generating the file checksum, we
  336. * need to copy the file content into the enclave before hashing.
  337. * For optimization, we use a relatively small buffer (1024 byte) to
  338. * store the data for checksum generation.
  339. */
  340. #define FILE_CHUNK_SIZE 1024UL
  341. uint8_t small_chunk[FILE_CHUNK_SIZE]; /* Buffer for hashing */
  342. size_t chunk_offset = 0;
  343. for (; chunk_offset < mapping_size; chunk_offset += FILE_CHUNK_SIZE) {
  344. uint64_t chunk_size = MIN(mapping_size - chunk_offset, FILE_CHUNK_SIZE);
  345. /* Any file content needs to be copied into the enclave before
  346. * checking and re-hashing */
  347. memcpy(small_chunk, umem + chunk_offset, chunk_size);
  348. /* Update the file checksum */
  349. ret = lib_SHA256Update(&sha, small_chunk, chunk_size);
  350. if (ret < 0)
  351. goto unmap;
  352. /* Update the checksum for the file chunk */
  353. ret = lib_AESCMACUpdate(&aes_cmac, small_chunk, chunk_size);
  354. if (ret < 0)
  355. goto unmap;
  356. }
  357. /* Store the checksum for one file chunk for checking */
  358. ret = lib_AESCMACFinish(&aes_cmac, (uint8_t *) s, sizeof *s);
  359. unmap:
  360. ocall_munmap_untrusted(umem, mapping_size);
  361. if (ret < 0)
  362. goto failed;
  363. }
  364. sgx_checksum_t hash;
  365. /* Finalize and checking if the checksum of the whole file matches
  366. * with record given in the manifest. */
  367. ret = lib_SHA256Final(&sha, (uint8_t *) hash.bytes);
  368. if (ret < 0)
  369. goto failed;
  370. if (memcmp(&hash, &tf->checksum, sizeof(sgx_checksum_t))) {
  371. ret = -PAL_ERROR_DENIED;
  372. goto failed;
  373. }
  374. _DkSpinLock(&trusted_file_lock);
  375. if (tf->stubs || tf->index == -PAL_ERROR_DENIED)
  376. free(tf->stubs);
  377. *stubptr = tf->stubs = stubs;
  378. *sizeptr = tf->size;
  379. ret = tf->index;
  380. _DkSpinUnlock(&trusted_file_lock);
  381. return ret;
  382. failed:
  383. free(stubs);
  384. _DkSpinLock(&trusted_file_lock);
  385. if (tf->stubs) {
  386. *stubptr = tf->stubs;
  387. *sizeptr = tf->size;
  388. ret = tf->index;
  389. } else {
  390. tf->index = -PAL_ERROR_DENIED;
  391. }
  392. _DkSpinUnlock(&trusted_file_lock);
  393. #if PRINT_ENCLAVE_STAT
  394. if (!ret) {
  395. sgx_stub_t * loaded_stub;
  396. uint64_t loaded_size;
  397. PAL_HANDLE handle = NULL;
  398. if (!_DkStreamOpen(&handle, normpath, PAL_ACCESS_RDONLY, 0, 0, 0))
  399. load_trusted_file (handle, &loaded_stub, &loaded_size);
  400. }
  401. #endif
  402. return ret;
  403. }
  404. int get_file_check_policy ()
  405. {
  406. return file_check_policy;
  407. }
  408. static void set_file_check_policy (int policy)
  409. {
  410. file_check_policy = policy;
  411. }
  412. /*
  413. * A common helper function for copying and checking the file contents
  414. * from a buffer mapped outside the enclaves into an in-enclave buffer.
  415. * If needed, regions at either the beginning or the end of the copied regions
  416. * are copied into a scratch buffer to avoid a TOCTTOU race.
  417. *
  418. * * Note that it must be done this way to avoid the following TOCTTOU race
  419. * * condition with the untrusted host as an adversary:
  420. * * Adversary: put good contents in buffer
  421. * * Enclave: buffer check passes
  422. * * Adversary: put bad contents in buffer
  423. * * Enclave: copies in bad buffer contents
  424. *
  425. * * For optimization, we verify the memory in place, as the application code
  426. * should not use the memory before return. There can be subtle interactions
  427. * at the edges of a region with ELF loading. Namely, the ELF loader will
  428. * want to map several file chunks that are not aligned to TRUSTED_STUB_SIZE
  429. * next to each other, sometimes overlapping. There is probably room to
  430. * improve load time with more smarts around ELF loading, but for now, just
  431. * make things work.
  432. *
  433. * 'umem' is the untrusted file memory mapped outside the enclave (should
  434. * already be mapped up by the caller). 'umem_start' and 'umem_end' are
  435. * the offset _within the file_ of 'umem'. 'umem_start' should be aligned
  436. * to the file checking chunk size (TRUSTED_STUB_SIZE). 'umem_end' can be
  437. * either aligned, or equal to 'total_size'. 'buffer' is the in-enclave
  438. * buffer for copying the file content. 'offset' is the offset within the file
  439. * for copying into the buffer. 'size' is the size of the in-enclave buffer.
  440. * 'stubs' contain the checksums of all the chunks in a file.
  441. */
  442. int copy_and_verify_trusted_file (const char * path, const void * umem,
  443. uint64_t umem_start, uint64_t umem_end,
  444. void * buffer, uint64_t offset, uint64_t size,
  445. sgx_stub_t * stubs, uint64_t total_size)
  446. {
  447. /* Check that the untrusted mapping is aligned to TRUSTED_STUB_SIZE
  448. * and includes the range for copying into the buffer */
  449. assert(IS_ALIGNED(umem_start, TRUSTED_STUB_SIZE));
  450. assert(offset >= umem_start && offset + size <= umem_end);
  451. /* Start copying and checking at umem_start. The checked content may or
  452. * may not be copied into the file content, depending on the offset of
  453. * the content within the file. */
  454. uint64_t checking = umem_start;
  455. /* The stubs is an array of 128-bit hash values of the file chunks.
  456. * from the beginning of the file. 's' points to the stub that needs to
  457. * be checked for the current offset. */
  458. sgx_stub_t * s = stubs + checking / TRUSTED_STUB_SIZE;
  459. int ret = 0;
  460. for (; checking < umem_end ; checking += TRUSTED_STUB_SIZE, s++) {
  461. /* Check one chunk at a time. */
  462. uint64_t checking_size = MIN(total_size - checking, TRUSTED_STUB_SIZE);
  463. uint64_t checking_end = checking + checking_size;
  464. sgx_checksum_t hash;
  465. if (checking >= offset && checking_end <= offset + size) {
  466. /* If the checking chunk completely overlaps with the region
  467. * needed for copying into the buffer, simplying use the buffer
  468. * for checking */
  469. memcpy(buffer + checking - offset, umem + checking - umem_start,
  470. checking_size);
  471. /* Storing the checksum (using AES-CMAC) inside hash. */
  472. ret = lib_AESCMAC((uint8_t*)&enclave_key, sizeof(enclave_key),
  473. buffer + checking - offset, checking_size,
  474. (uint8_t*)&hash, sizeof(hash));
  475. } else {
  476. /* If the checking chunk only partially overlaps with the region,
  477. * read the file content in smaller chunks and only copy the part
  478. * needed by the caller. */
  479. LIB_AESCMAC_CONTEXT aes_cmac;
  480. ret = lib_AESCMACInit(&aes_cmac, (uint8_t*)&enclave_key, sizeof(enclave_key));
  481. if (ret < 0)
  482. goto failed;
  483. uint8_t small_chunk[FILE_CHUNK_SIZE]; /* A small buffer */
  484. uint64_t chunk_offset = checking;
  485. for (; chunk_offset < checking_end
  486. ; chunk_offset += FILE_CHUNK_SIZE) {
  487. uint64_t chunk_size = MIN(checking_end - chunk_offset,
  488. FILE_CHUNK_SIZE);
  489. /* Copy into the small buffer before hashing the content */
  490. memcpy(small_chunk, umem + (chunk_offset - umem_start),
  491. chunk_size);
  492. /* Update the hash for the current chunk */
  493. ret = lib_AESCMACUpdate(&aes_cmac, small_chunk, chunk_size);
  494. if (ret < 0)
  495. goto failed;
  496. /* Determine if the part just copied and checked is needed
  497. * by the caller. If so, copy it into the user buffer. */
  498. uint64_t copy_start = chunk_offset;
  499. uint64_t copy_end = copy_start + chunk_size;
  500. if (copy_start < offset)
  501. copy_start = offset;
  502. if (copy_end > offset + size)
  503. copy_end = offset + size;
  504. if (copy_end > copy_start)
  505. memcpy(buffer + (copy_start - offset),
  506. small_chunk + (copy_start - chunk_offset),
  507. copy_end - copy_start);
  508. }
  509. /* Storing the checksum (using AES-CMAC) inside hash. */
  510. ret = lib_AESCMACFinish(&aes_cmac, (uint8_t*)&hash, sizeof(hash));
  511. }
  512. if (ret < 0)
  513. goto failed;
  514. /*
  515. * Check if the hash matches with the checksum of current chunk.
  516. * If not, return with access denied. Note: some file content may
  517. * still be in the buffer (including the corrupted part).
  518. * We assume the user won't use the content if this function
  519. * returns with failures.
  520. *
  521. * XXX: Maybe we should zero the buffer after denying the access?
  522. */
  523. if (memcmp(s, &hash, sizeof(sgx_stub_t))) {
  524. SGX_DBG(DBG_E, "Accesing file:%s is denied. Does not match with MAC"
  525. " at chunk starting at %lu-%lu.\n",
  526. path, checking, checking_end);
  527. return -PAL_ERROR_DENIED;
  528. }
  529. }
  530. return 0;
  531. failed:
  532. return -PAL_ERROR_DENIED;
  533. }
  534. static int register_trusted_file (const char * uri, const char * checksum_str)
  535. {
  536. struct trusted_file * tf = NULL, * new;
  537. size_t uri_len = strlen(uri);
  538. int ret;
  539. _DkSpinLock(&trusted_file_lock);
  540. LISTP_FOR_EACH_ENTRY(tf, &trusted_file_list, list) {
  541. if (tf->uri_len == uri_len && !memcmp(tf->uri, uri, uri_len)) {
  542. _DkSpinUnlock(&trusted_file_lock);
  543. return 0;
  544. }
  545. }
  546. _DkSpinUnlock(&trusted_file_lock);
  547. new = malloc(sizeof(struct trusted_file));
  548. if (!new)
  549. return -PAL_ERROR_NOMEM;
  550. INIT_LIST_HEAD(new, list);
  551. new->uri_len = uri_len;
  552. memcpy(new->uri, uri, uri_len + 1);
  553. new->size = 0;
  554. new->stubs = NULL;
  555. if (checksum_str) {
  556. PAL_STREAM_ATTR attr;
  557. ret = _DkStreamAttributesQuery(uri, &attr);
  558. if (!ret)
  559. new->size = attr.pending_size;
  560. char checksum_text[sizeof(sgx_checksum_t) * 2 + 1] = "\0";
  561. size_t nbytes = 0;
  562. for (; nbytes < sizeof(sgx_checksum_t) ; nbytes++) {
  563. char byte1 = checksum_str[nbytes * 2];
  564. char byte2 = checksum_str[nbytes * 2 + 1];
  565. unsigned char val = 0;
  566. if (byte1 == 0 || byte2 == 0) {
  567. break;
  568. }
  569. if (!(byte1 >= '0' && byte1 <= '9') &&
  570. !(byte1 >= 'a' && byte1 <= 'f')) {
  571. break;
  572. }
  573. if (!(byte2 >= '0' && byte2 <= '9') &&
  574. !(byte2 >= 'a' && byte2 <= 'f')) {
  575. break;
  576. }
  577. if (byte1 >= '0' && byte1 <= '9')
  578. val = byte1 - '0';
  579. if (byte1 >= 'a' && byte1 <= 'f')
  580. val = byte1 - 'a' + 10;
  581. val *= 16;
  582. if (byte2 >= '0' && byte2 <= '9')
  583. val += byte2 - '0';
  584. if (byte2 >= 'a' && byte2 <= 'f')
  585. val += byte2 - 'a' + 10;
  586. new->checksum.bytes[nbytes] = val;
  587. snprintf(checksum_text + nbytes * 2, 3, "%02x", val);
  588. }
  589. if (nbytes < sizeof(sgx_checksum_t)) {
  590. free(new);
  591. return -PAL_ERROR_INVAL;
  592. }
  593. new->index = (++trusted_file_indexes);
  594. SGX_DBG(DBG_S, "trusted: [%ld] %s %s\n", new->index,
  595. checksum_text, new->uri);
  596. } else {
  597. memset(&new->checksum, 0, sizeof(sgx_checksum_t));
  598. new->index = 0;
  599. SGX_DBG(DBG_S, "allowed: %s\n", new->uri);
  600. }
  601. _DkSpinLock(&trusted_file_lock);
  602. LISTP_FOR_EACH_ENTRY(tf, &trusted_file_list, list) {
  603. if (tf->uri_len == uri_len && !memcmp(tf->uri, uri, uri_len)) {
  604. _DkSpinUnlock(&trusted_file_lock);
  605. free(new);
  606. return 0;
  607. }
  608. }
  609. LISTP_ADD_TAIL(new, &trusted_file_list, list);
  610. _DkSpinUnlock(&trusted_file_lock);
  611. return 0;
  612. }
  613. static int init_trusted_file (const char * key, const char * uri)
  614. {
  615. char cskey[URI_MAX], * tmp;
  616. char checksum[URI_MAX];
  617. char normpath[URI_MAX];
  618. tmp = strcpy_static(cskey, "sgx.trusted_checksum.", URI_MAX);
  619. memcpy(tmp, key, strlen(key) + 1);
  620. ssize_t ret = get_config(pal_state.root_config, cskey, checksum, sizeof(checksum));
  621. if (ret < 0)
  622. return 0;
  623. /* Normalize the uri */
  624. if (!strstartswith_static(uri, "file:")) {
  625. SGX_DBG(DBG_E, "Invalid URI [%s]: Trusted files must start with 'file:'\n", uri);
  626. return -PAL_ERROR_INVAL;
  627. }
  628. assert(sizeof(normpath) > URI_FILE_PREFIX_LEN);
  629. normpath [0] = 'f';
  630. normpath [1] = 'i';
  631. normpath [2] = 'l';
  632. normpath [3] = 'e';
  633. normpath [4] = ':';
  634. size_t len = sizeof(normpath) - URI_FILE_PREFIX_LEN;
  635. ret = get_norm_path(uri + URI_FILE_PREFIX_LEN, normpath + URI_FILE_PREFIX_LEN, &len);
  636. if (ret < 0) {
  637. SGX_DBG(DBG_E,
  638. "Path (%s) normalization failed: %s\n",
  639. uri + URI_FILE_PREFIX_LEN,
  640. pal_strerror(ret));
  641. return ret;
  642. }
  643. return register_trusted_file(normpath, checksum);
  644. }
  645. int init_trusted_files (void) {
  646. struct config_store* store = pal_state.root_config;
  647. char* cfgbuf = NULL;
  648. ssize_t cfgsize;
  649. int nuris, ret;
  650. char key[CONFIG_MAX];
  651. char uri[CONFIG_MAX];
  652. char* k;
  653. char* tmp;
  654. if (pal_sec.exec_name[0] != '\0') {
  655. ret = init_trusted_file("exec", pal_sec.exec_name);
  656. if (ret < 0)
  657. goto out;
  658. }
  659. cfgbuf = malloc(CONFIG_MAX);
  660. if (!cfgbuf) {
  661. ret = -PAL_ERROR_NOMEM;
  662. goto out;
  663. }
  664. ssize_t len = get_config(store, "loader.preload", cfgbuf, CONFIG_MAX);
  665. if (len > 0) {
  666. int npreload = 0;
  667. char key[10];
  668. const char * start, * end;
  669. for (start = cfgbuf ; start < cfgbuf + len ; start = end + 1) {
  670. for (end = start ; end < cfgbuf + len && *end && *end != ',' ; end++);
  671. if (end > start) {
  672. char uri[end - start + 1];
  673. memcpy(uri, start, end - start);
  674. uri[end - start] = 0;
  675. snprintf(key, 10, "preload%d", npreload++);
  676. ret = init_trusted_file(key, uri);
  677. if (ret < 0)
  678. goto out;
  679. }
  680. }
  681. }
  682. cfgsize = get_config_entries_size(store, "sgx.trusted_files");
  683. if (cfgsize <= 0)
  684. goto no_trusted;
  685. free(cfgbuf);
  686. cfgbuf = malloc(cfgsize);
  687. if (!cfgbuf) {
  688. ret = -PAL_ERROR_NOMEM;
  689. goto out;
  690. }
  691. nuris = get_config_entries(store, "sgx.trusted_files", cfgbuf, cfgsize);
  692. if (nuris <= 0)
  693. goto no_trusted;
  694. tmp = strcpy_static(key, "sgx.trusted_files.", sizeof(key));
  695. k = cfgbuf;
  696. for (int i = 0 ; i < nuris ; i++) {
  697. len = strlen(k);
  698. memcpy(tmp, k, len + 1);
  699. k += len + 1;
  700. len = get_config(store, key, uri, sizeof(uri));
  701. if (len > 0) {
  702. ret = init_trusted_file(key + static_strlen("sgx.trusted_files."), uri);
  703. if (ret < 0)
  704. goto out;
  705. }
  706. }
  707. no_trusted:
  708. cfgsize = get_config_entries_size(store, "sgx.allowed_files");
  709. if (cfgsize <= 0)
  710. goto no_allowed;
  711. free(cfgbuf);
  712. cfgbuf = malloc(cfgsize);
  713. if (!cfgbuf) {
  714. ret = -PAL_ERROR_NOMEM;
  715. goto out;
  716. }
  717. nuris = get_config_entries(store, "sgx.allowed_files", cfgbuf, cfgsize);
  718. if (nuris <= 0)
  719. goto no_allowed;
  720. tmp = strcpy_static(key, "sgx.allowed_files.", sizeof(key));
  721. k = cfgbuf;
  722. for (int i = 0 ; i < nuris ; i++) {
  723. len = strlen(k);
  724. memcpy(tmp, k, len + 1);
  725. k += len + 1;
  726. len = get_config(store, key, uri, sizeof(uri));
  727. if (len <= 0) {
  728. continue;
  729. }
  730. /* Normalize the uri */
  731. char norm_path[URI_MAX];
  732. if (!strstartswith_static(uri, "file:")) {
  733. SGX_DBG(DBG_E, "Invalid URI [%s]: Allowed files must start with 'file:'\n", uri);
  734. ret = -PAL_ERROR_INVAL;
  735. goto out;
  736. }
  737. assert(sizeof(norm_path) > URI_FILE_PREFIX_LEN);
  738. memcpy(norm_path, "file:", URI_FILE_PREFIX_LEN);
  739. size_t norm_path_len = sizeof(norm_path) - URI_FILE_PREFIX_LEN;
  740. ret = get_norm_path(uri + URI_FILE_PREFIX_LEN,
  741. norm_path + URI_FILE_PREFIX_LEN,
  742. &norm_path_len);
  743. if (ret < 0) {
  744. SGX_DBG(DBG_E,
  745. "Path (%s) normalization failed: %s\n",
  746. uri + URI_FILE_PREFIX_LEN,
  747. pal_strerror(ret));
  748. goto out;
  749. }
  750. register_trusted_file(norm_path, NULL);
  751. }
  752. no_allowed:
  753. ret = 0;
  754. if (get_config(store, "sgx.allow_file_creation", cfgbuf, cfgsize) > 0 && cfgbuf[0] == '1')
  755. allow_file_creation = true;
  756. else
  757. allow_file_creation = false;
  758. out:
  759. free(cfgbuf);
  760. return ret;
  761. }
  762. int init_trusted_children (void)
  763. {
  764. struct config_store * store = pal_state.root_config;
  765. char key[CONFIG_MAX], mrkey[CONFIG_MAX];
  766. char uri[CONFIG_MAX], mr_enclave[CONFIG_MAX];
  767. char * tmp1 = strcpy_static(key, "sgx.trusted_children.", sizeof(key));
  768. char * tmp2 = strcpy_static(mrkey, "sgx.trusted_mrenclave.", sizeof(mrkey));
  769. ssize_t cfgsize = get_config_entries_size(store, "sgx.trusted_mrenclave");
  770. if (cfgsize <= 0)
  771. return 0;
  772. char * cfgbuf = malloc(cfgsize);
  773. if (!cfgbuf)
  774. return -PAL_ERROR_NOMEM;
  775. int nuris = get_config_entries(store, "sgx.trusted_mrenclave",
  776. cfgbuf, cfgsize);
  777. if (nuris > 0) {
  778. char * k = cfgbuf;
  779. for (int i = 0 ; i < nuris ; i++) {
  780. int len = strlen(k);
  781. memcpy(tmp1, k, len + 1);
  782. memcpy(tmp2, k, len + 1);
  783. k += len + 1;
  784. ssize_t ret = get_config(store, key, uri, sizeof(uri));
  785. if (ret < 0)
  786. continue;
  787. ret = get_config(store, mrkey, mr_enclave, sizeof(mr_enclave));
  788. if (ret > 0)
  789. register_trusted_child(uri, mr_enclave);
  790. }
  791. }
  792. free(cfgbuf);
  793. return 0;
  794. }
  795. int init_file_check_policy (void)
  796. {
  797. char cfgbuf[CONFIG_MAX];
  798. ssize_t ret = get_config(pal_state.root_config, "sgx.file_check_policy",
  799. cfgbuf, sizeof(cfgbuf));
  800. if (ret > 0) {
  801. if (!strcmp_static(cfgbuf, "strict"))
  802. set_file_check_policy(FILE_CHECK_POLICY_STRICT);
  803. else if (!strcmp_static(cfgbuf, "allow_all_but_log"))
  804. set_file_check_policy(FILE_CHECK_POLICY_ALLOW_ALL_BUT_LOG);
  805. else
  806. INIT_FAIL(PAL_ERROR_INVAL, "unknown file check policy");
  807. SGX_DBG(DBG_S, "File check policy: %s\n", cfgbuf);
  808. }
  809. return 0;
  810. }
  811. #if 0
  812. void test_dh (void)
  813. {
  814. int ret;
  815. DhKey key1, key2;
  816. uint32_t privsz1, privsz2, pubsz1, pubsz2, agreesz1, agreesz2;
  817. unsigned char priv1[128], pub1[128], priv2[128], pub2[128], agree1[128],
  818. agree2[128], scratch[257];
  819. InitDhKey(&key1);
  820. InitDhKey(&key2);
  821. ret = DhSetKey(&key1, dh_param.p, sizeof(dh_param.p), dh_param.g,
  822. sizeof(dh_param.g));
  823. if (ret < 0) {
  824. SGX_DBG(DBG_S, "DhSetKey for key 1 failed: %d\n", ret);
  825. return;
  826. }
  827. ret = DhSetKey(&key2, dh_param.p, sizeof(dh_param.p), dh_param.g,
  828. sizeof(dh_param.g));
  829. if (ret < 0) {
  830. SGX_DBG(DBG_S, "DhSetKey for key 2 failed: %d\n", ret);
  831. return;
  832. }
  833. ret = DhGenerateKeyPair(&key1, priv1, &privsz1, pub1, &pubsz1);
  834. if (ret < 0) {
  835. SGX_DBG(DBG_S, "DhGenerateKeyPair for key 1 failed: %d\n", ret);
  836. return;
  837. }
  838. ret = DhGenerateKeyPair(&key2, priv2, &privsz2, pub2, &pubsz2);
  839. if (ret < 0) {
  840. SGX_DBG(DBG_S, "DhGenerateKeyPair for key 2 failed: %d\n", ret);
  841. return;
  842. }
  843. ret = DhAgree(&key1, agree1, &agreesz1, priv1, privsz1, pub2, pubsz2);
  844. if (ret < 0) {
  845. SGX_DBG(DBG_S, "DhAgree for key 1 failed: %d\n", ret);
  846. return;
  847. }
  848. ret = DhAgree(&key2, agree2, &agreesz2, priv2, privsz2, pub1, pubsz1);
  849. if (ret < 0) {
  850. SGX_DBG(DBG_S, "DhAgree for key 1 failed: %d\n", ret);
  851. return;
  852. }
  853. FreeDhKey(&key1);
  854. FreeDhKey(&key2);
  855. SGX_DBG(DBG_S, "key exchange(side A): %s\n",
  856. __bytes2hexstr(agree1, agreesz1, scratch, agreesz1 * 2 + 1));
  857. SGX_DBG(DBG_S, "key exchange(side B): %s\n",
  858. __bytes2hexstr(agree2, agreesz2, scratch, agreesz2 * 2 + 1));
  859. }
  860. #endif
  861. #define RSA_KEY_SIZE 2048
  862. #define RSA_E 3
  863. int init_enclave (void)
  864. {
  865. // Get report to initialize info (MR_ENCLAVE, etc.) about this enclave from
  866. // a trusted source.
  867. // Since this report is only read by ourselves we can
  868. // leave targetinfo zeroed.
  869. __sgx_mem_aligned sgx_target_info_t targetinfo = {0};
  870. __sgx_mem_aligned struct pal_enclave_state reportdata = {0};
  871. __sgx_mem_aligned sgx_report_t report;
  872. assert(sizeof(reportdata) == sizeof(sgx_report_data_t));
  873. int ret = sgx_report(&targetinfo, (sgx_report_data_t*)&reportdata, &report);
  874. if (ret) {
  875. SGX_DBG(DBG_E, "failed to get self report: %d\n", ret);
  876. return -PAL_ERROR_INVAL;
  877. }
  878. memcpy(&pal_sec.mr_enclave, &report.body.mr_enclave, sizeof(pal_sec.mr_enclave));
  879. memcpy(&pal_sec.mr_signer, &report.body.mr_signer, sizeof(pal_sec.mr_signer));
  880. pal_sec.enclave_attributes = report.body.attributes;
  881. #if 0
  882. /*
  883. * This enclave-specific key is a building block for authenticating
  884. * new pipe connections with other enclaves that are already
  885. * authenticated. Since pipe protection is a future feature, this key
  886. * is currently unused and hence deprecated.
  887. */
  888. int ret;
  889. LIB_RSA_KEY *rsa = malloc(sizeof(LIB_RSA_KEY));
  890. lib_RSAInitKey(rsa);
  891. ret = lib_RSAGenerateKey(rsa, RSA_KEY_SIZE, RSA_E);
  892. if (ret < 0) {
  893. SGX_DBG(DBG_E, "lib_RSAGenerateKey failed: %d\n", ret);
  894. return ret;
  895. }
  896. pal_enclave_config.enclave_key = rsa;
  897. #endif
  898. /*
  899. * The enclave id is uniquely created for each enclave as a token
  900. * for authenticating the enclave as the sender of attestation.
  901. * See 'host/Linux-SGX/db_process.c' for further explanation.
  902. */
  903. ret = _DkRandomBitsRead(&pal_enclave_state.enclave_id,
  904. sizeof(pal_enclave_state.enclave_id));
  905. if (ret < 0) {
  906. SGX_DBG(DBG_E, "Failed to generate a random id: %d\n", ret);
  907. return ret;
  908. }
  909. return 0;
  910. }
  911. int _DkStreamKeyExchange(PAL_HANDLE stream, PAL_SESSION_KEY* key) {
  912. uint8_t pub[DH_SIZE] __attribute__((aligned(DH_SIZE)));
  913. uint8_t agree[DH_SIZE] __attribute__((aligned(DH_SIZE)));
  914. PAL_NUM pubsz, agreesz;
  915. LIB_DH_CONTEXT context;
  916. int64_t bytes;
  917. int64_t ret;
  918. ret = lib_DhInit(&context);
  919. if (ret < 0) {
  920. SGX_DBG(DBG_E, "Key Exchange: DH Init failed: %ld\n", ret);
  921. goto out_no_final;
  922. }
  923. pubsz = sizeof pub;
  924. ret = lib_DhCreatePublic(&context, pub, &pubsz);
  925. if (ret < 0) {
  926. SGX_DBG(DBG_E, "Key Exchange: DH CreatePublic failed: %ld\n", ret);
  927. goto out;
  928. }
  929. assert(pubsz > 0 && pubsz <= DH_SIZE);
  930. if (pubsz < DH_SIZE) {
  931. /* Insert leading zero bytes if necessary. These values are big-
  932. * endian, so we either need to know the length of the bignum or
  933. * zero-pad at the beginning instead of the end. This code chooses
  934. * to do the latter. */
  935. memmove(pub + (DH_SIZE - pubsz), pub, pubsz);
  936. memset(pub, 0, DH_SIZE - pubsz);
  937. }
  938. for (bytes = 0, ret = 0; bytes < DH_SIZE; bytes += ret) {
  939. ret = _DkStreamWrite(stream, 0, DH_SIZE - bytes, pub + bytes, NULL, 0);
  940. if (ret < 0) {
  941. if (ret == -PAL_ERROR_INTERRUPTED || ret == -PAL_ERROR_TRYAGAIN) {
  942. ret = 0;
  943. continue;
  944. }
  945. SGX_DBG(DBG_E, "Failed to exchange the secret key via RPC: %ld\n", ret);
  946. goto out;
  947. }
  948. }
  949. for (bytes = 0, ret = 0 ; bytes < DH_SIZE ; bytes += ret) {
  950. ret = _DkStreamRead(stream, 0, DH_SIZE - bytes, pub + bytes, NULL, 0);
  951. if (ret < 0) {
  952. if (ret == -PAL_ERROR_INTERRUPTED || ret == -PAL_ERROR_TRYAGAIN) {
  953. ret = 0;
  954. continue;
  955. }
  956. SGX_DBG(DBG_E, "Failed to exchange the secret key via RPC: %ld\n", ret);
  957. goto out;
  958. }
  959. }
  960. agreesz = sizeof agree;
  961. ret = lib_DhCalcSecret(&context, pub, DH_SIZE, agree, &agreesz);
  962. if (ret < 0) {
  963. SGX_DBG(DBG_E, "Key Exchange: DH CalcSecret failed: %ld\n", ret);
  964. goto out;
  965. }
  966. assert(agreesz > 0 && agreesz <= sizeof agree);
  967. /*
  968. * Using SHA256 as a KDF to convert the 128-byte DH secret to a 256-bit AES key.
  969. * According to the NIST recommendation:
  970. * https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-56Cr1.pdf,
  971. * a key derivation function (KDF) can be a secure hash function (e.g., SHA-256),
  972. * HMAC, or KMAC.
  973. */
  974. LIB_SHA256_CONTEXT sha;
  975. if ((ret = lib_SHA256Init(&sha)) < 0 ||
  976. (ret = lib_SHA256Update(&sha, agree, agreesz)) < 0 ||
  977. (ret = lib_SHA256Final(&sha, (uint8_t*)key)) < 0) {
  978. SGX_DBG(DBG_E, "Failed to derive the session key: %ld\n", ret);
  979. goto out;
  980. }
  981. SGX_DBG(DBG_S, "Key exchange succeeded: %s\n", ALLOCA_BYTES2HEXSTR(*key));
  982. ret = 0;
  983. out:
  984. lib_DhFinal(&context);
  985. out_no_final:
  986. return ret;
  987. }
  988. /*
  989. * Initalize the request of local report exchange.
  990. *
  991. * We refer to this enclave as A and to the other enclave as B, e.g., A is this
  992. * parent enclave and B is the child enclave in the fork case (for more info,
  993. * see comments in db_process.c).
  994. */
  995. int _DkStreamReportRequest(PAL_HANDLE stream, sgx_sign_data_t* data,
  996. check_mr_enclave_t check_mr_enclave) {
  997. __sgx_mem_aligned sgx_target_info_t target_info;
  998. __sgx_mem_aligned sgx_report_t report;
  999. uint64_t bytes;
  1000. int64_t ret;
  1001. /* A -> B: targetinfo[A] */
  1002. memset(&target_info, 0, sizeof(target_info));
  1003. memcpy(&target_info.mr_enclave, &pal_sec.mr_enclave, sizeof(sgx_measurement_t));
  1004. memcpy(&target_info.attributes, &pal_sec.enclave_attributes, sizeof(sgx_attributes_t));
  1005. for (bytes = 0, ret = 0; bytes < SGX_TARGETINFO_FILLED_SIZE; bytes += ret) {
  1006. ret = _DkStreamWrite(stream, 0, SGX_TARGETINFO_FILLED_SIZE - bytes,
  1007. ((void*)&target_info) + bytes, NULL, 0);
  1008. if (ret < 0) {
  1009. if (ret == -PAL_ERROR_INTERRUPTED || ret == -PAL_ERROR_TRYAGAIN) {
  1010. ret = 0;
  1011. continue;
  1012. }
  1013. SGX_DBG(DBG_E, "Failed to send target info via RPC: %ld\n", ret);
  1014. goto out;
  1015. }
  1016. }
  1017. /* B -> A: report[B -> A] */
  1018. for (bytes = 0, ret = 0 ; bytes < sizeof(report) ; bytes += ret) {
  1019. ret = _DkStreamRead(stream, 0, sizeof(report) - bytes,
  1020. ((void*)&report) + bytes, NULL, 0);
  1021. if (ret < 0) {
  1022. if (ret == -PAL_ERROR_INTERRUPTED || ret == -PAL_ERROR_TRYAGAIN) {
  1023. ret = 0;
  1024. continue;
  1025. }
  1026. SGX_DBG(DBG_E, "Failed to receive local report via RPC: %ld\n", ret);
  1027. goto out;
  1028. }
  1029. }
  1030. SGX_DBG(DBG_S, "Received local report (mr_enclave = %s)\n",
  1031. ALLOCA_BYTES2HEXSTR(report.body.mr_enclave.m));
  1032. /* Verify report[B -> A] */
  1033. ret = sgx_verify_report(&report);
  1034. if (ret < 0) {
  1035. SGX_DBG(DBG_E, "Failed to verify local report: %ld\n", ret);
  1036. goto out;
  1037. }
  1038. struct pal_enclave_state* remote_state = (void*)&report.body.report_data;
  1039. ret = check_mr_enclave(stream, &report.body.mr_enclave, remote_state);
  1040. if (ret < 0) {
  1041. SGX_DBG(DBG_E, "Failed to check local report: %ld\n", ret);
  1042. goto out;
  1043. }
  1044. if (ret == 1) {
  1045. SGX_DBG(DBG_E, "Not an allowed enclave (mr_enclave = %s). Maybe missing 'sgx.trusted_children' in the manifest file?\n",
  1046. ALLOCA_BYTES2HEXSTR(report.body.mr_enclave.m));
  1047. ret = -PAL_ERROR_DENIED;
  1048. goto out;
  1049. }
  1050. SGX_DBG(DBG_S, "Local attestation succeeded!\n");
  1051. /* A -> B: report[A -> B] */
  1052. memcpy(&target_info.mr_enclave , &report.body.mr_enclave, sizeof(sgx_measurement_t));
  1053. memcpy(&target_info.attributes, &report.body.attributes, sizeof(sgx_attributes_t));
  1054. ret = sgx_get_report(&target_info, data, &report);
  1055. if (ret < 0) {
  1056. SGX_DBG(DBG_E, "Failed to get local report from CPU: %ld\n", ret);
  1057. goto out;
  1058. }
  1059. for (bytes = 0, ret = 0 ; bytes < sizeof(report) ; bytes += ret) {
  1060. ret = _DkStreamWrite(stream, 0, sizeof(report) - bytes,
  1061. ((void*)&report) + bytes, NULL, 0);
  1062. if (ret < 0) {
  1063. if (ret == -PAL_ERROR_INTERRUPTED || ret == -PAL_ERROR_TRYAGAIN) {
  1064. ret = 0;
  1065. continue;
  1066. }
  1067. SGX_DBG(DBG_E, "Failed to send local report via RPC: %ld\n", ret);
  1068. goto out;
  1069. }
  1070. }
  1071. return 0;
  1072. out:
  1073. DkStreamDelete(stream, 0);
  1074. return ret;
  1075. }
  1076. /*
  1077. * Respond to the request of local report exchange.
  1078. *
  1079. * We refer to this enclave as B and to the other enclave as A, e.g., B is this
  1080. * child enclave and A is the parent enclave in the fork case (for more info,
  1081. * see comments in db_process.c).
  1082. */
  1083. int _DkStreamReportRespond(PAL_HANDLE stream, sgx_sign_data_t* data,
  1084. check_mr_enclave_t check_mr_enclave) {
  1085. __sgx_mem_aligned sgx_target_info_t target_info;
  1086. __sgx_mem_aligned sgx_report_t report;
  1087. uint64_t bytes;
  1088. int64_t ret;
  1089. memset(&target_info, 0, sizeof(target_info));
  1090. /* A -> B: targetinfo[A] */
  1091. for (bytes = 0, ret = 0 ; bytes < SGX_TARGETINFO_FILLED_SIZE ; bytes += ret) {
  1092. ret = _DkStreamRead(stream, 0, SGX_TARGETINFO_FILLED_SIZE - bytes,
  1093. ((void*)&target_info) + bytes, NULL, 0);
  1094. if (ret < 0) {
  1095. if (ret == -PAL_ERROR_INTERRUPTED || ret == -PAL_ERROR_TRYAGAIN) {
  1096. ret = 0;
  1097. continue;
  1098. }
  1099. SGX_DBG(DBG_E, "Failed to receive target info via RPC: %ld\n", ret);
  1100. goto out;
  1101. }
  1102. }
  1103. /* B -> A: report[B -> A] */
  1104. ret = sgx_get_report(&target_info, data, &report);
  1105. if (ret < 0) {
  1106. SGX_DBG(DBG_E, "Failed to get local report from CPU: %ld\n", ret);
  1107. goto out;
  1108. }
  1109. for (bytes = 0, ret = 0 ; bytes < sizeof(report) ; bytes += ret) {
  1110. ret = _DkStreamWrite(stream, 0, sizeof(report) - bytes,
  1111. ((void*)&report) + bytes, NULL, 0);
  1112. if (ret < 0) {
  1113. if (ret == -PAL_ERROR_INTERRUPTED || ret == -PAL_ERROR_TRYAGAIN) {
  1114. ret = 0;
  1115. continue;
  1116. }
  1117. SGX_DBG(DBG_E, "Failed to send local report via PRC: %ld\n", ret);
  1118. goto out;
  1119. }
  1120. }
  1121. /* A -> B: report[A -> B] */
  1122. for (bytes = 0, ret = 0 ; bytes < sizeof(report) ; bytes += ret) {
  1123. ret = _DkStreamRead(stream, 0, sizeof(report) - bytes,
  1124. ((void*)&report) + bytes, NULL, 0);
  1125. if (ret < 0) {
  1126. if (ret == -PAL_ERROR_INTERRUPTED || ret == -PAL_ERROR_TRYAGAIN) {
  1127. ret = 0;
  1128. continue;
  1129. }
  1130. SGX_DBG(DBG_E, "Failed to receive local report via RPC: %ld\n", ret);
  1131. goto out;
  1132. }
  1133. }
  1134. SGX_DBG(DBG_S, "Received local report (mr_enclave = %s)\n",
  1135. ALLOCA_BYTES2HEXSTR(report.body.mr_enclave.m));
  1136. /* Verify report[A -> B] */
  1137. ret = sgx_verify_report(&report);
  1138. if (ret < 0) {
  1139. SGX_DBG(DBG_E, "Failed to verify local report: %ld\n", ret);
  1140. goto out;
  1141. }
  1142. struct pal_enclave_state* remote_state = (void*)&report.body.report_data;
  1143. ret = check_mr_enclave(stream, &report.body.mr_enclave, remote_state);
  1144. if (ret < 0) {
  1145. SGX_DBG(DBG_E, "Failed to check mr_enclave: %ld\n", ret);
  1146. goto out;
  1147. }
  1148. if (ret == 1) {
  1149. SGX_DBG(DBG_E, "Not an allowed enclave (mr_enclave = %s). Maybe missing 'sgx.trusted_children' in the manifest file?\n",
  1150. ALLOCA_BYTES2HEXSTR(report.body.mr_enclave.m));
  1151. ret = -PAL_ERROR_DENIED;
  1152. goto out;
  1153. }
  1154. SGX_DBG(DBG_S, "Local attestation succeeded!\n");
  1155. return 0;
  1156. out:
  1157. DkStreamDelete(stream, 0);
  1158. return ret;
  1159. }
  1160. /*
  1161. * Restore an sgx_cpu_context_t as generated by .Lhandle_exception. Execution will
  1162. * continue as specified by the rip in the context.
  1163. *
  1164. * It is required that:
  1165. *
  1166. * ctx == ctx->rsp - (sizeof(sgx_cpu_context_t) + RED_ZONE_SIZE)
  1167. *
  1168. * This means that the ctx is allocated directly below the "normal" stack
  1169. * (honoring its red zone). This is needed to properly restore the old state
  1170. * (see _restore_sgx_context for details).
  1171. *
  1172. * For the original sgx_cpu_context_t allocated by .Lhandle_exception this is true.
  1173. * This is a safe wrapper around _restore_sgx_context, which checks this
  1174. * preconditon.
  1175. */
  1176. void restore_sgx_context(sgx_cpu_context_t *ctx) {
  1177. if (((uint64_t) ctx) != ctx->rsp - (sizeof(sgx_cpu_context_t) + RED_ZONE_SIZE)) {
  1178. SGX_DBG(DBG_E, "Invalid sgx_cpu_context_t pointer passed to restore_sgx_context!\n");
  1179. ocall_exit(1, /*is_exitgroup=*/false);
  1180. }
  1181. _restore_sgx_context(ctx);
  1182. }