sqc 0.4.13

Software Code Quality - CERT C compliance checker
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
//! FIO02-C: Canonicalize path names originating from tainted sources
//!
//! This rule detects file operations on path names from untrusted sources without
//! proper canonicalization. Path names should be converted to canonical form using
//! realpath() or canonicalize_file_name() before validation or file operations.
//!
//! ## Examples:
//!
//! **Non-compliant:**
//! ```c
//! int main(int argc, char *argv[]) {
//!   if (fopen(argv[1], "w") == NULL) {  // Direct use of argv without canonicalization
//!     return 1;
//!   }
//! }
//! ```
//!
//! **Non-compliant:**
//! ```c
//! char *env_path = getenv("CONFIG_FILE");
//! FILE *f = fopen(env_path, "r");  // Direct use of environment variable
//! ```
//!
//! **Compliant:**
//! ```c
//! int main(int argc, char *argv[]) {
//!   char *canonical = realpath(argv[1], NULL);
//!   if (canonical == NULL) {
//!     return 1;
//!   }
//!   if (fopen(canonical, "w") == NULL) {
//!     free(canonical);
//!     return 1;
//!   }
//!   free(canonical);
//! }
//! ```
//!
//! ## Detection Strategy:
//! - Track tainted data sources (argv, getenv, user input functions)
//! - Track canonicalization calls (realpath, canonicalize_file_name)
//! - Detect file operations (fopen, open, etc.) on tainted paths
//! - Flag violations when file operations use tainted paths without canonicalization

use super::super::{CertRule, RuleViolation};
use crate::manifest::{RuleCategory, Severity};
use crate::utility::cert_c::ast_utils::get_node_text;
use std::collections::HashSet;
use tree_sitter::Node;

pub struct Fio02C;

impl CertRule for Fio02C {
    fn rule_id(&self) -> &'static str {
        "FIO02-C"
    }

    fn description(&self) -> &'static str {
        "Canonicalize path names originating from tainted sources"
    }

    fn severity(&self) -> Severity {
        Severity::High
    }

    fn category(&self) -> RuleCategory {
        RuleCategory::Rule
    }

    fn cert_id(&self) -> &'static str {
        "FIO02-C"
    }

    fn check(&self, node: &Node, source: &str) -> Vec<RuleViolation> {
        let mut violations = Vec::new();

        // Collect tainted variables in this scope
        let mut tainted_vars = HashSet::new();
        let mut canonicalized_vars = HashSet::new();

        self.check_node(
            node,
            source,
            &mut violations,
            &mut tainted_vars,
            &mut canonicalized_vars,
        );

        violations
    }
}

