-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathssrf_test.go
More file actions
755 lines (639 loc) · 22.9 KB
/
Copy pathssrf_test.go
File metadata and controls
755 lines (639 loc) · 22.9 KB
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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
package ssrf_test
import (
"context"
"errors"
"net"
"net/http"
"strings"
"syscall"
"testing"
"time"
"github.com/chrj/ssrf"
"github.com/foxcpp/go-mockdns"
)
// dialAndExpect is a helper that attempts a connection using the DialContext
// returned by the provided options, and checks whether the resulting error
// matches the expected outcome.
func dialAndExpect(t *testing.T, addr string, expectErr bool, opts ...ssrf.Option) error {
t.Helper()
dial := ssrf.DialContext(opts...)
_, err := dial(context.Background(), "tcp", addr)
if expectErr && err == nil {
t.Errorf("expected error for %q but got none", addr)
} else if !expectErr && err != nil {
t.Errorf("unexpected error for %q: %v", addr, err)
}
return err
}
// ---- Error type ------------------------------------------------------------
func TestError_Error(t *testing.T) {
e := &ssrf.Error{Reason: "test reason"}
if got := e.Error(); got != "ssrf: test reason" {
t.Errorf("Error() = %q; want %q", got, "ssrf: test reason")
}
}
// ---- IPv4Only --------------------------------------------------------------
func TestIPv4Only_AllowsIPv4(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer func() { _ = ln.Close() }()
go acceptAndClose(ln)
_, port, _ := net.SplitHostPort(ln.Addr().String())
resolver := &mockdns.Resolver{Zones: map[string]mockdns.Zone{
"ipv4.test.": {A: []string{"127.0.0.1"}},
}}
dial := ssrf.DialContext(ssrf.IPv4Only(), ssrf.WithResolver(resolver))
conn, err := dial(context.Background(), "tcp", "ipv4.test:"+port)
if err != nil {
t.Fatalf("IPv4Only should allow IPv4 address: %v", err)
}
_ = conn.Close()
}
func TestIPv4Only_BlocksIPv6(t *testing.T) {
resolver := &mockdns.Resolver{Zones: map[string]mockdns.Zone{
"ipv6host.test.": {AAAA: []string{"2606:2800:220:1:248:1893:25c8:1946"}},
}}
err := dialAndExpect(t, "ipv6host.test:80", true,
ssrf.IPv4Only(), ssrf.WithResolver(resolver))
checkSSRFError(t, err, "IPv4 only")
}
// ---- IPv6Only --------------------------------------------------------------
func TestIPv6Only_AllowsIPv6(t *testing.T) {
ln, err := net.Listen("tcp", "[::1]:0")
if err != nil {
t.Skip("IPv6 loopback not available")
}
defer func() { _ = ln.Close() }()
go acceptAndClose(ln)
_, port, _ := net.SplitHostPort(ln.Addr().String())
resolver := &mockdns.Resolver{Zones: map[string]mockdns.Zone{
"ipv6.test.": {AAAA: []string{"::1"}},
}}
dial := ssrf.DialContext(ssrf.IPv6Only(), ssrf.WithResolver(resolver))
conn, err := dial(context.Background(), "tcp", "ipv6.test:"+port)
if err != nil {
t.Fatalf("IPv6Only should allow IPv6 address: %v", err)
}
_ = conn.Close()
}
func TestIPv6Only_BlocksIPv4(t *testing.T) {
resolver := &mockdns.Resolver{Zones: map[string]mockdns.Zone{
"ipv4host.test.": {A: []string{"127.0.0.1"}},
}}
err := dialAndExpect(t, "ipv4host.test:80", true,
ssrf.IPv6Only(), ssrf.WithResolver(resolver))
checkSSRFError(t, err, "IPv6 only")
}
// ---- NoPrivateRanges -------------------------------------------------------
func TestNoPrivateRanges_BlocksLoopback(t *testing.T) {
resolver := &mockdns.Resolver{Zones: map[string]mockdns.Zone{
"loopback.test.": {A: []string{"127.0.0.1"}},
}}
err := dialAndExpect(t, "loopback.test:80", true,
ssrf.NoPrivateRanges(), ssrf.WithResolver(resolver))
checkSSRFError(t, err, "private or reserved")
}
func TestNoPrivateRanges_BlocksIPv6Loopback(t *testing.T) {
resolver := &mockdns.Resolver{Zones: map[string]mockdns.Zone{
"loopback6.test.": {AAAA: []string{"::1"}},
}}
err := dialAndExpect(t, "loopback6.test:80", true,
ssrf.NoPrivateRanges(), ssrf.WithResolver(resolver))
checkSSRFError(t, err, "private or reserved")
}
func TestNoPrivateRanges_Blocks10(t *testing.T) {
resolver := &mockdns.Resolver{Zones: map[string]mockdns.Zone{
"ten.test.": {A: []string{"10.0.0.1"}},
}}
err := dialAndExpect(t, "ten.test:80", true,
ssrf.NoPrivateRanges(), ssrf.WithResolver(resolver))
checkSSRFError(t, err, "private or reserved")
}
func TestNoPrivateRanges_Blocks172_16(t *testing.T) {
resolver := &mockdns.Resolver{Zones: map[string]mockdns.Zone{
"rfc1918-b.test.": {A: []string{"172.16.0.1"}},
}}
err := dialAndExpect(t, "rfc1918-b.test:80", true,
ssrf.NoPrivateRanges(), ssrf.WithResolver(resolver))
checkSSRFError(t, err, "private or reserved")
}
func TestNoPrivateRanges_Blocks192_168(t *testing.T) {
resolver := &mockdns.Resolver{Zones: map[string]mockdns.Zone{
"rfc1918-c.test.": {A: []string{"192.168.1.1"}},
}}
err := dialAndExpect(t, "rfc1918-c.test:80", true,
ssrf.NoPrivateRanges(), ssrf.WithResolver(resolver))
checkSSRFError(t, err, "private or reserved")
}
func TestNoPrivateRanges_BlocksLinkLocal(t *testing.T) {
resolver := &mockdns.Resolver{Zones: map[string]mockdns.Zone{
"linklocal.test.": {A: []string{"169.254.0.1"}},
}}
err := dialAndExpect(t, "linklocal.test:80", true,
ssrf.NoPrivateRanges(), ssrf.WithResolver(resolver))
checkSSRFError(t, err, "private or reserved")
}
func TestNoPrivateRanges_BlocksIPv6LinkLocal(t *testing.T) {
resolver := &mockdns.Resolver{Zones: map[string]mockdns.Zone{
"linklocal6.test.": {AAAA: []string{"fe80::1"}},
}}
err := dialAndExpect(t, "linklocal6.test:80", true,
ssrf.NoPrivateRanges(), ssrf.WithResolver(resolver))
checkSSRFError(t, err, "private or reserved")
}
func TestNoPrivateRanges_BlocksIPv6ULA(t *testing.T) {
resolver := &mockdns.Resolver{Zones: map[string]mockdns.Zone{
"ula.test.": {AAAA: []string{"fc00::1"}},
}}
err := dialAndExpect(t, "ula.test:80", true,
ssrf.NoPrivateRanges(), ssrf.WithResolver(resolver))
checkSSRFError(t, err, "private or reserved")
}
func TestNoPrivateRanges_AllowsPublicIPv4(t *testing.T) {
// Resolve to a public IP to verify NoPrivateRanges does not block it.
// hermeticDialer aborts the dial before any packet is sent, so the test
// exercises the DialContext code path without making a real network call.
resolver := &mockdns.Resolver{Zones: map[string]mockdns.Zone{
"public.test.": {A: []string{"109.205.61.17"}},
}}
dial := ssrf.DialContext(
ssrf.NoPrivateRanges(),
ssrf.WithResolver(resolver),
ssrf.WithDialer(hermeticDialer()),
)
_, err := dial(context.Background(), "tcp", "public.test:80")
if isSsrfError(err) {
t.Errorf("NoPrivateRanges should allow public IPs; got ssrf error: %v", err)
}
}
// ---- DenyCIDR --------------------------------------------------------------
func TestDenyCIDR_BlocksMatchingAddress(t *testing.T) {
resolver := &mockdns.Resolver{Zones: map[string]mockdns.Zone{
"denied.test.": {A: []string{"10.20.30.40"}},
}}
err := dialAndExpect(t, "denied.test:80", true,
ssrf.DenyCIDR("10.0.0.0/8"), ssrf.WithResolver(resolver))
checkSSRFError(t, err, "denied range")
}
func TestDenyCIDR_AllowsNonMatchingAddress(t *testing.T) {
// 127.0.0.1 is not in 10.0.0.0/8 so DenyCIDR should not block it.
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer func() { _ = ln.Close() }()
go acceptAndClose(ln)
_, port, _ := net.SplitHostPort(ln.Addr().String())
resolver := &mockdns.Resolver{Zones: map[string]mockdns.Zone{
"allowed.test.": {A: []string{"127.0.0.1"}},
}}
dial := ssrf.DialContext(ssrf.DenyCIDR("10.0.0.0/8"), ssrf.WithResolver(resolver))
conn, err := dial(context.Background(), "tcp", "allowed.test:"+port)
if err != nil {
t.Fatalf("DenyCIDR(10/8) should not block 127.0.0.1: %v", err)
}
_ = conn.Close()
}
func TestDenyCIDR_MultipleRanges(t *testing.T) {
resolver := &mockdns.Resolver{Zones: map[string]mockdns.Zone{
"denied-multi.test.": {A: []string{"192.168.5.5"}},
}}
opts := []ssrf.Option{
ssrf.DenyCIDR("10.0.0.0/8", "192.168.0.0/16"),
ssrf.WithResolver(resolver),
}
err := dialAndExpect(t, "denied-multi.test:80", true, opts...)
checkSSRFError(t, err, "denied range")
}
func TestDenyCIDR_IPv6(t *testing.T) {
resolver := &mockdns.Resolver{Zones: map[string]mockdns.Zone{
"denied6.test.": {AAAA: []string{"fc00::1"}},
}}
err := dialAndExpect(t, "denied6.test:80", true,
ssrf.DenyCIDR("fc00::/7"), ssrf.WithResolver(resolver))
checkSSRFError(t, err, "denied range")
}
// ---- AllowCIDR -------------------------------------------------------------
func TestAllowCIDR_AllowsMatchingAddress(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer func() { _ = ln.Close() }()
go acceptAndClose(ln)
_, port, _ := net.SplitHostPort(ln.Addr().String())
resolver := &mockdns.Resolver{Zones: map[string]mockdns.Zone{
"allowed.test.": {A: []string{"127.0.0.1"}},
}}
dial := ssrf.DialContext(ssrf.AllowCIDR("127.0.0.0/8"), ssrf.WithResolver(resolver))
conn, err := dial(context.Background(), "tcp", "allowed.test:"+port)
if err != nil {
t.Fatalf("AllowCIDR should allow matching address: %v", err)
}
_ = conn.Close()
}
func TestAllowCIDR_BlocksNonMatchingAddress(t *testing.T) {
resolver := &mockdns.Resolver{Zones: map[string]mockdns.Zone{
"blocked.test.": {A: []string{"10.0.0.1"}},
}}
err := dialAndExpect(t, "blocked.test:80", true,
ssrf.AllowCIDR("203.0.113.0/24"), ssrf.WithResolver(resolver))
checkSSRFError(t, err, "not in any allowed range")
}
func TestAllowCIDR_MultipleRanges(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer func() { _ = ln.Close() }()
go acceptAndClose(ln)
_, port, _ := net.SplitHostPort(ln.Addr().String())
resolver := &mockdns.Resolver{Zones: map[string]mockdns.Zone{
"multi.test.": {A: []string{"127.0.0.1"}},
}}
opts := []ssrf.Option{
ssrf.AllowCIDR("10.0.0.0/8", "127.0.0.0/8"),
ssrf.WithResolver(resolver),
}
dial := ssrf.DialContext(opts...)
conn, err := dial(context.Background(), "tcp", "multi.test:"+port)
if err != nil {
t.Fatalf("AllowCIDR should allow matching address in multiple ranges: %v", err)
}
_ = conn.Close()
}
func TestAllowCIDR_IPv6(t *testing.T) {
ln, err := net.Listen("tcp", "[::1]:0")
if err != nil {
t.Skip("IPv6 loopback not available")
}
defer func() { _ = ln.Close() }()
go acceptAndClose(ln)
_, port, _ := net.SplitHostPort(ln.Addr().String())
resolver := &mockdns.Resolver{Zones: map[string]mockdns.Zone{
"ipv6-allowed.test.": {AAAA: []string{"::1"}},
}}
dial := ssrf.DialContext(
ssrf.AllowCIDR("::1/128"),
ssrf.WithResolver(resolver),
)
conn, err := dial(context.Background(), "tcp", "ipv6-allowed.test:"+port)
if err != nil {
t.Fatalf("AllowCIDR should allow matching IPv6 address: %v", err)
}
_ = conn.Close()
}
// ---- Combined options ------------------------------------------------------
func TestCombined_IPv4OnlyAndNoPrivate(t *testing.T) {
resolver := &mockdns.Resolver{Zones: map[string]mockdns.Zone{
"loopback6.test.": {AAAA: []string{"::1"}},
}}
// IPv6 loopback should be blocked by IPv4Only.
err := dialAndExpect(t, "loopback6.test:80", true,
ssrf.IPv4Only(), ssrf.NoPrivateRanges(), ssrf.WithResolver(resolver))
checkSSRFError(t, err, "IPv4 only")
}
func TestCombined_AllowAndDeny_DenyWins(t *testing.T) {
resolver := &mockdns.Resolver{Zones: map[string]mockdns.Zone{
"deny-wins.test.": {A: []string{"10.10.1.1"}},
}}
// The address is inside the allow range but also inside the deny range;
// deny should be evaluated first.
opts := []ssrf.Option{
ssrf.AllowCIDR("10.0.0.0/8"),
ssrf.DenyCIDR("10.10.0.0/16"),
ssrf.WithResolver(resolver),
}
err := dialAndExpect(t, "deny-wins.test:80", true, opts...)
checkSSRFError(t, err, "denied range")
}
// ---- Hostname resolution ---------------------------------------------------
func TestDialContext_ResolvesHostname(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer func() { _ = ln.Close() }()
go acceptAndClose(ln)
_, port, _ := net.SplitHostPort(ln.Addr().String())
resolver := &mockdns.Resolver{Zones: map[string]mockdns.Zone{
"resolved.test.": {A: []string{"127.0.0.1"}},
}}
dial := ssrf.DialContext(ssrf.WithResolver(resolver))
conn, err := dial(context.Background(), "tcp", "resolved.test:"+port)
if err != nil {
t.Fatalf("expected connection to succeed, got: %v", err)
}
_ = conn.Close()
}
func TestDialContext_BlocksLocalhost_NoPrivate(t *testing.T) {
resolver := &mockdns.Resolver{Zones: map[string]mockdns.Zone{
"localhost.test.": {A: []string{"127.0.0.1"}},
}}
err := dialAndExpect(t, "localhost.test:80", true,
ssrf.NoPrivateRanges(), ssrf.WithResolver(resolver))
checkSSRFError(t, err, "private or reserved")
}
// ---- Integration: http.Transport -------------------------------------------
func TestHTTPTransport_Integration(t *testing.T) {
// Set up a local HTTP server.
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer func() { _ = ln.Close() }()
go func() {
for {
conn, err := ln.Accept()
if err != nil {
return
}
conn.Write([]byte("HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n")) //nolint:errcheck
_ = conn.Close()
}
}()
_, port, _ := net.SplitHostPort(ln.Addr().String())
resolver := &mockdns.Resolver{Zones: map[string]mockdns.Zone{
"httptest.test.": {A: []string{"127.0.0.1"}},
}}
t.Run("no options allows loopback", func(t *testing.T) {
tr := &http.Transport{
DialContext: ssrf.DialContext(ssrf.WithResolver(resolver)),
}
client := &http.Client{Transport: tr}
resp, err := client.Get("http://httptest.test:" + port + "/")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
_ = resp.Body.Close()
})
t.Run("NoPrivateRanges blocks loopback", func(t *testing.T) {
tr := &http.Transport{
DialContext: ssrf.DialContext(ssrf.NoPrivateRanges(), ssrf.WithResolver(resolver)),
}
client := &http.Client{Transport: tr}
resp, err := client.Get("http://httptest.test:" + port + "/")
if resp != nil {
_ = resp.Body.Close()
}
if err == nil {
t.Fatal("expected error but got none")
}
if !strings.Contains(err.Error(), "private or reserved") {
t.Errorf("expected 'private or reserved' in error, got: %v", err)
}
})
}
// ---- WithResolver ----------------------------------------------------------
func TestWithResolver_UsesCustomResolver(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer func() { _ = ln.Close() }()
go acceptAndClose(ln)
_, port, _ := net.SplitHostPort(ln.Addr().String())
resolver := &mockdns.Resolver{Zones: map[string]mockdns.Zone{
"custom.resolver.test.": {A: []string{"127.0.0.1"}},
}}
dial := ssrf.DialContext(ssrf.WithResolver(resolver))
conn, err := dial(context.Background(), "tcp", "custom.resolver.test:"+port)
if err != nil {
t.Fatalf("expected connection via custom resolver, got: %v", err)
}
_ = conn.Close()
}
// ---- DNS rebinding protection ----------------------------------------------
// TestDialContext_DNSRebindingProtection demonstrates that the dialer resolves
// hostnames to IP addresses exactly once per dial call, validates the resolved
// IP, and then connects using the raw IP — never the original hostname. This
// prevents DNS rebinding: even if an attacker changes DNS between the
// validation step and the TCP connect step, the connection still goes to the
// IP that was validated.
func TestDialContext_DNSRebindingProtection(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer func() { _ = ln.Close() }()
go acceptAndClose(ln)
_, port, _ := net.SplitHostPort(ln.Addr().String())
resolver := &mockdns.Resolver{Zones: map[string]mockdns.Zone{
// The fake hostname resolves to 127.0.0.1 (a private address).
"rebind.test.": {A: []string{"127.0.0.1"}},
}}
// SSRF rules are applied to the resolved IP, not the hostname.
// With NoPrivateRanges the connection MUST be blocked because the hostname
// resolves to 127.0.0.1 (private). A hostname-only check would miss this.
dial := ssrf.DialContext(
ssrf.NoPrivateRanges(),
ssrf.WithResolver(resolver),
)
_, err = dial(context.Background(), "tcp", "rebind.test:"+port)
checkSSRFError(t, err, "private or reserved")
// Without NoPrivateRanges the connection should succeed via the resolved IP.
dial = ssrf.DialContext(ssrf.WithResolver(resolver))
conn, err := dial(context.Background(), "tcp", "rebind.test:"+port)
if err != nil {
t.Fatalf("expected successful connection, got: %v", err)
}
_ = conn.Close()
}
// ---- Invalid addr ----------------------------------------------------------
func TestDialContext_InvalidAddr(t *testing.T) {
resolver := &mockdns.Resolver{Zones: map[string]mockdns.Zone{}}
dial := ssrf.DialContext(ssrf.WithResolver(resolver))
_, err := dial(context.Background(), "tcp", "not-valid")
if err == nil {
t.Error("expected error for invalid address, got nil")
}
}
// ---- New / Dialer struct ----------------------------------------------------
func TestNew_ReturnsDialer(t *testing.T) {
d := ssrf.NewDialer(ssrf.NoPrivateRanges())
if d == nil {
t.Fatal("New returned nil")
}
}
func TestDialer_DialContext(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer func() { _ = ln.Close() }()
go acceptAndClose(ln)
_, port, _ := net.SplitHostPort(ln.Addr().String())
d := ssrf.NewDialer()
conn, err := d.DialContext(context.Background(), "tcp", "127.0.0.1:"+port)
if err != nil {
t.Fatalf("expected connection to succeed, got: %v", err)
}
_ = conn.Close()
}
func TestDialer_DialContext_BlocksPrivate(t *testing.T) {
d := ssrf.NewDialer(ssrf.NoPrivateRanges())
_, err := d.DialContext(context.Background(), "tcp", "127.0.0.1:80")
checkSSRFError(t, err, "private or reserved")
}
// ---- CheckIP ----------------------------------------------------------------
func TestDialer_CheckIP_AllowsPublic(t *testing.T) {
d := ssrf.NewDialer(ssrf.NoPrivateRanges())
if err := d.CheckIP(net.ParseIP("109.205.61.17")); err != nil {
t.Errorf("CheckIP should allow public IP, got: %v", err)
}
}
func TestDialer_CheckIP_BlocksPrivate(t *testing.T) {
d := ssrf.NewDialer(ssrf.NoPrivateRanges())
err := d.CheckIP(net.ParseIP("10.0.0.1"))
checkSSRFError(t, err, "private or reserved")
}
func TestDialer_CheckIP_BlocksCGNAT(t *testing.T) {
d := ssrf.NewDialer(ssrf.NoPrivateRanges())
err := d.CheckIP(net.ParseIP("100.100.100.100"))
checkSSRFError(t, err, "private or reserved")
}
func TestDialer_CheckIP_BlocksDenied(t *testing.T) {
d := ssrf.NewDialer(ssrf.DenyCIDR("203.0.113.0/24"))
err := d.CheckIP(net.ParseIP("203.0.113.5"))
checkSSRFError(t, err, "denied range")
}
func TestDialer_CheckIP_RespectsAllow(t *testing.T) {
d := ssrf.NewDialer(ssrf.AllowCIDR("10.0.0.0/8"))
if err := d.CheckIP(net.ParseIP("10.1.2.3")); err != nil {
t.Errorf("CheckIP should allow IP in allowed range, got: %v", err)
}
err := d.CheckIP(net.ParseIP("192.168.1.1"))
checkSSRFError(t, err, "not in any allowed range")
}
func TestDialer_CheckIP_NormalisesIPv4Mapped(t *testing.T) {
d := ssrf.NewDialer(ssrf.NoPrivateRanges())
// ::ffff:127.0.0.1 should be normalised to 127.0.0.1 and blocked.
ip := net.ParseIP("::ffff:127.0.0.1")
err := d.CheckIP(ip)
checkSSRFError(t, err, "private or reserved")
}
// ---- WithDialer -------------------------------------------------------------
func TestWithDialer_UsesProvidedDialer(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer func() { _ = ln.Close() }()
go acceptAndClose(ln)
_, port, _ := net.SplitHostPort(ln.Addr().String())
base := &net.Dialer{Timeout: 5 * time.Second}
d := ssrf.NewDialer(ssrf.WithDialer(base))
conn, err := d.DialContext(context.Background(), "tcp", "127.0.0.1:"+port)
if err != nil {
t.Fatalf("expected connection with custom dialer, got: %v", err)
}
_ = conn.Close()
}
// ---- network parameter / option mismatch ----------------------------------
func TestDialContext_IPv4Only_RejectsTCP6(t *testing.T) {
d := ssrf.NewDialer(ssrf.IPv4Only())
_, err := d.DialContext(context.Background(), "tcp6", "example.test:80")
checkSSRFError(t, err, "incompatible with IPv4Only")
}
func TestDialContext_IPv6Only_RejectsTCP4(t *testing.T) {
d := ssrf.NewDialer(ssrf.IPv6Only())
_, err := d.DialContext(context.Background(), "tcp4", "example.test:80")
checkSSRFError(t, err, "incompatible with IPv6Only")
}
func TestDialContext_IPv4Only_AllowsTCP4(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
defer func() { _ = ln.Close() }()
go acceptAndClose(ln)
_, port, _ := net.SplitHostPort(ln.Addr().String())
resolver := &mockdns.Resolver{Zones: map[string]mockdns.Zone{
"ipv4match.test.": {A: []string{"127.0.0.1"}},
}}
d := ssrf.NewDialer(ssrf.IPv4Only(), ssrf.WithResolver(resolver))
conn, err := d.DialContext(context.Background(), "tcp4", "ipv4match.test:"+port)
if err != nil {
t.Fatalf("IPv4Only with tcp4 should succeed: %v", err)
}
_ = conn.Close()
}
// ---- IPv4Only + IPv6Only mutual exclusion -----------------------------------
func TestIPv4OnlyAndIPv6Only_Panics(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Error("expected panic when both IPv4Only and IPv6Only are set")
}
}()
ssrf.NewDialer(ssrf.IPv4Only(), ssrf.IPv6Only())
}
func TestIPv4OnlyAndIPv6Only_PanicsViaDialContext(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Error("expected panic when both IPv4Only and IPv6Only are set via DialContext")
}
}()
ssrf.DialContext(ssrf.IPv4Only(), ssrf.IPv6Only())
}
// ---- AllowCIDR panic on bad CIDR -------------------------------------------
func TestAllowCIDR_PanicOnBadCIDR(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Error("expected panic for invalid CIDR in AllowCIDR")
}
}()
ssrf.AllowCIDR("not-a-cidr")
}
// ---- DenyCIDR panic on bad CIDR --------------------------------------------
func TestDenyCIDR_PanicOnBadCIDR(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Error("expected panic for invalid CIDR in DenyCIDR")
}
}()
ssrf.DenyCIDR("not-a-cidr")
}
// ---- helpers ---------------------------------------------------------------
// hermeticDialer returns a *net.Dialer whose Control hook returns an error
// before the connect syscall fires, so tests exercising the DialContext path
// against a "public" IP never actually send a packet over the network.
func hermeticDialer() *net.Dialer {
return &net.Dialer{
Control: func(network, address string, c syscall.RawConn) error {
return errors.New("hermetic: blocking real network dial")
},
}
}
func isSsrfError(err error) bool {
if err == nil {
return false
}
var ssrfErr *ssrf.Error
return errors.As(err, &ssrfErr)
}
func checkSSRFError(t *testing.T, err error, wantSubstr string) {
t.Helper()
if err == nil {
t.Fatalf("expected an ssrf.Error containing %q, got nil", wantSubstr)
}
var ssrfErr *ssrf.Error
if !errors.As(err, &ssrfErr) {
t.Fatalf("expected *ssrf.Error, got %T: %v", err, err)
}
if !strings.Contains(ssrfErr.Reason, wantSubstr) {
t.Errorf("ssrf.Error.Reason = %q; want it to contain %q", ssrfErr.Reason, wantSubstr)
}
}
// acceptAndClose drains a listener by accepting and immediately closing every
// incoming connection. It returns when the listener is closed.
func acceptAndClose(ln net.Listener) {
for {
c, err := ln.Accept()
if err != nil {
return
}
_ = c.Close()
}
}