Skip to main content

kz_server/
security.rs

1use crate::error::{Result, ServerError};
2use axum::http::HeaderMap;
3
4pub const DEFAULT_CREDENTIAL_LOCATION: &str = "header:Authorization:Bearer";
5
6const BLOCKED_HOSTS: &[&str] = &[
7    "localhost", "0.0.0.0", "::1", "169.254.169.254", "fd00:ec2::254",
8    "metadata.google.internal", "metadata.goog", "metadata", "100.100.100.200",
9];
10
11const BLOCKED_SUFFIXES: &[&str] = &[".internal", ".local"];
12
13pub struct CredentialLocation<'a> {
14    pub header_name: &'a str,
15    pub prefix: &'a str,
16}
17
18pub fn extract_bearer_token(headers: &HeaderMap) -> Option<String> {
19    headers
20        .get("authorization")?
21        .to_str()
22        .ok()?
23        .strip_prefix("Bearer ")
24        .filter(|t| !t.is_empty())
25        .map(String::from)
26}
27
28pub fn effective_location(location: Option<&str>) -> &str {
29    location.unwrap_or(DEFAULT_CREDENTIAL_LOCATION)
30}
31
32pub fn parse_credential_location(location: &str) -> std::result::Result<CredentialLocation<'_>, String> {
33    let parts: Vec<&str> = location.splitn(3, ':').collect();
34    if parts.len() < 2 || parts[0] != "header" {
35        return Err(format!("invalid credential_location format: {location}"));
36    }
37    Ok(CredentialLocation {
38        header_name: parts[1],
39        prefix: if parts.len() == 3 { parts[2] } else { "" },
40    })
41}
42
43pub fn format_credential_value(loc: &CredentialLocation<'_>, secret_value: &str) -> String {
44    if loc.prefix.is_empty() {
45        secret_value.to_string()
46    } else {
47        format!("{} {secret_value}", loc.prefix)
48    }
49}
50
51pub fn is_blocked_host(host: &str) -> bool {
52    // Strip brackets for IPv6 literals like [::1]
53    let unbracketed = host.trim_start_matches('[').trim_end_matches(']');
54    // For IPv6 addresses (contain ':'), don't split on ':' to strip port
55    let clean = if unbracketed.contains(':') {
56        unbracketed
57    } else {
58        // For IPv4/hostname with optional port, take only the host part
59        unbracketed.split(':').next().unwrap_or(unbracketed)
60    };
61    if BLOCKED_HOSTS.contains(&clean) {
62        return true;
63    }
64    if BLOCKED_SUFFIXES.iter().any(|s| clean.ends_with(s)) {
65        return true;
66    }
67    is_private_ip(clean)
68}
69
70pub fn validate_ref(ref_path: &str) -> Result<()> {
71    if ref_path.is_empty() {
72        return Err(ServerError::PathTraversal("empty ref".into()));
73    }
74    if ref_path.contains('%') {
75        return Err(ServerError::PathTraversal("encoded characters not allowed".into()));
76    }
77    if ref_path.contains('\0') {
78        return Err(ServerError::PathTraversal("null bytes not allowed".into()));
79    }
80    if ref_path.split('/').any(|seg| seg == "..") {
81        return Err(ServerError::PathTraversal(ref_path.into()));
82    }
83    Ok(())
84}
85
86fn is_private_ipv4(addr: std::net::Ipv4Addr) -> bool {
87    let o = addr.octets();
88    o[0] == 10
89        || (o[0] == 172 && (16..=31).contains(&o[1]))
90        || (o[0] == 192 && o[1] == 168)
91        || o[0] == 127
92        || (o[0] == 169 && o[1] == 254)
93}
94
95fn is_private_ipv6(addr: std::net::Ipv6Addr) -> bool {
96    // Check IPv4-mapped addresses
97    if let Some(v4) = addr.to_ipv4_mapped() {
98        return is_private_ipv4(v4);
99    }
100    let s = addr.segments();
101    s[0] == 0xfd00 || s[0] == 0xfe80 || addr == std::net::Ipv6Addr::LOCALHOST
102}
103
104/// Detect non-standard IP representations that bypass std::net parsing
105fn looks_like_ip_bypass(host: &str) -> bool {
106    // Pure decimal IP (e.g., 2130706433 = 127.0.0.1)
107    if host.chars().all(|c| c.is_ascii_digit()) && host.parse::<u64>().is_ok() {
108        return true;
109    }
110    // Hex IP (0x7f000001 or 0x7f.0.0.1)
111    if host.starts_with("0x") || host.starts_with("0X") {
112        return true;
113    }
114    // Octal octets (leading zero in any segment: 0177.0.0.1)
115    if host.contains('.') {
116        let segments: Vec<&str> = host.split('.').collect();
117        if segments.len() == 4 && segments.iter().all(|s| s.chars().all(|c| c.is_ascii_digit())) {
118            if segments.iter().any(|s| s.len() > 1 && s.starts_with('0')) {
119                return true;
120            }
121        }
122    }
123    false
124}
125
126fn is_private_ip(host: &str) -> bool {
127    // Standard IPv4
128    if let Ok(addr) = host.parse::<std::net::Ipv4Addr>() {
129        return is_private_ipv4(addr);
130    }
131    // Standard IPv6
132    if let Ok(addr) = host.parse::<std::net::Ipv6Addr>() {
133        return is_private_ipv6(addr);
134    }
135    // Reject suspicious IP formats that could bypass parsing
136    // (octal: 0177.0.0.1, hex: 0x7f.0.0.1, decimal: 2130706433)
137    if looks_like_ip_bypass(host) {
138        return true;
139    }
140    false
141}