enclave_framework.c 43 KB

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