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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
// Copyright (c) 2026 Bountyy Oy. All rights reserved.
// This software is proprietary and confidential.

use crate::http_client::HttpClient;
use crate::types::{ScanConfig, Severity, Vulnerability};
use regex::Regex;
use std::sync::Arc;
use tracing::info;

mod uuid {
    pub use uuid::Uuid;
}

/// Scanner for sensitive data exposure (files, credentials, configuration)
pub struct SensitiveDataScanner {
    http_client: Arc<HttpClient>,
}

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

    /// Run sensitive data exposure scan
    pub async fn scan(
        &self,
        url: &str,
        _config: &ScanConfig,
    ) -> anyhow::Result<(Vec<Vulnerability>, usize)> {
        info!("Starting sensitive data exposure scan on {}", url);

        let mut all_vulnerabilities = Vec::new();
        let mut total_tests = 0;

        // Parse base URL
        let url_obj = match url::Url::parse(url) {
            Ok(u) => u,
            Err(e) => {
                info!("Failed to parse URL: {}", e);
                return Ok((all_vulnerabilities, 0));
            }
        };

        let base_url = format!(
            "{}://{}",
            url_obj.scheme(),
            url_obj.host_str().unwrap_or("")
        );

        // Test sensitive file paths
        let sensitive_paths = self.get_sensitive_paths();

        for path in &sensitive_paths {
            total_tests += 1;
            let test_url = format!("{}{}", base_url, path);

            match self.http_client.get(&test_url).await {
                Ok(response) => {
                    if let Some(vuln) = self.analyze_sensitive_file(
                        &response.body,
                        response.status_code,
                        path,
                        &test_url,
                    ) {
                        all_vulnerabilities.push(vuln);
                    }
                }
                Err(_) => {
                    // File not accessible, continue
                }
            }
        }

        // Check main response for exposed credentials
        total_tests += 1;
        match self.http_client.get(url).await {
            Ok(response) => {
                let cred_vulns = self.scan_for_credentials(&response.body, url);
                all_vulnerabilities.extend(cred_vulns);
            }
            Err(_) => {
                // Continue
            }
        }

        info!(
            "Sensitive data exposure scan completed: {} tests run, {} vulnerabilities found",
            total_tests,
            all_vulnerabilities.len()
        );

        Ok((all_vulnerabilities, total_tests))
    }

    /// Get list of sensitive paths to test
    fn get_sensitive_paths(&self) -> Vec<&'static str> {
        vec![
            // Environment and config files
            "/.env",
            "/.env.local",
            "/.env.production",
            "/.env.development",
            "/config.php",
            "/configuration.php",
            "/wp-config.php",
            "/wp-config.php.bak",
            "/config.json",
            "/config.yml",
            "/config.yaml",
            "/settings.json",
            "/settings.yml",
            "/web.config",
            "/application.properties",
            "/config/database.yml",
            "/config/secrets.yml",
            "/config/app.yml",
            // Git files
            "/.git/config",
            "/.git/HEAD",
            "/.git/index",
            "/.gitignore",
            // Package manager files
            "/package.json",
            "/package-lock.json",
            "/composer.json",
            "/composer.lock",
            "/yarn.lock",
            "/Gemfile",
            "/Gemfile.lock",
            "/requirements.txt",
            "/Pipfile",
            "/Pipfile.lock",
            // Database dumps
            "/backup.sql",
            "/dump.sql",
            "/database.sql",
            "/db.sql",
            "/mysql.sql",
            "/postgres.sql",
            "/data.sql",
            // Debug and info files
            "/phpinfo.php",
            "/info.php",
            "/test.php",
            "/debug.php",
            "/_debug",
            "/debug",
            // Log files
            "/logs/error.log",
            "/logs/access.log",
            "/log/error.log",
            "/error.log",
            "/access.log",
            "/error_log",
            "/debug.log",
            // API documentation
            "/api/swagger.json",
            "/api-docs",
            "/swagger.json",
            "/swagger.yaml",
            "/openapi.json",
            "/graphql",
            "/v1/api-docs",
            "/api/v1/swagger",
            // Server status
            "/server-status",
            "/server-info",
            "/status",
            "/health",
            // Other sensitive files
            "/.DS_Store",
            "/robots.txt",
            "/.well-known/security.txt",
            "/sitemap.xml",
            "/admin/config",
            "/.htaccess",
            "/.htpasswd",
            "/web.config.bak",
            "/backup.zip",
            "/site.zip",
            "/www.zip",
        ]
    }

    /// Analyze response for sensitive file exposure
    fn analyze_sensitive_file(
        &self,
        body: &str,
        status_code: u16,
        path: &str,
        url: &str,
    ) -> Option<Vulnerability> {
        if status_code != 200 || body.is_empty() {
            return None;
        }

        let body_lower = body.to_lowercase();

        // .env file exposure
        if path.contains(".env") {
            let env_patterns = ["db_password=", "api_key=", "secret=", "password=", "token="];
            if env_patterns.iter().any(|p| body_lower.contains(p)) {
                return Some(self.create_vulnerability(
                    "Environment File Exposed",
                    url,
                    &self.truncate_evidence(body, 200),
                    Severity::Critical,
                    "CWE-215",
                    9.8,
                    "Remove .env files from web root. Use server-side environment variables. Add .env to .gitignore.",
                ));
            }
        }

        // Git repository exposure
        if path.contains(".git") {
            if body.contains("[core]")
                || body.contains("repositoryformatversion")
                || body.contains("ref: refs/")
            {
                return Some(self.create_vulnerability(
                    "Git Repository Files Exposed",
                    url,
                    &self.truncate_evidence(body, 200),
                    Severity::High,
                    "CWE-540",
                    7.5,
                    "Remove .git directory from web root. Add server configuration to deny access to .git folders.",
                ));
            }
        }

        // Configuration files
        if path.contains("config") || path.contains("wp-config") || path.contains("web.config") {
            let cred_patterns = [
                "password",
                "username",
                "db_name",
                "db_user",
                "db_password",
                "db_host",
            ];
            if cred_patterns.iter().any(|p| body_lower.contains(p)) {
                return Some(self.create_vulnerability(
                    "Configuration File with Credentials Exposed",
                    url,
                    &self.truncate_evidence(body, 200),
                    Severity::Critical,
                    "CWE-200",
                    9.1,
                    "Remove configuration files from web root. Store outside document root. Use environment variables.",
                ));
            }
        }

        // SQL dumps
        if path.contains(".sql") {
            if body.contains("INSERT INTO")
                || body.contains("CREATE TABLE")
                || body.contains("DROP TABLE")
            {
                return Some(self.create_vulnerability(
                    "Database Dump File Exposed",
                    url,
                    "SQL dump contains database structure and data",
                    Severity::Critical,
                    "CWE-538",
                    8.8,
                    "Remove SQL dump files from web root. Store backups securely outside public access.",
                ));
            }
        }

        // phpinfo exposure
        if path.contains("phpinfo") || path.contains("info.php") {
            if body.contains("PHP Version")
                || body.contains("phpinfo()")
                || body.contains("php.ini")
            {
                return Some(self.create_vulnerability(
                    "PHPInfo Page Exposed",
                    url,
                    "PHPInfo reveals server configuration and environment variables",
                    Severity::Medium,
                    "CWE-200",
                    5.3,
                    "Remove phpinfo() files from production. Disable in production environments.",
                ));
            }
        }

        // API documentation
        if path.contains("swagger") || path.contains("api-docs") || path.contains("openapi") {
            if body_lower.contains("swagger")
                || body_lower.contains("openapi")
                || body_lower.contains("\"paths\"")
            {
                return Some(self.create_vulnerability(
                    "API Documentation Exposed",
                    url,
                    "API documentation reveals endpoints and schema",
                    Severity::Medium,
                    "CWE-200",
                    5.3,
                    "Restrict access to API documentation in production. Require authentication.",
                ));
            }
        }

        // Log files
        if path.contains("log") {
            if body.contains("ERROR")
                || body.contains("WARNING")
                || body.contains("Exception")
                || body.contains("Stack trace")
            {
                return Some(self.create_vulnerability(
                    "Log File Exposed",
                    url,
                    "Log file may contain sensitive error information",
                    Severity::Medium,
                    "CWE-532",
                    5.3,
                    "Remove log files from web root. Configure logging to secure location. Disable directory listing.",
                ));
            }
        }

        // Server status pages
        if path.contains("server-status") || path.contains("server-info") {
            if body_lower.contains("apache")
                || body_lower.contains("server version")
                || body_lower.contains("uptime")
            {
                return Some(self.create_vulnerability(
                    "Server Status Page Exposed",
                    url,
                    "Server status reveals configuration and active connections",
                    Severity::Low,
                    "CWE-200",
                    3.7,
                    "Restrict access to server status pages. Require authentication or disable entirely.",
                ));
            }
        }

        // Package manager files (informational)
        if path.contains("package.json") || path.contains("composer.json") {
            if body_lower.contains("dependencies") || body_lower.contains("\"name\"") {
                return Some(self.create_vulnerability(
                    "Package Manager File Exposed",
                    url,
                    "Package file reveals dependencies and versions",
                    Severity::Info,
                    "CWE-200",
                    2.0,
                    "Consider restricting access to package manager files to prevent version enumeration.",
                ));
            }
        }

        None
    }

    /// Scan response body for exposed credentials
    fn scan_for_credentials(&self, body: &str, url: &str) -> Vec<Vulnerability> {
        let mut vulnerabilities = Vec::new();

        // AWS Access Keys
        if let Some(matches) = self.regex_scan(body, r"AKIA[0-9A-Z]{16}") {
            for evidence in matches.into_iter().take(2) {
                vulnerabilities.push(self.create_vulnerability(
                    "AWS Access Key Exposed in Response",
                    url,
                    &evidence,
                    Severity::Critical,
                    "CWE-798",
                    9.5,
                    "Rotate AWS credentials immediately. Remove from client-side code. Use IAM roles.",
                ));
            }
        }

        // Stripe Secret Keys
        if let Some(matches) = self.regex_scan(body, r"sk_live_[a-zA-Z0-9]{24,}") {
            for evidence in matches.into_iter().take(2) {
                vulnerabilities.push(self.create_vulnerability(
                    "Stripe Secret Key Exposed in Response",
                    url,
                    &evidence,
                    Severity::Critical,
                    "CWE-798",
                    9.5,
                    "Rotate Stripe secret key immediately. Never expose secret keys client-side.",
                ));
            }
        }

        // Google API Keys
        if let Some(matches) = self.regex_scan(body, r"AIza[0-9A-Za-z\-_]{35}") {
            for evidence in matches.into_iter().take(2) {
                vulnerabilities.push(self.create_vulnerability(
                    "Google API Key Exposed in Response",
                    url,
                    &evidence,
                    Severity::High,
                    "CWE-798",
                    7.5,
                    "Rotate Google API key. Implement API key restrictions (IP, referrer, API limits).",
                ));
            }
        }

        // GitHub Tokens
        if let Some(matches) = self.regex_scan(body, r"ghp_[a-zA-Z0-9]{36}") {
            for evidence in matches.into_iter().take(2) {
                vulnerabilities.push(self.create_vulnerability(
                    "GitHub Personal Access Token Exposed",
                    url,
                    &evidence,
                    Severity::Critical,
                    "CWE-798",
                    9.0,
                    "Revoke GitHub token immediately. Use GitHub Apps or OAuth for authentication.",
                ));
            }
        }

        // Slack Tokens
        if let Some(matches) = self.regex_scan(body, r"xox[baprs]-[a-zA-Z0-9\-]{10,}") {
            for evidence in matches.into_iter().take(2) {
                vulnerabilities.push(self.create_vulnerability(
                    "Slack Token Exposed in Response",
                    url,
                    &evidence,
                    Severity::High,
                    "CWE-798",
                    8.0,
                    "Revoke Slack token immediately. Rotate credentials. Use environment variables.",
                ));
            }
        }

        vulnerabilities
    }

    /// Perform regex scan and return matches
    fn regex_scan(&self, content: &str, pattern: &str) -> Option<Vec<String>> {
        let regex = match Regex::new(pattern) {
            Ok(r) => r,
            Err(_) => return None,
        };

        let matches: Vec<String> = regex
            .find_iter(content)
            .map(|m| {
                let matched = m.as_str();
                if matched.len() > 40 {
                    format!("{}...", &matched[..40])
                } else {
                    matched.to_string()
                }
            })
            .collect();

        if matches.is_empty() {
            None
        } else {
            Some(matches)
        }
    }

    /// Truncate evidence to specified length
    fn truncate_evidence(&self, text: &str, max_len: usize) -> String {
        if text.len() > max_len {
            format!("{}...", &text[..max_len])
        } else {
            text.to_string()
        }
    }

    /// Create a vulnerability record
    fn create_vulnerability(
        &self,
        vuln_type: &str,
        url: &str,
        evidence: &str,
        severity: Severity,
        cwe: &str,
        cvss: f32,
        remediation: &str,
    ) -> Vulnerability {
        Vulnerability {
            id: format!("sensdata_{}", uuid::Uuid::new_v4().to_string()),
            vuln_type: vuln_type.to_string(),
            severity,
            confidence: crate::types::Confidence::High,
            category: "Sensitive Data Exposure".to_string(),
            url: url.to_string(),
            parameter: None,
            payload: "".to_string(),
            description: format!("{}: {}", vuln_type, evidence),
            evidence: Some(evidence.to_string()),
            cwe: cwe.to_string(),
            cvss,
            verified: true,
            false_positive: false,
            remediation: remediation.to_string(),
            discovered_at: chrono::Utc::now().to_rfc3339(),
            ml_data: None,
        }
    }
}

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

    fn create_test_scanner() -> SensitiveDataScanner {
        let client = Arc::new(HttpClient::new(10000, 3).unwrap());
        SensitiveDataScanner::new(client)
    }

    #[test]
    fn test_analyze_env_file() {
        let scanner = create_test_scanner();

        let body = "DB_PASSWORD=secret123\nAPI_KEY=abc123\nSECRET=xyz789";
        let vuln = scanner.analyze_sensitive_file(body, 200, "/.env", "https://example.com/.env");

        assert!(vuln.is_some());
        let v = vuln.unwrap();
        assert_eq!(v.severity, Severity::Critical);
        assert!(v.vuln_type.contains("Environment File"));
    }

    #[test]
    fn test_analyze_git_config() {
        let scanner = create_test_scanner();

        let body = "[core]\n\trepositoryformatversion = 0\n\tfilemode = true";
        let vuln = scanner.analyze_sensitive_file(
            body,
            200,
            "/.git/config",
            "https://example.com/.git/config",
        );

        assert!(vuln.is_some());
        let v = vuln.unwrap();
        assert!(v.vuln_type.contains("Git Repository"));
    }

    #[test]
    fn test_analyze_sql_dump() {
        let scanner = create_test_scanner();

        let body = "CREATE TABLE users (id INT, name VARCHAR(255));\nINSERT INTO users VALUES (1, 'admin');";
        let vuln = scanner.analyze_sensitive_file(
            body,
            200,
            "/backup.sql",
            "https://example.com/backup.sql",
        );

        assert!(vuln.is_some());
        let v = vuln.unwrap();
        assert_eq!(v.severity, Severity::Critical);
        assert!(v.vuln_type.contains("Database Dump"));
    }

    #[test]
    fn test_analyze_phpinfo() {
        let scanner = create_test_scanner();

        let body = "PHP Version 7.4.3\nSystem => Linux\nphp.ini => /etc/php/7.4/php.ini";
        let vuln = scanner.analyze_sensitive_file(
            body,
            200,
            "/phpinfo.php",
            "https://example.com/phpinfo.php",
        );

        assert!(vuln.is_some());
        let v = vuln.unwrap();
        assert!(v.vuln_type.contains("PHPInfo"));
    }

    #[test]
    fn test_regex_scan_aws_key() {
        let scanner = create_test_scanner();

        let body = r#"{"aws_key": "AKIAIOSFODNN7EXAMPLE"}"#;
        let matches = scanner.regex_scan(body, r"AKIA[0-9A-Z]{16}");

        assert!(matches.is_some());
        let m = matches.unwrap();
        assert_eq!(m.len(), 1);
        assert!(m[0].contains("AKIAIOSFODNN7EXAMPLE"));
    }

    #[test]
    fn test_scan_for_credentials() {
        let scanner = create_test_scanner();

        let body = r#"{"stripe_key": "sk_test_FAKE_KEY_FOR_TESTING_ONLY"}"#;
        let vulns = scanner.scan_for_credentials(body, "https://example.com");

        assert!(!vulns.is_empty());
        assert!(vulns.iter().any(|v| v.vuln_type.contains("Stripe")));
    }

    #[test]
    fn test_get_sensitive_paths() {
        let scanner = create_test_scanner();
        let paths = scanner.get_sensitive_paths();

        assert!(paths.len() > 70);
        assert!(paths.contains(&"/.env"));
        assert!(paths.contains(&"/.git/config"));
        assert!(paths.contains(&"/phpinfo.php"));
        assert!(paths.contains(&"/backup.sql"));
    }
}