configure_ds.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. #!/usr/bin/env python
  2. # SPDX-FileCopyrightText: 2020-2022 Espressif Systems (Shanghai) CO LTD
  3. # SPDX-License-Identifier: Apache-2.0
  4. import argparse
  5. import hashlib
  6. import hmac
  7. import json
  8. import os
  9. import struct
  10. import subprocess
  11. import sys
  12. from cryptography.hazmat.backends import default_backend
  13. from cryptography.hazmat.primitives import serialization
  14. from cryptography.hazmat.primitives.asymmetric import rsa
  15. from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
  16. from cryptography.utils import int_to_bytes
  17. try:
  18. import nvs_partition_gen as nvs_gen
  19. except ImportError:
  20. idf_path = os.getenv('IDF_PATH')
  21. if not idf_path or not os.path.exists(idf_path):
  22. raise Exception('IDF_PATH not found')
  23. sys.path.insert(0, os.path.join(idf_path, 'components', 'nvs_flash', 'nvs_partition_generator'))
  24. import nvs_partition_gen as nvs_gen
  25. # Check python version is proper or not to avoid script failure
  26. assert sys.version_info >= (3, 6, 0), 'Python version too low.'
  27. esp_ds_data_dir = 'esp_ds_data'
  28. # hmac_key_file is generated when HMAC_KEY is calculated, it is used when burning HMAC_KEY to efuse
  29. hmac_key_file = esp_ds_data_dir + '/hmac_key.bin'
  30. # csv and bin filenames are default filenames for nvs partition files created with this script
  31. csv_filename = esp_ds_data_dir + '/pre_prov.csv'
  32. bin_filename = esp_ds_data_dir + '/pre_prov.bin'
  33. expected_json_path = os.path.join('build', 'config', 'sdkconfig.json')
  34. # Targets supported by the script
  35. supported_targets = {'esp32s2', 'esp32c3', 'esp32s3'}
  36. supported_key_size = {'esp32s2':[1024, 2048, 3072, 4096], 'esp32c3':[1024, 2048, 3072], 'esp32s3':[1024, 2048, 3072, 4096]}
  37. # @return
  38. # on success idf_target - value of the IDF_TARGET read from build/config/sdkconfig.json
  39. # on failure None
  40. def get_idf_target():
  41. if os.path.exists(expected_json_path):
  42. sdkconfig = json.load(open(expected_json_path))
  43. idf_target_read = sdkconfig['IDF_TARGET']
  44. return idf_target_read
  45. else:
  46. print('ERROR: IDF_TARGET has not been set for the supported targets,'
  47. "\nplase execute command \"idf.py set-target {TARGET}\" in the example directory")
  48. return None
  49. def load_privatekey(key_file_path, password=None):
  50. key_file = open(key_file_path, 'rb')
  51. key = key_file.read()
  52. key_file.close()
  53. return serialization.load_pem_private_key(key, password=password, backend=default_backend())
  54. def number_as_bytes(number, pad_bits=None):
  55. """
  56. Given a number, format as a little endian array of bytes
  57. """
  58. result = int_to_bytes(number)[::-1]
  59. while pad_bits is not None and len(result) < (pad_bits // 8):
  60. result += b'\x00'
  61. return result
  62. # @return
  63. # c : ciphertext_c
  64. # iv : initialization vector
  65. # key_size : key size of the RSA private key in bytes.
  66. # @input
  67. # privkey : path to the RSA private key
  68. # priv_key_pass : path to the RSA privaete key password
  69. # hmac_key : HMAC key value ( to calculate DS params)
  70. # idf_target : The target chip for the script (e.g. esp32s2, esp32c3, esp32s3)
  71. # @info
  72. # The function calculates the encrypted private key parameters.
  73. # Consult the DS documentation (available for the ESP32-S2) in the esp-idf programming guide for more details about the variables and calculations.
  74. def calculate_ds_parameters(privkey, priv_key_pass, hmac_key, idf_target):
  75. private_key = load_privatekey(privkey, priv_key_pass)
  76. if not isinstance(private_key, rsa.RSAPrivateKey):
  77. print('ERROR: Only RSA private keys are supported')
  78. sys.exit(-1)
  79. if hmac_key is None:
  80. print('ERROR: hmac_key cannot be None')
  81. sys.exit(-2)
  82. priv_numbers = private_key.private_numbers()
  83. pub_numbers = private_key.public_key().public_numbers()
  84. Y = priv_numbers.d
  85. M = pub_numbers.n
  86. key_size = private_key.key_size
  87. if key_size not in supported_key_size[idf_target]:
  88. print('ERROR: Private key size {0} not supported for the target {1},\nthe supported key sizes are {2}'
  89. .format(key_size, idf_target, str(supported_key_size[idf_target])))
  90. sys.exit(-1)
  91. iv = os.urandom(16)
  92. rr = 1 << (key_size * 2)
  93. rinv = rr % pub_numbers.n
  94. mprime = - rsa._modinv(M, 1 << 32)
  95. mprime &= 0xFFFFFFFF
  96. length = key_size // 32 - 1
  97. # get max supported key size for the respective target
  98. max_len = max(supported_key_size[idf_target])
  99. aes_key = hmac.HMAC(hmac_key, b'\xFF' * 32, hashlib.sha256).digest()
  100. md_in = number_as_bytes(Y, max_len) + \
  101. number_as_bytes(M, max_len) + \
  102. number_as_bytes(rinv, max_len) + \
  103. struct.pack('<II', mprime, length) + \
  104. iv
  105. # expected_len = max_len_Y + max_len_M + max_len_rinv + (mprime + length packed (8 bytes))+ iv (16 bytes)
  106. expected_len = (max_len / 8) * 3 + 8 + 16
  107. assert len(md_in) == expected_len
  108. md = hashlib.sha256(md_in).digest()
  109. # In case of ESP32-S2
  110. # Y4096 || M4096 || Rb4096 || M_prime32 || LENGTH32 || MD256 || 0x08*8
  111. # In case of ESP32-C3
  112. # Y3072 || M3072 || Rb3072 || M_prime32 || LENGTH32 || MD256 || 0x08*8
  113. p = number_as_bytes(Y, max_len) + \
  114. number_as_bytes(M, max_len) + \
  115. number_as_bytes(rinv, max_len) + \
  116. md + \
  117. struct.pack('<II', mprime, length) + \
  118. b'\x08' * 8
  119. # expected_len = max_len_Y + max_len_M + max_len_rinv + md (32 bytes) + (mprime + length packed (8bytes)) + padding (8 bytes)
  120. expected_len = (max_len / 8) * 3 + 32 + 8 + 8
  121. assert len(p) == expected_len
  122. cipher = Cipher(algorithms.AES(aes_key), modes.CBC(iv), backend=default_backend())
  123. encryptor = cipher.encryptor()
  124. c = encryptor.update(p) + encryptor.finalize()
  125. return c, iv, key_size
  126. # @info
  127. # The function makes use of the "espefuse.py" script to read the efuse summary
  128. def efuse_summary(args, idf_target):
  129. os.system('python $IDF_PATH/components/esptool_py/esptool/espefuse.py --chip {0} -p {1} summary'.format(idf_target, (args.port)))
  130. # @info
  131. # The function makes use of the "espefuse.py" script to burn the HMAC key on the efuse.
  132. def efuse_burn_key(args, idf_target):
  133. # In case of a development (default) usecase we disable the read protection.
  134. key_block_status = '--no-read-protect'
  135. if args.production is True:
  136. # Whitespace character will have no additional effect on the command and
  137. # read protection will be enabled as the default behaviour of the command
  138. key_block_status = ' '
  139. os.system('python $IDF_PATH/components/esptool_py/esptool/espefuse.py --chip {0} -p {1} burn_key '
  140. '{2} {3} HMAC_DOWN_DIGITAL_SIGNATURE {4}'
  141. .format((idf_target), (args.port), ('BLOCK_KEY' + str(args.efuse_key_id)), (hmac_key_file), (key_block_status)))
  142. # @info
  143. # Generate a custom csv file of encrypted private key parameters.
  144. # The csv file is required by the nvs_partition_generator utility to create the nvs partition.
  145. def generate_csv_file(c, iv, hmac_key_id, key_size, csv_file):
  146. with open(csv_file, 'wt', encoding='utf8') as f:
  147. f.write('# This is a generated csv file containing required parameters for the Digital Signature operation\n')
  148. f.write('key,type,encoding,value\nesp_ds_ns,namespace,,\n')
  149. f.write('esp_ds_c,data,hex2bin,%s\n' % (c.hex()))
  150. f.write('esp_ds_iv,data,hex2bin,%s\n' % (iv.hex()))
  151. f.write('esp_ds_key_id,data,u8,%d\n' % (hmac_key_id))
  152. f.write('esp_ds_rsa_len,data,u16,%d\n' % (key_size))
  153. class DefineArgs(object):
  154. def __init__(self, attributes):
  155. for key, value in attributes.items():
  156. self.__setattr__(key, value)
  157. # @info
  158. # This function uses the nvs_partition_generater utility
  159. # to generate the nvs partition of the encrypted private key parameters.
  160. def generate_nvs_partition(input_filename, output_filename):
  161. nvs_args = DefineArgs({
  162. 'input': input_filename,
  163. 'outdir': os.getcwd(),
  164. 'output': output_filename,
  165. 'size': hex(0x3000),
  166. 'version': 2,
  167. 'keyfile':None,
  168. })
  169. nvs_gen.generate(nvs_args, is_encr_enabled=False, encr_key=None)
  170. # @return
  171. # The json formatted summary of the efuse.
  172. def get_efuse_summary_json(args, idf_target):
  173. _efuse_summary = None
  174. try:
  175. _efuse_summary = subprocess.check_output(('python $IDF_PATH/components/esptool_py/esptool/espefuse.py '
  176. '--chip {0} -p {1} summary --format json'.format(idf_target, (args.port))), shell=True)
  177. except subprocess.CalledProcessError as e:
  178. print((e.output).decode('UTF-8'))
  179. sys.exit(-1)
  180. _efuse_summary = _efuse_summary.decode('UTF-8')
  181. # Remove everything before actual json data from efuse_summary command output.
  182. _efuse_summary = _efuse_summary[_efuse_summary.find('{'):]
  183. try:
  184. _efuse_summary_json = json.loads(_efuse_summary)
  185. except json.JSONDecodeError:
  186. print('ERROR: failed to parse the json output')
  187. sys.exit(-1)
  188. return _efuse_summary_json
  189. # @return
  190. # on success: 256 bit HMAC key present in the given key_block (args.efuse_key_id)
  191. # on failure: None
  192. # @info
  193. # This function configures the provided efuse key_block.
  194. # If the provided efuse key_block is empty the function generates a new HMAC key and burns it in the efuse key_block.
  195. # If the key_block already contains a key the function reads the key from the efuse key_block
  196. def configure_efuse_key_block(args, idf_target):
  197. efuse_summary_json = get_efuse_summary_json(args, idf_target)
  198. key_blk = 'BLOCK_KEY' + str(args.efuse_key_id)
  199. key_purpose = 'KEY_PURPOSE_' + str(args.efuse_key_id)
  200. kb_writeable = efuse_summary_json[key_blk]['writeable']
  201. kb_readable = efuse_summary_json[key_blk]['readable']
  202. hmac_key_read = None
  203. # If the efuse key block is writable (empty) then generate and write
  204. # the new hmac key and check again
  205. # If the efuse key block is not writable (already contains a key) then check if it is redable
  206. if kb_writeable is True:
  207. print('Provided key block (KEY BLOCK %1d) is writable\n Generating a new key and burning it in the efuse..\n' % (args.efuse_key_id))
  208. new_hmac_key = os.urandom(32)
  209. with open(hmac_key_file, 'wb') as key_file:
  210. key_file.write(new_hmac_key)
  211. # Burn efuse key
  212. efuse_burn_key(args, idf_target)
  213. if args.production is False:
  214. # Read fresh summary of the efuse to read the key value from efuse.
  215. # If the key read from efuse matches with the key generated
  216. # on host then burn_key operation was successfull
  217. new_efuse_summary_json = get_efuse_summary_json(args, idf_target)
  218. hmac_key_read = new_efuse_summary_json[key_blk]['value']
  219. print(hmac_key_read)
  220. hmac_key_read = bytes.fromhex(hmac_key_read)
  221. if new_hmac_key == hmac_key_read:
  222. print('Key was successfully written to the efuse (KEY BLOCK %1d)' % (args.efuse_key_id))
  223. else:
  224. print('ERROR: Failed to burn the hmac key to efuse (KEY BLOCK %1d),'
  225. '\nPlease execute the script again using a different key id' % (args.efuse_key_id))
  226. return None
  227. else:
  228. new_efuse_summary_json = get_efuse_summary_json(args, idf_target)
  229. if new_efuse_summary_json[key_purpose]['value'] != 'HMAC_DOWN_DIGITAL_SIGNATURE':
  230. print('ERROR: Failed to verify the key purpose of the key block{})'.format(args.efuse_key_id))
  231. return None
  232. hmac_key_read = new_hmac_key
  233. else:
  234. # If the efuse key block is redable, then read the key from efuse block and use it for encrypting the RSA private key parameters.
  235. # If the efuse key block is not redable or it has key purpose set to a different
  236. # value than "HMAC_DOWN_DIGITAL_SIGNATURE" then we cannot use it for DS operation
  237. if kb_readable is True:
  238. if efuse_summary_json[key_purpose]['value'] == 'HMAC_DOWN_DIGITAL_SIGNATURE':
  239. print('Provided efuse key block (KEY BLOCK %1d) already contains a key with key_purpose=HMAC_DOWN_DIGITAL_SIGNATURE,'
  240. '\nusing the same key for encrypting the private key data...\n' % (args.efuse_key_id))
  241. hmac_key_read = efuse_summary_json[key_blk]['value']
  242. hmac_key_read = bytes.fromhex(hmac_key_read)
  243. if args.keep_ds_data is True:
  244. with open(hmac_key_file, 'wb') as key_file:
  245. key_file.write(hmac_key_read)
  246. else:
  247. print('ERROR: Provided efuse key block ((KEY BLOCK %1d)) contains a key with key purpose different'
  248. 'than HMAC_DOWN_DIGITAL_SIGNATURE,\nplease execute the script again with a different value of the efuse key id.' % (args.efuse_key_id))
  249. return None
  250. else:
  251. print('ERROR: Provided efuse key block (KEY BLOCK %1d) is not readable and writeable,'
  252. '\nplease execute the script again with a different value of the efuse key id.' % (args.efuse_key_id))
  253. return None
  254. # Return the hmac key burned into the efuse
  255. return hmac_key_read
  256. def cleanup(args):
  257. if args.keep_ds_data is False:
  258. if os.path.exists(hmac_key_file):
  259. os.remove(hmac_key_file)
  260. if os.path.exists(csv_filename):
  261. os.remove(csv_filename)
  262. def main():
  263. parser = argparse.ArgumentParser(description='''Generate an HMAC key and burn it in the desired efuse key block (required for Digital Signature),
  264. Generates an NVS partition containing the encrypted private key parameters from the client private key.
  265. ''')
  266. parser.add_argument(
  267. '--private-key',
  268. dest='privkey',
  269. default='client.key',
  270. metavar='relative/path/to/client-priv-key',
  271. help='relative path to client private key')
  272. parser.add_argument(
  273. '--pwd', '--password',
  274. dest='priv_key_pass',
  275. metavar='[password]',
  276. help='the password associated with the private key')
  277. parser.add_argument(
  278. '--summary',
  279. dest='summary',action='store_true',
  280. help='Provide this option to print efuse summary of the chip')
  281. parser.add_argument(
  282. '--efuse_key_id',
  283. dest='efuse_key_id', type=int, choices=range(1,6),
  284. metavar='[key_id] ',
  285. default=1,
  286. help='Provide the efuse key_id which contains/will contain HMAC_KEY, default is 1')
  287. parser.add_argument(
  288. '--port', '-p',
  289. dest='port',
  290. metavar='[port]',
  291. required=True,
  292. help='UART com port to which the ESP device is connected')
  293. parser.add_argument(
  294. '--keep_ds_data_on_host','-keep_ds_data',
  295. dest='keep_ds_data', action='store_true',
  296. help='Keep encrypted private key data and key on host machine for testing purpose')
  297. parser.add_argument(
  298. '--production', '-prod',
  299. dest='production', action='store_true',
  300. help='Enable production configurations. e.g.keep efuse key block read protection enabled')
  301. args = parser.parse_args()
  302. idf_target = get_idf_target()
  303. if idf_target not in supported_targets:
  304. if idf_target is not None:
  305. print('ERROR: The script does not support the target %s' % idf_target)
  306. sys.exit(-1)
  307. idf_target = str(idf_target)
  308. if args.summary is not False:
  309. efuse_summary(args, idf_target)
  310. sys.exit(0)
  311. if (os.path.exists(args.privkey) is False):
  312. print('ERROR: The provided private key file does not exist')
  313. sys.exit(-1)
  314. if (os.path.exists(esp_ds_data_dir) is False):
  315. os.makedirs(esp_ds_data_dir)
  316. # Burn hmac_key on the efuse block (if it is empty) or read it
  317. # from the efuse block (if the efuse block already contains a key).
  318. hmac_key_read = configure_efuse_key_block(args, idf_target)
  319. if hmac_key_read is None:
  320. sys.exit(-1)
  321. # Calculate the encrypted private key data along with all other parameters
  322. c, iv, key_size = calculate_ds_parameters(args.privkey, args.priv_key_pass, hmac_key_read, idf_target)
  323. # Generate csv file for the DS data and generate an NVS partition.
  324. generate_csv_file(c, iv, args.efuse_key_id, key_size, csv_filename)
  325. generate_nvs_partition(csv_filename, bin_filename)
  326. cleanup(args)
  327. if __name__ == '__main__':
  328. main()