website-vulnerability-scanner 0.2.1

Cross-platform defensive website security & configuration scanner with GUI and CLI reports.
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
use std::collections::HashSet;

use reqwest::header::HeaderMap;
use url::Url;

use crate::models::{Category, Confidence, Finding, Severity};

fn mask_secret(raw: &str) -> String {
    let trimmed = raw.trim();
    let chars: Vec<char> = trimmed.chars().collect();
    if chars.len() <= 8 {
        return "[REDACTED_SECRET]".to_string();
    }
    let head: String = chars.iter().take(4).collect();
    let tail: String = chars[chars.len() - 2..].iter().collect();
    format!("{head}****{tail} (len={})", chars.len())
}

fn decode_base64url(input: &str) -> Option<Vec<u8>> {
    let mut buf = Vec::with_capacity((input.len() * 3) / 4 + 3);
    let mut acc: u32 = 0;
    let mut bits: u8 = 0;

    for b in input.bytes() {
        let val = match b {
            b'A'..=b'Z' => b - b'A',
            b'a'..=b'z' => b - b'a' + 26,
            b'0'..=b'9' => b - b'0' + 52,
            b'-' | b'+' => 62,
            b'_' | b'/' => 63,
            b'=' => break,
            _ => return None,
        };
        acc = (acc << 6) | u32::from(val);
        bits += 6;
        if bits >= 8 {
            bits -= 8;
            buf.push(((acc >> bits) & 0xff) as u8);
        }
    }
    Some(buf)
}

fn find_prefixed_token<'a>(
    text: &'a str,
    prefix: &str,
    min_tail_len: usize,
    is_valid_char: fn(char) -> bool,
) -> Option<&'a str> {
    let mut start = 0;
    while let Some(rel) = text[start..].find(prefix) {
        let idx = start + rel;
        let tail = &text[idx + prefix.len()..];
        let tail_len = tail
            .char_indices()
            .take_while(|(_, c)| is_valid_char(*c))
            .last()
            .map(|(i, c)| i + c.len_utf8())
            .unwrap_or(0);
        if tail_len >= min_tail_len {
            // Avoid matching parts of longer placeholder words like "AKIA_EXAMPLE_DOC"
            let candidate = &text[idx..idx + prefix.len() + tail_len];
            if !candidate.to_ascii_uppercase().contains("EXAMPLE")
                && !candidate.to_ascii_uppercase().contains("DUMMY")
                && !candidate.to_ascii_uppercase().contains("PLACEHOLDER")
            {
                return Some(candidate);
            }
        }
        start = idx + prefix.len();
    }
    None
}

