syncable_cli/analyzer/kubelint/templates/
privilegeescalation.rs

1//! Privilege escalation detection template.
2
3use crate::analyzer::kubelint::context::Object;
4use crate::analyzer::kubelint::extract;
5use crate::analyzer::kubelint::templates::{CheckFunc, ParameterDesc, Template, TemplateError};
6use crate::analyzer::kubelint::types::{Diagnostic, ObjectKindsDesc};
7
8/// Template for detecting privilege escalation.
9pub struct PrivilegeEscalationTemplate;
10
11impl Template for PrivilegeEscalationTemplate {
12    fn key(&self) -> &str {
13        "privilege-escalation"
14    }
15
16    fn human_name(&self) -> &str {
17        "Privilege Escalation"
18    }
19
20    fn description(&self) -> &str {
21        "Detects containers that allow privilege escalation"
22    }
23
24    fn supported_object_kinds(&self) -> ObjectKindsDesc {
25        ObjectKindsDesc::default()
26    }
27
28    fn parameters(&self) -> Vec<ParameterDesc> {
29        Vec::new()
30    }
31
32    fn instantiate(
33        &self,
34        _params: &serde_yaml::Value,
35    ) -> Result<Box<dyn CheckFunc>, TemplateError> {
36        Ok(Box::new(PrivilegeEscalationCheck))
37    }
38}
39
40struct PrivilegeEscalationCheck;
41
42impl CheckFunc for PrivilegeEscalationCheck {
43    fn check(&self, object: &Object) -> Vec<Diagnostic> {
44        let mut diagnostics = Vec::new();
45
46        if let Some(pod_spec) = extract::pod_spec::extract_pod_spec(&object.k8s_object) {
47            for container in extract::container::all_containers(pod_spec) {
48                // Check if allowPrivilegeEscalation is explicitly set to true
49                // or if it's not set at all (default is true in Kubernetes)
50                let allows_escalation = container
51                    .security_context
52                    .as_ref()
53                    .map(|sc| sc.allow_privilege_escalation != Some(false))
54                    .unwrap_or(true);
55
56                if allows_escalation {
57                    diagnostics.push(Diagnostic {
58                        message: format!(
59                            "Container '{}' allows privilege escalation",
60                            container.name
61                        ),
62                        remediation: Some(
63                            "Set securityContext.allowPrivilegeEscalation to false.".to_string(),
64                        ),
65                    });
66                }
67            }
68        }
69
70        diagnostics
71    }
72}