efivar.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. #!/usr/bin/env python3
  2. ## SPDX-License-Identifier: GPL-2.0-only
  3. #
  4. # EFI variable store utilities.
  5. #
  6. # (c) 2020 Paulo Alcantara <palcantara@suse.de>
  7. #
  8. import os
  9. import struct
  10. import uuid
  11. import time
  12. import zlib
  13. import argparse
  14. from OpenSSL import crypto
  15. # U-Boot variable store format (version 1)
  16. UBOOT_EFI_VAR_FILE_MAGIC = 0x0161566966456255
  17. # UEFI variable attributes
  18. EFI_VARIABLE_NON_VOLATILE = 0x1
  19. EFI_VARIABLE_BOOTSERVICE_ACCESS = 0x2
  20. EFI_VARIABLE_RUNTIME_ACCESS = 0x4
  21. EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS = 0x10
  22. EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS = 0x20
  23. EFI_VARIABLE_READ_ONLY = 1 << 31
  24. NV_BS = EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS
  25. NV_BS_RT = NV_BS | EFI_VARIABLE_RUNTIME_ACCESS
  26. NV_BS_RT_AT = NV_BS_RT | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS
  27. DEFAULT_VAR_ATTRS = NV_BS_RT
  28. # vendor GUIDs
  29. EFI_GLOBAL_VARIABLE_GUID = '8be4df61-93ca-11d2-aa0d-00e098032b8c'
  30. EFI_IMAGE_SECURITY_DATABASE_GUID = 'd719b2cb-3d3a-4596-a3bc-dad00e67656f'
  31. EFI_CERT_TYPE_PKCS7_GUID = '4aafd29d-68df-49ee-8aa9-347d375665a7'
  32. WIN_CERT_TYPE_EFI_GUID = 0x0ef1
  33. WIN_CERT_REVISION = 0x0200
  34. var_attrs = {
  35. 'NV': EFI_VARIABLE_NON_VOLATILE,
  36. 'BS': EFI_VARIABLE_BOOTSERVICE_ACCESS,
  37. 'RT': EFI_VARIABLE_RUNTIME_ACCESS,
  38. 'AT': EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS,
  39. 'RO': EFI_VARIABLE_READ_ONLY,
  40. 'AW': EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS,
  41. }
  42. var_guids = {
  43. 'EFI_GLOBAL_VARIABLE_GUID': EFI_GLOBAL_VARIABLE_GUID,
  44. 'EFI_IMAGE_SECURITY_DATABASE_GUID': EFI_IMAGE_SECURITY_DATABASE_GUID,
  45. }
  46. class EfiStruct:
  47. # struct efi_var_file
  48. var_file_fmt = '<QQLL'
  49. var_file_size = struct.calcsize(var_file_fmt)
  50. # struct efi_var_entry
  51. var_entry_fmt = '<LLQ16s'
  52. var_entry_size = struct.calcsize(var_entry_fmt)
  53. # struct efi_time
  54. var_time_fmt = '<H6BLh2B'
  55. var_time_size = struct.calcsize(var_time_fmt)
  56. # WIN_CERTIFICATE
  57. var_win_cert_fmt = '<L2H'
  58. var_win_cert_size = struct.calcsize(var_win_cert_fmt)
  59. # WIN_CERTIFICATE_UEFI_GUID
  60. var_win_cert_uefi_guid_fmt = var_win_cert_fmt+'16s'
  61. var_win_cert_uefi_guid_size = struct.calcsize(var_win_cert_uefi_guid_fmt)
  62. class EfiVariable:
  63. def __init__(self, size, attrs, time, guid, name, data):
  64. self.size = size
  65. self.attrs = attrs
  66. self.time = time
  67. self.guid = guid
  68. self.name = name
  69. self.data = data
  70. def calc_crc32(buf):
  71. return zlib.crc32(buf) & 0xffffffff
  72. class EfiVariableStore:
  73. def __init__(self, infile):
  74. self.infile = infile
  75. self.efi = EfiStruct()
  76. if os.path.exists(self.infile) and os.stat(self.infile).st_size > self.efi.var_file_size:
  77. with open(self.infile, 'rb') as f:
  78. buf = f.read()
  79. self._check_header(buf)
  80. self.ents = buf[self.efi.var_file_size:]
  81. else:
  82. self.ents = bytearray()
  83. def _check_header(self, buf):
  84. hdr = struct.unpack_from(self.efi.var_file_fmt, buf, 0)
  85. magic, crc32 = hdr[1], hdr[3]
  86. if magic != UBOOT_EFI_VAR_FILE_MAGIC:
  87. print("err: invalid magic number: %s"%hex(magic))
  88. exit(1)
  89. if crc32 != calc_crc32(buf[self.efi.var_file_size:]):
  90. print("err: invalid crc32: %s"%hex(crc32))
  91. exit(1)
  92. def _get_var_name(self, buf):
  93. name = ''
  94. for i in range(0, len(buf) - 1, 2):
  95. if not buf[i] and not buf[i+1]:
  96. break
  97. name += chr(buf[i])
  98. return ''.join([chr(x) for x in name.encode('utf_16_le') if x]), i + 2
  99. def _next_var(self, offs=0):
  100. size, attrs, time, guid = struct.unpack_from(self.efi.var_entry_fmt, self.ents, offs)
  101. data_fmt = str(size)+"s"
  102. offs += self.efi.var_entry_size
  103. name, namelen = self._get_var_name(self.ents[offs:])
  104. offs += namelen
  105. data = struct.unpack_from(data_fmt, self.ents, offs)[0]
  106. # offset to next 8-byte aligned variable entry
  107. offs = (offs + len(data) + 7) & ~7
  108. return EfiVariable(size, attrs, time, uuid.UUID(bytes_le=guid), name, data), offs
  109. def __iter__(self):
  110. self.offs = 0
  111. return self
  112. def __next__(self):
  113. if self.offs < len(self.ents):
  114. var, noffs = self._next_var(self.offs)
  115. self.offs = noffs
  116. return var
  117. else:
  118. raise StopIteration
  119. def __len__(self):
  120. return len(self.ents)
  121. def _set_var(self, guid, name_data, size, attrs, tsec):
  122. ent = struct.pack(self.efi.var_entry_fmt,
  123. size,
  124. attrs,
  125. tsec,
  126. uuid.UUID(guid).bytes_le)
  127. ent += name_data
  128. self.ents += ent
  129. def del_var(self, guid, name, attrs):
  130. offs = 0
  131. while offs < len(self.ents):
  132. var, loffs = self._next_var(offs)
  133. if var.name == name and str(var.guid) == guid:
  134. if var.attrs != attrs:
  135. print("err: attributes don't match")
  136. exit(1)
  137. self.ents = self.ents[:offs] + self.ents[loffs:]
  138. return
  139. offs = loffs
  140. print("err: variable not found")
  141. exit(1)
  142. def set_var(self, guid, name, data, size, attrs):
  143. offs = 0
  144. while offs < len(self.ents):
  145. var, loffs = self._next_var(offs)
  146. if var.name == name and str(var.guid) == guid:
  147. if var.attrs != attrs:
  148. print("err: attributes don't match")
  149. exit(1)
  150. # make room for updating var
  151. self.ents = self.ents[:offs] + self.ents[loffs:]
  152. break
  153. offs = loffs
  154. tsec = int(time.time()) if attrs & EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS else 0
  155. nd = name.encode('utf_16_le') + b"\x00\x00" + data
  156. # U-Boot variable format requires the name + data blob to be 8-byte aligned
  157. pad = ((len(nd) + 7) & ~7) - len(nd)
  158. nd += bytes([0] * pad)
  159. return self._set_var(guid, nd, size, attrs, tsec)
  160. def save(self):
  161. hdr = struct.pack(self.efi.var_file_fmt,
  162. 0,
  163. UBOOT_EFI_VAR_FILE_MAGIC,
  164. len(self.ents) + self.efi.var_file_size,
  165. calc_crc32(self.ents))
  166. with open(self.infile, 'wb') as f:
  167. f.write(hdr)
  168. f.write(self.ents)
  169. def parse_attrs(attrs):
  170. v = DEFAULT_VAR_ATTRS
  171. if attrs:
  172. v = 0
  173. for i in attrs.split(','):
  174. v |= var_attrs[i.upper()]
  175. return v
  176. def parse_data(val, vtype):
  177. if not val or not vtype:
  178. return None, 0
  179. fmt = { 'u8': '<B', 'u16': '<H', 'u32': '<L', 'u64': '<Q' }
  180. if vtype.lower() == 'file':
  181. with open(val, 'rb') as f:
  182. data = f.read()
  183. return data, len(data)
  184. if vtype.lower() == 'str':
  185. data = val.encode('utf-8')
  186. return data, len(data)
  187. if vtype.lower() == 'nil':
  188. return None, 0
  189. i = fmt[vtype.lower()]
  190. return struct.pack(i, int(val)), struct.calcsize(i)
  191. def parse_args(args):
  192. name = args.name
  193. attrs = parse_attrs(args.attrs)
  194. guid = args.guid if args.guid else EFI_GLOBAL_VARIABLE_GUID
  195. if name.lower() == 'db' or name.lower() == 'dbx':
  196. name = name.lower()
  197. guid = EFI_IMAGE_SECURITY_DATABASE_GUID
  198. attrs = NV_BS_RT_AT
  199. elif name.lower() == 'pk' or name.lower() == 'kek':
  200. name = name.upper()
  201. guid = EFI_GLOBAL_VARIABLE_GUID
  202. attrs = NV_BS_RT_AT
  203. data, size = parse_data(args.data, args.type)
  204. return guid, name, attrs, data, size
  205. def cmd_set(args):
  206. env = EfiVariableStore(args.infile)
  207. guid, name, attrs, data, size = parse_args(args)
  208. env.set_var(guid=guid, name=name, data=data, size=size, attrs=attrs)
  209. env.save()
  210. def print_var(var):
  211. print(var.name+':')
  212. print(" "+str(var.guid)+' '+''.join([x for x in var_guids if str(var.guid) == var_guids[x]]))
  213. print(" "+'|'.join([x for x in var_attrs if var.attrs & var_attrs[x]])+", DataSize = %s"%hex(var.size))
  214. hexdump(var.data)
  215. def cmd_print(args):
  216. env = EfiVariableStore(args.infile)
  217. if not args.name and not args.guid and not len(env):
  218. return
  219. found = False
  220. for var in env:
  221. if not args.name:
  222. if args.guid and args.guid != str(var.guid):
  223. continue
  224. print_var(var)
  225. found = True
  226. else:
  227. if args.name != var.name or (args.guid and args.guid != str(var.guid)):
  228. continue
  229. print_var(var)
  230. found = True
  231. if not found:
  232. print("err: variable not found")
  233. exit(1)
  234. def cmd_del(args):
  235. env = EfiVariableStore(args.infile)
  236. attrs = parse_attrs(args.attrs)
  237. guid = args.guid if args.guid else EFI_GLOBAL_VARIABLE_GUID
  238. env.del_var(guid, args.name, attrs)
  239. env.save()
  240. def pkcs7_sign(cert, key, buf):
  241. with open(cert, 'r') as f:
  242. crt = crypto.load_certificate(crypto.FILETYPE_PEM, f.read())
  243. with open(key, 'r') as f:
  244. pkey = crypto.load_privatekey(crypto.FILETYPE_PEM, f.read())
  245. PKCS7_BINARY = 0x80
  246. PKCS7_DETACHED = 0x40
  247. PKCS7_NOATTR = 0x100
  248. bio_in = crypto._new_mem_buf(buf)
  249. p7 = crypto._lib.PKCS7_sign(crt._x509, pkey._pkey, crypto._ffi.NULL, bio_in,
  250. PKCS7_BINARY|PKCS7_DETACHED|PKCS7_NOATTR)
  251. bio_out = crypto._new_mem_buf()
  252. crypto._lib.i2d_PKCS7_bio(bio_out, p7)
  253. return crypto._bio_to_string(bio_out)
  254. # UEFI 2.8 Errata B "8.2.2 Using the EFI_VARIABLE_AUTHENTICATION_2 descriptor"
  255. def cmd_sign(args):
  256. guid, name, attrs, data, _ = parse_args(args)
  257. attrs |= EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS
  258. efi = EfiStruct()
  259. tm = time.localtime()
  260. etime = struct.pack(efi.var_time_fmt,
  261. tm.tm_year, tm.tm_mon, tm.tm_mday,
  262. tm.tm_hour, tm.tm_min, tm.tm_sec,
  263. 0, 0, 0, 0, 0)
  264. buf = name.encode('utf_16_le') + uuid.UUID(guid).bytes_le + attrs.to_bytes(4, byteorder='little') + etime
  265. if data:
  266. buf += data
  267. sig = pkcs7_sign(args.cert, args.key, buf)
  268. desc = struct.pack(efi.var_win_cert_uefi_guid_fmt,
  269. efi.var_win_cert_uefi_guid_size + len(sig),
  270. WIN_CERT_REVISION,
  271. WIN_CERT_TYPE_EFI_GUID,
  272. uuid.UUID(EFI_CERT_TYPE_PKCS7_GUID).bytes_le)
  273. with open(args.outfile, 'wb') as f:
  274. if data:
  275. f.write(etime + desc + sig + data)
  276. else:
  277. f.write(etime + desc + sig)
  278. def main():
  279. ap = argparse.ArgumentParser(description='EFI variable store utilities')
  280. subp = ap.add_subparsers(help="sub-command help")
  281. printp = subp.add_parser('print', help='get/list EFI variables')
  282. printp.add_argument('--infile', '-i', required=True, help='file to save the EFI variables')
  283. printp.add_argument('--name', '-n', help='variable name')
  284. printp.add_argument('--guid', '-g', help='vendor GUID')
  285. printp.set_defaults(func=cmd_print)
  286. setp = subp.add_parser('set', help='set EFI variable')
  287. setp.add_argument('--infile', '-i', required=True, help='file to save the EFI variables')
  288. setp.add_argument('--name', '-n', required=True, help='variable name')
  289. setp.add_argument('--attrs', '-a', help='variable attributes (values: nv,bs,rt,at,ro,aw)')
  290. setp.add_argument('--guid', '-g', help="vendor GUID (default: %s)"%EFI_GLOBAL_VARIABLE_GUID)
  291. setp.add_argument('--type', '-t', help='variable type (values: file|u8|u16|u32|u64|str)')
  292. setp.add_argument('--data', '-d', help='data or filename')
  293. setp.set_defaults(func=cmd_set)
  294. delp = subp.add_parser('del', help='delete EFI variable')
  295. delp.add_argument('--infile', '-i', required=True, help='file to save the EFI variables')
  296. delp.add_argument('--name', '-n', required=True, help='variable name')
  297. delp.add_argument('--attrs', '-a', help='variable attributes (values: nv,bs,rt,at,ro,aw)')
  298. delp.add_argument('--guid', '-g', help="vendor GUID (default: %s)"%EFI_GLOBAL_VARIABLE_GUID)
  299. delp.set_defaults(func=cmd_del)
  300. signp = subp.add_parser('sign', help='sign time-based EFI payload')
  301. signp.add_argument('--cert', '-c', required=True, help='x509 certificate filename in PEM format')
  302. signp.add_argument('--key', '-k', required=True, help='signing certificate filename in PEM format')
  303. signp.add_argument('--name', '-n', required=True, help='variable name')
  304. signp.add_argument('--attrs', '-a', help='variable attributes (values: nv,bs,rt,at,ro,aw)')
  305. signp.add_argument('--guid', '-g', help="vendor GUID (default: %s)"%EFI_GLOBAL_VARIABLE_GUID)
  306. signp.add_argument('--type', '-t', required=True, help='variable type (values: file|u8|u16|u32|u64|str|nil)')
  307. signp.add_argument('--data', '-d', help='data or filename')
  308. signp.add_argument('--outfile', '-o', required=True, help='output filename of signed EFI payload')
  309. signp.set_defaults(func=cmd_sign)
  310. args = ap.parse_args()
  311. if hasattr(args, "func"):
  312. args.func(args)
  313. else:
  314. ap.print_help()
  315. def group(a, *ns):
  316. for n in ns:
  317. a = [a[i:i+n] for i in range(0, len(a), n)]
  318. return a
  319. def join(a, *cs):
  320. return [cs[0].join(join(t, *cs[1:])) for t in a] if cs else a
  321. def hexdump(data):
  322. toHex = lambda c: '{:02X}'.format(c)
  323. toChr = lambda c: chr(c) if 32 <= c < 127 else '.'
  324. make = lambda f, *cs: join(group(list(map(f, data)), 8, 2), *cs)
  325. hs = make(toHex, ' ', ' ')
  326. cs = make(toChr, ' ', '')
  327. for i, (h, c) in enumerate(zip(hs, cs)):
  328. print (' {:010X}: {:48} {:16}'.format(i * 16, h, c))
  329. if __name__ == '__main__':
  330. main()