Debian Codegraph @

modules/packet_proxy/packet_proxy_linux.go

raw symbols SCIP
1 package packet_proxy
2
3 import (
4 "fmt"
5 "plugin"
6 "context"
7 "strings"
8 "syscall"
9 "time"
10
11 "github.com/bettercap/bettercap/core"
12 "github.com/bettercap/bettercap/session"
13
14 nfqueue "github.com/florianl/go-nfqueue/v2"
15
16 "github.com/evilsocket/islazy/fs"
17 )
18
19 type PacketProxy struct {
20 session.SessionModule
21 chainName string
22 rule string
23 queue *nfqueue.Nfqueue
24 queueNum int
25 queueCb nfqueue.HookFunc
26 pluginPath string
27 plugin *plugin.Plugin
28 }
29
30 // this is ugly, but since we can only pass a function
31 // (not a struct function) as a callback to nfqueue,
32 // we need this in order to recover the state.
33 var mod *PacketProxy
34
35 func NewPacketProxy(s *session.Session) *PacketProxy {
36 mod = &PacketProxy{
37 SessionModule: session.NewSessionModule("packet.proxy", s),
38 queue: nil,
39 queueCb: nil,
40 queueNum: 0,
41 chainName: "OUTPUT",
42 }
43
44 mod.AddHandler(session.NewModuleHandler("packet.proxy on", "",
45 "Start the NFQUEUE based packet proxy.",
46 func(args []string) error {
47 return mod.Start()
48 }))
49
50 mod.AddHandler(session.NewModuleHandler("packet.proxy off", "",
51 "Stop the NFQUEUE based packet proxy.",
52 func(args []string) error {
53 return mod.Stop()
54 }))
55
56 mod.AddParam(session.NewIntParameter("packet.proxy.queue.num",
57 "0",
58 "NFQUEUE number to bind to."))
59
60 mod.AddParam(session.NewStringParameter("packet.proxy.chain",
61 "OUTPUT",
62 "",
63 "Chain name of the iptables rule."))
64
65 mod.AddParam(session.NewStringParameter("packet.proxy.plugin",
66 "",
67 "",
68 "Go plugin file to load and call for every packet."))
69
70 mod.AddParam(session.NewStringParameter("packet.proxy.rule",
71 "",
72 "",
73 "Any additional iptables rule to make the queue more selective (ex. --destination 8.8.8.8)."))
74
75 return mod
76 }
77
78 func (mod PacketProxy) Name() string {
79 return "packet.proxy"
80 }
81
82 func (mod PacketProxy) Description() string {
83 return "A Linux only module that relies on NFQUEUEs in order to filter packets."
84 }
85
86 func (mod PacketProxy) Author() string {
87 return "Simone Margaritelli <[email protected]>"
88 }
89
90 func (mod *PacketProxy) destroyQueue() {
91 if mod.queue == nil {
92 return
93 }
94
95 mod.queue.Close()
96 mod.queue = nil
97 }
98
99 func (mod *PacketProxy) runRule(enable bool) (err error) {
100 action := "-I"
101 if !enable {
102 action = "-D"
103 }
104
105 args := []string{
106 action, mod.chainName,
107 }
108
109 if mod.rule != "" {
110 rule := strings.Split(mod.rule, " ")
111 args = append(args, rule...)
112 }
113
114 args = append(args, []string{
115 "-j", "NFQUEUE",
116 "--queue-num", fmt.Sprintf("%d", mod.queueNum),
117 }...)
118
119 mod.Debug("iptables %s", args)
120
121 _, err = core.Exec("iptables", args)
122 return
123 }
124
125 func (mod *PacketProxy) Configure() (err error) {
126 mod.destroyQueue()
127
128 if err, mod.queueNum = mod.IntParam("packet.proxy.queue.num"); err != nil {
129 return
130 } else if err, mod.chainName = mod.StringParam("packet.proxy.chain"); err != nil {
131 return
132 } else if err, mod.rule = mod.StringParam("packet.proxy.rule"); err != nil {
133 return
134 } else if err, mod.pluginPath = mod.StringParam("packet.proxy.plugin"); err != nil {
135 return
136 }
137
138 if mod.pluginPath != "" {
139 if !fs.Exists(mod.pluginPath) {
140 return fmt.Errorf("%s does not exist.", mod.pluginPath)
141 }
142
143 mod.Info("loading packet proxy plugin from %s ...", mod.pluginPath)
144
145 var ok bool
146 var sym plugin.Symbol
147
148 if mod.plugin, err = plugin.Open(mod.pluginPath); err != nil {
149 return
150 } else if sym, err = mod.plugin.Lookup("OnPacket"); err != nil {
151 return
152 } else if mod.queueCb, ok = sym.(func(nfqueue.Attribute) int); !ok {
153 return fmt.Errorf("Symbol OnPacket is not a valid callback function.")
154 }
155
156 if sym, err = mod.plugin.Lookup("OnStart"); err == nil {
157 var onStartCb func() int
158 if onStartCb, ok = sym.(func() int); !ok {
159 return fmt.Errorf("OnStart signature does not match expected signature: 'func() int'")
160 } else {
161 var result int
162 if result = onStartCb(); result != 0 {
163 return fmt.Errorf("OnStart returned non-zero result. result=%d", result)
164 }
165 }
166 }
167 } else {
168 mod.Warning("no plugin set")
169 }
170
171 config := nfqueue.Config {
172 NfQueue: uint16(mod.queueNum),
173 Copymode: nfqueue.NfQnlCopyPacket,
174 AfFamily: syscall.AF_INET,
175 MaxPacketLen: 0xFFFF,
176 MaxQueueLen: 0xFF,
177 WriteTimeout: 15 * time.Millisecond,
178 }
179
180 mod.Debug("config: %+v", config)
181
182 if err = mod.runRule(true); err != nil {
183 return
184 } else if mod.queue, err = nfqueue.Open(&config); err != nil {
185 return
186 } else if err = mod.queue.RegisterWithErrorFunc(context.Background(), dummyCallback, func(e error) int {
187 mod.Error("%v", e)
188 return -1
189 }); err != nil {
190 return
191 }
192
193 return nil
194 }
195
196 // we need this because for some reason we can't directly
197 // pass the symbol loaded from the plugin as a direct
198 // CGO callback ... ¯\_(ツ)_/¯
199 func dummyCallback(attribute nfqueue.Attribute) int {
200 if mod.queueCb != nil {
201 return mod.queueCb(attribute)
202 } else {
203 id := *attribute.PacketID
204
205 mod.Info("[%d] %v", id, *attribute.Payload)
206
207 mod.queue.SetVerdict(id, nfqueue.NfAccept)
208 return 0
209 }
210 }
211
212 func (mod *PacketProxy) Start() error {
213 if mod.Running() {
214 return session.ErrAlreadyStarted(mod.Name())
215 } else if err := mod.Configure(); err != nil {
216 return err
217 }
218
219 return mod.SetRunning(true, func() {
220 mod.Info("started on queue number %d", mod.queueNum)
221 })
222 }
223
224 func (mod *PacketProxy) Stop() (err error) {
225 return mod.SetRunning(false, func() {
226 mod.runRule(false)
227
228 if mod.plugin != nil {
229 var sym plugin.Symbol
230 if sym, err = mod.plugin.Lookup("OnStop"); err == nil {
231 var onStopCb func()
232 var ok bool
233 if onStopCb, ok = sym.(func()); !ok {
234 mod.Error("OnStop signature does not match expected signature: 'func()', unable to call OnStop.")
235 } else {
236 onStopCb()
237 }
238 }
239 }
240 })
241 }