lonkero 3.6.2

Web scanner built for actual pentests. Fast, modular, Rust.
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
// Copyright (c) 2026 Bountyy Oy. All rights reserved.
// This software is proprietary and confidential.

/**
 * Bountyy Oy - Security Headers Scanner
 * Tests for missing or misconfigured HTTP security headers
 *
 * @copyright 2026 Bountyy Oy
 * @license Proprietary - Enterprise Edition
 */
use crate::http_client::{HttpClient, HttpResponse};
use crate::types::{Confidence, ScanConfig, Severity, Vulnerability};
use anyhow::Result;
use std::sync::Arc;
use tracing::{debug, info};

pub struct SecurityHeadersScanner {
    http_client: Arc<HttpClient>,
}

impl SecurityHeadersScanner {
    pub fn new(http_client: Arc<HttpClient>) -> Self {
        Self { http_client }
    }

    /// Scan URL for security header misconfigurations
    pub async fn scan(
        &self,
        url: &str,
        _config: &ScanConfig,
    ) -> Result<(Vec<Vulnerability>, usize)> {
        info!("[Security Headers] Scanning: {}", url);

        let mut vulnerabilities = Vec::new();
        let tests_run = 1; // Single request to check all headers

        match self.http_client.get(url).await {
            Ok(response) => {
                // Skip if response is 404 Not Found or other error status codes
                // Security headers on non-existent pages are not meaningful findings
                if response.status_code == 404 {
                    debug!("[Security Headers] Skipping 404 response: {}", url);
                    return Ok((vulnerabilities, tests_run));
                }

                // Skip if response body indicates a "not found" error
                // (some APIs return 200 with error JSON instead of proper 404)
                if self.is_not_found_response(&response.body) {
                    debug!("[Security Headers] Skipping not-found error response: {}", url);
                    return Ok((vulnerabilities, tests_run));
                }

                // Skip 5xx server errors as they may have different header configurations
                if response.status_code >= 500 {
                    debug!("[Security Headers] Skipping server error response: {}", url);
                    return Ok((vulnerabilities, tests_run));
                }

                // Check each security header
                self.check_hsts(&response, url, &mut vulnerabilities);
                self.check_csp(&response, url, &mut vulnerabilities);
                self.check_x_frame_options(&response, url, &mut vulnerabilities);
                self.check_x_content_type_options(&response, url, &mut vulnerabilities);
                self.check_x_xss_protection(&response, url, &mut vulnerabilities);
                self.check_referrer_policy(&response, url, &mut vulnerabilities);
                self.check_permissions_policy(&response, url, &mut vulnerabilities);
                self.check_cors_headers(&response, url, &mut vulnerabilities);
            }
            Err(e) => {
                debug!("Failed to fetch URL for header check: {}", e);
            }
        }

        info!(
            "[SUCCESS] [Security Headers] Completed scan, found {} issues",
            vulnerabilities.len()
        );

        Ok((vulnerabilities, tests_run))
    }

    /// Check if response body indicates a "not found" or similar error
    /// Some APIs return 200 OK with error JSON instead of proper HTTP status codes
    fn is_not_found_response(&self, body: &str) -> bool {
        let body_lower = body.to_lowercase();

        // Check for common API error patterns indicating resource not found
        let not_found_patterns = [
            "\"error\":\"not found\"",
            "\"error\": \"not found\"",
            "\"message\":\"the requested resource does not exist\"",
            "\"message\": \"the requested resource does not exist\"",
            "resource does not exist",
            "endpoint not found",
            "route not found",
            "\"status\":\"not_found\"",
            "\"status\": \"not_found\"",
            "\"code\":404",
            "\"code\": 404",
        ];

        for pattern in &not_found_patterns {
            if body_lower.contains(pattern) {
                return true;
            }
        }

        // Check for JSON error response with success:false and error containing "not found"
        if body_lower.contains("\"success\":false") || body_lower.contains("\"success\": false") {
            if body_lower.contains("not found") || body_lower.contains("does not exist") {
                return true;
            }
        }

        false
    }

