pyhubblenetwork 0.11.0__tar.gz → 0.12.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.
Files changed (35) hide show
  1. {pyhubblenetwork-0.11.0 → pyhubblenetwork-0.12.0}/PKG-INFO +1 -1
  2. {pyhubblenetwork-0.11.0 → pyhubblenetwork-0.12.0}/pyproject.toml +1 -1
  3. {pyhubblenetwork-0.11.0 → pyhubblenetwork-0.12.0}/src/hubblenetwork/cli.py +125 -162
  4. {pyhubblenetwork-0.11.0 → pyhubblenetwork-0.12.0}/src/hubblenetwork/crypto.py +38 -18
  5. pyhubblenetwork-0.12.0/src/hubblenetwork/detect.py +196 -0
  6. {pyhubblenetwork-0.11.0 → pyhubblenetwork-0.12.0}/src/hubblenetwork/sat.py +49 -0
  7. {pyhubblenetwork-0.11.0 → pyhubblenetwork-0.12.0}/tests/test_ble_validate.py +3 -104
  8. pyhubblenetwork-0.12.0/tests/test_detect.py +349 -0
  9. {pyhubblenetwork-0.11.0 → pyhubblenetwork-0.12.0}/tests/test_sat.py +80 -1
  10. {pyhubblenetwork-0.11.0 → pyhubblenetwork-0.12.0}/tests/test_sat_decrypt.py +130 -3
  11. {pyhubblenetwork-0.11.0 → pyhubblenetwork-0.12.0}/.gitignore +0 -0
  12. {pyhubblenetwork-0.11.0 → pyhubblenetwork-0.12.0}/LICENSE +0 -0
  13. {pyhubblenetwork-0.11.0 → pyhubblenetwork-0.12.0}/README.md +0 -0
  14. {pyhubblenetwork-0.11.0 → pyhubblenetwork-0.12.0}/plugins/pyhubblenetwork/skills/hubble-ready-test/README.md +0 -0
  15. {pyhubblenetwork-0.11.0 → pyhubblenetwork-0.12.0}/src/hubblenetwork/__init__.py +0 -0
  16. {pyhubblenetwork-0.11.0 → pyhubblenetwork-0.12.0}/src/hubblenetwork/ble.py +0 -0
  17. {pyhubblenetwork-0.11.0 → pyhubblenetwork-0.12.0}/src/hubblenetwork/cloud.py +0 -0
  18. {pyhubblenetwork-0.11.0 → pyhubblenetwork-0.12.0}/src/hubblenetwork/device.py +0 -0
  19. {pyhubblenetwork-0.11.0 → pyhubblenetwork-0.12.0}/src/hubblenetwork/errors.py +0 -0
  20. {pyhubblenetwork-0.11.0 → pyhubblenetwork-0.12.0}/src/hubblenetwork/org.py +0 -0
  21. {pyhubblenetwork-0.11.0 → pyhubblenetwork-0.12.0}/src/hubblenetwork/packets.py +0 -0
  22. {pyhubblenetwork-0.11.0 → pyhubblenetwork-0.12.0}/src/hubblenetwork/ready.py +0 -0
  23. {pyhubblenetwork-0.11.0 → pyhubblenetwork-0.12.0}/tests/__init__.py +0 -0
  24. {pyhubblenetwork-0.11.0 → pyhubblenetwork-0.12.0}/tests/conftest.py +0 -0
  25. {pyhubblenetwork-0.11.0 → pyhubblenetwork-0.12.0}/tests/test_aes_eax.py +0 -0
  26. {pyhubblenetwork-0.11.0 → pyhubblenetwork-0.12.0}/tests/test_cli_ctr_autodetect.py +0 -0
  27. {pyhubblenetwork-0.11.0 → pyhubblenetwork-0.12.0}/tests/test_cli_payload.py +0 -0
  28. {pyhubblenetwork-0.11.0 → pyhubblenetwork-0.12.0}/tests/test_cloud_integration.py +0 -0
  29. {pyhubblenetwork-0.11.0 → pyhubblenetwork-0.12.0}/tests/test_counter_eid.py +0 -0
  30. {pyhubblenetwork-0.11.0 → pyhubblenetwork-0.12.0}/tests/test_metrics.py +0 -0
  31. {pyhubblenetwork-0.11.0 → pyhubblenetwork-0.12.0}/tests/test_org_delete_device.py +0 -0
  32. {pyhubblenetwork-0.11.0 → pyhubblenetwork-0.12.0}/tests/test_register_device_cloud.py +0 -0
  33. {pyhubblenetwork-0.11.0 → pyhubblenetwork-0.12.0}/tests/test_register_device_validation.py +0 -0
  34. {pyhubblenetwork-0.11.0 → pyhubblenetwork-0.12.0}/tests/test_sat_integration.py +0 -0
  35. {pyhubblenetwork-0.11.0 → pyhubblenetwork-0.12.0}/tests/test_unencrypted.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyhubblenetwork
