forked from Ullaakut/nmap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nmap.go
1624 lines (1381 loc) · 47.8 KB
/
nmap.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
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
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Package nmap provides idiomatic `nmap` bindings for go developers.
package nmap
import (
"bufio"
"bytes"
"context"
"encoding/xml"
"fmt"
"io"
"os/exec"
"strings"
"syscall"
"time"
"github.com/pkg/errors"
"golang.org/x/sync/errgroup"
)
// ScanRunner represents something that can run a scan.
type ScanRunner interface {
Run() (result *Run, warnings []string, err error)
}
// Streamer constantly streams the stdout.
type Streamer interface {
Write(d []byte) (int, error)
Bytes() []byte
}
// Scanner represents an Nmap scanner.
type Scanner struct {
cmd *exec.Cmd
modifySysProcAttr func(*syscall.SysProcAttr)
args []string
binaryPath string
ctx context.Context
portFilter func(Port) bool
hostFilter func(Host) bool
stderr, stdout bufio.Scanner
}
// Option is a function that is used for grouping of Scanner options.
// Option adds or removes nmap command line arguments.
type Option func(*Scanner)
// NewScanner creates a new Scanner, and can take options to apply to the scanner.
func NewScanner(options ...Option) (*Scanner, error) {
scanner := &Scanner{}
for _, option := range options {
option(scanner)
}
if scanner.binaryPath == "" {
var err error
scanner.binaryPath, err = exec.LookPath("nmap")
if err != nil {
return nil, ErrNmapNotInstalled
}
}
if scanner.ctx == nil {
scanner.ctx = context.Background()
}
return scanner, nil
}
// Run runs nmap synchronously and returns the result of the scan.
func (s *Scanner) Run() (result *Run, warnings []string, err error) {
var (
stdout, stderr bytes.Buffer
resume bool
)
args := s.args
for _, arg := range args {
if arg == "--resume" {
resume = true
break
}
}
if !resume {
// Enable XML output
args = append(args, "-oX")
// Get XML output in stdout instead of writing it in a file
args = append(args, "-")
}
// Prepare nmap process
cmd := exec.Command(s.binaryPath, args...)
cmd.SysProcAttr = &syscall.SysProcAttr{HideWindow: true}
if s.modifySysProcAttr != nil {
s.modifySysProcAttr(cmd.SysProcAttr)
}
cmd.Stdout = &stdout
cmd.Stderr = &stderr
// Run nmap process
err = cmd.Start()
if err != nil {
return nil, warnings, err
}
// Make a goroutine to notify the select when the scan is done.
done := make(chan error, 1)
go func() {
done <- cmd.Wait()
}()
// Wait for nmap process or timeout
select {
case <-s.ctx.Done():
// Context was done before the scan was finished.
// The process is killed and a timeout error is returned.
_ = cmd.Process.Kill()
return nil, warnings, ErrScanTimeout
case <-done:
// Process nmap stderr output containing none-critical errors and warnings
// Everyone needs to check whether one or some of these warnings is a hard issue in their use case
if stderr.Len() > 0 {
warnings = strings.Split(strings.Trim(stderr.String(), "\n"), "\n")
}
// Check for warnings that will inevitably lead to parsing errors, hence, have priority.
if err := analyzeWarnings(warnings); err != nil {
return nil, warnings, err
}
// Parse nmap xml output. Usually nmap always returns valid XML, even if there is a scan error.
// Potentially available warnings are returned too, but probably not the reason for a broken XML.
result, err := Parse(stdout.Bytes())
if err != nil {
warnings = append(warnings, err.Error()) // Append parsing error to warnings for those who are interested.
return nil, warnings, ErrParseOutput
}
// Critical scan errors are reflected in the XML.
if result != nil && len(result.Stats.Finished.ErrorMsg) > 0 {
switch {
case strings.Contains(result.Stats.Finished.ErrorMsg, "Error resolving name"):
return result, warnings, ErrResolveName
// TODO: Add cases for other known errors we might want to guard.
default:
return result, warnings, fmt.Errorf(result.Stats.Finished.ErrorMsg)
}
}
// Call filters if they are set.
if s.portFilter != nil {
result = choosePorts(result, s.portFilter)
}
if s.hostFilter != nil {
result = chooseHosts(result, s.hostFilter)
}
// Return result, optional warnings but no error
return result, warnings, nil
}
}
// RunWithProgress runs nmap synchronously and returns the result of the scan.
// It needs a channel to constantly stream the progress.
func (s *Scanner) RunWithProgress(liveProgress chan<- float32) (result *Run, warnings []string, err error) {
var stdout, stderr bytes.Buffer
args := s.args
// Enable XML output.
args = append(args, "-oX")
// Get XML output in stdout instead of writing it in a file.
args = append(args, "-")
// Enable progress output every second.
args = append(args, "--stats-every", "1s")
// Prepare nmap process.
cmd := exec.Command(s.binaryPath, args...)
if s.modifySysProcAttr != nil {
s.modifySysProcAttr(cmd.SysProcAttr)
}
cmd.Stderr = &stderr
cmd.Stdout = &stdout
// Run nmap process.
err = cmd.Start()
if err != nil {
return nil, warnings, err
}
// Make a goroutine to notify the select when the scan is done.
done := make(chan error, 1)
doneProgress := make(chan bool, 1)
go func() {
done <- cmd.Wait()
}()
// Make goroutine to check the progress every second.
// Listening for channel doneProgress.
go func() {
type progress struct {
TaskProgress []TaskProgress `xml:"taskprogress" json:"task_progress"`
}
p := &progress{}
for {
select {
case <-doneProgress:
close(liveProgress)
return
default:
time.Sleep(time.Second)
_ = xml.Unmarshal(stdout.Bytes(), p)
//result, _ := Parse(stdout.Bytes())
if len(p.TaskProgress) > 0 {
liveProgress <- p.TaskProgress[len(p.TaskProgress)-1].Percent
}
}
}
}()
// Wait for nmap process or timeout.
select {
case <-s.ctx.Done():
// Trigger progress function exit.
close(doneProgress)
// Context was done before the scan was finished.
// The process is killed and a timeout error is returned.
_ = cmd.Process.Kill()
return nil, warnings, ErrScanTimeout
case <-done:
// Trigger progress function exit.
close(doneProgress)
// Process nmap stderr output containing none-critical errors and warnings.
// Everyone needs to check whether one or some of these warnings is a hard issue in their use case.
if stderr.Len() > 0 {
warnings = strings.Split(strings.Trim(stderr.String(), "\n"), "\n")
}
// Check for warnings that will inevitably lead to parsing errors, hence, have priority.
if err := analyzeWarnings(warnings); err != nil {
return nil, warnings, err
}
// Parse nmap xml output. Usually nmap always returns valid XML, even if there is a scan error.
// Potentially available warnings are returned too, but probably not the reason for a broken XML.
result, err := Parse(stdout.Bytes())
if err != nil {
warnings = append(warnings, err.Error()) // Append parsing error to warnings for those who are interested.
return nil, warnings, ErrParseOutput
}
// Critical scan errors are reflected in the XML.
if result != nil && len(result.Stats.Finished.ErrorMsg) > 0 {
switch {
case strings.Contains(result.Stats.Finished.ErrorMsg, "Error resolving name"):
return result, warnings, ErrResolveName
// TODO: Add cases for other known errors we might want to guard.
default:
return result, warnings, fmt.Errorf(result.Stats.Finished.ErrorMsg)
}
}
// Call filters if they are set.
if s.portFilter != nil {
result = choosePorts(result, s.portFilter)
}
if s.hostFilter != nil {
result = chooseHosts(result, s.hostFilter)
}
// Return result, optional warnings but no error.
return result, warnings, nil
}
}
// RunWithStreamer runs nmap synchronously. The XML output is written directly to a file.
// It uses a streamer interface to constantly stream the stdout.
func (s *Scanner) RunWithStreamer(stream Streamer, file string) (warnings []string, err error) {
args := s.args
// Enable XML output.
args = append(args, "-oX")
// Get XML output in stdout instead of writing it in a file.
args = append(args, file)
// Enable progress output every second.
args = append(args, "--stats-every", "5s")
// Prepare nmap process.
cmd := exec.CommandContext(s.ctx, s.binaryPath, args...)
if s.modifySysProcAttr != nil {
s.modifySysProcAttr(cmd.SysProcAttr)
}
// Write stderr to buffer.
stderrBuf := bytes.Buffer{}
cmd.Stderr = &stderrBuf
// Connect to the StdoutPipe.
stdoutIn, err := cmd.StdoutPipe()
if err != nil {
return warnings, errors.WithMessage(err, "connect to StdoutPipe failed")
}
stdout := stream
// Run nmap process.
if err := cmd.Start(); err != nil {
return warnings, errors.WithMessage(err, "start command failed")
}
// Copy stdout to pipe.
g, _ := errgroup.WithContext(s.ctx)
g.Go(func() error {
_, err = io.Copy(stdout, stdoutIn)
return err
})
cmdErr := cmd.Wait()
if err := g.Wait(); err != nil {
warnings = append(warnings, errors.WithMessage(err, "read from stdout failed").Error())
}
if cmdErr != nil {
return warnings, errors.WithMessage(err, "nmap command failed")
}
// Process nmap stderr output containing none-critical errors and warnings.
// Everyone needs to check whether one or some of these warnings is a hard issue in their use case.
if stderrBuf.Len() > 0 {
warnings = append(warnings, strings.Split(strings.Trim(stderrBuf.String(), "\n"), "\n")...)
}
// Check for warnings that will inevitably lead to parsing errors, hence, have priority.
if err := analyzeWarnings(warnings); err != nil {
return warnings, err
}
// Return result, optional warnings but no error.
return warnings, nil
}
// RunAsync runs nmap asynchronously and returns error.
// TODO: RunAsync should return warnings as well.
func (s *Scanner) RunAsync() error {
args := s.args
// Enable XML output.
args = append(args, "-oX")
// Get XML output in stdout instead of writing it in a file.
args = append(args, "-")
s.cmd = exec.Command(s.binaryPath, args...)
if s.modifySysProcAttr != nil {
s.modifySysProcAttr(s.cmd.SysProcAttr)
}
stderr, err := s.cmd.StderrPipe()
if err != nil {
return fmt.Errorf("unable to get error output from asynchronous nmap run: %v", err)
}
stdout, err := s.cmd.StdoutPipe()
if err != nil {
return fmt.Errorf("unable to get standard output from asynchronous nmap run: %v", err)
}
s.stdout = *bufio.NewScanner(stdout)
s.stderr = *bufio.NewScanner(stderr)
if err := s.cmd.Start(); err != nil {
return fmt.Errorf("unable to execute asynchronous nmap run: %v", err)
}
go func() {
<-s.ctx.Done()
_ = s.cmd.Process.Kill()
}()
return nil
}
// Wait waits for the cmd to finish and returns error.
func (s *Scanner) Wait() error {
return s.cmd.Wait()
}
// GetStdout returns stdout variable for scanner.
func (s *Scanner) GetStdout() bufio.Scanner {
return s.stdout
}
// GetStderr returns stderr variable for scanner.
func (s *Scanner) GetStderr() bufio.Scanner {
return s.stderr
}
// AddOptions sets more scan options after the scan is created.
func (s *Scanner) AddOptions(options ...Option) {
for _, option := range options {
option(s)
}
}
func chooseHosts(result *Run, filter func(Host) bool) *Run {
var filteredHosts []Host
for _, host := range result.Hosts {
if filter(host) {
filteredHosts = append(filteredHosts, host)
}
}
result.Hosts = filteredHosts
return result
}
func choosePorts(result *Run, filter func(Port) bool) *Run {
for idx := range result.Hosts {
var filteredPorts []Port
for _, port := range result.Hosts[idx].Ports {
if filter(port) {
filteredPorts = append(filteredPorts, port)
}
}
result.Hosts[idx].Ports = filteredPorts
}
return result
}
func analyzeWarnings(warnings []string) error {
// Check for warnings that will inevitably lead to parsing errors, hence, have priority.
for _, warning := range warnings {
switch {
case strings.Contains(warning, "Malloc Failed!"):
return ErrMallocFailed
// TODO: Add cases for other known errors we might want to guard.
default:
}
}
return nil
}
// WithContext adds a context to a scanner, to make it cancellable and able to timeout.
func WithContext(ctx context.Context) Option {
return func(s *Scanner) {
s.ctx = ctx
}
}
// WithBinaryPath sets the nmap binary path for a scanner.
func WithBinaryPath(binaryPath string) Option {
return func(s *Scanner) {
s.binaryPath = binaryPath
}
}
// WithCustomArguments sets custom arguments to give to the nmap binary.
// There should be no reason to use this, unless you are using a custom build
// of nmap or that this repository isn't up to date with the latest options
// of the official nmap release.
// You can use this as a quick way to paste an nmap command into your go code,
// but remember that the whole purpose of this repository is to be idiomatic,
// provide type checking, enums for the values that can be passed, etc.
func WithCustomArguments(args ...string) Option {
return func(s *Scanner) {
s.args = append(s.args, args...)
}
}
// WithFilterPort allows to set a custom function to filter out ports that
// don't fulfill a given condition. When the given function returns true,
// the port is kept, otherwise it is removed from the result. Can be used
// along with WithFilterHost.
func WithFilterPort(portFilter func(Port) bool) Option {
return func(s *Scanner) {
s.portFilter = portFilter
}
}
// WithFilterHost allows to set a custom function to filter out hosts that
// don't fulfill a given condition. When the given function returns true,
// the host is kept, otherwise it is removed from the result. Can be used
// along with WithFilterPort.
func WithFilterHost(hostFilter func(Host) bool) Option {
return func(s *Scanner) {
s.hostFilter = hostFilter
}
}
/*** Target specification ***/
// WithTargets sets the target of a scanner.
func WithTargets(targets ...string) Option {
return func(s *Scanner) {
s.args = append(s.args, targets...)
}
}
// WithTargetExclusion sets the excluded targets of a scanner.
func WithTargetExclusion(target string) Option {
return func(s *Scanner) {
s.args = append(s.args, "--exclude")
s.args = append(s.args, target)
}
}
// WithTargetInput sets the input file name to set the targets.
func WithTargetInput(inputFileName string) Option {
return func(s *Scanner) {
s.args = append(s.args, "-iL")
s.args = append(s.args, inputFileName)
}
}
// WithTargetExclusionInput sets the input file name to set the target exclusions.
func WithTargetExclusionInput(inputFileName string) Option {
return func(s *Scanner) {
s.args = append(s.args, "--excludefile")
s.args = append(s.args, inputFileName)
}
}
// WithRandomTargets sets the amount of targets to randomly choose from the targets.
func WithRandomTargets(randomTargets int) Option {
return func(s *Scanner) {
s.args = append(s.args, "-iR")
s.args = append(s.args, fmt.Sprint(randomTargets))
}
}
// WithUnique makes each address be scanned only once.
// The default behavior is to scan each address as many times
// as it is specified in the target list, such as when network
// ranges overlap or different hostnames resolve to the same
// address.
func WithUnique() Option {
return func(s *Scanner) {
s.args = append(s.args, "--unique")
}
}
/*** Host discovery ***/
// WithListScan sets the discovery mode to simply list the targets to scan and not scan them.
func WithListScan() Option {
return func(s *Scanner) {
s.args = append(s.args, "-sL")
}
}
// WithPingScan sets the discovery mode to simply ping the targets to scan and not scan them.
func WithPingScan() Option {
return func(s *Scanner) {
s.args = append(s.args, "-sn")
}
}
// WithSkipHostDiscovery diables host discovery and considers all hosts as online.
func WithSkipHostDiscovery() Option {
return func(s *Scanner) {
s.args = append(s.args, "-Pn")
}
}
// WithSYNDiscovery sets the discovery mode to use SYN packets.
// If the portList argument is empty, this will enable SYN discovery
// for all ports. Otherwise, it will be only for the specified ports.
func WithSYNDiscovery(ports ...string) Option {
portList := strings.Join(ports, ",")
return func(s *Scanner) {
s.args = append(s.args, fmt.Sprintf("-PS%s", portList))
}
}
// WithACKDiscovery sets the discovery mode to use ACK packets.
// If the portList argument is empty, this will enable ACK discovery
// for all ports. Otherwise, it will be only for the specified ports.
func WithACKDiscovery(ports ...string) Option {
portList := strings.Join(ports, ",")
return func(s *Scanner) {
s.args = append(s.args, fmt.Sprintf("-PA%s", portList))
}
}
// WithUDPDiscovery sets the discovery mode to use UDP packets.
// If the portList argument is empty, this will enable UDP discovery
// for all ports. Otherwise, it will be only for the specified ports.
func WithUDPDiscovery(ports ...string) Option {
portList := strings.Join(ports, ",")
return func(s *Scanner) {
s.args = append(s.args, fmt.Sprintf("-PU%s", portList))
}
}
// WithSCTPDiscovery sets the discovery mode to use SCTP packets
// containing a minimal INIT chunk.
// If the portList argument is empty, this will enable SCTP discovery
// for all ports. Otherwise, it will be only for the specified ports.
// Warning: on Unix, only the privileged user root is generally
// able to send and receive raw SCTP packets.
func WithSCTPDiscovery(ports ...string) Option {
portList := strings.Join(ports, ",")
return func(s *Scanner) {
s.args = append(s.args, fmt.Sprintf("-PY%s", portList))
}
}
// WithICMPEchoDiscovery sets the discovery mode to use an ICMP type 8
// packet (an echo request), like the standard packets sent by the ping
// command.
// Many hosts and firewalls block these packets, so this is usually not
// the best for exploring networks.
func WithICMPEchoDiscovery() Option {
return func(s *Scanner) {
s.args = append(s.args, "-PE")
}
}
// WithICMPTimestampDiscovery sets the discovery mode to use an ICMP type 13
// packet (a timestamp request).
// This query can be valuable when administrators specifically block echo
// request packets while forgetting that other ICMP queries can be used
// for the same purpose.
func WithICMPTimestampDiscovery() Option {
return func(s *Scanner) {
s.args = append(s.args, "-PP")
}
}
// WithICMPNetMaskDiscovery sets the discovery mode to use an ICMP type 17
// packet (an address mask request).
// This query can be valuable when administrators specifically block echo
// request packets while forgetting that other ICMP queries can be used
// for the same purpose.
func WithICMPNetMaskDiscovery() Option {
return func(s *Scanner) {
s.args = append(s.args, "-PM")
}
}
// WithIPProtocolPingDiscovery sets the discovery mode to use the IP
// protocol ping.
// If no protocols are specified, the default is to send multiple IP
// packets for ICMP (protocol 1), IGMP (protocol 2), and IP-in-IP
// (protocol 4).
func WithIPProtocolPingDiscovery(protocols ...string) Option {
protocolList := strings.Join(protocols, ",")
return func(s *Scanner) {
s.args = append(s.args, fmt.Sprintf("-PO%s", protocolList))
}
}
// WithDisabledDNSResolution disables DNS resolution in the discovery
// step of the nmap scan.
func WithDisabledDNSResolution() Option {
return func(s *Scanner) {
s.args = append(s.args, "-n")
}
}
// WithForcedDNSResolution enforces DNS resolution in the discovery
// step of the nmap scan.
func WithForcedDNSResolution() Option {
return func(s *Scanner) {
s.args = append(s.args, "-R")
}
}
// WithCustomDNSServers sets custom DNS servers for the scan.
// List format: dns1[,dns2],...
func WithCustomDNSServers(dnsServers ...string) Option {
dnsList := strings.Join(dnsServers, ",")
return func(s *Scanner) {
s.args = append(s.args, "--dns-servers")
s.args = append(s.args, dnsList)
}
}
// WithSystemDNS sets the scanner's DNS to the system's DNS.
func WithSystemDNS() Option {
return func(s *Scanner) {
s.args = append(s.args, "--system-dns")
}
}
// WithTraceRoute enables the tracing of the hop path to each host.
func WithTraceRoute() Option {
return func(s *Scanner) {
s.args = append(s.args, "--traceroute")
}
}
/*** Scan techniques ***/
// WithSYNScan sets the scan technique to use SYN packets over TCP.
// This is the default method, as it is fast, stealthy and not
// hampered by restrictive firewalls.
func WithSYNScan() Option {
return func(s *Scanner) {
s.args = append(s.args, "-sS")
}
}
// WithConnectScan sets the scan technique to use TCP connections.
// This is the default method used when a user does not have raw
// packet privileges. Target machines are likely to log these
// connections.
func WithConnectScan() Option {
return func(s *Scanner) {
s.args = append(s.args, "-sT")
}
}
// WithACKScan sets the scan technique to use ACK packets over TCP.
// This scan is unable to determine if a port is open.
// When scanning unfiltered systems, open and closed ports will both
// return a RST packet.
// Nmap then labels them as unfiltered, meaning that they are reachable
// by the ACK packet, but whether they are open or closed is undetermined.
func WithACKScan() Option {
return func(s *Scanner) {
s.args = append(s.args, "-sA")
}
}
// WithWindowScan sets the scan technique to use ACK packets over TCP and
// examining the TCP window field of the RST packets returned.
// Window scan is exactly the same as ACK scan except that it exploits
// an implementation detail of certain systems to differentiate open ports
// from closed ones, rather than always printing unfiltered when a RST
// is returned.
func WithWindowScan() Option {
return func(s *Scanner) {
s.args = append(s.args, "-sW")
}
}
// WithMaimonScan sends the same packets as NULL, FIN, and Xmas scans,
// except that the probe is FIN/ACK. Many BSD-derived systems will drop
// these packets if the port is open.
func WithMaimonScan() Option {
return func(s *Scanner) {
s.args = append(s.args, "-sM")
}
}
// WithUDPScan sets the scan technique to use UDP packets.
// It can be combined with a TCP scan type such as SYN scan
// to check both protocols during the same run.
// UDP scanning is generally slower than TCP, but should not
// be ignored.
func WithUDPScan() Option {
return func(s *Scanner) {
s.args = append(s.args, "-sU")
}
}
// WithTCPNullScan sets the scan technique to use TCP null packets.
// (TCP flag header is 0). This scan method can be used to exploit
// a loophole in the TCP RFC.
// If an RST packet is received, the port is considered closed,
// while no response means it is open|filtered.
func WithTCPNullScan() Option {
return func(s *Scanner) {
s.args = append(s.args, "-sN")
}
}
// WithTCPFINScan sets the scan technique to use TCP packets with
// the FIN flag set.
// This scan method can be used to exploit a loophole in the TCP RFC.
// If an RST packet is received, the port is considered closed,
// while no response means it is open|filtered.
func WithTCPFINScan() Option {
return func(s *Scanner) {
s.args = append(s.args, "-sF")
}
}
// WithTCPXmasScan sets the scan technique to use TCP packets with
// the FIN, PSH and URG flags set.
// This scan method can be used to exploit a loophole in the TCP RFC.
// If an RST packet is received, the port is considered closed,
// while no response means it is open|filtered.
func WithTCPXmasScan() Option {
return func(s *Scanner) {
s.args = append(s.args, "-sX")
}
}
// TCPFlag represents a TCP flag.
type TCPFlag int
// Flag enumerations.
const (
FlagNULL TCPFlag = 0
FlagFIN TCPFlag = 1
FlagSYN TCPFlag = 2
FlagRST TCPFlag = 4
FlagPSH TCPFlag = 8
FlagACK TCPFlag = 16
FlagURG TCPFlag = 32
FlagECE TCPFlag = 64
FlagCWR TCPFlag = 128
FlagNS TCPFlag = 256
)
// WithTCPScanFlags sets the scan technique to use custom TCP flags.
func WithTCPScanFlags(flags ...TCPFlag) Option {
var total int
for _, flag := range flags {
total += int(flag)
}
return func(s *Scanner) {
s.args = append(s.args, "--scanflags")
s.args = append(s.args, fmt.Sprintf("%x", total))
}
}
// WithIdleScan sets the scan technique to use a zombie host to
// allow for a truly blind TCP port scan of the target.
// Besides being extraordinarily stealthy (due to its blind nature),
// this scan type permits mapping out IP-based trust relationships
// between machines.
func WithIdleScan(zombieHost string, probePort int) Option {
return func(s *Scanner) {
s.args = append(s.args, "-sI")
if probePort != 0 {
s.args = append(s.args, fmt.Sprintf("%s:%d", zombieHost, probePort))
} else {
s.args = append(s.args, zombieHost)
}
}
}
// WithSCTPInitScan sets the scan technique to use SCTP packets
// containing an INIT chunk.
// It can be performed quickly, scanning thousands of ports per
// second on a fast network not hampered by restrictive firewalls.
// Like SYN scan, INIT scan is relatively unobtrusive and stealthy,
// since it never completes SCTP associations.
func WithSCTPInitScan() Option {
return func(s *Scanner) {
s.args = append(s.args, "-sY")
}
}
// WithSCTPCookieEchoScan sets the scan technique to use SCTP packets
// containing a COOKIE-ECHO chunk.
// The advantage of this scan type is that it is not as obvious a port
// scan than an INIT scan. Also, there may be non-stateful firewall
// rulesets blocking INIT chunks, but not COOKIE ECHO chunks.
func WithSCTPCookieEchoScan() Option {
return func(s *Scanner) {
s.args = append(s.args, "-sZ")
}
}
// WithIPProtocolScan sets the scan technique to use the IP protocol.
// IP protocol scan allows you to determine which IP protocols
// (TCP, ICMP, IGMP, etc.) are supported by target machines. This isn't
// technically a port scan, since it cycles through IP protocol numbers
// rather than TCP or UDP port numbers.
func WithIPProtocolScan() Option {
return func(s *Scanner) {
s.args = append(s.args, "-sO")
}
}
// WithFTPBounceScan sets the scan technique to use the an FTP relay host.
// It takes an argument of the form "<username>:<password>@<server>:<port>. <Server>".
// You may omit <username>:<password>, in which case anonymous login credentials
// (user: anonymous password:-wwwuser@) are used.
// The port number (and preceding colon) may be omitted as well, in which case the
// default FTP port (21) on <server> is used.
func WithFTPBounceScan(FTPRelayHost string) Option {
return func(s *Scanner) {
s.args = append(s.args, "-b")
s.args = append(s.args, FTPRelayHost)
}
}
/*** Port specification and scan order ***/
// WithPorts sets the ports which the scanner should scan on each host.
func WithPorts(ports ...string) Option {
portList := strings.Join(ports, ",")
return func(s *Scanner) {
// Find if any port is set.
var place int = -1
for p, value := range s.args {
if value == "-p" {
place = p
break
}
}
// Add ports.
if place >= 0 {
portList = s.args[place+1] + "," + portList
s.args[place+1] = portList
} else {
s.args = append(s.args, "-p")
s.args = append(s.args, portList)
}
}
}
// WithPortExclusions sets the ports that the scanner should not scan on each host.
func WithPortExclusions(ports ...string) Option {
portList := strings.Join(ports, ",")
return func(s *Scanner) {
s.args = append(s.args, "--exclude-ports")
s.args = append(s.args, portList)
}
}
// WithFastMode makes the scan faster by scanning fewer ports than the default scan.
func WithFastMode() Option {
return func(s *Scanner) {
s.args = append(s.args, "-F")
}
}
// WithConsecutivePortScanning makes the scan go through ports consecutively instead of
// picking them out randomly.
func WithConsecutivePortScanning() Option {
return func(s *Scanner) {
s.args = append(s.args, "-r")
}
}
// WithMostCommonPorts sets the scanner to go through the provided number of most
// common ports.
func WithMostCommonPorts(number int) Option {
return func(s *Scanner) {
s.args = append(s.args, "--top-ports")
s.args = append(s.args, fmt.Sprint(number))
}
}
// WithPortRatio sets the scanner to go the ports more common than the given ratio.
// Ratio must be a float between 0 and 1.
func WithPortRatio(ratio float32) Option {
return func(s *Scanner) {
if ratio < 0 || ratio > 1 {
panic("value given to nmap.WithPortRatio() should be between 0 and 1")
}
s.args = append(s.args, "--port-ratio")
s.args = append(s.args, fmt.Sprintf("%.1f", ratio))
}
}
/*** Service/Version detection ***/
// WithServiceInfo enables the probing of open ports to determine service and version
// info.
func WithServiceInfo() Option {
return func(s *Scanner) {
s.args = append(s.args, "-sV")
}
}
// WithVersionIntensity sets the level of intensity with which nmap should
// probe the open ports to get version information.
// Intensity should be a value between 0 (light) and 9 (try all probes). The
// default value is 7.
func WithVersionIntensity(intensity int16) Option {
return func(s *Scanner) {