example_test.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. from __future__ import print_function
  2. import binascii
  3. from io import BytesIO
  4. from collections import namedtuple
  5. import os
  6. import sys
  7. import ttfw_idf
  8. try:
  9. import espsecure
  10. except ImportError:
  11. idf_path = os.getenv("IDF_PATH")
  12. if not idf_path or not os.path.exists(idf_path):
  13. raise
  14. sys.path.insert(0, os.path.join(idf_path, "components", "esptool_py", "esptool"))
  15. import espsecure
  16. # To prepare a test runner for this example:
  17. # 1. Generate zero flash encryption key:
  18. # dd if=/dev/zero of=key.bin bs=1 count=32
  19. # 2.Burn Efuses:
  20. # espefuse.py --do-not-confirm -p $ESPPORT burn_efuse FLASH_CRYPT_CONFIG 0xf
  21. # espefuse.py --do-not-confirm -p $ESPPORT burn_efuse FLASH_CRYPT_CNT 0x1
  22. # espefuse.py --do-not-confirm -p $ESPPORT burn_key flash_encryption key.bin
  23. @ttfw_idf.idf_example_test(env_tag='Example_Flash_Encryption')
  24. def test_examples_security_flash_encryption(env, extra_data):
  25. dut = env.get_dut('flash_encryption', 'examples/security/flash_encryption', dut_class=ttfw_idf.ESP32DUT)
  26. # start test
  27. dut.start_app()
  28. # calculate the expected ciphertext
  29. flash_addr = int(dut.app.partition_table["storage"]["offset"], 0)
  30. plain_hex_str = '00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f'
  31. plain_data = binascii.unhexlify(plain_hex_str.replace(' ', ''))
  32. # Emulate espsecure encrypt_flash_data command
  33. EncryptFlashDataArgs = namedtuple('EncryptFlashDataArgs', ['output', 'plaintext_file', 'address', 'keyfile', 'flash_crypt_conf'])
  34. args = EncryptFlashDataArgs(BytesIO(), BytesIO(plain_data), flash_addr, BytesIO(b'\x00' * 32), 0xF)
  35. espsecure.encrypt_flash_data(args)
  36. expected_ciphertext = args.output.getvalue()
  37. hex_ciphertext = binascii.hexlify(expected_ciphertext).decode('ascii')
  38. expected_str = (' '.join(hex_ciphertext[i:i + 2] for i in range(0, 16, 2)) + ' ' +
  39. ' '.join(hex_ciphertext[i:i + 2] for i in range(16, 32, 2)))
  40. lines = [
  41. 'FLASH_CRYPT_CNT eFuse value is 1',
  42. 'Flash encryption feature is enabled in DEVELOPMENT mode',
  43. 'with esp_partition_write',
  44. plain_hex_str,
  45. 'with esp_partition_read',
  46. plain_hex_str,
  47. 'with spi_flash_read',
  48. expected_str
  49. ]
  50. for line in lines:
  51. dut.expect(line, timeout=2)
  52. if __name__ == '__main__':
  53. test_examples_security_flash_encryption()