3
- Version: 0.11.0
3
+ Version: 0.12.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
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "pyhubblenetwork"
7
- version = "0.11.0"
7
+ version = "0.12.0"
8
8
  requires-python = ">=3.9"
9
9
  authors = [
10
10
  { name="Paul Buckley", email="paul@hubble.com" },
@@ -24,6 +24,11 @@ from hubblenetwork import ready as ready_mod
24
24
  from hubblenetwork import sat as sat_mod
25
25
  from hubblenetwork import decrypt, decrypt_satellite, UNIX_TIME, DEVICE_UPTIME
26
26
  from hubblenetwork.crypto import find_time_counter_delta
27
+ from hubblenetwork.detect import (
28
+ CtrCounterModeDetector,
29
+ EaxExponentDetector,
30
+ detect_eid_type,
31
+ )
27
32
  from hubblenetwork import cloud
28
33
  from hubblenetwork import InvalidCredentialsError
29
34
  from hubblenetwork.errors import BackendError
@@ -83,36 +88,6 @@ def _get_pkt_from_be_with_timestamp(org, device, timestamp):
83
88
  return None
84
89
 
85
90
 
86
- def _detect_eid_type(
87
- key: bytes,
88
- pkts: List[EncryptedPacket],
89
- ) -> tuple[Optional[EncryptedPacket], Optional[DecryptedPacket], Optional[str], bool]:
90
- epoch_pkt = None
91
- epoch_dec = None
92
- counter_pkt = None
93
- counter_dec = None
94
- for pkt in pkts:
95
- if epoch_pkt is None:
96
- result = decrypt(key, pkt)
97
- if result:
98
- epoch_pkt = pkt
99
- epoch_dec = result
100
- if counter_pkt is None:
101
- result = decrypt(key, pkt, counter_mode=DEVICE_UPTIME)
102
- if result:
103
- counter_pkt = pkt
104
- counter_dec = result
105
- if epoch_pkt and counter_pkt:
106
- break
107
- if epoch_pkt and counter_pkt:
108
- return (epoch_pkt, epoch_dec, "AMBIGUOUS", True)
109
- if epoch_pkt:
110
- return (epoch_pkt, epoch_dec, UNIX_TIME, False)
111
- if counter_pkt:
112
- return (counter_pkt, counter_dec, DEVICE_UPTIME, False)
113
- return (None, None, None, False)
114
-
115
-
116
91
  def _announce_auto_detect(auto_ctr: bool, auto_eax: bool, *, suppress: bool) -> None:
117
92
  if suppress or not (auto_ctr or auto_eax):
118
93
  return
@@ -129,85 +104,14 @@ def _announce_auto_detect(auto_ctr: bool, auto_eax: bool, *, suppress: bool) ->
129
104
  )
130
105
 
131
106
 
