Skip to main content

crackers/config/
constraint.rs

1use crate::error::CrackersError;
2use crate::synthesis::builder::{StateConstraintGenerator, TransitionConstraintGenerator};
3use jingle::modeling::{ModeledBlock, ModelingContext, State};
4use jingle::sleigh::{SleighArchInfo, VarNode};
5use jingle::varnode::{ResolvedIndirectVarNode, ResolvedVarnode};
6#[cfg(feature = "pyo3")]
7use pyo3::pyclass;
8use serde::{Deserialize, Serialize};
9use std::borrow::Borrow;
10use std::collections::HashMap;
11use std::ops::Add;
12use std::sync::Arc;
13use tracing::{Level, event};
14use z3::ast::{BV, Bool};
15
16#[derive(Clone, Debug, Deserialize, Serialize, Default)]
17#[cfg_attr(feature = "pyo3", pyclass(get_all, set_all))]
18pub struct ConstraintConfig {
19    pub precondition: Option<StateEqualityConstraint>,
20    pub postcondition: Option<StateEqualityConstraint>,
21    pub pointer: Option<PointerRangeConstraints>,
22}
23
24impl ConstraintConfig {
25    pub fn get_preconditions<T: Borrow<SleighArchInfo>>(
26        &self,
27        sleigh: T,
28    ) -> impl Iterator<Item = Arc<StateConstraintGenerator>> {
29        let sleigh = sleigh.borrow().clone();
30        self.precondition
31            .iter()
32            .flat_map(move |c| c.constraints(sleigh.clone(), self.pointer.clone()))
33    }
34
35    pub fn get_postconditions<T: Borrow<SleighArchInfo>>(
36        &self,
37        sleigh: T,
38    ) -> impl Iterator<Item = Arc<StateConstraintGenerator>> {
39        self.postcondition
40            .iter()
41            .flat_map(move |c| c.constraints(sleigh.borrow().clone(), self.pointer.clone()))
42    }
43
44    pub fn get_pointer_constraints(
45        &self,
46    ) -> impl Iterator<Item = Arc<TransitionConstraintGenerator>> + '_ {
47        self.pointer.iter().map(|c| c.constraints())
48    }
49}
50
51#[derive(Clone, Debug, Deserialize, Serialize)]
52#[cfg_attr(feature = "pyo3", pyclass(get_all, set_all))]
53pub struct StateEqualityConstraint {
54    pub register: Option<HashMap<String, i64>>,
55    pub pointer: Option<HashMap<String, String>>,
56    pub memory: Option<MemoryEqualityConstraint>,
57}
58
59impl StateEqualityConstraint {
60    pub fn constraints<T: Borrow<SleighArchInfo>>(
61        &self,
62        info: T,
63        c: Option<PointerRangeConstraints>,
64    ) -> impl Iterator<Item = Arc<StateConstraintGenerator>> {
65        let info = info.borrow().clone();
66        let info2 = info.clone();
67        let register_iterator = self.register.iter().flat_map(move |map| {
68            let info = info.clone();
69            map.iter().filter_map(move |(name, value)| {
70                if let Some(vn) = info.register(name) {
71                    Some(Arc::new(gen_register_constraint(vn.clone(), *value as u64))
72                        as Arc<StateConstraintGenerator>)
73                } else {
74                    event!(Level::WARN, "Unrecognized register name: {}", name);
75                    None
76                }
77            })
78        });
79        let memory_iterator = self
80            .memory
81            .iter()
82            .map(|c| Arc::new(gen_memory_constraint(c.clone())) as Arc<StateConstraintGenerator>);
83        let info = info2;
84        let pointer_iterator = self.pointer.iter().flat_map(move |map| {
85            let c1 = c.clone();
86            let info = info.clone();
87            map.iter().filter_map(move |(name, value)| {
88                if let Some(vn) = info.register(name) {
89                    Some(Arc::new(gen_register_pointer_constraint(
90                        vn.clone(),
91                        value.clone(),
92                        c1.clone(),
93                    )) as Arc<StateConstraintGenerator>)
94                } else {
95                    event!(Level::WARN, "Unrecognized register name: {}", name);
96                    None
97                }
98            })
99        });
100        register_iterator
101            .chain(memory_iterator)
102            .chain(pointer_iterator)
103    }
104}
105
106#[derive(Clone, Debug, Deserialize, Serialize)]
107#[cfg_attr(feature = "pyo3", pyclass(get_all, set_all))]
108pub struct MemoryEqualityConstraint {
109    pub space: String,
110    pub address: u64,
111    pub size: usize,
112    pub value: u8,
113}
114
115#[derive(Clone, Debug, Deserialize, Serialize, Default)]
116#[cfg_attr(feature = "pyo3", pyclass(get_all, set_all))]
117pub struct PointerRangeConstraints {
118    pub read: Option<Vec<PointerRange>>,
119    pub write: Option<Vec<PointerRange>>,
120}
121
122impl PointerRangeConstraints {
123    pub fn constraints(&self) -> Arc<TransitionConstraintGenerator> {
124        Arc::new(gen_pointer_range_transition_invariant(self.clone()))
125    }
126}
127#[derive(Copy, Clone, Debug, Deserialize, Serialize)]
128#[cfg_attr(feature = "pyo3", pyclass(get_all, set_all))]
129pub struct PointerRange {
130    pub min: u64,
131    pub max: u64,
132}
133
134/// Generates a state constraint that a given varnode must be equal to a given value
135pub fn gen_memory_constraint(
136    m: MemoryEqualityConstraint,
137) -> impl Fn(&State, u64) -> Result<Bool, CrackersError> + Send + Sync + Clone + 'static {
138    move |state, _addr| {
139        let data = state.read_varnode(
140            &state
141                .arch_info()
142                .varnode(&m.space, m.address, m.size)
143                .unwrap(),
144        )?;
145        let constraint = data.eq(BV::from_u64(m.value as u64, data.get_size()));
146        Ok(constraint)
147    }
148}
149
150/// Generates a state constraint that a given varnode must be equal to a given value
151/// todo: can consolidate this with the above one I think
152pub fn gen_register_constraint(
153    vn: VarNode,
154    value: u64,
155) -> impl Fn(&State, u64) -> Result<Bool, CrackersError> + 'static + Send + Sync + Clone {
156    move |state, _addr| {
157        let data = state.read_varnode(&vn)?;
158        let constraint = data.eq(BV::from_u64(value, data.get_size()));
159        Ok(constraint)
160    }
161}
162
163/// Generates a constraint enforcing that the given varnode contains a pointer into the default
164/// code space, pointing to the provided string
165pub fn gen_register_pointer_constraint(
166    vn: VarNode,
167    value: String,
168    m: Option<PointerRangeConstraints>,
169) -> impl Fn(&State, u64) -> Result<Bool, CrackersError> + Clone {
170    move |state, _addr| {
171        let m = m.clone();
172        let mut bools = vec![];
173        let pointer = state.read_varnode(&vn)?;
174        for (i, byte) in value.as_bytes().iter().enumerate() {
175            let expected = BV::from_u64(*byte as u64, 8);
176            let char_ptr = ResolvedVarnode::Indirect(ResolvedIndirectVarNode {
177                // dumb but whatever
178                pointer_location: vn.clone(),
179                pointer: pointer.clone().add(i as u64),
180                access_size_bytes: 1,
181                pointer_space_idx: state.get_default_code_space_info().index,
182            });
183            let actual = state.read_resolved(&char_ptr)?;
184            bools.push(actual.eq(&expected))
185        }
186        let pointer = state.read_varnode(&vn)?;
187        let resolved = ResolvedVarnode::Indirect(ResolvedIndirectVarNode {
188            pointer_location: vn.clone(),
189            pointer_space_idx: state.get_default_code_space_info().index,
190            access_size_bytes: value.len(),
191            pointer,
192        });
193        let mut constraint = Bool::and(&bools);
194        if let Some(c) = m.and_then(|m| m.read) {
195            let callback = gen_pointer_range_state_invariant(c);
196            let cc = callback(&resolved, state)?;
197            if let Some(b) = cc {
198                constraint = Bool::and(&[constraint, b])
199            }
200        }
201        Ok(constraint)
202    }
203}
204
205/// Generates an invariant enforcing that the given varnode, read from a given state, is within
206/// the given range.
207pub fn gen_pointer_range_state_invariant(
208    m: Vec<PointerRange>,
209) -> impl Fn(&ResolvedVarnode, &State) -> Result<Option<Bool>, CrackersError> + Clone {
210    move |vn, state| {
211        match vn {
212            ResolvedVarnode::Direct(d) => {
213                // todo: this is gross
214                let should_constrain =
215                    state.arch_info().default_code_space_index() == d.space_index;
216                match should_constrain {
217                    false => Ok(None),
218                    true => {
219                        let bool = m
220                            .iter()
221                            .any(|mm| d.offset >= mm.min && (d.offset + d.size as u64) <= mm.max);
222                        Ok(Some(Bool::from_bool(bool)))
223                    }
224                }
225            }
226            ResolvedVarnode::Indirect(vn) => {
227                let mut terms = vec![];
228                for mm in &m {
229                    let min = BV::from_u64(mm.min, vn.pointer.get_size());
230                    let max = BV::from_u64(mm.max, vn.pointer.get_size());
231                    let constraint = Bool::and(&[vn.pointer.bvuge(&min), vn.pointer.bvule(&max)]);
232                    terms.push(constraint);
233                }
234
235                Ok(Some(Bool::or(terms.as_slice())))
236            }
237        }
238    }
239}
240
241pub fn gen_pointer_range_transition_invariant(
242    m: PointerRangeConstraints,
243) -> impl Fn(&ModeledBlock) -> Result<Option<Bool>, CrackersError> + Send + Sync + Clone + 'static {
244    move |block| {
245        let mut bools = vec![];
246        if let Some(r) = &m.read {
247            let inv = gen_pointer_range_state_invariant(r.clone());
248            for x in block.get_inputs() {
249                if let Some(c) = inv(&x, block.get_final_state())? {
250                    bools.push(c);
251                }
252            }
253        }
254        if let Some(r) = &m.write {
255            let inv = gen_pointer_range_state_invariant(r.clone());
256            for x in block.get_outputs() {
257                if let Some(c) = inv(&x, block.get_final_state())? {
258                    bools.push(c);
259                }
260            }
261        }
262        Ok(Some(Bool::and(&bools)))
263    }
264}