gossan-hidden 0.3.3

Hidden endpoint and misconfiguration scanner for gossan (CORS, SSRF, JWT, Swagger, cache deception), part of the security research ecosystem
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
//! Dependency confusion probe.
//!
//! Detects exposed package manifest files that reveal internal package names,
//! scopes, and registries, the raw material for dependency confusion /
//! typosquatting attacks.

use gossan_core::Target;
use reqwest::Client;
use secfinding::{Evidence, Finding, Severity};

/// Manifest files that disclose dependency information.
const MANIFESTS: &[(&str, &str, &[&str])] = &[
    (
        "/package.json",
        "npm package.json exposed",
        &["dependencies", "devDependencies", "name", "version"],
    ),
    (
        "/composer.json",
        "PHP composer.json exposed",
        &["require", "require-dev", "name"],
    ),
    ("/requirements.txt", "Python requirements.txt exposed", &[]),
    ("/Gemfile", "Ruby Gemfile exposed", &["gem", "source"]),
    ("/go.mod", "Go go.mod exposed", &["module", "require"]),
    (
        "/pom.xml",
        "Maven pom.xml exposed",
        &["<project", "<dependency>"],
    ),
    (
        "/build.gradle",
        "Gradle build.gradle exposed",
        &["dependencies", "repositories"],
    ),
    (
        "/Cargo.toml",
        "Rust Cargo.toml exposed",
        &["[package]", "[dependencies]"],
    ),
];

pub async fn probe(
    client: &Client,
    target: &Target,
    baseline: Option<&crate::soft404::BaselineFingerprint>,
) -> anyhow::Result<Vec<Finding>> {
    let Target::Web(asset) = target else {
        return Ok(vec![]);
    };
    let base = asset.url.as_str().trim_end_matches('/');
    let mut findings = Vec::new();

    for (path, title, confirms) in MANIFESTS {
        let url = format!("{}{}", base, path);
        let Ok(resp) = client.get(&url).send().await else {
            continue;
        };
        if resp.status().as_u16() != 200 {
            continue;
        }
        let body = gossan_core::net::bounded_text(resp, crate::MAX_BODY_BYTES)
            .await?;

        if crate::soft404::is_likely_404(200, body.as_bytes(), baseline, false) {
            continue;
        }

        // Confirm it's a real manifest, not a generic 200 page
        let confirmed = if confirms.is_empty() {
            body.len() > 10 && !body.trim_start().starts_with('<')
        } else {
            confirms.iter().any(|c| body.contains(c))
        };

        if !confirmed {
            continue;
        }

        let scopes = extract_scopes(path, &body);
        let detail = if scopes.is_empty() {
            format!(
                "{} is publicly accessible. Dependency names and versions are disclosed, \
                 enabling dependency confusion or typosquatting attacks.",
                url
            )
        } else {
            format!(
                "{} is publicly accessible. Detected scope(s): {}. \
                 An attacker can register these names on public registries \
                 to inject malicious code into the build pipeline.",
                url,
                scopes.join(", ")
            )
        };

        gossan_core::try_push_finding(
            crate::supply_chain_finding(target, Severity::Medium, *title, detail)
                .evidence(Evidence::HttpResponse {
                    status: 200,
                    headers: vec![],
                    body_excerpt: Some(body.chars().take(crate::MAX_BODY_EXCERPT_CHARS).collect::<String>().into()),
                })
                .tag("supply-chain")
                .tag("dependency-confusion")
                .tag("exposure"),
            &mut findings,
        );
    }

    Ok(findings)
}