fn audit_secrets(body: &str, url: &Url) -> Vec<Finding> {
    let mut findings = Vec::new();
    let is_alnum = |c: char| c.is_ascii_alphanumeric();
    let is_upper_alnum = |c: char| c.is_ascii_uppercase() || c.is_ascii_digit();
    let is_token_char = |c: char| c.is_ascii_alphanumeric() || c == '_' || c == '-';

    if let Some(tok) = find_prefixed_token(body, "AKIA", 16, is_upper_alnum) {
        if tok.len() == 20 {
            findings.push(Finding {
                id: "LEAK-SECRET-AWS".into(),
                category: Category::SecretsAndLeaks,
                severity: Severity::Critical,
                title: "Potential AWS Access Key ID exposed in response".into(),
                summary: "An AWS Access Key ID pattern (`AKIA...`) was detected in HTTP response content.".into(),
                evidence: Some(format!("{} at {}", mask_secret(tok), url)),
                remediation: "Revoke the exposed IAM key immediately and remove secrets from responses/client bundles.".into(),
                standard_ref: Some("OWASP ASVS V14.3 / WSTG-INFO".into()),
                confidence: Confidence::High,
            });
        }
    }

    for gh_prefix in ["ghp_", "gho_", "ghu_", "ghs_", "github_pat_"] {
        if let Some(tok) = find_prefixed_token(body, gh_prefix, 20, is_token_char) {
            findings.push(Finding {
                id: "LEAK-SECRET-GITHUB".into(),
                category: Category::SecretsAndLeaks,
                severity: Severity::Critical,
                title: "Potential GitHub access token exposed in response".into(),
                summary: format!("A GitHub token (`{gh_prefix}...`) was found in response content."),
                evidence: Some(format!("{} at {}", mask_secret(tok), url)),
                remediation: "Revoke the token in GitHub settings and inject credentials strictly on the server side.".into(),
                standard_ref: Some("OWASP ASVS V2.10 / V14.3".into()),
                confidence: Confidence::High,
            });
            break;
        }
    }

    for stripe_prefix in ["sk_live_", "rk_live_"] {
        if let Some(tok) = find_prefixed_token(body, stripe_prefix, 16, is_alnum) {
            findings.push(Finding {
                id: "LEAK-SECRET-STRIPE".into(),
                category: Category::SecretsAndLeaks,
                severity: Severity::Critical,
                title: "Stripe live secret key exposed in response".into(),
                summary: "A live Stripe secret/restricted key was detected in HTTP response content.".into(),
                evidence: Some(format!("{} at {}", mask_secret(tok), url)),
                remediation: "Roll the Stripe API key immediately and keep secret keys strictly on backend servers.".into(),
                standard_ref: Some("OWASP ASVS V14.3".into()),
                confidence: Confidence::High,
            });
            break;
        }
    }

    for slack_prefix in ["xoxb-", "xoxp-", "xoxa-", "xoxr-"] {
        if let Some(tok) = find_prefixed_token(body, slack_prefix, 16, is_token_char) {
            findings.push(Finding {
                id: "LEAK-SECRET-SLACK".into(),
                category: Category::SecretsAndLeaks,
                severity: Severity::Critical,
                title: "Slack API token exposed in response".into(),
                summary: "A Slack token pattern was found in HTTP response content.".into(),
                evidence: Some(format!("{} at {}", mask_secret(tok), url)),
                remediation: "Revoke the Slack app token and rotate workspace credentials.".into(),
                standard_ref: Some("OWASP ASVS V14.3".into()),
                confidence: Confidence::High,
            });
            break;
        }
    }

    if let Some(tok) = find_prefixed_token(body, "AIza", 32, is_token_char) {
        findings.push(Finding {
            id: "LEAK-SECRET-GOOGLE-API".into(),
            category: Category::SecretsAndLeaks,
            severity: Severity::Medium,
            title: "Google API key detected in response".into(),
            summary: "A Google API key (`AIza...`) is embedded in response output. Verify referrer/API restrictions if intended to be public.".into(),
            evidence: Some(format!("{} at {}", mask_secret(tok), url)),
            remediation: "Restrict the key by HTTP referrer/IP and enabled APIs in Google Cloud Console, or move calls server-side.".into(),
            standard_ref: Some("OWASP ASVS V14.3".into()),
            confidence: Confidence::Medium,
        });
    }

    for pem in [
        "-----BEGIN RSA PRIVATE KEY-----",
        "-----BEGIN EC PRIVATE KEY-----",
        "-----BEGIN PRIVATE KEY-----",
        "-----BEGIN OPENSSH PRIVATE KEY-----",
    ] {
        if body.contains(pem) {
            findings.push(Finding {
                id: "LEAK-PRIVATE-KEY".into(),
                category: Category::SecretsAndLeaks,
                severity: Severity::Critical,
                title: "Cryptographic private key material exposed in response".into(),
                summary: format!("Detected PEM private key header `{pem}` in HTTP response."),
                evidence: Some(format!("{pem} at {url}")),
                remediation: "Revoke and replace the compromised key pair immediately and block access to key files.".into(),
                standard_ref: Some("OWASP ASVS V6.4 / V14.3".into()),
                confidence: Confidence::High,
            });
            break;
        }
    }

    for scheme in [
        "postgres://",
        "postgresql://",
        "mysql://",
        "mongodb://",
        "mongodb+srv://",
        "redis://",
    ] {
        if let Some(pos) = body.find(scheme) {
            let tail = &body[pos..body.len().min(pos + 120)];
            if let Some(at_pos) = tail.find('@') {
                let auth_part = &tail[scheme.len()..at_pos];
                if auth_part.contains(':') && !auth_part.contains(' ') {
                    findings.push(Finding {
                        id: "LEAK-DB-CONNECTION".into(),
                        category: Category::SecretsAndLeaks,
                        severity: Severity::Critical,
                        title: "Database connection string with credentials exposed".into(),
                        summary: format!("Detected a `{scheme}user:***@...` connection URI in response content."),
                        evidence: Some(format!("{scheme}[CREDENTIALS_REDACTED]@... at {url}")),
                        remediation: "Remove database credentials from HTTP responses/configs and rotate the database password.".into(),
                        standard_ref: Some("OWASP ASVS V2.10 / V14.3".into()),
                        confidence: Confidence::High,
                    });
                    break;
                }
            }
        }
    }

    findings
}

