This repository has been archived by the owner on Jan 9, 2023. It is now read-only.
/
security_group.go
108 lines (92 loc) · 2.71 KB
/
security_group.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
// Copyright Jetstack Ltd. See LICENSE for details.
package amazon
import (
"fmt"
"net"
"github.com/jetstack/tarmak/pkg/tarmak/cluster/firewall"
"github.com/jetstack/tarmak/pkg/tarmak/role"
)
const masterELB = "master_elb"
type AWSSGRule struct {
Comment string
Destination string
Source string
Service string
Direction string
Identifier *string
FromPort uint16
ToPort uint16
Protocol string
CIDRBlock *net.IPNet
SourceSGGroupID string
SGID string
}
func awsGroupID(role string) string {
switch role {
case "vault":
return "${var.vault_security_group_id}"
case "bastion":
return "${var.bastion_security_group_id}"
default:
return fmt.Sprintf("${aws_security_group.kubernetes_%s.id}", role)
}
}
func GenerateAWSRules(role *role.Role) (awsRules []*AWSSGRule, err error) {
// Get all firewall rules where the role is mentioned in the destination
for _, rule := range firewall.Rules() {
for _, destination := range rule.Destinations {
if destination.Role == role.Name() || (role.Name() == "master" && destination.Role == masterELB) {
awsRules = append(awsRules, generateFromRule(rule, role, &destination)...)
}
}
}
return awsRules, nil
}
func generateFromRule(rule *firewall.Rule, role *role.Role, destination *firewall.Host) []*AWSSGRule {
var awsRules []*AWSSGRule
for _, source := range rule.Sources {
for _, service := range rule.Services {
for _, port := range service.Ports {
awsRule := &AWSSGRule{
Comment: rule.Comment,
Service: service.Name,
Direction: rule.Direction,
Protocol: service.Protocol,
CIDRBlock: source.CIDR,
Identifier: port.Identifier,
}
// use single port for from and to if not nil
if port.Single != nil {
awsRule.FromPort = *port.Single
awsRule.ToPort = *port.Single
} else {
awsRule.FromPort = *port.RangeFrom
awsRule.ToPort = *port.RangeTo
}
// if source has no role and the name is "all" use the role name
// for source else use the source name
if source.Role == "" {
if source.Name == "all" {
awsRule.SourceSGGroupID = awsGroupID(role.Name())
awsRule.Source = role.Name()
} else {
awsRule.SourceSGGroupID = awsGroupID(source.Name)
awsRule.Source = source.Name
}
} else {
awsRule.Source = source.Role
awsRule.SourceSGGroupID = awsGroupID(source.Role)
}
// if the role is elb then add elb to destination name
if destination.Role == masterELB {
awsRule.Destination = fmt.Sprintf("%s_elb", role.TFName())
} else {
awsRule.Destination = role.TFName()
}
awsRule.SGID = awsGroupID(destination.Role)
awsRules = append(awsRules, awsRule)
}
}
}
return awsRules
}