fn extract_scopes(path: &str, body: &str) -> Vec<String> {
    let mut scopes = Vec::new();

    if path == "/package.json" {
        // Look for scoped npm packages: "@scope/name". Real package.json
        // files often serialise as one line; iterating `find('@')` would
        // only catch the first scope. Use `match_indices` so every `@`
        // in every line is considered.
        for line in body.lines() {
            for (start, _) in line.match_indices('@') {
                let rest = &line[start + 1..];
                if let Some(slash) = rest.find('/') {
                    let scope = &rest[..slash];
                    if !scope.is_empty()
                        && !scope.contains(' ')
                        && !scope.contains('"')
                        && !scopes.contains(&scope.to_string())
                    {
                        scopes.push(scope.to_string());
                    }
                }
            }
        }
    } else if path == "/composer.json" {
        // Composer require map is also commonly one-line. Walk every
        // double-quoted token and keep the ones that look like
        // `vendor/package` (forward-slash, no whitespace).
        for line in body.lines() {
            let mut cursor = 0;
            while let Some(open_rel) = line[cursor..].find('"') {
                let open = cursor + open_rel;
                let after = &line[open + 1..];
                let Some(close_rel) = after.find('"') else {
                    break;
                };
                let close = open + 1 + close_rel;
                let token = &line[open + 1..close];
                if token.contains('/')
                    && !token.contains(' ')
                    && !scopes.contains(&token.to_string())
                {
                    scopes.push(token.to_string());
                }
                cursor = close + 1;
            }
        }
    }

    scopes.into_iter().take(5).collect()
}

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

    #[test]
    fn extract_npm_scopes() {
        let body = r#"{ "dependencies": { "@internal/auth": "1.0.0", "@tools/build": "2.0.0" } }"#;
        let scopes = extract_scopes("/package.json", body);
        assert!(scopes.contains(&"internal".to_string()));
        assert!(scopes.contains(&"tools".to_string()));
    }

    #[test]
    fn extract_composer_packages() {
        let body = r#"{ "require": { "vendor/package": "^1.0" } }"#;
        let scopes = extract_scopes("/composer.json", body);
        assert!(scopes.contains(&"vendor/package".to_string()));
    }

    #[test]
    fn manifests_include_package_json() {
        assert!(MANIFESTS.iter().any(|(p, _, _)| *p == "/package.json"));
    }

    #[test]
    fn manifests_include_cargo_toml() {
        assert!(MANIFESTS.iter().any(|(p, _, _)| *p == "/Cargo.toml"));
    }

    #[test]
    fn extract_scopes_empty_for_unknown_path() {
        let scopes = extract_scopes("/unknown.txt", "anything");
        assert!(scopes.is_empty());
    }

    #[test]
    fn extract_scopes_limits_to_five() {
        let body = (0..10)
            .map(|i| format!("\"@scope{}/pkg\": \"1.0.0\"", i))
            .collect::<Vec<_>>()
            .join(", ");
        let scopes = extract_scopes("/package.json", &body);
        assert_eq!(scopes.len(), 5);
    }

    #[test]
    fn manifests_all_have_non_empty_title() {
        for (_, title, _) in MANIFESTS {
            assert!(!title.is_empty());
        }
    }

    #[test]
    fn extract_npm_scopes_ignores_invalid() {
        let body = r#"{ "dependencies": { "@ bad scope/pkg": "1.0.0" } }"#;
        let scopes = extract_scopes("/package.json", body);
        assert!(scopes.is_empty());
    }

    #[test]
    fn extract_composer_scopes_ignores_whitespace() {
        let body = r#"{ "require": { "bad vendor / bad package": "^1.0" } }"#;
        let scopes = extract_scopes("/composer.json", body);
        assert!(!scopes.iter().any(|s| s.contains(' ')));
    }

    #[test]
    fn manifests_include_go_mod() {
        assert!(MANIFESTS.iter().any(|(p, _, _)| *p == "/go.mod"));
    }

    #[test]
    fn manifests_all_have_confirmation_strings_or_empty() {
        for (_, _, confirms) in MANIFESTS {
            // Every manifest either has confirm strings or explicitly empty list
            assert!(confirms.is_empty() || !confirms.is_empty());
        }
    }

    #[test]
    fn extract_scopes_dedupes_duplicates() {
        let body = r#"{ "dependencies": { "@internal/a": "1.0.0", "@internal/b": "2.0.0" } }"#;
        let scopes = extract_scopes("/package.json", body);
        assert_eq!(scopes.len(), 1);
        assert_eq!(scopes[0], "internal");
    }

    #[test]
    fn extract_scopes_empty_body() {
        let scopes = extract_scopes("/package.json", "");
        assert!(scopes.is_empty());
    }

    #[test]
    fn extract_scopes_single_param() {
        let body = r#"{"dependencies":{"@scope/pkg":"1.0.0"}}"#;
        let scopes = extract_scopes("/package.json", body);
        assert_eq!(scopes.len(), 1);
        assert_eq!(scopes[0], "scope");
    }

    #[test]
    fn extract_scopes_100_params() {
        let deps: Vec<String> = (0..100)
            .map(|i| format!("\"@scope{}/pkg\": \"1.0.0\"", i))
            .collect();
        let body = format!("{{\"dependencies\":{{{}}}}}", deps.join(", "));
        let scopes = extract_scopes("/package.json", &body);
        assert_eq!(scopes.len(), 5); // capped at 5
    }

    #[test]
    fn extract_scopes_special_chars_ignored() {
        let body = r#"{"dependencies":{"@bad scope/pkg":"1.0.0"}}"#;
        let scopes = extract_scopes("/package.json", body);
        assert!(scopes.is_empty());
    }

    #[test]
    fn extract_scopes_unicode_in_package_name() {
        let body = r#"{"dependencies":{"@日本語/pkg":"1.0.0"}}"#;
        let scopes = extract_scopes("/package.json", body);
        assert_eq!(scopes.len(), 1);
        assert_eq!(scopes[0], "日本語");
    }

    #[test]
    fn extract_scopes_path_traversal_extracts_first_segment() {
        let body = r#"{"dependencies":{"@../etc/passwd/pkg":"1.0.0"}}"#;
        let scopes = extract_scopes("/package.json", body);
        assert_eq!(scopes.len(), 1);
        // extract_scopes splits on first '/', so ".." is the scope segment
        assert_eq!(scopes[0], "..");
    }

    #[test]
    fn extract_scopes_url_encoding_no_literal_slash() {
        let body = r#"{"dependencies":{"@scope%2Fpkg":"1.0.0"}}"#;
        let scopes = extract_scopes("/package.json", body);
        // %2F is not a literal '/', so no scope is extracted
        assert!(scopes.is_empty());
    }

    #[test]
    fn extract_scopes_null_bytes_preserved_in_segment() {
        let body = "{\"dependencies\":{\"@scope\0/pkg\":\"1.0.0\"}}";
        let scopes = extract_scopes("/package.json", body);
        assert_eq!(scopes.len(), 1);
        assert_eq!(scopes[0], "scope\0");
    }

    #[test]
    fn extract_scopes_composer_empty() {
        let scopes = extract_scopes("/composer.json", "");
        assert!(scopes.is_empty());
    }

    #[test]
    fn extract_scopes_composer_single_package() {
        let body = r#"{"require":{"vendor/package":"^1.0"}}"#;
        let scopes = extract_scopes("/composer.json", body);
        assert_eq!(scopes.len(), 1);
        assert_eq!(scopes[0], "vendor/package");
    }

    #[test]
    fn extract_scopes_composer_100_packages() {
        let pkgs: Vec<String> = (0..100)
            .map(|i| format!("\"vendor{}/package\": \"^1.0\"", i))
            .collect();
        let body = format!("{{\"require\":{{{}}}}}", pkgs.join(", "));
        let scopes = extract_scopes("/composer.json", &body);
        assert_eq!(scopes.len(), 5); // capped at 5
    }

    #[test]
    fn extract_scopes_unknown_path_returns_empty() {
        let scopes = extract_scopes("/unknown.txt", "anything");
        assert!(scopes.is_empty());
    }

    #[tokio::test]
    async fn catch_all_html_manifest_suppressed_by_soft404_baseline() {
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let server = MockServer::start().await;
        let shell = "<html><body> name version dependencies </body></html>";
        Mock::given(method("GET"))
            .and(path("/package.json"))
            .respond_with(ResponseTemplate::new(200).set_body_string(shell))
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .respond_with(ResponseTemplate::new(200).set_body_string(shell))
            .mount(&server)
            .await;

        let client = reqwest::Client::new();
        let target = gossan_core::testkit::web_target(&server.uri());
        let baseline = crate::soft404::establish(&client, &server.uri()).await;
        let findings = probe(&client, &target, baseline.as_ref()).await.unwrap();
        assert!(
            findings.is_empty(),
            "expected package.json finding suppressed on catch-all HTML, got {:?}",
            findings
        );
    }

    #[tokio::test]
    async fn real_manifest_fires_when_body_differs_from_baseline() {
        use wiremock::matchers::{method, path};
        use wiremock::{Mock, MockServer, ResponseTemplate};

        let server = MockServer::start().await;
        let shell = "<html><body>SPA shell</body></html>";
        // Make the real manifest body much larger than the baseline shell so the
        // length check does not classify it as a soft-404 in non-strict mode.
        let manifest = format!(
            r#"{{"name":"x","dependencies":{{}},"description":"{}"}}"#,
            "x".repeat(500)
        );
        Mock::given(method("GET"))
            .and(path("/package.json"))
            .respond_with(ResponseTemplate::new(200).set_body_string(manifest))
            .mount(&server)
            .await;
        Mock::given(method("GET"))
            .respond_with(ResponseTemplate::new(200).set_body_string(shell))
            .mount(&server)
            .await;

        let client = reqwest::Client::new();
        let target = gossan_core::testkit::web_target(&server.uri());
        let baseline = crate::soft404::establish(&client, &server.uri()).await;
        let findings = probe(&client, &target, baseline.as_ref()).await.unwrap();
        assert!(
            findings.iter().any(|f| f.title().contains("package.json")),
            "expected package.json finding when body differs from baseline, got {:?}",
            findings
        );
    }
}