forked from signalsciences/sigsci-module-golang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
module_test.go
483 lines (438 loc) · 14.8 KB
/
module_test.go
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
package sigsci
import (
"bufio"
"bytes"
"crypto/tls"
"fmt"
"net/http"
"net/http/httptest"
"net/http/httputil"
"reflect"
"strconv"
"strings"
"testing"
"time"
)
func TestNewRPCMsgInWithModuleConfigFromRequest(t *testing.T) {
c, err := NewModuleConfig(
AllowUnknownContentLength(true),
ServerFlavor("SugarAndSpice"),
AltResponseCodes(403),
AnomalyDuration(10*time.Second),
AnomalySize(8192),
CustomInspector(&RPCInspector{}, func(_ *http.Request) bool { return true }, func(_ *http.Request) {}),
CustomHeaderExtractor(func(_ *http.Request) (http.Header, error) { return nil, nil }),
Debug(true),
MaxContentLength(500000),
Socket("tcp", "0.0.0.0:1234"),
Timeout(10*time.Millisecond),
)
if err != nil {
t.Fatalf("Failed to create module config: %s", err)
}
b := bytes.Buffer{}
b.WriteString("test")
r, err := http.NewRequest("GET", "http://localhost/", &b)
if err != nil {
t.Fatal(err)
}
r.RemoteAddr = "127.0.0.1"
r.Header.Add("If-None-Match", `W/"wyzzy"`)
r.RequestURI = "http://localhost/"
r.TLS = &tls.ConnectionState{}
want := RPCMsgIn{
ServerName: "localhost",
ServerFlavor: "SugarAndSpice",
Method: "GET",
Scheme: "https",
URI: "http://localhost/",
Protocol: "HTTP/1.1",
RemoteAddr: "127.0.0.1",
HeadersIn: [][2]string{{"Host", "localhost"}, {"If-None-Match", `W/"wyzzy"`}},
}
eq := func(got, want RPCMsgIn) (ne string, equal bool) {
switch {
case got.ServerName != want.ServerName:
return "ServerHostname", false
case got.Method != want.Method:
return "Method", false
case got.Scheme != want.Scheme:
return "Scheme", false
case got.URI != want.URI:
return "URI", false
case got.Protocol != want.Protocol:
return "Protocol", false
case got.RemoteAddr != want.RemoteAddr:
return "RemoteAddr", false
case !reflect.DeepEqual(got.HeadersIn, want.HeadersIn):
return "HeadersIn", false
case got.ServerFlavor != want.ServerFlavor:
return "ServerFlavor", false
default:
return "", true
}
}
got := NewRPCMsgInWithModuleConfig(c, r, nil)
if ne, equal := eq(*got, want); !equal {
t.Errorf("NewRPCMsgInWithModuleConfig: incorrect %q", ne)
}
}
func TestNewRPCMsgFromRequest(t *testing.T) {
b := bytes.Buffer{}
b.WriteString("test")
r, err := http.NewRequest("GET", "http://localhost/", &b)
if err != nil {
t.Fatal(err)
}
r.RemoteAddr = "127.0.0.1"
r.Header.Add("If-None-Match", `W/"wyzzy"`)
r.RequestURI = "http://localhost/"
r.TLS = &tls.ConnectionState{}
want := RPCMsgIn{
ServerName: "localhost",
Method: "GET",
Scheme: "https",
URI: "http://localhost/",
Protocol: "HTTP/1.1",
RemoteAddr: "127.0.0.1",
HeadersIn: [][2]string{{"Host", "localhost"}, {"If-None-Match", `W/"wyzzy"`}},
}
eq := func(got, want RPCMsgIn) (ne string, equal bool) {
switch {
case got.ServerName != want.ServerName:
return "ServerHostname", false
case got.Method != want.Method:
return "Method", false
case got.Scheme != want.Scheme:
return "Scheme", false
case got.URI != want.URI:
return "URI", false
case got.Protocol != want.Protocol:
return "Protocol", false
case got.RemoteAddr != want.RemoteAddr:
return "RemoteAddr", false
case !reflect.DeepEqual(got.HeadersIn, want.HeadersIn):
return "HeadersIn", false
default:
return "", true
}
}
got := NewRPCMsgIn(r, nil, -1, -1, -1, "", "")
if ne, equal := eq(*got, want); !equal {
t.Errorf("NewRPCMsgIn: incorrect %q", ne)
}
}
// helper functions
func TestStripPort(t *testing.T) {
cases := []struct {
want string
content string
}{
// Invalid, should not change
{"", ""},
{"foo:bar:baz", "foo:bar:baz"},
// Valid, should have port removed if exists
{"127.0.0.1", "127.0.0.1"},
{"127.0.0.1", "127.0.0.1:8000"},
}
for pos, tt := range cases {
got := stripPort(tt.content)
if got != tt.want {
t.Errorf("test %d: StripPort(%q) = %q, want %q", pos, tt.content, got, tt.want)
}
}
}
func TestShouldReadBody(t *testing.T) {
m, err := NewModule(
http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
status := http.StatusOK
http.Error(w, fmt.Sprintf("%d %s\n", status, http.StatusText(status)), status)
}),
MaxContentLength(20),
)
if err != nil {
t.Fatalf("Failed to create module: %s", err)
}
cases := []struct {
want bool
genreq func() []byte
}{
// No C-T
{false, func() []byte {
return genTestRequest("GET", "http://example.com/", "", "")
}},
// Invalid C-T
{false, func() []byte {
return genTestRequest("GET", "http://example.com/", "bad/type", `{}`)
}},
// Zero length
{false, func() []byte {
return genTestRequest("GET", "http://example.com/", "application/json", ``)
}},
// Too long
{false, func() []byte {
return genTestRequest("GET", "http://example.com/", "application/json", `{"foo":"12345678901234567890"}`)
}},
// Good to read
{true, func() []byte {
return genTestRequest("GET", "http://example.com/", "application/json", `{}`)
}},
}
for pos, tt := range cases {
req, err := requestParseRaw("127.0.0.1:59000", tt.genreq())
if err != nil {
t.Fatalf("Failed to generate request: %s", err)
}
got := shouldReadBody(req, m)
if got != tt.want {
t.Errorf("test %d: expected %v got %v", pos, tt.want, got)
}
}
}
func TestConvertHeaders(t *testing.T) {
cases := []struct {
want [][2]string // Only the order of like keys matters
content http.Header // Order of values matter
}{
// Empty
{
[][2]string{},
http.Header{},
},
// Single values
{
[][2]string{
{http.CanonicalHeaderKey("a"), "val a"},
{http.CanonicalHeaderKey("b"), "val b"},
}, http.Header{
http.CanonicalHeaderKey("a"): {"val a"},
http.CanonicalHeaderKey("b"): {"val b"},
},
},
// Multiple values
{
[][2]string{
{http.CanonicalHeaderKey("a"), "val a"},
{http.CanonicalHeaderKey("b"), "val b1"},
{http.CanonicalHeaderKey("b"), "val b2"},
}, http.Header{
http.CanonicalHeaderKey("a"): {"val a"},
http.CanonicalHeaderKey("b"): {"val b1", "val b2"},
},
},
}
for pos, tt := range cases {
got := convertHeaders(tt.content)
// Convert result back to a http.Header for comparison
hmap := http.Header{}
for _, v := range got {
hmap.Add(v[0], v[1])
}
if !reflect.DeepEqual(tt.content, hmap) {
t.Errorf("test %d: expected %#v, got %#v", pos, tt.content, hmap)
}
}
}
func TestInspectableContentType(t *testing.T) {
cases := []struct {
want bool
content string
}{
{true, "application/x-www-form-urlencoded"},
{true, "application/x-www-form-urlencoded; charset=UTF-8"},
{true, "multipart/form-data"},
{true, "text/xml"},
{true, "application/xml"},
{true, "text/xml;charset=UTF-8"},
{true, "application/xml; charset=iso-2022-kr"},
{true, "application/rss+xml"},
{true, "application/json"},
{true, "application/x-javascript"},
{true, "text/javascript"},
{true, "text/x-javascript"},
{true, "text/x-json"},
{true, "application/javascript"},
{true, "application/graphql"},
{false, "octet/stream"},
{false, "junk/yard"},
}
for pos, tt := range cases {
got := inspectableContentType(tt.content)
if got != tt.want {
t.Errorf("test %d: expected %v got %v", pos, tt.want, got)
}
}
}
func TestModule(t *testing.T) {
cases := []struct {
req []byte // Raw HTTP request
resp int32 // Inspection response
tags string // Any tags in the PreRequest call
}{
{genTestRequest("GET", "http://example.com/", "", ""), 200, ""},
{genTestRequest("GET", "http://example.com/", "", ""), 406, "XSS"},
{genTestRequest("GET", "http://example.com/", "", ""), 403, "XSS"},
{genTestRequest("GET", "http://example.com/", "", ""), 500, "XSS"},
{genTestRequest("GET", "http://example.com/", "", ""), 200, ""},
{genTestRequest("OPTIONS", "http://example.com/", "", ""), 200, ""},
{genTestRequest("OPTIONS", "http://example.com/", "", ""), 406, "XSS"},
{genTestRequest("OPTIONS", "http://example.com/", "", ""), 403, "XSS"},
{genTestRequest("OPTIONS", "http://example.com/", "", ""), 500, "XSS"},
{genTestRequest("OPTIONS", "http://example.com/", "", ""), 200, ""},
{genTestRequest("CONNECT", "http://example.com/", "", ""), 200, ""},
{genTestRequest("CONNECT", "http://example.com/", "", ""), 406, "XSS"},
{genTestRequest("CONNECT", "http://example.com/", "", ""), 403, "XSS"},
{genTestRequest("CONNECT", "http://example.com/", "", ""), 500, "XSS"},
{genTestRequest("CONNECT", "http://example.com/", "", ""), 200, ""},
{genTestRequest("POST", "http://example.com/", "application/x-www-form-urlencoded", "a=1"), 200, ""},
{genTestRequest("POST", "http://example.com/", "application/x-www-form-urlencoded", "a=1"), 406, "XSS"},
{genTestRequest("POST", "http://example.com/", "application/x-www-form-urlencoded", "a=1"), 403, "XSS"},
{genTestRequest("POST", "http://example.com/", "application/x-www-form-urlencoded", "a=1"), 500, "XSS"},
{genTestRequest("POST", "http://example.com/", "application/x-www-form-urlencoded", "a=1"), 200, ""},
{genTestRequest("PUT", "http://example.com/", "application/x-www-form-urlencoded", "a=1"), 200, ""},
{genTestRequest("PUT", "http://example.com/", "application/x-www-form-urlencoded", "a=1"), 406, "XSS"},
{genTestRequest("PUT", "http://example.com/", "application/x-www-form-urlencoded", "a=1"), 403, "XSS"},
{genTestRequest("PUT", "http://example.com/", "application/x-www-form-urlencoded", "a=1"), 500, "XSS"},
{genTestRequest("PUT", "http://example.com/", "application/x-www-form-urlencoded", "a=1"), 200, ""},
{genTestRequest("POST", "http://example.com/", "text/xml;charset=UTF-8", `<a>1</a>`), 200, ""},
{genTestRequest("POST", "http://example.com/", "text/xml;charset=UTF-8", `<a>1</a>`), 406, "XSS"},
{genTestRequest("POST", "http://example.com/", "text/xml;charset=UTF-8", `<a>1</a>`), 403, "XSS"},
{genTestRequest("POST", "http://example.com/", "text/xml;charset=UTF-8", `<a>1</a>`), 500, "XSS"},
{genTestRequest("POST", "http://example.com/", "text/xml;charset=UTF-8", `<a>1</a>`), 200, ""},
{genTestRequest("POST", "http://example.com/", "application/xml; charset=iso-2022-kr", `<a>1</a>`), 200, ""},
{genTestRequest("POST", "http://example.com/", "application/xml; charset=iso-2022-kr", `<a>1</a>`), 406, "XSS"},
{genTestRequest("POST", "http://example.com/", "application/xml; charset=iso-2022-kr", `<a>1</a>`), 403, "XSS"},
{genTestRequest("POST", "http://example.com/", "application/xml; charset=iso-2022-kr", `<a>1</a>`), 500, "XSS"},
{genTestRequest("POST", "http://example.com/", "application/xml; charset=iso-2022-kr", `<a>1</a>`), 200, ""},
{genTestRequest("POST", "http://example.com/", "application/rss+xml", `<a>1</a>`), 200, ""},
{genTestRequest("POST", "http://example.com/", "application/rss+xml", `<a>1</a>`), 406, "XSS"},
{genTestRequest("POST", "http://example.com/", "application/rss+xml", `<a>1</a>`), 403, "XSS"},
{genTestRequest("POST", "http://example.com/", "application/rss+xml", `<a>1</a>`), 500, "XSS"},
{genTestRequest("POST", "http://example.com/", "application/rss+xml", `<a>1</a>`), 200, ""},
{genTestRequest("POST", "http://example.com/", "application/graphql", `{}`), 200, ""},
}
for pos, tt := range cases {
respstr := strconv.Itoa(int(tt.resp))
m, err := NewModule(
http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
status := http.StatusOK
http.Error(w, fmt.Sprintf("%d %s\n", status, http.StatusText(status)), status)
}),
Timeout(500*time.Millisecond),
AltResponseCodes(403, 500),
Debug(true),
CustomInspector(newTestInspector(tt.resp, tt.tags), nil, nil),
)
if err != nil {
t.Fatalf("test %d: Failed to create module: %s", pos, err)
}
req, err := requestParseRaw("127.0.0.1:12345", tt.req)
if err != nil {
t.Fatalf("test %d: Failed to parse request: %s\n%s", pos, err, tt.req)
}
if dump, err := httputil.DumpRequest(req, true); err == nil {
t.Log("CLIENT REQUEST:\n" + string(dump))
}
if hv := req.Header.Get(`X-Sigsci-Agentresponse`); hv != "" {
t.Errorf("test %d: unexpected request header %s=%s", pos, `X-Sigsci-Agentresponse`, hv)
}
w := httptest.NewRecorder()
m.ServeHTTP(w, req)
resp := w.Result()
if dump, err := httputil.DumpRequest(req, true); err == nil {
t.Log("SERVER REQUEST:\n" + string(dump))
}
if hv := req.Header.Get(`X-Sigsci-Agentresponse`); hv == "" || hv != respstr {
t.Errorf("test %d: unexpected request header %s=%s, expected %q", pos, `X-Sigsci-Agentresponse`, hv, respstr)
}
if len(tt.tags) > 0 {
if hv := req.Header.Get(`X-Sigsci-Requestid`); hv == "" {
t.Errorf("test %d: expected request header %s=%s", pos, `X-Sigsci-Requestid`, hv)
}
}
if dump, err := httputil.DumpResponse(resp, true); err == nil {
t.Log("SERVER RESPONSE:\n" + string(dump))
}
if resp.StatusCode != int(tt.resp) {
t.Errorf("test %d: unexpected status code=%d, expected=%d", pos, resp.StatusCode, tt.resp)
}
}
}
func genTestRequest(meth, uri, ctype, payload string) []byte {
var err error
var req *http.Request
if len(payload) > 0 {
req, err = http.NewRequest(meth, uri, strings.NewReader(payload))
if err != nil {
panic(err)
}
} else {
req, err = http.NewRequest(meth, uri, nil)
if err != nil {
panic(err)
}
}
req.Header.Set(`User-Agent`, `SigSci Module Tester/0.1`)
if len(ctype) > 0 {
req.Header.Set(`Content-Type`, ctype)
}
// This will add some extra headers typically added by the client
dump, err := httputil.DumpRequestOut(req, true)
if err != nil {
panic(err)
}
return dump
}
// requestParseRaw creates a request from the given raw HTTP data
func requestParseRaw(raddr string, raw []byte) (*http.Request, error) {
req, err := http.ReadRequest(bufio.NewReader(bytes.NewReader(raw)))
if err != nil {
return nil, err
}
// Set fields typically set by the server
req.RemoteAddr = raddr
return req, nil
}
// testInspector is a custom inspector that calls the simulator
// harness within the golang module
type testInspector struct {
resp int32 // Response code (200, 406, etc.)
tags string // EX: "XSS" (csv)
}
func newTestInspector(resp int32, tags string) *testInspector {
return &testInspector{
resp: resp,
tags: tags,
}
}
func (insp *testInspector) ModuleInit(in *RPCMsgIn, out *RPCMsgOut) error {
out.WAFResponse = 200
out.RequestID = ""
out.RequestHeaders = nil
return nil
}
func (insp *testInspector) PreRequest(in *RPCMsgIn, out *RPCMsgOut) error {
out.WAFResponse = insp.resp
if len(insp.tags) > 0 {
out.RequestID = "0123456789abcdef01234567"
out.RequestHeaders = [][2]string{
{"X-SigSci-Tags", insp.tags},
}
} else {
out.RequestID = ""
out.RequestHeaders = nil
}
return nil
}
func (insp *testInspector) PostRequest(in *RPCMsgIn, out *RPCMsgOut) error {
out.WAFResponse = insp.resp
out.RequestID = ""
out.RequestHeaders = nil
return nil
}
func (insp *testInspector) UpdateRequest(in *RPCMsgIn2, out *RPCMsgOut) error {
out.WAFResponse = insp.resp
out.RequestID = ""
out.RequestHeaders = nil
return nil
}