示例#1
0
def generate_trustzone_binary(tzm_conf: click.File) -> None:
    """Generate TrustZone binary from json configuration file."""
    config_data = load_configuration(tzm_conf.name)
    check_config(config_data, TrustZone.get_validation_schemas())
    trustzone = TrustZone.from_config(config_data)
    tz_data = trustzone.export()
    output_file = config_data["tzpOutputFile"]
    write_file(tz_data, output_file, mode="wb")
    click.echo(f"Success. (Trustzone binary: {output_file} created.)")
示例#2
0
def test_export_invalid(sample_tz_data):
    tz = TrustZone(family="lpc55xx",
                   tz_type=TrustZoneType.CUSTOM,
                   customizations=sample_tz_data)
    tz.presets = None
    with pytest.raises(SPSDKError, match="Preset data not present"):
        tz.export()
    tz = TrustZone(family="lpc55xx",
                   tz_type=TrustZoneType.CUSTOM,
                   customizations=sample_tz_data)
    tz.customs = None
    with pytest.raises(SPSDKError, match="Data not present"):
        tz.export()
示例#3
0
文件: elftosb.py 项目: saper/spsdk
def _get_trustzone(config: elftosb_helper.MasterBootImageConfig) -> TrustZone:
    """Create appropriate TrustZone instance."""
    if not config.trustzone_preset_file:
        return TrustZone.disabled()
    try:
        tz_config_data = json.loads(load_file(config.trustzone_preset_file))
        tz_config = elftosb_helper.TrustZoneConfig(tz_config_data)
        return TrustZone.custom(
            family=tz_config.family, revision=tz_config.revision, customizations=tz_config.presets
        )
    except ValueError:
        tz_raw_data = load_binary(config.trustzone_preset_file)
        return TrustZone.from_binary(
            family=config.family, revision=config.revision, raw_data=tz_raw_data
        )
示例#4
0
def test_signed_xip_multiple_certificates_invalid_input(data_dir):
    """Test invalid input for multiple certificates"""
    # indexed certificate is not specified
    der_file_names = ['selfsign_4096_v3.der.crt', 'selfsign_3072_v3.der.crt', 'selfsign_2048_v3.der.crt']
    with pytest.raises(IndexError):
        certificate_block(data_dir, der_file_names, 3)

    # indexed certificate is not specified
    der_file_names = ['selfsign_4096_v3.der.crt', None, 'selfsign_3072_v3.der.crt', 'selfsign_2048_v3.der.crt']
    with pytest.raises(ValueError):
        certificate_block(data_dir, der_file_names, 1)

    # public key in certificate and private key does not match
    der_file_names = ['selfsign_4096_v3.der.crt']
    cert_block = certificate_block(data_dir, der_file_names, 0)
    priv_key_pem_data = _load_private_key(data_dir, 'selfsign_privatekey_rsa2048.pem')
    with pytest.raises(ValueError):
        MasterBootImage(app=bytes(range(128)), load_addr=0, image_type=MasterBootImageType.SIGNED_XIP_IMAGE,
                        trust_zone=TrustZone.disabled(),
                        cert_block=cert_block, priv_key_pem_data=priv_key_pem_data).export()

    # chain of certificates does not match
    der_file_names = ['selfsign_4096_v3.der.crt']
    chain_certificates = ['ch3_crt2_v3.der.crt']
    with pytest.raises(ValueError):
        certificate_block(data_dir, der_file_names, 0, chain_certificates)
