-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
332 lines (312 loc) · 8.12 KB
/
main.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
package main
import (
"flag"
"fmt"
"net"
"os"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/cheggaaa/pb"
"github.com/go-ping/ping"
)
const ver string = "v0.9.2"
var ports string
var parallels int
var all bool
var showCostTime bool
var debug bool
var isPing bool
var warning bool
var ms int64
var mutex sync.Mutex
var showVer bool
var showHelp bool
// TCPAddrStatus TCPAddr with scan result
type TCPAddrStatus struct {
Addr net.TCPAddr
Status string
}
var resAddrs []TCPAddrStatus
// AppendStatus Append scan result with lock
func AppendStatus(tcpStatus TCPAddrStatus) {
mutex.Lock()
resAddrs = append(resAddrs, tcpStatus)
mutex.Unlock()
}
// IPStringToInt Convert IP string to int
func IPStringToInt(ipString string) int {
ipSegs := strings.Split(ipString, ".")
var ipInt int = 0
var pos uint = 24
for _, ipSeg := range ipSegs {
tempInt, _ := strconv.Atoi(ipSeg)
tempInt = tempInt << pos
ipInt = ipInt | tempInt
pos -= 8
}
return ipInt
}
// IPIntToString Convert IP int to string
func IPIntToString(ipInt int) string {
ipSecs := make([]string, 4)
for i := 0; i < 4; i++ {
ipSecs[3-i] = strconv.Itoa(ipInt & 0xFF)
ipInt >>= 8
}
return strings.Join(ipSecs, ".")
}
// AppendPort Append scan aim port with checking valid
func AppendPort(ports []int, port int) []int {
if port > 0 && port < 65536 {
ports = append(ports, port)
}
return ports
}
func init() {
flag.BoolVar(&all, "a", false, "All ports, 1-65535")
flag.BoolVar(&showCostTime, "c", false, "Show network connecting cost time")
flag.BoolVar(&debug, "d", false, "Debug, show every scan result, instead of show opening port only")
flag.BoolVar(&isPing, "g", false, "Ping check")
flag.StringVar(&ports, "p", "21,22,23,53,80,135,139,443,445,1080,1433,1521,3306,3389,5432,6379,8080", "Specify ports or port range. eg. 80,443,8080 or 80-8080")
flag.IntVar(¶llels, "s", 200, "Parallel scan threads")
flag.Int64Var(&ms, "t", 1000, "Connect timeout, ms")
flag.BoolVar(&showHelp, "h", false, "Show help")
flag.BoolVar(&showVer, "v", false, "Show version")
flag.Usage = func() {
fmt.Fprintf(os.Stdout, "Go network scan tool.\nVersion: "+ver+"\n")
if !showVer {
fmt.Fprintf(os.Stdout, "\nUsage: gns [Options] <IP range or domain>\neg: gns -p 22-8080 -s 300 10.0.1.1-100\n\nOptions:\n")
flag.PrintDefaults()
}
}
testing.Init()
flag.Parse()
}
// CheckPort check network port connectable or not
func CheckPort(ip net.IP, port int, wg *sync.WaitGroup, parallelChan chan int, bar *pb.ProgressBar) {
defer wg.Done()
var needRetry bool
tcpAddr := net.TCPAddr{
IP: ip,
Port: port,
}
timeStart := time.Now()
conn, err := net.DialTimeout("tcp", fmt.Sprintf("[%v]:%v", tcpAddr.IP, tcpAddr.Port), time.Duration(ms*int64(time.Millisecond)))
timeCost := time.Since(timeStart).String()
if err == nil {
msg := "opening"
if showCostTime {
msg += " " + timeCost
}
AppendStatus(TCPAddrStatus{tcpAddr, msg})
conn.Close()
} else {
errMsg := err.Error()
if strings.Contains(errMsg, "connection refused") {
errMsg = "refused"
} else if strings.Contains(errMsg, "connect: operation timed out") || strings.Contains(errMsg, "i/o timeout") {
errMsg = "timeout"
} else if strings.Contains(errMsg, "socket: too many open files") {
warning = true
needRetry = true
errMsg = "retrying"
}
if showCostTime {
errMsg += " " + timeCost
}
if debug {
AppendStatus(TCPAddrStatus{tcpAddr, errMsg})
}
}
// Too many open socket got error, need retry
if needRetry {
wg.Add(1)
CheckPort(ip, port, wg, parallelChan, bar)
} else {
bar.Increment()
<-parallelChan
}
}
// CheckPing ping ip
func CheckPing(ip net.IP, wg *sync.WaitGroup, parallelChan chan int, bar *pb.ProgressBar) {
defer wg.Done()
var msg string = "ping "
pinger, err := ping.NewPinger(ip.String())
if err != nil {
msg = err.Error()
} else {
pinger.Timeout = 1000 * time.Millisecond
if runtime.GOOS == "windows" {
pinger.SetPrivileged(true)
}
pinger.Count = 3
err = pinger.Run() // Block until finished.
if err != nil {
msg = err.Error()
} else {
stats := pinger.Statistics() // get send/receive/duplicate/rtt stats
if stats.PacketsRecv > 0 {
msg += fmt.Sprintf("%d/%d %dms", stats.PacketsRecv, stats.PacketsSent, stats.AvgRtt.Milliseconds())
} else {
msg += "timeout"
}
}
}
tcpAddr := net.TCPAddr{
IP: ip,
Port: 0,
}
if strings.Contains(msg, "/") || debug {
AppendStatus(TCPAddrStatus{tcpAddr, msg})
}
bar.Increment()
<-parallelChan
}
func main() {
if showHelp || showVer {
flag.Usage()
return
}
var aimIPs []net.IP
host := flag.Arg(0)
if len(host) == 0 {
flag.Usage()
return
}
if ip := net.ParseIP(host); ip != nil {
aimIPs = append(aimIPs, ip)
} else if ip, ipNet, _ := net.ParseCIDR(host); ipNet != nil {
fmt.Printf("IP CIDR: %v, %v\n", ip, ipNet)
for i := IPStringToInt(ip.String()); i > 0; i++ {
tmpIP := net.ParseIP(IPIntToString(i))
if ipNet.IP.Equal(tmpIP) {
continue
} else if ipNet.Contains(tmpIP) && !tmpIP.IsLoopback() && !tmpIP.IsMulticast() && !tmpIP.IsUnspecified() {
aimIPs = append(aimIPs, tmpIP)
} else {
break
}
}
} else if isIPRange, _ := regexp.Match(`^(\d{1,3}\.){3}\d{1,3}-\d{1,3}$`, []byte(host)); isIPRange {
ipSpecs := strings.Split(host, ".")
rangeSpecs := strings.Split(ipSpecs[3], "-")
startNum, _ := strconv.Atoi(rangeSpecs[0])
endNum, _ := strconv.Atoi(rangeSpecs[1])
if startNum > endNum {
tmp := endNum
endNum = startNum
startNum = tmp
}
ipSpecs = ipSpecs[:len(ipSpecs)-1]
for i := startNum; i <= endNum; i++ {
tmpIPSpecs := append(ipSpecs, strconv.Itoa(i))
if tmpIP := net.ParseIP(strings.Join(tmpIPSpecs, ".")); tmpIP != nil {
aimIPs = append(aimIPs, tmpIP)
}
}
} else {
ips, err := net.LookupIP(host)
if err == nil && len(ips) > 0 {
fmt.Printf("Resolving %v => %v\n", host, ips)
aimIPs = append(aimIPs, ips[0])
}
}
if len(aimIPs) == 0 {
fmt.Fprintln(os.Stderr, "Invalid IP, hostname or domain")
return
}
var aimPorts []int
var msg string
if isPing {
aimPorts = append(aimPorts, 0)
msg = "Ping"
} else {
if all {
ports = "1-65535"
}
isList, _ := regexp.Match(`^\d[,\d]*$`, []byte(ports))
isRange, _ := regexp.Match(`^\d+-\d+$`, []byte(ports))
var startPort, endPort int
if isRange {
portSecs := strings.Split(ports, "-")
startPort, _ = strconv.Atoi(portSecs[0])
endPort, _ = strconv.Atoi(portSecs[1])
}
if !isList && !isRange {
fmt.Fprintln(os.Stderr, "Invalid ports")
return
}
if isRange {
if startPort > endPort {
tmpPort := endPort
endPort = startPort
startPort = tmpPort
}
for i := startPort; i <= endPort; i++ {
aimPorts = AppendPort(aimPorts, i)
}
} else {
for _, p := range strings.Split(ports, ",") {
port, _ := strconv.Atoi(p)
aimPorts = AppendPort(aimPorts, port)
}
}
if len(aimPorts) == 0 {
fmt.Fprintln(os.Stderr, "No valid network port to scan, port must between 1 and 65535.")
return
}
msg = "Scaning port"
if strings.Contains(ports, ",") || strings.Contains(ports, "-") {
msg += "s "
} else {
msg += " "
}
msg += ports + " on"
}
if debug {
fmt.Println(msg, aimIPs)
}
scanCount := len(aimIPs) * len(aimPorts)
wg := &sync.WaitGroup{}
wg.Add(scanCount)
bar := pb.StartNew(scanCount)
bar.ShowTimeLeft = true
parallelChan := make(chan int, parallels)
for _, ip := range aimIPs {
if isPing {
parallelChan <- 1
go CheckPing(ip, wg, parallelChan, bar)
} else {
for _, port := range aimPorts {
parallelChan <- 1
go CheckPort(ip, port, wg, parallelChan, bar)
}
}
}
wg.Wait()
bar.Finish()
fmt.Println("----Scan Result----")
if !debug && len(resAddrs) == 0 {
if isPing {
fmt.Println("No reachable IP")
} else {
fmt.Println("No opening port")
}
} else {
sort.SliceStable(resAddrs, func(i, j int) bool {
return IPStringToInt(resAddrs[i].Addr.IP.String())*65536+resAddrs[i].Addr.Port < IPStringToInt(resAddrs[j].Addr.IP.String())*65536+resAddrs[j].Addr.Port
})
for _, t := range resAddrs {
fmt.Println(t.Addr.String() + " : " + t.Status)
}
}
if warning {
fmt.Fprintln(os.Stderr, "Warning: too many open sockets, please slow down.")
}
}