use tree_sitter::Node;
use super::super::{CertRule, RuleViolation};
use crate::manifest::{RuleCategory, Severity};
use crate::utility::cert_c::ast_utils::get_node_text;
pub struct Mem06C;
impl CertRule for Mem06C {
fn rule_id(&self) -> &'static str {
"MEM06-C"
}
fn description(&self) -> &'static str {
"Ensure that sensitive data is not written out to disk"
}
fn severity(&self) -> Severity {
Severity::Medium
}
fn category(&self) -> RuleCategory {
RuleCategory::Recommendation
}
fn cert_id(&self) -> &'static str {
"MEM06-C"
}
fn check(&self, node: &Node, source: &str) -> Vec<RuleViolation> {
let mut violations = Vec::new();
self.check_node(node, source, &mut violations);
violations
}
}
impl Mem06C {
fn check_node(&self, node: &Node, source: &str, violations: &mut Vec<RuleViolation>) {
if node.kind() == "call_expression" {
if let Some(func_node) = node.child_by_field_name("function") {
let func_name = get_node_text(&func_node, source);
if func_name == "malloc" || func_name == "calloc" || func_name == "realloc" {
if !self.has_memory_protection(node, source) {
violations.push(RuleViolation {
rule_id: self.rule_id().to_string(),
severity: self.severity(),
line: node.start_position().row + 1,
column: node.start_position().column + 1,
file_path: String::new(),
message: format!(
"Sensitive data allocated with {} may be written to disk. \
Use mlock() (POSIX) or VirtualLock() (Windows) to lock memory pages, \
or use setrlimit(RLIMIT_CORE, 0) to disable core dumps.",
func_name
),
suggestion: Some(
"Consider using mlock()/munlock() to prevent memory from being \
swapped to disk, or use setrlimit() to disable core dumps."
.to_string(),
),
requires_manual_review: None,
});
}
}
}
}
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
self.check_node(&child, source, violations);
}
}
fn has_memory_protection(&self, node: &Node, source: &str) -> bool {
let mut parent = node.parent();
while let Some(p) = parent {
if p.kind() == "function_definition" || p.kind() == "translation_unit" {
return self.search_for_protection(&p, source);
}
parent = p.parent();
}
false
}
fn search_for_protection(&self, node: &Node, source: &str) -> bool {
if node.kind() == "call_expression" {
if let Some(func_node) = node.child_by_field_name("function") {
let func_name = get_node_text(&func_node, source);
let func_name_str = func_name.trim();
match func_name_str {
"mlock" | "munlock" | "mlockall" | "munlockall" => return true,
"VirtualLock" | "VirtualUnlock" => return true,
"VirtualAlloc" => return true,
"setrlimit"
if self.is_rlimit_core_call(node, source) => {
return true;
}
_ => {}
}
}
}
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
if self.search_for_protection(&child, source) {
return true;
}
}
false
}
fn is_rlimit_core_call(&self, node: &Node, source: &str) -> bool {
let mut cursor = node.walk();
for child in node.children(&mut cursor) {
let text = get_node_text(&child, source);
if text.contains("RLIMIT_CORE") {
return true;
}
}
false
}
}