enclave_framework.c 44 KB

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