示例#5
0
def test_multiple_images_with_relocation_table(data_dir):
    """Test image that contains multiple binary images and relocation table
    :param data_dir: absolute path, where test data are located
    """
    with open(os.path.join(data_dir, 'multicore', "testfffffff.bin"),
              "rb") as f:
        img_data = f.read()
    with open(os.path.join(data_dir, 'multicore', "normal_boot.bin"),
              "rb") as f:
        img1_data = f.read()
    with open(os.path.join(data_dir, 'multicore', "special_boot.bin"),
              "rb") as f:
        img2_data = f.read()

    with open(os.path.join(data_dir, 'multicore', "rt5xxA0.json"), "rb") as f:
        trust_zone_data = json.loads(f.read())['trustZonePreset']

    table = MultipleImageTable()
    table.add_entry(MultipleImageEntry(img1_data, 0x80000))
    table.add_entry(MultipleImageEntry(img2_data, 0x80600))

    mbi = MasterBootImage(app=img_data,
                          app_table=table,
                          load_addr=0,
                          image_type=MasterBootImageType.CRC_RAM_IMAGE,
                          trust_zone=TrustZone.custom('rt5xx',
                                                      trust_zone_data))

    assert _compare_image(mbi, os.path.join(data_dir, 'multicore'),
                          'expected_output.bin')
示例#6
0
def test_ram_signed_keystore(data_dir: str, image_file_name: str, ram_addr: int) -> None:
    """Create signed load-to-RAM image with keys stored in key-store

    :param data_dir: absolute path with data files
    :param image_file_name: name of the input image file (including extension)
    :param ram_addr: address in RAM, where the image should be located
    """
    # read unsigned image (must be built without boot header)
    path = os.path.join(data_dir, INPUT_IMAGES_SUBDIR, image_file_name)
    org_data = load_binary(path)

    cert_block, priv_key_pem_data = create_cert_block(data_dir)

    key_store = get_keystore(data_dir)

    with open(os.path.join(data_dir, KEYSTORE_SUBDIR, 'userkey.txt'), 'r') as f:
        hmac_user_key = f.readline()

    mbi = MasterBootImage(app=org_data,
                          image_type=MasterBootImageType.SIGNED_RAM_IMAGE,
                          load_addr=ram_addr,
                          trust_zone=TrustZone.disabled(),
                          key_store=key_store,
                          cert_block=cert_block,
                          priv_key_pem_data=priv_key_pem_data,
                          hmac_key=hmac_user_key)

    out_image_file_name = image_file_name.replace('_unsigned.bin', '_signed_keystore.bin')
    write_image(data_dir, out_image_file_name, mbi.export())
示例#7
0
def generate_config_templates(family: str, output_folder: str) -> None:
    """Generate all possible configuration for selected family."""
    if not family:
        raise SPSDKError("The chip family must be specified.")

    templates: Dict[str, str] = {}
    # 1: Generate all configuration for MBI
    templates.update(mbi_generate_config_templates(family))
    # 2: Add TrustZone Configuration file
    templates.update(TrustZone.generate_config_template(family))
    # 3: Optionally add Secure Binary v3.1 Configuration file
    templates.update(SecureBinary31.generate_config_template(family))

    # And generate all config templates files
    for template in templates:
        file_name = f"{template}.yml"
        if os.path.isfile(output_folder):
            raise SPSDKError(f"The specified path {output_folder} is file.")
        if not os.path.isdir(output_folder):
            os.mkdir(output_folder)
        full_file_name = os.path.join(output_folder, file_name)
        if not os.path.isfile(full_file_name):
            click.echo(f"Creating {file_name} template file.")
            with open(full_file_name, "w") as f:
                f.write(templates[template])
        else:
            click.echo(f"Skip creating {file_name}, this file already exists.")
