1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
use super::State;
use super::WarningContext;
use super::CWE_MODULE;
use crate::abstract_domain::AbstractDomain;
use crate::abstract_domain::AbstractIdentifier;
use crate::analysis::function_signature::FunctionSignature;
use crate::analysis::graph::Graph;
use crate::analysis::pointer_inference::PointerInference;
use crate::analysis::vsa_results::VsaResult;
use crate::intermediate_representation::*;
use crate::prelude::*;
use crate::utils::log::CweWarning;
use crate::utils::log::LogMessage;
use std::collections::BTreeMap;
use std::collections::BTreeSet;

/// The context struct for the fixpoint algorithm that contains references to the analysis results
/// of other analyses used in this analysis.
pub struct Context<'a> {
    /// A pointer to the project struct.
    pub project: &'a Project,
    /// The names of extern functions that deallocate memory.
    /// These functions will create dangling pointers during the analysis.
    pub deallocation_symbols: BTreeSet<String>,
    /// A pointer to the control flow graph.
    pub graph: &'a Graph<'a>,
    /// A pointer to the results of the pointer inference analysis.
    pub pointer_inference: &'a PointerInference<'a>,
    /// A pointer to the computed function signatures for all internal functions.
    pub function_signatures: &'a BTreeMap<Tid, FunctionSignature>,
    /// A sender channel that can be used to collect context objects for CWEwarnings.
    pub cwe_warning_collector: crossbeam_channel::Sender<WarningContext>,
    /// A sender channel that can be used to collect log messages.
    pub log_collector: crossbeam_channel::Sender<LogMessage>,
    /// Generic function arguments assumed for calls to functions where the real number of parameters are unknown.
    generic_function_parameter: Vec<Arg>,
}

