-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtrailpolicy.go
More file actions
103 lines (76 loc) · 2.07 KB
/
trailpolicy.go
File metadata and controls
103 lines (76 loc) · 2.07 KB
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
// Package trailpolicy will derive an AWS IAM Policy Document from actions found within Cloudtrail logs.
package trailpolicy
import (
"encoding/json"
"fmt"
"sort"
"strings"
)
type cloudtrailLog struct {
Records []cloudtrailRecord
}
type cloudtrailRecord struct {
EventSource string
EventName string
}
type policyDocument struct {
Version string
Statement []policyStatement
}
type policyStatement struct {
Effect string
Action []string
Resource string
}
func parse(cloudtrailJSON []byte) (*[]cloudtrailRecord, error) {
trail := cloudtrailLog{}
if err := json.Unmarshal(cloudtrailJSON, &trail); err != nil {
return nil, err
}
return &trail.Records, nil
}
func deriveAction(record cloudtrailRecord) string {
service := strings.Split(record.EventSource, ".")[0]
return service + ":" + record.EventName
}
func createPolicy(r *[]cloudtrailRecord) (*policyDocument, error) {
actions := make(map[string]struct{})
for _, record := range *r {
action := deriveAction(record)
actions[action] = struct{}{}
}
keys := make([]string, len(actions))
i := 0
for k := range actions {
keys[i] = k
i++
}
sort.Strings(keys)
document := policyDocument{
Version: "2012-10-17",
Statement: []policyStatement{{Effect: "Allow", Resource: "*", Action: keys}}}
return &document, nil
}
func createPolicyJSON(document *policyDocument) (*[]byte, error) {
result, err := json.MarshalIndent(*document, "", " ")
if err != nil {
return nil, err
}
return &result, nil
}
// Convert takes a JSON based Cloudtrail log and returns a JSON based IAM Policy Document
func Convert(cloudtrailJSON []byte) (string, error) {
cloudtrailRecords, err := parse(cloudtrailJSON)
if err != nil {
return "", fmt.Errorf("error parsing Cloudtrail log: %s", err.Error())
}
policy, err := createPolicy(cloudtrailRecords)
if err != nil {
return "", fmt.Errorf("error creating Policy Document: %s", err.Error())
}
jsonPolicy, err := createPolicyJSON(policy)
if err != nil {
return "", fmt.Errorf("error encoding Policy Document: %s", err.Error())
}
return string(*jsonPolicy), nil
}