示例#8
0
def test_encrypted_ram_single_certificate_no_tz(data_dir,
                                                keysource: KeySourceType,
                                                keystore_fn: Optional[str],
                                                ctr_iv: str,
                                                expected_mbi: str):
    """Test encrypted image with fixed counter init vector"""
    with open(os.path.join(data_dir, 'testfffffff.bin'), "rb") as f:
        org_data = f.read()
    user_key = 'E39FD7AB61AE6DDDA37158A0FC3008C6D61100A03C7516EA1BE55A39F546BAD5'
    key_store_bin = None
    if keystore_fn:
        with open(os.path.join(data_dir, keystore_fn), "rb") as f:
            key_store_bin = f.read()
    key_store = KeyStore(keysource, key_store_bin)
    ctr_init_vector = bytes.fromhex(ctr_iv)
    # create certification block
    cert_block = certificate_block(data_dir, ['selfsign_2048_v3.der.crt'])
    priv_key_pem_data = _load_private_key(data_dir,
                                          'selfsign_privatekey_rsa2048.pem')

    mbi = MasterBootImage(app=org_data,
                          image_type=MasterBootImageType.ENCRYPTED_RAM_IMAGE,
                          load_addr=0x12345678,
                          trust_zone=TrustZone.disabled(),
                          cert_block=cert_block,
                          priv_key_pem_data=priv_key_pem_data,
                          hmac_key=user_key,
                          key_store=key_store,
                          ctr_init_vector=ctr_init_vector)

    assert _compare_image(mbi, data_dir, expected_mbi)
示例#9
0
def test_signed_xip_certificates_chain_no_tz(data_dir, der_certificates,
                                             chain_certificates, priv_key,
                                             expected_mbi):
    """Test signed image with multiple certificates, different key length
    :param data_dir: absolute path, where test data are located
    :param der_certificates: list of filenames of der root certificates
    :param chain_certificates: list of filenames of der cerificates
    :param priv_key: private key filename
    :param expected_mbi: filename of expected bootable image
    """
    with open(os.path.join(data_dir, 'testfffffff.bin'), "rb") as f:
        org_data = f.read()
    # create certification block
    cert_block = certificate_block(data_dir, der_certificates, 0,
                                   chain_certificates)
    priv_key_pem_data = _load_private_key(data_dir, priv_key)

    mbi = MasterBootImage(app=org_data,
                          load_addr=0,
                          image_type=MasterBootImageType.SIGNED_XIP_IMAGE,
                          trust_zone=TrustZone.disabled(),
                          cert_block=cert_block,
                          priv_key_pem_data=priv_key_pem_data)

    assert _compare_image(mbi, data_dir, expected_mbi)
示例#10
0
def test_ram_encrypted_otp(data_dir: str, image_file_name: str, ram_addr: int) -> None:
    """Test encrypted load-to-RAM image with key stored in OTP

    :param data_dir: absolute path with data files
    :param image_file_name: name of the input image file (including extension)
    :param ram_addr: address in RAM, where the image should be located
    """
    path = os.path.join(data_dir, INPUT_IMAGES_SUBDIR, image_file_name)
    org_data = load_binary(path)
    key_store = KeyStore(KeySourceType.OTP)

    cert_block, priv_key_pem_data = create_cert_block(data_dir)

    with open(os.path.join(data_dir, KEYSTORE_SUBDIR, 'userkey.txt'), 'r') as f:
        hmac_user_key = f.readline()

    mbi = MasterBootImage(app=org_data,
                          image_type=MasterBootImageType.ENCRYPTED_RAM_IMAGE,
                          load_addr=ram_addr,
                          trust_zone=TrustZone.disabled(),
                          cert_block=cert_block,
                          priv_key_pem_data=priv_key_pem_data,
                          hmac_key=hmac_user_key,
                          key_store=key_store,
                          ctr_init_vector=ENCR_CTR_IV)

    out_image_file_name = image_file_name.replace('_unsigned.bin', '_encr_otp.bin')
    write_image(data_dir, out_image_file_name, mbi.export())
