pytest_simple_ota.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. # SPDX-FileCopyrightText: 2022 Espressif Systems (Shanghai) CO LTD
  2. # SPDX-License-Identifier: Unlicense OR CC0-1.0
  3. import http.server
  4. import multiprocessing
  5. import os
  6. import ssl
  7. import sys
  8. from typing import Tuple
  9. import pexpect
  10. import pytest
  11. from common_test_methods import get_env_config_variable, get_host_ip4_by_dest_ip
  12. from pytest_embedded import Dut
  13. server_cert = '-----BEGIN CERTIFICATE-----\n' \
  14. 'MIIDWDCCAkACCQCbF4+gVh/MLjANBgkqhkiG9w0BAQsFADBuMQswCQYDVQQGEwJJ\n'\
  15. 'TjELMAkGA1UECAwCTUgxDDAKBgNVBAcMA1BVTjEMMAoGA1UECgwDRVNQMQwwCgYD\n'\
  16. 'VQQLDANFU1AxDDAKBgNVBAMMA0VTUDEaMBgGCSqGSIb3DQEJARYLZXNwQGVzcC5j\n'\
  17. 'b20wHhcNMjEwNzEyMTIzNjI3WhcNNDEwNzA3MTIzNjI3WjBuMQswCQYDVQQGEwJJ\n'\
  18. 'TjELMAkGA1UECAwCTUgxDDAKBgNVBAcMA1BVTjEMMAoGA1UECgwDRVNQMQwwCgYD\n'\
  19. 'VQQLDANFU1AxDDAKBgNVBAMMA0VTUDEaMBgGCSqGSIb3DQEJARYLZXNwQGVzcC5j\n'\
  20. 'b20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDhxF/y7bygndxPwiWL\n'\
  21. 'SwS9LY3uBMaJgup0ufNKVhx+FhGQOu44SghuJAaH3KkPUnt6SOM8jC97/yQuc32W\n'\
  22. 'ukI7eBZoA12kargSnzdv5m5rZZpd+NznSSpoDArOAONKVlzr25A1+aZbix2mKRbQ\n'\
  23. 'S5w9o1N2BriQuSzd8gL0Y0zEk3VkOWXEL+0yFUT144HnErnD+xnJtHe11yPO2fEz\n'\
  24. 'YaGiilh0ddL26PXTugXMZN/8fRVHP50P2OG0SvFpC7vghlLp4VFM1/r3UJnvL6Oz\n'\
  25. '3ALc6dhxZEKQucqlpj8l1UegszQToopemtIj0qXTHw2+uUnkUyWIPjPC+wdOAoap\n'\
  26. 'rFTRAgMBAAEwDQYJKoZIhvcNAQELBQADggEBAItw24y565k3C/zENZlxyzto44ud\n'\
  27. 'IYPQXN8Fa2pBlLe1zlSIyuaA/rWQ+i1daS8nPotkCbWZyf5N8DYaTE4B0OfvoUPk\n'\
  28. 'B5uGDmbuk6akvlB5BGiYLfQjWHRsK9/4xjtIqN1H58yf3QNROuKsPAeywWS3Fn32\n'\
  29. '3//OpbWaClQePx6udRYMqAitKR+QxL7/BKZQsX+UyShuq8hjphvXvk0BW8ONzuw9\n'\
  30. 'RcoORxM0FzySYjeQvm4LhzC/P3ZBhEq0xs55aL2a76SJhq5hJy7T/Xz6NFByvlrN\n'\
  31. 'lFJJey33KFrAf5vnV9qcyWFIo7PYy2VsaaEjFeefr7q3sTFSMlJeadexW2Y=\n'\
  32. '-----END CERTIFICATE-----\n'
  33. server_key = '-----BEGIN PRIVATE KEY-----\n'\
  34. 'MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDhxF/y7bygndxP\n'\
  35. 'wiWLSwS9LY3uBMaJgup0ufNKVhx+FhGQOu44SghuJAaH3KkPUnt6SOM8jC97/yQu\n'\
  36. 'c32WukI7eBZoA12kargSnzdv5m5rZZpd+NznSSpoDArOAONKVlzr25A1+aZbix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GXMHuMWgQbSZeM1aFFhoMvlBO7yogBTKb4Ecpu9wI5e3Kan3Al\n'\
  52. 'pZYltuyf+VhP6XG3IMBEYdoNJyYhu+nzyEdMg8CwXg+8LC7FMis/Ve+o7aS5scgG\n'\
  53. '1to/N9DK/swCsdTRdzmc/ZDbVC+TuVsebFBGYZTyO5KgqLpezqaIQrTxAoGALFCU\n'\
  54. '10glO9MVyl9H3clap5v+MQ3qcOv/EhaMnw6L2N6WVT481tnxjW4ujgzrFcE4YuxZ\n'\
  55. 'hgwYu9TOCmeqopGwBvGYWLbj+C4mfSahOAs0FfXDoYazuIIGBpuv03UhbpB1Si4O\n'\
  56. 'rJDfRnuCnVWyOTkl54gKJ2OusinhjztBjcrV1XkCgYEA3qNi4uBsPdyz9BZGb/3G\n'\
  57. 'rOMSw0CaT4pEMTLZqURmDP/0hxvTk1polP7O/FYwxVuJnBb6mzDa0xpLFPTpIAnJ\n'\
  58. 'YXB8xpXU69QVh+EBbemdJWOd+zp5UCfXvb2shAeG3Tn/Dz4cBBMEUutbzP+or0nG\n'\
  59. 'vSXnRLaxQhooWm+IuX9SuBQ=\n'\
  60. '-----END PRIVATE KEY-----\n'
  61. def start_https_server(ota_image_dir: str, server_ip: str, server_port: int, server_file: str = None, key_file: str = None) -> None:
  62. os.chdir(ota_image_dir)
  63. if server_file is None:
  64. server_file = os.path.join(ota_image_dir, 'server_cert.pem')
  65. cert_file_handle = open(server_file, 'w+')
  66. cert_file_handle.write(server_cert)
  67. cert_file_handle.close()
  68. if key_file is None:
  69. key_file = os.path.join(ota_image_dir, 'server_key.pem')
  70. key_file_handle = open('server_key.pem', 'w+')
  71. key_file_handle.write(server_key)
  72. key_file_handle.close()
  73. httpd = http.server.HTTPServer((server_ip, server_port), http.server.SimpleHTTPRequestHandler)
  74. httpd.socket = ssl.wrap_socket(httpd.socket,
  75. keyfile=key_file,
  76. certfile=server_file, server_side=True)
  77. httpd.serve_forever()
  78. def check_sha256(sha256_expected: str, sha256_reported: str) -> None:
  79. print('sha256_expected: %s' % (sha256_expected))
  80. print('sha256_reported: %s' % (sha256_reported))
  81. if sha256_expected not in sha256_reported:
  82. raise ValueError('SHA256 mismatch')
  83. else:
  84. print('SHA256 expected and reported are the same')
  85. def calc_all_sha256(dut: Dut) -> Tuple[str, str]:
  86. bootloader_path = os.path.join(dut.app.binary_path, 'bootloader', 'bootloader.bin')
  87. sha256_bootloader = dut.app.get_sha256(bootloader_path)
  88. app_path = os.path.join(dut.app.binary_path, 'simple_ota.bin')
  89. sha256_app = dut.app.get_sha256(app_path)
  90. return str(sha256_bootloader), str(sha256_app)
  91. @pytest.mark.esp32
  92. @pytest.mark.esp32c3
  93. @pytest.mark.esp32s2
  94. @pytest.mark.esp32s3
  95. @pytest.mark.wifi_high_traffic
  96. def test_examples_protocol_simple_ota_example(dut: Dut) -> None:
  97. """
  98. steps: |
  99. 1. join AP/Ethernet
  100. 2. Fetch OTA image over HTTPS
  101. 3. Reboot with the new OTA image
  102. """
  103. sha256_bootloader, sha256_app = calc_all_sha256(dut)
  104. # Start server
  105. thread1 = multiprocessing.Process(target=start_https_server, args=(dut.app.binary_path, '0.0.0.0', 8000))
  106. thread1.daemon = True
  107. thread1.start()
  108. try:
  109. # start test
  110. dut.expect('Loaded app from partition at offset 0x10000', timeout=30)
  111. check_sha256(sha256_bootloader, str(dut.expect(r'SHA-256 for bootloader:\s+([a-f0-9]){64}')[0]))
  112. check_sha256(sha256_app, str(dut.expect(r'SHA-256 for current firmware:\s+([a-f0-9]){64}')[0]))
  113. # Parse IP address of STA
  114. if dut.app.sdkconfig.get('EXAMPLE_WIFI_SSID_PWD_FROM_STDIN') is True:
  115. env_name = 'wifi_high_traffic'
  116. dut.expect('Please input ssid password:')
  117. ap_ssid = get_env_config_variable(env_name, 'ap_ssid')
  118. ap_password = get_env_config_variable(env_name, 'ap_password')
  119. dut.write(f'{ap_ssid} {ap_password}')
  120. try:
  121. ip_address = dut.expect(r'IPv4 address: (\d+\.\d+\.\d+\.\d+)[^\d]', timeout=30)[1].decode()
  122. print('Connected to AP/Ethernet with IP: {}'.format(ip_address))
  123. except pexpect.exceptions.TIMEOUT:
  124. raise ValueError('ENV_TEST_FAILURE: Cannot connect to AP/Ethernet')
  125. host_ip = get_host_ip4_by_dest_ip(ip_address)
  126. dut.expect('Starting OTA example task', timeout=30)
  127. print('writing to device: {}'.format('https://' + host_ip + ':8000/simple_ota.bin'))
  128. dut.write('https://' + host_ip + ':8000/simple_ota.bin')
  129. dut.expect('OTA Succeed, Rebooting...', timeout=60)
  130. # after reboot
  131. dut.expect('Loaded app from partition at offset 0x110000', timeout=30)
  132. dut.expect('OTA example app_main start', timeout=10)
  133. finally:
  134. thread1.terminate()
  135. @pytest.mark.esp32
  136. @pytest.mark.esp32c3
  137. @pytest.mark.esp32s2
  138. @pytest.mark.esp32s3
  139. @pytest.mark.ethernet_ota
  140. @pytest.mark.parametrize('config', ['spiram',], indirect=True)
  141. def test_examples_protocol_simple_ota_example_ethernet_with_spiram_config(dut: Dut) -> None:
  142. """
  143. steps: |
  144. 1. join AP/Ethernet
  145. 2. Fetch OTA image over HTTPS
  146. 3. Reboot with the new OTA image
  147. """
  148. # Start server
  149. thread1 = multiprocessing.Process(target=start_https_server, args=(dut.app.binary_path, '0.0.0.0', 8000))
  150. thread1.daemon = True
  151. thread1.start()
  152. try:
  153. # start test
  154. dut.expect('Loaded app from partition at offset 0x10000', timeout=30)
  155. try:
  156. ip_address = dut.expect(r'IPv4 address: (\d+\.\d+\.\d+\.\d+)[^\d]', timeout=30)[1].decode()
  157. print('Connected to AP/Ethernet with IP: {}'.format(ip_address))
  158. except pexpect.exceptions.TIMEOUT:
  159. raise ValueError('ENV_TEST_FAILURE: Cannot connect to AP/Ethernet')
  160. host_ip = get_host_ip4_by_dest_ip(ip_address)
  161. dut.expect('Starting OTA example task', timeout=30)
  162. print('writing to device: {}'.format('https://' + host_ip + ':8000/simple_ota.bin'))
  163. dut.write('https://' + host_ip + ':8000/simple_ota.bin')
  164. dut.expect('OTA Succeed, Rebooting...', timeout=60)
  165. # after reboot
  166. dut.expect('Loaded app from partition at offset 0x110000', timeout=30)
  167. dut.expect('OTA example app_main start', timeout=10)
  168. finally:
  169. thread1.terminate()
  170. @pytest.mark.esp32
  171. @pytest.mark.esp32c3
  172. @pytest.mark.flash_encryption_wifi_high_traffic
  173. @pytest.mark.nightly_run
  174. @pytest.mark.parametrize('config', ['flash_enc_wifi',], indirect=True)
  175. @pytest.mark.parametrize('skip_autoflash', ['y'], indirect=True)
  176. def test_examples_protocol_simple_ota_example_with_flash_encryption_wifi(dut: Dut) -> None:
  177. """
  178. steps: |
  179. 1. join AP/Ethernet
  180. 2. Fetch OTA image over HTTPS
  181. 3. Reboot with the new OTA image
  182. """
  183. # start test
  184. # Erase flash
  185. dut.serial.erase_flash()
  186. dut.serial.flash()
  187. # Start server
  188. thread1 = multiprocessing.Process(target=start_https_server, args=(dut.app.binary_path, '0.0.0.0', 8000))
  189. thread1.daemon = True
  190. thread1.start()
  191. try:
  192. dut.expect('Loaded app from partition at offset 0x20000', timeout=30)
  193. dut.expect('Flash encryption mode is DEVELOPMENT', timeout=10)
  194. # Parse IP address of STA
  195. if dut.app.sdkconfig.get('EXAMPLE_WIFI_SSID_PWD_FROM_STDIN') is True:
  196. env_name = 'flash_encryption_wifi_high_traffic'
  197. dut.expect('Please input ssid password:')
  198. ap_ssid = get_env_config_variable(env_name, 'ap_ssid')
  199. ap_password = get_env_config_variable(env_name, 'ap_password')
  200. dut.write(f'{ap_ssid} {ap_password}')
  201. try:
  202. ip_address = dut.expect(r'IPv4 address: (\d+\.\d+\.\d+\.\d+)[^\d]', timeout=30)[1].decode()
  203. print('Connected to AP/Ethernet with IP: {}'.format(ip_address))
  204. except pexpect.exceptions.TIMEOUT:
  205. raise ValueError('ENV_TEST_FAILURE: Cannot connect to AP/Ethernet')
  206. host_ip = get_host_ip4_by_dest_ip(ip_address)
  207. dut.expect('Starting OTA example task', timeout=30)
  208. print('writing to device: {}'.format('https://' + host_ip + ':8000/simple_ota.bin'))
  209. dut.write('https://' + host_ip + ':8000/simple_ota.bin')
  210. dut.expect('OTA Succeed, Rebooting...', timeout=60)
  211. # after reboot
  212. dut.expect('Loaded app from partition at offset 0x120000', timeout=30)
  213. dut.expect('Flash encryption mode is DEVELOPMENT', timeout=10)
  214. dut.expect('OTA example app_main start', timeout=10)
  215. finally:
  216. thread1.terminate()
  217. @pytest.mark.esp32
  218. @pytest.mark.esp32c3
  219. @pytest.mark.esp32s2
  220. @pytest.mark.esp32s3
  221. @pytest.mark.ethernet_ota
  222. @pytest.mark.parametrize('config', ['on_update_no_sb_ecdsa',], indirect=True)
  223. def test_examples_protocol_simple_ota_example_with_verify_app_signature_on_update_no_secure_boot_ecdsa(dut: Dut) -> None:
  224. """
  225. steps: |
  226. 1. join AP/Ethernet
  227. 2. Fetch OTA image over HTTPS
  228. 3. Reboot with the new OTA image
  229. """
  230. sha256_bootloader, sha256_app = calc_all_sha256(dut)
  231. # Start server
  232. thread1 = multiprocessing.Process(target=start_https_server, args=(dut.app.binary_path, '0.0.0.0', 8000))
  233. thread1.daemon = True
  234. thread1.start()
  235. try:
  236. # start test
  237. dut.expect('Loaded app from partition at offset 0x20000', timeout=30)
  238. check_sha256(sha256_bootloader, str(dut.expect(r'SHA-256 for bootloader:\s+([a-f0-9]){64}')[0]))
  239. check_sha256(sha256_app, str(dut.expect(r'SHA-256 for current firmware:\s+([a-f0-9]){64}')[0]))
  240. try:
  241. ip_address = dut.expect(r'IPv4 address: (\d+\.\d+\.\d+\.\d+)[^\d]', timeout=30)[1].decode()
  242. print('Connected to AP/Ethernet with IP: {}'.format(ip_address))
  243. except pexpect.exceptions.TIMEOUT:
  244. raise ValueError('ENV_TEST_FAILURE: Cannot connect to AP/Ethernet')
  245. host_ip = get_host_ip4_by_dest_ip(ip_address)
  246. dut.expect('Starting OTA example task', timeout=30)
  247. print('writing to device: {}'.format('https://' + host_ip + ':8000/simple_ota.bin'))
  248. dut.write('https://' + host_ip + ':8000/simple_ota.bin')
  249. dut.expect('Writing to partition subtype 16 at offset 0x120000', timeout=20)
  250. dut.expect('Verifying image signature...', timeout=60)
  251. dut.expect('OTA Succeed, Rebooting...', timeout=60)
  252. # after reboot
  253. dut.expect('Loaded app from partition at offset 0x120000', timeout=20)
  254. dut.expect('OTA example app_main start', timeout=10)
  255. finally:
  256. thread1.terminate()
  257. @pytest.mark.esp32
  258. @pytest.mark.esp32c3
  259. @pytest.mark.esp32s2
  260. @pytest.mark.esp32s3
  261. @pytest.mark.ethernet_ota
  262. @pytest.mark.parametrize('config', ['on_update_no_sb_rsa',], indirect=True)
  263. def test_examples_protocol_simple_ota_example_with_verify_app_signature_on_update_no_secure_boot_rsa(dut: Dut) -> None:
  264. """
  265. steps: |
  266. 1. join AP/Ethernet
  267. 2. Fetch OTA image over HTTPS
  268. 3. Reboot with the new OTA image
  269. """
  270. sha256_bootloader, sha256_app = calc_all_sha256(dut)
  271. # Start server
  272. thread1 = multiprocessing.Process(target=start_https_server, args=(dut.app.binary_path, '0.0.0.0', 8000))
  273. thread1.daemon = True
  274. thread1.start()
  275. try:
  276. # start test
  277. dut.expect('Loaded app from partition at offset 0x20000', timeout=30)
  278. check_sha256(sha256_bootloader, str(dut.expect(r'SHA-256 for bootloader:\s+([a-f0-9]){64}')[0]))
  279. check_sha256(sha256_app, str(dut.expect(r'SHA-256 for current firmware:\s+([a-f0-9]){64}')[0]))
  280. try:
  281. ip_address = dut.expect(r'IPv4 address: (\d+\.\d+\.\d+\.\d+)[^\d]', timeout=30)[1].decode()
  282. print('Connected to AP/Ethernet with IP: {}'.format(ip_address))
  283. except pexpect.exceptions.TIMEOUT:
  284. raise ValueError('ENV_TEST_FAILURE: Cannot connect to AP/Ethernet')
  285. host_ip = get_host_ip4_by_dest_ip(ip_address)
  286. dut.expect('Starting OTA example task', timeout=30)
  287. print('writing to device: {}'.format('https://' + host_ip + ':8000/simple_ota.bin'))
  288. dut.write('https://' + host_ip + ':8000/simple_ota.bin')
  289. dut.expect('Writing to partition subtype 16 at offset 0x120000', timeout=20)
  290. dut.expect('Verifying image signature...', timeout=60)
  291. dut.expect('#0 app key digest == #0 trusted key digest', timeout=10)
  292. dut.expect('Verifying with RSA-PSS...', timeout=10)
  293. dut.expect('Signature verified successfully!', timeout=10)
  294. dut.expect('OTA Succeed, Rebooting...', timeout=60)
  295. # after reboot
  296. dut.expect('Loaded app from partition at offset 0x120000', timeout=20)
  297. dut.expect('OTA example app_main start', timeout=10)
  298. finally:
  299. thread1.terminate()
  300. if __name__ == '__main__':
  301. if sys.argv[2:]: # if two or more arguments provided:
  302. # Usage: example_test.py <image_dir> <server_port> [cert_di>]
  303. this_dir = os.path.dirname(os.path.realpath(__file__))
  304. bin_dir = os.path.join(this_dir, sys.argv[1])
  305. port = int(sys.argv[2])
  306. cert_dir = bin_dir if not sys.argv[3:] else os.path.join(this_dir, sys.argv[3]) # optional argument
  307. print('Starting HTTPS server at "https://:{}"'.format(port))
  308. start_https_server(bin_dir, '', port,
  309. server_file=os.path.join(cert_dir, 'ca_cert.pem'),
  310. key_file=os.path.join(cert_dir, 'ca_key.pem'))