enclave_framework.c 43 KB

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