-
Notifications
You must be signed in to change notification settings - Fork 55
/
probe_netbios.go
385 lines (310 loc) · 8.72 KB
/
probe_netbios.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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
package main
import (
"bytes"
"encoding/binary"
"fmt"
"log"
"math/rand"
"net"
"strings"
"time"
)
const MaxPendingReplies int = 256
const MaxProbeResponseTime time.Duration = time.Second * 2
type NetbiosInfo struct {
statusRecv time.Time
nameSent time.Time
nameRecv time.Time
statusReply NetbiosReplyStatus
nameReply NetbiosReplyStatus
}
type ProbeNetbios struct {
Probe
socket net.PacketConn
replies map[string]*NetbiosInfo
}
type NetbiosReplyHeader struct {
XID uint16
Flags uint16
QuestionCount uint16
AnswerCount uint16
AuthCount uint16
AdditionalCount uint16
QuestionName [34]byte
RecordType uint16
RecordClass uint16
RecordTTL uint32
RecordLength uint16
}
type NetbiosReplyName struct {
Name [15]byte
Type uint8
Flag uint16
}
type NetbiosReplyAddress struct {
Flag uint16
Address [4]uint8
}
type NetbiosReplyStatus struct {
Header NetbiosReplyHeader
HostName [15]byte
UserName [15]byte
Names []NetbiosReplyName
Addresses []NetbiosReplyAddress
HWAddr string
}
func (this *ProbeNetbios) ProcessReplies() {
buff := make([]byte, 1500)
this.replies = make(map[string]*NetbiosInfo)
for {
rlen, raddr, rerr := this.socket.ReadFrom(buff)
if rerr != nil {
if nerr, ok := rerr.(net.Error); ok && nerr.Timeout() {
log.Printf("probe %s receiver timed out: %s", this, rerr)
continue
}
// Complain about other error types
log.Printf("probe %s receiver returned error: %s", this, rerr)
return
}
ip := raddr.(*net.UDPAddr).IP.String()
reply := this.ParseReply(buff[0 : rlen-1])
if len(reply.Names) == 0 && len(reply.Addresses) == 0 {
continue
}
_, found := this.replies[ip]
if !found {
nbinfo := new(NetbiosInfo)
this.replies[ip] = nbinfo
}
// Handle status replies by sending a name request
if reply.Header.RecordType == 0x21 {
// log.Printf("probe %s received a status reply of %d bytes from %s", this, rlen, raddr)
this.replies[ip].statusReply = reply
this.replies[ip].statusRecv = time.Now()
ntime := time.Time{}
if this.replies[ip].nameSent == ntime {
this.replies[ip].nameSent = time.Now()
this.SendNameRequest(ip)
}
}
// Handle name replies by reporting the result
if reply.Header.RecordType == 0x20 {
// log.Printf("probe %s received a name reply of %d bytes from %s", this, rlen, raddr)
this.replies[ip].nameReply = reply
this.replies[ip].nameRecv = time.Now()
this.ReportResult(ip)
}
}
}
func (this *ProbeNetbios) SendRequest(ip string, req []byte) {
addr, aerr := net.ResolveUDPAddr("udp", ip+":137")
if aerr != nil {
log.Printf("probe %s failed to resolve %s (%s)", this, ip, aerr)
return
}
// Retry in case of network buffer congestion
wcnt := 0
for wcnt = 0; wcnt < 5; wcnt++ {
this.CheckRateLimit()
_, werr := this.socket.WriteTo(req, addr)
if werr != nil {
log.Printf("probe %s [%d/%d] failed to send to %s (%s)", this, wcnt+1, 5, ip, werr)
time.Sleep(100 * time.Millisecond)
continue
}
break
}
// Were we able to send it eventually?
if wcnt == 5 {
log.Printf("probe %s [%d/%d] gave up sending to %s", this, wcnt, 5, ip)
}
}
func (this *ProbeNetbios) SendStatusRequest(ip string) {
// log.Printf("probe %s is sending a status request to %s", this, ip)
this.SendRequest(ip, this.CreateStatusRequest())
}
func (this *ProbeNetbios) SendNameRequest(ip string) {
sreply := this.replies[ip].statusReply
name := TrimName(string(sreply.HostName[:]))
this.SendRequest(ip, this.CreateNameRequest(name))
}
func (this *ProbeNetbios) ResultFromIP(ip string) ScanResult {
sreply := this.replies[ip].statusReply
nreply := this.replies[ip].nameReply
res := ScanResult{
Host: ip,
Port: "137",
Proto: "udp",
Probe: this.String(),
}
res.Info = make(map[string]string)
res.Name = TrimName(string(sreply.HostName[:]))
if nreply.Header.RecordType == 0x20 {
for _, ainfo := range nreply.Addresses {
net := fmt.Sprintf("%d.%d.%d.%d", ainfo.Address[0], ainfo.Address[1], ainfo.Address[2], ainfo.Address[3])
if net == "0.0.0.0" {
continue
}
res.Nets = append(res.Nets, net)
}
}
if sreply.HWAddr != "00:00:00:00:00:00" {
res.Info["hwaddr"] = sreply.HWAddr
}
username := TrimName(string(sreply.UserName[:]))
if len(username) > 0 && username != res.Name {
res.Info["username"] = username
}
for _, rname := range sreply.Names {
tname := TrimName(string(rname.Name[:]))
if tname == res.Name {
continue
}
if rname.Flag&0x0800 != 0 {
continue
}
res.Info["domain"] = tname
}
return res
}
func (this *ProbeNetbios) ReportResult(ip string) {
this.output <- this.ResultFromIP(ip)
delete(this.replies, ip)
}
func (this *ProbeNetbios) ReportIncompleteResults() {
for ip, _ := range this.replies {
this.ReportResult(ip)
}
}
func (this *ProbeNetbios) EncodeNetbiosName(name [16]byte) [32]byte {
encoded := [32]byte{}
for i := 0; i < 16; i++ {
if name[i] == 0 {
encoded[(i*2)+0] = 'C'
encoded[(i*2)+1] = 'A'
} else {
encoded[(i*2)+0] = byte((name[i] / 16) + 0x41)
encoded[(i*2)+1] = byte((name[i] % 16) + 0x41)
}
}
return encoded
}
func (this *ProbeNetbios) DecodeNetbiosName(name [32]byte) [16]byte {
decoded := [16]byte{}
for i := 0; i < 16; i++ {
if name[(i*2)+0] == 'C' && name[(i*2)+1] == 'A' {
decoded[i] = 0
} else {
decoded[i] = ((name[(i*2)+0] * 16) - 0x41) + (name[(i*2)+1] - 0x41)
}
}
return decoded
}
func (this *ProbeNetbios) ParseReply(buff []byte) NetbiosReplyStatus {
resp := NetbiosReplyStatus{}
temp := bytes.NewBuffer(buff)
binary.Read(temp, binary.BigEndian, &resp.Header)
if resp.Header.QuestionCount != 0 {
return resp
}
if resp.Header.AnswerCount == 0 {
return resp
}
// Names
if resp.Header.RecordType == 0x21 {
var rcnt uint8
var ridx uint8
binary.Read(temp, binary.BigEndian, &rcnt)
for ridx = 0; ridx < rcnt; ridx++ {
name := NetbiosReplyName{}
binary.Read(temp, binary.BigEndian, &name)
resp.Names = append(resp.Names, name)
if name.Type == 0x20 {
resp.HostName = name.Name
}
if name.Type == 0x03 {
resp.UserName = name.Name
}
}
var hwbytes [6]uint8
binary.Read(temp, binary.BigEndian, &hwbytes)
resp.HWAddr = fmt.Sprintf("%.2x:%.2x:%.2x:%.2x:%.2x:%.2x",
hwbytes[0], hwbytes[1], hwbytes[2], hwbytes[3], hwbytes[4], hwbytes[5],
)
return resp
}
// Addresses
if resp.Header.RecordType == 0x20 {
var ridx uint16
for ridx = 0; ridx < (resp.Header.RecordLength / 6); ridx++ {
addr := NetbiosReplyAddress{}
binary.Read(temp, binary.BigEndian, &addr)
resp.Addresses = append(resp.Addresses, addr)
}
}
return resp
}
func (this *ProbeNetbios) CreateStatusRequest() []byte {
return []byte{
byte(rand.Intn(256)), byte(rand.Intn(256)),
0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x20, 0x43, 0x4b, 0x41, 0x41, 0x41,
0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41,
0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41,
0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41,
0x41, 0x41, 0x41, 0x00, 0x00, 0x21, 0x00, 0x01,
}
}
func (this *ProbeNetbios) CreateNameRequest(name string) []byte {
nbytes := [16]byte{}
copy(nbytes[0:15], []byte(strings.ToUpper(name)[:]))
req := []byte{
byte(rand.Intn(256)), byte(rand.Intn(256)),
0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x20,
0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41,
0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41,
0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41,
0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41,
0x00, 0x00, 0x20, 0x00, 0x01,
}
encoded := this.EncodeNetbiosName(nbytes)
copy(req[13:45], encoded[0:32])
return req
}
func (this *ProbeNetbios) Initialize() {
this.Setup()
this.name = "netbios"
this.waiter.Add(1)
// Open socket
this.socket, _ = net.ListenPacket("udp", "")
go func() {
go this.ProcessReplies()
for dip := range this.input {
this.SendStatusRequest(dip)
// If our pending replies gets > MAX, stop, process, report, clear, resume
if len(this.replies) > MaxPendingReplies {
log.Printf("probe %s is flushing due to maximum replies hit (%d)", this, len(this.replies))
time.Sleep(MaxProbeResponseTime)
this.ReportIncompleteResults()
}
}
// Sleep for packet timeout of initial probe
log.Printf("probe %s is waiting for final replies to status probe", this)
time.Sleep(MaxProbeResponseTime)
// The receiver is sending interface probes in response to status probes
log.Printf("probe %s is waiting for final replies to interface probe", this)
time.Sleep(MaxProbeResponseTime)
// Shut down receiver
this.socket.Close()
// Report any incomplete results (status reply but no name replies)
this.ReportIncompleteResults()
// Complete
this.waiter.Done()
}()
return
}
func init() {
probes = append(probes, new(ProbeNetbios))
}