-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtrafpol.go
375 lines (312 loc) · 8.36 KB
/
trafpol.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
// Package trafpol contains the traffic policing.
package trafpol
import (
"context"
"fmt"
"net"
log "github.com/sirupsen/logrus"
"github.com/telekom-mms/oc-daemon/internal/cpd"
"github.com/telekom-mms/oc-daemon/internal/devmon"
"github.com/telekom-mms/oc-daemon/internal/dnsmon"
)
// trafPolAddrCmd is a TrafPol address command.
type trafPolAddrCmd struct {
add bool
ip net.IP
ok bool
done chan struct{}
}
// TrafPol is a traffic policing component.
type TrafPol struct {
config *Config
devmon *devmon.DevMon
dnsmon *dnsmon.DNSMon
cpd *cpd.CPD
// capPortal indicates if a captive portal is detected
capPortal bool
// allowed devices, addresses, names
allowDevs *AllowDevs
allowAddrs map[string]*net.IPNet
allowNames map[string][]net.IP
// resolver for allowed names, channel for resolver updates
resolver *Resolver
resolvUp chan *ResolvedName
// address commands channel
cmds chan *trafPolAddrCmd
loopDone chan struct{}
done chan struct{}
}
// handleDeviceUpdate handles a device update.
func (t *TrafPol) handleDeviceUpdate(ctx context.Context, u *devmon.Update) {
// add or remove virtual device to/from allowed devices
// skip adding physical devices and only allow adding virtual devices.
// we cannot be sure about the type when removing devices, so do not
// skip when removing devices.
if u.Add && u.Type != "device" {
t.allowDevs.Add(ctx, u.Device)
return
}
t.allowDevs.Remove(ctx, u.Device)
}
// handleDNSUpdate handles a dns config update.
func (t *TrafPol) handleDNSUpdate() {
// update allowed names
t.resolver.Resolve()
// triger captive portal detection
t.cpd.Probe()
}
// handleCPDReport handles a CPD report.
func (t *TrafPol) handleCPDReport(ctx context.Context, report *cpd.Report) {
if !report.Detected {
// no captive portal detected
// check if there was a portal before
if t.capPortal {
// refresh all IPs, maybe they pointed to a
// portal host in case of dns-based portals
t.resolver.Resolve()
// remove ports from allowed ports
removePortalPorts(ctx, t.config.PortalPorts)
t.capPortal = false
log.WithField("capPortal", t.capPortal).Info("TrafPol changed CPD status")
}
return
}
// add ports to allowed ports
if !t.capPortal {
addPortalPorts(ctx, t.config.PortalPorts)
t.capPortal = true
log.WithField("capPortal", t.capPortal).Info("TrafPol changed CPD status")
}
}
// getAllowedHostsIPs returns the IPs of the allowed hosts,
// used for filter rules
func (t *TrafPol) getAllowedHostsIPs() []*net.IPNet {
// get a list of all unique ip addresses from
// - allowed names
// - allowed addrs
ipset := make(map[string]*net.IPNet)
for _, n := range t.allowNames {
for _, ip := range n {
ipnet := &net.IPNet{
IP: ip,
Mask: net.CIDRMask(32, 32),
}
if ip.To4() == nil {
ipnet.Mask = net.CIDRMask(128, 128)
}
ipset[ipnet.String()] = ipnet
}
}
for _, a := range t.allowAddrs {
ipset[a.String()] = a
}
// get resulting list of IPs
ips := []*net.IPNet{}
for _, ip := range ipset {
ips = append(ips, ip)
}
return ips
}
// handleResolverUpdate handles a resolver update.
func (t *TrafPol) handleResolverUpdate(ctx context.Context, update *ResolvedName) {
// update allowed names
t.allowNames[update.Name] = update.IPs
// set new filter rules
setAllowedIPs(ctx, t.getAllowedHostsIPs())
}
// handleAddressCommand handles an address command.
func (t *TrafPol) handleAddressCommand(ctx context.Context, cmd *trafPolAddrCmd) {
defer close(cmd.done)
// convert to ipnet
ipnet := &net.IPNet{IP: cmd.ip, Mask: net.CIDRMask(32, 32)}
if cmd.ip.To4() == nil {
ipnet.Mask = net.CIDRMask(128, 128)
}
// update allowed addrs
s := ipnet.String()
if cmd.add {
if _, ok := t.allowAddrs[s]; ok {
// ip already in allowed addrs
return
}
t.allowAddrs[s] = ipnet
} else {
if _, ok := t.allowAddrs[s]; !ok {
// ip not in allowed addrs
return
}
delete(t.allowAddrs, s)
}
// set new filter rules
setAllowedIPs(ctx, t.getAllowedHostsIPs())
// added/removed successfully
cmd.ok = true
}
// start starts the traffic policing component.
func (t *TrafPol) start(ctx context.Context) {
defer close(t.loopDone)
defer unsetFilterRules(ctx)
defer t.resolver.Stop()
defer t.cpd.Stop()
defer t.devmon.Stop()
defer t.dnsmon.Stop()
// enter main loop
for {
select {
case u := <-t.devmon.Updates():
// Device Update
log.WithField("update", u).Debug("TrafPol got DevMon update")
t.handleDeviceUpdate(ctx, u)
case <-t.dnsmon.Updates():
// DNS Update
log.Debug("TrafPol got DNSMon update")
t.handleDNSUpdate()
case r := <-t.cpd.Results():
// CPD Result
log.WithField("result", r).Debug("TrafPol got CPD result")
t.handleCPDReport(ctx, r)
case u := <-t.resolvUp:
// Resolver Update
log.WithField("update", u).Debug("TrafPol got Resolver update")
t.handleResolverUpdate(ctx, u)
case c := <-t.cmds:
// Address Command
log.WithField("command", c).Debug("TrafPol got address command")
t.handleAddressCommand(ctx, c)
case <-t.done:
// shutdown
return
}
}
}
// Start starts the traffic policing component.
func (t *TrafPol) Start() error {
log.Debug("TrafPol starting")
// create context
ctx := context.Background()
// set firewall config
setFilterRules(ctx, t.config.FirewallMark)
// set filter rules
setAllowedIPs(ctx, t.getAllowedHostsIPs())
// start resolver for allowed names
t.resolver.Start()
// start captive portal detection
t.cpd.Start()
// start device monitor
err := t.devmon.Start()
if err != nil {
err = fmt.Errorf("TrafPol could not start DevMon: %w", err)
goto cleanup_devmon
}
// start dns monitor
err = t.dnsmon.Start()
if err != nil {
err = fmt.Errorf("TrafPol could not start DNSMon: %w", err)
goto cleanup_dnsmon
}
go t.start(ctx)
return nil
// clean up after error
cleanup_dnsmon:
t.devmon.Stop()
cleanup_devmon:
t.cpd.Stop()
t.resolver.Stop()
unsetFilterRules(ctx)
return err
}
// Stop stops the traffic policing component.
func (t *TrafPol) Stop() {
close(t.done)
// wait for everything
<-t.loopDone
log.Debug("TrafPol stopped")
}
// AddAllowedAddr adds addr to the allowed addresses.
func (t *TrafPol) AddAllowedAddr(addr net.IP) (ok bool) {
log.WithField("addr", addr).
Debug("TrafPol adding IP to allowed addresses")
c := &trafPolAddrCmd{
add: true,
ip: addr,
done: make(chan struct{}),
}
t.cmds <- c
<-c.done
return c.ok
}
// RemoveAllowedAddr removes addr from the allowed addresses.
func (t *TrafPol) RemoveAllowedAddr(addr net.IP) (ok bool) {
log.WithField("addr", addr).
Debug("TrafPol removing IP from allowed addresses")
c := &trafPolAddrCmd{
ip: addr,
done: make(chan struct{}),
}
t.cmds <- c
<-c.done
return c.ok
}
// parseAllowedHosts parses the allowed hosts and returns IP addresses and DNS names
func parseAllowedHosts(hosts []string) (addrs []*net.IPNet, names []string) {
for _, h := range hosts {
// check if it's an IP address
if ip := net.ParseIP(h); ip != nil {
ipnet := &net.IPNet{
IP: ip,
Mask: net.CIDRMask(32, 32),
}
if ip.To4() == nil {
ipnet.Mask = net.CIDRMask(128, 128)
}
addrs = append(addrs, ipnet)
continue
}
// check if it's an IP network
if _, ipnet, err := net.ParseCIDR(h); err == nil {
addrs = append(addrs, ipnet)
continue
}
// assume dns name
names = append(names, h)
}
return
}
// NewTrafPol returns a new traffic policing component.
func NewTrafPol(config *Config) *TrafPol {
// create cpd
c := cpd.NewCPD(cpd.NewConfig())
// get allowed addrs and names
hosts := append(config.AllowedHosts, c.Hosts()...)
a, n := parseAllowedHosts(hosts)
// create allowed addrs and names
addrs := make(map[string]*net.IPNet)
names := make(map[string][]net.IP)
for _, addr := range a {
addrs[addr.String()] = addr
}
for _, name := range n {
names[name] = []net.IP{}
}
// create channel for resolver updates
resolvUp := make(chan *ResolvedName)
// return trafpol
return &TrafPol{
config: config,
devmon: devmon.NewDevMon(),
dnsmon: dnsmon.NewDNSMon(dnsmon.NewConfig()),
cpd: c,
allowDevs: NewAllowDevs(),
allowAddrs: addrs,
allowNames: names,
resolver: NewResolver(config, n, resolvUp),
resolvUp: resolvUp,
cmds: make(chan *trafPolAddrCmd),
loopDone: make(chan struct{}),
done: make(chan struct{}),
}
}
// Cleanup cleans up old configuration after a failed shutdown.
func Cleanup(ctx context.Context) {
cleanupFilterRules(ctx)
}