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

commit 7e142d181093c6de9f6a0732760e3aff63a8a751
parent 72e797f4a782e108f7876735dc1746389f74c549
Author: djnn <[email protected]>
Date: Sun, 27 Sep 2026 21:00:41 +0900

fix(core): ranking consistency fixes

Diffstat:
Msrc/arch/aarch64.rs | 14++++++++++----
Msrc/arch/arm.rs | 34+++++++++++++++++++++++++---------
Msrc/arch/mod.rs | 77+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Msrc/rules.rs | 107+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------

4 files changed, 204 insertions(+), 28 deletions(-)

diff --git a/src/arch/aarch64.rs b/src/arch/aarch64.rs
@@ -41,10 +41,16 @@ pub fn decode(mnemonic: &str, o: &[Op; 3]) -> Option<Kind> {
             base: reg(o, 1)?,
             imm: -imm(o, 2)?,
         }),
-        "mov" => Some(Kind::Mov {
-            dst: reg(o, 0)?,
-            src: reg(o, 1)?,
-        }),
+        "mov" => match o[1] {
+            Op::Imm(val) => Some(Kind::SetConst {
+                dst: reg(o, 0)?,
+                val: val as u64,
+            }),
+            _ => Some(Kind::Mov {
+                dst: reg(o, 0)?,
+                src: reg(o, 1)?,
+            }),
+        },
         _ => None,
     }
 }
diff --git a/src/arch/arm.rs b/src/arch/arm.rs
@@ -78,15 +78,31 @@ pub fn decode(mnemonic: &str, o: &[Op; 3], addr: u64, bin: &Binary) -> Option<Ki
                 })
             }
         }
-        "sub" => Some(Kind::AddImm {
-            dst: reg(o, 0)?,
-            base: reg(o, 1)?,
-            imm: -imm(o, 2)?,
-        }),
-        "mov" => Some(Kind::Mov {
-            dst: reg(o, 0)?,
-            src: reg(o, 1)?,
-        }),
+        "sub" => {
+            let (dst, base) = (reg(o, 0)?, reg(o, 1)?);
+            if base == ArmReg::ARM_REG_PC as u16 {
+                Some(Kind::SetConst {
+                    dst,
+                    val: pc_relative(addr, -imm(o, 2)?),
+                })
+            } else {
+                Some(Kind::AddImm {
+                    dst,
+                    base,
+                    imm: -imm(o, 2)?,
+                })
+            }
+        }
+        "mov" => match o[1] {
+            Op::Imm(val) => Some(Kind::SetConst {
+                dst: reg(o, 0)?,
+                val: val as u64,
+            }),
+            _ => Some(Kind::Mov {
+                dst: reg(o, 0)?,
+                src: reg(o, 1)?,
+            }),
+        },
         _ => None,
     }
 }
diff --git a/src/arch/mod.rs b/src/arch/mod.rs
@@ -5,7 +5,7 @@ pub mod mips;
 use crate::load::Binary;
 use anyhow::Result;
 use capstone::arch::arm::ArmOperandType;
-use capstone::arch::arm64::Arm64OperandType;
+use capstone::arch::arm64::{Arm64OperandType, Arm64Shift};
 use capstone::arch::mips::MipsOperand;
 use capstone::arch::ArchOperand;
 use capstone::prelude::*;
@@ -162,7 +162,10 @@ fn operands(ops: &[ArchOperand]) -> [Op; 3] {
         },
         Some(ArchOperand::Arm64Operand(o)) => match o.op_type {
             Arm64OperandType::Reg(r) => Op::Reg(r.0),
-            Arm64OperandType::Imm(v) => Op::Imm(v),
+            Arm64OperandType::Imm(v) => match o.shift {
+                Arm64Shift::Lsl(n) => Op::Imm(v << n),
+                _ => Op::Imm(v),
+            },
             Arm64OperandType::Mem(m) => Op::Mem(m.base().0, m.disp() as i64),
             _ => Op::None,
         },
