balrog.git


balrog

~ ELF file analysis tool to be used after firmware extraction
git clone https://github.com/djnnvx/balrog.git
log | files | refs | archive | README

graph.rs (12371B)

      1 use crate::arch::{self, Ins, Kind};
      2 use crate::load::Binary;
      3 use std::collections::hash_map::Entry;
      4 use std::collections::{HashMap, HashSet, VecDeque};
      5 
      6 #[derive(Clone, Copy, Debug, PartialEq)]
      7 pub enum Val {
      8     Num(u64),
      9     Stack(i64),
     10     Import(u64),
     11     Ret(usize),
     12 }
     13 
     14 pub struct CallSite {
     15     pub site: u64,
     16     pub func: u64,
     17     pub import: Option<String>,
     18     pub target: u64,
     19     pub args: Vec<Option<Val>>,
     20 }
     21 
     22 pub struct Graph {
     23     pub names: HashMap<u64, String>,
     24     pub sites: Vec<CallSite>,
     25     pub edges: HashMap<u64, HashSet<u64>>,
     26     pub strings: HashMap<u64, Vec<String>>,
     27     pub addr_taken: HashSet<u64>,
     28 }
     29 
     30 fn function_starts(bin: &Binary, insns: &[Ins], stubs: &HashMap<u64, String>) -> Vec<u64> {
     31     let decoded: HashSet<u64> = insns.iter().map(|ins| ins.addr).collect();
     32     let mut starts: HashSet<u64> = HashSet::new();
     33     if decoded.contains(&bin.entry) {
     34         starts.insert(bin.entry);
     35     }
     36     for (_, addr) in bin.locals.iter().chain(bin.exports.iter()) {
     37         if decoded.contains(addr) {
     38             starts.insert(*addr);
     39         }
     40     }
     41     for ins in insns {
     42         if let Kind::Call(target) = ins.kind {
     43             if !stubs.contains_key(&target) && decoded.contains(&target) {
     44                 starts.insert(target);
     45             }
     46         }
     47     }
     48     for addr in stubs.keys() {
     49         starts.remove(addr);
     50     }
     51     let mut starts: Vec<u64> = starts.into_iter().collect();
     52     starts.sort_unstable();
     53     starts
     54 }
     55 
     56 fn function_names(bin: &Binary) -> HashMap<u64, String> {
     57     let mut names = HashMap::new();
     58     for (name, addr) in bin.locals.iter().chain(bin.exports.iter()) {
     59         names.entry(*addr).or_insert_with(|| name.clone());
     60     }
     61     names
     62 }
     63 
     64 struct Regs<'a> {
     65     bin: &'a Binary,
     66     sp: u16,
     67     gp: Option<u16>,
     68     nargs: usize,
     69     vals: HashMap<u16, Val>,
     70 }
     71 
     72 impl<'a> Regs<'a> {
     73     fn new(bin: &'a Binary) -> Regs<'a> {
     74         Regs {
     75             bin,
     76             sp: arch::sp_reg(bin.arch),
     77             gp: arch::gp_reg(bin.arch),
     78             nargs: arch::arg_count(bin.arch),
     79             vals: HashMap::new(),
     80         }
     81     }
     82 
     83     fn enter(&mut self) {
     84         self.vals.clear();
     85         self.vals.insert(self.sp, Val::Stack(0));
     86         self.pin_gp();
     87     }
     88 
     89     fn pin_gp(&mut self) {
     90         if let (Some(g), Some(r)) = (self.bin.gp, self.gp) {
     91             self.vals.insert(r, Val::Num(g));
     92         }
     93     }
     94 
     95     fn set(&mut self, dst: u16, v: Option<Val>) -> Option<Val> {
     96         match v {
     97             Some(v) => self.vals.insert(dst, v),
     98             None => self.vals.remove(&dst),
     99         };
    100         v
    101     }
    102 
    103     fn got_slot(&self, base: u16, disp: i64) -> Option<u64> {
    104         match self.vals.get(&base) {
    105             Some(Val::Num(addr)) => Some(addr.wrapping_add(disp as u64)),
    106             _ => None,
    107         }
    108     }
    109 
    110     fn step(&mut self, kind: Kind) -> Option<Val> {
    111         let wrote = match kind {
    112             Kind::SetConst { dst, val } | Kind::PcVal { dst, val } => {
    113                 self.set(dst, Some(Val::Num(val)))
    114             }
    115             Kind::AddImm { dst, base, imm } => {
    116                 let sum = match self.vals.get(&base) {
    117                     Some(Val::Num(addr)) => Some(Val::Num(addr.wrapping_add(imm as u64))),
    118                     Some(Val::Stack(offset)) => Some(Val::Stack(offset + imm)),
    119                     _ => None,
    120                 };
    121                 self.set(dst, sum)
    122             }
    123             Kind::Mov { dst, src } => {
    124                 let moved = self.vals.get(&src).copied();
    125                 self.set(dst, moved)
    126             }
    127             Kind::Load { dst, base, disp } => {
    128                 let import = self
    129                     .got_slot(base, disp)
    130                     .filter(|slot| self.bin.got2sym.contains_key(slot))
    131                     .map(Val::Import);
    132                 self.set(dst, import)
    133             }
    134             _ => None,
    135         };
    136         self.pin_gp();
    137         wrote
    138     }
    139 
    140     fn arg_value(&self, index: usize) -> Option<Val> {
    141         let reg = arch::arg_reg(self.bin.arch, index)?;
    142         let value = self.vals.get(&reg).copied()?;
    143         if matches!(value, Val::Import(_)) {
    144             return None;
    145         }
    146         Some(value)
    147     }
    148 
    149     fn args(&self) -> Vec<Option<Val>> {
    150         (0..self.nargs).map(|index| self.arg_value(index)).collect()
    151     }
    152 
    153     fn import_at(&self, reg: u16) -> Option<&String> {
    154         match self.vals.get(&reg) {
    155             Some(Val::Import(slot)) => self.bin.got2sym.get(slot),
    156             _ => None,
    157         }
    158     }
    159 
    160     fn returned(&mut self, site: Option<usize>) {
    161         if let Some(r) = arch::ret_reg(self.bin.arch) {
    162             self.set(r, site.map(Val::Ret));
    163         }
    164     }
    165 
    166     fn clobber_args(&mut self) {
    167         for n in 0..self.nargs {
    168             if let Some(r) = arch::arg_reg(self.bin.arch, n) {
    169                 self.vals.remove(&r);
    170             }
    171         }
    172     }
    173 }
    174 
    175 const MAX_STRINGS_PER_FUNC: usize = 24;
    176 const MIN_STRING_LEN: usize = 4;
    177 
    178 fn record_constant(bin: &Binary, func: u64, value: u64, starts: &[u64], out: &mut Graph) {
    179     if starts.binary_search(&value).is_ok() {
    180         out.addr_taken.insert(value);
    181         return;
    182     }
    183     let Some(text) = bin.cstr_at(value) else {
    184         return;
    185     };
    186     if text.len() < MIN_STRING_LEN {
    187         return;
    188     }
    189     let strings = out.strings.entry(func).or_default();
    190     if strings.len() < MAX_STRINGS_PER_FUNC && !strings.contains(&text) {
    191         strings.push(text);
    192     }
    193 }
    194 
    195 fn first_arg_is_constant(site: &CallSite) -> bool {
    196     matches!(site.args.first(), Some(Some(Val::Num(_))))
    197 }
    198 
    199 impl Graph {
    200     pub fn build(bin: &Binary, insns: &[Ins], stubs: HashMap<u64, String>) -> Graph {
    201         let starts = function_starts(bin, insns, &stubs);
    202         let mut g = Graph {
    203             names: function_names(bin),
    204             sites: Vec::new(),
    205             edges: HashMap::new(),
    206             strings: HashMap::new(),
    207             addr_taken: HashSet::new(),
    208         };
    209         let mut regs = Regs::new(bin);
    210         let mut cur_func: u64 = starts.first().copied().unwrap_or(0);
    211 
    212         for ins in insns {
    213             if starts.binary_search(&ins.addr).is_ok() {
    214                 cur_func = ins.addr;
    215                 regs.enter();
    216             }
    217             let wrote = regs.step(ins.kind);
    218             match ins.kind {
    219                 Kind::Call(target) => {
    220                     let import = stubs.get(&target).cloned();
    221                     if import.is_none() && starts.binary_search(&target).is_ok() {
    222                         g.edges.entry(cur_func).or_default().insert(target);
    223                     }
    224                     g.sites.push(CallSite {
    225                         site: ins.addr,
    226                         func: cur_func,
    227                         import,
    228                         target,
    229                         args: regs.args(),
    230                     });
    231                     regs.clobber_args();
    232                     regs.returned(Some(g.sites.len() - 1));
    233                 }
    234                 Kind::CallInd { reg } => {
    235                     let mut pushed = None;
    236                     if let Some(name) = regs.import_at(reg).cloned() {
    237                         g.sites.push(CallSite {
    238                             site: ins.addr,
    239                             func: cur_func,
    240                             import: Some(name),
    241                             target: 0,
    242                             args: regs.args(),
    243                         });
    244                         pushed = Some(g.sites.len() - 1);
    245                     }
    246                     regs.clobber_args();
    247                     regs.returned(pushed);
    248                 }
    249                 // enter() only resets at detected function starts; a return is the other frame boundary.
    250                 Kind::Ret => regs.enter(),
    251                 _ => {}
    252             }
    253             if let Some(Val::Num(value)) = wrote {
    254                 record_constant(bin, cur_func, value, &starts, &mut g);
    255             }
    256         }
    257         g
    258     }
    259 
    260     pub fn func_name(&self, addr: u64) -> String {
    261         self.names
    262             .get(&addr)
    263             .cloned()
    264             .unwrap_or_else(|| format!("sub_{addr:x}"))
    265     }
    266 
    267     pub fn reach_from(&self, inputs: &[&str]) -> HashMap<u64, u32> {
    268         let mut dist: HashMap<u64, u32> = HashMap::new();
    269         let mut queue = VecDeque::new();
    270         for site in &self.sites {
    271             let Some(import) = &site.import else { continue };
    272             if inputs.contains(&import.as_str()) {
    273                 dist.insert(site.func, 0);
    274                 queue.push_back(site.func);
    275             }
    276         }
    277         while let Some(func) = queue.pop_front() {
    278             let depth = dist[&func];
    279             let Some(callees) = self.edges.get(&func) else {
    280                 continue;
    281             };
    282             for &callee in callees {
    283                 if let Entry::Vacant(slot) = dist.entry(callee) {
    284                     slot.insert(depth + 1);
    285                     queue.push_back(callee);
    286                 }
    287             }
    288         }
    289         dist
    290     }
    291 
    292     pub fn shell_equivalent(&self, seeds: &[&str]) -> HashSet<u64> {
    293         let mut tainted: HashSet<u64> = HashSet::new();
    294         for site in &self.sites {
    295             let Some(import) = &site.import else { continue };
    296             if seeds.contains(&import.as_str()) && !first_arg_is_constant(site) {
    297                 tainted.insert(site.func);
    298             }
    299         }
    300         loop {
    301             let before = tainted.len();
    302             for site in &self.sites {
    303                 if site.import.is_none()
    304                     && tainted.contains(&site.target)
    305                     && !first_arg_is_constant(site)
    306                 {
    307                     tainted.insert(site.func);
    308                 }
    309             }
    310             if tainted.len() == before {
    311                 break;
    312             }
    313         }
    314         tainted
    315     }
    316 }
    317 
    318 #[cfg(test)]
    319 mod tests {
    320     use super::*;
    321     use crate::arch::{arg_reg, Arch, Ins, Kind};
    322 
    323     fn empty_bin() -> Binary {
    324         Binary {
    325             path: "/t".into(),
    326             data: vec![],
    327             arch: Arch::Aarch64,
    328             little: true,
    329             entry: 0,
    330             segs: vec![],
    331             got2sym: HashMap::new(),
    332             undef_stub: vec![],
    333             imports: HashSet::new(),
    334             exports: vec![],
    335             locals: vec![],
    336             gp: None,
    337         }
    338     }
    339 
    340     fn stream() -> (Vec<Ins>, HashMap<u64, String>) {
    341         let x0 = arg_reg(Arch::Aarch64, 0).unwrap();
    342         let x2 = arg_reg(Arch::Aarch64, 2).unwrap();
    343         let insns = vec![
    344             Ins {
    345                 addr: 0x0,
    346                 kind: Kind::Call(0x100),
    347             },
    348             Ins {
    349                 addr: 0x4,
    350                 kind: Kind::Ret,
    351             },
    352             Ins {
    353                 addr: 0x8,
    354                 kind: Kind::Mov { dst: x2, src: x0 },
    355             },
    356             Ins {
    357                 addr: 0xc,
    358                 kind: Kind::Call(0x200),
    359             },
    360         ];
    361         let stubs = HashMap::from([(0x100, "recv".to_string()), (0x200, "memcpy".to_string())]);
    362         (insns, stubs)
    363     }
    364 
    365     #[test]
    366     fn ret_stops_cross_function_ret_leak() {
    367         let (insns, stubs) = stream();
    368         let g = Graph::build(&empty_bin(), &insns, stubs);
    369         let memcpy = g
    370             .sites
    371             .iter()
    372             .find(|s| s.import.as_deref() == Some("memcpy"))
    373             .unwrap();
    374         assert_eq!(
    375             memcpy.args.get(2),
    376             Some(&None),
    377             "recv return leaked across ret into memcpy"
    378         );
    379     }
    380 
    381     #[test]
    382     fn call_return_flows_to_next_sink() {
    383         let x0 = arg_reg(Arch::Aarch64, 0).unwrap();
    384         let x2 = arg_reg(Arch::Aarch64, 2).unwrap();
    385         let insns = vec![
    386             Ins {
    387                 addr: 0x0,
    388                 kind: Kind::Call(0x100),
    389             },
    390             Ins {
    391                 addr: 0x4,
    392                 kind: Kind::Mov { dst: x2, src: x0 },
    393             },
    394             Ins {
    395                 addr: 0x8,
    396                 kind: Kind::Call(0x200),
    397             },
    398         ];
    399         let stubs = HashMap::from([(0x100, "recv".to_string()), (0x200, "memcpy".to_string())]);
    400         let g = Graph::build(&empty_bin(), &insns, stubs);
    401         let memcpy = g
    402             .sites
    403             .iter()
    404             .find(|s| s.import.as_deref() == Some("memcpy"))
    405             .unwrap();
    406         assert_eq!(memcpy.args.get(2), Some(&Some(Val::Ret(0))));
    407     }
    408 }