示例#11
0
def test_signed_ram_single_certificate_no_tz(data_dir, user_key,
                                             key_store_filename, expected_mbi):
    """Test non-XIP signed image with single certificate
    :param data_dir: absolute path, where test data are located
    """
    with open(os.path.join(data_dir, 'testfffffff.bin'), "rb") as f:
        org_data = f.read()
    # create certification block
    cert_block = certificate_block(data_dir, ['selfsign_2048_v3.der.crt'])
    priv_key_pem_data = _load_private_key(data_dir,
                                          'selfsign_privatekey_rsa2048.pem')
    key_store = None
    if key_store_filename:
        with open(os.path.join(data_dir, key_store_filename), "rb") as f:
            key_store_bin = f.read()
        key_store = KeyStore(KeySourceType.KEYSTORE, key_store_bin)

    mbi = MasterBootImage(app=org_data,
                          image_type=MasterBootImageType.SIGNED_RAM_IMAGE,
                          load_addr=0x12345678,
                          trust_zone=TrustZone.disabled(),
                          cert_block=cert_block,
                          priv_key_pem_data=priv_key_pem_data,
                          hmac_key=user_key,
                          key_store=key_store)

    assert _compare_image(mbi, data_dir, expected_mbi)
示例#12
0
def test_multiple_images_with_relocation_table(data_dir):
    """Test image that contains multiple binary images and relocation table
    :param data_dir: absolute path, where test data are located
    """
    with open(os.path.join(data_dir, "multicore", "testfffffff.bin"),
              "rb") as f:
        img_data = f.read()
    with open(os.path.join(data_dir, "multicore", "normal_boot.bin"),
              "rb") as f:
        img1_data = f.read()
    with open(os.path.join(data_dir, "multicore", "special_boot.bin"),
              "rb") as f:
        img2_data = f.read()

    with open(os.path.join(data_dir, "multicore", "rt5xxA0.json"), "rb") as f:
        trust_zone_data = json.loads(f.read())["trustZonePreset"]

    table = MultipleImageTable()
    table.add_entry(MultipleImageEntry(img1_data, 0x80000))
    table.add_entry(MultipleImageEntry(img2_data, 0x80600))

    mbi = Mbi_CrcRamRtxxx(
        app=img_data,
        app_table=table,
        load_addr=0,
        trust_zone=TrustZone.custom("rt5xx", trust_zone_data),
    )

    assert _compare_image(mbi, os.path.join(data_dir, "multicore"),
                          "expected_output.bin")
示例#13
0
def test_ram_encrypted_keystore(data_dir: str, image_file_name: str,
                                ram_addr: int) -> None:
    """Test encrypted load-to-RAM image with key stored in key-store

    :param data_dir: absolute path with data files
    :param image_file_name: name of the input image file (including extension)
    :param ram_addr: address in RAM, where the image should be located
    """
    path = os.path.join(data_dir, INPUT_IMAGES_SUBDIR, image_file_name)
    org_data = load_binary(path)

    # load keystore with HMAC user key
    key_store = get_keystore(data_dir)

    cert_block, priv_key_pem_data = create_cert_block(data_dir)

    with open(os.path.join(data_dir, KEYSTORE_SUBDIR, "userkey.txt"),
              "r") as f:
        hmac_user_key = f.readline()

    mbi = Mbi_EncryptedRamRtxxx(
        app=org_data,
        load_addr=ram_addr,
        trust_zone=TrustZone.disabled(),
        cert_block=cert_block,
        priv_key_data=priv_key_pem_data,
        hmac_key=hmac_user_key,
        key_store=key_store,
        ctr_init_vector=ENCR_CTR_IV,
    )

    out_image_file_name = image_file_name.replace("_unsigned.bin",
                                                  "_encr_keystore.bin")
    write_image(data_dir, out_image_file_name, mbi.export())
示例#14
0
def test_invalid_export_mbi(data_dir):
    with open(os.path.join(data_dir, "testfffffff.bin"), "rb") as f:
        org_data = f.read()
    user_key = "E39FD7AB61AE6DDDA37158A0FC3008C6D61100A03C7516EA1BE55A39F546BAD5"
    key_store_bin = None
    key_store = KeyStore(KeySourceType.KEYSTORE, key_store_bin)
    cert_block = certificate_block(data_dir, ["selfsign_2048_v3.der.crt"])
    priv_key_pem_data = _load_private_key(data_dir,
                                          "selfsign_privatekey_rsa2048.pem")
    mbi = Mbi_EncryptedRamRtxxx(
        app=org_data,
        load_addr=0x12345678,
        trust_zone=TrustZone.disabled(),
        cert_block=cert_block,
        priv_key_data=priv_key_pem_data,
        hmac_key=user_key,
        key_store=key_store,
        ctr_init_vector=bytes(16),
    )
    mbi.priv_key_data = None
    with pytest.raises(SPSDKError):
        mbi.export()
    mbi.priv_key_data = priv_key_pem_data
    mbi.cert_block = None
    with pytest.raises(SPSDKError):
        mbi.export()
