Skip to content

Commit 724f4fe

Browse files
TMHSDigitalclaude
andcommitted
feat(simulate): honor -hit-rate uniformly and add -seed
Twelve common prefixes resolved ~90% of the time regardless of -hit-rate, and results came from an unseeded RNG, so demos and tests could not be reproduced. Outcomes, records and fake timings are now a pure function of (seed, name) via a mixed FNV hash, -hit-rate applies to every name, and -seed selects the seed (a random one is printed when it is omitted). The TUI uses a random seed per scan. Fixes #44 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 39ae5f1 commit 724f4fe

7 files changed

Lines changed: 96 additions & 48 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,13 +24,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
2424
- `-format jsonl` streams one JSON object per resolved subdomain, so structured output can be piped live (#34).
2525
- `-show-records` appends `TYPE=value` record pairs to `text` output on stdout and in the `-o` file (#34, ROADMAP N2).
2626
- TUI form gains *Max Names* (`-max-queries`) and *No Abort* (`-no-abort`), both persisted in `last.json`. A recursive TUI scan above the 1e7 ceiling can now be started with a cap instead of enabling *Force*, which also disables the wildcard abort (#35).
27+
- `-seed <n>` makes simulation mode reproducible: each outcome, record and reported timing is derived from the seed and the name, so the same seed gives the same results. Without `-seed` a random seed is chosen and printed in the simulation banner (#44).
2728

2829
### Changed
2930
- When stdout is not a terminal, `text` results are printed as bare subdomain names (no `Found:` prefix), so `subenum ... | sort -u` or `| httpx` works without `cut`. Terminal output is unchanged. `examples/multi_domain_scan.sh` now counts lines instead of `Found:` (#34).
3031
- Wordlists are normalized on load: blank lines and `#` comments are ignored, entries are lowercased before deduplication (so `WWW` and `www` are one query), and entries that are not valid DNS labels (whitespace, `*`, empty or over-long labels) or whose full name would exceed 253 characters are skipped and reported on stderr. Underscore labels such as `_dmarc` are kept. A wordlist with no valid entries is an error (#33).
3132
- `-max-queries` help text and docs now say what it counts: candidate names (jobs), not wire queries.
3233
- Release binaries and the Docker image are built with the latest stable Go toolchain (Docker builder `golang:1.27.1-alpine`, digest-pinned) instead of Go 1.24.2. `go.mod` still declares 1.24.2 as the minimum, and CI now tests both the minimum and the latest stable toolchain. CI runs `govulncheck` on every push and PR, and Dependabot tracks the Dockerfile base images. Release jobs build without a shared cache (#38).
3334
- `-version` no longer relies on a hand-maintained `0.7.0` fallback. Without ldflags it reports the module version recorded by `go install` (for example `v0.7.0`), or `dev` for local builds; the Makefile and Dockerfile fallbacks are `dev` too. README and the landing page document `go install github.com/TMHSDigital/subenum@latest` and add a "Why subenum" section (#39).
35+
- Simulation mode applies `-hit-rate` uniformly. Previously 12 common prefixes (`www`, `api`, `dev`, ...) always resolved about 90% of the time, so `-hit-rate 1` still produced many hits and recursive simulate scans grew much faster than the rate suggested (#44).
3436

3537
## [0.7.0] - 2026-09-16
3638

‎README.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,8 @@ make help # list all targets
243243
| `-v` | `false` | Verbose output: IPs, timings, per-query detail (stderr) |
244244
| `-progress` | `true` | Live progress line on stderr |
245245
| `-simulate` | `false` | Simulation mode: no real DNS queries |
246-
| `-hit-rate <n>` | `15` | Simulated resolution rate, percent (1-100) |
246+
| `-hit-rate <n>` | `15` | Simulated resolution rate, percent (1-100), applied uniformly to every name |
247+
| `-seed <n>` | `0` | Simulation seed; the same seed reproduces the same results (line order can vary unless `-t 1`). `0` picks a random seed and prints it |
247248
| `-tui` | `false` | Launch the interactive Terminal UI |
248249
| `-version` | n/a | Print version and exit |
249250
| `-retries <n>` | n/a | **Deprecated** - alias for `-attempts`, prints a warning |

‎internal/dns/simulate.go‎

Lines changed: 35 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,49 +1,57 @@
11
package dns
22

33
import (
4+
"encoding/binary"
45
"fmt"
5-
"math/rand/v2"
6+
"hash/fnv"
67
"strings"
78
"time"
89
)
910

1011
// SimulateResolve returns a synthetic DNS result without performing any network
1112
// I/O, along with synthetic records for the requested types when the domain
12-
// "resolves". Common subdomain prefixes resolve ~90% of the time; everything
13-
// else uses the supplied hitRate (0-100).
14-
func SimulateResolve(domain string, hitRate int, logf Logf, types []string) ([]Record, bool) {
15-
commonSubdomains := []string{
16-
"www", "mail", "ftp", "blog",
17-
"api", "dev", "staging", "test",
18-
"admin", "portal", "app", "secure",
19-
}
20-
21-
for _, sub := range commonSubdomains {
22-
if strings.HasPrefix(domain, sub+".") {
23-
if rand.IntN(100) < 90 {
24-
return synthResolved(domain, types, logf)
25-
}
26-
return synthFailed(domain, logf)
27-
}
13+
// "resolves". Exactly hitRate percent (0-100) of names resolve, whatever their
14+
// prefix.
15+
//
16+
// The outcome, records and reported timing are a pure function of (seed,
17+
// domain), so the same seed reproduces the same scan regardless of worker
18+
// scheduling. Callers pick a random seed when the user does not supply one.
19+
func SimulateResolve(domain string, hitRate int, seed uint64, logf Logf, types []string) ([]Record, bool) {
20+
h := simHash(seed, domain)
21+
if int(h%100) < hitRate {
22+
return synthResolved(domain, types, h, logf)
2823
}
24+
return synthFailed(domain, h, logf)
25+
}
2926

30-
if rand.IntN(100) < hitRate {
31-
return synthResolved(domain, types, logf)
32-
}
33-
return synthFailed(domain, logf)
27+
// simHash mixes the seed and the lowercased name into 64 well-distributed bits.
28+
func simHash(seed uint64, domain string) uint64 {
29+
f := fnv.New64a()
30+
var b [8]byte
31+
binary.LittleEndian.PutUint64(b[:], seed)
32+
_, _ = f.Write(b[:])
33+
_, _ = f.Write([]byte(strings.ToLower(strings.TrimSuffix(domain, "."))))
34+
// splitmix64 finalizer: FNV's low bits alone are too regular for h%100.
35+
x := f.Sum64()
36+
x ^= x >> 30
37+
x *= 0xbf58476d1ce4e5b9
38+
x ^= x >> 27
39+
x *= 0x94d049bb133111eb
40+
x ^= x >> 31
41+
return x
3442
}
3543

36-
func synthResolved(domain string, types []string, logf Logf) ([]Record, bool) {
44+
func synthResolved(domain string, types []string, h uint64, logf Logf) ([]Record, bool) {
3745
if len(types) == 0 {
3846
types = DefaultTypes
3947
}
4048
var records []Record
4149
for _, t := range types {
4250
switch t {
4351
case "A":
44-
records = append(records, Record{Type: "A", Value: fmt.Sprintf("10.%d.%d.%d", rand.IntN(255), rand.IntN(255), 1+rand.IntN(254))})
52+
records = append(records, Record{Type: "A", Value: fmt.Sprintf("10.%d.%d.%d", (h>>8)%255, (h>>16)%255, 1+(h>>24)%254)})
4553
case "AAAA":
46-
records = append(records, Record{Type: "AAAA", Value: fmt.Sprintf("2001:db8::%x", rand.IntN(65535))})
54+
records = append(records, Record{Type: "AAAA", Value: fmt.Sprintf("2001:db8::%x", (h>>32)&0xffff)})
4755
case "CNAME":
4856
records = append(records, Record{Type: "CNAME", Value: "target." + domain})
4957
}
@@ -52,15 +60,15 @@ func synthResolved(domain string, types []string, logf Logf) ([]Record, bool) {
5260
return nil, false
5361
}
5462
if logf != nil {
55-
fakeTiming := time.Duration(50+rand.IntN(450)) * time.Millisecond
63+
fakeTiming := time.Duration(50+(h>>48)%450) * time.Millisecond
5664
logf("Resolved (SIMULATED): %s (%s: %s) in %s", domain, records[0].Type, records[0].Value, fakeTiming)
5765
}
5866
return records, true
5967
}
6068

61-
func synthFailed(domain string, logf Logf) ([]Record, bool) {
69+
func synthFailed(domain string, h uint64, logf Logf) ([]Record, bool) {
6270
if logf != nil {
63-
fakeTiming := time.Duration(100+rand.IntN(500)) * time.Millisecond
71+
fakeTiming := time.Duration(100+(h>>48)%500) * time.Millisecond
6472
logf("Failed to resolve (SIMULATED): %s (Error: no such host) in %s", domain, fakeTiming)
6573
}
6674
return nil, false

‎internal/dns/simulate_test.go‎

Lines changed: 44 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,57 @@
11
package dns
22

33
import (
4+
"fmt"
5+
"reflect"
46
"sync"
57
"testing"
68
)
79

810
func TestSimulateResolve(t *testing.T) {
9-
runs := 500
10-
11-
resolved := 0
12-
for i := 0; i < runs; i++ {
13-
if _, ok := SimulateResolve("www.example.com", 15, nil, DefaultTypes); ok {
14-
resolved++
11+
for seed := uint64(0); seed < 200; seed++ {
12+
if _, ok := SimulateResolve("zzz-random-prefix.example.com", 0, seed, nil, DefaultTypes); ok {
13+
t.Fatalf("seed %d: 0%% hit rate resolved", seed)
14+
}
15+
if _, ok := SimulateResolve("zzz-random-prefix.example.com", 100, seed, nil, DefaultTypes); !ok {
16+
t.Fatalf("seed %d: 100%% hit rate did not resolve", seed)
1517
}
1618
}
17-
if resolved == 0 {
18-
t.Errorf("Expected common subdomains to resolve in simulation, got 0/%d", runs)
19+
}
20+
21+
// TestSimulateHitRateHonored covers #44: -hit-rate applies uniformly, with no
22+
// hidden 90% boost for common prefixes like www or api.
23+
func TestSimulateHitRateHonored(t *testing.T) {
24+
const n = 5000
25+
for _, prefix := range []string{"www", "api", "p"} {
26+
hits := 0
27+
for i := 0; i < n; i++ {
28+
if _, ok := SimulateResolve(fmt.Sprintf("%s.example.com", prefix), 10, uint64(i), nil, DefaultTypes); ok {
29+
hits++
30+
}
31+
}
32+
if pct := hits * 100 / n; pct < 7 || pct > 13 {
33+
t.Errorf("prefix %q: %d%% resolved at -hit-rate 10", prefix, pct)
34+
}
1935
}
36+
}
2037

21-
resolved = 0
22-
for i := 0; i < runs; i++ {
23-
if _, ok := SimulateResolve("zzz-random-prefix.example.com", 0, nil, DefaultTypes); ok {
24-
resolved++
38+
// TestSimulateDeterministic covers #44: the same seed reproduces the same
39+
// outcome and records; a different seed generally does not.
40+
func TestSimulateDeterministic(t *testing.T) {
41+
differs := false
42+
for i := 0; i < 100; i++ {
43+
name := fmt.Sprintf("h%d.example.com", i)
44+
r1, ok1 := SimulateResolve(name, 50, 42, nil, DefaultTypes)
45+
r2, ok2 := SimulateResolve(name, 50, 42, nil, DefaultTypes)
46+
if ok1 != ok2 || !reflect.DeepEqual(r1, r2) {
47+
t.Fatalf("%s: seed 42 not reproducible: %v/%v vs %v/%v", name, ok1, r1, ok2, r2)
48+
}
49+
if _, ok3 := SimulateResolve(name, 50, 43, nil, DefaultTypes); ok3 != ok1 {
50+
differs = true
2551
}
2652
}
27-
if resolved != 0 {
28-
t.Errorf("Expected 0%% hit rate to never resolve, got %d/%d", resolved, runs)
53+
if !differs {
54+
t.Error("seeds 42 and 43 produced identical outcomes for 100 names")
2955
}
3056
}
3157

@@ -49,7 +75,7 @@ func TestParseTypes(t *testing.T) {
4975

5076
func TestSimulateResolveTypes(t *testing.T) {
5177
// Force a resolve with hitRate 100 and request only CNAME.
52-
recs, ok := SimulateResolve("zzz.example.com", 100, nil, []string{"CNAME"})
78+
recs, ok := SimulateResolve("zzz.example.com", 100, 1, nil, []string{"CNAME"})
5379
if !ok {
5480
t.Fatal("expected simulate to resolve at hitRate 100")
5581
}
@@ -59,7 +85,7 @@ func TestSimulateResolveTypes(t *testing.T) {
5985
}
6086

6187
// TestSimulateResolveConcurrent calls SimulateResolve from many goroutines at
62-
// once. With math/rand/v2 top-level functions this is race-free; the test
88+
// once. Results are a pure function of (seed, name), so this is race-free; the test
6389
// exists to be caught by `go test -race`.
6490
func TestSimulateResolveConcurrent(t *testing.T) {
6591
const goroutines = 64
@@ -71,8 +97,8 @@ func TestSimulateResolveConcurrent(t *testing.T) {
7197
go func() {
7298
defer wg.Done()
7399
for i := 0; i < perGoroutine; i++ {
74-
SimulateResolve("api.example.com", 50, nil, DefaultTypes)
75-
SimulateResolve("zzz-random.example.com", 25, func(string, ...any) {}, DefaultTypes)
100+
SimulateResolve("api.example.com", 50, uint64(i), nil, DefaultTypes)
101+
SimulateResolve("zzz-random.example.com", 25, uint64(i), func(string, ...any) {}, DefaultTypes)
76102
}
77103
}()
78104
}

‎internal/scan/runner.go‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ type Config struct {
2727
DNSServer string
2828
Simulate bool
2929
HitRate int
30+
Seed uint64 // simulation seed: the same seed reproduces the same simulated results
3031
Attempts int
3132
Force bool
3233
Verbose bool // log every lookup; through Logf when set, else unsynchronized to stderr
@@ -458,7 +459,7 @@ func processJob(ctx context.Context, cfg Config, j job, maxDepth int, limiter *d
458459
records, outcome = cfg.resolveHook(ctx, j.domain)
459460
case cfg.Simulate:
460461
var ok bool
461-
records, ok = dns.SimulateResolve(j.domain, cfg.HitRate, cfg.logf(), cfg.Types)
462+
records, ok = dns.SimulateResolve(j.domain, cfg.HitRate, cfg.Seed, cfg.logf(), cfg.Types)
462463
if ok {
463464
outcome = dns.OutcomeFound
464465
} else {

‎internal/tui/model.go‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ package tui
44
import (
55
"bufio"
66
"context"
7+
"math/rand/v2"
78
"os"
89
"time"
910

@@ -149,6 +150,7 @@ func (m Model) beginScan(vals formValues) (tea.Model, tea.Cmd) {
149150
DNSServer: vals.dnsServer,
150151
Simulate: vals.simulate,
151152
HitRate: vals.hitRate,
153+
Seed: rand.Uint64(),
152154
Attempts: vals.attempts,
153155
Force: vals.force,
154156
Types: vals.recordTypes,

‎main.go‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ import (
2525
"errors"
2626
"flag"
2727
"fmt"
28+
"math/rand/v2"
2829
"os"
2930
"os/signal"
3031
"runtime/debug"
@@ -95,6 +96,7 @@ type cliFlags struct {
9596
showProgress bool
9697
testMode bool
9798
testHitRate int
99+
seed uint64
98100
outputFile string
99101
attempts int
100102
retries int
@@ -123,7 +125,8 @@ func parseFlags(args []string) (cliFlags, []string, *flag.FlagSet, error) {
123125
fs.BoolVar(&f.showVersion, "version", false, "Show version information")
124126
fs.BoolVar(&f.showProgress, "progress", true, "Show progress during scanning")
125127
fs.BoolVar(&f.testMode, "simulate", false, "Run in simulation mode without actual DNS queries (for testing)")
126-
fs.IntVar(&f.testHitRate, "hit-rate", 15, "In simulation mode, percentage of subdomains that will 'resolve' (1-100)")
128+
fs.IntVar(&f.testHitRate, "hit-rate", 15, "In simulation mode, percentage of names that resolve (1-100)")
129+
fs.Uint64Var(&f.seed, "seed", 0, "In simulation mode, seed for reproducible results (0 = random; the seed used is printed)")
127130
fs.StringVar(&f.outputFile, "o", "", "Write results to file (in addition to stdout)")
128131
fs.IntVar(&f.attempts, "attempts", 0, "Total DNS resolution attempts per subdomain (1 = no retry)")
129132
fs.IntVar(&f.retries, "retries", 0, "Deprecated: use -attempts instead")
@@ -309,11 +312,15 @@ func run() (code int) {
309312
}
310313

311314
if f.testMode {
315+
if f.seed == 0 {
316+
f.seed = rand.Uint64()
317+
}
312318
out.Info("")
313319
out.Info("╔════════════════════════════════════════════════════════════════════╗")
314320
out.Info("║ SIMULATION MODE ACTIVE - NO ACTUAL DNS QUERIES WILL BE PERFORMED ║")
315321
out.Info("║ Results are artificially generated for educational purposes only ║")
316322
out.Info("╚════════════════════════════════════════════════════════════════════╝")
323+
out.Info("Simulation seed: %d (pass -seed %d to reproduce these results)", f.seed, f.seed)
317324
out.Info("")
318325
}
319326

@@ -413,6 +420,7 @@ func run() (code int) {
413420
DNSServer: f.dnsServer,
414421
Simulate: f.testMode,
415422
HitRate: f.testHitRate,
423+
Seed: f.seed,
416424
Attempts: maxAttempts,
417425
Force: f.force,
418426
Verbose: f.verbose,

0 commit comments

Comments
 (0)