-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtrafpol.go
414 lines (344 loc) · 9.46 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
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
414
// Package trafpol contains the traffic policing.
package trafpol
import (
"context"
"fmt"
"net/netip"
log "github.com/sirupsen/logrus"
"github.com/telekom-mms/oc-daemon/internal/cpd"
"github.com/telekom-mms/oc-daemon/internal/daemoncfg"
"github.com/telekom-mms/oc-daemon/internal/devmon"
"github.com/telekom-mms/oc-daemon/internal/dnsmon"
)
// TrafPol command types.
const (
trafPolCmdAddAddress uint8 = iota + 1
trafPolCmdRemoveAddress
trafPolCmdGetState
)
// State is the internal TrafPol state.
type State struct {
CaptivePortal bool
AllowedDevices []string
AllowedAddresses []netip.Prefix
AllowedNames map[string][]netip.Addr
}
// trafPolCmd is a TrafPol command.
type trafPolCmd struct {
typ uint8
ip netip.Addr
ok bool
state *State
done chan struct{}
}
// TrafPol is a traffic policing component.
type TrafPol struct {
config *daemoncfg.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 *AllowAddrs
allowNames *AllowNames
// resolver for allowed names, channel for resolver updates
resolver *Resolver
resolvUp chan *ResolvedName
// address commands channel
cmds chan *trafPolCmd
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" {
if t.allowDevs.Add(u.Device) {
addAllowedDevice(ctx, t.config, u.Device)
}
return
}
if t.allowDevs.Remove(u.Device) {
removeAllowedDevice(ctx, t.config, u.Device)
}
}
// handleDNSUpdate handles a dns config update.
func (t *TrafPol) handleDNSUpdate() {
// update allowed names
t.resolver.Resolve()
// trigger 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)
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)
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() []netip.Prefix {
// get a list of all unique ip addresses from
// - allowed names
// - allowed addrs
ipset := make(map[string]netip.Prefix)
for _, n := range t.allowNames.GetAll() {
for _, ip := range n {
prefix := netip.PrefixFrom(ip, ip.BitLen())
ipset[prefix.String()] = prefix
}
}
for _, a := range t.allowAddrs.List() {
ipset[a.String()] = a
}
// get resulting list of IPs
ips := []netip.Prefix{}
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.Add(update.Name, update.IPs)
// set new filter rules
setAllowedIPs(ctx, t.config, t.getAllowedHostsIPs())
}
// handleAddressCommand handles an address command.
func (t *TrafPol) handleAddressCommand(ctx context.Context, cmd *trafPolCmd) {
// convert to prefix
prefix := netip.PrefixFrom(cmd.ip, cmd.ip.BitLen())
// update allowed addrs
if cmd.typ == trafPolCmdAddAddress {
if ok := t.allowAddrs.Add(prefix); !ok {
// ip already in allowed addrs
return
}
} else {
if ok := t.allowAddrs.Remove(prefix); !ok {
// ip not in allowed addrs
return
}
}
// set new filter rules
setAllowedIPs(ctx, t.config, t.getAllowedHostsIPs())
// added/removed successfully
cmd.ok = true
}
// handleGetStateCommand handles a get state command.
func (t *TrafPol) handleGetStateCommand(cmd *trafPolCmd) {
// set state
cmd.state = &State{
CaptivePortal: t.capPortal,
AllowedDevices: t.allowDevs.List(),
AllowedAddresses: t.allowAddrs.List(),
AllowedNames: t.allowNames.GetAll(),
}
}
// handleCommand handles a command.
func (t *TrafPol) handleCommand(ctx context.Context, cmd *trafPolCmd) {
defer close(cmd.done)
switch cmd.typ {
case trafPolCmdAddAddress, trafPolCmdRemoveAddress:
t.handleAddressCommand(ctx, cmd)
case trafPolCmdGetState:
t.handleGetStateCommand(cmd)
}
}
// start starts the traffic policing component.
func (t *TrafPol) start(ctx context.Context) {
defer close(t.loopDone)
defer unsetFilterRules(ctx, t.config)
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:
// Command
log.WithField("command", c).Debug("TrafPol got command")
t.handleCommand(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)
// set filter rules
setAllowedIPs(ctx, t.config, 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, t.config)
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 netip.Addr) (ok bool) {
log.WithField("addr", addr).
Debug("TrafPol adding IP to allowed addresses")
c := &trafPolCmd{
typ: trafPolCmdAddAddress,
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 netip.Addr) (ok bool) {
log.WithField("addr", addr).
Debug("TrafPol removing IP from allowed addresses")
c := &trafPolCmd{
typ: trafPolCmdRemoveAddress,
ip: addr,
done: make(chan struct{}),
}
t.cmds <- c
<-c.done
return c.ok
}
// GetState returns the internal TrafPol state.
func (t *TrafPol) GetState() *State {
log.Debug("TrafPol getting internal state")
c := &trafPolCmd{
typ: trafPolCmdGetState,
done: make(chan struct{}),
}
t.cmds <- c
<-c.done
return c.state
}
// parseAllowedHosts parses the allowed hosts and returns IP addresses and DNS names
func parseAllowedHosts(hosts []string) (addrs []netip.Prefix, names []string) {
for _, h := range hosts {
// check if it's an IP address
if ip, err := netip.ParseAddr(h); err == nil {
prefix := netip.PrefixFrom(ip, ip.BitLen())
addrs = append(addrs, prefix)
continue
}
// check if it's an IP network
if prefix, err := netip.ParsePrefix(h); err == nil {
addrs = append(addrs, prefix)
continue
}
// assume dns name
names = append(names, h)
}
return
}
// NewTrafPol returns a new traffic policing component.
func NewTrafPol(config *daemoncfg.Config) *TrafPol {
// create cpd
c := cpd.NewCPD(daemoncfg.NewCPD())
// get allowed addrs and names
hosts := append(config.TrafficPolicing.AllowedHosts, c.Hosts()...)
a, n := parseAllowedHosts(hosts)
// create allowed addrs and names
addrs := NewAllowAddrs()
names := NewAllowNames()
for _, addr := range a {
addrs.Add(addr)
}
for _, name := range n {
names.Add(name, []netip.Addr{})
}
// 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.TrafficPolicing, n, resolvUp),
resolvUp: resolvUp,
cmds: make(chan *trafPolCmd),
loopDone: make(chan struct{}),
done: make(chan struct{}),
}
}
// Cleanup cleans up old configuration after a failed shutdown.
func Cleanup(ctx context.Context, conf *daemoncfg.Config) {
cleanupFilterRules(ctx, conf)
}