-
Notifications
You must be signed in to change notification settings - Fork 155
/
security_group.go
312 lines (265 loc) · 9.94 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
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
/*
Copyright 2021 The Kubermatic Kubernetes Platform contributors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package aws
import (
"context"
"errors"
"fmt"
"github.com/aws/aws-sdk-go-v2/service/ec2"
ec2types "github.com/aws/aws-sdk-go-v2/service/ec2/types"
"github.com/aws/smithy-go"
kubermaticv1 "k8c.io/kubermatic/v2/pkg/apis/kubermatic/v1"
"k8c.io/kubermatic/v2/pkg/provider"
kubermaticresources "k8c.io/kubermatic/v2/pkg/resources"
"k8s.io/utils/ptr"
)
func securityGroupName(cluster *kubermaticv1.Cluster) string {
return resourceNamePrefix + cluster.Name
}
// Get security group by aws generated id string (sg-xxxxx).
// Error is returned in case no such group exists.
func getSecurityGroupByID(ctx context.Context, client *ec2.Client, vpc *ec2types.Vpc, id string) (*ec2types.SecurityGroup, error) {
if vpc == nil || vpc.VpcId == nil {
return nil, errors.New("no valid VPC given")
}
dsgOut, err := client.DescribeSecurityGroups(ctx, &ec2.DescribeSecurityGroupsInput{
GroupIds: []string{id},
Filters: []ec2types.Filter{ec2VPCFilter(ptr.Deref(vpc.VpcId, ""))},
})
if err != nil && !isNotFound(err) {
return nil, fmt.Errorf("failed to get security group: %w", err)
}
if dsgOut == nil || len(dsgOut.SecurityGroups) == 0 {
return nil, fmt.Errorf("security group with id '%s' not found in VPC %s", id, *vpc.VpcId)
}
return &dsgOut.SecurityGroups[0], nil
}
func reconcileSecurityGroup(ctx context.Context, client *ec2.Client, cluster *kubermaticv1.Cluster, update provider.ClusterUpdater) (*kubermaticv1.Cluster, error) {
vpcID := cluster.Spec.Cloud.AWS.VPCID
groupID := cluster.Spec.Cloud.AWS.SecurityGroupID
// if we already have an ID on the cluster, check if that group still exists
if groupID != "" {
describeOut, err := client.DescribeSecurityGroups(ctx, &ec2.DescribeSecurityGroupsInput{
GroupIds: []string{groupID},
Filters: []ec2types.Filter{ec2VPCFilter(vpcID)},
})
if err != nil && !isNotFound(err) {
return cluster, fmt.Errorf("failed to get security groups: %w", err)
}
// not found
if describeOut == nil || len(describeOut.SecurityGroups) == 0 {
groupID = ""
}
}
// if no ID was stored on the cluster object or the group doesn't exist anymore,
// try to find it by its name instead, just so we do not accidentally create
// multiple groups with the same name (which would not be allowed by AWS)
groupName := securityGroupName(cluster)
if groupID == "" {
describeOut, err := client.DescribeSecurityGroups(ctx, &ec2.DescribeSecurityGroupsInput{
Filters: []ec2types.Filter{
ec2VPCFilter(vpcID),
{
Name: ptr.To("group-name"),
Values: []string{groupName},
},
},
})
if err != nil {
return cluster, fmt.Errorf("failed to get security groups: %w", err)
}
// found the group by its name!
if len(describeOut.SecurityGroups) >= 1 {
groupID = ptr.Deref(describeOut.SecurityGroups[0].GroupId, "")
}
}
// if we still have no ID, we must create a new group
if groupID == "" {
out, err := client.CreateSecurityGroup(ctx, &ec2.CreateSecurityGroupInput{
VpcId: &vpcID,
GroupName: ptr.To(groupName),
Description: ptr.To(fmt.Sprintf("Security group for the Kubernetes cluster %s", cluster.Name)),
TagSpecifications: []ec2types.TagSpecification{{
ResourceType: ec2types.ResourceTypeSecurityGroup,
Tags: []ec2types.Tag{
ec2OwnershipTag(cluster.Name),
},
}},
})
if err != nil {
return cluster, fmt.Errorf("failed to create security group %s: %w", groupName, err)
}
groupID = *out.GroupId
}
ipv4Permissions := cluster.IsIPv4Only() || cluster.IsDualStack()
ipv6Permissions := cluster.IsIPv6Only() || cluster.IsDualStack()
permissions := getCommonSecurityGroupPermissions(groupID, ipv4Permissions, ipv6Permissions)
lowPort, highPort := getNodePortRange(cluster)
nodePortsAllowedIPRanges := kubermaticresources.GetNodePortsAllowedIPRanges(cluster, cluster.Spec.Cloud.AWS.NodePortsAllowedIPRanges, cluster.Spec.Cloud.AWS.NodePortsAllowedIPRange)
permissions = append(permissions, getNodePortSecurityGroupPermissions(lowPort, highPort, nodePortsAllowedIPRanges.GetIPv4CIDRs(), nodePortsAllowedIPRanges.GetIPv6CIDRs())...)
// Iterate over the permissions and add them one by one, because if an error occurs
// (e.g., one permission already exists) none of them would be created
for _, perm := range permissions {
// try to add permission
_, err := client.AuthorizeSecurityGroupIngress(ctx, &ec2.AuthorizeSecurityGroupIngressInput{
GroupId: ptr.To(groupID),
IpPermissions: []ec2types.IpPermission{
perm,
},
})
if err != nil {
var awsErr smithy.APIError
if !errors.As(err, &awsErr) || awsErr.ErrorCode() != "InvalidPermission.Duplicate" {
return cluster, fmt.Errorf("failed to authorize security group %s with id %s: %w", groupName, groupID, err)
}
}
}
return update(ctx, cluster.Name, func(cluster *kubermaticv1.Cluster) {
cluster.Spec.Cloud.AWS.SecurityGroupID = groupID
})
}
func getNodePortRange(cluster *kubermaticv1.Cluster) (int, int) {
return kubermaticresources.NewTemplateDataBuilder().
WithNodePortRange(cluster.Spec.ComponentsOverride.Apiserver.NodePortRange).
WithCluster(cluster).
Build().
NodePorts()
}
func getCommonSecurityGroupPermissions(securityGroupID string, ipv4Permissions, ipv6Permissions bool) []ec2types.IpPermission {
permissions := []ec2types.IpPermission{
// all protocols from within the sg
{
IpProtocol: ptr.To("-1"),
UserIdGroupPairs: []ec2types.UserIdGroupPair{{
GroupId: ptr.To(securityGroupID),
}},
},
}
// tcp:22 from everywhere
sshPermission := ec2types.IpPermission{
IpProtocol: ptr.To("tcp"),
FromPort: ptr.To[int32](provider.DefaultSSHPort),
ToPort: ptr.To[int32](provider.DefaultSSHPort),
}
if ipv4Permissions {
sshPermission.IpRanges = []ec2types.IpRange{{
CidrIp: ptr.To(kubermaticresources.IPv4MatchAnyCIDR),
}}
}
if ipv6Permissions {
sshPermission.Ipv6Ranges = []ec2types.Ipv6Range{{
CidrIpv6: ptr.To(kubermaticresources.IPv6MatchAnyCIDR),
}}
}
permissions = append(permissions, sshPermission)
// ICMP (v4) from/to everywhere
if ipv4Permissions {
permissions = append(permissions, ec2types.IpPermission{
IpProtocol: ptr.To("icmp"),
FromPort: ptr.To[int32](-1), // any port
ToPort: ptr.To[int32](-1), // any port
IpRanges: []ec2types.IpRange{{
CidrIp: ptr.To(kubermaticresources.IPv4MatchAnyCIDR),
}},
})
}
// ICMPv6 from/to everywhere
if ipv6Permissions {
permissions = append(permissions, ec2types.IpPermission{
IpProtocol: ptr.To("icmpv6"),
FromPort: ptr.To[int32](-1), // any port
ToPort: ptr.To[int32](-1), // any port
Ipv6Ranges: []ec2types.Ipv6Range{{
CidrIpv6: ptr.To(kubermaticresources.IPv6MatchAnyCIDR),
}},
})
}
return permissions
}
func getNodePortSecurityGroupPermissions(lowPort, highPort int, ipv4IPRanges, ipv6IPRanges []string) []ec2types.IpPermission {
tcpNodePortPermission := ec2types.IpPermission{
IpProtocol: ptr.To("tcp"),
FromPort: ptr.To[int32](int32(lowPort)),
ToPort: ptr.To[int32](int32(highPort)),
}
udpNodePortPermission := ec2types.IpPermission{
IpProtocol: ptr.To("udp"),
FromPort: ptr.To[int32](int32(lowPort)),
ToPort: ptr.To[int32](int32(highPort)),
}
for _, cidr := range ipv4IPRanges {
tcpNodePortPermission.IpRanges = append(tcpNodePortPermission.IpRanges, ec2types.IpRange{
CidrIp: ptr.To(cidr),
})
udpNodePortPermission.IpRanges = append(udpNodePortPermission.IpRanges, ec2types.IpRange{
CidrIp: ptr.To(cidr),
})
}
for _, cidr := range ipv6IPRanges {
tcpNodePortPermission.Ipv6Ranges = append(tcpNodePortPermission.Ipv6Ranges, ec2types.Ipv6Range{
CidrIpv6: ptr.To(cidr),
})
udpNodePortPermission.Ipv6Ranges = append(udpNodePortPermission.Ipv6Ranges, ec2types.Ipv6Range{
CidrIpv6: ptr.To(cidr),
})
}
return []ec2types.IpPermission{tcpNodePortPermission, udpNodePortPermission}
}
func cleanUpSecurityGroup(ctx context.Context, client *ec2.Client, cluster *kubermaticv1.Cluster) error {
vpcID := cluster.Spec.Cloud.AWS.VPCID
groupID := cluster.Spec.Cloud.AWS.SecurityGroupID
// if we don't have the ID on the cluster object, try our best to find any
// orphaned security groups by their names and still clean up as best as we can
if groupID == "" {
groupName := securityGroupName(cluster)
describeOut, err := client.DescribeSecurityGroups(ctx, &ec2.DescribeSecurityGroupsInput{
Filters: []ec2types.Filter{
ec2VPCFilter(vpcID),
{
Name: ptr.To("group-name"),
Values: []string{groupName},
},
},
})
if err != nil {
return fmt.Errorf("failed to get security groups: %w", err)
}
// We found a group with a matching name!
if len(describeOut.SecurityGroups) > 0 {
groupID = *describeOut.SecurityGroups[0].GroupId
}
}
// if we still have no group ID, there is nothing to do for us
if groupID == "" {
return nil
}
// check if we own the security group
describeOut, err := client.DescribeSecurityGroups(ctx, &ec2.DescribeSecurityGroupsInput{
GroupIds: []string{groupID},
Filters: []ec2types.Filter{ec2VPCFilter(vpcID)},
})
if err != nil && !isNotFound(err) {
return fmt.Errorf("failed to get security groups: %w", err)
}
// someone has already deleted the group
if describeOut == nil || len(describeOut.SecurityGroups) == 0 {
return nil
}
// check if we own the SG
if !hasEC2Tag(ec2OwnershipTag(cluster.Name), describeOut.SecurityGroups[0].Tags) {
return nil
}
// time to delete the group
_, err = client.DeleteSecurityGroup(ctx, &ec2.DeleteSecurityGroupInput{GroupId: &groupID})
return err
}