/
metadata.go
395 lines (344 loc) · 9.92 KB
/
metadata.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
package rego
import (
"context"
"fmt"
"strings"
"github.com/mitchellh/mapstructure"
"github.com/open-policy-agent/opa/ast"
"github.com/open-policy-agent/opa/rego"
"github.com/aquasecurity/trivy/pkg/iac/framework"
"github.com/aquasecurity/trivy/pkg/iac/providers"
"github.com/aquasecurity/trivy/pkg/iac/scan"
"github.com/aquasecurity/trivy/pkg/iac/severity"
iacTypes "github.com/aquasecurity/trivy/pkg/iac/types"
)
type StaticMetadata struct {
ID string
AVDID string
Title string
ShortCode string
Aliases []string
Description string
Severity string
RecommendedActions string
PrimaryURL string
References []string
InputOptions InputOptions
Package string
Frameworks map[framework.Framework][]string
Provider string
Service string
Library bool
CloudFormation *scan.EngineMetadata
Terraform *scan.EngineMetadata
}
func NewStaticMetadata(pkgPath string, inputOpt InputOptions) *StaticMetadata {
return &StaticMetadata{
ID: "N/A",
Title: "N/A",
Severity: "UNKNOWN",
Description: fmt.Sprintf("Rego module: %s", pkgPath),
Package: pkgPath,
InputOptions: inputOpt,
Frameworks: make(map[framework.Framework][]string),
}
}
func (sm *StaticMetadata) Update(meta map[string]any) error {
upd := func(field *string, key string) {
if raw, ok := meta[key]; ok {
*field = fmt.Sprintf("%s", raw)
}
}
upd(&sm.ID, "id")
upd(&sm.AVDID, "avd_id")
upd(&sm.Title, "title")
upd(&sm.ShortCode, "short_code")
upd(&sm.Description, "description")
upd(&sm.Service, "service")
upd(&sm.Provider, "provider")
upd(&sm.RecommendedActions, "recommended_actions")
upd(&sm.RecommendedActions, "recommended_action")
if raw, ok := meta["severity"]; ok {
sm.Severity = strings.ToUpper(fmt.Sprintf("%s", raw))
}
if raw, ok := meta["library"]; ok {
if lib, ok := raw.(bool); ok {
sm.Library = lib
}
}
if raw, ok := meta["url"]; ok {
sm.References = append(sm.References, fmt.Sprintf("%s", raw))
}
if raw, ok := meta["frameworks"]; ok {
frameworks, ok := raw.(map[string][]string)
if !ok {
return fmt.Errorf("failed to parse framework metadata: not an object")
}
for fw, sections := range frameworks {
sm.Frameworks[framework.Framework(fw)] = sections
}
}
if raw, ok := meta["related_resources"]; ok {
switch relatedResources := raw.(type) {
case []map[string]any:
for _, relatedResource := range relatedResources {
if raw, ok := relatedResource["ref"]; ok {
sm.References = append(sm.References, fmt.Sprintf("%s", raw))
}
}
case []string:
sm.References = append(sm.References, relatedResources...)
}
}
sm.updateAliases(meta)
var err error
if sm.CloudFormation, err = NewEngineMetadata("cloud_formation", meta); err != nil {
return err
}
if sm.Terraform, err = NewEngineMetadata("terraform", meta); err != nil {
return err
}
return nil
}
func (sm *StaticMetadata) updateAliases(meta map[string]any) {
if raw, ok := meta["aliases"]; ok {
if aliases, ok := raw.([]interface{}); ok {
for _, a := range aliases {
sm.Aliases = append(sm.Aliases, fmt.Sprintf("%s", a))
}
}
}
}
func (sm *StaticMetadata) FromAnnotations(annotations *ast.Annotations) error {
sm.Title = annotations.Title
sm.Description = annotations.Description
for _, resource := range annotations.RelatedResources {
if !resource.Ref.IsAbs() {
continue
}
sm.References = append(sm.References, resource.Ref.String())
}
if custom := annotations.Custom; custom != nil {
if err := sm.Update(custom); err != nil {
return err
}
}
if len(annotations.RelatedResources) > 0 {
sm.PrimaryURL = annotations.RelatedResources[0].Ref.String()
}
return nil
}
func NewEngineMetadata(schema string, meta map[string]interface{}) (*scan.EngineMetadata, error) {
var sMap map[string]interface{}
if raw, ok := meta[schema]; ok {
sMap, ok = raw.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("failed to parse %s metadata: not an object", schema)
}
}
var em scan.EngineMetadata
if val, ok := sMap["good_examples"].(string); ok {
em.GoodExamples = []string{val}
}
if val, ok := sMap["bad_examples"].(string); ok {
em.BadExamples = []string{val}
}
if val, ok := sMap["links"].(string); ok {
em.Links = []string{val}
}
if val, ok := sMap["remediation_markdown"].(string); ok {
em.RemediationMarkdown = val
}
return &em, nil
}
type InputOptions struct {
Combined bool
Selectors []Selector
}
type Selector struct {
Type string
Subtypes []SubType
}
type SubType struct {
Group string
Version string
Kind string
Namespace string
Service string // only for cloud
Provider string // only for cloud
}
func (m StaticMetadata) ToRule() scan.Rule {
provider := "generic"
if m.Provider != "" {
provider = m.Provider
} else if len(m.InputOptions.Selectors) > 0 {
provider = m.InputOptions.Selectors[0].Type
}
service := "general"
if m.Service != "" {
service = m.Service
}
return scan.Rule{
AVDID: m.AVDID,
Aliases: append(m.Aliases, m.ID),
ShortCode: m.ShortCode,
Summary: m.Title,
Explanation: m.Description,
Impact: "",
Resolution: m.RecommendedActions,
Provider: providers.Provider(provider),
Service: service,
Links: m.References,
Severity: severity.Severity(m.Severity),
RegoPackage: m.Package,
Frameworks: m.Frameworks,
CloudFormation: m.CloudFormation,
Terraform: m.Terraform,
}
}
type MetadataRetriever struct {
compiler *ast.Compiler
}
func NewMetadataRetriever(compiler *ast.Compiler) *MetadataRetriever {
return &MetadataRetriever{
compiler: compiler,
}
}
func (m *MetadataRetriever) findPackageAnnotations(module *ast.Module) *ast.Annotations {
annotationSet := m.compiler.GetAnnotationSet()
if annotationSet == nil {
return nil
}
for _, annotation := range annotationSet.Flatten() {
if annotation.GetPackage().Path.String() != module.Package.Path.String() || annotation.Annotations.Scope != "package" {
continue
}
return annotation.Annotations
}
return nil
}
func (m *MetadataRetriever) RetrieveMetadata(ctx context.Context, module *ast.Module, contents ...any) (*StaticMetadata, error) {
metadata := NewStaticMetadata(
module.Package.Path.String(),
m.queryInputOptions(ctx, module),
)
// read metadata from official rego annotations if possible
if annotations := m.findPackageAnnotations(module); annotations != nil {
if err := metadata.FromAnnotations(annotations); err != nil {
return nil, err
}
return metadata, nil
}
// otherwise, try to read metadata from the rego module itself - we used to do this before annotations were a thing
namespace := getModuleNamespace(module)
metadataQuery := fmt.Sprintf("data.%s.__rego_metadata__", namespace)
options := []func(*rego.Rego){
rego.Query(metadataQuery),
rego.Compiler(m.compiler),
rego.Capabilities(nil),
}
// support dynamic metadata fields
for _, in := range contents {
options = append(options, rego.Input(in))
}
instance := rego.New(options...)
set, err := instance.Eval(ctx)
if err != nil {
return nil, err
}
// no metadata supplied
if set == nil {
return metadata, nil
}
if len(set) != 1 {
return nil, fmt.Errorf("failed to parse metadata: unexpected set length")
}
if len(set[0].Expressions) != 1 {
return nil, fmt.Errorf("failed to parse metadata: unexpected expression length")
}
expression := set[0].Expressions[0]
meta, ok := expression.Value.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("failed to parse metadata: not an object")
}
if err := metadata.Update(meta); err != nil {
return nil, err
}
return metadata, nil
}
// nolint: gocyclo
func (m *MetadataRetriever) queryInputOptions(ctx context.Context, module *ast.Module) InputOptions {
options := InputOptions{
Combined: false,
Selectors: nil,
}
var metadata map[string]interface{}
// read metadata from official rego annotations if possible
if annotation := m.findPackageAnnotations(module); annotation != nil && annotation.Custom != nil {
if input, ok := annotation.Custom["input"]; ok {
if mapped, ok := input.(map[string]interface{}); ok {
metadata = mapped
}
}
}
if metadata == nil {
namespace := getModuleNamespace(module)
inputOptionQuery := fmt.Sprintf("data.%s.__rego_input__", namespace)
instance := rego.New(
rego.Query(inputOptionQuery),
rego.Compiler(m.compiler),
rego.Capabilities(nil),
)
set, err := instance.Eval(ctx)
if err != nil {
return options
}
if len(set) != 1 {
return options
}
if len(set[0].Expressions) != 1 {
return options
}
expression := set[0].Expressions[0]
meta, ok := expression.Value.(map[string]interface{})
if !ok {
return options
}
metadata = meta
}
if raw, ok := metadata["combine"]; ok {
if combine, ok := raw.(bool); ok {
options.Combined = combine
}
}
if raw, ok := metadata["selector"]; ok {
if each, ok := raw.([]interface{}); ok {
for _, rawSelector := range each {
var selector Selector
if selectorMap, ok := rawSelector.(map[string]interface{}); ok {
if rawType, ok := selectorMap["type"]; ok {
selector.Type = fmt.Sprintf("%s", rawType)
// handle backward compatibility for "defsec" source type which is now "cloud"
if selector.Type == string(iacTypes.SourceDefsec) {
selector.Type = string(iacTypes.SourceCloud)
}
}
if subType, ok := selectorMap["subtypes"].([]interface{}); ok {
for _, subT := range subType {
if st, ok := subT.(map[string]interface{}); ok {
s := SubType{}
_ = mapstructure.Decode(st, &s)
selector.Subtypes = append(selector.Subtypes, s)
}
}
}
}
options.Selectors = append(options.Selectors, selector)
}
}
}
return options
}
func getModuleNamespace(module *ast.Module) string {
return strings.TrimPrefix(module.Package.Path.String(), "data.")
}