-
Notifications
You must be signed in to change notification settings - Fork 107
/
Copy pathnmap_test.go
563 lines (475 loc) · 11.6 KB
/
nmap_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
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
package nmap
import (
"bytes"
"context"
"encoding/xml"
"fmt"
"io/ioutil"
"os"
"os/exec"
"reflect"
"strings"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
type testStreamer struct{}
// Write is a function that handles the normal nmap stdout.
func (c *testStreamer) Write(d []byte) (int, error) {
return len(d), nil
}
func TestNmapNotInstalled(t *testing.T) {
oldPath := os.Getenv("PATH")
_ = os.Setenv("PATH", "")
s, err := NewScanner(context.TODO())
if err == nil {
t.Error("expected NewScanner to fail if nmap is not found in $PATH")
}
if s != nil {
t.Error("expected NewScanner to return a nil scanner if nmap is not found in $PATH")
}
_ = os.Setenv("PATH", oldPath)
}
func TestRun(t *testing.T) {
nmapPath, err := exec.LookPath("nmap")
if err != nil {
panic("nmap is required to run those tests")
}
tests := []struct {
description string
options []Option
testTimeout bool
compareWholeRun bool
expectedResult *Run
expectedErr bool
expectedWarnings []string
}{
{
description: "invalid binary path",
options: []Option{
WithTargets("0.0.0.0"),
WithBinaryPath("/invalid"),
},
expectedErr: true,
expectedWarnings: []string{},
},
{
description: "output can't be parsed",
options: []Option{
WithTargets("0.0.0.0"),
WithBinaryPath("echo"),
},
expectedErr: true,
expectedWarnings: []string{"EOF"},
},
{
description: "context timeout",
options: []Option{
WithTargets("0.0.0.0/16"),
},
testTimeout: true,
expectedErr: true,
expectedWarnings: []string{},
},
{
description: "scan localhost",
options: []Option{
WithTargets("localhost"),
WithTimingTemplate(TimingFastest),
},
expectedResult: &Run{
Args: nmapPath + " -T5 -oX - localhost",
Scanner: "nmap",
},
expectedWarnings: []string{},
},
{
description: "scan invalid target",
options: []Option{
WithTimingTemplate(TimingFastest),
},
expectedWarnings: []string{"WARNING: No targets were specified, so 0 hosts scanned."},
expectedResult: &Run{
Scanner: "nmap",
Args: nmapPath + " -T5 -oX -",
},
},
{
description: "scan error resolving name",
options: []Option{
WithBinaryPath("tests/scripts/fake_nmap.sh"),
WithCustomArguments("tests/xml/scan_error_resolving_name.xml"),
},
expectedErr: true,
expectedWarnings: []string{},
expectedResult: &Run{
Scanner: "fake_nmap",
Args: "nmap test",
},
},
{
description: "scan unsupported error",
options: []Option{
WithBinaryPath("tests/scripts/fake_nmap.sh"),
WithCustomArguments("tests/xml/scan_error_other.xml"),
},
expectedErr: true,
expectedWarnings: []string{},
expectedResult: &Run{
Scanner: "fake_nmap",
Args: "nmap test",
},
},
{
description: "scan localhost with filters",
options: []Option{
WithBinaryPath("tests/scripts/fake_nmap.sh"),
WithCustomArguments("tests/xml/scan_invalid_services.xml"),
WithFilterHost(func(h Host) bool {
return len(h.Ports) == 2
}),
WithFilterPort(func(p Port) bool {
return p.Service.Product == "VALID"
}),
WithTimingTemplate(TimingFastest),
},
compareWholeRun: true,
expectedWarnings: []string{},
expectedResult: &Run{
XMLName: xml.Name{Local: "nmaprun"},
Args: "nmap test",
Scanner: "fake_nmap",
Hosts: []Host{
{
Addresses: []Address{
{
Addr: "66.35.250.168",
},
},
Ports: []Port{
{
ID: 80,
State: State{
State: "open",
},
Service: Service{
Name: "http",
Product: "VALID",
},
},
{
ID: 443,
State: State{
State: "open",
},
Service: Service{
Name: "https",
Product: "VALID",
},
},
},
},
},
},
},
}
for _, test := range tests {
t.Run(test.description, func(t *testing.T) {
ctx := context.Background()
if test.testTimeout {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(context.Background(), 99*time.Hour)
go (func() {
// Cancel context to force timeout
defer cancel()
time.Sleep(1 * time.Millisecond)
})()
}
s, err := NewScanner(ctx, test.options...)
if err != nil {
panic(err) // this is never supposed to err, as we are testing run and not new.
}
result, warns, err := s.Run()
if !assert.Equal(t, test.expectedErr, err != nil) {
return
}
assert.Equal(t, test.expectedWarnings, *warns)
if test.expectedResult == nil {
return
}
if test.compareWholeRun {
result.rawXML = nil
if !reflect.DeepEqual(test.expectedResult, result) {
t.Errorf("expected result to be %+v, got %+v", test.expectedResult, result)
}
} else {
if result.Args != test.expectedResult.Args {
t.Errorf("expected args %s got %s", test.expectedResult.Args, result.Args)
}
if result.Scanner != test.expectedResult.Scanner {
t.Errorf("expected scanner %s got %s", test.expectedResult.Scanner, result.Scanner)
}
}
})
}
}
func TestRunWithProgress(t *testing.T) {
// Open and parse sample result for testing
dat, err := ioutil.ReadFile("tests/xml/scan_base.xml")
if err != nil {
panic(err)
}
var r = &Run{}
_ = Parse(dat, r)
tests := []struct {
description string
options []Option
compareWholeRun bool
expectedResult *Run
expectedProgress []float32
expectedErr error
expectedWarnings []string
}{
{
description: "fake scan with slow output for progress streaming",
options: []Option{
WithBinaryPath("tests/scripts/fake_nmap_delay.sh"),
WithCustomArguments("tests/xml/scan_base.xml"),
},
compareWholeRun: true,
expectedResult: r,
expectedProgress: []float32{3.22, 56.66, 77.02, 81.95, 86.79, 87.84},
expectedErr: nil,
},
}
for _, test := range tests {
t.Run(test.description, func(t *testing.T) {
s, err := NewScanner(context.TODO(), test.options...)
if err != nil {
panic(err) // this is never supposed to err, as we are testing run and not new.
}
progress := make(chan float32, 5)
result, _, err := s.Progress(progress).Run()
assert.Equal(t, test.expectedErr, err)
if err != nil {
return
}
// Test if channel data compares to given progress array
var progressOutput []float32
for n := range progress {
progressOutput = append(progressOutput, n)
}
assert.Equal(t, test.expectedProgress, progressOutput)
// Test if read output equals parsed xml file
if test.compareWholeRun {
assert.Equal(t, test.expectedResult.Hosts, result.Hosts)
}
})
}
}
func TestRunWithStreamer(t *testing.T) {
streamer := &testStreamer{}
tests := []struct {
description string
options []Option
expectedErr error
expectedWarnings []string
}{
{
description: "fake scan with streaming",
options: []Option{
WithBinaryPath("tests/scripts/fake_nmap.sh"),
WithCustomArguments("tests/xml/scan_base.xml"),
},
expectedErr: nil,
expectedWarnings: []string{},
},
}
for _, test := range tests {
t.Run(test.description, func(t *testing.T) {
s, err := NewScanner(context.TODO(), test.options...)
if err != nil {
panic(err) // this is never supposed to err, as we are testing run and not new.
}
_, warnings, err := s.Streamer(streamer).Run()
assert.Equal(t, test.expectedErr, err)
assert.Equal(t, test.expectedWarnings, *warnings)
})
}
}
func TestRunAsync(t *testing.T) {
tests := []struct {
description string
options []Option
testTimeout bool
compareWholeRun bool
expectedResult *Run
expectedRunAsyncErr bool
expectedWaitErr bool
}{
{
description: "invalid binary path",
options: []Option{
WithTargets("0.0.0.0"),
WithBinaryPath("/invalid"),
},
expectedRunAsyncErr: true,
},
{
description: "output can't be parsed",
options: []Option{
WithTargets("0.0.0.0"),
WithBinaryPath("echo"),
},
expectedWaitErr: true,
},
{
description: "context timeout",
options: []Option{
WithTargets("0.0.0.0/16"),
},
testTimeout: true,
expectedWaitErr: true,
},
}
for _, test := range tests {
t.Run(test.description, func(t *testing.T) {
ctx := context.Background()
if test.testTimeout {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(context.Background(), 99*time.Hour)
go (func() {
// Cancel context to force timeout
defer cancel()
time.Sleep(10 * time.Millisecond)
})()
}
s, err := NewScanner(ctx, test.options...)
if err != nil {
panic(err) // this is never supposed to err, as we are testing run and not new.
}
done := make(chan error)
result, _, err := s.Async(done).Run()
if test.expectedRunAsyncErr {
assert.NotNil(t, err)
}
if err != nil {
return
}
err = <-done
if test.expectedWaitErr {
assert.Error(t, err)
} else {
assert.NoError(t, err)
}
if err != nil {
return
}
if test.expectedResult == nil {
return
}
if test.compareWholeRun {
result.rawXML = nil
if !reflect.DeepEqual(test.expectedResult, result) {
t.Errorf("expected result to be %+v, got %+v", test.expectedResult, result)
}
}
})
}
}
func TestCheckStdErr(t *testing.T) {
tests := []struct {
description string
stderr string
warnings []string
expectedErr error
}{
{
description: "Find no error warning",
stderr: " NoWarning \nNoWarning ",
warnings: []string{"NoWarning", "NoWarning"},
expectedErr: nil,
},
{
description: "Find malloc error",
stderr: " Malloc Failed! with ",
warnings: []string{"Malloc Failed! with"},
expectedErr: ErrMallocFailed,
},
}
for _, test := range tests {
t.Run(test.description, func(t *testing.T) {
buf := bytes.Buffer{}
_, _ = buf.Write([]byte(test.stderr))
var warnings []string
err := checkStdErr(&buf, &warnings)
assert.Equal(t, test.expectedErr, err)
assert.True(t, reflect.DeepEqual(test.warnings, warnings))
})
}
}
// Test to verify the fix for a race condition works
// See: https://github.com/Ullaakut/nmap/issues/122
func TestParseXMLOutputRaceCondition(t *testing.T) {
scans := make(chan int, 100)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var wg sync.WaitGroup
// Publish many scan orders
wg.Add(1)
go func() {
defer wg.Done()
for taskId := 0; taskId < 1000; taskId++ {
wg.Add(1)
scans <- taskId
}
}()
// Consume scan orders with workers in parallel
for worker := 1; worker <= 10; worker++ {
wg.Add(1)
go func(w int) {
defer wg.Done()
for {
var taskId int
select {
case <-ctx.Done():
t.Logf("stopping worker %d", w)
return
case i, ok := <-scans:
if !ok {
t.Logf("stopping worker %d", w)
return
}
taskId = i
default:
t.Logf("stopping worker %d", w)
return
}
_, err := getNmapVersion(ctx)
if err != nil {
t.Errorf("[w:%d] failed scan %d with err: %s", w, taskId, err)
} else {
t.Logf("[w:%d] completed scan %d", w, taskId)
}
wg.Done()
}
}(worker)
}
wg.Wait()
}
// getNmapVersion returns the version of nmap installed on the system.
// e.g. "7.80".
func getNmapVersion(ctx context.Context) (string, error) {
scanner, err := NewScanner(ctx)
if err != nil {
return "", fmt.Errorf("nmap.NewScanner: %w", err)
}
var sb strings.Builder
scanner.Streamer(&sb)
results, warnings, err := scanner.Run()
if err != nil {
return "", fmt.Errorf("nmap.Run: %w (%v). Result: %+v", err, warnings, sb.String())
}
return results.Version, nil
}