def test_parse_silabs_ebl(): list(validators.parse_silabs_ebl(VALID_EBL_IMAGE)) image = create_ebl_image([(b"AA", b"test"), (b"BB", b"foo" * 20)]) header, tag1, tag2, checksum = validators.parse_silabs_ebl(image) assert len(image) % 64 == 0 assert header[0] == b"\x00\x00" and len(header[1]) == 140 assert tag1 == (b"AA", b"test") assert tag2 == (b"BB", b"foo" * 20) assert checksum[0] == b"\xFC\x04" and len(checksum[1]) == 4 # Padding needs to be a multiple of 64 bytes with pytest.raises(ValidationError): list(validators.parse_silabs_ebl(image[:-1])) with pytest.raises(ValidationError): list(validators.parse_silabs_ebl(image + b"\xFF")) # Nothing can come after the padding assert list(validators.parse_silabs_ebl(image[:-1] + b"\xFF")) with pytest.raises(ValidationError): list(validators.parse_silabs_ebl(image[:-1] + b"\xAB")) # Truncated images are detected with pytest.raises(ValidationError): list( validators.parse_silabs_ebl(image[:image.index(b"test")] + b"\xFF" * 44)) # As are corrupted images of the correct length but with bad tag lengths with pytest.raises(ValidationError): index = image.index(b"test") bad_image = image[:index - 2] + b"\xFF\xFF" + image[index:] list(validators.parse_silabs_ebl(bad_image)) # Truncated but at a 64-byte boundary, missing CRC footer with pytest.raises(ValidationError): bad_image = create_ebl_image([(b"AA", b"test" * 11)]) bad_image = bad_image[:bad_image.rindex(b"test") + 4] list(validators.parse_silabs_ebl(bad_image)) # Corrupted images are detected corrupted_image = image.replace(b"foo", b"goo", 1) assert image != corrupted_image with pytest.raises(ValidationError): list(validators.parse_silabs_ebl(corrupted_image))
def create_ebl_image(tags): # All images start with a 140-byte "0x0000" header tags = [(b"\x00\x00", b"jklm" * 35)] + tags assert all([len(tag) == 2 for tag, value in tags]) image = b"".join(tag + len(value).to_bytes(2, "big") + value for tag, value in tags) # And end with a checksum image += b"\xFC\x04\x00\x04" + zlib.crc32(image + b"\xFC\x04\x00\x04").to_bytes( 4, "little") if len(image) % 64 != 0: image += b"\xFF" * (64 - len(image) % 64) assert list(validators.parse_silabs_ebl(image)) return image