synapse-waf 0.9.0

High-performance WAF and reverse proxy with embedded intelligence β€” built on Cloudflare Pingora
Documentation
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
//! Virtual host matching for multi-site routing.
//!
//! This module provides hostname-based routing with support for exact matches
//! and wildcard patterns (e.g., `*.example.com`).
//!
//! # Performance Optimizations (Phase 1)
//! - Uses `unicase::Ascii` for zero-allocation case-insensitive matching
//! - Uses `ahash::RandomState` for 2-3x faster HashMap lookups

use crate::config::AccessControlConfig;
use crate::headers::CompiledHeaderConfig;
use crate::shadow::ShadowMirrorConfig;
use ahash::RandomState;
use regex::Regex;
use std::collections::HashMap;
use tracing::{debug, warn};
use unicase::Ascii;

/// Configuration for a single virtual host site.
#[derive(Debug, Clone)]
pub struct SiteConfig {
    /// Hostname pattern (exact or wildcard like `*.example.com`)
    pub hostname: String,
    /// Upstream backend addresses
    pub upstreams: Vec<String>,
    /// Whether TLS is enabled for this site
    pub tls_enabled: bool,
    /// Path to TLS certificate (if TLS enabled)
    pub tls_cert: Option<String>,
    /// Path to TLS private key (if TLS enabled)
    pub tls_key: Option<String>,
    /// WAF threshold override (0-100, None uses global default)
    pub waf_threshold: Option<u8>,
    /// Whether WAF is enabled for this site
    pub waf_enabled: bool,
    /// Access control configuration (optional)
    pub access_control: Option<AccessControlConfig>,
    /// Header manipulation configuration (optional)
    pub headers: Option<CompiledHeaderConfig>,
    /// Shadow mirroring configuration for honeypot delivery
    pub shadow_mirror: Option<ShadowMirrorConfig>,
}

impl Default for SiteConfig {
    fn default() -> Self {
        Self {
            hostname: String::new(),
            upstreams: Vec::new(),
            tls_enabled: false,
            tls_cert: None,
            tls_key: None,
            waf_threshold: None,
            waf_enabled: true,
            access_control: None,
            headers: None,
            shadow_mirror: None,
        }
    }
}

impl From<crate::config::SiteYamlConfig> for SiteConfig {
    fn from(yaml: crate::config::SiteYamlConfig) -> Self {
        Self {
            hostname: yaml.hostname,
            upstreams: yaml
                .upstreams
                .iter()
                .map(|u| format!("{}:{}", u.host, u.port))
                .collect(),
            tls_enabled: yaml.tls.is_some(),
            tls_cert: yaml.tls.as_ref().map(|t| t.cert_path.clone()),
            tls_key: yaml.tls.as_ref().map(|t| t.key_path.clone()),
            waf_threshold: yaml.waf.as_ref().and_then(|w| w.threshold),
            waf_enabled: yaml.waf.as_ref().map(|w| w.enabled).unwrap_or(true),
            access_control: yaml.access_control,
            headers: yaml.headers.as_ref().map(|headers| headers.compile()),
            shadow_mirror: yaml.shadow_mirror,
        }
    }
}

/// Compiled wildcard pattern for hostname matching.
#[derive(Debug)]
struct WildcardPattern {
    /// Original pattern string
    pattern: String,
    /// Compiled regex for matching
    regex: Regex,
    /// Reference to site config
    site_index: usize,
}

/// Virtual host matcher with O(1) exact matching and wildcard fallback.
///
/// Security features:
/// - Limits wildcard complexity (max 3 wildcards, 253 char limit)
/// - Sanitizes host headers (rejects null bytes, invalid chars)
/// - Case-insensitive matching via pre-normalization
///
/// Performance features (Phase 1):
/// - Uses `Ascii<String>` for case-insensitive keys (zero-allocation lookups)
/// - Uses `ahash::RandomState` for 2-3x faster HashMap operations
#[derive(Debug)]
pub struct VhostMatcher {
    /// Exact hostname -> site index mapping (O(1) lookup with fast hashing)
    exact_matches: HashMap<Ascii<String>, usize, RandomState>,
    /// Wildcard patterns checked in order
    wildcard_patterns: Vec<WildcardPattern>,
    /// All site configurations
    sites: Vec<SiteConfig>,
    /// Default site index (if any)
    default_site: Option<usize>,
}

impl VhostMatcher {
    /// Maximum allowed wildcards in a pattern (prevents ReDoS).
    const MAX_WILDCARDS: usize = 3;
    /// Maximum hostname length per RFC 1035.
    const MAX_HOSTNAME_LEN: usize = 253;

