Repository navigation
Expand file tree
/
Copy pathagent.py
More file actions
1703 lines (1455 loc) · 77.1 KB
/
Copy pathagent.py
File metadata and controls
1703 lines (1455 loc) · 77.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
# File: agent.py
# BinCodeQL — Datalog-powered binary analysis co-pilot
# Interactive agent with Binary Ninja MCP + Souffle Datalog tools
import os
import sys
import asyncio
import subprocess
import tempfile
import json
from pathlib import Path
from typing import Optional
# Ensure sibling-module imports work whether this file is loaded as a
# package submodule (ADK's `from . import agent`) or run as a script
# (`python agent.py`). Without this, `import pipeline` / `import
# agent_factory` fail under ADK's package loader because bin_datalog/
# is not automatically on sys.path.
_PKG_DIR = Path(__file__).parent.resolve()
if str(_PKG_DIR) not in sys.path:
sys.path.insert(0, str(_PKG_DIR))
from dotenv import load_dotenv # noqa: E402
from google.adk.agents import LlmAgent # noqa: E402
from google.adk.tools.mcp_tool.mcp_toolset import MCPToolset, StdioConnectionParams, StdioServerParameters # noqa: E402
from google.adk.tools import FunctionTool # noqa: E402
from google.adk.models.lite_llm import LiteLlm # noqa: E402
import pipeline # noqa: E402
from agent_factory import create_model # noqa: E402
load_dotenv(_PKG_DIR / ".env", override=True)
# =============================================================================
# Configuration
# =============================================================================
MCP_PYTHON_PATH = os.getenv("MCP_PYTHON_PATH", "python3")
MCP_BRIDGE_PATH = os.getenv("MCP_BRIDGE_PATH", "")
BNDB_PATH = os.getenv("BNDB_PATH", "")
PROJECT_DIR = Path(__file__).parent
RULES_DIR = PROJECT_DIR / "rules"
FACTS_DIR = PROJECT_DIR / "facts"
OUTPUT_DIR = PROJECT_DIR / "output"
# Souffle execution knobs. `-j` adds multi-core parallelism to the Datalog
# evaluator (helps most on transitive-closure-heavy rules like bn_flow.dl
# and interproc.dl). `-c` compiles to C++ and then executes — much faster
# for large fact sets but adds ~1-2min compile overhead on the first run
# per rule file. Cached compilation output lives under TMPDIR.
SOUFFLE_JOBS = os.getenv("SOUFFLE_JOBS", "auto")
SOUFFLE_COMPILE = os.getenv("SOUFFLE_COMPILE", "0") not in ("0", "", "false", "False")
def _souffle_cmd(rule_path: str, facts_dir: str, output_dir: str) -> list:
"""Build the souffle subprocess argv with current knobs applied.
Thin wrapper over `pipeline.souffle_cmd` that injects the project's
env-var-driven knobs (SOUFFLE_JOBS / SOUFFLE_COMPILE).
"""
return pipeline.souffle_cmd(
rule_path, facts_dir, output_dir,
jobs=SOUFFLE_JOBS, compile_mode=SOUFFLE_COMPILE,
)
# Model configuration + factory live in agent_factory.py so the
# triage agent (scan mode) and any future agent entry-point share the
# same prompt-caching / retry / extended-thinking behavior.
# `create_model()` is imported above.
def create_mcp_toolset():
if not MCP_BRIDGE_PATH:
raise ValueError(
"MCP_BRIDGE_PATH not set. Add it to .env (see .env.example)."
)
return MCPToolset(
connection_params=StdioConnectionParams(
server_params=StdioServerParameters(
command=MCP_PYTHON_PATH,
args=[MCP_BRIDGE_PATH],
)
)
)
# =============================================================================
# Tool: Clean workspace (remove stale facts and output files)
# =============================================================================
def tool_clean_workspace(
clean_facts: bool = True,
clean_output: bool = True,
) -> dict:
"""Remove stale .facts and .csv files to start a fresh analysis.
Call this before beginning a new analysis session to ensure no stale
data from previous runs contaminates results.
Args:
clean_facts: If True, remove all .facts files from facts/ dir.
clean_output: If True, remove all .csv files from output/ dir.
Returns:
Dict with counts of removed files.
"""
removed = {"facts": 0, "output": 0}
if clean_facts:
for f in FACTS_DIR.glob("*.facts"):
f.unlink()
removed["facts"] += 1
if clean_output:
for f in OUTPUT_DIR.glob("*.csv"):
f.unlink()
removed["output"] += 1
return removed
# =============================================================================
# Tool: Extract MLIL-SSA facts from a function
# =============================================================================
def tool_extract_facts(
function_name: str,
mlil_ssa_text: str,
append: bool = True,
facts_dir: str = "",
) -> dict:
"""Extract Datalog facts from MLIL-SSA text for a function.
Call this AFTER using the BN MCP tool `get_il(function_name, "mlil", ssa=True)`
to obtain the MLIL-SSA text. This tool parses that text into Souffle-compatible
fact files (Def, Use, Call, ActualArg, PhiSource, FormalParam, etc.).
By default, successive calls ACCUMULATE facts (append=True). Call
`tool_clean_workspace` first to start fresh, then call this for each
function to build up the fact database incrementally.
Args:
function_name: Name of the function being parsed.
mlil_ssa_text: Raw MLIL-SSA text from Binary Ninja.
append: If True (default), merge new facts with existing .facts files
(deduplicated). If False, overwrite files.
facts_dir: Directory to write .facts files. Defaults to project facts/ dir.
Returns:
Dict with parse stats: fact counts per relation, any unparsed lines,
and `unresolved_callees` — list of hex-address callees that need
resolution via `function_at` + `tool_resolve_calls`.
"""
import sys
sys.path.insert(0, str(PROJECT_DIR))
from mlil_parser import parse_mlil_ssa, FactKind
from fact_writer import write_facts
target_dir = Path(facts_dir) if facts_dir else FACTS_DIR
target_dir.mkdir(parents=True, exist_ok=True)
facts = parse_mlil_ssa(function_name, mlil_ssa_text)
# Check for unparsed lines by re-running and capturing stderr
import io
old_stdout = sys.stdout
sys.stdout = capture = io.StringIO()
_ = parse_mlil_ssa(function_name, mlil_ssa_text)
sys.stdout = old_stdout
unparsed = [l for l in capture.getvalue().split('\n') if 'UNPARSED' in l]
stats = write_facts(facts, target_dir, append=append)
# Scan for unresolved hex-address callees
unresolved = sorted(set(
f.fields["callee"]
for f in facts
if f.kind == FactKind.CALL and f.fields["callee"].startswith("0x")
))
return {
"function": function_name,
"total_facts": len(facts),
"relations": {k: v for k, v in sorted(stats.items())},
"unparsed_lines": len(unparsed),
"unparsed_samples": unparsed[:5] if unparsed else [],
"facts_dir": str(target_dir),
"unresolved_callees": unresolved,
}
# =============================================================================
# Tool: Resolve hex call targets to function names
# =============================================================================
def tool_resolve_calls(
address_map: dict,
facts_dir: str = "",
) -> dict:
"""Resolve hex-address callees in Call.facts to function names.
After extracting facts, Call.facts may contain hex addresses (e.g., "0x436600")
instead of function names. Use the BN MCP `function_at` tool to discover what
function lives at each address, then call this tool with the mapping.
Args:
address_map: Dict mapping hex addresses to function names,
e.g. {"0x436600": "memcpy", "0x41a2f0": "png_crc_read"}.
facts_dir: Directory containing .facts files. Defaults to project facts/ dir.
Returns:
Dict with resolution stats.
"""
import sys
sys.path.insert(0, str(PROJECT_DIR))
from resolve_calls import resolve_call_targets
target_dir = str(Path(facts_dir) if facts_dir else FACTS_DIR)
import io
old_stdout = sys.stdout
sys.stdout = capture = io.StringIO()
resolve_call_targets(target_dir, address_map)
sys.stdout = old_stdout
return {"result": capture.getvalue().strip(), "facts_dir": target_dir}
# =============================================================================
# Tool: Run Souffle Datalog query
# =============================================================================
def tool_run_souffle(
rule_file: str = "",
custom_rules: str = "",
facts_dir: str = "",
output_dir: str = "",
timeout_seconds: int = 30,
) -> dict:
"""Run a Souffle Datalog query against extracted facts.
You can either:
1. Run an existing rule file from the rules/ directory (e.g. "interproc.dl")
2. Provide custom Datalog rules as a string (written to a temp file and run)
The query reads .facts files from facts_dir and writes results to output_dir.
Args:
rule_file: Name of a rule file in rules/ dir (e.g., "interproc.dl", "taint.dl").
Ignored if custom_rules is provided.
custom_rules: Custom Souffle Datalog program as a string. If provided,
this is written to a temp file and executed instead of rule_file.
facts_dir: Directory containing .facts input files.
output_dir: Directory for output CSV files.
timeout_seconds: Max execution time (default 30s).
Returns:
Dict with stdout, stderr, return code, and list of output files with contents.
"""
fdir = str(Path(facts_dir) if facts_dir else FACTS_DIR)
odir = str(Path(output_dir) if output_dir else OUTPUT_DIR)
Path(odir).mkdir(parents=True, exist_ok=True)
# Clear stale output CSVs before running to avoid mixing old/new results
for stale in Path(odir).glob("*.csv"):
stale.unlink()
# Determine the .dl file to run
if custom_rules:
tmp = tempfile.NamedTemporaryFile(mode='w', suffix='.dl', delete=False,
dir=str(PROJECT_DIR))
tmp.write(custom_rules)
tmp.close()
dl_path = tmp.name
elif rule_file:
dl_path = str(RULES_DIR / rule_file)
if not Path(dl_path).exists():
return {"error": f"Rule file not found: {dl_path}"}
else:
return {"error": "Provide either rule_file or custom_rules"}
try:
result = subprocess.run(
_souffle_cmd(dl_path, fdir, odir),
capture_output=True, text=True, timeout=timeout_seconds,
)
# Collect output files
outputs = {}
for f in sorted(Path(odir).glob("*.csv")):
content = f.read_text().strip()
if content:
lines = content.split('\n')
outputs[f.name] = {
"rows": len(lines),
"preview": lines[:20], # first 20 rows
}
return {
"return_code": result.returncode,
"stdout": result.stdout.strip() if result.stdout else "",
"stderr": result.stderr.strip() if result.stderr else "",
"output_files": outputs,
"rule_file": dl_path,
}
except subprocess.TimeoutExpired:
return {"error": f"Souffle timed out after {timeout_seconds}s"}
finally:
if custom_rules:
Path(dl_path).unlink(missing_ok=True)
# =============================================================================
# Tool: List available rule files and fact files
# =============================================================================
def tool_list_datalog_files() -> dict:
"""List available Datalog rule files and fact files.
Returns the rule files in rules/ and fact files in facts/ with their sizes
and column schemas, so you know what's available to query.
"""
import sys
sys.path.insert(0, str(PROJECT_DIR))
from fact_writer import SCHEMA_DOCS
from mlil_parser import FactKind
# Build filename→columns lookup from SCHEMA_DOCS
from fact_writer import RELATION_SCHEMA
file_columns = {}
for kind, cols in SCHEMA_DOCS.items():
schema = RELATION_SCHEMA.get(kind)
if schema:
file_columns[schema[0]] = cols
rules = []
for f in sorted(RULES_DIR.glob("*.dl")):
rules.append({"name": f.name, "size_bytes": f.stat().st_size})
facts = []
for f in sorted(FACTS_DIR.glob("*.facts")):
lines = f.read_text().strip().count('\n') + 1 if f.stat().st_size > 0 else 0
entry = {"name": f.name, "rows": lines}
if f.name in file_columns:
entry["columns"] = file_columns[f.name]
facts.append(entry)
return {"rules": rules, "facts": facts}
# =============================================================================
# Tool: Read a rule or output file
# =============================================================================
def tool_read_file(file_path: str, max_bytes: int = 200_000) -> dict:
"""Read any text file on disk — rules, facts, CSV outputs, prior
reports, decompilation scratchpads, READMEs, third-party advisory
notes, etc.
Use this whenever the user references prior work ("the report we
wrote last week", "the LibXML2 advisory in docs/"), points at a
GitLab/CVE writeup pasted into the repo, or otherwise asks you to
build on something already on disk. Reading a prior report first
avoids redoing the discovery+extraction phase from scratch — pull
out the cited functions, addresses, and verdicts, then run only
the additional facts/queries the follow-up question needs.
Args:
file_path: Project-relative path (e.g., "rules/interproc.dl",
"output/TaintedSink.csv", "facts/Call.facts",
"reports/<old_report>.md", "docs/foo.md") or an absolute
path anywhere on disk.
max_bytes: Truncation guard. Files larger than this are read
up to the cap and `truncated: true` is set in the result;
ask the user (or call again with a higher cap) if you
need the rest. Default 200 KB — big enough for any single
report or rule file, small enough to keep the context
window healthy.
"""
p = Path(file_path)
if not p.is_absolute():
p = PROJECT_DIR / p
if not p.exists():
return {"error": f"File not found: {p}"}
size = p.stat().st_size
truncated = size > max_bytes
with p.open("r", encoding="utf-8", errors="replace") as fh:
content = fh.read(max_bytes)
return {
"path": str(p),
"size_bytes": size,
"bytes_read": len(content.encode("utf-8")),
"truncated": truncated,
"content": content,
}
def tool_list_reports(
name_filter: str = "",
reports_dir: str = "",
limit: int = 50,
) -> dict:
"""List prior analysis reports under `reports/` (newest first).
Use this when the user mentions a prior analysis without giving
the exact filename ("the FFmpeg sentinel report", "what did we
say about libxml2 last month?"). Pick the most likely match by
title/timestamp, then `tool_read_file` to load it.
Args:
name_filter: Optional substring filter on the filename
(case-insensitive). E.g. "ffmpeg" or "sentinel".
reports_dir: Optional override directory. Defaults to the
repo's `reports/`.
limit: Maximum number of entries to return (newest first).
Returns:
Dict with `reports`: list of {filename, path, size_bytes,
mtime_iso} sorted newest first, plus `count` and `dir`.
"""
from datetime import datetime, timezone
target_dir = Path(reports_dir) if reports_dir else REPORTS_DIR
if not target_dir.exists():
return {"reports": [], "count": 0, "dir": str(target_dir),
"note": "reports directory does not exist yet"}
needle = name_filter.lower().strip()
entries = []
for p in target_dir.iterdir():
if not p.is_file():
continue
if needle and needle not in p.name.lower():
continue
st = p.stat()
entries.append({
"filename": p.name,
"path": str(p),
"size_bytes": st.st_size,
"mtime_iso": datetime.fromtimestamp(
st.st_mtime, tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
"_mtime": st.st_mtime,
})
entries.sort(key=lambda x: x["_mtime"], reverse=True)
for e in entries:
e.pop("_mtime", None)
return {
"reports": entries[:limit],
"count": len(entries),
"dir": str(target_dir),
"filter": name_filter,
}
# =============================================================================
# Tool: Generate TaintTransfer.facts from signatures
# =============================================================================
def tool_generate_signatures(
extra_signatures: list[dict] = None,
) -> dict:
"""Generate TaintTransfer.facts from the signatures rule file.
Runs rules/signatures.dl to produce TaintTransfer.csv, then copies it
to facts/TaintTransfer.facts so interproc.dl can use it.
Optionally add extra signatures (e.g., for newly discovered library functions).
Args:
extra_signatures: Optional list of dicts with keys:
func (str), out_arg (str), in_arg (str).
Example: [{"func": "png_crc_read", "out_arg": "arg1", "in_arg": "external"}]
Returns:
Dict with the number of TaintTransfer facts generated.
"""
# If extra signatures provided, append to a temp copy of signatures.dl
sig_file = RULES_DIR / "signatures.dl"
dl_content = sig_file.read_text()
if extra_signatures:
# Insert before the .output line
extra_lines = []
for sig in extra_signatures:
extra_lines.append(
f'TaintTransfer("{sig["func"]}", "{sig["out_arg"]}", "{sig["in_arg"]}").'
)
dl_content = dl_content.replace(
'.output TaintTransfer',
'\n'.join(extra_lines) + '\n.output TaintTransfer'
)
# Write temp file and run
tmp = tempfile.NamedTemporaryFile(mode='w', suffix='.dl', delete=False)
tmp.write(dl_content)
tmp.close()
try:
result = subprocess.run(
_souffle_cmd(tmp.name, str(FACTS_DIR), str(OUTPUT_DIR)),
capture_output=True, text=True, timeout=15,
)
if result.returncode != 0:
return {"error": result.stderr}
# Copy output to facts dir
result_info = {}
src = OUTPUT_DIR / "TaintTransfer.csv"
dst = FACTS_DIR / "TaintTransfer.facts"
if src.exists():
dst.write_text(src.read_text())
content = src.read_text().strip()
rows = content.count('\n') + 1 if content else 0
result_info["taint_transfer_facts"] = rows
result_info["taint_transfer_path"] = str(dst)
else:
return {"error": "TaintTransfer.csv not generated"}
# Also copy BufferWriteSource if produced
bws_src = OUTPUT_DIR / "BufferWriteSource.csv"
bws_dst = FACTS_DIR / "BufferWriteSource.facts"
if bws_src.exists():
bws_dst.write_text(bws_src.read_text())
content = bws_src.read_text().strip()
bws_rows = content.count('\n') + 1 if content else 0
result_info["buffer_write_source_facts"] = bws_rows
result_info["buffer_write_source_path"] = str(bws_dst)
# Also copy TaintKill if produced
tk_src = OUTPUT_DIR / "TaintKill.csv"
tk_dst = FACTS_DIR / "TaintKill.facts"
if tk_src.exists():
tk_dst.write_text(tk_src.read_text())
content = tk_src.read_text().strip()
tk_rows = content.count('\n') + 1 if content else 0
result_info["taint_kill_facts"] = tk_rows
result_info["taint_kill_path"] = str(tk_dst)
return result_info
finally:
Path(tmp.name).unlink(missing_ok=True)
# =============================================================================
# Tool: Generate source/sink annotation fact files
# =============================================================================
# Built-in catalogs for dangerous sinks and taint source functions
_BUILTIN_SINKS = [
("memcpy", 0, "buffer_overflow_dst"),
("memcpy", 2, "buffer_overflow_size"),
("memmove", 0, "buffer_overflow_dst"),
("memmove", 2, "buffer_overflow_size"),
("strcpy", 0, "buffer_overflow_dst"),
("strncpy", 0, "buffer_overflow_dst"),
("strcat", 0, "buffer_overflow_dst"),
("sprintf", 0, "format_buffer_overflow"),
("snprintf", 0, "format_buffer_overflow"),
("system", 0, "command_injection"),
("execve", 0, "command_injection"),
("free", 0, "double_free"),
]
_BUILTIN_SOURCES = [
("read", "external"),
("recv", "external"),
("recvfrom", "external"),
("fread", "external"),
("fgets", "external"),
("gets", "external"),
("getenv", "external"),
("getline", "external"),
("scanf", "external"),
("recvmsg", "external"),
]
# =============================================================================
# Tool: Batch extract facts via headless Binary Ninja
# =============================================================================
def tool_extract_facts_batch(
binary_path: str,
function_names: list[str] = None,
extract_all: bool = False,
) -> dict:
"""Extract Datalog facts from a binary or .bndb database using Binary Ninja.
Accepts either a raw binary (ELF/PE/Mach-O) or a pre-analyzed .bndb
database. Using .bndb is significantly faster — BN skips analysis and
loads pre-computed MLIL-SSA directly.
One call replaces the multi-step MCP extraction workflow (get_il → parse →
write facts). Runs a headless BN subprocess that walks MLIL-SSA objects
directly, producing .facts files including StackVar.
Use this for batch extraction of multiple functions. For incremental,
interactive exploration, continue using `tool_extract_facts` with MCP.
Requires: BN_PYTHON or BN_PYTHON_PATH env var set, or BN on system path.
Args:
binary_path: Path to the binary or .bndb file to analyze.
function_names: List of function names to extract.
extract_all: If True, extract ALL functions (ignores function_names).
Returns:
Dict with extraction summary or error.
"""
if not binary_path and BNDB_PATH:
binary_path = BNDB_PATH
import sys
sys.path.insert(0, str(PROJECT_DIR))
from bn_utils import extract_facts_batch
return extract_facts_batch(binary_path, function_names, str(FACTS_DIR), extract_all)
# =============================================================================
# Tool: Find functions with loops (BOIL pre-filter)
# =============================================================================
def tool_find_loop_functions(
binary_path: str = "",
min_blocks: int = 2,
) -> dict:
"""Find all functions containing loops (back-edges) in a binary.
This is a lightweight pre-filter for BOIL analysis. Scanning for back-edges
is much faster than full fact extraction — use this first to identify
loop-containing functions, then extract facts only for those functions
before running boil.dl.
Typical workflow for BOIL analysis on large binaries:
1. tool_find_loop_functions(binary_path) → get list of loop functions
2. tool_extract_facts_batch(binary_path, function_names=loop_funcs)
3. tool_run_souffle(rule_file="boil.dl")
Requires: BN_PYTHON or BN_PYTHON_PATH env var set, or BN on system path.
Args:
binary_path: Path to binary or .bndb database. Falls back to BNDB_PATH env var.
min_blocks: Minimum basic blocks to consider (default: 2, skips trivial stubs).
Returns:
Dict with total_functions, loop_functions count, and list of function info
(name, addr, blocks, loops) for each loop-containing function.
"""
if not binary_path and BNDB_PATH:
binary_path = BNDB_PATH
if not binary_path:
return {"error": "No binary_path provided and BNDB_PATH not set"}
import sys
sys.path.insert(0, str(PROJECT_DIR))
from bn_utils import find_loop_functions
return find_loop_functions(binary_path, min_blocks=min_blocks)
def tool_generate_annotations(
extra_sources: list[dict] = None,
extra_sinks: list[dict] = None,
facts_dir: str = "",
) -> dict:
"""Generate DangerousSink.facts and TaintSourceFunc.facts from built-in catalogs.
These fact files are loaded by interproc.dl via `.input` directives instead
of being hardcoded in the rule file. You can extend the catalogs with
extra entries for binary-specific functions.
Args:
extra_sources: Optional list of dicts with keys:
func (str), category (str, e.g. "external").
Example: [{"func": "png_read_data", "category": "external"}]
extra_sinks: Optional list of dicts with keys:
func (str), arg_idx (int), risk (str).
Example: [{"func": "png_crc_read", "arg_idx": 1, "risk": "buffer_overflow"}]
facts_dir: Directory for .facts files. Defaults to project facts/ dir.
Returns:
Dict with counts of sink and source facts written.
"""
target_dir = Path(facts_dir) if facts_dir else FACTS_DIR
target_dir.mkdir(parents=True, exist_ok=True)
# Sinks
sink_rows = set()
for func, idx, risk in _BUILTIN_SINKS:
sink_rows.add((func, str(idx), risk))
if extra_sinks:
for s in extra_sinks:
sink_rows.add((s["func"], str(s["arg_idx"]), s["risk"]))
sorted_sinks = sorted(sink_rows)
sink_path = target_dir / "DangerousSink.facts"
with open(sink_path, 'w') as fp:
for row in sorted_sinks:
fp.write('\t'.join(row) + '\n')
# Sources
source_rows = set()
for func, cat in _BUILTIN_SOURCES:
source_rows.add((func, cat))
if extra_sources:
for s in extra_sources:
source_rows.add((s["func"], s["category"]))
sorted_sources = sorted(source_rows)
source_path = target_dir / "TaintSourceFunc.facts"
with open(source_path, 'w') as fp:
for row in sorted_sources:
fp.write('\t'.join(row) + '\n')
return {
"sinks": len(sorted_sinks),
"sources": len(sorted_sources),
"sink_path": str(sink_path),
"source_path": str(source_path),
}
# =============================================================================
# Session token-usage accumulator
# =============================================================================
# Updated by `_record_usage` (registered as the LlmAgent's after_model
# callback). Read by `tool_session_usage` and embedded in every report
# so analyses carry their own cost ledger.
_USAGE_TOTALS: dict = {
"turns": 0,
"prompt_tokens": 0,
"candidates_tokens": 0, # output tokens
"thoughts_tokens": 0, # extended-thinking tokens (Anthropic)
"cached_tokens": 0, # cache-read tokens (Anthropic prompt cache)
"tool_use_prompt_tokens": 0,
"total_tokens": 0,
}
def _record_usage(callback_context, llm_response) -> None:
"""ADK after_model_callback — accumulate per-turn token usage."""
um = getattr(llm_response, "usage_metadata", None)
if um is None:
return
_USAGE_TOTALS["turns"] += 1
for src, dst in (
("prompt_token_count", "prompt_tokens"),
("candidates_token_count", "candidates_tokens"),
("thoughts_token_count", "thoughts_tokens"),
("cached_content_token_count", "cached_tokens"),
("tool_use_prompt_token_count", "tool_use_prompt_tokens"),
("total_token_count", "total_tokens"),
):
v = getattr(um, src, None)
if v:
_USAGE_TOTALS[dst] += int(v)
def tool_session_usage(reset: bool = False) -> dict:
"""Return cumulative LLM token usage for the current session.
The agent SHOULD call this near the end of any non-trivial analysis
and pass the result into `tool_write_analysis_report` (or rely on
that tool's auto-embed of the same numbers). Use `reset=True` to
clear counters at the start of a fresh analysis.
Returned keys:
turns — number of model calls
prompt_tokens — input tokens billed
candidates_tokens — output tokens billed
thoughts_tokens — extended-thinking tokens (anthropic/*)
cached_tokens — cache-read tokens (anthropic prompt cache)
tool_use_prompt_tokens — tokens charged for tool-use scaffolding
total_tokens — provider-reported total
"""
snapshot = dict(_USAGE_TOTALS)
if reset:
for k in _USAGE_TOTALS:
_USAGE_TOTALS[k] = 0
return snapshot
# =============================================================================
# Tool: Write analysis report to reports/
# =============================================================================
REPORTS_DIR = PROJECT_DIR / "reports"
_SEVERITY_BADGES = {
"high": "[HIGH]",
"medium": "[MEDIUM]",
"low": "[LOW]",
"info": "[INFO]",
}
_STATUS_BADGES = {
"confirmed": "confirmed",
"likely": "likely",
"plausible-unverified": "plausible-unverified",
"inconclusive": "inconclusive",
"refuted": "refuted",
"no_candidates": "no_candidates",
}
def _slugify(text: str) -> str:
import re
slug = re.sub(r"[^a-zA-Z0-9_-]+", "_", text).strip("_").lower()
return slug[:60] if len(slug) > 60 else slug
def tool_write_analysis_report(
title: str,
binary: str,
findings: list[dict] = None,
hypotheses: list[dict] = None,
status: str = "",
raw_markdown: str = "",
filename: str = "",
reports_dir: str = "",
) -> dict:
"""Persist an analysis report to the reports/ directory.
Call this at the end of any non-trivial analysis session, AND whenever
you conclude "not detected" / "inconclusive" so the hypothesis trace
survives. The hybrid LLM+Datalog contract requires that reasoning
(not just rule output) is preserved.
Args:
title: Short report title, e.g. "FFmpeg H.264 slice_table review".
binary: Absolute or relative path to the binary analyzed.
findings: List of finding dicts. Each should carry:
- severity: "high" | "medium" | "low" | "info"
- category: short tag (e.g. "sentinel_collision",
"tainted_counter_as_index")
- function: function name (optional)
- addr: hex or int address (optional)
- evidence: list[str] — each cites a CSV row, fact, or MCP
lookup. REQUIRED — findings without evidence
will be flagged in the output.
- reasoning: one-paragraph explanation tying the facts to
the exploitability claim.
- confidence: "confirmed" | "likely" | "plausible-unverified"
hypotheses: List of hypothesis dicts from the reflective loop:
- name: e.g. "sentinel collision at slice_table"
- verdict: "confirmed" | "likely" | "plausible-unverified"
| "refuted"
- facts_checked: list[str] — specific CSV/fact rows examined.
- mcp_checked: list[str] — MCP calls made (e.g.
"decompile_function(h264_init)").
- note: one-line reasoning.
status: Overall session verdict. Use "confirmed" when findings were
proven exploitable; "inconclusive" when rules missed and
reflective anomalies remain; "refuted" when the reported bug
class was actively disproven; "no_candidates" only when no
interesting sinks/loops exist at all. Empty string → omitted.
raw_markdown: Optional free-form narrative appended at the end —
use for multi-paragraph reasoning or code snippets that don't
fit the structured schema.
filename: Optional override. Defaults to
reports/<slug(title)>_<YYYYMMDD_HHMMSS>.md.
reports_dir: Optional override directory. Defaults to the repo's
reports/ (gitignored).
Returns:
Dict with file path, bytes written, finding count, hypothesis count.
"""
from datetime import datetime
findings = findings or []
hypotheses = hypotheses or []
target_dir = Path(reports_dir) if reports_dir else REPORTS_DIR
target_dir.mkdir(parents=True, exist_ok=True)
now = datetime.utcnow()
ts_iso = now.strftime("%Y-%m-%dT%H:%M:%SZ")
ts_file = now.strftime("%Y%m%d_%H%M%S")
if filename:
fname = filename if filename.endswith(".md") else filename + ".md"
else:
fname = f"{_slugify(title) or 'analysis'}_{ts_file}.md"
out_path = target_dir / fname
lines: list[str] = []
lines.append(f"# {title}\n")
lines.append("## Metadata\n")
lines.append(f"- **binary:** `{binary}`")
lines.append(f"- **timestamp:** {ts_iso}")
if status:
badge = _STATUS_BADGES.get(status, status)
lines.append(f"- **status:** {badge}")
lines.append(f"- **finding_count:** {len(findings)}")
lines.append(f"- **hypothesis_count:** {len(hypotheses)}")
lines.append("")
# Findings grouped by severity (high → medium → low → info → other)
if findings:
lines.append("## Findings\n")
order = ["high", "medium", "low", "info"]
bucketed: dict[str, list[dict]] = {}
for f in findings:
sev = str(f.get("severity", "info")).lower()
bucketed.setdefault(sev, []).append(f)
# Stable order, with unknown severities last
sev_keys = [s for s in order if s in bucketed] + [
s for s in bucketed if s not in order
]
for sev in sev_keys:
badge = _SEVERITY_BADGES.get(sev, sev.upper())
lines.append(f"### {badge}\n")
for f in bucketed[sev]:
cat = f.get("category", "uncategorized")
func = f.get("function", "")
addr = f.get("addr", "")
header_bits = [f"**{cat}**"]
if func:
header_bits.append(f"`{func}`")
if addr not in (None, ""):
addr_str = hex(addr) if isinstance(addr, int) else str(addr)
header_bits.append(f"@ {addr_str}")
lines.append("#### " + " ".join(header_bits))
evidence = f.get("evidence") or []
if not evidence:
lines.append("- _⚠️ no evidence cited — please add fact/CSV/MCP references_")
else:
lines.append("**Evidence:**")
for e in evidence:
lines.append(f"- {e}")
reasoning = f.get("reasoning", "").strip()
if reasoning:
lines.append("")
lines.append(f"**Reasoning:** {reasoning}")
conf = f.get("confidence", "")
if conf:
badge_c = _STATUS_BADGES.get(conf, conf)
lines.append(f"**Confidence:** {badge_c}")
lines.append("")
# Hypotheses table
if hypotheses:
lines.append("## Hypotheses considered\n")
lines.append("| # | Hypothesis | Verdict | Facts checked | MCP checked | Note |")
lines.append("|---|---|---|---|---|---|")
for i, h in enumerate(hypotheses, 1):
name = h.get("name", "(unnamed)")
verdict = h.get("verdict", "")
badge_v = _STATUS_BADGES.get(verdict, verdict)
facts = ", ".join(h.get("facts_checked") or []) or "—"
mcp = ", ".join(h.get("mcp_checked") or []) or "—"
note = (h.get("note") or "").replace("|", "\\|")
lines.append(
f"| {i} | {name} | {badge_v} | {facts} | {mcp} | {note} |"
)
lines.append("")
if raw_markdown:
lines.append("## Notes\n")
lines.append(raw_markdown.rstrip())
lines.append("")
# Auto-embed session token usage so each report carries its own cost
# ledger. Numbers come from the after_model_callback accumulator.
usage = dict(_USAGE_TOTALS)
if usage.get("turns", 0) > 0:
lines.append("## Token usage\n")
lines.append(f"- **turns:** {usage['turns']}")
lines.append(f"- **prompt_tokens:** {usage['prompt_tokens']:,}")
lines.append(f"- **candidates_tokens:** {usage['candidates_tokens']:,}")
if usage.get("thoughts_tokens"):
lines.append(f"- **thoughts_tokens:** {usage['thoughts_tokens']:,}")
if usage.get("cached_tokens"):
lines.append(f"- **cached_tokens:** {usage['cached_tokens']:,}")
if usage.get("tool_use_prompt_tokens"):
lines.append(
f"- **tool_use_prompt_tokens:** {usage['tool_use_prompt_tokens']:,}"
)
lines.append(f"- **total_tokens:** {usage['total_tokens']:,}")
lines.append("")
content = "\n".join(lines)
out_path.write_text(content, encoding="utf-8")
return {
"path": str(out_path),
"bytes": len(content.encode("utf-8")),
"finding_count": len(findings),
"hypothesis_count": len(hypotheses),
"status": status,
}
# =============================================================================
# Tool: Set entry-point taint (attack surface specification)
# =============================================================================
def tool_set_entry_taint(
entries: list[dict],
facts_dir: str = "",
) -> dict:
"""Specify which exported API parameters are attacker-controlled.
For library analysis where there are no calls to read()/recv() — the
library's exported API IS the attack surface. Mark params as tainted
and interproc.dl will seed TaintedVar from them.
Args:
entries: List of dicts with keys:
func (str): Function name (e.g., "parse_image")
param_idx (int): 0-based parameter index (e.g., 1 for arg2)