#![allow(clippy::collapsible_if)]
use super::dominators::{self, dominates};
use super::rules;
use super::{
AnalysisContext, BodyConstFacts, CfgAnalysis, CfgFinding, Confidence, is_entry_point_func,
};
use crate::callgraph::callee_leaf_name;
use crate::cfg::StmtKind;
use crate::labels::{Cap, DataLabel, RuntimeLabelRule};
use crate::patterns::Severity;
use crate::ssa::const_prop::ConstLattice;
use crate::ssa::type_facts::TypeFactResult;
use crate::ssa::{SsaOp, SsaValue};
use crate::taint::path_state::{PredicateKind, classify_condition};
use petgraph::graph::NodeIndex;
use std::collections::HashSet;
pub struct UnguardedSink;
fn is_all_args_constant(ctx: &AnalysisContext, sink: NodeIndex) -> bool {
if ctx.cfg[sink].all_args_literal {
return true;
}
let sink_info = &ctx.cfg[sink];
let callee_desc = sink_info.call.callee.as_deref().unwrap_or("");
let callee_parts: Vec<&str> = callee_desc
.split(['.', ':'])
.map(|p| p.split('(').next().unwrap_or(p))
.collect();
let outer_parts: Vec<&str> = sink_info
.call
.outer_callee
.as_deref()
.map(|oc| {
oc.split(['.', ':'])
.map(|p| p.split('(').next().unwrap_or(p))
.collect()
})
.unwrap_or_default();
let sink_func = sink_info.ast.enclosing_func.as_deref();
sink_info.taint.uses.iter().all(|u| {
if callee_parts.contains(&u.as_str())
|| u == callee_desc
|| outer_parts.contains(&u.as_str())
{
return true;
}
for idx in ctx.cfg.node_indices() {
let info = &ctx.cfg[idx];
if info.ast.enclosing_func.as_deref() != sink_func {
continue;
}
if info.taint.defines.as_deref() == Some(u.as_str()) {
if info.taint.uses.is_empty()
&& !info
.taint
.labels
.iter()
.any(|l| matches!(l, DataLabel::Source(_)))
{
return true;
}
}
}
false
}) || ssa_all_sink_operands_constant(ctx, sink, callee_desc, &callee_parts, &outer_parts)
}
fn ssa_all_sink_operands_constant(
ctx: &AnalysisContext,
sink: NodeIndex,
callee_desc: &str,
callee_parts: &[&str],
outer_parts: &[&str],
) -> bool {
let Some(facts) = ctx.body_const_facts else {
return false;
};
let Some(&sink_val) = facts.ssa.cfg_node_map.get(&sink) else {
return false;
};
let Some(inst) = find_inst(&facts.ssa, sink_val) else {
return false;
};
let SsaOp::Call { args, receiver, .. } = &inst.op else {
return false;
};
let operand_const = |v: SsaValue| -> bool {
ssa_operand_constant(v, facts, callee_desc, callee_parts, outer_parts)
};
let args_ok = args
.iter()
.all(|group| group.iter().all(|v| operand_const(*v)));
let receiver_ok = receiver.is_none_or(operand_const);
args_ok && receiver_ok
}
fn ssa_all_sink_operands_const_or_param(ctx: &AnalysisContext, sink: NodeIndex) -> bool {
let Some(facts) = ctx.body_const_facts else {
return false;
};
let Some(&sink_val) = facts.ssa.cfg_node_map.get(&sink) else {
return false;
};
let Some(inst) = find_inst(&facts.ssa, sink_val) else {
return false;
};
let SsaOp::Call { args, receiver, .. } = &inst.op else {
return false;
};
if !func_body_has_named_const_assign(facts) {
return false;
}
let operand_safe = |v: SsaValue| -> bool { ssa_operand_const_or_param(v, facts, ctx.cfg) };
let args_ok = args
.iter()
.all(|group| group.iter().all(|v| operand_safe(*v)));
let receiver_ok = receiver.is_none_or(operand_safe);
args_ok && receiver_ok
}
fn func_body_has_named_const_assign(facts: &BodyConstFacts) -> bool {
for block in &facts.ssa.blocks {
for inst in &block.body {
if inst.var_name.is_none() {
continue;
}
let rhs_const = match &inst.op {
SsaOp::Const(_) => true,
SsaOp::Assign(vals) => vals.iter().all(|v| {
matches!(
facts.const_values.get(v),
Some(
ConstLattice::Str(_)
| ConstLattice::Int(_)
| ConstLattice::Bool(_)
| ConstLattice::Null
)
)
}),
_ => false,
};
if rhs_const {
return true;
}
}
}
false
}
fn ssa_operand_const_or_param(
root: SsaValue,
facts: &BodyConstFacts,
cfg: &crate::cfg::Cfg,
) -> bool {
let mut visited: HashSet<SsaValue> = HashSet::new();
let mut stack = vec![root];
while let Some(v) = stack.pop() {
if !visited.insert(v) {
continue;
}
match facts.const_values.get(&v) {
Some(ConstLattice::Str(_))
| Some(ConstLattice::Int(_))
| Some(ConstLattice::Bool(_))
| Some(ConstLattice::Null) => continue,
_ => {}
}
let Some(inst) = find_inst(&facts.ssa, v) else {
return false;
};
let cfg_node = inst.cfg_node;
if cfg
.node_weight(cfg_node)
.map(|info| {
info.taint
.labels
.iter()
.any(|l| matches!(l, DataLabel::Source(_)))
})
.unwrap_or(false)
{
return false;
}
match &inst.op {
SsaOp::Const(_) => {}
SsaOp::Assign(vals) => stack.extend(vals.iter().copied()),
SsaOp::Phi(ops) => stack.extend(ops.iter().map(|(_, v)| *v)),
SsaOp::Call { args, receiver, .. } => {
for group in args {
stack.extend(group.iter().copied());
}
if let Some(r) = receiver {
stack.push(*r);
}
}
SsaOp::Param { .. } | SsaOp::SelfParam | SsaOp::CatchParam => {
}
SsaOp::Source => return false,
SsaOp::Nop | SsaOp::Undef => {}
SsaOp::FieldProj { receiver, .. } => stack.push(*receiver),
}
}
true
}
fn ssa_operand_constant(
root: SsaValue,
facts: &BodyConstFacts,
callee_desc: &str,
callee_parts: &[&str],
outer_parts: &[&str],
) -> bool {
let mut visited: HashSet<SsaValue> = HashSet::new();
let mut stack = vec![root];
while let Some(v) = stack.pop() {
if !visited.insert(v) {
continue;
}
match facts.const_values.get(&v) {
Some(ConstLattice::Str(_))
| Some(ConstLattice::Int(_))
| Some(ConstLattice::Bool(_))
| Some(ConstLattice::Null) => continue,
Some(ConstLattice::Varying) => {
}
_ => {}
}
let Some(inst) = find_inst(&facts.ssa, v) else {
return false;
};
match &inst.op {
SsaOp::Const(_) => {}
SsaOp::Assign(vals) => stack.extend(vals.iter().copied()),
SsaOp::Phi(ops) => stack.extend(ops.iter().map(|(_, v)| *v)),
SsaOp::Call { args, receiver, .. } => {
for group in args {
stack.extend(group.iter().copied());
}
if let Some(r) = receiver {
stack.push(*r);
}
}
SsaOp::Param { .. } | SsaOp::SelfParam | SsaOp::CatchParam | SsaOp::Source => {
let name = inst.var_name.as_deref().unwrap_or("");
if matches!(inst.op, SsaOp::Source) {
return false;
}
if !is_callee_fragment(name, callee_desc, callee_parts, outer_parts) {
return false;
}
}
SsaOp::Nop => {}
SsaOp::Undef => {}
SsaOp::FieldProj { receiver, .. } => stack.push(*receiver),
}
}
true
}
fn is_callee_fragment(
name: &str,
callee_desc: &str,
callee_parts: &[&str],
outer_parts: &[&str],
) -> bool {
if name.is_empty() {
return true;
}
if callee_parts.contains(&name) || outer_parts.contains(&name) || name == callee_desc {
return true;
}
if callee_desc.len() > name.len() && callee_desc.starts_with(name) {
let rest = &callee_desc[name.len()..];
if rest.starts_with('.') || rest.starts_with("::") {
return true;
}
}
false
}
fn find_inst(ssa: &crate::ssa::SsaBody, v: SsaValue) -> Option<&crate::ssa::SsaInst> {
let def = ssa.value_defs.get(v.0 as usize)?;
let block = ssa.blocks.get(def.block.0 as usize)?;
block
.phis
.iter()
.chain(block.body.iter())
.find(|inst| inst.value == v)
}
fn sink_args_typed_safe(ctx: &AnalysisContext, sink: NodeIndex, sink_caps: Cap) -> bool {
let Some(facts) = ctx.body_const_facts else {
return false;
};
let Some(type_facts) = ctx.type_facts else {
return false;
};
let Some(&sink_val) = facts.ssa.cfg_node_map.get(&sink) else {
return false;
};
let Some(inst) = find_inst(&facts.ssa, sink_val) else {
return false;
};
let SsaOp::Call { args, receiver, .. } = &inst.op else {
return false;
};
let sink_info = &ctx.cfg[sink];
let callee_desc = sink_info.call.callee.as_deref().unwrap_or("");
let callee_parts: Vec<&str> = callee_desc
.split(['.', ':'])
.map(|p| p.split('(').next().unwrap_or(p))
.collect();
let outer_parts: Vec<&str> = sink_info
.call
.outer_callee
.as_deref()
.map(|oc| {
oc.split(['.', ':'])
.map(|p| p.split('(').next().unwrap_or(p))
.collect()
})
.unwrap_or_default();
let is_real_arg = |v: SsaValue| -> bool {
let Some(def) = find_inst(&facts.ssa, v) else {
return true;
};
match &def.op {
SsaOp::Param { .. } => {
let name = def.var_name.as_deref().unwrap_or("");
!is_callee_fragment(name, callee_desc, &callee_parts, &outer_parts)
}
SsaOp::Const(_) => false,
_ => true,
}
};
let mut values: Vec<SsaValue> = Vec::new();
if let Some(r) = receiver {
if is_real_arg(*r) {
values.push(*r);
}
}
for group in args {
for v in group.iter() {
if is_real_arg(*v) {
values.push(*v);
}
}
}
type_facts_suppress(&values, sink_caps, type_facts)
}
fn sink_args_summary_validated_safe(ctx: &AnalysisContext, sink: NodeIndex) -> bool {
let local_map = ctx.ssa_summaries;
let global_map = ctx.global_summaries.map(|g| g.snapshot_ssa());
if local_map.is_none() && global_map.is_none() {
return false;
}
let sink_info = &ctx.cfg[sink];
use crate::cfg::StmtKind;
let callee_desc = sink_info.call.callee.as_deref().unwrap_or("");
let callee_parts: Vec<&str> = callee_desc
.split(['.', ':'])
.map(|p| p.split('(').next().unwrap_or(p))
.collect();
let outer_parts: Vec<&str> = sink_info
.call
.outer_callee
.as_deref()
.map(|oc| {
oc.split(['.', ':'])
.map(|p| p.split('(').next().unwrap_or(p))
.collect()
})
.unwrap_or_default();
let mut arg_use_names: Vec<String> = Vec::new();
if !sink_info.call.arg_uses.is_empty() {
for group in &sink_info.call.arg_uses {
for u in group {
if !arg_use_names.iter().any(|n| n == u) {
arg_use_names.push(u.clone());
}
}
}
}
if arg_use_names.is_empty() {
for u in &sink_info.taint.uses {
if is_callee_fragment(u, callee_desc, &callee_parts, &outer_parts) {
continue;
}
if !arg_use_names.iter().any(|n| n == u) {
arg_use_names.push(u.clone());
}
}
}
if arg_use_names.is_empty() {
return false;
}
let lookup_validated = |callee_text: &str| -> Option<bool> {
let leaf = callee_leaf_name(callee_text);
let mut matches: Vec<&crate::summary::ssa_summary::SsaFuncSummary> = Vec::new();
if let Some(map) = local_map {
for (key, sum) in map {
if key.name == leaf || key.name == callee_text {
matches.push(sum);
}
}
}
if matches.is_empty() {
if let Some(map) = global_map {
for (key, sum) in map {
if key.name == leaf || key.name == callee_text {
matches.push(sum);
}
}
}
}
if matches.len() != 1 {
return None;
}
let sum = matches[0];
if sum.validated_params_to_return.is_empty() {
return Some(false);
}
let propagates = sum
.param_to_return
.iter()
.map(|(idx, _)| *idx)
.collect::<Vec<usize>>();
if propagates.is_empty() {
return Some(true);
}
let all_validated = propagates
.iter()
.all(|p| sum.validated_params_to_return.contains(p));
Some(all_validated)
};
let mut to_validate: Vec<String> = arg_use_names.clone();
let mut visited: HashSet<NodeIndex> = HashSet::new();
let mut frontier: Vec<NodeIndex> = ctx
.cfg
.neighbors_directed(sink, petgraph::Direction::Incoming)
.collect();
let mut iter_budget = 256usize;
while let Some(n) = frontier.pop() {
if iter_budget == 0 {
return false;
}
iter_budget -= 1;
if !visited.insert(n) {
continue;
}
let info = &ctx.cfg[n];
if info.kind == StmtKind::Call {
if let Some(def_name) = info.taint.defines.as_deref() {
if let Some(pos) = to_validate.iter().position(|u| u == def_name) {
let callee = info.call.callee.as_deref().unwrap_or("");
if !matches!(lookup_validated(callee), Some(true)) {
return false;
}
to_validate.remove(pos);
if to_validate.is_empty() {
return true;
}
}
}
}
for pred in ctx.cfg.neighbors_directed(n, petgraph::Direction::Incoming) {
frontier.push(pred);
}
}
to_validate.is_empty()
}
fn type_facts_suppress(values: &[SsaValue], sink_caps: Cap, type_facts: &TypeFactResult) -> bool {
crate::ssa::type_facts::is_type_safe_for_sink(values, sink_caps, type_facts)
}
fn sink_args_static_map_safe(ctx: &AnalysisContext, sink: NodeIndex, sink_caps: Cap) -> bool {
if !sink_caps.intersects(Cap::SHELL_ESCAPE) {
return false;
}
let Some(facts) = ctx.body_const_facts else {
return false;
};
let Some(&sink_val) = facts.ssa.cfg_node_map.get(&sink) else {
return false;
};
let Some(inst) = find_inst(&facts.ssa, sink_val) else {
return false;
};
let SsaOp::Call { args, receiver, .. } = &inst.op else {
return false;
};
let sm =
crate::ssa::static_map::analyze(&facts.ssa, ctx.cfg, Some(ctx.lang), &facts.const_values);
if sm.is_empty() {
return false;
}
let sink_info = &ctx.cfg[sink];
let callee_desc = sink_info.call.callee.as_deref().unwrap_or("");
let callee_parts: Vec<&str> = callee_desc
.split(['.', ':'])
.map(|p| p.split('(').next().unwrap_or(p))
.collect();
let outer_parts: Vec<&str> = sink_info
.call
.outer_callee
.as_deref()
.map(|oc| {
oc.split(['.', ':'])
.map(|p| p.split('(').next().unwrap_or(p))
.collect()
})
.unwrap_or_default();
let is_real_arg = |v: SsaValue| -> bool {
let Some(def) = find_inst(&facts.ssa, v) else {
return true;
};
match &def.op {
SsaOp::Param { .. } => {
let name = def.var_name.as_deref().unwrap_or("");
!is_callee_fragment(name, callee_desc, &callee_parts, &outer_parts)
}
SsaOp::Const(_) => false,
_ => true,
}
};
let mut values: Vec<SsaValue> = Vec::new();
if let Some(r) = receiver {
if is_real_arg(*r) {
values.push(*r);
}
}
for group in args {
for v in group.iter() {
if is_real_arg(*v) {
values.push(*v);
}
}
}
if values.is_empty() {
return false;
}
values.iter().all(|v| match sm.finite_string_values.get(v) {
Some(set) if !set.is_empty() => set
.iter()
.all(|s| crate::abstract_interp::string_domain::is_shell_safe_literal(s)),
_ => false,
})
}
fn match_config_sanitizer(callee: &str, extra: &[RuntimeLabelRule]) -> Option<Cap> {
let mut callee_lower: Option<String> = None;
for rule in extra {
let cap = match rule.label {
DataLabel::Sanitizer(c) => c,
_ => continue,
};
for m in &rule.matchers {
if rule.case_sensitive {
if m.ends_with('_') {
if callee.starts_with(m.as_str()) {
return Some(cap);
}
} else if callee.ends_with(m.as_str()) {
return Some(cap);
}
} else {
let cl = callee_lower.get_or_insert_with(|| callee.to_ascii_lowercase());
let ml = m.to_ascii_lowercase();
if ml.ends_with('_') {
if cl.starts_with(&ml) {
return Some(cap);
}
} else if cl.ends_with(&ml) {
return Some(cap);
}
}
}
}
None
}
fn cond_indirect_validator_callee(
info: &crate::cfg::NodeInfo,
ctx: &AnalysisContext,
) -> Option<String> {
if info.condition_vars.len() != 1 {
return None;
}
let var_name = info.condition_vars[0].as_str();
let cond_func = info.ast.enclosing_func.as_deref();
let cond_span_start = info.ast.span.0;
let mut best: Option<(usize, &str)> = None;
for nidx in ctx.cfg.node_indices() {
let n = &ctx.cfg[nidx];
if n.kind != crate::cfg::StmtKind::Call {
continue;
}
if n.taint.defines.as_deref() != Some(var_name) {
continue;
}
if n.ast.enclosing_func.as_deref() != cond_func {
continue;
}
let span_start = n.ast.span.0;
if span_start >= cond_span_start {
continue;
}
let Some(callee) = n.call.callee.as_deref() else {
continue;
};
match best {
Some((s, _)) if s >= span_start => {}
_ => best = Some((span_start, callee)),
}
}
let (_, callee) = best?;
crate::ssa::type_facts::classify_input_validator_callee(callee).map(|_| callee.to_string())
}
fn find_guard_nodes(ctx: &AnalysisContext) -> Vec<(NodeIndex, Cap)> {
let guard_rules = rules::guard_rules(ctx.lang);
let config_rules = ctx
.analysis_rules
.map(|r| r.extra_labels.as_slice())
.unwrap_or(&[]);
let mut result = Vec::new();
for idx in ctx.cfg.node_indices() {
let info = &ctx.cfg[idx];
if info.kind == StmtKind::If {
if let Some(cond_text) = &info.condition_text {
let kind = classify_condition(cond_text);
let allowlist_has_target = if kind == PredicateKind::AllowlistCheck {
crate::taint::path_state::classify_condition_with_target(cond_text)
.1
.is_some()
} else {
true
};
if matches!(
kind,
PredicateKind::TypeCheck | PredicateKind::ValidationCall,
) || (kind == PredicateKind::AllowlistCheck && allowlist_has_target)
{
result.push((idx, Cap::all()));
} else if cond_indirect_validator_callee(info, ctx).is_some() {
result.push((idx, Cap::all()));
} else if matches!(
kind,
PredicateKind::ShellMetaValidated | PredicateKind::BoundedLength
) {
result.push((idx, Cap::SHELL_ESCAPE | Cap::CODE_EXEC));
} else {
let axes = crate::abstract_interp::path_domain::classify_path_rejection_axes(
cond_text,
);
if !axes.is_empty() {
result.push((idx, Cap::FILE_IO));
}
}
}
}
if info.kind != StmtKind::Call {
continue;
}
if let Some(callee) = &info.call.callee {
if let Some(cap) = match_config_sanitizer(callee, config_rules) {
result.push((idx, cap));
continue;
}
let callee_lower = callee.to_ascii_lowercase();
for rule in guard_rules {
let matched = rule.matchers.iter().any(|m| {
let ml = m.to_ascii_lowercase();
if ml.ends_with('_') {
callee_lower.starts_with(&ml)
} else {
callee_lower.ends_with(&ml)
}
});
if matched {
result.push((idx, rule.applies_to_sink_caps));
break;
}
}
}
}
result
}
fn taint_confirms_sink(ctx: &AnalysisContext, sink: NodeIndex) -> bool {
ctx.taint_findings.iter().any(|f| f.sink == sink)
}
fn sink_arg_is_source_derived(ctx: &AnalysisContext, sink: NodeIndex) -> bool {
let sink_info = &ctx.cfg[sink];
let sink_func = sink_info.ast.enclosing_func.as_deref();
let sink_uses = &sink_info.taint.uses;
if sink_uses.is_empty() {
return false;
}
for idx in ctx.cfg.node_indices() {
let info = &ctx.cfg[idx];
if info.ast.enclosing_func.as_deref() != sink_func {
continue;
}
if !info
.taint
.labels
.iter()
.any(|l| matches!(l, DataLabel::Source(_)))
{
continue;
}
if let Some(def) = &info.taint.defines
&& sink_uses.iter().any(|u| u == def)
{
return true;
}
}
false
}
fn sink_arg_is_parameter_only(ctx: &AnalysisContext, sink: NodeIndex) -> bool {
let sink_info = &ctx.cfg[sink];
let sink_func = sink_info.ast.enclosing_func.as_deref();
let sink_uses = &sink_info.taint.uses;
if sink_uses.is_empty() {
return true; }
let param_names: Vec<&str> = ctx
.func_summaries
.values()
.filter(|s| {
ctx.cfg[s.entry].ast.enclosing_func.as_deref() == sink_func
})
.flat_map(|s| s.param_names.iter().map(|p| p.as_str()))
.collect();
if param_names.is_empty() {
return false; }
sink_uses.iter().all(|u| param_names.contains(&u.as_str()))
}
pub(crate) fn has_redirect_path_prefix(source_bytes: &[u8], span: (usize, usize)) -> bool {
let (start, end) = span;
if start >= source_bytes.len() || end > source_bytes.len() {
return false;
}
let text = &source_bytes[start..end];
if let Some(paren_pos) = text.iter().position(|&b| b == b'(') {
let after_paren = &text[paren_pos + 1..];
let trimmed = after_paren
.iter()
.skip_while(|&&b| b == b' ' || b == b'\n' || b == b'\t')
.copied()
.collect::<Vec<_>>();
if trimmed.starts_with(b"`/") {
return true;
}
if trimmed.starts_with(b"\"/") || trimmed.starts_with(b"'/") {
return true;
}
}
false
}
fn is_internal_redirect(ctx: &AnalysisContext, sink: NodeIndex, sink_caps: Cap) -> bool {
if !sink_caps.contains(Cap::SSRF) {
return false;
}
let sink_info = &ctx.cfg[sink];
let callee = match &sink_info.call.callee {
Some(c) => c.as_str(),
None => return false,
};
if !callee.ends_with("redirect") && !callee.ends_with("Redirect") {
return false;
}
has_redirect_path_prefix(ctx.source_bytes, sink_info.ast.span)
}
fn sink_in_entrypoint(ctx: &AnalysisContext, sink: NodeIndex) -> bool {
let sink_info = &ctx.cfg[sink];
if let Some(func_name) = &sink_info.ast.enclosing_func {
is_entry_point_func(func_name, ctx.lang)
} else {
false
}
}
impl CfgAnalysis for UnguardedSink {
fn name(&self) -> &'static str {
"unguarded-sink"
}
fn run(&self, ctx: &AnalysisContext) -> Vec<CfgFinding> {
let doms = dominators::compute_dominators(ctx.cfg, ctx.entry);
let sink_nodes = dominators::find_sink_nodes(ctx.cfg);
let guard_nodes = find_guard_nodes(ctx);
let mut findings = Vec::new();
for sink in &sink_nodes {
let sink_info = &ctx.cfg[*sink];
let sink_caps = sink_info.taint.labels.iter().fold(Cap::empty(), |acc, l| {
if let DataLabel::Sink(caps) = l {
acc | *caps
} else {
acc
}
});
if sink_caps.is_empty() {
continue;
}
let sink_func = sink_info.ast.enclosing_func.as_deref();
let is_guarded = guard_nodes.iter().any(|(guard_idx, guard_caps)| {
let guard_func = ctx.cfg[*guard_idx].ast.enclosing_func.as_deref();
(*guard_caps & sink_caps) != Cap::empty()
&& guard_func == sink_func
&& dominates(&doms, *guard_idx, *sink)
});
let has_sanitizer = ctx.cfg.node_indices().any(|idx| {
let node_func = ctx.cfg[idx].ast.enclosing_func.as_deref();
ctx.cfg[idx].taint.labels.iter().any(|l| {
if let DataLabel::Sanitizer(san_caps) = l {
(*san_caps & sink_caps) != Cap::empty()
&& node_func == sink_func
&& dominates(&doms, idx, *sink)
} else {
false
}
})
});
let has_interprocedural_sanitizer = sink_info.arg_callees.iter().any(|mc| {
if let Some(callee) = mc {
let leaf = callee_leaf_name(callee);
ctx.func_summaries.iter().any(|(k, s)| {
k.name == leaf && (s.sanitizer_caps & sink_caps) != Cap::empty()
})
} else {
false
}
});
if is_guarded || has_sanitizer || has_interprocedural_sanitizer {
continue;
}
let callee_desc = sink_info.call.callee.as_deref().unwrap_or("(unknown sink)");
let has_taint = taint_confirms_sink(ctx, *sink);
let source_derived = sink_arg_is_source_derived(ctx, *sink);
if is_all_args_constant(ctx, *sink) && !has_taint {
continue;
}
let has_shell_array_gate = sink_info.call.gate_filters.iter().any(|gf| {
gf.label_caps.contains(Cap::SHELL_ESCAPE) && gf.destination_uses.is_some()
});
if !has_taint
&& !has_shell_array_gate
&& ssa_all_sink_operands_const_or_param(ctx, *sink)
{
continue;
}
if !has_taint && sink_args_typed_safe(ctx, *sink, sink_caps) {
continue;
}
if !has_taint && sink_args_static_map_safe(ctx, *sink, sink_caps) {
continue;
}
if !has_taint && sink_args_summary_validated_safe(ctx, *sink) {
continue;
}
if sink_info.parameterized_query {
continue;
}
if is_internal_redirect(ctx, *sink, sink_caps) {
continue;
}
let param_only = sink_arg_is_parameter_only(ctx, *sink);
let in_entrypoint = sink_in_entrypoint(ctx, *sink);
let (severity, confidence) = if has_taint || source_derived {
(Severity::High, Confidence::High)
} else if param_only && !in_entrypoint {
continue;
} else if !ctx.taint_active {
(Severity::Low, Confidence::Low)
} else {
let high_risk =
Cap::SHELL_ESCAPE | Cap::CODE_EXEC | Cap::SQL_QUERY | Cap::DESERIALIZE;
if (sink_caps & high_risk).is_empty() {
continue; }
let sink_func = sink_info.ast.enclosing_func.as_deref();
let has_sources = ctx.cfg.node_indices().any(|n| {
let info = &ctx.cfg[n];
info.ast.enclosing_func.as_deref() == sink_func
&& info
.taint
.labels
.iter()
.any(|l| matches!(l, DataLabel::Source(_)))
});
let has_params = ctx.func_summaries.values().any(|s| {
s.entry.index() < ctx.cfg.node_count()
&& ctx.cfg[s.entry].ast.enclosing_func.as_deref() == sink_func
&& !s.param_names.is_empty()
});
if !has_sources && !has_params {
continue; }
(Severity::Medium, Confidence::Medium)
};
findings.push(CfgFinding {
rule_id: "cfg-unguarded-sink".to_string(),
title: "Unguarded sink".to_string(),
severity,
confidence,
span: sink_info.ast.span,
message: format!("Sink `{callee_desc}` has no dominating guard or sanitizer"),
evidence: vec![*sink],
score: None,
});
}
findings
}
}