-
Notifications
You must be signed in to change notification settings - Fork 5
/
waf2.go
269 lines (228 loc) · 8.58 KB
/
waf2.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
package waf2
import (
"fmt"
util "github.com/aldelo/common"
awshttp2 "github.com/aldelo/common/wrapper/aws"
"github.com/aldelo/common/wrapper/aws/awsregion"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/wafv2"
"net/http"
)
/*
* Copyright 2020-2023 Aldelo, LP
*
* 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.
*/
// =================================================================================================================
// AWS CREDENTIAL:
// use $> aws configure (to set aws access key and secret to target machine)
// Store AWS Access ID and Secret Key into Default Profile Using '$ aws configure' cli
//
// To Install & Setup AWS CLI on Host:
// 1) https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2-linux.html
// On Ubuntu, if host does not have zip and unzip:
// $> sudo apt install zip
// $> sudo apt install unzip
// On Ubuntu, to install AWS CLI v2:
// $> curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
// $> unzip awscliv2.zip
// $> sudo ./aws/install
// 2) $> aws configure set region awsRegionName --profile default
// 3) $> aws configure
// follow prompts to enter Access ID and Secret Key
//
// AWS Region Name Reference:
// us-west-2, us-east-1, ap-northeast-1, etc
// See: https://docs.aws.amazon.com/general/latest/gr/rande.html
// =================================================================================================================
// ================================================================================================================
// STRUCTS
// ================================================================================================================
type WAF2 struct {
// define the AWS region that s3 is located at
AwsRegion awsregion.AWSRegion
// custom http2 client options
HttpOptions *awshttp2.HttpClientSettings
// store aws session object
sess *session.Session
// store waf2 object
waf2Obj *wafv2.WAFV2
}
// ================================================================================================================
// STRUCTS FUNCTIONS
// ================================================================================================================
// ----------------------------------------------------------------------------------------------------------------
// utility functions
// ----------------------------------------------------------------------------------------------------------------
// Connect will establish a connection to the WAF2 service
func (w *WAF2) Connect() error {
// clean up prior session reference
w.sess = nil
if !w.AwsRegion.Valid() || w.AwsRegion == awsregion.UNKNOWN {
return fmt.Errorf("Connect To WAF2 Failed: (AWS Session Error) " + "Region is Required")
}
// create custom http2 client if needed
var httpCli *http.Client
var httpErr error
if w.HttpOptions == nil {
w.HttpOptions = new(awshttp2.HttpClientSettings)
}
// use custom http2 client
h2 := &awshttp2.AwsHttp2Client{
Options: w.HttpOptions,
}
if httpCli, httpErr = h2.NewHttp2Client(); httpErr != nil {
return fmt.Errorf("Connect to WAF2 Failed: (AWS Session Error) " + "Create Custom Http2 Client Errored = " + httpErr.Error())
}
// establish aws session connection and keep session object in struct
if sess, err := session.NewSession(
&aws.Config{
Region: aws.String(w.AwsRegion.Key()),
HTTPClient: httpCli,
}); err != nil {
// aws session error
return fmt.Errorf("Connect To WAF2 Failed: (AWS Session Error) " + err.Error())
} else {
// aws session obtained
w.waf2Obj = wafv2.New(sess)
if w.waf2Obj == nil {
return fmt.Errorf("Connect To WAF2 Object Failed: (New WAF2 Connection) " + "Connection Object Nil")
}
// session stored to struct
return nil
}
}
// UpdateIPSet will update an existing IPSet with new addresses specified
// ipsetName = exact name from WAF2 IP Set already created
// ipsetId = exact id from WAF2 IP Set already created
// scope = 'REGIONAL' or other scope per aws WAF2 doc (defaults to REGIONAL if blank)
// newAddr = addresses to add to ip set
//
// note: aws limit is 10000 ip per ip set
func (w *WAF2) UpdateIPSet(ipsetName string, ipsetId string, scope string, newAddr []string) error {
if util.LenTrim(ipsetName) == 0 {
return fmt.Errorf("UpdateIPSet Failed: ipsetName is Required")
}
if util.LenTrim(ipsetId) == 0 {
return fmt.Errorf("UpdateIPSet Failed: ipsetId is Required")
}
if util.LenTrim(scope) == 0 {
scope = "REGIONAL"
}
if len(newAddr) == 0 {
return fmt.Errorf("UpdateIPSet Failed: New Address to Add is Required")
}
var lockToken *string
var addrList []string
if getOutput, err := w.waf2Obj.GetIPSet(&wafv2.GetIPSetInput{
Name: aws.String(ipsetName),
Id: aws.String(ipsetId),
Scope: aws.String(scope),
}); err != nil {
// error
return fmt.Errorf("Get IP Set Failed: %s", err.Error())
} else {
lockToken = getOutput.LockToken
addrList = aws.StringValueSlice(getOutput.IPSet.Addresses)
addrList = append(addrList, newAddr...)
if len(addrList) > 10000 {
addrList = addrList[len(addrList)-10000:]
}
}
if _, err := w.waf2Obj.UpdateIPSet(&wafv2.UpdateIPSetInput{
Name: aws.String(ipsetName),
Id: aws.String(ipsetId),
Scope: aws.String(scope),
Addresses: aws.StringSlice(addrList),
LockToken: lockToken,
}); err != nil {
// error encountered
return fmt.Errorf("Update IP Set Failed: %s", err.Error())
} else {
// update completed
return nil
}
}
// UpdateRegexPatternSet will update an existing RegexPatternSet with new regex patterns specified
// regexPatternSetName = exact name from WAF2 Regex Pattern Set already created
// regexPatternSetId = exact id from WAF2 Regex Pattern Set already created
// scope = 'REGIONAL' or other scope per aws WAF2 doc (defaults to REGIONAL if blank)
// newRegexPatterns = regex patterns to add to regex pattern set
//
// NOTE = AWS limits to 10 regex expressions per regex set, and max of 10 regex sets
//
// this method will take the newest regex pattern to replace the older patterns
func (w *WAF2) UpdateRegexPatternSet(regexPatternSetName string, regexPatternSetId string, scope string, newRegexPatterns []string) error {
if util.LenTrim(regexPatternSetName) == 0 {
return fmt.Errorf("UpdateRegexPatternSet Failed: regexPatternSetName is Required")
}
if util.LenTrim(regexPatternSetId) == 0 {
return fmt.Errorf("UpdateRegexPatternSet Failed: regexPatternSetId is Required")
}
if util.LenTrim(scope) == 0 {
scope = "REGIONAL"
}
if len(newRegexPatterns) == 0 {
return fmt.Errorf("UpdateRegexPatternSet Failed: New Regex Pattern to Add is Required")
}
var lockToken *string
var patternsList []*wafv2.Regex
if getOutput, err := w.waf2Obj.GetRegexPatternSet(&wafv2.GetRegexPatternSetInput{
Name: aws.String(regexPatternSetName),
Id: aws.String(regexPatternSetId),
Scope: aws.String(scope),
}); err != nil {
// error
return fmt.Errorf("Get Regex Pattern Set Failed: %s", err.Error())
} else {
lockToken = getOutput.LockToken
var oldList []string
patternsList = getOutput.RegexPatternSet.RegularExpressionList
newAddedCount := 0
if len(patternsList) > 0 {
for _, v := range patternsList {
oldList = append(oldList, aws.StringValue(v.RegexString))
}
}
for _, v := range newRegexPatterns {
if !util.StringSliceContains(&oldList, v) {
patternsList = append(patternsList, &wafv2.Regex{
RegexString: aws.String(v),
})
oldList = append(oldList, v)
newAddedCount++
}
}
if newAddedCount == 0 {
return nil
}
// take the last 10
if len(patternsList) > 10 {
patternsList = patternsList[len(patternsList)-10:]
}
}
if _, err := w.waf2Obj.UpdateRegexPatternSet(&wafv2.UpdateRegexPatternSetInput{
Name: aws.String(regexPatternSetName),
Id: aws.String(regexPatternSetId),
Scope: aws.String(scope),
RegularExpressionList: patternsList,
LockToken: lockToken,
}); err != nil {
// error encountered
return fmt.Errorf("Update Regex Patterns Set Failed: %s", err.Error())
} else {
// update completed
return nil
}
}