#![warn(missing_docs)]
use std::fmt;
use globset::{Glob, GlobSetBuilder};
use rf_core::{
Arch, Binary, Endianness, Image, LoadedBinary, MachOBinary, Mitigations, RawBinary, Section,
UniversalBinary,
};
use rf_scan::{CancelToken, Gadget, ScanOptions};
mod info;
pub mod pe_exports;
pub mod query;
pub const DEFAULT_MAX_FILE_SIZE: u64 = 512 * 1024 * 1024;
pub fn parse_size(s: &str, what: &str) -> Result<u64, String> {
let t = s.trim();
if t.is_empty() {
return Err(format!("invalid {what} {s:?}: empty"));
}
let (digits, mult) = match t.as_bytes()[t.len() - 1] {
b'k' | b'K' => (&t[..t.len() - 1], 1024u64),
b'm' | b'M' => (&t[..t.len() - 1], 1024 * 1024),
b'g' | b'G' => (&t[..t.len() - 1], 1024 * 1024 * 1024),
_ => (t, 1),
};
let n: u64 = digits
.trim()
.parse()
.map_err(|e| format!("invalid {what} {s:?}: {e}"))?;
n.checked_mul(mult)
.ok_or_else(|| format!("invalid {what} {s:?}: overflows a u64"))
}
pub fn check_input_metadata(
path: &str,
meta: &std::fs::Metadata,
max_bytes: u64,
) -> Result<(), String> {
if !meta.is_file() {
let kind = if meta.is_dir() {
"a directory"
} else {
"not a regular file (character device, FIFO, socket or symlink loop?)"
};
return Err(format!(
"cannot read {path}: {kind}; rop-finder reads whole files into memory and \
refuses inputs with no fixed length"
));
}
let len = meta.len();
if len > max_bytes {
return Err(format!(
"cannot read {path}: {len} bytes exceeds the --max-file-size limit of \
{max_bytes} bytes; re-run with --max-file-size {len} to allow it"
));
}
Ok(())
}
pub fn read_input_file(path: &str, max_bytes: u64) -> Result<Vec<u8>, String> {
let meta = std::fs::metadata(path).map_err(|e| format!("cannot read {path}: {e}"))?;
check_input_metadata(path, &meta, max_bytes)?;
let bytes = std::fs::read(path).map_err(|e| format!("cannot read {path}: {e}"))?;
if bytes.len() as u64 > max_bytes {
return Err(format!(
"cannot read {path}: file grew past the --max-file-size limit of {max_bytes} bytes \
while it was being read"
));
}
Ok(bytes)
}
pub fn parse_hex(s: &str, what: &str) -> Result<u64, String> {
let t = s.trim().trim_start_matches("0x").trim_start_matches("0X");
u64::from_str_radix(t, 16).map_err(|e| format!("invalid {what} {s:?}: {e}"))
}
pub fn parse_range(s: &str) -> Result<Option<(u64, u64)>, String> {
let (a, b) = s
.split_once('-')
.ok_or_else(|| format!("invalid --range {s:?} (expected 0x...-0x...)"))?;
let start = parse_hex(a, "--range start")?;
let end = parse_hex(b, "--range end")?;
if start == 0 && end == 0 {
return Ok(None);
}
if start > end {
return Err(format!("invalid --range {s:?} (start > end)"));
}
Ok(Some((start, end)))
}
pub fn parse_badbytes(s: &str) -> Result<Vec<u8>, String> {
let mut out = Vec::new();
for part in s.split('|') {
if part.is_empty() {
continue; }
if let Some((lo, hi)) = part.split_once('-') {
let lo = parse_hex(lo, "--badbytes range low")?;
let hi = parse_hex(hi, "--badbytes range high")?;
if lo > 0xff || hi > 0xff || lo > hi {
return Err(format!("invalid --badbytes range {part:?}"));
}
out.extend((lo as u8)..=(hi as u8));
} else {
let b = parse_hex(part, "--badbytes byte")?;
if b > 0xff {
return Err(format!("invalid --badbytes byte {part:?}"));
}
out.push(b as u8);
}
}
Ok(out)
}
pub fn arch_name(arch: Arch) -> &'static str {
match arch {
Arch::X86 => "x86",
Arch::X64 => "x64",
Arch::Arm => "arm",
Arch::ArmThumb => "arm-thumb",
Arch::Arm64 => "arm64",
Arch::Mips32 => "mips32",
Arch::Mips64 => "mips64",
Arch::Ppc32 => "ppc32",
Arch::Ppc64 => "ppc64",
Arch::Sparc => "sparc",
Arch::Sparc64 => "sparc64",
Arch::SparcV9 => "sparcv9",
Arch::RiscV32 => "riscv32",
Arch::RiscV64 => "riscv64",
}
}
pub fn endian_name(e: Endianness) -> &'static str {
match e {
Endianness::Little => "little",
Endianness::Big => "big",
}
}
pub enum Target {
Elf(rf_core::ElfBinary),
Pe(rf_core::PeBinary),
MachO(MachOBinary),
Universal(UniversalBinary),
Raw(RawBinary),
}
pub struct RegionView {
arch: Arch,
pub endian: Endianness,
pub base: u64,
pub entry: u64,
pub regions: Vec<Section>,
pub named_exec: Vec<Section>,
pub universal: bool,
}
pub fn resolve_arch(
target: &Target,
arch: Option<&str>,
compat: bool,
) -> Result<Option<Arch>, ScanError> {
let named = match arch {
Some(a) => Some(Arch::from_slice_name(a).ok_or_else(|| {
ScanError::Usage(format!(
"unknown --arch {a:?}; expected an architecture slice name such as \
x86_64, i386, arm64, arm, ppc, ppc64"
))
})?),
None => None,
};
match target {
Target::Universal(u) => match named {
Some(a) => {
u.select(a).map_err(|e| ScanError::Usage(e.to_string()))?;
Ok(Some(a))
}
None => {
if u.needs_arch_selection() && !compat {
let available = u
.slice_infos()
.iter()
.map(|s| s.name())
.collect::<Vec<_>>()
.join(", ");
Err(ScanError::Usage(format!(
"universal (fat Mach-O) binary holds {} architecture slices \
({available}); pass --arch <slice> to choose one. Refusing to scan \
the concatenation: the slices' virtual address ranges overlap and \
every slice but the first would be disassembled with the wrong \
decoder, so most of the output would be fabricated",
u.slices().len()
)))
} else {
Ok(None)
}
}
},
other => match named {
None => Ok(None),
Some(a) => {
let actual = build_view(other).arch();
if a == actual {
Ok(Some(a))
} else {
Err(ScanError::Usage(format!(
"--arch {} does not match this binary: it is {}. --arch selects a \
slice of a fat (Universal) Mach-O; it does not reinterpret a \
single-architecture image (use --rawArch for that)",
a.slice_name(),
actual.slice_name()
)))
}
}
},
}
}
pub fn build_view_selected(target: &Target, arch: Option<Arch>) -> RegionView {
match (target, arch) {
(Target::Universal(u), Some(a)) => match u.select(a) {
Ok(slice) => RegionView {
arch: slice.arch(),
endian: slice.endianness(),
base: slice.image_base(),
entry: slice.entry(),
regions: slice.exec_scan_regions().to_vec(),
named_exec: slice.exec_sections().into_iter().cloned().collect(),
universal: true,
},
Err(_) => build_view(target),
},
_ => build_view(target),
}
}
pub fn build_view(target: &Target) -> RegionView {
match target {
Target::Elf(b) => RegionView::single(
Image::arch(b),
Image::endianness(b),
b.image_base(),
b.entry(),
b.exec_scan_regions(),
b.exec_sections(),
),
Target::Pe(b) => RegionView::single(
Image::arch(b),
Image::endianness(b),
b.image_base(),
b.entry(),
b.exec_scan_regions(),
b.exec_sections(),
),
Target::MachO(b) => RegionView::single(
Image::arch(b),
Image::endianness(b),
b.image_base(),
b.entry(),
b.exec_scan_regions(),
b.exec_sections(),
),
Target::Raw(b) => RegionView::single(
Image::arch(b),
Image::endianness(b),
b.image_base(),
b.entry(),
b.exec_scan_regions(),
b.exec_sections(),
),
Target::Universal(u) => {
let first = &u.slices()[0];
RegionView {
arch: first.arch(),
endian: first.endianness(),
base: first.image_base(),
entry: first.entry(),
regions: u.all_exec_scan_regions().into_iter().cloned().collect(),
named_exec: u
.slices()
.iter()
.flat_map(|s| s.exec_sections().into_iter().cloned())
.collect(),
universal: true,
}
}
}
}
impl RegionView {
fn single(
arch: Arch,
endian: Endianness,
base: u64,
entry: u64,
regions: &[Section],
named_exec: Vec<&Section>,
) -> Self {
RegionView {
arch,
endian,
base,
entry,
regions: regions.to_vec(),
named_exec: named_exec.into_iter().cloned().collect(),
universal: false,
}
}
}
impl Image for RegionView {
fn arch(&self) -> Arch {
self.arch
}
fn endianness(&self) -> Endianness {
self.endian
}
fn image_base(&self) -> u64 {
self.base
}
fn entry(&self) -> u64 {
self.entry
}
fn exec_sections(&self) -> Vec<&Section> {
self.named_exec.iter().collect()
}
fn exec_scan_regions(&self) -> &[Section] {
&self.regions
}
fn rebase(&mut self, new_base: u64) {
let delta = new_base.wrapping_sub(self.base);
for s in &mut self.regions {
s.vaddr = s.vaddr.wrapping_add(delta);
}
for s in &mut self.named_exec {
s.vaddr = s.vaddr.wrapping_add(delta);
}
self.entry = self.entry.wrapping_add(delta);
self.base = new_base;
}
}
pub fn select_sections(
named_exec: &[Section],
patterns: &[String],
) -> Result<(Vec<Section>, bool), String> {
let mut builder = GlobSetBuilder::new();
for p in patterns {
let glob = Glob::new(p).map_err(|e| format!("invalid --section pattern {p:?}: {e}"))?;
builder.add(glob);
}
let set = builder
.build()
.map_err(|e| format!("invalid --section patterns: {e}"))?;
let matched: Vec<Section> = named_exec
.iter()
.filter(|s| set.is_match(&s.name))
.cloned()
.collect();
let fallback_names =
!named_exec.is_empty() && named_exec.iter().all(|s| s.name.starts_with("PT_LOAD#"));
if matched.is_empty() {
let available = named_exec
.iter()
.map(|s| s.name.as_str())
.collect::<Vec<_>>()
.join(", ");
return Err(format!(
"no executable section matches {patterns:?}; available executable sections: {available}"
));
}
Ok((matched, fallback_names))
}
pub struct ScanResult {
pub gadgets: Vec<Gadget>,
pub addr_size: usize,
pub universal_arch: Option<Arch>,
pub selected_sections: Option<Vec<(String, u64, u64)>>,
}
pub fn hexs(v: u64) -> String {
format!("0x{v:x}")
}
fn section_json(s: &Section, delta: u64) -> serde_json::Value {
serde_json::json!({
"name": s.name,
"vaddr": hexs(s.vaddr.wrapping_add(delta)),
"size": s.size,
"executable": s.executable,
"writable": s.writable,
})
}
fn rebase_delta(image_base: u64, new_base: Option<u64>) -> u64 {
new_base.map_or(0, |n| n.wrapping_sub(image_base))
}
struct InfoView<'a> {
format: &'static str,
arch: Arch,
endian: Endianness,
image_base: u64,
entry: u64,
sections: &'a [Section],
imports: Vec<serde_json::Value>,
mitigations: &'a Mitigations,
symbols: Option<Vec<serde_json::Value>>,
delta: u64,
}
fn image_info(v: InfoView) -> serde_json::Value {
let mut o = serde_json::json!({
"format": v.format,
"arch": arch_name(v.arch),
"endianness": endian_name(v.endian),
"addr_size": v.arch.addr_size(),
"image_base": hexs(v.image_base.wrapping_add(v.delta)),
"entry": hexs(v.entry.wrapping_add(v.delta)),
"sections": v.sections.iter().map(|s| section_json(s, v.delta)).collect::<Vec<_>>(),
"imports": v.imports,
"mitigations": info::mitigations_json(v.mitigations),
"mitigations_order": info::mitigation_order_json(v.mitigations),
});
let map = o.as_object_mut().expect("json! built an object");
if let Some(note) = v.mitigations.note() {
map.insert("mitigations_note".into(), note.into());
}
if let Some(syms) = v.symbols {
map.insert("symbol_count".into(), syms.len().into());
map.insert("symbols".into(), syms.into());
}
o
}
fn macho_info(b: &MachOBinary, delta: u64) -> serde_json::Value {
image_info(InfoView {
format: "macho",
arch: b.arch(),
endian: b.endianness(),
image_base: b.image_base(),
entry: b.entry(),
sections: b.sections(),
imports: Vec::new(),
mitigations: b.mitigations(),
symbols: None,
delta,
})
}
pub fn info_json(target: &Target, new_base: Option<u64>) -> serde_json::Value {
match target {
Target::Elf(b) => {
let delta = rebase_delta(b.image_base(), new_base);
image_info(InfoView {
format: "elf",
arch: Image::arch(b),
endian: Image::endianness(b),
image_base: b.image_base(),
entry: b.entry(),
sections: b.sections(),
imports: b
.imports()
.iter()
.map(|s| info::elf_import_json(s, delta))
.collect(),
mitigations: b.mitigations(),
symbols: Some(
b.symbols()
.iter()
.map(|s| info::symbol_json(s, delta))
.collect(),
),
delta,
})
}
Target::Pe(b) => {
let delta = rebase_delta(b.image_base(), new_base);
let imports = b
.imports()
.iter()
.map(|i| {
serde_json::json!({
"dll": i.dll,
"symbol": i.name,
"iat_vaddr": hexs(i.iat_slot_vaddr.wrapping_add(delta)),
"hint_name_vaddr": hexs(i.hint_name_vaddr.wrapping_add(delta)),
})
})
.collect();
image_info(InfoView {
format: "pe",
arch: Image::arch(b),
endian: Image::endianness(b),
image_base: b.image_base(),
entry: b.entry(),
sections: b.sections(),
imports,
mitigations: b.mitigations(),
symbols: None,
delta,
})
}
Target::MachO(b) => macho_info(b, rebase_delta(b.image_base(), new_base)),
Target::Raw(b) => {
let m = b.mitigations();
image_info(InfoView {
format: "raw",
arch: Image::arch(b),
endian: Image::endianness(b),
image_base: b.image_base(),
entry: b.entry(),
sections: std::slice::from_ref(b.section()),
imports: Vec::new(),
mitigations: &m,
symbols: None,
delta: rebase_delta(b.image_base(), new_base),
})
}
Target::Universal(u) => {
let first_base = u.slices()[0].image_base();
let delta = rebase_delta(first_base, new_base);
let slices: Vec<serde_json::Value> = u
.slices()
.iter()
.zip(u.slice_infos())
.map(|(s, info)| {
let mut v = macho_info(s, delta);
if let Some(o) = v.as_object_mut() {
o.insert("slice".into(), info.name().into());
o.insert("slice_offset".into(), hexs(info.offset).into());
o.insert("slice_size".into(), info.size.into());
}
v
})
.collect();
serde_json::json!({
"format": "universal",
"fat64": u.is_fat64(),
"arch_selection_required": u.needs_arch_selection(),
"slices": slices,
})
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ScanError {
Usage(String),
Binary(String),
Chain(String),
}
impl fmt::Display for ScanError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ScanError::Usage(m) | ScanError::Binary(m) | ScanError::Chain(m) => f.write_str(m),
}
}
}
impl std::error::Error for ScanError {}
pub type RawSpec = (Arch, Endianness, bool);
#[derive(Debug, Clone)]
pub struct ScanRequest {
pub depth: usize,
pub rop: bool,
pub jop: bool,
pub sys: bool,
pub multibr: bool,
pub only: Option<String>,
pub filter: Option<String>,
pub range: Option<String>,
pub badbytes: Option<String>,
pub offset: Option<String>,
pub base: Option<String>,
pub section: Vec<String>,
pub thumb: bool,
pub cfg_aware: bool,
pub align: Option<usize>,
pub call_preceded: bool,
pub all: bool,
pub noinstr: bool,
pub arch: Option<String>,
pub max_gadgets: Option<usize>,
pub max_memory: Option<usize>,
pub compat: bool,
}
impl Default for ScanRequest {
fn default() -> Self {
ScanRequest {
depth: 10,
rop: true,
jop: true,
sys: true,
multibr: false,
only: None,
filter: None,
range: None,
badbytes: None,
offset: None,
base: None,
section: Vec::new(),
thumb: false,
cfg_aware: false,
align: None,
call_preceded: false,
all: false,
noinstr: false,
arch: None,
max_gadgets: None,
max_memory: None,
compat: false,
}
}
}
pub struct ScanOutcome {
pub result: ScanResult,
pub opts: ScanOptions,
pub fallback_names: bool,
}
impl From<LoadedBinary> for Target {
fn from(l: LoadedBinary) -> Self {
match l {
LoadedBinary::Elf(b) => Target::Elf(b),
LoadedBinary::Pe(b) => Target::Pe(b),
LoadedBinary::MachO(b) => Target::MachO(b),
LoadedBinary::Raw(b) => Target::Raw(b),
LoadedBinary::Universal(u) => Target::Universal(u),
}
}
}
pub fn load_target(bytes: &[u8], raw: Option<RawSpec>) -> Result<Target, ScanError> {
if let Some((arch, endian, _)) = raw {
return Ok(Target::Raw(RawBinary::new(bytes, arch, endian)));
}
Binary::load(bytes)
.map(Target::from)
.map_err(|e| ScanError::Binary(e.to_string()))
}
#[derive(Debug, Clone, Default)]
pub struct ScanBudget {
pub cancel: CancelToken,
pub max_gadgets: Option<usize>,
pub max_memory: Option<usize>,
}
pub fn request_options(req: &ScanRequest, raw: Option<RawSpec>) -> Result<ScanOptions, ScanError> {
request_options_with(req, raw, &ScanBudget::default())
}
pub fn request_options_with(
req: &ScanRequest,
raw: Option<RawSpec>,
budget: &ScanBudget,
) -> Result<ScanOptions, ScanError> {
if req.depth < 2 {
return Err(ScanError::Usage("--depth must be >= 2".to_string()));
}
let usage = |e: String| ScanError::Usage(e);
let mut opts = ScanOptions {
depth: req.depth,
rop: req.rop,
jop: req.jop,
sys: req.sys,
multibr: req.multibr,
only: req
.only
.as_deref()
.map(|s| s.split('|').map(|x| x.to_string()).collect()),
range: match &req.range {
Some(r) => parse_range(r).map_err(usage)?,
None => None,
},
badbytes: match &req.badbytes {
Some(b) => parse_badbytes(b).map_err(usage)?,
None => Vec::new(),
},
filter: req
.filter
.as_deref()
.map(|s| s.split('|').map(|x| x.to_string()).collect())
.unwrap_or_default(),
offset: match &req.offset {
Some(o) => parse_hex(o, "--offset").map_err(usage)?,
None => 0,
},
thumb: req.thumb,
cfg_aware: req.cfg_aware,
align: req.align,
call_preceded: req.call_preceded,
all: req.all,
noinstr: req.noinstr,
parallel: true,
filter_re: None,
cancel: budget.cancel.clone(),
max_gadgets: budget.max_gadgets.or(req.max_gadgets),
max_memory: budget.max_memory.or(req.max_memory),
};
if let Some((_, _, raw_thumb)) = raw {
opts.thumb = opts.thumb || raw_thumb;
}
Ok(opts)
}
pub type SectionEntry = (String, u64, u64);
pub struct PreparedView {
pub view: RegionView,
pub selected_sections: Option<Vec<SectionEntry>>,
pub fallback_names: bool,
}
pub fn prepare_view(
target: &Target,
base: Option<u64>,
sections: &[String],
arch: Option<&str>,
compat: bool,
) -> Result<PreparedView, ScanError> {
let slice = resolve_arch(target, arch, compat)?;
let mut view = build_view_selected(target, slice);
if let Some(base) = base {
view.rebase(base);
}
let mut selected_sections = None;
let mut fallback_names = false;
if !sections.is_empty() {
let (matched, fb) =
select_sections(&view.named_exec, sections).map_err(ScanError::Usage)?;
fallback_names = fb;
selected_sections = Some(
matched
.iter()
.map(|s| (s.name.clone(), s.vaddr, s.size))
.collect(),
);
view.regions = matched;
}
Ok(PreparedView {
view,
selected_sections,
fallback_names,
})
}
pub fn scan_bytes(
bytes: &[u8],
raw: Option<RawSpec>,
req: &ScanRequest,
) -> Result<ScanOutcome, ScanError> {
let opts = request_options(req, raw)?;
let target = load_target(bytes, raw)?;
let base = req
.base
.as_deref()
.map(|b| parse_hex(b, "--base"))
.transpose()
.map_err(ScanError::Usage)?;
let prepared = prepare_view(&target, base, &req.section, req.arch.as_deref(), req.compat)?;
let view = prepared.view;
let selected_sections = prepared.selected_sections;
let fallback_names = prepared.fallback_names;
let universal_arch = view.universal.then_some(view.arch());
let gadgets = run_scan_engine(&view, &opts).map_err(ScanError::Binary)?;
Ok(ScanOutcome {
result: ScanResult {
gadgets,
addr_size: view.addr_size(),
universal_arch,
selected_sections,
},
opts,
fallback_names,
})
}
pub struct ScanProduct {
pub gadgets: Vec<Gadget>,
pub addr_size: usize,
pub universal_arch: Option<Arch>,
pub selected_sections: Option<Vec<SectionEntry>>,
pub fallback_names: bool,
pub offset: u64,
}
#[derive(Debug)]
pub enum ScanFailure {
Request(ScanError),
Engine(rf_scan::Error),
}
impl From<ScanError> for ScanFailure {
fn from(e: ScanError) -> Self {
ScanFailure::Request(e)
}
}
impl fmt::Display for ScanFailure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ScanFailure::Request(e) => write!(f, "{e}"),
ScanFailure::Engine(e) => write!(f, "{e}"),
}
}
}
impl std::error::Error for ScanFailure {}
pub fn scan_bytes_cancellable(
bytes: &[u8],
req: &ScanRequest,
budget: &ScanBudget,
) -> Result<ScanProduct, ScanFailure> {
let opts = request_options_with(req, None, budget)?;
let target = load_target(bytes, None)?;
let base = req
.base
.as_deref()
.map(|b| parse_hex(b, "--base"))
.transpose()
.map_err(ScanError::Usage)?;
let prepared = prepare_view(&target, base, &req.section, req.arch.as_deref(), req.compat)?;
let view = prepared.view;
let universal_arch = view.universal.then(|| Image::arch(&view));
let gadgets = rf_scan::scan_bounded(&view, &opts).map_err(ScanFailure::Engine)?;
Ok(ScanProduct {
gadgets,
addr_size: view.addr_size(),
universal_arch,
selected_sections: prepared.selected_sections,
fallback_names: prepared.fallback_names,
offset: opts.offset,
})
}
pub fn scan_warnings(
target: &Target,
view: &RegionView,
cfg_aware: bool,
compat: bool,
) -> Vec<String> {
let mut out = Vec::new();
if cfg_aware && !rf_scan::ibt_applicable(view) {
out.push(
"[Warning] --cfg-aware: this binary contains no endbr32/endbr64 landing pads, \
so Intel CET/IBT is not enforced on it and the flag constrains nothing. \
(PE GUARD_CF is a different mitigation and is not what --cfg-aware models.)"
.to_string(),
);
}
if let Target::Elf(b) = target {
if let Some(d) = b.mode_divergence() {
out.push(format!(
"[Warning] ELF e_machine {:#x} declares {}-bit code but EI_CLASS says \
{}-bit. rop-finder decodes it as {}-bit (the width the instruction \
encodings actually use); ROPgadget decodes it as {}-bit. Gadget text and \
counts will differ from the oracle on this file.",
d.machine, d.rf_bits, d.oracle_bits, d.rf_bits, d.oracle_bits
));
}
}
if compat {
if let Target::Universal(u) = target {
if u.needs_arch_selection() {
out.push(format!(
"[Warning] --compat: scanning all {} slices of this fat Mach-O \
concatenated and decoding every one of them as {}, exactly as \
ROPgadget does. Every slice but the first is decoded with the WRONG \
architecture: its listing mixes FABRICATED gadgets — misreadings of \
another architecture's instructions, at addresses indistinguishable \
from the genuine ones — with real gadgets it silently drops. Use \
--arch <slice> for a trustworthy listing.",
u.slices().len(),
view.arch().slice_name()
));
}
}
}
out
}
pub fn run_scan_engine(view: &RegionView, opts: &ScanOptions) -> Result<Vec<Gadget>, String> {
if opts.max_gadgets.is_none() && opts.max_memory.is_none() {
return rf_scan::scan_binary(view, opts).map_err(|e| e.to_string());
}
rf_scan::scan_bounded(view, opts).map_err(scan_error_message)
}
pub fn scan_error_message(e: rf_scan::Error) -> String {
match e {
rf_scan::Error::Budget { produced, limit } => format!(
"scan budget exhausted after {produced} gadgets (limit {limit}); raise \
--max-gadgets/--max-memory, lower --depth, or narrow the scan with --section"
),
other => other.to_string(),
}
}
pub fn info_bytes(
bytes: &[u8],
raw: Option<RawSpec>,
new_base: Option<u64>,
) -> Result<serde_json::Value, ScanError> {
let target = load_target(bytes, raw)?;
Ok(info_json(&target, new_base))
}
pub fn target_format(target: &Target) -> &'static str {
match target {
Target::Elf(_) => "elf",
Target::Pe(_) => "pe",
Target::MachO(_) => "macho",
Target::Universal(_) => "universal",
Target::Raw(_) => "raw",
}
}
#[derive(Debug, Clone, Default)]
pub struct ChainSpec {
pub target: String,
pub api_addr: Option<String>,
pub api_name: Option<String>,
pub shellcode_addr: Option<String>,
pub shellcode_size: Option<String>,
pub chain_base: Option<String>,
pub prot: Option<String>,
pub syscall: Option<String>,
pub syscall_args: Option<String>,
pub pivot: Option<String>,
pub stage: Option<String>,
}
impl ChainSpec {
pub fn linux() -> Self {
ChainSpec {
target: "linux-execve".to_string(),
..ChainSpec::default()
}
}
}
pub struct ChainOutcome {
pub chain: rf_chain::RopChain,
pub outcome: ScanOutcome,
pub assumptions: Option<rf_chain::windows::WinAssumptions>,
}
pub fn parse_syscall_args(spec: &str) -> Result<Vec<(String, u64)>, String> {
let mut out = Vec::new();
for item in spec.split(',').map(str::trim).filter(|s| !s.is_empty()) {
let (reg, value) = item.split_once('=').ok_or_else(|| {
format!("invalid --syscall-args item {item:?}: expected <reg>=<value>")
})?;
let reg = reg.trim().to_ascii_lowercase();
if reg.is_empty() {
return Err(format!(
"invalid --syscall-args item {item:?}: empty register name"
));
}
let value = parse_hex(value.trim(), "--syscall-args")?;
out.push((reg, value));
}
Ok(out)
}
pub fn parse_syscall_nr(v: &str) -> Result<u64, String> {
let t = v.trim();
if let Some(hex) = t.strip_prefix("0x").or_else(|| t.strip_prefix("0X")) {
return u64::from_str_radix(hex, 16).map_err(|e| format!("invalid --syscall {v:?}: {e}"));
}
t.parse::<u64>()
.map_err(|e| format!("invalid --syscall {v:?}: {e}"))
}
pub fn parse_hex_bytes(v: &str, flag: &str) -> Result<Vec<u8>, String> {
let t: String = v
.trim()
.trim_start_matches("0x")
.chars()
.filter(|c| !c.is_whitespace())
.collect();
if t.is_empty() {
return Err(format!("{flag}: no bytes given"));
}
if t.len() % 2 != 0 {
return Err(format!(
"{flag} {v:?}: hex byte string has an odd number of digits"
));
}
(0..t.len())
.step_by(2)
.map(|i| u8::from_str_radix(&t[i..i + 2], 16).map_err(|e| format!("{flag} {v:?}: {e}")))
.collect()
}
pub fn linux_opts(spec: &ChainSpec) -> Result<rf_chain::LinuxChainOpts, ScanError> {
use rf_chain::LinuxTarget;
let usage = ScanError::Usage;
let target = LinuxTarget::parse(&spec.target).ok_or_else(|| {
ScanError::Usage(format!(
"unknown Linux chain target {:?}; supported: {}",
spec.target,
LinuxTarget::NAMES.join(", ")
))
})?;
Ok(rf_chain::LinuxChainOpts {
target,
syscall_nr: spec
.syscall
.as_deref()
.map(parse_syscall_nr)
.transpose()
.map_err(usage)?,
syscall_args: spec
.syscall_args
.as_deref()
.map(parse_syscall_args)
.transpose()
.map_err(usage)?
.unwrap_or_default(),
func_addr: spec
.api_addr
.as_deref()
.map(|a| parse_hex(a, "--api-addr"))
.transpose()
.map_err(usage)?,
shellcode_addr: spec
.shellcode_addr
.as_deref()
.map(|a| parse_hex(a, "--shellcode-addr"))
.transpose()
.map_err(usage)?,
shellcode_size: match &spec.shellcode_size {
Some(s) => parse_hex(s, "--shellcode-size").map_err(usage)?,
None => rf_chain::linux::DEFAULT_LINUX_LEN,
},
prot: match &spec.prot {
Some(s) => parse_hex(s, "--prot").map_err(usage)?,
None => rf_chain::linux::DEFAULT_LINUX_PROT,
},
})
}
pub fn chain_json(outcome: &ChainOutcome) -> String {
let mut value = outcome.chain.to_json();
if let Some(obj) = value.as_object_mut() {
obj.insert(
"assumptions".to_string(),
match outcome.assumptions.as_ref() {
Some(a) => serde_json::to_value(a).unwrap_or(serde_json::Value::Null),
None => serde_json::Value::Null,
},
);
}
serde_json::to_string_pretty(&value).unwrap()
}
fn chain_err(e: rf_chain::ChainError) -> ScanError {
match e {
rf_chain::ChainError::Unsupported { .. } => ScanError::Usage(e.to_string()),
other => ScanError::Chain(other.to_string()),
}
}
pub fn win_opts(spec: &ChainSpec) -> Result<rf_chain::WinChainOpts, ScanError> {
use rf_chain::windows::{ApiRecipe, ChainBaseParity};
let usage = ScanError::Usage;
let raw_names: Vec<&str> = match spec.api_name.as_deref().map(str::trim) {
None | Some("") => vec![],
Some(v) => v
.split(',')
.map(str::trim)
.filter(|s| !s.is_empty())
.collect(),
};
let canonical = |name: &str| -> Result<String, ScanError> {
ApiRecipe::NAMES
.iter()
.find(|n| n.eq_ignore_ascii_case(name))
.map(|n| (*n).to_string())
.ok_or_else(|| {
ScanError::Usage(format!(
"--api-name {name:?}: supported values are {} (their argument recipes differ, so an unmodelled API cannot be called correctly)",
ApiRecipe::NAMES.join(", ")
))
})
};
let names: Vec<String> = if raw_names.is_empty() {
vec![rf_chain::WinChainOpts::default().api_name]
} else {
raw_names
.iter()
.map(|n| canonical(n))
.collect::<Result<Vec<_>, _>>()?
};
let addrs: Vec<u64> = match spec.api_addr.as_deref().map(str::trim) {
None | Some("") => Vec::new(),
Some(v) => v
.split(',')
.map(str::trim)
.filter(|s| !s.is_empty())
.map(|a| parse_hex(a, "--api-addr"))
.collect::<Result<Vec<_>, _>>()
.map_err(usage)?,
};
if !addrs.is_empty() && addrs.len() != names.len() {
return Err(ScanError::Usage(format!(
"--api-addr has {} address(es) but --api-name names {} API(s): a composed chain needs one runtime address per call, or none at all (IAT resolution)",
addrs.len(),
names.len()
)));
}
let addr_of = |i: usize| addrs.get(i).copied();
let chain_base = match spec.chain_base.as_deref().map(str::trim) {
None | Some("") => ChainBaseParity::default(),
Some(v) => ChainBaseParity::parse(v).ok_or_else(|| {
ScanError::Usage(format!(
"--chain-base {v:?}: supported values are {}",
ChainBaseParity::VALUES.join(", ")
))
})?,
};
Ok(rf_chain::WinChainOpts {
api_name: names[0].clone(),
api_addr: addr_of(0),
extra_calls: names
.iter()
.enumerate()
.skip(1)
.map(|(i, n)| (n.clone(), addr_of(i)))
.collect(),
shellcode_addr: spec
.shellcode_addr
.as_deref()
.map(|a| parse_hex(a, "--shellcode-addr"))
.transpose()
.map_err(usage)?,
shellcode_size: match &spec.shellcode_size {
Some(s) => parse_hex(s, "--shellcode-size").map_err(usage)?,
None => rf_chain::windows::DEFAULT_SHELLCODE_SIZE,
},
new_protect: match &spec.prot {
Some(s) => parse_hex(s, "--prot").map_err(usage)?,
None => rf_chain::windows::DEFAULT_PROTECT,
},
chain_base,
pivot: spec
.pivot
.as_deref()
.map(|a| parse_hex(a, "--chain-pivot"))
.transpose()
.map_err(usage)?,
stage: spec
.stage
.as_deref()
.map(|h| parse_hex_bytes(h, "--stage"))
.transpose()
.map_err(usage)?
.unwrap_or_default(),
exports: Vec::new(),
})
}
pub fn chain_targets() -> Vec<&'static str> {
let mut v: Vec<&'static str> = rf_chain::LinuxTarget::NAMES.to_vec();
v.push("windows-virtualprotect");
v
}
fn check_chain_target(
name: &str,
target: &Target,
arch: Arch,
format: &str,
) -> Result<(), ScanError> {
let unsupported = || {
Err(chain_err(rf_chain::ChainError::Unsupported {
arch: rf_chain::arch_name(arch),
format: format.to_string(),
}))
};
match name {
t if rf_chain::LinuxTarget::parse(t).is_some() => {
if !matches!(target, Target::Elf(_)) || !matches!(arch, Arch::X86 | Arch::X64) {
return unsupported();
}
}
"windows-virtualprotect" => {
if !matches!(target, Target::Pe(_)) || !matches!(arch, Arch::X86 | Arch::X64) {
return unsupported();
}
}
other => {
return Err(ScanError::Usage(format!(
"unknown chain target {other:?}; supported: {}",
chain_targets().join(", ")
)));
}
}
Ok(())
}
fn plan_once(
bytes: &[u8],
raw: Option<RawSpec>,
req: &ScanRequest,
spec: &ChainSpec,
) -> Result<(rf_chain::ChainPlan, Vec<rf_scan::Gadget>, u64), ScanError> {
let opts = request_options(req, raw)?;
let mut target = load_target(bytes, raw)?;
let format = target_format(&target);
let arch = match &target {
Target::Elf(b) => Image::arch(b),
Target::Pe(b) => Image::arch(b),
t => Image::arch(&build_view(t)),
};
if !chain_targets().contains(&spec.target.as_str()) {
return Err(ScanError::Usage(format!(
"unknown chain target {:?}; supported: {}",
spec.target,
chain_targets().join(", ")
)));
}
let base = req
.base
.as_deref()
.map(|b| parse_hex(b, "--base"))
.transpose()
.map_err(ScanError::Usage)?;
match &mut target {
Target::Elf(b) => {
if let Some(base) = base {
b.rebase(base);
}
}
Target::Pe(b) => {
if let Some(base) = base {
b.rebase(base);
}
}
_ => {}
}
let prepared = prepare_view(&target, None, &req.section, req.arch.as_deref(), req.compat)?;
let gadgets = rf_scan::scan_binary(&prepared.view, &opts)
.map_err(|e| ScanError::Binary(e.to_string()))?;
let sections: &[rf_core::Section] = match &target {
Target::Elf(b) => b.sections(),
Target::Pe(b) => b.sections(),
_ => &[],
};
let data_sections: Vec<rf_chain::DataSection> = sections
.iter()
.filter(|s| !s.executable)
.map(|s| rf_chain::DataSection {
name: s.name.clone(),
vaddr: s.vaddr.wrapping_add(opts.offset),
writable: s.writable,
})
.collect();
let plan = match (&target, spec.target.as_str()) {
(_, "windows-virtualprotect") => {
let mut wopts = win_opts(spec)?;
if let Target::Pe(pe) = &target {
wopts.exports = pe_exports::parse_pe_exports(bytes, pe.image_base());
}
rf_chain::plan_windows(
&gadgets,
&data_sections,
match &target {
Target::Pe(pe) => pe.imports(),
_ => &[],
},
arch,
format,
&wopts,
&opts.badbytes,
)
}
_ => {
let lopts = linux_opts(spec)?;
rf_chain::plan_linux(
&gadgets,
&data_sections,
arch,
format,
&opts.badbytes,
&lopts,
)
}
};
Ok((plan, gadgets, opts.offset))
}
pub fn plan_chain_bytes(
bytes: &[u8],
raw: Option<RawSpec>,
req: &ScanRequest,
spec: &ChainSpec,
) -> Result<ChainPlanOutcome, ScanError> {
let (mut plan, gadgets, offset) = plan_once(bytes, raw, req, spec)?;
if plan.requirements.iter().any(|r| !r.satisfied) {
let deeper = ScanRequest {
depth: req.depth.saturating_mul(2),
..req.clone()
};
if let Ok((v, _, _)) = plan_once(bytes, raw, &deeper, spec) {
plan.merge_relaxation(
&v,
"depth",
&req.depth.to_string(),
&deeper.depth.to_string(),
);
}
let multibr = ScanRequest {
multibr: true,
..req.clone()
};
if !req.multibr {
if let Ok((v, _, _)) = plan_once(bytes, raw, &multibr, spec) {
plan.merge_relaxation(&v, "multibr", "false", "true");
}
}
}
Ok(ChainPlanOutcome {
plan,
gadgets,
offset,
})
}
pub fn plan_json(outcome: &ChainPlanOutcome) -> String {
serde_json::to_string_pretty(&outcome.plan.to_json()).unwrap()
}
pub struct ChainPlanOutcome {
pub plan: rf_chain::ChainPlan,
pub gadgets: Vec<rf_scan::Gadget>,
pub offset: u64,
}
impl ChainPlanOutcome {
pub fn gadget_bytes(&self, vaddr: u64) -> Option<&[u8]> {
self.gadgets
.iter()
.find(|g| g.vaddr == vaddr)
.map(|g| g.bytes.as_slice())
}
}
pub fn chain_bytes(
bytes: &[u8],
raw: Option<RawSpec>,
req: &ScanRequest,
spec: &ChainSpec,
) -> Result<ChainOutcome, ScanError> {
let opts = request_options(req, raw)?;
let mut target = load_target(bytes, raw)?;
let format = target_format(&target);
let arch = match &target {
Target::Elf(b) => Image::arch(b),
Target::Pe(b) => Image::arch(b),
t => Image::arch(&build_view(t)), };
check_chain_target(&spec.target, &target, arch, format)?;
let base = req
.base
.as_deref()
.map(|b| parse_hex(b, "--base"))
.transpose()
.map_err(ScanError::Usage)?;
match &mut target {
Target::Elf(b) => {
if let Some(base) = base {
b.rebase(base);
}
}
Target::Pe(b) => {
if let Some(base) = base {
b.rebase(base);
}
}
_ => {}
}
if let Target::Pe(b) = &target {
if b.guard_cf() && !req.cfg_aware {
eprintln!(
"[Warning] PE is GUARD_CF-marked (CFG/CET); generated chains may be blocked \
under enforced IBT — consider --cfg-aware"
);
}
}
let prepared = prepare_view(&target, None, &req.section, req.arch.as_deref(), req.compat)?;
let universal_arch = prepared.view.universal.then_some(prepared.view.arch());
let gadgets = rf_scan::scan_binary(&prepared.view, &opts)
.map_err(|e| ScanError::Binary(e.to_string()))?;
let sections: &[rf_core::Section] = match &target {
Target::Elf(b) => b.sections(),
Target::Pe(b) => b.sections(),
_ => unreachable!("dispatched above"),
};
let data_sections: Vec<rf_chain::DataSection> = sections
.iter()
.filter(|s| !s.executable)
.map(|s| rf_chain::DataSection {
name: s.name.clone(),
vaddr: s.vaddr.wrapping_add(opts.offset),
writable: s.writable,
})
.collect();
if let Target::Elf(b) = &target {
let is_dyn = b.mitigations().enabled(rf_core::mitigations::PIE)
== rf_core::mitigations::Enabled::Yes;
if let Some(w) = rf_chain::linux::pie_chain_warning(is_dyn, b.image_base(), opts.offset) {
eprintln!("[Warning] {w}");
}
}
let mut assumptions = None;
let chain = match spec.target.as_str() {
t if rf_chain::LinuxTarget::parse(t).is_some() => {
let lopts = linux_opts(spec)?;
rf_chain::build_linux(
&gadgets,
&data_sections,
arch,
format,
&opts.badbytes,
&lopts,
)
.map_err(chain_err)?
}
"windows-virtualprotect" => {
let Target::Pe(pe) = &target else {
unreachable!("dispatched above")
};
let mut wopts = win_opts(spec)?;
wopts.exports = pe_exports::parse_pe_exports(bytes, pe.image_base());
let chain = rf_chain::build_windows_virtualprotect(
&gadgets,
&data_sections,
pe.imports(),
arch,
format,
&wopts,
&opts.badbytes,
)
.map_err(chain_err)?;
assumptions = Some(
rf_chain::windows::windows_assumptions(&data_sections, arch, &wopts)
.map_err(chain_err)?,
);
chain
}
_ => unreachable!("validated above"),
};
Ok(ChainOutcome {
chain,
assumptions,
outcome: ScanOutcome {
result: ScanResult {
gadgets,
addr_size: prepared.view.addr_size(),
universal_arch,
selected_sections: prepared.selected_sections,
},
opts,
fallback_names: prepared.fallback_names,
},
})
}
pub fn target_base(target: &Target) -> u64 {
match target {
Target::Elf(b) => b.image_base(),
Target::Pe(b) => b.image_base(),
Target::MachO(b) => b.image_base(),
Target::Raw(b) => b.image_base(),
Target::Universal(u) => u.slices()[0].image_base(),
}
}
pub fn fmt_addr(vaddr: u64, addr_size: usize) -> String {
match addr_size {
4 => format!("0x{vaddr:08x}"),
_ => format!("0x{vaddr:016x}"),
}
}
pub fn section_of(selected: &[(String, u64, u64)], vaddr: u64) -> Option<String> {
selected
.iter()
.find(|(_, s_vaddr, s_size)| vaddr >= *s_vaddr && vaddr < s_vaddr.wrapping_add(*s_size))
.map(|(name, _, _)| name.clone())
}