-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathvpnsetup.go
547 lines (462 loc) · 13.6 KB
/
vpnsetup.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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
// Package vpnsetup contains the VPN setup component.
package vpnsetup
import (
"context"
"net"
"strconv"
"strings"
"time"
log "github.com/sirupsen/logrus"
"github.com/telekom-mms/oc-daemon/internal/dnsproxy"
"github.com/telekom-mms/oc-daemon/internal/execs"
"github.com/telekom-mms/oc-daemon/internal/splitrt"
"github.com/telekom-mms/oc-daemon/pkg/vpnconfig"
)
// command types.
const (
commandSetup uint8 = iota
commandTeardown
)
// command is a VPNSetup command.
type command struct {
cmd uint8
vpnconf *vpnconfig.Config
done chan struct{}
}
// VPNSetup sets up the configuration of the vpn tunnel that belongs to the
// current VPN connection.
type VPNSetup struct {
splitrt *splitrt.SplitRouting
splitrtConf *splitrt.Config
dnsProxy *dnsproxy.Proxy
dnsProxyConf *dnsproxy.Config
ensureDone chan struct{}
ensureClosed chan struct{}
cmds chan *command
done chan struct{}
closed chan struct{}
}
// setupVPNDevice sets up the vpn device with config.
func setupVPNDevice(ctx context.Context, c *vpnconfig.Config) {
// set mtu on device
mtu := strconv.Itoa(c.Device.MTU)
if stdout, stderr, err := execs.RunIPLink(ctx, "set", c.Device.Name, "mtu", mtu); err != nil {
log.WithError(err).WithFields(log.Fields{
"device": c.Device.Name,
"mtu": mtu,
"stdout": string(stdout),
"stderr": string(stderr),
}).Error("Daemon could not set mtu on device")
return
}
// set device up
if stdout, stderr, err := execs.RunIPLink(ctx, "set", c.Device.Name, "up"); err != nil {
log.WithError(err).WithFields(log.Fields{
"device": c.Device.Name,
"stdout": string(stdout),
"stderr": string(stderr),
}).Error("Daemon could not set device up")
return
}
// set ipv4 and ipv6 addresses on device
setupIP := func(ip net.IP, mask net.IPMask) {
ipnet := &net.IPNet{
IP: ip,
Mask: mask,
}
dev := c.Device.Name
addr := ipnet.String()
if stdout, stderr, err := execs.RunIPAddress(ctx, "add", addr, "dev", dev); err != nil {
log.WithError(err).WithFields(log.Fields{
"device": dev,
"ip": addr,
"stdout": string(stdout),
"stderr": string(stderr),
}).Error("Daemon could not set ip on device")
return
}
}
if len(c.IPv4.Address) > 0 {
setupIP(c.IPv4.Address, c.IPv4.Netmask)
}
if len(c.IPv6.Address) > 0 {
setupIP(c.IPv6.Address, c.IPv6.Netmask)
}
}
// teardownVPNDevice tears down the configured vpn device.
func teardownVPNDevice(ctx context.Context, c *vpnconfig.Config) {
// set device down
if stdout, stderr, err := execs.RunIPLink(ctx, "set", c.Device.Name, "down"); err != nil {
log.WithError(err).WithFields(log.Fields{
"device": c.Device.Name,
"stdout": string(stdout),
"stderr": string(stderr),
}).Error("Daemon could not set device down")
return
}
}
// setupRouting sets up routing using config.
func (v *VPNSetup) setupRouting(vpnconf *vpnconfig.Config) {
if v.splitrt != nil {
return
}
v.splitrt = splitrt.NewSplitRouting(v.splitrtConf, vpnconf)
if err := v.splitrt.Start(); err != nil {
log.WithError(err).Error("VPNSetup error setting split routing")
}
}
// teardownRouting tears down the routing configuration.
func (v *VPNSetup) teardownRouting() {
if v.splitrt == nil {
return
}
v.splitrt.Stop()
v.splitrt = nil
}
// setupDNSServer sets the DNS server.
func (v *VPNSetup) setupDNSServer(ctx context.Context, config *vpnconfig.Config) {
device := config.Device.Name
if stdout, stderr, err := execs.RunResolvectl(ctx, "dns", device, v.dnsProxyConf.Address); err != nil {
log.WithError(err).WithFields(log.Fields{
"device": device,
"server": v.dnsProxyConf.Address,
"stdout": string(stdout),
"stderr": string(stderr),
}).Error("VPNSetup error setting dns server")
}
}
// setupDNSDomains sets the DNS domains.
func (v *VPNSetup) setupDNSDomains(ctx context.Context, config *vpnconfig.Config) {
device := config.Device.Name
if stdout, stderr, err := execs.RunResolvectl(ctx, "domain", device, config.DNS.DefaultDomain, "~."); err != nil {
log.WithError(err).WithFields(log.Fields{
"device": device,
"domain": config.DNS.DefaultDomain,
"stdout": string(stdout),
"stderr": string(stderr),
}).Error("VPNSetup error setting dns domains")
}
}
// setupDNSDefaultRoute sets the DNS default route.
func (v *VPNSetup) setupDNSDefaultRoute(ctx context.Context, config *vpnconfig.Config) {
device := config.Device.Name
if stdout, stderr, err := execs.RunResolvectl(ctx, "default-route", device, "yes"); err != nil {
log.WithError(err).WithFields(log.Fields{
"device": device,
"stdout": string(stdout),
"stderr": string(stderr),
}).Error("VPNSetup error setting dns default route")
}
}
// setupDNS sets up DNS using config.
func (v *VPNSetup) setupDNS(ctx context.Context, config *vpnconfig.Config) {
// configure dns proxy
// set remotes
remotes := config.DNS.Remotes()
v.dnsProxy.SetRemotes(remotes)
// set watches
excludes := config.Split.DNSExcludes()
log.WithField("excludes", excludes).Debug("Daemon setting DNS Split Excludes")
v.dnsProxy.SetWatches(excludes)
// update dns configuration of host
// set dns server for device
v.setupDNSServer(ctx, config)
// set domains for device
// this includes "~." to use this device for all domains
v.setupDNSDomains(ctx, config)
// set default route for device
v.setupDNSDefaultRoute(ctx, config)
// flush dns caches
if stdout, stderr, err := execs.RunResolvectl(ctx, "flush-caches"); err != nil {
log.WithError(err).WithFields(log.Fields{
"stdout": string(stdout),
"stderr": string(stderr),
}).Error("VPNSetup error flushing dns caches during setup")
}
// reset learnt server features
if stdout, stderr, err := execs.RunResolvectl(ctx, "reset-server-features"); err != nil {
log.WithError(err).WithFields(log.Fields{
"stdout": string(stdout),
"stderr": string(stderr),
}).Error("VPNSetup error resetting server features during setup")
}
}
// teardownDNS tears down the DNS configuration.
func (v *VPNSetup) teardownDNS(ctx context.Context, vpnconf *vpnconfig.Config) {
// update dns proxy configuration
// reset remotes
remotes := map[string][]string{}
v.dnsProxy.SetRemotes(remotes)
// reset watches
v.dnsProxy.SetWatches([]string{})
// update dns configuration of host
// undo device dns configuration
if stdout, stderr, err := execs.RunResolvectl(ctx, "revert", vpnconf.Device.Name); err != nil {
log.WithError(err).WithFields(log.Fields{
"device": vpnconf.Device.Name,
"stdout": string(stdout),
"stderr": string(stderr),
}).Error("VPNSetup error reverting dns configuration")
}
// flush dns caches
if stdout, stderr, err := execs.RunResolvectl(ctx, "flush-caches"); err != nil {
log.WithError(err).WithFields(log.Fields{
"stdout": string(stdout),
"stderr": string(stderr),
}).Error("VPNSetup error flushing dns caches during teardown")
}
// reset learnt server features
if stdout, stderr, err := execs.RunResolvectl(ctx, "reset-server-features"); err != nil {
log.WithError(err).WithFields(log.Fields{
"stdout": string(stdout),
"stderr": string(stderr),
}).Error("VPNSetup error resetting server features during teardown")
}
}
// checkDNSProtocols checks the configured DNS protocols, only checks default-route.
func (v *VPNSetup) checkDNSProtocols(protocols []string) bool {
// check if default route is set
ok := false
for _, protocol := range protocols {
if protocol == "+DefaultRoute" {
ok = true
}
}
return ok
}
// checkDNSServers checks the configured DNS servers.
func (v *VPNSetup) checkDNSServers(servers []string) bool {
// check dns server ip
if len(servers) != 1 || servers[0] != v.dnsProxyConf.Address {
// server not correct
return false
}
return true
}
// checkDNSDomain checks the configured DNS domains.
func (v *VPNSetup) checkDNSDomain(config *vpnconfig.Config, domains []string) bool {
// get domains in config
inConfig := strings.Fields(config.DNS.DefaultDomain)
inConfig = append(inConfig, "~.")
// check domains in config
for _, c := range inConfig {
found := false
for _, d := range domains {
if c == d {
found = true
}
}
if !found {
// domains not correct
return false
}
}
return true
}
// ensureDNS ensures the DNS config.
func (v *VPNSetup) ensureDNS(ctx context.Context, config *vpnconfig.Config) bool {
log.Debug("VPNSetup checking DNS settings")
// get dns settings
device := config.Device.Name
stdout, stderr, err := execs.RunResolvectl(ctx, "status", device, "--no-pager")
if err != nil {
log.WithError(err).WithFields(log.Fields{
"device": device,
"stdout": string(stdout),
"stderr": string(stderr),
}).Error("VPNSetup error getting DNS settings")
return false
}
// parse and check dns settings line by line
var protOK, srvOK, domOK bool
lines := strings.Split(string(stdout), "\n")
for _, line := range lines {
// try to find separator ":"
before, after, found := strings.Cut(strings.TrimSpace(line), ":")
if !found {
continue
}
// get fields after separator
f := strings.Fields(after)
// check settings if present
switch before {
case "Protocols":
protOK = v.checkDNSProtocols(f)
case "DNS Servers":
srvOK = v.checkDNSServers(f)
case "DNS Domain":
domOK = v.checkDNSDomain(config, f)
}
}
// reset settings if incorrect/not present
if !protOK {
// protocols are not correct
log.Error("VPNSetup found invalid DNS protocols, trying to fix")
// reset default route for device
v.setupDNSDefaultRoute(ctx, config)
}
if !srvOK {
// servers are not correct
log.Error("VPNSetup found invalid DNS servers, trying to fix")
// reset dns server
v.setupDNSServer(ctx, config)
}
if !domOK {
// domains are not correct
log.Error("VPNSetup found invalid DNS domains, trying to fix")
// reset domains for device
v.setupDNSDomains(ctx, config)
}
// combine results
return protOK && srvOK && domOK
}
// ensureConfig ensured that the VPN config is and stays active.
func (v *VPNSetup) ensureConfig(ctx context.Context, vpnconf *vpnconfig.Config) {
defer close(v.ensureClosed)
timerInvalid := time.Second
timerValid := 15 * time.Second
timer := timerInvalid
for {
select {
case <-time.After(timer):
log.Debug("VPNSetup checking VPN configuration")
// ensure DNS settings
if ok := v.ensureDNS(ctx, vpnconf); !ok {
timer = timerInvalid
break
}
// vpn config is OK
timer = timerValid
case <-v.ensureDone:
return
}
}
}
// startEnsure starts ensuring the VPN config.
func (v *VPNSetup) startEnsure(ctx context.Context, vpnconf *vpnconfig.Config) {
v.ensureDone = make(chan struct{})
v.ensureClosed = make(chan struct{})
go v.ensureConfig(ctx, vpnconf)
}
// stopEnsure stops ensuring the VPN config.
func (v *VPNSetup) stopEnsure() {
close(v.ensureDone)
<-v.ensureClosed
}
// setup sets up the vpn configuration.
func (v *VPNSetup) setup(ctx context.Context, vpnconf *vpnconfig.Config) {
// setup device, routing, dns
setupVPNDevice(ctx, vpnconf)
v.setupRouting(vpnconf)
v.setupDNS(ctx, vpnconf)
// ensure VPN config
v.startEnsure(ctx, vpnconf)
}
// teardown tears down the vpn configuration.
func (v *VPNSetup) teardown(ctx context.Context, vpnconf *vpnconfig.Config) {
// stop ensuring VPN config
v.stopEnsure()
// tear down device, routing, dns
teardownVPNDevice(ctx, vpnconf)
v.teardownRouting()
v.teardownDNS(ctx, vpnconf)
}
// handleCommand handles a command.
func (v *VPNSetup) handleCommand(ctx context.Context, c *command) {
defer close(c.done)
switch c.cmd {
case commandSetup:
v.setup(ctx, c.vpnconf)
case commandTeardown:
v.teardown(ctx, c.vpnconf)
}
}
// handleDNSReport handles a DNS report.
func (v *VPNSetup) handleDNSReport(r *dnsproxy.Report) {
log.WithField("report", r).Debug("Daemon handling DNS report")
if v.splitrt == nil {
// split routing not active, close report and do not forward
r.Close()
return
}
// forward report to split routing
select {
case v.splitrt.DNSReports() <- r:
case <-v.done:
}
}
// start starts the VPN setup.
func (v *VPNSetup) start() {
defer close(v.closed)
// create context
ctx := context.Background()
// start DNS-Proxy
v.dnsProxy.Start()
defer v.dnsProxy.Stop()
for {
select {
case c := <-v.cmds:
v.handleCommand(ctx, c)
case r := <-v.dnsProxy.Reports():
v.handleDNSReport(r)
case <-v.done:
return
}
}
}
// Start starts the VPN setup.
func (v *VPNSetup) Start() {
go v.start()
}
// Stop stops the VPN setup.
func (v *VPNSetup) Stop() {
close(v.done)
<-v.closed
}
// Setup sets the VPN config up.
func (v *VPNSetup) Setup(vpnconfig *vpnconfig.Config) {
c := &command{
cmd: commandSetup,
vpnconf: vpnconfig,
done: make(chan struct{}),
}
v.cmds <- c
<-c.done
}
// Teardown tears the VPN config down.
func (v *VPNSetup) Teardown(vpnconfig *vpnconfig.Config) {
c := &command{
cmd: commandTeardown,
vpnconf: vpnconfig,
done: make(chan struct{}),
}
v.cmds <- c
<-c.done
}
// NewVPNSetup returns a new VPNSetup.
func NewVPNSetup(
dnsProxyConfig *dnsproxy.Config,
splitrtConfig *splitrt.Config,
) *VPNSetup {
return &VPNSetup{
dnsProxy: dnsproxy.NewProxy(dnsProxyConfig),
dnsProxyConf: dnsProxyConfig,
splitrtConf: splitrtConfig,
cmds: make(chan *command),
done: make(chan struct{}),
closed: make(chan struct{}),
}
}
// Cleanup cleans up the configuration after a failed shutdown.
func Cleanup(ctx context.Context, vpnDevice string, splitrtConfig *splitrt.Config) {
// dns, device, split routing
if _, _, err := execs.RunResolvectl(ctx, "revert", vpnDevice); err == nil {
log.WithField("device", vpnDevice).
Warn("VPNSetup cleaned up dns config")
}
if _, _, err := execs.RunIPLink(ctx, "delete", vpnDevice); err == nil {
log.WithField("device", vpnDevice).
Warn("VPNSetup cleaned up vpn device")
}
splitrt.Cleanup(ctx, splitrtConfig)
}