summaryrefslogtreecommitdiffstats
path: root/freestyle_hid/tools/extract_chatter.py
blob: 80e96292aa87fc36abfe8d373d7c99787f6af9fd (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
#!/usr/bin/env python3
#
# SPDX-FileCopyrightText: © 2019 The usbmon-tools Authors
# SPDX-FileCopyrightText: © 2020 The freestyle-hid Authors
#
# SPDX-License-Identifier: Apache-2.0

import logging
import sys
import textwrap
from typing import BinaryIO

import click
import click_log
import construct
import usbmon
import usbmon.chatter
import usbmon.pcapng
import usbmon.support.hid

logger = logging.getLogger()
click_log.basic_config(logger)

_KEEPALIVE_TYPE = 0x22

_UNENCRYPTED_TYPES = (
    0x01,
    0x04,
    0x05,
    0x06,
    0x0C,
    0x0D,
    0x14,
    0x15,
    0x33,
    0x34,
    0x35,
    0x71,
    _KEEPALIVE_TYPE,
)

_ENCRYPTION_SETUP_TYPES = (0x14, 0x33)

_START_AUTHORIZE_CMD = 0x11
_CHALLENGE_CMD = 0x16
_CHALLENGE_RESPONSE_CMD = 0x17
_CHALLENGE_ACCEPTED_CMD = 0x18

_ABBOTT_VENDOR_ID = 0x1A61
_LIBRE2_PRODUCT_ID = 0x3950

_ENCRYPTED_MESSAGE = construct.Struct(
    encrypted_message=construct.Bytes(64 - 1 - 4 - 4),
    sequence_number=construct.Int32ul,
    mac=construct.Int32ul,
)


@click.command()
@click_log.simple_verbosity_option(logger, "--vlog")
@click.option(
    "--device-address",
    help=(
        "Device address (busnum.devnum) of the device to extract capture"
        " of. If none provided, device descriptors will be relied on."
    ),
)
@click.option(
    "--encrypted-protocol / --no-encrypted-protocol",
    default=False,
    help=(
        "Whether to expect encrypted protocol in the capture."
        " Ignored if the device descriptors are present in the capture."
    ),
)
@click.option(
    "--verbose-encryption-setup / --no-verbose-encryption-setup",
    default=False,
    help=(
        "Whether to parse encryption setup commands and printing their component"
        " together with the raw messsage."
    ),
)
@click.option(
    "--print-keepalive / --no-print-keepalive",
    default=False,
    help=(
        "Whether to print the keepalive messages sent by the device. "
        "Keepalive messages are usually safely ignored."
    ),
)
@click.argument(
    "pcap-file",
    type=click.File(mode="rb"),
)
def main(
    *,
    device_address: str,
    encrypted_protocol: bool,
    verbose_encryption_setup: bool,
    print_keepalive: bool,
    pcap_file: BinaryIO,
) -> None:
    if sys.version_info < (3, 7):
        raise Exception("Unsupported Python version, please use at least Python 3.7.")

    session = usbmon.pcapng.parse_stream(pcap_file, retag_urbs=False)

    if not device_address:
        possible_addresses = list(session.find_devices_by_ids(_ABBOTT_VENDOR_ID, None))
        if len(possible_addresses) > 1:
            possible_addresses_str = ", ".join(
                str(address) for address in possible_addresses
            )
            raise click.UsageError(
                f"Multiple Abbott devices found, please select one of {possible_addresses_str}"
            )
        elif len(possible_addresses) == 0:
            raise click.UsageError("No Abbott devices found.")
        else:
            (device_address,) = possible_addresses

    if device_address not in session.device_descriptors:
        logging.warning(
            f"Unable to find device {device_address} in the capture's descriptors."
            " Assuming non-encrypted protocol.",
        )
    else:
        descriptor = session.device_descriptors[device_address]
        assert descriptor.vendor_id == _ABBOTT_VENDOR_ID

        if descriptor.product_id == _LIBRE2_PRODUCT_ID:
            encrypted_protocol = True

    for packet in usbmon.support.hid.select(session, device_address=device_address):
        assert packet.report_content
        message_type = packet.report_id

        if message_type == _KEEPALIVE_TYPE and not print_keepalive:
            continue

        message_metadata = []

        if encrypted_protocol and message_type not in _UNENCRYPTED_TYPES:
            # With encrypted communication, the length of the message is also encrypted,
            # and all the packets use the full 64 bytes. So instead, we extract what
            # metadata we can.
            parsed = _ENCRYPTED_MESSAGE.parse(packet.report_content)
            message_metadata.extend(
                [f"SEQUENCE_NUMBER={parsed.sequence_number}", f"MAC={parsed.mac:04x}"]
            )

            message_type_str = f"x{message_type:02x}"
            message = parsed.encrypted_message
        elif verbose_encryption_setup and message_type in _ENCRYPTION_SETUP_TYPES:
            message_length = packet.report_content[0]
            message_end_idx = 1 + message_length
            message = packet.report_content[1:message_end_idx]

            if message[0] == _START_AUTHORIZE_CMD:
                message_metadata.append("START_AUTHORIZE")
            elif message[0] == _CHALLENGE_CMD:
                message_metadata.append("CHALLENGE")
                challenge = message[1:9]
                iv = message[9:16]
                message_metadata.append(f"CHALLENGE={challenge.hex()}")
                message_metadata.append(f"IV={iv.hex()}")
            elif message[0] == _CHALLENGE_RESPONSE_CMD:
                message_metadata.append("CHALLENGE_RESPONSE")
                encrypted_challenge = message[1:17]
                challenge_mac = message[18:26]
                message_metadata.append(
                    f"ENCRYPTED_CHALLENGE={encrypted_challenge.hex()}"
                )
                message_metadata.append(f"MAC={challenge_mac.hex()}")
            elif message[0] == _CHALLENGE_ACCEPTED_CMD:
                message_metadata.append("CHALLENGE_ACCEPTED")

            message_metadata.append(f"RAW_LENGTH={message_length}")
            message_type_str = f" {message_type:02x}"
        else:
            message_length = packet.report_content[0]
            message_metadata.append(f"LENGTH={message_length}")
            message_end_idx = 1 + message_length
            message_type_str = f" {message_type:02x}"
            message = packet.report_content[1:message_end_idx]

        if message_metadata:
            metadata_string = "\n".join(
                textwrap.wrap(
                    " ".join(message_metadata), width=80, break_long_words=False
                )
            )
            print(metadata_string)

        print(
            usbmon.chatter.dump_bytes(
                packet.direction,
                message,
                prefix=f"[{message_type_str}]",
                print_empty=True,
            ),
            "\n",
        )


if __name__ == "__main__":
    main()