configure_ds.py: Fix double quoted strings ( pre_hook check )

This commit is contained in:
Aditya Patwardhan
2021-01-22 12:11:04 +05:30
parent 79c23a1886
commit 7c11988d19

View File

@@ -29,14 +29,14 @@ from cryptography.utils import int_to_bytes
try: try:
import nvs_partition_gen as nvs_gen import nvs_partition_gen as nvs_gen
except ImportError: except ImportError:
idf_path = os.getenv("IDF_PATH") idf_path = os.getenv('IDF_PATH')
if not idf_path or not os.path.exists(idf_path): if not idf_path or not os.path.exists(idf_path):
raise Exception("IDF_PATH not found") raise Exception('IDF_PATH not found')
sys.path.insert(0, os.path.join(idf_path, "components", "nvs_flash", "nvs_partition_generator")) sys.path.insert(0, os.path.join(idf_path, 'components', 'nvs_flash', 'nvs_partition_generator'))
import nvs_partition_gen as nvs_gen import nvs_partition_gen as nvs_gen
# Check python version is proper or not to avoid script failure # Check python version is proper or not to avoid script failure
assert sys.version_info >= (3, 6, 0), "Python version too low." assert sys.version_info >= (3, 6, 0), 'Python version too low.'
esp_ds_data_dir = 'esp_ds_data' esp_ds_data_dir = 'esp_ds_data'
# hmac_key_file is generated when HMAC_KEY is calculated, it is used when burning HMAC_KEY to efuse # hmac_key_file is generated when HMAC_KEY is calculated, it is used when burning HMAC_KEY to efuse
@@ -59,7 +59,7 @@ def get_idf_target():
idf_target_read = sdkconfig['IDF_TARGET'] idf_target_read = sdkconfig['IDF_TARGET']
return idf_target_read return idf_target_read
else: else:
print("ERROR: IDF_TARGET has not been set for the supported targets," print('ERROR: IDF_TARGET has not been set for the supported targets,'
"\nplase execute command \"idf.py set-target {TARGET}\" in the example directory") "\nplase execute command \"idf.py set-target {TARGET}\" in the example directory")
return None return None
@@ -96,10 +96,10 @@ def number_as_bytes(number, pad_bits=None):
def calculate_ds_parameters(privkey, priv_key_pass, hmac_key, idf_target): def calculate_ds_parameters(privkey, priv_key_pass, hmac_key, idf_target):
private_key = load_privatekey(privkey, priv_key_pass) private_key = load_privatekey(privkey, priv_key_pass)
if not isinstance(private_key, rsa.RSAPrivateKey): if not isinstance(private_key, rsa.RSAPrivateKey):
print("ERROR: Only RSA private keys are supported") print('ERROR: Only RSA private keys are supported')
sys.exit(-1) sys.exit(-1)
if hmac_key is None: if hmac_key is None:
print("ERROR: hmac_key cannot be None") print('ERROR: hmac_key cannot be None')
sys.exit(-2) sys.exit(-2)
priv_numbers = private_key.private_numbers() priv_numbers = private_key.private_numbers()
@@ -108,7 +108,7 @@ def calculate_ds_parameters(privkey, priv_key_pass, hmac_key, idf_target):
M = pub_numbers.n M = pub_numbers.n
key_size = private_key.key_size key_size = private_key.key_size
if key_size not in supported_key_size[idf_target]: if key_size not in supported_key_size[idf_target]:
print("ERROR: Private key size {0} not supported for the target {1},\nthe supported key sizes are {2}" print('ERROR: Private key size {0} not supported for the target {1},\nthe supported key sizes are {2}'
.format(key_size, idf_target, str(supported_key_size[idf_target]))) .format(key_size, idf_target, str(supported_key_size[idf_target])))
sys.exit(-1) sys.exit(-1)
@@ -122,12 +122,12 @@ def calculate_ds_parameters(privkey, priv_key_pass, hmac_key, idf_target):
# get max supported key size for the respective target # get max supported key size for the respective target
max_len = max(supported_key_size[idf_target]) max_len = max(supported_key_size[idf_target])
aes_key = hmac.HMAC(hmac_key, b"\xFF" * 32, hashlib.sha256).digest() aes_key = hmac.HMAC(hmac_key, b'\xFF' * 32, hashlib.sha256).digest()
md_in = number_as_bytes(Y, max_len) + \ md_in = number_as_bytes(Y, max_len) + \
number_as_bytes(M, max_len) + \ number_as_bytes(M, max_len) + \
number_as_bytes(rinv, max_len) + \ number_as_bytes(rinv, max_len) + \
struct.pack("<II", mprime, length) + \ struct.pack('<II', mprime, length) + \
iv iv
# expected_len = max_len_Y + max_len_M + max_len_rinv + (mprime + length packed (8 bytes))+ iv (16 bytes) # expected_len = max_len_Y + max_len_M + max_len_rinv + (mprime + length packed (8 bytes))+ iv (16 bytes)
@@ -142,7 +142,7 @@ def calculate_ds_parameters(privkey, priv_key_pass, hmac_key, idf_target):
number_as_bytes(M, max_len) + \ number_as_bytes(M, max_len) + \
number_as_bytes(rinv, max_len) + \ number_as_bytes(rinv, max_len) + \
md + \ md + \
struct.pack("<II", mprime, length) + \ struct.pack('<II', mprime, length) + \
b'\x08' * 8 b'\x08' * 8
# expected_len = max_len_Y + max_len_M + max_len_rinv + md (32 bytes) + (mprime + length packed (8bytes)) + padding (8 bytes) # expected_len = max_len_Y + max_len_M + max_len_rinv + md (32 bytes) + (mprime + length packed (8bytes)) + padding (8 bytes)
@@ -158,7 +158,7 @@ def calculate_ds_parameters(privkey, priv_key_pass, hmac_key, idf_target):
# @info # @info
# The function makes use of the "espefuse.py" script to read the efuse summary # The function makes use of the "espefuse.py" script to read the efuse summary
def efuse_summary(args, idf_target): def efuse_summary(args, idf_target):
os.system("python $IDF_PATH/components/esptool_py/esptool/espefuse.py --chip {0} -p {1} summary".format(idf_target, (args.port))) os.system('python $IDF_PATH/components/esptool_py/esptool/espefuse.py --chip {0} -p {1} summary'.format(idf_target, (args.port)))
# @info # @info
@@ -172,9 +172,9 @@ def efuse_burn_key(args, idf_target):
# read protection will be enabled as the default behaviour of the command # read protection will be enabled as the default behaviour of the command
key_block_status = ' ' key_block_status = ' '
os.system("python $IDF_PATH/components/esptool_py/esptool/espefuse.py --chip {0} -p {1} burn_key " os.system('python $IDF_PATH/components/esptool_py/esptool/espefuse.py --chip {0} -p {1} burn_key '
"{2} {3} HMAC_DOWN_DIGITAL_SIGNATURE {4}" '{2} {3} HMAC_DOWN_DIGITAL_SIGNATURE {4}'
.format((idf_target), (args.port), ("BLOCK_KEY" + str(args.efuse_key_id)), (hmac_key_file), (key_block_status))) .format((idf_target), (args.port), ('BLOCK_KEY' + str(args.efuse_key_id)), (hmac_key_file), (key_block_status)))
# @info # @info
@@ -183,12 +183,12 @@ def efuse_burn_key(args, idf_target):
def generate_csv_file(c, iv, hmac_key_id, key_size, csv_file): def generate_csv_file(c, iv, hmac_key_id, key_size, csv_file):
with open(csv_file, 'wt', encoding='utf8') as f: with open(csv_file, 'wt', encoding='utf8') as f:
f.write("# This is a generated csv file containing required parameters for the Digital Signature operation\n") f.write('# This is a generated csv file containing required parameters for the Digital Signature operation\n')
f.write("key,type,encoding,value\nesp_ds_ns,namespace,,\n") f.write('key,type,encoding,value\nesp_ds_ns,namespace,,\n')
f.write("esp_ds_c,data,hex2bin,%s\n" % (c.hex())) f.write('esp_ds_c,data,hex2bin,%s\n' % (c.hex()))
f.write("esp_ds_iv,data,hex2bin,%s\n" % (iv.hex())) f.write('esp_ds_iv,data,hex2bin,%s\n' % (iv.hex()))
f.write("esp_ds_key_id,data,u8,%d\n" % (hmac_key_id)) f.write('esp_ds_key_id,data,u8,%d\n' % (hmac_key_id))
f.write("esp_ds_rsa_len,data,u16,%d\n" % (key_size)) f.write('esp_ds_rsa_len,data,u16,%d\n' % (key_size))
class DefineArgs(object): class DefineArgs(object):
@@ -219,8 +219,8 @@ def generate_nvs_partition(input_filename, output_filename):
def get_efuse_summary_json(args, idf_target): def get_efuse_summary_json(args, idf_target):
_efuse_summary = None _efuse_summary = None
try: try:
_efuse_summary = subprocess.check_output(("python $IDF_PATH/components/esptool_py/esptool/espefuse.py " _efuse_summary = subprocess.check_output(('python $IDF_PATH/components/esptool_py/esptool/espefuse.py '
"--chip {0} -p {1} summary --format json".format(idf_target, (args.port))), shell=True) '--chip {0} -p {1} summary --format json'.format(idf_target, (args.port))), shell=True)
except subprocess.CalledProcessError as e: except subprocess.CalledProcessError as e:
print((e.output).decode('UTF-8')) print((e.output).decode('UTF-8'))
sys.exit(-1) sys.exit(-1)
@@ -272,8 +272,8 @@ def configure_efuse_key_block(args, idf_target):
if new_hmac_key == hmac_key_read: if new_hmac_key == hmac_key_read:
print('Key was successfully written to the efuse (KEY BLOCK %1d)' % (args.efuse_key_id)) print('Key was successfully written to the efuse (KEY BLOCK %1d)' % (args.efuse_key_id))
else: else:
print("ERROR: Failed to burn the hmac key to efuse (KEY BLOCK %1d)," print('ERROR: Failed to burn the hmac key to efuse (KEY BLOCK %1d),'
"\nPlease execute the script again using a different key id" % (args.efuse_key_id)) '\nPlease execute the script again using a different key id' % (args.efuse_key_id))
return None return None
else: else:
# If the efuse key block is redable, then read the key from efuse block and use it for encrypting the RSA private key parameters. # If the efuse key block is redable, then read the key from efuse block and use it for encrypting the RSA private key parameters.
@@ -281,20 +281,20 @@ def configure_efuse_key_block(args, idf_target):
# value than "HMAC_DOWN_DIGITAL_SIGNATURE" then we cannot use it for DS operation # value than "HMAC_DOWN_DIGITAL_SIGNATURE" then we cannot use it for DS operation
if kb_readable is True: if kb_readable is True:
if efuse_summary_json[key_purpose]['value'] == 'HMAC_DOWN_DIGITAL_SIGNATURE': if efuse_summary_json[key_purpose]['value'] == 'HMAC_DOWN_DIGITAL_SIGNATURE':
print("Provided efuse key block (KEY BLOCK %1d) already contains a key with key_purpose=HMAC_DOWN_DIGITAL_SIGNATURE," print('Provided efuse key block (KEY BLOCK %1d) already contains a key with key_purpose=HMAC_DOWN_DIGITAL_SIGNATURE,'
"\nusing the same key for encrypting the private key data...\n" % (args.efuse_key_id)) '\nusing the same key for encrypting the private key data...\n' % (args.efuse_key_id))
hmac_key_read = efuse_summary_json[key_blk]['value'] hmac_key_read = efuse_summary_json[key_blk]['value']
hmac_key_read = bytes.fromhex(hmac_key_read) hmac_key_read = bytes.fromhex(hmac_key_read)
if args.keep_ds_data is True: if args.keep_ds_data is True:
with open(hmac_key_file, 'wb') as key_file: with open(hmac_key_file, 'wb') as key_file:
key_file.write(hmac_key_read) key_file.write(hmac_key_read)
else: else:
print("ERROR: Provided efuse key block ((KEY BLOCK %1d)) contains a key with key purpose different" print('ERROR: Provided efuse key block ((KEY BLOCK %1d)) contains a key with key purpose different'
"than HMAC_DOWN_DIGITAL_SIGNATURE,\nplease execute the script again with a different value of the efuse key id." % (args.efuse_key_id)) 'than HMAC_DOWN_DIGITAL_SIGNATURE,\nplease execute the script again with a different value of the efuse key id.' % (args.efuse_key_id))
return None return None
else: else:
print("ERROR: Provided efuse key block (KEY BLOCK %1d) is not readable and writeable," print('ERROR: Provided efuse key block (KEY BLOCK %1d) is not readable and writeable,'
"\nplease execute the script again with a different value of the efuse key id." % (args.efuse_key_id)) '\nplease execute the script again with a different value of the efuse key id.' % (args.efuse_key_id))
return None return None
# Return the hmac key read from the efuse # Return the hmac key read from the efuse
@@ -322,7 +322,7 @@ def main():
help='relative path to client private key') help='relative path to client private key')
parser.add_argument( parser.add_argument(
"--pwd", '--password', '--pwd', '--password',
dest='priv_key_pass', dest='priv_key_pass',
metavar='[password]', metavar='[password]',
help='the password associated with the private key') help='the password associated with the private key')
@@ -340,7 +340,7 @@ def main():
help='Provide the efuse key_id which contains/will contain HMAC_KEY, default is 1') help='Provide the efuse key_id which contains/will contain HMAC_KEY, default is 1')
parser.add_argument( parser.add_argument(
"--port", '-p', '--port', '-p',
dest='port', dest='port',
metavar='[port]', metavar='[port]',
required=True, required=True,
@@ -391,5 +391,5 @@ def main():
cleanup(args) cleanup(args)
if __name__ == "__main__": if __name__ == '__main__':
main() main()