示例#15
0
def test_ram_signed_otp(data_dir: str, image_file_name: str,
                        ram_addr: int) -> None:
    """Create signed load-to-RAM image with keys stored in OTP

    :param data_dir: absolute path with data files
    :param image_file_name: name of the input image file (including extension)
    :param ram_addr: address in RAM, where the image should be located
    """
    # read unsigned image (must be built without boot header)
    path = os.path.join(data_dir, INPUT_IMAGES_SUBDIR, image_file_name)
    unsigned_img = load_binary(path)

    keystore = KeyStore(KeySourceType.OTP)

    cert_block, priv_key_pem_data = create_cert_block(data_dir)

    mbi = Mbi_PlainSignedRamRtxxx(
        app=unsigned_img,
        load_addr=ram_addr,
        key_store=keystore,
        hmac_key=MASTER_KEY,
        trust_zone=TrustZone.disabled(),
        cert_block=cert_block,
        priv_key_data=priv_key_pem_data,
    )

    out_image_file_name = image_file_name.replace("_unsigned.bin",
                                                  "_signed_otp.bin")
    write_image(data_dir, out_image_file_name, mbi.export())
示例#16
0
文件: elftosb.py 项目: saper/spsdk
def generate_trustzone_binary(tzm_conf: click.File) -> None:
    """Generate TrustZone binary from json configuration file."""
    config_data = json.load(tzm_conf)
    config = elftosb_helper.TrustZoneConfig(config_data)
    trustzone = TrustZone.custom(family=config.family, revision=config.revision, customizations=config.presets)
    tz_data = trustzone.export()
    with open(config.output_file, 'wb') as f:
        f.write(tz_data)
示例#17
0
def test_tz_incorrect_data(sample_tz_data):
    with pytest.raises(SPSDKError):
        TrustZone(
            family="lpc55xx",
            raw_data=bytes(4),
            tz_type=TrustZoneType.CUSTOM,
            customizations=sample_tz_data,
        )
示例#18
0
def generate_trustzone() -> None:
    """Generate custom trustzone presets.

    For this example we have only few settings in configuration file.
    The full set is available in `spsdk/data/tz_presets` folder
    """
    supperted_families = TrustZone().get_families()
    print("Supported families:")
    print("\n".join(supperted_families))

    with open(os.path.join(DATA_DIR, "lpc55xx_tz.json")) as config_file:
        config_data = json.load(config_file)

    tz_presets = TrustZone.custom(family="lpc55xx", customizations=config_data)
    tz_data = tz_presets.export()

    with open(os.path.join(THIS_DIR, "tz.bin"), "wb") as binary_file:
        binary_file.write(tz_data)
示例#19
0
def test_binary(data_dir, family, json_config, binary):
    with open(os.path.join(data_dir, json_config)) as json_config_file:
        json_config_data = json.load(json_config_file)

    with open(os.path.join(data_dir, binary), "rb") as binary_file:
        binary_data = binary_file.read()

    my_data = TrustZone(
        family=family,
        customizations=json_config_data["trustZonePreset"]).export()
    assert my_data == binary_data
示例#20
0
def test_plain_xip_crc_default_tz(data_dir, input_img, expected_mbi):
    """Test plain image with CRC and default TZ-M
    :param data_dir: absolute path, where test data are located
    :param input_img: file name of input image (binary)
    :param expected_mbi: file name of MBI image file with expected data
    """
    with open(os.path.join(data_dir, input_img), "rb") as f:
        org_data = f.read()

    mbi = MasterBootImage(app=org_data, load_addr=0, image_type=MasterBootImageType.CRC_XIP_IMAGE,
                          trust_zone=TrustZone.enabled())

    assert _compare_image(mbi, data_dir, expected_mbi)
