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
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 Int08C;
impl CertRule for Int08C {
fn rule_id(&self) -> &'static str {
"INT08-C"
}
fn description(&self) -> &'static str {
"Verify that all integer values are in range"
}
fn severity(&self) -> Severity {
Severity::Medium
}
fn category(&self) -> RuleCategory {
RuleCategory::Rule
}
fn cert_id(&self) -> &'static str {
"INT08-C"
}
fn check(&self, node: &Node, source: &str) -> Vec<RuleViolation> {
let mut violations = Vec::new();
// Collect variable declarations with their types
let mut variables: HashMap<String, (String, usize)> = HashMap::new();
self.collect_declarations(node, source, &mut variables);
// Find arithmetic expressions on narrow integer types
self.check_arithmetic_expressions(node, source, &variables, &mut violations);
violations
}
}
impl Int08C {
/// Collect variable declarations and their types
fn collect_declarations(
&self,
node: &Node,
source: &str,
variables: &mut HashMap<String, (String, usize)>,
) {
if node.kind() == "declaration" {
let decl_text = get_node_text(node, source);
// Extract type and variable name
if let Some((var_type, var_name)) = self.parse_declaration(&decl_text) {
variables.insert(var_name, (var_type, node.start_position().row + 1));
}
}
// Recursively process children
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
self.collect_declarations(&child, source, variables);
}
}
/// Parse declaration to extract type and variable name
fn parse_declaration(&self, decl_text: &str) -> Option<(String, String)> {
let parts: Vec<&str> = decl_text.split_whitespace().collect();
if parts.len() >= 2 {
// Handle types like "int x", "unsigned int x", "long x"
if parts.len() >= 3 && (parts[0] == "unsigned" || parts[0] == "signed") {
// "unsigned int x" or "signed int x"
let var_type = format!("{} {}", parts[0], parts[1]);
let var_name = parts[2]
.trim_end_matches(';')
.trim_end_matches(',')
.split('=')
.next()?
.trim()
.to_string();
return Some((var_type, var_name));
} else {
// Simple type like "int x" or "long x"
let var_type = parts[0].to_string();
let var_name = parts[1]
.trim_end_matches(';')
.trim_end_matches(',')
.split('=')
.next()?
.trim()
.to_string();
return Some((var_type, var_name));
}
}
None
}
/// Check arithmetic expressions for overflow risks
fn check_arithmetic_expressions(
&self,
node: &Node,
source: &str,
variables: &HashMap<String, (String, usize)>,
violations: &mut Vec<RuleViolation>,
) {
// Check if this is a binary expression (arithmetic)
if node.kind() == "binary_expression" {
if let Some(op) = node.child_by_field_name("operator") {
let op_text = get_node_text(&op, source);
// Check for arithmetic operators
if matches!(op_text.trim(), "+" | "-" | "*" | "/" | "%" | "<<" | ">>") {
// Get the operands
if let (Some(left), Some(right)) = (
node.child_by_field_name("left"),
node.child_by_field_name("right"),
) {
// Check if operands involve narrow integer types
let left_vars = self.extract_variables(&left, source);
let right_vars = self.extract_variables(&right, source);
let mut all_vars: HashSet<String> = HashSet::new();
all_vars.extend(left_vars);
all_vars.extend(right_vars);
for var in all_vars {
if let Some((var_type, _decl_line)) = variables.get(&var) {
// Check if this is a narrow integer type
if self.is_narrow_integer_type(var_type) {
// Check if there's appropriate overflow protection
if !self.has_overflow_protection(node, &var, var_type, source) {
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
message: format!(
"Arithmetic expression involving '{}' (narrow type '{}') without proper overflow protection",
var, var_type
),
severity: self.severity(),
line: node.start_position().row + 1,
column: node.start_position().column + 1,
file_path: String::new(),
suggestion: Some(format!(
"Use a wider type (e.g., 'long' instead of '{}') or add overflow checks before the operation",
var_type
)),
requires_manual_review: None,
});
// Only report once per expression
return;
}
}
}
}
}
}
}
}
// Recursively check children
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
self.check_arithmetic_expressions(&child, source, variables, violations);
}
}
/// Extract variable names from an expression
fn extract_variables(&self, node: &Node, source: &str) -> HashSet<String> {
let mut vars = HashSet::new();
if node.kind() == "identifier" {
let text = get_node_text(node, source);
vars.insert(text.trim().to_string());
}
// Recursively extract from child nodes
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
vars.extend(self.extract_variables(&child, source));
}
vars
}
/// Check if a type is a narrow integer type (prone to overflow)
/// Per CERT INT08-C, narrow types are those smaller than int:
/// char, short, and their signed/unsigned variants.
/// int itself is NOT narrow - overflow on int is covered by INT32-C.
fn is_narrow_integer_type(&self, type_name: &str) -> bool {
matches!(
type_name,
"short" | "char" | "signed short" | "unsigned short" | "signed char" | "unsigned char"
)
}
/// Check if there's appropriate overflow protection for this expression
fn has_overflow_protection(
&self,
expr_node: &Node,
var_name: &str,
_var_type: &str,
source: &str,
) -> bool {
// Find the containing scope
let mut current = expr_node.parent();
let mut scope: Option<Node> = None;
while let Some(node) = current {
if matches!(
node.kind(),
"compound_statement" | "function_definition" | "translation_unit" | "if_statement"
) {
scope = Some(node);
break;
}
current = node.parent();
}
if let Some(scope_node) = scope {
// Look for overflow checks BEFORE this expression
// Proper checks would be like: if (i >= INT_MAX) or if (i < INT_MAX)
// NOT checks that use the overflowing expression itself like: if (i + 1 <= i)
return self.find_proper_overflow_check(
&scope_node,
expr_node.start_position().row,
var_name,
source,
);
}
false
}
/// Find proper overflow check that comes BEFORE the expression
fn find_proper_overflow_check(
&self,
scope: &Node,
expr_line: usize,
var_name: &str,
source: &str,
) -> bool {
let mut cursor = scope.walk();
for child in scope.children(&mut cursor) {
// Only check statements that come BEFORE the expression
if child.start_position().row < expr_line {
if child.kind() == "if_statement" {
if let Some(condition) = child.child_by_field_name("condition") {
let cond_text = get_node_text(&condition, source);
// Check for proper overflow protection patterns
// Good: "i >= INT_MAX", "i < INT_MAX", "i > MAX_VALUE"
// Bad: "i + 1 <= i" (uses the overflowing expression itself)
if cond_text.contains(var_name) {
// Check if it's a proper range check (not using the overflow expression)
if self.is_proper_range_check(&cond_text, var_name) {
return true;
}
}
}
}
}
// Recursively search in child scopes
if self.find_proper_overflow_check(&child, expr_line, var_name, source) {
return true;
}
}
false
}
/// Check if a condition is a proper range check
fn is_proper_range_check(&self, condition: &str, var_name: &str) -> bool {
// Proper checks compare the variable against limits like INT_MAX, MAX_VALUE
// Not proper: checks that use arithmetic on the variable itself
// Look for comparisons with MAX/MIN constants
if (condition.contains("MAX") || condition.contains("MIN")) && condition.contains(var_name)
{
// Check that the variable appears WITHOUT arithmetic operators applied to it
// e.g., "i >= INT_MAX" is good, but "i + 1 <= i" is bad
let has_var_arithmetic = condition.contains(&format!("{} +", var_name))
|| condition.contains(&format!("{} -", var_name))
|| condition.contains(&format!("{} *", var_name))
|| condition.contains(&format!("{} /", var_name))
|| condition.contains(&format!("+ {}", var_name))
|| condition.contains(&format!("- {}", var_name));
return !has_var_arithmetic;
}
false
}
}