    /// Creates a new VhostMatcher from site configurations.
    ///
    /// # Errors
    /// Returns an error if:
    /// - A wildcard pattern has too many wildcards
    /// - A hostname exceeds the maximum length
    /// - A wildcard pattern fails to compile
    pub fn new(sites: Vec<SiteConfig>) -> Result<Self, VhostError> {
        // Pre-allocate with capacity hint (PERF-P3-1)
        let mut exact_matches = HashMap::with_capacity_and_hasher(sites.len(), RandomState::new());
        let mut wildcard_patterns = Vec::with_capacity(sites.len() / 4); // ~25% wildcards typical
        let mut default_site = None;

        for (index, site) in sites.iter().enumerate() {
            // Validate hostname length
            if site.hostname.len() > Self::MAX_HOSTNAME_LEN {
                return Err(VhostError::HostnameTooLong {
                    hostname: site.hostname.clone(),
                    max_len: Self::MAX_HOSTNAME_LEN,
                });
            }

            // Normalize hostname - Ascii handles case-insensitive comparison
            let normalized = site.hostname.to_lowercase();

            // Check if this is a wildcard pattern
            if normalized.contains('*') {
                // Validate wildcard count
                let wildcard_count = normalized.matches('*').count();
                if wildcard_count > Self::MAX_WILDCARDS {
                    return Err(VhostError::TooManyWildcards {
                        pattern: site.hostname.clone(),
                        count: wildcard_count,
                        max: Self::MAX_WILDCARDS,
                    });
                }

                // Convert wildcard pattern to regex
                let regex_pattern = Self::wildcard_to_regex(&normalized);
                let regex = Regex::new(&regex_pattern).map_err(|e| VhostError::InvalidPattern {
                    pattern: site.hostname.clone(),
                    reason: e.to_string(),
                })?;

                wildcard_patterns.push(WildcardPattern {
                    pattern: normalized,
                    regex,
                    site_index: index,
                });
            } else if normalized == "_" || normalized == "default" {
                // Special default site marker
                default_site = Some(index);
            } else {
                // Exact match - wrap in Ascii for case-insensitive key (PERF-P0-1)
                exact_matches.insert(Ascii::new(normalized), index);
            }
        }

        // Sort wildcards by specificity (more specific patterns first)
        wildcard_patterns.sort_by(|a, b| {
            // More segments = more specific
            let a_segments = a.pattern.matches('.').count();
            let b_segments = b.pattern.matches('.').count();
            b_segments.cmp(&a_segments)
        });

        Ok(Self {
            exact_matches,
            wildcard_patterns,
            sites,
            default_site,
        })
    }

    /// Create an empty matcher with no sites.
    pub fn empty() -> Self {
        Self {
            exact_matches: HashMap::with_hasher(RandomState::new()),
            wildcard_patterns: Vec::new(),
            sites: Vec::new(),
            default_site: None,
        }
    }

    /// Converts a wildcard pattern to a regex pattern.
    fn wildcard_to_regex(pattern: &str) -> String {
        let mut regex = String::from("^");
        for ch in pattern.chars() {
            match ch {
                '*' => regex.push_str("[a-z0-9-]*"),
                '.' => regex.push_str("\\."),
                '-' => regex.push('-'),
                c if c.is_ascii_alphanumeric() => regex.push(c),
                _ => regex.push_str(&regex::escape(&ch.to_string())),
            }
        }
        regex.push('$');
        regex
    }

    /// Sanitizes and validates a host header value.
    ///
    /// # Security
    /// - Rejects null bytes
    /// - Rejects non-ASCII characters
    /// - Strips port numbers
    /// - Normalizes to lowercase
    pub fn sanitize_host(host: &str) -> Result<String, VhostError> {
        // Reject null bytes (potential injection)
        if host.contains('\0') {
            return Err(VhostError::InvalidHost {
                host: host.to_string(),
                reason: "contains null byte".to_string(),
            });
        }

        // Reject non-printable or non-ASCII characters
        if !host.chars().all(|c| c.is_ascii() && !c.is_control()) {
            return Err(VhostError::InvalidHost {
                host: host.to_string(),
                reason: "contains invalid characters".to_string(),
            });
        }

        // Strip port number if present
        let hostname = host.split(':').next().unwrap_or(host);

        // Validate hostname characters (RFC 1123)
        if !hostname.is_empty() && !Self::is_valid_hostname(hostname) {
            return Err(VhostError::InvalidHost {
                host: host.to_string(),
                reason: "invalid hostname characters".to_string(),
            });
        }

        Ok(hostname.to_lowercase())
    }

