-
Notifications
You must be signed in to change notification settings - Fork 0
/
hagelslag.go
226 lines (184 loc) · 5.22 KB
/
hagelslag.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
package main
import (
"context"
"errors"
"flag"
"fmt"
"io"
"net"
"os"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/writeconcern"
)
type Hagelslag struct {
// This channel is embedded since its pretty contained in this struct
connections chan string
Scanner Scanner
StartingIP string
Port string
URI string
OnlyConnect bool
Rate int
}
type Scanner interface {
// Name of the scanner
Name() string
// Port to connect to
Port() string
// 'tcp' or 'udp'
Network() string
// Responsible for sending and receiving all the necessary data for saving
Scan(ip string, conn net.Conn) ([]byte, int64, error)
// Saves the response to the database
Save(ip string, latency int64, data []byte, collection *mongo.Collection) error
}
func NewHagelslag() (Hagelslag, error) {
ip := flag.String("ip", "", "IP address to start from, without port")
scannerName := flag.String("scanner", "http", "Scanner to use (default: http)")
port := flag.String("port", "", "Override the scanners port")
uri := flag.String("uri", "mongodb://localhost:27017", "MongoDB URI (default: mongodb://localhost:27017)")
connect := flag.Bool("only-connect", false, "Skip scanning, connect and save if successful (default: false)")
rate := flag.Int("rate", 1000, "Limit of connections, be careful with this value (default: 1000)")
flag.Parse()
h := Hagelslag{
StartingIP: *ip,
URI: *uri,
OnlyConnect: *connect,
Rate: *rate,
}
// Checking if the database is reachable
client, err := mongo.Connect(context.TODO(), options.Client().SetServerSelectionTimeout(3*time.Second).ApplyURI(h.URI))
if err != nil {
return Hagelslag{}, fmt.Errorf("failed to connect to database: %s", err)
}
err = client.Ping(context.TODO(), nil)
if err != nil {
return Hagelslag{}, fmt.Errorf("failed to ping database: %s", err)
}
err = client.Disconnect(context.TODO())
if err != nil {
return Hagelslag{}, fmt.Errorf("failed to disconnect from database: %s", err)
}
scanner := strings.ToLower(*scannerName)
switch scanner {
case "http":
h.Scanner = HTTP{}
case "minecraft":
h.Scanner = Minecraft{}
case "veloren":
h.Scanner = Veloren{}
default:
return Hagelslag{}, fmt.Errorf("unknown scanner '%s'", scanner)
}
if *port != "" {
h.Port = *port
} else {
h.Port = h.Scanner.Port()
}
if h.OnlyConnect {
file, err := os.OpenFile("connections.out", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
if err != nil {
return Hagelslag{}, fmt.Errorf("failed to open file: %s", err)
}
h.connections = make(chan string)
go h.saveConnections(file)
}
return h, nil
}
func (h Hagelslag) worker(addresses chan string, semaphore chan struct{}, wg *sync.WaitGroup) {
defer wg.Done()
options := options.Client().
ApplyURI(h.URI).
SetWriteConcern(&writeconcern.WriteConcern{})
client, err := mongo.Connect(context.TODO(), options)
if err != nil {
fmt.Printf("failed to connect to database: %s\n", err)
return
}
err = client.Ping(context.TODO(), nil)
if err != nil {
fmt.Printf("failed to ping database: %s\n", err)
return
}
name := h.Scanner.Name()
network := h.Scanner.Network()
dialer := net.Dialer{
KeepAlive: -1,
Timeout: 1 * time.Second,
}
collection := client.Database("hagelslag").Collection(name)
for address := range addresses {
go h.spawn(semaphore, address, network, dialer, collection)
}
err = client.Disconnect(context.TODO())
if err != nil {
fmt.Printf("failed to disconnect from database: %s\n", err)
}
}
func (h Hagelslag) spawn(semaphore chan struct{}, address string, network string, dialer net.Dialer, collection *mongo.Collection) {
// Release the slot when done
defer func() { <-semaphore }()
// Connection
conn, err := dialer.Dial(network, address)
if err != nil {
// Don't log anything
return
}
defer conn.Close()
if h.OnlyConnect {
atomic.AddInt64(&SUCCESS, 1)
h.connections <- address
return
}
// Read and Write deadline
err = conn.SetDeadline(time.Now().Add(3 * time.Second))
if err != nil {
return
}
response, latency, err := h.Scanner.Scan(address, conn)
if len(response) == 0 && err == nil {
// No response, or wrong response (not wanted, can be discarded)
return
}
if err != nil {
// Don't log these errors
if errors.Is(err, os.ErrDeadlineExceeded) || errors.Is(err, syscall.ECONNRESET) || errors.Is(err, io.EOF) {
return
}
if SHUTTING_DOWN {
return
}
os.Stderr.WriteString("\nERROR SCAN " + address + ": " + err.Error() + "\n")
return
}
err = h.Scanner.Save(address, latency, response, collection)
if err != nil {
if SHUTTING_DOWN {
return
}
os.Stderr.WriteString("\nERROR SAVE " + address + ": " + err.Error() + "\n")
return
}
atomic.AddInt64(&SUCCESS, 1)
}
// Only used when OnlyConnect is true
//
// Wait for addresses and append them to a file
func (h Hagelslag) saveConnections(file *os.File) {
defer file.Close()
portLen := len(h.Port) + 1
for address := range h.connections {
// Removing the port
address = address[:len(address)-portLen]
_, err := file.WriteString(address + "\n")
if err != nil {
os.Stderr.WriteString("\nERROR SAVE " + address + ": " + err.Error() + "\n")
}
}
}