    /// Check HSTS (HTTP Strict Transport Security)
    fn check_hsts(
        &self,
        response: &HttpResponse,
        url: &str,
        vulnerabilities: &mut Vec<Vulnerability>,
    ) {
        if let Some(hsts) = response.header("strict-transport-security") {
            // Check if max-age is too short
            if hsts.contains("max-age") {
                if hsts.contains("max-age=0") || hsts.contains("max-age=1") {
                    vulnerabilities.push(self.create_vulnerability(
                        "Weak HSTS Configuration",
                        url,
                        Severity::Medium,
                        Confidence::High,
                        "HSTS max-age is too short (less than 1 year recommended)",
                        format!("HSTS header found but weak: {}", hsts),
                        5.0,
                    ));
                }
            }

            // Check for includeSubDomains
            if !hsts.contains("includeSubDomains") {
                vulnerabilities.push(self.create_vulnerability(
                    "HSTS Missing includeSubDomains",
                    url,
                    Severity::Low,
                    Confidence::High,
                    "HSTS configured without includeSubDomains directive",
                    "Subdomains are not protected by HSTS".to_string(),
                    3.0,
                ));
            }
        } else if url.starts_with("https") {
            vulnerabilities.push(self.create_vulnerability(
                "Missing HSTS Header",
                url,
                Severity::Medium,
                Confidence::High,
                "HTTP Strict Transport Security (HSTS) header is missing",
                "HTTPS site without HSTS is vulnerable to SSL stripping attacks".to_string(),
                5.3,
            ));
        }
    }

    /// Check Content Security Policy
    fn check_csp(
        &self,
        response: &HttpResponse,
        url: &str,
        vulnerabilities: &mut Vec<Vulnerability>,
    ) {
        if let Some(csp) = response.header("content-security-policy") {
            // Check for unsafe-inline or unsafe-eval
            if csp.contains("unsafe-inline") || csp.contains("unsafe-eval") {
                vulnerabilities.push(self.create_vulnerability(
                    "Weak CSP Configuration",
                    url,
                    Severity::Medium,
                    Confidence::High,
                    "Content Security Policy allows unsafe-inline or unsafe-eval",
                    format!("CSP: {}", csp),
                    5.0,
                ));
            }

            // Check for wildcard sources
            if csp.contains("* ") || csp.contains(" *") {
                vulnerabilities.push(self.create_vulnerability(
                    "Permissive CSP Configuration",
                    url,
                    Severity::Low,
                    Confidence::High,
                    "Content Security Policy uses wildcard (*) allowing any source",
                    format!("CSP contains wildcard: {}", csp),
                    4.0,
                ));
            }
        } else {
            vulnerabilities.push(self.create_vulnerability(
                "Missing CSP Header",
                url,
                Severity::Medium,
                Confidence::High,
                "Content Security Policy (CSP) header is missing",
                "No CSP protection against XSS and data injection attacks".to_string(),
                5.3,
            ));
        }
    }

    /// Check X-Frame-Options
    /// NOTE: Clickjacking detection is handled by the dedicated ClickjackingScanner
    /// to avoid duplicate findings. This function is kept for reference but disabled.
    fn check_x_frame_options(
        &self,
        _response: &HttpResponse,
        _url: &str,
        _vulnerabilities: &mut Vec<Vulnerability>,
    ) {
        // Disabled - clickjacking is detected by the dedicated ClickjackingScanner
        // to avoid duplicate vulnerability reports
    }

    /// Check X-Content-Type-Options
    fn check_x_content_type_options(
        &self,
        response: &HttpResponse,
        url: &str,
        vulnerabilities: &mut Vec<Vulnerability>,
    ) {
        if response.header("x-content-type-options").is_none() {
            vulnerabilities.push(self.create_vulnerability(
                "Missing X-Content-Type-Options",
                url,
                Severity::Low,
                Confidence::High,
                "X-Content-Type-Options header is missing",
                "Browsers may MIME-sniff content, leading to security issues".to_string(),
                3.1,
            ));
        }
    }

