-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.py
More file actions
1332 lines (1158 loc) · 51.7 KB
/
Copy pathcli.py
File metadata and controls
1332 lines (1158 loc) · 51.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""CLI entry point for MemDiver — headless analysis and interactive UI."""
import argparse
import json
import logging
import subprocess
import sys
from pathlib import Path
# Ensure package root is on sys.path for bare imports (matches legacy_app.py/run.py pattern)
sys.path.insert(0, str(Path(__file__).parent))
logger = logging.getLogger("memdiver.cli")
def _decrypt_parent_parser() -> argparse.ArgumentParser:
"""Shared parent parser for encrypted-MSL decryption flags (spec §10).
Attach via ``parents=[_decrypt_parent_parser()]`` to any subcommand that
opens a dump, so it accepts a key for AES/XChaCha-encrypted .msl files.
"""
p = argparse.ArgumentParser(add_help=False)
g = p.add_argument_group("encrypted MSL (spec §10)")
g.add_argument("--key-file", help="32-byte raw content-encryption key file "
"(KeyEncap=None, KDF=None)")
g.add_argument("--passphrase", help="Passphrase for Argon2id-derived key "
"(KeyEncap=None, KDF=Argon2id)")
g.add_argument("--kem-key-file", help="Recipient private key file for "
"X25519/ML-KEM/hybrid key encapsulation")
return p
def _key_material_from_args(args: argparse.Namespace) -> dict:
"""Build the open_dump() key-material kwargs from decryption CLI flags.
Returns a dict with key/passphrase/kem_private_key (all None when no
decryption flags were supplied), suitable for ``open_dump(path, **kw)``.
"""
key = None
if getattr(args, "key_file", None):
key = Path(args.key_file).read_bytes()
kem_private = None
if getattr(args, "kem_key_file", None):
kem_private = Path(args.kem_key_file).read_bytes()
passphrase = None
if getattr(args, "passphrase", None):
passphrase = args.passphrase.encode("utf-8")
return {"key": key, "passphrase": passphrase, "kem_private_key": kem_private}
def _warn_tag_status(source) -> None:
"""Print a user-facing line about an encrypted dump's AEAD verification.
Green = verified, red = failed/missing key. Plaintext dumps say nothing.
"""
from msl.enums import TagStatus
status = getattr(source, "tag_status", TagStatus.NOT_ENCRYPTED)
if status == TagStatus.VALID:
print("memdiver: AEAD verified — encrypted dump decrypted successfully",
file=sys.stderr)
elif status == TagStatus.CORRUPTED:
print("memdiver: ERROR — AEAD verification FAILED (wrong key or tampered file)",
file=sys.stderr)
elif status == TagStatus.MISSING_KEY:
print("memdiver: ERROR — dump is encrypted; supply --key-file / "
"--passphrase / --kem-key-file", file=sys.stderr)
def _resolve_dump_paths(raw_paths: list) -> list:
"""Expand directories to all supported dump flavours; pass through files.
Recognised extensions inside a run directory:
* ``.dump`` and ``.msl`` (legacy + Memory Slice)
* ``.gcore.core`` and bare ``.core`` (Linux gcore/ELF core)
* ``gdb_raw.bin`` / ``lldb_raw.bin`` (regioned raw dumps)
"""
paths: list[Path] = []
for p in raw_paths:
path = Path(p)
if path.is_dir():
collected: list[Path] = []
collected.extend(path.glob("*.dump"))
collected.extend(path.glob("*.msl"))
collected.extend(path.glob("*.gcore.core"))
collected.extend(path.glob("*.core"))
collected.extend(path.glob("*gdb_raw.bin"))
collected.extend(path.glob("*lldb_raw.bin"))
# De-duplicate (``*.gcore.core`` overlaps ``*.core``) and sort.
paths.extend(sorted({c.resolve(): c for c in collected}.values()))
elif path.is_file():
paths.append(path)
else:
logger.warning("Skipping non-existent path: %s", p)
return paths
def _setup_logging(verbose: bool) -> None:
"""Configure logging for CLI mode."""
from core.log import setup_logging
setup_logging(level="DEBUG" if verbose else "WARNING")
def _write_output(
data: dict,
output_path: str | None,
fmt: str = "json",
) -> None:
"""Write data to file or stdout as json or jsonl."""
if fmt == "jsonl":
text = _format_jsonl(data)
else:
text = json.dumps(data, indent=2)
if output_path:
Path(output_path).write_text(text)
logger.info("Output written to %s", output_path)
else:
print(text)
def _format_jsonl(data: dict) -> str:
"""Serialize a BatchResult-shaped dict as newline-delimited JSON.
One record per completed job + a trailing summary line tagged
``"_type": "summary"``. Non-batch shapes (no ``jobs`` list) fall
back to a single-line JSON dump.
"""
jobs = data.get("jobs")
if not isinstance(jobs, list):
return json.dumps(data)
lines = [json.dumps(j) for j in jobs]
summary = {k: v for k, v in data.items() if k != "jobs"}
summary["_type"] = "summary"
lines.append(json.dumps(summary))
return "\n".join(lines) + "\n"
def _print_missing_package(package: str, extra: str | None = None) -> None:
"""Print a uniform 'package missing' install hint to stderr.
``extra`` names an optional-dependencies group (e.g. ``"experiment"``).
When omitted, the hint points at a base-install reinstall.
"""
if extra:
message = (
f"{package} is not available. Install the '{extra}' extras with:\n"
f" pip install memdiver[{extra}]"
)
else:
message = (
f"{package} is missing from your environment. It is part of the "
f"base install; try: pip install --force-reinstall memdiver"
)
print(message, file=sys.stderr)
def _cmd_ui(args: argparse.Namespace) -> int:
"""Launch the Marimo interactive UI."""
extra = getattr(args, "extra_args", [])
app = str(Path(__file__).parent / "run.py")
return subprocess.call([sys.executable, "-m", "marimo", "run", app] + extra)
def _cmd_web(args: argparse.Namespace) -> int:
"""Launch the FastAPI + React web application."""
try:
import uvicorn
from api.main import create_app
except ImportError:
print(
"FastAPI backend requires 'fastapi' and 'uvicorn'. "
"Install with: pip install memdiver",
file=sys.stderr,
)
return 1
port = getattr(args, "port", 8080)
print(f"MemDiver starting on http://127.0.0.1:{port}", file=sys.stderr, flush=True)
try:
app = create_app()
uvicorn.run(app, host="127.0.0.1", port=port, log_level="info")
except KeyboardInterrupt:
pass
return 0
def _cmd_app(args: argparse.Namespace) -> int:
"""Launch the legacy NiceGUI web application (if installed)."""
try:
import nicegui # noqa: F401
except ImportError:
_print_missing_package("NiceGUI")
return 1
app_path = str(Path(__file__).parent / "legacy_app.py")
return subprocess.call([sys.executable, app_path])
def _cmd_analyze(args: argparse.Namespace) -> int:
"""Run analysis on library directories."""
from core.input_schemas import AnalyzeRequest
from engine.batch import run_analysis_request
from engine.serializer import serialize_result
lib_dirs = [Path(d) for d in args.library_dirs]
try:
request = AnalyzeRequest(
library_dirs=lib_dirs,
phase=args.phase,
protocol_version=args.protocol_version,
keylog_filename=args.keylog_filename,
template_name=args.template,
max_runs=args.max_runs,
normalize=args.normalize,
expand_keys=not args.no_expand,
)
except ValueError as exc:
logger.error("Invalid request: %s", exc)
return 1
result = run_analysis_request(request)
_write_output(serialize_result(result), args.output)
return 0
def _cmd_scan(args: argparse.Namespace) -> int:
"""Scan a dataset root for available data."""
from core.discovery import DatasetScanner
from core.input_schemas import ScanRequest
from engine.serializer import serialize_dataset_info
try:
request = ScanRequest(
dataset_root=Path(args.root),
keylog_filename=args.keylog_filename,
protocols=args.protocols,
)
except ValueError as exc:
logger.error("Invalid request: %s", exc)
return 1
scanner = DatasetScanner(request.dataset_root, request.keylog_filename)
info = scanner.fast_scan(protocols=request.protocols)
_write_output(serialize_dataset_info(info), args.output)
return 0
def _cmd_mcp(args: argparse.Namespace) -> int:
"""Start the MCP server for AI integration."""
try:
from mcp_server.server import main as mcp_main
except ImportError:
_print_missing_package("The 'mcp' package")
return 1
transport = "sse" if args.sse else "stdio"
mcp_main(transport=transport, port=getattr(args, "port", 8080))
return 0
def _cmd_batch(args: argparse.Namespace) -> int:
"""Run a batch of analysis jobs from a config file."""
from core.input_schemas import AnalyzeRequest, BatchRequest
from engine.batch import BatchRunner
config_path = Path(args.config)
try:
with open(config_path) as f:
batch_cfg = json.load(f)
except (json.JSONDecodeError, OSError) as exc:
logger.error("Failed to read batch config: %s", exc)
return 1
jobs = []
for job_cfg in batch_cfg.get("jobs", []):
try:
jobs.append(AnalyzeRequest(
library_dirs=[Path(d) for d in job_cfg["library_dirs"]],
phase=job_cfg["phase"],
protocol_version=job_cfg["protocol_version"],
keylog_filename=job_cfg.get("keylog_filename", "keylog.csv"),
template_name=job_cfg.get("template_name", "Auto-detect"),
max_runs=job_cfg.get("max_runs", 10),
normalize=job_cfg.get("normalize", False),
expand_keys=job_cfg.get("expand_keys", True),
))
except (ValueError, KeyError) as exc:
logger.error("Invalid job config: %s", exc)
return 1
effective_format = (
getattr(args, "output_format", None)
or batch_cfg.get("output_format", "json")
)
try:
batch = BatchRequest(
jobs=jobs,
output_format=effective_format,
)
except ValueError as exc:
logger.error("Invalid batch config: %s", exc)
return 1
def _progress(current: int, total: int, status: str | None) -> None:
if args.verbose:
print(f"[{current}/{total}] {status or ''}", file=sys.stderr)
runner = BatchRunner(workers=args.workers)
result = runner.run(batch, progress_callback=_progress)
_write_output(result.to_dict(), args.output, fmt=batch.output_format)
return 0
def _cmd_import(args: argparse.Namespace) -> int:
"""Import a raw .dump file to .msl format."""
from msl.importer import import_raw_dump
raw = Path(args.dump_file)
out = Path(args.output) if args.output else raw.with_suffix(".msl")
secrets = None
if args.keylog:
from core.keylog import KeylogParser
secrets = KeylogParser().parse(Path(args.keylog))
result = import_raw_dump(raw, out, pid=args.pid, secrets=secrets)
print(json.dumps({
"source": str(result.source_path),
"output": str(result.output_path),
"regions": result.regions_written,
"key_hints": result.key_hints_written,
"bytes": result.total_bytes,
}, indent=2))
return 0
def _cmd_consensus(args: argparse.Namespace) -> int:
"""Build consensus matrix from dump files and output region analysis."""
from core.dump_source import open_dump
from engine.consensus import ConsensusVector
dump_paths = _resolve_dump_paths(args.dumps)
if len(dump_paths) < 2:
print(f"Need at least 2 dumps, got {len(dump_paths)}", file=sys.stderr)
return 1
logger.info("Building consensus from %d dumps", len(dump_paths))
key_material = _key_material_from_args(args)
sources = [open_dump(p, **key_material) for p in dump_paths]
try:
cm = ConsensusVector()
cm.build_from_sources(sources, normalize=args.normalize)
min_len = args.min_length
volatile = cm.get_volatile_regions(min_length=min_len)
static = cm.get_static_regions(min_length=min_len)
result = {
"num_dumps": cm.num_dumps,
"size": cm.size,
"classification_counts": cm.classification_counts(),
"volatile_regions": [
{"start": r.start, "end": r.end, "length": r.end - r.start,
"mean_variance": round(float(r.mean_variance), 2), "classification": r.classification}
for r in volatile
],
"static_regions": [
{"start": r.start, "end": r.end, "length": r.end - r.start,
"mean_variance": 0.0, "classification": r.classification}
for r in static
],
}
# Alignment filtering
if args.align:
aligned = cm.get_aligned_candidates(
block_size=args.block_size,
alignment=args.alignment_bytes,
density_threshold=args.density,
)
result["aligned_candidates"] = [
{"start": r.start, "end": r.end, "length": r.end - r.start,
"mean_variance": round(float(r.mean_variance), 2)}
for r in aligned
]
# Convergence sweep
if args.convergence:
from engine.convergence import run_convergence_sweep
from engine.serializer import serialize_convergence_result
sweep = run_convergence_sweep(
dump_paths,
max_fp=args.max_fp,
)
result["convergence"] = serialize_convergence_result(sweep)
_write_output(result, args.output)
finally:
for s in sources:
if hasattr(s, "__exit__"):
try:
s.__exit__(None, None, None)
except Exception:
pass
return 0
def _consensus_state_paths(state_path: Path) -> "tuple[Path, Path]":
stem = state_path.with_suffix("")
return stem.with_suffix(".mean.npy"), stem.with_suffix(".m2.npy")
def _load_welford_session(state_path: Path):
"""Load persisted incremental-consensus state from disk."""
import numpy as np
from core.variance import WelfordVariance
state = json.loads(state_path.read_text())
mean = np.load(state["mean_path"])
m2 = np.load(state["m2_path"])
welford = WelfordVariance.from_state(mean, m2, int(state["num_dumps"]))
return state, welford
def _cmd_consensus_begin(args: argparse.Namespace) -> int:
"""Create a new incremental consensus session persisted on disk."""
import numpy as np
state_path = Path(args.state)
mean_path, m2_path = _consensus_state_paths(state_path)
state_path.parent.mkdir(parents=True, exist_ok=True)
mean = np.zeros(args.size, dtype=np.float32)
m2 = np.zeros(args.size, dtype=np.float32)
np.save(mean_path, mean)
np.save(m2_path, m2)
state_path.write_text(json.dumps({
"size": args.size,
"num_dumps": 0,
"mean_path": str(mean_path),
"m2_path": str(m2_path),
}, indent=2))
print(f"Begun consensus session: size={args.size} state={state_path}")
return 0
def _cmd_consensus_add(args: argparse.Namespace) -> int:
"""Fold one dump into an existing incremental consensus session."""
import numpy as np
from core.dump_source import open_dump
state_path = Path(args.state)
state, welford = _load_welford_session(state_path)
size = int(state["size"])
with open_dump(Path(args.dump), **_key_material_from_args(args)) as source:
_warn_tag_status(source)
data = source.read_all()[:size]
if len(data) < size:
print(
f"Dump shorter than consensus size ({len(data)} < {size})",
file=sys.stderr,
)
return 1
welford.add_dump(data)
new_mean, new_m2, new_n = welford.state_arrays()
np.save(state["mean_path"], new_mean)
np.save(state["m2_path"], new_m2)
state["num_dumps"] = new_n
state_path.write_text(json.dumps(state, indent=2))
current = welford.variance()
print(
f"[{new_n}] mean_var={float(current.mean()):.2f} "
f"max_var={float(current.max()):.2f}"
)
return 0
def _cmd_consensus_finalize(args: argparse.Namespace) -> int:
"""Materialize variance + classifications from a persisted session."""
from core.variance import classify_variance, count_classifications
state_path = Path(args.state)
state, welford = _load_welford_session(state_path)
size = int(state["size"])
variance = welford.variance()
classifications = classify_variance(variance)
counts = count_classifications(classifications)
result = {
"num_dumps": welford.num_dumps,
"size": size,
"classification_counts": counts,
"variance_summary": {
"mean": float(variance.mean()),
"max": float(variance.max()),
"min": float(variance.min()),
},
}
_write_output(result, args.output)
return 0
def _cmd_search_reduce(args: argparse.Namespace) -> int:
"""Run variance → alignment → entropy reduction on a finalized session."""
from core.dump_source import open_dump
from engine.candidate_pipeline import reduce_search_space
state_path = Path(args.state)
_state, welford = _load_welford_session(state_path)
variance = welford.variance()
with open_dump(Path(args.reference_dump), **_key_material_from_args(args)) as source:
_warn_tag_status(source)
reference_data = source.read_all()[: len(variance)]
result = reduce_search_space(
variance, reference_data, num_dumps=welford.num_dumps,
alignment=args.alignment,
block_size=args.block_size,
density_threshold=args.density_threshold,
min_variance=args.min_variance,
entropy_window=args.entropy_window,
entropy_threshold=args.entropy_threshold,
min_region=args.min_region,
)
_write_output(result.to_dict(), args.output)
return 0
def _cmd_brute_force(args: argparse.Namespace) -> int:
"""Iterate candidates through a user oracle and emit hits.json."""
from core.dump_source import open_dump
from engine.brute_force import run_brute_force, write_result
with open_dump(Path(args.dump), **_key_material_from_args(args)) as source:
_warn_tag_status(source)
reference_data = source.read_all()
key_sizes = tuple(int(k.strip()) for k in args.key_sizes.split(",") if k.strip())
result = run_brute_force(
candidates_path=Path(args.candidates),
reference_data=reference_data,
oracle_path=Path(args.oracle),
oracle_config_path=Path(args.oracle_config) if args.oracle_config else None,
key_sizes=key_sizes,
stride=args.stride,
jobs=args.jobs,
exhaustive=not args.first_hit,
state_path=Path(args.state) if args.state else None,
top_k=args.top_k,
)
write_result(result, Path(args.output))
if result.hits:
print(
f"memdiver: verified {len(result.hits)} hit(s); first at offset "
f"0x{result.hits[0].offset:x} ({result.hits[0].length} bytes)",
file=sys.stderr,
)
else:
print(
f"memdiver: exhausted {result.total_candidates} candidates, "
f"0 verified; top-{len(result.top_k)} written to {args.output}",
file=sys.stderr,
)
return result.exit_code
def _cmd_n_sweep(args: argparse.Namespace) -> int:
"""Sweep N ∈ n_values, run consensus → reduce → oracle, emit reports."""
from core.dump_source import open_dump
from engine.nsweep import run_nsweep, write_nsweep_artifacts
from engine.oracle import load_oracle, load_oracle_config
runs_dir = Path(args.runs_dir)
dump_paths = sorted(runs_dir.glob(f"*/{args.dump_glob}"))
if not dump_paths:
dump_paths = sorted(runs_dir.rglob(args.dump_glob))
if not dump_paths:
print(f"no dumps matched {runs_dir}/*/{args.dump_glob}", file=sys.stderr)
return 1
n_values = [int(n.strip()) for n in args.n_values.split(",") if n.strip()]
key_sizes = tuple(int(k.strip()) for k in args.key_sizes.split(",") if k.strip())
oracle_config = load_oracle_config(
Path(args.oracle_config) if args.oracle_config else None
)
oracle = load_oracle(Path(args.oracle), oracle_config)
km = _key_material_from_args(args)
sources = [open_dump(p, **km).__enter__() for p in dump_paths]
if sources:
_warn_tag_status(sources[0])
try:
result = run_nsweep(
sources,
n_values=n_values,
reduce_kwargs=dict(
alignment=args.alignment,
block_size=args.block_size,
density_threshold=args.density_threshold,
min_variance=args.min_variance,
entropy_window=args.entropy_window,
entropy_threshold=args.entropy_threshold,
min_region=args.min_region,
),
oracle=oracle,
key_sizes=key_sizes,
stride=args.stride,
exhaustive=not args.first_hit,
)
finally:
for src in sources:
try:
src.__exit__(None, None, None)
except Exception:
pass
paths = write_nsweep_artifacts(result, Path(args.output_dir))
print(result.headline(), file=sys.stderr)
print(f"wrote {paths['json']}, {paths['md']}, {paths['html']}", file=sys.stderr)
return 0 if result.first_hit_n is not None else 2
def _cmd_emit_plugin(args: argparse.Namespace) -> int:
"""Emit a Volatility3 plugin from a hits.json neighborhood variance."""
from core.dump_source import open_dump
from engine.vol3_emit import emit_plugin_from_hits_file
with open_dump(Path(args.reference), **_key_material_from_args(args)) as source:
_warn_tag_status(source)
reference_data = source.read_all()
out = emit_plugin_from_hits_file(
hits_path=Path(args.hit),
reference_data=reference_data,
name=args.name,
output_path=Path(args.output),
hit_index=args.hit_index,
description=args.description,
variance_threshold=args.variance_threshold,
)
print(f"wrote vol3 plugin {out}", file=sys.stderr)
return 0
def _cmd_export(args: argparse.Namespace) -> int:
"""Export a byte pattern from dump files as YARA/JSON/Volatility3.
Thin CLI adapter over ``api.services.analysis_service.auto_export_pattern``.
The service function owns the consensus → pattern pipeline, so the
CLI and the HTTP API cannot drift. Prior to PR 4 this command had
its own copy of the pipeline that:
1. Opened DumpSource objects via ``open_dump(p)`` without calling
``.open()`` on them, so ``MslDumpSource.get_reader()`` raised
``RuntimeError("MslDumpSource not opened; use context manager")``
on any MSL input — effectively crashing ``memdiver export --auto``
outright for the ``.msl`` file type.
2. Fed the aligned memory-relative offsets from ``build_from_sources``
into ``StaticChecker.check(dump_paths, offset, length)`` which
reads **raw file bytes** at those offsets. The bytes that came
back were not the bytes at the memory offset — they were
arbitrary file content that happened to sit at the same numeric
position. Latent bug; never triggered because (1) killed the
command first.
Both bugs are closed here by delegation to the service.
"""
from api.services.analysis_service import (
AnalysisServiceError,
auto_export_pattern,
manual_export_pattern,
)
dump_paths = _resolve_dump_paths(args.dumps)
if len(dump_paths) < 2:
print(f"Need at least 2 dumps, got {len(dump_paths)}", file=sys.stderr)
return 1
key_material = _key_material_from_args(args)
try:
if args.auto:
result = auto_export_pattern(
dump_paths,
fmt=args.format,
name=args.name,
align=getattr(args, "align", False),
context=getattr(args, "context", 32),
min_static_ratio=args.min_static_ratio,
key_material=key_material,
)
else:
if args.offset is None or args.length is None:
print(
"Specify --offset and --length, or use --auto",
file=sys.stderr,
)
return 1
if any(key_material.values()):
print(
"memdiver: note — manual --offset/--length export reads raw "
"file bytes; decryption flags apply only to --auto",
file=sys.stderr,
)
result = manual_export_pattern(
dump_paths,
offset=args.offset,
length=args.length,
fmt=args.format,
name=args.name,
min_static_ratio=args.min_static_ratio,
)
except AnalysisServiceError as exc:
print(str(exc), file=sys.stderr)
return 1
region = result["region"]
logger.info(
"Auto-selected region: offset=0x%x length=%d (key 0x%x-0x%x)",
region["offset"], region["length"],
region["key_start"], region["key_end"],
)
print(
f"Auto-detected region: offset=0x{region['offset']:x}, "
f"{region['length']} bytes (key at 0x{region['key_start']:x}-"
f"0x{region['key_end']:x}, context={args.context}B)",
file=sys.stderr,
)
content = result["content"]
if args.output:
Path(args.output).write_text(content)
print(f"Exported {result['format']} to {args.output}", file=sys.stderr)
else:
print(content)
return 0
def _cmd_gen_kem_key(args: argparse.Namespace) -> int:
"""Generate a KEM keypair for encrypted-MSL recipients (spec §10.4).
Writes the public key (shared with producers) and the private key (used
later via ``--kem-key-file`` to decrypt). Hybrid keys are the
concatenation of the X25519 and ML-KEM-768 halves.
"""
from msl.crypto import (MslCryptoError, kem_generate_keypair,
kem_is_available)
from msl.enums import KeyEncap
mechanisms = {
"X25519": KeyEncap.X25519,
"ML-KEM-768": KeyEncap.ML_KEM_768,
"ML-KEM-1024": KeyEncap.ML_KEM_1024,
"X25519+ML-KEM-768": KeyEncap.X25519_ML_KEM_768,
}
mech = mechanisms[args.mechanism]
if not kem_is_available(mech):
print(f"memdiver: {args.mechanism} unavailable; install the post-quantum "
f"extra: pip install memdiver[crypto]", file=sys.stderr)
return 1
try:
public_key, private_key = kem_generate_keypair(mech)
except MslCryptoError as exc:
print(f"memdiver: {exc}", file=sys.stderr)
return 1
Path(args.public_out).write_bytes(public_key)
Path(args.private_out).write_bytes(private_key)
print(f"memdiver: wrote {args.public_out} ({len(public_key)}B public) and "
f"{args.private_out} ({len(private_key)}B private) for {args.mechanism}",
file=sys.stderr)
return 0
def _cmd_import_dir(args: argparse.Namespace) -> int:
"""Import all .dump files in a run directory to .msl format."""
from msl.importer import import_run_directory
results = import_run_directory(
Path(args.run_dir), Path(args.output_dir),
keylog_filename=args.keylog_filename,
)
print(json.dumps([{
"source": str(r.source_path),
"output": str(r.output_path),
"key_hints": r.key_hints_written,
} for r in results], indent=2))
return 0
def _cmd_verify(args: argparse.Namespace) -> int:
"""Verify a candidate key at a given offset against known ciphertext."""
from engine.verification import VERIFIER_REGISTRY, VERIFICATION_IV
dump_path = Path(args.dump)
if not dump_path.is_file():
print(f"Dump file not found: {dump_path}", file=sys.stderr)
return 1
cipher = args.cipher
if cipher not in VERIFIER_REGISTRY:
print(f"Unknown cipher: {cipher}. Available: {list(VERIFIER_REGISTRY)}",
file=sys.stderr)
return 1
verifier = VERIFIER_REGISTRY[cipher]
dump_data = dump_path.read_bytes()
offset = args.offset
length = args.length
if offset + length > len(dump_data):
print(f"Offset 0x{offset:x} + length {length} exceeds dump size {len(dump_data)}",
file=sys.stderr)
return 1
candidate = dump_data[offset:offset + length]
ciphertext = bytes.fromhex(args.ciphertext_hex)
iv = bytes.fromhex(args.iv_hex) if args.iv_hex else VERIFICATION_IV
from engine.verification import VERIFICATION_PLAINTEXT
result_val = verifier.verify(candidate, ciphertext, iv, VERIFICATION_PLAINTEXT)
result = {
"offset": f"0x{offset:x}",
"length": length,
"cipher": cipher,
"verified": result_val,
"key_hex": candidate.hex() if result_val else None,
}
_write_output(result, getattr(args, 'output', None))
return 0
def _cmd_experiment(args: argparse.Namespace) -> int:
"""Orchestrate: spawn target, dump, build consensus, verify, export."""
try:
from core.dump_driver import DumpOrchestrator
from engine.consensus import ConsensusVector
from engine.verification import (
AesCbcVerifier, VERIFICATION_PLAINTEXT, VERIFICATION_IV,
)
from architect.static_checker import StaticChecker
from architect.pattern_generator import PatternGenerator
except ImportError:
_print_missing_package("The experiment flow", extra="experiment")
return 1
target_path = Path(args.target)
if not target_path.is_file():
print(f"Target script not found: {target_path}", file=sys.stderr)
return 1
tools = args.tools.split(",") if args.tools else None
orch = DumpOrchestrator(tools=tools)
if not orch.available_tools:
_print_missing_package("No dump tools available", extra="experiment")
print(
"This installs frida-tools and memslicer. The lldb backend is "
"optional and must be installed via your OS (Xcode on macOS, "
"'apt install lldb' on Debian/Ubuntu, etc.).",
file=sys.stderr,
)
return 1
print(f"Available tools: {[t.name for t in orch.available_tools]}", file=sys.stderr)
print(f"Running {args.num_runs} iterations per tool...", file=sys.stderr)
# Step 1: Run experiment
exp = orch.run_experiment(
target_path, args.num_runs, args.output_dir,
)
# Step 2: Per-tool analysis
verifier = AesCbcVerifier()
all_tool_results = {}
for tool_name, tool_dir in exp.tool_dirs.items():
dump_paths = sorted(
list(tool_dir.glob("*/*.dump")) + list(tool_dir.glob("*/*.msl"))
)
if len(dump_paths) < 2:
print(f" [{tool_name}] Not enough dumps ({len(dump_paths)}), skipping",
file=sys.stderr)
continue
print(f" [{tool_name}] Analyzing {len(dump_paths)} dumps...", file=sys.stderr)
# Build consensus
cm = ConsensusVector()
cm.build(dump_paths)
aligned = cm.get_aligned_candidates()
volatile = cm.get_volatile_regions()
# Decryption verification
first_data = dump_paths[0].read_bytes()
first_key = exp.metadata["runs"][0]["key_hex"]
key_bytes = bytes.fromhex(first_key)
ct = verifier.create_ciphertext(key_bytes, VERIFICATION_PLAINTEXT, VERIFICATION_IV)
dec_verified = False
for region in aligned:
for off in range(region.start, region.end - 31):
candidate = first_data[off:off + 32]
if verifier.verify(candidate, ct, VERIFICATION_IV, VERIFICATION_PLAINTEXT):
dec_verified = True
break
if dec_verified:
break
# Auto-export pattern
plugin_content = None
if volatile:
best = max(volatile, key=lambda r: r.end - r.start)
ctx = 32
exp_offset = max(0, best.start - ctx)
exp_end = min(cm.size, best.end + ctx)
exp_length = exp_end - exp_offset
static_mask, reference = StaticChecker.check(dump_paths, exp_offset, exp_length)
if reference:
pattern = PatternGenerator.generate(reference, static_mask, f"{tool_name}_aes256_key")
if pattern:
fmt = args.export_format
if fmt in ("volatility3", "vol3"):
from architect.volatility3_exporter import Volatility3Exporter
from architect.yara_exporter import YaraExporter
yara_rule = YaraExporter.export(pattern)
plugin_content = Volatility3Exporter.export(pattern, yara_rule=yara_rule)
elif fmt == "yara":
from architect.yara_exporter import YaraExporter
plugin_content = YaraExporter.export(pattern)
# Save plugin
plugin_path = None
if plugin_content:
plugins_dir = args.output_dir / "plugins"
plugins_dir.mkdir(parents=True, exist_ok=True)
ext = ".py" if args.export_format in ("volatility3", "vol3") else ".yar"
plugin_path = plugins_dir / f"{tool_name}_aes256_key{ext}"
plugin_path.write_text(plugin_content)
tool_result = {
"tool": tool_name,
"format": "MSL (.msl)" if tool_name == "memslicer" else "Raw (.dump)",
"num_dumps": len(dump_paths),
"volatile_regions": len(volatile),
"aligned_regions": len(aligned),
"decryption_verified": dec_verified,
"plugin_saved": str(plugin_path) if plugin_path else None,
}
# Convergence sweep
if args.convergence:
from engine.convergence import run_convergence_sweep
from engine.serializer import serialize_convergence_result
# Build ground truth from first run's key position
# (we don't know the exact offset in real dumps, so skip precision/recall)
sweep = run_convergence_sweep(
dump_paths, max_fp=args.max_fp,
)
tool_result["convergence"] = serialize_convergence_result(sweep)
all_tool_results[tool_name] = tool_result
# Print comparison table
_print_experiment_table(all_tool_results)
# Write JSON output
if args.output:
_write_output(all_tool_results, args.output)
return 0
def _print_experiment_table(results: dict) -> None:
"""Print side-by-side tool comparison table."""
tools = list(results.keys())
if not tools:
print("No results to display.")
return
w = 17
tw = 15
print(f"\n{'=' * (w + len(tools) * (tw + 3) + 3)}")
print(" EXPERIMENT RESULTS — Per-Tool Comparison")
print(f"{'=' * (w + len(tools) * (tw + 3) + 3)}")
# Header
header = f"{'Metric':<{w}}"
for t in tools:
header += f" | {t:^{tw}}"
print(f"\n{header}")
print(f"{'-' * w}" + "".join(f"-+-{'-' * tw}" for _ in tools))