-
Notifications
You must be signed in to change notification settings - Fork 132
/
resource_fastly_service_waf_configuration.go
637 lines (597 loc) · 20 KB
/
resource_fastly_service_waf_configuration.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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
package fastly
import (
"context"
"errors"
"fmt"
"log"
"sort"
gofastly "github.com/fastly/go-fastly/v6/fastly"
"github.com/hashicorp/go-cty/cty"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
)
func resourceServiceWAFConfiguration() *schema.Resource {
return &schema.Resource{
CreateContext: resourceServiceWAFConfigurationCreate,
ReadContext: resourceServiceWAFConfigurationRead,
UpdateContext: resourceServiceWAFConfigurationUpdate,
DeleteContext: resourceServiceWAFConfigurationDelete,
Importer: &schema.ResourceImporter{
StateContext: resourceServiceWAFConfigurationImport,
},
CustomizeDiff: customdiff.All(
validateWAFConfigurationResource,
customdiff.ComputedIf("cloned_version", func(_ context.Context, d *schema.ResourceDiff, _ interface{}) bool {
// If anything other than "activate" has changed, the current version will be
// cloned in resourceServiceWAFConfigurationV1Update so set it as recomputed.
for _, changedKey := range d.GetChangedKeysPrefix("") {
if changedKey == "activate" {
continue
}
return true
}
return false
}),
),
Schema: map[string]*schema.Schema{
"waf_id": {
Type: schema.TypeString,
Required: true,
ForceNew: true,
Description: "The ID of the Web Application Firewall that the configuration belongs to",
},
"activate": {
Type: schema.TypeBool,
Description: "Conditionally prevents a new firewall version from being activated. The apply step will continue to create a new draft version but will not activate it if this is set to `false`. Default `true`",
Default: true,
Optional: true,
},
"active": {
Type: schema.TypeBool,
Description: "Whether a specific firewall version is currently deployed",
Computed: true,
},
"cloned_version": {
Type: schema.TypeInt,
Computed: true,
Description: "The latest cloned firewall version by the provider",
},
"allowed_http_versions": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "Allowed HTTP versions",
},
"allowed_methods": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "A space-separated list of HTTP method names",
},
"allowed_request_content_type": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "Allowed request content types",
},
"allowed_request_content_type_charset": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "Allowed request content type charset",
},
"arg_length": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
Description: "The maximum number of arguments allowed",
},
"arg_name_length": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
Description: "The maximum allowed argument name length",
},
"combined_file_sizes": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
Description: "The maximum allowed size of all files",
},
"critical_anomaly_score": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
Description: "Score value to add for critical anomalies",
},
"crs_validate_utf8_encoding": {
Type: schema.TypeBool,
Optional: true,
Computed: true,
Description: "CRS validate UTF8 encoding",
},
"error_anomaly_score": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
Description: "Score value to add for error anomalies",
},
"high_risk_country_codes": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "A space-separated list of country codes in ISO 3166-1 (two-letter) format",
},
"http_violation_score_threshold": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
Description: "HTTP violation threshold",
ValidateFunc: validation.IntAtLeast(1),
},
"inbound_anomaly_score_threshold": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
Description: "Inbound anomaly threshold",
ValidateFunc: validation.IntAtLeast(1),
},
"lfi_score_threshold": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
Description: "Local file inclusion attack threshold",
ValidateFunc: validation.IntAtLeast(1),
},
"max_file_size": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
Description: "The maximum allowed file size, in bytes",
},
"max_num_args": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
Description: "The maximum number of arguments allowed",
},
"number": {
Type: schema.TypeInt,
Computed: true,
Description: "The WAF firewall version",
},
"notice_anomaly_score": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
Description: "Score value to add for notice anomalies",
},
"paranoia_level": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
Description: "The configured paranoia level",
},
"php_injection_score_threshold": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
Description: "PHP injection threshold",
ValidateFunc: validation.IntAtLeast(1),
},
"rce_score_threshold": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
Description: "Remote code execution threshold",
ValidateFunc: validation.IntAtLeast(1),
},
"restricted_extensions": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "A space-separated list of allowed file extensions",
},
"restricted_headers": {
Type: schema.TypeString,
Optional: true,
Computed: true,
Description: "A space-separated list of allowed header names",
},
"rfi_score_threshold": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
Description: "Remote file inclusion attack threshold",
ValidateFunc: validation.IntAtLeast(1),
},
"session_fixation_score_threshold": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
Description: "Session fixation attack threshold",
ValidateFunc: validation.IntAtLeast(1),
},
"sql_injection_score_threshold": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
Description: "SQL injection attack threshold",
ValidateFunc: validation.IntAtLeast(1),
},
"total_arg_length": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
Description: "The maximum size of argument names and values",
},
"warning_anomaly_score": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
Description: "Score value to add for warning anomalies",
},
"xss_score_threshold": {
Type: schema.TypeInt,
Optional: true,
Computed: true,
Description: "XSS attack threshold",
ValidateFunc: validation.IntAtLeast(1),
},
"rule": activeRule,
"rule_exclusion": wafRuleExclusion,
},
}
}
// this method calls update because the creation of the waf (within the service resource) automatically creates
// the first waf version, and this makes both a create and an updating exactly the same operation.
func resourceServiceWAFConfigurationCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
log.Printf("[INFO] creating configuration for WAF: %s", d.Get("waf_id").(string))
d.SetId(d.Get("waf_id").(string))
return resourceServiceWAFConfigurationUpdate(ctx, d, meta)
}
func resourceServiceWAFConfigurationUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
conn := meta.(*FastlyClient).conn
// If any attributes other than Computed (unconfigurable) or "activate" have changed, clone a new firewall version.
// Otherwise, don't clone but activate a draft version that was previously created with "activate = false".
var needsChange bool
for k, v := range resourceServiceWAFConfiguration().Schema {
if (v.Computed && !v.Optional) || k == "activate" {
continue
}
if d.HasChange(k) {
needsChange = true
break
}
}
wafID := d.Get("waf_id").(string)
log.Printf("[INFO] updating configuration for WAF: %s", wafID)
var latestVersion *gofastly.WAFVersion
var err error
if needsChange {
latestVersion, err = getLatestVersion(d, meta)
if err != nil {
return diag.FromErr(err)
}
if latestVersion.Locked {
latestVersion, err = conn.CloneWAFVersion(&gofastly.CloneWAFVersionInput{
WAFID: wafID,
WAFVersionNumber: latestVersion.Number,
})
if err != nil {
return diag.FromErr(err)
}
}
err = d.Set("cloned_version", latestVersion.Number)
if err != nil {
return diag.FromErr(err)
}
input := buildUpdateInput(d, latestVersion.ID, latestVersion.Number)
if input.HasChanges() {
latestVersion, err = conn.UpdateWAFVersion(input)
if err != nil {
return diag.FromErr(err)
}
}
if d.HasChange("rule") {
if err := updateRules(d, meta, wafID, latestVersion.Number); err != nil {
return diag.FromErr(err)
}
}
if d.HasChange("rule_exclusion") {
if err := updateWAFRuleExclusions(d, meta, wafID, latestVersion.Number); err != nil {
return diag.FromErr(err)
}
}
} else {
// Retrieve draft version
versionToRead := d.Get("cloned_version").(int)
latestVersion, err = conn.GetWAFVersion(&gofastly.GetWAFVersionInput{
WAFID: wafID,
WAFVersionNumber: versionToRead,
})
if err != nil {
return diag.FromErr(err)
}
}
shouldActivate := d.Get("activate").(bool)
versionNotYetActivated := !needsChange && (!latestVersion.Locked && !latestVersion.Active)
if shouldActivate && (needsChange || versionNotYetActivated) {
err := conn.DeployWAFVersion(&gofastly.DeployWAFVersionInput{
WAFID: wafID,
WAFVersionNumber: d.Get("cloned_version").(int),
})
if err != nil {
return diag.FromErr(err)
}
statusCheck := &WAFDeploymentChecker{
Timeout: d.Timeout(schema.TimeoutCreate),
Delay: WAFStatusCheckDelay,
MinTimeout: WAFStatusCheckMinTimeout,
Check: DefaultWAFDeploymentChecker(conn),
}
err = statusCheck.waitForDeployment(ctx, wafID, latestVersion)
if err != nil {
return diag.FromErr(err)
}
}
return resourceServiceWAFConfigurationRead(ctx, d, meta)
}
func resourceServiceWAFConfigurationRead(_ context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
latestVersion, err := getLatestVersion(d, meta)
if err != nil {
if errRes, ok := err.(*gofastly.HTTPError); ok {
if errRes.StatusCode == 404 {
d.SetId("")
return diag.Diagnostics{
diag.Diagnostic{
Severity: diag.Warning,
Summary: fmt.Sprintf("WAF (%s) not found - removing from state", d.Get("waf_id")),
AttributePath: cty.Path{cty.GetAttrStep{Name: "waf_id"}},
},
}
}
}
return diag.FromErr(err)
}
if d.Get("cloned_version").(int) == 0 {
err := d.Set("cloned_version", latestVersion.Number)
if err != nil {
return diag.FromErr(err)
}
}
if d.Get("activate") == false {
conn := meta.(*FastlyClient).conn
wafID := d.Get("waf_id").(string)
versionToRead := d.Get("cloned_version").(int)
latestVersion, err = conn.GetWAFVersion(&gofastly.GetWAFVersionInput{
WAFID: wafID,
WAFVersionNumber: versionToRead,
})
if err != nil {
return diag.FromErr(err)
}
} else {
err := d.Set("cloned_version", latestVersion.Number)
if err != nil {
return diag.FromErr(err)
}
}
log.Printf("[INFO] retrieving WAF version number: %d", latestVersion.Number)
refreshWAFConfig(d, latestVersion)
if err := readWAFRules(meta, d, latestVersion.Number); err != nil {
return diag.FromErr(err)
}
// As the rule exclusion API is still behind a beta feature
// flag, ensure we only read if the Set is non-empty.
//
// TODO(phamann): Remove d.GetOk() guard once in limited availability.
if _, ok := d.GetOk("rule_exclusion"); ok {
if err := readWAFRuleExclusions(meta, d, latestVersion.Number); err != nil {
return diag.FromErr(err)
}
}
return nil
}
func resourceServiceWAFConfigurationDelete(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
conn := meta.(*FastlyClient).conn
wafID := d.Get("waf_id").(string)
log.Printf("[INFO] destroying configuration by creating empty version of WAF: %s", wafID)
emptyVersion, err := conn.CreateEmptyWAFVersion(&gofastly.CreateEmptyWAFVersionInput{
WAFID: wafID,
})
if err != nil {
return diag.FromErr(err)
}
err = conn.DeployWAFVersion(&gofastly.DeployWAFVersionInput{
WAFID: wafID,
WAFVersionNumber: emptyVersion.Number,
})
if err != nil {
return diag.FromErr(err)
}
statusCheck := &WAFDeploymentChecker{
Timeout: d.Timeout(schema.TimeoutCreate),
Delay: WAFStatusCheckDelay,
MinTimeout: WAFStatusCheckMinTimeout,
Check: DefaultWAFDeploymentChecker(conn),
}
err = statusCheck.waitForDeployment(ctx, wafID, emptyVersion)
if err != nil {
return diag.Errorf("Error waiting for WAF Version (%s) to be deleted: %s", d.Id(), err)
}
d.SetId("")
return nil
}
func resourceServiceWAFConfigurationImport(_ context.Context, d *schema.ResourceData, _ interface{}) ([]*schema.ResourceData, error) {
wafID := d.Id()
err := d.Set("waf_id", wafID)
if err != nil {
return nil, fmt.Errorf("error importing WAF configuration: WAF %s, %s", wafID, err)
}
return []*schema.ResourceData{d}, nil
}
func getLatestVersion(d *schema.ResourceData, meta interface{}) (*gofastly.WAFVersion, error) {
conn := meta.(*FastlyClient).conn
wafID := d.Get("waf_id").(string)
resp, err := conn.ListAllWAFVersions(&gofastly.ListAllWAFVersionsInput{
WAFID: wafID,
})
if err != nil {
return nil, err
}
latest, err := determineLatestVersion(resp.Items)
if err != nil {
return nil, fmt.Errorf("[ERR] Error looking up WAF id: %s, with error %s", wafID, err)
}
return latest, nil
}
func buildUpdateInput(d *schema.ResourceData, id string, number int) *gofastly.UpdateWAFVersionInput {
input := &gofastly.UpdateWAFVersionInput{
WAFVersionID: &id,
WAFVersionNumber: &number,
}
if v, ok := d.GetOk("waf_id"); ok {
input.WAFID = gofastly.String(v.(string))
}
if v, ok := d.GetOk("allowed_http_versions"); ok {
input.AllowedHTTPVersions = gofastly.String(v.(string))
}
if v, ok := d.GetOk("allowed_methods"); ok {
input.AllowedMethods = gofastly.String(v.(string))
}
if v, ok := d.GetOk("allowed_request_content_type"); ok {
input.AllowedRequestContentType = gofastly.String(v.(string))
}
if v, ok := d.GetOk("allowed_request_content_type_charset"); ok {
input.AllowedRequestContentTypeCharset = gofastly.String(v.(string))
}
if v, ok := d.GetOk("arg_length"); ok {
input.ArgLength = gofastly.Int(v.(int))
}
if v, ok := d.GetOk("arg_name_length"); ok {
input.ArgNameLength = gofastly.Int(v.(int))
}
if v, ok := d.GetOk("combined_file_sizes"); ok {
input.CombinedFileSizes = gofastly.Int(v.(int))
}
if v, ok := d.GetOk("critical_anomaly_score"); ok {
input.CriticalAnomalyScore = gofastly.Int(v.(int))
}
if v, ok := d.GetOk("crs_validate_utf8_encoding"); ok {
input.CRSValidateUTF8Encoding = gofastly.Bool(v.(bool))
}
if v, ok := d.GetOk("error_anomaly_score"); ok {
input.ErrorAnomalyScore = gofastly.Int(v.(int))
}
if v, ok := d.GetOk("high_risk_country_codes"); ok {
input.HighRiskCountryCodes = gofastly.String(v.(string))
}
if v, ok := d.GetOk("http_violation_score_threshold"); ok {
input.HTTPViolationScoreThreshold = gofastly.Int(v.(int))
}
if v, ok := d.GetOk("inbound_anomaly_score_threshold"); ok {
input.InboundAnomalyScoreThreshold = gofastly.Int(v.(int))
}
if v, ok := d.GetOk("lfi_score_threshold"); ok {
input.LFIScoreThreshold = gofastly.Int(v.(int))
}
if v, ok := d.GetOk("max_file_size"); ok {
input.MaxFileSize = gofastly.Int(v.(int))
}
if v, ok := d.GetOk("max_num_args"); ok {
input.MaxNumArgs = gofastly.Int(v.(int))
}
if v, ok := d.GetOk("notice_anomaly_score"); ok {
input.NoticeAnomalyScore = gofastly.Int(v.(int))
}
if v, ok := d.GetOk("paranoia_level"); ok {
input.ParanoiaLevel = gofastly.Int(v.(int))
}
if v, ok := d.GetOk("php_injection_score_threshold"); ok {
input.PHPInjectionScoreThreshold = gofastly.Int(v.(int))
}
if v, ok := d.GetOk("rce_score_threshold"); ok {
input.RCEScoreThreshold = gofastly.Int(v.(int))
}
if v, ok := d.GetOk("restricted_extensions"); ok {
input.RestrictedExtensions = gofastly.String(v.(string))
}
if v, ok := d.GetOk("restricted_headers"); ok {
input.RestrictedHeaders = gofastly.String(v.(string))
}
if v, ok := d.GetOk("rfi_score_threshold"); ok {
input.RFIScoreThreshold = gofastly.Int(v.(int))
}
if v, ok := d.GetOk("session_fixation_score_threshold"); ok {
input.SessionFixationScoreThreshold = gofastly.Int(v.(int))
}
if v, ok := d.GetOk("sql_injection_score_threshold"); ok {
input.SQLInjectionScoreThreshold = gofastly.Int(v.(int))
}
if v, ok := d.GetOk("total_arg_length"); ok {
input.TotalArgLength = gofastly.Int(v.(int))
}
if v, ok := d.GetOk("warning_anomaly_score"); ok {
input.WarningAnomalyScore = gofastly.Int(v.(int))
}
if v, ok := d.GetOk("xss_score_threshold"); ok {
input.XSSScoreThreshold = gofastly.Int(v.(int))
}
return input
}
func refreshWAFConfig(d *schema.ResourceData, version *gofastly.WAFVersion) {
d.Set("active", version.Active)
d.Set("allowed_http_versions", version.AllowedHTTPVersions)
d.Set("allowed_methods", version.AllowedMethods)
d.Set("allowed_request_content_type", version.AllowedRequestContentType)
d.Set("allowed_request_content_type_charset", version.AllowedRequestContentTypeCharset)
d.Set("arg_length", version.ArgLength)
d.Set("arg_name_length", version.ArgNameLength)
d.Set("combined_file_sizes", version.CombinedFileSizes)
d.Set("critical_anomaly_score", version.CriticalAnomalyScore)
d.Set("crs_validate_utf8_encoding", version.CRSValidateUTF8Encoding)
d.Set("error_anomaly_score", version.ErrorAnomalyScore)
d.Set("high_risk_country_codes", version.HighRiskCountryCodes)
d.Set("http_violation_score_threshold", version.HTTPViolationScoreThreshold)
d.Set("inbound_anomaly_score_threshold", version.InboundAnomalyScoreThreshold)
d.Set("lfi_score_threshold", version.LFIScoreThreshold)
d.Set("max_file_size", version.MaxFileSize)
d.Set("max_num_args", version.MaxNumArgs)
d.Set("number", version.Number)
d.Set("notice_anomaly_score", version.NoticeAnomalyScore)
d.Set("paranoia_level", version.ParanoiaLevel)
d.Set("php_injection_score_threshold", version.PHPInjectionScoreThreshold)
d.Set("rce_score_threshold", version.RCEScoreThreshold)
d.Set("restricted_extensions", version.RestrictedExtensions)
d.Set("restricted_headers", version.RestrictedHeaders)
d.Set("rfi_score_threshold", version.RFIScoreThreshold)
d.Set("session_fixation_score_threshold", version.SessionFixationScoreThreshold)
d.Set("sql_injection_score_threshold", version.SQLInjectionScoreThreshold)
d.Set("total_arg_length", version.TotalArgLength)
d.Set("warning_anomaly_score", version.WarningAnomalyScore)
d.Set("xss_score_threshold", version.XSSScoreThreshold)
}
func determineLatestVersion(versions []*gofastly.WAFVersion) (*gofastly.WAFVersion, error) {
if len(versions) == 0 {
return nil, errors.New("the list of WAFVersions cannot be empty")
}
sort.Slice(versions, func(i, j int) bool {
return versions[i].Number > versions[j].Number
})
// Find the current active firewall version
// or, pick the most recent version if there's no active version yet
latest := versions[0]
for _, v := range versions {
if v.Active {
latest = v
break
}
}
return latest, nil
}
func validateWAFConfigurationResource(_ context.Context, d *schema.ResourceDiff, _ interface{}) error {
return validateWAFRuleExclusion(d)
}