    /// Check X-XSS-Protection
    fn check_x_xss_protection(
        &self,
        response: &HttpResponse,
        url: &str,
        vulnerabilities: &mut Vec<Vulnerability>,
    ) {
        if let Some(xss_protection) = response.header("x-xss-protection") {
            if xss_protection == "0" {
                vulnerabilities.push(self.create_vulnerability(
                    "XSS Protection Disabled",
                    url,
                    Severity::Medium,
                    Confidence::High,
                    "X-XSS-Protection explicitly disabled (set to 0)",
                    "Browser XSS filter is turned off".to_string(),
                    4.0,
                ));
            }
        }
        // Note: X-XSS-Protection is deprecated, so we don't warn if it's missing
    }

    /// Check Referrer-Policy
    fn check_referrer_policy(
        &self,
        response: &HttpResponse,
        url: &str,
        vulnerabilities: &mut Vec<Vulnerability>,
    ) {
        if let Some(referrer) = response.header("referrer-policy") {
            if referrer.contains("unsafe-url") || referrer == "no-referrer-when-downgrade" {
                vulnerabilities.push(self.create_vulnerability(
                    "Weak Referrer Policy",
                    url,
                    Severity::Low,
                    Confidence::High,
                    "Referrer-Policy may leak sensitive information in URLs",
                    format!("Referrer-Policy: {}", referrer),
                    3.1,
                ));
            }
        } else {
            vulnerabilities.push(self.create_vulnerability(
                "Missing Referrer-Policy",
                url,
                Severity::Low,
                Confidence::Medium,
                "Referrer-Policy header is missing",
                "Referrer information may be leaked to third parties".to_string(),
                3.0,
            ));
        }
    }

    /// Check Permissions-Policy (formerly Feature-Policy)
    fn check_permissions_policy(
        &self,
        response: &HttpResponse,
        url: &str,
        vulnerabilities: &mut Vec<Vulnerability>,
    ) {
        let has_permissions_policy = response.header("permissions-policy").is_some();
        let has_feature_policy = response.header("feature-policy").is_some();

        if !has_permissions_policy && !has_feature_policy {
            vulnerabilities.push(
                self.create_vulnerability(
                    "Missing Permissions-Policy",
                    url,
                    Severity::Info,
                    Confidence::Medium,
                    "Permissions-Policy header is missing",
                    "Consider restricting browser features (camera, microphone, geolocation, etc.)"
                        .to_string(),
                    2.0,
                ),
            );
        }
    }

    /// Check CORS headers for misconfigurations
    fn check_cors_headers(
        &self,
        response: &HttpResponse,
        url: &str,
        vulnerabilities: &mut Vec<Vulnerability>,
    ) {
        if let Some(acao) = response.header("access-control-allow-origin") {
            // Check for wildcard with credentials
            if acao == "*" {
                if let Some(credentials) = response.header("access-control-allow-credentials") {
                    if credentials == "true" {
                        vulnerabilities.push(self.create_vulnerability(
                            "Insecure CORS Configuration",
                            url,
                            Severity::High,
                            Confidence::High,
                            "CORS allows all origins (*) with credentials enabled",
                            "This configuration allows any origin to make authenticated requests".to_string(),
                            6.5,
                        ));
                    }
                }
            }

            // Check for null origin
            if acao == "null" {
                vulnerabilities.push(self.create_vulnerability(
                    "CORS Allows Null Origin",
                    url,
                    Severity::Medium,
                    Confidence::High,
                    "CORS Access-Control-Allow-Origin set to 'null'",
                    "Null origin can be exploited via sandboxed iframes".to_string(),
                    5.3,
                ));
            }
        }
    }

