gossan-subdomain 0.3.3

Subdomain discovery scanner for gossan (CT logs, Wayback, permutations, DNS bruteforce), 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
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
//! Hermetic DNS discovery tests  -  exact name assertions against loopback zones.

use std::collections::{HashMap, HashSet};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::sync::Arc;
use std::time::Duration;

use gossan_core::Target;

fn resolver_port() -> u16 {
    std::env::var("GOSSAN_RESOLVER_PORT")
        .expect("GOSSAN_RESOLVER_PORT not set")
        .parse()
        .expect("GOSSAN_RESOLVER_PORT must be a u16")
}

use crate::bruteforce::run_bruteforce_with_words;
use crate::hermetic_dns::{
    gossan_resolver_for, resolver_for, test_env_lock, AdversarialMode, HermeticZone, HostRecords,
    WildcardMode,
};
use crate::wildcard::detect_wildcards;

fn host(
    a: Option<Ipv4Addr>,
    aaaa: Option<Ipv6Addr>,
    cname: Option<&str>,
) -> HostRecords {
    HostRecords {
        a,
        aaaa,
        cname: cname.map(str::to_string),
    }
}

async fn sleep_server() {
    tokio::time::sleep(Duration::from_millis(50)).await;
}

fn exact_set(found: &[String]) -> HashSet<&str> {
    found.iter().map(String::as_str).collect()
}

fn assert_exact(found: &[String], expected: &[&str]) {
    let got = exact_set(found);
    let want: HashSet<&str> = expected.iter().copied().collect();
    assert_eq!(
        got, want,
        "exact discovery set mismatch: got {found:?}, expected {expected:?}"
    );
}

/// PROVING: multi-hop CNAME chain (CNAME → CNAME → A) is still discovered.
#[tokio::test]
async fn multi_hop_cname_chain_is_discovered() {
    let mut hosts = HashMap::new();
    hosts.insert(
        "chain.example.com".to_string(),
        host(None, None, Some("hop.example.com")),
    );
    hosts.insert(
        "hop.example.com".to_string(),
        host(None, None, Some("leaf.example.com")),
    );
    hosts.insert(
        "leaf.example.com".to_string(),
        host(Some(Ipv4Addr::new(10, 0, 0, 1)), None, None),
    );
    let addr = HermeticZone {
        hosts,
        wildcard: WildcardMode::NxDomain,
        adversarial: AdversarialMode::Normal,
    }
    .serve()
    .await;
    sleep_server().await;

    let found = run_bruteforce_with_words(
        "example.com",
        &["chain"],
        resolver_for(addr),
        None,
        1,
    )
    .await
    .unwrap();
    assert_exact(&found, &["chain.example.com"]);
}

/// PROVING: explicit CNAME to a wildcard A target is a true positive (not filtered).
#[tokio::test]
async fn cname_to_wildcard_a_is_still_discovered() {
    let wild_ip = Ipv4Addr::new(1, 2, 3, 4);
    let mut hosts = HashMap::new();
    hosts.insert(
        "alias.example.com".to_string(),
        host(None, None, Some("sink.example.com")),
    );
    hosts.insert("sink.example.com".to_string(), host(Some(wild_ip), None, None));
    let addr = HermeticZone {
        hosts,
        wildcard: WildcardMode::NxDomain,
        adversarial: AdversarialMode::Normal,
    }
    .serve()
    .await;
    sleep_server().await;

    let wildcards = HashSet::from([IpAddr::V4(wild_ip)]);
    let found = run_bruteforce_with_words(
        "example.com",
        &["alias", "noise"],
        resolver_for(addr),
        Some(wildcards),
        1,
    )
    .await
    .unwrap();
    assert_exact(&found, &["alias.example.com"]);
}

/// PROVING: AAAA-only host is discovered (no A record).
#[tokio::test]
async fn aaaa_only_host_is_discovered() {
    let v6 = Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1);
    let mut hosts = HashMap::new();
    hosts.insert(
        "v6only.example.com".to_string(),
        host(None, Some(v6), None),
    );
    let addr = HermeticZone {
        hosts,
        wildcard: WildcardMode::NxDomain,
        adversarial: AdversarialMode::Normal,
    }
    .serve()
    .await;
    sleep_server().await;

    let found = run_bruteforce_with_words(
        "example.com",
        &["v6only"],
        resolver_for(addr),
        None,
        1,
    )
    .await
    .unwrap();
    assert_exact(&found, &["v6only.example.com"]);
}

