-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjanus.py
More file actions
2183 lines (1964 loc) · 82.1 KB
/
janus.py
File metadata and controls
2183 lines (1964 loc) · 82.1 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
#!/usr/bin/env python3
"""
Janus - Turn red team and purple team operational logs into actionable intelligence.
CLI entry point for Mythic pull-mode and other source parsers.
"""
import argparse
import json
import os
import re
import sys
import zlib
import traceback
from datetime import datetime, timezone
from pathlib import Path
if sys.version_info < (3, 12):
print(
"error: Janus requires Python 3.12 or newer. Use the Go janus-cli wrapper or a newer Python runtime.",
file=sys.stderr,
)
raise SystemExit(2)
import requests
import yaml
from Analyzers.SummaryAnalysis.summary_visualization import (
analyze as summary_visualization,
)
from Analyzers.CommandAnalysis.command_failure_summary import (
analyze as command_failure_summary,
)
from Analyzers.CommandAnalysis.command_retry_success import (
analyze as command_retry_success,
)
from Analyzers.CommandAnalysis.command_duration import (
analyze as command_duration,
)
from Analyzers.CommandAnalysis.outlier_context import (
analyze as outlier_context,
)
from Analyzers.WorkflowAnalysis.callback_health import (
analyze as callback_health,
)
from Analyzers.CommandAnalysis.av_tracker import (
analyze as av_tracker,
)
from Analyzers.WorkflowAnalysis.dwell_time import (
analyze as dwell_time,
)
from Analyzers.WorkflowAnalysis.parameter_entropy import (
analyze as parameter_entropy,
)
from Analyzers.ToolingAnalysis.argument_position_profile import (
analyze as argument_position_profile,
)
from Analyzers.ToolingAnalysis.tool_dump import (
analyze as tool_dump,
)
from Core.analyzer_registry import (
ALL_ANALYZERS,
ANALYZER_OUTPUTS,
MULTI_ANALYZE_ANALYZERS,
PARTIAL_LOAD_ANALYZERS,
)
from Core.analyzer_behavior_registry import build_analyzer_context
from Core.html_output import generate_html
from Core.io import (
EventValidationError,
create_latest_symlink,
get_versioned_output_dir,
validate_events,
write_bundle,
write_ndjson,
)
from Core.output_rule import (
apply_output_rule_to_results,
apply_arguments_rule_to_tasks,
apply_retention_policy,
detect_retention_from_events,
privacy_warnings_for_analyzer,
resolve_output_rule,
resolve_arguments_rule,
resolve_retention_policy,
RetentionPolicy,
)
from Parsers.Mythic.mythic_pull import MythicPullParser, slugify
from Parsers.Mythic.partial_data_adapter import load_partial_mythic_json
from Parsers.Ghostwriter.client import GhostwriterSchemaError
from Parsers.Ghostwriter.ghostwriter_pull import GhostwriterPullParser
from Parsers.Ghostwriter.ghostwriter_pull import slugify as gw_slugify
from Parsers.CobaltStrike.cobalt_strike_rest import (
CobaltStrikeRestPullParser,
slugify as cs_slugify,
run_cobaltstrike_rest_ingest,
)
DEFAULT_MYTHIC_ENDPOINT = "https://10.0.0.217:7443/graphql/"
DEFAULT_GHOSTWRITER_ENDPOINT = "https://127.0.0.1"
DEFAULT_COBALT_STRIKE_REST_ENDPOINT = "https://127.0.0.1:50050"
DEFAULT_CONFIG_PATH = Path("Config/janus.yml")
GW_API_TOKEN_ENV = "GHOSTWRITER_API_KEY"
def _format_file_uri(path: Path) -> str:
"""Return a file:// URI for a local path."""
return path.resolve().as_uri()
def _print_mythic_request_hints(endpoint: str, verify_tls: bool, exc_text: str) -> None:
"""Print focused troubleshooting hints for Mythic request failures."""
exc_lower = exc_text.lower()
print(f"hint: configured endpoint is '{endpoint}'", file=sys.stderr)
print("hint: verify mythic.endpoint in Config/janus.yml matches your Mythic URL and port.", file=sys.stderr)
protocol_mismatch = (
"record layer failure" in exc_lower
or "wrong version number" in exc_lower
or "unknown protocol" in exc_lower
)
if protocol_mismatch:
print(
"hint: this usually means an HTTP/HTTPS mismatch (for example https://... pointed at an HTTP service).",
file=sys.stderr,
)
print(
"hint: if Mythic is HTTP, use an endpoint like 'http://<host>:<port>/graphql/'.",
file=sys.stderr,
)
cert_verify_failed = (
"certificate_verify_failed" in exc_lower
or "certificate verify failed" in exc_lower
or "self-signed certificate" in exc_lower
)
if verify_tls:
if cert_verify_failed:
print(
"hint: TLS certificate validation failed (likely self-signed or untrusted cert).",
file=sys.stderr,
)
print(
"hint: set mythic.verify_tls: false in Config/janus.yml for lab/self-signed Mythic endpoints.",
file=sys.stderr,
)
print(
"hint: or rerun this command with --insecure for a one-off test.",
file=sys.stderr,
)
else:
print(
"hint: if Mythic uses a self-signed cert, retry with '--insecure' after confirming the endpoint protocol.",
file=sys.stderr,
)
ANALYZER_FUNCTIONS = {
"summary-visualization": summary_visualization,
"command-failure-summary": command_failure_summary,
"command-retry-success": command_retry_success,
"command-duration": command_duration,
"outlier-context": outlier_context,
"callback-health": callback_health,
"av-tracker": av_tracker,
"dwell-time": dwell_time,
"parameter-entropy": parameter_entropy,
"argument-position-profile": argument_position_profile,
"tool-dump": tool_dump,
}
REGISTRY_AWARE_ANALYZERS = {
"command-duration",
"parameter-entropy",
"outlier-context",
"argument-position-profile",
"tool-dump",
}
def _build_runtime_analyzer_context(output_dir: Path | None = None) -> dict:
context = build_analyzer_context()
if output_dir is not None:
context["output_dir"] = str(output_dir)
return context
def load_config(config_path: Path | None) -> dict:
"""Load YAML config if path provided."""
if config_path is None or not config_path.exists():
return {}
with config_path.open(encoding="utf-8") as f:
return yaml.safe_load(f) or {}
def _resolve_cli_source(config: dict, requested_source: str | None) -> str:
if requested_source:
return requested_source
configured = config.get("source")
if configured in {"mythic", "ghostwriter", "cobaltstrike"}:
return configured
has_mythic = bool(config.get("mythic"))
has_ghostwriter = bool(config.get("ghostwriter"))
has_cobaltstrike = bool(config.get("cobaltstrike"))
if has_ghostwriter and not has_mythic:
return "ghostwriter"
if has_cobaltstrike and not has_mythic and not has_ghostwriter:
return "cobaltstrike"
return "mythic"
def _merge_common_metadata(result: dict, common_metadata: dict) -> dict:
merged = dict(result)
merged["analyzer"] = common_metadata["analyzer"]
merged_metadata = dict(result.get("metadata", {}))
merged_metadata.update(common_metadata.get("metadata", {}))
merged["metadata"] = merged_metadata
return merged
def _run_analyzer(analyzer_name: str, analyzer_func, task_events: list[dict], result_events: list[dict], context: dict) -> dict:
if analyzer_name in REGISTRY_AWARE_ANALYZERS:
return analyzer_func(task_events, result_events, context)
return analyzer_func(task_events, result_events)
def find_previous_versions(
base_dir: Path, operation_slug: str, current_version: str
) -> list[dict]:
"""
Scan for other {slug}_* directories, return sorted list (newest first).
``operation_slug`` is the filesystem-safe slug stored in ``bundle.json``
(falls back to ``op-{id}`` for legacy directories).
Returns list of dicts with keys: version, dir_name, report_path
"""
if not base_dir.exists():
return []
pattern = re.compile(
rf"^{re.escape(operation_slug)}_(\d{{8}}_\d{{6}})(?:_[a-f0-9]{{8}})?$"
)
versions = []
for item in base_dir.iterdir():
if not item.is_dir():
continue
match = pattern.match(item.name)
if match:
version = match.group(1)
if version != current_version:
report_path = item / "report.html"
if report_path.exists():
versions.append({
"version": version,
"dir_name": item.name,
"report_path": report_path,
})
# Sort by version string (YYYYMMDD_HHMMSS format is naturally sortable)
versions.sort(key=lambda v: v["version"], reverse=True)
return versions
def run_mythic(
operation_id: int,
endpoint: str | None,
api_token: str | None,
verify_tls: bool,
out_dir: Path,
config: dict,
debug: bool = False,
no_versioning: bool = False,
output_rule_cli: str | None = None,
arguments_rule_cli: str | None = None,
) -> int:
"""Run Mythic pull-mode parser."""
mythic_cfg = config.get("mythic", {})
endpoint = endpoint or mythic_cfg.get("endpoint") or DEFAULT_MYTHIC_ENDPOINT
api_token = api_token or mythic_cfg.get("api_token")
if not api_token:
print(
"error: API token required. Set --api-token or mythic.api_token in config.",
file=sys.stderr,
)
return 1
if not verify_tls:
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
parser = MythicPullParser(endpoint=endpoint, api_token=api_token, verify_tls=verify_tls, debug=debug)
print("Preflight: connectivity/auth (Mythic)...")
try:
parser.preflight(operation_id=operation_id)
except requests.exceptions.RequestException as exc:
exc_text = str(exc)
print(
f"error: Mythic preflight failed before ingest for operation {operation_id}: {exc_text}",
file=sys.stderr,
)
_print_mythic_request_hints(endpoint, verify_tls, exc_text)
if debug:
traceback.print_exc()
return 1
except Exception as exc:
print(f"error: Mythic preflight failed: {exc}", file=sys.stderr)
if debug:
traceback.print_exc()
return 1
print("Preflight: OK")
# Resolve the real operation name from Mythic before creating the
# output directory so the slug appears in the directory name.
operation_name = parser.fetch_operation_name(operation_id)
op_slug = slugify(operation_name)
print(f"Operation: {operation_name} (ID: {operation_id}, slug: {op_slug})")
# Generate analysis timestamp and versioned directory
analysis_timestamp = datetime.now(timezone.utc)
if no_versioning:
target_dir = out_dir
else:
target_dir = get_versioned_output_dir(out_dir, op_slug, analysis_timestamp)
target_dir.mkdir(parents=True, exist_ok=True)
policy = resolve_retention_policy(config, output_rule_cli, arguments_rule_cli)
try:
metadata = parser.run(
operation_id=operation_id,
out_dir=target_dir,
analysis_timestamp=analysis_timestamp,
operation_name=operation_name,
output_rule=policy.output_rule,
arguments_rule=policy.arguments_rule,
)
except requests.exceptions.RequestException as exc:
exc_text = str(exc)
print(f"error: Mythic request failed while pulling operation {operation_id}: {exc_text}", file=sys.stderr)
_print_mythic_request_hints(endpoint, verify_tls, exc_text)
if debug:
traceback.print_exc()
return 1
except Exception as exc:
print(f"error: Mythic pull failed: {exc}", file=sys.stderr)
if debug:
traceback.print_exc()
return 1
# Create 'latest' symlink/marker unless versioning is disabled
if not no_versioning:
create_latest_symlink(out_dir, target_dir)
task_count = metadata["task_count"]
result_count = metadata["result_count"]
status_counts = metadata["status_counts"]
print(f"Output directory: {target_dir}")
print(f"Tasks pulled: {task_count}")
print(f"Results pulled: {result_count}")
print(f"Status: success={status_counts['success']}, error={status_counts['error']}, unknown={status_counts['unknown']}")
return 0
def run_ghostwriter(
oplog_id: int,
endpoint: str | None,
api_token: str | None,
verify_tls: bool,
out_dir: Path,
config: dict,
debug: bool = False,
no_versioning: bool = False,
output_rule_cli: str | None = None,
arguments_rule_cli: str | None = None,
) -> int:
"""Run Ghostwriter raw export."""
gw_cfg = config.get("ghostwriter", {})
endpoint = endpoint or gw_cfg.get("endpoint") or DEFAULT_GHOSTWRITER_ENDPOINT
# Auth resolution: CLI --api-token > env GHOSTWRITER_API_KEY > legacy env > config api_token
api_token = (
api_token
or os.environ.get(GW_API_TOKEN_ENV)
or os.environ.get("GW_API_TOKEN")
or gw_cfg.get("api_token")
)
if not verify_tls:
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
if not api_token:
print(
"error: Ghostwriter API token required. Set --api-token, GHOSTWRITER_API_KEY, or ghostwriter.api_token in config.",
file=sys.stderr,
)
return 1
parser = GhostwriterPullParser(
endpoint=endpoint, api_token=api_token, verify_tls=verify_tls, debug=debug
)
print("Preflight: connectivity/auth (Ghostwriter)...")
try:
parser.require_oplog_access()
oplog_name = parser.fetch_oplog_name(oplog_id)
except GhostwriterSchemaError as exc:
print(f"error: {exc}", file=sys.stderr)
return 1
except requests.exceptions.SSLError as exc:
print(f"error: Ghostwriter preflight failed (TLS): {exc}", file=sys.stderr)
print(f"hint: configured endpoint is '{endpoint}'", file=sys.stderr)
print(
"hint: if this is a lab/self-signed endpoint, set ghostwriter.verify_tls: false in Config/janus.yml "
"or rerun with --insecure.",
file=sys.stderr,
)
return 1
except requests.exceptions.RequestException as exc:
print(f"error: Ghostwriter preflight failed (connectivity/auth): {exc}", file=sys.stderr)
print(f"hint: configured endpoint is '{endpoint}'", file=sys.stderr)
print(
"hint: verify ghostwriter.endpoint and credentials/token in Config/janus.yml, then retry.",
file=sys.stderr,
)
return 1
except Exception as exc:
print(f"error: Ghostwriter preflight failed: {exc}", file=sys.stderr)
return 1
print("Preflight: OK")
op_slug = gw_slugify(oplog_name)
print(f"Oplog export target: {oplog_name} (ID: {oplog_id}, slug: {op_slug})")
analysis_timestamp = datetime.now(timezone.utc)
if no_versioning:
target_dir = out_dir
else:
target_dir = get_versioned_output_dir(out_dir, op_slug, analysis_timestamp)
target_dir.mkdir(parents=True, exist_ok=True)
policy = resolve_retention_policy(config, output_rule_cli, arguments_rule_cli)
metadata = parser.run(
oplog_id=oplog_id,
out_dir=target_dir,
analysis_timestamp=analysis_timestamp,
oplog_name=oplog_name,
output_rule=policy.output_rule,
arguments_rule=policy.arguments_rule,
)
if not no_versioning:
create_latest_symlink(out_dir, target_dir)
print(f"Output directory: {target_dir}")
print(f"Raw export: {target_dir / metadata['raw_export_path']}")
print(f"Events: {target_dir / metadata['events_path']}")
print(f"Entries exported: {metadata['entry_count']}")
print(f"Tasks normalized: {metadata['task_count']}")
print(f"Results normalized: {metadata['result_count']}")
status_counts = metadata["status_counts"]
print(f"Status: success={status_counts['success']}, error={status_counts['error']}, unknown={status_counts['unknown']}")
return 0
def load_events(events_path: Path, validate: bool = False) -> tuple[list[dict], list[dict]]:
"""Read events.ndjson and split into task and result event lists.
Args:
events_path: Path to NDJSON events file.
validate: When True, enforce required event schema.
"""
task_events = []
result_events = []
unknown_event_types = set()
with events_path.open(encoding="utf-8") as f:
for line_number, line in enumerate(f, start=1):
line = line.strip()
if not line:
continue
try:
event = json.loads(line)
except json.JSONDecodeError as exc:
raise ValueError(
f"{events_path}:{line_number}: malformed JSON: {exc.msg}"
) from exc
event_type = event.get("event_type")
if event_type == "task":
task_events.append(event)
elif event_type == "result":
result_events.append(event)
else:
unknown_event_types.add(str(event_type))
if unknown_event_types:
unknown_list = ", ".join(sorted(unknown_event_types))
print(
f"warning: skipped events with unknown event_type(s): {unknown_list}",
file=sys.stderr,
)
if validate:
try:
validate_events(task_events + result_events)
except EventValidationError as exc:
raise ValueError(f"{events_path}: invalid event schema: {exc}") from exc
return task_events, result_events
def _derive_unique_operation_id(
used_operation_ids: set[int],
base_id: int,
source_key: str,
) -> int:
"""Generate a deterministic unique operation_id for merged datasets."""
if base_id > 0 and base_id not in used_operation_ids:
return base_id
candidate = 1000000000 + (zlib.crc32(source_key.encode("utf-8")) % 1000000000)
while candidate in used_operation_ids or candidate <= 0:
candidate += 1
return candidate
def _remap_operation_id(events: list[dict], operation_id: int) -> None:
"""Rewrite operation_id for all events in-place."""
for event in events:
event["operation_id"] = operation_id
def _expand_input_pattern(pattern: str) -> list[Path]:
"""Expand an input glob pattern with light path normalization.
On Windows, patterns ending in duplicated separators like ``out/complete//``
can fail to match even though the equivalent normalized directory exists.
We try the original pattern first, then a normalized variant, and finally
accept a direct directory path when the normalized form names one.
"""
import glob
candidates: list[str] = []
seen: set[str] = set()
def add_candidate(value: str) -> None:
if value and value not in seen:
seen.add(value)
candidates.append(value)
add_candidate(pattern)
normalized = os.path.normpath(pattern)
add_candidate(normalized)
stripped = normalized.rstrip("/\\")
add_candidate(stripped)
matches: list[Path] = []
matched_paths: set[Path] = set()
for candidate in candidates:
for matched in glob.glob(candidate, recursive=True):
path = Path(matched)
if path in matched_paths:
continue
matched_paths.add(path)
matches.append(path)
direct_dir = Path(normalized)
if direct_dir.is_dir() and direct_dir not in matched_paths:
matches.append(direct_dir)
return [path for path in matches if path.is_dir()]
def load_ghostwriter_raw_export(
raw_export_path: Path,
out_dir: Path | None = None,
analysis_timestamp: datetime | None = None,
config: dict | None = None,
output_rule_cli: str | None = None,
arguments_rule_cli: str | None = None,
) -> int:
"""Normalize an existing Ghostwriter raw_export.json into events.ndjson."""
if not raw_export_path.exists():
print(f"error: raw export not found: {raw_export_path}", file=sys.stderr)
return 1
try:
with raw_export_path.open(encoding="utf-8") as f:
raw_export = json.load(f)
except Exception as exc:
print(f"error: failed to read Ghostwriter raw export: {exc}", file=sys.stderr)
return 1
output_dir = out_dir or raw_export_path.parent
output_dir.mkdir(parents=True, exist_ok=True)
task_events, result_events, normalized = GhostwriterPullParser.normalize_export(raw_export)
events_path = output_dir / "events.ndjson"
bundle_path = output_dir / "bundle.json"
existing_bundle = {}
if bundle_path.exists():
try:
with bundle_path.open(encoding="utf-8") as f:
existing_bundle = json.load(f)
except Exception:
existing_bundle = {}
effective_config = dict(config or {})
if (
output_rule_cli is None
and "output_rule" not in effective_config
and existing_bundle.get("output_rule")
):
effective_config["output_rule"] = existing_bundle["output_rule"]
if (
arguments_rule_cli is None
and "arguments_rule" not in effective_config
and existing_bundle.get("arguments_rule")
):
effective_config["arguments_rule"] = existing_bundle["arguments_rule"]
policy = resolve_retention_policy(effective_config, output_rule_cli, arguments_rule_cli)
apply_retention_policy(task_events, result_events, policy)
all_events = [e.to_dict() for e in task_events] + [e.to_dict() for e in result_events]
write_ndjson(all_events, events_path)
status_counts = {"success": 0, "error": 0, "unknown": 0}
for event in result_events:
status_counts[event.status] += 1
op_name = raw_export.get("oplog_name") or existing_bundle.get("operation_name") or f"oplog-{raw_export.get('oplog_id', 0)}"
metadata = {
"source": "ghostwriter",
"operation_id": int(raw_export.get("oplog_id") or existing_bundle.get("operation_id") or 0),
"operation_name": op_name,
"operation_slug": gw_slugify(op_name),
"ghostwriter_endpoint": existing_bundle.get("ghostwriter_endpoint", ""),
"export_format": raw_export.get("export_format", "ghostwriter_raw"),
"entry_count": len(raw_export.get("entries", [])),
"task_count": len(task_events),
"result_count": len(result_events),
"status_counts": status_counts,
"skipped_entry_count": normalized["skipped_entries"],
"schema_probe": raw_export.get("schema_probe", {}),
"raw_export_path": raw_export_path.name,
"events_path": events_path.name,
"output_rule": policy.output_rule,
"arguments_rule": policy.arguments_rule,
}
write_bundle(metadata, bundle_path, analysis_timestamp)
print(f"Wrote: {events_path}")
print(f"Tasks loaded: {metadata['task_count']}")
print(f"Results loaded: {metadata['result_count']}")
print(f"Status: success={status_counts['success']}, error={status_counts['error']}, unknown={status_counts['unknown']}")
return 0
def run_analyze(
analyzer: str,
events_path: Path,
out_dir: Path,
analysis_timestamp: str | None = None,
) -> int:
"""Run an analyzer against an existing events.ndjson file."""
if not events_path.exists():
raw_export_path = events_path.parent / "raw_export.json"
if raw_export_path.exists():
bundle_path = events_path.parent / "bundle.json"
bundle_metadata = {}
if bundle_path.exists():
try:
with bundle_path.open(encoding="utf-8") as f:
bundle_metadata = json.load(f)
except Exception:
bundle_metadata = {}
output_rule = bundle_metadata.get("output_rule")
arguments_rule = bundle_metadata.get("arguments_rule")
if not output_rule or not arguments_rule:
print(
"error: events.ndjson is missing and raw_export.json is available, "
"but the original retention policy cannot be recovered safely.",
file=sys.stderr,
)
print(
"hint: raw_export.json is the unfiltered Ghostwriter source snapshot used for "
"later re-normalization. To avoid silently regenerating less-restricted events, "
"Janus requires the recorded output_rule and arguments_rule before auto-rebuild.",
file=sys.stderr,
)
print(
"hint: re-run `ghostwriter-load` with an explicit config or "
"`--output-rule/--arguments-rule`, or restore the original bundle.json.",
file=sys.stderr,
)
return 1
print(
"events.ndjson missing; re-normalizing existing Ghostwriter export "
f"from {raw_export_path} using recorded retention "
f"(output_rule={output_rule}, arguments_rule={arguments_rule})"
)
rc = load_ghostwriter_raw_export(
raw_export_path,
out_dir=events_path.parent,
config={
"output_rule": output_rule,
"arguments_rule": arguments_rule,
},
)
if rc != 0:
return rc
else:
print(f"error: events file not found: {events_path}", file=sys.stderr)
return 1
# Try to load bundle.json from same directory to extract operation metadata
bundle_path = events_path.parent / "bundle.json"
bundle_metadata = {}
if bundle_path.exists():
try:
with bundle_path.open(encoding="utf-8") as f:
bundle_metadata = json.load(f)
except Exception:
pass
task_events, result_events = load_events(events_path)
analyzer_context = _build_runtime_analyzer_context(out_dir)
retention_info = detect_retention_from_events(
task_events,
result_events,
bundle_metadata=bundle_metadata,
)
# Common metadata section for all analyzers
analyzer_metadata = {
"analyzer": analyzer,
"metadata": {
"events_analyzed": len(task_events) + len(result_events),
},
}
# Enrich with operation metadata if available
for key in ("operation_id", "operation_name", "operation_slug",
"mythic_endpoint", "ghostwriter_endpoint",
"analysis_version", "analysis_timestamp",
"janus_version"):
if key in bundle_metadata:
analyzer_metadata["metadata"][key] = bundle_metadata[key]
# Inject retention/privacy metadata
if retention_info.get("privacy_limited"):
analyzer_metadata["metadata"]["retention"] = {
"arguments_retained": retention_info["arguments_retained"],
"output_retained": retention_info["output_retained"],
"observed_arguments_rules": retention_info["observed_arguments_rules"],
"observed_output_rules": retention_info["observed_output_rules"],
}
pw = privacy_warnings_for_analyzer(analyzer, retention_info)
if pw:
analyzer_metadata["metadata"]["privacy_warnings"] = pw
if analyzer == "summary-visualization":
result = summary_visualization(task_events, result_events)
result = _merge_common_metadata(result, analyzer_metadata)
out_path = out_dir / "summary_visualization.json"
out_path.parent.mkdir(parents=True, exist_ok=True)
with out_path.open("w", encoding="utf-8") as f:
json.dump(result, f, indent=2, ensure_ascii=False)
print(f"Wrote: {out_path}")
sd = result["status_distribution"]
print(f"Status: {sd['success']} success, {sd['error']} error, {sd['unknown']} unknown")
summary = result["summary"]
print(f"Timeline: {summary['timeline_buckets']} buckets over {summary['span_hours']}h")
elif analyzer == "command-failure-summary":
result = command_failure_summary(task_events, result_events)
result = _merge_common_metadata(result, analyzer_metadata)
out_path = out_dir / "command_failure_summary.json"
out_path.parent.mkdir(parents=True, exist_ok=True)
with out_path.open("w", encoding="utf-8") as f:
json.dump(result, f, indent=2, ensure_ascii=False)
print(f"Wrote: {out_path}")
for cmd_name, stats in result["commands"].items():
rate = f"{stats['failure_rate']:.1%}"
print(f" {cmd_name}: {stats['execution_count']} executions, {rate} failure")
elif analyzer == "command-retry-success":
result = command_retry_success(task_events, result_events)
result = _merge_common_metadata(result, analyzer_metadata)
out_path = out_dir / "command_retry_success.json"
out_path.parent.mkdir(parents=True, exist_ok=True)
with out_path.open("w", encoding="utf-8") as f:
json.dump(result, f, indent=2, ensure_ascii=False)
print(f"Wrote: {out_path}")
summary = result["summary"]
print(f"Found {summary['total_retry_sequences']} retry sequences")
if summary["most_retried_command"]:
print(f"Most retried command: {summary['most_retried_command']}")
print(f"Average retries to success: {summary['avg_retries_to_success']}")
elif analyzer == "command-duration":
result = command_duration(task_events, result_events, analyzer_context)
result = _merge_common_metadata(result, analyzer_metadata)
out_path = out_dir / "command_duration.json"
out_path.parent.mkdir(parents=True, exist_ok=True)
with out_path.open("w", encoding="utf-8") as f:
json.dump(result, f, indent=2, ensure_ascii=False)
print(f"Wrote: {out_path}")
durations = result["durations"]
if durations:
# Find slowest and fastest commands
slowest = max(durations.items(), key=lambda x: x[1]["mean_seconds"])
fastest = min(durations.items(), key=lambda x: x[1]["mean_seconds"])
print(f"Slowest command: {slowest[0]} (avg: {slowest[1]['mean_seconds']}s)")
print(f"Fastest command: {fastest[0]} (avg: {fastest[1]['mean_seconds']}s)")
elif analyzer == "outlier-context":
result = outlier_context(task_events, result_events, analyzer_context)
result = _merge_common_metadata(result, analyzer_metadata)
out_path = out_dir / "outlier_context_analysis.json"
out_path.parent.mkdir(parents=True, exist_ok=True)
with out_path.open("w", encoding="utf-8") as f:
json.dump(result, f, indent=2, ensure_ascii=False)
print(f"Wrote: {out_path}")
outliers = result.get("outliers", [])
print(f"Enriched {len(outliers)} outlier(s) with context")
agg = result.get("aggregations", {})
prec = agg.get("most_common_preceding_command", {})
if prec:
top_prec = max(prec.items(), key=lambda x: x[1])
print(f"Most common preceding command: {top_prec[0]} ({top_prec[1]}x)")
elif analyzer == "callback-health":
result = callback_health(task_events, result_events)
result = _merge_common_metadata(result, analyzer_metadata)
out_path = out_dir / "callback_health.json"
out_path.parent.mkdir(parents=True, exist_ok=True)
with out_path.open("w", encoding="utf-8") as f:
json.dump(result, f, indent=2, ensure_ascii=False)
print(f"Wrote: {out_path}")
summary = result.get("summary", {})
print(f"Callbacks: {summary.get('total_callbacks', 0)} total, "
f"{summary.get('healthy_count', 0)} healthy, "
f"{summary.get('degraded_count', 0)} degraded, "
f"{summary.get('dead_count', 0)} dead")
elif analyzer == "av-tracker":
result = av_tracker(task_events, result_events)
result = _merge_common_metadata(result, analyzer_metadata)
out_path = out_dir / "av_tracker.json"
out_path.parent.mkdir(parents=True, exist_ok=True)
with out_path.open("w", encoding="utf-8") as f:
json.dump(result, f, indent=2, ensure_ascii=False)
print(f"Wrote: {out_path}")
summary = result.get("summary", {})
print(f"Scanned {summary.get('ps_tasks_scanned', 0)} ps result(s)")
print(f"Detections: {summary.get('detection_count', 0)} across {summary.get('callbacks_with_detections', 0)} callback(s)")
vendors = summary.get("vendors_detected", [])
if vendors:
print("Vendors detected: " + ", ".join(vendors))
elif analyzer == "dwell-time":
result = dwell_time(task_events, result_events)
result = _merge_common_metadata(result, analyzer_metadata)
out_path = out_dir / "dwell_time.json"
out_path.parent.mkdir(parents=True, exist_ok=True)
with out_path.open("w", encoding="utf-8") as f:
json.dump(result, f, indent=2, ensure_ascii=False)
print(f"Wrote: {out_path}")
stats = result["global_statistics"]
print(f"Dwell measurements: {stats['dwell_count']}")
print(f"Mean dwell time: {stats['mean_seconds']}s")
print(f"P95 dwell time: {stats['p95_seconds']}s")
print(f"Max dwell time: {stats['max_seconds']}s")
print(f"Outliers detected: {stats['outlier_count']}")
elif analyzer == "parameter-entropy":
result = parameter_entropy(task_events, result_events, analyzer_context)
result = _merge_common_metadata(result, analyzer_metadata)
out_path = out_dir / "parameter_entropy.json"
out_path.parent.mkdir(parents=True, exist_ok=True)
with out_path.open("w", encoding="utf-8") as f:
json.dump(result, f, indent=2, ensure_ascii=False)
print(f"Wrote: {out_path}")
summary = result["summary"]
print(f"Total findings: {summary['total_findings']}")
print(f"Tasks with findings: {summary['tasks_with_findings']}")
for ftype, count in summary.get("by_type", {}).items():
print(f" {ftype}: {count}")
if summary.get("repeated_high_entropy_tokens"):
print(f"Repeated high-entropy tokens: {summary['repeated_high_entropy_tokens']}")
elif analyzer == "argument-position-profile":
result = argument_position_profile(task_events, result_events, analyzer_context)
result = _merge_common_metadata(result, analyzer_metadata)
out_path = out_dir / "argument_position_profile.json"
out_path.parent.mkdir(parents=True, exist_ok=True)
with out_path.open("w", encoding="utf-8") as f:
json.dump(result, f, indent=2, ensure_ascii=False)
print(f"Wrote: {out_path}")
summary = result["summary"]
print(f"Commands profiled: {summary['commands_profiled']}")
print(f"Max argument depth: {summary['max_depth_observed']}")
print(f"Positions profiled: {summary['positions_profiled']}")
print(f"Findings: {summary['total_findings']}")
for ftype, count in summary.get("findings_by_type", {}).items():
print(f" {ftype}: {count}")
elif analyzer == "tool-dump":
result = tool_dump(task_events, result_events, analyzer_context)
result = _merge_common_metadata(result, analyzer_metadata)
out_path = out_dir / "tool_dump.json"
out_path.parent.mkdir(parents=True, exist_ok=True)
with out_path.open("w", encoding="utf-8") as f:
json.dump(result, f, indent=2, ensure_ascii=False)
print(f"Wrote: {out_path}")
summary = result["summary"]
print(f"Groups defined: {summary['groups_defined']}")
print(f"Groups with matches: {summary['groups_with_matches']}")
print(f"Total matches: {summary['total_matches']}")
for group in result.get("groups", []):
if group.get("match_count", 0) == 0:
continue
dump_path = group.get("dump_path") or "<not written>"
print(f" {group['name']}: {group['match_count']} match(es) -> {dump_path}")
else:
print(f"error: unknown analyzer: {analyzer}", file=sys.stderr)
return 1
return 0
def run_analyze_all(
events_path: Path,
out_dir: Path,
analysis_timestamp: str | None = None,
) -> int:
"""Run all analyzers against an existing events.ndjson file."""
for analyzer_name in ALL_ANALYZERS:
print(f"\nRunning analyzer: {analyzer_name}")
rc = run_analyze(
analyzer=analyzer_name,
events_path=events_path,
out_dir=out_dir,
analysis_timestamp=analysis_timestamp,
)
if rc != 0:
return rc
return 0
def run_partial_load(
partial_json_path: Path,
operation_id: int | None,
operation_name: str | None,
out_dir: Path,
no_versioning: bool = False,
run_analyzers: bool = True,
config: dict | None = None,
output_rule_cli: str | None = None,
arguments_rule_cli: str | None = None,
) -> int:
"""Load partial Mythic JSON (incomplete GraphQL pulls), normalize, run analyzers, and generate HTML report."""
if not partial_json_path.exists():
print(f"error: JSON file not found: {partial_json_path}", file=sys.stderr)
return 1
print(f"Loading partial Mythic data from: {partial_json_path}")
# Load and normalize partial data
task_events, result_events, metadata = load_partial_mythic_json(
partial_json_path,
operation_id=operation_id,
operation_name=operation_name,
)
policy = resolve_retention_policy(config or {}, output_rule_cli, arguments_rule_cli)
apply_retention_policy(task_events, result_events, policy)
metadata = dict(metadata)
metadata["output_rule"] = policy.output_rule
metadata["arguments_rule"] = policy.arguments_rule
operation_id = metadata["operation_id"]
operation_name = metadata["operation_name"]
op_slug = metadata["operation_slug"]
print(f"Operation: {operation_name} (ID: {operation_id}, slug: {op_slug})")
print(f"Tasks loaded: {metadata['task_count']}")
print(f"Results loaded: {metadata['result_count']}")
status_counts = metadata["status_counts"]
print(f"Status: success={status_counts['success']}, error={status_counts['error']}, unknown={status_counts['unknown']}")
# Generate analysis timestamp and versioned directory
analysis_timestamp = datetime.now(timezone.utc)