132
- def _decrypt_eax_with_detect(
133
- key: bytes,
134
- pkt: AesEaxPacket,
135
- *,
136
- auto_detect: bool,
137
- fixed_exponent: int,
138
- cache: dict,
139
- announced: list[str],
140
- suppress_info: bool,
141
- ) -> Optional[DecryptedPacket]:
142
- if not auto_detect:
143
- return decrypt_eax(key, pkt, period_exponent=fixed_exponent)
144
-
145
- cached = cache.get(pkt.eid)
146
- if cached is not None:
147
- result = decrypt_eax(key, pkt, period_exponent=cached)
148
- if result:
149
- return result
150
-
151
- for candidate in range(16):
152
- result = decrypt_eax(key, pkt, period_exponent=candidate)
153
- if result is None:
154
- continue
155
- cache[pkt.eid] = candidate
156
- if not announced and not suppress_info:
157
- announced.append("eax")
158
- click.secho(
159
- f"[INFO] Detected: AES-128-EAX, counter_source=DEVICE_UPTIME, "
160
- f"period_exponent={candidate} (period={1 << candidate}s)",
161
- fg="green",
162
- err=True,
163
- )
164
- return result
165
- return None
166
-
107
+ def _announce_detection(label: Optional[str], *, suppress: bool) -> None:
108
+ """Print the one-shot ``[INFO] Detected:`` line for a fresh detection.
167
109
 
168
- def _decrypt_ctr_with_detect(
169
- key: bytes,
170
- pkt: EncryptedPacket,
171
- *,
172
- auto_detect: bool,
173
- fixed_counter_mode: str,
174
- days: int,
175
- cache: dict,
176
- announced: list[str],
177
- suppress_info: bool,
178
- ) -> Optional[DecryptedPacket]:
179
- if not auto_detect:
180
- return decrypt(key, pkt, days=days, counter_mode=fixed_counter_mode)
181
-
182
- def _try(mode: str) -> Optional[DecryptedPacket]:
183
- kwargs = {"counter_mode": mode}
184
- if mode == UNIX_TIME:
185
- kwargs["days"] = days
186
- return decrypt(key, pkt, **kwargs)
187
-
188
- if pkt.eid is not None:
189
- cached = cache.get(pkt.eid)
190
- if cached is not None:
191
- result = _try(cached)
192
- if result:
193
- return result
194
-
195
- for mode in (UNIX_TIME, DEVICE_UPTIME):
196
- result = _try(mode)
197
- if result is None:
198
- continue
199
- if pkt.eid is not None:
200
- cache[pkt.eid] = mode
201
- if not announced and not suppress_info:
202
- announced.append("ctr")
203
- variant = "AES-128-CTR" if len(key) == 16 else "AES-256-CTR"
204
- click.secho(
205
- f"[INFO] Detected: {variant}, counter_source={mode}",
206
- fg="green",
207
- err=True,
208
- )
209
- return result
210
- return None
110
+ ``label`` is set by the detector only on the first successful detection of a
111
+ scan, so a no-op when it is None or output is suppressed (JSON mode).
112
+ """
113
+ if label and not suppress:
114
+ click.secho(f"[INFO] Detected: {label}", fg="green", err=True)
211
115
 
212
116
 
213
117
  def _format_payload(payload, fmt: str) -> str:
