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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
// Copyright (c) 2026 Bountyy Oy. All rights reserved.
// This software is proprietary and confidential.

/**
 * Bountyy Oy - CORS Misconfiguration Scanner
 * Tests for insecure Cross-Origin Resource Sharing configurations
 *
 * @copyright 2026 Bountyy Oy
 * @license Proprietary - Enterprise Edition
 */
use crate::detection_helpers::AppCharacteristics;
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 CorsScanner {
    http_client: Arc<HttpClient>,
}

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

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

        let mut vulnerabilities = Vec::new();
        let mut tests_run = 0;

        // Test 1: Check baseline CORS headers (no Origin header)
        tests_run += 1;
        match self.http_client.get(url).await {
            Ok(response) => {
                // Store characteristics for intelligent detection
                let _characteristics = AppCharacteristics::from_response(&response, url);
                self.check_baseline_cors(&response, url, &mut vulnerabilities);
            }
            Err(e) => {
                debug!("Failed to fetch URL for CORS check: {}", e);
            }
        }

        // Test 2: Test with attacker origin
        tests_run += 1;
        if let Ok(response) = self.send_with_origin(url, "https://evil.com").await {
            self.check_reflected_origin(&response, url, "https://evil.com", &mut vulnerabilities);
        }

        // Test 3: Test with null origin
        tests_run += 1;
        if let Ok(response) = self.send_with_origin(url, "null").await {
            self.check_null_origin(&response, url, &mut vulnerabilities);
        }

        // Test 4: Test with subdomain origin
        tests_run += 1;
        if let Some(domain) = self.extract_domain(url) {
            let subdomain_origin = format!("https://evil.{}", domain);
            if let Ok(response) = self.send_with_origin(url, &subdomain_origin).await {
                self.check_subdomain_exploit(
                    &response,
                    url,
                    &subdomain_origin,
                    &mut vulnerabilities,
                );
            }
        }

        // Test 5: Test with pre-domain origin (prefix attack)
        tests_run += 1;
        if let Some(domain) = self.extract_domain(url) {
            let prefix_origin = format!("https://{}.evil.com", domain);
            if let Ok(response) = self.send_with_origin(url, &prefix_origin).await {
                self.check_prefix_exploit(&response, url, &prefix_origin, &mut vulnerabilities);
            }
        }

        // Test 6: Test with localhost origin
        tests_run += 1;
        if let Ok(response) = self.send_with_origin(url, "http://localhost").await {
            self.check_localhost_origin(&response, url, &mut vulnerabilities);
        }

        // Test 7: Test for credentials exposure
        tests_run += 1;
        if let Ok(response) = self
            .send_with_credentials(url, "https://attacker.com")
            .await
        {
            self.check_credentials_exposure(&response, url, &mut vulnerabilities);
        }

        info!(
            "[SUCCESS] [CORS] Completed {} tests, found {} issues",
            tests_run,
            vulnerabilities.len()
        );

        Ok((vulnerabilities, tests_run))
    }

    /// Send request with custom Origin header
    async fn send_with_origin(&self, url: &str, origin: &str) -> Result<HttpResponse> {
        let headers = vec![("Origin".to_string(), origin.to_string())];
        self.http_client.get_with_headers(url, headers).await
    }

    /// Send request with credentials
    async fn send_with_credentials(&self, url: &str, origin: &str) -> Result<HttpResponse> {
        let headers = vec![
            ("Origin".to_string(), origin.to_string()),
            (
                "Cookie".to_string(),
                "session=test_session_value".to_string(),
            ),
        ];
        self.http_client.get_with_headers(url, headers).await
    }

    /// Extract domain from URL
    fn extract_domain(&self, url: &str) -> Option<String> {
        if let Ok(parsed) = url::Url::parse(url) {
            parsed.host_str().map(|s| s.to_string())
        } else {
            None
        }
    }

    /// Check baseline CORS configuration
    fn check_baseline_cors(
        &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(
                            "Critical CORS Misconfiguration",
                            url,
                            Severity::Critical,
                            Confidence::High,
                            "CORS allows all origins (*) with credentials enabled",
                            format!("Access-Control-Allow-Origin: {}, Access-Control-Allow-Credentials: true", acao),
                            8.8,
                        ));
                    }
                } else {
                    vulnerabilities.push(self.create_vulnerability(
                        "Permissive CORS Policy",
                        url,
                        Severity::Medium,
                        Confidence::High,
                        "CORS allows all origins (*) - potential data leakage",
                        format!("Access-Control-Allow-Origin: {}", acao),
                        5.3,
                    ));
                }
            }
        }
    }

    /// Check for reflected origin (trusts any origin)
    fn check_reflected_origin(
        &self,
        response: &HttpResponse,
        url: &str,
        test_origin: &str,
        vulnerabilities: &mut Vec<Vulnerability>,
    ) {
        if let Some(acao) = response.header("access-control-allow-origin") {
            if acao == test_origin {
                let has_credentials = response
                    .header("access-control-allow-credentials")
                    .map(|c| c == "true")
                    .unwrap_or(false);

                if has_credentials {
                    vulnerabilities.push(self.create_vulnerability(
                        "CORS Reflected Origin with Credentials",
                        url,
                        Severity::Critical,
                        Confidence::High,
                        "Server reflects arbitrary Origin header and allows credentials",
                        format!(
                            "Sent Origin: {}, Reflected: {}, Credentials: true",
                            test_origin, acao
                        ),
                        9.1,
                    ));
                } else {
                    vulnerabilities.push(self.create_vulnerability(
                        "CORS Reflected Origin",
                        url,
                        Severity::High,
                        Confidence::High,
                        "Server reflects arbitrary Origin header",
                        format!("Sent Origin: {}, Reflected: {}", test_origin, acao),
                        7.4,
                    ));
                }
            }
        }
    }

    /// Check for null origin acceptance
    fn check_null_origin(
        &self,
        response: &HttpResponse,
        url: &str,
        vulnerabilities: &mut Vec<Vulnerability>,
    ) {
        if let Some(acao) = response.header("access-control-allow-origin") {
            if acao == "null" {
                vulnerabilities.push(self.create_vulnerability(
                    "CORS Allows Null Origin",
                    url,
                    Severity::High,
                    Confidence::High,
                    "CORS accepts 'null' origin - exploitable via sandboxed iframes",
                    "Access-Control-Allow-Origin: null - Can be exploited via data: URIs or sandboxed iframes".to_string(),
                    7.5,
                ));
            }
        }
    }

    /// Check for subdomain exploitation
    fn check_subdomain_exploit(
        &self,
        response: &HttpResponse,
        url: &str,
        subdomain_origin: &str,
        vulnerabilities: &mut Vec<Vulnerability>,
    ) {
        if let Some(acao) = response.header("access-control-allow-origin") {
            if acao == subdomain_origin || acao.contains("*.") {
                vulnerabilities.push(self.create_vulnerability(
                    "CORS Subdomain Wildcard Exploit",
                    url,
                    Severity::High,
                    Confidence::Medium,
                    "CORS trusts subdomains - attacker can register malicious subdomain",
                    format!("Server accepts subdomain origin: {}", subdomain_origin),
                    6.8,
                ));
            }
        }
    }

    /// Check for prefix exploitation
    fn check_prefix_exploit(
        &self,
        response: &HttpResponse,
        url: &str,
        prefix_origin: &str,
        vulnerabilities: &mut Vec<Vulnerability>,
    ) {
        if let Some(acao) = response.header("access-control-allow-origin") {
            if acao == prefix_origin {
                vulnerabilities.push(self.create_vulnerability(
                    "CORS Domain Prefix Exploit",
                    url,
                    Severity::High,
                    Confidence::High,
                    "CORS validates origin with weak regex - accepts malicious domains with trusted domain as prefix",
                    format!("Server accepts prefix origin: {}", prefix_origin),
                    7.2,
                ));
            }
        }
    }

    /// Check for localhost origin acceptance
    fn check_localhost_origin(
        &self,
        response: &HttpResponse,
        url: &str,
        vulnerabilities: &mut Vec<Vulnerability>,
    ) {
        if let Some(acao) = response.header("access-control-allow-origin") {
            if acao == "http://localhost" || acao == "http://127.0.0.1" {
                vulnerabilities.push(self.create_vulnerability(
                    "CORS Allows Localhost",
                    url,
                    Severity::Medium,
                    Confidence::High,
                    "CORS accepts localhost origin - could be exploited by local attackers",
                    format!("Access-Control-Allow-Origin: {}", acao),
                    5.5,
                ));
            }
        }
    }

    /// Check for credentials exposure
    fn check_credentials_exposure(
        &self,
        response: &HttpResponse,
        url: &str,
        vulnerabilities: &mut Vec<Vulnerability>,
    ) {
        if let Some(acao) = response.header("access-control-allow-origin") {
            if acao != "null" && acao != "" {
                if let Some(credentials) = response.header("access-control-allow-credentials") {
                    if credentials == "true" {
                        // Check if methods include sensitive operations
                        if let Some(methods) = response.header("access-control-allow-methods") {
                            if methods.contains("DELETE")
                                || methods.contains("PUT")
                                || methods.contains("PATCH")
                            {
                                vulnerabilities.push(self.create_vulnerability(
                                    "CORS Exposes Credentials with Write Methods",
                                    url,
                                    Severity::High,
                                    Confidence::Medium,
                                    "CORS allows credentials with write methods (PUT/DELETE/PATCH)",
                                    format!(
                                        "Origin: {}, Methods: {}, Credentials: true",
                                        acao, methods
                                    ),
                                    7.1,
                                ));
                            }
                        }
                    }
                }
            }
        }
    }

    /// 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!("cors_{}", uuid::Uuid::new_v4().to_string()),
            vuln_type: format!("CORS 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-942".to_string(), // Permissive Cross-domain Policy with Untrusted Domains
            cvss,
            verified: true,
            false_positive: false,
            remediation: r#"IMMEDIATE ACTION REQUIRED:

1. **Implement Strict Origin Whitelist**
   - Never use Access-Control-Allow-Origin: *
   - Maintain explicit list of trusted origins
   - Validate Origin header against whitelist

2. **Secure Credentials Handling**
   - Only enable credentials (Access-Control-Allow-Credentials: true) for trusted origins
   - Never combine wildcard (*) with credentials

3. **Avoid Common Mistakes**
   - Don't reflect Origin header without validation
   - Don't trust null origin
   - Don't use weak regex validation (e.g., contains() checks)
   - Don't trust all subdomains

4. **Recommended Configuration (Example)**
   ```
   // Node.js/Express example
   const allowedOrigins = ['https://app.example.com', 'https://admin.example.com'];

   app.use((req, res, next) => {
     const origin = req.headers.origin;
     if (allowedOrigins.includes(origin)) {
       res.setHeader('Access-Control-Allow-Origin', origin);
       res.setHeader('Access-Control-Allow-Credentials', 'true');
     }
     next();
   });
   ```

5. **Security Headers**
   - Use Vary: Origin header
   - Implement proper pre-flight request handling
   - Limit Access-Control-Allow-Methods to necessary methods

6. **Additional Protection**
   - Implement CSRF tokens for state-changing operations
   - Use SameSite cookie attribute
   - Consider implementing Content Security Policy

References:
- OWASP CORS Guide: https://owasp.org/www-community/attacks/CORS_OriginHeaderScrutiny
- PortSwigger CORS: https://portswigger.net/web-security/cors
"#
            .to_string(),
            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_wildcard_with_credentials() {
        let scanner = CorsScanner::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_baseline_cors(&response, "https://example.com", &mut vulns);

        assert_eq!(vulns.len(), 1, "Should detect wildcard with credentials");
        assert_eq!(vulns[0].severity, Severity::Critical);
    }

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

        let mut headers = HashMap::new();
        headers.insert(
            "access-control-allow-origin".to_string(),
            "https://evil.com".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_reflected_origin(
            &response,
            "https://example.com",
            "https://evil.com",
            &mut vulns,
        );

        assert!(
            vulns.len() > 0,
            "Should detect reflected origin with credentials"
        );
        assert_eq!(vulns[0].severity, Severity::Critical);
    }

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

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

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

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

        assert_eq!(vulns.len(), 1, "Should detect null origin");
        assert_eq!(vulns[0].severity, Severity::High);
    }

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

        let domain = scanner.extract_domain("https://api.example.com/path");
        assert_eq!(domain, Some("api.example.com".to_string()));

        let domain2 = scanner.extract_domain("http://localhost:3000");
        assert_eq!(domain2, Some("localhost".to_string()));
    }

    #[test]
    fn test_no_cors_headers() {
        let scanner = CorsScanner::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_baseline_cors(&response, "https://example.com", &mut vulns);

        assert_eq!(
            vulns.len(),
            0,
            "Should not report vulnerability when no CORS headers present"
        );
    }
}