-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathmasscan.go
120 lines (114 loc) · 2.11 KB
/
masscan.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
package masscan
import (
"bytes"
"encoding/xml"
"fmt"
"io"
"os/exec"
"github.com/pkg/errors"
)
type Masscan struct {
SystemPath string
Args []string
Ports string
Ranges string
Rate string
Exclude string
Result []byte
}
func (m *Masscan) SetSystemPath(systemPath string) {
if systemPath != "" {
m.SystemPath = systemPath
}
}
func (m *Masscan) SetArgs(arg ...string) {
m.Args = arg
}
func (m *Masscan) SetPorts(ports string) {
m.Ports = ports
}
func (m *Masscan) SetRanges(ranges string) {
m.Ranges = ranges
}
func (m *Masscan) SetRate(rate string) {
m.Rate = rate
}
func (m *Masscan) SetExclude(exclude string) {
m.Exclude = exclude
}
// Start scanning
func (m *Masscan) Run() error {
var (
cmd *exec.Cmd
outb, errs bytes.Buffer
)
if m.Rate != "" {
m.Args = append(m.Args, "--rate")
m.Args = append(m.Args, m.Rate)
}
if m.Ranges != "" {
m.Args = append(m.Args, "--range")
m.Args = append(m.Args, m.Ranges)
}
if m.Ports != "" {
m.Args = append(m.Args, "-p")
m.Args = append(m.Args, m.Ports)
}
if m.Exclude != "" {
m.Args = append(m.Args, "--exclude")
m.Args = append(m.Args, m.Exclude)
}
m.Args = append(m.Args, "-oX")
m.Args = append(m.Args, "-")
cmd = exec.Command(m.SystemPath, m.Args...)
fmt.Println(cmd.Args)
cmd.Stdout = &outb
cmd.Stderr = &errs
err := cmd.Run()
if err != nil {
if errs.Len() > 0 {
return errors.New(errs.String())
}
return err
}
m.Result = outb.Bytes()
return nil
}
// Parse scans result.
func (m *Masscan) Parse() ([]Host, error) {
var hosts []Host
decoder := xml.NewDecoder(bytes.NewReader(m.Result))
for {
t, err := decoder.Token()
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
if t == nil {
break
}
switch se := t.(type) {
case xml.StartElement:
if se.Name.Local == "host" {
var host Host
err := decoder.DecodeElement(&host, &se)
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
hosts = append(hosts, host)
}
default:
}
}
return hosts, nil
}
func New() *Masscan {
return &Masscan{
SystemPath: "masscan",
}
}