示例#21
0
def test_encrypted_random_ctr_single_certificate_no_tz(data_dir):
    """Test encrypted image with random counter init vector"""
    with open(os.path.join(data_dir, 'testfffffff.bin'), "rb") as f:
        org_data = f.read()
    user_key = 'E39FD7AB61AE6DDDA37158A0FC3008C6D61100A03C7516EA1BE55A39F546BAD5'
    key_store = KeyStore(KeySourceType.KEYSTORE, None)
    cert_block = certificate_block(data_dir, ['selfsign_2048_v3.der.crt'])
    priv_key_pem_data = _load_private_key(data_dir, 'selfsign_privatekey_rsa2048.pem')
    mbi = MasterBootImage(app=org_data, image_type=MasterBootImageType.ENCRYPTED_RAM_IMAGE, load_addr=0x12345678,
                          trust_zone=TrustZone.disabled(),
                          cert_block=cert_block, priv_key_pem_data=priv_key_pem_data,
                          hmac_key=user_key, key_store=key_store)
    assert mbi.export()
    assert mbi.info()
示例#22
0
def test_plain_xip_crc_default_tz(data_dir, input_img, expected_mbi):
    """Test plain image with CRC and default TZ-M
    :param data_dir: absolute path, where test data are located
    :param input_img: file name of input image (binary)
    :param expected_mbi: file name of MBI image file with expected data
    """
    with open(os.path.join(data_dir, input_img), "rb") as f:
        org_data = f.read()

    mbi = Mbi_CrcXip(
        app=org_data,
        trust_zone=TrustZone.enabled(),
    )

    assert _compare_image(mbi, data_dir, expected_mbi)
示例#23
0
def test_master_boot_image_invalid_hmac(data_dir):
    with open(os.path.join(data_dir, "testfffffff.bin"), "rb") as f:
        org_data = f.read()
    user_key = "E39FD7AB61AE6DDDA37158A0FC3008C6D61100A03C7516EA1BE55A39F546BAD5"
    key_store = KeyStore(KeySourceType.KEYSTORE, None)
    cert_block = certificate_block(data_dir, ["selfsign_2048_v3.der.crt"])
    priv_key_pem_data = _load_private_key(data_dir, "selfsign_privatekey_rsa2048.pem")
    mbi = Mbi_EncryptedRamRtxxx(
        app=org_data,
        load_addr=0x12345678,
        trust_zone=TrustZone.disabled(),
        cert_block=cert_block,
        priv_key_data=priv_key_pem_data,
        hmac_key=user_key,
        key_store=key_store,
    )
    mbi.hmac_key = None
    assert mbi.compute_hmac(data=bytes(16)) == bytes()
示例#24
0
def test_signed_xip_single_certificate_no_tz(data_dir, priv_key, der_certificate, expected_mbi):
    """Test signed XIP image with single certificate, different key length
    :param data_dir: absolute path, where test data are located
    :param priv_key: filename of private key used for signing
    :param der_certificate: filename of corresponding certificate in DER format
    :param expected_mbi: filename of expected bootable image
    """
    with open(os.path.join(data_dir, 'testfffffff.bin'), "rb") as f:
        org_data = f.read()
    # create certification block
    cert_block = certificate_block(data_dir, [der_certificate])
    priv_key_pem_data = _load_private_key(data_dir, priv_key)

    mbi = MasterBootImage(app=org_data, load_addr=0, image_type=MasterBootImageType.SIGNED_XIP_IMAGE,
                          trust_zone=TrustZone.disabled(),
                          cert_block=cert_block, priv_key_pem_data=priv_key_pem_data)

    assert _compare_image(mbi, data_dir, expected_mbi)
