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
use super::super::{CertRule, RuleViolation};
use crate::manifest::{RuleCategory, Severity};
use crate::utility::cert_c::ast_utils::get_node_text;
use tree_sitter::Node;
pub struct Fio03C;
impl CertRule for Fio03C {
fn rule_id(&self) -> &'static str {
"FIO03-C"
}
fn severity(&self) -> Severity {
Severity::Medium
}
fn description(&self) -> &'static str {
"Do not make assumptions about fopen() and file creation"
}
fn category(&self) -> RuleCategory {
RuleCategory::Recommendation
}
fn cert_id(&self) -> &'static str {
"FIO03-C"
}
fn check(&self, node: &Node, source: &str) -> Vec<RuleViolation> {
let mut violations = Vec::new();
// Check for fopen() calls with "w" or "w+" mode that may incorrectly assume file creation
if node.kind() == "call_expression" {
if let Some(function_node) = node.child_by_field_name("function") {
let func_name = get_node_text(&function_node, source);
if func_name == "fopen" {
if let Some(args_node) = node.child_by_field_name("arguments") {
// Look for string literals in arguments that represent write mode without 'x'
for i in 0..args_node.child_count() {
if let Some(arg) = args_node.child(i) {
if arg.kind() == "string_literal" {
let mode_text = get_node_text(&arg, source);
let mode_value = mode_text.trim().trim_matches('"');
// Check for write modes without exclusive creation flag
let is_unsafe_write_mode = (mode_value == "w"
|| mode_value == "w+"
|| mode_value == "wb"
|| mode_value == "w+b"
|| mode_value == "wb+")
&& !mode_value.contains('x');
if is_unsafe_write_mode {
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: self.severity(),
message: format!(
"fopen() with mode {} does not guarantee exclusive file creation. Use \"wx\" or \"w+x\" mode for exclusive creation.",
mode_text
),
file_path: String::new(),
line: node.start_position().row + 1,
column: node.start_position().column + 1,
suggestion: Some("Use fopen() with \"wx\" or \"w+x\" mode for C11, or use open() with O_CREAT|O_EXCL for POSIX".to_string()),
..Default::default()
});
}
}
}
}
}
}
}
} // Recursively check child nodes
for i in 0..node.child_count() {
if let Some(child) = node.child(i) {
violations.extend(self.check(&child, source));
}
}
violations
}
}