@@ -942,9 +846,15 @@ def ble_detect(
942
846
 
943
847
  _announce_auto_detect(auto_detect_ctr, auto_detect_eax, suppress=use_json)
944
848
 
945
- detected_ctr_modes: dict = {}
946
- detected_eax_exponents: dict = {}
947
- announced: list[str] = []
849
+ ctr_detector = CtrCounterModeDetector(
850
+ auto_detect=auto_detect_ctr,
851
+ fixed_counter_mode=counter_mode,
852
+ days=days,
853
+ key_len=len(decoded_key),
854
+ )
855
+ eax_detector = EaxExponentDetector(
856
+ auto_detect=auto_detect_eax, fixed_exponent=period_exponent
857
+ )
948
858
 
949
859
  # Set up timeout tracking
950
860
  start = time.monotonic()
@@ -978,26 +888,21 @@ def ble_detect(
978
888
 
979
889
  decrypted_pkt = None
980
890
  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,
891
+ d = eax_detector.decrypt(
892
+ decrypt_fn=lambda exp: decrypt_eax(
893
+ decoded_key, pkt, period_exponent=exp
894
+ ),
895
+ cache_key=pkt.eid,
989
896
  )
897
+ _announce_detection(d.label, suppress=use_json)
898
+ decrypted_pkt = d.result
990
899
  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,
900
+ d = ctr_detector.decrypt(
901
+ decrypt_fn=lambda **kw: decrypt(decoded_key, pkt, **kw),
902
+ cache_key=pkt.eid,
1000
903
  )
904
+ _announce_detection(d.label, suppress=use_json)
905
+ decrypted_pkt = d.result
1001
906
  # UnencryptedPacket and UnknownPacket fall through — keep scanning.
1002
907
 
1003
908
  if decrypted_pkt:
@@ -1193,9 +1098,15 @@ def ble_scan(
1193
1098
  auto_detect_ctr, auto_detect_eax, suppress=printer.suppress_info_messages
1194
1099
  )
1195
1100
 
1196
- detected_ctr_modes: dict = {}
1197
- detected_eax_exponents: dict = {}
1198
- announced: list[str] = []
1101
+ ctr_detector = CtrCounterModeDetector(
1102
+ auto_detect=auto_detect_ctr,
1103
+ fixed_counter_mode=counter_mode,
1104
+ days=days,
1105
+ key_len=len(decoded_key) if decoded_key is not None else 0,
1106
+ )
1107
+ eax_detector = EaxExponentDetector(
1108
+ auto_detect=auto_detect_eax, fixed_exponent=period_exponent
1109
+ )
1199
1110
 
1200
1111
  try:
1201
1112
  while deadline is None or time.monotonic() < deadline:
@@ -1227,15 +1138,16 @@ def ble_scan(
1227
1138
  # AES-EAX packets: decrypt if key provided, else show raw fields
1228
1139
  elif isinstance(pkt, AesEaxPacket):
1229
1140
  if decoded_key:
1230
- decrypted_pkt = _decrypt_eax_with_detect(
1231
- decoded_key,
1232
- pkt,
1233
- auto_detect=auto_detect_eax,
1234
- fixed_exponent=period_exponent,
1235
- cache=detected_eax_exponents,
1236
- announced=announced,
1237
- suppress_info=printer.suppress_info_messages,
1141
+ d = eax_detector.decrypt(
1142
+ decrypt_fn=lambda exp: decrypt_eax(
1143
+ decoded_key, pkt, period_exponent=exp
1144
+ ),
1145
+ cache_key=pkt.eid,
1146
+ )
1147
+ _announce_detection(
1148
+ d.label, suppress=printer.suppress_info_messages
1238
1149
  )
1150
+ decrypted_pkt = d.result
1239
1151
  if decrypted_pkt:
1240
1152
  printer.print_row(decrypted_pkt, decrypt_status="ok")
1241
1153
  elif show_failed_decryption:
@@ -1244,16 +1156,14 @@ def ble_scan(
1244
1156
  printer.print_row(pkt)
1245
1157
  elif isinstance(pkt, EncryptedPacket):
1246
1158
  if decoded_key:
1247
- decrypted_pkt = _decrypt_ctr_with_detect(
1248
- decoded_key,
1249
- pkt,
1250
- auto_detect=auto_detect_ctr,
1251
- fixed_counter_mode=counter_mode,
1252
- days=days,
1253
- cache=detected_ctr_modes,
1254
- announced=announced,
1255
- suppress_info=printer.suppress_info_messages,
1159
+ d = ctr_detector.decrypt(
1160
+ decrypt_fn=lambda **kw: decrypt(decoded_key, pkt, **kw),
1161
+ cache_key=pkt.eid,
1162
+ )
1163
+ _announce_detection(
1164
+ d.label, suppress=printer.suppress_info_messages
1256
1165
  )
1166
+ decrypted_pkt = d.result
1257
1167
  if decrypted_pkt:
1258
1168
  printer.print_row(decrypted_pkt, decrypt_status="ok")
1259
1169
  if ingest:
@@ -1518,7 +1428,7 @@ def ble_validate(key: str, device_id: str, org_id: str, token: str, timeout: int
1518
1428
 
1519
1429
  # Step 6: Validate encryption and detect EID type
1520
1430
  _validate_info("Validating encryption of received packets")
1521
- pkt_to_ingest, dec_result, eid_label, _ = _detect_eid_type(decoded_key, pkts)
1431
+ pkt_to_ingest, dec_result, eid_label, _ = detect_eid_type(decoded_key, pkts)
1522
1432
  if not pkt_to_ingest:
1523
1433
  _validate_error(
1524
1434
  'Unable to decrypt packet with given device key.'
@@ -3154,6 +3064,8 @@ def _run_sat_scan(
3154
3064
  debug: bool = False,
3155
3065
  key: Optional[str] = None,
3156
3066
  days: int = 2,
3067
+ counter_mode: str = UNIX_TIME,
3068
+ auto_detect_ctr: bool = False,
3157
3069
  show_failed_decryption: bool = False,
3158
3070
  ) -> None:
3159
3071
  """Shared implementation for ``sat scan`` and ``sat mock-scan``."""
@@ -3167,8 +3079,7 @@ def _run_sat_scan(
3167
3079
  show_decrypt_status=show_failed_decryption,
3168
3080
  )
3169
3081
 
3170
- # Pre-decode the key if provided. Satellite packets always use the
3171
- # UNIX_TIME (day-based) counter, so only --days is relevant.
3082
+ # Pre-decode the key if provided.
3172
3083
  decoded_key: Optional[bytes] = None
3173
3084
  if key:
3174
3085
  try:
@@ -3179,6 +3090,18 @@ def _run_sat_scan(
3179
3090
  return
3180
3091
  raise click.ClickException(f"Invalid key: {e}")
3181
3092
 
3093
+ if decoded_key is not None and auto_detect_ctr:
3094
+ _announce_auto_detect(
3095
+ auto_ctr=True, auto_eax=False, suppress=printer.suppress_info_messages
3096
+ )
3097
+
3098
+ ctr_detector = CtrCounterModeDetector(
3099
+ auto_detect=auto_detect_ctr,
3100
+ fixed_counter_mode=counter_mode,
3101
+ days=days,
3102
+ key_len=len(decoded_key) if decoded_key is not None else 0,
3103
+ )
3104
+
3182
3105
  if debug:
3183
3106
  sat_logger = logging.getLogger("hubblenetwork.sat")
3184
3107
  sat_logger.setLevel(logging.DEBUG)
@@ -3196,6 +3119,9 @@ def _run_sat_scan(
3196
3119
  sys.exit(1)
3197
3120
 
3198
3121
  if not printer.suppress_info_messages:
3122
+ click.secho(
3123
+ f"[INFO] Web GUI: {sat_mod.web_ui_url()}", fg="green"
3124
+ )
3199
3125
  click.secho(
3200
3126
  f"[INFO] Starting {mode_label}... (Press Ctrl+C to stop)"
3201
3127
  )
@@ -3225,14 +3151,22 @@ def _run_sat_scan(
3225
3151
  # With a key, the user wants only packets the key can decrypt.
3226
3152
  decrypted = None
3227
3153
  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,
3154
+ # Satellite streams have no per-packet EID; omitting cache_key
3155
+ # lets the detector share one per-stream slot for the scan.
3156
+ d = ctr_detector.decrypt(
3157
+ decrypt_fn=lambda **kw: decrypt_satellite(
3158
+ decoded_key,
3159
+ seq_no=pkt.seq_num,
3160
+ auth_tag=pkt.auth_tag,
3161
+ encrypted_payload=pkt.payload,
3162
+ timestamp=pkt.timestamp,
3163
+ **kw,
3164
+ ),
3165
+ )
3166
+ _announce_detection(
3167
+ d.label, suppress=printer.suppress_info_messages
3235
3168
  )
3169
+ decrypted = d.result
3236
3170
  if decrypted is not None:
3237
3171
  printer.print_row(
3238
3172
  replace(pkt, payload=decrypted), decrypt_status="ok"
@@ -3306,7 +3240,8 @@ def _sat_scan_options(fn):
3306
3240
  default=None,
3307
3241
  show_default=False,
3308
3242
  help="Key to decrypt packet payloads (hex or base64, 16 or 32 bytes). "
3309
- "Satellite packets always use the UNIX_TIME counter.",
3243
+ "The counter source (UNIX_TIME / DEVICE_UPTIME) is auto-detected "
3244
+ "unless --counter-mode is given.",
3310
3245
  )
3311
3246
  @click.option(
3312
3247
  "--days",
@@ -3314,7 +3249,15 @@ def _sat_scan_options(fn):
3314
3249
  type=int,
3315
3250
  default=2,
3316
3251
  show_default=True,
3317
- help="Days to search around each packet's timestamp when decrypting",
3252
+ help="Days to search around each packet's timestamp when decrypting "
3253
+ "with the UNIX_TIME counter",
3254
+ )
3255
+ @click.option(
3256
+ "--counter-mode",
3257
+ type=click.Choice([UNIX_TIME, DEVICE_UPTIME], case_sensitive=False),
3258
+ default=UNIX_TIME,
3259
+ show_default=False,
3260
+ help="EID counter source for decryption. Omit to auto-detect from packets.",
3318
3261
  )
3319
3262
  @click.option(
3320
3263
  "--show-failed-decryption",
@@ -3323,14 +3266,17 @@ def _sat_scan_options(fn):
3323
3266
  help="Show packets that fail decryption/authentication with the provided "
3324
3267
  "key. Adds a DECRYPT column indicating OK/FAIL.",
3325
3268
  )
3326
- def sat_scan(**kwargs) -> None:
3269
+ @click.pass_context
3270
+ def sat_scan(ctx, **kwargs) -> None:
3327
3271
  """
3328
3272
  Start the satellite receiver and stream decoded packets.
3329
3273
 
3330
3274
  Requires Docker and a PlutoSDR device connected via USB.
3331
3275
 
3332
3276
  Pass --key to decrypt packet payloads locally; packets the key cannot
3333
- decrypt are hidden unless --show-failed-decryption is given.
3277
+ decrypt are hidden unless --show-failed-decryption is given. The counter
3278
+ source is auto-detected (UNIX_TIME or DEVICE_UPTIME) unless --counter-mode
3279
+ is given explicitly.
3334
3280
 
3335
3281
  Example:
3336
3282
  hubblenetwork sat scan --timeout 30
@@ -3338,6 +3284,23 @@ def sat_scan(**kwargs) -> None:
3338
3284
  hubblenetwork sat scan -n 5
3339
3285
  hubblenetwork sat scan --key "a562a2f7e4c62bed52ab09633878f62b" --timeout 60
3340
3286
  """
3287
+ key = kwargs.get("key")
3288
+ counter_mode = kwargs["counter_mode"]
3289
+
3290
+ def _explicit(name: str) -> bool:
3291
+ return ctx.get_parameter_source(name) == click.core.ParameterSource.COMMANDLINE
3292
+
3293
+ # counter_mode defaults to UNIX_TIME, so a DEVICE_UPTIME value here always
3294
+ # means the user passed it explicitly (matches the ble scan/detect guards).
3295
+ if counter_mode == DEVICE_UPTIME:
3296
+ if not key:
3297
+ raise click.UsageError("--counter-mode DEVICE_UPTIME requires --key")
3298
+ if _explicit("days"):
3299
+ raise click.UsageError(
3300
+ "--counter-mode DEVICE_UPTIME and --days are mutually exclusive"
3301
+ )
3302
+
3303
+ kwargs["auto_detect_ctr"] = key is not None and not _explicit("counter_mode")
3341
3304
  _run_sat_scan(mock=False, **kwargs)
3342
3305
 
3343
3306
 
@@ -157,12 +157,13 @@ def _check_tag_matches(
157
157
  return tag == parsed.auth_tag
158
158
 
159
159
 
160
- def decrypt(
161
- key: bytes,
162
- encrypted_pkt: EncryptedPacket,
163
- days: int = 2,
164
- counter_mode: str = UNIX_TIME,
165
- ) -> Optional[DecryptedPacket]:
160
+ def _normalize_counter_mode(counter_mode: str, days: int) -> str:
161
+ """Validate and upper-case ``counter_mode``, enforcing the DEVICE_UPTIME rule.
162
+
163
+ Shared by :func:`decrypt` and :func:`decrypt_satellite`. Returns the
164
+ normalized mode; raises ``ValueError`` for an unknown mode or for
165
+ ``DEVICE_UPTIME`` combined with a non-default ``days``.
166
+ """
166
167
  counter_mode = counter_mode.upper()
167
168
  if counter_mode not in _VALID_COUNTER_MODES:
168
169
  raise ValueError(
@@ -170,6 +171,16 @@ def decrypt(
170
171
  )
171
172
  if counter_mode == DEVICE_UPTIME and days != 2:
172
173
  raise ValueError("Cannot specify both counter_mode=DEVICE_UPTIME and days")
174
+ return counter_mode
175
+
176
+
177
+ def decrypt(
178
+ key: bytes,
179
+ encrypted_pkt: EncryptedPacket,
180
+ days: int = 2,
181
+ counter_mode: str = UNIX_TIME,
182
+ ) -> Optional[DecryptedPacket]:
183
+ counter_mode = _normalize_counter_mode(counter_mode, days)
173
184
 
174
185
  parsed = ParsedPacket(encrypted_pkt)
175
186
  keylen = len(key)
@@ -211,29 +222,38 @@ def decrypt_satellite(
211
222
  encrypted_payload: bytes,
212
223
  timestamp: Optional[float] = None,
213
224
  days: int = 2,
225
+ counter_mode: str = UNIX_TIME,
214
226
  ) -> Optional[bytes]:
215
227
  """Decrypt a satellite packet's encrypted customer payload.
216
228
 
217
229
  Satellite packets deliver the sequence number, 4-byte auth tag, and
218
230
  encrypted customer payload as separate fields, unlike BLE where they are
219
231
  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.
232
+ scheme is identical to BLE (see :func:`decrypt`).
222
233
 
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.
234
+ The counter swept to find a matching auth tag depends on ``counter_mode``:
226
235
 
227
- Returns the decrypted payload bytes, or None if no day matches (wrong
228
- key or outside the search window).
236
+ - ``UNIX_TIME`` (default): the day counter is swept +/-``days`` around the
237
+ packet's ``timestamp`` (or the current UTC day when ``timestamp`` is None).
238
+ - ``DEVICE_UPTIME``: the device-uptime counter is swept over the fixed pool
239
+ 0-127. ``timestamp`` and ``days`` are unused in this mode.
240
+
241
+ Returns the decrypted payload bytes for the first counter whose derived
242
+ auth tag matches, or None if none match (wrong key, wrong mode, or outside
243
+ the search window).
229
244
  """
245
+ counter_mode = _normalize_counter_mode(counter_mode, days)
246
+
230
247
  keylen = len(key)
231
- if timestamp is None:
232
- timestamp = datetime.now(timezone.utc).timestamp()
233
- base = int(timestamp) // 86400
248
+ if counter_mode == DEVICE_UPTIME:
249
+ candidates = range(128)
250
+ else:
251
+ if timestamp is None:
252
+ timestamp = datetime.now(timezone.utc).timestamp()
253
+ base = int(timestamp) // 86400
254
+ candidates = (base + delta for delta in range(-days, days + 1))
234
255
 
235
- for delta in range(-days, days + 1):
236
- time_counter = base + delta
256
+ for time_counter in candidates:
237
257
  daily_key = _get_encryption_key(key, time_counter, seq_no, keylen=keylen)
238
258
  if _get_auth_tag(daily_key, encrypted_payload) == auth_tag:
239
259
  nonce = _get_nonce(key, time_counter, seq_no, keylen=keylen)