fn audit_jwts(text: &str, url: &Url) -> Vec<Finding> {
    let mut findings = Vec::new();
    let mut search_from = 0usize;
    let mut checked = 0usize;

    while let Some(rel) = text[search_from..].find("eyJ") {
        if checked >= 8 {
            break;
        }
        let idx = search_from + rel;
        search_from = idx + 3;

        let token: String = text[idx..]
            .chars()
            .take_while(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '-' || *c == '.')
            .collect();
        let parts: Vec<&str> = token.split('.').collect();
        if parts.len() != 3 || parts[0].len() < 8 || parts[1].len() < 8 {
            continue;
        }

        let Some(hdr_bytes) = decode_base64url(parts[0]) else {
            continue;
        };
        let Ok(hdr_json) = serde_json::from_slice::<serde_json::Value>(&hdr_bytes) else {
            continue;
        };
        let Some(pay_bytes) = decode_base64url(parts[1]) else {
            continue;
        };
        let Ok(pay_json) = serde_json::from_slice::<serde_json::Value>(&pay_bytes) else {
            continue;
        };

        checked += 1;
        if hdr_json
            .get("alg")
            .and_then(|v| v.as_str())
            .map(|a| a.eq_ignore_ascii_case("none"))
            .unwrap_or(false)
        {
            findings.push(Finding {
                id: "AUTH-JWT-ALG-NONE".into(),
                category: Category::ApiSecurity,
                severity: Severity::Critical,
                title: "JWT using insecure `alg: none` observed in response".into(),
                summary: "A JSON Web Token with signature algorithm `none` was issued or returned.".into(),
                evidence: Some(format!("alg=none in token at {url}")),
                remediation: "Enforce strong asymmetric (RS256/EdDSA) or HMAC (HS256) JWT verification and explicitly reject `alg=none`.".into(),
                standard_ref: Some("OWASP ASVS V3.5.3 / WSTG-SESS".into()),
                confidence: Confidence::High,
            });
        }

        if pay_json.get("exp").is_none() {
            findings.push(Finding {
                id: "AUTH-JWT-NO-EXP".into(),
                category: Category::ApiSecurity,
                severity: Severity::Medium,
                title: "JWT missing expiration (`exp`) claim".into(),
                summary: "A JSON Web Token returned by the application has no `exp` claim, leaving leaked tokens valid indefinitely.".into(),
                evidence: Some(format!("JWT without `exp` at {url}")),
                remediation: "Set a short `exp` lifetime on all issued JWTs and rotate refresh tokens properly.".into(),
                standard_ref: Some("OWASP ASVS V3.5.1".into()),
                confidence: Confidence::High,
            });
        }
    }

    findings
}

fn audit_stacktraces_and_internal_ips(headers: &HeaderMap, body: &str, url: &Url) -> Vec<Finding> {
    let mut findings = Vec::new();

    let markers = [
        "NullPointerException",
        "System.NullReferenceException",
        "You have an error in your SQL syntax",
        "PG::SyntaxError",
        "SQLite3::SQLException",
        "Traceback (most recent call last):",
        "panicked at '",
        "at Object.<anonymous>",
    ];
    for m in markers {
        if body.contains(m) {
            findings.push(Finding {
                id: "INFO-API-STACKTRACE".into(),
                category: Category::SecretsAndLeaks,
                severity: Severity::High,
                title: "Application stack trace or SQL error exposed in response".into(),
                summary: "Detailed runtime stack traces expose file paths, dependencies, and query structure.".into(),
                evidence: Some(format!("Marker `{m}` at {url}")),
                remediation: "Disable verbose error responses in production and log stack traces server-side only.".into(),
                standard_ref: Some("OWASP ASVS V7.4.1 / WSTG-ERRH-01".into()),
                confidence: Confidence::High,
            });
            break;
        }
    }

    for (name, val) in headers {
        let lower_name = name.as_str().to_ascii_lowercase();
        if matches!(
            lower_name.as_str(),
            "x-backend-server" | "x-upstream" | "x-internal-ip" | "x-server-ip" | "x-host"
        ) {
            if let Ok(v) = val.to_str() {
                findings.push(Finding {
                    id: "INFO-INTERNAL-HEADER".into(),
                    category: Category::InformationDisclosure,
                    severity: Severity::Low,
                    title: format!("Internal routing header exposed: {name}"),
                    summary: "Server exposes internal infrastructure hostnames or backend node identifiers.".into(),
                    evidence: Some(format!("{name}: {v}")),
                    remediation: "Strip internal proxy/upstream headers before returning responses to clients.".into(),
                    standard_ref: Some("OWASP WSTG-INFO-02".into()),
                    confidence: Confidence::High,
                });
            }
        }
    }

    findings
}

