def main(argv): options = myargs(argv) print("options={}".format(options)) if not options.s_hex_file and not options.ns_hex_file: print('Error: no files to sign') exit(1) tools = CySecureTools(options.device, options.policy_file) if options.s_hex_file: print('signing tfm_s image:', options.s_hex_file) tools.sign_image(options.s_hex_file, 1) # rename signed image to *_signed.hex name, ext = os.path.splitext(options.s_hex_file) s_hex_signed_file = name + '_signed' + ext try: move(options.s_hex_file, s_hex_signed_file) except IOError as e: print("Failed to copy file '{}' to '{}' ({})" .format(options.s_hex_file, s_hex_signed_file, e.message)) raise print('Signed TFM-S image:', s_hex_signed_file) if options.ns_hex_file: print('signing tfm_ns image:', options.ns_hex_file) tools.sign_image(options.ns_hex_file, 16) # rename signed image to *_signed.hex name, ext = os.path.splitext(options.ns_hex_file) ns_hex_signed_file = name + '_signed' + ext try: move(options.ns_hex_file, ns_hex_signed_file) except IOError as e: print("Failed to copy file '{}' to '{}' ({})" .format(options.ns_hex_file, ns_hex_signed_file, e.message)) raise print('Signed TFM-NS image:', ns_hex_signed_file) # for CM4, sign_image creates an unsigned copy of the image # named <image to sign>_cm4.hex. Delete it to avoid confusion. file_name = name + '_cm4' + ext if os.path.isfile(file_name): try: os.remove(file_name) except IOError: print("Could not erase '{}'" .format(file_name)) print('Done.')
import os from cysecuretools import CySecureTools from cysecuretools.execute import provision_device as prov_device # from cysecuretools.execute.sys_call import get_prov_details from cysecuretools.execute.programmer.programmer import ProgrammingTool from cysecuretools.execute.provisioning_lib.cyprov_pem import PemKey from OpenSSL import crypto, SSL cytools = CySecureTools('CY8CPROTO-064S2-SB', 'policy_single_stage_CM4_2m.json') def create_app_keys(): cytools.create_keys() def read_device_pub_key(): tool = ProgrammingTool.create(cytools.PROGRAMMING_TOOL) # Read Device Key and save if tool.connect(cytools.target_name): print('Reading public key from device') key = prov_device.read_public_key(tool, cytools.register_map) if not key: print('Error: Cannot read device public key.') return pub_key_json = 'device_pub_key.json' with open(pub_key_json, 'w') as json_file:
def main(argv): create_signing_keys = False options = myargs(argv) print("options: {}\r\n".format(options)) if not options.policy_file: options.policy_file = 'policy_multi_CM0_CM4_tfm_dev_certs.json' options.policy_file = os.path.join('policy', options.policy_file) answer = \ input('Policy file name was not provided, use default {}? (Y/n): ' .format(options.policy_file)) if answer == 'N' or answer == 'n': print("Please specify policy as a parameter: `-p <policy>`") exit(1) if not os.path.isfile(options.policy_file): print("Policy file {} doesn't exit.".format(options.policy_file)) exit(1) if not options.device: options.device = "cy8ckit-064s0s2-4343w" answer = input("\r\nDevice is not provided, use default {}? (Y/n): " .format(options.device)) if answer == 'N' or answer == 'n': print("Please specify device as a parameter: `-d <device>'") exit(1) # Create cysecuretools object global cytools cytools = CySecureTools(options.device, options.policy_file) if not options.serial_number: dev_serial_num = \ input("\r\nSelect unique device serial number for {} (digits only):\n" .format(cytools.target_name.upper())) if not dev_serial_num.isnumeric(): print('Error: device serial number not number') exit(1) else: dev_serial_num = options.serial_number # signing keys if not options.new_keys and not options.existing_keys: answer = \ input('\r\nDo you want to create a new set of keys (y/N): ') if answer == 'Y' or answer == 'y': print('Will create new keys.') create_signing_keys = True else: # TBD: check if the keys exist (open json, read keys) print('Will use existing keys.') else: if options.new_keys: create_signing_keys = True else: create_signing_keys = False print("\r\n") print("##################################################################") print("Current configuration:") print("Policy file: {}".format(options.policy_file)) print("Device: {}".format(options.device)) print("Serial Number: {}".format(dev_serial_num)) print("Create new signing keys: {}".format(create_signing_keys)) print("##################################################################") print("\r\n") print("!!! Make sure the board is in the DAPLink mode (Mode LED blinks at 2Hz) !!!") print("\r\n") if not options.force_reprov: answer = input('Reprovision the device. Are you sure? (y/N): ') if answer is not 'y' and answer is not 'Y': print('Reprovision skipped.') exit(1) if create_signing_keys == True: print('Creating new signing keys.') create_app_keys(overwrite=True) # invalidate SPE image in Flash so it won't run. ret = erase_flash(0x10000000, 0x1000) if ret != 0: exit(1) ret = read_device_pub_key() if ret != 0: exit(1) ret = generate_device_cert(dev_serial_num) if ret != 0: exit(1) create_provisioning_packet() re_provision_device(options.device, options.policy_file) exit(0)
def main(argv): options = myargs(argv) print("options: {}".format(options)) if not options.policy_path: options.policy_path = 'policy' tools = CySecureTools( options.target_name, options.policy_path + "/" + options.policy_file + '.json') if (options.toolchain == 'ARM'): fromelf_cmd = options.toolchain_path + "/bin/fromelf" app_elf_file = options.build_dir + "/" + options.app_name + ".elf" fromelf_result_dir = options.build_dir + "/" + "fromelf_result" # Check if gcc tools path is valid if (os.path.isdir(options.toolchain_path) == False): print("ERROR: 'ARM Compiler' tools folder not found in path: {}". format(options.toolchain_path)) exit(-1) # Check if elf is valid if (os.path.isfile(app_elf_file) == False): print("ERROR: ELF file not found in path: {}\r\n".format( app_elf_file)) exit(-1) # Split elf file into sections shell_cmd = [ fromelf_cmd, '--i32', '--output=' + fromelf_result_dir, app_elf_file ] ret = exec_shell_command(shell_cmd) if (ret != 0): exit(ret) em_eeprom_hex = fromelf_result_dir + "/" + ".cy_em_eeprom" app_hex_path = options.build_dir + '/' + options.app_name + '.hex' if (os.path.isfile(em_eeprom_hex) == True): sections_list = [ f for f in os.listdir(fromelf_result_dir) if os.path.isfile(os.path.join(fromelf_result_dir, f)) ] sections_list.remove('.cy_em_eeprom') flash = IntelHex() for section in sections_list: sect = IntelHex(fromelf_result_dir + "/" + section) flash.merge(sect, overlap='replace') flash.write_hex_file(app_hex_path, False) CM0_app_src_path = options.cm0_app_path + '/' + options.cm0_app_name + '.hex' CM0_app_dst_path = options.build_dir + '/' + options.cm0_app_name + '.hex' # CySecureTools Image ID for CM4 Applications is # 1) 1 for single-stage, # 2) 16 in case of multi-stage, # Image ID for CM0 Applications is always 1 if (options.core == "CM4"): if (options.secure_boot_stage == "single"): # Sign CM4 image tools.sign_image(app_hex_path, 1) else: # Sign CM4 image tools.sign_image(app_hex_path, 16) # Make a copy of CM0P app image in build folder shutil.copy2(CM0_app_src_path, CM0_app_dst_path) # Sign CM0 image tools.sign_image(CM0_app_dst_path, 1) # Merge CM0, CM4 into a single hex file ihex = IntelHex() ihex.padding = 0x00 ihex.loadfile(app_hex_path, 'hex') \ ihex.merge(IntelHex(CM0_app_dst_path), 'ignore') \ ihex.write_hex_file(app_hex_path, write_start_addr=False, byte_count=16) else: tools.sign_image(app_hex_path, 1) if (os.path.isfile(em_eeprom_hex) == True): # Add emulated EEPROM Section back flash = IntelHex(app_hex_path) eeprom = IntelHex(em_eeprom_hex) flash.merge(eeprom) flash.write_hex_file(app_hex_path, False) else: gcc_objcopy_eabi_cmd = options.toolchain_path + '/bin/arm-none-eabi-objcopy' app_elf_file = options.build_dir + "/" + options.app_name + ".elf" # Check if gcc tools path is valid if (os.path.isdir(options.toolchain_path) == False): print("ERROR: GCC tools folder not found in path: {}".format( options.toolchain_path)) exit(-1) # Check if elf is valid if (os.path.isfile(app_elf_file) == False): print("ERROR: ELF file not found in path: {}\r\n".format( app_elf_file)) exit(-1) # Strip away emulated EEPROM section from hex file before signing shell_cmd = [ gcc_objcopy_eabi_cmd, '-R', '.cy_em_eeprom', '-O', 'ihex', app_elf_file, options.build_dir + "/" + options.app_name + ".hex" ] ret = exec_shell_command(shell_cmd) if (ret != 0): exit(ret) # Store emulated eeprom section in a seperate hex file shell_cmd = [ gcc_objcopy_eabi_cmd, '-j', '.cy_em_eeprom', '-O', 'ihex', options.build_dir + "/" + options.app_name + ".elf", options.build_dir + "/em_eeprom.hex" ] ret = exec_shell_command(shell_cmd) if (ret != 0): exit(ret) app_hex_path = options.build_dir + '/' + options.app_name + '.hex' CM0_app_src_path = options.cm0_app_path + '/' + options.cm0_app_name + '.hex' CM0_app_dst_path = options.build_dir + '/' + options.cm0_app_name + '.hex' # CySecureTools Image ID for CM4 Applications is # 1) 1 for single-stage, # 2) 16 in case of multi-stage, # Image ID for CM0 Applications is always 1 if (options.core == "CM4"): if (options.secure_boot_stage == "single"): # Sign CM4 image tools.sign_image(app_hex_path, 1) else: # Sign CM4 image tools.sign_image(app_hex_path, 16) # Make a copy of CM0P app image in build folder shutil.copy2(CM0_app_src_path, CM0_app_dst_path) # Sign CM0 image tools.sign_image(CM0_app_dst_path, 1) # Merge CM0, CM4 into a single hex file ihex = IntelHex() ihex.padding = 0x00 ihex.loadfile(app_hex_path, 'hex') \ ihex.merge(IntelHex(CM0_app_dst_path), 'ignore') \ ihex.write_hex_file(app_hex_path, write_start_addr=False, byte_count=16) else: tools.sign_image(app_hex_path, 1) # Add emulated EEPROM Section back flash = IntelHex(app_hex_path) eeprom = IntelHex(options.build_dir + "/em_eeprom.hex") flash.merge(eeprom) flash.write_hex_file(app_hex_path, False) exit(0)
def main(argv): options = myargs(argv) print("options: {}\r\n".format(options)) if not options.policy_file: options.policy_file = 'policy_multi_img_CM0p_CM4_debug_2M.json' options.policy_file = os.path.join('policy', options.policy_file) answer = \ input('Policy file name was not provided, use default {}? (Y/n): ' .format(options.policy_file)) if answer == 'N' or answer == 'n': exit(1) if not os.path.isfile(options.policy_file): print("Policy file {} doesn't exit.".format(options.policy_file)) exit(1) if not options.device: options.device = "cys06xxa" answer = input("\r\nDevice is not provided, use default {}? (Y/n): " .format(options.device)) if answer == 'N' or answer == 'n': exit(1) # Create cysecuretools object global cytools cytools = CySecureTools(options.device, options.policy_file) # erase existing user images print("\r\nPlease make sure the board is in CMSIS-DAP mode (LED is on)") answer = input("and press any key") print("Erasing the user images...") ret, output = erase_user_images(options.oocd_path) if ret != 0: return 1 print("Wait while the board completes reboot...") time.sleep(5) print("\r\nPlease switch to DAP Link mode (LED is blinking)") input('and press any key when ready') print("Wait for 10 seconds while device is being enumareated...") time.sleep(10) # signing keys answer = \ input('\r\nDo you want to create a new set of keys (y/N): ') if answer == 'Y' or answer == 'y': print('Create new keys.') create_app_keys() else: # TBD: check if the keys exist (open json, read keys) print('Will use existing keys.') ret = read_device_pub_key() if ret != 0: return 1 ret = generate_device_cert() if ret != 0: return 1 create_provisioning_packet() ret = re_provision_device(options.device, options.policy_file) if ret != 0: return 1 print('\r\nSwitch back to the CMSIS-DAP mode (mode LED is on)') return 0
def main(ctx, target, policy, verbose, quiet, logfile_off, no_interactive_mode, skip_validation): """ Common options (e.g. -t, -p, -v, -q) are common for all commands and must precede them: \b cysecuretools -t <TARGET> -p <POLICY> <COMMAND> --<COMMAND_OPTION> \b For detailed help for command use: \b cysecuretools <COMMAND> --help \b For detailed description of using CySecureTools please refer to readme.md """ if quiet: LoggingConfigurator.disable_logging() elif verbose: LoggingConfigurator.set_logger_level(logging.DEBUG) ctx.ensure_object(dict) log_file = not logfile_off if require_target(): if 'init' in sys.argv: validate_init_cmd_args() policy_path = default_policy(target) log_file = False else: policy_path = policy.name if policy else None try: ctx.obj['TOOL'] = CySecureTools(target, policy_path, log_file, no_interactive_mode, skip_validation) except ValidationError: pass except Exception as e: logger.error(e) logger.debug(e, exc_info=True) else: if 'version' in sys.argv: if '--target' in sys.argv or '-t' in sys.argv: try: ctx.obj['TOOL'] = CySecureTools( target, log_file=log_file, skip_prompts=no_interactive_mode, skip_validation=skip_validation) except ValidationError: pass except Exception as e: logger.error(e) logger.debug(e, exc_info=True) else: try: ctx.obj['TOOL'] = CySecureTools( log_file=log_file, skip_prompts=no_interactive_mode, skip_validation=skip_validation) except Exception as e: logger.error(e) logger.debug(e, exc_info=True) exit(1)