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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
//! FIO42-C: Close files when they are no longer needed
//!
//! A call to fopen() or freopen() must be matched with a call to fclose()
//! before the lifetime of the last pointer that stores the return value ends
//! or before normal program termination.
//!
//! ## Examples:
//!
//! **Non-compliant:**
//! ```c
//! void process_file(const char *filename) {
//!     FILE *fp = fopen(filename, "r");
//!     if (fp == NULL) {
//!         return;
//!     }
//!     // ... process file ...
//!     return; // FILE* leak - fclose() never called
//! }
//! ```
//!
//! **Compliant:**
//! ```c
//! void process_file(const char *filename) {
//!     FILE *fp = fopen(filename, "r");
//!     if (fp == NULL) {
//!         return;
//!     }
//!     // ... process file ...
//!     if (fclose(fp) != 0) {
//!         // Handle error
//!     }
//! }
//! ```

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

pub struct Fio42C;

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

    fn description(&self) -> &'static str {
        "Close files when they are no longer needed"
    }

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

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

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

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

        // Track file resources across the AST
        let mut tracker = FileResourceTracker::new();
        tracker.analyze_node(node, source, &mut violations);

        violations
    }
}

struct FileResourceTracker {
    // Track FILE* variables from fopen/freopen
    file_pointers: HashMap<String, ResourceInfo>,
    // Track file descriptors from open()
    file_descriptors: HashMap<String, ResourceInfo>,
    // Track HANDLEs from CreateFile()
    file_handles: HashMap<String, ResourceInfo>,
    // Track which resources have been closed
    closed_resources: HashSet<String>,
}

#[derive(Clone)]
#[allow(dead_code)]
struct ResourceInfo {
    var_name: String,
    resource_type: ResourceType,
    line: usize,
    column: usize,
}

#[derive(Clone, PartialEq)]
#[allow(clippy::enum_variant_names)]
enum ResourceType {
    FilePointer,    // FILE* from fopen/freopen
    FileDescriptor, // int fd from open()
    FileHandle,     // HANDLE from CreateFile()
}

impl FileResourceTracker {
    fn new() -> Self {
        Self {
            file_pointers: HashMap::new(),
            file_descriptors: HashMap::new(),
            file_handles: HashMap::new(),
            closed_resources: HashSet::new(),
        }
    }