@@ -278,3 +281,73 @@ pub fn resolve_stubs(bin: &Binary, insns: &[Ins]) -> HashMap<u64, String> {
     }
     out
 }
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use std::collections::{HashMap, HashSet};
+    use std::path::PathBuf;
+
+    fn dummy(arch: Arch, little: bool) -> Binary {
+        Binary {
+            path: PathBuf::new(),
+            data: vec![],
+            arch,
+            little,
+            entry: 0,
+            segs: vec![],
+            got2sym: HashMap::new(),
+            undef_stub: vec![],
+            imports: HashSet::new(),
+            exports: vec![],
+            locals: vec![],
+            gp: None,
+        }
+    }
+
+    fn decode_one(arch: Arch, bytes: &[u8], addr: u64, want_mnem: &str) -> Kind {
+        let bin = dummy(arch, true);
+        let cs = build(arch, true).unwrap();
+        let insns = cs.disasm_count(bytes, addr, 1).unwrap();
+        let insn = insns.iter().next().expect("no instruction decoded");
+        assert_eq!(insn.mnemonic(), Some(want_mnem));
+        classify(&cs, &bin, insn).expect("classify returned None")
+    }
+
+    #[test]
+    fn aarch64_add_lsl12_scales_imm() {
+        let k = decode_one(Arch::Aarch64, &[0xbe, 0x07, 0x40, 0x11], 0, "add");
+        match k {
+            Kind::AddImm { imm, .. } => assert_eq!(imm, 0x1000),
+            other => panic!("got {other:?}"),
+        }
+    }
+
+    #[test]
+    fn aarch64_mov_imm_recovers_const() {
+        let k = decode_one(Arch::Aarch64, &[0xe1, 0xff, 0x9f, 0x52], 0, "mov");
+        match k {
+            Kind::SetConst { val, .. } => assert_eq!(val, 0xffff),
+            other => panic!("got {other:?}"),
+        }
+    }
+
+    #[test]
+    fn arm_mov_imm_recovers_const() {
+        let k = decode_one(Arch::Arm, &[0x07, 0x30, 0xa0, 0xe3], 0, "mov");
+        match k {
+            Kind::SetConst { val, .. } => assert_eq!(val, 7),
+            other => panic!("got {other:?}"),
+        }
+    }
+
+    #[test]
+    fn arm_sub_pc_is_pc_resolved() {
+        let addr = 0u64;
+        let k = decode_one(Arch::Arm, &[0x04, 0x00, 0x4f, 0xe2], addr, "sub");
+        match k {
+            Kind::SetConst { val, .. } => assert_eq!(val, addr + 8 - 4),
+            other => panic!("got {other:?}"),
+        }
+    }
+}
diff --git a/src/rules.rs b/src/rules.rs
@@ -91,6 +91,7 @@ pub const SHELL: &[&str] = &[
     "ugs_execRoot_shell",
     "prctl_runCommandInShellWithTimeout",
     "safe_popen",
+    "qid_sys_execute_update_script",
 ];
 pub const SHELL_ARG1: &[&str] = &["SLIBCExecl"];
 pub const EVAL: &[&str] = &[
@@ -554,14 +555,15 @@ fn unbounded_scan(fmt: &str) -> bool {
             i = j + 1;
             continue;
         }
-        if j < chars.len() && chars[j] == '*' {
+        let suppressed = j < chars.len() && chars[j] == '*';
+        if suppressed {
             j += 1;
         }
         let had_width = j < chars.len() && chars[j].is_ascii_digit();
         while j < chars.len() && chars[j].is_ascii_digit() {
             j += 1;
         }
-        if j < chars.len() && (chars[j] == 's' || chars[j] == '[') && !had_width {
+        if j < chars.len() && (chars[j] == 's' || chars[j] == '[') && !had_width && !suppressed {
             return true;
         }
         i = j + 1;
@@ -650,11 +652,7 @@ fn socket_paths(g: &Graph) -> Vec<String> {
 }
 
 fn is_exec_primitive(import: &str) -> bool {
-    SHELL.contains(&import)
-        || PRINTF_EXEC.contains(&import)
-        || ARGV_EXEC.contains(&import)
-        || import.contains("exec")
-        || import.contains("system_cmd")
+    SHELL.contains(&import) || PRINTF_EXEC.contains(&import) || ARGV_EXEC.contains(&import)
 }
 
 fn exec_imports(bin: &Binary) -> Vec<&str> {
@@ -687,7 +685,7 @@ impl<'a> Scan<'a> {
         Scan {
             bin,
             graph,
-            name: bin.name(),
+            name: bin.path.to_string_lossy().into_owned(),
             reach: graph.reach_from(UNTRUSTED_INPUTS),
             wrappers: graph.shell_equivalent(&seeds),
             calls: call_index(graph),
@@ -941,7 +939,8 @@ fn sized_write(s: &Site, len: usize) -> Option<Hit> {
         return Some(h);
     }
     let fortify_disabled = fortify_bound(s).is_some_and(is_neutered);
-    let stack_dest = s.stack(0);
+    let dest = if s.imp == "bcopy" { 1 } else { 0 };
+    let stack_dest = s.stack(dest);
     let measures_reachable_input = measures_input(s) && s.reach == Some(0);
     let suspicious = stack_dest.is_some() || fortify_disabled || measures_reachable_input;
     if !s.unknown(len) || !suspicious {
@@ -1131,7 +1130,7 @@ fn unix_listener(s: &Site) -> Option<Hit> {
     for p in s.scan.unix_paths.iter().take(MAX_SOCKET_PATHS) {
         h.note(format!("socket path {p:?}"));
     }
-    if s.scan.no_peercred {
+    if s.scan.no_peercred && !s.scan.unix_paths.is_empty() {
         h.bump(30, "no SO_PEERCRED / getpeereid anywhere in this binary");
     }
     let execs = &s.scan.exec_imports;
@@ -1500,9 +1499,9 @@ mod tests {
     }
 
     #[test]
-    fn unbounded_scan_treats_suppressed_star_as_unbounded() {
-        // %*s discards input into no buffer, yet the parser still flags it.
-        assert!(unbounded_scan("%*s"));
+    fn unbounded_scan_ignores_suppressed_star() {
+        assert!(!unbounded_scan("%*s"));
+        assert!(!unbounded_scan("%*[^\n]"));
     }
 
     #[test]
@@ -1538,4 +1537,86 @@ mod tests {
         assert_eq!(mode_note(0o0666), Some("world-writable mode 0o666".to_string()));
         assert_eq!(mode_note(0o0755), None);
     }
+
+    fn bin(arch: crate::arch::Arch, imports: &[&str]) -> Binary {
+        Binary {
+            path: "/rootfs/bin/foo".into(),
+            data: vec![],
+            arch,
+            little: true,
+            entry: 0,
+            segs: vec![],
+            got2sym: HashMap::new(),
+            undef_stub: vec![],
+            imports: imports.iter().map(|s| s.to_string()).collect(),
+            exports: vec![],
+            locals: vec![],
+            gp: None,
+        }
+    }
+
+    fn graph(sites: Vec<CallSite>, strings: HashMap<u64, Vec<String>>) -> Graph {
+        Graph {
+            names: HashMap::new(),
+            sites,
+            edges: HashMap::new(),
+            strings,
+            addr_taken: HashSet::new(),
+        }
+    }
+
+    fn site(import: &str, args: Vec<Option<Val>>) -> CallSite {
+        CallSite { site: 0x1000, func: 0, import: Some(import.into()), target: 0, args }
+    }
+
+    #[test]
+    fn is_exec_primitive_rejects_substrings() {
+        assert!(!is_exec_primitive("regexec"));
+        assert!(!is_exec_primitive("sqlite3_exec"));
+        assert!(!is_exec_primitive("pcre_exec"));
+        assert!(is_exec_primitive("system"));
+        assert!(is_exec_primitive("qid_sys_execute_update_script"));
+    }
+
+    #[test]
+    fn finding_bin_carries_full_path_not_basename() {
+        let b = bin(crate::arch::Arch::Aarch64, &[]);
+        let g = graph(vec![site("system", vec![None])], HashMap::new());
+        let findings = analyze(&b, &g);
+        assert!(findings.iter().any(|f| f.bin == "/rootfs/bin/foo"));
+        assert!(!findings.iter().any(|f| f.bin == "foo"));
+    }
+
+    #[test]
+    fn bind_tcp_without_socket_evidence_omits_peercred_bonus() {
+        let b = bin(crate::arch::Arch::Aarch64, &[]);
+        let g = graph(vec![site("bind", vec![])], HashMap::new());
+        let findings = analyze(&b, &g);
+        assert!(!findings
+            .iter()
+            .any(|f| f.evidence.iter().any(|e| e.contains("no SO_PEERCRED"))));
+    }
+
+    #[test]
+    fn bind_unix_socket_fires_peercred_bonus() {
+        let b = bin(crate::arch::Arch::Aarch64, &[]);
+        let mut strings = HashMap::new();
+        strings.insert(0x1000u64, vec!["/tmp/foo.sock".to_string()]);
+        let g = graph(vec![site("bind", vec![])], strings);
+        let findings = analyze(&b, &g);
+        assert!(findings
+            .iter()
+            .any(|f| f.evidence.iter().any(|e| e.contains("no SO_PEERCRED"))));
+    }
+
+    #[test]
+    fn bcopy_destination_is_arg1() {
+        let b = bin(crate::arch::Arch::Aarch64, &[]);
+        let args = vec![None, Some(Val::Stack(-0x10)), None];
+        let g = graph(vec![site("bcopy", args)], HashMap::new());
+        let findings = analyze(&b, &g);
+        assert!(findings
+            .iter()
+            .any(|f| f.evidence.iter().any(|e| e.contains("stack buffer"))));
+    }
 }