-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintegration_test.go
More file actions
393 lines (341 loc) · 10.2 KB
/
Copy pathintegration_test.go
File metadata and controls
393 lines (341 loc) · 10.2 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
package main
import (
"context"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
func startTestProxy(t *testing.T, allowInternal, allowDNSRebinding bool) (string, func()) {
t.Helper()
proxy := NewSSRFProxy()
proxy.blockInternalIPs = !allowInternal
proxy.blockDNSRebinding = !allowDNSRebinding
proxy.verbose = false
proxy.timeoutDuration = 5 * time.Second
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("listen: %v", err)
}
server := &http.Server{
Handler: http.HandlerFunc(proxy.rootHandler),
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 30 * time.Second,
}
go func() {
_ = server.Serve(ln)
}()
baseURL := "http://" + ln.Addr().String()
client := &http.Client{Timeout: 2 * time.Second}
deadline := time.Now().Add(5 * time.Second)
for {
resp, err := client.Get(baseURL + "/health")
if err == nil {
resp.Body.Close()
break
}
if time.Now().After(deadline) {
server.Close()
t.Fatalf("Server failed to start within timeout: %v", err)
}
time.Sleep(50 * time.Millisecond)
}
cleanup := func() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_ = server.Shutdown(ctx)
}
return baseURL, cleanup
}
func TestIntegrationHealthCheck(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
baseURL, cleanup := startTestProxy(t, false, false)
defer cleanup()
resp, err := http.Get(baseURL + "/health")
if err != nil {
t.Fatalf("Health check failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("Expected status 200, got %d", resp.StatusCode)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
t.Fatalf("Failed to read response body: %v", err)
}
if !strings.Contains(string(body), "healthy") {
t.Errorf("Expected health response to contain 'healthy', got: %s", string(body))
}
}
func TestIntegrationBlockInternalIPs(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
testCases := []struct {
name string
allowInternal bool
targetURL string
expectBlocked bool
}{
{"Block localhost strict", false, "http://127.0.0.1:9/test", true},
{"Block private IP strict", false, "http://192.168.1.1/test", true},
{"Allow localhost permissive", true, "http://127.0.0.1:9/test", false},
{"Block decimal loopback", false, "http://2130706433/", true},
{"Block unspecified", false, "http://0.0.0.0/", true},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
baseURL, cleanup := startTestProxy(t, tc.allowInternal, false)
defer cleanup()
client := &http.Client{Timeout: 5 * time.Second}
req, err := http.NewRequest("GET", baseURL+"/", nil)
if err != nil {
t.Fatalf("Failed to create request: %v", err)
}
req.Header.Set("X-Target-URL", tc.targetURL)
resp, err := client.Do(req)
if err != nil {
t.Fatalf("Request failed: %v", err)
}
defer resp.Body.Close()
if tc.expectBlocked {
if resp.StatusCode != http.StatusForbidden {
body, _ := io.ReadAll(resp.Body)
t.Errorf("Expected status 403 (blocked), got %d. Body: %s", resp.StatusCode, string(body))
}
} else if resp.StatusCode == http.StatusForbidden {
t.Errorf("Expected request to be allowed, got 403 (blocked)")
}
})
}
}
func TestIntegrationUncommonMethods(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, "ok")
}))
defer upstream.Close()
baseURL, cleanup := startTestProxy(t, true, true)
defer cleanup()
testCases := []struct {
method string
expectBlocked bool
}{
{"GET", false},
{"DELETE", false},
{"HEAD", false},
{"TRACE", true},
{"CONNECT", true},
{"OPTIONS", true},
}
client := &http.Client{Timeout: 5 * time.Second}
for _, tc := range testCases {
t.Run(tc.method, func(t *testing.T) {
req, err := http.NewRequest(tc.method, baseURL+"/", nil)
if err != nil {
t.Fatalf("Failed to create request: %v", err)
}
req.Header.Set("X-Target-URL", upstream.URL)
resp, err := client.Do(req)
if err != nil {
t.Fatalf("Request failed: %v", err)
}
defer resp.Body.Close()
if tc.expectBlocked {
if resp.StatusCode != http.StatusForbidden {
t.Errorf("Method %s should be blocked (403), got %d", tc.method, resp.StatusCode)
}
} else if resp.StatusCode == http.StatusForbidden {
body, _ := io.ReadAll(resp.Body)
t.Errorf("Method %s should be allowed, got 403. Body: %s", tc.method, string(body))
}
})
}
}
func TestIntegrationCustomHeaders(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, "ok")
}))
defer upstream.Close()
baseURL, cleanup := startTestProxy(t, true, true)
defer cleanup()
// External via header should work when internals are allowed for httptest hosts.
client := &http.Client{Timeout: 5 * time.Second}
req, err := http.NewRequest("GET", baseURL+"/", nil)
if err != nil {
t.Fatal(err)
}
req.Header.Set("X-Target-URL", upstream.URL)
resp, err := client.Do(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode == http.StatusForbidden {
t.Fatalf("expected allowed upstream, got 403")
}
strictURL, strictCleanup := startTestProxy(t, false, false)
defer strictCleanup()
for _, target := range []string{"http://127.0.0.1:9/test", "http://192.168.1.1/test"} {
req, err := http.NewRequest("GET", strictURL+"/", nil)
if err != nil {
t.Fatal(err)
}
req.Header.Set("X-Target-URL", target)
resp, err := client.Do(req)
if err != nil {
t.Fatal(err)
}
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
if resp.StatusCode != http.StatusForbidden {
t.Fatalf("expected 403 for %s, got %d body=%s", target, resp.StatusCode, body)
}
}
}
func TestIntegrationDNSRebinding(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
testCases := []struct {
name string
allowDNSRebinding bool
targetURL string
expectBlocked bool
}{
{"DNS rebinding strict", false, "http://127.0.0.1.evil.example/test", true},
{"DNS rebinding permissive", true, "http://127.0.0.1.evil.example/test", false},
{"Localhost subdomain strict", false, "http://localhost.evil.example/test", true},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
baseURL, cleanup := startTestProxy(t, true, tc.allowDNSRebinding)
defer cleanup()
client := &http.Client{Timeout: 5 * time.Second}
req, err := http.NewRequest("GET", baseURL+"/", nil)
if err != nil {
t.Fatalf("Failed to create request: %v", err)
}
req.Header.Set("X-Target-URL", tc.targetURL)
resp, err := client.Do(req)
if err != nil {
t.Fatalf("Request failed: %v", err)
}
defer resp.Body.Close()
if tc.expectBlocked {
if resp.StatusCode != http.StatusForbidden {
body, _ := io.ReadAll(resp.Body)
t.Errorf("Expected 403 (blocked), got %d. Body: %s", resp.StatusCode, string(body))
}
} else if resp.StatusCode == http.StatusForbidden {
body, _ := io.ReadAll(resp.Body)
t.Errorf("Expected allowed, got 403. Body: %s", string(body))
}
})
}
}
func TestIntegrationPathMode(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
baseURL, cleanup := startTestProxy(t, false, false)
defer cleanup()
resp, err := http.Get(baseURL + "/http://127.0.0.1/")
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusForbidden {
body, _ := io.ReadAll(resp.Body)
t.Fatalf("path mode should block internal target, got %d body=%s", resp.StatusCode, body)
}
}
func TestIntegrationRedirectChain(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
internalHit := false
internal := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
internalHit = true
fmt.Fprint(w, "PWNED")
}))
defer internal.Close()
external := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, internal.URL, http.StatusFound)
}))
defer external.Close()
proxy := NewSSRFProxy()
firstHop := external.Listener.Addr().String()
client := &http.Client{
Timeout: 5 * time.Second,
Transport: &http.Transport{
DisableKeepAlives: true,
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
if addr == firstHop {
return (&net.Dialer{}).DialContext(ctx, network, addr)
}
return proxy.safeDialContext(ctx, network, addr)
},
},
CheckRedirect: func(req *http.Request, via []*http.Request) error {
req.Header.Del("X-Target-URL")
detections := proxy.validateRedirect(req)
if len(detections) > 0 {
return &ssrfBlockError{detections: detections, reason: "SSRF detected in redirect"}
}
return nil
},
}
resp, err := client.Get(external.URL)
if resp != nil {
io.Copy(io.Discard, resp.Body)
resp.Body.Close()
}
if internalHit {
t.Fatal("redirect to internal server was followed")
}
if err == nil {
t.Fatal("expected SSRF block error on redirect")
}
}
func TestIntegrationExternalService(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, "ok")
}))
defer upstream.Close()
baseURL, cleanup := startTestProxy(t, true, true)
defer cleanup()
client := &http.Client{Timeout: 10 * time.Second}
req, err := http.NewRequest("GET", baseURL+"/", nil)
if err != nil {
t.Fatalf("Failed to create request: %v", err)
}
req.Header.Set("X-Target-URL", upstream.URL)
resp, err := client.Do(req)
if err != nil {
t.Fatalf("request failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusForbidden {
body, _ := io.ReadAll(resp.Body)
t.Errorf("External service was blocked: %s", string(body))
}
}