pyhubblenetwork 0.10.0__tar.gz → 0.11.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {pyhubblenetwork-0.10.0 → pyhubblenetwork-0.11.0}/PKG-INFO +67 -2
- {pyhubblenetwork-0.10.0 → pyhubblenetwork-0.11.0}/README.md +66 -1
- {pyhubblenetwork-0.10.0 → pyhubblenetwork-0.11.0}/pyproject.toml +1 -1
- {pyhubblenetwork-0.10.0 → pyhubblenetwork-0.11.0}/src/hubblenetwork/__init__.py +2 -1
- {pyhubblenetwork-0.10.0 → pyhubblenetwork-0.11.0}/src/hubblenetwork/cli.py +178 -37
- {pyhubblenetwork-0.10.0 → pyhubblenetwork-0.11.0}/src/hubblenetwork/crypto.py +37 -0
- {pyhubblenetwork-0.10.0 → pyhubblenetwork-0.11.0}/src/hubblenetwork/packets.py +3 -0
- {pyhubblenetwork-0.10.0 → pyhubblenetwork-0.11.0}/src/hubblenetwork/sat.py +10 -0
- {pyhubblenetwork-0.10.0 → pyhubblenetwork-0.11.0}/tests/test_aes_eax.py +15 -0
- pyhubblenetwork-0.11.0/tests/test_sat_decrypt.py +281 -0
- {pyhubblenetwork-0.10.0 → pyhubblenetwork-0.11.0}/tests/test_unencrypted.py +53 -0
- {pyhubblenetwork-0.10.0 → pyhubblenetwork-0.11.0}/.gitignore +0 -0
- {pyhubblenetwork-0.10.0 → pyhubblenetwork-0.11.0}/LICENSE +0 -0
- {pyhubblenetwork-0.10.0 → pyhubblenetwork-0.11.0}/plugins/pyhubblenetwork/skills/hubble-ready-test/README.md +0 -0
- {pyhubblenetwork-0.10.0 → pyhubblenetwork-0.11.0}/src/hubblenetwork/ble.py +0 -0
- {pyhubblenetwork-0.10.0 → pyhubblenetwork-0.11.0}/src/hubblenetwork/cloud.py +0 -0
- {pyhubblenetwork-0.10.0 → pyhubblenetwork-0.11.0}/src/hubblenetwork/device.py +0 -0
- {pyhubblenetwork-0.10.0 → pyhubblenetwork-0.11.0}/src/hubblenetwork/errors.py +0 -0
- {pyhubblenetwork-0.10.0 → pyhubblenetwork-0.11.0}/src/hubblenetwork/org.py +0 -0
- {pyhubblenetwork-0.10.0 → pyhubblenetwork-0.11.0}/src/hubblenetwork/ready.py +0 -0
- {pyhubblenetwork-0.10.0 → pyhubblenetwork-0.11.0}/tests/__init__.py +0 -0
- {pyhubblenetwork-0.10.0 → pyhubblenetwork-0.11.0}/tests/conftest.py +0 -0
- {pyhubblenetwork-0.10.0 → pyhubblenetwork-0.11.0}/tests/test_ble_validate.py +0 -0
- {pyhubblenetwork-0.10.0 → pyhubblenetwork-0.11.0}/tests/test_cli_ctr_autodetect.py +0 -0
- {pyhubblenetwork-0.10.0 → pyhubblenetwork-0.11.0}/tests/test_cli_payload.py +0 -0
- {pyhubblenetwork-0.10.0 → pyhubblenetwork-0.11.0}/tests/test_cloud_integration.py +0 -0
- {pyhubblenetwork-0.10.0 → pyhubblenetwork-0.11.0}/tests/test_counter_eid.py +0 -0
- {pyhubblenetwork-0.10.0 → pyhubblenetwork-0.11.0}/tests/test_metrics.py +0 -0
- {pyhubblenetwork-0.10.0 → pyhubblenetwork-0.11.0}/tests/test_org_delete_device.py +0 -0
- {pyhubblenetwork-0.10.0 → pyhubblenetwork-0.11.0}/tests/test_register_device_cloud.py +0 -0
- {pyhubblenetwork-0.10.0 → pyhubblenetwork-0.11.0}/tests/test_register_device_validation.py +0 -0
- {pyhubblenetwork-0.10.0 → pyhubblenetwork-0.11.0}/tests/test_sat.py +0 -0
- {pyhubblenetwork-0.10.0 → pyhubblenetwork-0.11.0}/tests/test_sat_integration.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: pyhubblenetwork
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.11.0
|
|
4
4
|
Summary: Hubble SDK host-side tools
|
|
5
5
|
Author-email: Paul Buckley <paul@hubble.com>
|
|
6
6
|
License-Expression: Apache-2.0
|
|
@@ -37,6 +37,7 @@ Description-Content-Type: text/markdown
|
|
|
37
37
|
- [Installation](#installation)
|
|
38
38
|
- [Quick start](#quick-start)
|
|
39
39
|
- [CLI usage](#cli-usage)
|
|
40
|
+
- [Validating a device end-to-end](#validating-a-device-end-to-end)
|
|
40
41
|
- [Satellite scanning (PlutoSDR)](#satellite-scanning-plutosdr)
|
|
41
42
|
- [Configuration](#configuration)
|
|
42
43
|
- [Public API (summary)](#public-api-summary)
|
|
@@ -179,6 +180,46 @@ Commands that output packet data (`ble scan`, `ble detect`, `org get-packets`) s
|
|
|
179
180
|
|
|
180
181
|
This applies to all output formats (tabular, json, csv).
|
|
181
182
|
|
|
183
|
+
## Validating a device end-to-end
|
|
184
|
+
|
|
185
|
+
The `ble validate` command runs a full end-to-end health check on a single Hubble
|
|
186
|
+
device, confirming that everything from your credentials to the cloud backend is
|
|
187
|
+
wired up correctly. It is the quickest way to answer "is my device working?"
|
|
188
|
+
|
|
189
|
+
```bash
|
|
190
|
+
hubblenetwork ble validate \
|
|
191
|
+
--key "a562a2f7e4c62bed52ab09633878f62b" \
|
|
192
|
+
--device-id "3f4b2c0c-2d43-4cbe-9c1f-0a4c2d59e2a1"
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
The command performs these steps in order, stopping at the first failure:
|
|
196
|
+
|
|
197
|
+
1. **Validates input formats** — the device key (hex or base64, 16- or 32-byte)
|
|
198
|
+
and the device ID (standard 8-4-4-4-12 UUID).
|
|
199
|
+
2. **Loads credentials** — from `--org-id`/`--token` or the `HUBBLE_ORG_ID` and
|
|
200
|
+
`HUBBLE_API_TOKEN` environment variables.
|
|
201
|
+
3. **Validates the organization credentials** against the backend.
|
|
202
|
+
4. **Confirms the device is registered** in your organization.
|
|
203
|
+
5. **Scans for BLE advertisements** from Hubble-compatible devices.
|
|
204
|
+
6. **Decrypts a received packet** with the provided key and reports the detected
|
|
205
|
+
EID type (`UNIX_TIME` or `DEVICE_UPTIME`).
|
|
206
|
+
7. **Ingests the packet** into the backend and **reads it back** to confirm the
|
|
207
|
+
full round trip succeeded.
|
|
208
|
+
|
|
209
|
+
### Options
|
|
210
|
+
|
|
211
|
+
| Option | Description |
|
|
212
|
+
|--------|-------------|
|
|
213
|
+
| `--key`, `-k` | Device key, used to test packet encryption (required). Accepts hex or base64, 16- or 32-byte. |
|
|
214
|
+
| `--device-id`, `-d` | Device UUID, used to test the backend (required). |
|
|
215
|
+
| `--org-id` | Organization ID (defaults to the `HUBBLE_ORG_ID` env var). |
|
|
216
|
+
| `--token` | API token (defaults to the `HUBBLE_API_TOKEN` env var). |
|
|
217
|
+
| `--timeout`, `-t` | BLE scan timeout in seconds (default: 30). |
|
|
218
|
+
|
|
219
|
+
If a step fails, the command prints targeted debugging tips. A common cause of a
|
|
220
|
+
failed scan is a slow advertising interval combined with OS-level BLE scan
|
|
221
|
+
optimizations — simply running the command again often resolves it.
|
|
222
|
+
|
|
182
223
|
## Satellite scanning (PlutoSDR)
|
|
183
224
|
|
|
184
225
|
The `sat` command group receives packets via a PlutoSDR SDR dongle. It runs a Docker container ([`ghcr.io/hubblenetwork/sdr-docker`](https://ghcr.io/hubblenetwork/sdr-docker)) that handles RF reception and decoding, then polls that container's HTTP API and streams decoded packets to stdout.
|
|
@@ -205,8 +246,20 @@ hubblenetwork sat scan -o json
|
|
|
205
246
|
|
|
206
247
|
# Combine options
|
|
207
248
|
hubblenetwork sat scan -o json --timeout 60 -n 20
|
|
249
|
+
|
|
250
|
+
# Decrypt payloads locally with a device key (hex or base64, 16 or 32 bytes)
|
|
251
|
+
hubblenetwork sat scan --key "a562a2f7e4c62bed52ab09633878f62b"
|
|
252
|
+
|
|
253
|
+
# Show packets the key can't decrypt too (adds a DECRYPT OK/FAIL column)
|
|
254
|
+
hubblenetwork sat scan --key "<key>" --show-failed-decryption
|
|
208
255
|
```
|
|
209
256
|
|
|
257
|
+
When `--key` is supplied, each packet's payload is decrypted locally using the
|
|
258
|
+
same AES-CTR scheme as BLE. Satellite packets always use the UNIX_TIME (day-based)
|
|
259
|
+
counter; `--days` controls how many days around each packet's timestamp are
|
|
260
|
+
searched (default 2). Packets the key cannot decrypt are hidden unless
|
|
261
|
+
`--show-failed-decryption` is given.
|
|
262
|
+
|
|
210
263
|
The command automatically:
|
|
211
264
|
1. Verifies Docker is available
|
|
212
265
|
2. Pulls the latest PlutoSDR image (if not cached)
|
|
@@ -226,9 +279,21 @@ for pkt in sat.scan(timeout=60.0, poll_interval=2.0):
|
|
|
226
279
|
|
|
227
280
|
# Or fetch the current packet buffer without managing the container yourself
|
|
228
281
|
packets: list[SatellitePacket] = sat.fetch_packets()
|
|
282
|
+
|
|
283
|
+
# Decrypt a packet's payload locally (UNIX_TIME counter)
|
|
284
|
+
from hubblenetwork import decrypt_satellite
|
|
285
|
+
|
|
286
|
+
for pkt in sat.scan(timeout=60.0):
|
|
287
|
+
if pkt.auth_tag is not None:
|
|
288
|
+
plaintext = decrypt_satellite(
|
|
289
|
+
key, seq_no=pkt.seq_num, auth_tag=pkt.auth_tag,
|
|
290
|
+
encrypted_payload=pkt.payload, timestamp=pkt.timestamp,
|
|
291
|
+
)
|
|
292
|
+
if plaintext is not None:
|
|
293
|
+
print(pkt.device_id, plaintext)
|
|
229
294
|
```
|
|
230
295
|
|
|
231
|
-
`SatellitePacket` fields: `device_id`, `seq_num`, `device_type`, `timestamp`, `rssi_dB`, `channel_num`, `freq_offset_hz`, `payload` (bytes).
|
|
296
|
+
`SatellitePacket` fields: `device_id`, `seq_num`, `device_type`, `timestamp`, `rssi_dB`, `channel_num`, `freq_offset_hz`, `payload` (bytes), `auth_tag` (bytes or `None`).
|
|
232
297
|
|
|
233
298
|
### Errors
|
|
234
299
|
|
|
@@ -14,6 +14,7 @@
|
|
|
14
14
|
- [Installation](#installation)
|
|
15
15
|
- [Quick start](#quick-start)
|
|
16
16
|
- [CLI usage](#cli-usage)
|
|
17
|
+
- [Validating a device end-to-end](#validating-a-device-end-to-end)
|
|
17
18
|
- [Satellite scanning (PlutoSDR)](#satellite-scanning-plutosdr)
|
|
18
19
|
- [Configuration](#configuration)
|
|
19
20
|
- [Public API (summary)](#public-api-summary)
|
|
@@ -156,6 +157,46 @@ Commands that output packet data (`ble scan`, `ble detect`, `org get-packets`) s
|
|
|
156
157
|
|
|
157
158
|
This applies to all output formats (tabular, json, csv).
|
|
158
159
|
|
|
160
|
+
## Validating a device end-to-end
|
|
161
|
+
|
|
162
|
+
The `ble validate` command runs a full end-to-end health check on a single Hubble
|
|
163
|
+
device, confirming that everything from your credentials to the cloud backend is
|
|
164
|
+
wired up correctly. It is the quickest way to answer "is my device working?"
|
|
165
|
+
|
|
166
|
+
```bash
|
|
167
|
+
hubblenetwork ble validate \
|
|
168
|
+
--key "a562a2f7e4c62bed52ab09633878f62b" \
|
|
169
|
+
--device-id "3f4b2c0c-2d43-4cbe-9c1f-0a4c2d59e2a1"
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
The command performs these steps in order, stopping at the first failure:
|
|
173
|
+
|
|
174
|
+
1. **Validates input formats** — the device key (hex or base64, 16- or 32-byte)
|
|
175
|
+
and the device ID (standard 8-4-4-4-12 UUID).
|
|
176
|
+
2. **Loads credentials** — from `--org-id`/`--token` or the `HUBBLE_ORG_ID` and
|
|
177
|
+
`HUBBLE_API_TOKEN` environment variables.
|
|
178
|
+
3. **Validates the organization credentials** against the backend.
|
|
179
|
+
4. **Confirms the device is registered** in your organization.
|
|
180
|
+
5. **Scans for BLE advertisements** from Hubble-compatible devices.
|
|
181
|
+
6. **Decrypts a received packet** with the provided key and reports the detected
|
|
182
|
+
EID type (`UNIX_TIME` or `DEVICE_UPTIME`).
|
|
183
|
+
7. **Ingests the packet** into the backend and **reads it back** to confirm the
|
|
184
|
+
full round trip succeeded.
|
|
185
|
+
|
|
186
|
+
### Options
|
|
187
|
+
|
|
188
|
+
| Option | Description |
|
|
189
|
+
|--------|-------------|
|
|
190
|
+
| `--key`, `-k` | Device key, used to test packet encryption (required). Accepts hex or base64, 16- or 32-byte. |
|
|
191
|
+
| `--device-id`, `-d` | Device UUID, used to test the backend (required). |
|
|
192
|
+
| `--org-id` | Organization ID (defaults to the `HUBBLE_ORG_ID` env var). |
|
|
193
|
+
| `--token` | API token (defaults to the `HUBBLE_API_TOKEN` env var). |
|
|
194
|
+
| `--timeout`, `-t` | BLE scan timeout in seconds (default: 30). |
|
|
195
|
+
|
|
196
|
+
If a step fails, the command prints targeted debugging tips. A common cause of a
|
|
197
|
+
failed scan is a slow advertising interval combined with OS-level BLE scan
|
|
198
|
+
optimizations — simply running the command again often resolves it.
|
|
199
|
+
|
|
159
200
|
## Satellite scanning (PlutoSDR)
|
|
160
201
|
|
|
161
202
|
The `sat` command group receives packets via a PlutoSDR SDR dongle. It runs a Docker container ([`ghcr.io/hubblenetwork/sdr-docker`](https://ghcr.io/hubblenetwork/sdr-docker)) that handles RF reception and decoding, then polls that container's HTTP API and streams decoded packets to stdout.
|
|
@@ -182,8 +223,20 @@ hubblenetwork sat scan -o json
|
|
|
182
223
|
|
|
183
224
|
# Combine options
|
|
184
225
|
hubblenetwork sat scan -o json --timeout 60 -n 20
|
|
226
|
+
|
|
227
|
+
# Decrypt payloads locally with a device key (hex or base64, 16 or 32 bytes)
|
|
228
|
+
hubblenetwork sat scan --key "a562a2f7e4c62bed52ab09633878f62b"
|
|
229
|
+
|
|
230
|
+
# Show packets the key can't decrypt too (adds a DECRYPT OK/FAIL column)
|
|
231
|
+
hubblenetwork sat scan --key "<key>" --show-failed-decryption
|
|
185
232
|
```
|
|
186
233
|
|
|
234
|
+
When `--key` is supplied, each packet's payload is decrypted locally using the
|
|
235
|
+
same AES-CTR scheme as BLE. Satellite packets always use the UNIX_TIME (day-based)
|
|
236
|
+
counter; `--days` controls how many days around each packet's timestamp are
|
|
237
|
+
searched (default 2). Packets the key cannot decrypt are hidden unless
|
|
238
|
+
`--show-failed-decryption` is given.
|
|
239
|
+
|
|
187
240
|
The command automatically:
|
|
188
241
|
1. Verifies Docker is available
|
|
189
242
|
2. Pulls the latest PlutoSDR image (if not cached)
|
|
@@ -203,9 +256,21 @@ for pkt in sat.scan(timeout=60.0, poll_interval=2.0):
|
|
|
203
256
|
|
|
204
257
|
# Or fetch the current packet buffer without managing the container yourself
|
|
205
258
|
packets: list[SatellitePacket] = sat.fetch_packets()
|
|
259
|
+
|
|
260
|
+
# Decrypt a packet's payload locally (UNIX_TIME counter)
|
|
261
|
+
from hubblenetwork import decrypt_satellite
|
|
262
|
+
|
|
263
|
+
for pkt in sat.scan(timeout=60.0):
|
|
264
|
+
if pkt.auth_tag is not None:
|
|
265
|
+
plaintext = decrypt_satellite(
|
|
266
|
+
key, seq_no=pkt.seq_num, auth_tag=pkt.auth_tag,
|
|
267
|
+
encrypted_payload=pkt.payload, timestamp=pkt.timestamp,
|
|
268
|
+
)
|
|
269
|
+
if plaintext is not None:
|
|
270
|
+
print(pkt.device_id, plaintext)
|
|
206
271
|
```
|
|
207
272
|
|
|
208
|
-
`SatellitePacket` fields: `device_id`, `seq_num`, `device_type`, `timestamp`, `rssi_dB`, `channel_num`, `freq_offset_hz`, `payload` (bytes).
|
|
273
|
+
`SatellitePacket` fields: `device_id`, `seq_num`, `device_type`, `timestamp`, `rssi_dB`, `channel_num`, `freq_offset_hz`, `payload` (bytes), `auth_tag` (bytes or `None`).
|
|
209
274
|
|
|
210
275
|
### Errors
|
|
211
276
|
|
|
@@ -12,7 +12,7 @@ from . import sat
|
|
|
12
12
|
from .packets import Location, EncryptedPacket, UnencryptedPacket, DecryptedPacket, SatellitePacket, AesEaxPacket, UnknownPacket
|
|
13
13
|
from .device import Device
|
|
14
14
|
from .org import Organization
|
|
15
|
-
from .crypto import decrypt, decrypt_eax, UNIX_TIME, DEVICE_UPTIME
|
|
15
|
+
from .crypto import decrypt, decrypt_eax, decrypt_satellite, UNIX_TIME, DEVICE_UPTIME
|
|
16
16
|
from .errors import InvalidCredentialsError
|
|
17
17
|
from .cloud import Credentials, Environment
|
|
18
18
|
|
|
@@ -23,6 +23,7 @@ __all__ = [
|
|
|
23
23
|
"sat",
|
|
24
24
|
"decrypt",
|
|
25
25
|
"decrypt_eax",
|
|
26
|
+
"decrypt_satellite",
|
|
26
27
|
"UNIX_TIME",
|
|
27
28
|
"DEVICE_UPTIME",
|
|
28
29
|
"SatellitePacket",
|
|
@@ -11,6 +11,7 @@ import base64
|
|
|
11
11
|
import binascii
|
|
12
12
|
import logging
|
|
13
13
|
import uuid
|
|
14
|
+
from dataclasses import replace
|
|
14
15
|
from datetime import datetime
|
|
15
16
|
from functools import partial
|
|
16
17
|
from typing import Optional, List
|
|
@@ -21,7 +22,7 @@ from hubblenetwork.packets import SatellitePacket, UnencryptedPacket, AesEaxPack
|
|
|
21
22
|
from hubblenetwork import ble as ble_mod
|
|
22
23
|
from hubblenetwork import ready as ready_mod
|
|
23
24
|
from hubblenetwork import sat as sat_mod
|
|
24
|
-
from hubblenetwork import decrypt, UNIX_TIME, DEVICE_UPTIME
|
|
25
|
+
from hubblenetwork import decrypt, decrypt_satellite, UNIX_TIME, DEVICE_UPTIME
|
|
25
26
|
from hubblenetwork.crypto import find_time_counter_delta
|
|
26
27
|
from hubblenetwork import cloud
|
|
27
28
|
from hubblenetwork import InvalidCredentialsError
|
|
@@ -112,6 +113,22 @@ def _detect_eid_type(
|
|
|
112
113
|
return (None, None, None, False)
|
|
113
114
|
|
|
114
115
|
|
|
116
|
+
def _announce_auto_detect(auto_ctr: bool, auto_eax: bool, *, suppress: bool) -> None:
|
|
117
|
+
if suppress or not (auto_ctr or auto_eax):
|
|
118
|
+
return
|
|
119
|
+
parts = []
|
|
120
|
+
if auto_ctr:
|
|
121
|
+
parts.append("AES-CTR counter_source")
|
|
122
|
+
if auto_eax:
|
|
123
|
+
parts.append("AES-EAX period_exponent (0..15)")
|
|
124
|
+
click.secho(
|
|
125
|
+
f"[WARN] No {' / '.join(parts)} provided. Auto-detecting "
|
|
126
|
+
f"decryption configuration from incoming packets...",
|
|
127
|
+
fg="yellow",
|
|
128
|
+
err=True,
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
|
|
115
132
|
def _decrypt_eax_with_detect(
|
|
116
133
|
key: bytes,
|
|
117
134
|
pkt: AesEaxPacket,
|
|
@@ -120,7 +137,7 @@ def _decrypt_eax_with_detect(
|
|
|
120
137
|
fixed_exponent: int,
|
|
121
138
|
cache: dict,
|
|
122
139
|
announced: list[str],
|
|
123
|
-
|
|
140
|
+
suppress_info: bool,
|
|
124
141
|
) -> Optional[DecryptedPacket]:
|
|
125
142
|
if not auto_detect:
|
|
126
143
|
return decrypt_eax(key, pkt, period_exponent=fixed_exponent)
|
|
@@ -136,7 +153,7 @@ def _decrypt_eax_with_detect(
|
|
|
136
153
|
if result is None:
|
|
137
154
|
continue
|
|
138
155
|
cache[pkt.eid] = candidate
|
|
139
|
-
if not announced and not
|
|
156
|
+
if not announced and not suppress_info:
|
|
140
157
|
announced.append("eax")
|
|
141
158
|
click.secho(
|
|
142
159
|
f"[INFO] Detected: AES-128-EAX, counter_source=DEVICE_UPTIME, "
|
|
@@ -157,7 +174,7 @@ def _decrypt_ctr_with_detect(
|
|
|
157
174
|
days: int,
|
|
158
175
|
cache: dict,
|
|
159
176
|
announced: list[str],
|
|
160
|
-
|
|
177
|
+
suppress_info: bool,
|
|
161
178
|
) -> Optional[DecryptedPacket]:
|
|
162
179
|
if not auto_detect:
|
|
163
180
|
return decrypt(key, pkt, days=days, counter_mode=fixed_counter_mode)
|
|
@@ -181,7 +198,7 @@ def _decrypt_ctr_with_detect(
|
|
|
181
198
|
continue
|
|
182
199
|
if pkt.eid is not None:
|
|
183
200
|
cache[pkt.eid] = mode
|
|
184
|
-
if not announced and not
|
|
201
|
+
if not announced and not suppress_info:
|
|
185
202
|
announced.append("ctr")
|
|
186
203
|
variant = "AES-128-CTR" if len(key) == 16 else "AES-256-CTR"
|
|
187
204
|
click.secho(
|
|
@@ -372,6 +389,11 @@ def _format_ready_json_error(
|
|
|
372
389
|
}
|
|
373
390
|
|
|
374
391
|
|
|
392
|
+
def _decrypt_status_cell(decrypt_status: Optional[str]) -> str:
|
|
393
|
+
"""Render a decrypt status as a table cell ("OK"/"FAIL"/"-")."""
|
|
394
|
+
return {"ok": "OK", "fail": "FAIL"}.get(decrypt_status, "-")
|
|
395
|
+
|
|
396
|
+
|
|
375
397
|
class _StreamingPrinterBase:
|
|
376
398
|
"""Base class for streaming packet printers."""
|
|
377
399
|
|
|
@@ -477,7 +499,7 @@ class _StreamingTablePrinter(_StreamingPrinterBase):
|
|
|
477
499
|
ts = datetime.fromtimestamp(pkt.timestamp).strftime("%H:%M:%S")
|
|
478
500
|
row: List = []
|
|
479
501
|
if self._show_decrypt_status:
|
|
480
|
-
row.append(
|
|
502
|
+
row.append(_decrypt_status_cell(decrypt_status))
|
|
481
503
|
row.extend([pkt.timestamp, ts, pkt.rssi if pkt.rssi is not None else "None"])
|
|
482
504
|
|
|
483
505
|
version = getattr(pkt, "protocol_version", None)
|
|
@@ -573,11 +595,12 @@ _STREAMING_PRINTERS = {
|
|
|
573
595
|
def _sat_packet_to_dict(
|
|
574
596
|
pkt: SatellitePacket,
|
|
575
597
|
payload_format: str = "base64",
|
|
598
|
+
decrypt_status: Optional[str] = None,
|
|
576
599
|
**_: object,
|
|
577
600
|
) -> dict:
|
|
578
601
|
"""Convert a SatellitePacket to a dictionary for JSON serialization."""
|
|
579
602
|
ts = datetime.fromtimestamp(pkt.timestamp).strftime("%c")
|
|
580
|
-
|
|
603
|
+
data = {
|
|
581
604
|
"device_id": pkt.device_id,
|
|
582
605
|
"seq_num": pkt.seq_num,
|
|
583
606
|
"device_type": pkt.device_type,
|
|
@@ -588,12 +611,18 @@ def _sat_packet_to_dict(
|
|
|
588
611
|
"freq_offset_hz": pkt.freq_offset_hz,
|
|
589
612
|
"payload": _format_payload(pkt.payload, payload_format),
|
|
590
613
|
}
|
|
614
|
+
if pkt.auth_tag is not None:
|
|
615
|
+
data["auth_tag"] = pkt.auth_tag.hex()
|
|
616
|
+
if decrypt_status is not None:
|
|
617
|
+
data["decrypt_status"] = decrypt_status
|
|
618
|
+
return data
|
|
591
619
|
|
|
592
620
|
|
|
593
621
|
class _SatStreamingTablePrinter(_StreamingPrinterBase):
|
|
594
622
|
"""Print satellite packet rows as they arrive."""
|
|
595
623
|
|
|
596
624
|
_COL_WIDTHS = {
|
|
625
|
+
"DECRYPT": 8,
|
|
597
626
|
"DEVICE_ID": 12,
|
|
598
627
|
"SEQ": 6,
|
|
599
628
|
"TYPE": 8,
|
|
@@ -604,37 +633,45 @@ class _SatStreamingTablePrinter(_StreamingPrinterBase):
|
|
|
604
633
|
"PAYLOAD": 20,
|
|
605
634
|
}
|
|
606
635
|
|
|
607
|
-
|
|
636
|
+
_BASE_HEADERS = ["DEVICE_ID", "SEQ", "TYPE", "TIME", "RSSI_DB", "CHANNEL", "FREQ_OFFSET", "PAYLOAD"]
|
|
608
637
|
|
|
609
|
-
def __init__(self, payload_format: str = "base64"):
|
|
610
|
-
super().__init__()
|
|
638
|
+
def __init__(self, payload_format: str = "base64", show_decrypt_status: bool = False):
|
|
639
|
+
super().__init__(show_decrypt_status=show_decrypt_status)
|
|
611
640
|
self._header_printed = False
|
|
612
641
|
self._payload_format = payload_format
|
|
642
|
+
self._headers = (
|
|
643
|
+
["DECRYPT", *self._BASE_HEADERS]
|
|
644
|
+
if show_decrypt_status
|
|
645
|
+
else list(self._BASE_HEADERS)
|
|
646
|
+
)
|
|
613
647
|
|
|
614
648
|
def _format_row(self, values: List) -> str:
|
|
615
649
|
parts = []
|
|
616
650
|
for i, val in enumerate(values):
|
|
617
|
-
width = self._COL_WIDTHS.get(self.
|
|
651
|
+
width = self._COL_WIDTHS.get(self._headers[i], 10)
|
|
618
652
|
parts.append(f"{str(val):<{width}}")
|
|
619
653
|
return "| " + " | ".join(parts) + " |"
|
|
620
654
|
|
|
621
655
|
def _make_separator(self) -> str:
|
|
622
656
|
parts = []
|
|
623
|
-
for header in self.
|
|
657
|
+
for header in self._headers:
|
|
624
658
|
width = self._COL_WIDTHS.get(header, 10)
|
|
625
659
|
parts.append("-" * width)
|
|
626
660
|
return "+-" + "-+-".join(parts) + "-+"
|
|
627
661
|
|
|
628
|
-
def print_row(self, pkt: SatellitePacket) -> None:
|
|
662
|
+
def print_row(self, pkt: SatellitePacket, decrypt_status: Optional[str] = None) -> None:
|
|
629
663
|
if not self._header_printed:
|
|
630
664
|
click.echo("")
|
|
631
665
|
click.echo(self._make_separator())
|
|
632
|
-
click.secho(self._format_row(self.
|
|
666
|
+
click.secho(self._format_row(self._headers), bold=True)
|
|
633
667
|
click.echo(self._make_separator())
|
|
634
668
|
self._header_printed = True
|
|
635
669
|
|
|
636
670
|
ts = datetime.fromtimestamp(pkt.timestamp).strftime("%c")
|
|
637
|
-
row = [
|
|
671
|
+
row: List = []
|
|
672
|
+
if self._show_decrypt_status:
|
|
673
|
+
row.append(_decrypt_status_cell(decrypt_status))
|
|
674
|
+
row.extend([
|
|
638
675
|
pkt.device_id,
|
|
639
676
|
pkt.seq_num,
|
|
640
677
|
pkt.device_type,
|
|
@@ -643,7 +680,7 @@ class _SatStreamingTablePrinter(_StreamingPrinterBase):
|
|
|
643
680
|
pkt.channel_num,
|
|
644
681
|
f"{pkt.freq_offset_hz:.1f}",
|
|
645
682
|
_format_payload(pkt.payload, self._payload_format),
|
|
646
|
-
]
|
|
683
|
+
])
|
|
647
684
|
click.echo(self._format_row(row))
|
|
648
685
|
click.echo(self._make_separator())
|
|
649
686
|
self._packet_count += 1
|
|
@@ -816,7 +853,15 @@ def ble() -> None:
|
|
|
816
853
|
type=click.Choice(["UNIX_TIME", "DEVICE_UPTIME"], case_sensitive=False),
|
|
817
854
|
default="UNIX_TIME",
|
|
818
855
|
show_default=True,
|
|
819
|
-
help="EID counter mode
|
|
856
|
+
help="EID counter mode for AES-CTR packets",
|
|
857
|
+
)
|
|
858
|
+
@click.option(
|
|
859
|
+
"--period-exponent",
|
|
860
|
+
"-e",
|
|
861
|
+
type=int,
|
|
862
|
+
default=0,
|
|
863
|
+
show_default=True,
|
|
864
|
+
help="EID rotation period exponent for AES-EAX packets (0-15). Period = 2^n seconds.",
|
|
820
865
|
)
|
|
821
866
|
@click.option(
|
|
822
867
|
"--format",
|
|
@@ -848,6 +893,7 @@ def ble_detect(
|
|
|
848
893
|
key: str = None,
|
|
849
894
|
days: int = 2,
|
|
850
895
|
counter_mode: str = "UNIX_TIME",
|
|
896
|
+
period_exponent: int = 0,
|
|
851
897
|
output_format: str = "tabular",
|
|
852
898
|
payload_format: str = "base64",
|
|
853
899
|
debug: bool = False,
|
|
@@ -888,6 +934,18 @@ def ble_detect(
|
|
|
888
934
|
_output_error(f"Key decoding failed: {e}")
|
|
889
935
|
return
|
|
890
936
|
|
|
937
|
+
def _explicit(name: str) -> bool:
|
|
938
|
+
return ctx.get_parameter_source(name) == click.core.ParameterSource.COMMANDLINE
|
|
939
|
+
|
|
940
|
+
auto_detect_ctr = not _explicit("counter_mode")
|
|
941
|
+
auto_detect_eax = not _explicit("period_exponent")
|
|
942
|
+
|
|
943
|
+
_announce_auto_detect(auto_detect_ctr, auto_detect_eax, suppress=use_json)
|
|
944
|
+
|
|
945
|
+
detected_ctr_modes: dict = {}
|
|
946
|
+
detected_eax_exponents: dict = {}
|
|
947
|
+
announced: list[str] = []
|
|
948
|
+
|
|
891
949
|
# Set up timeout tracking
|
|
892
950
|
start = time.monotonic()
|
|
893
951
|
deadline = None if timeout is None else start + timeout
|
|
@@ -918,10 +976,29 @@ def ble_detect(
|
|
|
918
976
|
|
|
919
977
|
logger.debug("Packet received, attempting decryption...")
|
|
920
978
|
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
979
|
+
decrypted_pkt = None
|
|
980
|
+
if isinstance(pkt, AesEaxPacket):
|
|
981
|
+
decrypted_pkt = _decrypt_eax_with_detect(
|
|
982
|
+
decoded_key,
|
|
983
|
+
pkt,
|
|
984
|
+
auto_detect=auto_detect_eax,
|
|
985
|
+
fixed_exponent=period_exponent,
|
|
986
|
+
cache=detected_eax_exponents,
|
|
987
|
+
announced=announced,
|
|
988
|
+
suppress_info=use_json,
|
|
989
|
+
)
|
|
990
|
+
elif isinstance(pkt, EncryptedPacket):
|
|
991
|
+
decrypted_pkt = _decrypt_ctr_with_detect(
|
|
992
|
+
decoded_key,
|
|
993
|
+
pkt,
|
|
994
|
+
auto_detect=auto_detect_ctr,
|
|
995
|
+
fixed_counter_mode=counter_mode,
|
|
996
|
+
days=days,
|
|
997
|
+
cache=detected_ctr_modes,
|
|
998
|
+
announced=announced,
|
|
999
|
+
suppress_info=use_json,
|
|
1000
|
+
)
|
|
1001
|
+
# UnencryptedPacket and UnknownPacket fall through — keep scanning.
|
|
925
1002
|
|
|
926
1003
|
if decrypted_pkt:
|
|
927
1004
|
# If we can decrypt it, output success
|
|
@@ -1112,18 +1189,9 @@ def ble_scan(
|
|
|
1112
1189
|
auto_detect_ctr = decoded_key is not None and not _explicit("counter_mode")
|
|
1113
1190
|
auto_detect_eax = decoded_key is not None and not _explicit("period_exponent")
|
|
1114
1191
|
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
parts.append("AES-CTR counter_source")
|
|
1119
|
-
if auto_detect_eax:
|
|
1120
|
-
parts.append("AES-EAX period_exponent (0..15)")
|
|
1121
|
-
click.secho(
|
|
1122
|
-
f"[WARN] No {' / '.join(parts)} provided. Auto-detecting "
|
|
1123
|
-
f"decryption configuration from incoming packets...",
|
|
1124
|
-
fg="yellow",
|
|
1125
|
-
err=True,
|
|
1126
|
-
)
|
|
1192
|
+
_announce_auto_detect(
|
|
1193
|
+
auto_detect_ctr, auto_detect_eax, suppress=printer.suppress_info_messages
|
|
1194
|
+
)
|
|
1127
1195
|
|
|
1128
1196
|
detected_ctr_modes: dict = {}
|
|
1129
1197
|
detected_eax_exponents: dict = {}
|
|
@@ -1143,6 +1211,14 @@ def ble_scan(
|
|
|
1143
1211
|
if not pkt:
|
|
1144
1212
|
break
|
|
1145
1213
|
|
|
1214
|
+
# When a key is supplied the user only wants packets the key can
|
|
1215
|
+
# validly decrypt. Version-1 packets are never encrypted and
|
|
1216
|
+
# unknown versions can't be decrypted, so skip both entirely.
|
|
1217
|
+
if decoded_key is not None and isinstance(
|
|
1218
|
+
pkt, (UnencryptedPacket, UnknownPacket)
|
|
1219
|
+
):
|
|
1220
|
+
continue
|
|
1221
|
+
|
|
1146
1222
|
# Unencrypted packets: apply network_id filter, print directly
|
|
1147
1223
|
if isinstance(pkt, UnencryptedPacket):
|
|
1148
1224
|
if network_id is not None and pkt.network_id != network_id:
|
|
@@ -1158,7 +1234,7 @@ def ble_scan(
|
|
|
1158
1234
|
fixed_exponent=period_exponent,
|
|
1159
1235
|
cache=detected_eax_exponents,
|
|
1160
1236
|
announced=announced,
|
|
1161
|
-
|
|
1237
|
+
suppress_info=printer.suppress_info_messages,
|
|
1162
1238
|
)
|
|
1163
1239
|
if decrypted_pkt:
|
|
1164
1240
|
printer.print_row(decrypted_pkt, decrypt_status="ok")
|
|
@@ -1176,7 +1252,7 @@ def ble_scan(
|
|
|
1176
1252
|
days=days,
|
|
1177
1253
|
cache=detected_ctr_modes,
|
|
1178
1254
|
announced=announced,
|
|
1179
|
-
|
|
1255
|
+
suppress_info=printer.suppress_info_messages,
|
|
1180
1256
|
)
|
|
1181
1257
|
if decrypted_pkt:
|
|
1182
1258
|
printer.print_row(decrypted_pkt, decrypt_status="ok")
|
|
@@ -3076,6 +3152,9 @@ def _run_sat_scan(
|
|
|
3076
3152
|
poll_interval: float,
|
|
3077
3153
|
payload_format: str,
|
|
3078
3154
|
debug: bool = False,
|
|
3155
|
+
key: Optional[str] = None,
|
|
3156
|
+
days: int = 2,
|
|
3157
|
+
show_failed_decryption: bool = False,
|
|
3079
3158
|
) -> None:
|
|
3080
3159
|
"""Shared implementation for ``sat scan`` and ``sat mock-scan``."""
|
|
3081
3160
|
mode_label = "mock satellite receiver" if mock else "satellite receiver"
|
|
@@ -3083,7 +3162,22 @@ def _run_sat_scan(
|
|
|
3083
3162
|
printer_class = _SAT_STREAMING_PRINTERS.get(
|
|
3084
3163
|
output_format.lower(), _SatStreamingTablePrinter
|
|
3085
3164
|
)
|
|
3086
|
-
printer = printer_class(
|
|
3165
|
+
printer = printer_class(
|
|
3166
|
+
payload_format=payload_format,
|
|
3167
|
+
show_decrypt_status=show_failed_decryption,
|
|
3168
|
+
)
|
|
3169
|
+
|
|
3170
|
+
# Pre-decode the key if provided. Satellite packets always use the
|
|
3171
|
+
# UNIX_TIME (day-based) counter, so only --days is relevant.
|
|
3172
|
+
decoded_key: Optional[bytes] = None
|
|
3173
|
+
if key:
|
|
3174
|
+
try:
|
|
3175
|
+
decoded_key = _parse_key(key)
|
|
3176
|
+
except ValueError as e:
|
|
3177
|
+
if printer.suppress_info_messages:
|
|
3178
|
+
click.echo(json.dumps({"error": f"Invalid key: {e}"}))
|
|
3179
|
+
return
|
|
3180
|
+
raise click.ClickException(f"Invalid key: {e}")
|
|
3087
3181
|
|
|
3088
3182
|
if debug:
|
|
3089
3183
|
sat_logger = logging.getLogger("hubblenetwork.sat")
|
|
@@ -3127,7 +3221,26 @@ def _run_sat_scan(
|
|
|
3127
3221
|
timeout=timeout, poll_interval=poll_interval, mock=mock,
|
|
3128
3222
|
on_status=_on_status,
|
|
3129
3223
|
):
|
|
3130
|
-
|
|
3224
|
+
if decoded_key is not None:
|
|
3225
|
+
# With a key, the user wants only packets the key can decrypt.
|
|
3226
|
+
decrypted = None
|
|
3227
|
+
if pkt.auth_tag is not None:
|
|
3228
|
+
decrypted = decrypt_satellite(
|
|
3229
|
+
decoded_key,
|
|
3230
|
+
seq_no=pkt.seq_num,
|
|
3231
|
+
auth_tag=pkt.auth_tag,
|
|
3232
|
+
encrypted_payload=pkt.payload,
|
|
3233
|
+
timestamp=pkt.timestamp,
|
|
3234
|
+
days=days,
|
|
3235
|
+
)
|
|
3236
|
+
if decrypted is not None:
|
|
3237
|
+
printer.print_row(
|
|
3238
|
+
replace(pkt, payload=decrypted), decrypt_status="ok"
|
|
3239
|
+
)
|
|
3240
|
+
elif show_failed_decryption:
|
|
3241
|
+
printer.print_row(pkt, decrypt_status="fail")
|
|
3242
|
+
else:
|
|
3243
|
+
printer.print_row(pkt)
|
|
3131
3244
|
if count is not None and printer.packet_count >= count:
|
|
3132
3245
|
break
|
|
3133
3246
|
except sat_mod.DockerError as exc:
|
|
@@ -3186,16 +3299,44 @@ def _sat_scan_options(fn):
|
|
|
3186
3299
|
|
|
3187
3300
|
@sat.command("scan")
|
|
3188
3301
|
@_sat_scan_options
|
|
3302
|
+
@click.option(
|
|
3303
|
+
"--key",
|
|
3304
|
+
"-k",
|
|
3305
|
+
type=str,
|
|
3306
|
+
default=None,
|
|
3307
|
+
show_default=False,
|
|
3308
|
+
help="Key to decrypt packet payloads (hex or base64, 16 or 32 bytes). "
|
|
3309
|
+
"Satellite packets always use the UNIX_TIME counter.",
|
|
3310
|
+
)
|
|
3311
|
+
@click.option(
|
|
3312
|
+
"--days",
|
|
3313
|
+
"-d",
|
|
3314
|
+
type=int,
|
|
3315
|
+
default=2,
|
|
3316
|
+
show_default=True,
|
|
3317
|
+
help="Days to search around each packet's timestamp when decrypting",
|
|
3318
|
+
)
|
|
3319
|
+
@click.option(
|
|
3320
|
+
"--show-failed-decryption",
|
|
3321
|
+
is_flag=True,
|
|
3322
|
+
default=False,
|
|
3323
|
+
help="Show packets that fail decryption/authentication with the provided "
|
|
3324
|
+
"key. Adds a DECRYPT column indicating OK/FAIL.",
|
|
3325
|
+
)
|
|
3189
3326
|
def sat_scan(**kwargs) -> None:
|
|
3190
3327
|
"""
|
|
3191
3328
|
Start the satellite receiver and stream decoded packets.
|
|
3192
3329
|
|
|
3193
3330
|
Requires Docker and a PlutoSDR device connected via USB.
|
|
3194
3331
|
|
|
3332
|
+
Pass --key to decrypt packet payloads locally; packets the key cannot
|
|
3333
|
+
decrypt are hidden unless --show-failed-decryption is given.
|
|
3334
|
+
|
|
3195
3335
|
Example:
|
|
3196
3336
|
hubblenetwork sat scan --timeout 30
|
|
3197
3337
|
hubblenetwork sat scan -o json --timeout 10
|
|
3198
3338
|
hubblenetwork sat scan -n 5
|
|
3339
|
+
hubblenetwork sat scan --key "a562a2f7e4c62bed52ab09633878f62b" --timeout 60
|
|
3199
3340
|
"""
|
|
3200
3341
|
_run_sat_scan(mock=False, **kwargs)
|
|
3201
3342
|
|
|
@@ -204,6 +204,43 @@ def decrypt(
|
|
|
204
204
|
return None
|
|
205
205
|
|
|
206
206
|
|
|
207
|
+
def decrypt_satellite(
|
|
208
|
+
key: bytes,
|
|
209
|
+
seq_no: int,
|
|
210
|
+
auth_tag: bytes,
|
|
211
|
+
encrypted_payload: bytes,
|
|
212
|
+
timestamp: Optional[float] = None,
|
|
213
|
+
days: int = 2,
|
|
214
|
+
) -> Optional[bytes]:
|
|
215
|
+
"""Decrypt a satellite packet's encrypted customer payload.
|
|
216
|
+
|
|
217
|
+
Satellite packets deliver the sequence number, 4-byte auth tag, and
|
|
218
|
+
encrypted customer payload as separate fields, unlike BLE where they are
|
|
219
|
+
packed into one advertisement. The underlying AES-256/128-CTR + CMAC
|
|
220
|
+
scheme is identical to BLE (see :func:`decrypt`), and satellite always
|
|
221
|
+
uses the UNIX_TIME (day-based) counter.
|
|
222
|
+
|
|
223
|
+
The day counter is swept +/-``days`` around the packet's ``timestamp``
|
|
224
|
+
(or the current UTC day when ``timestamp`` is None), returning the
|
|
225
|
+
decrypted payload for the first day whose derived auth tag matches.
|
|
226
|
+
|
|
227
|
+
Returns the decrypted payload bytes, or None if no day matches (wrong
|
|
228
|
+
key or outside the search window).
|
|
229
|
+
"""
|
|
230
|
+
keylen = len(key)
|
|
231
|
+
if timestamp is None:
|
|
232
|
+
timestamp = datetime.now(timezone.utc).timestamp()
|
|
233
|
+
base = int(timestamp) // 86400
|
|
234
|
+
|
|
235
|
+
for delta in range(-days, days + 1):
|
|
236
|
+
time_counter = base + delta
|
|
237
|
+
daily_key = _get_encryption_key(key, time_counter, seq_no, keylen=keylen)
|
|
238
|
+
if _get_auth_tag(daily_key, encrypted_payload) == auth_tag:
|
|
239
|
+
nonce = _get_nonce(key, time_counter, seq_no, keylen=keylen)
|
|
240
|
+
return _aes_decrypt(daily_key, nonce, encrypted_payload)
|
|
241
|
+
return None
|
|
242
|
+
|
|
243
|
+
|
|
207
244
|
def find_time_counter_delta(
|
|
208
245
|
key: bytes, encrypted_pkt: EncryptedPacket, max_days_back: int = 365
|
|
209
246
|
) -> Optional[int]:
|
|
@@ -99,3 +99,6 @@ class SatellitePacket:
|
|
|
99
99
|
channel_num: int
|
|
100
100
|
freq_offset_hz: float
|
|
101
101
|
payload: bytes # encrypted payload bytes (base64-decoded from API)
|
|
102
|
+
# 4-byte CMAC auth tag, when reported by the receiver. Needed to locally
|
|
103
|
+
# decrypt the payload (identifies the day counter); None if unavailable.
|
|
104
|
+
auth_tag: Optional[bytes] = None
|
|
@@ -177,6 +177,15 @@ def _parse_jsonl(text: str) -> List[SatellitePacket]:
|
|
|
177
177
|
obj = json.loads(line)
|
|
178
178
|
payload_b64 = obj.get("payload_b64", "")
|
|
179
179
|
payload = base64.b64decode(payload_b64) if payload_b64 else b""
|
|
180
|
+
# The receiver reports the 4-byte CMAC auth tag as a big-endian
|
|
181
|
+
# integer. It's required to locally decrypt the payload; absent for
|
|
182
|
+
# mock packets and older receivers.
|
|
183
|
+
auth_tag_val = obj.get("auth_tag")
|
|
184
|
+
auth_tag = (
|
|
185
|
+
int(auth_tag_val).to_bytes(4, "big")
|
|
186
|
+
if isinstance(auth_tag_val, int)
|
|
187
|
+
else None
|
|
188
|
+
)
|
|
180
189
|
packets.append(
|
|
181
190
|
SatellitePacket(
|
|
182
191
|
device_id=obj["device_id"],
|
|
@@ -187,6 +196,7 @@ def _parse_jsonl(text: str) -> List[SatellitePacket]:
|
|
|
187
196
|
channel_num=obj["channel_num"],
|
|
188
197
|
freq_offset_hz=obj["freq_offset_hz"],
|
|
189
198
|
payload=payload,
|
|
199
|
+
auth_tag=auth_tag,
|
|
190
200
|
)
|
|
191
201
|
)
|
|
192
202
|
except (KeyError, TypeError, json.JSONDecodeError) as exc:
|
|
@@ -453,6 +453,21 @@ class TestCliAesEaxScan:
|
|
|
453
453
|
assert len(parsed) == 1
|
|
454
454
|
assert parsed[0]["protocol_version"] == 5
|
|
455
455
|
|
|
456
|
+
@patch("hubblenetwork.cli.ble_mod.scan_single")
|
|
457
|
+
def test_scan_unknown_packet_hidden_with_key(self, mock_scan):
|
|
458
|
+
"""With --key, unknown (non-decryptable) packets are not shown."""
|
|
459
|
+
pkt = _make_dummy_unknown_packet()
|
|
460
|
+
mock_scan.side_effect = [pkt, None]
|
|
461
|
+
|
|
462
|
+
runner = CliRunner()
|
|
463
|
+
key_b64 = "AAAAAAAAAAAAAAAAAAAAAA=="
|
|
464
|
+
result = runner.invoke(
|
|
465
|
+
cli, ["ble", "scan", "--timeout", "1", "--key", key_b64, "-o", "json"]
|
|
466
|
+
)
|
|
467
|
+
assert result.exit_code == 0
|
|
468
|
+
parsed = json.loads(result.output)
|
|
469
|
+
assert parsed == []
|
|
470
|
+
|
|
456
471
|
|
|
457
472
|
# ---------------------------------------------------------------------------
|
|
458
473
|
# CLI auto-detect tests for AES-EAX packets
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
"""Tests for satellite packet decryption (`decrypt_satellite` and `sat scan --key`)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
from datetime import datetime, timezone
|
|
7
|
+
|
|
8
|
+
import pytest
|
|
9
|
+
from click.testing import CliRunner
|
|
10
|
+
from Crypto.Cipher import AES
|
|
11
|
+
from Crypto.Hash import CMAC
|
|
12
|
+
from Crypto.Protocol.KDF import SP800_108_Counter
|
|
13
|
+
|
|
14
|
+
from hubblenetwork import decrypt_satellite
|
|
15
|
+
from hubblenetwork.cli import cli
|
|
16
|
+
from hubblenetwork.errors import DockerError, SatelliteError
|
|
17
|
+
from hubblenetwork.packets import SatellitePacket
|
|
18
|
+
from hubblenetwork import sat
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
# ---------------------------------------------------------------------------
|
|
22
|
+
# Reference encryption helpers (mirrors firmware / platform-e2e-tests)
|
|
23
|
+
# ---------------------------------------------------------------------------
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _kdf(key: bytes, size: int, label: str, context) -> bytes:
|
|
27
|
+
return SP800_108_Counter(
|
|
28
|
+
key,
|
|
29
|
+
size,
|
|
30
|
+
lambda k, d: CMAC.new(k, d, AES).digest(),
|
|
31
|
+
label=label.encode(),
|
|
32
|
+
context=str(context).encode(),
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _enc_key(master: bytes, time_counter: int, counter: int) -> bytes:
|
|
37
|
+
ek = _kdf(master, len(master), "EncryptionKey", time_counter)
|
|
38
|
+
return _kdf(ek, len(master), "Key", counter)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _nonce(master: bytes, time_counter: int, counter: int) -> bytes:
|
|
42
|
+
nk = _kdf(master, len(master), "NonceKey", time_counter)
|
|
43
|
+
return _kdf(nk, 12, "Nonce", counter)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def make_encrypted_sat_payload(
|
|
47
|
+
master_key: bytes,
|
|
48
|
+
seq_no: int,
|
|
49
|
+
plaintext: bytes,
|
|
50
|
+
time_counter: int,
|
|
51
|
+
) -> tuple[bytes, bytes]:
|
|
52
|
+
"""Return (encrypted_payload, auth_tag) for a satellite packet.
|
|
53
|
+
|
|
54
|
+
Matches the BLE-equivalent AES-CTR + CMAC scheme used by Hubble firmware.
|
|
55
|
+
"""
|
|
56
|
+
enc_key = _enc_key(master_key, time_counter, seq_no)
|
|
57
|
+
nonce = _nonce(master_key, time_counter, seq_no)
|
|
58
|
+
ciphertext = AES.new(enc_key, AES.MODE_CTR, nonce=nonce).encrypt(plaintext)
|
|
59
|
+
auth_tag = CMAC.new(enc_key, ciphertext, AES).digest()[:4]
|
|
60
|
+
return ciphertext, auth_tag
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
_MASTER_256 = bytes(range(32))
|
|
64
|
+
_MASTER_128 = bytes(range(16))
|
|
65
|
+
_TODAY_TC = int(datetime.now(timezone.utc).timestamp()) // 86400
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
# ---------------------------------------------------------------------------
|
|
69
|
+
# decrypt_satellite
|
|
70
|
+
# ---------------------------------------------------------------------------
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class TestDecryptSatellite:
|
|
74
|
+
def test_roundtrip_aes256_today(self):
|
|
75
|
+
plaintext = b"hello sat"
|
|
76
|
+
ct, tag = make_encrypted_sat_payload(_MASTER_256, 5, plaintext, _TODAY_TC)
|
|
77
|
+
out = decrypt_satellite(
|
|
78
|
+
_MASTER_256, seq_no=5, auth_tag=tag, encrypted_payload=ct,
|
|
79
|
+
timestamp=_TODAY_TC * 86400,
|
|
80
|
+
)
|
|
81
|
+
assert out == plaintext
|
|
82
|
+
|
|
83
|
+
def test_roundtrip_aes128(self):
|
|
84
|
+
plaintext = b"abc123"
|
|
85
|
+
ct, tag = make_encrypted_sat_payload(_MASTER_128, 17, plaintext, _TODAY_TC)
|
|
86
|
+
out = decrypt_satellite(
|
|
87
|
+
_MASTER_128, seq_no=17, auth_tag=tag, encrypted_payload=ct,
|
|
88
|
+
timestamp=_TODAY_TC * 86400,
|
|
89
|
+
)
|
|
90
|
+
assert out == plaintext
|
|
91
|
+
|
|
92
|
+
def test_finds_neighbouring_day(self):
|
|
93
|
+
# Packet was encrypted for yesterday but received "today".
|
|
94
|
+
plaintext = b"yesterday"
|
|
95
|
+
enc_tc = _TODAY_TC - 1
|
|
96
|
+
ct, tag = make_encrypted_sat_payload(_MASTER_256, 9, plaintext, enc_tc)
|
|
97
|
+
out = decrypt_satellite(
|
|
98
|
+
_MASTER_256, seq_no=9, auth_tag=tag, encrypted_payload=ct,
|
|
99
|
+
timestamp=_TODAY_TC * 86400, days=2,
|
|
100
|
+
)
|
|
101
|
+
assert out == plaintext
|
|
102
|
+
|
|
103
|
+
def test_wrong_key_returns_none(self):
|
|
104
|
+
ct, tag = make_encrypted_sat_payload(_MASTER_256, 1, b"secret", _TODAY_TC)
|
|
105
|
+
wrong = bytes([0xFF] * 32)
|
|
106
|
+
out = decrypt_satellite(
|
|
107
|
+
wrong, seq_no=1, auth_tag=tag, encrypted_payload=ct,
|
|
108
|
+
timestamp=_TODAY_TC * 86400,
|
|
109
|
+
)
|
|
110
|
+
assert out is None
|
|
111
|
+
|
|
112
|
+
def test_out_of_window_returns_none(self):
|
|
113
|
+
plaintext = b"old"
|
|
114
|
+
enc_tc = _TODAY_TC - 10
|
|
115
|
+
ct, tag = make_encrypted_sat_payload(_MASTER_256, 3, plaintext, enc_tc)
|
|
116
|
+
out = decrypt_satellite(
|
|
117
|
+
_MASTER_256, seq_no=3, auth_tag=tag, encrypted_payload=ct,
|
|
118
|
+
timestamp=_TODAY_TC * 86400, days=2,
|
|
119
|
+
)
|
|
120
|
+
assert out is None
|
|
121
|
+
|
|
122
|
+
def test_timestamp_none_uses_today(self):
|
|
123
|
+
plaintext = b"now"
|
|
124
|
+
ct, tag = make_encrypted_sat_payload(_MASTER_256, 7, plaintext, _TODAY_TC)
|
|
125
|
+
out = decrypt_satellite(
|
|
126
|
+
_MASTER_256, seq_no=7, auth_tag=tag, encrypted_payload=ct,
|
|
127
|
+
)
|
|
128
|
+
assert out == plaintext
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
# ---------------------------------------------------------------------------
|
|
132
|
+
# JSONL parsing of auth_tag
|
|
133
|
+
# ---------------------------------------------------------------------------
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
class TestAuthTagParsing:
|
|
137
|
+
def test_auth_tag_parsed_to_bytes(self):
|
|
138
|
+
payload_b64 = base64.b64encode(b"\x01\x02\x03").decode()
|
|
139
|
+
line = (
|
|
140
|
+
'{"device_id": "0xAA", "seq_num": 1, "device_type": "silabs", '
|
|
141
|
+
'"timestamp": 0.0, "rssi_dB": 0.0, "channel_num": 0, '
|
|
142
|
+
f'"freq_offset_hz": 0.0, "auth_tag": 305419896, "payload_b64": "{payload_b64}"}}\n'
|
|
143
|
+
)
|
|
144
|
+
pkts = sat._parse_jsonl(line)
|
|
145
|
+
assert len(pkts) == 1
|
|
146
|
+
assert pkts[0].auth_tag == (305419896).to_bytes(4, "big")
|
|
147
|
+
|
|
148
|
+
def test_missing_auth_tag_is_none(self):
|
|
149
|
+
payload_b64 = base64.b64encode(b"\x01").decode()
|
|
150
|
+
line = (
|
|
151
|
+
'{"device_id": "0xAA", "seq_num": 1, "device_type": "silabs", '
|
|
152
|
+
'"timestamp": 0.0, "rssi_dB": 0.0, "channel_num": 0, '
|
|
153
|
+
f'"freq_offset_hz": 0.0, "payload_b64": "{payload_b64}"}}\n'
|
|
154
|
+
)
|
|
155
|
+
pkts = sat._parse_jsonl(line)
|
|
156
|
+
assert len(pkts) == 1
|
|
157
|
+
assert pkts[0].auth_tag is None
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
# ---------------------------------------------------------------------------
|
|
161
|
+
# CLI - sat scan --key
|
|
162
|
+
# ---------------------------------------------------------------------------
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _make_encrypted_sat_pkt(seq_no=42, plaintext=b"data_42") -> SatellitePacket:
|
|
166
|
+
ct, tag = make_encrypted_sat_payload(_MASTER_256, seq_no, plaintext, _TODAY_TC)
|
|
167
|
+
return SatellitePacket(
|
|
168
|
+
device_id="0xBB2973BD",
|
|
169
|
+
seq_num=seq_no,
|
|
170
|
+
device_type="silabs",
|
|
171
|
+
timestamp=_TODAY_TC * 86400 + 100,
|
|
172
|
+
rssi_dB=-42.3,
|
|
173
|
+
channel_num=2,
|
|
174
|
+
freq_offset_hz=21654.5,
|
|
175
|
+
payload=ct,
|
|
176
|
+
auth_tag=tag,
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
class TestSatScanKeyCli:
|
|
181
|
+
@pytest.fixture
|
|
182
|
+
def runner(self):
|
|
183
|
+
return CliRunner()
|
|
184
|
+
|
|
185
|
+
def test_key_option_in_help(self, runner):
|
|
186
|
+
result = runner.invoke(cli, ["sat", "scan", "--help"])
|
|
187
|
+
assert result.exit_code == 0
|
|
188
|
+
assert "--key" in result.output
|
|
189
|
+
|
|
190
|
+
def test_decrypts_payload_tabular(self, runner, monkeypatch):
|
|
191
|
+
pkt = _make_encrypted_sat_pkt()
|
|
192
|
+
monkeypatch.setattr(sat, "DockerError", DockerError, raising=False)
|
|
193
|
+
|
|
194
|
+
import hubblenetwork.cli as cli_mod
|
|
195
|
+
|
|
196
|
+
monkeypatch.setattr(cli_mod.sat_mod, "scan", lambda **kw: iter([pkt]))
|
|
197
|
+
monkeypatch.setattr(cli_mod.sat_mod, "ensure_docker_available", lambda: None)
|
|
198
|
+
|
|
199
|
+
result = runner.invoke(
|
|
200
|
+
cli,
|
|
201
|
+
["sat", "scan", "--key", _MASTER_256.hex(), "--timeout", "1",
|
|
202
|
+
"--poll-interval", "0.1", "--payload-format", "string"],
|
|
203
|
+
)
|
|
204
|
+
assert result.exit_code == 0
|
|
205
|
+
assert "data_42" in result.output
|
|
206
|
+
|
|
207
|
+
def test_hides_undecryptable_by_default(self, runner, monkeypatch):
|
|
208
|
+
# Packet that the key cannot decrypt (random ciphertext + bogus tag).
|
|
209
|
+
bad = SatellitePacket(
|
|
210
|
+
device_id="0xBB2973BD", seq_num=1, device_type="silabs",
|
|
211
|
+
timestamp=_TODAY_TC * 86400, rssi_dB=-42.3, channel_num=2,
|
|
212
|
+
freq_offset_hz=21654.5, payload=b"\xde\xad\xbe\xef",
|
|
213
|
+
auth_tag=b"\x00\x00\x00\x00",
|
|
214
|
+
)
|
|
215
|
+
import hubblenetwork.cli as cli_mod
|
|
216
|
+
|
|
217
|
+
monkeypatch.setattr(cli_mod.sat_mod, "scan", lambda **kw: iter([bad]))
|
|
218
|
+
monkeypatch.setattr(cli_mod.sat_mod, "ensure_docker_available", lambda: None)
|
|
219
|
+
|
|
220
|
+
result = runner.invoke(
|
|
221
|
+
cli,
|
|
222
|
+
["sat", "scan", "--key", _MASTER_256.hex(), "--timeout", "1",
|
|
223
|
+
"--poll-interval", "0.1"],
|
|
224
|
+
)
|
|
225
|
+
assert result.exit_code == 0
|
|
226
|
+
assert "0 packet(s) received" in result.output
|
|
227
|
+
|
|
228
|
+
def test_show_failed_decryption(self, runner, monkeypatch):
|
|
229
|
+
bad = SatellitePacket(
|
|
230
|
+
device_id="0xBB2973BD", seq_num=1, device_type="silabs",
|
|
231
|
+
timestamp=_TODAY_TC * 86400, rssi_dB=-42.3, channel_num=2,
|
|
232
|
+
freq_offset_hz=21654.5, payload=b"\xde\xad\xbe\xef",
|
|
233
|
+
auth_tag=b"\x00\x00\x00\x00",
|
|
234
|
+
)
|
|
235
|
+
import hubblenetwork.cli as cli_mod
|
|
236
|
+
|
|
237
|
+
monkeypatch.setattr(cli_mod.sat_mod, "scan", lambda **kw: iter([bad]))
|
|
238
|
+
monkeypatch.setattr(cli_mod.sat_mod, "ensure_docker_available", lambda: None)
|
|
239
|
+
|
|
240
|
+
result = runner.invoke(
|
|
241
|
+
cli,
|
|
242
|
+
["sat", "scan", "--key", _MASTER_256.hex(),
|
|
243
|
+
"--show-failed-decryption", "--timeout", "1", "--poll-interval", "0.1"],
|
|
244
|
+
)
|
|
245
|
+
assert result.exit_code == 0
|
|
246
|
+
assert "FAIL" in result.output
|
|
247
|
+
assert "1 packet(s) received" in result.output
|
|
248
|
+
|
|
249
|
+
def test_decrypts_payload_json(self, runner, monkeypatch):
|
|
250
|
+
pkt = _make_encrypted_sat_pkt(seq_no=42, plaintext=b"hello")
|
|
251
|
+
import hubblenetwork.cli as cli_mod
|
|
252
|
+
|
|
253
|
+
monkeypatch.setattr(cli_mod.sat_mod, "scan", lambda **kw: iter([pkt]))
|
|
254
|
+
monkeypatch.setattr(cli_mod.sat_mod, "ensure_docker_available", lambda: None)
|
|
255
|
+
|
|
256
|
+
result = runner.invoke(
|
|
257
|
+
cli,
|
|
258
|
+
["sat", "scan", "-o", "json", "--key", _MASTER_256.hex(),
|
|
259
|
+
"--show-failed-decryption", "--payload-format", "string",
|
|
260
|
+
"--timeout", "1", "--poll-interval", "0.1"],
|
|
261
|
+
)
|
|
262
|
+
assert result.exit_code == 0
|
|
263
|
+
assert "hello" in result.output
|
|
264
|
+
assert '"decrypt_status": "ok"' in result.output
|
|
265
|
+
|
|
266
|
+
def test_decrypts_payload_json_no_status_without_flag(self, runner, monkeypatch):
|
|
267
|
+
# Without --show-failed-decryption, no decrypt_status field (matches BLE).
|
|
268
|
+
pkt = _make_encrypted_sat_pkt(seq_no=42, plaintext=b"hello")
|
|
269
|
+
import hubblenetwork.cli as cli_mod
|
|
270
|
+
|
|
271
|
+
monkeypatch.setattr(cli_mod.sat_mod, "scan", lambda **kw: iter([pkt]))
|
|
272
|
+
monkeypatch.setattr(cli_mod.sat_mod, "ensure_docker_available", lambda: None)
|
|
273
|
+
|
|
274
|
+
result = runner.invoke(
|
|
275
|
+
cli,
|
|
276
|
+
["sat", "scan", "-o", "json", "--key", _MASTER_256.hex(),
|
|
277
|
+
"--payload-format", "string", "--timeout", "1", "--poll-interval", "0.1"],
|
|
278
|
+
)
|
|
279
|
+
assert result.exit_code == 0
|
|
280
|
+
assert "hello" in result.output
|
|
281
|
+
assert "decrypt_status" not in result.output
|
|
@@ -192,3 +192,56 @@ def test_scan_count_with_unencrypted(mock_scan):
|
|
|
192
192
|
assert result.exit_code == 0
|
|
193
193
|
parsed = json.loads(result.output)
|
|
194
194
|
assert len(parsed) == 2
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
# A valid 16-byte AES-128 key in base64 (decryption path is never hit for v1).
|
|
198
|
+
_KEY_B64 = "AAAAAAAAAAAAAAAAAAAAAA=="
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
@patch("hubblenetwork.cli.ble_mod.scan_single")
|
|
202
|
+
def test_scan_with_key_hides_unencrypted(mock_scan):
|
|
203
|
+
"""With --key, version-1 (unencrypted) packets are not shown."""
|
|
204
|
+
pkt = _make_unencrypted_packet()
|
|
205
|
+
mock_scan.side_effect = [pkt, None]
|
|
206
|
+
|
|
207
|
+
runner = CliRunner()
|
|
208
|
+
result = runner.invoke(
|
|
209
|
+
cli, ["ble", "scan", "--timeout", "1", "--key", _KEY_B64, "-o", "json"]
|
|
210
|
+
)
|
|
211
|
+
assert result.exit_code == 0
|
|
212
|
+
parsed = json.loads(result.output)
|
|
213
|
+
assert parsed == []
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
@patch("hubblenetwork.cli.ble_mod.scan_single")
|
|
217
|
+
def test_scan_with_key_hides_unencrypted_even_with_show_failed(mock_scan):
|
|
218
|
+
"""--show-failed-decryption is about encrypted packets; v1 stays hidden with a key."""
|
|
219
|
+
pkt = _make_unencrypted_packet()
|
|
220
|
+
mock_scan.side_effect = [pkt, None]
|
|
221
|
+
|
|
222
|
+
runner = CliRunner()
|
|
223
|
+
result = runner.invoke(
|
|
224
|
+
cli,
|
|
225
|
+
[
|
|
226
|
+
"ble", "scan", "--timeout", "1", "--key", _KEY_B64,
|
|
227
|
+
"-o", "json", "--show-failed-decryption",
|
|
228
|
+
],
|
|
229
|
+
)
|
|
230
|
+
assert result.exit_code == 0
|
|
231
|
+
parsed = json.loads(result.output)
|
|
232
|
+
assert parsed == []
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
@patch("hubblenetwork.cli.ble_mod.scan_single")
|
|
236
|
+
def test_scan_without_key_still_shows_unencrypted(mock_scan):
|
|
237
|
+
"""Without a key, version-1 packets are shown as before."""
|
|
238
|
+
pkt = _make_unencrypted_packet()
|
|
239
|
+
mock_scan.side_effect = [pkt, None]
|
|
240
|
+
|
|
241
|
+
runner = CliRunner()
|
|
242
|
+
result = runner.invoke(
|
|
243
|
+
cli, ["ble", "scan", "--timeout", "1", "-o", "json"]
|
|
244
|
+
)
|
|
245
|
+
assert result.exit_code == 0
|
|
246
|
+
parsed = json.loads(result.output)
|
|
247
|
+
assert len(parsed) == 1
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|