pub fn analyze_response_leaks(headers: &HeaderMap, body: &str, url: &Url) -> Vec<Finding> {
    let mut findings = Vec::new();
    findings.extend(audit_secrets(body, url));
    findings.extend(audit_jwts(body, url));
    for hv in headers.get_all(reqwest::header::SET_COOKIE) {
        if let Ok(s) = hv.to_str() {
            findings.extend(audit_jwts(s, url));
        }
    }
    findings.extend(audit_stacktraces_and_internal_ips(headers, body, url));
    findings
}

pub fn extract_js_routes_and_sourcemap(js_body: &str, js_url: &Url) -> (Option<Url>, Vec<Url>) {
    let mut sourcemap = None;
    for line in js_body.lines().rev().take(15) {
        let trimmed = line.trim();
        for prefix in ["//# sourceMappingURL=", "//@ sourceMappingURL="] {
            if let Some(raw_map) = trimmed.strip_prefix(prefix) {
                let candidate = raw_map.trim();
                if !candidate.starts_with("data:") {
                    if let Ok(resolved) = js_url.join(candidate) {
                        if resolved.host_str() == js_url.host_str() {
                            sourcemap = Some(resolved);
                        }
                    }
                }
                break;
            }
        }
        if sourcemap.is_some() {
            break;
        }
    }

    let mut discovered = Vec::new();
    let mut seen = HashSet::new();
    let api_prefixes = [
        "/api/", "/v1/", "/v2/", "/graphql", "/admin", "/account", "/profile",
    ];

    for quote in ['"', '\'', '`'] {
        let mut rest = js_body;
        while let Some(pos) = rest.find(quote) {
            let after = &rest[pos + 1..];
            let Some(end) = after.find(quote) else {
                break;
            };
            let literal = &after[..end];
            rest = &after[end + 1..];

            if literal.len() < 3
                || literal.len() > 80
                || literal.contains("${")
                || literal.contains(' ')
                || literal.contains('*')
            {
                continue;
            }

            if api_prefixes.iter().any(|p| literal.starts_with(p)) {
                if let Ok(resolved) = js_url.join(literal) {
                    if resolved.host_str() == js_url.host_str()
                        && seen.insert(resolved.as_str().to_string())
                    {
                        discovered.push(resolved);
                        if discovered.len() >= 15 {
                            return (sourcemap, discovered);
                        }
                    }
                }
            }
        }
    }

    (sourcemap, discovered)
}

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

    #[test]
    fn detects_and_masks_leaked_secrets_and_db_uri() {
        let url = Url::parse("https://app.example.test/config.js").unwrap();
        let body = r#"
            const aws = "AKIA1234567890ABCDEF";
            const db = "postgres://admin:SuperSecretPass99@db.internal:5432/prod";
            const key = "-----BEGIN PRIVATE KEY-----\nABC";
        "#;
        let findings = analyze_response_leaks(&HeaderMap::new(), body, &url);
        let ids: Vec<&str> = findings.iter().map(|f| f.id.as_str()).collect();
        assert!(ids.contains(&"LEAK-SECRET-AWS"));
        assert!(ids.contains(&"LEAK-DB-CONNECTION"));
        assert!(ids.contains(&"LEAK-PRIVATE-KEY"));

        let joined: String = findings
            .iter()
            .filter_map(|f| f.evidence.clone())
            .collect::<Vec<_>>()
            .join(" ");
        assert!(!joined.contains("AKIA1234567890ABCDEF"));
        assert!(!joined.contains("SuperSecretPass99"));
    }

    #[test]
    fn detects_jwt_issues_and_js_sourcemap_and_routes() {
        let url = Url::parse("https://app.example.test/static/main.js").unwrap();
        // Header {"alg":"none","typ":"JWT"}, Payload {"sub":"123"} (no exp)
        let jwt = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiIxMjMifQ.sig";
        let js = format!(
            "const ep = \"/api/v1/users\"; const t = \"{jwt}\";\n//# sourceMappingURL=main.js.map\n"
        );
        let findings = analyze_response_leaks(&HeaderMap::new(), &js, &url);
        assert!(findings.iter().any(|f| f.id == "AUTH-JWT-ALG-NONE"));
        assert!(findings.iter().any(|f| f.id == "AUTH-JWT-NO-EXP"));

        let (map, routes) = extract_js_routes_and_sourcemap(&js, &url);
        assert_eq!(
            map.unwrap().as_str(),
            "https://app.example.test/static/main.js.map"
        );
        assert_eq!(routes[0].as_str(), "https://app.example.test/api/v1/users");
    }
}