    /// Validates that a hostname contains only valid DNS characters.
    fn is_valid_hostname(hostname: &str) -> bool {
        hostname
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '.')
            && !hostname.starts_with('-')
            && !hostname.ends_with('-')
    }

    /// Matches a host header to a site configuration.
    ///
    /// # Arguments
    /// * `host` - The raw Host header value
    ///
    /// # Returns
    /// The matching site configuration, or None if no match found.
    ///
    /// # Performance
    /// Uses `Ascii::new()` for zero-allocation case-insensitive lookup (PERF-P0-1)
    #[inline]
    pub fn match_host(&self, host: &str) -> Option<&SiteConfig> {
        // Sanitize the host header (returns lowercase)
        let hostname = match Self::sanitize_host(host) {
            Ok(h) => h,
            Err(e) => {
                warn!("Invalid host header: {}", e);
                return self.default_site.map(|i| &self.sites[i]);
            }
        };

        // Try exact match first (O(1)) - Ascii provides case-insensitive comparison (PERF-P0-1)
        if let Some(&index) = self.exact_matches.get(&Ascii::new(hostname.clone())) {
            debug!("Exact match for host '{}' -> site {}", hostname, index);
            return Some(&self.sites[index]);
        }

        // Try wildcard patterns (O(n) where n = wildcard count)
        for pattern in &self.wildcard_patterns {
            if pattern.regex.is_match(&hostname) {
                debug!(
                    "Wildcard match for host '{}' -> pattern '{}' -> site {}",
                    hostname, pattern.pattern, pattern.site_index
                );
                return Some(&self.sites[pattern.site_index]);
            }
        }

        // Fall back to default site
        if let Some(index) = self.default_site {
            debug!("Using default site for host '{}'", hostname);
            return Some(&self.sites[index]);
        }

        debug!("No match found for host '{}'", hostname);
        None
    }

    /// Returns all configured sites.
    pub fn sites(&self) -> &[SiteConfig] {
        &self.sites
    }

    /// Returns the number of configured sites.
    pub fn site_count(&self) -> usize {
        self.sites.len()
    }
}

/// Errors that can occur during vhost matching.
#[derive(Debug, thiserror::Error)]
pub enum VhostError {
    #[error("hostname '{hostname}' exceeds maximum length of {max_len}")]
    HostnameTooLong { hostname: String, max_len: usize },

    #[error("pattern '{pattern}' has {count} wildcards, max is {max}")]
    TooManyWildcards {
        pattern: String,
        count: usize,
        max: usize,
    },

    #[error("invalid pattern '{pattern}': {reason}")]
    InvalidPattern { pattern: String, reason: String },

    #[error("invalid host header '{host}': {reason}")]
    InvalidHost { host: String, reason: String },
}

#[cfg(test)]
mod tests {
    use super::*;

    fn make_site(hostname: &str) -> SiteConfig {
        SiteConfig {
            hostname: hostname.to_string(),
            upstreams: vec!["127.0.0.1:8080".to_string()],
            ..Default::default()
        }
    }

    #[test]
    fn test_exact_match() {
        let sites = vec![make_site("example.com"), make_site("api.example.com")];
        let matcher = VhostMatcher::new(sites).unwrap();

        assert!(matcher.match_host("example.com").is_some());
        assert!(matcher.match_host("api.example.com").is_some());
        assert!(matcher.match_host("other.com").is_none());
    }

    #[test]
    fn test_case_insensitive() {
        let sites = vec![make_site("Example.COM")];
        let matcher = VhostMatcher::new(sites).unwrap();

        assert!(matcher.match_host("example.com").is_some());
        assert!(matcher.match_host("EXAMPLE.COM").is_some());
        assert!(matcher.match_host("Example.Com").is_some());
    }

    #[test]
    fn test_wildcard_match() {
        let sites = vec![make_site("*.example.com"), make_site("example.com")];
        let matcher = VhostMatcher::new(sites).unwrap();

        assert!(matcher.match_host("example.com").is_some());
        assert!(matcher.match_host("api.example.com").is_some());
        assert!(matcher.match_host("www.example.com").is_some());
        assert!(matcher.match_host("other.com").is_none());
    }

    #[test]
    fn test_port_stripping() {
        let sites = vec![make_site("example.com")];
        let matcher = VhostMatcher::new(sites).unwrap();

        assert!(matcher.match_host("example.com:8080").is_some());
        assert!(matcher.match_host("example.com:443").is_some());
    }

    #[test]
    fn test_default_site() {
        let sites = vec![make_site("example.com"), make_site("_")];
        let matcher = VhostMatcher::new(sites).unwrap();

        assert!(matcher.match_host("example.com").is_some());
        assert!(matcher.match_host("unknown.com").is_some()); // Falls back to default
    }

    #[test]
    fn test_sanitize_null_byte() {
        let result = VhostMatcher::sanitize_host("example\0.com");
        assert!(result.is_err());
    }

    #[test]
    fn test_sanitize_non_ascii() {
        let result = VhostMatcher::sanitize_host("δΎ‹γˆ.com");
        assert!(result.is_err());
    }

    #[test]
    fn test_too_many_wildcards() {
        let sites = vec![make_site("*.*.*.*")];
        let result = VhostMatcher::new(sites);
        assert!(result.is_err());
    }

    #[test]
    fn test_hostname_too_long() {
        let long_hostname = "a".repeat(300);
        let sites = vec![make_site(&long_hostname)];
        let result = VhostMatcher::new(sites);
        assert!(result.is_err());
    }

    #[test]
    fn test_wildcard_specificity() {
        let sites = vec![make_site("*.example.com"), make_site("*.api.example.com")];
        let matcher = VhostMatcher::new(sites).unwrap();

        // More specific pattern should match first
        let site = matcher.match_host("v1.api.example.com").unwrap();
        assert_eq!(site.hostname, "*.api.example.com");
    }
}