sgx_main.c 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125
  1. #include <pal_linux.h>
  2. #include <pal_linux_error.h>
  3. #include <pal_rtld.h>
  4. #include <hex.h>
  5. #include "sgx_internal.h"
  6. #include "sgx_tls.h"
  7. #include "sgx_enclave.h"
  8. #include "debugger/sgx_gdb.h"
  9. #include <asm/fcntl.h>
  10. #include <asm/socket.h>
  11. #include <linux/fs.h>
  12. #include <linux/in.h>
  13. #include <linux/in6.h>
  14. #include <asm/errno.h>
  15. #include <ctype.h>
  16. #include <sysdep.h>
  17. #include <sysdeps/generic/ldsodefs.h>
  18. unsigned long pagesize = PRESET_PAGESIZE;
  19. unsigned long pagemask = ~(PRESET_PAGESIZE - 1);
  20. unsigned long pageshift = PRESET_PAGESIZE - 1;
  21. struct pal_enclave pal_enclave;
  22. static inline
  23. char * alloc_concat(const char * p, size_t plen,
  24. const char * s, size_t slen)
  25. {
  26. plen = (plen != (size_t)-1) ? plen : (p ? strlen(p) : 0);
  27. slen = (slen != (size_t)-1) ? slen : (s ? strlen(s) : 0);
  28. char * buf = malloc(plen + slen + 1);
  29. if (!buf)
  30. return NULL;
  31. if (plen)
  32. memcpy(buf, p, plen);
  33. if (slen)
  34. memcpy(buf + plen, s, slen);
  35. buf[plen + slen] = '\0';
  36. return buf;
  37. }
  38. static unsigned long parse_int (const char * str)
  39. {
  40. unsigned long num = 0;
  41. int radix = 10;
  42. char c;
  43. if (str[0] == '0') {
  44. str++;
  45. radix = 8;
  46. if (str[0] == 'x') {
  47. str++;
  48. radix = 16;
  49. }
  50. }
  51. while ((c = *(str++))) {
  52. int8_t val = hex2dec(c);
  53. if (val < 0)
  54. break;
  55. if ((uint8_t) val >= radix)
  56. break;
  57. num = num * radix + (uint8_t) val;
  58. }
  59. if (c == 'G' || c == 'g')
  60. num *= 1024 * 1024 * 1024;
  61. else if (c == 'M' || c == 'm')
  62. num *= 1024 * 1024;
  63. else if (c == 'K' || c == 'k')
  64. num *= 1024;
  65. return num;
  66. }
  67. static char * resolve_uri (const char * uri, const char ** errstring)
  68. {
  69. if (!strstartswith_static(uri, "file:")) {
  70. *errstring = "Invalid URI";
  71. return NULL;
  72. }
  73. char path_buf[URI_MAX];
  74. size_t len = URI_MAX;
  75. int ret = get_norm_path(uri + 5, path_buf, &len);
  76. if (ret < 0) {
  77. *errstring = "Invalid URI";
  78. return NULL;
  79. }
  80. return alloc_concat("file:", static_strlen("file:"), path_buf, len);
  81. }
  82. static
  83. int scan_enclave_binary (int fd, unsigned long * base, unsigned long * size,
  84. unsigned long * entry)
  85. {
  86. int ret = 0;
  87. if (IS_ERR(ret = INLINE_SYSCALL(lseek, 3, fd, 0, SEEK_SET)))
  88. return -ERRNO(ret);
  89. char filebuf[FILEBUF_SIZE];
  90. ret = INLINE_SYSCALL(read, 3, fd, filebuf, FILEBUF_SIZE);
  91. if (IS_ERR(ret))
  92. return -ERRNO(ret);
  93. const ElfW(Ehdr) * header = (void *) filebuf;
  94. const ElfW(Phdr) * phdr = (void *) filebuf + header->e_phoff;
  95. const ElfW(Phdr) * ph;
  96. struct loadcmd {
  97. ElfW(Addr) mapstart, mapend;
  98. } loadcmds[16], *c;
  99. int nloadcmds = 0;
  100. for (ph = phdr ; ph < &phdr[header->e_phnum] ; ph++)
  101. if (ph->p_type == PT_LOAD) {
  102. if (nloadcmds == 16)
  103. return -EINVAL;
  104. c = &loadcmds[nloadcmds++];
  105. c->mapstart = ALLOC_ALIGNDOWN(ph->p_vaddr);
  106. c->mapend = ALLOC_ALIGNUP(ph->p_vaddr + ph->p_memsz);
  107. }
  108. *base = loadcmds[0].mapstart;
  109. *size = loadcmds[nloadcmds - 1].mapend - loadcmds[0].mapstart;
  110. if (entry)
  111. *entry = header->e_entry;
  112. return 0;
  113. }
  114. static
  115. int load_enclave_binary (sgx_arch_secs_t * secs, int fd,
  116. unsigned long base, unsigned long prot)
  117. {
  118. int ret = 0;
  119. if (IS_ERR(ret = INLINE_SYSCALL(lseek, 3, fd, 0, SEEK_SET)))
  120. return -ERRNO(ret);
  121. char filebuf[FILEBUF_SIZE];
  122. ret = INLINE_SYSCALL(read, 3, fd, filebuf, FILEBUF_SIZE);
  123. if (IS_ERR(ret))
  124. return -ERRNO(ret);
  125. const ElfW(Ehdr) * header = (void *) filebuf;
  126. const ElfW(Phdr) * phdr = (void *) filebuf + header->e_phoff;
  127. const ElfW(Phdr) * ph;
  128. struct loadcmd {
  129. ElfW(Addr) mapstart, mapend, datastart, dataend, allocend;
  130. unsigned int mapoff;
  131. int prot;
  132. } loadcmds[16], *c;
  133. int nloadcmds = 0;
  134. for (ph = phdr ; ph < &phdr[header->e_phnum] ; ph++)
  135. if (ph->p_type == PT_LOAD) {
  136. if (nloadcmds == 16)
  137. return -EINVAL;
  138. c = &loadcmds[nloadcmds++];
  139. c->mapstart = ALLOC_ALIGNDOWN(ph->p_vaddr);
  140. c->mapend = ALLOC_ALIGNUP(ph->p_vaddr + ph->p_filesz);
  141. c->datastart = ph->p_vaddr;
  142. c->dataend = ph->p_vaddr + ph->p_filesz;
  143. c->allocend = ph->p_vaddr + ph->p_memsz;
  144. c->mapoff = ALLOC_ALIGNDOWN(ph->p_offset);
  145. c->prot = (ph->p_flags & PF_R ? PROT_READ : 0)|
  146. (ph->p_flags & PF_W ? PROT_WRITE : 0)|
  147. (ph->p_flags & PF_X ? PROT_EXEC : 0)|prot;
  148. }
  149. base -= loadcmds[0].mapstart;
  150. for (c = loadcmds; c < &loadcmds[nloadcmds] ; c++) {
  151. ElfW(Addr) zero = c->dataend;
  152. ElfW(Addr) zeroend = ALLOC_ALIGNUP(c->allocend);
  153. ElfW(Addr) zeropage = ALLOC_ALIGNUP(zero);
  154. if (zeroend < zeropage)
  155. zeropage = zeroend;
  156. if (c->mapend > c->mapstart) {
  157. void * addr = (void *) INLINE_SYSCALL(mmap, 6, NULL,
  158. c->mapend - c->mapstart,
  159. PROT_READ|PROT_WRITE,
  160. MAP_PRIVATE | MAP_FILE,
  161. fd, c->mapoff);
  162. if (IS_ERR_P(addr))
  163. return -ERRNO_P(addr);
  164. if (c->datastart > c->mapstart)
  165. memset(addr, 0, c->datastart - c->mapstart);
  166. if (zeropage > zero)
  167. memset(addr + zero - c->mapstart, 0, zeropage - zero);
  168. ret = add_pages_to_enclave(secs, (void *) base + c->mapstart, addr,
  169. c->mapend - c->mapstart,
  170. SGX_PAGE_REG, c->prot, 0,
  171. (c->prot & PROT_EXEC) ? "code" : "data");
  172. INLINE_SYSCALL(munmap, 2, addr, c->mapend - c->mapstart);
  173. if (ret < 0)
  174. return ret;
  175. }
  176. if (zeroend > zeropage) {
  177. ret = add_pages_to_enclave(secs, (void *) base + zeropage, NULL,
  178. zeroend - zeropage,
  179. SGX_PAGE_REG, c->prot, false, "bss");
  180. if (ret < 0)
  181. return ret;
  182. }
  183. }
  184. return 0;
  185. }
  186. int initialize_enclave (struct pal_enclave * enclave)
  187. {
  188. int ret = 0;
  189. int enclave_image;
  190. sgx_arch_token_t enclave_token;
  191. sgx_arch_enclave_css_t enclave_sigstruct;
  192. sgx_arch_secs_t enclave_secs;
  193. unsigned long enclave_entry_addr;
  194. unsigned long heap_min = DEFAULT_HEAP_MIN;
  195. /* this array may overflow the stack, so we allocate it in BSS */
  196. static void* tcs_addrs[MAX_DBG_THREADS];
  197. enclave_image = INLINE_SYSCALL(open, 3, ENCLAVE_FILENAME, O_RDONLY, 0);
  198. if (IS_ERR(enclave_image)) {
  199. SGX_DBG(DBG_E, "Cannot find %s\n", ENCLAVE_FILENAME);
  200. ret = -ERRNO(enclave_image);
  201. goto out;
  202. }
  203. char cfgbuf[CONFIG_MAX];
  204. /* Reading sgx.enclave_size from manifest */
  205. if (get_config(enclave->config, "sgx.enclave_size", cfgbuf, CONFIG_MAX) <= 0) {
  206. SGX_DBG(DBG_E, "Enclave size is not specified\n");
  207. ret = -EINVAL;
  208. goto out;
  209. }
  210. enclave->size = parse_int(cfgbuf);
  211. if (!enclave->size || !IS_POWER_OF_2(enclave->size)) {
  212. SGX_DBG(DBG_E, "Enclave size not a power of two (an SGX-imposed requirement)\n");
  213. ret = -EINVAL;
  214. goto out;
  215. }
  216. /* Reading sgx.thread_num from manifest */
  217. if (get_config(enclave->config, "sgx.thread_num", cfgbuf, CONFIG_MAX) > 0) {
  218. enclave->thread_num = parse_int(cfgbuf);
  219. if (enclave->thread_num > MAX_DBG_THREADS) {
  220. SGX_DBG(DBG_E, "Too many threads to debug\n");
  221. ret = -EINVAL;
  222. goto out;
  223. }
  224. } else {
  225. enclave->thread_num = 1;
  226. }
  227. /* Reading sgx.static_address from manifest */
  228. if (get_config(enclave->config, "sgx.static_address", cfgbuf, CONFIG_MAX) > 0 && cfgbuf[0] == '1')
  229. enclave->baseaddr = heap_min;
  230. else
  231. enclave->baseaddr = heap_min = 0;
  232. ret = read_enclave_token(enclave->token, &enclave_token);
  233. if (ret < 0) {
  234. SGX_DBG(DBG_E, "Reading enclave token failed: %d\n", -ret);
  235. goto out;
  236. }
  237. ret = read_enclave_sigstruct(enclave->sigfile, &enclave_sigstruct);
  238. if (ret < 0) {
  239. SGX_DBG(DBG_E, "Reading enclave sigstruct failed: %d\n", -ret);
  240. goto out;
  241. }
  242. ret = create_enclave(&enclave_secs, enclave->baseaddr, enclave->size, &enclave_token);
  243. if (ret < 0) {
  244. SGX_DBG(DBG_E, "Creating enclave failed: %d\n", -ret);
  245. goto out;
  246. }
  247. enclave->baseaddr = enclave_secs.base;
  248. enclave->size = enclave_secs.size;
  249. enclave->ssaframesize = enclave_secs.ssa_frame_size * pagesize;
  250. struct stat stat;
  251. ret = INLINE_SYSCALL(fstat, 2, enclave->manifest, &stat);
  252. if (IS_ERR(ret)) {
  253. SGX_DBG(DBG_E, "Reading manifest file's size failed: %d\n", -ret);
  254. ret = -ERRNO(ret);
  255. goto out;
  256. }
  257. int manifest_size = stat.st_size;
  258. /* Start populating enclave memory */
  259. struct mem_area {
  260. const char * desc;
  261. bool skip_eextend;
  262. int fd;
  263. bool is_binary; /* only meaningful if fd != -1 */
  264. unsigned long addr, size, prot;
  265. enum sgx_page_type type;
  266. };
  267. struct mem_area * areas =
  268. __alloca(sizeof(areas[0]) * (10 + enclave->thread_num));
  269. int area_num = 0;
  270. /* The manifest needs to be allocated at the upper end of the enclave
  271. * memory. That's used by pal_linux_main to find the manifest area. So add
  272. * it first to the list with memory areas. */
  273. areas[area_num] = (struct mem_area) {
  274. .desc = "manifest", .skip_eextend = false, .fd = enclave->manifest,
  275. .is_binary = false, .addr = 0, .size = ALLOC_ALIGNUP(manifest_size),
  276. .prot = PROT_READ, .type = SGX_PAGE_REG
  277. };
  278. area_num++;
  279. areas[area_num] = (struct mem_area) {
  280. .desc = "ssa", .skip_eextend = false, .fd = -1,
  281. .is_binary = false, .addr = 0,
  282. .size = enclave->thread_num * enclave->ssaframesize * SSAFRAMENUM,
  283. .prot = PROT_READ | PROT_WRITE, .type = SGX_PAGE_REG
  284. };
  285. struct mem_area* ssa_area = &areas[area_num++];
  286. areas[area_num] = (struct mem_area) {
  287. .desc = "tcs", .skip_eextend = false, .fd = -1,
  288. .is_binary = false, .addr = 0, .size = enclave->thread_num * pagesize,
  289. .prot = 0, .type = SGX_PAGE_TCS
  290. };
  291. struct mem_area* tcs_area = &areas[area_num++];
  292. areas[area_num] = (struct mem_area) {
  293. .desc = "tls", .skip_eextend = false, .fd = -1,
  294. .is_binary = false, .addr = 0, .size = enclave->thread_num * pagesize,
  295. .prot = PROT_READ | PROT_WRITE, .type = SGX_PAGE_REG
  296. };
  297. struct mem_area* tls_area = &areas[area_num++];
  298. struct mem_area* stack_areas = &areas[area_num]; /* memorize for later use */
  299. for (uint32_t t = 0; t < enclave->thread_num; t++) {
  300. areas[area_num] = (struct mem_area) {
  301. .desc = "stack", .skip_eextend = false, .fd = -1,
  302. .is_binary = false, .addr = 0, .size = ENCLAVE_STACK_SIZE,
  303. .prot = PROT_READ | PROT_WRITE, .type = SGX_PAGE_REG
  304. };
  305. area_num++;
  306. }
  307. areas[area_num] = (struct mem_area) {
  308. .desc = "pal", .skip_eextend = false, .fd = enclave_image,
  309. .is_binary = true, .addr = 0, .size = 0 /* set below */,
  310. .prot = 0, .type = SGX_PAGE_REG
  311. };
  312. struct mem_area* pal_area = &areas[area_num++];
  313. ret = scan_enclave_binary(enclave_image, &pal_area->addr, &pal_area->size, &enclave_entry_addr);
  314. if (ret < 0) {
  315. SGX_DBG(DBG_E, "Scanning Pal binary (%s) failed: %d\n", ENCLAVE_FILENAME, -ret);
  316. goto out;
  317. }
  318. struct mem_area* exec_area = NULL;
  319. if (enclave->exec != -1) {
  320. areas[area_num] = (struct mem_area) {
  321. .desc = "exec", .skip_eextend = false, .fd = enclave->exec,
  322. .is_binary = true, .addr = 0, .size = 0 /* set below */,
  323. .prot = PROT_WRITE, .type = SGX_PAGE_REG
  324. };
  325. exec_area = &areas[area_num++];
  326. ret = scan_enclave_binary(enclave->exec, &exec_area->addr, &exec_area->size, NULL);
  327. if (ret < 0) {
  328. SGX_DBG(DBG_E, "Scanning application binary failed: %d\n", -ret);
  329. goto out;
  330. }
  331. }
  332. unsigned long populating = enclave->size;
  333. for (int i = 0 ; i < area_num ; i++) {
  334. if (areas[i].addr)
  335. continue;
  336. areas[i].addr = populating - areas[i].size;
  337. populating = SATURATED_P_SUB(areas[i].addr, MEMORY_GAP, 0);
  338. }
  339. enclave_entry_addr += pal_area->addr;
  340. if (exec_area) {
  341. if (exec_area->addr + exec_area->size > pal_area->addr - MEMORY_GAP) {
  342. SGX_DBG(DBG_E, "Application binary overlaps with Pal binary\n");
  343. ret = -EINVAL;
  344. goto out;
  345. }
  346. if (exec_area->addr + exec_area->size + MEMORY_GAP < populating) {
  347. if (populating > heap_min) {
  348. unsigned long addr = exec_area->addr + exec_area->size + MEMORY_GAP;
  349. if (addr < heap_min)
  350. addr = heap_min;
  351. areas[area_num] = (struct mem_area) {
  352. .desc = "free", .skip_eextend = true, .fd = -1,
  353. .is_binary = false, .addr = addr, .size = populating - addr,
  354. .prot = PROT_READ | PROT_WRITE | PROT_EXEC, .type = SGX_PAGE_REG
  355. };
  356. area_num++;
  357. }
  358. populating = SATURATED_P_SUB(exec_area->addr, MEMORY_GAP, 0);
  359. }
  360. }
  361. if (populating > heap_min) {
  362. areas[area_num] = (struct mem_area) {
  363. .desc = "free", .skip_eextend = true, .fd = -1,
  364. .is_binary = false, .addr = heap_min, .size = populating - heap_min,
  365. .prot = PROT_READ | PROT_WRITE | PROT_EXEC, .type = SGX_PAGE_REG
  366. };
  367. area_num++;
  368. }
  369. for (int i = 0 ; i < area_num ; i++) {
  370. if (areas[i].fd != -1 && areas[i].is_binary) {
  371. ret = load_enclave_binary(&enclave_secs, areas[i].fd, areas[i].addr, areas[i].prot);
  372. if (ret < 0) {
  373. SGX_DBG(DBG_E, "Loading enclave binary failed: %d\n", -ret);
  374. goto out;
  375. }
  376. continue;
  377. }
  378. void * data = NULL;
  379. if (!strcmp_static(areas[i].desc, "tls")) {
  380. data = (void *) INLINE_SYSCALL(mmap, 6, NULL, areas[i].size,
  381. PROT_READ|PROT_WRITE,
  382. MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
  383. if (IS_ERR_P(data) || data == NULL) {
  384. /* Note that Graphene currently doesn't handle 0x0 addresses */
  385. SGX_DBG(DBG_E, "Allocating memory for tls pages failed\n");
  386. goto out;
  387. }
  388. for (uint32_t t = 0 ; t < enclave->thread_num ; t++) {
  389. struct enclave_tls * gs = data + pagesize * t;
  390. memset(gs, 0, pagesize);
  391. assert(sizeof(*gs) <= pagesize);
  392. gs->common.self = (PAL_TCB *)(
  393. tls_area->addr + pagesize * t + enclave_secs.base);
  394. gs->enclave_size = enclave->size;
  395. gs->tcs_offset = tcs_area->addr + pagesize * t;
  396. gs->initial_stack_offset =
  397. stack_areas[t].addr + ENCLAVE_STACK_SIZE;
  398. gs->ssa = (void *) ssa_area->addr +
  399. enclave->ssaframesize * SSAFRAMENUM * t +
  400. enclave_secs.base;
  401. gs->gpr = gs->ssa +
  402. enclave->ssaframesize - sizeof(sgx_pal_gpr_t);
  403. gs->manifest_size = manifest_size;
  404. gs->heap_min = (void *) enclave_secs.base + heap_min;
  405. gs->heap_max = (void *) enclave_secs.base + pal_area->addr - MEMORY_GAP;
  406. if (exec_area) {
  407. gs->exec_addr = (void *) enclave_secs.base + exec_area->addr;
  408. gs->exec_size = exec_area->size;
  409. }
  410. gs->thread = NULL;
  411. }
  412. } else if (!strcmp_static(areas[i].desc, "tcs")) {
  413. data = (void *) INLINE_SYSCALL(mmap, 6, NULL, areas[i].size,
  414. PROT_READ|PROT_WRITE,
  415. MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
  416. if (IS_ERR_P(data) || data == NULL) {
  417. /* Note that Graphene currently doesn't handle 0x0 addresses */
  418. SGX_DBG(DBG_E, "Allocating memory for tcs pages failed\n");
  419. goto out;
  420. }
  421. for (uint32_t t = 0 ; t < enclave->thread_num ; t++) {
  422. sgx_arch_tcs_t * tcs = data + pagesize * t;
  423. memset(tcs, 0, pagesize);
  424. tcs->ossa = ssa_area->addr +
  425. enclave->ssaframesize * SSAFRAMENUM * t;
  426. tcs->nssa = SSAFRAMENUM;
  427. tcs->oentry = enclave_entry_addr;
  428. tcs->ofs_base = 0;
  429. tcs->ogs_base = tls_area->addr + t * pagesize;
  430. tcs->ofs_limit = 0xfff;
  431. tcs->ogs_limit = 0xfff;
  432. tcs_addrs[t] = (void *) enclave_secs.base + tcs_area->addr + pagesize * t;
  433. }
  434. } else if (areas[i].fd != -1) {
  435. data = (void *) INLINE_SYSCALL(mmap, 6, NULL, areas[i].size,
  436. PROT_READ,
  437. MAP_FILE|MAP_PRIVATE,
  438. areas[i].fd, 0);
  439. if (IS_ERR_P(data) || data == NULL) {
  440. /* Note that Graphene currently doesn't handle 0x0 addresses */
  441. SGX_DBG(DBG_E, "Allocating memory for file %s failed\n", areas[i].desc);
  442. goto out;
  443. }
  444. }
  445. ret = add_pages_to_enclave(&enclave_secs, (void *) areas[i].addr, data, areas[i].size,
  446. areas[i].type, areas[i].prot, areas[i].skip_eextend, areas[i].desc);
  447. if (data)
  448. INLINE_SYSCALL(munmap, 2, data, areas[i].size);
  449. if (ret < 0) {
  450. SGX_DBG(DBG_E, "Adding pages (%s) to enclave failed: %d\n", areas[i].desc, -ret);
  451. goto out;
  452. }
  453. }
  454. ret = init_enclave(&enclave_secs, &enclave_sigstruct, &enclave_token);
  455. if (ret < 0) {
  456. SGX_DBG(DBG_E, "Initializing enclave failed: %d\n", -ret);
  457. goto out;
  458. }
  459. create_tcs_mapper((void *) enclave_secs.base + tcs_area->addr, enclave->thread_num);
  460. struct enclave_dbginfo * dbg = (void *)
  461. INLINE_SYSCALL(mmap, 6, DBGINFO_ADDR,
  462. sizeof(struct enclave_dbginfo),
  463. PROT_READ|PROT_WRITE,
  464. MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED,
  465. -1, 0);
  466. if (IS_ERR_P(dbg)) {
  467. SGX_DBG(DBG_E, "Cannot allocate debug information (GDB will not work)\n");
  468. } else {
  469. dbg->pid = INLINE_SYSCALL(getpid, 0);
  470. dbg->base = enclave->baseaddr;
  471. dbg->size = enclave->size;
  472. dbg->ssaframesize = enclave->ssaframesize;
  473. dbg->aep = async_exit_pointer;
  474. dbg->thread_tids[0] = dbg->pid;
  475. for (int i = 0 ; i < MAX_DBG_THREADS ; i++)
  476. dbg->tcs_addrs[i] = tcs_addrs[i];
  477. }
  478. ret = 0;
  479. out:
  480. if (enclave_image >= 0)
  481. INLINE_SYSCALL(close, 1, enclave_image);
  482. return ret;
  483. }
  484. static int mcast_s (int port)
  485. {
  486. struct sockaddr_in addr;
  487. int ret = 0;
  488. addr.sin_family = AF_INET;
  489. addr.sin_addr.s_addr = INADDR_ANY;
  490. addr.sin_port = htons(port);
  491. int fd = INLINE_SYSCALL(socket, 3, AF_INET, SOCK_DGRAM, 0);
  492. if (IS_ERR(fd))
  493. return -ERRNO(fd);
  494. ret = INLINE_SYSCALL(setsockopt, 5, fd, IPPROTO_IP, IP_MULTICAST_IF,
  495. &addr.sin_addr.s_addr, sizeof(addr.sin_addr.s_addr));
  496. if (IS_ERR(ret))
  497. return -ERRNO(ret);
  498. return fd;
  499. }
  500. static int mcast_c (int port)
  501. {
  502. int ret = 0, fd;
  503. struct sockaddr_in addr;
  504. addr.sin_family = AF_INET;
  505. addr.sin_addr.s_addr = INADDR_ANY;
  506. addr.sin_port = htons(port);
  507. fd = INLINE_SYSCALL(socket, 3, AF_INET, SOCK_DGRAM, 0);
  508. if (IS_ERR(fd))
  509. return -ERRNO(fd);
  510. int reuse = 1;
  511. INLINE_SYSCALL(setsockopt, 5, fd, SOL_SOCKET, SO_REUSEADDR,
  512. &reuse, sizeof(reuse));
  513. ret = INLINE_SYSCALL(bind, 3, fd, &addr, sizeof(addr));
  514. if (IS_ERR(ret))
  515. return -ERRNO(ret);
  516. ret = INLINE_SYSCALL(setsockopt, 5, fd, IPPROTO_IP, IP_MULTICAST_IF,
  517. &addr.sin_addr.s_addr, sizeof(addr.sin_addr.s_addr));
  518. if (IS_ERR(ret))
  519. return -ERRNO(ret);
  520. inet_pton4(MCAST_GROUP, sizeof(MCAST_GROUP) - 1,
  521. &addr.sin_addr.s_addr);
  522. struct ip_mreq group;
  523. group.imr_multiaddr.s_addr = addr.sin_addr.s_addr;
  524. group.imr_interface.s_addr = INADDR_ANY;
  525. ret = INLINE_SYSCALL(setsockopt, 5, fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
  526. &group, sizeof(group));
  527. if (IS_ERR(ret))
  528. return -ERRNO(ret);
  529. return fd;
  530. }
  531. static unsigned long randval = 0;
  532. void getrand (void * buffer, size_t size)
  533. {
  534. size_t bytes = 0;
  535. while (bytes + sizeof(uint64_t) <= size) {
  536. *(uint64_t*) (buffer + bytes) = randval;
  537. randval = hash64(randval);
  538. bytes += sizeof(uint64_t);
  539. }
  540. if (bytes < size) {
  541. memcpy(buffer + bytes, &randval, size - bytes);
  542. randval = hash64(randval);
  543. }
  544. }
  545. static void create_instance (struct pal_sec * pal_sec)
  546. {
  547. PAL_NUM id;
  548. getrand(&id, sizeof(id));
  549. snprintf(pal_sec->pipe_prefix, sizeof(pal_sec->pipe_prefix), "/graphene/%016lx/", id);
  550. pal_sec->instance_id = id;
  551. }
  552. static int load_manifest (int fd, struct config_store ** config_ptr)
  553. {
  554. int ret = 0;
  555. int nbytes = INLINE_SYSCALL(lseek, 3, fd, 0, SEEK_END);
  556. if (IS_ERR(nbytes)) {
  557. SGX_DBG(DBG_E, "Cannot detect size of manifest file\n");
  558. return -ERRNO(nbytes);
  559. }
  560. struct config_store * config = malloc(sizeof(struct config_store));
  561. if (!config) {
  562. SGX_DBG(DBG_E, "Not enough memory for config_store of manifest\n");
  563. return -ENOMEM;
  564. }
  565. void * config_raw = (void *)
  566. INLINE_SYSCALL(mmap, 6, NULL, nbytes, PROT_READ, MAP_PRIVATE, fd, 0);
  567. if (IS_ERR_P(config_raw)) {
  568. SGX_DBG(DBG_E, "Cannot mmap manifest file\n");
  569. ret = -ERRNO_P(config_raw);
  570. goto out;
  571. }
  572. config->raw_data = config_raw;
  573. config->raw_size = nbytes;
  574. config->malloc = malloc;
  575. config->free = NULL;
  576. const char * errstring = NULL;
  577. ret = read_config(config, NULL, &errstring);
  578. if (ret < 0) {
  579. SGX_DBG(DBG_E, "Cannot read manifest: %s\n", errstring);
  580. goto out;
  581. }
  582. *config_ptr = config;
  583. ret = 0;
  584. out:
  585. if (ret < 0) {
  586. free(config);
  587. if (!IS_ERR_P(config_raw))
  588. INLINE_SYSCALL(munmap, 2, config_raw, nbytes);
  589. }
  590. return ret;
  591. }
  592. /*
  593. * Returns the number of online CPUs read from /sys/devices/system/cpu/online, -errno on failure.
  594. * Understands complex formats like "1,3-5,6".
  595. */
  596. static int get_cpu_count(void) {
  597. int fd = INLINE_SYSCALL(open, 3, "/sys/devices/system/cpu/online", O_RDONLY|O_CLOEXEC, 0);
  598. if (fd < 0)
  599. return unix_to_pal_error(ERRNO(fd));
  600. char buf[64];
  601. int ret = INLINE_SYSCALL(read, 3, fd, buf, sizeof(buf) - 1);
  602. if (ret < 0) {
  603. INLINE_SYSCALL(close, 1, fd);
  604. return unix_to_pal_error(ERRNO(ret));
  605. }
  606. buf[ret] = '\0'; /* ensure null-terminated buf even in partial read */
  607. char* end;
  608. char* ptr = buf;
  609. int cpu_count = 0;
  610. while (*ptr) {
  611. while (*ptr == ' ' || *ptr == '\t' || *ptr == ',')
  612. ptr++;
  613. int firstint = (int)strtol(ptr, &end, 10);
  614. if (ptr == end)
  615. break;
  616. if (*end == '\0' || *end == ',') {
  617. /* single CPU index, count as one more CPU */
  618. cpu_count++;
  619. } else if (*end == '-') {
  620. /* CPU range, count how many CPUs in range */
  621. ptr = end + 1;
  622. int secondint = (int)strtol(ptr, &end, 10);
  623. if (secondint > firstint)
  624. cpu_count += secondint - firstint + 1; // inclusive (e.g., 0-7, or 8-16)
  625. }
  626. ptr = end;
  627. }
  628. INLINE_SYSCALL(close, 1, fd);
  629. if (cpu_count == 0)
  630. return -PAL_ERROR_STREAMNOTEXIST;
  631. return cpu_count;
  632. }
  633. static int load_enclave (struct pal_enclave * enclave,
  634. int manifest_fd,
  635. char * manifest_uri,
  636. char * exec_uri,
  637. char * args, size_t args_size,
  638. char * env, size_t env_size,
  639. bool exec_uri_inferred)
  640. {
  641. struct pal_sec * pal_sec = &enclave->pal_sec;
  642. int ret;
  643. struct timeval tv;
  644. #if PRINT_ENCLAVE_STAT == 1
  645. INLINE_SYSCALL(gettimeofday, 2, &tv, NULL);
  646. pal_sec->start_time = tv.tv_sec * 1000000UL + tv.tv_usec;
  647. #endif
  648. ret = open_gsgx();
  649. if (ret < 0)
  650. return ret;
  651. if (!is_wrfsbase_supported())
  652. return -EPERM;
  653. INLINE_SYSCALL(gettimeofday, 2, &tv, NULL);
  654. randval = tv.tv_sec * 1000000UL + tv.tv_usec;
  655. pal_sec->pid = INLINE_SYSCALL(getpid, 0);
  656. pal_sec->uid = INLINE_SYSCALL(getuid, 0);
  657. pal_sec->gid = INLINE_SYSCALL(getgid, 0);
  658. int num_cpus = get_cpu_count();
  659. if (num_cpus < 0) {
  660. return num_cpus;
  661. }
  662. pal_sec->num_cpus = num_cpus;
  663. #ifdef DEBUG
  664. size_t env_i = 0;
  665. while (env_i < env_size) {
  666. if (!strcmp_static(&env[env_i], "IN_GDB=1")) {
  667. SGX_DBG(DBG_I, "[ Running under GDB ]\n");
  668. pal_sec->in_gdb = true;
  669. } else if (strstartswith_static(&env[env_i], "LD_PRELOAD=")) {
  670. uint64_t env_i_size = strnlen(&env[env_i], env_size - env_i) + 1;
  671. memmove(&env[env_i], &env[env_i + env_i_size], env_size - env_i - env_i_size);
  672. env_size -= env_i_size;
  673. continue;
  674. }
  675. env_i += strnlen(&env[env_i], env_size - env_i) + 1;
  676. }
  677. #endif
  678. enclave->manifest = manifest_fd;
  679. ret = load_manifest(enclave->manifest, &enclave->config);
  680. if (ret < 0) {
  681. SGX_DBG(DBG_E, "Invalid manifest: %s\n", manifest_uri);
  682. return -EINVAL;
  683. }
  684. char cfgbuf[CONFIG_MAX];
  685. const char * errstring;
  686. // A manifest can specify an executable with a different base name
  687. // than the manifest itself. Always give the exec field of the manifest
  688. // precedence if specified.
  689. if (get_config(enclave->config, "loader.exec", cfgbuf, CONFIG_MAX) > 0) {
  690. exec_uri = resolve_uri(cfgbuf, &errstring);
  691. exec_uri_inferred = false;
  692. if (!exec_uri) {
  693. SGX_DBG(DBG_E, "%s: %s\n", errstring, cfgbuf);
  694. return -EINVAL;
  695. }
  696. }
  697. enclave->exec = INLINE_SYSCALL(open, 3, exec_uri + static_strlen("file:"),
  698. O_RDONLY|O_CLOEXEC, 0);
  699. if (IS_ERR(enclave->exec)) {
  700. if (exec_uri_inferred) {
  701. // It is valid for an enclave not to have an executable.
  702. // We need to catch the case where we inferred the executable
  703. // from the manifest file name, but it doesn't exist, and let
  704. // the enclave go a bit further. Go ahead and warn the user,
  705. // though.
  706. SGX_DBG(DBG_I, "Inferred executable cannot be opened: %s. This may be ok, "
  707. "or may represent a manifest misconfiguration. This typically "
  708. "represents advanced usage, and if it is not what you intended, "
  709. "try setting the loader.exec field in the manifest.\n", exec_uri);
  710. enclave->exec = -1;
  711. } else {
  712. SGX_DBG(DBG_E, "Cannot open executable %s\n", exec_uri);
  713. return -EINVAL;
  714. }
  715. }
  716. if (get_config(enclave->config, "sgx.sigfile", cfgbuf, CONFIG_MAX) < 0) {
  717. SGX_DBG(DBG_E, "Sigstruct file not found ('sgx.sigfile' must be specified in manifest)\n");
  718. return -EINVAL;
  719. }
  720. char * sig_uri = resolve_uri(cfgbuf, &errstring);
  721. if (!sig_uri) {
  722. SGX_DBG(DBG_E, "%s: %s\n", errstring, cfgbuf);
  723. return -EINVAL;
  724. }
  725. if (!strendswith(sig_uri, ".sig")) {
  726. SGX_DBG(DBG_E, "Invalid sigstruct file URI as %s\n", cfgbuf);
  727. free(sig_uri);
  728. return -EINVAL;
  729. }
  730. enclave->sigfile = INLINE_SYSCALL(open, 3, sig_uri + static_strlen("file:"),
  731. O_RDONLY|O_CLOEXEC, 0);
  732. if (IS_ERR(enclave->sigfile)) {
  733. SGX_DBG(DBG_E, "Cannot open sigstruct file %s\n", sig_uri);
  734. free(sig_uri);
  735. return -EINVAL;
  736. }
  737. char * token_uri = alloc_concat(sig_uri, strlen(sig_uri) - static_strlen(".sig"), ".token", -1);
  738. free(sig_uri);
  739. if (!token_uri) {
  740. INLINE_SYSCALL(close, 1, enclave->sigfile);
  741. return -ENOMEM;
  742. }
  743. enclave->token = INLINE_SYSCALL(open, 3, token_uri + static_strlen("file:"),
  744. O_RDONLY|O_CLOEXEC, 0);
  745. if (IS_ERR(enclave->token)) {
  746. SGX_DBG(DBG_E, "Cannot open token \'%s\'. Use \'"
  747. PAL_FILE("pal-sgx-get-token")
  748. "\' on the runtime host or run \'make SGX=1 sgx-tokens\' "
  749. "in the Graphene source to create the token file.\n",
  750. token_uri);
  751. free(token_uri);
  752. return -EINVAL;
  753. }
  754. SGX_DBG(DBG_I, "Token file: %s\n", token_uri);
  755. free(token_uri);
  756. ret = initialize_enclave(enclave);
  757. if (ret < 0)
  758. return ret;
  759. if (!pal_sec->instance_id)
  760. create_instance(&enclave->pal_sec);
  761. memcpy(pal_sec->manifest_name, manifest_uri, strlen(manifest_uri) + 1);
  762. if (enclave->exec == -1) {
  763. memset(pal_sec->exec_name, 0, sizeof(PAL_SEC_STR));
  764. } else {
  765. memcpy(pal_sec->exec_name, exec_uri, strlen(exec_uri) + 1);
  766. }
  767. if (!pal_sec->mcast_port) {
  768. unsigned short mcast_port;
  769. getrand(&mcast_port, sizeof(unsigned short));
  770. pal_sec->mcast_port = mcast_port > 1024 ? mcast_port : mcast_port + 1024;
  771. }
  772. if ((ret = mcast_s(pal_sec->mcast_port)) >= 0) {
  773. pal_sec->mcast_srv = ret;
  774. if ((ret = mcast_c(pal_sec->mcast_port)) >= 0) {
  775. pal_sec->mcast_cli = ret;
  776. } else {
  777. INLINE_SYSCALL(close, 1, pal_sec->mcast_srv);
  778. pal_sec->mcast_srv = 0;
  779. }
  780. }
  781. ret = sgx_signal_setup();
  782. if (ret < 0)
  783. return ret;
  784. ret = init_aesm_targetinfo(&pal_sec->aesm_targetinfo);
  785. if (ret < 0)
  786. return ret;
  787. void* alt_stack = (void*)INLINE_SYSCALL(mmap, 6, NULL, ALT_STACK_SIZE,
  788. PROT_READ | PROT_WRITE,
  789. MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
  790. if (IS_ERR_P(alt_stack))
  791. return -ENOMEM;
  792. /* initialize TCB at the top of the alternative stack */
  793. PAL_TCB_LINUX* tcb = alt_stack + ALT_STACK_SIZE - sizeof(PAL_TCB_LINUX);
  794. tcb->common.self = &tcb->common;
  795. tcb->alt_stack = alt_stack;
  796. tcb->stack = NULL; /* main thread uses the stack provided by Linux */
  797. tcb->tcs = NULL; /* initialized by child thread */
  798. pal_thread_init(tcb);
  799. /* start running trusted PAL */
  800. ecall_enclave_start(args, args_size, env, env_size);
  801. #if PRINT_ENCLAVE_STAT == 1
  802. PAL_NUM exit_time = 0;
  803. INLINE_SYSCALL(gettimeofday, 2, &tv, NULL);
  804. exit_time = tv.tv_sec * 1000000UL + tv.tv_usec;
  805. #endif
  806. unmap_tcs();
  807. INLINE_SYSCALL(munmap, 2, alt_stack, ALT_STACK_SIZE);
  808. INLINE_SYSCALL(exit, 0);
  809. return 0;
  810. }
  811. int main (int argc, char ** argv, char ** envp)
  812. {
  813. char * manifest_uri = NULL;
  814. char * exec_uri = NULL;
  815. const char * pal_loader = argv[0];
  816. int fd = -1;
  817. int ret = 0;
  818. bool exec_uri_inferred = false; // Handle the case where the exec uri is
  819. // inferred from the manifest name somewhat
  820. // differently
  821. argc--;
  822. argv++;
  823. int is_child = sgx_init_child_process(&pal_enclave.pal_sec);
  824. if (is_child < 0) {
  825. ret = is_child;
  826. goto out;
  827. }
  828. if (!is_child) {
  829. /* occupy PROC_INIT_FD so no one will use it */
  830. INLINE_SYSCALL(dup2, 2, 0, PROC_INIT_FD);
  831. if (!argc)
  832. goto usage;
  833. if (!strcmp_static(argv[0], "file:")) {
  834. exec_uri = alloc_concat(argv[0], -1, NULL, -1);
  835. } else {
  836. exec_uri = alloc_concat("file:", -1, argv[0], -1);
  837. }
  838. } else {
  839. exec_uri = alloc_concat(pal_enclave.pal_sec.exec_name, -1, NULL, -1);
  840. }
  841. if (!exec_uri) {
  842. ret = -ENOMEM;
  843. goto out;
  844. }
  845. fd = INLINE_SYSCALL(open, 3, exec_uri + static_strlen("file:"), O_RDONLY|O_CLOEXEC, 0);
  846. if (IS_ERR(fd)) {
  847. SGX_DBG(DBG_E, "Input file not found: %s\n", exec_uri);
  848. ret = fd;
  849. goto usage;
  850. }
  851. char file_first_four_bytes[4];
  852. ret = INLINE_SYSCALL(read, 3, fd, file_first_four_bytes, sizeof(file_first_four_bytes));
  853. if (IS_ERR(ret)) {
  854. goto out;
  855. }
  856. if (ret != sizeof(file_first_four_bytes)) {
  857. ret = -EINVAL;
  858. goto out;
  859. }
  860. char manifest_base_name[URI_MAX];
  861. size_t manifest_base_name_len = sizeof(manifest_base_name);
  862. ret = get_base_name(exec_uri + static_strlen("file:"), manifest_base_name,
  863. &manifest_base_name_len);
  864. if (ret < 0) {
  865. goto out;
  866. }
  867. if (strendswith(manifest_base_name, ".manifest")) {
  868. if (!strcpy_static(manifest_base_name + manifest_base_name_len, ".sgx",
  869. sizeof(manifest_base_name) - manifest_base_name_len)) {
  870. ret = -E2BIG;
  871. goto out;
  872. }
  873. } else if (!strendswith(manifest_base_name, ".manifest.sgx")) {
  874. if (!strcpy_static(manifest_base_name + manifest_base_name_len, ".manifest.sgx",
  875. sizeof(manifest_base_name) - manifest_base_name_len)) {
  876. ret = -E2BIG;
  877. goto out;
  878. }
  879. }
  880. int manifest_fd = -1;
  881. if (memcmp(file_first_four_bytes, "\177ELF", sizeof(file_first_four_bytes))) {
  882. /* exec_uri doesn't refer to ELF executable, so it must refer to the
  883. * manifest. Verify this and update exec_uri with the manifest suffix
  884. * removed.
  885. */
  886. size_t exec_uri_len = strlen(exec_uri);
  887. if (strendswith(exec_uri, ".manifest")) {
  888. exec_uri[exec_uri_len - static_strlen(".manifest")] = '\0';
  889. } else if (strendswith(exec_uri, ".manifest.sgx")) {
  890. INLINE_SYSCALL(lseek, 3, fd, 0, SEEK_SET);
  891. manifest_fd = fd;
  892. exec_uri[exec_uri_len - static_strlen(".manifest.sgx")] = '\0';
  893. } else {
  894. SGX_DBG(DBG_E, "Invalid manifest file specified: %s\n", exec_uri);
  895. goto usage;
  896. }
  897. exec_uri_inferred = true;
  898. }
  899. if (manifest_fd == -1) {
  900. INLINE_SYSCALL(close, 1, fd);
  901. fd = manifest_fd = INLINE_SYSCALL(open, 3, manifest_base_name, O_RDONLY|O_CLOEXEC, 0);
  902. if (IS_ERR(fd)) {
  903. SGX_DBG(DBG_E, "Cannot open manifest file: %s\n", manifest_base_name);
  904. goto usage;
  905. }
  906. }
  907. manifest_uri = alloc_concat("file:", static_strlen("file:"), manifest_base_name, -1);
  908. if (!manifest_uri) {
  909. ret = -ENOMEM;
  910. goto out;
  911. }
  912. SGX_DBG(DBG_I, "Manifest file: %s\n", manifest_uri);
  913. SGX_DBG(DBG_I, "Executable file: %s\n", exec_uri);
  914. /*
  915. * While C does not guarantee that the argv[i] and envp[i] strings are
  916. * continuous we know that we are running on Linux, which does this. This
  917. * saves us creating a copy of all argv and envp strings.
  918. */
  919. char * args = argv[0];
  920. size_t args_size = argc > 0 ? (argv[argc - 1] - argv[0]) + strlen(argv[argc - 1]) + 1: 0;
  921. int envc = 0;
  922. while (envp[envc] != NULL) {
  923. envc++;
  924. }
  925. char * env = envp[0];
  926. size_t env_size = envc > 0 ? (envp[envc - 1] - envp[0]) + strlen(envp[envc - 1]) + 1: 0;
  927. ret = load_enclave(&pal_enclave, manifest_fd, manifest_uri, exec_uri, args, args_size, env, env_size,
  928. exec_uri_inferred);
  929. out:
  930. if (pal_enclave.exec >= 0)
  931. INLINE_SYSCALL(close, 1, pal_enclave.exec);
  932. if (pal_enclave.sigfile >= 0)
  933. INLINE_SYSCALL(close, 1, pal_enclave.sigfile);
  934. if (pal_enclave.token >= 0)
  935. INLINE_SYSCALL(close, 1, pal_enclave.token);
  936. if (!IS_ERR(fd))
  937. INLINE_SYSCALL(close, 1, fd);
  938. free(exec_uri);
  939. free(manifest_uri);
  940. return ret;
  941. usage:
  942. SGX_DBG(DBG_E, "USAGE: %s [executable|manifest] args ...\n", pal_loader);
  943. ret = -EINVAL;
  944. goto out;
  945. }