enclave_framework.c 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245
  1. /* -*- mode:c; c-file-style:"k&r"; c-basic-offset: 4; tab-width:4; indent-tabs-mode:nil; mode:auto-fill; fill-column:78; -*- */
  2. /* vim: set ts=4 sw=4 et tw=78 fo=cqt wm=0: */
  3. #include <pal_linux.h>
  4. #include <pal_linux_error.h>
  5. #include <pal_internal.h>
  6. #include <pal_debug.h>
  7. #include <pal_security.h>
  8. #include <pal_crypto.h>
  9. #include <api.h>
  10. #include <list.h>
  11. #include <stdbool.h>
  12. #include "enclave_pages.h"
  13. 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. int sgx_get_report (sgx_arch_hash_t * mrenclave,
  78. sgx_arch_attributes_t * attributes,
  79. void * enclave_data,
  80. sgx_arch_report_t * report)
  81. {
  82. sgx_arch_targetinfo_t targetinfo;
  83. memset(&targetinfo, 0, sizeof(sgx_arch_targetinfo_t));
  84. memcpy(targetinfo.mrenclave, mrenclave, sizeof(sgx_arch_hash_t));
  85. memcpy(&targetinfo.attributes, attributes, sizeof(sgx_arch_attributes_t));
  86. struct pal_enclave_state state;
  87. memcpy(&state, &pal_enclave_state, sizeof(struct pal_enclave_state));
  88. memcpy(&state.data, enclave_data, PAL_ATTESTATION_DATA_SIZE);
  89. int ret = sgx_report(&targetinfo, &state, report);
  90. if (ret)
  91. return -PAL_ERROR_DENIED;
  92. SGX_DBG(DBG_S, "Generated report:\n");
  93. SGX_DBG(DBG_S, " cpusvn: %08lx %08lx\n", report->cpusvn[0],
  94. report->cpusvn[1]);
  95. SGX_DBG(DBG_S, " mrenclave: %s\n", ALLOCA_BYTES2HEXSTR(report->mrenclave));
  96. SGX_DBG(DBG_S, " mrsigner: %s\n", ALLOCA_BYTES2HEXSTR(report->mrsigner));
  97. SGX_DBG(DBG_S, " attributes.flags: %016lx\n", report->attributes.flags);
  98. SGX_DBG(DBG_S, " sttributes.xfrm: %016lx\n", report->attributes.xfrm);
  99. SGX_DBG(DBG_S, " isvprodid: %02x\n", report->isvprodid);
  100. SGX_DBG(DBG_S, " isvsvn: %02x\n", report->isvsvn);
  101. SGX_DBG(DBG_S, " keyid: %s\n", ALLOCA_BYTES2HEXSTR(report->keyid));
  102. SGX_DBG(DBG_S, " mac: %s\n", ALLOCA_BYTES2HEXSTR(report->mac));
  103. return 0;
  104. }
  105. static sgx_arch_key128_t enclave_key;
  106. #define KEYBUF_SIZE ((sizeof(sgx_arch_key128_t) * 2) + 1)
  107. int sgx_verify_report (sgx_arch_report_t * report)
  108. {
  109. sgx_arch_keyrequest_t keyrequest;
  110. memset(&keyrequest, 0, sizeof(sgx_arch_keyrequest_t));
  111. keyrequest.keyname = REPORT_KEY;
  112. memcpy(keyrequest.keyid, report->keyid, sizeof(keyrequest.keyid));
  113. int ret = sgx_getkey(&keyrequest, &enclave_key);
  114. if (ret) {
  115. SGX_DBG(DBG_S, "Can't get report key\n");
  116. return -PAL_ERROR_DENIED;
  117. }
  118. SGX_DBG(DBG_S, "Get report key for verification: %s\n",
  119. ALLOCA_BYTES2HEXSTR(enclave_key));
  120. return 0;
  121. }
  122. int init_enclave_key (void)
  123. {
  124. sgx_arch_keyrequest_t keyrequest;
  125. memset(&keyrequest, 0, sizeof(sgx_arch_keyrequest_t));
  126. keyrequest.keyname = SEAL_KEY;
  127. int ret = sgx_getkey(&keyrequest, &enclave_key);
  128. if (ret) {
  129. SGX_DBG(DBG_S, "Can't get report key\n");
  130. return -PAL_ERROR_DENIED;
  131. }
  132. SGX_DBG(DBG_S, "Get sealing key: %s\n", ALLOCA_BYTES2HEXSTR(enclave_key));
  133. return 0;
  134. }
  135. /*
  136. * The file integrity check is designed as follow:
  137. *
  138. * For each file that requires authentication (specified in the manifest
  139. * as "sgx.trusted_files.xxx"), a SHA256 checksum is generated and stored
  140. * in the manifest, signed and verified as part of the enclave's crypto
  141. * measurement. When user requests for opening the file, Graphene loads
  142. * the whole file, generate the SHA256 checksum, and check with the known
  143. * checksums listed in the manifest. If the checksum does not match, and
  144. * neither does the file is allowed for unauthenticated access, the file
  145. * access will be rejected.
  146. *
  147. * During the generation of the SHA256 checksum, a 128-bit hash is also
  148. * generated for each chunk in the file. The per-chunk hashes are used
  149. * for partial verification in future reads, to avoid re-verifying the
  150. * whole file again or the need of caching file contents. The per-chunk
  151. * hashes are stored as "stubs" for each file. For a performance reason,
  152. * each per-chunk hash is a 128-bit AES-CMAC hash value, using a secret
  153. * key generated at the beginning of the enclave.
  154. */
  155. DEFINE_LIST(trusted_file);
  156. struct trusted_file {
  157. LIST_TYPE(trusted_file) list;
  158. int64_t index;
  159. uint64_t size;
  160. int uri_len;
  161. char uri[URI_MAX];
  162. sgx_checksum_t checksum;
  163. sgx_stub_t * stubs;
  164. };
  165. DEFINE_LISTP(trusted_file);
  166. static LISTP_TYPE(trusted_file) trusted_file_list = LISTP_INIT;
  167. static struct spinlock trusted_file_lock = LOCK_INIT;
  168. static int trusted_file_indexes = 0;
  169. static bool allow_file_creation = 0;
  170. /*
  171. * 'load_trusted_file' checks if the file to be opened is trusted
  172. * or allowed for unauthenticated access, according to the manifest.
  173. *
  174. * file: file handle to be opened
  175. * stubptr: buffer for catching matched file stub.
  176. * sizeptr: size pointer
  177. * create: this file is newly created or not
  178. *
  179. * return: 0 succeed
  180. */
  181. int load_trusted_file (PAL_HANDLE file, sgx_stub_t ** stubptr,
  182. uint64_t * sizeptr, int create)
  183. {
  184. struct trusted_file * tf = NULL, * tmp;
  185. char uri[URI_MAX];
  186. char normpath[URI_MAX];
  187. int ret, fd = file->file.fd, uri_len, len;
  188. if (!(HANDLE_HDR(file)->flags & RFD(0)))
  189. return -PAL_ERROR_DENIED;
  190. uri_len = _DkStreamGetName(file, uri, URI_MAX);
  191. if (uri_len < 0)
  192. return uri_len;
  193. /* Allow to create the file when allow_file_creation is turned on;
  194. The created file is added to allowed_file list for later access */
  195. if (create && allow_file_creation) {
  196. register_trusted_file(uri, NULL);
  197. *sizeptr = 0;
  198. return 0;
  199. }
  200. /* Normalize the uri */
  201. if (!strpartcmp_static(uri, "file:")) {
  202. SGX_DBG(DBG_E, "Invalid URI [%s]: Trusted files must start with 'file:'\n", uri);;
  203. return -PAL_ERROR_INVAL;
  204. }
  205. normpath [0] = 'f';
  206. normpath [1] = 'i';
  207. normpath [2] = 'l';
  208. normpath [3] = 'e';
  209. normpath [4] = ':';
  210. len = get_norm_path(uri + 5, normpath + 5, 0, URI_MAX);
  211. uri_len = len + 5;
  212. _DkSpinLock(&trusted_file_lock);
  213. listp_for_each_entry(tmp, &trusted_file_list, list) {
  214. if (tmp->stubs) {
  215. /* trusted files: must be exactly the same URI */
  216. if (tmp->uri_len == uri_len && !memcmp(tmp->uri, normpath, uri_len + 1)) {
  217. tf = tmp;
  218. break;
  219. }
  220. } else {
  221. /* allowed files: must be a subfolder or file */
  222. if (tmp->uri_len <= uri_len &&
  223. !memcmp(tmp->uri, normpath, tmp->uri_len) &&
  224. (!normpath[tmp->uri_len] || normpath[tmp->uri_len] == '/')) {
  225. tf = tmp;
  226. break;
  227. }
  228. }
  229. }
  230. _DkSpinUnlock(&trusted_file_lock);
  231. if (!tf)
  232. return -PAL_ERROR_DENIED;
  233. if (tf->index < 0)
  234. return tf->index;
  235. #if CACHE_FILE_STUBS == 1
  236. if (tf->index && tf->stubs) {
  237. *stubptr = tf->stubs;
  238. *sizeptr = tf->size;
  239. return 0;
  240. }
  241. #endif
  242. if (!tf->index) {
  243. *stubptr = NULL;
  244. PAL_STREAM_ATTR attr;
  245. ret = _DkStreamAttributesQuery(normpath, &attr);
  246. if (!ret)
  247. *sizeptr = attr.pending_size;
  248. else
  249. *sizeptr = 0;
  250. return 0;
  251. }
  252. int nstubs = tf->size / TRUSTED_STUB_SIZE +
  253. (tf->size % TRUSTED_STUB_SIZE ? 1 : 0);
  254. sgx_stub_t * stubs = malloc(sizeof(sgx_stub_t) * nstubs);
  255. if (!stubs)
  256. return -PAL_ERROR_NOMEM;
  257. sgx_stub_t * s = stubs; /* stubs is an array of 128bit values */
  258. uint64_t offset = 0;
  259. LIB_SHA256_CONTEXT sha;
  260. void * umem;
  261. ret = lib_SHA256Init(&sha);
  262. if (ret < 0)
  263. goto failed;
  264. for (; offset < tf->size ; offset += TRUSTED_STUB_SIZE, s++) {
  265. /* For each stub, generate a 128bit hash of a file chunk with
  266. * AES-CMAC, and then update the SHA256 digest. */
  267. uint64_t mapping_size = MIN(tf->size - offset, TRUSTED_STUB_SIZE);
  268. LIB_AESCMAC_CONTEXT aes_cmac;
  269. ret = lib_AESCMACInit(&aes_cmac, (uint8_t *) &enclave_key,
  270. AES_CMAC_KEY_LEN);
  271. if (ret < 0)
  272. goto failed;
  273. ret = ocall_map_untrusted(fd, offset, mapping_size, PROT_READ, &umem);
  274. if (IS_ERR(ret)) {
  275. ret = unix_to_pal_error(ERRNO(ret));
  276. goto unmap;
  277. }
  278. /*
  279. * To prevent TOCTOU attack when generating the file checksum, we
  280. * need to copy the file content into the enclave before hashing.
  281. * For optimization, we use a relatively small buffer (1024 byte) to
  282. * store the data for checksum generation.
  283. */
  284. #define FILE_CHUNK_SIZE 1024
  285. uint8_t small_chunk[FILE_CHUNK_SIZE]; /* Buffer for hashing */
  286. int chunk_offset = 0;
  287. for (; chunk_offset < mapping_size; chunk_offset += FILE_CHUNK_SIZE) {
  288. uint64_t chunk_size = MIN(mapping_size - chunk_offset, FILE_CHUNK_SIZE);
  289. /* Any file content needs to be copied into the enclave before
  290. * checking and re-hashing */
  291. memcpy(small_chunk, umem + chunk_offset, chunk_size);
  292. /* Update the file checksum */
  293. ret = lib_SHA256Update(&sha, small_chunk, chunk_size);
  294. if (ret < 0)
  295. goto unmap;
  296. /* Update the checksum for the file chunk */
  297. ret = lib_AESCMACUpdate(&aes_cmac, small_chunk, chunk_size);
  298. if (ret < 0)
  299. goto unmap;
  300. }
  301. /* Store the checksum for one file chunk for checking */
  302. ret = lib_AESCMACFinish(&aes_cmac, (uint8_t *) s, sizeof *s);
  303. unmap:
  304. ocall_unmap_untrusted(umem, mapping_size);
  305. if (ret < 0)
  306. goto failed;
  307. }
  308. sgx_checksum_t hash;
  309. /* Finalize and checking if the checksum of the whole file matches
  310. * with record given in the manifest. */
  311. ret = lib_SHA256Final(&sha, (uint8_t *) hash.bytes);
  312. if (ret < 0)
  313. goto failed;
  314. if (memcmp(&hash, &tf->checksum, sizeof(sgx_checksum_t))) {
  315. ret = -PAL_ERROR_DENIED;
  316. goto failed;
  317. }
  318. _DkSpinLock(&trusted_file_lock);
  319. if (tf->stubs || tf->index == -PAL_ERROR_DENIED)
  320. free(tf->stubs);
  321. *stubptr = tf->stubs = stubs;
  322. *sizeptr = tf->size;
  323. ret = tf->index;
  324. _DkSpinUnlock(&trusted_file_lock);
  325. return ret;
  326. failed:
  327. free(stubs);
  328. _DkSpinLock(&trusted_file_lock);
  329. if (tf->stubs) {
  330. *stubptr = tf->stubs;
  331. *sizeptr = tf->size;
  332. ret = tf->index;
  333. } else {
  334. tf->index = -PAL_ERROR_DENIED;
  335. }
  336. _DkSpinUnlock(&trusted_file_lock);
  337. #if PRINT_ENCLAVE_STAT
  338. if (!ret) {
  339. sgx_stub_t * loaded_stub;
  340. uint64_t loaded_size;
  341. PAL_HANDLE handle = NULL;
  342. if (!_DkStreamOpen(&handle, normpath, PAL_ACCESS_RDONLY, 0, 0, 0))
  343. load_trusted_file (handle, &loaded_stub, &loaded_size);
  344. }
  345. #endif
  346. return ret;
  347. }
  348. /*
  349. * A common helper function for copying and checking the file contents
  350. * from a buffer mapped outside the enclaves into an in-enclave buffer.
  351. * If needed, regions at either the beginning or the end of the copied regions
  352. * are copied into a scratch buffer to avoid a TOCTTOU race.
  353. *
  354. * * Note that it must be done this way to avoid the following TOCTTOU race
  355. * * condition with the untrusted host as an adversary:
  356. * * Adversary: put good contents in buffer
  357. * * Enclave: buffer check passes
  358. * * Adversary: put bad contents in buffer
  359. * * Enclave: copies in bad buffer contents
  360. *
  361. * * For optimization, we verify the memory in place, as the application code
  362. * should not use the memory before return. There can be subtle interactions
  363. * at the edges of a region with ELF loading. Namely, the ELF loader will
  364. * want to map several file chunks that are not aligned to TRUSTED_STUB_SIZE
  365. * next to each other, sometimes overlapping. There is probably room to
  366. * improve load time with more smarts around ELF loading, but for now, just
  367. * make things work.
  368. *
  369. * 'umem' is the untrusted file memory mapped outside the enclave (should
  370. * already be mapped up by the caller). 'umem_start' and 'umem_end' are
  371. * the offset _within the file_ of 'umem'. 'umem_start' should be aligned
  372. * to the file checking chunk size (TRUSTED_STUB_SIZE). 'umem_end' can be
  373. * either aligned, or equal to 'total_size'. 'buffer' is the in-enclave
  374. * buffer for copying the file content. 'offset' is the offset within the file
  375. * for copying into the buffer. 'size' is the size of the in-enclave buffer.
  376. * 'stubs' contain the checksums of all the chunks in a file.
  377. */
  378. int copy_and_verify_trusted_file (const char * path, const void * umem,
  379. uint64_t umem_start, uint64_t umem_end,
  380. void * buffer, uint64_t offset, uint64_t size,
  381. sgx_stub_t * stubs, uint64_t total_size)
  382. {
  383. /* Check that the untrusted mapping is aligned to TRUSTED_STUB_SIZE
  384. * and includes the range for copying into the buffer */
  385. assert(umem_start % TRUSTED_STUB_SIZE == 0);
  386. assert(offset >= umem_start && offset + size <= umem_end);
  387. /* Start copying and checking at umem_start. The checked content may or
  388. * may not be copied into the file content, depending on the offset of
  389. * the content within the file. */
  390. uint64_t checking = umem_start;
  391. /* The stubs is an array of 128-bit hash values of the file chunks.
  392. * from the beginning of the file. 's' points to the stub that needs to
  393. * be checked for the current offset. */
  394. sgx_stub_t * s = stubs + checking / TRUSTED_STUB_SIZE;
  395. int ret = 0;
  396. for (; checking < umem_end ; checking += TRUSTED_STUB_SIZE, s++) {
  397. /* Check one chunk at a time. */
  398. uint64_t checking_size = MIN(total_size - checking, TRUSTED_STUB_SIZE);
  399. uint64_t checking_end = checking + checking_size;
  400. uint8_t hash[AES_CMAC_DIGEST_LEN];
  401. if (checking >= offset && checking_end <= offset + size) {
  402. /* If the checking chunk completely overlaps with the region
  403. * needed for copying into the buffer, simplying use the buffer
  404. * for checking */
  405. memcpy(buffer + checking - offset, umem + checking - umem_start,
  406. checking_size);
  407. /* Storing the checksum (using AES-CMAC) inside hash. */
  408. ret = lib_AESCMAC((uint8_t *) &enclave_key,
  409. AES_CMAC_KEY_LEN,
  410. buffer + checking - offset, checking_size,
  411. hash, sizeof(hash));
  412. } else {
  413. /* If the checking chunk only partially overlaps with the region,
  414. * read the file content in smaller chunks and only copy the part
  415. * needed by the caller. */
  416. LIB_AESCMAC_CONTEXT aes_cmac;
  417. ret = lib_AESCMACInit(&aes_cmac, (uint8_t *) &enclave_key,
  418. AES_CMAC_KEY_LEN);
  419. if (ret < 0)
  420. goto failed;
  421. uint8_t small_chunk[FILE_CHUNK_SIZE]; /* A small buffer */
  422. uint64_t chunk_offset = checking;
  423. for (; chunk_offset < checking_end
  424. ; chunk_offset += FILE_CHUNK_SIZE) {
  425. uint64_t chunk_size = MIN(checking_end - chunk_offset,
  426. FILE_CHUNK_SIZE);
  427. /* Copy into the small buffer before hashing the content */
  428. memcpy(small_chunk, umem + (chunk_offset - umem_start),
  429. chunk_size);
  430. /* Update the hash for the current chunk */
  431. ret = lib_AESCMACUpdate(&aes_cmac, small_chunk, chunk_size);
  432. if (ret < 0)
  433. goto failed;
  434. /* Determine if the part just copied and checked is needed
  435. * by the caller. If so, copy it into the user buffer. */
  436. uint64_t copy_start = chunk_offset;
  437. uint64_t copy_end = copy_start + chunk_size;
  438. if (copy_start < offset)
  439. copy_start = offset;
  440. if (copy_end > offset + size)
  441. copy_end = offset + size;
  442. if (copy_end > copy_start)
  443. memcpy(buffer + (copy_start - offset),
  444. small_chunk + (copy_start - chunk_offset),
  445. copy_end - copy_start);
  446. }
  447. /* Storing the checksum (using AES-CMAC) inside hash. */
  448. ret = lib_AESCMACFinish(&aes_cmac, hash, sizeof(hash));
  449. }
  450. if (ret < 0)
  451. goto failed;
  452. /*
  453. * Check if the hash matches with the checksum of current chunk.
  454. * If not, return with access denied. Note: some file content may
  455. * still be in the buffer (including the corrupted part).
  456. * We assume the user won't use the content if this function
  457. * returns with failures.
  458. *
  459. * XXX: Maybe we should zero the buffer after denying the access?
  460. */
  461. if (memcmp(s, hash, sizeof(sgx_stub_t))) {
  462. SGX_DBG(DBG_E, "Accesing file:%s is denied. Does not match with MAC"
  463. " at chunk starting at %lu-%lu.\n",
  464. path, checking, checking_end);
  465. return -PAL_ERROR_DENIED;
  466. }
  467. }
  468. return 0;
  469. failed:
  470. return -PAL_ERROR_DENIED;
  471. }
  472. static int register_trusted_file (const char * uri, const char * checksum_str)
  473. {
  474. struct trusted_file * tf = NULL, * new;
  475. int uri_len = strlen(uri);
  476. int ret;
  477. _DkSpinLock(&trusted_file_lock);
  478. listp_for_each_entry(tf, &trusted_file_list, list) {
  479. if (tf->uri_len == uri_len && !memcmp(tf->uri, uri, uri_len)) {
  480. _DkSpinUnlock(&trusted_file_lock);
  481. return 0;
  482. }
  483. }
  484. _DkSpinUnlock(&trusted_file_lock);
  485. new = malloc(sizeof(struct trusted_file));
  486. if (!new)
  487. return -PAL_ERROR_NOMEM;
  488. INIT_LIST_HEAD(new, list);
  489. new->uri_len = uri_len;
  490. memcpy(new->uri, uri, uri_len + 1);
  491. new->size = 0;
  492. new->stubs = NULL;
  493. if (checksum_str) {
  494. PAL_STREAM_ATTR attr;
  495. ret = _DkStreamAttributesQuery(uri, &attr);
  496. if (!ret)
  497. new->size = attr.pending_size;
  498. char checksum_text[sizeof(sgx_checksum_t) * 2 + 1] = "\0";
  499. int nbytes = 0;
  500. for (; nbytes < sizeof(sgx_checksum_t) ; nbytes++) {
  501. char byte1 = checksum_str[nbytes * 2];
  502. char byte2 = checksum_str[nbytes * 2 + 1];
  503. unsigned char val = 0;
  504. if (byte1 == 0 || byte2 == 0) {
  505. break;
  506. }
  507. if (!(byte1 >= '0' && byte1 <= '9') &&
  508. !(byte1 >= 'a' && byte1 <= 'f')) {
  509. break;
  510. }
  511. if (!(byte2 >= '0' && byte2 <= '9') &&
  512. !(byte2 >= 'a' && byte2 <= 'f')) {
  513. break;
  514. }
  515. if (byte1 >= '0' && byte1 <= '9')
  516. val = byte1 - '0';
  517. if (byte1 >= 'a' && byte1 <= 'f')
  518. val = byte1 - 'a' + 10;
  519. val *= 16;
  520. if (byte2 >= '0' && byte2 <= '9')
  521. val += byte2 - '0';
  522. if (byte2 >= 'a' && byte2 <= 'f')
  523. val += byte2 - 'a' + 10;
  524. new->checksum.bytes[nbytes] = val;
  525. snprintf(checksum_text + nbytes * 2, 3, "%02x", val);
  526. }
  527. if (nbytes < sizeof(sgx_checksum_t)) {
  528. free(new);
  529. return -PAL_ERROR_INVAL;
  530. }
  531. new->index = (++trusted_file_indexes);
  532. SGX_DBG(DBG_S, "trusted: [%ld] %s %s\n", new->index,
  533. checksum_text, new->uri);
  534. } else {
  535. memset(&new->checksum, 0, sizeof(sgx_checksum_t));
  536. new->index = 0;
  537. SGX_DBG(DBG_S, "allowed: %s\n", new->uri);
  538. }
  539. _DkSpinLock(&trusted_file_lock);
  540. listp_for_each_entry(tf, &trusted_file_list, list) {
  541. if (tf->uri_len == uri_len && !memcmp(tf->uri, uri, uri_len)) {
  542. _DkSpinUnlock(&trusted_file_lock);
  543. free(new);
  544. return 0;
  545. }
  546. }
  547. listp_add_tail(new, &trusted_file_list, list);
  548. _DkSpinUnlock(&trusted_file_lock);
  549. return 0;
  550. }
  551. static int init_trusted_file (const char * key, const char * uri)
  552. {
  553. char cskey[URI_MAX], * tmp;
  554. char checksum[URI_MAX];
  555. char normpath[URI_MAX];
  556. tmp = strcpy_static(cskey, "sgx.trusted_checksum.", URI_MAX);
  557. memcpy(tmp, key, strlen(key) + 1);
  558. ssize_t len = get_config(pal_state.root_config, cskey, checksum, CONFIG_MAX);
  559. if (len < 0)
  560. return 0;
  561. /* Normalize the uri */
  562. if (!strpartcmp_static(uri, "file:")) {
  563. SGX_DBG(DBG_E, "Invalid URI [%s]: Trusted files must start with 'file:'\n", uri);
  564. return -PAL_ERROR_INVAL;
  565. }
  566. normpath [0] = 'f';
  567. normpath [1] = 'i';
  568. normpath [2] = 'l';
  569. normpath [3] = 'e';
  570. normpath [4] = ':';
  571. len = get_norm_path(uri + 5, normpath + 5, 0, URI_MAX);
  572. return register_trusted_file(normpath, checksum);
  573. }
  574. int init_trusted_files (void)
  575. {
  576. struct config_store * store = pal_state.root_config;
  577. char * cfgbuf = NULL;
  578. ssize_t cfgsize;
  579. int nuris, ret;
  580. if (pal_sec.exec_name[0] != '\0') {
  581. ret = init_trusted_file("exec", pal_sec.exec_name);
  582. if (ret < 0)
  583. goto out;
  584. }
  585. cfgbuf = malloc(CONFIG_MAX);
  586. if (!cfgbuf) {
  587. ret = -PAL_ERROR_NOMEM;
  588. goto out;
  589. }
  590. ssize_t len = get_config(store, "loader.preload", cfgbuf, CONFIG_MAX);
  591. if (len > 0) {
  592. int npreload = 0;
  593. char key[10];
  594. const char * start, * end;
  595. for (start = cfgbuf ; start < cfgbuf + len ; start = end + 1) {
  596. for (end = start ; end < cfgbuf + len && *end && *end != ',' ; end++);
  597. if (end > start) {
  598. char uri[end - start + 1];
  599. memcpy(uri, start, end - start);
  600. uri[end - start] = 0;
  601. snprintf(key, 10, "preload%d", npreload++);
  602. ret = init_trusted_file(key, uri);
  603. if (ret < 0)
  604. goto out;
  605. }
  606. }
  607. }
  608. cfgsize = get_config_entries_size(store, "sgx.trusted_files");
  609. if (cfgsize <= 0)
  610. goto no_trusted;
  611. free(cfgbuf);
  612. cfgbuf = malloc(cfgsize);
  613. if (!cfgbuf) {
  614. ret = -PAL_ERROR_NOMEM;
  615. goto out;
  616. }
  617. nuris = get_config_entries(store, "sgx.trusted_files", cfgbuf, cfgsize);
  618. if (nuris <= 0)
  619. goto no_trusted;
  620. {
  621. char key[CONFIG_MAX], uri[CONFIG_MAX];
  622. char * k = cfgbuf, * tmp;
  623. tmp = strcpy_static(key, "sgx.trusted_files.", CONFIG_MAX);
  624. for (int i = 0 ; i < nuris ; i++) {
  625. len = strlen(k);
  626. memcpy(tmp, k, len + 1);
  627. k += len + 1;
  628. len = get_config(store, key, uri, CONFIG_MAX);
  629. if (len > 0) {
  630. ret = init_trusted_file(key + 18, uri);
  631. if (ret < 0)
  632. goto out;
  633. }
  634. }
  635. }
  636. no_trusted:
  637. cfgsize = get_config_entries_size(store, "sgx.allowed_files");
  638. if (cfgsize <= 0)
  639. goto no_allowed;
  640. free(cfgbuf);
  641. cfgbuf = malloc(cfgsize);
  642. if (!cfgbuf) {
  643. ret = -PAL_ERROR_NOMEM;
  644. goto out;
  645. }
  646. nuris = get_config_entries(store, "sgx.allowed_files", cfgbuf, cfgsize);
  647. if (nuris <= 0)
  648. goto no_allowed;
  649. {
  650. char key[CONFIG_MAX], uri[CONFIG_MAX];
  651. char * k = cfgbuf, * tmp;
  652. tmp = strcpy_static(key, "sgx.allowed_files.", CONFIG_MAX);
  653. for (int i = 0 ; i < nuris ; i++) {
  654. len = strlen(k);
  655. memcpy(tmp, k, len + 1);
  656. k += len + 1;
  657. len = get_config(store, key, uri, CONFIG_MAX);
  658. if (len > 0)
  659. register_trusted_file(uri, NULL);
  660. }
  661. }
  662. no_allowed:
  663. ret = 0;
  664. if (get_config(store, "sgx.allow_file_creation", cfgbuf, CONFIG_MAX) <= 0) {
  665. allow_file_creation = false;
  666. } else
  667. allow_file_creation = true;
  668. out:
  669. free(cfgbuf);
  670. return ret;
  671. }
  672. int init_trusted_children (void)
  673. {
  674. struct config_store * store = pal_state.root_config;
  675. char key[CONFIG_MAX], mrkey[CONFIG_MAX];
  676. char uri[CONFIG_MAX], mrenclave[CONFIG_MAX];
  677. char * tmp1 = strcpy_static(key, "sgx.trusted_children.", CONFIG_MAX);
  678. char * tmp2 = strcpy_static(mrkey, "sgx.trusted_mrenclave.", CONFIG_MAX);
  679. ssize_t cfgsize = get_config_entries_size(store, "sgx.trusted_mrenclave");
  680. if (cfgsize <= 0)
  681. return 0;
  682. char * cfgbuf = malloc(cfgsize);
  683. if (!cfgbuf)
  684. return -PAL_ERROR_NOMEM;
  685. int nuris = get_config_entries(store, "sgx.trusted_mrenclave",
  686. cfgbuf, cfgsize);
  687. if (nuris > 0) {
  688. char * k = cfgbuf;
  689. for (int i = 0 ; i < nuris ; i++) {
  690. int len = strlen(k);
  691. memcpy(tmp1, k, len + 1);
  692. memcpy(tmp2, k, len + 1);
  693. k += len + 1;
  694. ssize_t ret = get_config(store, key, uri, CONFIG_MAX);
  695. if (ret < 0)
  696. continue;
  697. ret = get_config(store, mrkey, mrenclave, CONFIG_MAX);
  698. if (ret > 0)
  699. register_trusted_child(uri, mrenclave);
  700. }
  701. }
  702. free(cfgbuf);
  703. return 0;
  704. }
  705. #if 0
  706. void test_dh (void)
  707. {
  708. int ret;
  709. DhKey key1, key2;
  710. uint32_t privsz1, privsz2, pubsz1, pubsz2, agreesz1, agreesz2;
  711. unsigned char priv1[128], pub1[128], priv2[128], pub2[128], agree1[128],
  712. agree2[128], scratch[257];
  713. InitDhKey(&key1);
  714. InitDhKey(&key2);
  715. ret = DhSetKey(&key1, dh_param.p, sizeof(dh_param.p), dh_param.g,
  716. sizeof(dh_param.g));
  717. if (ret < 0) {
  718. SGX_DBG(DBG_S, "DhSetKey for key 1 failed: %d\n", ret);
  719. return;
  720. }
  721. ret = DhSetKey(&key2, dh_param.p, sizeof(dh_param.p), dh_param.g,
  722. sizeof(dh_param.g));
  723. if (ret < 0) {
  724. SGX_DBG(DBG_S, "DhSetKey for key 2 failed: %d\n", ret);
  725. return;
  726. }
  727. ret = DhGenerateKeyPair(&key1, priv1, &privsz1, pub1, &pubsz1);
  728. if (ret < 0) {
  729. SGX_DBG(DBG_S, "DhGenerateKeyPair for key 1 failed: %d\n", ret);
  730. return;
  731. }
  732. ret = DhGenerateKeyPair(&key2, priv2, &privsz2, pub2, &pubsz2);
  733. if (ret < 0) {
  734. SGX_DBG(DBG_S, "DhGenerateKeyPair for key 2 failed: %d\n", ret);
  735. return;
  736. }
  737. ret = DhAgree(&key1, agree1, &agreesz1, priv1, privsz1, pub2, pubsz2);
  738. if (ret < 0) {
  739. SGX_DBG(DBG_S, "DhAgree for key 1 failed: %d\n", ret);
  740. return;
  741. }
  742. ret = DhAgree(&key2, agree2, &agreesz2, priv2, privsz2, pub1, pubsz1);
  743. if (ret < 0) {
  744. SGX_DBG(DBG_S, "DhAgree for key 1 failed: %d\n", ret);
  745. return;
  746. }
  747. FreeDhKey(&key1);
  748. FreeDhKey(&key2);
  749. SGX_DBG(DBG_S, "key exchange(side A): %s\n",
  750. __bytes2hexstr(agree1, agreesz1, scratch, agreesz1 * 2 + 1));
  751. SGX_DBG(DBG_S, "key exchange(side B): %s\n",
  752. __bytes2hexstr(agree2, agreesz2, scratch, agreesz2 * 2 + 1));
  753. }
  754. #endif
  755. #define RSA_KEY_SIZE 2048
  756. #define RSA_E 3
  757. int init_enclave (void)
  758. {
  759. // Get report to initialize info (MRENCLAVE, etc.) about this enclave from
  760. // a trusted source.
  761. // Since this report is only read by ourselves we can
  762. // leave targetinfo zeroed.
  763. sgx_arch_targetinfo_t targetinfo = {0};
  764. struct pal_enclave_state reportdata = {0};
  765. sgx_arch_report_t report;
  766. int ret = sgx_report(&targetinfo, &reportdata, &report);
  767. if (ret) {
  768. SGX_DBG(DBG_E, "failed to get self report: %d\n", ret);
  769. return -PAL_ERROR_INVAL;
  770. }
  771. memcpy(pal_sec.mrenclave, report.mrenclave, sizeof(pal_sec.mrenclave));
  772. memcpy(pal_sec.mrsigner, report.mrsigner, sizeof(pal_sec.mrsigner));
  773. pal_sec.enclave_attributes = report.attributes;
  774. #if 0
  775. /*
  776. * This enclave-specific key is a building block for authenticating
  777. * new pipe connections with other enclaves that are already
  778. * authenticated. Since pipe protection is a future feature, this key
  779. * is currently unused and hence deprecated.
  780. */
  781. int ret;
  782. LIB_RSA_KEY *rsa = malloc(sizeof(LIB_RSA_KEY));
  783. lib_RSAInitKey(rsa);
  784. ret = lib_RSAGenerateKey(rsa, RSA_KEY_SIZE, RSA_E);
  785. if (ret < 0) {
  786. SGX_DBG(DBG_S, "lib_RSAGenerateKey failed: %d\n", ret);
  787. return ret;
  788. }
  789. pal_enclave_config.enclave_key = rsa;
  790. #endif
  791. /*
  792. * The enclave identifier is uniquely created for each enclave as a token
  793. * for authenticating the enclave as the sender of attestation.
  794. * TODO: documenting the inter-enclave attestation protocol.
  795. */
  796. _DkRandomBitsRead(&pal_enclave_state.enclave_identifier,
  797. sizeof(pal_enclave_state.enclave_identifier));
  798. SGX_DBG(DBG_S, "enclave (software) key hash: %s\n",
  799. ALLOCA_BYTES2HEXSTR(pal_enclave_state.enclave_identifier));
  800. return 0;
  801. }
  802. int _DkStreamKeyExchange (PAL_HANDLE stream, PAL_SESSION_KEY * keyptr)
  803. {
  804. uint8_t session_key[sizeof(PAL_SESSION_KEY)]
  805. __attribute__((aligned(sizeof(PAL_SESSION_KEY))));
  806. uint8_t pub[DH_SIZE] __attribute__((aligned(DH_SIZE)));
  807. uint8_t agree[DH_SIZE] __attribute__((aligned(DH_SIZE)));
  808. PAL_NUM pubsz, agreesz;
  809. LIB_DH_CONTEXT context;
  810. int ret;
  811. ret = lib_DhInit(&context);
  812. if (ret < 0) {
  813. SGX_DBG(DBG_S, "Key Exchange: DH Init failed: %d\n", ret);
  814. goto out_no_final;
  815. }
  816. pubsz = sizeof pub;
  817. ret = lib_DhCreatePublic(&context, pub, &pubsz);
  818. if (ret < 0) {
  819. SGX_DBG(DBG_S, "Key Exchange: DH CreatePublic failed: %d\n", ret);
  820. goto out;
  821. }
  822. assert(pubsz > 0 && pubsz <= DH_SIZE);
  823. if (pubsz < DH_SIZE) {
  824. /* Insert leading zero bytes if necessary. These values are big-
  825. * endian, so we either need to know the length of the bignum or
  826. * zero-pad at the beginning instead of the end. This code chooses
  827. * to do the latter. */
  828. memmove(pub + (DH_SIZE - pubsz), pub, pubsz);
  829. memset(pub, 0, DH_SIZE - pubsz);
  830. }
  831. ret = _DkStreamWrite(stream, 0, DH_SIZE, pub, NULL, 0);
  832. if (ret != DH_SIZE) {
  833. SGX_DBG(DBG_S, "Key Exchange: DkStreamWrite failed: %d\n", ret);
  834. goto out;
  835. }
  836. ret = _DkStreamRead(stream, 0, DH_SIZE, pub, NULL, 0);
  837. if (ret != DH_SIZE) {
  838. SGX_DBG(DBG_S, "Key Exchange: DkStreamRead failed: %d\n", ret);
  839. goto out;
  840. }
  841. agreesz = sizeof agree;
  842. ret = lib_DhCalcSecret(&context, pub, DH_SIZE, agree, &agreesz);
  843. if (ret < 0) {
  844. SGX_DBG(DBG_S, "Key Exchange: DH CalcSecret failed: %d\n", ret);
  845. goto out;
  846. }
  847. assert(agreesz > 0 && agreesz <= sizeof agree);
  848. // TODO(security): use a real KDF
  849. memset(session_key, 0, sizeof(session_key));
  850. for (int i = 0 ; i < agreesz ; i++)
  851. session_key[i % sizeof(session_key)] ^= agree[i];
  852. SGX_DBG(DBG_S, "key exchange: (%p) %s\n", session_key,
  853. ALLOCA_BYTES2HEXSTR(session_key));
  854. if (keyptr)
  855. memcpy(keyptr, session_key, sizeof(PAL_SESSION_KEY));
  856. ret = 0;
  857. out:
  858. lib_DhFinal(&context);
  859. out_no_final:
  860. return ret;
  861. }
  862. struct attestation_request {
  863. sgx_arch_hash_t mrenclave;
  864. sgx_arch_attributes_t attributes;
  865. };
  866. struct attestation {
  867. sgx_arch_hash_t mrenclave;
  868. sgx_arch_attributes_t attributes;
  869. sgx_arch_report_t report;
  870. };
  871. int _DkStreamAttestationRequest (PAL_HANDLE stream, void * data,
  872. int (*check_mrenclave) (sgx_arch_hash_t *,
  873. void *, void *),
  874. void * check_param)
  875. {
  876. struct attestation_request req;
  877. struct attestation att;
  878. int bytes, ret;
  879. memcpy(req.mrenclave, pal_sec.mrenclave, sizeof(sgx_arch_hash_t));
  880. memcpy(&req.attributes, &pal_sec.enclave_attributes,
  881. sizeof(sgx_arch_attributes_t));
  882. SGX_DBG(DBG_S, "Sending attestation request ... (mrenclave = %s)\n",\
  883. ALLOCA_BYTES2HEXSTR(req.mrenclave));
  884. for (bytes = 0, ret = 0 ; bytes < sizeof(req) ; bytes += ret) {
  885. ret = _DkStreamWrite(stream, 0, sizeof(req) - bytes,
  886. ((void *) &req) + bytes, NULL, 0);
  887. if (ret < 0) {
  888. SGX_DBG(DBG_S, "Attestation Request: DkStreamWrite failed: %d\n", ret);
  889. goto out;
  890. }
  891. }
  892. for (bytes = 0, ret = 0 ; bytes < sizeof(att) ; bytes += ret) {
  893. ret = _DkStreamRead(stream, 0, sizeof(att) - bytes,
  894. ((void *) &att) + bytes, NULL, 0);
  895. if (ret < 0) {
  896. SGX_DBG(DBG_S, "Attestation Request: DkStreamRead failed: %d\n", ret);
  897. goto out;
  898. }
  899. }
  900. SGX_DBG(DBG_S, "Received attestation (mrenclave = %s)\n",
  901. ALLOCA_BYTES2HEXSTR(att.mrenclave));
  902. ret = sgx_verify_report(&att.report);
  903. if (ret < 0) {
  904. SGX_DBG(DBG_S, "Attestation Request: sgx_verify_report failed: %d\n", ret);
  905. goto out;
  906. }
  907. if (ret == 1) {
  908. SGX_DBG(DBG_S, "Remote attestation not signed by SGX!\n");
  909. ret = -PAL_ERROR_DENIED;
  910. goto out;
  911. }
  912. ret = check_mrenclave(&att.report.mrenclave, &att.report.report_data,
  913. check_param);
  914. if (ret < 0) {
  915. SGX_DBG(DBG_S, "Attestation Request: check_mrenclave failed: %d\n", ret);
  916. goto out;
  917. }
  918. if (ret == 1) {
  919. SGX_DBG(DBG_S, "Not an allowed enclave (mrenclave = %s)\n",
  920. ALLOCA_BYTES2HEXSTR(att.mrenclave));
  921. ret = -PAL_ERROR_DENIED;
  922. goto out;
  923. }
  924. SGX_DBG(DBG_S, "Remote attestation succeed!\n");
  925. ret = sgx_get_report(&att.mrenclave, &att.attributes, data, &att.report);
  926. if (ret < 0) {
  927. SGX_DBG(DBG_S, "Attestation Request: sgx_get_report failed: %d\n", ret);
  928. goto out;
  929. }
  930. memcpy(att.mrenclave, pal_sec.mrenclave, sizeof(sgx_arch_hash_t));
  931. memcpy(&att.attributes, &pal_sec.enclave_attributes,
  932. sizeof(sgx_arch_attributes_t));
  933. SGX_DBG(DBG_S, "Sending attestation ... (mrenclave = %s)\n",
  934. ALLOCA_BYTES2HEXSTR(att.mrenclave));
  935. for (bytes = 0, ret = 0 ; bytes < sizeof(att) ; bytes += ret) {
  936. ret = _DkStreamWrite(stream, 0, sizeof(att) - bytes,
  937. ((void *) &att) + bytes, NULL, 0);
  938. if (ret < 0) {
  939. SGX_DBG(DBG_S, "Attestation Request: DkStreamWrite failed: %d\n", ret);
  940. goto out;
  941. }
  942. }
  943. return 0;
  944. out:
  945. DkStreamDelete(stream, 0);
  946. return ret;
  947. }
  948. int _DkStreamAttestationRespond (PAL_HANDLE stream, void * data,
  949. int (*check_mrenclave) (sgx_arch_hash_t *,
  950. void *, void *),
  951. void * check_param)
  952. {
  953. struct attestation_request req;
  954. struct attestation att;
  955. int bytes, ret;
  956. for (bytes = 0, ret = 0 ; bytes < sizeof(req) ; bytes += ret) {
  957. ret = _DkStreamRead(stream, 0, sizeof(req) - bytes,
  958. ((void *) &req) + bytes, NULL, 0);
  959. if (ret < 0) {
  960. SGX_DBG(DBG_S, "Attestation Respond: DkStreamRead failed: %d\n", ret);
  961. goto out;
  962. }
  963. }
  964. SGX_DBG(DBG_S, "Received attestation request ... (mrenclave = %s)\n",
  965. ALLOCA_BYTES2HEXSTR(req.mrenclave));
  966. ret = sgx_get_report(&req.mrenclave, &req.attributes, data, &att.report);
  967. if (ret < 0) {
  968. SGX_DBG(DBG_S, "Attestation Respond: sgx_get_report failed: %d\n", ret);
  969. goto out;
  970. }
  971. memcpy(att.mrenclave, pal_sec.mrenclave, sizeof(sgx_arch_hash_t));
  972. memcpy(&att.attributes, &pal_sec.enclave_attributes,
  973. sizeof(sgx_arch_attributes_t));
  974. SGX_DBG(DBG_S, "Sending attestation ... (mrenclave = %s)\n",
  975. ALLOCA_BYTES2HEXSTR(att.mrenclave));
  976. for (bytes = 0, ret = 0 ; bytes < sizeof(att) ; bytes += ret) {
  977. ret = _DkStreamWrite(stream, 0, sizeof(att) - bytes,
  978. ((void *) &att) + bytes, NULL, 0);
  979. if (ret < 0) {
  980. SGX_DBG(DBG_S, "Attestation Respond: DkStreamWrite failed: %d\n", ret);
  981. goto out;
  982. }
  983. }
  984. for (bytes = 0, ret = 0 ; bytes < sizeof(att) ; bytes += ret) {
  985. ret = _DkStreamRead(stream, 0, sizeof(att) - bytes,
  986. ((void *) &att) + bytes, NULL, 0);
  987. if (ret < 0) {
  988. SGX_DBG(DBG_S, "Attestation Respond: DkStreamRead failed: %d\n", ret);
  989. goto out;
  990. }
  991. }
  992. SGX_DBG(DBG_S, "Received attestation (mrenclave = %s)\n",
  993. ALLOCA_BYTES2HEXSTR(att.mrenclave));
  994. ret = sgx_verify_report(&att.report);
  995. if (ret < 0) {
  996. SGX_DBG(DBG_S, "Attestation Respond: sgx_verify_report failed: %d\n", ret);
  997. goto out;
  998. }
  999. if (ret == 1) {
  1000. SGX_DBG(DBG_S, "Remote attestation not signed by SGX!\n");
  1001. goto out;
  1002. }
  1003. ret = check_mrenclave(&att.report.mrenclave, &att.report.report_data,
  1004. check_param);
  1005. if (ret < 0) {
  1006. SGX_DBG(DBG_S, "Attestation Request: check_mrenclave failed: %d\n", ret);
  1007. goto out;
  1008. }
  1009. if (ret == 1) {
  1010. SGX_DBG(DBG_S, "Not an allowed enclave (mrenclave = %s)\n",
  1011. ALLOCA_BYTES2HEXSTR(att.mrenclave));
  1012. ret = -PAL_ERROR_DENIED;
  1013. goto out;
  1014. }
  1015. SGX_DBG(DBG_S, "Remote attestation succeeded!\n");
  1016. return 0;
  1017. out:
  1018. DkStreamDelete(stream, 0);
  1019. return ret;
  1020. }
  1021. /*
  1022. * Restore an sgx_context_t as generated by .Lhandle_exception. Execution will
  1023. * continue as specified by the rip in the context.
  1024. *
  1025. * It is required that:
  1026. *
  1027. * ctx == ctx->rsp - (sizeof(sgx_context_t) + RED_ZONE_SIZE)
  1028. *
  1029. * This means that the ctx is allocated directly below the "normal" stack
  1030. * (honoring its red zone). This is needed to properly restore the old state
  1031. * (see _restore_sgx_context for details).
  1032. *
  1033. * For the original sgx_context_t allocated by .Lhandle_exception this is true.
  1034. * This is a safe wrapper around _restore_sgx_context, which checks this
  1035. * preconditon.
  1036. */
  1037. void restore_sgx_context(sgx_context_t *ctx) {
  1038. if (((uint64_t) ctx) != ctx->rsp - (sizeof(sgx_context_t) + RED_ZONE_SIZE)) {
  1039. SGX_DBG(DBG_E, "Invalid sgx_context_t pointer passed to restore_sgx_context!\n");
  1040. ocall_exit(1);
  1041. }
  1042. _restore_sgx_context(ctx);
  1043. }