impl<'a> Context<'a> {
    /// Generate a new context struct from the given analysis results and a channel for gathering log messages and CWE warnings.
    pub fn new<'b>(
        analysis_results: &'b AnalysisResults<'a>,
        cwe_warning_collector: crossbeam_channel::Sender<WarningContext>,
        log_collector: crossbeam_channel::Sender<LogMessage>,
        deallocation_symbols: BTreeSet<String>,
    ) -> Context<'a>
    where
        'a: 'b,
    {
        let generic_function_parameter: Vec<_> =
            if let Some(cconv) = analysis_results.project.get_standard_calling_convention() {
                cconv
                    .integer_parameter_register
                    .iter()
                    .map(|reg| Arg::from_var(reg.clone(), None))
                    .collect()
            } else {
                Vec::new()
            };
        Context {
            project: analysis_results.project,
            deallocation_symbols,
            graph: analysis_results.control_flow_graph,
            pointer_inference: analysis_results.pointer_inference.unwrap(),
            function_signatures: analysis_results.function_signatures.unwrap(),
            cwe_warning_collector,
            log_collector,
            generic_function_parameter,
        }
    }

    /// For the given call parameters of the given call check for possible Use-After-Free bugs
    /// and return the possible causes for such bugs.
    fn collect_cwe_warnings_of_call_params<'b>(
        &self,
        state: &mut State,
        call_tid: &Tid,
        call_params: impl IntoIterator<Item = &'b Arg>,
    ) -> Option<Vec<(AbstractIdentifier, Vec<Tid>)>> {
        let mut warnings = Vec::new();
        for arg in call_params {
            if let Some(arg_value) = self
                .pointer_inference
                .eval_parameter_arg_at_call(call_tid, arg)
            {
                if let Some(mut warning_causes) = state.check_address_for_use_after_free(&arg_value)
                {
                    warnings.append(&mut warning_causes);
                }
            }
        }
        if !warnings.is_empty() {
            Some(warnings)
        } else {
            None
        }
    }

    /// Check the parameters of an internal function call for dangling pointers and report CWE warnings accordingly.
    fn check_internal_call_params_for_use_after_free(
        &self,
        state: &mut State,
        callee_sub_tid: &Tid,
        call_tid: &Tid,
    ) {
        let function_signature = match self.function_signatures.get(callee_sub_tid) {
            Some(fn_sig) => fn_sig,
            None => return,
        };
        let mut warning_causes = Vec::new();
        for (arg, access_pattern) in &function_signature.parameters {
            if access_pattern.is_dereferenced() {
                if let Some(arg_value) = self
                    .pointer_inference
                    .eval_parameter_location_at_call(call_tid, arg)
                {
                    if let Some(mut warnings) = state.check_address_for_use_after_free(&arg_value) {
                        warning_causes.append(&mut warnings);
                    }
                }
            }
        }
        let callee_sub_name = &self.project.program.term.subs[callee_sub_tid].term.name;
        if !warning_causes.is_empty() {
            self.generate_cwe_warning(
                "CWE416",
                format!(
                    "(Use After Free) Call to {} at {} may access dangling pointers through its parameters",
                    callee_sub_name,
                    call_tid.address
                ),
                call_tid,
                warning_causes,
                &state.current_fn_tid
            );
        }
    }

    /// Handle a call to `free` by marking the corresponding memory object IDs as dangling and detecting possible double frees.
    fn handle_call_to_free(&self, state: &mut State, call_tid: &Tid, free_symbol: &ExternSymbol) {
        if free_symbol.parameters.is_empty() {
            let error_msg = LogMessage::new_error("free symbol without parameter encountered.")
                .location(call_tid.clone())
                .source(CWE_MODULE.name);
            self.log_collector.send(error_msg).unwrap();
            return;
        }
        if let Some(param) = self
            .pointer_inference
            .eval_parameter_arg_at_call(call_tid, &free_symbol.parameters[0])
        {
            if let Some(pi_state) = self.pointer_inference.get_state_at_jmp_tid(call_tid) {
                if let Some(warning_causes) =
                    state.handle_param_of_free_call(call_tid, &param, pi_state)
                {
                    self.generate_cwe_warning(
                        "CWE415",
                        format!(
                            "(Double Free) Object may have been freed before at {}",
                            call_tid.address
                        ),
                        call_tid,
                        warning_causes,
                        &state.current_fn_tid,
                    );
                }
            }
        }
    }

    /// Generate a CWE warning and send it to the warning collector channel.
    fn generate_cwe_warning(
        &self,
        name: &str,
        description: String,
        location: &Tid,
        warning_causes: Vec<(AbstractIdentifier, Vec<Tid>)>,
        root_function: &Tid,
    ) {
        let cwe_warning = CweWarning {
            name: name.to_string(),
            version: CWE_MODULE.version.to_string(),
            addresses: vec![location.address.clone()],
            tids: vec![format!("{location}")],
            symbols: Vec::new(),
            other: Vec::new(),
            description,
        };
        self.cwe_warning_collector
            .send(WarningContext::new(
                cwe_warning,
                warning_causes,
                root_function.clone(),
            ))
            .unwrap();
    }
}