/// PROVING + ADVERSARIAL: wildcard labels are suppressed; explicit records survive.
#[tokio::test]
async fn wildcard_filter_keeps_real_and_drops_garbage() {
    let wild_ip = Ipv4Addr::new(1, 2, 3, 4);
    let real_ip = Ipv4Addr::new(9, 9, 9, 9);
    let mut hosts = HashMap::new();
    hosts.insert("api.example.com".to_string(), host(Some(real_ip), None, None));
    hosts.insert(
        "real.example.com".to_string(),
        host(Some(real_ip), None, None),
    );
    let addr = HermeticZone {
        hosts,
        wildcard: WildcardMode::A(wild_ip),
        adversarial: AdversarialMode::Normal,
    }
    .serve()
    .await;
    sleep_server().await;

    let resolver = resolver_for(addr);
    let wildcards = detect_wildcards("example.com", &resolver, 3).await;
    assert!(
        wildcards.contains(&IpAddr::V4(wild_ip)),
        "wildcard probe must learn wildcard IP"
    );

    let found = run_bruteforce_with_words(
        "example.com",
        &["api", "real", "zzzgossan-garbage-label"],
        resolver,
        Some(wildcards),
        1,
    )
    .await
    .unwrap();
    assert_exact(&found, &["api.example.com", "real.example.com"]);
}

/// PRECISION LINCHPIN: on a NON-wildcard zone `detect_wildcards` MUST
/// return an empty set. The existing suite only ever asserts the set is
/// *non-empty* on a wildcard zone  -  the asymmetric (and more dangerous)
/// side was untested: if detection ever reports a phantom wildcard IP
/// here, bruteforce compares every hit against that bogus set and
/// silently DROPS real subdomains that happen to share the IP  -  total
/// recall destruction with no error. End-to-end: an empty wildcard set
/// must therefore filter nothing.
#[tokio::test]
async fn detect_wildcards_on_non_wildcard_zone_is_empty() {
    let real_ip = Ipv4Addr::new(9, 9, 9, 9);
    let mut hosts = HashMap::new();
    hosts.insert("api.example.com".to_string(), host(Some(real_ip), None, None));
    let addr = HermeticZone {
        hosts,
        wildcard: WildcardMode::NxDomain,
        adversarial: AdversarialMode::Normal,
    }
    .serve()
    .await;
    sleep_server().await;

    let resolver = resolver_for(addr);
    let wildcards = detect_wildcards("example.com", &resolver, 5).await;
    assert!(
        wildcards.is_empty(),
        "a non-wildcard zone MUST yield an empty wildcard set (a phantom \
         entry silently drops real subdomains); got {wildcards:?}"
    );

    // And an empty set must filter nothing  -  the real host survives.
    let found = run_bruteforce_with_words(
        "example.com",
        &["api", "zzzgossan-nope-label"],
        resolver,
        Some(wildcards),
        1,
    )
    .await
    .unwrap();
    assert_exact(&found, &["api.example.com"]);
}

/// PRECISION: the learned wildcard set is EXACTLY the synthesised IP  - 
/// no spurious extras (e.g. from the CNAME-chain branch) that would
/// widen the filter and drop unrelated real subdomains.
#[tokio::test]
async fn detect_wildcards_set_is_exactly_the_synthesised_ip() {
    let wild_ip = Ipv4Addr::new(1, 2, 3, 4);
    let addr = HermeticZone {
        hosts: HashMap::new(),
        wildcard: WildcardMode::A(wild_ip),
        adversarial: AdversarialMode::Normal,
    }
    .serve()
    .await;
    sleep_server().await;

    let wildcards = detect_wildcards("example.com", &resolver_for(addr), 5).await;
    let expected: HashSet<IpAddr> = std::iter::once(IpAddr::V4(wild_ip)).collect();
    assert_eq!(
        wildcards, expected,
        "wildcard set must be exactly {{{wild_ip}}}, got {wildcards:?}"
    );
}

/// ADVERSARIAL PRECISION: a broken / hostile resolver (empty answers,
/// NXDOMAIN-with-CNAME, truncated garbage) MUST NOT be misread as
/// "wildcard present". A fabricated wildcard from a flaky upstream would
/// discard every genuine bruteforce finding  -  fail closed to "no
/// wildcard", never crash.
#[tokio::test]
async fn broken_dns_does_not_fabricate_a_wildcard() {
    for mode in [
        AdversarialMode::EmptyAnswer,
        AdversarialMode::NxdomainWithCname,
        AdversarialMode::TruncatedGarbage,
    ] {
        let addr = HermeticZone {
            hosts: HashMap::new(),
            wildcard: WildcardMode::NxDomain,
            adversarial: mode,
        }
        .serve()
        .await;
        sleep_server().await;

        let wildcards = detect_wildcards("example.com", &resolver_for(addr), 4).await;
        assert!(
            wildcards.is_empty(),
            "broken DNS mode {mode:?} must not fabricate a wildcard set, \
             got {wildcards:?}"
        );
    }
}

/// PROVING: recursion finds a deep name under a discovered `dev` label.
#[tokio::test]
async fn recursion_finds_deep_name_under_dev() {
    let mut hosts = HashMap::new();
    hosts.insert(
        "dev.example.com".to_string(),
        host(Some(Ipv4Addr::new(10, 1, 0, 1)), None, None),
    );
    hosts.insert(
        "admin.dev.example.com".to_string(),
        host(Some(Ipv4Addr::new(10, 1, 0, 2)), None, None),
    );
    let addr = HermeticZone {
        hosts,
        wildcard: WildcardMode::NxDomain,
        adversarial: AdversarialMode::Normal,
    }
    .serve()
    .await;
    sleep_server().await;

    let found = run_bruteforce_with_words(
        "example.com",
        &["dev", "admin"],
        resolver_for(addr),
        None,
        2,
    )
    .await
    .unwrap();
    assert_exact(
        &found,
        &["dev.example.com", "admin.dev.example.com"],
    );
}

