example_test.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. from __future__ import print_function
  2. import binascii
  3. import os
  4. import sys
  5. from collections import namedtuple
  6. from io import BytesIO
  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 = dut.app.partition_table['storage']['offset']
  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', 'aes_xts'])
  34. args = EncryptFlashDataArgs(BytesIO(), BytesIO(plain_data), flash_addr, BytesIO(b'\x00' * 32), 0xF, None)
  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. # The status of NVS encryption for the "nvs" partition
  50. 'NVS partition "nvs" is encrypted.'
  51. ]
  52. for line in lines:
  53. dut.expect(line, timeout=2)
  54. if __name__ == '__main__':
  55. test_examples_security_flash_encryption()