    /// Create vulnerability record
    fn create_vulnerability(
        &self,
        title: &str,
        url: &str,
        severity: Severity,
        confidence: Confidence,
        description: &str,
        evidence: String,
        cvss: f32,
    ) -> Vulnerability {
        Vulnerability {
            id: format!("header_{}", uuid::Uuid::new_v4().to_string()),
            vuln_type: format!("Security Header Misconfiguration - {}", title),
            severity,
            confidence,
            category: "Configuration".to_string(),
            url: url.to_string(),
            parameter: None,
            payload: String::new(),
            description: description.to_string(),
            evidence: Some(evidence),
            cwe: "CWE-16".to_string(), // Configuration
            cvss,
            verified: true,
            false_positive: false,
            remediation: format!(
                r#"Configure proper security headers:

For {}:
- HSTS: Set Strict-Transport-Security with max-age=31536000; includeSubDomains; preload
- CSP: Implement strict Content-Security-Policy without unsafe-inline/unsafe-eval
- X-Frame-Options: Set to DENY or SAMEORIGIN, or use CSP frame-ancestors
- X-Content-Type-Options: Set to nosniff
- Referrer-Policy: Use strict-origin-when-cross-origin or no-referrer
- Permissions-Policy: Restrict unnecessary browser features

Recommended configuration (Nginx example):
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self'" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
"#,
                title
            ),
            discovered_at: chrono::Utc::now().to_rfc3339(),
            ml_data: None,
        }
    }
}

// UUID generation helper
mod uuid {
    use rand::Rng;

    pub struct Uuid;

    impl Uuid {
        pub fn new_v4() -> Self {
            Self
        }

        pub fn to_string(&self) -> String {
            let mut rng = rand::rng();
            format!(
                "{:08x}-{:04x}-{:04x}-{:04x}-{:012x}",
                rng.random::<u32>(),
                rng.random::<u16>(),
                rng.random::<u16>(),
                rng.random::<u16>(),
                rng.random::<u64>() & 0xffffffffffff
            )
        }
    }
}

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

    #[test]
    fn test_missing_hsts() {
        let scanner = SecurityHeadersScanner::new(Arc::new(HttpClient::new(5, 2).unwrap()));

        let response = HttpResponse {
            status_code: 200,
            body: String::new(),
            headers: HashMap::new(),
            duration_ms: 100,
        };

        let mut vulns = Vec::new();
        scanner.check_hsts(&response, "https://example.com", &mut vulns);

        assert_eq!(vulns.len(), 1, "Should detect missing HSTS");
        assert_eq!(vulns[0].severity, Severity::Medium);
    }

    #[test]
    fn test_missing_csp() {
        let scanner = SecurityHeadersScanner::new(Arc::new(HttpClient::new(5, 2).unwrap()));

        let response = HttpResponse {
            status_code: 200,
            body: String::new(),
            headers: HashMap::new(),
            duration_ms: 100,
        };

        let mut vulns = Vec::new();
        scanner.check_csp(&response, "https://example.com", &mut vulns);

        assert_eq!(vulns.len(), 1, "Should detect missing CSP");
    }

    #[test]
    fn test_weak_csp() {
        let scanner = SecurityHeadersScanner::new(Arc::new(HttpClient::new(5, 2).unwrap()));

        let mut headers = HashMap::new();
        headers.insert(
            "content-security-policy".to_string(),
            "default-src 'self' 'unsafe-inline'".to_string(),
        );

        let response = HttpResponse {
            status_code: 200,
            body: String::new(),
            headers,
            duration_ms: 100,
        };

        let mut vulns = Vec::new();
        scanner.check_csp(&response, "https://example.com", &mut vulns);

        assert_eq!(vulns.len(), 1, "Should detect unsafe-inline in CSP");
    }

    #[test]
    fn test_insecure_cors() {
        let scanner = SecurityHeadersScanner::new(Arc::new(HttpClient::new(5, 2).unwrap()));

        let mut headers = HashMap::new();
        headers.insert("access-control-allow-origin".to_string(), "*".to_string());
        headers.insert(
            "access-control-allow-credentials".to_string(),
            "true".to_string(),
        );

        let response = HttpResponse {
            status_code: 200,
            body: String::new(),
            headers,
            duration_ms: 100,
        };

        let mut vulns = Vec::new();
        scanner.check_cors_headers(&response, "https://example.com", &mut vulns);

        assert!(vulns.len() > 0, "Should detect insecure CORS");
        assert_eq!(vulns[0].severity, Severity::High);
    }
}