Repository navigation
Expand file tree
/
Copy pathhandler.go
More file actions
413 lines (359 loc) · 12.1 KB
/
Copy pathhandler.go
File metadata and controls
413 lines (359 loc) · 12.1 KB
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
package arp
import (
"bytes"
"context"
"fmt"
"net"
"sync"
"time"
"log"
marp "github.com/mdlayher/arp"
)
// Config holds configuration parameters
//
// Set FullNetworkScanInterval = 0 to avoid network scan
type Config struct {
NIC string `yaml:"-"`
HostMAC net.HardwareAddr `yaml:"-"`
HostIP net.IP `yaml:"-"`
RouterIP net.IP `yaml:"-"`
HomeLAN net.IPNet `yaml:"-"`
FullNetworkScanInterval time.Duration `yaml:"-"` // Set it to zero if no scan required
ProbeInterval time.Duration `yaml:"-"` // how often to probe if IP is online
OfflineDeadline time.Duration `yaml:"-"` // mark offline if more than OfflineInte
PurgeDeadline time.Duration `yaml:"-"`
}
func (c Config) String() string {
return fmt.Sprintf("hostmac=%s hostIP=%s routerIP=%s homeLAN=%s scan=%v probe=%s offline=%v purge=%v",
c.HostMAC, c.HostIP, c.RouterIP, c.HomeLAN, c.FullNetworkScanInterval, c.ProbeInterval, c.OfflineDeadline, c.PurgeDeadline)
}
// Handler stores instance variables
type Handler struct {
client *marp.Client
table *arpTable
config Config
routerEntry MACEntry // store the router mac address
sync.RWMutex
notification chan<- MACEntry // notification channel for state change
ctx context.Context // context to cancel internal goroutines
}
var (
// Debug - set Debug to true to see debugging messages
Debug bool
)
// New creates an ARP handler for a given interface.
func New(config Config) (c *Handler, err error) {
c = newHandler(config)
ifi, err := net.InterfaceByName(config.NIC)
if err != nil {
return nil, fmt.Errorf("InterfaceByName error: %w", err)
}
// Set up ARP client with socket
c.client, err = marp.Dial(ifi)
if err != nil {
return nil, fmt.Errorf("ARP dial error: %w", err)
}
return c, nil
}
func newHandler(config Config) (c *Handler) {
c = &Handler{}
c.table, _ = loadARPProcTable() // load linux proc table
c.config.NIC = config.NIC
c.config.HostMAC = config.HostMAC
c.config.HostIP = config.HostIP.To4()
c.config.RouterIP = config.RouterIP.To4()
c.config.HomeLAN = config.HomeLAN
c.config.FullNetworkScanInterval = config.FullNetworkScanInterval
c.config.ProbeInterval = config.ProbeInterval
c.config.OfflineDeadline = config.OfflineDeadline
c.config.PurgeDeadline = config.PurgeDeadline
if c.config.FullNetworkScanInterval <= 0 || c.config.FullNetworkScanInterval > time.Hour*12 {
c.config.FullNetworkScanInterval = time.Minute * 60
}
if c.config.ProbeInterval <= 0 || c.config.ProbeInterval > time.Minute*10 {
c.config.ProbeInterval = time.Minute * 2
}
if c.config.OfflineDeadline <= c.config.ProbeInterval {
c.config.OfflineDeadline = c.config.ProbeInterval * 2
}
if c.config.PurgeDeadline <= c.config.OfflineDeadline {
c.config.PurgeDeadline = time.Minute * 61
}
if Debug {
log.Printf("ARP Config %s", c.config)
c.PrintTable()
}
return c
}
// AddNotificationChannel set the notification channel for when the MACEntry
// change state between online and offline.
func (c *Handler) AddNotificationChannel(notification chan<- MACEntry) {
c.notification = notification
c.Lock()
table := c.table.getTable()
c.Unlock()
go func() {
for i := range table {
c.notification <- table[i]
}
}()
}
// FindMAC returns a MACEntry or empty if not found
func (c *Handler) FindMAC(mac net.HardwareAddr) (entry MACEntry, found bool) {
c.RLock()
defer c.RUnlock()
e := c.table.findByMAC(mac)
if e == nil {
return MACEntry{}, false
}
return *e, true
}
// FindIP returns a MACEntry or empty if not found
func (c *Handler) FindIP(ip net.IP) (entry MACEntry, found bool) {
c.RLock()
defer c.RUnlock()
e := c.table.findByIP(ip)
if e == nil {
return MACEntry{}, false
}
return *e, true
}
// PrintTable print the ARP table to stdout.
func (c *Handler) PrintTable() {
c.RLock()
defer c.RUnlock()
log.Printf("ARP Table: %v entries", len(c.table.macTable))
c.table.printTable()
}
// GetTable return the mac table as a shallow array of MACEntry
func (c *Handler) GetTable() []MACEntry {
return c.table.getTable()
}
// Close will terminate the ListenAndServer goroutine as well as all other pending goroutines.
func (c *Handler) Close() {
// Close the arp socket
c.client.Close()
}
// ListenAndServe listen for ARP packets and action each.
//
// When a new MAC is detected, it is automatically added to the ARP table and marked as online.
// Use packet buffer and selectivelly copy mac and ip if we need to keep it
//
// Online and offline notifications
// It will track when a MAC switch between online and offline and will send a message
// in the notification channel set via AddNotificationChannel(). It will poll each known device
// based on the scanInterval parameter using a unicast ARP request.
//
//
// Virtual MACs
// A virtual MAC is a fake mac address used when claiming an existing IP during spoofing.
// ListenAndServe will send ARP reply on behalf of virtual MACs
//
func (c *Handler) ListenAndServe(ctx context.Context) error {
var wg sync.WaitGroup
// Set ZERO timeout to block forever
if err := c.client.SetReadDeadline(time.Time{}); err != nil {
return fmt.Errorf("ARP error in socket: %w", err)
}
myctx, cancel := context.WithCancel(ctx)
c.ctx = myctx
if c.config.FullNetworkScanInterval != 0 {
// continuosly scan for network devices
go func() {
wg.Add(1)
if err := c.scanLoop(c.ctx, c.config.FullNetworkScanInterval); err != nil {
log.Print("ARP goroutine scanLoop terminated unexpectedly", err)
c.Close() // force error in main loop
}
wg.Done()
if Debug {
log.Print("ARP goroutine scanLoop ended")
}
}()
}
// continously probe for online reply
go func() {
wg.Add(1)
if err := c.probeOnlineLoop(c.ctx, c.config.ProbeInterval); err != nil {
log.Print("ARP goroutine probeOnlineLoop terminated unexpectedly", err)
}
c.Close() // close conn to force error in main loopi to finish quickly
wg.Done()
if Debug {
log.Print("ARP goroutine probeOnlineLoop ended")
}
}()
// continously check for online-offline transition
go func() {
wg.Add(1)
if err := c.purgeLoop(c.ctx, c.config.OfflineDeadline, c.config.PurgeDeadline); err != nil {
log.Print("ARP ListenAndServer purgeLoop terminated unexpectedly", err)
c.Close() // force error in main loop
}
wg.Done()
if Debug {
log.Print("ARP goroutine purgeLoop ended")
}
}()
// Do a full scan on start
if c.config.FullNetworkScanInterval != 0 {
go func() {
time.Sleep(time.Millisecond * 100) // Time to start read loop below
if err := c.ScanNetwork(c.ctx, c.config.HomeLAN); err != nil {
log.Print("ARP ListenAndServer scanNetwork terminated unexpectedly", err)
c.Close() // force error in main loop
}
if Debug {
log.Print("ARP goroutine scanNetwork ended")
}
}()
}
// Loop and wait for ARP packets
for {
packet, _, err := c.client.Read()
if ctx.Err() != nil {
cancel()
wg.Wait()
if Debug {
log.Print("ARP goroutine ListenAndServe ended")
}
return nil
}
if err != nil {
// "interrupted system call" occurs frequently after go 1.14
// simply retry - don't wait
if err1, ok := err.(net.Error); ok && err1.Temporary() {
// log.Print("ARP read error is temporary - retry ", err1)
continue
}
if Debug {
log.Print("ARP read error ", err)
}
cancel()
wg.Wait()
return fmt.Errorf("ARP ListenAndServer terminated unexpectedly: %w", err)
}
notify := 0
// skip link local packets
if packet.SenderIP.IsLinkLocalUnicast() ||
packet.TargetIP.IsLinkLocalUnicast() {
if Debug {
log.Printf("ARP skipping link local packet smac=%v sip=%v tmac=%v tip=%v", packet.SenderHardwareAddr, packet.SenderIP, packet.TargetHardwareAddr, packet.TargetIP)
}
continue
}
if Debug {
switch {
case packet.Operation == marp.OperationReply:
log.Printf("ARP ip=%s reply recvd smac=%s tmac=%s tip=%s", packet.SenderIP, packet.SenderHardwareAddr, packet.TargetHardwareAddr, packet.TargetIP)
case packet.Operation == marp.OperationRequest:
switch {
case packet.SenderIP.Equal(packet.TargetIP):
log.Printf("ARP ip=%s announcement recvd smac=%s tmac=%s tip=%s", packet.SenderIP, packet.SenderHardwareAddr, packet.TargetHardwareAddr, packet.TargetIP)
case packet.SenderIP.Equal(net.IPv4zero):
log.Printf("ARP ip=%s probe recvd for tip=%s smac=%s tmac=%s", packet.SenderIP, packet.TargetIP, packet.SenderHardwareAddr, packet.TargetHardwareAddr)
default:
log.Printf("ARP ip=%s who is tip=%s smac=%v tmac=%v", packet.SenderIP, packet.TargetIP, packet.SenderHardwareAddr, packet.TargetHardwareAddr)
}
default:
log.Printf("ARP invalid operation=%v packet=%+v", packet.Operation, packet)
continue
}
}
// Ignore router packets
if bytes.Equal(packet.SenderIP, c.config.RouterIP) {
if c.routerEntry.MAC == nil { // store router MAC
c.routerEntry.MAC = dupMAC(packet.SenderHardwareAddr)
c.routerEntry.IPArray[0] = IPEntry{IP: c.config.RouterIP}
}
continue
}
// Ignore host packets
if bytes.Equal(packet.SenderHardwareAddr, c.config.HostMAC) {
continue
}
// if targetIP is a virtual host, we are claiming the ip; reply and return
c.RLock()
if target := c.table.findVirtualIP(packet.TargetIP); target != nil {
mac := target.MAC
c.RUnlock()
if Debug {
log.Printf("ARP ip=%s is virtual - send reply smac=%v", packet.TargetIP, mac)
}
c.reply(packet.SenderHardwareAddr, mac, packet.TargetIP, EthernetBroadcast, packet.TargetIP)
continue
}
c.RUnlock()
// We are not interested in probe ACD (Address Conflict Detection) packets
// if this is a probe, the sender IP will be zeros; do nothing as the sender IP is not valid yet.
//
// +============+===+===========+===========+============+============+===================+===========+
// | Type | op| dstMAC | srcMAC | SenderMAC | SenderIP | TargetMAC | TargetIP |
// +============+===+===========+===========+============+============+===================+===========+
// | ACD probe | 1 | broadcast | clientMAC | clientMAC | 0x00 | 0x00 | targetIP |
// | ACD announ | 1 | broadcast | clientMAC | clientMAC | clientIP | ff:ff:ff:ff:ff:ff | clientIP |
// +============+===+===========+===========+============+============+===================+===========+
if packet.SenderIP.Equal(net.IPv4zero) {
continue
}
c.Lock()
sender := c.table.findByMAC(packet.SenderHardwareAddr)
if sender == nil {
// If new client, then create a MACEntry in table
sender, _ = c.table.upsert(StateNormal, dupMAC(packet.SenderHardwareAddr), dupIP(packet.SenderIP))
notify++
} else {
// notify online transition
if sender.Online == false {
notify++
}
}
// Skip packets that we sent as virtual host (i.e. we sent these)
if sender.State == StateVirtualHost {
c.Unlock()
continue
}
sender.LastUpdated = time.Now()
switch packet.Operation {
case marp.OperationRequest:
switch sender.State {
case StateHunt:
// If this is a new IP, stop hunting it.
// The spoof goroutine will detect the mac changed to normal and terminate.
if !c.table.updateIP(sender, dupIP(packet.SenderIP)) {
sender.State = StateNormal
notify++
}
case StateNormal:
if !c.table.updateIP(sender, dupIP(packet.SenderIP)) {
notify++
}
default:
log.Print("ARP unexpected client state in request =", sender.State)
}
case marp.OperationReply:
// Android does not send collision detection request,
// we will see a reply instead. Check if the address has changed.
if !c.table.updateIP(sender, dupIP(packet.SenderIP)) {
sender.State = StateNormal // will end hunt goroutine
notify++
}
}
if notify > 0 {
if sender.Online == false {
sender.Online = true
if Debug {
log.Printf("ARP ip=%s is online mac=%s state=%s ips=%s", packet.SenderIP, sender.MAC, sender.State, sender.IPs())
}
} else {
if Debug {
log.Printf("ARP ip=%s is online - updated ip for mac=%s state=%s ips=%s", packet.SenderIP, sender.MAC, sender.State, sender.IPs())
}
}
if c.notification != nil {
c.notification <- *sender
}
}
c.Unlock()
}
}