forked from GoogleCloudPlatform/professional-services
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmain.go
395 lines (360 loc) · 12.1 KB
/
main.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
// Copyright 2021 Google LLC
//
// 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 main
import (
"flag"
"fmt"
"log"
"net/url"
"regexp"
"sort"
"strings"
"github.com/getkin/kin-openapi/openapi3"
"gopkg.in/yaml.v2"
)
var input = flag.String("input", "", "Input file OpenAPI3 spec, can either be a local path or a http or https URL (required)")
var enableLayer7DdosDefenseConfig = flag.Bool("enableLayer7DdosDefenseConfig", false, "Should the Layer 7 DDOS Defense be enabled https://cloud.google.com/armor/docs/adaptive-protection-overview (optional; default false)")
var compressedFormat = flag.Bool("compressed", false, "Should you run into rule quotas you can try the compressed format,\n which tries to compact the API specification into a single rule. This has a risk of allowing unspecified methods on some paths. (optional; default false)")
var methodwise = flag.Bool("methodwise", true, "The methodwise format creates a rule per HTTP Method, the path expression is compressed to decrease size by ommitting paths that are covered by a regulare expression (optional; default true)")
var pathwise = flag.Bool("pathwise", false, "The pathwise format, creates a single rule per path (paths that are included in other path expressions are ommited), it provides human readable rules (optional; default false)")
var startPriority = flag.Int("priority", 1000, "Start priority for the rules (optional; default 1000)")
var generateDefaultDenyRule = flag.Bool("defaultRule", true, "Should a default deny rule be generated (optional; default true)")
var denyRuleResponseCode = flag.Int("defaultDenyResponseCode", 404, "HTTP Status Code for the default deny rule (optional; default 404)")
func main() {
flag.Parse()
CheckPreconditions()
var err error
doc, err := ReadOpenApiSpec(strings.TrimSpace(*input))
if err != nil {
log.Fatalf("Failed loading OpenAPI spec: %v", err)
return
}
rules := []Rule{}
if *compressedFormat {
rules, err = GeneratedCompressedRules(rules, doc)
if err != nil {
log.Fatalf("Failed creating compressedrules: %v", err)
return
}
} else {
if *methodwise {
rules, err = GenerateMethodwiseRules(rules, doc)
if err != nil {
log.Fatalf("Failed creating methodwise rules: %v", err)
return
}
} else if *pathwise {
rules, err = GeneratePathwiseRules(rules, doc)
if err != nil {
log.Fatalf("Failed creating rules: %v", err)
return
}
}
}
if *generateDefaultDenyRule {
rules = append(rules, *DefaultRule())
}
policy := NewPolicy(fmt.Sprintf("Policy for %s", doc.Info.Title), "Generated policy based on OpenAPI definition", *enableLayer7DdosDefenseConfig, rules)
output, err := yaml.Marshal(&policy)
if err != nil {
log.Fatalf("Couldn't marshal output: %v", err)
return
}
fmt.Print(string(output))
}
func GeneratePathwiseRules(rules []Rule, doc *openapi3.T) ([]Rule, error) {
priority := *startPriority
var paths = []string{}
for path, _ := range doc.Paths {
pathRegEx := ToRegEx(path)
paths = append(paths, pathRegEx)
}
paths = FilterPaths(paths)
for path, v := range doc.Paths {
if Contains(paths, ToRegEx(path)) {
methodPart := ""
for method, _ := range v.Operations() {
if methodPart == "" {
methodPart = fmt.Sprintf("request.method=='%s'", method)
} else {
methodPart = fmt.Sprintf("%s || request.method=='%s'", methodPart, method)
}
}
expression := fmt.Sprintf("(%s) && request.path.matches('%s')", methodPart, ToRegEx(path))
if len(expression) > 2048 {
log.Println("[WARN] The security policy contains more than 2048 characters, you might run into the limit for expression length.")
} else if len(expression) > 1024 {
log.Println("[WARN] The security policy contains more than 1024 characters, you might run into the limit for subexpression length.")
}
rule, err := NewRule(fmt.Sprintf("Rule for %s", path), "allow", priority, false, expression)
if err != nil {
return nil, err
}
if priority == 120 {
log.Println("[WARN] The security policy contains more than 20 rules, you might run into Quota issues.")
}
rules = append(rules, *rule)
priority++
}
}
return rules, nil
}
func GenerateMethodwiseRules(rules []Rule, doc *openapi3.T) ([]Rule, error) {
methodToPaths := make(map[string][]string)
for path, v := range doc.Paths {
for method, _ := range v.Operations() {
methodToPaths[method] = append(methodToPaths[method], ToRegEx(path))
}
}
priority := *startPriority
for method, paths := range methodToPaths {
paths = FilterPaths(paths)
sort.Strings(paths)
var pathPart string = ""
for _, path := range paths {
if pathPart == "" {
pathPart = path
} else {
pathPart = fmt.Sprintf("%s|%s", pathPart, path)
}
}
expression := fmt.Sprintf("request.method=='%s' && request.path.matches('%s')", method, pathPart)
if len(expression) > 2048 {
log.Println("[WARN] The security policy contains more than 2048 characters, you might run into the limit for expression length.")
} else if len(expression) > 1024 {
log.Println("[WARN] The security policy contains more than 1024 characters, you might run into the limit for subexpression length.")
}
var rule *Rule
rule, err := NewRule(fmt.Sprintf("Generated rules for method %s", method), "allow", priority, false, expression)
if err != nil {
return nil, err
}
if priority == 120 {
log.Println("[WARN] The security policy contains more than 20 rules, you might run into Quota issues.")
}
rules = append(rules, *rule)
priority++
}
return rules, nil
}
func GeneratedCompressedRules(rules []Rule, doc *openapi3.T) ([]Rule, error) {
var methodPart string = ""
var paths = []string{}
for path, v := range doc.Paths {
pathRegEx := ToRegEx(path)
if !Contains(paths, pathRegEx) {
paths = append(paths, pathRegEx)
}
for method, _ := range v.Operations() {
if !strings.Contains(methodPart, method) {
if methodPart == "" {
methodPart = fmt.Sprintf("request.method=='%s'", method)
} else {
methodPart = fmt.Sprintf("%s || request.method=='%s'", methodPart, method)
}
}
}
}
paths = FilterPaths(paths)
sort.Strings(paths)
var pathPart string = ""
for _, path := range paths {
if pathPart == "" {
pathPart = path
} else {
pathPart = fmt.Sprintf("%s|%s", pathPart, path)
}
}
expression := fmt.Sprintf("(%s) && request.path.matches('%s')", methodPart, pathPart)
if len(expression) > 2048 {
log.Println("[WARN] The security policy contains more than 2048 characters, you might run into the limit for expression length.")
} else if len(expression) > 1024 {
log.Println("[WARN] The security policy contains more than 1024 characters, you might run into the limit for subexpression length.")
}
rule, err := NewRule("Generated path and method rules", "allow", *startPriority, false, expression)
if err != nil {
return nil, err
}
rules = append(rules, *rule)
return rules, nil
}
func DefaultRule() *Rule {
rule, err := NewRuleWithIpRanges("Default Rule", fmt.Sprintf("deny(%d)", *denyRuleResponseCode), 2147483647, false,
[]string{"*"},
)
if err != nil {
log.Fatalf("Failed creating rule: %v", err)
return nil
}
return rule
}
func ToRegEx(input string) string {
regex, err := regexp.Compile(`{[-a-zA-Z0-9@:%._\+~#=]*}`)
if err != nil {
log.Fatalf("Failed parsing input file: %v", err)
return ""
}
return fmt.Sprintf("%s$", regex.ReplaceAllString(strings.TrimSpace(input), "[^/]*"))
}
func Contains(array []string, value string) bool {
for i := 0; i < len(array); i++ {
if array[i] == value {
return true
}
}
return false
}
func ContainsWithRegex(array []string, regex string) bool {
compileRegEx, err := regexp.Compile(regex)
if err != nil {
log.Panic(err)
return false
}
for i := 0; i < len(array); i++ {
if array[i] == regex {
return true
} else if compileRegEx.MatchString(array[i]) {
return true
}
}
return false
}
func FilterPaths(paths []string) []string {
for i := 0; i < len(paths); i++ {
path1 := paths[i]
for _, path2 := range paths {
compileRegEx, err := regexp.Compile(path2)
if err != nil {
log.Panic(err)
}
if compileRegEx.MatchString(path1) {
index := IndexOf(paths, path1)
if index != -1 {
paths = append(paths[:index], paths[index+1:]...)
i = 0
}
}
}
}
return paths
}
func IndexOf(array []string, element string) int {
for index, ele := range array {
if ele == element {
return index
}
}
return -1
}
func CheckPreconditions() {
if strings.TrimSpace(*input) == "" {
fmt.Println("Please provide the required parameters")
flag.PrintDefaults()
return
}
if *compressedFormat && *pathwise || *pathwise && *methodwise || *compressedFormat && *methodwise {
fmt.Println("Please select either compressed, methodwise or pathwise")
flag.PrintDefaults()
return
}
if !(*compressedFormat || *pathwise || *methodwise) {
fmt.Println("Please select either compressed, methodwise or pathwise")
flag.PrintDefaults()
return
}
}
func ReadOpenApiSpec(filePath string) (*openapi3.T, error) {
if strings.Index(filePath, "https://") == 0 || strings.Index(filePath, "http://") == 0 {
url, err := url.Parse(filePath)
if err != nil {
log.Fatalf("Couldn't parse input url: %v", err)
return nil, err
}
doc, err := openapi3.NewLoader().LoadFromURI(url)
if err != nil {
log.Fatalf("Failed reading and parsing input file: %v", err)
return nil, err
}
return doc, nil
} else {
doc, err := openapi3.NewLoader().LoadFromFile(filePath)
if err != nil {
log.Fatalf("Failed parsing input file: %v", err)
return nil, err
}
return doc, nil
}
}
type Rule struct {
Action string `yaml:"action,omitempty"`
Description string `yaml:"description,omitempty"`
Kind string `yaml:"kind,omitempty"`
Preview bool `yaml:"preview,omitempty"`
Priority int `yaml:"priority,omitempty"`
Match struct {
Expr struct {
Expression string `yaml:"expression,omitempty"`
} `yaml:"expr,omitempty"`
Config struct {
SrcIpRanges []string `yaml:"srcIpRanges,omitempty"`
} `yaml:"config,omitempty"`
VersionedExpr string `yaml:"versionedExpr,omitempty"`
} `yaml:"match,omitempty"`
}
func NewRule(description string, action string, priority int, preview bool, expression string) (*Rule, error) {
rule := Rule{
Action: action,
Description: description,
Kind: "compute#securityPolicyRule",
Priority: priority,
Preview: preview,
}
rule.Match.Expr.Expression = expression
return &rule, nil
}
func NewRuleWithIpRanges(description string, action string, priority int, preview bool, ipRanges []string) (*Rule, error) {
rule := Rule{
Action: action,
Description: description,
Kind: "compute#securityPolicyRule",
Priority: priority,
Preview: preview,
}
rule.Match.Config.SrcIpRanges = ipRanges
rule.Match.VersionedExpr = "SRC_IPS_V1"
return &rule, nil
}
type Policy struct {
Name string `yaml:"name,omitempty"`
Description string `yaml:"description,omitempty"`
Kind string `yaml:"kind,omitempty"`
Type string `yaml:"type,omitempty"`
AdaptiveProtectionConfig struct {
Layer7DdosDefenseConfig struct {
Enable bool `yaml:"enable,omitempty"`
} `yaml:"layer7DdosDefenseConfig,omitempty"`
} `yaml:"adaptiveProtectionConfig,omitempty"`
Rules []Rule `yaml:"rules,omitempty"`
}
func NewPolicy(name string, description string, ddosProtectionEnabled bool, rules []Rule) Policy {
policy := Policy{
Name: name,
Description: description,
Kind: "compute#securityPolicy",
Type: "CLOUD_ARMOR",
Rules: rules,
}
policy.AdaptiveProtectionConfig.Layer7DdosDefenseConfig.Enable = ddosProtectionEnabled
return policy
}