impl Fio02C {
    fn check_node(
        &self,
        node: &Node,
        source: &str,
        violations: &mut Vec<RuleViolation>,
        tainted_vars: &mut HashSet<String>,
        canonicalized_vars: &mut HashSet<String>,
    ) {
        match node.kind() {
            "function_definition" => {
                // Check for main function with argv parameter
                if let Some(declarator) = node.child_by_field_name("declarator") {
                    if self.is_main_function(&declarator, source) {
                        // Mark argv as tainted
                        tainted_vars.insert("argv".to_string());
                    }
                }
            }
            "assignment_expression" | "init_declarator" => {
                self.check_assignment(node, source, tainted_vars, canonicalized_vars);
            }
            "call_expression" => {
                self.check_call_expression(
                    node,
                    source,
                    violations,
                    tainted_vars,
                    canonicalized_vars,
                );
            }
            _ => {}
        }

        // Recursively check child nodes
        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                self.check_node(&child, source, violations, tainted_vars, canonicalized_vars);
            }
        }
    }

    fn is_main_function(&self, declarator: &Node, source: &str) -> bool {
        // Check if this is the main function
        if let Some(function_declarator) = self.find_function_declarator(*declarator) {
            if let Some(name_node) = function_declarator.child_by_field_name("declarator") {
                let func_name = get_node_text(&name_node, source).trim();
                if func_name == "main" {
                    return true;
                }
            }
        }
        false
    }

    fn find_function_declarator<'a>(&self, node: Node<'a>) -> Option<Node<'a>> {
        if node.kind() == "function_declarator" {
            return Some(node);
        }

        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                if let Some(result) = self.find_function_declarator(child) {
                    return Some(result);
                }
            }
        }
        None
    }

    fn check_assignment(
        &self,
        node: &Node,
        source: &str,
        tainted_vars: &mut HashSet<String>,
        canonicalized_vars: &mut HashSet<String>,
    ) {
        // Get the variable being assigned
        let var_name = if node.kind() == "assignment_expression" {
            if let Some(left) = node.child_by_field_name("left") {
                get_node_text(&left, source).trim().to_string()
            } else {
                return;
            }
        } else if node.kind() == "init_declarator" {
            if let Some(declarator) = node.child_by_field_name("declarator") {
                self.extract_identifier(&declarator, source)
                    .unwrap_or_default()
            } else {
                return;
            }
        } else {
            return;
        };

        // Get the value being assigned
        let value_node = if node.kind() == "assignment_expression" {
            node.child_by_field_name("right")
        } else {
            node.child_by_field_name("value")
        };

        if let Some(value) = value_node {
            let _value_text = get_node_text(&value, source).trim();

            // Check if assigned from tainted source
            if self.is_tainted_source(&value, source, tainted_vars) {
                tainted_vars.insert(var_name.clone());
            }

            // Check if assigned from canonicalization function
            if self.is_canonicalization_call(&value, source) {
                canonicalized_vars.insert(var_name.clone());
                // Canonicalized variable is no longer tainted
                tainted_vars.remove(&var_name);
            }
        }
    }

    fn extract_identifier(&self, node: &Node, source: &str) -> Option<String> {
        if node.kind() == "identifier" {
            return Some(get_node_text(node, source).trim().to_string());
        }

        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                if let Some(id) = self.extract_identifier(&child, source) {
                    return Some(id);
                }
            }
        }
        None
    }

    fn is_tainted_source(&self, node: &Node, source: &str, tainted_vars: &HashSet<String>) -> bool {
        match node.kind() {
            "call_expression" => {
                // Check for taint source functions
                if let Some(func) = node.child_by_field_name("function") {
                    let func_name = get_node_text(&func, source).trim();
                    if self.is_taint_source_function(func_name) {
                        return true;
                    }
                }
            }
            "subscript_expression" => {
                // Check for argv[i] access
                if let Some(array) = node.child_by_field_name("argument") {
                    let array_name = get_node_text(&array, source).trim();
                    if tainted_vars.contains(array_name) || array_name == "argv" {
                        return true;
                    }
                }
            }
            "identifier" => {
                let var_name = get_node_text(node, source).trim();
                if tainted_vars.contains(var_name) {
                    return true;
                }
            }
            _ => {}
        }

        // Recursively check children
        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                if self.is_tainted_source(&child, source, tainted_vars) {
                    return true;
                }
            }
        }

        false
    }

    fn is_taint_source_function(&self, func_name: &str) -> bool {
        matches!(
            func_name,
            "getenv"
                | "gets"
                | "fgets"
                | "scanf"
                | "fscanf"
                | "sscanf"
                | "getchar"
                | "fgetc"
                | "getc"
                | "read"
                | "recv"
                | "recvfrom"
                | "recvmsg"
        )
    }

    fn is_canonicalization_call(&self, node: &Node, source: &str) -> bool {
        if node.kind() == "call_expression" {
            if let Some(func) = node.child_by_field_name("function") {
                let func_name = get_node_text(&func, source).trim();
                return matches!(func_name, "realpath" | "canonicalize_file_name");
            }
        }
        false
    }

    fn check_call_expression(
        &self,
        node: &Node,
        source: &str,
        violations: &mut Vec<RuleViolation>,
        tainted_vars: &HashSet<String>,
        canonicalized_vars: &HashSet<String>,
    ) {
        if let Some(func) = node.child_by_field_name("function") {
            let func_name = get_node_text(&func, source).trim();

            if self.is_file_operation_function(func_name) {
                // Get the first argument (path name)
                if let Some(args) = node.child_by_field_name("arguments") {
                    if let Some(first_arg) = self.get_first_argument(&args) {
                        let arg_text = get_node_text(&first_arg, source).trim();

                        // Check if the argument is tainted
                        if self.is_tainted_source(&first_arg, source, tainted_vars) {
                            // Check if it was canonicalized
                            if !self.is_canonicalized_var(arg_text, canonicalized_vars) {
                                self.report_violation(
                                    node, source, func_name, arg_text, violations,
                                );
                            }
                        }
                    }
                }
            }
        }
    }

    fn is_file_operation_function(&self, func_name: &str) -> bool {
        matches!(
            func_name,
            "fopen"
                | "open"
                | "freopen"
                | "creat"
                | "stat"
                | "lstat"
                | "access"
                | "chmod"
                | "chown"
                | "remove"
                | "unlink"
                | "rename"
                | "mkdir"
                | "rmdir"
                | "pathconf"
                | "fpathconf"
                | "readlink"
                | "symlink"
                | "link"
                | "chdir"
                | "opendir"
                | "execve"
                | "execv"
                | "execl"
                | "execlp"
                | "execvp"
                | "CreateFile"
                | "CreateFileA"
                | "CreateFileW"
                | "DeleteFile"
                | "DeleteFileA"
                | "DeleteFileW"
                | "MoveFile"
                | "MoveFileA"
                | "MoveFileW"
                | "CopyFile"
                | "CopyFileA"
                | "CopyFileW"
                | "_wfopen"
                | "_wopen"
                | "GetFullPathName"
                | "GetFullPathNameA"
                | "GetFullPathNameW"
        )
    }

    fn get_first_argument<'a>(&self, args_node: &'a Node<'a>) -> Option<Node<'a>> {
        for i in 0..args_node.child_count() {
            if let Some(child) = args_node.child(i) {
                if child.kind() != "(" && child.kind() != ")" && child.kind() != "," {
                    return Some(child);
                }
            }
        }
        None
    }

    fn is_canonicalized_var(&self, arg_text: &str, canonicalized_vars: &HashSet<String>) -> bool {
        // Simple check - just look for variable name
        canonicalized_vars.iter().any(|var| arg_text.contains(var))
    }

    fn report_violation(
        &self,
        node: &Node,
        source: &str,
        func_name: &str,
        arg_text: &str,
        violations: &mut Vec<RuleViolation>,
    ) {
        let start_point = node.start_position();
        let _call_text = get_node_text(node, source).trim().to_string();

        violations.push(RuleViolation {
            rule_id: self.rule_id().to_string(),
            severity: Severity::High,
            message: format!(
                "File operation '{}' uses tainted path '{}' without canonicalization. Use realpath() or canonicalize_file_name() before file operations.",
                func_name,
                if arg_text.len() > 40 {
                    format!("{}...", &arg_text[..40])
                } else {
                    arg_text.to_string()
                }
            ),
            file_path: String::new(),
            line: start_point.row + 1,
            column: start_point.column + 1,
            suggestion: Some(format!(
                "Canonicalize the path before use:\n  char *canonical = realpath({}, NULL);\n  if (canonical == NULL) {{ /* handle error */ }}\n  {}(canonical, ...);\n  free(canonical);",
                arg_text,
                func_name
            )),
            ..Default::default()
        });
    }
}