enclave_framework.c 43 KB

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