configure_ds.py 16 KB

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