-
Notifications
You must be signed in to change notification settings - Fork 6
/
aws_policy_equivalence.go
473 lines (397 loc) · 12.4 KB
/
aws_policy_equivalence.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
// Package awspolicy contains functions to compare structural equivalence
// of AWS IAM policies.
package awspolicy
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
import (
"encoding/json"
"errors"
"fmt"
"reflect"
"regexp"
"strings"
"github.com/mitchellh/mapstructure"
)
// PoliciesAreEquivalent tests for the structural equivalence of two
// AWS policies. It does not read into the semantics, other than treating
// single element string arrays as equivalent to a string without an
// array, as the AWS endpoints do.
//
// It will, however, detect reordering and ignore whitespace.
//
// Returns true if the policies are structurally equivalent, false
// otherwise. If either of the input strings are not valid JSON,
// false is returned along with an error.
func PoliciesAreEquivalent(policy1, policy2 string) (bool, error) {
policy1intermediate := &intermediateAwsPolicyDocument{}
if err := json.Unmarshal([]byte(policy1), policy1intermediate); err != nil {
return false, fmt.Errorf("Error unmarshaling policy: %s", err)
}
policy2intermediate := &intermediateAwsPolicyDocument{}
if err := json.Unmarshal([]byte(policy2), policy2intermediate); err != nil {
return false, fmt.Errorf("Error unmarshaling policy: %s", err)
}
policy1Doc, err := policy1intermediate.document()
if err != nil {
return false, fmt.Errorf("Error parsing policy: %s", err)
}
policy2Doc, err := policy2intermediate.document()
if err != nil {
return false, fmt.Errorf("Error parsing policy: %s", err)
}
return policy1Doc.equals(policy2Doc), nil
}
type intermediateAwsPolicyDocument struct {
Version string `json:",omitempty"`
Id string `json:",omitempty"`
Statements interface{} `json:"Statement"`
}
func (intermediate *intermediateAwsPolicyDocument) document() (*awsPolicyDocument, error) {
var statements []*awsPolicyStatement
switch s := intermediate.Statements.(type) {
case []interface{}:
if err := mapstructure.Decode(s, &statements); err != nil {
return nil, fmt.Errorf("Error parsing statement: %s", err)
}
case map[string]interface{}:
var singleStatement *awsPolicyStatement
if err := mapstructure.Decode(s, &singleStatement); err != nil {
return nil, fmt.Errorf("Error parsing statement: %s", err)
}
statements = append(statements, singleStatement)
default:
return nil, errors.New("Unknown error parsing statement")
}
document := &awsPolicyDocument{
Version: intermediate.Version,
Id: intermediate.Id,
Statements: statements,
}
return document, nil
}
type awsPolicyDocument struct {
Version string
Id string
Statements []*awsPolicyStatement
}
func (doc *awsPolicyDocument) equals(other *awsPolicyDocument) bool {
// Check the basic fields of the document
if doc.Version != other.Version {
return false
}
if doc.Id != other.Id {
return false
}
// If we have different number of statements we are very unlikely
// to have them be equivalent.
if len(doc.Statements) != len(other.Statements) {
return false
}
// If we have the same number of statements in the policy, does
// each statement in the intermediate have a corresponding statement in
// other which is equal? If no, policies are not equal, if yes,
// then they may be.
for _, ours := range doc.Statements {
found := false
for _, theirs := range other.Statements {
if ours.equals(theirs) {
found = true
}
}
if !found {
return false
}
}
// Now we need to repeat this process the other way around to
// ensure we don't have any matching errors.
for _, theirs := range other.Statements {
found := false
for _, ours := range doc.Statements {
if theirs.equals(ours) {
found = true
}
}
if !found {
return false
}
}
return true
}
type awsPolicyStatement struct {
Sid string `json:",omitempty" mapstructure:"Sid"`
Effect string `json:",omitempty" mapstructure:"Effect"`
Actions interface{} `json:"Action,omitempty" mapstructure:"Action"`
NotActions interface{} `json:"NotAction,omitempty" mapstructure:"NotAction"`
Resources interface{} `json:"Resource,omitempty" mapstructure:"Resource"`
NotResources interface{} `json:"NotResource,omitempty" mapstructure:"NotResource"`
Principals interface{} `json:"Principal,omitempty" mapstructure:"Principal"`
NotPrincipals interface{} `json:"NotPrincipal,omitempty" mapstructure:"NotPrincipal"`
Conditions map[string]map[string]interface{} `json:"Condition,omitempty" mapstructure:"Condition"`
}
func (statement *awsPolicyStatement) equals(other *awsPolicyStatement) bool {
if statement.Sid != other.Sid {
return false
}
if strings.ToLower(statement.Effect) != strings.ToLower(other.Effect) {
return false
}
ourActions := newAWSStringSet(statement.Actions)
theirActions := newAWSStringSet(other.Actions)
if !ourActions.equals(theirActions) {
return false
}
ourNotActions := newAWSStringSet(statement.NotActions)
theirNotActions := newAWSStringSet(other.NotActions)
if !ourNotActions.equals(theirNotActions) {
return false
}
ourResources := newAWSStringSet(statement.Resources)
theirResources := newAWSStringSet(other.Resources)
if !ourResources.equals(theirResources) {
return false
}
ourNotResources := newAWSStringSet(statement.NotResources)
theirNotResources := newAWSStringSet(other.NotResources)
if !ourNotResources.equals(theirNotResources) {
return false
}
ourConditionsBlock := awsConditionsBlock(statement.Conditions)
theirConditionsBlock := awsConditionsBlock(other.Conditions)
if !ourConditionsBlock.Equals(theirConditionsBlock) {
return false
}
if statement.Principals != nil || other.Principals != nil {
stringPrincipalsEqual := stringPrincipalsEqual(statement.Principals, other.Principals)
mapPrincipalsEqual := mapPrincipalsEqual(statement.Principals, other.Principals)
if !(stringPrincipalsEqual || mapPrincipalsEqual) {
return false
}
}
if statement.NotPrincipals != nil || other.NotPrincipals != nil {
stringNotPrincipalsEqual := stringPrincipalsEqual(statement.NotPrincipals, other.NotPrincipals)
mapNotPrincipalsEqual := mapPrincipalsEqual(statement.NotPrincipals, other.NotPrincipals)
if !(stringNotPrincipalsEqual || mapNotPrincipalsEqual) {
return false
}
}
return true
}
func mapPrincipalsEqual(ours, theirs interface{}) bool {
ourPrincipalMap, oursOk := ours.(map[string]interface{})
theirPrincipalMap, theirsOk := theirs.(map[string]interface{})
oursNormalized := make(map[string]awsPrincipalStringSet)
if oursOk {
for key, val := range ourPrincipalMap {
var tmp = newAWSPrincipalStringSet(val)
if len(tmp) > 0 {
oursNormalized[key] = tmp
}
}
}
theirsNormalized := make(map[string]awsPrincipalStringSet)
if theirsOk {
for key, val := range theirPrincipalMap {
var tmp = newAWSPrincipalStringSet(val)
if len(tmp) > 0 {
theirsNormalized[key] = newAWSPrincipalStringSet(val)
}
}
}
for key, ours := range oursNormalized {
theirs, ok := theirsNormalized[key]
if !ok {
return false
}
if !ours.equals(theirs) {
return false
}
}
for key, theirs := range theirsNormalized {
ours, ok := oursNormalized[key]
if !ok {
return false
}
if !theirs.equals(ours) {
return false
}
}
return true
}
func stringPrincipalsEqual(ours, theirs interface{}) bool {
ourPrincipal, oursIsString := ours.(string)
theirPrincipal, theirsIsString := theirs.(string)
if !(oursIsString && theirsIsString) {
return false
}
if ourPrincipal == theirPrincipal {
return true
}
// Handle AWS converting account ID principal to root IAM user ARN
// ACCOUNTID == arn:PARTITION:iam::ACCOUNTID:root
awsAccountIDRegex := regexp.MustCompile(`^[0-9]{12}$`)
if awsAccountIDRegex.MatchString(ourPrincipal) {
if theirArn, err := parseAwsArnString(theirPrincipal); err == nil {
if theirArn.service == "iam" && theirArn.resource == "root" && theirArn.account == ourPrincipal {
return true
}
}
}
if awsAccountIDRegex.MatchString(theirPrincipal) {
if ourArn, err := parseAwsArnString(ourPrincipal); err == nil {
if ourArn.service == "iam" && ourArn.resource == "root" && ourArn.account == theirPrincipal {
return true
}
}
}
return false
}
type awsConditionsBlock map[string]map[string]interface{}
func (conditions awsConditionsBlock) Equals(other awsConditionsBlock) bool {
if conditions == nil && other != nil || other == nil && conditions != nil {
return false
}
if len(conditions) != len(other) {
return false
}
oursNormalized := make(map[string]map[string]awsStringSet)
for key, condition := range conditions {
normalizedCondition := make(map[string]awsStringSet)
for innerKey, val := range condition {
normalizedCondition[innerKey] = newAWSStringSet(val)
}
oursNormalized[key] = normalizedCondition
}
theirsNormalized := make(map[string]map[string]awsStringSet)
for key, condition := range other {
normalizedCondition := make(map[string]awsStringSet)
for innerKey, val := range condition {
normalizedCondition[innerKey] = newAWSStringSet(val)
}
theirsNormalized[key] = normalizedCondition
}
for key, ours := range oursNormalized {
theirs, ok := theirsNormalized[key]
if !ok {
return false
}
for innerKey, oursInner := range ours {
theirsInner, ok := theirs[innerKey]
if !ok {
return false
}
if !oursInner.equals(theirsInner) {
return false
}
}
}
for key, theirs := range theirsNormalized {
ours, ok := oursNormalized[key]
if !ok {
return false
}
for innerKey, theirsInner := range theirs {
oursInner, ok := ours[innerKey]
if !ok {
return false
}
if !theirsInner.equals(oursInner) {
return false
}
}
}
return true
}
type awsStringSet []string
type awsPrincipalStringSet awsStringSet
// newAWSStringSet constructs an awsStringSet from an interface{} - which
// may be nil, a single string, or []interface{} (each of which is a string).
// This corresponds with how structures come off the JSON unmarshaler
// without any custom encoding rules.
func newAWSStringSet(members interface{}) awsStringSet {
if members == nil {
return awsStringSet{}
}
if single, ok := members.(string); ok {
return awsStringSet{single}
}
if multiple, ok := members.([]interface{}); ok {
if len(multiple) == 0 {
return awsStringSet{}
}
actions := make([]string, len(multiple))
for i, action := range multiple {
if _, ok := action.(string); !ok {
return nil
}
actions[i] = action.(string)
}
return awsStringSet(actions)
}
return nil
}
func newAWSPrincipalStringSet(members interface{}) awsPrincipalStringSet {
return awsPrincipalStringSet(newAWSStringSet(members))
}
func (actions awsStringSet) equals(other awsStringSet) bool {
if actions == nil || other == nil {
return false
}
if len(actions) != len(other) {
return false
}
ourMap := map[string]struct{}{}
theirMap := map[string]struct{}{}
for _, action := range actions {
ourMap[action] = struct{}{}
}
for _, action := range other {
theirMap[action] = struct{}{}
}
return reflect.DeepEqual(ourMap, theirMap)
}
func (ours awsPrincipalStringSet) equals(theirs awsPrincipalStringSet) bool {
if len(ours) != len(theirs) {
return false
}
for _, ourPrincipal := range ours {
matches := false
for _, theirPrincipal := range theirs {
if stringPrincipalsEqual(ourPrincipal, theirPrincipal) {
matches = true
break
}
}
if !matches {
return false
}
}
return true
}
// awsArn describes an Amazon Resource Name
// More information: http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html
type awsArn struct {
account string
partition string
region string
resource string
service string
}
// parseAwsArnString converts a string into an awsArn
// Expects string in form of: arn:PARTITION:SERVICE:REGION:ACCOUNT:RESOURCE
func parseAwsArnString(arn string) (awsArn, error) {
if !strings.HasPrefix(arn, "arn:") {
return awsArn{}, fmt.Errorf("expected arn: prefix, received: %s", arn)
}
arnParts := strings.SplitN(arn, ":", 6)
if len(arnParts) != 6 {
return awsArn{}, fmt.Errorf("expected 6 colon delimited sections, received: %s", arn)
}
return awsArn{
account: arnParts[4],
partition: arnParts[1],
region: arnParts[3],
resource: arnParts[5],
service: arnParts[2],
}, nil
}