forked from hawshemi/SNI-Finder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
255 lines (208 loc) · 5.82 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
package main
import (
"context"
"crypto/tls"
"flag"
"fmt"
"math/big"
"net"
"os"
"strings"
"sync"
"time"
"github.com/sirupsen/logrus"
)
const (
defaultAddress = "0.0.0.0"
defaultPort = "443"
defaultThreadCount = 128
defaultTimeout = 4
outPutDef = true
outPutFileName = "results.txt"
showFailDef = false
numIPsToCheck = 10000
workerPoolSize = 100
)
var log = logrus.New()
var zeroIP = net.ParseIP("0.0.0.0")
var maxIP = net.ParseIP("255.255.255.255")
var TlsDic = map[uint16]string{
0x0301: "1.0",
0x0302: "1.1",
0x0303: "1.2",
0x0304: "1.3",
}
type CustomTextFormatter struct {
logrus.TextFormatter
}
type Scanner struct {
addr string
port string
showFail bool
output bool
timeout time.Duration
wg *sync.WaitGroup
numberOfThread int
mu sync.Mutex
ip net.IP
logFile *os.File
dialer *net.Dialer
logChan chan string
}
func (f *CustomTextFormatter) Format(entry *logrus.Entry) ([]byte, error) {
timestamp := entry.Time.Format("2006-01-02 15:04:05")
msg := entry.Message
// Create the log entry without the "level=info" and with a new line
formattedEntry := timestamp + msg + "\n\n"
return []byte(formattedEntry), nil
}
func (s *Scanner) Print(outStr string) {
// Split the output string into IP address and the rest
parts := strings.Split(outStr, " ")
ipAddress := parts[0] // Extract the IP address part
rest := strings.Join(parts[1:], " ") // Extract the rest of the message
// Calculate the maximum IP address length
maxIPLength := len("255.255.255.255")
// Format the IP address with a fixed width
formattedIP := fmt.Sprintf("%-*s", maxIPLength-8, ipAddress)
// Create the final log entry with IP alignment
logEntry := formattedIP + rest
s.logChan <- logEntry
}
func main() {
addrPtr := flag.String("addr", defaultAddress, "Destination to start scan")
portPtr := flag.String("port", defaultPort, "Port to scan")
threadPtr := flag.Int("thread", defaultThreadCount, "Number of threads to scan in parallel")
outPutFile := flag.Bool("o", outPutDef, "Is output to results.txt")
timeOutPtr := flag.Int("timeOut", defaultTimeout, "Time out of a scan")
showFailPtr := flag.Bool("showFail", showFailDef, "Is Show fail logs")
flag.Parse()
s := &Scanner{
addr: *addrPtr,
port: *portPtr,
showFail: *showFailPtr,
output: *outPutFile,
timeout: time.Duration(*timeOutPtr) * time.Second,
wg: &sync.WaitGroup{},
numberOfThread: *threadPtr,
ip: net.ParseIP(*addrPtr),
dialer: &net.Dialer{},
logChan: make(chan string, numIPsToCheck),
}
// Initialize Logrus settings
log.SetFormatter(&CustomTextFormatter{})
log.SetLevel(logrus.InfoLevel) // Set the desired log level
if *outPutFile {
var err error
s.logFile, err = os.OpenFile(outPutFileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600)
if err != nil {
log.WithError(err).Error("Failed to open log file")
return
}
defer s.logFile.Close()
}
go s.logWriter()
// Create a buffered channel for IPs to scan
ipChan := make(chan net.IP, numIPsToCheck)
// Start the worker pool
for i := 0; i < s.numberOfThread; i++ {
go s.worker(ipChan)
}
// Generate the IPs to scan and send them to the channel
for i := 0; i < numIPsToCheck; i++ {
nextIP := s.nextIP(true)
if nextIP != nil {
s.wg.Add(1)
ipChan <- nextIP
}
}
close(ipChan)
// Wait for all scans to complete
s.wg.Wait()
close(s.logChan)
log.Info("Scan completed.")
}
func (s *Scanner) logWriter() {
for str := range s.logChan {
log.Info(str) // Log with Info level
if s.output {
_, err := s.logFile.WriteString(str + "\n")
if err != nil {
log.WithError(err).Error("Error writing into file")
}
}
}
}
func (s *Scanner) worker(ipChan <-chan net.IP) {
for ip := range ipChan {
s.Scan(ip)
s.wg.Done()
}
}
func (s *Scanner) nextIP(increment bool) net.IP {
s.mu.Lock()
defer s.mu.Unlock()
ipb := big.NewInt(0).SetBytes(s.ip.To4())
if increment {
ipb.Add(ipb, big.NewInt(1))
} else {
ipb.Sub(ipb, big.NewInt(1))
}
b := ipb.Bytes()
b = append(make([]byte, 4-len(b)), b...)
nextIP := net.IP(b)
if nextIP.Equal(zeroIP) || nextIP.Equal(maxIP) {
return nil
}
s.ip = nextIP
return s.ip
}
func (s *Scanner) Scan(ip net.IP) {
str := ip.String()
if ip.To4() == nil {
str = "[" + str + "]"
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
conn, err := s.dialer.DialContext(ctx, "tcp", str+":"+s.port)
if err != nil {
if s.showFail {
s.Print(fmt.Sprintf("Dial failed: %v", err))
}
return
}
defer conn.Close() // Ensure the connection is closed
remoteAddr := conn.RemoteAddr().(*net.TCPAddr)
remoteIP := remoteAddr.IP.String()
port := remoteAddr.Port
line := fmt.Sprintf("%s:%d", remoteIP, port) + "\t"
conn.SetDeadline(time.Now().Add(s.timeout))
c := tls.Client(conn, &tls.Config{
InsecureSkipVerify: true,
NextProtos: []string{"h2", "http/1.1"},
})
err = c.Handshake()
if err != nil {
if s.showFail {
s.Print(fmt.Sprintf("%s - TLS handshake failed: %v", line, err))
}
return
}
defer c.Close() // Ensure the TLS client is also properly closed
state := c.ConnectionState()
alpn := state.NegotiatedProtocol
if alpn == "" {
alpn = " "
}
if s.showFail || (state.Version == 0x0304 && alpn == "h2") {
certSubject := ""
if len(state.PeerCertificates) > 0 {
certSubject = state.PeerCertificates[0].Subject.CommonName
}
numPeriods := strings.Count(certSubject, ".")
if strings.HasPrefix(certSubject, "*") || certSubject == "localhost" || numPeriods != 1 || certSubject == "invalid2.invalid" {
return
}
s.Print(fmt.Sprint(" ", line, "---- TLS v", TlsDic[state.Version], " ALPN: ", alpn, " ---- ", certSubject, ":", s.port))
}
}