pal-sgx-sign 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929
  1. #!/usr/bin/env python3
  2. # pylint: disable=invalid-name
  3. import argparse
  4. import datetime
  5. import functools
  6. import hashlib
  7. import os
  8. import struct
  9. import subprocess
  10. import sys
  11. sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
  12. import generated_offsets as offs # pylint: disable=import-error,wrong-import-position
  13. # pylint: enable=invalid-name
  14. # Default / Architectural Options
  15. ARCHITECTURE = "amd64"
  16. SSAFRAMESIZE = offs.PAGESIZE
  17. DEFAULT_ENCLAVE_SIZE = '256M'
  18. DEFAULT_THREAD_NUM = 4
  19. ENCLAVE_HEAP_MIN = offs.DEFAULT_HEAP_MIN
  20. # Utilities
  21. ZERO_PAGE = bytes(offs.PAGESIZE)
  22. def roundup(addr):
  23. remaining = addr % offs.PAGESIZE
  24. if remaining:
  25. return addr + (offs.PAGESIZE - remaining)
  26. return addr
  27. def rounddown(addr):
  28. return addr - addr % offs.PAGESIZE
  29. def parse_size(value):
  30. scale = 1
  31. if value.endswith("K"):
  32. scale = 1024
  33. if value.endswith("M"):
  34. scale = 1024 * 1024
  35. if value.endswith("G"):
  36. scale = 1024 * 1024 * 1024
  37. if scale != 1:
  38. value = value[:-1]
  39. return int(value, 0) * scale
  40. # Reading / Writing Manifests
  41. def read_manifest(filename):
  42. manifest = dict()
  43. manifest_layout = []
  44. with open(filename, "r") as file:
  45. for line in file:
  46. if line == "":
  47. manifest_layout.append((None, None))
  48. break
  49. pound = line.find("#")
  50. if pound != -1:
  51. comment = line[pound:].strip()
  52. line = line[:pound]
  53. else:
  54. comment = None
  55. line = line.strip()
  56. equal = line.find("=")
  57. if equal != -1:
  58. key = line[:equal].strip()
  59. manifest[key] = line[equal + 1:].strip()
  60. else:
  61. key = None
  62. manifest_layout.append((key, comment))
  63. return (manifest, manifest_layout)
  64. def exec_sig_manifest(args, manifest):
  65. if 'exec' not in args or args.get('depend'):
  66. if 'loader.exec' in manifest:
  67. exec_url = manifest['loader.exec']
  68. if not exec_url.startswith('file:'):
  69. print("executable must be a local file", file=sys.stderr)
  70. return 1
  71. exec_path = exec_url[5:] # strip preceding 'file:'
  72. if os.path.isabs(exec_path):
  73. args['exec'] = exec_path
  74. else:
  75. args['exec'] = os.path.join(
  76. os.path.dirname(args['manifest']), exec_path)
  77. if 'sgx.sigfile' in manifest:
  78. args['sigfile'] = resolve_uri(manifest['sgx.sigfile'],
  79. check_exist=False)
  80. else:
  81. sigfile = args['output']
  82. for ext in ['.manifest.sgx.d', '.manifest.sgx', '.manifest']:
  83. if sigfile.endswith(ext):
  84. sigfile = sigfile[:-len(ext)]
  85. break
  86. args['sigfile'] = sigfile + '.sig'
  87. manifest['sgx.sigfile'] = 'file:' + os.path.basename(args['sigfile'])
  88. return 0
  89. def output_manifest(filename, manifest, manifest_layout):
  90. with open(filename, 'w') as file:
  91. written = []
  92. file.write('# DO NOT MODIFY. THIS FILE WAS AUTO-GENERATED.\n\n')
  93. for (key, comment) in manifest_layout:
  94. line = ''
  95. if key is not None:
  96. line += key + ' = ' + manifest[key]
  97. written.append(key)
  98. if comment is not None:
  99. if line != '':
  100. line += ' '
  101. line += comment
  102. file.write(line)
  103. file.write('\n')
  104. file.write('\n')
  105. file.write('# Generated by Graphene\n')
  106. file.write('\n')
  107. for key in sorted(manifest):
  108. if key not in written:
  109. file.write("%s = %s\n" % (key, manifest[key]))
  110. # Loading Enclave Attributes
  111. def get_enclave_attributes(manifest):
  112. sgx_flags = {
  113. 'FLAG_DEBUG': struct.pack("<Q", offs.SGX_FLAGS_DEBUG),
  114. 'FLAG_MODE64BIT': struct.pack("<Q", offs.SGX_FLAGS_MODE64BIT),
  115. }
  116. sgx_xfrms = {
  117. 'XFRM_LEGACY': struct.pack("<Q", offs.SGX_XFRM_LEGACY),
  118. 'XFRM_AVX': struct.pack("<Q", offs.SGX_XFRM_AVX),
  119. 'XFRM_AVX512': struct.pack("<Q", offs.SGX_XFRM_AVX512),
  120. 'XFRM_MPX': struct.pack("<Q", offs.SGX_XFRM_MPX),
  121. }
  122. sgx_miscs = {
  123. 'MISC_EXINFO': struct.pack("<L", offs.SGX_MISCSELECT_EXINFO),
  124. }
  125. default_attributes = {
  126. 'FLAG_DEBUG',
  127. 'XFRM_LEGACY',
  128. }
  129. if ARCHITECTURE == 'amd64':
  130. default_attributes.add('FLAG_MODE64BIT')
  131. manifest_options = {
  132. 'debug': 'FLAG_DEBUG',
  133. 'require_avx': 'XFRM_AVX',
  134. 'require_avx512': 'XFRM_AVX512',
  135. 'require_mpx': 'XFRM_MPX',
  136. 'support_exinfo': 'MISC_EXINFO',
  137. }
  138. attributes = default_attributes
  139. for opt in manifest_options:
  140. key = 'sgx.' + opt
  141. if key in manifest:
  142. if manifest[key] == '1':
  143. attributes.add(manifest_options[opt])
  144. else:
  145. attributes.discard(manifest_options[opt])
  146. flags_raw = struct.pack("<Q", 0)
  147. xfrms_raw = struct.pack("<Q", 0)
  148. miscs_raw = struct.pack("<L", 0)
  149. for attr in attributes:
  150. if attr in sgx_flags:
  151. flags_raw = bytes([a | b for a, b in
  152. zip(flags_raw, sgx_flags[attr])])
  153. if attr in sgx_xfrms:
  154. xfrms_raw = bytes([a | b for a, b in
  155. zip(xfrms_raw, sgx_xfrms[attr])])
  156. if attr in sgx_miscs:
  157. miscs_raw = bytes([a | b for a, b in
  158. zip(miscs_raw, sgx_miscs[attr])])
  159. return flags_raw, xfrms_raw, miscs_raw
  160. # Generate Checksums / Measurement
  161. def resolve_uri(uri, check_exist=True):
  162. orig_uri = uri
  163. if uri.startswith('file:'):
  164. target = os.path.normpath(uri[5:])
  165. else:
  166. target = os.path.normpath(uri)
  167. if check_exist and not os.path.exists(target):
  168. raise Exception(
  169. 'Cannot resolve ' + orig_uri + ' or the file does not exist.')
  170. return target
  171. def get_checksum(filename):
  172. digest = hashlib.sha256()
  173. with open(filename, 'rb') as file:
  174. digest.update(file.read())
  175. return digest.digest()
  176. def get_trusted_files(manifest, args, check_exist=True, do_checksum=True):
  177. targets = dict()
  178. if 'exec' in args:
  179. targets['exec'] = (args['exec'], resolve_uri(args['exec'],
  180. check_exist))
  181. if 'loader.preload' in manifest:
  182. for i, uri in enumerate(str.split(manifest['loader.preload'], ',')):
  183. targets['preload' + str(i)] = (uri, resolve_uri(uri, check_exist))
  184. for (key, val) in manifest.items():
  185. if not key.startswith('sgx.trusted_files.'):
  186. continue
  187. key = key[len('sgx.trusted_files.'):]
  188. if key in targets:
  189. raise Exception(
  190. 'repeated key in manifest: sgx.trusted_files.' + key)
  191. targets[key] = (val, resolve_uri(val, check_exist))
  192. if do_checksum:
  193. for (key, val) in targets.items():
  194. (uri, target) = val
  195. checksum = get_checksum(target).hex()
  196. targets[key] = (uri, target, checksum)
  197. return targets
  198. def get_trusted_children(manifest, check_exist=True, do_checksum=True):
  199. targets = dict()
  200. for (key, val) in manifest.items():
  201. if not key.startswith('sgx.trusted_children.'):
  202. continue
  203. key = key[len('sgx.trusted_children.'):]
  204. if key in targets:
  205. raise Exception(
  206. 'repeated key in manifest: sgx.trusted_children.' + key)
  207. target = resolve_uri(val, check_exist)
  208. if not target.endswith('.sig'):
  209. target += '.sig'
  210. if do_checksum:
  211. sig = open(target, 'rb').read()[
  212. offs.SGX_ARCH_ENCLAVE_CSS_ENCLAVE_HASH:
  213. offs.SGX_ARCH_ENCLAVE_CSS_ENCLAVE_HASH + offs.SGX_HASH_SIZE].hex()
  214. targets[key] = (val, target, sig)
  215. else:
  216. targets[key] = (val, target)
  217. return targets
  218. # Populate Enclave Memory
  219. PAGEINFO_R = 0x1
  220. PAGEINFO_W = 0x2
  221. PAGEINFO_X = 0x4
  222. PAGEINFO_TCS = 0x100
  223. PAGEINFO_REG = 0x200
  224. def get_loadcmds(filename):
  225. loadcmds = []
  226. proc = subprocess.Popen(['readelf', '-l', '-W', filename],
  227. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  228. while True:
  229. line = proc.stdout.readline()
  230. if not line:
  231. break
  232. line = line.decode()
  233. stripped = line.strip()
  234. if not stripped.startswith('LOAD'):
  235. continue
  236. tokens = stripped.split()
  237. if len(tokens) < 6:
  238. continue
  239. if len(tokens) >= 7 and tokens[7] == "E":
  240. tokens[6] += tokens[7]
  241. prot = 0
  242. for token in tokens[6]:
  243. if token == "R":
  244. prot = prot | 4
  245. if token == "W":
  246. prot = prot | 2
  247. if token == "E":
  248. prot = prot | 1
  249. loadcmds.append((int(tokens[1][2:], 16), # offset
  250. int(tokens[2][2:], 16), # addr
  251. int(tokens[4][2:], 16), # filesize
  252. int(tokens[5][2:], 16), # memsize
  253. prot))
  254. proc.wait()
  255. if proc.returncode != 0:
  256. return None
  257. return loadcmds
  258. class MemoryArea:
  259. # pylint: disable=too-few-public-methods,too-many-instance-attributes
  260. def __init__(self, desc, file=None, content=None, addr=None, size=None,
  261. flags=None, measure=True):
  262. # pylint: disable=too-many-arguments
  263. self.desc = desc
  264. self.file = file
  265. self.content = content
  266. self.addr = addr
  267. self.size = size
  268. self.flags = flags
  269. self.is_binary = False
  270. self.measure = measure
  271. if file:
  272. loadcmds = get_loadcmds(file)
  273. if loadcmds:
  274. mapaddr = 0xffffffffffffffff
  275. mapaddr_end = 0
  276. for (_, addr_, _, memsize, _) in loadcmds:
  277. if rounddown(addr_) < mapaddr:
  278. mapaddr = rounddown(addr_)
  279. if roundup(addr_ + memsize) > mapaddr_end:
  280. mapaddr_end = roundup(addr_ + memsize)
  281. self.is_binary = True
  282. self.size = mapaddr_end - mapaddr
  283. if mapaddr > 0:
  284. self.addr = mapaddr
  285. else:
  286. self.size = os.stat(file).st_size
  287. if self.addr is not None:
  288. self.addr = rounddown(self.addr)
  289. if self.size is not None:
  290. self.size = roundup(self.size)
  291. def get_memory_areas(attr, args):
  292. areas = []
  293. areas.append(
  294. MemoryArea('ssa',
  295. size=attr['thread_num'] * SSAFRAMESIZE * offs.SSAFRAMENUM,
  296. flags=PAGEINFO_R | PAGEINFO_W | PAGEINFO_REG))
  297. areas.append(MemoryArea('tcs', size=attr['thread_num'] * offs.TCS_SIZE,
  298. flags=PAGEINFO_TCS))
  299. areas.append(MemoryArea('tls', size=attr['thread_num'] * offs.PAGESIZE,
  300. flags=PAGEINFO_R | PAGEINFO_W | PAGEINFO_REG))
  301. for _ in range(attr['thread_num']):
  302. areas.append(MemoryArea('stack', size=offs.ENCLAVE_STACK_SIZE,
  303. flags=PAGEINFO_R | PAGEINFO_W | PAGEINFO_REG))
  304. areas.append(MemoryArea('pal', file=args['libpal'], flags=PAGEINFO_REG))
  305. if 'exec' in args:
  306. areas.append(MemoryArea('exec', file=args['exec'],
  307. flags=PAGEINFO_W | PAGEINFO_REG))
  308. return areas
  309. def find_areas(areas, desc):
  310. return [area for area in areas if area.desc == desc]
  311. def find_area(areas, desc, allow_none=False):
  312. matching = find_areas(areas, desc)
  313. if not matching and allow_none:
  314. return None
  315. if len(matching) != 1:
  316. raise KeyError(
  317. "Could not find exactly one MemoryArea '{}'".format(desc))
  318. return matching[0]
  319. def entry_point(elf_path):
  320. env = os.environ
  321. env['LC_ALL'] = 'C'
  322. out = subprocess.check_output(
  323. ['readelf', '-l', '--', elf_path], env=env)
  324. for line in out.splitlines():
  325. line = line.decode()
  326. if line.startswith("Entry point "):
  327. return int(line[12:], 0)
  328. raise ValueError("Could not find entry point of elf file")
  329. def baseaddr():
  330. if ENCLAVE_HEAP_MIN == 0:
  331. return offs.ENCLAVE_HIGH_ADDRESS
  332. return 0
  333. def gen_area_content(attr, areas):
  334. # pylint: disable=too-many-locals
  335. manifest_area = find_area(areas, 'manifest')
  336. exec_area = find_area(areas, 'exec', True)
  337. pal_area = find_area(areas, 'pal')
  338. ssa_area = find_area(areas, 'ssa')
  339. tcs_area = find_area(areas, 'tcs')
  340. tls_area = find_area(areas, 'tls')
  341. stacks = find_areas(areas, 'stack')
  342. tcs_data = bytearray(tcs_area.size)
  343. def set_tcs_field(t, offset, pack_fmt, value):
  344. struct.pack_into(pack_fmt, tcs_data, t * offs.TCS_SIZE + offset, value)
  345. tls_data = bytearray(tls_area.size)
  346. def set_tls_field(t, offset, value):
  347. struct.pack_into('<Q', tls_data, t * offs.PAGESIZE + offset, value)
  348. enclave_heap_max = pal_area.addr - offs.MEMORY_GAP
  349. # Sanity check that we measure everything except the heap which is zeroed
  350. # on enclave startup.
  351. for area in areas:
  352. if (area.addr + area.size <= ENCLAVE_HEAP_MIN or
  353. area.addr >= enclave_heap_max or area is exec_area):
  354. if not area.measure:
  355. raise ValueError("Memory area, which is not the heap, "
  356. "is not measured")
  357. elif area.desc != 'free':
  358. raise ValueError("Unexpected memory area is in heap range")
  359. for t in range(0, attr['thread_num']):
  360. ssa_offset = ssa_area.addr + SSAFRAMESIZE * offs.SSAFRAMENUM * t
  361. ssa = baseaddr() + ssa_offset
  362. set_tcs_field(t, offs.TCS_OSSA, '<Q', ssa_offset)
  363. set_tcs_field(t, offs.TCS_NSSA, '<L', offs.SSAFRAMENUM)
  364. set_tcs_field(t, offs.TCS_OENTRY, '<Q',
  365. pal_area.addr + entry_point(pal_area.file))
  366. set_tcs_field(t, offs.TCS_OGS_BASE, '<Q', tls_area.addr + offs.PAGESIZE * t)
  367. set_tcs_field(t, offs.TCS_OFS_LIMIT, '<L', 0xfff)
  368. set_tcs_field(t, offs.TCS_OGS_LIMIT, '<L', 0xfff)
  369. set_tls_field(t, offs.SGX_COMMON_SELF,
  370. tls_area.addr + offs.PAGESIZE * t + baseaddr())
  371. set_tls_field(t, offs.SGX_ENCLAVE_SIZE, attr['enclave_size'])
  372. set_tls_field(t, offs.SGX_TCS_OFFSET, tcs_area.addr + offs.TCS_SIZE * t)
  373. set_tls_field(t, offs.SGX_INITIAL_STACK_OFFSET,
  374. stacks[t].addr + stacks[t].size)
  375. set_tls_field(t, offs.SGX_SSA, ssa)
  376. set_tls_field(t, offs.SGX_GPR, ssa + SSAFRAMESIZE - offs.SGX_GPR_SIZE)
  377. set_tls_field(t, offs.SGX_MANIFEST_SIZE,
  378. os.stat(manifest_area.file).st_size)
  379. set_tls_field(t, offs.SGX_HEAP_MIN, baseaddr() + ENCLAVE_HEAP_MIN)
  380. set_tls_field(t, offs.SGX_HEAP_MAX, baseaddr() + enclave_heap_max)
  381. if exec_area is not None:
  382. set_tls_field(t, offs.SGX_EXEC_ADDR, baseaddr() + exec_area.addr)
  383. set_tls_field(t, offs.SGX_EXEC_SIZE, exec_area.size)
  384. tcs_area.content = tcs_data
  385. tls_area.content = tls_data
  386. def populate_memory_areas(attr, areas):
  387. populating = attr['enclave_size']
  388. for area in areas:
  389. if area.addr is not None:
  390. continue
  391. area.addr = populating - area.size
  392. if area.addr < ENCLAVE_HEAP_MIN:
  393. raise Exception("Enclave size is not large enough")
  394. populating = max(area.addr - offs.MEMORY_GAP, 0)
  395. free_areas = []
  396. for area in areas:
  397. if area.addr + area.size + offs.MEMORY_GAP < populating:
  398. addr = area.addr + area.size + offs.MEMORY_GAP
  399. flags = PAGEINFO_R | PAGEINFO_W | PAGEINFO_X | PAGEINFO_REG
  400. free_areas.append(
  401. MemoryArea('free', addr=addr, size=populating - addr,
  402. flags=flags, measure=False))
  403. populating = max(area.addr - offs.MEMORY_GAP, 0)
  404. if populating > ENCLAVE_HEAP_MIN:
  405. flags = PAGEINFO_R | PAGEINFO_W | PAGEINFO_X | PAGEINFO_REG
  406. free_areas.append(
  407. MemoryArea('free', addr=ENCLAVE_HEAP_MIN,
  408. size=populating - ENCLAVE_HEAP_MIN, flags=flags,
  409. measure=False))
  410. gen_area_content(attr, areas)
  411. return areas + free_areas
  412. def generate_measurement(attr, areas):
  413. # pylint: disable=too-many-statements,too-many-branches,too-many-locals
  414. def do_ecreate(digest, size):
  415. data = struct.pack("<8sLQ44s", b"ECREATE", SSAFRAMESIZE // offs.PAGESIZE,
  416. size, b"")
  417. digest.update(data)
  418. def do_eadd(digest, offset, flags):
  419. data = struct.pack("<8sQQ40s", b"EADD", offset, flags, b"")
  420. digest.update(data)
  421. def do_eextend(digest, offset, content):
  422. if len(content) != 256:
  423. raise ValueError("Exactly 256 bytes expected")
  424. data = struct.pack("<8sQ48s", b"EEXTEND", offset, b"")
  425. digest.update(data)
  426. digest.update(content)
  427. def include_page(digest, offset, flags, content, measure):
  428. if len(content) != offs.PAGESIZE:
  429. raise ValueError("Exactly one page expected")
  430. do_eadd(digest, offset, flags)
  431. if measure:
  432. for i in range(0, offs.PAGESIZE, 256):
  433. do_eextend(digest, offset + i, content[i:i + 256])
  434. mrenclave = hashlib.sha256()
  435. do_ecreate(mrenclave, attr['enclave_size'])
  436. def print_area(addr, size, flags, desc, measured):
  437. if flags & PAGEINFO_REG:
  438. type_ = 'REG'
  439. if flags & PAGEINFO_TCS:
  440. type_ = 'TCS'
  441. prot = ['-', '-', '-']
  442. if flags & PAGEINFO_R:
  443. prot[0] = 'R'
  444. if flags & PAGEINFO_W:
  445. prot[1] = 'W'
  446. if flags & PAGEINFO_X:
  447. prot[2] = 'X'
  448. prot = ''.join(prot)
  449. desc = '(' + desc + ')'
  450. if measured:
  451. desc += ' measured'
  452. if size == offs.PAGESIZE:
  453. print(" %016x [%s:%s] %s" % (addr, type_, prot, desc))
  454. else:
  455. print(" %016x-%016lx [%s:%s] %s" %
  456. (addr, addr + size, type_, prot, desc))
  457. def load_file(digest, file, offset, addr, filesize, memsize, desc, flags):
  458. # pylint: disable=too-many-arguments
  459. f_addr = rounddown(offset)
  460. m_addr = rounddown(addr)
  461. m_size = roundup(addr + memsize) - m_addr
  462. print_area(m_addr, m_size, flags, desc, True)
  463. for page in range(m_addr, m_addr + m_size, offs.PAGESIZE):
  464. start = page - m_addr + f_addr
  465. end = start + offs.PAGESIZE
  466. start_zero = b""
  467. if start < offset:
  468. if offset - start >= offs.PAGESIZE:
  469. start_zero = ZERO_PAGE
  470. else:
  471. start_zero = bytes(offset - start)
  472. end_zero = b""
  473. if end > offset + filesize:
  474. if end - offset - filesize >= offs.PAGESIZE:
  475. end_zero = ZERO_PAGE
  476. else:
  477. end_zero = bytes(end - offset - filesize)
  478. start += len(start_zero)
  479. end -= len(end_zero)
  480. if start < end:
  481. file.seek(start)
  482. data = file.read(end - start)
  483. else:
  484. data = b""
  485. if len(start_zero + data + end_zero) != offs.PAGESIZE:
  486. raise Exception("wrong calculation")
  487. include_page(digest, page, flags, start_zero + data + end_zero, True)
  488. for area in areas:
  489. if area.file:
  490. with open(area.file, 'rb') as file:
  491. if area.is_binary:
  492. loadcmds = get_loadcmds(area.file)
  493. if loadcmds:
  494. mapaddr = 0xffffffffffffffff
  495. for (offset, addr, filesize, memsize,
  496. prot) in loadcmds:
  497. if rounddown(addr) < mapaddr:
  498. mapaddr = rounddown(addr)
  499. baseaddr_ = area.addr - mapaddr
  500. for (offset, addr, filesize, memsize, prot) in loadcmds:
  501. flags = area.flags
  502. if prot & 4:
  503. flags = flags | PAGEINFO_R
  504. if prot & 2:
  505. flags = flags | PAGEINFO_W
  506. if prot & 1:
  507. flags = flags | PAGEINFO_X
  508. if flags & PAGEINFO_X:
  509. desc = 'code'
  510. else:
  511. desc = 'data'
  512. load_file(mrenclave, file, offset, baseaddr_ + addr,
  513. filesize, memsize, desc, flags)
  514. else:
  515. load_file(mrenclave, file, 0, area.addr,
  516. os.stat(area.file).st_size, area.size,
  517. area.desc, area.flags)
  518. else:
  519. for addr in range(area.addr, area.addr + area.size, offs.PAGESIZE):
  520. data = ZERO_PAGE
  521. if area.content is not None:
  522. start = addr - area.addr
  523. end = start + offs.PAGESIZE
  524. data = area.content[start:end]
  525. include_page(mrenclave, addr, area.flags, data, area.measure)
  526. print_area(area.addr, area.size, area.flags, area.desc,
  527. area.measure)
  528. return mrenclave.digest()
  529. def generate_sigstruct(attr, args, mrenclave):
  530. '''Generate Sigstruct.
  531. field format: (offset, type, value)
  532. ''' # pylint: disable=too-many-locals
  533. fields = {
  534. 'header': (offs.SGX_ARCH_ENCLAVE_CSS_HEADER,
  535. "<4L", 0x00000006, 0x000000e1, 0x00010000, 0x00000000),
  536. 'module_vendor': (offs.SGX_ARCH_ENCLAVE_CSS_MODULE_VENDOR, "<L", 0x00000000),
  537. 'date': (offs.SGX_ARCH_ENCLAVE_CSS_DATE, "<HBB", attr['year'], attr['month'], attr['day']),
  538. 'header2': (offs.SGX_ARCH_ENCLAVE_CSS_HEADER2,
  539. "<4L", 0x00000101, 0x00000060, 0x00000060, 0x00000001),
  540. 'hw_version': (offs.SGX_ARCH_ENCLAVE_CSS_HW_VERSION, "<L", 0x00000000),
  541. 'misc_select': (offs.SGX_ARCH_ENCLAVE_CSS_MISC_SELECT, "4s", attr['misc_select']),
  542. 'misc_mask': (offs.SGX_ARCH_ENCLAVE_CSS_MISC_MASK, "4s", attr['misc_select']),
  543. 'attributes': (offs.SGX_ARCH_ENCLAVE_CSS_ATTRIBUTES, "8s8s", attr['flags'], attr['xfrms']),
  544. 'attribute_mask': (offs.SGX_ARCH_ENCLAVE_CSS_ATTRIBUTE_MASK,
  545. "8s8s", attr['flags'], attr['xfrms']),
  546. 'enclave_hash': (offs.SGX_ARCH_ENCLAVE_CSS_ENCLAVE_HASH, "32s", mrenclave),
  547. 'isv_prod_id': (offs.SGX_ARCH_ENCLAVE_CSS_ISV_PROD_ID, "<H", attr['isv_prod_id']),
  548. 'isv_svn': (offs.SGX_ARCH_ENCLAVE_CSS_ISV_SVN, "<H", attr['isv_svn']),
  549. }
  550. sign_buffer = bytearray(128 + 128)
  551. for field in fields.values():
  552. if field[0] >= offs.SGX_ARCH_ENCLAVE_CSS_MISC_SELECT:
  553. struct.pack_into(field[1], sign_buffer,
  554. field[0] - offs.SGX_ARCH_ENCLAVE_CSS_MISC_SELECT + 128,
  555. *field[2:])
  556. else:
  557. struct.pack_into(field[1], sign_buffer, field[0], *field[2:])
  558. proc = subprocess.Popen(
  559. ['openssl', 'rsa', '-modulus', '-in', args['key'], '-noout'],
  560. stdout=subprocess.PIPE)
  561. modulus_out, _ = proc.communicate()
  562. modulus = bytes.fromhex(modulus_out[8:8+offs.SE_KEY_SIZE*2].decode())
  563. modulus = bytes(reversed(modulus))
  564. proc = subprocess.Popen(
  565. ['openssl', 'sha256', '-binary', '-sign', args['key']],
  566. stdin=subprocess.PIPE, stdout=subprocess.PIPE)
  567. signature, _ = proc.communicate(sign_buffer)
  568. signature = signature[::-1]
  569. modulus_int = int.from_bytes(modulus, byteorder='little')
  570. signature_int = int.from_bytes(signature, byteorder='little')
  571. tmp1 = signature_int * signature_int
  572. q1_int = tmp1 // modulus_int
  573. tmp2 = tmp1 % modulus_int
  574. q2_int = tmp2 * signature_int // modulus_int
  575. q1 = q1_int.to_bytes(384, byteorder='little') # pylint: disable=invalid-name
  576. q2 = q2_int.to_bytes(384, byteorder='little') # pylint: disable=invalid-name
  577. fields.update({
  578. 'modulus': (offs.SGX_ARCH_ENCLAVE_CSS_MODULUS, "384s", modulus),
  579. 'exponent': (offs.SGX_ARCH_ENCLAVE_CSS_EXPONENT, "<L", 3),
  580. 'signature': (offs.SGX_ARCH_ENCLAVE_CSS_SIGNATURE, "384s", signature),
  581. 'q1': (offs.SGX_ARCH_ENCLAVE_CSS_Q1, "384s", q1),
  582. 'q2': (offs.SGX_ARCH_ENCLAVE_CSS_Q2, "384s", q2),
  583. })
  584. buffer = bytearray(offs.SGX_ARCH_ENCLAVE_CSS_SIZE)
  585. for field in fields.values():
  586. struct.pack_into(field[1], buffer, field[0], *field[2:])
  587. return buffer
  588. # Main Program
  589. argparser = argparse.ArgumentParser(
  590. epilog='With sign mode(without -depend), libpal and key are also required')
  591. argparser.add_argument('--output', '-output', metavar='OUTPUT',
  592. type=str, required=True,
  593. help='Output .manifest.sgx file '
  594. '(manifest augmented with autogenerated fields)')
  595. argparser.add_argument('--libpal', '-libpal', metavar='LIBPAL',
  596. type=str, required=False,
  597. help='Input libpal file '
  598. '(required as part of the enclave measurement)')
  599. argparser.add_argument('--key', '-key', metavar='KEY',
  600. type=str, required=False,
  601. help='specify signing key(.pem) file')
  602. argparser.add_argument('--manifest', '-manifest', metavar='MANIFEST',
  603. type=str, required=True,
  604. help='Input .manifest file '
  605. '(user-prepared manifest template)')
  606. argparser.add_argument('--exec', '-exec', metavar='EXEC',
  607. type=str, required=False,
  608. help='Input executable file '
  609. '(required as part of the enclave measurement)')
  610. argparser.add_argument('--depend', '-depend',
  611. action='store_true', required=False,
  612. help='Generate dependency for Makefile')
  613. def parse_args(args):
  614. args = argparser.parse_args(args)
  615. args_dict = {
  616. 'output': args.output,
  617. 'libpal': args.libpal,
  618. 'key': args.key,
  619. 'manifest': args.manifest,
  620. }
  621. if args.exec is not None:
  622. args_dict['exec'] = args.exec
  623. if args.depend:
  624. args_dict['depend'] = True
  625. else:
  626. # libpal and key are required
  627. if args.libpal is None or args.key is None:
  628. argparser.error("libpal and key are also required to sign")
  629. return None
  630. return args_dict
  631. def main_sign(args):
  632. # pylint: disable=too-many-statements,too-many-branches,too-many-locals
  633. manifest, manifest_layout = read_manifest(args['manifest'])
  634. if exec_sig_manifest(args, manifest) != 0:
  635. return 1
  636. # Get attributes from manifest
  637. attr = dict()
  638. parse_int = functools.partial(int, base=0)
  639. for key, default, parse, attr_key in [
  640. ('enclave_size', DEFAULT_ENCLAVE_SIZE, parse_size, 'enclave_size'),
  641. ('thread_num', str(DEFAULT_THREAD_NUM), parse_int, 'thread_num'),
  642. ('isvprodid', '0', parse_int, 'isv_prod_id'),
  643. ('isvsvn', '0', parse_int, 'isv_svn'),
  644. ]:
  645. attr[attr_key] = parse(manifest.setdefault('sgx.' + key, default))
  646. (attr['flags'], attr['xfrms'], attr['misc_select']) = get_enclave_attributes(manifest)
  647. today = datetime.date.today()
  648. attr['year'] = today.year
  649. attr['month'] = today.month
  650. attr['day'] = today.day
  651. print("Attributes:")
  652. print(" size: %d" % attr['enclave_size'])
  653. print(" thread_num: %d" % attr['thread_num'])
  654. print(" isv_prod_id: %d" % attr['isv_prod_id'])
  655. print(" isv_svn: %d" % attr['isv_svn'])
  656. print(" attr.flags: %016x" % int.from_bytes(attr['flags'], byteorder='big'))
  657. print(" attr.xfrm: %016x" % int.from_bytes(attr['xfrms'], byteorder='big'))
  658. print(" misc_select: %08x" % int.from_bytes(attr['misc_select'], byteorder='big'))
  659. print(" date: %d-%02d-%02d" % (attr['year'], attr['month'], attr['day']))
  660. # Check client info for remote attestation
  661. # (if sgx.ra_client.spid is provided)
  662. print("Attestation:")
  663. if 'sgx.ra_client_spid' in manifest and manifest['sgx.ra_client_spid']:
  664. print(" spid: " + manifest['sgx.ra_client_spid'])
  665. if 'sgx.ra_client_key' in manifest and manifest['sgx.ra_client_key']:
  666. print(" key: " + manifest['sgx.ra_client_key'])
  667. else:
  668. print(" *** sgx.ra_client_key not specified ***")
  669. return 1
  670. if 'sgx.ra_client_linkable' in manifest:
  671. print(" linkable: " + manifest['sgx.ra_client_linkable'])
  672. else:
  673. print(" linkable: 0")
  674. else:
  675. print(" *** Client info is not specified. Graphene will not perform"
  676. " remote attestation before execution. Please provide"
  677. " sgx.ra_client_spid and sgx.ra_client_key in the manifest. ***")
  678. # Get trusted checksums and measurements
  679. print("Trusted files:")
  680. for key, val in get_trusted_files(manifest, args).items():
  681. (uri, _, checksum) = val
  682. print(" %s %s" % (checksum, uri))
  683. manifest['sgx.trusted_checksum.' + key] = checksum
  684. print("Trusted children:")
  685. for key, val in get_trusted_children(manifest).items():
  686. (uri, _, mrenclave) = val
  687. print(" %s %s" % (mrenclave, uri))
  688. manifest['sgx.trusted_mrenclave.' + key] = mrenclave
  689. # Try populate memory areas
  690. memory_areas = get_memory_areas(attr, args)
  691. if manifest.get('sgx.static_address', None) is None:
  692. # If static_address is not specified explicitly, deduce from executable
  693. if any([a.addr is not None for a in memory_areas]):
  694. manifest['sgx.static_address'] = '1'
  695. else:
  696. global ENCLAVE_HEAP_MIN # pylint: disable=global-statement
  697. ENCLAVE_HEAP_MIN = 0
  698. manifest['sgx.static_address'] = '0'
  699. if manifest.get('sgx.allow_file_creation', None) is None:
  700. manifest['sgx.allow_file_creation'] = '0'
  701. output_manifest(args['output'], manifest, manifest_layout)
  702. memory_areas = [
  703. MemoryArea('manifest', file=args['output'],
  704. flags=PAGEINFO_R | PAGEINFO_REG)
  705. ] + memory_areas
  706. memory_areas = populate_memory_areas(attr, memory_areas)
  707. print("Memory:")
  708. # Generate measurement
  709. mrenclave = generate_measurement(attr, memory_areas)
  710. print("Measurement:")
  711. print(" %s" % mrenclave.hex())
  712. # Generate sigstruct
  713. open(args['sigfile'], 'wb').write(
  714. generate_sigstruct(attr, args, mrenclave))
  715. return 0
  716. def make_depend(args):
  717. manifest_file = args['manifest']
  718. output = args['output']
  719. (manifest, _) = read_manifest(manifest_file)
  720. if exec_sig_manifest(args, manifest) != 0:
  721. return 1
  722. dependencies = set()
  723. for filename in get_trusted_files(manifest, args, check_exist=False,
  724. do_checksum=False).values():
  725. dependencies.add(filename[1])
  726. for filename in get_trusted_children(manifest, check_exist=False,
  727. do_checksum=False).values():
  728. dependencies.add(filename[1])
  729. with open(output, 'w') as file:
  730. manifest_sgx = output
  731. if manifest_sgx.endswith('.d'):
  732. manifest_sgx = manifest_sgx[:-len('.d')]
  733. file.write('%s %s:' % (manifest_sgx, args['sigfile']))
  734. for filename in dependencies:
  735. file.write(' \\\n\t%s' % filename)
  736. file.write('\n')
  737. return 0
  738. def main(args=None):
  739. args = parse_args(args)
  740. if args is None:
  741. return 1
  742. if args.get('depend'):
  743. return make_depend(args)
  744. return main_sign(args)
  745. if __name__ == "__main__":
  746. sys.exit(main())