pyhubblenetwork 0.9.0__tar.gz → 0.10.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.9.0 → pyhubblenetwork-0.10.0}/PKG-INFO +1 -1
- {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.0}/pyproject.toml +1 -1
- {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.0}/src/hubblenetwork/cli.py +188 -46
- {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.0}/src/hubblenetwork/crypto.py +9 -9
- {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.0}/tests/test_aes_eax.py +144 -0
- pyhubblenetwork-0.10.0/tests/test_cli_ctr_autodetect.py +137 -0
- {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.0}/.gitignore +0 -0
- {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.0}/LICENSE +0 -0
- {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.0}/README.md +0 -0
- {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.0}/plugins/pyhubblenetwork/skills/hubble-ready-test/README.md +0 -0
- {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.0}/src/hubblenetwork/__init__.py +0 -0
- {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.0}/src/hubblenetwork/ble.py +0 -0
- {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.0}/src/hubblenetwork/cloud.py +0 -0
- {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.0}/src/hubblenetwork/device.py +0 -0
- {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.0}/src/hubblenetwork/errors.py +0 -0
- {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.0}/src/hubblenetwork/org.py +0 -0
- {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.0}/src/hubblenetwork/packets.py +0 -0
- {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.0}/src/hubblenetwork/ready.py +0 -0
- {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.0}/src/hubblenetwork/sat.py +0 -0
- {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.0}/tests/__init__.py +0 -0
- {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.0}/tests/conftest.py +0 -0
- {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.0}/tests/test_ble_validate.py +0 -0
- {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.0}/tests/test_cli_payload.py +0 -0
- {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.0}/tests/test_cloud_integration.py +0 -0
- {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.0}/tests/test_counter_eid.py +0 -0
- {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.0}/tests/test_metrics.py +0 -0
- {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.0}/tests/test_org_delete_device.py +0 -0
- {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.0}/tests/test_register_device_cloud.py +0 -0
- {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.0}/tests/test_register_device_validation.py +0 -0
- {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.0}/tests/test_sat.py +0 -0
- {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.0}/tests/test_sat_integration.py +0 -0
- {pyhubblenetwork-0.9.0 → pyhubblenetwork-0.10.0}/tests/test_unencrypted.py +0 -0
|
@@ -34,6 +34,31 @@ _handler.setFormatter(logging.Formatter("%(levelname)s - %(message)s"))
|
|
|
34
34
|
logger.addHandler(_handler)
|
|
35
35
|
|
|
36
36
|
|
|
37
|
+
def _parse_key(key_str: str) -> bytes:
|
|
38
|
+
"""Parse an encryption key from hex or base64. Returns raw bytes.
|
|
39
|
+
|
|
40
|
+
Accepts 128-bit (16 bytes) or 256-bit (32 bytes) keys.
|
|
41
|
+
Strings of exactly 32 or 64 characters are tried as hex first, then base64.
|
|
42
|
+
"""
|
|
43
|
+
s = key_str.strip()
|
|
44
|
+
if len(s) in (32, 64):
|
|
45
|
+
try:
|
|
46
|
+
return bytes.fromhex(s)
|
|
47
|
+
except ValueError:
|
|
48
|
+
pass
|
|
49
|
+
try:
|
|
50
|
+
key_bytes = base64.b64decode(s, validate=True)
|
|
51
|
+
except binascii.Error as e:
|
|
52
|
+
raise ValueError(
|
|
53
|
+
f"Invalid key format: {e}. Provide hex (32 or 64 hex chars) or base64."
|
|
54
|
+
)
|
|
55
|
+
if len(key_bytes) not in (16, 32):
|
|
56
|
+
raise ValueError(
|
|
57
|
+
f"Key must be 16 bytes (AES-128) or 32 bytes (AES-256), got {len(key_bytes)}."
|
|
58
|
+
)
|
|
59
|
+
return key_bytes
|
|
60
|
+
|
|
61
|
+
|
|
37
62
|
def _validate_info(msg):
|
|
38
63
|
click.secho("[INFO] ", fg="cyan", bold=True, nl=False)
|
|
39
64
|
click.echo(msg + "... ", nl=False)
|
|
@@ -87,6 +112,87 @@ def _detect_eid_type(
|
|
|
87
112
|
return (None, None, None, False)
|
|
88
113
|
|
|
89
114
|
|
|
115
|
+
def _decrypt_eax_with_detect(
|
|
116
|
+
key: bytes,
|
|
117
|
+
pkt: AesEaxPacket,
|
|
118
|
+
*,
|
|
119
|
+
auto_detect: bool,
|
|
120
|
+
fixed_exponent: int,
|
|
121
|
+
cache: dict,
|
|
122
|
+
announced: list[str],
|
|
123
|
+
printer,
|
|
124
|
+
) -> Optional[DecryptedPacket]:
|
|
125
|
+
if not auto_detect:
|
|
126
|
+
return decrypt_eax(key, pkt, period_exponent=fixed_exponent)
|
|
127
|
+
|
|
128
|
+
cached = cache.get(pkt.eid)
|
|
129
|
+
if cached is not None:
|
|
130
|
+
result = decrypt_eax(key, pkt, period_exponent=cached)
|
|
131
|
+
if result:
|
|
132
|
+
return result
|
|
133
|
+
|
|
134
|
+
for candidate in range(16):
|
|
135
|
+
result = decrypt_eax(key, pkt, period_exponent=candidate)
|
|
136
|
+
if result is None:
|
|
137
|
+
continue
|
|
138
|
+
cache[pkt.eid] = candidate
|
|
139
|
+
if not announced and not printer.suppress_info_messages:
|
|
140
|
+
announced.append("eax")
|
|
141
|
+
click.secho(
|
|
142
|
+
f"[INFO] Detected: AES-128-EAX, counter_source=DEVICE_UPTIME, "
|
|
143
|
+
f"period_exponent={candidate} (period={1 << candidate}s)",
|
|
144
|
+
fg="green",
|
|
145
|
+
err=True,
|
|
146
|
+
)
|
|
147
|
+
return result
|
|
148
|
+
return None
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _decrypt_ctr_with_detect(
|
|
152
|
+
key: bytes,
|
|
153
|
+
pkt: EncryptedPacket,
|
|
154
|
+
*,
|
|
155
|
+
auto_detect: bool,
|
|
156
|
+
fixed_counter_mode: str,
|
|
157
|
+
days: int,
|
|
158
|
+
cache: dict,
|
|
159
|
+
announced: list[str],
|
|
160
|
+
printer,
|
|
161
|
+
) -> Optional[DecryptedPacket]:
|
|
162
|
+
if not auto_detect:
|
|
163
|
+
return decrypt(key, pkt, days=days, counter_mode=fixed_counter_mode)
|
|
164
|
+
|
|
165
|
+
def _try(mode: str) -> Optional[DecryptedPacket]:
|
|
166
|
+
kwargs = {"counter_mode": mode}
|
|
167
|
+
if mode == UNIX_TIME:
|
|
168
|
+
kwargs["days"] = days
|
|
169
|
+
return decrypt(key, pkt, **kwargs)
|
|
170
|
+
|
|
171
|
+
if pkt.eid is not None:
|
|
172
|
+
cached = cache.get(pkt.eid)
|
|
173
|
+
if cached is not None:
|
|
174
|
+
result = _try(cached)
|
|
175
|
+
if result:
|
|
176
|
+
return result
|
|
177
|
+
|
|
178
|
+
for mode in (UNIX_TIME, DEVICE_UPTIME):
|
|
179
|
+
result = _try(mode)
|
|
180
|
+
if result is None:
|
|
181
|
+
continue
|
|
182
|
+
if pkt.eid is not None:
|
|
183
|
+
cache[pkt.eid] = mode
|
|
184
|
+
if not announced and not printer.suppress_info_messages:
|
|
185
|
+
announced.append("ctr")
|
|
186
|
+
variant = "AES-128-CTR" if len(key) == 16 else "AES-256-CTR"
|
|
187
|
+
click.secho(
|
|
188
|
+
f"[INFO] Detected: {variant}, counter_source={mode}",
|
|
189
|
+
fg="green",
|
|
190
|
+
err=True,
|
|
191
|
+
)
|
|
192
|
+
return result
|
|
193
|
+
return None
|
|
194
|
+
|
|
195
|
+
|
|
90
196
|
def _format_payload(payload, fmt: str) -> str:
|
|
91
197
|
"""Format packet payload bytes for display."""
|
|
92
198
|
if not isinstance(payload, bytes):
|
|
@@ -695,7 +801,7 @@ def ble() -> None:
|
|
|
695
801
|
type=str,
|
|
696
802
|
default=None,
|
|
697
803
|
show_default=False,
|
|
698
|
-
help="Key to decrypt packets (base64
|
|
804
|
+
help="Key to decrypt packets (hex or base64, 16 or 32 bytes)",
|
|
699
805
|
)
|
|
700
806
|
@click.option(
|
|
701
807
|
"--days",
|
|
@@ -753,8 +859,8 @@ def ble_detect(
|
|
|
753
859
|
The key parameter is required. Check the 'success' field in JSON output.
|
|
754
860
|
|
|
755
861
|
Example:
|
|
756
|
-
hubblenetwork ble detect --key "
|
|
757
|
-
hubblenetwork ble detect -k "
|
|
862
|
+
hubblenetwork ble detect --key "a562a2f7e4c62bed52ab09633878f62b" --timeout 20
|
|
863
|
+
hubblenetwork ble detect -k "q9vH3u2J4aN8Rw1KpZsO+A==" -o tabular
|
|
758
864
|
"""
|
|
759
865
|
use_json = output_format.lower() == "json"
|
|
760
866
|
|
|
@@ -774,13 +880,12 @@ def ble_detect(
|
|
|
774
880
|
else:
|
|
775
881
|
click.secho(f"[ERROR] {msg}", fg="red", err=True)
|
|
776
882
|
|
|
777
|
-
# Try to decode the base64 key
|
|
778
883
|
try:
|
|
779
|
-
decoded_key = bytearray(
|
|
884
|
+
decoded_key = bytearray(_parse_key(key))
|
|
780
885
|
logger.debug("Key decoded successfully")
|
|
781
|
-
except
|
|
782
|
-
logger.error(f"
|
|
783
|
-
_output_error("
|
|
886
|
+
except ValueError as e:
|
|
887
|
+
logger.error(f"Key decoding failed: {e}")
|
|
888
|
+
_output_error(f"Key decoding failed: {e}")
|
|
784
889
|
return
|
|
785
890
|
|
|
786
891
|
# Set up timeout tracking
|
|
@@ -874,7 +979,7 @@ def ble_detect(
|
|
|
874
979
|
type=str,
|
|
875
980
|
default=None,
|
|
876
981
|
show_default=False,
|
|
877
|
-
help="
|
|
982
|
+
help="Key to decrypt packets (hex or base64, 16 or 32 bytes)",
|
|
878
983
|
)
|
|
879
984
|
@click.option(
|
|
880
985
|
"--days",
|
|
@@ -886,17 +991,18 @@ def ble_detect(
|
|
|
886
991
|
)
|
|
887
992
|
@click.option(
|
|
888
993
|
"--counter-mode",
|
|
889
|
-
type=click.Choice([
|
|
890
|
-
default=
|
|
994
|
+
type=click.Choice([UNIX_TIME, DEVICE_UPTIME], case_sensitive=False),
|
|
995
|
+
default=UNIX_TIME,
|
|
891
996
|
show_default=True,
|
|
892
997
|
help="EID counter mode for AES-CTR packets",
|
|
893
998
|
)
|
|
894
999
|
@click.option(
|
|
895
|
-
"--
|
|
1000
|
+
"--period-exponent",
|
|
1001
|
+
"-e",
|
|
896
1002
|
type=int,
|
|
897
1003
|
default=0,
|
|
898
1004
|
show_default=True,
|
|
899
|
-
help="
|
|
1005
|
+
help="EID rotation period exponent for AES-EAX packets (0-15). Period = 2^n seconds. Matches rot_exp in device config.",
|
|
900
1006
|
)
|
|
901
1007
|
@click.option(
|
|
902
1008
|
"--network-id",
|
|
@@ -939,7 +1045,7 @@ def ble_scan(
|
|
|
939
1045
|
key: Optional[str] = None,
|
|
940
1046
|
days: int = 2,
|
|
941
1047
|
counter_mode: str = "UNIX_TIME",
|
|
942
|
-
|
|
1048
|
+
period_exponent: int = 0,
|
|
943
1049
|
output_format: str = "tabular",
|
|
944
1050
|
payload_format: str = "base64",
|
|
945
1051
|
show_failed_decryption: bool = False,
|
|
@@ -951,7 +1057,7 @@ def ble_scan(
|
|
|
951
1057
|
|
|
952
1058
|
Example:
|
|
953
1059
|
hubblenetwork ble scan --timeout 30
|
|
954
|
-
hubblenetwork ble scan --key "
|
|
1060
|
+
hubblenetwork ble scan --key "a562a2f7e4c62bed52ab09633878f62b" --timeout 60
|
|
955
1061
|
hubblenetwork ble scan -o json --timeout 10
|
|
956
1062
|
hubblenetwork ble scan -n 5 # Stop after 5 packets
|
|
957
1063
|
hubblenetwork ble scan --network-id 4378792717
|
|
@@ -990,13 +1096,39 @@ def ble_scan(
|
|
|
990
1096
|
decoded_key: Optional[bytearray] = None
|
|
991
1097
|
if key:
|
|
992
1098
|
try:
|
|
993
|
-
decoded_key = bytearray(
|
|
994
|
-
except
|
|
1099
|
+
decoded_key = bytearray(_parse_key(key))
|
|
1100
|
+
except ValueError as e:
|
|
995
1101
|
if printer.suppress_info_messages:
|
|
996
1102
|
click.echo(json.dumps({"error": f"Invalid base64 key: {e}"}))
|
|
997
1103
|
return
|
|
998
1104
|
raise click.ClickException(f"Invalid base64 key: {e}")
|
|
999
1105
|
|
|
1106
|
+
# Click's parameter source lets users disable auto-detect by passing the
|
|
1107
|
+
# default value verbatim — otherwise we couldn't tell "default" apart
|
|
1108
|
+
# from "user explicitly chose UNIX_TIME / exponent=0".
|
|
1109
|
+
def _explicit(name: str) -> bool:
|
|
1110
|
+
return ctx.get_parameter_source(name) == click.core.ParameterSource.COMMANDLINE
|
|
1111
|
+
|
|
1112
|
+
auto_detect_ctr = decoded_key is not None and not _explicit("counter_mode")
|
|
1113
|
+
auto_detect_eax = decoded_key is not None and not _explicit("period_exponent")
|
|
1114
|
+
|
|
1115
|
+
if (auto_detect_ctr or auto_detect_eax) and not printer.suppress_info_messages:
|
|
1116
|
+
parts = []
|
|
1117
|
+
if auto_detect_ctr:
|
|
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
|
+
)
|
|
1127
|
+
|
|
1128
|
+
detected_ctr_modes: dict = {}
|
|
1129
|
+
detected_eax_exponents: dict = {}
|
|
1130
|
+
announced: list[str] = []
|
|
1131
|
+
|
|
1000
1132
|
try:
|
|
1001
1133
|
while deadline is None or time.monotonic() < deadline:
|
|
1002
1134
|
# Check if we've hit the count limit
|
|
@@ -1019,7 +1151,15 @@ def ble_scan(
|
|
|
1019
1151
|
# AES-EAX packets: decrypt if key provided, else show raw fields
|
|
1020
1152
|
elif isinstance(pkt, AesEaxPacket):
|
|
1021
1153
|
if decoded_key:
|
|
1022
|
-
decrypted_pkt =
|
|
1154
|
+
decrypted_pkt = _decrypt_eax_with_detect(
|
|
1155
|
+
decoded_key,
|
|
1156
|
+
pkt,
|
|
1157
|
+
auto_detect=auto_detect_eax,
|
|
1158
|
+
fixed_exponent=period_exponent,
|
|
1159
|
+
cache=detected_eax_exponents,
|
|
1160
|
+
announced=announced,
|
|
1161
|
+
printer=printer,
|
|
1162
|
+
)
|
|
1023
1163
|
if decrypted_pkt:
|
|
1024
1164
|
printer.print_row(decrypted_pkt, decrypt_status="ok")
|
|
1025
1165
|
elif show_failed_decryption:
|
|
@@ -1028,8 +1168,15 @@ def ble_scan(
|
|
|
1028
1168
|
printer.print_row(pkt)
|
|
1029
1169
|
elif isinstance(pkt, EncryptedPacket):
|
|
1030
1170
|
if decoded_key:
|
|
1031
|
-
decrypted_pkt =
|
|
1032
|
-
decoded_key,
|
|
1171
|
+
decrypted_pkt = _decrypt_ctr_with_detect(
|
|
1172
|
+
decoded_key,
|
|
1173
|
+
pkt,
|
|
1174
|
+
auto_detect=auto_detect_ctr,
|
|
1175
|
+
fixed_counter_mode=counter_mode,
|
|
1176
|
+
days=days,
|
|
1177
|
+
cache=detected_ctr_modes,
|
|
1178
|
+
announced=announced,
|
|
1179
|
+
printer=printer,
|
|
1033
1180
|
)
|
|
1034
1181
|
if decrypted_pkt:
|
|
1035
1182
|
printer.print_row(decrypted_pkt, decrypt_status="ok")
|
|
@@ -1069,7 +1216,7 @@ def ble_scan(
|
|
|
1069
1216
|
"-k",
|
|
1070
1217
|
required=True,
|
|
1071
1218
|
type=str,
|
|
1072
|
-
help="Key for checking time counter (base64
|
|
1219
|
+
help="Key for checking time counter (hex or base64, 16 or 32 bytes)",
|
|
1073
1220
|
)
|
|
1074
1221
|
@click.option(
|
|
1075
1222
|
"--json-output",
|
|
@@ -1091,20 +1238,15 @@ def ble_check_time(
|
|
|
1091
1238
|
A device is considered out of spec if it is more than 2 days off.
|
|
1092
1239
|
|
|
1093
1240
|
Example:
|
|
1094
|
-
hubblenetwork ble check-time --key "
|
|
1241
|
+
hubblenetwork ble check-time --key "a562a2f7e4c62bed52ab09633878f62b" --timeout 30
|
|
1095
1242
|
"""
|
|
1096
|
-
# Decode the key
|
|
1097
1243
|
try:
|
|
1098
|
-
decoded_key = bytearray(
|
|
1099
|
-
except
|
|
1244
|
+
decoded_key = bytearray(_parse_key(key))
|
|
1245
|
+
except ValueError as e:
|
|
1100
1246
|
if json_output:
|
|
1101
|
-
click.echo(json.dumps({"error":
|
|
1247
|
+
click.echo(json.dumps({"error": str(e)}))
|
|
1102
1248
|
else:
|
|
1103
|
-
click.secho(
|
|
1104
|
-
f"[ERROR] Base64 decoding failed for provided key: {e}",
|
|
1105
|
-
fg="red",
|
|
1106
|
-
err=True,
|
|
1107
|
-
)
|
|
1249
|
+
click.secho(f"[ERROR] {e}", fg="red", err=True)
|
|
1108
1250
|
return
|
|
1109
1251
|
|
|
1110
1252
|
if not json_output:
|
|
@@ -1232,14 +1374,15 @@ def ble_validate(key: str, device_id: str, org_id: str, token: str, timeout: int
|
|
|
1232
1374
|
# Step 1: Validate inputs
|
|
1233
1375
|
_validate_info("Validating format of inputs")
|
|
1234
1376
|
try:
|
|
1235
|
-
decoded_key =
|
|
1236
|
-
except
|
|
1377
|
+
decoded_key = _parse_key(key)
|
|
1378
|
+
except ValueError as e:
|
|
1237
1379
|
_validate_error(
|
|
1238
|
-
'Incorrectly formatted device key
|
|
1239
|
-
'\
|
|
1240
|
-
'\n
|
|
1241
|
-
'\n
|
|
1242
|
-
'\
|
|
1380
|
+
f'Incorrectly formatted device key: {e}'
|
|
1381
|
+
'\nAccepted formats (fake keys):'
|
|
1382
|
+
'\n Hex 16-byte: "a562a2f7e4c62bed52ab09633878f62b"'
|
|
1383
|
+
'\n Hex 32-byte: "a562a2f7e4c62bed52ab09633878f62ba562a2f7e4c62bed52ab09633878f62b"'
|
|
1384
|
+
'\n Base64 16-byte: "q9vH3u2J4aN8Rw1KpZsO+A=="'
|
|
1385
|
+
'\n Base64 32-byte: "N4e7xq9X1pQ0sVbY2mT3uA6fH9rK2dW5cG8jL1oQ0vU="'
|
|
1243
1386
|
)
|
|
1244
1387
|
try:
|
|
1245
1388
|
uuid.UUID(device_id)
|
|
@@ -2070,7 +2213,7 @@ def ready_read_time(
|
|
|
2070
2213
|
"--key",
|
|
2071
2214
|
"-k",
|
|
2072
2215
|
required=True,
|
|
2073
|
-
help="
|
|
2216
|
+
help="Encryption key (hex or base64; 16 bytes = AES-128-CTR, 32 bytes = AES-256-CTR)",
|
|
2074
2217
|
)
|
|
2075
2218
|
@click.option(
|
|
2076
2219
|
"--timeout",
|
|
@@ -2100,25 +2243,24 @@ def ready_write_key(
|
|
|
2100
2243
|
32 bytes for AES-256-CTR).
|
|
2101
2244
|
|
|
2102
2245
|
Example:
|
|
2103
|
-
hubblenetwork ready write-key --address AA:BB:CC:DD:EE:FF --key
|
|
2104
|
-
hubblenetwork ready write-key -a AA:BB:CC:DD:EE:FF -k
|
|
2246
|
+
hubblenetwork ready write-key --address AA:BB:CC:DD:EE:FF --key a562a2f7e4c62bed52ab09633878f62b
|
|
2247
|
+
hubblenetwork ready write-key -a AA:BB:CC:DD:EE:FF -k "q9vH3u2J4aN8Rw1KpZsO+A==" --format json
|
|
2105
2248
|
"""
|
|
2106
2249
|
use_json = output_format.lower() == "json"
|
|
2107
2250
|
|
|
2108
|
-
# Decode the base64 key
|
|
2109
2251
|
try:
|
|
2110
|
-
key_bytes =
|
|
2111
|
-
except
|
|
2252
|
+
key_bytes = _parse_key(key)
|
|
2253
|
+
except ValueError as e:
|
|
2112
2254
|
if use_json:
|
|
2113
2255
|
json_output = _format_ready_json_error(
|
|
2114
2256
|
command="ready write-key",
|
|
2115
2257
|
device_address=address,
|
|
2116
|
-
error=Exception(
|
|
2258
|
+
error=Exception(str(e)),
|
|
2117
2259
|
duration_ms=0,
|
|
2118
2260
|
)
|
|
2119
2261
|
click.echo(json.dumps(json_output, indent=2))
|
|
2120
2262
|
else:
|
|
2121
|
-
click.secho(f"[ERROR]
|
|
2263
|
+
click.secho(f"[ERROR] {e}", fg="red", err=True)
|
|
2122
2264
|
sys.exit(1)
|
|
2123
2265
|
|
|
2124
2266
|
if not use_json:
|
|
@@ -77,11 +77,11 @@ def _derive_eid_key(key: bytes, counter: int) -> bytes:
|
|
|
77
77
|
return AES.new(key, AES.MODE_ECB).encrypt(msg1)
|
|
78
78
|
|
|
79
79
|
|
|
80
|
-
def _generate_eid(key: bytes, counter: int,
|
|
80
|
+
def _generate_eid(key: bytes, counter: int, period_exponent: int = 0) -> int:
|
|
81
81
|
"""Generate an 8-byte EID for a given counter value using AES-ECB."""
|
|
82
82
|
key_0 = _derive_eid_key(key, counter)
|
|
83
|
-
masked = counter & ~((1 <<
|
|
84
|
-
msg2 = b"\x00" * 11 +
|
|
83
|
+
masked = counter & ~((1 << period_exponent) - 1)
|
|
84
|
+
msg2 = b"\x00" * 11 + period_exponent.to_bytes(1, "big") + masked.to_bytes(4, "big")
|
|
85
85
|
eid_block = AES.new(key_0, AES.MODE_ECB).encrypt(msg2)
|
|
86
86
|
return int.from_bytes(eid_block[0:8], "big")
|
|
87
87
|
|
|
@@ -89,7 +89,7 @@ def _generate_eid(key: bytes, counter: int, scale_factor: int = 0) -> int:
|
|
|
89
89
|
def decrypt_eax(
|
|
90
90
|
key: bytes,
|
|
91
91
|
pkt: AesEaxPacket,
|
|
92
|
-
|
|
92
|
+
period_exponent: int = 0,
|
|
93
93
|
pool_size: int = 128,
|
|
94
94
|
) -> Optional[DecryptedPacket]:
|
|
95
95
|
"""Decrypt an AES-EAX packet by trying candidate counters.
|
|
@@ -98,19 +98,19 @@ def decrypt_eax(
|
|
|
98
98
|
the packet's EID. On match, constructs the nonce and decrypts.
|
|
99
99
|
|
|
100
100
|
Args:
|
|
101
|
-
|
|
102
|
-
are multiples of 2**
|
|
103
|
-
in device config or log2(period_in_seconds) in the API.
|
|
101
|
+
period_exponent: EID rotation period exponent (0-15). Period = 2^n seconds.
|
|
102
|
+
Counter values are multiples of 2**period_exponent. Corresponds to
|
|
103
|
+
rot_exp in device config or log2(period_in_seconds) in the API.
|
|
104
104
|
pool_size: Number of counters to try (default 128).
|
|
105
105
|
"""
|
|
106
|
-
step = 1 <<
|
|
106
|
+
step = 1 << period_exponent
|
|
107
107
|
# key_0 is constant when high counter bytes are 00 00 (counter < 65536)
|
|
108
108
|
key_0 = _derive_eid_key(key, 0)
|
|
109
109
|
ecb = AES.new(key_0, AES.MODE_ECB)
|
|
110
110
|
|
|
111
111
|
for i in range(pool_size):
|
|
112
112
|
counter = i * step
|
|
113
|
-
msg2 = b"\x00" * 11 +
|
|
113
|
+
msg2 = b"\x00" * 11 + period_exponent.to_bytes(1, "big") + counter.to_bytes(4, "big")
|
|
114
114
|
eid_block = ecb.encrypt(msg2)
|
|
115
115
|
candidate_eid = int.from_bytes(eid_block[0:8], "big")
|
|
116
116
|
|
|
@@ -454,6 +454,150 @@ class TestCliAesEaxScan:
|
|
|
454
454
|
assert parsed[0]["protocol_version"] == 5
|
|
455
455
|
|
|
456
456
|
|
|
457
|
+
# ---------------------------------------------------------------------------
|
|
458
|
+
# CLI auto-detect tests for AES-EAX packets
|
|
459
|
+
# ---------------------------------------------------------------------------
|
|
460
|
+
|
|
461
|
+
|
|
462
|
+
def _build_eax_packet_at_exponent(key: bytes, period_exponent: int, plaintext: bytes) -> AesEaxPacket:
|
|
463
|
+
"""Build a real AES-EAX packet whose EID/tag matches the given exponent."""
|
|
464
|
+
from hubblenetwork.crypto import _generate_eid as gen_eid
|
|
465
|
+
# Pick a counter that's a multiple of the step (so it's enumerable
|
|
466
|
+
# by decrypt_eax with this exponent).
|
|
467
|
+
step = 1 << period_exponent
|
|
468
|
+
counter = 3 * step # 3rd slot
|
|
469
|
+
eid = gen_eid(key, counter, period_exponent=period_exponent)
|
|
470
|
+
nonce_salt = b"\x9A\xBC"
|
|
471
|
+
nonce = counter.to_bytes(4, "big") + nonce_salt
|
|
472
|
+
cipher = _AES.new(key, _AES.MODE_EAX, mac_len=4, nonce=nonce)
|
|
473
|
+
ciphertext, tag = cipher.encrypt_and_digest(plaintext)
|
|
474
|
+
return AesEaxPacket(
|
|
475
|
+
timestamp=1700000000,
|
|
476
|
+
location=_FAKE_LOCATION,
|
|
477
|
+
protocol_version=2,
|
|
478
|
+
nonce_salt=nonce_salt,
|
|
479
|
+
eid=eid,
|
|
480
|
+
payload=ciphertext,
|
|
481
|
+
auth_tag=tag,
|
|
482
|
+
rssi=-70,
|
|
483
|
+
)
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
_EAX_KEY_HEX = _EAX_KEY.hex()
|
|
487
|
+
|
|
488
|
+
|
|
489
|
+
class TestCliAesEaxAutoDetect:
|
|
490
|
+
@patch("hubblenetwork.cli.ble_mod.scan_single")
|
|
491
|
+
def test_auto_detect_finds_correct_exponent(self, mock_scan):
|
|
492
|
+
"""Without -e, auto-detect resolves period_exponent and decrypts."""
|
|
493
|
+
pkt = _build_eax_packet_at_exponent(_EAX_KEY, period_exponent=12, plaintext=b"hi-eax")
|
|
494
|
+
mock_scan.side_effect = [pkt, None]
|
|
495
|
+
|
|
496
|
+
runner = CliRunner()
|
|
497
|
+
result = runner.invoke(cli, ["ble", "scan", "--timeout", "1", "--key", _EAX_KEY_HEX])
|
|
498
|
+
assert result.exit_code == 0
|
|
499
|
+
assert "[WARN]" in result.stderr
|
|
500
|
+
assert "Auto-detecting" in result.stderr
|
|
501
|
+
assert "period_exponent=12" in result.stderr
|
|
502
|
+
assert "period=4096s" in result.stderr
|
|
503
|
+
# decrypted payload appears in the table
|
|
504
|
+
assert "hi-eax" in result.stdout or "aGktZWF4" in result.stdout # raw or base64
|
|
505
|
+
|
|
506
|
+
@patch("hubblenetwork.cli.ble_mod.scan_single")
|
|
507
|
+
def test_auto_detect_uses_cache_for_same_eid(self, mock_scan):
|
|
508
|
+
"""Second packet with same EID hits cache (no extra detection banner)."""
|
|
509
|
+
pkt = _build_eax_packet_at_exponent(_EAX_KEY, period_exponent=5, plaintext=b"a")
|
|
510
|
+
mock_scan.side_effect = [pkt, pkt, None]
|
|
511
|
+
|
|
512
|
+
from hubblenetwork.crypto import decrypt_eax as real_decrypt_eax
|
|
513
|
+
from unittest.mock import MagicMock
|
|
514
|
+
wrapped = MagicMock(side_effect=real_decrypt_eax)
|
|
515
|
+
with patch("hubblenetwork.cli.decrypt_eax", wrapped):
|
|
516
|
+
runner = CliRunner()
|
|
517
|
+
result = runner.invoke(cli, ["ble", "scan", "--timeout", "1", "--key", _EAX_KEY_HEX])
|
|
518
|
+
|
|
519
|
+
assert result.exit_code == 0
|
|
520
|
+
# First packet: scan candidates 0..5 (6 calls). Second packet: 1 cache hit.
|
|
521
|
+
assert wrapped.call_count == 7
|
|
522
|
+
# Detection banner emitted exactly once.
|
|
523
|
+
assert result.stderr.count("[INFO] Detected:") == 1
|
|
524
|
+
|
|
525
|
+
@patch("hubblenetwork.cli.ble_mod.scan_single")
|
|
526
|
+
def test_no_warn_when_both_flags_provided(self, mock_scan):
|
|
527
|
+
"""With explicit -e and --counter-mode, no auto-detect warning or banner."""
|
|
528
|
+
pkt = _build_eax_packet_at_exponent(_EAX_KEY, period_exponent=7, plaintext=b"x")
|
|
529
|
+
mock_scan.side_effect = [pkt, None]
|
|
530
|
+
|
|
531
|
+
runner = CliRunner()
|
|
532
|
+
result = runner.invoke(
|
|
533
|
+
cli,
|
|
534
|
+
[
|
|
535
|
+
"ble", "scan", "--timeout", "1",
|
|
536
|
+
"--key", _EAX_KEY_HEX,
|
|
537
|
+
"-e", "7",
|
|
538
|
+
"--counter-mode", "UNIX_TIME",
|
|
539
|
+
],
|
|
540
|
+
)
|
|
541
|
+
assert result.exit_code == 0
|
|
542
|
+
assert "[WARN]" not in result.stderr
|
|
543
|
+
assert "[INFO] Detected:" not in result.stderr
|
|
544
|
+
|
|
545
|
+
@patch("hubblenetwork.cli.ble_mod.scan_single")
|
|
546
|
+
def test_warn_only_mentions_active_axes(self, mock_scan):
|
|
547
|
+
"""Passing -e but not --counter-mode → warning mentions only CTR axis."""
|
|
548
|
+
pkt = _build_eax_packet_at_exponent(_EAX_KEY, period_exponent=7, plaintext=b"x")
|
|
549
|
+
mock_scan.side_effect = [pkt, None]
|
|
550
|
+
|
|
551
|
+
runner = CliRunner()
|
|
552
|
+
result = runner.invoke(
|
|
553
|
+
cli,
|
|
554
|
+
["ble", "scan", "--timeout", "1", "--key", _EAX_KEY_HEX, "-e", "7"],
|
|
555
|
+
)
|
|
556
|
+
assert result.exit_code == 0
|
|
557
|
+
assert "AES-CTR counter_source" in result.stderr
|
|
558
|
+
assert "AES-EAX" not in result.stderr # EAX axis was opted out
|
|
559
|
+
# No EAX detection banner since EAX is not auto-detecting.
|
|
560
|
+
assert "[INFO] Detected:" not in result.stderr
|
|
561
|
+
|
|
562
|
+
@patch("hubblenetwork.cli.ble_mod.scan_single")
|
|
563
|
+
def test_silent_in_json_mode(self, mock_scan):
|
|
564
|
+
"""JSON output stays parse-clean even with auto-detect."""
|
|
565
|
+
pkt = _build_eax_packet_at_exponent(_EAX_KEY, period_exponent=4, plaintext=b"j")
|
|
566
|
+
mock_scan.side_effect = [pkt, None]
|
|
567
|
+
|
|
568
|
+
runner = CliRunner()
|
|
569
|
+
result = runner.invoke(
|
|
570
|
+
cli,
|
|
571
|
+
["ble", "scan", "--timeout", "1", "--key", _EAX_KEY_HEX, "-o", "json"],
|
|
572
|
+
)
|
|
573
|
+
assert result.exit_code == 0
|
|
574
|
+
parsed = json.loads(result.stdout)
|
|
575
|
+
assert len(parsed) == 1
|
|
576
|
+
# Warning + info banner suppressed entirely (JSON mode suppresses info).
|
|
577
|
+
assert "[WARN]" not in result.stderr
|
|
578
|
+
assert "[INFO] Detected:" not in result.stderr
|
|
579
|
+
|
|
580
|
+
@patch("hubblenetwork.cli.ble_mod.scan_single")
|
|
581
|
+
def test_detection_failure_with_show_failed(self, mock_scan):
|
|
582
|
+
"""No exponent matches → no banner, packet shown as fail when flag set."""
|
|
583
|
+
# Build packet with one key, scan with another → all 16 candidates fail.
|
|
584
|
+
wrong_key = bytes(range(16, 32))
|
|
585
|
+
pkt = _build_eax_packet_at_exponent(_EAX_KEY, period_exponent=3, plaintext=b"w")
|
|
586
|
+
mock_scan.side_effect = [pkt, None]
|
|
587
|
+
|
|
588
|
+
runner = CliRunner()
|
|
589
|
+
result = runner.invoke(
|
|
590
|
+
cli,
|
|
591
|
+
["ble", "scan", "--timeout", "1", "--key", wrong_key.hex(),
|
|
592
|
+
"-o", "json", "--show-failed-decryption"],
|
|
593
|
+
)
|
|
594
|
+
assert result.exit_code == 0
|
|
595
|
+
parsed = json.loads(result.stdout)
|
|
596
|
+
assert len(parsed) == 1
|
|
597
|
+
assert parsed[0]["decrypt_status"] == "fail"
|
|
598
|
+
assert "[INFO] Detected:" not in result.stderr
|
|
599
|
+
|
|
600
|
+
|
|
457
601
|
# ---------------------------------------------------------------------------
|
|
458
602
|
# Public API export tests
|
|
459
603
|
# ---------------------------------------------------------------------------
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
"""CLI auto-detect tests for AES-CTR (counter_source) in `ble scan`."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from unittest.mock import patch
|
|
5
|
+
|
|
6
|
+
from click.testing import CliRunner
|
|
7
|
+
|
|
8
|
+
from hubblenetwork.cli import cli
|
|
9
|
+
from hubblenetwork.packets import DecryptedPacket, EncryptedPacket, Location
|
|
10
|
+
|
|
11
|
+
from tests.test_counter_eid import _encrypt_payload
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
_FAKE_LOC = Location(lat=0.0, lon=0.0, fake=True)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _make_ctr_packet_with_eid(key: bytes, counter: int, seq_no: int, plaintext: bytes, eid: int) -> EncryptedPacket:
|
|
18
|
+
payload = _encrypt_payload(key, counter, seq_no, plaintext)
|
|
19
|
+
return EncryptedPacket(
|
|
20
|
+
timestamp=1700000000,
|
|
21
|
+
location=_FAKE_LOC,
|
|
22
|
+
payload=payload,
|
|
23
|
+
rssi=-70,
|
|
24
|
+
protocol_version=0,
|
|
25
|
+
eid=eid,
|
|
26
|
+
auth_tag=payload[6:10],
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _decrypted(payload: bytes = b"d", counter: int = 1, seq_no: int = 1) -> DecryptedPacket:
|
|
31
|
+
return DecryptedPacket(
|
|
32
|
+
timestamp=1700000000,
|
|
33
|
+
device_id="",
|
|
34
|
+
device_name="",
|
|
35
|
+
location=_FAKE_LOC,
|
|
36
|
+
tags={},
|
|
37
|
+
payload=payload,
|
|
38
|
+
rssi=-70,
|
|
39
|
+
counter=counter,
|
|
40
|
+
sequence=seq_no,
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
_KEY_256_HEX = bytes(range(32)).hex()
|
|
45
|
+
_KEY_128_HEX = bytes(range(16)).hex()
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class TestCliCtrAutoDetect:
|
|
49
|
+
@patch("hubblenetwork.cli.decrypt")
|
|
50
|
+
@patch("hubblenetwork.cli.ble_mod.scan_single")
|
|
51
|
+
def test_finds_unix_time(self, mock_scan, mock_decrypt):
|
|
52
|
+
"""UNIX_TIME succeeds on first try → banner names UNIX_TIME."""
|
|
53
|
+
pkt = _make_ctr_packet_with_eid(bytes(range(32)), 0, 1, b"x", eid=0xAB)
|
|
54
|
+
mock_scan.side_effect = [pkt, None]
|
|
55
|
+
mock_decrypt.side_effect = lambda key, p, **kw: (
|
|
56
|
+
_decrypted() if kw.get("counter_mode") == "UNIX_TIME" else None
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
runner = CliRunner()
|
|
60
|
+
result = runner.invoke(cli, ["ble", "scan", "--timeout", "1", "--key", _KEY_256_HEX])
|
|
61
|
+
assert result.exit_code == 0
|
|
62
|
+
assert "[INFO] Detected: AES-256-CTR, counter_source=UNIX_TIME" in result.stderr
|
|
63
|
+
|
|
64
|
+
@patch("hubblenetwork.cli.decrypt")
|
|
65
|
+
@patch("hubblenetwork.cli.ble_mod.scan_single")
|
|
66
|
+
def test_finds_device_uptime(self, mock_scan, mock_decrypt):
|
|
67
|
+
"""UNIX_TIME fails, DEVICE_UPTIME succeeds → banner names DEVICE_UPTIME."""
|
|
68
|
+
pkt = _make_ctr_packet_with_eid(bytes(range(32)), 0, 1, b"x", eid=0xAB)
|
|
69
|
+
mock_scan.side_effect = [pkt, None]
|
|
70
|
+
mock_decrypt.side_effect = lambda key, p, **kw: (
|
|
71
|
+
_decrypted() if kw.get("counter_mode") == "DEVICE_UPTIME" else None
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
runner = CliRunner()
|
|
75
|
+
result = runner.invoke(cli, ["ble", "scan", "--timeout", "1", "--key", _KEY_256_HEX])
|
|
76
|
+
assert result.exit_code == 0
|
|
77
|
+
assert "[INFO] Detected: AES-256-CTR, counter_source=DEVICE_UPTIME" in result.stderr
|
|
78
|
+
|
|
79
|
+
@patch("hubblenetwork.cli.decrypt")
|
|
80
|
+
@patch("hubblenetwork.cli.ble_mod.scan_single")
|
|
81
|
+
def test_caches_per_eid(self, mock_scan, mock_decrypt):
|
|
82
|
+
"""Two packets with same EID: detect on first, cache hit on second."""
|
|
83
|
+
pkt = _make_ctr_packet_with_eid(bytes(range(32)), 0, 1, b"x", eid=0xCAFE)
|
|
84
|
+
mock_scan.side_effect = [pkt, pkt, None]
|
|
85
|
+
|
|
86
|
+
# DEVICE_UPTIME succeeds; UNIX_TIME fails (so we exercise both modes
|
|
87
|
+
# on first packet and only DEVICE_UPTIME on the cached second packet).
|
|
88
|
+
mock_decrypt.side_effect = lambda key, p, **kw: (
|
|
89
|
+
_decrypted() if kw.get("counter_mode") == "DEVICE_UPTIME" else None
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
runner = CliRunner()
|
|
93
|
+
result = runner.invoke(cli, ["ble", "scan", "--timeout", "1", "--key", _KEY_256_HEX])
|
|
94
|
+
assert result.exit_code == 0
|
|
95
|
+
# First packet: 2 calls (UNIX_TIME fail, DEVICE_UPTIME success).
|
|
96
|
+
# Second packet: 1 call via cache (DEVICE_UPTIME).
|
|
97
|
+
modes_called = [c.kwargs.get("counter_mode") for c in mock_decrypt.call_args_list]
|
|
98
|
+
assert modes_called == ["UNIX_TIME", "DEVICE_UPTIME", "DEVICE_UPTIME"]
|
|
99
|
+
# Detection banner emitted exactly once.
|
|
100
|
+
assert result.stderr.count("[INFO] Detected:") == 1
|
|
101
|
+
|
|
102
|
+
@patch("hubblenetwork.cli.decrypt")
|
|
103
|
+
@patch("hubblenetwork.cli.ble_mod.scan_single")
|
|
104
|
+
def test_no_warn_when_counter_mode_provided(self, mock_scan, mock_decrypt):
|
|
105
|
+
"""Explicit --counter-mode + -e disables both auto-detect axes."""
|
|
106
|
+
pkt = _make_ctr_packet_with_eid(bytes(range(32)), 0, 1, b"x", eid=0xAB)
|
|
107
|
+
mock_scan.side_effect = [pkt, None]
|
|
108
|
+
mock_decrypt.return_value = _decrypted()
|
|
109
|
+
|
|
110
|
+
runner = CliRunner()
|
|
111
|
+
result = runner.invoke(
|
|
112
|
+
cli,
|
|
113
|
+
[
|
|
114
|
+
"ble", "scan", "--timeout", "1",
|
|
115
|
+
"--key", _KEY_256_HEX,
|
|
116
|
+
"--counter-mode", "UNIX_TIME",
|
|
117
|
+
"-e", "0",
|
|
118
|
+
],
|
|
119
|
+
)
|
|
120
|
+
assert result.exit_code == 0
|
|
121
|
+
assert "[WARN]" not in result.stderr
|
|
122
|
+
assert "[INFO] Detected:" not in result.stderr
|
|
123
|
+
# decrypt() was called without the auto-detect probe (just once).
|
|
124
|
+
assert mock_decrypt.call_count == 1
|
|
125
|
+
|
|
126
|
+
@patch("hubblenetwork.cli.decrypt")
|
|
127
|
+
@patch("hubblenetwork.cli.ble_mod.scan_single")
|
|
128
|
+
def test_reports_correct_key_size(self, mock_scan, mock_decrypt):
|
|
129
|
+
"""Banner labels AES-128-CTR for a 16-byte key."""
|
|
130
|
+
pkt = _make_ctr_packet_with_eid(bytes(range(16)), 0, 1, b"x", eid=0xAB)
|
|
131
|
+
mock_scan.side_effect = [pkt, None]
|
|
132
|
+
mock_decrypt.side_effect = lambda key, p, **kw: _decrypted()
|
|
133
|
+
|
|
134
|
+
runner = CliRunner()
|
|
135
|
+
result = runner.invoke(cli, ["ble", "scan", "--timeout", "1", "--key", _KEY_128_HEX])
|
|
136
|
+
assert result.exit_code == 0
|
|
137
|
+
assert "[INFO] Detected: AES-128-CTR, counter_source=UNIX_TIME" in result.stderr
|
|
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
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|