forked from submariner-io/submariner
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ipsec.go
623 lines (551 loc) · 16.1 KB
/
ipsec.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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
package ipsec
import (
"fmt"
"github.com/bronze1man/goStrongswanVici"
"github.com/kelseyhightower/envconfig"
"github.com/rancher/submariner/pkg/types"
"github.com/rancher/submariner/pkg/util"
"io/ioutil"
"k8s.io/klog"
"net"
"os"
"os/exec"
"reflect"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/coreos/go-iptables/iptables"
)
const (
pidFile = "/var/run/charon.pid"
// DefaultReplayWindowSize specifies the replay window size for charon
DefaultReplayWindowSize = "1024"
// DefaultIkeSaRekeyInterval specifies the default rekey interval for IKE_SA
DefaultIkeSaRekeyInterval = "4h"
// DefaultChildSaRekeyInterval specifies the default rekey interval for CHILD_SA
DefaultChildSaRekeyInterval = "1h"
)
type Engine struct {
sync.Mutex
LocalSubnets []string
LocalCluster types.SubmarinerCluster
LocalEndpoint types.SubmarinerEndpoint
SecretKey string
ReplayWindowSize string
IPSecIkeSaRekeyInterval string
IPSecChildSaRekeyInterval string
Debug bool
LogFile string
}
type IPSecSpecification struct {
PSK string
Debug bool
LogFile string
}
func NewEngine(localSubnets []string, localCluster types.SubmarinerCluster, localEndpoint types.SubmarinerEndpoint) *Engine {
ipSecSpec := IPSecSpecification{}
err := envconfig.Process("ce_ipsec", &ipSecSpec)
if err != nil {
klog.Fatal(err)
}
return &Engine{
ReplayWindowSize: DefaultReplayWindowSize,
IPSecIkeSaRekeyInterval: DefaultIkeSaRekeyInterval,
IPSecChildSaRekeyInterval: DefaultChildSaRekeyInterval,
LocalCluster: localCluster,
LocalEndpoint: localEndpoint,
LocalSubnets: localSubnets,
SecretKey: ipSecSpec.PSK,
Debug: ipSecSpec.Debug,
LogFile: ipSecSpec.LogFile,
}
}
func (i *Engine) StartEngine(ignition bool) error {
if ignition {
klog.Infof("Starting IPSec Engine (Charon)")
ifi, err := util.GetDefaultGatewayInterface()
if err != nil {
klog.Fatal(err)
}
klog.V(8).Infof("Device of default gateway interface was %s", ifi.Name)
ipt, err := iptables.New()
if err != nil {
klog.Fatalf("error while initializing iptables: %v", err)
}
klog.V(6).Infof("Installing/ensuring the SUBMARINER-POSTROUTING and SUBMARINER-FORWARD chains")
ipt.NewChain("nat", "SUBMARINER-POSTROUTING")
ipt.NewChain("filter", "SUBMARINER-FORWARD")
forwardToSubPostroutingRuleSpec := []string{"-j", "SUBMARINER-POSTROUTING"}
ipt.AppendUnique("nat", "POSTROUTING", forwardToSubPostroutingRuleSpec...)
forwardToSubForwardRuleSpec := []string{"-j", "SUBMARINER-FORWARD"}
ipt.AppendUnique("filter", "FORWARD", forwardToSubForwardRuleSpec...)
go runCharon(i.Debug, i.LogFile)
}
if err := i.loadConns(); err != nil {
klog.Fatalf("Failed to load connections from charon: %v", err)
return err
}
return nil
}
func (i *Engine) ReloadEngine() error {
// to be implemented
return nil
}
func (i *Engine) StopEngine() error {
// to be implemented
return nil
}
func (i *Engine) SyncCables(clusterId string, endpoints []types.SubmarinerEndpoint) error {
klog.V(2).Infof("Starting selective cable sync")
activeConnections, err := i.getActiveConns(false, clusterId)
if err != nil {
return err
}
for _, active := range activeConnections {
klog.V(6).Infof("Analyzing currently active connection: %s", active)
delete := true
for _, endpoint := range endpoints {
connName := endpoint.Spec.CableName
if active == connName {
klog.V(6).Infof("Active connection %s was found in the list of endpoints, not stopping it", connName)
delete = false
}
}
if delete {
klog.Infof("Triggering remove cable of connection %s", active)
i.RemoveCable(active)
}
}
for _, endpoint := range endpoints {
connInstalled := false
connName := endpoint.Spec.CableName
for _, cname := range activeConnections {
if connName == cname {
klog.Infof("Cable with name: %s was already installed", connName)
connInstalled = true
}
}
if !connInstalled {
klog.Infof("Marking cable %s to be installed", endpoint.Spec.CableName)
i.InstallCable(endpoint)
}
}
return nil
}
func (i *Engine) InstallCable(endpoint types.SubmarinerEndpoint) error {
if endpoint.Spec.ClusterID == i.LocalCluster.ID {
klog.V(4).Infof("Not installing cable for local cluster")
return nil
}
if reflect.DeepEqual(endpoint.Spec, i.LocalEndpoint.Spec) {
klog.V(4).Infof("Not installing self")
return nil
}
klog.V(2).Infof("Installing cable %s", endpoint.Spec.CableName)
activeConnections, err := i.getActiveConns(false, endpoint.Spec.ClusterID)
if err != nil {
return err
}
for _, active := range activeConnections {
klog.V(6).Infof("Analyzing currently active connection: %s", active)
if active == endpoint.Spec.CableName {
klog.V(6).Infof("Cable %s is already installed, not installing twice", active)
return nil
}
if util.GetClusterIdFromCableName(active) == endpoint.Spec.ClusterID {
return fmt.Errorf("error while installing cable %s, already found a pre-existing cable belonging to this cluster %s", active, endpoint.Spec.ClusterID)
}
}
client, err := getClient()
if err != nil {
return err
}
defer client.Close()
i.Lock()
defer i.Unlock()
if err := i.loadSharedKey(endpoint); err != nil {
klog.Errorf("Encountered issue while trying to load shared keys")
return err
}
var localEndpointIP, remoteEndpointIP string
if endpoint.Spec.NATEnabled {
localEndpointIP = i.LocalEndpoint.Spec.PublicIP.String()
remoteEndpointIP = endpoint.Spec.PublicIP.String()
} else {
localEndpointIP = i.LocalEndpoint.Spec.PrivateIP.String()
remoteEndpointIP = endpoint.Spec.PrivateIP.String()
}
var localTs, remoteTs, localAddr, remoteAddr []string
localTs = append(localTs, fmt.Sprintf("%s/32", i.LocalEndpoint.Spec.PrivateIP.String()))
localTs = append(localTs, i.LocalSubnets...)
localAddr = append(localAddr, i.LocalEndpoint.Spec.PrivateIP.String())
remoteTs = append(remoteTs, fmt.Sprintf("%s/32", endpoint.Spec.PrivateIP.String()))
remoteTs = append(remoteTs, endpoint.Spec.Subnets...)
remoteAddr = append(remoteAddr, remoteEndpointIP)
// todo: make the ESP proposals configurable
childSAConf := goStrongswanVici.ChildSAConf{
Local_ts: localTs,
Remote_ts: remoteTs,
ESPProposals: []string{"aes128gcm16-modp2048", "aes-modp2048"},
StartAction: "start",
CloseAction: "restart",
Mode: "tunnel",
ReqID: "0",
RekeyTime: i.IPSecChildSaRekeyInterval,
InstallPolicy: "yes",
}
klog.V(6).Infof("Using ReplayWindowSize: %v", i.ReplayWindowSize)
childSAConf.ReplayWindow = i.ReplayWindowSize
authLConf := goStrongswanVici.AuthConf{
ID: localEndpointIP,
AuthMethod: "psk",
}
authRConf := goStrongswanVici.AuthConf{
ID: remoteEndpointIP,
AuthMethod: "psk",
}
ikeConf := goStrongswanVici.IKEConf{
LocalAddrs: localAddr,
RemoteAddrs: remoteAddr,
Proposals: []string{"aes128gcm16-sha256-modp2048", "aes-sha1-modp2048"},
Version: "2",
LocalAuth: authLConf,
RemoteAuth: authRConf,
RekeyTime: i.IPSecIkeSaRekeyInterval,
Encap: "yes",
Mobike: "no",
}
ikeConf.Children = map[string]goStrongswanVici.ChildSAConf{
"submariner-child-" + endpoint.Spec.CableName: childSAConf,
}
// Sometimes, the connection doesn't load, so try to load it multiple times.
for i := 0; i < 6; i++ {
err = client.LoadConn(&map[string]goStrongswanVici.IKEConf{
endpoint.Spec.CableName: ikeConf,
})
if err == nil {
break
}
}
if err != nil {
klog.Errorf("failed loading connection %s: %v", endpoint.Spec.CableName, err)
return err
}
ifi, err := util.GetDefaultGatewayInterface()
if err != nil {
klog.Fatal(err)
}
klog.V(4).Infof("Device of default gateway interface was %s", ifi.Name)
ipt, err := iptables.New()
if err != nil {
klog.Fatalf("error while initializing iptables: %v", err)
}
addresses, err := ifi.Addrs()
if err != nil {
klog.Fatal(err)
}
for _, addr := range addresses {
ipAddr, ipNet, err := net.ParseCIDR(addr.String())
if err != nil {
klog.Errorf("error while parsing address %v", err)
}
if ipAddr.To4() != nil {
for _, subnet := range endpoint.Spec.Subnets {
ruleSpec := []string{"-s", ipNet.String(), "-d", subnet, "-i", ifi.Name, "-j", "ACCEPT"}
klog.V(8).Infof("Installing iptables rule: %s", strings.Join(ruleSpec, " "))
err = ipt.AppendUnique("filter", "SUBMARINER-FORWARD", ruleSpec...)
if err != nil {
klog.Errorf("error while installing iptables rule: %v", err)
}
ruleSpec = []string{"-d", ipNet.String(), "-s", subnet, "-i", ifi.Name, "-j", "ACCEPT"}
klog.V(8).Infof("Installing iptables rule: %s", strings.Join(ruleSpec, " "))
err = ipt.AppendUnique("filter", "SUBMARINER-FORWARD", ruleSpec...)
if err != nil {
klog.Errorf("error while installing iptables rule: %v", err)
}
// -t nat -I POSTROUTING -s <local-network-cidr> -d <remote-cidr> -j SNAT --to-source <this-local-ip>
ruleSpec = []string{"-s", ipNet.String(), "-d", subnet, "-j", "SNAT", "--to-source", ipAddr.String()}
klog.V(8).Infof("Installing iptables rule: %s", strings.Join(ruleSpec, " "))
err = ipt.AppendUnique("nat", "SUBMARINER-POSTROUTING", ruleSpec...)
if err != nil {
klog.Errorf("error while installing iptables rule: %v", err)
}
}
} else {
klog.V(6).Infof("Skipping adding rule because IPv6 network %s found", ipNet.String())
}
}
klog.V(2).Infof("Loaded connection: %v", endpoint.Spec.CableName)
return nil
}
func (i *Engine) RemoveCable(cableId string) error {
i.Lock()
defer i.Unlock()
client, err := getClient()
if err != nil {
return err
}
defer client.Close()
/*
err = client.Terminate(&goStrongswanVici.TerminateRequest{
Child: "submariner-child-" + cableId,
})
if err != nil {
klog.Errorf("Error when terminating child connection %s : %v", cableId, err)
}
err = client.Terminate(&goStrongswanVici.TerminateRequest{
Ike: cableId,
})
if err != nil {
klog.Errorf("Error when terminating ike connection %s : %v", cableId, err)
} */
klog.Infof("Unloading connection %s", cableId)
err = client.UnloadConn(&goStrongswanVici.UnloadConnRequest{
Name: cableId,
})
if err != nil {
klog.Errorf("Error when unloading connection %s : %v", cableId, err)
return err
}
connections, err := client.ListConns("")
if err != nil {
klog.Errorf("Error while retrieving connections active after delete")
} else {
for _, conn := range connections {
klog.V(6).Infof("Found connection %v", conn)
}
}
saDeleted := false
count := 0
for {
if saDeleted {
break
}
if count > 2 {
klog.Infof("Waited for connection terminate for 2 iterations, triggering a force delete of the IKE")
err = client.Terminate(&goStrongswanVici.TerminateRequest{
Ike: cableId,
Force: "yes",
})
if err != nil {
klog.Errorf("error when terminating ike connection %s : %v", cableId, err)
}
}
sas, err := client.ListSas("", "")
if err != nil {
klog.Errorf("error while retrieving sas active after delete")
} else {
found := false
for _, samap := range sas {
klog.V(6).Infof("Found SA %v", samap)
sa, stillExists := samap[cableId]
if stillExists && ( sa.State == "DELETING" || sa.State == "CONNECTING" ){
found = true
break
} else if sa.State == "ESTABLISHED" {
// what should we do here in this case? it could be perfectly legitimate that the connection was re-established,
// i.e. datastore expired a good connection that was dead temporarily... in this case the sa shows up the way we want
// if a true failover happens there should never be an established connection, but perhaps we should force delete
// the connection anyway
klog.V(4).Infof("It appears the peer became healthy again, and this connection was established")
saDeleted = true
break
}
}
if found {
klog.V(6).Infof("SA is still in deleting state; waiting 5 seconds before looking again")
count++
time.Sleep(5 * time.Second)
} else {
saDeleted = true
}
}
}
klog.Infof("Removed connection %s", cableId)
return nil
}
func (i *Engine) PrintConns() {
client, _ := getClient()
defer client.Close()
connList, err := client.ListConns("")
if err != nil {
klog.Errorf("error list-conns: %v \n", err)
}
for _, connection := range connList {
klog.Infof("connection map: %v", connection)
}
}
func (i *Engine) getActiveConns(getAll bool, clusterId string) ([]string, error) {
i.Lock()
defer i.Unlock()
var connections []string
var prefix string
if getAll {
prefix = "submariner-cable-"
} else {
prefix = fmt.Sprintf("submariner-cable-%s-", clusterId)
}
client, err := getClient()
if err != nil {
return nil, err
}
defer client.Close()
conns, err := client.ListConns("")
if err != nil {
return nil, err
}
for _, conn := range conns {
for k := range conn {
if strings.HasPrefix(k, prefix) {
klog.V(4).Infof("Found existing connection: %s", k)
connections = append(connections, k)
}
}
}
return connections, nil
}
func (i *Engine) loadSharedKey(endpoint types.SubmarinerEndpoint) error {
client, err := getClient()
if err != nil {
return err
}
defer client.Close()
klog.Infof("Loading shared key for endpoint")
var identities []string
var publicIP, privateIP string
privateIP = endpoint.Spec.PrivateIP.String()
identities = append(identities, privateIP)
if endpoint.Spec.NATEnabled {
publicIP = endpoint.Spec.PublicIP.String()
if publicIP != privateIP {
identities = append(identities, publicIP)
}
}
sharedKey := &goStrongswanVici.Key{
Typ: "IKE",
Data: i.SecretKey,
Owners: identities,
}
err = client.LoadShared(sharedKey)
if err != nil {
klog.Infof("Failed to load pre-shared key for %s: %v", privateIP, err)
if endpoint.Spec.NATEnabled {
klog.Infof("Failed to load pre-shared key for %s: %v", publicIP, err)
}
return err
}
return nil
}
func runCharon(debug bool, logFile string) {
klog.Infof("Starting Charon")
// Ignore error
os.Remove("/var/run/charon.vici")
args := []string{}
for _, i := range strings.Split("dmn|mgr|ike|chd|cfg|knl|net|asn|tnc|imc|imv|pts|tls|esp|lib", "|") {
args = append(args, "--debug-"+i)
if debug {
args = append(args, "3")
} else {
args = append(args, "1")
}
}
cmd := exec.Command("charon", args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if logFile != "" {
output, err := os.OpenFile(logFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
klog.Fatalf("Failed to log to file %s: %v", logFile, err)
}
defer output.Close()
cmd.Stdout = output
cmd.Stderr = output
}
cmd.SysProcAttr = &syscall.SysProcAttr{
Pdeathsig: syscall.SIGTERM,
}
cmd.Start()
klog.Fatalf("charon exited: %v", cmd.Wait())
}
func (i *Engine) killCharon(pid string) {
pidNum, err := strconv.Atoi(pid)
if err == nil {
err = syscall.Kill(pidNum, syscall.SIGKILL)
}
if err != nil {
klog.Errorf("Can't kill %s: %v", pid, err)
}
}
func (i *Engine) loadConns() error {
i.Lock()
defer i.Unlock()
client, err := getClient()
if err != nil {
return err
}
defer client.Close()
conns, err := client.ListConns("")
if err != nil {
return err
}
for _, conn := range conns {
for k := range conn {
if strings.HasPrefix(k, "submariner-conn-") {
klog.Infof("Found existing connection: %s", k)
}
}
}
return nil
}
func (i *Engine) monitorCharon() {
pid := ""
for {
newPidBytes, err := ioutil.ReadFile(pidFile)
if err != nil {
klog.Fatalf("Failed to read %s", pidFile)
}
newPid := strings.TrimSpace(string(newPidBytes))
if pid == "" {
pid = newPid
klog.Infof("Charon running PID: %s", pid)
} else if pid != newPid {
klog.Fatalf("Charon restarted, old PID: %s, new PID: %s", pid, newPid)
} else {
i.Lock()
if err := Test(); err != nil {
klog.Errorf("Killing charon due to: %v", err)
i.killCharon(pid)
}
i.Unlock()
}
time.Sleep(2 * time.Second)
}
}
func Test() error {
client, err := getClient()
if err != nil {
return err
}
defer client.Close()
if _, err := client.ListConns(""); err != nil {
return err
}
return nil
}
func getClient() (*goStrongswanVici.ClientConn, error) {
var err error
for i := 0; i < 3; i++ {
var client *goStrongswanVici.ClientConn
client, err = goStrongswanVici.NewClientConnFromDefaultSocket()
if err == nil {
return client, nil
}
if i > 0 {
klog.Errorf("Failed to connect to charon: %v", err)
}
time.Sleep(1 * time.Second)
}
return nil, err
}