xap.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  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, ret_len, *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. args_len += 2
  48. args_data = args[0].to_bytes(2, byteorder='little')
  49. padding_len = 64 - 3 - args_len
  50. padding = b"\x00" * padding_len
  51. if args_data:
  52. padding = args_data + padding
  53. buffer = token + args_len.to_bytes(1, byteorder='little') + sub.to_bytes(1, byteorder='little') + route.to_bytes(1, byteorder='little') + padding
  54. # prepend 0 on windows because reasons...
  55. if 'windows' in platform().lower():
  56. buffer = b"\x00" + buffer
  57. device.write(buffer)
  58. # get resp
  59. array_alpha = device.read(4 + ret_len, 100)
  60. # validate tok sent == resp
  61. if str(token) != str(array_alpha[:2]):
  62. return None
  63. return array_alpha[4:]
  64. def _query_device(device):
  65. ver_data = _xap_transaction(device, 0x00, 0x00, 4)
  66. if not ver_data:
  67. return {'xap': 'UNKNOWN'}
  68. # to u32 to BCD string
  69. a = (ver_data[3] << 24) + (ver_data[2] << 16) + (ver_data[1] << 8) + (ver_data[0])
  70. ver = f'{a>>24}.{a>>16 & 0xFF}.{a & 0xFFFF}'
  71. secure = int.from_bytes(_xap_transaction(device, 0x00, 0x03, 1), 'little')
  72. secure = 'unlocked' if secure == 2 else 'LOCKED'
  73. return {'xap': ver, 'secure': secure}
  74. def _query_device_info_len(device):
  75. len_data = _xap_transaction(device, 0x01, 0x05, 4)
  76. if not len_data:
  77. return 0
  78. # to u32
  79. return (len_data[3] << 24) + (len_data[2] << 16) + (len_data[1] << 8) + (len_data[0])
  80. def _query_device_info_chunk(device, offset):
  81. return _xap_transaction(device, 0x01, 0x06, 32, offset)
  82. def _query_device_info(device):
  83. datalen = _query_device_info_len(device)
  84. if not datalen:
  85. return {}
  86. data = []
  87. offset = 0
  88. while offset < datalen:
  89. data += _query_device_info_chunk(device, offset)
  90. offset += 32
  91. str_data = gzip.decompress(bytearray(data[:datalen]))
  92. return json.loads(str_data)
  93. def _list_devices():
  94. """Dump out available devices
  95. """
  96. cli.log.info('Available devices:')
  97. devices = _search()
  98. for dev in devices:
  99. device = hid.Device(path=dev['path'])
  100. data = _query_device(device)
  101. 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'])
  102. if cli.config.general.verbose:
  103. # TODO: better formatting like "lsusb -v"?
  104. data = _query_device_info(device)
  105. print_dotted_output(data)
  106. @cli.argument('-d', '--device', help='device to select - uses format <pid>:<vid>.')
  107. @cli.argument('-i', '--index', default=0, help='device index to select.')
  108. @cli.argument('-l', '--list', arg_only=True, action='store_true', help='List available devices.')
  109. @cli.subcommand('Acquire debugging information from usb XAP devices.', hidden=False if cli.config.user.developer else True)
  110. def xap(cli):
  111. """Acquire debugging information from XAP devices
  112. """
  113. # Lazy load to avoid issues
  114. global hid
  115. import hid
  116. if cli.args.list:
  117. return _list_devices()
  118. cli.log.warn("TODO: Device specific stuff")