    fn analyze_node(&mut self, node: &Node, source: &str, violations: &mut Vec<RuleViolation>) {
        // First pass: find function definitions to analyze
        if node.kind() == "function_definition" {
            self.analyze_function(node, source, violations);
        }

        // Recurse to find all functions
        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                self.analyze_node(&child, source, violations);
            }
        }
    }

    fn analyze_function(
        &mut self,
        func_node: &Node,
        source: &str,
        violations: &mut Vec<RuleViolation>,
    ) {
        // Reset tracking for this function scope
        self.file_pointers.clear();
        self.file_descriptors.clear();
        self.file_handles.clear();
        self.closed_resources.clear();

        // Get function body
        if let Some(body) = func_node.child_by_field_name("body") {
            // Collect all resource allocations
            self.collect_resources(&body, source);

            // Collect all resource deallocations
            self.collect_closes(&body, source);

            // Check for unclosed resources
            self.check_unclosed_resources(violations);

            // CWE-459: check for temp file creation without cleanup
            self.check_temp_file_cleanup(&body, source, violations);
        }
    }

    fn collect_resources(&mut self, node: &Node, source: &str) {
        match node.kind() {
            "declaration" => {
                self.check_file_pointer_declaration(node, source);
            }
            "assignment_expression" => {
                self.check_file_pointer_assignment(node, source);
            }
            _ => {}
        }

        // Recurse
        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                self.collect_resources(&child, source);
            }
        }
    }

    fn check_file_pointer_declaration(&mut self, node: &Node, source: &str) {
        let decl_text = get_node_text(node, source);

        // Check for FILE* declarations with fopen/freopen
        if decl_text.contains("FILE") && decl_text.contains("*") {
            // Look for init_declarator with fopen/freopen
            for i in 0..node.child_count() {
                if let Some(child) = node.child(i) {
                    if child.kind() == "init_declarator" {
                        if let Some(value) = child.child_by_field_name("value") {
                            let value_text = get_node_text(&value, source);
                            if value_text.contains("fopen") || value_text.contains("freopen") {
                                if let Some(var_name) = self.extract_declarator_name(&child, source)
                                {
                                    self.file_pointers.insert(
                                        var_name.clone(),
                                        ResourceInfo {
                                            var_name,
                                            resource_type: ResourceType::FilePointer,
                                            line: node.start_position().row + 1,
                                            column: node.start_position().column + 1,
                                        },
                                    );
                                }
                            }
                        }
                    }
                }
            }
        }

        // Check for POSIX file descriptor from open()
        if decl_text.contains("int") && decl_text.contains("open(") {
            for i in 0..node.child_count() {
                if let Some(child) = node.child(i) {
                    if child.kind() == "init_declarator" {
                        if let Some(value) = child.child_by_field_name("value") {
                            let value_text = get_node_text(&value, source);
                            if value_text.contains("open(") {
                                if let Some(var_name) = self.extract_declarator_name(&child, source)
                                {
                                    self.file_descriptors.insert(
                                        var_name.clone(),
                                        ResourceInfo {
                                            var_name,
                                            resource_type: ResourceType::FileDescriptor,
                                            line: node.start_position().row + 1,
                                            column: node.start_position().column + 1,
                                        },
                                    );
                                }
                            }
                        }
                    }
                }
            }
        }

        // Check for Windows HANDLE from CreateFile()
        if decl_text.contains("HANDLE") && decl_text.contains("CreateFile") {
            for i in 0..node.child_count() {
                if let Some(child) = node.child(i) {
                    if child.kind() == "init_declarator" {
                        if let Some(value) = child.child_by_field_name("value") {
                            let value_text = get_node_text(&value, source);
                            if value_text.contains("CreateFile") {
                                if let Some(var_name) = self.extract_declarator_name(&child, source)
                                {
                                    self.file_handles.insert(
                                        var_name.clone(),
                                        ResourceInfo {
                                            var_name,
                                            resource_type: ResourceType::FileHandle,
                                            line: node.start_position().row + 1,
                                            column: node.start_position().column + 1,
                                        },
                                    );
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    fn check_file_pointer_assignment(&mut self, node: &Node, source: &str) {
        if let (Some(left), Some(right)) = (
            node.child_by_field_name("left"),
            node.child_by_field_name("right"),
        ) {
            let right_text = get_node_text(&right, source);
            let var_name = get_node_text(&left, source).to_string();

            // Check for FILE* assignment from fopen/freopen
            if right_text.contains("fopen") || right_text.contains("freopen") {
                self.file_pointers.insert(
                    var_name.clone(),
                    ResourceInfo {
                        var_name: var_name.clone(),
                        resource_type: ResourceType::FilePointer,
                        line: node.start_position().row + 1,
                        column: node.start_position().column + 1,
                    },
                );
            }

            // Check for fd assignment from open()
            if right_text.contains("open(") {
                self.file_descriptors.insert(
                    var_name.clone(),
                    ResourceInfo {
                        var_name: var_name.clone(),
                        resource_type: ResourceType::FileDescriptor,
                        line: node.start_position().row + 1,
                        column: node.start_position().column + 1,
                    },
                );
            }

            // Check for HANDLE assignment from CreateFile()
            if right_text.contains("CreateFile") {
                self.file_handles.insert(
                    var_name.clone(),
                    ResourceInfo {
                        var_name: var_name.clone(),
                        resource_type: ResourceType::FileHandle,
                        line: node.start_position().row + 1,
                        column: node.start_position().column + 1,
                    },
                );
            }
        }
    }

    fn collect_closes(&mut self, node: &Node, source: &str) {
        if node.kind() == "call_expression" {
            if let Some(function) = node.child_by_field_name("function") {
                let func_name = get_node_text(&function, source);

                // Track fclose() calls
                if func_name == "fclose" {
                    if let Some(args) = node.child_by_field_name("arguments") {
                        let args_text = get_node_text(&args, source);
                        let var_name = args_text.trim_matches(|c| c == '(' || c == ')').trim();
                        self.closed_resources.insert(var_name.to_string());
                    }
                }

                // Track POSIX close() calls
                if func_name == "close" {
                    if let Some(args) = node.child_by_field_name("arguments") {
                        let args_text = get_node_text(&args, source);
                        let var_name = args_text.trim_matches(|c| c == '(' || c == ')').trim();
                        self.closed_resources.insert(var_name.to_string());
                    }
                }

                // Track Windows CloseHandle() calls
                if func_name == "CloseHandle" {
                    if let Some(args) = node.child_by_field_name("arguments") {
                        let args_text = get_node_text(&args, source);
                        let var_name = args_text.trim_matches(|c| c == '(' || c == ')').trim();
                        self.closed_resources.insert(var_name.to_string());
                    }
                }
            }
        }

        // Recurse
        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                self.collect_closes(&child, source);
            }
        }
    }

    fn check_unclosed_resources(&self, violations: &mut Vec<RuleViolation>) {
        // Check FILE* pointers
        for (var_name, info) in &self.file_pointers {
            if !self.closed_resources.contains(var_name) {
                violations.push(RuleViolation {
                    rule_id: "FIO42-C".to_string(),
                    message: format!(
                        "FILE pointer '{}' opened with fopen/freopen but never closed with fclose()",
                        var_name
                    ),
                    severity: Severity::High,
                    line: info.line,
                    column: info.column,
                    file_path: String::new(),
                    suggestion: Some(format!(
                        "Add fclose({}) before function returns or program exits",
                        var_name
                    )),
                    requires_manual_review: None,
                });
            }
        }

        // Check file descriptors
        for (var_name, info) in &self.file_descriptors {
            if !self.closed_resources.contains(var_name) {
                violations.push(RuleViolation {
                    rule_id: "FIO42-C".to_string(),
                    message: format!(
                        "File descriptor '{}' opened with open() but never closed with close()",
                        var_name
                    ),
                    severity: Severity::High,
                    line: info.line,
                    column: info.column,
                    file_path: String::new(),
                    suggestion: Some(format!(
                        "Add close({}) before function returns or program exits",
                        var_name
                    )),
                    requires_manual_review: None,
                });
            }
        }

        // Check Windows HANDLEs
        for (var_name, info) in &self.file_handles {
            if !self.closed_resources.contains(var_name) {
                violations.push(RuleViolation {
                    rule_id: "FIO42-C".to_string(),
                    message: format!(
                        "File HANDLE '{}' opened with CreateFile() but never closed with CloseHandle()",
                        var_name
                    ),
                    severity: Severity::High,
                    line: info.line,
                    column: info.column,
                    file_path: String::new(),
                    suggestion: Some(format!(
                        "Add CloseHandle({}) before function returns or program exits",
                        var_name
                    )),
                    requires_manual_review: None,
                });
            }
        }
    }

    fn extract_declarator_name(&self, node: &Node, source: &str) -> Option<String> {
        if let Some(declarator) = node.child_by_field_name("declarator") {
            return self.find_identifier(&declarator, source);
        }
        None
    }

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

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

        None
    }

    // ── CWE-459: Temp file creation without cleanup ─────────────────────────

    /// Check if a function creates temp files but never deletes them
    fn check_temp_file_cleanup(
        &self,
        body: &Node,
        source: &str,
        violations: &mut Vec<RuleViolation>,
    ) {
        let mut temp_creations: Vec<(usize, usize)> = Vec::new();
        let mut has_cleanup = false;
        self.scan_temp_file_calls(body, source, &mut temp_creations, &mut has_cleanup);

        if !has_cleanup {
            for (line, col) in &temp_creations {
                violations.push(RuleViolation {
                    rule_id: "FIO42-C".to_string(),
                    message:
                        "Temporary file created but never deleted (missing unlink/remove call)"
                            .to_string(),
                    severity: Severity::Medium,
                    line: *line,
                    column: *col,
                    file_path: String::new(),
                    suggestion: Some(
                        "Call unlink() or remove() on the temporary file before function returns"
                            .to_string(),
                    ),
                    requires_manual_review: None,
                });
            }
        }
    }

    /// Recursively scan for temp file creation and cleanup calls
    fn scan_temp_file_calls(
        &self,
        node: &Node,
        source: &str,
        temp_creations: &mut Vec<(usize, usize)>,
        has_cleanup: &mut bool,
    ) {
        if node.kind() == "call_expression" {
            if let Some(func) = node.child_by_field_name("function") {
                let name = get_node_text(&func, source).trim().to_string();
                match name.as_str() {
                    "mkstemp" | "MKSTEMP" | "_mkstemp" | "mktemp" | "MKTEMP" | "_wmktemp"
                    | "mkdtemp" | "tmpnam" => {
                        temp_creations.push((
                            node.start_position().row + 1,
                            node.start_position().column + 1,
                        ));
                    }
                    "unlink" | "UNLINK" | "_unlink" | "_wunlink" | "remove" | "DeleteFile"
                    | "DeleteFileA" | "DeleteFileW" => {
                        *has_cleanup = true;
                    }
                    _ => {}
                }
            }
        }

        for i in 0..node.child_count() {
            if let Some(child) = node.child(i) {
                self.scan_temp_file_calls(&child, source, temp_creations, has_cleanup);
            }
        }
    }
}