示例#25
0
def test_encrypted_random_ctr_single_certificate_no_tz(data_dir):
    """Test encrypted image with random counter init vector"""
    with open(os.path.join(data_dir, "testfffffff.bin"), "rb") as f:
        org_data = f.read()
    user_key = "E39FD7AB61AE6DDDA37158A0FC3008C6D61100A03C7516EA1BE55A39F546BAD5"
    key_store = KeyStore(KeySourceType.KEYSTORE, None)
    cert_block = certificate_block(data_dir, ["selfsign_2048_v3.der.crt"])
    priv_key_pem_data = _load_private_key(data_dir, "selfsign_privatekey_rsa2048.pem")
    mbi = Mbi_EncryptedRamRtxxx(
        app=org_data,
        load_addr=0x12345678,
        trust_zone=TrustZone.disabled(),
        cert_block=cert_block,
        priv_key_data=priv_key_pem_data,
        hmac_key=user_key,
        key_store=key_store,
    )
    assert mbi.export()
示例#26
0
def test_plain_xip_crc_custom_tz(data_dir, input_img, tz_config, family, expected_mbi):
    """Test plain image with CRC and custom TZ-M
    :param data_dir: absolute path, where test data are located
    :param input_img: file name of input image (binary)
    :param tz_config: file name of trust-zone configuration JSON file
    :param family: identification of the processor for conversion of trust-zone data
    :param expected_mbi: file name of MBI image file with expected data
    """
    with open(os.path.join(data_dir, input_img), "rb") as f:
        org_data = f.read()
    with open(os.path.join(data_dir, expected_mbi), "rb") as f:
        expected_data = f.read()
    with open(os.path.join(data_dir, tz_config)) as f:
        tz_presets = json.load(f)["trustZonePreset"]

    mbi = MasterBootImage(app=org_data, load_addr=0, image_type=MasterBootImageType.CRC_XIP_IMAGE,
                          trust_zone=TrustZone(family=family, customizations=tz_presets))

    assert _compare_image(mbi, data_dir, expected_mbi)
示例#27
0
def test_base_info(data_dir):
    """Basic test for MasterBootImage - information """
    # plain image
    mbi = MasterBootImage(app=bytes(range(64)),
                          load_addr=0,
                          enable_hw_user_mode_keys=True)
    output = mbi.info()
    repr_strings = [
        "Master Boot Image", "Image type", "Image length", "TrustZone",
        'HW user mode keys'
    ]
    for req_string in repr_strings:
        assert req_string in output, f'string {req_string} is not in the output: {output}'
    # CRC image
    mbi = MasterBootImage(app=bytes(range(64)),
                          image_type=MasterBootImageType.CRC_RAM_IMAGE,
                          load_addr=0x1000)
    output = mbi.info()
    repr_strings = [
        "Master Boot Image", "Image type", "Image length", "TrustZone"
    ]
    for req_string in repr_strings:
        assert req_string in output, f'string {req_string} is not in the output: {output}'
    # signed image
    priv_key_pem_data = _load_private_key(data_dir, 'private_rsa4096.pem')
    cert_block = certificate_block(
        data_dir, ['selfsign_4096_v3.der.crt', 'selfsign_3072_v3.der.crt'], 0)
    mbi = MasterBootImage(app=bytes(range(64)),
                          load_addr=0x12345678,
                          image_type=MasterBootImageType.SIGNED_XIP_IMAGE,
                          trust_zone=TrustZone.custom(
                              "lpc55xx",
                              {"MPU Control Register.(cm33_mpu_ctrl)": "0x0"}),
                          cert_block=cert_block,
                          priv_key_pem_data=priv_key_pem_data)
    output = mbi.info()
    repr_strings = [
        "Master Boot Image", "Image type", "Image length", "TrustZone"
    ]
    for req_string in repr_strings:
        assert req_string in output, f'string {req_string} is not in the output: {output}'
