enclave_framework.c 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313
  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);
  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);
  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)
  527. {
  528. struct trusted_file * tf = NULL, * new;
  529. size_t uri_len = strlen(uri);
  530. int ret;
  531. spinlock_lock(&trusted_file_lock);
  532. LISTP_FOR_EACH_ENTRY(tf, &trusted_file_list, list) {
  533. if (tf->uri_len == uri_len && !memcmp(tf->uri, uri, uri_len)) {
  534. spinlock_unlock(&trusted_file_lock);
  535. return 0;
  536. }
  537. }
  538. spinlock_unlock(&trusted_file_lock);
  539. new = malloc(sizeof(struct trusted_file));
  540. if (!new)
  541. return -PAL_ERROR_NOMEM;
  542. INIT_LIST_HEAD(new, list);
  543. new->uri_len = uri_len;
  544. memcpy(new->uri, uri, uri_len + 1);
  545. new->size = 0;
  546. new->stubs = NULL;
  547. if (checksum_str) {
  548. PAL_STREAM_ATTR attr;
  549. ret = _DkStreamAttributesQuery(uri, &attr);
  550. if (!ret)
  551. new->size = attr.pending_size;
  552. char checksum_text[sizeof(sgx_checksum_t) * 2 + 1] = "\0";
  553. size_t nbytes = 0;
  554. for (; nbytes < sizeof(sgx_checksum_t) ; nbytes++) {
  555. char byte1 = checksum_str[nbytes * 2];
  556. char byte2 = checksum_str[nbytes * 2 + 1];
  557. unsigned char val = 0;
  558. if (byte1 == 0 || byte2 == 0) {
  559. break;
  560. }
  561. if (!(byte1 >= '0' && byte1 <= '9') &&
  562. !(byte1 >= 'a' && byte1 <= 'f')) {
  563. break;
  564. }
  565. if (!(byte2 >= '0' && byte2 <= '9') &&
  566. !(byte2 >= 'a' && byte2 <= 'f')) {
  567. break;
  568. }
  569. if (byte1 >= '0' && byte1 <= '9')
  570. val = byte1 - '0';
  571. if (byte1 >= 'a' && byte1 <= 'f')
  572. val = byte1 - 'a' + 10;
  573. val *= 16;
  574. if (byte2 >= '0' && byte2 <= '9')
  575. val += byte2 - '0';
  576. if (byte2 >= 'a' && byte2 <= 'f')
  577. val += byte2 - 'a' + 10;
  578. new->checksum.bytes[nbytes] = val;
  579. snprintf(checksum_text + nbytes * 2, 3, "%02x", val);
  580. }
  581. if (nbytes < sizeof(sgx_checksum_t)) {
  582. free(new);
  583. return -PAL_ERROR_INVAL;
  584. }
  585. new->index = (++trusted_file_indexes);
  586. SGX_DBG(DBG_S, "trusted: [%ld] %s %s\n", new->index,
  587. checksum_text, new->uri);
  588. } else {
  589. memset(&new->checksum, 0, sizeof(sgx_checksum_t));
  590. new->index = 0;
  591. SGX_DBG(DBG_S, "allowed: %s\n", new->uri);
  592. }
  593. spinlock_lock(&trusted_file_lock);
  594. LISTP_FOR_EACH_ENTRY(tf, &trusted_file_list, list) {
  595. if (tf->uri_len == uri_len && !memcmp(tf->uri, uri, uri_len)) {
  596. spinlock_unlock(&trusted_file_lock);
  597. free(new);
  598. return 0;
  599. }
  600. }
  601. LISTP_ADD_TAIL(new, &trusted_file_list, list);
  602. spinlock_unlock(&trusted_file_lock);
  603. return 0;
  604. }
  605. static int init_trusted_file (const char * key, const char * uri)
  606. {
  607. char cskey[URI_MAX], * tmp;
  608. char checksum[URI_MAX];
  609. char normpath[URI_MAX];
  610. tmp = strcpy_static(cskey, "sgx.trusted_checksum.", URI_MAX);
  611. memcpy(tmp, key, strlen(key) + 1);
  612. ssize_t ret = get_config(pal_state.root_config, cskey, checksum, sizeof(checksum));
  613. if (ret < 0)
  614. return 0;
  615. /* Normalize the uri */
  616. if (!strstartswith_static(uri, URI_PREFIX_FILE)) {
  617. SGX_DBG(DBG_E, "Invalid URI [%s]: Trusted files must start with 'file:'\n", uri);
  618. return -PAL_ERROR_INVAL;
  619. }
  620. assert(sizeof(normpath) > URI_PREFIX_FILE_LEN);
  621. memcpy(normpath, URI_PREFIX_FILE, URI_PREFIX_FILE_LEN);
  622. size_t len = sizeof(normpath) - URI_PREFIX_FILE_LEN;
  623. ret = get_norm_path(uri + URI_PREFIX_FILE_LEN, normpath + URI_PREFIX_FILE_LEN, &len);
  624. if (ret < 0) {
  625. SGX_DBG(DBG_E,
  626. "Path (%s) normalization failed: %s\n",
  627. uri + URI_PREFIX_FILE_LEN,
  628. pal_strerror(ret));
  629. return ret;
  630. }
  631. return register_trusted_file(normpath, checksum);
  632. }
  633. int init_trusted_files (void) {
  634. struct config_store* store = pal_state.root_config;
  635. char* cfgbuf = NULL;
  636. ssize_t cfgsize;
  637. int nuris, ret;
  638. char key[CONFIG_MAX];
  639. char uri[CONFIG_MAX];
  640. char* k;
  641. char* tmp;
  642. if (pal_sec.exec_name[0] != '\0') {
  643. ret = init_trusted_file("exec", pal_sec.exec_name);
  644. if (ret < 0)
  645. goto out;
  646. }
  647. cfgbuf = malloc(CONFIG_MAX);
  648. if (!cfgbuf) {
  649. ret = -PAL_ERROR_NOMEM;
  650. goto out;
  651. }
  652. ssize_t len = get_config(store, "loader.preload", cfgbuf, CONFIG_MAX);
  653. if (len > 0) {
  654. int npreload = 0;
  655. char key[10];
  656. const char * start, * end;
  657. for (start = cfgbuf ; start < cfgbuf + len ; start = end + 1) {
  658. for (end = start ; end < cfgbuf + len && *end && *end != ',' ; end++);
  659. if (end > start) {
  660. char uri[end - start + 1];
  661. memcpy(uri, start, end - start);
  662. uri[end - start] = 0;
  663. snprintf(key, 10, "preload%d", npreload++);
  664. ret = init_trusted_file(key, uri);
  665. if (ret < 0)
  666. goto out;
  667. }
  668. }
  669. }
  670. cfgsize = get_config_entries_size(store, "sgx.trusted_files");
  671. if (cfgsize <= 0)
  672. goto no_trusted;
  673. free(cfgbuf);
  674. cfgbuf = malloc(cfgsize);
  675. if (!cfgbuf) {
  676. ret = -PAL_ERROR_NOMEM;
  677. goto out;
  678. }
  679. nuris = get_config_entries(store, "sgx.trusted_files", cfgbuf, cfgsize);
  680. if (nuris <= 0)
  681. goto no_trusted;
  682. tmp = strcpy_static(key, "sgx.trusted_files.", sizeof(key));
  683. k = cfgbuf;
  684. for (int i = 0 ; i < nuris ; i++) {
  685. len = strlen(k);
  686. memcpy(tmp, k, len + 1);
  687. k += len + 1;
  688. len = get_config(store, key, uri, sizeof(uri));
  689. if (len > 0) {
  690. ret = init_trusted_file(key + static_strlen("sgx.trusted_files."), uri);
  691. if (ret < 0)
  692. goto out;
  693. }
  694. }
  695. no_trusted:
  696. cfgsize = get_config_entries_size(store, "sgx.allowed_files");
  697. if (cfgsize <= 0)
  698. goto no_allowed;
  699. free(cfgbuf);
  700. cfgbuf = malloc(cfgsize);
  701. if (!cfgbuf) {
  702. ret = -PAL_ERROR_NOMEM;
  703. goto out;
  704. }
  705. nuris = get_config_entries(store, "sgx.allowed_files", cfgbuf, cfgsize);
  706. if (nuris <= 0)
  707. goto no_allowed;
  708. tmp = strcpy_static(key, "sgx.allowed_files.", sizeof(key));
  709. k = cfgbuf;
  710. for (int i = 0 ; i < nuris ; i++) {
  711. len = strlen(k);
  712. memcpy(tmp, k, len + 1);
  713. k += len + 1;
  714. len = get_config(store, key, uri, sizeof(uri));
  715. if (len <= 0) {
  716. continue;
  717. }
  718. /* Normalize the uri */
  719. char norm_path[URI_MAX];
  720. if (!strstartswith_static(uri, URI_PREFIX_FILE)) {
  721. SGX_DBG(DBG_E, "Invalid URI [%s]: Allowed files must start with 'file:'\n", uri);
  722. ret = -PAL_ERROR_INVAL;
  723. goto out;
  724. }
  725. assert(sizeof(norm_path) > URI_PREFIX_FILE_LEN);
  726. memcpy(norm_path, URI_PREFIX_FILE, URI_PREFIX_FILE_LEN);
  727. size_t norm_path_len = sizeof(norm_path) - URI_PREFIX_FILE_LEN;
  728. ret = get_norm_path(uri + URI_PREFIX_FILE_LEN,
  729. norm_path + URI_PREFIX_FILE_LEN,
  730. &norm_path_len);
  731. if (ret < 0) {
  732. SGX_DBG(DBG_E,
  733. "Path (%s) normalization failed: %s\n",
  734. uri + URI_PREFIX_FILE_LEN,
  735. pal_strerror(ret));
  736. goto out;
  737. }
  738. register_trusted_file(norm_path, NULL);
  739. }
  740. no_allowed:
  741. ret = 0;
  742. if (get_config(store, "sgx.allow_file_creation", cfgbuf, cfgsize) > 0 && cfgbuf[0] == '1')
  743. allow_file_creation = true;
  744. else
  745. allow_file_creation = false;
  746. out:
  747. free(cfgbuf);
  748. return ret;
  749. }
  750. int init_trusted_children (void)
  751. {
  752. struct config_store * store = pal_state.root_config;
  753. char key[CONFIG_MAX], mrkey[CONFIG_MAX];
  754. char uri[CONFIG_MAX], mr_enclave[CONFIG_MAX];
  755. char * tmp1 = strcpy_static(key, "sgx.trusted_children.", sizeof(key));
  756. char * tmp2 = strcpy_static(mrkey, "sgx.trusted_mrenclave.", sizeof(mrkey));
  757. ssize_t cfgsize = get_config_entries_size(store, "sgx.trusted_mrenclave");
  758. if (cfgsize <= 0)
  759. return 0;
  760. char * cfgbuf = malloc(cfgsize);
  761. if (!cfgbuf)
  762. return -PAL_ERROR_NOMEM;
  763. int nuris = get_config_entries(store, "sgx.trusted_mrenclave",
  764. cfgbuf, cfgsize);
  765. if (nuris > 0) {
  766. char * k = cfgbuf;
  767. for (int i = 0 ; i < nuris ; i++) {
  768. int len = strlen(k);
  769. memcpy(tmp1, k, len + 1);
  770. memcpy(tmp2, k, len + 1);
  771. k += len + 1;
  772. ssize_t ret = get_config(store, key, uri, sizeof(uri));
  773. if (ret < 0)
  774. continue;
  775. ret = get_config(store, mrkey, mr_enclave, sizeof(mr_enclave));
  776. if (ret > 0)
  777. register_trusted_child(uri, mr_enclave);
  778. }
  779. }
  780. free(cfgbuf);
  781. return 0;
  782. }
  783. int init_file_check_policy (void)
  784. {
  785. char cfgbuf[CONFIG_MAX];
  786. ssize_t ret = get_config(pal_state.root_config, "sgx.file_check_policy",
  787. cfgbuf, sizeof(cfgbuf));
  788. if (ret > 0) {
  789. if (!strcmp_static(cfgbuf, "strict"))
  790. set_file_check_policy(FILE_CHECK_POLICY_STRICT);
  791. else if (!strcmp_static(cfgbuf, "allow_all_but_log"))
  792. set_file_check_policy(FILE_CHECK_POLICY_ALLOW_ALL_BUT_LOG);
  793. else
  794. INIT_FAIL(PAL_ERROR_INVAL, "unknown file check policy");
  795. SGX_DBG(DBG_S, "File check policy: %s\n", cfgbuf);
  796. }
  797. return 0;
  798. }
  799. int init_enclave (void)
  800. {
  801. // Get report to initialize info (MR_ENCLAVE, etc.) about this enclave from
  802. // a trusted source.
  803. // Since this report is only read by ourselves we can
  804. // leave targetinfo zeroed.
  805. __sgx_mem_aligned sgx_target_info_t targetinfo = {0};
  806. __sgx_mem_aligned struct pal_enclave_state reportdata = {0};
  807. __sgx_mem_aligned sgx_report_t report;
  808. assert(sizeof(reportdata) == sizeof(sgx_report_data_t));
  809. int ret = sgx_report(&targetinfo, (sgx_report_data_t*)&reportdata, &report);
  810. if (ret) {
  811. SGX_DBG(DBG_E, "failed to get self report: %d\n", ret);
  812. return -PAL_ERROR_INVAL;
  813. }
  814. memcpy(&pal_sec.mr_enclave, &report.body.mr_enclave, sizeof(pal_sec.mr_enclave));
  815. memcpy(&pal_sec.mr_signer, &report.body.mr_signer, sizeof(pal_sec.mr_signer));
  816. pal_sec.enclave_attributes = report.body.attributes;
  817. /*
  818. * The enclave id is uniquely created for each enclave as a token
  819. * for authenticating the enclave as the sender of attestation.
  820. * See 'host/Linux-SGX/db_process.c' for further explanation.
  821. */
  822. ret = _DkRandomBitsRead(&pal_enclave_state.enclave_id,
  823. sizeof(pal_enclave_state.enclave_id));
  824. if (ret < 0) {
  825. SGX_DBG(DBG_E, "Failed to generate a random id: %d\n", ret);
  826. return ret;
  827. }
  828. return 0;
  829. }
  830. int _DkStreamKeyExchange(PAL_HANDLE stream, PAL_SESSION_KEY* key) {
  831. uint8_t pub[DH_SIZE] __attribute__((aligned(DH_SIZE)));
  832. uint8_t agree[DH_SIZE] __attribute__((aligned(DH_SIZE)));
  833. PAL_NUM pubsz, agreesz;
  834. LIB_DH_CONTEXT context;
  835. int64_t bytes;
  836. int64_t ret;
  837. ret = lib_DhInit(&context);
  838. if (ret < 0) {
  839. SGX_DBG(DBG_E, "Key Exchange: DH Init failed: %ld\n", ret);
  840. goto out_no_final;
  841. }
  842. pubsz = sizeof pub;
  843. ret = lib_DhCreatePublic(&context, pub, &pubsz);
  844. if (ret < 0) {
  845. SGX_DBG(DBG_E, "Key Exchange: DH CreatePublic failed: %ld\n", ret);
  846. goto out;
  847. }
  848. assert(pubsz > 0 && pubsz <= DH_SIZE);
  849. if (pubsz < DH_SIZE) {
  850. /* Insert leading zero bytes if necessary. These values are big-
  851. * endian, so we either need to know the length of the bignum or
  852. * zero-pad at the beginning instead of the end. This code chooses
  853. * to do the latter. */
  854. memmove(pub + (DH_SIZE - pubsz), pub, pubsz);
  855. memset(pub, 0, DH_SIZE - pubsz);
  856. }
  857. for (bytes = 0, ret = 0; bytes < DH_SIZE; bytes += ret) {
  858. ret = _DkStreamWrite(stream, 0, DH_SIZE - bytes, pub + bytes, NULL, 0);
  859. if (ret < 0) {
  860. if (ret == -PAL_ERROR_INTERRUPTED || ret == -PAL_ERROR_TRYAGAIN) {
  861. ret = 0;
  862. continue;
  863. }
  864. SGX_DBG(DBG_E, "Failed to exchange the secret key via RPC: %ld\n", ret);
  865. goto out;
  866. }
  867. }
  868. for (bytes = 0, ret = 0 ; bytes < DH_SIZE ; bytes += ret) {
  869. ret = _DkStreamRead(stream, 0, DH_SIZE - bytes, pub + bytes, NULL, 0);
  870. if (ret < 0) {
  871. if (ret == -PAL_ERROR_INTERRUPTED || ret == -PAL_ERROR_TRYAGAIN) {
  872. ret = 0;
  873. continue;
  874. }
  875. SGX_DBG(DBG_E, "Failed to exchange the secret key via RPC: %ld\n", ret);
  876. goto out;
  877. }
  878. }
  879. agreesz = sizeof agree;
  880. ret = lib_DhCalcSecret(&context, pub, DH_SIZE, agree, &agreesz);
  881. if (ret < 0) {
  882. SGX_DBG(DBG_E, "Key Exchange: DH CalcSecret failed: %ld\n", ret);
  883. goto out;
  884. }
  885. assert(agreesz > 0 && agreesz <= sizeof agree);
  886. /*
  887. * Using SHA256 as a KDF to convert the 128-byte DH secret to a 256-bit AES key.
  888. * According to the NIST recommendation:
  889. * https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-56Cr1.pdf,
  890. * a key derivation function (KDF) can be a secure hash function (e.g., SHA-256),
  891. * HMAC, or KMAC.
  892. */
  893. LIB_SHA256_CONTEXT sha;
  894. if ((ret = lib_SHA256Init(&sha)) < 0 ||
  895. (ret = lib_SHA256Update(&sha, agree, agreesz)) < 0 ||
  896. (ret = lib_SHA256Final(&sha, (uint8_t*)key)) < 0) {
  897. SGX_DBG(DBG_E, "Failed to derive the session key: %ld\n", ret);
  898. goto out;
  899. }
  900. SGX_DBG(DBG_S, "Key exchange succeeded: %s\n", ALLOCA_BYTES2HEXSTR(*key));
  901. ret = 0;
  902. out:
  903. lib_DhFinal(&context);
  904. out_no_final:
  905. return ret;
  906. }
  907. /*
  908. * Initalize the request of local report exchange.
  909. *
  910. * We refer to this enclave as A and to the other enclave as B, e.g., A is this
  911. * parent enclave and B is the child enclave in the fork case (for more info,
  912. * see comments in db_process.c).
  913. */
  914. int _DkStreamReportRequest(PAL_HANDLE stream, sgx_sign_data_t* data,
  915. check_mr_enclave_t check_mr_enclave) {
  916. __sgx_mem_aligned sgx_target_info_t target_info;
  917. __sgx_mem_aligned sgx_report_t report;
  918. uint64_t bytes;
  919. int64_t ret;
  920. /* A -> B: targetinfo[A] */
  921. memset(&target_info, 0, sizeof(target_info));
  922. memcpy(&target_info.mr_enclave, &pal_sec.mr_enclave, sizeof(sgx_measurement_t));
  923. memcpy(&target_info.attributes, &pal_sec.enclave_attributes, sizeof(sgx_attributes_t));
  924. for (bytes = 0, ret = 0; bytes < SGX_TARGETINFO_FILLED_SIZE; bytes += ret) {
  925. ret = _DkStreamWrite(stream, 0, SGX_TARGETINFO_FILLED_SIZE - bytes,
  926. ((void*)&target_info) + bytes, NULL, 0);
  927. if (ret < 0) {
  928. if (ret == -PAL_ERROR_INTERRUPTED || ret == -PAL_ERROR_TRYAGAIN) {
  929. ret = 0;
  930. continue;
  931. }
  932. SGX_DBG(DBG_E, "Failed to send target info via RPC: %ld\n", ret);
  933. goto out;
  934. }
  935. }
  936. /* B -> A: report[B -> A] */
  937. for (bytes = 0, ret = 0 ; bytes < sizeof(report) ; bytes += ret) {
  938. ret = _DkStreamRead(stream, 0, sizeof(report) - bytes,
  939. ((void*)&report) + bytes, NULL, 0);
  940. if (ret < 0) {
  941. if (ret == -PAL_ERROR_INTERRUPTED || ret == -PAL_ERROR_TRYAGAIN) {
  942. ret = 0;
  943. continue;
  944. }
  945. SGX_DBG(DBG_E, "Failed to receive local report via RPC: %ld\n", ret);
  946. goto out;
  947. }
  948. }
  949. SGX_DBG(DBG_S, "Received local report (mr_enclave = %s)\n",
  950. ALLOCA_BYTES2HEXSTR(report.body.mr_enclave.m));
  951. /* Verify report[B -> A] */
  952. ret = sgx_verify_report(&report);
  953. if (ret < 0) {
  954. SGX_DBG(DBG_E, "Failed to verify local report: %ld\n", ret);
  955. goto out;
  956. }
  957. struct pal_enclave_state* remote_state = (void*)&report.body.report_data;
  958. ret = check_mr_enclave(stream, &report.body.mr_enclave, remote_state);
  959. if (ret < 0) {
  960. SGX_DBG(DBG_E, "Failed to check local report: %ld\n", ret);
  961. goto out;
  962. }
  963. if (ret == 1) {
  964. SGX_DBG(DBG_E, "Not an allowed enclave (mr_enclave = %s). Maybe missing 'sgx.trusted_children' in the manifest file?\n",
  965. ALLOCA_BYTES2HEXSTR(report.body.mr_enclave.m));
  966. ret = -PAL_ERROR_DENIED;
  967. goto out;
  968. }
  969. SGX_DBG(DBG_S, "Local attestation succeeded!\n");
  970. /* A -> B: report[A -> B] */
  971. memcpy(&target_info.mr_enclave , &report.body.mr_enclave, sizeof(sgx_measurement_t));
  972. memcpy(&target_info.attributes, &report.body.attributes, sizeof(sgx_attributes_t));
  973. ret = sgx_get_report(&target_info, data, &report);
  974. if (ret < 0) {
  975. SGX_DBG(DBG_E, "Failed to get local report from CPU: %ld\n", ret);
  976. goto out;
  977. }
  978. for (bytes = 0, ret = 0 ; bytes < sizeof(report) ; bytes += ret) {
  979. ret = _DkStreamWrite(stream, 0, sizeof(report) - bytes,
  980. ((void*)&report) + bytes, NULL, 0);
  981. if (ret < 0) {
  982. if (ret == -PAL_ERROR_INTERRUPTED || ret == -PAL_ERROR_TRYAGAIN) {
  983. ret = 0;
  984. continue;
  985. }
  986. SGX_DBG(DBG_E, "Failed to send local report via RPC: %ld\n", ret);
  987. goto out;
  988. }
  989. }
  990. return 0;
  991. out:
  992. DkStreamDelete(stream, 0);
  993. return ret;
  994. }
  995. /*
  996. * Respond to the request of local report exchange.
  997. *
  998. * We refer to this enclave as B and to the other enclave as A, e.g., B is this
  999. * child enclave and A is the parent enclave in the fork case (for more info,
  1000. * see comments in db_process.c).
  1001. */
  1002. int _DkStreamReportRespond(PAL_HANDLE stream, sgx_sign_data_t* data,
  1003. check_mr_enclave_t check_mr_enclave) {
  1004. __sgx_mem_aligned sgx_target_info_t target_info;
  1005. __sgx_mem_aligned sgx_report_t report;
  1006. uint64_t bytes;
  1007. int64_t ret;
  1008. memset(&target_info, 0, sizeof(target_info));
  1009. /* A -> B: targetinfo[A] */
  1010. for (bytes = 0, ret = 0 ; bytes < SGX_TARGETINFO_FILLED_SIZE ; bytes += ret) {
  1011. ret = _DkStreamRead(stream, 0, SGX_TARGETINFO_FILLED_SIZE - bytes,
  1012. ((void*)&target_info) + bytes, NULL, 0);
  1013. if (ret < 0) {
  1014. if (ret == -PAL_ERROR_INTERRUPTED || ret == -PAL_ERROR_TRYAGAIN) {
  1015. ret = 0;
  1016. continue;
  1017. }
  1018. SGX_DBG(DBG_E, "Failed to receive target info via RPC: %ld\n", ret);
  1019. goto out;
  1020. }
  1021. }
  1022. /* B -> A: report[B -> A] */
  1023. ret = sgx_get_report(&target_info, data, &report);
  1024. if (ret < 0) {
  1025. SGX_DBG(DBG_E, "Failed to get local report from CPU: %ld\n", ret);
  1026. goto out;
  1027. }
  1028. for (bytes = 0, ret = 0 ; bytes < sizeof(report) ; bytes += ret) {
  1029. ret = _DkStreamWrite(stream, 0, sizeof(report) - bytes,
  1030. ((void*)&report) + bytes, NULL, 0);
  1031. if (ret < 0) {
  1032. if (ret == -PAL_ERROR_INTERRUPTED || ret == -PAL_ERROR_TRYAGAIN) {
  1033. ret = 0;
  1034. continue;
  1035. }
  1036. SGX_DBG(DBG_E, "Failed to send local report via PRC: %ld\n", ret);
  1037. goto out;
  1038. }
  1039. }
  1040. /* A -> B: report[A -> B] */
  1041. for (bytes = 0, ret = 0 ; bytes < sizeof(report) ; bytes += ret) {
  1042. ret = _DkStreamRead(stream, 0, sizeof(report) - bytes,
  1043. ((void*)&report) + bytes, NULL, 0);
  1044. if (ret < 0) {
  1045. if (ret == -PAL_ERROR_INTERRUPTED || ret == -PAL_ERROR_TRYAGAIN) {
  1046. ret = 0;
  1047. continue;
  1048. }
  1049. SGX_DBG(DBG_E, "Failed to receive local report via RPC: %ld\n", ret);
  1050. goto out;
  1051. }
  1052. }
  1053. SGX_DBG(DBG_S, "Received local report (mr_enclave = %s)\n",
  1054. ALLOCA_BYTES2HEXSTR(report.body.mr_enclave.m));
  1055. /* Verify report[A -> B] */
  1056. ret = sgx_verify_report(&report);
  1057. if (ret < 0) {
  1058. SGX_DBG(DBG_E, "Failed to verify local report: %ld\n", ret);
  1059. goto out;
  1060. }
  1061. struct pal_enclave_state* remote_state = (void*)&report.body.report_data;
  1062. ret = check_mr_enclave(stream, &report.body.mr_enclave, remote_state);
  1063. if (ret < 0) {
  1064. SGX_DBG(DBG_E, "Failed to check mr_enclave: %ld\n", ret);
  1065. goto out;
  1066. }
  1067. if (ret == 1) {
  1068. SGX_DBG(DBG_E, "Not an allowed enclave (mr_enclave = %s). Maybe missing 'sgx.trusted_children' in the manifest file?\n",
  1069. ALLOCA_BYTES2HEXSTR(report.body.mr_enclave.m));
  1070. ret = -PAL_ERROR_DENIED;
  1071. goto out;
  1072. }
  1073. SGX_DBG(DBG_S, "Local attestation succeeded!\n");
  1074. return 0;
  1075. out:
  1076. DkStreamDelete(stream, 0);
  1077. return ret;
  1078. }
  1079. int _DkStreamSecureInit(PAL_HANDLE stream, bool is_server, PAL_SESSION_KEY* session_key,
  1080. LIB_SSL_CONTEXT** out_ssl_ctx) {
  1081. int stream_fd;
  1082. if (IS_HANDLE_TYPE(stream, process))
  1083. stream_fd = stream->process.stream;
  1084. else
  1085. return -PAL_ERROR_BADHANDLE;
  1086. LIB_SSL_CONTEXT* ssl_ctx = malloc(sizeof(*ssl_ctx));
  1087. if (!ssl_ctx)
  1088. return -PAL_ERROR_NOMEM;
  1089. int ret = lib_SSLInit(ssl_ctx, stream_fd, is_server,
  1090. (const uint8_t*)session_key, sizeof(*session_key),
  1091. ocall_read, ocall_write);
  1092. if (ret != 0) {
  1093. free(ssl_ctx);
  1094. return ret;
  1095. }
  1096. *out_ssl_ctx = ssl_ctx;
  1097. return 0;
  1098. }
  1099. int _DkStreamSecureFree(LIB_SSL_CONTEXT* ssl_ctx) {
  1100. lib_SSLFree(ssl_ctx);
  1101. free(ssl_ctx);
  1102. return 0;
  1103. }
  1104. int _DkStreamSecureRead(LIB_SSL_CONTEXT* ssl_ctx, uint8_t* buf, size_t len) {
  1105. return lib_SSLRead(ssl_ctx, buf, len);
  1106. }
  1107. int _DkStreamSecureWrite(LIB_SSL_CONTEXT* ssl_ctx, const uint8_t* buf, size_t len) {
  1108. return lib_SSLWrite(ssl_ctx, buf, len);
  1109. }