xap.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. """Interactions with compatible XAP devices
  2. """
  3. import json
  4. import random
  5. import gzip
  6. from platform import platform
  7. from milc import cli
  8. def _is_xap_usage(x):
  9. return x['usage_page'] == 0xFF51 and x['usage'] == 0x0058
  10. def _is_filtered_device(x):
  11. name = "%04x:%04x" % (x['vendor_id'], x['product_id'])
  12. return name.lower().startswith(cli.args.device.lower())
  13. def _search():
  14. devices = filter(_is_xap_usage, hid.enumerate())
  15. if cli.args.device:
  16. devices = filter(_is_filtered_device, devices)
  17. return list(devices)
  18. def print_dotted_output(kb_info_json, prefix=''):
  19. """Print the info.json in a plain text format with dot-joined keys.
  20. """
  21. for key in sorted(kb_info_json):
  22. new_prefix = f'{prefix}.{key}' if prefix else key
  23. if key in ['parse_errors', 'parse_warnings']:
  24. continue
  25. elif key == 'layouts' and prefix == '':
  26. cli.echo(' {fg_blue}layouts{fg_reset}: %s', ', '.join(sorted(kb_info_json['layouts'].keys())))
  27. elif isinstance(kb_info_json[key], dict):
  28. print_dotted_output(kb_info_json[key], new_prefix)
  29. elif isinstance(kb_info_json[key], list):
  30. data = kb_info_json[key]
  31. if len(data) and isinstance(data[0], dict):
  32. for index, item in enumerate(data, start=0):
  33. cli.echo(' {fg_blue}%s.%s{fg_reset}: %s', new_prefix, index, str(item))
  34. else:
  35. cli.echo(' {fg_blue}%s{fg_reset}: %s', new_prefix, ', '.join(sorted(map(str, data))))
  36. else:
  37. cli.echo(' {fg_blue}%s{fg_reset}: %s', new_prefix, kb_info_json[key])
  38. def _xap_transaction(device, sub, route, *args):
  39. # gen token
  40. tok = random.getrandbits(16)
  41. token = tok.to_bytes(2, byteorder='little')
  42. # send with padding
  43. # TODO: this code is total garbage
  44. args_data = []
  45. args_len = 2
  46. if len(args) == 1:
  47. if isinstance(args[0], (bytes, bytearray)):
  48. args_len += len(args[0])
  49. args_data = args[0]
  50. else:
  51. args_len += 2
  52. args_data = args[0].to_bytes(2, byteorder='little')
  53. padding_len = 64 - 3 - args_len
  54. padding = b"\x00" * padding_len
  55. if args_data:
  56. padding = args_data + padding
  57. buffer = token + args_len.to_bytes(1, byteorder='little') + sub.to_bytes(1, byteorder='little') + route.to_bytes(1, byteorder='little') + padding
  58. # prepend 0 on windows because reasons...
  59. if 'windows' in platform().lower():
  60. buffer = b"\x00" + buffer
  61. device.write(buffer)
  62. # get resp
  63. array_alpha = device.read(64, 100)
  64. # validate tok sent == resp
  65. if str(token) != str(array_alpha[:2]):
  66. return None
  67. if int(array_alpha[2]) != 0x01:
  68. return None
  69. payload_len = int(array_alpha[3])
  70. return array_alpha[4:4 + payload_len]
  71. def _query_device(device):
  72. ver_data = _xap_transaction(device, 0x00, 0x00)
  73. if not ver_data:
  74. return {'xap': 'UNKNOWN'}
  75. # to u32 to BCD string
  76. a = (ver_data[3] << 24) + (ver_data[2] << 16) + (ver_data[1] << 8) + (ver_data[0])
  77. ver = f'{a>>24}.{a>>16 & 0xFF}.{a & 0xFFFF}'
  78. secure = int.from_bytes(_xap_transaction(device, 0x00, 0x03), 'little')
  79. secure = 'unlocked' if secure == 2 else 'LOCKED'
  80. return {'xap': ver, 'secure': secure}
  81. def _query_device_info_len(device):
  82. len_data = _xap_transaction(device, 0x01, 0x05)
  83. if not len_data:
  84. return 0
  85. # to u32
  86. return (len_data[3] << 24) + (len_data[2] << 16) + (len_data[1] << 8) + (len_data[0])
  87. def _query_device_info_chunk(device, offset):
  88. return _xap_transaction(device, 0x01, 0x06, offset)
  89. def _query_device_info(device):
  90. datalen = _query_device_info_len(device)
  91. if not datalen:
  92. return {}
  93. data = []
  94. offset = 0
  95. while offset < datalen:
  96. data += _query_device_info_chunk(device, offset)
  97. offset += 32
  98. str_data = gzip.decompress(bytearray(data[:datalen]))
  99. return json.loads(str_data)
  100. def _list_devices():
  101. """Dump out available devices
  102. """
  103. cli.log.info('Available devices:')
  104. devices = _search()
  105. for dev in devices:
  106. device = hid.Device(path=dev['path'])
  107. data = _query_device(device)
  108. cli.log.info(" %04x:%04x %s %s [API:%s] %s", dev['vendor_id'], dev['product_id'], dev['manufacturer_string'], dev['product_string'], data['xap'], data['secure'])
  109. if cli.config.general.verbose:
  110. # TODO: better formatting like "lsusb -v"?
  111. data = _query_device_info(device)
  112. print_dotted_output(data)
  113. def xap_doit():
  114. print("xap_doit")
  115. # get layer count
  116. # layers = _xap_transaction(device, 0x04, 0x01)
  117. # layers = int.from_bytes(layers, "little")
  118. # print(f'layers:{layers}')
  119. # get keycode [layer:0, row:0, col:0]
  120. # keycode = _xap_transaction(device, 0x04, 0x02, b"\x00\x00\x00")
  121. # keycode = int.from_bytes(keycode, "little")
  122. # keycode_map = {
  123. # # TODO: this should be data driven...
  124. # 0x04: 'KC_A',
  125. # 0x05: 'KC_B',
  126. # 0x29: 'KC_ESCAPE'
  127. # }
  128. # print('keycode:' + keycode_map.get(keycode, 'unknown'))
  129. # Reboot
  130. # _xap_transaction(device, 0x01, 0x07)
  131. def xap_broadcast_listen(device):
  132. try:
  133. cli.log.info("Listening for XAP broadcasts...")
  134. while 1:
  135. array_alpha = device.read(64, 100)
  136. if str(b"\xFF\xFF") == str(array_alpha[:2]):
  137. if array_alpha[2] == 1:
  138. cli.log.info(" Broadcast: Secure[%02x]", array_alpha[4])
  139. else:
  140. cli.log.info(" Broadcast: type[%02x] data:[%02x]", array_alpha[2], array_alpha[4])
  141. except KeyboardInterrupt:
  142. cli.log.info("Stopping...")
  143. def xap_unlock(device):
  144. _xap_transaction(device, 0x00, 0x04)
  145. @cli.argument('-d', '--device', help='device to select - uses format <pid>:<vid>.')
  146. @cli.argument('-i', '--index', default=0, help='device index to select.')
  147. @cli.argument('-l', '--list', arg_only=True, action='store_true', help='List available devices.')
  148. @cli.argument('action', nargs='?', arg_only=True)
  149. @cli.subcommand('Acquire debugging information from usb XAP devices.', hidden=False if cli.config.user.developer else True)
  150. def xap(cli):
  151. """Acquire debugging information from XAP devices
  152. """
  153. # Lazy load to avoid issues
  154. global hid
  155. import hid
  156. if cli.args.list:
  157. return _list_devices()
  158. # Connect to first available device
  159. devices = _search()
  160. if not devices:
  161. cli.log.error("No devices found!")
  162. return False
  163. dev = devices[0]
  164. device = hid.Device(path=dev['path'])
  165. cli.log.info("Connected to:%04x:%04x %s %s", dev['vendor_id'], dev['product_id'], dev['manufacturer_string'], dev['product_string'])
  166. # xap_doit(device)
  167. if cli.args.action == 'unlock':
  168. xap_unlock(device)
  169. cli.log.info("Done")
  170. elif cli.args.action == 'listen':
  171. xap_broadcast_listen(device)
  172. elif not cli.args.action:
  173. xap_broadcast_listen(device)