1#![deny(clippy::indexing_slicing, clippy::string_slice)]
59
60#[allow(clippy::indexing_slicing)]
64pub mod confine;
65
66pub mod audit;
67pub mod cache;
68pub mod checksec;
69pub mod cursor;
70pub mod find;
71pub mod guard;
72pub mod logging;
73pub mod pattern;
74pub mod resources;
75pub mod scan;
76pub mod schema;
77pub mod semantics;
78pub mod stats;
79
80use std::path::PathBuf;
81use std::sync::Arc;
82use std::time::{Duration, Instant};
83
84use rf_cache::{CachedGadget, CachedScan};
85
86use rmcp::handler::server::wrapper::Parameters;
87use rmcp::model::{CallToolResult, ContentBlock};
88use rmcp::service::RequestContext;
89use rmcp::{tool, tool_handler, tool_router, ErrorData as McpError, RoleServer, ServerHandler};
90use schemars::JsonSchema;
91use serde::{Deserialize, Serialize};
92use serde_json::{json, Value};
93use sha2::Digest;
94
95pub use audit::{AuditLog, AuditRecord};
96pub use cache::Cache;
97pub use confine::{AllowRoot, ConfinedFile};
98pub use cursor::Cursor;
99pub use guard::Guard;
100pub use logging::Notifier;
101pub use schema::{
102 ChainResponse, ErrorCode, GadgetRecord, InfoResponse, ScanResponse, ToolErrorBody, Warning,
103};
104pub use semantics::{GadgetFilter, Order, Semantics};
105pub use stats::{ServerStats, Verdict};
106
107pub const DEFAULT_MAX_RESULTS: usize = 1000;
108pub const HARD_MAX_RESULTS: usize = 50000;
109pub const DEFAULT_TIMEOUT_SECS: u64 = 60;
110pub const HARD_MAX_TIMEOUT_SECS: u64 = 300;
111pub const DEFAULT_MAX_DEPTH: usize = 64;
115pub const DEFAULT_MAX_FILE_BYTES: u64 = 256 * 1024 * 1024;
118pub const DEFAULT_MAX_CONCURRENT: usize = 2;
120pub const DEFAULT_MAX_GADGETS: usize = 5_000_000;
124pub const DEFAULT_CACHE_MEM_BYTES: u64 = rf_cache::DEFAULT_MEM_MAX_BYTES;
126pub const DEFAULT_CACHE_TTL: Duration = rf_cache::DEFAULT_MEM_TTL;
128pub const DEFAULT_CURSOR_TTL: Duration = cache::DEFAULT_CURSOR_TTL;
131pub const DEFAULT_PROBE_THRESHOLD: u64 = 20;
134pub const PROBE_DELAY: Duration = Duration::from_millis(250);
136pub const DEFAULT_MAX_INFO_ITEMS: usize = 4096;
140
141pub const DEFAULT_MAX_SYMBOLS: usize = 0;
157
158const ALLOWED_FLAGS: &[&str] = &[
160 "depth",
161 "norop",
162 "nojop",
163 "nosys",
164 "only",
165 "filter",
166 "re",
167 "range",
168 "section",
169 "base",
170 "offset",
171 "badbytes",
172 "align",
173 "multibr",
174 "json",
175 "arch",
176 "all",
177 "callPreceded",
178];
179const VALUE_FLAGS: &[&str] = &[
181 "depth", "only", "filter", "re", "range", "section", "base", "offset", "badbytes", "align",
182 "arch",
183];
184
185#[derive(Debug, Clone)]
190pub struct ServerConfig {
191 pub allow_dirs: Vec<PathBuf>,
197 pub cache_dir: Option<PathBuf>,
199 pub timeout: Duration,
200 pub max_results: usize,
201 pub max_depth: usize,
203 pub max_file_bytes: u64,
206 pub max_concurrent: usize,
208 pub scan_threads: usize,
211 pub max_gadgets: Option<usize>,
213 pub cache_mem_bytes: u64,
216 pub cache_ttl: Duration,
217 pub cursor_ttl: Duration,
220 pub workspace_dir: Option<PathBuf>,
224 pub audit_log: Option<PathBuf>,
226 pub audit_log_max_mb: u64,
227 pub probe_threshold: u64,
230 pub max_info_items: usize,
232 pub verbose_path_errors: bool,
234}
235
236impl Default for ServerConfig {
237 fn default() -> Self {
238 ServerConfig {
239 allow_dirs: Vec::new(),
240 cache_dir: None,
241 timeout: Duration::from_secs(DEFAULT_TIMEOUT_SECS),
242 max_results: DEFAULT_MAX_RESULTS,
243 max_depth: DEFAULT_MAX_DEPTH,
244 max_file_bytes: DEFAULT_MAX_FILE_BYTES,
245 max_concurrent: DEFAULT_MAX_CONCURRENT,
246 scan_threads: guard::default_scan_threads(),
247 max_gadgets: Some(DEFAULT_MAX_GADGETS),
248 cache_mem_bytes: DEFAULT_CACHE_MEM_BYTES,
249 cache_ttl: DEFAULT_CACHE_TTL,
250 cursor_ttl: DEFAULT_CURSOR_TTL,
251 workspace_dir: None,
252 audit_log: None,
253 audit_log_max_mb: audit::DEFAULT_AUDIT_MAX_MB,
254 probe_threshold: DEFAULT_PROBE_THRESHOLD,
255 max_info_items: DEFAULT_MAX_INFO_ITEMS,
256 verbose_path_errors: false,
257 }
258 }
259}
260
261#[derive(Debug)]
272pub struct ToolError {
273 pub code: ErrorCode,
274 pub kind: &'static str,
277 pub message: String,
278 pub details: Option<Value>,
281 pub retryable: bool,
283 pub suggestion: Option<Value>,
285}
286
287impl ToolError {
288 pub(crate) fn new(code: ErrorCode, message: impl Into<String>) -> Self {
289 ToolError {
290 code,
291 kind: code.as_str(),
292 message: message.into(),
293 details: None,
294 retryable: code.default_retryable(),
295 suggestion: None,
296 }
297 }
298
299 pub(crate) fn with_details(
300 code: ErrorCode,
301 message: impl Into<String>,
302 details: Value,
303 ) -> Self {
304 ToolError {
305 details: Some(details),
306 ..ToolError::new(code, message)
307 }
308 }
309
310 #[must_use]
312 pub(crate) fn with_kind(mut self, kind: &'static str) -> Self {
313 self.kind = kind;
314 self
315 }
316
317 #[must_use]
318 pub(crate) fn retryable(mut self, yes: bool) -> Self {
319 self.retryable = yes;
320 self
321 }
322
323 #[must_use]
324 pub(crate) fn with_suggestion(mut self, suggestion: Value) -> Self {
325 self.suggestion = Some(suggestion);
326 self
327 }
328
329 #[must_use]
332 pub fn is_hard_timeout(&self) -> bool {
333 self.code == ErrorCode::Timeout && self.kind == "timeout_hard"
334 }
335
336 fn to_json(&self) -> Value {
337 json!({"error": {
338 "code": self.code,
339 "message": self.message,
340 "retryable": self.retryable,
341 "details": self.details.clone().unwrap_or_else(|| json!({})),
342 "suggestion": self.suggestion.clone().unwrap_or(Value::Null),
343 }})
344 }
345}
346
347fn sha256_hex(bytes: &[u8]) -> String {
362 let mut h = sha2::Sha256::new();
363 h.update(bytes);
364 format!("{:x}", h.finalize())
365}
366
367#[derive(Debug, Deserialize, Serialize, JsonSchema)]
376pub struct GadgetQuery {
377 pub binary_path: String,
380 pub depth: Option<usize>,
382 pub section: Option<String>,
385 pub base: Option<String>,
388 pub offset: Option<String>,
390 pub only: Option<String>,
392 pub range: Option<String>,
394 pub badbytes: Option<String>,
397 pub max_results: Option<usize>,
399 pub order: Option<String>,
406 pub sort_by: Option<String>,
410 pub cursor: Option<String>,
414 pub class: Option<String>,
418 pub label: Option<String>,
421 pub writes_reg: Option<String>,
425 pub reads_reg: Option<String>,
427 pub preserves_regs: Option<String>,
430 pub from_stack: Option<bool>,
435 pub terminator: Option<String>,
442 pub max_side_effects: Option<u32>,
444 pub max_insns: Option<u32>,
446 pub set_reg: Option<String>,
450 pub no_clobber: Option<Vec<String>>,
456 pub max_stack_delta: Option<i64>,
461 pub pivot: Option<bool>,
464 pub search: Option<String>,
470 pub arch: Option<String>,
475 pub timeout_secs: Option<u64>,
477}
478
479fn arch_from_bytes(bytes: &[u8]) -> Option<rf_core::Arch> {
481 use rf_core::{Image, LoadedBinary};
482 match rf_core::Binary::load(bytes).ok()? {
483 LoadedBinary::Elf(b) => Some(Image::arch(&b)),
484 LoadedBinary::Pe(b) => Some(Image::arch(&b)),
485 LoadedBinary::MachO(b) => Some(Image::arch(&b)),
486 LoadedBinary::Universal(u) => u.slices().first().map(Image::arch),
489 LoadedBinary::Raw(b) => Some(Image::arch(&b)),
490 }
491}
492
493#[derive(Debug, Deserialize, Serialize, JsonSchema)]
501pub struct SearchQuery {
502 pub binary_path: String,
505 pub pattern: String,
508 pub depth: Option<usize>,
510 pub section: Option<String>,
512 pub base: Option<String>,
514 pub offset: Option<String>,
516 pub range: Option<String>,
518 pub badbytes: Option<String>,
520 pub max_results: Option<usize>,
522 pub order: Option<String>,
524 pub cursor: Option<String>,
526 pub class: Option<String>,
528 pub label: Option<String>,
530 pub writes_reg: Option<String>,
532 pub reads_reg: Option<String>,
534 pub preserves_regs: Option<String>,
536 pub from_stack: Option<bool>,
538 pub terminator: Option<String>,
542 pub max_side_effects: Option<u32>,
543 pub max_insns: Option<u32>,
544 pub set_reg: Option<String>,
548 pub no_clobber: Option<Vec<String>>,
554 pub max_stack_delta: Option<i64>,
559 pub pivot: Option<bool>,
562 pub search: Option<String>,
568 pub arch: Option<String>,
573 pub timeout_secs: Option<u64>,
575}
576
577#[derive(Debug, Deserialize, Serialize, JsonSchema)]
590pub struct EffectQuery {
591 pub binary_path: String,
594 pub depth: Option<usize>,
596
597 pub set_reg: Option<String>,
603 pub from_stack: Option<bool>,
608 pub no_clobber: Option<Vec<String>>,
613 pub reads_reg: Option<String>,
615 pub max_stack_delta: Option<i64>,
620 pub max_side_effects: Option<u32>,
622 pub max_insns: Option<u32>,
624 pub terminator: Option<String>,
628 pub search: Option<String>,
634 pub pivot: Option<bool>,
638 pub class: Option<String>,
641 pub label: Option<String>,
643 pub writes_reg: Option<String>,
646 pub preserves_regs: Option<String>,
650
651 pub section: Option<String>,
654 pub base: Option<String>,
656 pub offset: Option<String>,
658 pub range: Option<String>,
660 pub badbytes: Option<String>,
662 pub max_results: Option<usize>,
664 pub order: Option<String>,
666 pub cursor: Option<String>,
668 pub arch: Option<String>,
671 pub timeout_secs: Option<u64>,
673}
674
675#[derive(Debug, Deserialize, Serialize, JsonSchema)]
676pub struct RawCommandQuery {
677 pub binary_path: String,
680 pub args: Vec<String>,
685 pub max_results: Option<usize>,
687 pub order: Option<String>,
689 pub cursor: Option<String>,
691 pub class: Option<String>,
693 pub label: Option<String>,
695 pub writes_reg: Option<String>,
697 pub reads_reg: Option<String>,
699 pub preserves_regs: Option<String>,
701 pub from_stack: Option<bool>,
703 pub terminator: Option<String>,
706 pub max_side_effects: Option<u32>,
707 pub max_insns: Option<u32>,
708 pub set_reg: Option<String>,
712 pub no_clobber: Option<Vec<String>>,
718 pub max_stack_delta: Option<i64>,
723 pub pivot: Option<bool>,
726 pub search: Option<String>,
732 pub timeout_secs: Option<u64>,
734}
735
736#[derive(Debug, Deserialize, Serialize, JsonSchema)]
742pub struct IdsQuery {
743 pub binary_path: String,
746 pub ids: Vec<String>,
750 pub depth: Option<usize>,
753 pub base: Option<String>,
757 pub offset: Option<String>,
759 pub section: Option<String>,
761 pub arch: Option<String>,
763 pub timeout_secs: Option<u64>,
765}
766
767#[derive(Debug, Deserialize, Serialize, JsonSchema)]
769pub struct StringQuery {
770 pub binary_path: String,
773 pub string: String,
777 pub memstr: Option<bool>,
782 pub base: Option<String>,
785 pub offset: Option<String>,
787 pub range: Option<String>,
790 pub max_results: Option<usize>,
792 pub cursor: Option<String>,
794 pub arch: Option<String>,
797 pub timeout_secs: Option<u64>,
799}
800
801#[derive(Debug, Deserialize, Serialize, JsonSchema)]
803pub struct BytesQuery {
804 pub binary_path: String,
807 pub opcode: String,
811 pub base: Option<String>,
813 pub offset: Option<String>,
815 pub range: Option<String>,
817 pub max_results: Option<usize>,
819 pub cursor: Option<String>,
821 pub arch: Option<String>,
824 pub timeout_secs: Option<u64>,
826}
827
828#[derive(Debug, Deserialize, Serialize, JsonSchema)]
830pub struct MitigationsQuery {
831 pub binary_path: String,
834 pub timeout_secs: Option<u64>,
836}
837
838#[derive(Debug, Deserialize, Serialize, JsonSchema)]
839pub struct InfoQuery {
840 pub binary_path: String,
843 pub base: Option<String>,
845 pub max_sections: Option<usize>,
848 pub max_imports: Option<usize>,
851 pub max_symbols: Option<usize>,
860 pub timeout_secs: Option<u64>,
862}
863
864#[derive(Debug, Deserialize, Serialize, JsonSchema)]
865pub struct ChainQuery {
866 pub binary_path: String,
869 pub target: String,
872 pub depth: Option<usize>,
874 pub base: Option<String>,
876 pub offset: Option<String>,
878 pub badbytes: Option<String>,
881 pub cfg_aware: Option<bool>,
883 pub api_addr: Option<String>,
886 pub api_name: Option<String>,
890 pub shellcode_addr: Option<String>,
893 pub shellcode_size: Option<String>,
895 pub chain_base: Option<String>,
899 pub prot: Option<String>,
903 pub syscall: Option<String>,
906 pub syscall_args: Option<String>,
909 pub chain_pivot: Option<String>,
913 pub stage: Option<String>,
917 pub arch: Option<String>,
922 pub timeout_secs: Option<u64>,
924}
925
926fn clamp_max_results(req: Option<usize>, default: usize) -> usize {
931 req.unwrap_or(default).clamp(1, HARD_MAX_RESULTS)
932}
933
934fn clamp_timeout(req: Option<u64>, default: Duration) -> Duration {
935 req.map(|s| Duration::from_secs(s.clamp(1, HARD_MAX_TIMEOUT_SECS)))
936 .unwrap_or(default)
937}
938
939#[derive(Debug)]
941pub struct ParsedArgs {
942 pub request: rf_api::ScanRequest,
943 pub re: Option<String>,
946}
947
948pub fn parse_align(v: &str) -> Result<usize, String> {
958 let t = v.trim();
959 if let Some(hex) = t.strip_prefix("0x").or_else(|| t.strip_prefix("0X")) {
960 if hex.is_empty() {
961 return Err(format!("invalid --align {v:?}: no digits after 0x"));
962 }
963 return usize::from_str_radix(hex, 16).map_err(|e| format!("invalid --align {v:?}: {e}"));
964 }
965 t.parse::<usize>()
966 .map_err(|e| format!("invalid --align {v:?}: {e}"))
967}
968
969pub fn parse_ropgadget_args(args: &[String]) -> Result<ParsedArgs, ToolError> {
972 let mut req = rf_api::ScanRequest::default();
973 let mut re = None;
974 let mut i = 0;
975 while i < args.len() {
976 let Some(arg) = args.get(i) else { break };
977 let Some(stripped) = arg.strip_prefix("--") else {
978 return Err(usage_flag(format!(
979 "unexpected positional argument {arg:?}; only --flags are accepted"
980 )));
981 };
982 let (name, inline_val) = match stripped.split_once('=') {
983 Some((n, v)) => (n, Some(v.to_string())),
984 None => (stripped, None),
985 };
986 if !ALLOWED_FLAGS.contains(&name) {
987 return Err(usage_flag(format!(
988 "flag --{name} is not allowed; allowlist: {}",
989 ALLOWED_FLAGS
990 .iter()
991 .map(|f| format!("--{f}"))
992 .collect::<Vec<_>>()
993 .join(" ")
994 )));
995 }
996 let takes_value = VALUE_FLAGS.contains(&name);
997 let value = if takes_value {
998 match inline_val {
999 Some(v) => Some(v),
1000 None => {
1001 i += 1;
1002 let Some(v) = args.get(i) else {
1003 return Err(usage_flag(format!("flag --{name} requires a value")));
1004 };
1005 if v.starts_with("--") {
1006 return Err(usage_flag(format!(
1007 "flag --{name} requires a value (got {v:?})"
1008 )));
1009 }
1010 Some(v.clone())
1011 }
1012 }
1013 } else {
1014 if inline_val.is_some() {
1015 return Err(usage_flag(format!("flag --{name} does not take a value")));
1016 }
1017 None
1018 };
1019 match name {
1020 "depth" => {
1021 req.depth = value.unwrap().parse().map_err(|_| {
1022 ToolError::new(ErrorCode::UsageError, "invalid --depth value".to_string())
1023 })?;
1024 }
1025 "norop" => req.rop = false,
1026 "nojop" => req.jop = false,
1027 "nosys" => req.sys = false,
1028 "multibr" => req.multibr = true,
1029 "json" => {} "only" => req.only = value,
1031 "filter" => req.filter = value,
1032 "range" => req.range = value,
1033 "section" => req.section.extend(split_sections(value.as_deref())),
1034 "base" => req.base = value,
1035 "offset" => req.offset = value,
1036 "badbytes" => req.badbytes = value,
1037 "re" => re = value,
1038 "arch" => req.arch = value,
1039 "all" => req.all = true,
1040 "callPreceded" => req.call_preceded = true,
1041 "align" => {
1042 let v = value.unwrap();
1044 req.align =
1045 Some(parse_align(&v).map_err(|e| ToolError::new(ErrorCode::UsageError, e))?);
1046 }
1047 _ => unreachable!("allowlist checked above"),
1048 }
1049 i += 1;
1050 }
1051 Ok(ParsedArgs { request: req, re })
1052}
1053
1054macro_rules! raw_filter {
1064 ($q:expr) => {
1065 semantics::RawFilter {
1066 class: $q.class.as_deref(),
1067 label: $q.label.as_deref(),
1068 writes_reg: $q.writes_reg.as_deref(),
1069 reads_reg: $q.reads_reg.as_deref(),
1070 preserves_regs: $q.preserves_regs.as_deref(),
1071 from_stack: $q.from_stack,
1072 terminator: $q.terminator.as_deref(),
1073 max_side_effects: $q.max_side_effects,
1074 max_insns: $q.max_insns,
1075 set_reg: $q.set_reg.as_deref(),
1076 no_clobber: $q.no_clobber.as_deref().unwrap_or(&[]),
1077 max_stack_delta: $q.max_stack_delta,
1078 pivot: $q.pivot,
1079 search: $q.search.as_deref(),
1080 }
1081 };
1082}
1083
1084fn split_sections(section: Option<&str>) -> Vec<String> {
1085 section
1086 .map(|s| {
1087 s.split(',')
1088 .map(|x| x.trim().to_string())
1089 .filter(|x| !x.is_empty())
1090 .collect()
1091 })
1092 .unwrap_or_default()
1093}
1094
1095fn query_to_request(q: &GadgetQuery, rop: bool, jop: bool, sys: bool) -> rf_api::ScanRequest {
1096 rf_api::ScanRequest {
1097 depth: q.depth.unwrap_or(10),
1098 rop,
1099 jop,
1100 sys,
1101 multibr: false,
1102 only: q.only.clone(),
1103 filter: None,
1104 range: q.range.clone(),
1105 badbytes: q.badbytes.clone(),
1106 offset: q.offset.clone(),
1107 base: q.base.clone(),
1108 section: split_sections(q.section.as_deref()),
1109 thumb: false,
1110 cfg_aware: false,
1111 align: None,
1112 call_preceded: false,
1113 all: false,
1114 noinstr: false,
1115 arch: q.arch.clone(),
1116 max_gadgets: None,
1117 max_memory: None,
1118 compat: false,
1122 }
1123}
1124
1125struct FindRequest {
1132 binary_path: String,
1133 mode: find::Mode,
1134 query: String,
1136 base: Option<String>,
1137 offset: Option<String>,
1138 range: Option<String>,
1139 arch: Option<String>,
1140 max_results: Option<usize>,
1141 cursor: Option<String>,
1142 params_hash: String,
1143 timeout_secs: Option<u64>,
1144}
1145
1146fn search_addr_size(target: &rf_api::Target, arch: rf_core::Arch) -> usize {
1155 if matches!(target, rf_api::Target::Raw(_))
1156 && matches!(arch, rf_core::Arch::Arm | rf_core::Arch::ArmThumb)
1157 {
1158 return 8;
1159 }
1160 arch.addr_size()
1161}
1162
1163struct PostOpts {
1165 re: Option<String>,
1175 order: Order,
1177 filter: GadgetFilter,
1179 cursor: Option<String>,
1181 params_hash: String,
1184 max_results: Option<usize>,
1186 timeout_secs: Option<u64>,
1188 ids: Option<Vec<String>>,
1190}
1191
1192impl Default for PostOpts {
1193 fn default() -> Self {
1194 PostOpts {
1195 re: None,
1196 order: Order::Rank,
1197 filter: GadgetFilter::default(),
1198 cursor: None,
1199 params_hash: String::new(),
1200 max_results: None,
1201 timeout_secs: None,
1202 ids: None,
1203 }
1204 }
1205}
1206
1207#[derive(Clone)]
1208pub struct RopFinderMcp {
1209 config: Arc<ServerConfig>,
1210 cache: Arc<Cache>,
1211 roots: Arc<Vec<AllowRoot>>,
1214 guard: Arc<Guard>,
1217 stats: Arc<ServerStats>,
1218 audit: Option<Arc<AuditLog>>,
1220 notifier: Arc<Notifier>,
1223 session: Arc<str>,
1225}
1226
1227impl RopFinderMcp {
1228 pub fn new(config: ServerConfig) -> std::io::Result<Self> {
1233 let mut roots = Vec::with_capacity(config.allow_dirs.len());
1234 for d in &config.allow_dirs {
1235 let root = AllowRoot::open(d)?;
1236 if roots.iter().any(|r: &AllowRoot| r.id() == root.id()) {
1237 continue;
1238 }
1239 roots.push(root);
1240 }
1241 let session: Arc<str> = Arc::from(uuid::Uuid::new_v4().to_string().as_str());
1242 let audit = match &config.audit_log {
1243 None => None,
1244 Some(p) => Some(Arc::new(AuditLog::open(
1245 p,
1246 config.audit_log_max_mb,
1247 session.to_string(),
1248 )?)),
1249 };
1250 let cache = Cache::new(
1251 config.cache_dir.clone(),
1252 rf_cache::MemLimits {
1253 max_bytes: config.cache_mem_bytes,
1254 ttl: config.cache_ttl,
1255 },
1256 config.cursor_ttl,
1257 );
1258 let stats = Arc::new(ServerStats::default());
1259 let guard = Guard::new(config.max_concurrent, config.scan_threads, stats.clone())
1260 .map_err(std::io::Error::other)?;
1261 Ok(RopFinderMcp {
1262 config: Arc::new(config),
1263 cache: Arc::new(cache),
1264 roots: Arc::new(roots),
1265 guard: Arc::new(guard),
1266 stats,
1267 audit,
1268 notifier: Arc::new(Notifier::new()),
1269 session,
1270 })
1271 }
1272
1273 #[must_use]
1275 pub fn session_id(&self) -> &str {
1276 &self.session
1277 }
1278
1279 #[must_use]
1281 pub fn stats(&self) -> &ServerStats {
1282 &self.stats
1283 }
1284
1285 #[must_use]
1286 pub fn notifier(&self) -> &Notifier {
1287 &self.notifier
1288 }
1289
1290 fn open_confined(&self, binary_path: &str) -> Result<ConfinedFile, ToolError> {
1292 confine::open_confined_with(
1293 &self.roots,
1294 binary_path,
1295 self.config.max_file_bytes,
1296 self.config.verbose_path_errors,
1297 )
1298 }
1299
1300 fn check_depth(&self, depth: Option<usize>) -> Result<usize, ToolError> {
1302 let d = depth.unwrap_or(10);
1303 if d > self.config.max_depth {
1304 return Err(ToolError::with_details(
1305 ErrorCode::UsageError,
1306 format!(
1307 "depth {d} exceeds the server's max_depth of {}; \
1308 re-send with depth <= {}",
1309 self.config.max_depth, self.config.max_depth
1310 ),
1311 json!({"limit": "max_depth",
1312 "limit_value": self.config.max_depth,
1313 "got": d}),
1314 ));
1315 }
1316 Ok(d)
1317 }
1318
1319 fn config_response(&self) -> schema::ConfigResponse {
1327 schema::ConfigResponse {
1328 allow_roots: self.root_paths(),
1329 max_depth: self.config.max_depth as u64,
1330 max_file_bytes: self.config.max_file_bytes,
1331 max_results: self.config.max_results as u64,
1332 hard_max_results: HARD_MAX_RESULTS as u64,
1333 max_concurrent: self.config.max_concurrent as u64,
1334 scan_threads: self.guard.scan_threads() as u64,
1335 max_gadgets: self.config.max_gadgets.map(|g| g as u64),
1336 max_sections: self.config.max_info_items as u64,
1337 max_imports: self.config.max_info_items as u64,
1338 timeout_secs: self.config.timeout.as_secs(),
1339 cache: self.config.cache_dir.is_some(),
1340 cache_mem_max_bytes: self.config.cache_mem_bytes,
1341 cache_ttl_secs: self.config.cache_ttl.as_secs(),
1342 cursor_ttl_secs: self.config.cursor_ttl.as_secs(),
1343 workspace_dir: self
1344 .config
1345 .workspace_dir
1346 .as_ref()
1347 .map(|p| p.display().to_string()),
1348 audit_log: self.audit.is_some(),
1349 probe_threshold: self.config.probe_threshold,
1350 orders: semantics::ORDER_NAMES
1351 .iter()
1352 .map(|s| (*s).to_string())
1353 .collect(),
1354 error_codes: ErrorCode::all()
1355 .iter()
1356 .map(|c| c.as_str().to_string())
1357 .collect(),
1358 version: env!("CARGO_PKG_VERSION").to_string(),
1359 }
1360 }
1361
1362 pub fn root_paths(&self) -> Vec<String> {
1364 self.roots
1365 .iter()
1366 .map(|r| r.display_path().display().to_string())
1367 .collect()
1368 }
1369
1370 fn gadget_request(
1372 &self,
1373 q: &GadgetQuery,
1374 rop: bool,
1375 jop: bool,
1376 sys: bool,
1377 ) -> Result<rf_api::ScanRequest, ToolError> {
1378 let depth = self.check_depth(q.depth)?;
1379 let mut req = query_to_request(q, rop, jop, sys);
1380 req.depth = depth;
1381 Ok(req)
1382 }
1383
1384 fn cancel_signal(ctx: &RequestContext<RoleServer>) -> guard::CancelSignal {
1393 let ct = ctx.ct.clone();
1394 Box::pin(async move {
1395 ct.cancelled().await;
1396 })
1397 }
1398
1399 fn begin(
1403 &self,
1404 ctx: &RequestContext<RoleServer>,
1405 tool: &'static str,
1406 params_hash: String,
1407 ) -> (AuditRecord, Instant) {
1408 self.notifier.register(&ctx.peer);
1409 self.stats.record_request(tool);
1410 let req_id = ctx.id.to_string();
1411 tracing::debug!(tool, req_id = %req_id, "tool call");
1412 (AuditRecord::new(req_id, tool, params_hash), Instant::now())
1413 }
1414
1415 async fn finish<T: Serialize>(
1418 &self,
1419 mut rec: AuditRecord,
1420 started: Instant,
1421 out: Result<T, ToolError>,
1422 ) -> Result<CallToolResult, McpError> {
1423 let verdict = match &out {
1424 Ok(_) => Verdict::Ok,
1425 Err(e) => {
1426 rec.code = Some(e.kind.to_string());
1431 Verdict::for_code(e.kind)
1432 }
1433 };
1434 rec.verdict = verdict.as_str();
1435 let suspected = self
1436 .stats
1437 .record_verdict(verdict, self.config.probe_threshold);
1438 rec.probing_suspected = suspected;
1439 rec.duration_ms = started.elapsed().as_millis().min(u64::MAX as u128) as u64;
1440
1441 if let Err(e) = &out {
1445 if e.is_hard_timeout() {
1446 self.notifier.error(
1447 "worker_wedged",
1448 "a cancelled scan did not stop within the hard-join window",
1449 json!({"tool": rec.tool, "wedged_total": self.stats.wedged_now()}),
1450 );
1451 }
1452 }
1453 if suspected {
1454 self.notifier.warn(
1455 "path_probing",
1456 "consecutive path_denied results suggest an agent is enumerating the filesystem",
1457 json!({"denied_consecutive": self.stats.denied_consecutive_now(),
1458 "threshold": self.config.probe_threshold,
1459 "requested": rec.binary}),
1460 );
1461 }
1462
1463 if let Some(log) = &self.audit {
1464 log.write(&rec);
1465 }
1466
1467 if suspected {
1472 tokio::time::sleep(PROBE_DELAY).await;
1473 }
1474
1475 match out {
1476 Ok(v) => tool_ok(&v),
1477 Err(e) => tool_error(e),
1478 }
1479 }
1480
1481 async fn run_scan(
1490 &self,
1491 ctx: &RequestContext<RoleServer>,
1492 rec: &mut AuditRecord,
1493 req: rf_api::ScanRequest,
1494 binary_path: &str,
1495 post: PostOpts,
1496 ) -> Result<ScanResponse, ToolError> {
1497 let PostOpts {
1498 re: post_re,
1499 order,
1500 filter,
1501 cursor: cursor_in,
1502 params_hash,
1503 max_results,
1504 timeout_secs,
1505 ids,
1506 } = post;
1507 rec.binary = Some(binary_path.to_string());
1509 let confined = self.open_confined(binary_path)?;
1510 rec.binary = Some(confined.label.clone());
1513 let binary_label = confined.label.clone();
1514 let declared_len = confined.len;
1515 let max = clamp_max_results(max_results, self.config.max_results);
1516 let timeout = clamp_timeout(timeout_secs, self.config.timeout);
1517 let cache = self.cache.clone();
1518 let max_file_bytes = self.config.max_file_bytes;
1519 let max_gadgets = self.config.max_gadgets;
1520 let workspace = self.config.workspace_dir.clone();
1521
1522 let work =
1523 move |cancel: rf_scan::CancelToken| -> Result<(ScanResponse, ScanFacts), ToolError> {
1524 let bytes = confined.read_all(max_file_bytes)?;
1525 let file_hash = sha256_hex(&bytes);
1526 let key = rf_cache::make_key(
1543 &file_hash,
1544 &format!(
1545 "depth={}|rop={}|jop={}|sys={}|multibr={}|only={}|filter={}|range={}|\
1546 badbytes={}|offset={}|section={:?}|thumb={}|base={}|cfg_aware={}|\
1547 align={:?}|arch={}|all={}|noinstr={}|call_preceded={}|\
1548 max_gadgets={:?}|max_memory={:?}|compat={}|rec=3",
1549 req.depth,
1550 req.rop,
1551 req.jop,
1552 req.sys,
1553 req.multibr,
1554 req.only.as_deref().unwrap_or(""),
1555 req.filter.as_deref().unwrap_or(""),
1556 req.range.as_deref().unwrap_or(""),
1557 req.badbytes.as_deref().unwrap_or(""),
1558 req.offset.as_deref().unwrap_or(""),
1559 req.section,
1560 req.thumb,
1561 req.base.as_deref().unwrap_or(""),
1562 req.cfg_aware,
1563 req.align,
1564 req.arch.as_deref().unwrap_or(""),
1565 req.all,
1566 req.noinstr,
1567 req.call_preceded,
1568 req.max_gadgets.or(max_gadgets),
1569 req.max_memory,
1570 req.compat,
1571 ),
1572 );
1573 let offset = match &req.offset {
1577 Some(o) => rf_api::parse_hex(o, "--offset")
1578 .map_err(|e| ToolError::new(ErrorCode::UsageError, e))?,
1579 None => 0,
1580 };
1581 let class_arch = arch_from_bytes(&bytes);
1582 let mut warnings: Vec<Warning> = Vec::new();
1583
1584 let (scan, sems, cache_status) = if let Some(p) = cache.pinned(&key) {
1589 (p.scan, p.sems, "hit")
1593 } else if let Some(hit) = cache.get(&key) {
1594 let sems = Arc::new(semantics::classify_scan(
1595 &hit, &file_hash, offset, class_arch,
1596 ));
1597 cache.pin(&key, hit.clone(), sems.clone());
1598 (hit, sems, "hit")
1599 } else {
1600 let product =
1601 scan::scan_bytes_cancellable(&bytes, &req, &cancel, max_gadgets, None)
1602 .map_err(scan::ScanFail::to_tool_error)?;
1603 let arch = product.universal_arch.map(rf_api::arch_name);
1604 let addr_size = product.addr_size;
1605 let selected = product.selected_sections;
1606 let id_ctx = semantics::IdContext {
1607 binary_sha256: &file_hash,
1608 offset,
1609 };
1610 let classifier = class_arch.map(rf_classify::Classifier::new);
1614 let mut gadgets = Vec::with_capacity(product.gadgets.len());
1615 let mut built = Vec::with_capacity(product.gadgets.len());
1616 for g in &product.gadgets {
1617 let cls = classifier.as_ref().map(|c| c.classify(g));
1618 gadgets.push(CachedGadget {
1619 vaddr: rf_api::fmt_addr(g.vaddr, addr_size),
1620 bytes: g.bytes_hex(),
1621 text: g.text(),
1622 arch: arch.map(str::to_string),
1623 section: selected
1624 .as_deref()
1625 .and_then(|s| rf_api::section_of(s, g.vaddr.wrapping_sub(offset))),
1626 quality: cls.as_ref().map(|c| c.quality),
1627 class: cls.as_ref().map(|c| c.primary.name().to_string()),
1628 delay_slot: g.delay_slot,
1633 ..CachedGadget::default()
1634 });
1635 built.push(semantics::from_scan_gadget(g, cls, &id_ctx));
1636 }
1637 let arc = cache.put(
1638 &key,
1639 CachedScan {
1640 gadgets,
1641 fallback_names: product.fallback_names,
1642 ..CachedScan::default()
1643 },
1644 );
1645 let sems = Arc::new(built);
1646 cache.pin(&key, arc.clone(), sems.clone());
1647 (arc, sems, "miss")
1648 };
1649
1650 let mut idx: Vec<usize> = match &ids {
1652 Some(want) => {
1653 let mut by_id: std::collections::HashMap<&str, usize> =
1654 std::collections::HashMap::with_capacity(sems.len());
1655 for (i, s) in sems.iter().enumerate() {
1656 by_id.entry(s.id.as_str()).or_insert(i);
1657 }
1658 let mut out = Vec::with_capacity(want.len());
1659 let mut missing: Vec<&str> = Vec::new();
1660 for id in want {
1661 match by_id.get(id.as_str()) {
1662 Some(&i) => out.push(i),
1663 None => missing.push(id.as_str()),
1664 }
1665 }
1666 if !missing.is_empty() {
1667 warnings.push(
1668 Warning::truncation(
1669 "ids_not_found",
1670 "gadgets",
1671 out.len(),
1672 want.len(),
1673 )
1674 .with_detail(missing.join(",")),
1675 );
1676 }
1677 out
1678 }
1679 None => (0..scan.gadgets.len()).collect(),
1680 };
1681 if let Some(re) = &post_re {
1685 match regex::Regex::new(re) {
1686 Ok(re) => idx
1687 .retain(|&i| scan.gadgets.get(i).is_some_and(|g| re.is_match(&g.text))),
1688 Err(_) => idx.retain(|&i| {
1689 scan.gadgets
1690 .get(i)
1691 .is_some_and(|g| g.text.contains(re.as_str()))
1692 }),
1693 }
1694 }
1695 if !filter.is_empty() {
1696 idx.retain(|&i| sems.get(i).is_some_and(|s| filter.matches(s)));
1697 }
1698 semantics::sort_indices(&mut idx, order, &scan, &sems);
1699
1700 let total = idx.len() as u64;
1702 let start = match &cursor_in {
1703 Some(raw) => Cursor::decode(raw, &key, order.as_str(), ¶ms_hash)?.offset,
1704 None => 0,
1705 };
1706 let page: Vec<usize> = idx
1707 .iter()
1708 .skip(usize::try_from(start).unwrap_or(usize::MAX))
1709 .take(max)
1710 .copied()
1711 .collect();
1712 let gadgets: Vec<GadgetRecord> = page
1713 .iter()
1714 .filter_map(|&i| Some(GadgetRecord::build(scan.gadgets.get(i)?, sems.get(i)?)))
1715 .collect();
1716 let returned = gadgets.len() as u64;
1717 let truncated = start.saturating_add(returned) < total;
1718
1719 if scan.fallback_names {
1721 warnings.push(Warning::new(
1722 "fallback_section_names",
1723 "the binary has no section names; synthetic PT_LOAD#n names were matched \
1724 instead, so `section` values are positional rather than real",
1725 ));
1726 }
1727 if let Some(slice) = scan.gadgets.first().and_then(|g| g.arch.clone()) {
1728 warnings.push(
1729 Warning::new(
1730 "universal_slice_selected",
1731 "this is one slice of a fat (Universal) Mach-O; addresses are that \
1732 slice's",
1733 )
1734 .with_detail(slice),
1735 );
1736 }
1737 if gadgets.iter().any(|g| g.low_confidence) {
1738 warnings.push(Warning::new(
1739 "low_confidence_classification",
1740 "some gadgets were classified from disassembly text rather than decoder \
1741 metadata; treat class/labels/regs on those as advisory",
1742 ));
1743 }
1744 if truncated {
1745 warnings.push(Warning::truncation(
1746 "truncated",
1747 "gadgets",
1748 usize::try_from(returned).unwrap_or(usize::MAX),
1749 usize::try_from(total).unwrap_or(usize::MAX),
1750 ));
1751 }
1752
1753 let paged = total > returned;
1755 let resource_uri = paged.then(|| resources::scan_uri(&key));
1756 let workspace_file = match (&workspace, paged) {
1757 (Some(dir), true) => {
1758 resources::ensure_file(dir, &key, || resources::render_ndjson(&scan, &sems))
1759 .map(|p| p.display().to_string())
1760 }
1761 _ => None,
1762 };
1763
1764 let facts = ScanFacts {
1765 sha256: file_hash.clone(),
1766 bytes_read: bytes.len() as u64,
1767 cache: cache_status,
1768 total_count: total,
1769 returned,
1770 };
1771 Ok((
1772 ScanResponse {
1773 gadgets,
1774 total_count: total,
1775 returned,
1776 offset: start,
1777 truncated,
1778 next_cursor: Cursor::next(
1779 &key,
1780 order.as_str(),
1781 ¶ms_hash,
1782 start,
1783 returned,
1784 total,
1785 ),
1786 order: order.as_str().to_string(),
1787 binary_sha256: file_hash,
1788 binary_label,
1789 cache: cache_status.to_string(),
1790 cache_key: key,
1791 fallback_section_names: scan.fallback_names,
1792 warnings,
1793 resource_uri,
1794 workspace_file,
1795 },
1796 facts,
1797 ))
1798 };
1799
1800 let out = self
1801 .guard
1802 .run(Some(Self::cancel_signal(ctx)), timeout, work)
1803 .await;
1804 match out {
1805 Ok((v, facts)) => {
1806 facts.apply(rec);
1807 self.stats.add_bytes_read(facts.bytes_read);
1808 Ok(v)
1809 }
1810 Err(e) => {
1811 rec.bytes_read = 0;
1814 tracing::debug!(code = e.kind, declared_len, "tool call failed");
1815 Err(e)
1816 }
1817 }
1818 }
1819
1820 async fn run_find(
1830 &self,
1831 ctx: &RequestContext<RoleServer>,
1832 rec: &mut AuditRecord,
1833 opts: FindRequest,
1834 ) -> Result<find::SearchHitsResponse, ToolError> {
1835 let FindRequest {
1836 binary_path,
1837 mode,
1838 query,
1839 base,
1840 offset,
1841 range,
1842 arch,
1843 max_results,
1844 cursor: cursor_in,
1845 params_hash,
1846 timeout_secs,
1847 } = opts;
1848
1849 let byte_pattern = match mode {
1852 find::Mode::Opcode => Some(find::BytePattern::parse(&query)?),
1853 _ => None,
1854 };
1855
1856 rec.binary = Some(binary_path.clone());
1857 let confined = self.open_confined(&binary_path)?;
1858 rec.binary = Some(confined.label.clone());
1859 let binary_label = confined.label.clone();
1860 let base_value = base
1861 .as_deref()
1862 .map(|b| rf_api::parse_hex(b, "base"))
1863 .transpose()
1864 .map_err(|e| ToolError::new(ErrorCode::UsageError, e))?;
1865 let offset_value = offset
1866 .as_deref()
1867 .map(|o| rf_api::parse_hex(o, "offset"))
1868 .transpose()
1869 .map_err(|e| ToolError::new(ErrorCode::UsageError, e))?
1870 .unwrap_or(0);
1871 let range_value = range
1872 .as_deref()
1873 .map(rf_api::parse_range)
1874 .transpose()
1875 .map_err(|e| ToolError::new(ErrorCode::UsageError, e))?
1876 .flatten();
1877 let page = clamp_max_results(max_results, self.config.max_results);
1878 let timeout = clamp_timeout(timeout_secs, self.config.timeout);
1879 let max_file_bytes = self.config.max_file_bytes;
1880 let workspace = self.config.workspace_dir.clone();
1881 let cache = self.cache.clone();
1882
1883 let work = move |_cancel: rf_scan::CancelToken| -> Result<
1884 (find::SearchHitsResponse, ScanFacts),
1885 ToolError,
1886 > {
1887 let bytes = confined.read_all(max_file_bytes)?;
1888 let file_hash = sha256_hex(&bytes);
1889 let target = rf_api::load_target(&bytes, None).map_err(scan_err_to_tool)?;
1890 let selected = rf_api::resolve_arch(&target, arch.as_deref(), false)
1893 .map_err(scan_err_to_tool)?;
1894 let slice = match (&target, selected) {
1895 (rf_api::Target::Universal(u), Some(a)) => {
1896 Some(u.select(a).map_err(|e| {
1897 ToolError::new(ErrorCode::UsageError, e.to_string())
1898 })?)
1899 }
1900 _ => None,
1901 };
1902 let view = rf_api::build_view_selected(&target, selected);
1903 let image_base = view.base;
1904 let delta = base_value.map_or(0, |b| b.wrapping_sub(image_base));
1905 let opts = find::SearchOpts {
1906 delta,
1907 offset: offset_value,
1908 range: range_value,
1909 addr_size: search_addr_size(&target, rf_core::Image::arch(&view)),
1910 max_hits: HARD_MAX_RESULTS,
1913 };
1914 let windows = match mode {
1915 find::Mode::String => find::data_windows(&target, slice, delta),
1916 find::Mode::Opcode => find::exec_windows(&target, slice, delta),
1917 find::Mode::MemStr => {
1919 let mut w = find::exec_windows(&target, slice, delta);
1920 w.extend(find::data_windows(&target, slice, delta));
1921 w
1922 }
1923 };
1924 let sections_searched = find::window_names(&windows);
1925 let mut warnings: Vec<Warning> = Vec::new();
1926 if windows.is_empty() {
1927 warnings.push(Warning::new(
1928 "no_mapped_sections",
1929 "this container exposes no mapped section of the kind this search reads, \
1930 so the answer is empty by construction rather than by absence",
1931 ));
1932 }
1933
1934 let (all_hits, total) = match (mode, &byte_pattern) {
1935 (find::Mode::String, _) => find::find_string(&windows, &query, &opts)?,
1936 (find::Mode::MemStr, _) => find::find_memstr(&windows, &query, &opts),
1937 (find::Mode::Opcode, Some(p)) => find::find_opcode(&windows, p, &opts),
1938 (find::Mode::Opcode, None) => {
1940 return Err(ToolError::new(
1941 ErrorCode::Internal,
1942 "the opcode pattern was not compiled",
1943 ))
1944 }
1945 };
1946 if total > all_hits.len() as u64 {
1947 warnings.push(Warning::truncation(
1948 "hits_capped",
1949 "hits",
1950 all_hits.len(),
1951 usize::try_from(total).unwrap_or(usize::MAX),
1952 ));
1953 }
1954
1955 let key = format!(
1958 "s{}",
1959 rf_cache::sha256_hex(
1960 format!(
1961 "{file_hash}|{}|{query}|base={base_value:?}|offset={offset_value}|\
1962 range={range_value:?}|arch={}",
1963 mode.as_str(),
1964 arch.as_deref().unwrap_or("")
1965 )
1966 .as_bytes()
1967 )
1968 );
1969 let walkable = all_hits.len() as u64;
1970 let start = match &cursor_in {
1971 Some(raw) => Cursor::decode(raw, &key, "address", ¶ms_hash)?.offset,
1972 None => 0,
1973 };
1974 let hits: Vec<find::Hit> = all_hits
1975 .iter()
1976 .skip(usize::try_from(start).unwrap_or(usize::MAX))
1977 .take(page)
1978 .cloned()
1979 .collect();
1980 let returned = hits.len() as u64;
1981 let truncated = start.saturating_add(returned) < total;
1982 if truncated {
1983 warnings.push(Warning::truncation(
1984 "truncated",
1985 "hits",
1986 usize::try_from(returned).unwrap_or(usize::MAX),
1987 usize::try_from(total).unwrap_or(usize::MAX),
1988 ));
1989 }
1990
1991 let paged = walkable > returned;
1994 let (resource_uri, workspace_file) = if paged {
1995 let ndjson = find::render_ndjson(&all_hits);
1996 cache.pin_text(&key, &ndjson);
1997 let file = workspace
1998 .as_deref()
1999 .and_then(|dir| resources::ensure_file(dir, &key, || ndjson.clone()))
2000 .map(|p| p.display().to_string());
2001 (Some(resources::search_uri(&key)), file)
2002 } else {
2003 (None, None)
2004 };
2005
2006 let facts = ScanFacts {
2007 sha256: file_hash.clone(),
2008 bytes_read: bytes.len() as u64,
2009 cache: "none",
2010 total_count: total,
2011 returned,
2012 };
2013 Ok((
2014 find::SearchHitsResponse {
2015 hits,
2016 mode: mode.as_str().to_string(),
2017 query: query.clone(),
2018 total_count: total,
2019 returned,
2020 offset: start,
2021 truncated,
2022 next_cursor: Cursor::next(
2023 &key,
2024 "address",
2025 ¶ms_hash,
2026 start,
2027 returned,
2028 walkable,
2029 ),
2030 sections_searched,
2031 binary_sha256: file_hash,
2032 binary_label,
2033 warnings,
2034 resource_uri,
2035 workspace_file,
2036 },
2037 facts,
2038 ))
2039 };
2040
2041 match self
2042 .guard
2043 .run(Some(Self::cancel_signal(ctx)), timeout, work)
2044 .await
2045 {
2046 Ok((v, facts)) => {
2047 facts.apply(rec);
2048 self.stats.add_bytes_read(facts.bytes_read);
2049 Ok(v)
2050 }
2051 Err(e) => {
2052 rec.bytes_read = 0;
2053 Err(e)
2054 }
2055 }
2056 }
2057
2058 async fn run_mitigations(
2060 &self,
2061 ctx: &RequestContext<RoleServer>,
2062 rec: &mut AuditRecord,
2063 q: &MitigationsQuery,
2064 ) -> Result<checksec::MitigationsResponse, ToolError> {
2065 rec.binary = Some(q.binary_path.clone());
2066 let confined = self.open_confined(&q.binary_path)?;
2067 rec.binary = Some(confined.label.clone());
2068 let label = confined.label.clone();
2069 let timeout = clamp_timeout(q.timeout_secs, self.config.timeout);
2070 let max_file_bytes = self.config.max_file_bytes;
2071
2072 let work = move |_cancel: rf_scan::CancelToken| -> Result<
2073 (checksec::MitigationsResponse, ScanFacts),
2074 ToolError,
2075 > {
2076 let bytes = confined.read_all(max_file_bytes)?;
2077 let file_hash = sha256_hex(&bytes);
2078 let target = rf_api::load_target(&bytes, None).map_err(scan_err_to_tool)?;
2079 let out = checksec::report(&target, file_hash.clone(), label);
2080 let facts = ScanFacts {
2081 sha256: file_hash,
2082 bytes_read: bytes.len() as u64,
2083 cache: "none",
2084 total_count: 0,
2085 returned: 0,
2086 };
2087 Ok((out, facts))
2088 };
2089
2090 match self
2091 .guard
2092 .run(Some(Self::cancel_signal(ctx)), timeout, work)
2093 .await
2094 {
2095 Ok((v, facts)) => {
2096 rec.binary_sha256 = Some(facts.sha256.clone());
2097 rec.bytes_read = facts.bytes_read;
2098 rec.cache = Some("none");
2099 self.stats.add_bytes_read(facts.bytes_read);
2100 Ok(v)
2101 }
2102 Err(e) => Err(e),
2103 }
2104 }
2105
2106 async fn run_info(
2110 &self,
2111 ctx: &RequestContext<RoleServer>,
2112 rec: &mut AuditRecord,
2113 q: &InfoQuery,
2114 ) -> Result<InfoResponse, ToolError> {
2115 rec.binary = Some(q.binary_path.clone());
2116 let confined = self.open_confined(&q.binary_path)?;
2117 rec.binary = Some(confined.label.clone());
2118 let base = q
2119 .base
2120 .as_deref()
2121 .map(|b| rf_api::parse_hex(b, "--base"))
2122 .transpose()
2123 .map_err(|e| ToolError::new(ErrorCode::UsageError, e))?;
2124 let timeout = clamp_timeout(q.timeout_secs, self.config.timeout);
2125 let max_file_bytes = self.config.max_file_bytes;
2126 let cap = self.config.max_info_items;
2127 let max_sections = q.max_sections.unwrap_or(cap).clamp(1, cap);
2128 let max_imports = q.max_imports.unwrap_or(cap).clamp(1, cap);
2129 let max_symbols = q.max_symbols.unwrap_or(DEFAULT_MAX_SYMBOLS).min(cap);
2130
2131 let work =
2132 move |_cancel: rf_scan::CancelToken| -> Result<(InfoResponse, ScanFacts), ToolError> {
2133 let bytes = confined.read_all(max_file_bytes)?;
2134 let file_hash = sha256_hex(&bytes);
2135 let mut v = rf_api::info_bytes(&bytes, None, base).map_err(scan_err_to_tool)?;
2136 let warnings = truncate_info(&mut v, max_sections, max_imports, max_symbols);
2137 let out = InfoResponse::from_value(v, file_hash.clone(), warnings);
2138 let facts = ScanFacts {
2139 sha256: file_hash,
2140 bytes_read: bytes.len() as u64,
2141 cache: "none",
2142 total_count: 0,
2143 returned: 0,
2144 };
2145 Ok((out, facts))
2146 };
2147
2148 match self
2149 .guard
2150 .run(Some(Self::cancel_signal(ctx)), timeout, work)
2151 .await
2152 {
2153 Ok((v, facts)) => {
2154 rec.binary_sha256 = Some(facts.sha256.clone());
2155 rec.bytes_read = facts.bytes_read;
2156 rec.cache = Some("none");
2157 self.stats.add_bytes_read(facts.bytes_read);
2158 Ok(v)
2159 }
2160 Err(e) => Err(e),
2161 }
2162 }
2163
2164 async fn run_chain(
2169 &self,
2170 ctx: &RequestContext<RoleServer>,
2171 rec: &mut AuditRecord,
2172 q: ChainQuery,
2173 ) -> Result<ChainResponse, ToolError> {
2174 if !rf_api::chain_targets().contains(&q.target.as_str()) {
2175 return Err(ToolError::new(
2176 ErrorCode::UsageError,
2177 format!(
2178 "unknown chain target {:?}; supported: {}",
2179 q.target,
2180 rf_api::chain_targets().join(", ")
2181 ),
2182 ));
2183 }
2184 let depth = self.check_depth(q.depth)?;
2185 rec.binary = Some(q.binary_path.clone());
2186 let confined = self.open_confined(&q.binary_path)?;
2187 rec.binary = Some(confined.label.clone());
2188 let label = confined.label.clone();
2189 let timeout = clamp_timeout(q.timeout_secs, self.config.timeout);
2190 let max_file_bytes = self.config.max_file_bytes;
2191 let req = chain_scan_request(&q, depth, self.config.max_gadgets);
2192 let spec = chain_spec(&q);
2193 if spec.target == "windows-virtualprotect" {
2198 rf_api::win_opts(&spec).map_err(scan_err_to_tool)?;
2199 } else {
2200 rf_api::linux_opts(&spec).map_err(scan_err_to_tool)?;
2201 }
2202
2203 let binary_label = label.clone();
2212 let offset_hex = q.offset.clone();
2213 let work =
2214 move |_cancel: rf_scan::CancelToken| -> Result<(ChainResponse, ScanFacts), ToolError> {
2215 let bytes = confined.read_all(max_file_bytes)?;
2216 let file_hash = sha256_hex(&bytes);
2217 let outcome =
2218 rf_api::chain_bytes(&bytes, None, &req, &spec).map_err(scan_err_to_tool)?;
2219 let offset = match &offset_hex {
2220 Some(o) => rf_api::parse_hex(o, "--offset")
2221 .map_err(|e| ToolError::new(ErrorCode::UsageError, e))?,
2222 None => 0,
2223 };
2224 let facts = ScanFacts {
2225 sha256: file_hash.clone(),
2226 bytes_read: bytes.len() as u64,
2227 cache: "bypass",
2228 total_count: outcome.chain.words.len() as u64,
2229 returned: outcome.chain.words.len() as u64,
2230 };
2231 let out = chain_response(&outcome, file_hash, binary_label, offset);
2232 Ok((out, facts))
2233 };
2234
2235 match self
2236 .guard
2237 .run(Some(Self::cancel_signal(ctx)), timeout, work)
2238 .await
2239 {
2240 Ok((v, facts)) => {
2241 facts.apply(rec);
2242 self.stats.add_bytes_read(facts.bytes_read);
2243 Ok(v)
2244 }
2245 Err(e) => Err(e),
2246 }
2247 }
2248
2249 async fn run_plan(
2254 &self,
2255 ctx: &RequestContext<RoleServer>,
2256 rec: &mut AuditRecord,
2257 q: ChainQuery,
2258 ) -> Result<schema::PlanResponse, ToolError> {
2259 if !rf_api::chain_targets().contains(&q.target.as_str()) {
2260 return Err(ToolError::new(
2261 ErrorCode::UsageError,
2262 format!(
2263 "unknown chain target {:?}; supported: {}",
2264 q.target,
2265 rf_api::chain_targets().join(", ")
2266 ),
2267 ));
2268 }
2269 let depth = self.check_depth(q.depth)?;
2270 rec.binary = Some(q.binary_path.clone());
2271 let confined = self.open_confined(&q.binary_path)?;
2272 rec.binary = Some(confined.label.clone());
2273 let label = confined.label.clone();
2274 let timeout = clamp_timeout(q.timeout_secs, self.config.timeout);
2275 let max_file_bytes = self.config.max_file_bytes;
2276 let req = chain_scan_request(&q, depth, self.config.max_gadgets);
2277 let spec = chain_spec(&q);
2278 if spec.target == "windows-virtualprotect" {
2279 rf_api::win_opts(&spec).map_err(scan_err_to_tool)?;
2280 } else {
2281 rf_api::linux_opts(&spec).map_err(scan_err_to_tool)?;
2282 }
2283 let binary_label = label.clone();
2284 let offset_hex = q.offset.clone();
2285 let work = move |_cancel: rf_scan::CancelToken| -> Result<
2286 (schema::PlanResponse, ScanFacts),
2287 ToolError,
2288 > {
2289 let bytes = confined.read_all(max_file_bytes)?;
2290 let file_hash = sha256_hex(&bytes);
2291 let offset = match &offset_hex {
2292 Some(o) => rf_api::parse_hex(o, "--offset")
2293 .map_err(|e| ToolError::new(ErrorCode::UsageError, e))?,
2294 None => 0,
2295 };
2296 let outcome =
2297 rf_api::plan_chain_bytes(&bytes, None, &req, &spec).map_err(scan_err_to_tool)?;
2298 let out = plan_response(&outcome, file_hash.clone(), binary_label, offset);
2299 let facts = ScanFacts {
2300 sha256: file_hash,
2301 bytes_read: bytes.len() as u64,
2302 cache: "bypass",
2303 total_count: out.requirements.len() as u64,
2304 returned: out.satisfied_requirements.len() as u64,
2305 };
2306 Ok((out, facts))
2307 };
2308 match self
2309 .guard
2310 .run(Some(Self::cancel_signal(ctx)), timeout, work)
2311 .await
2312 {
2313 Ok((v, facts)) => {
2314 facts.apply(rec);
2315 self.stats.add_bytes_read(facts.bytes_read);
2316 Ok(v)
2317 }
2318 Err(e) => Err(e),
2319 }
2320 }
2321}
2322
2323struct ScanFacts {
2326 sha256: String,
2327 bytes_read: u64,
2328 cache: &'static str,
2329 total_count: u64,
2330 returned: u64,
2331}
2332
2333impl ScanFacts {
2334 fn apply(&self, rec: &mut AuditRecord) {
2335 rec.binary_sha256 = Some(self.sha256.clone());
2336 rec.bytes_read = self.bytes_read;
2337 rec.cache = Some(self.cache);
2338 rec.total_count = Some(self.total_count);
2339 rec.returned = Some(self.returned);
2340 }
2341}
2342
2343fn truncate_info(
2351 v: &mut Value,
2352 max_sections: usize,
2353 max_imports: usize,
2354 max_symbols: usize,
2355) -> Vec<Warning> {
2356 let mut warnings = Vec::new();
2357 let Some(obj) = v.as_object_mut() else {
2358 return warnings;
2359 };
2360 for (field, cap, code) in [
2361 ("sections", max_sections, "sections_truncated"),
2362 ("imports", max_imports, "imports_truncated"),
2363 ("symbols", max_symbols, "symbols_truncated"),
2366 ] {
2367 let Some(Value::Array(a)) = obj.get_mut(field) else {
2368 continue;
2369 };
2370 let total = a.len();
2371 if total > cap {
2372 a.truncate(cap);
2373 let mut w = Warning::truncation(code, field, cap, total);
2374 if field == "symbols" {
2375 w.detail = Some(
2380 "symbols are opt-in: pass max_symbols (up to 4096) to include them. `imports` (the SHN_UNDEF subset, with GOT/PLT) is reported regardless."
2381 .to_string(),
2382 );
2383 }
2384 warnings.push(w);
2385 }
2386 }
2387 warnings
2388}
2389
2390fn clone_query(q: &ChainQuery) -> ChainQuery {
2396 ChainQuery {
2397 binary_path: q.binary_path.clone(),
2398 target: q.target.clone(),
2399 depth: q.depth,
2400 base: q.base.clone(),
2401 offset: q.offset.clone(),
2402 badbytes: q.badbytes.clone(),
2403 cfg_aware: q.cfg_aware,
2404 api_addr: q.api_addr.clone(),
2405 api_name: q.api_name.clone(),
2406 shellcode_addr: q.shellcode_addr.clone(),
2407 shellcode_size: q.shellcode_size.clone(),
2408 chain_base: q.chain_base.clone(),
2409 prot: q.prot.clone(),
2410 syscall: q.syscall.clone(),
2411 syscall_args: q.syscall_args.clone(),
2412 chain_pivot: q.chain_pivot.clone(),
2413 stage: q.stage.clone(),
2414 arch: q.arch.clone(),
2415 timeout_secs: q.timeout_secs,
2416 }
2417}
2418
2419fn chain_scan_request(
2423 q: &ChainQuery,
2424 depth: usize,
2425 max_gadgets: Option<usize>,
2426) -> rf_api::ScanRequest {
2427 rf_api::ScanRequest {
2428 depth,
2429 rop: true,
2430 jop: true,
2431 sys: true,
2432 multibr: false,
2433 only: None,
2434 filter: None,
2435 range: None,
2436 badbytes: q.badbytes.clone(),
2437 offset: q.offset.clone(),
2438 base: q.base.clone(),
2439 section: Vec::new(),
2440 thumb: false,
2441 cfg_aware: q.cfg_aware.unwrap_or(false),
2442 align: None,
2443 call_preceded: false,
2444 all: false,
2445 noinstr: false,
2446 arch: q.arch.clone(),
2447 max_gadgets,
2448 max_memory: None,
2449 compat: false,
2450 }
2451}
2452
2453fn chain_spec(q: &ChainQuery) -> rf_api::ChainSpec {
2457 rf_api::ChainSpec {
2458 target: q.target.clone(),
2459 api_addr: q.api_addr.clone(),
2460 api_name: q.api_name.clone(),
2461 shellcode_addr: q.shellcode_addr.clone(),
2462 shellcode_size: q.shellcode_size.clone(),
2463 chain_base: q.chain_base.clone(),
2464 prot: q.prot.clone(),
2465 syscall: q.syscall.clone(),
2466 syscall_args: q.syscall_args.clone(),
2467 pivot: q.chain_pivot.clone(),
2468 stage: q.stage.clone(),
2469 }
2470}
2471
2472fn plan_response(
2475 outcome: &rf_api::ChainPlanOutcome,
2476 binary_sha256: String,
2477 binary_label: String,
2478 offset: u64,
2479) -> schema::PlanResponse {
2480 let mut plan = outcome.plan.clone();
2481 let sha = binary_sha256.clone();
2482 plan.attach_gadget_ids(|vaddr| {
2483 outcome
2484 .gadget_bytes(vaddr)
2485 .map(|b| schema::gadget_id(&sha, vaddr.wrapping_sub(offset), b))
2486 });
2487 schema::PlanResponse::from_plan(&plan, binary_sha256, binary_label)
2488}
2489
2490fn chain_response(
2498 outcome: &rf_api::ChainOutcome,
2499 binary_sha256: String,
2500 binary_label: String,
2501 offset: u64,
2502) -> ChainResponse {
2503 let chain = &outcome.chain;
2504 let by_vaddr: std::collections::HashMap<u64, &[u8]> = outcome
2505 .outcome
2506 .result
2507 .gadgets
2508 .iter()
2509 .map(|g| (g.vaddr, g.bytes.as_slice()))
2510 .collect();
2511 let gadgets = chain
2512 .gadgets
2513 .iter()
2514 .map(|g| schema::ChainGadgetRef {
2515 vaddr: format!("0x{:x}", g.vaddr),
2516 vaddr_u64: g.vaddr,
2517 text: g.text.clone(),
2518 id: by_vaddr
2519 .get(&g.vaddr)
2520 .map(|b| schema::gadget_id(&binary_sha256, g.vaddr.wrapping_sub(offset), b)),
2521 })
2522 .collect();
2523 let words = chain
2524 .words
2525 .iter()
2526 .map(|w| schema::ChainWordRecord {
2527 value: format!("0x{:x}", w.value),
2528 kind: match w.kind {
2529 rf_chain::WordKind::GadgetAddr => "gadget_addr",
2530 rf_chain::WordKind::Immediate => "immediate",
2531 rf_chain::WordKind::DataAddr => "data_addr",
2532 rf_chain::WordKind::CodeAddr => "code_addr",
2533 rf_chain::WordKind::Padding => "padding",
2534 }
2535 .to_string(),
2536 comment: w.comment.clone(),
2537 source_gadget: w.source_gadget.map(|i| i as u64),
2538 })
2539 .collect();
2540 ChainResponse {
2541 assumptions: outcome
2542 .assumptions
2543 .as_ref()
2544 .map(|a| schema::ChainAssumptions {
2545 api_name: a.api_name.clone(),
2546 pivot_addr: a.pivot_addr.map(|v| format!("0x{v:x}")),
2547 pivot_words: a.pivot_words as u64,
2548 chain_base_parity: a.chain_base_parity.to_string(),
2549 chain_base_mod16: a.chain_base_mod16,
2550 shellcode_addr: format!("0x{:x}", a.shellcode_addr),
2551 old_protect_addr: a.old_protect_addr.map(|v| format!("0x{v:x}")),
2552 }),
2553 chain: schema::ChainIr {
2554 arch: chain.arch.clone(),
2555 description: chain.description.clone(),
2556 script_comment: chain.script_comment.clone(),
2557 word_size: chain.word_size as u64,
2558 words,
2559 gadgets,
2560 },
2561 python: chain.to_python(),
2562 arch: chain.arch.clone(),
2563 description: chain.description.clone(),
2564 word_count: chain.words.len() as u64,
2565 binary_sha256,
2566 binary_label,
2567 warnings: Vec::new(),
2568 }
2569}
2570
2571fn params_hash<T: serde::Serialize>(q: &T) -> String {
2575 let mut v = serde_json::to_value(q).unwrap_or(Value::Null);
2576 if let Some(o) = v.as_object_mut() {
2577 o.remove("binary_path");
2578 }
2579 sha256_hex(v.to_string().as_bytes())
2580}
2581
2582fn scan_err_to_tool(e: rf_api::ScanError) -> ToolError {
2589 match e {
2590 rf_api::ScanError::Usage(m) => ToolError::new(ErrorCode::UsageError, m),
2591 rf_api::ScanError::Binary(m) => {
2592 ToolError::new(ErrorCode::UnsupportedBinary, m).with_kind("binary_error")
2593 }
2594 rf_api::ScanError::Chain(m) => {
2595 ToolError::with_details(ErrorCode::NotFound, m, json!({"what": "chain_gadget"}))
2596 .with_kind("chain_error")
2597 }
2598 }
2599}
2600
2601fn usage_flag(message: String) -> ToolError {
2604 ToolError::new(ErrorCode::UsageError, message).with_kind("invalid_flag")
2605}
2606
2607fn tool_error(err: ToolError) -> Result<CallToolResult, McpError> {
2608 let body = err.to_json();
2609 let mut r = CallToolResult::error(vec![ContentBlock::text(body.to_string())]);
2610 r.structured_content = Some(body);
2611 Ok(r)
2612}
2613
2614fn tool_ok<T: Serialize>(value: &T) -> Result<CallToolResult, McpError> {
2619 let Ok(v) = serde_json::to_value(value) else {
2620 return tool_error(ToolError::new(
2621 ErrorCode::Internal,
2622 "the response could not be serialized",
2623 ));
2624 };
2625 let mut r = CallToolResult::success(vec![ContentBlock::text(v.to_string())]);
2626 r.structured_content = Some(v);
2627 Ok(r)
2628}
2629
2630#[tool_router]
2631impl RopFinderMcp {
2632 #[tool(
2634 description = "Find ROP gadgets in a binary (ret-terminated). Results are RANKED by \
2635 default (order=\"rank\": usability tier, then quality, then fewest instructions, then \
2636 fewest side effects, then address), so the first page is the useful gadgets rather \
2637 than the alphabetical head; order=\"address\"|\"quality\"|\"text\" are also accepted. \
2638 Every record carries a stable id, the classification (class, labels, regs_written, \
2639 regs_read, regs_from_stack, side_effects, terminator, usability) and delay_slot. \
2640 Filter server-side with class/label/writes_reg/reads_reg/preserves_regs/from_stack/\
2641 terminator/max_side_effects/max_insns instead of pulling gadgets into context. Page \
2642 with next_cursor. binary_path must be an absolute path inside one of the server's \
2643 allow_roots (call get_server_config to list them); anything else returns path_denied. \
2644 depth above max_depth is rejected, not clamped. A request that exceeds timeout_secs is \
2645 STOPPED, not orphaned, and notifications/cancelled stops it too.",
2646 output_schema = crate::schema::scan_output_schema()
2647 )]
2648 async fn find_gadgets(
2649 &self,
2650 Parameters(q): Parameters<GadgetQuery>,
2651 ctx: RequestContext<RoleServer>,
2652 ) -> Result<CallToolResult, McpError> {
2653 let (mut rec, t0) = self.begin(&ctx, "find_gadgets", params_hash(&q));
2654 let out = self
2655 .gadget_scan(&ctx, &mut rec, &q, true, false, false)
2656 .await;
2657 self.finish(rec, t0, out).await
2658 }
2659
2660 #[tool(
2662 description = "Find JOP gadgets in a binary (jmp/call-terminated). Same parameters, \
2663 ranking, filters, cursor and caps as find_gadgets.",
2664 output_schema = crate::schema::scan_output_schema()
2665 )]
2666 async fn find_jop_gadgets(
2667 &self,
2668 Parameters(q): Parameters<GadgetQuery>,
2669 ctx: RequestContext<RoleServer>,
2670 ) -> Result<CallToolResult, McpError> {
2671 let (mut rec, t0) = self.begin(&ctx, "find_jop_gadgets", params_hash(&q));
2672 let out = self
2673 .gadget_scan(&ctx, &mut rec, &q, false, true, false)
2674 .await;
2675 self.finish(rec, t0, out).await
2676 }
2677
2678 #[tool(
2680 description = "Find SYS gadgets in a binary (syscall/sysenter/int). Same parameters, \
2681 ranking, filters, cursor and caps as find_gadgets.",
2682 output_schema = crate::schema::scan_output_schema()
2683 )]
2684 async fn find_syscall_gadgets(
2685 &self,
2686 Parameters(q): Parameters<GadgetQuery>,
2687 ctx: RequestContext<RoleServer>,
2688 ) -> Result<CallToolResult, McpError> {
2689 let (mut rec, t0) = self.begin(&ctx, "find_syscall_gadgets", params_hash(&q));
2690 let out = self
2691 .gadget_scan(&ctx, &mut rec, &q, false, false, true)
2692 .await;
2693 self.finish(rec, t0, out).await
2694 }
2695
2696 #[tool(
2698 description = "Find gadgets by their EFFECT, not their text: \"set rdi from the stack, \
2699 preserve rsi and rdx, at most one side effect, a clean ret\" is one call. Constraints: \
2700 set_reg (the register is written with a value YOUR PAYLOAD decides — stronger than \
2701 writes_reg, which `xor rdi, rdi` also satisfies), from_stack (that write must come off \
2702 the stack), no_clobber (matched against the classifier's `clobbers`, so `pop rdi` \
2703 survives no_clobber:[\"rdi\"] and `mov rdi, rax` does not), reads_reg, \
2704 max_stack_delta (net rsp movement, terminator included; a gadget whose delta is UNKNOWN \
2705 is rejected, never assumed 0), max_side_effects, max_insns, terminator \
2706 (ret|jmp|call|syscall|none|any, or the finer bare-ret|ret-imm|jmp-reg|jmp-mem|call-reg|call-mem|\
2707 far|other), search (ropper-style wildcards over the instruction sequence, e.g. \
2708 \"pop rdi; ret\"; `?` is one character, `%` any run), pivot (the stack-pivot preset), \
2709 plus class/label/writes_reg/preserves_regs. Scans ROP+JOP+SYS together, so `terminator` \
2710 chooses the family. EVERY result carries an `explanation` object — sets, reads, \
2711 clobbers, stack_delta, terminator and a one-line `why` — so a choice can be justified \
2712 without re-deriving semantics from gadget text. Ranked, paged with next_cursor, and a \
2713 paged result names an NDJSON resource with the whole set.",
2714 output_schema = crate::schema::scan_output_schema()
2715 )]
2716 async fn find_gadgets_by_effect(
2717 &self,
2718 Parameters(q): Parameters<EffectQuery>,
2719 ctx: RequestContext<RoleServer>,
2720 ) -> Result<CallToolResult, McpError> {
2721 let (mut rec, t0) = self.begin(&ctx, "find_gadgets_by_effect", params_hash(&q));
2722 let out = async {
2723 let depth = self.check_depth(q.depth)?;
2724 let req = rf_api::ScanRequest {
2725 depth,
2726 rop: true,
2731 jop: true,
2732 sys: true,
2733 multibr: false,
2734 only: None,
2735 filter: None,
2736 range: q.range.clone(),
2737 badbytes: q.badbytes.clone(),
2738 offset: q.offset.clone(),
2739 base: q.base.clone(),
2740 section: split_sections(q.section.as_deref()),
2741 thumb: false,
2742 cfg_aware: false,
2743 align: None,
2744 call_preceded: false,
2745 all: false,
2746 noinstr: false,
2747 arch: q.arch.clone(),
2748 max_gadgets: None,
2749 max_memory: None,
2750 compat: false,
2751 };
2752 let filter = GadgetFilter::parse(&raw_filter!(q))?;
2753 if filter.is_empty() {
2754 return Err(ToolError::with_details(
2755 ErrorCode::UsageError,
2756 "find_gadgets_by_effect was given no constraint; it would return the whole \
2757 scan. Pass at least one of set_reg, from_stack, no_clobber, reads_reg, \
2758 writes_reg, preserves_regs, max_stack_delta, max_side_effects, max_insns, \
2759 terminator, search, pivot, class or label — or call find_gadgets if an \
2760 unfiltered ranked list is what you want",
2761 json!({"parameter": "set_reg"}),
2762 ));
2763 }
2764 self.run_scan(
2765 &ctx,
2766 &mut rec,
2767 req,
2768 &q.binary_path,
2769 PostOpts {
2770 order: Order::parse(q.order.as_deref().unwrap_or("rank"))?,
2771 filter,
2772 cursor: q.cursor.clone(),
2773 params_hash: cursor::params_fingerprint(&q),
2774 max_results: q.max_results,
2775 timeout_secs: q.timeout_secs,
2776 ..Default::default()
2777 },
2778 )
2779 .await
2780 }
2781 .await;
2782 self.finish(rec, t0, out).await
2783 }
2784
2785 #[tool(
2787 description = "Find a string in the binary's MAPPED DATA sections — where \"/bin/sh\" \
2788 lives, and at what address. `string` is a BYTE regex (ROPgadget's --string semantics), \
2789 so \"/bin/sh\" is a literal and \"m..n\" matches four bytes. Set memstr:true for \
2790 ROPgadget's --memstr instead: each CHARACTER is located separately and only its first \
2791 occurrence is reported, searching executable sections before data ones, which is how \
2792 you assemble a string the binary does not contain contiguously. Each hit gives vaddr, \
2793 section, length, an escaped preview, the raw hex, and whether the section is writable \
2794 and executable — `writable` is what tells you an address is usable as scratch space. \
2795 SCOPE, and it is enforced rather than promised: only bytes inside sections the loader \
2796 MAPS are ever examined. There is no file-offset mode; headers, symbol and string \
2797 tables and debug data are unreachable because they are in no mapped section, and \
2798 `range` can only narrow the windows. `sections_searched` in the response names exactly \
2799 what was read. Paged with next_cursor; a paged result also names an NDJSON resource.",
2800 output_schema = crate::schema::search_output_schema()
2801 )]
2802 async fn find_string(
2803 &self,
2804 Parameters(q): Parameters<StringQuery>,
2805 ctx: RequestContext<RoleServer>,
2806 ) -> Result<CallToolResult, McpError> {
2807 let (mut rec, t0) = self.begin(&ctx, "find_string", params_hash(&q));
2808 let params_fp = cursor::params_fingerprint(&q);
2809 let mode = if q.memstr.unwrap_or(false) {
2810 find::Mode::MemStr
2811 } else {
2812 find::Mode::String
2813 };
2814 let out = self
2815 .run_find(
2816 &ctx,
2817 &mut rec,
2818 FindRequest {
2819 binary_path: q.binary_path.clone(),
2820 mode,
2821 query: q.string.clone(),
2822 base: q.base.clone(),
2823 offset: q.offset.clone(),
2824 range: q.range.clone(),
2825 arch: q.arch.clone(),
2826 max_results: q.max_results,
2827 cursor: q.cursor.clone(),
2828 params_hash: params_fp,
2829 timeout_secs: q.timeout_secs,
2830 },
2831 )
2832 .await;
2833 self.finish(rec, t0, out).await
2834 }
2835
2836 #[tool(
2838 description = "Find a byte sequence in the binary's MAPPED EXECUTABLE regions — the \
2839 same regions find_gadgets walks. `opcode` is hex (\"c9c3\", or \"c9 c3\"), and `??` \
2840 matches any one byte, so \"ff??e0\" finds `jmp rax` through `jmp r15`. A one-nibble \
2841 wildcard is refused rather than silently widened. Each hit gives vaddr, section, \
2842 length, an escaped preview, the raw hex and the section's writable/executable flags. \
2843 SCOPE: only bytes inside mapped executable sections are examined — there is no \
2844 file-offset mode and nothing outside a section is reachable; `sections_searched` names \
2845 exactly what was read, and `range` can only narrow it. Paged with next_cursor; a paged \
2846 result also names an NDJSON resource with the whole match set.",
2847 output_schema = crate::schema::search_output_schema()
2848 )]
2849 async fn find_bytes(
2850 &self,
2851 Parameters(q): Parameters<BytesQuery>,
2852 ctx: RequestContext<RoleServer>,
2853 ) -> Result<CallToolResult, McpError> {
2854 let (mut rec, t0) = self.begin(&ctx, "find_bytes", params_hash(&q));
2855 let params_fp = cursor::params_fingerprint(&q);
2856 let out = self
2857 .run_find(
2858 &ctx,
2859 &mut rec,
2860 FindRequest {
2861 binary_path: q.binary_path.clone(),
2862 mode: find::Mode::Opcode,
2863 query: q.opcode.clone(),
2864 base: q.base.clone(),
2865 offset: q.offset.clone(),
2866 range: q.range.clone(),
2867 arch: q.arch.clone(),
2868 max_results: q.max_results,
2869 cursor: q.cursor.clone(),
2870 params_hash: params_fp,
2871 timeout_secs: q.timeout_secs,
2872 },
2873 )
2874 .await;
2875 self.finish(rec, t0, out).await
2876 }
2877
2878 #[tool(
2880 description = "Report the binary's exploit mitigations, so an agent can decide whether \
2881 ROP is even the right technique before it scans. ELF: nx (PT_GNU_STACK), pie \
2882 (ET_DYN + DF_1_PIE/PT_INTERP/DT_DEBUG, distinguishing a PIE executable from a shared \
2883 object), relro, canary, fortify, rpath, runpath. PE: aslr, dep, high_entropy_va, \
2884 guard_cf and cet_compat as SEPARATE answers read from separate directories (CFG \
2885 validates indirect CALL targets and does NOT check a ret; only cet_compat means a \
2886 shadow stack), safe_seh, force_integrity. Mach-O: pie, nx_stack, nx_heap, \
2887 code_signature, hardened_runtime — per SLICE for a fat container, in `slices`, because \
2888 the slices genuinely disagree. Every entry is {name, enabled, evidence, detail} where \
2889 `enabled` is true, false, or the string \"unknown\" — never false standing in for \
2890 \"could not tell\" — and `evidence` names the header field that decided it, or the \
2891 one whose absence made it unknown. The order is the loader's and is meaningful; `name` \
2892 is the stable key. No scan is performed.",
2893 output_schema = crate::schema::mitigations_output_schema()
2894 )]
2895 async fn get_mitigations(
2896 &self,
2897 Parameters(q): Parameters<MitigationsQuery>,
2898 ctx: RequestContext<RoleServer>,
2899 ) -> Result<CallToolResult, McpError> {
2900 let (mut rec, t0) = self.begin(&ctx, "get_mitigations", params_hash(&q));
2901 let out = self.run_mitigations(&ctx, &mut rec, &q).await;
2902 self.finish(rec, t0, out).await
2903 }
2904
2905 #[tool(
2907 description = "Resolve stable gadget ids (the `id` field of any gadget record, e.g. \
2908 \"g_ab12cd34ef56gh78\") back to full records, so a plan can name gadgets instead of \
2909 re-sending their text. Rescans the binary at `depth` (default 10) and matches by id; \
2910 an id is independent of every scan parameter except `base`, so pass the same `base` \
2911 the ids came from. Ids that do not resolve are reported in warnings.ids_not_found \
2912 rather than failing the call. Results are returned in the order the ids were given.",
2913 output_schema = crate::schema::scan_output_schema()
2914 )]
2915 async fn get_gadgets(
2916 &self,
2917 Parameters(q): Parameters<IdsQuery>,
2918 ctx: RequestContext<RoleServer>,
2919 ) -> Result<CallToolResult, McpError> {
2920 let (mut rec, t0) = self.begin(&ctx, "get_gadgets", params_hash(&q));
2921 let out = async {
2922 if q.ids.is_empty() {
2923 return Err(ToolError::new(
2924 ErrorCode::UsageError,
2925 "ids must not be empty; pass the `id` field of gadgets you already have",
2926 ));
2927 }
2928 let depth = self.check_depth(q.depth)?;
2929 let req = rf_api::ScanRequest {
2930 depth,
2931 rop: true,
2932 jop: true,
2933 sys: true,
2934 multibr: false,
2935 only: None,
2936 filter: None,
2937 range: None,
2938 badbytes: None,
2939 offset: q.offset.clone(),
2940 base: q.base.clone(),
2941 section: split_sections(q.section.as_deref()),
2942 thumb: false,
2943 cfg_aware: false,
2944 align: None,
2945 call_preceded: false,
2946 all: false,
2947 noinstr: false,
2948 arch: q.arch.clone(),
2949 max_gadgets: None,
2950 max_memory: None,
2951 compat: false,
2952 };
2953 self.run_scan(
2954 &ctx,
2955 &mut rec,
2956 req,
2957 &q.binary_path,
2958 PostOpts {
2959 order: Order::Ids,
2960 ids: Some(q.ids.clone()),
2961 params_hash: cursor::params_fingerprint(&q),
2962 max_results: Some(q.ids.len().clamp(1, HARD_MAX_RESULTS)),
2963 timeout_secs: q.timeout_secs,
2964 ..Default::default()
2965 },
2966 )
2967 .await
2968 }
2969 .await;
2970 self.finish(rec, t0, out).await
2971 }
2972
2973 #[tool(
2975 description = "Get binary metadata as JSON: format, arch, endianness, addr_size, \
2976 image_base, entry, sections (name/vaddr/size/executable/writable), PE imports \
2977 (iat_vaddr is the IAT slot the loader patches; hint_name_vaddr is the \
2978 IMAGE_IMPORT_BY_NAME record; an ELF import instead carries addr/got/plt/type/binding, which is what a ret2plt chain resolves against), the ELF symbol table (`symbols`, OPT-IN: pass max_symbols to get it; symbol_count is always the true total, and null means this format's symbols are not read at all), fat Mach-O slices, binary_sha256 and warnings. The \
2979 shape is fixed: an ELF reports slices: [] and a fat Mach-O reports sections: []. Exploit \
2980 mitigations are NOT here: call get_mitigations, which types them and keeps the loader's \
2981 order. No scan is performed. Bounded like every other tool: timeout_secs (default 60), \
2982 --max-file-bytes, and max_sections/max_imports (default 4096 each) and max_symbols (default 0, max 4096) — a truncated \
2983 array is announced in warnings, never silently short.",
2984 output_schema = crate::schema::info_output_schema()
2985 )]
2986 async fn get_binary_info(
2987 &self,
2988 Parameters(q): Parameters<InfoQuery>,
2989 ctx: RequestContext<RoleServer>,
2990 ) -> Result<CallToolResult, McpError> {
2991 let (mut rec, t0) = self.begin(&ctx, "get_binary_info", params_hash(&q));
2992 let out = self.run_info(&ctx, &mut rec, &q).await;
2993 self.finish(rec, t0, out).await
2994 }
2995
2996 #[tool(
2998 description = "Report the server's effective configuration: allow_roots (the only \
2999 directories binary_path may name), max_depth, max_file_bytes, max_results, \
3000 max_concurrent, scan_threads, max_gadgets, timeout_secs, cursor_ttl_secs, whether an \
3001 on-disk cache and a workspace directory are enabled, the complete list of `order` \
3002 values, the complete list of error codes, and the server version. Call this first: \
3003 paths outside allow_roots are refused with a single path_denied code that \
3004 deliberately reveals nothing about the target, and a run of refusals is treated as \
3005 filesystem probing.",
3006 output_schema = crate::schema::config_output_schema()
3007 )]
3008 async fn get_server_config(
3009 &self,
3010 ctx: RequestContext<RoleServer>,
3011 ) -> Result<CallToolResult, McpError> {
3012 let (rec, t0) = self.begin(&ctx, "get_server_config", String::new());
3013 let out = Ok(self.config_response());
3014 self.finish(rec, t0, out).await
3015 }
3016
3017 #[tool(
3019 description = "Report this session's counters: requests_total and requests_by_tool, \
3020 ok/denied/timeout/cancelled/error totals, denied_consecutive and probing_suspected \
3021 (a run of path_denied results is the signal that an agent is enumerating the \
3022 filesystem), wedged_total (workers that did not stop within 5 s of being \
3023 cancelled), busy_total, inflight, bytes_read_total, and the cache's \
3024 hit/miss/eviction/tamper counters with its live cache_bytes against \
3025 cache_mem_max_bytes.",
3026 output_schema = crate::schema::stats_output_schema()
3027 )]
3028 async fn get_server_stats(
3029 &self,
3030 ctx: RequestContext<RoleServer>,
3031 ) -> Result<CallToolResult, McpError> {
3032 let (rec, t0) = self.begin(&ctx, "get_server_stats", String::new());
3033 let out = self.stats_response();
3034 self.finish(rec, t0, out).await
3035 }
3036
3037 #[tool(
3039 description = "Search gadgets by pattern: regex matched against gadget text \
3040 (e.g. \"pop r.*; ret\"); invalid regexes fall back to literal substring match. Runs a \
3041 full ROP+JOP+SYS scan, then filters. Same ranking, semantic filters, cursor and caps \
3042 as find_gadgets.",
3043 output_schema = crate::schema::scan_output_schema()
3044 )]
3045 async fn search_gadgets_by_pattern(
3046 &self,
3047 Parameters(q): Parameters<SearchQuery>,
3048 ctx: RequestContext<RoleServer>,
3049 ) -> Result<CallToolResult, McpError> {
3050 let (mut rec, t0) = self.begin(&ctx, "search_gadgets_by_pattern", params_hash(&q));
3051 let out = async {
3052 let depth = self.check_depth(q.depth)?;
3053 let req = rf_api::ScanRequest {
3054 depth,
3055 rop: true,
3056 jop: true,
3057 sys: true,
3058 multibr: false,
3059 only: None,
3060 filter: None,
3061 range: q.range.clone(),
3062 badbytes: q.badbytes.clone(),
3063 offset: q.offset.clone(),
3064 base: q.base.clone(),
3065 section: split_sections(q.section.as_deref()),
3066 thumb: false,
3067 cfg_aware: false,
3068 align: None,
3069 call_preceded: false,
3070 all: false,
3071 noinstr: false,
3072 arch: q.arch.clone(),
3073 max_gadgets: None,
3074 max_memory: None,
3075 compat: false,
3076 };
3077 self.run_scan(
3078 &ctx,
3079 &mut rec,
3080 req,
3081 &q.binary_path,
3082 PostOpts {
3083 re: Some(q.pattern.clone()),
3084 order: Order::parse(q.order.as_deref().unwrap_or("rank"))?,
3085 filter: GadgetFilter::parse(&raw_filter!(q))?,
3086 cursor: q.cursor.clone(),
3087 params_hash: cursor::params_fingerprint(&q),
3088 max_results: q.max_results,
3089 timeout_secs: q.timeout_secs,
3090 ids: None,
3091 },
3092 )
3093 .await
3094 }
3095 .await;
3096 self.finish(rec, t0, out).await
3097 }
3098
3099 #[tool(
3101 description = "Build a ROP chain. target must be \"linux-execve\" (ELF x86/x64 only, \
3102 ported from ROPgadget's ropmaker: x86 int 0x80 / x64 syscall, \"/bin//sh\" written \
3103 to a writable section), \"linux-mprotect\" (the NX answer: page-aligns the region \
3104 and calls mprotect), \"linux-syscall\" (any syscall -- pass `syscall` and \
3105 `syscall_args`), \"linux-ret2libc\" (calls `api_addr` with \"/bin//sh\": SysV arg1 \
3106 in rdi on x64, cdecl stack argument on x86), \"linux-srop\" (x86-64: rt_sigreturn \
3107 plus a sigcontext frame, so only `pop rax` and a trap are needed) or \
3108 \"windows-virtualprotect\". Every one of those has been EXECUTED under the emulator \
3109 harness on a shipped fixture; call plan_chain first to find out whether THIS binary \
3110 can host the one you want. Returns the chain IR as JSON \
3111 (words with kinds gadget_addr / immediate / data_addr / code_addr / padding plus the \
3112 referenced gadget table, each entry carrying the same stable id find_gadgets \
3113 returns), the equivalent python exploit script, arch, description and word_count. A \
3114 binary that lacks a required gadget fails with not_found. Chain builds bypass the \
3115 gadget cache.",
3116 output_schema = crate::schema::chain_output_schema()
3117 )]
3118 async fn build_rop_chain(
3119 &self,
3120 Parameters(q): Parameters<ChainQuery>,
3121 ctx: RequestContext<RoleServer>,
3122 ) -> Result<CallToolResult, McpError> {
3123 let (mut rec, t0) = self.begin(&ctx, "build_rop_chain", params_hash(&q));
3124 let probe = ChainQuery { ..clone_query(&q) };
3125 let out = match self.run_chain(&ctx, &mut rec, q).await {
3126 Ok(v) => Ok(v),
3127 Err(e) if matches!(e.code, ErrorCode::NotFound | ErrorCode::UsageError) => {
3132 let mut probe_rec = rec.clone();
3133 let detail = self.run_plan(&ctx, &mut probe_rec, probe).await.ok();
3134 Err(match detail {
3135 Some(plan) => {
3136 let mut d = match e.details.clone() {
3140 Some(Value::Object(m)) => m,
3141 _ => serde_json::Map::new(),
3142 };
3143 d.insert(
3144 "plan".to_string(),
3145 serde_json::to_value(&plan).unwrap_or(Value::Null),
3146 );
3147 ToolError {
3148 details: Some(Value::Object(d)),
3149 ..e
3150 }
3151 }
3152 None => e,
3153 })
3154 }
3155 Err(e) => Err(e),
3156 };
3157 self.finish(rec, t0, out).await
3158 }
3159
3160 #[tool(
3162 description = "Ask whether this binary can host a ROP chain for `target`, and if not, exactly why. ALWAYS succeeds: infeasibility is a result. Returns {feasible, requirements[{id, description, satisfied, strategies_tried[{pattern, candidates}], relaxations[{param, from, to, would_help}]}], satisfied_requirements[{id, gadget_id, vaddr}], assumptions{chain_base_parity, write_target, needs_leak}}. Requirement ids are stable (set_rdx, write_primitive, api_transfer, syscall_trap, stack_align). `candidates` counts the gadgets the builder could actually USE for that strategy (clean-tailed, and modelled by the constraint layer), so 0 means the strategy had nothing to work with, while a non-zero count with satisfied:false means something else rejected them. `would_help` is MEASURED, not guessed: the server re-scans at double depth and with multibr and re-runs the same probe. Every gadget_id resolves through get_gadgets. build_rop_chain returns this same document in its error details when it refuses.",
3163 output_schema = crate::schema::plan_output_schema()
3164 )]
3165 async fn plan_chain(
3166 &self,
3167 Parameters(q): Parameters<ChainQuery>,
3168 ctx: RequestContext<RoleServer>,
3169 ) -> Result<CallToolResult, McpError> {
3170 let (mut rec, t0) = self.begin(&ctx, "plan_chain", params_hash(&q));
3171 let out = self.run_plan(&ctx, &mut rec, q).await;
3172 self.finish(rec, t0, out).await
3173 }
3174
3175 #[tool(
3177 description = "Run a ROPgadget-style scan with explicit flags. args is a list like \
3178 [\"--depth\", \"6\", \"--only\", \"pop|ret\"]. Allowlist: --depth --norop --nojop \
3179 --nosys --only --filter --re --range --section --base --offset --badbytes --align \
3180 --multibr --json --arch --all --callPreceded; anything else (--string, --dump, \
3181 --console, ...) is rejected. --align is ROPgadget's real scan-time alignment \
3182 (decimal, as in ROPgadget's argparse; write 0x.. only if you mean hex), not an \
3183 address post-filter. --arch names a fat Mach-O slice and is REQUIRED for a \
3184 multi-slice binary. The result is ordered, filtered and paged exactly like \
3185 find_gadgets.",
3186 output_schema = crate::schema::scan_output_schema()
3187 )]
3188 async fn run_ropgadget_command(
3189 &self,
3190 Parameters(q): Parameters<RawCommandQuery>,
3191 ctx: RequestContext<RoleServer>,
3192 ) -> Result<CallToolResult, McpError> {
3193 let (mut rec, t0) = self.begin(&ctx, "run_ropgadget_command", params_hash(&q));
3194 let out = async {
3195 let parsed = parse_ropgadget_args(&q.args)?;
3196 self.check_depth(Some(parsed.request.depth))?;
3199 self.run_scan(
3200 &ctx,
3201 &mut rec,
3202 parsed.request,
3203 &q.binary_path,
3204 PostOpts {
3205 re: parsed.re,
3206 order: Order::parse(q.order.as_deref().unwrap_or("rank"))?,
3207 filter: GadgetFilter::parse(&raw_filter!(q))?,
3208 cursor: q.cursor.clone(),
3209 params_hash: cursor::params_fingerprint(&q),
3210 max_results: q.max_results,
3211 timeout_secs: q.timeout_secs,
3212 ids: None,
3213 },
3214 )
3215 .await
3216 }
3217 .await;
3218 self.finish(rec, t0, out).await
3219 }
3220}
3221
3222impl RopFinderMcp {
3223 async fn gadget_scan(
3226 &self,
3227 ctx: &RequestContext<RoleServer>,
3228 rec: &mut AuditRecord,
3229 q: &GadgetQuery,
3230 rop: bool,
3231 jop: bool,
3232 sys: bool,
3233 ) -> Result<ScanResponse, ToolError> {
3234 let req = self.gadget_request(q, rop, jop, sys)?;
3235 let order = Order::parse(
3240 q.order
3241 .as_deref()
3242 .or(q.sort_by.as_deref())
3243 .unwrap_or("rank"),
3244 )?;
3245 let filter = GadgetFilter::parse(&raw_filter!(q))?;
3246 self.run_scan(
3247 ctx,
3248 rec,
3249 req,
3250 &q.binary_path,
3251 PostOpts {
3252 order,
3253 filter,
3254 cursor: q.cursor.clone(),
3255 params_hash: cursor::params_fingerprint(q),
3256 max_results: q.max_results,
3257 timeout_secs: q.timeout_secs,
3258 ..Default::default()
3259 },
3260 )
3261 .await
3262 }
3263
3264 fn stats_response(&self) -> Result<schema::StatsResponse, ToolError> {
3266 let v = self.stats.snapshot(self.cache.stats_json());
3267 serde_json::from_value(v).map_err(|e| {
3268 ToolError::new(
3269 ErrorCode::Internal,
3270 format!("the counters do not match the declared schema: {e}"),
3271 )
3272 })
3273 }
3274}
3275
3276#[allow(deprecated)]
3281#[tool_handler(name = "rop-finder-mcp", version = "1.0.0")]
3282impl ServerHandler for RopFinderMcp {
3283 fn get_info(&self) -> rmcp::model::ServerInfo {
3288 rmcp::model::ServerInfo::new(
3289 rmcp::model::ServerCapabilities::builder()
3290 .enable_tools()
3291 .enable_logging()
3297 .enable_resources()
3301 .build(),
3302 )
3303 .with_server_info(rmcp::model::Implementation::new(
3304 "rop-finder-mcp",
3305 env!("CARGO_PKG_VERSION"),
3306 ))
3307 .with_instructions(self.instructions())
3308 }
3309
3310 async fn set_level(
3313 &self,
3314 request: rmcp::model::SetLevelRequestParams,
3315 _ctx: RequestContext<RoleServer>,
3316 ) -> Result<(), McpError> {
3317 self.notifier.set_level(request.level);
3318 Ok(())
3319 }
3320
3321 async fn list_resources(
3327 &self,
3328 _request: Option<rmcp::model::PaginatedRequestParams>,
3329 _ctx: RequestContext<RoleServer>,
3330 ) -> Result<rmcp::model::ListResourcesResult, McpError> {
3331 let resources = self
3332 .cache
3333 .pinned_keys()
3334 .into_iter()
3335 .map(|(key, count)| {
3336 if key.starts_with('s') && !key.contains("--") {
3341 rmcp::model::Resource::new(resources::search_uri(&key), format!("search {key}"))
3342 .with_mime_type(resources::NDJSON_MIME)
3343 .with_description(format!(
3344 "{count} search hits, one JSON object per line, in address order"
3345 ))
3346 } else {
3347 rmcp::model::Resource::new(resources::scan_uri(&key), format!("scan {key}"))
3348 .with_mime_type(resources::NDJSON_MIME)
3349 .with_description(format!(
3350 "{count} gadget records, one JSON object per line, in rank order"
3351 ))
3352 }
3353 })
3354 .collect();
3355 Ok(rmcp::model::ListResourcesResult::with_all_items(resources))
3356 }
3357
3358 async fn read_resource(
3367 &self,
3368 request: rmcp::model::ReadResourceRequestParams,
3369 _ctx: RequestContext<RoleServer>,
3370 ) -> Result<rmcp::model::ReadResourceResponse, McpError> {
3371 let uri = request.uri.clone();
3372 let text = if let Some(key) = resources::search_key_of(&uri) {
3375 let Some(body) = self.cache.pinned_text(key) else {
3376 return Err(McpError::resource_not_found(
3377 "that search is no longer held; re-run it to get a fresh resource_uri",
3378 Some(json!({"uri": uri, "cursor_ttl_secs": self.config.cursor_ttl.as_secs()})),
3379 ));
3380 };
3381 body.to_string()
3382 } else {
3383 let Some(key) = resources::cache_key_of(&uri) else {
3384 return Err(McpError::resource_not_found(
3385 "not a rop-finder resource; the forms are \
3386 ropfinder://scan/<cache_key>/gadgets.ndjson and \
3387 ropfinder://search/<key>/hits.ndjson",
3388 Some(json!({"uri": uri})),
3389 ));
3390 };
3391 let Some(p) = self.cache.pinned(key) else {
3392 return Err(McpError::resource_not_found(
3393 "that scan is no longer held; re-run the scan to get a fresh resource_uri",
3394 Some(json!({"uri": uri, "cursor_ttl_secs": self.config.cursor_ttl.as_secs()})),
3395 ));
3396 };
3397 resources::render_ndjson(&p.scan, &p.sems)
3398 };
3399 Ok(rmcp::model::ReadResourceResult::new(vec![
3400 rmcp::model::ResourceContents::TextResourceContents {
3401 uri,
3402 mime_type: Some(resources::NDJSON_MIME.to_string()),
3403 text,
3404 meta: None,
3405 },
3406 ])
3407 .into())
3408 }
3409}
3410
3411impl RopFinderMcp {
3412 pub fn instructions(&self) -> String {
3415 let roots = self.root_paths();
3416 let allowed = if roots.is_empty() {
3417 "(none — every binary_path will be refused)".to_string()
3418 } else {
3419 roots.join(", ")
3420 };
3421 format!(
3422 "ROP/JOP/SYS gadget search via rop-finder, plus Linux execve ROP chain \
3423 generation (build_rop_chain, ELF x86/x64).\n\
3424 binary_path MUST be an absolute path inside one of these directories: {allowed}. \
3425 Anything else — including a path that merely starts with one of those strings, a \
3426 relative path, or one containing \"..\" — is refused with a single `path_denied` \
3427 code that deliberately reveals nothing about the target, so probing for files is \
3428 pointless. Call get_server_config for the machine-readable allowlist and caps.\n\
3429 Caps: depth <= {} (larger values are REJECTED, not clamped), binaries <= {} bytes, \
3430 max_results default {} (hard max {}), {} scan(s) at a time, default timeout {} s.\n\
3431 Gadget results are RANKED by default (order=\"rank\"), carry a stable `id` you can \
3432 pass back to get_gadgets, and are paged with `next_cursor`. Prefer the server-side \
3433 filters — class, label, writes_reg, reads_reg, preserves_regs, from_stack, \
3434 terminator, max_side_effects, max_insns, and v0.4's set_reg, no_clobber, \
3435 max_stack_delta, pivot and search — over reading gadgets to filter them \
3436 yourself. find_gadgets_by_effect takes all of them at once and returns an \
3437 `explanation` with every gadget. find_string and find_bytes locate strings and \
3438 byte sequences, and read ONLY bytes inside MAPPED sections — never a file offset. \
3439 get_mitigations is checksec: nx/pie/relro/canary or aslr/dep/guard_cf/cet_compat, \
3440 each with its evidence, and \"unknown\" where the file does not say. A paged scan \
3441 or search also names an NDJSON resource holding the whole set.\n\
3442 Every tool declares an outputSchema; every response has a FIXED field set, with \
3443 null rather than a missing key. Errors are {{error: {{code, message, retryable, \
3444 details, suggestion}}}} and `code` is one of: {}.",
3445 self.config.max_depth,
3446 self.config.max_file_bytes,
3447 self.config.max_results,
3448 HARD_MAX_RESULTS,
3449 self.config.max_concurrent,
3450 self.config.timeout.as_secs(),
3451 ErrorCode::all()
3452 .iter()
3453 .map(|c| c.as_str())
3454 .collect::<Vec<_>>()
3455 .join(", "),
3456 )
3457 }
3458}
3459
3460#[cfg(test)]
3461mod tests {
3462
3463 #![allow(clippy::indexing_slicing)]
3466
3467 use super::*;
3468
3469 #[test]
3475 fn tool_handler_version_literal_matches_the_crate_version() {
3476 assert_eq!(
3477 "1.0.0",
3478 env!("CARGO_PKG_VERSION"),
3479 "bump the version literal in #[tool_handler(...)] to match Cargo.toml"
3480 );
3481 }
3482
3483 struct TempDir(PathBuf);
3485 impl TempDir {
3486 fn new(tag: &str) -> Self {
3487 let raw =
3488 std::env::temp_dir().join(format!("rf-mcp-test-{}-{}", tag, std::process::id()));
3489 let _ = std::fs::remove_dir_all(&raw);
3490 std::fs::create_dir_all(&raw).unwrap();
3491 TempDir(raw.canonicalize().unwrap())
3492 }
3493 fn canon(&self) -> &PathBuf {
3494 &self.0
3495 }
3496 }
3497 impl Drop for TempDir {
3498 fn drop(&mut self) {
3499 let _ = std::fs::remove_dir_all(&self.0);
3500 }
3501 }
3502
3503 fn args(v: &[&str]) -> Vec<String> {
3504 v.iter().map(|s| s.to_string()).collect()
3505 }
3506
3507 #[test]
3516 fn align_is_parsed_as_decimal_first_hex_only_with_a_prefix() {
3517 assert_eq!(parse_align("16").unwrap(), 16);
3518 assert_eq!(parse_align("0x10").unwrap(), 16);
3519 assert_eq!(parse_align("0X10").unwrap(), 16);
3520 assert_eq!(parse_align(" 4 ").unwrap(), 4);
3521 assert_eq!(parse_align("10").unwrap(), 10);
3522 assert_eq!(parse_align("0").unwrap(), 0);
3523 for bad in ["", "0x", "-4", "abcd", "0xzz", "4.5"] {
3524 assert!(parse_align(bad).is_err(), "{bad:?} must not parse");
3525 }
3526 assert_eq!(rf_api::parse_hex("16", "x").unwrap(), 22);
3529 assert_ne!(parse_align("16").unwrap() as u64, 22);
3530 }
3531
3532 #[test]
3537 fn align_reaches_the_engine_not_a_post_filter() {
3538 let p = parse_ropgadget_args(&args(&["--align", "16"])).unwrap();
3539 assert_eq!(p.request.align, Some(16));
3540 let p = parse_ropgadget_args(&args(&["--align=4"])).unwrap();
3541 assert_eq!(p.request.align, Some(4));
3542 let e = parse_ropgadget_args(&args(&["--align", "nope"])).unwrap_err();
3544 assert_eq!(e.code, ErrorCode::UsageError);
3545 }
3546
3547 #[test]
3550 fn arch_all_and_call_preceded_are_allowlisted_and_plumbed() {
3551 let p =
3552 parse_ropgadget_args(&args(&["--arch", "arm64", "--all", "--callPreceded"])).unwrap();
3553 assert_eq!(p.request.arch.as_deref(), Some("arm64"));
3554 assert!(p.request.all);
3555 assert!(p.request.call_preceded);
3556 assert!(!p.request.compat);
3559 }
3560
3561 #[test]
3565 fn default_config_allows_nothing() {
3566 let c = ServerConfig::default();
3567 assert!(c.allow_dirs.is_empty());
3568 assert_eq!(c.max_depth, DEFAULT_MAX_DEPTH);
3569 assert_eq!(c.max_concurrent, DEFAULT_MAX_CONCURRENT);
3570 assert_eq!(c.max_file_bytes, DEFAULT_MAX_FILE_BYTES);
3571 assert!(!c.verbose_path_errors);
3572
3573 let server = RopFinderMcp::new(c).unwrap();
3574 assert!(server.root_paths().is_empty());
3575 let err = server.open_confined("/etc/shadow").unwrap_err();
3577 assert_eq!(err.code, ErrorCode::PathDenied);
3578 assert!(!err.message.contains("os error"), "{err:?}");
3579 }
3580
3581 #[test]
3584 fn depth_over_max_is_rejected_not_clamped() {
3585 let server = RopFinderMcp::new(ServerConfig::default()).unwrap();
3586 assert_eq!(server.check_depth(None).unwrap(), 10);
3587 assert_eq!(server.check_depth(Some(64)).unwrap(), 64);
3588 let err = server.check_depth(Some(100_000)).unwrap_err();
3589 assert_eq!(err.code, ErrorCode::UsageError);
3590 let d = err.details.expect("structured details");
3591 assert_eq!(d["limit"], "max_depth");
3592 assert_eq!(d["limit_value"], 64);
3593 assert_eq!(d["got"], 100_000);
3594 assert_eq!(
3596 server.check_depth(Some(usize::MAX)).unwrap_err().code,
3597 ErrorCode::UsageError
3598 );
3599 }
3600
3601 #[test]
3604 fn duplicate_roots_collapse() {
3605 let t = TempDir::new("dup-roots");
3606 let c = ServerConfig {
3607 allow_dirs: vec![t.canon().clone(), t.canon().clone()],
3608 ..Default::default()
3609 };
3610 let server = RopFinderMcp::new(c).unwrap();
3611 assert_eq!(server.root_paths().len(), 1);
3612 }
3613
3614 #[test]
3617 fn server_config_and_instructions_publish_the_allowlist() {
3618 let t = TempDir::new("publish");
3619 let c = ServerConfig {
3620 allow_dirs: vec![t.canon().clone()],
3621 ..Default::default()
3622 };
3623 let server = RopFinderMcp::new(c).unwrap();
3624 let cfg = serde_json::to_value(server.config_response()).unwrap();
3625 for key in [
3626 "allow_roots",
3627 "max_depth",
3628 "max_file_bytes",
3629 "max_results",
3630 "max_concurrent",
3631 "cache",
3632 "cursor_ttl_secs",
3633 "orders",
3634 "error_codes",
3635 "version",
3636 ] {
3637 assert!(cfg.get(key).is_some(), "missing {key} in {cfg}");
3638 }
3639 assert_eq!(cfg["allow_roots"].as_array().unwrap().len(), 1);
3640 assert_eq!(cfg["cache"], false);
3641 assert_eq!(cfg["orders"], json!(["rank", "address", "quality", "text"]));
3644 assert_eq!(cfg["error_codes"].as_array().unwrap().len(), 9);
3645 let root = server.root_paths()[0].clone();
3646 assert!(server.instructions().contains(&root));
3647 assert!(server.instructions().contains("get_server_config"));
3648 assert!(server.instructions().contains("cursor_expired"));
3649 }
3650
3651 #[test]
3652 fn allowlist_accepts_documented_flags() {
3653 let p = parse_ropgadget_args(&args(&[
3654 "--depth",
3655 "6",
3656 "--norop",
3657 "--nojop",
3658 "--nosys",
3659 "--multibr",
3660 "--json",
3661 "--only",
3662 "pop|ret",
3663 "--filter",
3664 "leave",
3665 "--re",
3666 "pop.*ret",
3667 "--range",
3668 "0x1000-0x2000",
3669 "--section",
3670 ".text,.plt",
3671 "--base",
3672 "0x400000",
3673 "--offset",
3674 "0x1000",
3675 "--badbytes",
3676 "0a|0d",
3677 "--align",
3678 "0x10",
3679 ]))
3680 .unwrap();
3681 assert_eq!(p.request.depth, 6);
3682 assert!(!p.request.rop && !p.request.jop && !p.request.sys && p.request.multibr);
3683 assert_eq!(p.request.only.as_deref(), Some("pop|ret"));
3684 assert_eq!(p.request.filter.as_deref(), Some("leave"));
3685 assert_eq!(p.request.range.as_deref(), Some("0x1000-0x2000"));
3686 assert_eq!(p.request.section, vec![".text", ".plt"]);
3687 assert_eq!(p.request.base.as_deref(), Some("0x400000"));
3688 assert_eq!(p.request.offset.as_deref(), Some("0x1000"));
3689 assert_eq!(p.request.badbytes.as_deref(), Some("0a|0d"));
3690 assert_eq!(p.re.as_deref(), Some("pop.*ret"));
3691 assert_eq!(p.request.align, Some(16));
3694 let p = parse_ropgadget_args(&args(&["--depth=8"])).unwrap();
3696 assert_eq!(p.request.depth, 8);
3697 }
3698
3699 #[test]
3700 fn allowlist_rejects_side_channel_and_unknown_flags() {
3701 for bad in ["--string", "--dump", "--console", "--memstr", "--unknown"] {
3702 let err = parse_ropgadget_args(&args(&[bad])).unwrap_err();
3703 assert_eq!(err.code, ErrorCode::UsageError, "{bad}");
3704 assert_eq!(err.kind, "invalid_flag", "{bad}");
3705 assert!(err.message.contains("--depth"), "lists allowlist: {err:?}");
3706 }
3707 let err = parse_ropgadget_args(&args(&["--string", "password"])).unwrap_err();
3709 assert_eq!(err.kind, "invalid_flag");
3710 let err = parse_ropgadget_args(&args(&["/etc/passwd"])).unwrap_err();
3712 assert_eq!(err.kind, "invalid_flag");
3713 let err = parse_ropgadget_args(&args(&["--depth"])).unwrap_err();
3715 assert_eq!(err.kind, "invalid_flag");
3716 let err = parse_ropgadget_args(&args(&["--norop=1"])).unwrap_err();
3718 assert_eq!(err.kind, "invalid_flag");
3719 let err = parse_ropgadget_args(&args(&["--depth", "x"])).unwrap_err();
3721 assert_eq!(err.code, ErrorCode::UsageError);
3722 }
3723
3724 #[test]
3725 fn caps_are_clamped() {
3726 assert_eq!(clamp_max_results(None, 1000), 1000);
3727 assert_eq!(clamp_max_results(Some(5), 1000), 5);
3728 assert_eq!(clamp_max_results(Some(999_999), 1000), HARD_MAX_RESULTS);
3729 assert_eq!(clamp_max_results(Some(0), 1000), 1);
3730 assert_eq!(
3731 clamp_timeout(Some(999_999), Duration::from_secs(60)),
3732 Duration::from_secs(HARD_MAX_TIMEOUT_SECS)
3733 );
3734 assert_eq!(
3735 clamp_timeout(None, Duration::from_secs(60)),
3736 Duration::from_secs(60)
3737 );
3738 }
3739
3740 #[test]
3745 fn rank_beats_quality_at_putting_a_usable_gadget_first() {
3746 let mk = |vaddr: &str, bytes: &str, text: &str| CachedGadget {
3747 vaddr: vaddr.into(),
3748 bytes: bytes.into(),
3749 text: text.into(),
3750 ..CachedGadget::default()
3751 };
3752 let scan = CachedScan {
3753 gadgets: vec![
3754 mk(
3755 "0x1000",
3756 "504801d859c3",
3757 "push rax ; add rax, rbx ; pop rcx ; ret",
3758 ),
3759 mk("0x2000", "58c3", "pop rax ; ret"),
3760 mk("0x3000", "c3", "ret"),
3761 mk("0x0500", "5fc3", "pop rdi ; ret"),
3762 mk("0x4000", "cabc2b", "retf 0x2bbc"),
3763 ],
3764 ..CachedScan::default()
3765 };
3766 let sems = semantics::classify_scan(&scan, "00", 0, Some(rf_core::Arch::X64));
3767 let order_of = |o: Order| {
3768 let mut idx: Vec<usize> = (0..scan.gadgets.len()).collect();
3769 semantics::sort_indices(&mut idx, o, &scan, &sems);
3770 idx.iter()
3771 .map(|&i| scan.gadgets[i].vaddr.as_str())
3772 .collect::<Vec<_>>()
3773 };
3774 assert_eq!(
3780 order_of(Order::Rank),
3781 ["0x0500", "0x2000", "0x1000", "0x4000", "0x3000"]
3782 );
3783 assert_eq!(
3785 order_of(Order::Address),
3786 ["0x0500", "0x1000", "0x2000", "0x3000", "0x4000"]
3787 );
3788 let q = order_of(Order::Quality);
3792 assert_eq!(q[0], "0x0500", "{q:?}");
3793 assert!(
3794 q.iter().position(|v| *v == "0x3000").unwrap()
3795 < q.iter().position(|v| *v == "0x1000").unwrap(),
3796 "{q:?}"
3797 );
3798 }
3799
3800 fn one_ret() -> CachedScan {
3801 CachedScan {
3802 gadgets: vec![CachedGadget {
3803 vaddr: "0x1".into(),
3804 bytes: "c3".into(),
3805 text: "ret".into(),
3806 ..CachedGadget::default()
3807 }],
3808 ..CachedScan::default()
3809 }
3810 }
3811
3812 #[test]
3813 fn cache_roundtrip_mem_and_disk() {
3814 let t = TempDir::new("cache");
3815 let cache = Cache::new(
3816 Some(t.canon().clone()),
3817 rf_cache::MemLimits::default(),
3818 DEFAULT_CURSOR_TTL,
3819 );
3820 cache.put("k1", one_ret());
3821 assert_eq!(cache.get("k1").unwrap().gadgets.len(), 1);
3822 assert!(t.canon().join("k1.rfc").is_file());
3824 let cold = Cache::new(
3826 Some(t.canon().clone()),
3827 rf_cache::MemLimits::default(),
3828 DEFAULT_CURSOR_TTL,
3829 );
3830 assert!(cold.get("k1").is_some());
3831 assert!(cold.get("absent").is_none());
3832 assert_eq!(cold.disk_stats().unwrap().tampered, 0);
3833 }
3834
3835 #[test]
3839 fn a_poisoned_disk_entry_is_a_miss_not_a_result() {
3840 let t = TempDir::new("poison");
3841 {
3842 let cache = Cache::new(
3843 Some(t.canon().clone()),
3844 rf_cache::MemLimits::default(),
3845 DEFAULT_CURSOR_TTL,
3846 );
3847 cache.put("k1", one_ret());
3848 }
3849 let fabricated = br#"{"version":2,"gadgets":[{"vaddr":"0xdeadbeefcafe0000","bytes":"5fc3","text":"pop rdi ; ret"}],"fallback_names":false}"#;
3850 std::fs::write(t.canon().join("k1.rfc"), fabricated).unwrap();
3852 let cache = Cache::new(
3853 Some(t.canon().clone()),
3854 rf_cache::MemLimits::default(),
3855 DEFAULT_CURSOR_TTL,
3856 );
3857 assert!(cache.get("k1").is_none());
3858 assert_eq!(cache.disk_stats().unwrap().tampered, 1);
3859
3860 let mut framed = Vec::from(b"RFCACHE\x02".as_slice());
3862 framed.extend_from_slice(&[0u8; 32]);
3863 framed.extend_from_slice(fabricated);
3864 std::fs::write(t.canon().join("k1.rfc"), &framed).unwrap();
3865 let cache = Cache::new(
3866 Some(t.canon().clone()),
3867 rf_cache::MemLimits::default(),
3868 DEFAULT_CURSOR_TTL,
3869 );
3870 assert!(cache.get("k1").is_none());
3871 assert_eq!(cache.disk_stats().unwrap().tampered, 1);
3872 }
3873
3874 #[test]
3878 fn a_non_ascii_bytes_field_never_panics() {
3879 let t = TempDir::new("charboundary");
3880 {
3881 let cache = Cache::new(
3882 Some(t.canon().clone()),
3883 rf_cache::MemLimits::default(),
3884 DEFAULT_CURSOR_TTL,
3885 );
3886 cache.put("k1", one_ret());
3887 }
3888 let key = std::fs::read(t.canon().join(".cachekey")).unwrap();
3889 let body = r#"{"version":2,"gadgets":[{"vaddr":"0x1","bytes":"€€","text":"ret"}],"fallback_names":false}"#;
3890 let mut msg = Vec::from(b"k1\0".as_slice());
3891 msg.extend_from_slice(body.as_bytes());
3892 let mut framed = Vec::from(b"RFCACHE\x02".as_slice());
3893 framed.extend_from_slice(&rf_cache::hmac_sha256(&key, &msg));
3894 framed.extend_from_slice(body.as_bytes());
3895 std::fs::write(t.canon().join("k1.rfc"), &framed).unwrap();
3896
3897 let cache = Cache::new(
3898 Some(t.canon().clone()),
3899 rf_cache::MemLimits::default(),
3900 DEFAULT_CURSOR_TTL,
3901 );
3902 assert!(cache.get("k1").is_none(), "authenticated but unusable");
3903 assert_eq!(cache.disk_stats().unwrap().malformed, 1);
3904 assert_eq!(cache.disk_stats().unwrap().tampered, 0);
3905
3906 let g = CachedGadget {
3908 vaddr: "0x1".into(),
3909 bytes: "€€".into(),
3910 text: "ret".into(),
3911 ..CachedGadget::default()
3912 };
3913 assert!(g.to_scan_gadget().is_none());
3914 let poisoned = CachedScan {
3917 gadgets: vec![g],
3918 ..CachedScan::default()
3919 };
3920 let sems = semantics::classify_scan(&poisoned, "00", 0, Some(rf_core::Arch::X64));
3921 assert_eq!(sems.len(), 1);
3922 assert!(sems[0].class.is_none());
3923 assert!(sems[0].id.starts_with("g_"));
3924 }
3925}