-
Notifications
You must be signed in to change notification settings - Fork 194
/
policy.go
327 lines (295 loc) · 9.38 KB
/
policy.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
package policy
import (
"context"
"encoding/json"
"errors"
"fmt"
"io/fs"
"path"
"path/filepath"
"strings"
"github.com/aquasecurity/trivy-operator/pkg/configauditreport"
"github.com/aquasecurity/trivy-operator/pkg/plugins/trivy"
"github.com/aquasecurity/trivy/pkg/iac/severity"
"github.com/aquasecurity/trivy/pkg/mapfs"
"github.com/go-logr/logr"
"github.com/liamg/memoryfs"
"github.com/aquasecurity/trivy/pkg/iac/scan"
"github.com/aquasecurity/trivy/pkg/iac/scanners/kubernetes"
"github.com/aquasecurity/trivy/pkg/iac/scanners/options"
"github.com/aquasecurity/trivy-operator/pkg/kube"
"sigs.k8s.io/controller-runtime/pkg/client"
)
const (
keyPrefixPolicy = "policy."
keyPrefixLibrary = "library."
keySuffixKinds = ".kinds"
keySuffixRego = ".rego"
PoliciesNotFoundError = "failed to load rego policies from [externalPolicies]: stat externalPolicies: file does not exist"
)
const (
kindAny = "*"
kindWorkload = "Workload"
inputFolder = "inputs"
policiesFolder = "externalPolicies"
regoExt = "rego"
yamlExt = "yaml"
externalPoliciesNamespace = "trivyoperator"
)
type Policies struct {
data map[string]string
log logr.Logger
cac configauditreport.ConfigAuditConfig
clusterVersion string
policyLoader Loader
}
func NewPolicies(data map[string]string, cac configauditreport.ConfigAuditConfig, log logr.Logger, pl Loader, serverVersion string) *Policies {
return &Policies{
data: data,
log: log,
cac: cac,
policyLoader: pl,
clusterVersion: serverVersion,
}
}
func (p *Policies) Libraries() map[string]string {
libs := make(map[string]string)
for key, value := range p.data {
if !strings.HasPrefix(key, keyPrefixLibrary) {
continue
}
if !strings.HasSuffix(key, keySuffixRego) {
continue
}
libs[key] = value
}
return libs
}
func (p *Policies) PoliciesByKind(kind string) (map[string]string, error) {
policies := make(map[string]string)
for key, value := range p.data {
if strings.HasSuffix(key, keySuffixRego) && strings.HasPrefix(key, keyPrefixPolicy) {
// Check if kinds were defined for this policy
kindsKey := strings.TrimSuffix(key, keySuffixRego) + keySuffixKinds
if _, ok := p.data[kindsKey]; !ok {
return nil, fmt.Errorf("kinds not defined for policy: %s", key)
}
}
if !strings.HasSuffix(key, keySuffixKinds) {
continue
}
for _, k := range strings.Split(value, ",") {
if k == kindWorkload && !kube.IsWorkload(kind) {
continue
}
if k != kindAny && k != kindWorkload && k != kind {
continue
}
policyKey := strings.TrimSuffix(key, keySuffixKinds) + keySuffixRego
var ok bool
policies[policyKey], ok = p.data[policyKey]
if !ok {
return nil, fmt.Errorf("expected policy not found: %s", policyKey)
}
}
}
return policies, nil
}
func (p *Policies) Hash(kind string) (string, error) {
policies, err := p.loadPolicies(kind)
if err != nil {
return "", fmt.Errorf("failed to load built-in / external policies: %s: %w", kind, err)
}
return kube.ComputeHash(policies), nil
}
func (p *Policies) ModulesByKind(kind string) (map[string]string, error) {
modules, err := p.PoliciesByKind(kind)
if err != nil {
return nil, err
}
for key, value := range p.Libraries() {
modules[key] = value
}
return modules, nil
}
func (p *Policies) loadPolicies(kind string) ([]string, error) {
// read external policies
modByKind, err := p.ModulesByKind(kind)
if err != nil {
return nil, err
}
externalPolicies := make([]string, 0, len(modByKind))
for _, mod := range modByKind {
externalPolicies = append(externalPolicies, mod)
}
policies := make([]string, 0)
// read built-in policies
if p.cac.GetUseBuiltinRegoPolicies() {
policies, _, err = p.policyLoader.GetPoliciesAndBundlePath()
if err != nil {
return nil, err
}
}
if len(externalPolicies) > 0 {
policies = append(policies, externalPolicies...)
}
return policies, nil
}
// Applicable check if policies exist either built in or via policies configmap
func (p *Policies) Applicable(resourceKind string) (bool, string, error) {
HasExternalPolicies, err := p.ExternalPoliciesApplicable(resourceKind)
if err != nil {
return false, "", err
}
if !HasExternalPolicies && !p.cac.GetUseBuiltinRegoPolicies() && !p.cac.GetUseEmbeddedRegoPolicies() {
return false, fmt.Sprintf("no policies found for kind %s", resourceKind), nil
}
return true, "", nil
}
func (p *Policies) ExternalPoliciesApplicable(resourceKind string) (bool, error) {
policies, err := p.PoliciesByKind(resourceKind)
if err != nil {
return false, err
}
return len(policies) > 0, nil
}
// SupportedKind scan policies supported for this kind
func (p *Policies) SupportedKind(resource client.Object, rbacDEnable bool) (bool, error) {
resourceKind := resource.GetObjectKind().GroupVersionKind().Kind
if resourceKind == "" {
return false, errors.New("resource kind must not be blank")
}
for _, kind := range p.cac.GetSupportedConfigAuditKinds() {
if kind == resourceKind && !p.rbacDisabled(rbacDEnable, kind) {
return true, nil
}
}
return false, nil
}
func (p *Policies) rbacDisabled(rbacEnable bool, kind string) bool {
if !rbacEnable && kube.IsRoleTypes(kube.Kind(kind)) {
return true
}
return false
}
// Eval evaluates Rego policies with Kubernetes resource client.Object as input.
func (p *Policies) Eval(ctx context.Context, resource client.Object, inputs ...[]byte) (scan.Results, error) {
resourceKind := resource.GetObjectKind().GroupVersionKind().Kind
policies, err := p.loadPolicies(resourceKind)
if err != nil {
return nil, fmt.Errorf("failed listing externalPolicies by kind: %s: %w", resourceKind, err)
}
memfs := memoryfs.New()
hasPolicies := len(policies) > 0
if hasPolicies {
// add add policies to in-memory filesystem
err = createPolicyInputFS(memfs, policiesFolder, policies, regoExt)
if err != nil {
return nil, err
}
}
inputResource, err := resourceBytes(resource, inputs)
if err != nil {
return nil, err
}
// add resource input to in-memory filesystem
err = createPolicyInputFS(memfs, inputFolder, []string{string(inputResource)}, yamlExt)
if err != nil {
return nil, err
}
dataFS, dataPaths, err := createDataFS([]string{}, p.clusterVersion)
if err != nil {
return nil, err
}
so := p.scannerOptions(policiesFolder, dataPaths, dataFS, hasPolicies)
scanner := kubernetes.NewScanner(so...)
scanResult, err := scanner.ScanFS(ctx, memfs, inputFolder)
if err != nil {
return nil, err
}
// special case when lib return nil for both checks and error
if scanResult == nil {
return nil, fmt.Errorf("failed to run policy checks on resources")
}
return scanResult, nil
}
func resourceBytes(resource client.Object, inputs [][]byte) ([]byte, error) {
var inputResource []byte
var err error
if len(inputs) > 0 {
inputResource = inputs[0]
} else {
if jsonManifest, ok := resource.GetAnnotations()["kubectl.kubernetes.io/last-applied-configuration"]; ok {
inputResource = []byte(jsonManifest) // required for outdated-api when k8s convert resources
} else {
inputResource, err = json.Marshal(resource)
if err != nil {
return nil, err
}
}
}
return inputResource, nil
}
// GetResultID return the result id found in aliases (legacy) otherwise use AvdID
func (r *Policies) GetResultID(result scan.Result) string {
id := result.Rule().AVDID
if len(result.Rule().Aliases) > 0 {
id = result.Rule().Aliases[0]
}
return id
}
func (r *Policies) HasSeverity(resultSeverity severity.Severity) bool {
defaultSeverity := r.cac.GetSeverity()
if defaultSeverity == "" {
defaultSeverity = trivy.DefaultSeverity
}
return strings.Contains(defaultSeverity, string(resultSeverity))
}
func (p *Policies) scannerOptions(policiesFolder string, dataPaths []string, dataFS fs.FS, hasPolicies bool) []options.ScannerOption {
optionsArray := []options.ScannerOption{
options.ScannerWithDataDirs(dataPaths...),
options.ScannerWithDataFilesystem(dataFS),
}
if !hasPolicies && p.cac.GetUseEmbeddedRegoPolicies() {
optionsArray = append(optionsArray, options.ScannerWithEmbeddedPolicies(true))
optionsArray = append(optionsArray, options.ScannerWithEmbeddedLibraries(true))
} else {
optionsArray = append(optionsArray, options.ScannerWithPolicyDirs(policiesFolder))
}
return optionsArray
}
func createPolicyInputFS(memfs *memoryfs.FS, folderName string, fileData []string, ext string) error {
if len(fileData) == 0 {
return nil
}
if err := memfs.MkdirAll(filepath.Base(folderName), 0o700); err != nil {
return err
}
for index, file := range fileData {
if err := memfs.WriteFile(path.Join(folderName, fmt.Sprintf("file_%d.%s", index, ext)), []byte(file), 0o644); err != nil {
return err
}
}
return nil
}
func createDataFS(dataPaths []string, k8sVersion string) (fs.FS, []string, error) {
fsys := mapfs.New()
// Create a virtual file for Kubernetes scanning
if k8sVersion != "" {
if err := fsys.MkdirAll("system", 0700); err != nil {
return nil, nil, err
}
data := []byte(fmt.Sprintf(`{"k8s": {"version": "%s"}}`, k8sVersion))
if err := fsys.WriteVirtualFile("system/k8s-version.json", data, 0600); err != nil {
return nil, nil, err
}
}
for _, path := range dataPaths {
if err := fsys.CopyFilesUnder(path); err != nil {
return nil, nil, err
}
}
// data paths are no longer needed as fs.FS contains only needed files now.
dataPaths = []string{"."}
return fsys, dataPaths, nil
}