/
security_group.go
335 lines (290 loc) · 12.8 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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
/*
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 azure
import (
"context"
"fmt"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime"
"github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork"
kubermaticv1 "k8c.io/kubermatic/v2/pkg/apis/kubermatic/v1"
kuberneteshelper "k8c.io/kubermatic/v2/pkg/kubernetes"
"k8c.io/kubermatic/v2/pkg/provider"
kubermaticresources "k8c.io/kubermatic/v2/pkg/resources"
"k8s.io/utils/pointer"
)
func securityGroupName(cluster *kubermaticv1.Cluster) string {
return resourceNamePrefix + cluster.Name
}
func reconcileSecurityGroup(ctx context.Context, clients *ClientSet, location string, cluster *kubermaticv1.Cluster, update provider.ClusterUpdater) (*kubermaticv1.Cluster, error) {
if cluster.Spec.Cloud.Azure.SecurityGroup == "" {
cluster.Spec.Cloud.Azure.SecurityGroup = securityGroupName(cluster)
}
securityGroup, err := clients.SecurityGroups.Get(ctx, cluster.Spec.Cloud.Azure.ResourceGroup, cluster.Spec.Cloud.Azure.SecurityGroup, nil)
if err != nil && !isNotFound(err) {
return nil, err
}
// if we found a security group, we can check for the ownership tag to determine
// if the referenced security group is owned by this cluster and should be reconciled
if !isNotFound(err) && !hasOwnershipTag(securityGroup.Tags, cluster) {
return update(ctx, cluster.Name, func(updatedCluster *kubermaticv1.Cluster) {
updatedCluster.Spec.Cloud.Azure.SecurityGroup = cluster.Spec.Cloud.Azure.SecurityGroup
})
}
lowPort, highPort := kubermaticresources.NewTemplateDataBuilder().
WithNodePortRange(cluster.Spec.ComponentsOverride.Apiserver.NodePortRange).
WithCluster(cluster).
Build().
NodePorts()
nodePortsAllowedIPRanges := kubermaticresources.GetNodePortsAllowedIPRanges(cluster, cluster.Spec.Cloud.Azure.NodePortsAllowedIPRanges, cluster.Spec.Cloud.Azure.NodePortsAllowedIPRange)
target := targetSecurityGroup(cluster.Spec.Cloud, location, cluster.Name, lowPort, highPort, nodePortsAllowedIPRanges.GetIPv4CIDRs(), nodePortsAllowedIPRanges.GetIPv6CIDRs())
// check for attributes of the existing security group and return early if all values are already
// as expected. Since there are a lot of pointers in the network.SecurityGroup struct, we need to
// do a lot of "!= nil" checks so this does not panic.
//
// Attributes we check:
// - defined security rules
if !(securityGroup.Properties != nil && securityGroup.Properties.SecurityRules != nil &&
compareSecurityRules(securityGroup.Properties.SecurityRules, target.Properties.SecurityRules)) {
if err := ensureSecurityGroup(ctx, clients, cluster.Spec.Cloud, target); err != nil {
return cluster, err
}
}
return update(ctx, cluster.Name, func(updatedCluster *kubermaticv1.Cluster) {
updatedCluster.Spec.Cloud.Azure.SecurityGroup = cluster.Spec.Cloud.Azure.SecurityGroup
kuberneteshelper.AddFinalizer(updatedCluster, FinalizerSecurityGroup)
})
}
func targetSecurityGroup(cloud kubermaticv1.CloudSpec, location string, clusterName string, portRangeLow int, portRangeHigh int,
nodePortsIPv4CIDRs []string, nodePortsIPv6CIDRs []string) *armnetwork.SecurityGroup {
inbound := armnetwork.SecurityRuleDirectionInbound
outbound := armnetwork.SecurityRuleDirectionOutbound
all := armnetwork.SecurityRuleProtocolAsterisk
allow := armnetwork.SecurityRuleAccessAllow
tcp := armnetwork.SecurityRuleProtocolTCP
securityGroup := &armnetwork.SecurityGroup{
Name: pointer.String(cloud.Azure.SecurityGroup),
Location: pointer.String(location),
Tags: map[string]*string{
clusterTagKey: pointer.String(clusterName),
},
Properties: &armnetwork.SecurityGroupPropertiesFormat{
Subnets: []*armnetwork.Subnet{
{
Name: pointer.String(cloud.Azure.SubnetName),
ID: pointer.String(assembleSubnetID(cloud)),
},
},
// inbound
SecurityRules: []*armnetwork.SecurityRule{
{
Name: pointer.String("ssh_ingress"),
Properties: &armnetwork.SecurityRulePropertiesFormat{
Direction: &inbound,
Protocol: &tcp,
SourceAddressPrefix: pointer.String("*"),
SourcePortRange: pointer.String("*"),
DestinationAddressPrefix: pointer.String("*"),
DestinationPortRange: pointer.String("22"),
Access: &allow,
Priority: pointer.Int32(100),
},
},
{
Name: pointer.String("inter_node_comm"),
Properties: &armnetwork.SecurityRulePropertiesFormat{
Direction: &inbound,
Protocol: &all,
SourceAddressPrefix: pointer.String("VirtualNetwork"),
SourcePortRange: pointer.String("*"),
DestinationAddressPrefix: pointer.String("VirtualNetwork"),
DestinationPortRange: pointer.String("*"),
Access: &allow,
Priority: pointer.Int32(200),
},
},
{
Name: pointer.String("azure_load_balancer"),
Properties: &armnetwork.SecurityRulePropertiesFormat{
Direction: &inbound,
Protocol: &all,
SourceAddressPrefix: pointer.String("AzureLoadBalancer"),
SourcePortRange: pointer.String("*"),
DestinationAddressPrefix: pointer.String("*"),
DestinationPortRange: pointer.String("*"),
Access: &allow,
Priority: pointer.Int32(300),
},
},
// outbound
{
Name: pointer.String("outbound_allow_all"),
Properties: &armnetwork.SecurityRulePropertiesFormat{
Direction: &outbound,
Protocol: &all,
SourceAddressPrefix: pointer.String("*"),
SourcePortRange: pointer.String("*"),
DestinationAddressPrefix: pointer.String("*"),
DestinationPortRange: pointer.String("*"),
Access: &allow,
Priority: pointer.Int32(100),
},
},
},
},
}
if len(nodePortsIPv4CIDRs) > 0 {
securityGroup.Properties.SecurityRules = append(securityGroup.Properties.SecurityRules, nodePortsAllowedIPRangesRule("node_ports_ingress", 400, portRangeLow, portRangeHigh, nodePortsIPv4CIDRs))
}
if len(nodePortsIPv6CIDRs) > 0 {
securityGroup.Properties.SecurityRules = append(securityGroup.Properties.SecurityRules, nodePortsAllowedIPRangesRule("node_ports_ingress_ipv6", 401, portRangeLow, portRangeHigh, nodePortsIPv6CIDRs))
}
securityGroup.Properties.SecurityRules = append(securityGroup.Properties.SecurityRules, tcpDenyAllRule(), udpDenyAllRule(), icmpAllowAllRule())
return securityGroup
}
// ensureSecurityGroup will create or update an Azure security group. The call is idempotent.
func ensureSecurityGroup(ctx context.Context, clients *ClientSet, cloud kubermaticv1.CloudSpec, sg *armnetwork.SecurityGroup) error {
if sg == nil {
return fmt.Errorf("invalid security group reference passed")
}
future, err := clients.SecurityGroups.BeginCreateOrUpdate(ctx, cloud.Azure.ResourceGroup, cloud.Azure.SecurityGroup, *sg, nil)
if err != nil {
return fmt.Errorf("failed to create or update security group %q: %w", cloud.Azure.SecurityGroup, err)
}
_, err = future.PollUntilDone(ctx, &runtime.PollUntilDoneOptions{
Frequency: 5 * time.Second,
})
return err
}
func deleteSecurityGroup(ctx context.Context, clients *ClientSet, cloud kubermaticv1.CloudSpec) error {
future, err := clients.SecurityGroups.BeginDelete(ctx, cloud.Azure.ResourceGroup, cloud.Azure.SecurityGroup, nil)
if err != nil {
return ignoreNotFound(err)
}
_, err = future.PollUntilDone(ctx, &runtime.PollUntilDoneOptions{
Frequency: 5 * time.Second,
})
return err
}
// nodePortsAllowedIPRangesRule returns a security rule to allow access to node ports from provided IP ranges.
func nodePortsAllowedIPRangesRule(name string, priority int32, portRangeLow int, portRangeHigh int, nodePortsAllowedIPRanges []string) *armnetwork.SecurityRule {
inbound := armnetwork.SecurityRuleDirectionInbound
all := armnetwork.SecurityRuleProtocolAsterisk
allow := armnetwork.SecurityRuleAccessAllow
prefixes := []*string{}
for _, prefix := range nodePortsAllowedIPRanges {
prefixes = append(prefixes, pointer.String(prefix))
}
rule := &armnetwork.SecurityRule{
Name: pointer.String(name),
Properties: &armnetwork.SecurityRulePropertiesFormat{
Direction: &inbound,
Protocol: &all,
SourcePortRange: pointer.String("*"),
DestinationAddressPrefix: pointer.String("*"),
DestinationPortRange: pointer.String(fmt.Sprintf("%d-%d", portRangeLow, portRangeHigh)),
Access: &allow,
Priority: pointer.Int32(priority),
},
}
if len(nodePortsAllowedIPRanges) == 1 {
rule.Properties.SourceAddressPrefix = pointer.String(nodePortsAllowedIPRanges[0])
} else {
rule.Properties.SourceAddressPrefixes = prefixes
}
return rule
}
func tcpDenyAllRule() *armnetwork.SecurityRule {
inbound := armnetwork.SecurityRuleDirectionInbound
tcp := armnetwork.SecurityRuleProtocolTCP
deny := armnetwork.SecurityRuleAccessDeny
return &armnetwork.SecurityRule{
Name: pointer.String(denyAllTCPSecGroupRuleName),
Properties: &armnetwork.SecurityRulePropertiesFormat{
Direction: &inbound,
Protocol: &tcp,
SourceAddressPrefix: pointer.String("*"),
SourcePortRange: pointer.String("*"),
DestinationPortRange: pointer.String("*"),
DestinationAddressPrefix: pointer.String("*"),
Access: &deny,
Priority: pointer.Int32(800),
},
}
}
func udpDenyAllRule() *armnetwork.SecurityRule {
inbound := armnetwork.SecurityRuleDirectionInbound
udp := armnetwork.SecurityRuleProtocolUDP
deny := armnetwork.SecurityRuleAccessDeny
return &armnetwork.SecurityRule{
Name: pointer.String(denyAllUDPSecGroupRuleName),
Properties: &armnetwork.SecurityRulePropertiesFormat{
Direction: &inbound,
Protocol: &udp,
SourceAddressPrefix: pointer.String("*"),
SourcePortRange: pointer.String("*"),
DestinationPortRange: pointer.String("*"),
DestinationAddressPrefix: pointer.String("*"),
Access: &deny,
Priority: pointer.Int32(801),
},
}
}
// Alright, so here's the deal. We need to allow ICMP, but on Azure it is not possible
// to specify ICMP as a protocol in a rule - only TCP or UDP.
// Therefore we're hacking around it by first blocking all incoming TCP and UDP
// and if these don't match, we have an "allow all" rule. Dirty, but the only way.
// See also: https://tinyurl.com/azure-allow-icmp
func icmpAllowAllRule() *armnetwork.SecurityRule {
inbound := armnetwork.SecurityRuleDirectionInbound
all := armnetwork.SecurityRuleProtocolAsterisk
allow := armnetwork.SecurityRuleAccessAllow
return &armnetwork.SecurityRule{
Name: pointer.String(allowAllICMPSecGroupRuleName),
Properties: &armnetwork.SecurityRulePropertiesFormat{
Direction: &inbound,
Protocol: &all,
SourceAddressPrefix: pointer.String("*"),
SourcePortRange: pointer.String("*"),
DestinationAddressPrefix: pointer.String("*"),
DestinationPortRange: pointer.String("*"),
Access: &allow,
Priority: pointer.Int32(900),
},
}
}
func compareSecurityRules(a []*armnetwork.SecurityRule, b []*armnetwork.SecurityRule) bool {
if len(a) != len(b) {
return false
}
for i, rule := range a {
ruleB := b[i]
if *rule.Name != *ruleB.Name || rule.Properties.Direction != ruleB.Properties.Direction ||
rule.Properties.Protocol != ruleB.Properties.Protocol ||
rule.Properties.Access != ruleB.Properties.Access ||
!isEqualStringPtr(rule.Properties.SourceAddressPrefix, ruleB.Properties.SourceAddressPrefix) ||
!isEqualStringPtr(rule.Properties.SourcePortRange, ruleB.Properties.SourcePortRange) ||
!isEqualStringPtr(rule.Properties.DestinationPortRange, ruleB.Properties.DestinationPortRange) ||
!isEqualStringPtr(rule.Properties.DestinationAddressPrefix, ruleB.Properties.DestinationAddressPrefix) ||
!isEqualInt32Ptr(rule.Properties.Priority, ruleB.Properties.Priority) {
return false
}
}
return true
}
func isEqualStringPtr(s1 *string, s2 *string) bool {
return s1 == nil && s2 == nil || (s1 != nil && s2 != nil && *s1 == *s2)
}
func isEqualInt32Ptr(s1 *int32, s2 *int32) bool {
return s1 == nil && s2 == nil || (s1 != nil && s2 != nil && *s1 == *s2)
}