forked from Shopify/kubeaudit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
kubeaudit.go
335 lines (295 loc) · 9.15 KB
/
kubeaudit.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
// Package kubeaudit provides methods to find and fix security issues in Kubernetes resources.
//
// # Modes
//
// Kubeaudit supports three different modes. The mode used depends on the audit method used.
//
// 1. Manifest mode: Audit a manifest file
//
// 2. Local mode: Audit resources in a local kubeconfig file
//
// 3. Cluster mode: Audit resources in a running cluster (kubeaudit must be invoked from a container within the cluster)
//
// In manifest mode, kubeaudit can automatically fix security issues.
//
// Follow the instructions below to use kubeaudit:
//
// # First initialize the security auditors
//
// The auditors determine which security issues kubeaudit will look for. Each auditor is responsible for a different
// security issue. For an explanation of what each auditor checks for, see https://github.com/elliotxx/kubeaudit#auditors.
//
// To initialize all available auditors:
//
// import "github.com/elliotxx/kubeaudit/auditors/all"
//
// auditors, err := all.Auditors(config.KubeauditConfig{})
//
// Or, to initialize specific auditors, import each one:
//
// import (
// "github.com/elliotxx/kubeaudit/auditors/apparmor"
// "github.com/elliotxx/kubeaudit/auditors/image"
// )
//
// auditors := []kubeaudit.Auditable{
// apparmor.New(),
// image.New(image.Config{Image: "myimage:mytag"}),
// }
//
// # Initialize Kubeaudit
//
// Create a new instance of kubeaudit:
//
// kubeAuditor, err := kubeaudit.New(auditors)
//
// # Run the audit
//
// To run the audit in manifest mode:
//
// import "os"
//
// manifest, err := os.Open("/path/to/manifest.yaml")
// if err != nil {
// ...
// }
//
// report, err := kubeAuditor.AuditManifest(manifest)
//
// Or, to run the audit in local mode:
//
// report, err := kubeAuditor.AuditLocal("/path/to/kubeconfig.yml", kubeaudit.AuditOptions{})
//
// Or, to run the audit in cluster mode (pass it a namespace name as a string to only audit resources in that namespace, or an empty string to audit resources in all namespaces):
//
// report, err := auditor.AuditCluster(kubeaudit.AuditOptions{})
//
// # Get the results
//
// To print the results in a human readable way:
//
// report.PrintResults()
//
// Results are printed to standard out by default. To print to a string instead:
//
// var buf bytes.Buffer
// report.PrintResults(kubeaudit.WithWriter(&buf), kubeaudit.WithColor(false))
// resultsString := buf.String()
//
// Or, to get the result objects:
//
// results := report.Results()
//
// # Autofix
//
// Note that autofixing is only supported in manifest mode.
//
// To print the plan (what will be fixed):
//
// report.PrintPlan(os.Stdout)
//
// To automatically fix the security issues and print the fixed manifest:
//
// err = report.Fix(os.Stdout)
//
// # Override Errors
//
// Overrides can be used to ignore specific auditors for specific containers or pods.
// See the documentation for the specific auditor you wish to override at https://github.com/elliotxx/kubeaudit#auditors.
//
// # Custom Auditors
//
// Kubeaudit supports custom auditors. See the Custom Auditor example.
package kubeaudit
import (
"errors"
"fmt"
"io"
"io/ioutil"
"path/filepath"
"strings"
"github.com/elliotxx/kubeaudit/internal/k8sinternal"
"github.com/elliotxx/kubeaudit/pkg/k8s"
)
// Kubeaudit provides functions to audit and fix Kubernetes manifests
type Kubeaudit struct {
auditors []Auditable
}
type AuditOptions = k8sinternal.ClientOptions
// New returns a new Kubeaudit instance
func New(auditors []Auditable, opts ...Option) (*Kubeaudit, error) {
if len(auditors) == 0 {
return nil, errors.New("no auditors enabled")
}
auditor := &Kubeaudit{
auditors: auditors,
}
if err := auditor.parseOptions(opts); err != nil {
return nil, err
}
return auditor, nil
}
// AuditSingleManifest audits the Kubernetes resources in the provided manifest
func (a *Kubeaudit) AuditSingleManifest(manifest io.Reader) (*Report, error) {
manifestBytes, err := io.ReadAll(manifest)
if err != nil {
return nil, err
}
resource, err := getResourcesFromSingleManifest(manifestBytes)
if err != nil {
return nil, fmt.Errorf("failed to get resources from manifest: %w", err)
}
results, err := auditResources([]KubeResource{resource}, a.auditors)
if err != nil {
return nil, err
}
return NewReport(results), nil
}
// AuditManifest audits the Kubernetes resources in the provided manifest
func (a *Kubeaudit) AuditManifest(manifestPath string, manifest io.Reader) (*Report, error) {
manifestBytes, err := ioutil.ReadAll(manifest)
if err != nil {
return nil, err
}
resources, err := getResourcesFromManifest(manifestBytes)
if err != nil {
return nil, fmt.Errorf("failed to get resources from manifest: %w", err)
}
results, err := auditResources(resources, a.auditors)
if err != nil {
return nil, err
}
for _, result := range results {
auditResults := result.GetAuditResults()
if !filepath.IsAbs(manifestPath) {
manifestPath = strings.TrimPrefix(filepath.Clean("/"+manifestPath), "/")
}
for _, ar := range auditResults {
ar.FilePath = manifestPath
}
}
report := NewReport(results)
return report, nil
}
// AuditCluster audits the Kubernetes resources found in the cluster in which Kubeaudit is running
func (a *Kubeaudit) AuditCluster(options AuditOptions) (*Report, error) {
if !k8sinternal.IsRunningInCluster(k8sinternal.DefaultClient) {
return nil, errors.New("failed to audit resources in cluster mode: not running in cluster")
}
client, err := k8sinternal.NewKubeClientCluster(k8sinternal.DefaultClient)
if err != nil {
return nil, err
}
resources, err := getResourcesFromClient(client, options)
if err != nil {
return nil, err
}
results, err := auditResources(resources, a.auditors)
if err != nil {
return nil, err
}
report := NewReport(results)
return report, nil
}
// AuditLocal audits the Kubernetes resources found in the provided Kubernetes config file
func (a *Kubeaudit) AuditLocal(configpath string, context string, options AuditOptions) (*Report, error) {
client, err := k8sinternal.NewKubeClientLocal(configpath, context)
if err == k8sinternal.ErrNoReadableKubeConfig {
return nil, fmt.Errorf("failed to open kubeconfig file %s", configpath)
} else if err != nil {
return nil, err
}
resources, err := getResourcesFromClient(client, options)
if err != nil {
return nil, err
}
results, err := auditResources(resources, a.auditors)
if err != nil {
return nil, err
}
report := NewReport(results)
return report, nil
}
// Report contains the results after auditing
type Report struct {
results []Result
}
func NewReport(results []Result) *Report {
return &Report{results}
}
// RawResults returns all of the results for each Kubernetes resource, including ones that had no audit results.
// Generally, you will want to use Results() instead.
func (r *Report) RawResults() []Result {
return r.results
}
// Results returns the audit results for each Kubernetes resource
func (r *Report) Results() []Result {
results := make([]Result, 0, len(r.RawResults()))
for _, result := range r.RawResults() {
if len(result.GetAuditResults()) > 0 {
results = append(results, result)
}
}
return results
}
// ResultsWithMinSeverity returns the audit results for each Kubernetes resource with a minimum severity
func (r *Report) ResultsWithMinSeverity(minSeverity SeverityLevel) []Result {
var results []Result
for _, result := range r.RawResults() {
var filteredAuditResults []*AuditResult
for _, auditResult := range result.GetAuditResults() {
if auditResult.Severity >= minSeverity {
filteredAuditResults = append(filteredAuditResults, auditResult)
}
}
if len(filteredAuditResults) > 0 {
results = append(results, &WorkloadResult{
Resource: result.GetResource(),
AuditResults: filteredAuditResults,
})
}
}
return results
}
// HasErrors returns true if any findings have the level of Error
func (r *Report) HasErrors() (errorsFound bool) {
for _, workloadResult := range r.Results() {
for _, auditResult := range workloadResult.GetAuditResults() {
if auditResult.Severity >= Error {
return true
}
}
}
return false
}
// PrintResults writes the audit results to the specified writer. Defaults to printing results to stdout
func (r *Report) PrintResults(printOptions ...PrintOption) {
printer := NewPrinter(printOptions...)
printer.PrintReport(r)
}
// Fix tries to automatically patch any security concerns and writes the resulting manifest to the provided writer.
// Only applies when audit was performed on a manifest (not local or cluster)
func (r *Report) Fix(writer io.Writer) error {
fixed, err := fix(r.RawResults())
if err != nil {
return err
}
_, err = writer.Write(fixed)
return err
}
// PrintPlan writes the actions that will be performed by the Fix() function in a human-readable way to the
// provided writer. Only applies when audit was performed on a manifest (not local or cluster)
func (r *Report) PrintPlan(writer io.Writer) {
for _, result := range r.Results() {
for _, auditResult := range result.GetAuditResults() {
ok, plan := auditResult.FixPlan()
if ok {
fmt.Fprintln(writer, "* ", plan)
}
}
}
}
// Auditable is an interface which is implemented by auditors
type Auditable interface {
Audit(resource k8s.Resource, resources []k8s.Resource) ([]*AuditResult, error)
}