/// PROVING: `seen` keeps two distinct names; never emits duplicates.
#[tokio::test]
async fn dedup_keeps_distinct_names_and_no_duplicates() {
    let mut hosts = HashMap::new();
    hosts.insert(
        "api.example.com".to_string(),
        host(Some(Ipv4Addr::new(10, 2, 0, 1)), None, None),
    );
    hosts.insert(
        "www.example.com".to_string(),
        host(Some(Ipv4Addr::new(10, 2, 0, 2)), None, None),
    );
    let addr = HermeticZone {
        hosts,
        wildcard: WildcardMode::NxDomain,
        adversarial: AdversarialMode::Normal,
    }
    .serve()
    .await;
    sleep_server().await;

    let found = run_bruteforce_with_words(
        "example.com",
        &["api", "www", "api"],
        resolver_for(addr),
        None,
        1,
    )
    .await
    .unwrap();
    assert_exact(&found, &["api.example.com", "www.example.com"]);
    assert_eq!(
        found.len(),
        found.iter().collect::<HashSet<_>>().len(),
        "no duplicate emissions in result vec"
    );
}

/// PROVING: `GOSSAN_RESOLVER_PORT` routes `build_resolver` to the hermetic server.
#[tokio::test]
async fn gossan_resolver_port_targets_hermetic_server() {
    let mut hosts = HashMap::new();
    hosts.insert(
        "portprobe.example.com".to_string(),
        host(Some(Ipv4Addr::new(10, 3, 0, 1)), None, None),
    );
    let addr = HermeticZone {
        hosts,
        wildcard: WildcardMode::NxDomain,
        adversarial: AdversarialMode::Normal,
    }
    .serve()
    .await;
    sleep_server().await;

    let _env = test_env_lock();
    let _guard = EnvGuard::set("GOSSAN_RESOLVER_PORT", &addr.port().to_string());
    assert_eq!(
        resolver_port(),
        addr.port(),
        "GOSSAN_RESOLVER_PORT must target the hermetic server"
    );

    let found = run_bruteforce_with_words(
        "example.com",
        &["portprobe"],
        gossan_resolver_for(addr),
        None,
        1,
    )
    .await
    .unwrap();
    assert_exact(&found, &["portprobe.example.com"]);
}

/// PROVING: passive source failure does not abort bruteforce (task isolation).
#[tokio::test]
async fn passive_source_failure_does_not_abort_bruteforce() {
    let mut hosts = HashMap::new();
    hosts.insert(
        "api.example.com".to_string(),
        host(Some(Ipv4Addr::new(10, 4, 0, 1)), None, None),
    );
    let addr = HermeticZone {
        hosts,
        wildcard: WildcardMode::NxDomain,
        adversarial: AdversarialMode::Normal,
    }
    .serve()
    .await;
    sleep_server().await;

    let _env = test_env_lock();
    let resolver = gossan_resolver_for(addr);

    let passive: tokio::task::JoinHandle<anyhow::Result<Vec<Target>>> = tokio::spawn(async {
        Err(anyhow::anyhow!("hermetic passive source failure"))
    });
    let bf = tokio::spawn(async move {
        run_bruteforce_with_words("example.com", &["api"], resolver, None, 1).await
    });

    let (passive_res, bf_res) = tokio::join!(passive, bf);
    assert!(passive_res.unwrap().is_err());
    assert_exact(&bf_res.unwrap().unwrap(), &["api.example.com"]);
}

/// ADVERSARIAL: broken/empty DNS responses must not panic or invent hosts.
#[tokio::test]
async fn adversarial_dns_responses_do_not_panic_or_invent() {
    for mode in [
        AdversarialMode::NxdomainWithCname,
        AdversarialMode::EmptyAnswer,
        AdversarialMode::TruncatedGarbage,
    ] {
        let addr = HermeticZone {
            hosts: HashMap::new(),
            wildcard: WildcardMode::NxDomain,
            adversarial: mode,
        }
        .serve()
        .await;
        sleep_server().await;

        let found = run_bruteforce_with_words(
            "example.com",
            &["ghost", "dead"],
            resolver_for(addr),
            None,
            1,
        )
        .await
        .unwrap();
        assert!(
            found.is_empty(),
            "adversarial mode {:?} must not invent hosts, got {found:?}",
            mode
        );
    }
}

struct EnvGuard {
    key: &'static str,
    prev: Option<String>,
}

impl EnvGuard {
    fn set(key: &'static str, value: &str) -> Self {
        let prev = std::env::var(key).ok();
        std::env::set_var(key, value);
        Self { key, prev }
    }
}

impl Drop for EnvGuard {
    fn drop(&mut self) {
        match &self.prev {
            Some(v) => std::env::set_var(self.key, v),
            None => std::env::remove_var(self.key),
        }
    }
}