This repository has been archived by the owner on Feb 13, 2024. It is now read-only.
forked from barlowhaydnb/tpclash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patharp.go
107 lines (90 loc) · 2.09 KB
/
arp.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
package main
import (
"bytes"
"context"
"time"
"github.com/sirupsen/logrus"
arp "github.com/irai/packet/handlers/arp_spoofer"
"github.com/irai/packet"
)
type ARPHijacker struct {
tpcc *TPClashConf
cc *ClashConf
ips map[string]struct{}
}
func NewARPHijacker(cc *ClashConf, tpcc *TPClashConf) *ARPHijacker {
ips := map[string]struct{}{}
for _, ip := range tpcc.HijackIP {
ips[ip.String()] = struct{}{}
}
return &ARPHijacker{
tpcc: tpcc,
cc: cc,
ips: ips,
}
}
func (h *ARPHijacker) hijack(ctx context.Context) error {
s, err := packet.NewSession(h.cc.InterfaceName)
if err != nil {
return err
}
sf, err := arp.New(s)
if err != nil {
return err
}
// start packet processing goroutine
go func() {
defer s.Close()
defer func() { _ = sf.Close() }()
buffer := make([]byte, packet.EthMaxSize)
for {
n, _, err := s.ReadFrom(buffer)
if err != nil {
select {
case <-ctx.Done():
default:
logrus.Errorf("failed to reading packet: %v", err)
}
return
}
// Ignore packets sent by us
if bytes.Equal(packet.SrcMAC(buffer[:n]), s.NICInfo.HostAddr4.MAC) {
continue
}
// memory map packet so we can access all fields
frame, err := s.Parse(buffer[:n])
if err != nil {
logrus.Debugf("[ARP] failed to parse frame: %v", err)
continue
}
s.Notify(frame)
}
}()
go func() {
for {
select {
case <-ctx.Done():
return
case notification := <-s.C:
_, all := h.ips["0.0.0.0"]
_, contain := h.ips[notification.Addr.IP.String()]
if !all && !contain {
continue
}
switch notification.Online {
case true:
logrus.Infof("[ARP] %s %s is online...", notification.Addr.IP.String(), notification.Addr.MAC.String())
_, _ = sf.StartHunt(notification.Addr)
default:
logrus.Warnf("[ARP] %s %s is offline...", notification.Addr.IP.String(), notification.Addr.MAC.String())
_, _ = sf.StopHunt(notification.Addr)
}
case <-time.Tick(10 * time.Second):
if err = sf.Scan(); err != nil {
logrus.Errorf("[ARP] failed to scan: %v", err)
}
}
}
}()
return sf.Scan()
}