-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathfirewall.go
373 lines (329 loc) · 12.6 KB
/
firewall.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
package firewall
import (
"context"
"fmt"
"strconv"
"github.com/UpCloudLtd/terraform-provider-upcloud/internal/utils"
"github.com/UpCloudLtd/upcloud-go-api/v8/upcloud"
"github.com/UpCloudLtd/upcloud-go-api/v8/upcloud/request"
"github.com/UpCloudLtd/upcloud-go-api/v8/upcloud/service"
"github.com/hashicorp/go-cty/cty"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
)
func ResourceFirewallRules() *schema.Resource {
return &schema.Resource{
Description: `This resource represents a generated list of UpCloud firewall rules.
Firewall rules are used in conjunction with UpCloud servers.
Each server has its own firewall rules.
The firewall is enabled on all network interfaces except ones attached to private virtual networks.
The maximum number of firewall rules per server is 1000.`,
CreateContext: resourceFirewallRulesCreate,
ReadContext: resourceFirewallRulesRead,
UpdateContext: resourceFirewallRulesUpdate,
DeleteContext: resourceFirewallRulesDelete,
Importer: &schema.ResourceImporter{
StateContext: schema.ImportStatePassthroughContext,
},
Schema: map[string]*schema.Schema{
"server_id": {
Type: schema.TypeString,
Description: "The unique id of the server to be protected the firewall rules",
Required: true,
ForceNew: true,
},
"firewall_rule": {
Type: schema.TypeList,
Description: `A single firewall rule.
If used, IP address and port ranges must have both start and end values specified. These can be the same value if only one IP address or port number is specified.
Source and destination port numbers can only be set if the protocol is TCP or UDP.
The ICMP type may only be set if the protocol is ICMP.
Typical firewall rule should have "action", "direction", "protocol", "family" and at least one destination/source-address/port range.
The default rule can be created by providing only "action" and "direction" attributes. Default rule should be defined last.`,
MaxItems: 1000,
Required: true,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"direction": {
Type: schema.TypeString,
Description: "The direction of network traffic this rule will be applied to",
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"in", "out"}, false),
},
"action": {
Type: schema.TypeString,
Description: "Action to take if the rule conditions are met. Valid values `accept | drop`",
Required: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"accept", "drop"}, false),
},
"family": {
Type: schema.TypeString,
Description: "The address family of new firewall rule",
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"IPv4", "IPv6"}, false),
},
"protocol": {
Type: schema.TypeString,
Description: "The protocol this rule will be applied to",
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringInSlice([]string{"", "tcp", "udp", "icmp"}, false),
},
"icmp_type": {
Type: schema.TypeString,
Description: "The ICMP type",
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(0, 255),
},
"source_address_start": {
Type: schema.TypeString,
Description: "The source address range starts from this address",
Optional: true,
ForceNew: true,
ValidateFunc: validation.Any(validation.IsIPv4Address, validation.IsIPv6Address, validation.StringIsEmpty),
},
"source_address_end": {
Type: schema.TypeString,
Description: "The source address range ends from this address",
Optional: true,
ForceNew: true,
ValidateFunc: validation.Any(validation.IsIPv4Address, validation.IsIPv6Address, validation.StringIsEmpty),
},
"source_port_start": {
Type: schema.TypeString,
Description: "The source port range starts from this port number",
Optional: true,
ForceNew: true,
ValidateDiagFunc: firewallRuleValidateOptionalPort,
},
"source_port_end": {
Type: schema.TypeString,
Description: "The source port range ends from this port number",
Optional: true,
ForceNew: true,
ValidateDiagFunc: firewallRuleValidateOptionalPort,
},
"destination_address_start": {
Type: schema.TypeString,
Description: "The destination address range starts from this address",
Optional: true,
ForceNew: true,
ValidateFunc: validation.Any(validation.IsIPv4Address, validation.IsIPv6Address, validation.StringIsEmpty),
},
"destination_address_end": {
Type: schema.TypeString,
Description: "The destination address range ends from this address",
Optional: true,
ForceNew: true,
ValidateFunc: validation.Any(validation.IsIPv4Address, validation.IsIPv6Address, validation.StringIsEmpty),
},
"destination_port_start": {
Type: schema.TypeString,
Description: "The destination port range starts from this port number",
Optional: true,
ForceNew: true,
ValidateDiagFunc: firewallRuleValidateOptionalPort,
},
"destination_port_end": {
Type: schema.TypeString,
Description: "The destination port range ends from this port number",
Optional: true,
ForceNew: true,
ValidateDiagFunc: firewallRuleValidateOptionalPort,
},
"comment": {
Type: schema.TypeString,
Description: "Freeform comment string for the rule",
Optional: true,
ForceNew: true,
ValidateFunc: validation.StringLenBetween(0, 250),
},
},
},
},
},
}
}
func resourceFirewallRulesCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
client := meta.(*service.Service)
opts := &request.CreateFirewallRulesRequest{
ServerUUID: d.Get("server_id").(string),
}
if v, ok := d.GetOk("firewall_rule"); ok {
var firewallRules []upcloud.FirewallRule
for _, frMap := range v.([]interface{}) {
rule := frMap.(map[string]interface{})
firewallRule := upcloud.FirewallRule{
Action: rule["action"].(string),
Comment: rule["comment"].(string),
DestinationAddressStart: rule["destination_address_start"].(string),
DestinationAddressEnd: rule["destination_address_end"].(string),
DestinationPortStart: rule["destination_port_start"].(string),
DestinationPortEnd: rule["destination_port_end"].(string),
Direction: rule["direction"].(string),
Family: rule["family"].(string),
ICMPType: rule["icmp_type"].(string),
Protocol: rule["protocol"].(string),
SourceAddressStart: rule["source_address_start"].(string),
SourceAddressEnd: rule["source_address_end"].(string),
SourcePortStart: rule["source_port_start"].(string),
SourcePortEnd: rule["source_port_end"].(string),
}
firewallRules = append(firewallRules, firewallRule)
}
opts.FirewallRules = firewallRules
}
if _, err := client.WaitForServerState(ctx, &request.WaitForServerStateRequest{
UUID: opts.ServerUUID,
UndesiredState: upcloud.ServerStateMaintenance,
}); err != nil {
return diag.FromErr(err)
}
if err := client.CreateFirewallRules(ctx, opts); err != nil {
return diag.FromErr(err)
}
d.SetId(d.Get("server_id").(string))
return resourceFirewallRulesRead(ctx, d, meta)
}
func resourceFirewallRulesRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
client := meta.(*service.Service)
var diags diag.Diagnostics
opts := &request.GetFirewallRulesRequest{
ServerUUID: d.Id(),
}
firewallRules, err := client.GetFirewallRules(ctx, opts)
if err != nil {
return utils.HandleResourceError(d.Get("server_id").(string), d, err)
}
var frMaps []map[string]interface{}
for _, rule := range firewallRules.FirewallRules {
frMap := map[string]interface{}{
"action": rule.Action,
"comment": rule.Comment,
"destination_address_end": rule.DestinationAddressEnd,
"destination_address_start": rule.DestinationAddressStart,
"destination_port_start": rule.DestinationPortStart,
"destination_port_end": rule.DestinationPortEnd,
"direction": rule.Direction,
"family": rule.Family,
"icmp_type": rule.ICMPType,
"protocol": rule.Protocol,
"source_address_end": rule.SourceAddressEnd,
"source_address_start": rule.SourceAddressStart,
"source_port_start": rule.SourcePortStart,
"source_port_end": rule.SourcePortEnd,
}
frMaps = append(frMaps, frMap)
}
if err := d.Set("firewall_rule", frMaps); err != nil {
return diag.FromErr(err)
}
if err := d.Set("server_id", d.Id()); err != nil {
return diag.FromErr(err)
}
return diags
}
func resourceFirewallRulesUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
client := meta.(*service.Service)
opts := &request.CreateFirewallRulesRequest{
ServerUUID: d.Id(),
}
err := client.CreateFirewallRules(ctx, opts)
if err != nil {
return diag.FromErr(err)
}
if d.HasChange("firewall_rule") {
v := d.Get("firewall_rule")
var firewallRules []upcloud.FirewallRule
for _, frMap := range v.([]interface{}) {
rule := frMap.(map[string]interface{})
firewallRule := upcloud.FirewallRule{
Action: rule["action"].(string),
Comment: rule["comment"].(string),
DestinationAddressStart: rule["destination_address_start"].(string),
DestinationAddressEnd: rule["destination_address_end"].(string),
DestinationPortStart: rule["destination_port_start"].(string),
DestinationPortEnd: rule["destination_port_end"].(string),
Direction: rule["direction"].(string),
Family: rule["family"].(string),
ICMPType: rule["icmp_type"].(string),
Protocol: rule["protocol"].(string),
SourceAddressStart: rule["source_address_start"].(string),
SourceAddressEnd: rule["source_address_end"].(string),
SourcePortStart: rule["source_port_start"].(string),
SourcePortEnd: rule["source_port_end"].(string),
}
firewallRules = append(firewallRules, firewallRule)
}
opts.FirewallRules = firewallRules
}
err = client.CreateFirewallRules(ctx, opts)
if err != nil {
return diag.FromErr(err)
}
return resourceFirewallRulesRead(ctx, d, meta)
}
func resourceFirewallRulesDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
client := meta.(*service.Service)
var diags diag.Diagnostics
opts := &request.CreateFirewallRulesRequest{
ServerUUID: d.Id(),
FirewallRules: nil,
}
if _, err := client.WaitForServerState(ctx, &request.WaitForServerStateRequest{
UUID: opts.ServerUUID,
UndesiredState: upcloud.ServerStateMaintenance,
}); err != nil {
return diag.FromErr(err)
}
if err := client.CreateFirewallRules(ctx, opts); err != nil {
return diag.FromErr(err)
}
d.SetId("")
return diags
}
func firewallRuleValidateOptionalPort(v interface{}, path cty.Path) diag.Diagnostics {
const (
portMin int = 1
portMax int = 65535
)
var diags diag.Diagnostics
val, ok := v.(string)
if !ok {
diags = append(diags, diag.Diagnostic{
Severity: diag.Error,
Summary: "Bad type",
Detail: "expected type to be string",
AttributePath: path,
})
return diags
}
if val == "" {
return diags
}
i, err := strconv.Atoi(val)
if err != nil {
diags = append(diags, diag.Diagnostic{
Severity: diag.Error,
Summary: "Bad port format",
Detail: fmt.Sprintf("%s is not valid number", val),
AttributePath: path,
})
return diags
}
if portMin > i || i > portMax {
diags = append(diags, diag.Diagnostic{
Severity: diag.Error,
Summary: "Bad port",
Detail: fmt.Sprintf("%s is not within valid port range %d - %d", val, portMin, portMax),
AttributePath: path,
})
return diags
}
return diags
}