impl<'a> crate::analysis::forward_interprocedural_fixpoint::Context<'a> for Context<'a> {
    type Value = State;

    /// Get a reference to the control flow graph.
    fn get_graph(&self) -> &Graph<'a> {
        self.graph
    }

    /// Merge two node states.
    fn merge(&self, state1: &State, state2: &State) -> State {
        state1.merge(state2)
    }

    /// Check whether the `def` may access already freed memory.
    /// If yes, generate a CWE warning and mark the corresponding object IDs as already flagged.
    fn update_def(&self, state: &State, def: &Term<Def>) -> Option<State> {
        let mut state = state.clone();
        if let Some(address) = self.pointer_inference.eval_address_at_def(&def.tid) {
            if let Some(warning_causes) = state.check_address_for_use_after_free(&address) {
                self.generate_cwe_warning(
                    "CWE416",
                    format!(
                        "(Use After Free) Access through a dangling pointer at {}",
                        def.tid.address
                    ),
                    &def.tid,
                    warning_causes,
                    &state.current_fn_tid,
                );
            }
        }
        Some(state)
    }

    /// Just returns the unmodified state.
    fn update_jump(
        &self,
        state: &State,
        _jump: &Term<Jmp>,
        _untaken_conditional: Option<&Term<Jmp>>,
        _target: &Term<Blk>,
    ) -> Option<State> {
        Some(state.clone())
    }

    /// Check whether any call parameters are dangling pointers and generate CWE warnings accordingly.
    /// Always returns `None` since the analysis is a bottom-up analysis (i.e. no information flows from caller to callee).
    fn update_call(
        &self,
        state: &State,
        call: &Term<Jmp>,
        target: &crate::analysis::graph::Node,
        _calling_convention: &Option<String>,
    ) -> Option<State> {
        use crate::analysis::graph::Node;
        let sub = match *target {
            Node::BlkStart(_, sub) => sub,
            _ => return None,
        };
        let mut state = state.clone();
        self.check_internal_call_params_for_use_after_free(&mut state, &sub.tid, &call.tid);
        // No information flows from caller to callee, so we return `None` regardless.
        None
    }

    /// Collect the IDs of objects freed in the callee and mark the corresponding objects in the caller as freed.
    /// Also check the call parameters for Use-After-Frees.
    fn update_return(
        &self,
        state: Option<&State>,
        state_before_call: Option<&State>,
        call: &Term<Jmp>,
        _return_term: &Term<Jmp>,
        _calling_convention: &Option<String>,
    ) -> Option<State> {
        let (state_before_return, state_before_call) = match (state, state_before_call) {
            (Some(state_before_return), Some(state_before_call)) => {
                (state_before_return, state_before_call)
            }
            _ => return None,
        };
        let id_replacement_map = match self
            .pointer_inference
            .get_id_renaming_map_at_call_tid(&call.tid)
        {
            Some(map) => map,
            None => return None,
        };
        let pi_state_before_call = match self.pointer_inference.get_state_at_jmp_tid(&call.tid) {
            Some(pi_state) => pi_state,
            None => return None,
        };

        let mut state_after_return = state_before_call.clone();
        // Check for Use-After-Frees through function parameters.
        // FIXME: This is actually done twice, since the `update_call` method uses the same check.
        // But to remove the check there we would have to know the callee function TID here
        // even in the case when the call does not actually return at all.
        self.check_internal_call_params_for_use_after_free(
            &mut state_after_return,
            &state_before_return.current_fn_tid,
            &call.tid,
        );
        // Add object IDs of objects that may have been freed in the callee.
        state_after_return.collect_freed_objects_from_called_function(
            state_before_return,
            id_replacement_map,
            &call.tid,
            pi_state_before_call,
        );
        Some(state_after_return)
    }

    /// Handle extern symbols by checking for Use-After-Frees in the call parameters.
    /// Also handle calls to `free` by marking the corresponding object ID as dangling.
    fn update_call_stub(&self, state: &State, call: &Term<Jmp>) -> Option<State> {
        let mut state = state.clone();
        if let Some(extern_symbol) = match &call.term {
            Jmp::Call { target, .. } => self.project.program.term.extern_symbols.get(target),
            _ => None,
        } {
            match extern_symbol.name.as_str() {
                dealloc_sym if self.deallocation_symbols.contains(dealloc_sym) => {
                    self.handle_call_to_free(&mut state, &call.tid, extern_symbol)
                }
                extern_symbol_name => {
                    if let Some(warning_causes) = self.collect_cwe_warnings_of_call_params(
                        &mut state,
                        &call.tid,
                        &extern_symbol.parameters,
                    ) {
                        self.generate_cwe_warning(
                            "CWE416",
                            format!(
                                "(Use After Free) Call to {} at {} may access dangling pointers through its parameters",
                                extern_symbol_name,
                                call.tid.address
                                ),
                            &call.tid,
                            warning_causes,
                            &state.current_fn_tid,
                        );
                    }
                }
            }
        } else if let Some(warning_causes) = self.collect_cwe_warnings_of_call_params(
            &mut state,
            &call.tid,
            &self.generic_function_parameter,
        ) {
            self.generate_cwe_warning(
                "CWE416",
                format!(
                    "(Use After Free) Call at {} may access dangling pointers through its parameters",
                    call.tid.address
                    ),
                &call.tid,
                warning_causes,
                &state.current_fn_tid,
            );
        }
        Some(state)
    }

    /// Just returns the unmodified state
    fn specialize_conditional(
        &self,
        state: &State,
        _condition: &Expression,
        _block_before_condition: &Term<Blk>,
        _is_true: bool,
    ) -> Option<State> {
        Some(state.clone())
    }
}