-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgort.go
265 lines (247 loc) · 9.48 KB
/
gort.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
// Copyright (c) 2020 Yannic Wehner
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package main
import (
"flag"
"fmt"
"github.com/ElCap1tan/gort/internal/colorFmt"
"github.com/ElCap1tan/gort/internal/csvParser"
"github.com/ElCap1tan/gort/internal/symbols"
"github.com/ElCap1tan/gort/netUtil"
"github.com/ElCap1tan/gort/netUtil/pScan"
"github.com/fatih/color"
"io"
"net/http"
"os"
"path"
"path/filepath"
"runtime"
"time"
)
var dataFolder, resultFolder = "data", "scans"
func main() {
var usage = "" +
"Usage:\n" +
"\tgort [-p ports] [-mc count] [-closed] [-online] [-file] [-elevated] hosts\n" +
"\tMandatory argument:\n" +
"\thosts are comma separated values that can either be\n" +
"\t\tA single host : 192.88.99.1 or example.com\n" +
"\t\tA range of hosts : 192.88.99.1-50 or 192.88.99-100.1-50\n" +
"\t\tA CIDR formatted host range : 192.88.99.1/24\n" +
"\tOptional arguments\n" +
"\t\t-p\n" +
"\t\t\tports are comma separated values that either can be\n" +
"\t\t\t\tA single port : 80\n" +
"\t\t\t\tA range of ports : 80-100\n" +
"\t\t-mc [int]\n" +
"\t\t\tSets the number of most common open ports to scan. If omitted defaults to 1000.\n" +
"\t\t-closed\n" +
"\t\t\tIf this flag is passed ports with closed and unknown/filtered state are also shown in the console output.\n" +
"\t\t-online\n" +
"\t\t\tIf this flag is passed only hosts confirmed as online are shown in the console output.\n" +
"\t\t-file\n" +
"\t\t\tIf this flag is passed the scan result will be saved to a file.\n" +
"\t\t-elevated\n" +
"\t\t\tOnly important for Linux. If this flag is passed the ICMP echo requests will be send via raw sockets.\n" +
"\t\t\tYou might want to try in unprivileged mode first.\n" +
"\t\t\tImportant: Must be run as a super-user when this flag is used or else ping tests won't work!\n" +
"Examples:\n" +
"\t# scan the 1000 most common open ports of example.com\n" +
"\t\tgort example.com\n" +
"\t# scan the 500 most common open ports of example.com\n" +
"\t\tgort -mc 500 example.com\n" +
"\t# scan a custom list of ports for example.com and also show closed or unknown ports in result\n" +
"\t\tgort -p 80,443,1000-1024 -closed example.com\n" +
"\t# scan the subnet 192.88.99.0/24 for the 100 most common open ports and and a custom list of ports\n" +
"\t# and only show targets confirmed as online in the scan result (Some ports could be scanned double).\n" +
"\t\tgort -mc 100 -p 10334,12012 -online 192.88.99.0/24\n" +
"\t\tor\n" +
"\t\tgort -mc 100 -p 10334,12012 -online 192.88.99.0-255\n"
flag.Usage = func() {
fmt.Printf(usage)
}
var hostArgs string
mostCommonCount := flag.Int("mc", 1000, "")
portArgs := flag.String("p", "", "")
onlineOnly := flag.Bool("online", false, "")
showClosed := flag.Bool("closed", false, "")
writeFile := flag.Bool("file", false, "")
privileged := flag.Bool("elevated", false, "")
flag.Parse()
if flag.NArg() == 0 {
flag.Usage()
return
}
hostArgs = flag.Arg(0)
// Try to get execution path of the program. If successful tries to save the needed data in the same folder as
// the executable is located in. If not the data will be saved in the current working directory.
if execPath, err := getExecutionPath(); err == nil {
dataFolder = path.Join(execPath, dataFolder)
}
// Try to update port-numbers.xml and port_open_freq.csv if necessary
err := ensureDir(dataFolder)
if err != nil {
colorFmt.Fatalf("%s Error creating data dir '%s': %s", symbols.FAILURE, dataFolder, err.Error())
return
}
err = updateKnownPorts(5)
if err != nil {
colorFmt.Warnf("%s Error while updating list of known ports. Using old list...\n", symbols.INFO)
}
err = updatePortFreq(5)
if err != nil {
colorFmt.Warnf("%s Error while updating list of most common open ports. Using old list...\n", symbols.INFO)
}
if *portArgs == "" || *portArgs != "" && *mostCommonCount != 1000 {
mostCommon := csvParser.NewMostCommonPorts(dataFolder)
maxAvailable := 0
for _, p := range *mostCommon {
if p.Protocol == "tcp" {
maxAvailable++
}
}
if *mostCommonCount > maxAvailable {
colorFmt.Infof("%s Can't start scan for the %d most common open ports because stats are only available for %d ports. Using that number of ports instead...\n",
symbols.INFO, *mostCommonCount, maxAvailable)
*mostCommonCount = maxAvailable
}
if *portArgs == "" {
colorFmt.Infof("%s No port arguments provided assuming %d most common open ports...\n", symbols.INFO, *mostCommonCount)
} else {
colorFmt.Infof("%s Adding the %d most common open ports to the provided list of port arguments...\n", symbols.INFO, *mostCommonCount)
}
p := *portArgs + mostCommon.GetMostCommonString(*mostCommonCount)
portArgs = &p
}
colorFmt.Infof("%s Parsing and resolving host arguments...\n", symbols.INFO)
targets := pScan.ParseHostString(hostArgs, netUtil.ParsePortString(*portArgs, "tcp", dataFolder), *privileged)
colorFmt.Infof("%s STARTING SCAN...\n", symbols.INFO)
multiScanRes := targets.Scan()
tFinished := time.Now()
if runtime.GOOS == "windows" {
_, err = color.Output.Write([]byte(multiScanRes.CustomColorString(*onlineOnly, *showClosed) + "\n"))
if err != nil {
colorFmt.Infof("Error writing colored scan result to the console. Trying uncolored...")
fmt.Println(multiScanRes.String())
}
} else {
fmt.Println(multiScanRes.CustomColorString(*onlineOnly, *showClosed))
}
if *writeFile {
fileName := fmt.Sprintf("scanlog_%d-%02d-%02d_%02d-%02d-%02d.txt",
tFinished.Year(), tFinished.Month(), tFinished.Day(),
tFinished.Hour(), tFinished.Minute(), tFinished.Second())
err = ensureDir(resultFolder)
if err != nil {
colorFmt.Warnf("%s Failed to create results dir under '%s'. Trying to save in the current working directory.", symbols.INFO, resultFolder)
file, err := os.Create(fileName)
if err == nil {
_, err = file.WriteString(multiScanRes.String())
if err != nil {
println(err.Error())
} else {
colorFmt.Infof("%s Scan result saved as '%s'\n\n", symbols.INFO, fileName)
}
} else {
println(err.Error())
}
} else {
filePath := path.Join(resultFolder, fileName)
file, err := os.Create(filePath)
if err == nil {
_, err = file.WriteString(multiScanRes.String())
if err != nil {
println(err.Error())
} else {
colorFmt.Infof("%s Scan result saved as '%s'\n\n", symbols.INFO, filePath)
}
} else {
println(err.Error())
}
}
}
}
func updateKnownPorts(maxAgeDays int) error {
pnPath := path.Join(dataFolder, "service-names-port-numbers.xml")
url := "https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xml"
pnStats, err := os.Stat(pnPath)
if err != nil {
colorFmt.Warnf("%s Known ports list under %s not found. Trying to download it from %s...\n", symbols.INFO, pnPath, url)
err = fetchFile(url, pnPath)
return err
}
lastModTime := pnStats.ModTime()
if lastModTime.Add(time.Hour * 24 * time.Duration(maxAgeDays)).Before(time.Now()) {
colorFmt.Infof("%s List of known ports not updated since %d days. Trying to update now...\n", symbols.INFO, maxAgeDays)
err = fetchFile(url, pnPath)
return err
}
return err
}
func updatePortFreq(maxAgeDays int) error {
pfPath := path.Join(dataFolder, "port_open_freq.csv")
url := "https://docs.google.com/spreadsheets/d/1r_IriqmkTNPSTiUwii_hQ8Gwl2tfTUz8AGIOIL-wMIE/export?format=csv"
pfStats, err := os.Stat(pfPath)
if err != nil {
colorFmt.Warnf("%s Most common open ports list under %s not found. Trying to download it from %s...\n", symbols.INFO, pfPath, url)
err = fetchFile(url, pfPath)
return err
}
lastModTime := pfStats.ModTime()
if lastModTime.Add(time.Hour * 24 * time.Duration(maxAgeDays)).Before(time.Now()) {
colorFmt.Infof("%s List of most common open ports not updated since %d days. Trying to update now...\n", symbols.INFO, maxAgeDays)
err = fetchFile(url, pfPath)
return err
}
return err
}
func fetchFile(url, filePath string) error {
file, err := os.Create(filePath)
if err != nil {
return err
}
defer file.Close()
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
_, err = io.Copy(file, resp.Body)
if err == nil {
colorFmt.Successf("%s Success!\n", symbols.SUCCESS)
}
return err
}
func ensureDir(dirName string) error {
err := os.MkdirAll(dirName, 0766)
if err == nil || os.IsExist(err) {
return nil
}
return err
}
func getExecutionPath() (string, error) {
ex, err := os.Executable()
if err != nil {
return "", err
}
exPath := filepath.Dir(ex)
exPath, err = filepath.EvalSymlinks(exPath)
return exPath, err
}