esp_local_ctrl.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. #!/usr/bin/env python
  2. #
  3. # SPDX-FileCopyrightText: 2018-2022 Espressif Systems (Shanghai) CO LTD
  4. # SPDX-License-Identifier: Apache-2.0
  5. #
  6. import argparse
  7. import asyncio
  8. import json
  9. import os
  10. import ssl
  11. import struct
  12. import sys
  13. import textwrap
  14. import proto_lc
  15. try:
  16. import esp_prov
  17. import security
  18. except ImportError:
  19. idf_path = os.environ['IDF_PATH']
  20. sys.path.insert(0, idf_path + '/components/protocomm/python')
  21. sys.path.insert(1, idf_path + '/tools/esp_prov')
  22. import esp_prov
  23. import security
  24. # Set this to true to allow exceptions to be thrown
  25. config_throw_except = False
  26. # Property types enum
  27. PROP_TYPE_TIMESTAMP = 0
  28. PROP_TYPE_INT32 = 1
  29. PROP_TYPE_BOOLEAN = 2
  30. PROP_TYPE_STRING = 3
  31. # Property flags enum
  32. PROP_FLAG_READONLY = (1 << 0)
  33. def prop_typestr(prop):
  34. if prop['type'] == PROP_TYPE_TIMESTAMP:
  35. return 'TIME(us)'
  36. elif prop['type'] == PROP_TYPE_INT32:
  37. return 'INT32'
  38. elif prop['type'] == PROP_TYPE_BOOLEAN:
  39. return 'BOOLEAN'
  40. elif prop['type'] == PROP_TYPE_STRING:
  41. return 'STRING'
  42. return 'UNKNOWN'
  43. def encode_prop_value(prop, value):
  44. try:
  45. if prop['type'] == PROP_TYPE_TIMESTAMP:
  46. return struct.pack('q', value)
  47. elif prop['type'] == PROP_TYPE_INT32:
  48. return struct.pack('i', value)
  49. elif prop['type'] == PROP_TYPE_BOOLEAN:
  50. return struct.pack('?', value)
  51. elif prop['type'] == PROP_TYPE_STRING:
  52. return bytes(value, encoding='latin-1')
  53. return value
  54. except struct.error as e:
  55. print(e)
  56. return None
  57. def decode_prop_value(prop, value):
  58. try:
  59. if prop['type'] == PROP_TYPE_TIMESTAMP:
  60. return struct.unpack('q', value)[0]
  61. elif prop['type'] == PROP_TYPE_INT32:
  62. return struct.unpack('i', value)[0]
  63. elif prop['type'] == PROP_TYPE_BOOLEAN:
  64. return struct.unpack('?', value)[0]
  65. elif prop['type'] == PROP_TYPE_STRING:
  66. return value.decode('latin-1')
  67. return value
  68. except struct.error as e:
  69. print(e)
  70. return None
  71. def str_to_prop_value(prop, strval):
  72. try:
  73. if prop['type'] == PROP_TYPE_TIMESTAMP:
  74. return int(strval)
  75. elif prop['type'] == PROP_TYPE_INT32:
  76. return int(strval)
  77. elif prop['type'] == PROP_TYPE_BOOLEAN:
  78. return bool(strval)
  79. elif prop['type'] == PROP_TYPE_STRING:
  80. return strval
  81. return strval
  82. except ValueError as e:
  83. print(e)
  84. return None
  85. def prop_is_readonly(prop):
  86. return (prop['flags'] & PROP_FLAG_READONLY) != 0
  87. def on_except(err):
  88. if config_throw_except:
  89. raise RuntimeError(err)
  90. else:
  91. print(err)
  92. def get_security(secver, pop=None, verbose=False):
  93. if secver == 1:
  94. return security.Security1(pop, verbose)
  95. elif secver == 0:
  96. return security.Security0(verbose)
  97. return None
  98. async def get_transport(sel_transport, service_name, check_hostname):
  99. try:
  100. tp = None
  101. if (sel_transport == 'http'):
  102. example_path = os.environ['IDF_PATH'] + '/examples/protocols/esp_local_ctrl'
  103. cert_path = example_path + '/main/certs/rootCA.pem'
  104. ssl_ctx = ssl.create_default_context(cafile=cert_path)
  105. ssl_ctx.check_hostname = check_hostname
  106. tp = esp_prov.transport.Transport_HTTP(service_name, ssl_ctx)
  107. elif (sel_transport == 'ble'):
  108. tp = esp_prov.transport.Transport_BLE(
  109. devname=service_name, service_uuid='0000ffff-0000-1000-8000-00805f9b34fb',
  110. nu_lookup={'esp_local_ctrl/version': '0001',
  111. 'esp_local_ctrl/session': '0002',
  112. 'esp_local_ctrl/control': '0003'}
  113. )
  114. await tp.connect(devname=service_name)
  115. return tp
  116. except RuntimeError as e:
  117. on_except(e)
  118. return None
  119. async def version_match(tp, protover, verbose=False):
  120. try:
  121. response = await tp.send_data('proto-ver', protover)
  122. if verbose:
  123. print('proto-ver response : ', response)
  124. # First assume this to be a simple version string
  125. if response.lower() == protover.lower():
  126. return True
  127. try:
  128. # Else interpret this as JSON structure containing
  129. # information with versions and capabilities of both
  130. # provisioning service and application
  131. info = json.loads(response)
  132. if info['prov']['ver'].lower() == protover.lower():
  133. return True
  134. except ValueError:
  135. # If decoding as JSON fails, it means that capabilities
  136. # are not supported
  137. return False
  138. except Exception as e:
  139. on_except(e)
  140. return None
  141. async def has_capability(tp, capability='none', verbose=False):
  142. # Note : default value of `capability` argument cannot be empty string
  143. # because protocomm_httpd expects non zero content lengths
  144. try:
  145. response = await tp.send_data('proto-ver', capability)
  146. if verbose:
  147. print('proto-ver response : ', response)
  148. try:
  149. # Interpret this as JSON structure containing
  150. # information with versions and capabilities of both
  151. # provisioning service and application
  152. info = json.loads(response)
  153. supported_capabilities = info['prov']['cap']
  154. if capability.lower() == 'none':
  155. # No specific capability to check, but capabilities
  156. # feature is present so return True
  157. return True
  158. elif capability in supported_capabilities:
  159. return True
  160. return False
  161. except ValueError:
  162. # If decoding as JSON fails, it means that capabilities
  163. # are not supported
  164. return False
  165. except RuntimeError as e:
  166. on_except(e)
  167. return False
  168. async def establish_session(tp, sec):
  169. try:
  170. response = None
  171. while True:
  172. request = sec.security_session(response)
  173. if request is None:
  174. break
  175. response = await tp.send_data('esp_local_ctrl/session', request)
  176. if (response is None):
  177. return False
  178. return True
  179. except RuntimeError as e:
  180. on_except(e)
  181. return None
  182. async def get_all_property_values(tp, security_ctx):
  183. try:
  184. props = []
  185. message = proto_lc.get_prop_count_request(security_ctx)
  186. response = await tp.send_data('esp_local_ctrl/control', message)
  187. count = proto_lc.get_prop_count_response(security_ctx, response)
  188. if count == 0:
  189. raise RuntimeError('No properties found!')
  190. indices = [i for i in range(count)]
  191. message = proto_lc.get_prop_vals_request(security_ctx, indices)
  192. response = await tp.send_data('esp_local_ctrl/control', message)
  193. props = proto_lc.get_prop_vals_response(security_ctx, response)
  194. if len(props) != count:
  195. raise RuntimeError('Incorrect count of properties!', len(props), count)
  196. for p in props:
  197. p['value'] = decode_prop_value(p, p['value'])
  198. return props
  199. except RuntimeError as e:
  200. on_except(e)
  201. return []
  202. async def set_property_values(tp, security_ctx, props, indices, values, check_readonly=False):
  203. try:
  204. if check_readonly:
  205. for index in indices:
  206. if prop_is_readonly(props[index]):
  207. raise RuntimeError('Cannot set value of Read-Only property')
  208. message = proto_lc.set_prop_vals_request(security_ctx, indices, values)
  209. response = await tp.send_data('esp_local_ctrl/control', message)
  210. return proto_lc.set_prop_vals_response(security_ctx, response)
  211. except RuntimeError as e:
  212. on_except(e)
  213. return False
  214. def desc_format(*args):
  215. desc = ''
  216. for arg in args:
  217. desc += textwrap.fill(replace_whitespace=False, text=arg) + '\n'
  218. return desc
  219. async def main():
  220. parser = argparse.ArgumentParser(add_help=False)
  221. parser = argparse.ArgumentParser(description='Control an ESP32 running esp_local_ctrl service')
  222. parser.add_argument('--version', dest='version', type=str,
  223. help='Protocol version', default='')
  224. parser.add_argument('--transport', dest='transport', type=str,
  225. help='transport i.e http or ble', default='http')
  226. parser.add_argument('--name', dest='service_name', type=str,
  227. help='BLE Device Name / HTTP Server hostname or IP', default='')
  228. parser.add_argument('--sec_ver', dest='secver', type=int, default=None,
  229. help=desc_format(
  230. 'Protocomm security scheme used by the provisioning service for secure '
  231. 'session establishment. Accepted values are :',
  232. '\t- 0 : No security',
  233. '\t- 1 : X25519 key exchange + AES-CTR encryption',
  234. '\t + Authentication using Proof of Possession (PoP)',
  235. 'In case device side application uses IDF\'s provisioning manager, '
  236. 'the compatible security version is automatically determined from '
  237. 'capabilities retrieved via the version endpoint'))
  238. parser.add_argument('--pop', dest='pop', type=str, default='',
  239. help=desc_format(
  240. 'This specifies the Proof of possession (PoP) when security scheme 1 '
  241. 'is used'))
  242. parser.add_argument('--dont-check-hostname', action='store_true',
  243. # If enabled, the certificate won't be rejected for hostname mismatch.
  244. # This option is hidden because it should be used only for testing purposes.
  245. help=argparse.SUPPRESS)
  246. parser.add_argument('-v', '--verbose', dest='verbose', help='increase output verbosity', action='store_true')
  247. args = parser.parse_args()
  248. if args.version != '':
  249. print(f'==== Esp_Ctrl Version: {args.version} ====')
  250. if args.service_name == '':
  251. args.service_name = 'my_esp_ctrl_device'
  252. if args.transport == 'http':
  253. args.service_name += '.local'
  254. obj_transport = await get_transport(args.transport, args.service_name, not args.dont_check_hostname)
  255. if obj_transport is None:
  256. raise RuntimeError('Failed to establish connection')
  257. # If security version not specified check in capabilities
  258. if args.secver is None:
  259. # First check if capabilities are supported or not
  260. if not await has_capability(obj_transport):
  261. print('Security capabilities could not be determined, please specify "--sec_ver" explicitly')
  262. raise ValueError('Invalid Security Version')
  263. # When no_sec is present, use security 0, else security 1
  264. args.secver = int(not await has_capability(obj_transport, 'no_sec'))
  265. print(f'==== Security Scheme: {args.secver} ====')
  266. if (args.secver != 0) and not await has_capability(obj_transport, 'no_pop'):
  267. if len(args.pop) == 0:
  268. print('---- Proof of Possession argument not provided ----')
  269. exit(2)
  270. elif len(args.pop) != 0:
  271. print('---- Proof of Possession will be ignored ----')
  272. args.pop = ''
  273. obj_security = get_security(args.secver, args.pop, args.verbose)
  274. if obj_security is None:
  275. raise ValueError('Invalid Security Version')
  276. if args.version != '':
  277. print('\n==== Verifying protocol version ====')
  278. if not await version_match(obj_transport, args.version, args.verbose):
  279. raise RuntimeError('Error in protocol version matching')
  280. print('==== Verified protocol version successfully ====')
  281. print('\n==== Starting Session ====')
  282. if not await establish_session(obj_transport, obj_security):
  283. print('Failed to establish session. Ensure that security scheme and proof of possession are correct')
  284. raise RuntimeError('Error in establishing session')
  285. print('==== Session Established ====')
  286. while True:
  287. properties = await get_all_property_values(obj_transport, obj_security)
  288. if len(properties) == 0:
  289. raise RuntimeError('Error in reading property value')
  290. print('\n==== Available Properties ====')
  291. print('{0: >4} {1: <16} {2: <10} {3: <16} {4: <16}'.format(
  292. 'S.N.', 'Name', 'Type', 'Flags', 'Value'))
  293. for i in range(len(properties)):
  294. print('[{0: >2}] {1: <16} {2: <10} {3: <16} {4: <16}'.format(
  295. i + 1, properties[i]['name'], prop_typestr(properties[i]),
  296. ['','Read-Only'][prop_is_readonly(properties[i])],
  297. str(properties[i]['value'])))
  298. select = 0
  299. while True:
  300. try:
  301. inval = input('\nSelect properties to set (0 to re-read, \'q\' to quit) : ')
  302. if inval.lower() == 'q':
  303. print('Quitting...')
  304. exit(0)
  305. invals = inval.split(',')
  306. selections = [int(val) for val in invals]
  307. if min(selections) < 0 or max(selections) > len(properties):
  308. raise ValueError('Invalid input')
  309. break
  310. except ValueError as e:
  311. print(str(e) + '! Retry...')
  312. if len(selections) == 1 and selections[0] == 0:
  313. continue
  314. set_values = []
  315. set_indices = []
  316. for select in selections:
  317. while True:
  318. inval = input('Enter value to set for property (' + properties[select - 1]['name'] + ') : ')
  319. value = encode_prop_value(properties[select - 1],
  320. str_to_prop_value(properties[select - 1], inval))
  321. if value is None:
  322. print('Invalid input! Retry...')
  323. continue
  324. break
  325. set_values += [value]
  326. set_indices += [select - 1]
  327. if not await set_property_values(obj_transport, obj_security, properties, set_indices, set_values):
  328. print('Failed to set values!')
  329. if __name__ == '__main__':
  330. asyncio.run(main())