-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdata_source.go
More file actions
336 lines (310 loc) · 10.4 KB
/
Copy pathdata_source.go
File metadata and controls
336 lines (310 loc) · 10.4 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
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
/*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License.
*
* This product includes software developed at Datadog (https://www.datadoghq.com) Copyright 2024 Datadog, Inc.
*/
package terraform
import (
"bytes"
"context"
"encoding/json"
"path/filepath"
"github.com/DataDog/datadog-iac-scanner/pkg/builder/engine"
"github.com/DataDog/datadog-iac-scanner/pkg/logger"
"github.com/DataDog/datadog-iac-scanner/pkg/parser/terraform/converter"
"github.com/DataDog/datadog-iac-scanner/pkg/parser/terraform/functions"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hcldec"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/gocty"
ctyjson "github.com/zclconf/go-cty/cty/json"
)
type dataSourcePolicyCondition struct {
Test string `json:"test,omitempty"`
Variable string `json:"variable,omitempty"`
Values []string `json:"values,omitempty"`
}
type dataSourcePolicyPrincipal struct {
Type string `json:"type,omitempty"`
Identifiers []string `json:"identifiers,omitempty"`
}
type dataSourcePolicyStatement struct {
Actions []string `json:"actions"`
Condition dataSourcePolicyCondition `json:"condition"`
Effect string `json:"effect"`
NotActions []string `json:"not_actions"`
NotPrincipals dataSourcePolicyPrincipal `json:"not_principals"`
NotResources []string `json:"not_resources"`
Principals dataSourcePolicyPrincipal `json:"principals"`
Resources []string `json:"resources"`
Sid string `json:"sid"`
}
type dataSourcePolicy struct {
ID string `json:"id"`
Statement []dataSourcePolicyStatement `json:"statement"`
Version string `json:"version"`
}
type dataSource struct {
Value dataSourcePolicy `json:"value"`
}
type convertedPolicyCondition map[string]map[string][]string
type convertedPolicyPrincipal map[string][]string
type convertedPolicyStatement struct {
Actions []string `json:"Actions,omitempty"`
Condition convertedPolicyCondition `json:"Condition,omitempty"`
Effect string `json:"Effect,omitempty"`
NotActions []string `json:"Not_actions,omitempty"`
NotPrincipals convertedPolicyPrincipal `json:"Not_principals,omitempty"`
NotResources []string `json:"Not_resources,omitempty"`
Principals convertedPolicyPrincipal `json:"Principals,omitempty"`
Resources []string `json:"Resources,omitempty"`
Sid string `json:"Sid,omitempty"`
}
type convertedPolicy struct {
ID string `json:"Id,omitempty"`
Statement []convertedPolicyStatement `json:"Statement,omitempty"`
Version string `json:"Version,omitempty"`
}
func getDataSourcePolicy(ctx context.Context, currentPath string, inputVariables converter.VariableMap) converter.VariableMap {
contextLogger := logger.FromContext(ctx)
tfFiles, err := filepath.Glob(filepath.Join(currentPath, "*.tf"))
if err != nil {
contextLogger.Error().Msg("Error getting .tf files to parse data source")
return inputVariables
}
if len(tfFiles) == 0 {
return inputVariables
}
jsonMap := make(map[string]map[string]string)
for _, tfFile := range tfFiles {
parsedFile, parseErr := parseFile(tfFile, true)
if parseErr != nil {
contextLogger.Debug().Msgf("Error trying to parse file %s for data source.", tfFile)
continue
}
body, ok := parsedFile.Body.(*hclsyntax.Body)
if !ok {
continue
}
for _, block := range body.Blocks {
if block.Type == "data" && block.Labels[0] == "aws_iam_policy_document" && len(block.Labels) > 1 {
policyJSON := parseDataSourceBody(ctx, block.Body, inputVariables)
jsonMap[block.Labels[1]] = map[string]string{
"json": policyJSON,
}
}
}
}
policyResource := map[string]map[string]map[string]string{
"aws_iam_policy_document": jsonMap,
}
data, err := gocty.ToCtyValue(policyResource, cty.Map(cty.Map(cty.Map(cty.String))))
if err != nil {
contextLogger.Error().Msgf("Error trying to convert policy to cty value: %s", err)
return inputVariables
}
inputVariables["data"] = data
return inputVariables
}
func decodeDataSourcePolicy(ctx context.Context, value cty.Value) dataSourcePolicy {
contextLogger := logger.FromContext(ctx)
jsonified, err := ctyjson.Marshal(cty.UnknownAsNull(value), cty.DynamicPseudoType)
if err != nil {
contextLogger.Warn().Msgf("Error trying to decode data source block: %s", err)
return dataSourcePolicy{}
}
var data dataSource
err = json.Unmarshal(jsonified, &data)
if err != nil {
contextLogger.Error().Msgf("Error trying to encode data source json: %s", err)
return dataSourcePolicy{}
}
return data.Value
}
func getPrincipalSpec() *hcldec.ObjectSpec {
return &hcldec.ObjectSpec{
"type": &hcldec.AttrSpec{
Name: "type",
Type: cty.String,
Required: false,
},
"identifiers": &hcldec.AttrSpec{
Name: "identifiers",
Type: cty.List(cty.String),
Required: false,
},
}
}
func getConditionalSpec() *hcldec.ObjectSpec {
return &hcldec.ObjectSpec{
"test": &hcldec.AttrSpec{
Name: "test",
Type: cty.String,
Required: false,
},
"variable": &hcldec.AttrSpec{
Name: "variable",
Type: cty.String,
Required: false,
},
"values": &hcldec.AttrSpec{
Name: "values",
Type: cty.List(cty.String),
Required: false,
},
}
}
func getStatementSpec() *hcldec.BlockListSpec {
return &hcldec.BlockListSpec{
TypeName: "statement",
Nested: &hcldec.ObjectSpec{
"sid": &hcldec.AttrSpec{
Name: "sid",
Type: cty.String,
Required: false,
},
"effect": &hcldec.AttrSpec{
Name: "effect",
Type: cty.String,
Required: false,
},
"actions": &hcldec.AttrSpec{
Name: "actions",
Type: cty.List(cty.String),
Required: false,
},
"not_actions": &hcldec.AttrSpec{
Name: "not_actions",
Type: cty.List(cty.String),
Required: false,
},
"resources": &hcldec.AttrSpec{
Name: "resources",
Type: cty.List(cty.String),
Required: false,
},
"not_resources": &hcldec.AttrSpec{
Name: "not_resources",
Type: cty.List(cty.String),
Required: false,
},
"principals": &hcldec.BlockSpec{
TypeName: "principals",
Nested: getPrincipalSpec(),
},
"not_principals": &hcldec.BlockSpec{
TypeName: "not_principals",
Nested: getPrincipalSpec(),
},
"condition": &hcldec.BlockSpec{
TypeName: "condition",
Nested: getConditionalSpec(),
},
},
}
}
func parseDataSourceBody(ctx context.Context, body *hclsyntax.Body, inputVariables converter.VariableMap) string {
contextLogger := logger.FromContext(ctx)
dataSourceSpec := &hcldec.ObjectSpec{
"id": &hcldec.AttrSpec{
Name: "id",
Type: cty.String,
Required: false,
},
"version": &hcldec.AttrSpec{
Name: "version",
Type: cty.String,
Required: false,
},
"statement": getStatementSpec(),
}
resolveDataResources(ctx, body)
target, decodeErrs := hcldec.Decode(body, dataSourceSpec, &hcl.EvalContext{
Variables: inputVariables,
Functions: functions.TerraformFuncs,
})
// check decode errors
for _, decErr := range decodeErrs {
if decErr.Summary != "Unknown variable" {
contextLogger.Debug().Msgf("Error trying to eval data source block: %s", decErr.Summary)
return ""
}
contextLogger.Debug().Msg("Dismissed Error when decoding policy: Found unknown variable")
}
dataSourceJSON := decodeDataSourcePolicy(ctx, target)
convertedDataSource := convertedPolicy{
ID: dataSourceJSON.ID,
Version: dataSourceJSON.Version,
}
statements := make([]convertedPolicyStatement, len(dataSourceJSON.Statement))
for idx := range dataSourceJSON.Statement {
var convertedCondition convertedPolicyCondition
if dataSourceJSON.Statement[idx].Condition.Variable != "" {
convertedCondition = convertedPolicyCondition{
dataSourceJSON.Statement[idx].Condition.Test: map[string][]string{
dataSourceJSON.Statement[idx].Condition.Variable: dataSourceJSON.Statement[idx].Condition.Values,
},
}
}
var convertedPrincipal convertedPolicyPrincipal
if dataSourceJSON.Statement[idx].Principals.Type != "" {
convertedPrincipal = convertedPolicyPrincipal{
dataSourceJSON.Statement[idx].Principals.Type: dataSourceJSON.Statement[idx].Principals.Identifiers,
}
}
var convertedNotPrincipal convertedPolicyPrincipal
if dataSourceJSON.Statement[idx].NotPrincipals.Type != "" {
convertedNotPrincipal = convertedPolicyPrincipal{
dataSourceJSON.Statement[idx].NotPrincipals.Type: dataSourceJSON.Statement[idx].NotPrincipals.Identifiers,
}
}
convertedStatement := convertedPolicyStatement{
Actions: dataSourceJSON.Statement[idx].Actions,
Effect: dataSourceJSON.Statement[idx].Effect,
NotActions: dataSourceJSON.Statement[idx].NotActions,
NotResources: dataSourceJSON.Statement[idx].NotResources,
Resources: dataSourceJSON.Statement[idx].Resources,
Sid: dataSourceJSON.Statement[idx].Sid,
Condition: convertedCondition,
NotPrincipals: convertedNotPrincipal,
Principals: convertedPrincipal,
}
statements[idx] = convertedStatement
}
convertedDataSource.Statement = statements
buffer := &bytes.Buffer{}
encoder := json.NewEncoder(buffer)
encoder.SetEscapeHTML(false)
err := encoder.Encode(convertedDataSource)
if err != nil {
contextLogger.Error().Msgf("Error trying to encoding data source json: %s", err)
return ""
}
return buffer.String()
}
// resolveDataResources resolves the data resources expressions into LiteralValueExpr
func resolveDataResources(ctx context.Context, body *hclsyntax.Body) {
for _, block := range body.Blocks {
if resources, ok := block.Body.Attributes["resources"]; ok &&
block.Type == "statement" {
resolveTuple(ctx, resources.Expr)
}
}
}
func resolveTuple(ctx context.Context, expr hclsyntax.Expression) {
contextLogger := logger.FromContext(ctx)
e := engine.Engine{}
if v, ok := expr.(*hclsyntax.TupleConsExpr); ok {
for i, ex := range v.Exprs {
striExpr, err := e.ExpToString(ctx, ex)
if err != nil {
contextLogger.Error().Msgf("Error trying to ExpToString: %s", err)
}
v.Exprs[i] = &hclsyntax.LiteralValueExpr{
Val: cty.StringVal(striExpr),
SrcRange: v.Exprs[i].Range(),
}
}
}
}