示例#28
0
def test_errors(sample_tz_data):
    with pytest.raises(SPSDKError):
        TrustZone.custom(family="totaly_legit_family",
                         customizations=sample_tz_data)
    # throw error when TZ is disabled, but tz data are present
    with pytest.raises(SPSDKError):
        TrustZone(tz_type=TrustZoneType.DISABLED,
                  customizations=sample_tz_data)
    # throw error when TZ is set to CUSTOM but no data and no family are provided
    with pytest.raises(SPSDKError):
        TrustZone(tz_type=TrustZoneType.CUSTOM)
    # throw error when TZ is set to CUSTOM but no family is provided
    with pytest.raises(SPSDKError):
        TrustZone(tz_type=TrustZoneType.CUSTOM, customizations=sample_tz_data)
    # throw error when TZ is set to CUSTOM but no data are provided
    with pytest.raises(SPSDKError):
        TrustZone(tz_type=TrustZoneType.CUSTOM, family="lpc55xx")
    # throw error for invalid customization data
    with pytest.raises(SPSDKError):
        TrustZone(family="lpc55xx", customizations={"fake": "this is fake"})
    # throw error when TZ  type is custom and family is not set
    with pytest.raises(SPSDKError, match="Need to provide 'family' parameter"):
        TrustZone(tz_type=TrustZoneType.CUSTOM, family=None)
示例#29
0
def test_signed_xip_multiple_certificates_invalid_input(data_dir):
    """Test invalid input for multiple certificates"""
    # indexed certificate is not specified
    der_file_names = [
        "selfsign_4096_v3.der.crt",
        "selfsign_3072_v3.der.crt",
        "selfsign_2048_v3.der.crt",
    ]
    with pytest.raises(IndexError):
        certificate_block(data_dir, der_file_names, 3)

    # indexed certificate is not specified
    der_file_names = [
        "selfsign_4096_v3.der.crt",
        None,
        "selfsign_3072_v3.der.crt",
        "selfsign_2048_v3.der.crt",
    ]
    with pytest.raises(SPSDKError):
        certificate_block(data_dir, der_file_names, 1)

    # public key in certificate and private key does not match
    der_file_names = ["selfsign_4096_v3.der.crt"]
    cert_block = certificate_block(data_dir, der_file_names, 0)
    priv_key_pem_data = _load_private_key(data_dir,
                                          "selfsign_privatekey_rsa2048.pem")
    with pytest.raises(SPSDKError):
        Mbi_SignedXip(
            app=bytes(range(128)),
            trust_zone=TrustZone.disabled(),
            cert_block=cert_block,
            priv_key_data=priv_key_pem_data,
        ).export()

    # chain of certificates does not match
    der_file_names = ["selfsign_4096_v3.der.crt"]
    chain_certificates = ["ch3_crt2_v3.der.crt"]
    with pytest.raises(SPSDKError):
        certificate_block(data_dir, der_file_names, 0, chain_certificates)
示例#30
0
def test_errors(sample_tz_data):
    with pytest.raises(AssertionError):
        TrustZone.custom(family="totaly_legit_family",
                         customizations=sample_tz_data)
    # throw error when TZ is disabled, but tz data are present
    with pytest.raises(ValueError):
        TrustZone(tz_type=TrustZoneType.DISABLED,
                  customizations=sample_tz_data)
    # throw error when TZ is set to CUSTOM but no data and no family are provided
    with pytest.raises(AssertionError):
        TrustZone(tz_type=TrustZoneType.CUSTOM)

# throw error when TZ is set to CUSTOM but no family is provided
    with pytest.raises(AssertionError):
        TrustZone(tz_type=TrustZoneType.CUSTOM, customizations=sample_tz_data)
    # throw error when TZ is set to CUSTOM but no data are provided
    with pytest.raises(AssertionError):
        TrustZone(tz_type=TrustZoneType.CUSTOM, family="lpc55xx")
    # throw error for invalid customization data
    with pytest.raises(ValueError):
        TrustZone(family="lpc55xx", customizations={"fake": "this is fake"})