enclave_framework.c 43 KB

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