This repository has been archived by the owner on Dec 13, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathwaflyctl.go
2256 lines (1896 loc) · 67.9 KB
/
waflyctl.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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* WAF provisioning tool
*
* Copyright (c) 2018-2019 Fastly Inc.
* Author: Jose Enrique Hernandez
*/
package main
import (
"bytes"
"crypto/sha1"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"os/user"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/BurntSushi/toml"
"github.com/fastly/go-fastly/fastly"
"gopkg.in/alecthomas/kingpin.v2"
"gopkg.in/resty.v1"
)
var (
//logging variables
logFile string
//Info level logging
Info *log.Logger
//Warning level logging
Warning *log.Logger
//Error level logging
Error *log.Logger
// version number
version = "dev"
date = "unknown"
)
// TOMLConfig is the applications config file
type TOMLConfig struct {
Logpath string
APIEndpoint string
Tags []string
Publisher []string
Action string
Rules []int64
DisabledRules []int64
Owasp owaspSettings
Weblog WeblogSettings
Waflog WaflogSettings
Vclsnippet VCLSnippetSettings
AdditionalSnippets map[string]VCLSnippetSettings
Response ResponseSettings
Prefetch PrefetchSettings
}
// Backup is a backup of the rule status for a WAF
type Backup struct {
ServiceID string
ID string
Updated time.Time
Disabled []int64
Block []int64
Log []int64
Owasp owaspSettings
}
type owaspSettings struct {
AllowedHTTPVersions string
AllowedMethods string
AllowedRequestContentType string
AllowedRequestContentTypeCharset string
ArgLength int
ArgNameLength int
CombinedFileSizes int
CriticalAnomalyScore int
CRSValidateUTF8Encoding bool
ErrorAnomalyScore int
HTTPViolationScoreThreshold int
InboundAnomalyScoreThreshold int
LFIScoreThreshold int
MaxFileSize int
MaxNumArgs int
NoticeAnomalyScore int
ParanoiaLevel int
PHPInjectionScoreThreshold int
RCEScoreThreshold int
RestrictedExtensions string
RestrictedHeaders string
RFIScoreThreshold int
SessionFixationScoreThreshold int
SQLInjectionScoreThreshold int
XSSScoreThreshold int
TotalArgLength int
WarningAnomalyScore int
}
// WeblogSettings parameters for logs in config file
type WeblogSettings struct {
Name string
Address string
Port uint
Tlscacert string
Tlshostname string
Format string
Condition string
Expiry uint
}
// VCLSnippetSettings parameters for snippets in config file
type VCLSnippetSettings struct {
Name string
Content string
Type fastly.SnippetType
Priority int
Dynamic int
}
// WaflogSettings parameters from config
type WaflogSettings struct {
Name string
Address string
Port uint
Tlscacert string
Tlshostname string
Format string
}
// ResponseSettings parameters from config
type ResponseSettings struct {
Name string
HTTPStatusCode uint
HTTPResponse string
ContentType string
Content string
}
// PrefetchSettings parameters from config
type PrefetchSettings struct {
Name string
Statement string
Type string
Priority int
}
// RuleList contains list of rules
type RuleList struct {
Data []Rule
Links struct {
Last string `json:"last"`
First string `json:"first"`
Next string `json:"next"`
} `json:"links"`
Meta struct {
CurrentPage int `json:"current_page"`
PerPage int `json:"per_page"`
RecordCount int `json:"record_count"`
TotalPages int `json:"total_pages"`
} `json:"meta"`
}
// Rule from Fastly API
type Rule struct {
ID string `json:"id"`
Type string `json:"type"`
Attributes struct {
Message string `json:"message"`
Status string `json:"status"`
Publisher string `json:"publisher"`
ParanoiaLevel int `json:"paranoia_level"`
Revision int `json:"revision"`
Severity interface{} `json:"severity"`
Version interface{} `json:"version"`
RuleID string `json:"rule_id"`
ModsecRuleID string `json:"modsec_rule_id"`
UniqueRuleID string `json:"unique_rule_id"`
Source interface{} `json:"source"`
Vcl interface{} `json:"vcl"`
} `json:"attributes"`
}
// PagesOfRules contains a list of rulelist
type PagesOfRules struct {
page []RuleList
}
// PagesOfConfigurationSets contains a list of ConfigSetList
type PagesOfConfigurationSets struct {
page []ConfigSetList
}
// ConfigSetList contains a list of configuration set and its metadata
type ConfigSetList struct {
Data []ConfigSet
Links struct {
Last string `json:"last"`
First string `json:"first"`
Next string `json:"next"`
} `json:"links"`
Meta struct {
CurrentPage int `json:"current_page"`
PerPage int `json:"per_page"`
RecordCount int `json:"record_count"`
TotalPages int `json:"total_pages"`
} `json:"meta"`
}
// ConfigSet defines details of a configuration set
type ConfigSet struct {
ID string `json:"id"`
Type string `json:"type"`
Attributes struct {
Active bool `json:"active"`
Name string `json:"name"`
} `json:"attributes"`
}
// PatchRulesStatusCheck details the status of a ruleset deployment
type PatchRulesStatusCheck struct {
Data struct {
ID string
Attributes struct {
Status string
}
}
}
//Init function starts our logger
func Init(configFile string) TOMLConfig {
//load configs
var config TOMLConfig
if _, err := toml.DecodeFile(configFile, &config); err != nil {
fmt.Println("Could not read config file -", err)
os.Exit(1)
}
//assigned the right log path
if config.Logpath == "" {
fmt.Println("no log path defined using default waflyctl.log")
config.Logpath = "waflyctl.log"
}
/*
fmt.Println("config settings: ")
fmt.Println("- logpath",config.Logpath)
fmt.Println("- apiendpoint", config.APIEndpoint)
fmt.Println("- owasp", config.Owasp)
fmt.Println("- weblogs", config.Weblog.Port)
fmt.Println("- waflogs", config.Waflog.Port)
*/
//now lets create a logging object
file, err := os.OpenFile(config.Logpath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600)
if err != nil {
log.Fatalln("Failed to open log file", logFile, ":", err)
}
multi := io.MultiWriter(file, os.Stdout)
Info = log.New(multi,
"INFO: ",
log.Ldate|log.Ltime|log.Lshortfile)
Warning = log.New(multi,
"WARNING: ",
log.Ldate|log.Ltime|log.Lshortfile)
Error = log.New(multi,
"ERROR: ",
log.Ldate|log.Ltime|log.Lshortfile)
return config
}
func getActiveVersion(client *fastly.Client, serviceID string) int {
service, err := client.GetService(&fastly.GetServiceInput{
ID: serviceID,
})
if err != nil {
Error.Fatalf("Cannot get service %q: GetService: %v\n", serviceID, err)
}
for _, version := range service.Versions {
if version.Active {
return version.Number
}
}
Error.Fatal("No active version found (wrong service id?). Aborting")
return 0
}
func cloneVersion(client *fastly.Client, serviceID string, activeVersion int, comment string) int {
version, err := client.CloneVersion(&fastly.CloneVersionInput{
Service: serviceID,
Version: activeVersion,
})
if err != nil {
Error.Fatalf("Cannot clone version %d: CloneVersion: %v\n", activeVersion, err)
}
if comment == "" {
Info.Printf("New version %d created\n", version.Number)
} else {
client.UpdateVersion(&fastly.UpdateVersionInput{
Service: serviceID,
Version: version.Number,
Comment: comment,
})
Info.Printf("New version %d created. Comment: %s\n", version.Number, comment)
}
return version.Number
}
func prefetchCondition(client *fastly.Client, serviceID string, config TOMLConfig, version int) {
conditions, err := client.ListConditions(&fastly.ListConditionsInput{
Service: serviceID,
Version: version,
})
if err != nil {
Error.Fatalf("Cannot create prefetch condition %q: ListConditions: %v\n", config.Prefetch.Name, err)
}
if !conditionExists(conditions, config.Prefetch.Name) {
_, err = client.CreateCondition(&fastly.CreateConditionInput{
Service: serviceID,
Version: version,
Name: config.Prefetch.Name,
Statement: config.Prefetch.Statement,
Type: config.Prefetch.Type,
Priority: 10,
})
if err != nil {
Error.Fatalf("Cannot create prefetch condition %q: CreateCondition: %v\n", config.Prefetch.Name, err)
}
Info.Printf("Prefetch condition %q created\n", config.Prefetch.Name)
} else {
Warning.Printf("Prefetch condition %q already exists, skipping\n", config.Prefetch.Name)
}
}
func responseObject(client *fastly.Client, serviceID string, config TOMLConfig, version int) {
responses, err := client.ListResponseObjects(&fastly.ListResponseObjectsInput{
Service: serviceID,
Version: version,
})
if err != nil {
Error.Fatalf("Cannot create response object %q: ListResponseObjects: %v\n", config.Response.Name, err)
}
for _, response := range responses {
if strings.EqualFold(response.Name, config.Response.Name) {
Warning.Printf("Response object %q already exists, skipping\n", config.Response.Name)
return
}
}
_, err = client.CreateResponseObject(&fastly.CreateResponseObjectInput{
Service: serviceID,
Version: version,
Name: config.Response.Name,
Status: config.Response.HTTPStatusCode,
Response: config.Response.HTTPResponse,
Content: config.Response.Content,
ContentType: config.Response.ContentType,
})
if err != nil {
Error.Fatalf("Cannot create response object %q: CreateResponseObject: %v\n", config.Response.Name, err)
}
Info.Printf("Response object %q created\n", config.Response.Name)
}
func vclSnippet(client *fastly.Client, serviceID string, vclSnippet VCLSnippetSettings, version int) {
snippets, err := client.ListSnippets(&fastly.ListSnippetsInput{
Service: serviceID,
Version: version,
})
if err != nil {
Error.Fatalf("Cannot create VCL snippet %q: ListSnippets: %v\n", vclSnippet.Name, err)
}
for _, snippet := range snippets {
if snippet.Name == vclSnippet.Name {
Warning.Printf("VCL snippet %q already exists, skipping\n", vclSnippet.Name)
return
}
}
_, err = client.CreateSnippet(&fastly.CreateSnippetInput{
Service: serviceID,
Version: version,
Name: vclSnippet.Name,
Priority: vclSnippet.Priority,
Dynamic: vclSnippet.Dynamic,
Content: vclSnippet.Content,
Type: vclSnippet.Type,
})
if err != nil {
Error.Fatalf("Cannot create VCL snippet %q: CreateSnippet: %v\n", vclSnippet.Name, err)
}
Info.Printf("VCL snippet %q created\n", vclSnippet.Name)
}
func fastlyLogging(client *fastly.Client, serviceID string, config TOMLConfig, version int) {
if config.Weblog.Name != "" {
_, err := client.CreateSyslog(&fastly.CreateSyslogInput{
Service: serviceID,
Version: version,
Name: config.Weblog.Name,
Address: config.Weblog.Address,
Port: config.Weblog.Port,
UseTLS: fastly.CBool(true),
TLSCACert: config.Weblog.Tlscacert,
TLSHostname: config.Weblog.Tlshostname,
Format: config.Weblog.Format,
FormatVersion: 2,
MessageType: "blank",
})
switch {
case err == nil:
Info.Printf("Logging endpoint %q created\n", config.Weblog.Name)
case strings.Contains(err.Error(), "Duplicate record"):
Warning.Printf("Logging endpoint %q already exists, skipping\n", config.Weblog.Name)
default:
Error.Fatalf("Cannot create logging endpoint %q: CreateSyslog: %v\n", config.Weblog.Name, err)
}
} else {
Warning.Printf("Empty or invalid web log configuration, skipping\n")
}
if config.Waflog.Name != "" {
_, err := client.CreateSyslog(&fastly.CreateSyslogInput{
Service: serviceID,
Version: version,
Name: config.Waflog.Name,
Address: config.Waflog.Address,
Port: config.Waflog.Port,
UseTLS: fastly.CBool(true),
TLSCACert: config.Waflog.Tlscacert,
TLSHostname: config.Waflog.Tlshostname,
Format: config.Waflog.Format,
FormatVersion: 2,
MessageType: "blank",
Placement: "waf_debug",
})
switch {
case err == nil:
Info.Printf("Logging endpoint %q created\n", config.Waflog.Name)
case strings.Contains(err.Error(), "Duplicate record"):
Warning.Printf("Logging endpoint %q already exists, skipping\n", config.Waflog.Name)
default:
Error.Fatalf("Cannot create logging endpoint %q: CreateSyslog: %v\n", config.Waflog.Name, err)
}
} else {
Warning.Printf("Empty or invalid web log configuration, skipping\n")
}
}
func wafContainer(client *fastly.Client, serviceID string, config TOMLConfig, version int) string {
waf, err := client.CreateWAF(&fastly.CreateWAFInput{
Service: serviceID,
Version: version,
PrefetchCondition: config.Prefetch.Name,
Response: config.Response.Name,
})
if err != nil {
Error.Fatalf("Cannot create WAF: CreateWAF: %v\n", err)
}
Info.Printf("WAF %q created\n", waf.ID)
return waf.ID
}
func createOWASP(client *fastly.Client, serviceID string, config TOMLConfig, wafID string) {
var created bool
var err error
owasp, _ := client.GetOWASP(&fastly.GetOWASPInput{
Service: serviceID,
ID: wafID,
})
if owasp.ID == "" {
owasp, err = client.CreateOWASP(&fastly.CreateOWASPInput{
Service: serviceID,
ID: wafID,
})
if err != nil {
Error.Fatalf("%v\n", err)
}
created = true
}
owasp, err = client.UpdateOWASP(&fastly.UpdateOWASPInput{
Service: serviceID,
ID: wafID,
OWASPID: owasp.ID,
AllowedHTTPVersions: config.Owasp.AllowedHTTPVersions,
AllowedMethods: config.Owasp.AllowedMethods,
AllowedRequestContentType: config.Owasp.AllowedRequestContentType,
AllowedRequestContentTypeCharset: config.Owasp.AllowedRequestContentTypeCharset,
ArgLength: config.Owasp.ArgLength,
ArgNameLength: config.Owasp.ArgNameLength,
CombinedFileSizes: config.Owasp.CombinedFileSizes,
CriticalAnomalyScore: config.Owasp.CriticalAnomalyScore,
CRSValidateUTF8Encoding: config.Owasp.CRSValidateUTF8Encoding,
ErrorAnomalyScore: config.Owasp.ErrorAnomalyScore,
HTTPViolationScoreThreshold: config.Owasp.HTTPViolationScoreThreshold,
InboundAnomalyScoreThreshold: config.Owasp.InboundAnomalyScoreThreshold,
LFIScoreThreshold: config.Owasp.LFIScoreThreshold,
MaxFileSize: config.Owasp.MaxFileSize,
MaxNumArgs: config.Owasp.MaxNumArgs,
NoticeAnomalyScore: config.Owasp.NoticeAnomalyScore,
ParanoiaLevel: config.Owasp.ParanoiaLevel,
PHPInjectionScoreThreshold: config.Owasp.PHPInjectionScoreThreshold,
RCEScoreThreshold: config.Owasp.RCEScoreThreshold,
RestrictedExtensions: config.Owasp.RestrictedExtensions,
RestrictedHeaders: config.Owasp.RestrictedHeaders,
RFIScoreThreshold: config.Owasp.RFIScoreThreshold,
SessionFixationScoreThreshold: config.Owasp.SessionFixationScoreThreshold,
SQLInjectionScoreThreshold: config.Owasp.SQLInjectionScoreThreshold,
XSSScoreThreshold: config.Owasp.XSSScoreThreshold,
TotalArgLength: config.Owasp.TotalArgLength,
WarningAnomalyScore: config.Owasp.WarningAnomalyScore,
})
if err != nil {
Error.Fatalf("%v\n", err)
}
if created {
Info.Println("OWASP settings created with the following settings:")
} else {
Info.Println("OWASP settings updated with the following settings:")
}
Info.Println(" - AllowedHTTPVersions:", owasp.AllowedHTTPVersions)
Info.Println(" - AllowedMethods:", owasp.AllowedMethods)
Info.Println(" - AllowedRequestContentType:", owasp.AllowedRequestContentType)
Info.Println(" - AllowedRequestContentTypeCharset:", owasp.AllowedRequestContentTypeCharset)
Info.Println(" - ArgLength:", owasp.ArgLength)
Info.Println(" - ArgNameLength:", owasp.ArgNameLength)
Info.Println(" - CombinedFileSizes:", owasp.CombinedFileSizes)
Info.Println(" - CriticalAnomalyScore:", owasp.CriticalAnomalyScore)
Info.Println(" - CRSValidateUTF8Encoding:", owasp.CRSValidateUTF8Encoding)
Info.Println(" - ErrorAnomalyScore:", owasp.ErrorAnomalyScore)
Info.Println(" - HTTPViolationScoreThreshold:", owasp.HTTPViolationScoreThreshold)
Info.Println(" - InboundAnomalyScoreThreshold:", owasp.InboundAnomalyScoreThreshold)
Info.Println(" - LFIScoreThreshold:", owasp.LFIScoreThreshold)
Info.Println(" - MaxFileSize:", owasp.MaxFileSize)
Info.Println(" - MaxNumArgs:", owasp.MaxNumArgs)
Info.Println(" - NoticeAnomalyScore:", owasp.NoticeAnomalyScore)
Info.Println(" - ParanoiaLevel:", owasp.ParanoiaLevel)
Info.Println(" - PHPInjectionScoreThreshold:", owasp.PHPInjectionScoreThreshold)
Info.Println(" - RCEScoreThreshold:", owasp.RCEScoreThreshold)
Info.Println(" - RestrictedHeaders:", owasp.RestrictedHeaders)
Info.Println(" - RFIScoreThreshold:", owasp.RFIScoreThreshold)
Info.Println(" - SessionFixationScoreThreshold:", owasp.SessionFixationScoreThreshold)
Info.Println(" - SQLInjectionScoreThreshold:", owasp.SQLInjectionScoreThreshold)
Info.Println(" - XssScoreThreshold:", owasp.XSSScoreThreshold)
Info.Println(" - TotalArgLength:", owasp.TotalArgLength)
Info.Println(" - WarningAnomalyScore:", owasp.WarningAnomalyScore)
}
// DeleteLogsCall removes logging endpoints and any logging conditions.
func DeleteLogsCall(client *fastly.Client, serviceID string, config TOMLConfig, version int) bool {
//Get a list of SysLogs
slogs, err := client.ListSyslogs(&fastly.ListSyslogsInput{
Service: serviceID,
Version: version,
})
if err != nil {
Error.Println(err)
return false
}
//drop syslogs if they exist
if sysLogExists(slogs, config.Weblog.Name) {
Info.Printf("Deleting Web logging endpoint: %q\n", config.Weblog.Name)
err = client.DeleteSyslog(&fastly.DeleteSyslogInput{
Service: serviceID,
Version: version,
Name: config.Weblog.Name,
})
if err != nil {
fmt.Println(err)
return false
}
}
if sysLogExists(slogs, config.Waflog.Name) {
Info.Printf("Deleting WAF logging endpoint: %q\n", config.Waflog.Name)
err = client.DeleteSyslog(&fastly.DeleteSyslogInput{
Service: serviceID,
Version: version,
Name: config.Waflog.Name,
})
if err != nil {
fmt.Println(err)
return false
}
}
//first find if we have any PX conditions
conditions, err := client.ListConditions(&fastly.ListConditionsInput{
Service: serviceID,
Version: version,
})
if err != nil {
Error.Println(err)
return false
}
//remove logging conditions (and expiry conditions)
if conditionExists(conditions, "waf-soc-logging") {
Info.Println("Deleting logging condition: 'waf-soc-logging'")
err = client.DeleteCondition(&fastly.DeleteConditionInput{
Service: serviceID,
Version: version,
Name: "waf-soc-logging",
})
if err != nil {
Error.Println(err)
return false
}
}
if conditionExists(conditions, "waf-soc-logging-with-expiry") {
Info.Println("Deleting logging condition: 'waf-soc-logging-with-expiry'")
err = client.DeleteCondition(&fastly.DeleteConditionInput{
Service: serviceID,
Version: version,
Name: "waf-soc-logging-with-expiry",
})
if err != nil {
Error.Println(err)
return false
}
}
//Legacy conditions
//remove PerimeterX logging condition (if exists)
if conditionExists(conditions, "waf-soc-with-px") {
Info.Println("Deleting Legacy PerimeterX logging condition: 'waf-soc-with-px'")
err = client.DeleteCondition(&fastly.DeleteConditionInput{
Service: serviceID,
Version: version,
Name: "waf-soc-with-px",
})
if err != nil {
Error.Println(err)
return false
}
}
//remove legacy shielding logging condition (if exists)
if conditionExists(conditions, "waf-soc-with-shielding") {
Info.Println("Deleting Legacy Shielding logging condition: 'waf-soc-with-shielding'")
err = client.DeleteCondition(&fastly.DeleteConditionInput{
Service: serviceID,
Version: version,
Name: "waf-soc-with-shielding",
})
if err != nil {
Error.Println(err)
return false
}
}
return true
}
// conditionExists iterates through the given slice of conditions and returns
// whether the given name exists in the collection
func conditionExists(conds []*fastly.Condition, name string) bool {
for _, c := range conds {
if strings.EqualFold(c.Name, name) {
return true
}
}
return false
}
// sysLogExists iterates through the given slice of syslogs and returns
// whether the given name exists in the collection
func sysLogExists(slogs []*fastly.Syslog, name string) bool {
for _, sl := range slogs {
if strings.EqualFold(sl.Name, name) {
return true
}
}
return false
}
// DeprovisionWAF removes a WAF from a service
func DeprovisionWAF(client *fastly.Client, serviceID, apiKey string, config TOMLConfig, version int) bool {
/*
To Remove
1. Delete response
2. Delete prefetch
3. Delete WAF
*/
//get current waf objects
wafs, err := client.ListWAFs(&fastly.ListWAFsInput{
Service: serviceID,
Version: version,
})
if err != nil {
Error.Fatal(err)
return false
}
if len(wafs) == 0 {
Error.Printf("No WAF object exists in current service %s version #%v .. exiting\n", serviceID, version)
return false
}
//get list of conditions
//first find if we have any PX conditions
conditions, err := client.ListConditions(&fastly.ListConditionsInput{
Service: serviceID,
Version: version,
})
if err != nil {
Error.Fatal(err)
return false
}
for index, waf := range wafs {
//remove WAF Logging
result := DeleteLogsCall(client, serviceID, config, version)
Info.Printf("Deleting WAF #%v Logging\n", index+1)
if !result {
Error.Printf("Deleting WAF #%v Logging.\n", index+1)
}
Info.Printf("Deleting WAF #%v Container\n", index+1)
//remove WAF container
err = client.DeleteWAF(&fastly.DeleteWAFInput{
Service: serviceID,
Version: version,
ID: waf.ID,
})
if err != nil {
Error.Print(err)
return false
}
//remove WAF Response Object
Info.Printf("Deleting WAF #%v Response Object\n", index+1)
err = client.DeleteResponseObject(&fastly.DeleteResponseObjectInput{
Service: serviceID,
Version: version,
Name: "WAF_Response",
})
if err != nil {
Error.Print(err)
return false
}
//remove WAF Prefetch condition (if exists)
if conditionExists(conditions, "WAF_Prefetch") {
Info.Printf("Deleting WAF #%v Prefetch Condition\n", index+1)
err = client.DeleteCondition(&fastly.DeleteConditionInput{
Service: serviceID,
Version: version,
Name: "WAF_Prefetch",
})
if err != nil {
Error.Print(err)
return false
}
}
//remove VCL Snippet
Info.Printf("Deleting WAF #%v VCL Snippet\n", index+1)
apiCall := config.APIEndpoint + "/service/" + serviceID + "/version/" + strconv.Itoa(version) + "/snippet/" + config.Vclsnippet.Name
//get list of current snippets
_, err := resty.R().
SetHeader("Accept", "application/json").
SetHeader("Fastly-Key", apiKey).
Delete(apiCall)
//check if we had an issue with our call
if err != nil {
Error.Printf("Deleting WAF #%v VCL Snippet\n", index+1)
}
}
return true
}
func provisionWAF(client *fastly.Client, serviceID string, config TOMLConfig, version int) string {
prefetchCondition(client, serviceID, config, version)
responseObject(client, serviceID, config, version)
vclSnippet(client, serviceID, config.Vclsnippet, version)
if len(config.AdditionalSnippets) > 0 {
for _, snippet := range config.AdditionalSnippets {
vclSnippet(client, serviceID, snippet, version)
}
}
wafID := wafContainer(client, serviceID, config, version)
createOWASP(client, serviceID, config, wafID)
if !*omitLogs {
fastlyLogging(client, serviceID, config, version)
}
return wafID
}
func validateVersion(client *fastly.Client, serviceID string, version int) bool {
valid, _, err := client.ValidateVersion(&fastly.ValidateVersionInput{
Service: serviceID,
Version: version,
})
if err != nil {
Error.Fatal(err)
return false
}
if !valid {
Error.Println("Version invalid")
return false
}
Info.Printf("Config Version %v validated. Remember to activate it\n", version)
return true
}
func publisherConfig(apiEndpoint, apiKey, serviceID, wafID string, config TOMLConfig) bool {
for _, publisher := range config.Publisher {
if publisher == "" {
continue
}
//set our API call
apiCall := apiEndpoint + "/wafs/rules?filter[publisher]=" + publisher + "&page[number]=1"
resp, err := resty.R().
SetHeader("Accept", "application/vnd.api+json").
SetHeader("Fastly-Key", apiKey).
SetHeader("Content-Type", "application/vnd.api+json").
Get(apiCall)
//check if we had an issue with our call
if err != nil {
Error.Println("Error with API call: " + apiCall)
Error.Println(resp.String())
return false
}
//unmarshal the response and extract the rules
body := RuleList{}
json.Unmarshal([]byte(resp.String()), &body)
if len(body.Data) == 0 {
Error.Println("No Fastly Rules found")
return false
}
result := PagesOfRules{[]RuleList{}}
result.page = append(result.page, body)
currentpage := body.Meta.CurrentPage
totalpages := body.Meta.TotalPages
Info.Printf("Read Total Pages: %d with %d rules\n", body.Meta.TotalPages, body.Meta.RecordCount)
// iterate through pages collecting all rules
for currentpage := currentpage + 1; currentpage <= totalpages; currentpage++ {
Info.Printf("Reading page: %d out of %d\n", currentpage, totalpages)
//set our API call
apiCall := apiEndpoint + "/wafs/rules?filter[publisher]=" + publisher + "&page[number]=" + strconv.Itoa(currentpage)
resp, err := resty.R().
SetHeader("Accept", "application/vnd.api+json").
SetHeader("Fastly-Key", apiKey).
SetHeader("Content-Type", "application/vnd.api+json").
Get(apiCall)
//check if we had an issue with our call
if err != nil {
Error.Println("Error with API call: " + apiCall)
Error.Println(resp.String())
return false
}
//unmarshal the response and extract the service id
body := RuleList{}
json.Unmarshal([]byte(resp.String()), &body)
result.page = append(result.page, body)
}
Info.Println("- Publisher ", publisher)
for _, p := range result.page {
for _, r := range p.Data {
//set rule action on our tags
apiCall := apiEndpoint + "/service/" + serviceID + "/wafs/" + wafID + "/rules/" + r.ID + "/rule_status"
resp, err := resty.R().
SetHeader("Accept", "application/vnd.api+json").
SetHeader("Fastly-Key", apiKey).
SetHeader("Content-Type", "application/vnd.api+json").
SetBody(`{"data": {"attributes": {"status": "` + config.Action + `"},"id": "` + wafID + `-` + r.ID + `","type": "rule_status"}}`).
Patch(apiCall)
//check if we had an issue with our call
if err != nil {
Error.Println("Error with API call: " + apiCall)
Error.Println(resp.String())
os.Exit(1)
}
//check if our response was ok
if resp.Status() == "200 OK" {
Info.Printf("Rule %s was configured in the WAF with action %s\n", r.ID, config.Action)
} else {
Error.Printf("Could not set status: %s on rule tag: %s the response was: %s\n", config.Action, r.ID, resp.String())
}
}
}
}
return true
}
func tagsConfig(apiEndpoint, apiKey, serviceID, wafID string, config TOMLConfig, forceStatus bool) {
//Work on Tags first
//API Endpoint to call for domain searches
apiCall := apiEndpoint + "/wafs/tags"
//make the call
ruleList := RuleList{}
for _, tag := range config.Tags {
if tag == "" {
continue
}
resp, err := resty.R().
SetQueryString(fmt.Sprintf("filter[name]=%s&include=rules", tag)).
SetHeader("Accept", "application/vnd.api+json").
SetHeader("Fastly-Key", apiKey).
Get(apiCall)
//check if we had an issue with our call
if err != nil {
Error.Println("Error with API call: " + apiCall)
os.Exit(1)
}
//unmarshal the response and extract the service id
body := RuleList{}
json.Unmarshal([]byte(resp.String()), &body)
if len(body.Data) == 0 {
Error.Printf("Could not find any rules with tag: %s please make sure it exists..moving to the next tag\n", tag)
continue
}
//set rule action on our tags
apiCall := apiEndpoint + "/service/" + serviceID + "/wafs/" + wafID + "/rule_statuses"
resp, err = resty.R().
SetHeader("Accept", "application/vnd.api+json").
SetHeader("Fastly-Key", apiKey).
SetHeader("Content-Type", "application/vnd.api+json").
SetBody(fmt.Sprintf(`{"data": {"attributes": {"status": "%s", "name": "%s", "force": %t}, "id": "%s", "type": "rule_status"}}`, config.Action, tag, forceStatus, wafID)).
Post(apiCall)
//check if we had an issue with our call
if err != nil {
Error.Println("Error with API call: " + apiCall)
Error.Println(resp.String())
os.Exit(1)
}
//unmarshal the response. Keep track of unique rules added by each tag so we can provide an accurate count
ruleCount := 0
if len(ruleList.Data) > 0 {
tmpRuleList := RuleList{}