kubeaudit

package module
v0.0.0-...-e70be16 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 24, 2024 License: MIT Imports: 14 Imported by: 1

README

Build Status Go Report Card GoDoc

It is now a requirement for clusters to run Kubernetes >=1.19.

override labels with unregistered kubernetes.io annotations will be deprecated. It'll soon be a requirement to use kubeaudit.io instead. Refer to this discussion for additional context.

kubeaudit ☁ 🔒 💪

kubeaudit is a command line tool and a Go package to audit Kubernetes clusters for various different security concerns, such as:

  • run as non-root
  • use a read-only root filesystem
  • drop scary capabilities, don't add new ones
  • don't run privileged
  • and more!

tldr. kubeaudit makes sure you deploy secure containers!

Package

To use kubeaudit as a Go package, see the package docs.

The rest of this README will focus on how to use kubeaudit as a command line tool.

Command Line Interface (CLI)

Installation

Brew
brew install kubeaudit
Download a binary

Kubeaudit has official releases that are blessed and stable: Official releases

DIY build

Main may have newer features than the stable releases. If you need a newer feature not yet included in a release, make sure you're using Go 1.17+ and run the following:

go get -v github.com/elliotxx/kubeaudit

Start using kubeaudit with the Quick Start or view all the supported commands.

Kubectl Plugin

Prerequisite: kubectl v1.12.0 or later

With kubectl v1.12.0 introducing easy pluggability of external functions, kubeaudit can be invoked as kubectl audit by

  • running make plugin and having $GOPATH/bin available in your path.

or

  • renaming the binary to kubectl-audit and having it available in your path.
Docker

We no longer release images to Docker Hub (since Docker Hub sunset Free Team organizations). For the time being, old images are still available but may stop being available at any time. We will start publishing images to the Github Container registry soon.

To run kubeaudit as a job in your cluster see Running kubeaudit in a cluster.

Quick Start

kubeaudit has three modes:

  1. Manifest mode
  2. Local mode
  3. Cluster mode
Manifest Mode

If a Kubernetes manifest file is provided using the -f/--manifest flag, kubeaudit will audit the manifest file.

Example command:

kubeaudit all -f "/path/to/manifest.yml"

Example output:

$ kubeaudit all -f "internal/test/fixtures/all_resources/deployment-apps-v1.yml"

---------------- Results for ---------------

  apiVersion: apps/v1
  kind: Deployment
  metadata:
    name: deployment
    namespace: deployment-apps-v1

--------------------------------------------

-- [error] AppArmorAnnotationMissing
   Message: AppArmor annotation missing. The annotation 'container.apparmor.security.beta.kubernetes.io/container' should be added.
   Metadata:
      Container: container
      MissingAnnotation: container.apparmor.security.beta.kubernetes.io/container

-- [error] AutomountServiceAccountTokenTrueAndDefaultSA
   Message: Default service account with token mounted. automountServiceAccountToken should be set to 'false' or a non-default service account should be used.

-- [error] CapabilityShouldDropAll
   Message: Capability not set to ALL. Ideally, you should drop ALL capabilities and add the specific ones you need to the add list.
   Metadata:
      Container: container
      Capability: AUDIT_WRITE
...

If no errors with a given minimum severity are found, the following is returned:

All checks completed. 0 high-risk vulnerabilities found
Autofix

Manifest mode also supports autofixing all security issues using the autofix command:

kubeaudit autofix -f "/path/to/manifest.yml"

To write the fixed manifest to a new file instead of modifying the source file, use the -o/--output flag.

kubeaudit autofix -f "/path/to/manifest.yml" -o "/path/to/fixed"

To fix a manifest based on custom rules specified on a kubeaudit config file, use the -k/--kconfig flag.

kubeaudit autofix -k "/path/to/kubeaudit-config.yml" -f "/path/to/manifest.yml" -o "/path/to/fixed"
Cluster Mode

Kubeaudit can detect if it is running within a container in a cluster. If so, it will try to audit all Kubernetes resources in that cluster:

kubeaudit all
Local Mode

Kubeaudit will try to connect to a cluster using the local kubeconfig file ($HOME/.kube/config). A different kubeconfig location can be specified using the --kubeconfig flag. To specify a context of the kubeconfig, use the -c/--context flag.

kubeaudit all --kubeconfig "/path/to/config" --context my_cluster

For more information on kubernetes config files, see https://kubernetes.io/docs/concepts/configuration/organize-cluster-access-kubeconfig/

Audit Results

Kubeaudit produces results with three levels of severity:

  • Error: A security issue or invalid kubernetes configuration
  • Warning: A best practice recommendation
  • Info: Informational, no action required. This includes results that are overridden

The minimum severity level can be set using the --minSeverity/-m flag.

By default kubeaudit will output results in a human-readable way. If the output is intended to be further processed, it can be set to output JSON using the --format json flag. To output results as logs (the previous default) use --format logrus. Some output formats include colors to make results easier to read in a terminal. To disable colors (for example, if you are sending output to a text file), you can use the --no-color flag.

You can generate a kubeaudit report in SARIF using the --format sarif flag. To write the SARIF results to a file, you can redirect the output with >. For example:

kubeaudit all -f path-to-my-file.yaml --format="sarif" > example.sarif

If there are results of severity level error, kubeaudit will exit with exit code 2. This can be changed using the --exitcode/-e flag.

For all the ways kubeaudit can be customized, see Global Flags.

Commands

Command Description Documentation
all Runs all available auditors, or those specified using a kubeaudit config. docs
autofix Automatically fixes security issues. docs
version Prints the current kubeaudit version.
Auditors

Auditors can also be run individually.

Command Description Documentation
apparmor Finds containers running without AppArmor. docs
asat Finds pods using an automatically mounted default service account docs
capabilities Finds containers that do not drop the recommended capabilities or add new ones. docs
deprecatedapis Finds any resource defined with a deprecated API version. docs
hostns Finds containers that have HostPID, HostIPC or HostNetwork enabled. docs
image Finds containers which do not use the desired version of an image (via the tag) or use an image without a tag. docs
limits Finds containers which exceed the specified CPU and memory limits or do not specify any. docs
mounts Finds containers that have sensitive host paths mounted. docs
netpols Finds namespaces that do not have a default-deny network policy. docs
nonroot Finds containers running as root. docs
privesc Finds containers that allow privilege escalation. docs
privileged Finds containers running as privileged. docs
rootfs Finds containers which do not have a read-only filesystem. docs
seccomp Finds containers running without Seccomp. docs
Global Flags
Short Long Description
--format The output format to use (one of "sarif", "pretty", "logrus", "json") (default is "pretty")
--kubeconfig Path to local Kubernetes config file. Only used in local mode (default is $HOME/.kube/config)
-c --context The name of the kubeconfig context to use
-f --manifest Path to the yaml configuration to audit. Only used in manifest mode. You may use - to read from stdin.
-n --namespace Only audit resources in the specified namespace. Not currently supported in manifest mode.
-g --includegenerated Include generated resources in scan (such as Pods generated by deployments). If you would like kubeaudit to produce results for generated resources (for example if you have custom resources or want to catch orphaned resources where the owner resource no longer exists) you can use this flag.
-m --minseverity Set the lowest severity level to report (one of "error", "warning", "info") (default is "info")
-e --exitcode Exit code to use if there are results with severity of "error". Conventionally, 0 is used for success and all non-zero codes for an error. (default is 2)
--no-color Don't use colors in the output (default is false)

Configuration File

The kubeaudit config can be used for two things:

  1. Enabling only some auditors
  2. Specifying configuration for auditors

Any configuration that can be specified using flags for the individual auditors can be represented using the config.

The config has the following format:

enabledAuditors:
  # Auditors are enabled by default if they are not explicitly set to "false"
  apparmor: false
  asat: false
  capabilities: true
  deprecatedapis: true
  hostns: true
  image: true
  limits: true
  mounts: true
  netpols: true
  nonroot: true
  privesc: true
  privileged: true
  rootfs: true
  seccomp: true
auditors:
  capabilities:
    # add capabilities needed to the add list, so kubeaudit won't report errors
    allowAddList: ['AUDIT_WRITE', 'CHOWN']
  deprecatedapis:
    # If no versions are specified and the'deprecatedapis' auditor is enabled, WARN
    # results will be genereted for the resources defined with a deprecated API.
    currentVersion: '1.22'
    targetedVersion: '1.25'
  image:
    # If no image is specified and the 'image' auditor is enabled, WARN results
    # will be generated for containers which use an image without a tag
    image: 'myimage:mytag'
  limits:
    # If no limits are specified and the 'limits' auditor is enabled, WARN results
    # will be generated for containers which have no cpu or memory limits specified
    cpu: '750m'
    memory: '500m'

For more details about each auditor, including a description of the auditor-specific configuration in the config, see the Auditor Docs.

Note: The kubeaudit config is not the same as the kubeconfig file specified with the --kubeconfig flag, which refers to the Kubernetes config file (see Local Mode). Also note that only the all and autofix commands support using a kubeaudit config. It will not work with other commands.

Note: If flags are used in combination with the config file, flags will take precedence.

Override Errors

Security issues can be ignored for specific containers or pods by adding override labels. This means the auditor will produce info results instead of error results and the audit result name will have Allowed appended to it. The labels are documented in each auditor's documentation, but the general format for auditors that support overrides is as follows:

An override label consists of a key and a value.

The key is a combination of the override type (container or pod) and an override identifier which is unique to each auditor (see the docs for the specific auditor). The key can take one of two forms depending on the override type:

  1. Container overrides, which override the auditor for that specific container, are formatted as follows:
container.kubeaudit.io/[container name].[override identifier]
  1. Pod overrides, which override the auditor for all containers within the pod, are formatted as follows:
kubeaudit.io/[override identifier]

If the value is set to a non-empty string, it will be displayed in the info result as the OverrideReason:

$ kubeaudit asat -f "auditors/asat/fixtures/service-account-token-true-allowed.yml"

---------------- Results for ---------------

  apiVersion: v1
  kind: ReplicationController
  metadata:
    name: replicationcontroller
    namespace: service-account-token-true-allowed

--------------------------------------------

-- [info] AutomountServiceAccountTokenTrueAndDefaultSAAllowed
   Message: Audit result overridden: Default service account with token mounted. automountServiceAccountToken should be set to 'false' or a non-default service account should be used.
   Metadata:
      OverrideReason: SomeReason

As per Kubernetes spec, value must be 63 characters or less and must be empty or begin and end with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), and alphanumerics between.

Multiple override labels (for multiple auditors) can be added to the same resource.

See the specific auditor docs for the auditor you wish to override for examples.

To learn more about labels, see https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/

Contributing

If you'd like to fix a bug, contribute a feature or just correct a typo, please feel free to do so as long as you follow our Code of Conduct.

  1. Create your own fork!
  2. Get the source: go get github.com/elliotxx/kubeaudit
  3. Go to the source: cd $GOPATH/src/github.com/elliotxx/kubeaudit
  4. Add your forked repo as a fork: git remote add fork https://github.com/you-are-awesome/kubeaudit
  5. Create your feature branch: git checkout -b awesome-new-feature
  6. Install Kind
  7. Run the tests to see everything is working as expected: USE_KIND=true make test (to run tests without Kind: make test)
  8. Commit your changes: git commit -am 'Adds awesome feature'
  9. Push to the branch: git push fork
  10. Sign the Contributor License Agreement
  11. Submit a PR (All PR must be labeled with 🐛 (Bug fix), ✨ (New feature), 📖 (Documentation update), or ⚠ (Breaking changes) )
  12. ???
  13. Profit

Note that if you didn't sign the CLA before opening your PR, you can re-run the check by adding a comment to the PR that says "I've signed the CLA!"!

Documentation

Overview

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.

Example

Example shows how to audit and fix a Kubernetes manifest file

package main

import (
	"fmt"
	"os"
	"strings"

	"github.com/elliotxx/kubeaudit"
	"github.com/elliotxx/kubeaudit/auditors/all"
	"github.com/elliotxx/kubeaudit/config"

	log "github.com/sirupsen/logrus"
)

func main() {
	// A sample Kubernetes manifest file
	manifest := `
apiVersion: apps/v1
kind: Deployment
metadata:
  name: myAuditor 
  spec:
    template:
      spec:
        containers:
        - name: myContainer
`

	// Initialize all the security auditors using default configuration
	allAuditors, err := all.Auditors(config.KubeauditConfig{})
	if err != nil {
		log.Fatal(err)
	}

	// Initialize kubeaudit
	auditor, err := kubeaudit.New(allAuditors)
	if err != nil {
		log.Fatal(err)
	}

	// Run the audit in manifest mode
	report, err := auditor.AuditManifest("", strings.NewReader(manifest))
	if err != nil {
		log.Fatal(err)
	}

	// Print the audit results to screen
	report.PrintResults()

	// Print the plan to screen. These are the steps that will be taken by calling "report.Fix()".
	fmt.Println("\nPlan:")
	report.PrintPlan(os.Stdout)

	// Print the fixed manifest to screen. Note that this leaves the original manifest unmodified.
	fmt.Println("\nFixed manifest:")
	err = report.Fix(os.Stdout)
	if err != nil {
		log.Fatal(err)
	}
}
Output:

Example (AuditCluster)

ExampleAuditCluster shows how to run kubeaudit in cluster mode (only works if kubeaudit is being run from a container insdie of a cluster)

package main

import (
	"github.com/elliotxx/kubeaudit"
	"github.com/elliotxx/kubeaudit/auditors/all"
	"github.com/elliotxx/kubeaudit/config"

	log "github.com/sirupsen/logrus"
)

func main() {
	// Initialize all the security auditors using default configuration
	allAuditors, err := all.Auditors(config.KubeauditConfig{})
	if err != nil {
		log.Fatal(err)
	}

	// Initialize kubeaudit
	auditor, err := kubeaudit.New(allAuditors)
	if err != nil {
		log.Fatal(err)
	}

	// Run the audit in cluster mode. Note this will fail if kubeaudit is not running within a cluster.
	report, err := auditor.AuditCluster(kubeaudit.AuditOptions{})
	if err != nil {
		log.Fatal(err)
	}

	// Print the audit results to screen
	report.PrintResults()
}
Output:

Example (AuditLocal)

ExampleAuditLocal shows how to run kubeaudit in local mode

package main

import (
	"github.com/elliotxx/kubeaudit"
	"github.com/elliotxx/kubeaudit/auditors/all"
	"github.com/elliotxx/kubeaudit/config"

	log "github.com/sirupsen/logrus"
)

func main() {
	// Initialize all the security auditors using default configuration
	allAuditors, err := all.Auditors(config.KubeauditConfig{})
	if err != nil {
		log.WithError(err).Fatal("Error initializing all auditors")
	}

	// Initialize kubeaudit
	auditor, err := kubeaudit.New(allAuditors)
	if err != nil {
		log.Fatal(err)
	}

	// Run the audit in local mode
	report, err := auditor.AuditLocal("", "", kubeaudit.AuditOptions{})
	if err != nil {
		log.Fatal(err)
	}

	// Print the audit results to screen
	report.PrintResults()
}
Output:

Example (AuditorSubset)

ExampleAuditorSubset shows how to run kubeaudit with a subset of auditors

package main

import (
	"strings"

	"github.com/elliotxx/kubeaudit"
	"github.com/elliotxx/kubeaudit/auditors/apparmor"
	"github.com/elliotxx/kubeaudit/auditors/image"

	log "github.com/sirupsen/logrus"
)

func main() {
	// A sample Kubernetes manifest file
	manifest := `
apiVersion: apps/v1
kind: Deployment
metadata:
  name: myAuditor 
  spec:
    template:
      spec:
        containers:
        - name: myContainer
`

	// Initialize the auditors you want to use
	auditor, err := kubeaudit.New([]kubeaudit.Auditable{
		apparmor.New(),
		image.New(image.Config{Image: "myimage:mytag"}),
	})
	if err != nil {
		log.Fatal(err)
	}

	// Run the audit in the mode of your choosing. Here we use manifest mode.
	report, err := auditor.AuditManifest("", strings.NewReader(manifest))
	if err != nil {
		log.Fatal(err)
	}

	// Print the audit results to screen
	report.PrintResults()
}
Output:

Example (Config)

ExampleConfig shows how to use a kubeaudit with a config file. A kubeaudit config can be used to specify which security auditors to run, and to specify configuration for those auditors.

package main

import (
	"os"
	"strings"

	"github.com/elliotxx/kubeaudit"
	"github.com/elliotxx/kubeaudit/auditors/all"
	"github.com/elliotxx/kubeaudit/config"

	log "github.com/sirupsen/logrus"
)

func main() {
	configFile := "config/config.yaml"
	// A sample Kubernetes manifest file
	manifest := `
apiVersion: apps/v1
kind: Deployment
metadata:
  name: myAuditor 
  spec:
    template:
      spec:
        containers:
        - name: myContainer
`

	// Open the configuration file
	reader, err := os.Open(configFile)
	if err != nil {
		log.WithError(err).Fatal("Unable to open config file ", configFile)
	}

	// Load the config
	conf, err := config.New(reader)
	if err != nil {
		log.WithError(err).Fatal("Error parsing config file ", configFile)
	}

	// Initialize security auditors using the configuration
	auditors, err := all.Auditors(conf)
	if err != nil {
		log.Fatal(err)
	}

	// Initialize kubeaudit
	auditor, err := kubeaudit.New(auditors)
	if err != nil {
		log.Fatal(err)
	}

	// Run the audit in the mode of your choosing. Here we use manifest mode.
	report, err := auditor.AuditManifest("", strings.NewReader(manifest))
	if err != nil {
		log.Fatal(err)
	}

	// Print the audit results to screen
	report.PrintResults()
}
Output:

Example (CustomAuditor)

ExampleCustomAuditor shows how to use a custom auditor

package main

import (
	"fmt"
	"strings"

	"github.com/elliotxx/kubeaudit"
	"github.com/elliotxx/kubeaudit/pkg/k8s"

	log "github.com/sirupsen/logrus"
)

func NewCustomAuditor() kubeaudit.Auditable {
	return &myAuditor{}
}

// Your auditor must implement the Auditable interface, which requires only one method: Audit().
type myAuditor struct{}

// The Audit function takes in a resource to audit and returns audit results for that resource.
//
// Params
//
//	resource: Read-only. The resource to audit.
//	resources: Read-only. A reference to all resources. Can be used for context though most auditors don't need this.
//
// Return
//
//	auditResults: The results for the audit. Each result can optionally include a PendingFix object to
//	  define autofix behaviour (see below).
func (a *myAuditor) Audit(resource k8s.Resource, _ []k8s.Resource) ([]*kubeaudit.AuditResult, error) {
	return []*kubeaudit.AuditResult{
		{
			Auditor:  "Awesome",
			Rule:     "MyAudit",
			Severity: kubeaudit.Error,
			Message:  "My custom error",
			PendingFix: &myAuditorFix{
				newVal: "bye",
			},
		},
	}, nil
}

// To provide autofix behaviour for an audit result, implement the PendingFix interface. The PendingFix interface
// has two methods: Plan() and Apply().
type myAuditorFix struct {
	newVal string
}

// The Plan method explains what fix will be applied by Apply().
//
// Return
//
//	plan: A human-friendly explanation of what Apply() will do
func (f *myAuditorFix) Plan() string {
	return fmt.Sprintf("Set label 'hi' to '%s'", f.newVal)
}

// The Apply method applies a fix to a resource.
//
// Params
//
//	resource: A reference to the resource that should be fixed.
//
// Return
//
//	newResources: New resources created as part of the fix. Generally, it should not be necessary to create
//	  new resources, only modify the passed in resource.
func (f *myAuditorFix) Apply(resource k8s.Resource) []k8s.Resource {
	setLabel(resource, "hi", f.newVal)
	return nil
}

// This is just a helper function
func setLabel(resource k8s.Resource, key, value string) {
	switch kubeType := resource.(type) {
	case *k8s.PodV1:
		kubeType.Labels[key] = value
	case *k8s.DeploymentV1:
		kubeType.Labels[key] = value
	}
}

// A sample Kubernetes manifest file
var manifest = `
apiVersion: apps/v1
kind: Deployment
metadata:
  name: myAuditor 
spec:
  template:
    spec:
      containers:
      - name: myContainer
`

// ExampleCustomAuditor shows how to use a custom auditor
func main() {
	// Initialize kubeaudit with your custom auditor
	auditor, err := kubeaudit.New([]kubeaudit.Auditable{NewCustomAuditor()})
	if err != nil {
		log.Fatal(err)
	}

	// Run the audit in the mode of your choosing. Here we use manifest mode.
	report, err := auditor.AuditManifest("", strings.NewReader(manifest))
	if err != nil {
		log.Fatal(err)
	}

	// Print the results to screen
	report.PrintResults()
}
Output:

Example (PrintOptions)

ExamplePrintOptions shows how to use different print options for printing audit results.

package main

import (
	"os"

	"github.com/elliotxx/kubeaudit"
	"github.com/elliotxx/kubeaudit/auditors/apparmor"

	"github.com/sirupsen/logrus"
	log "github.com/sirupsen/logrus"
)

func main() {
	auditor, err := kubeaudit.New([]kubeaudit.Auditable{apparmor.New()})
	if err != nil {
		log.Fatal(err)
	}

	report, err := auditor.AuditLocal("", "", kubeaudit.AuditOptions{})
	if err != nil {
		log.Fatal(err)
	}

	// Print the audit results to a file
	f, err := os.Create("output.txt")
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()
	defer os.Remove("output.txt")
	report.PrintResults(kubeaudit.WithWriter(f))

	// Only print audit results with severity of Error (ignore info and warning)
	report.PrintResults(kubeaudit.WithMinSeverity(kubeaudit.Error))

	// Print results as JSON
	report.PrintResults(kubeaudit.WithFormatter(&logrus.JSONFormatter{}))
}
Output:

Index

Examples

Constants

View Source
const ErrorUnsupportedResource = "Unsupported resource"

ErrorUnsupportedResource occurs when Kubeaudit doesn't know how to audit the resource

View Source
const RedundantAuditorOverride = "RedundantAuditorOverride"

RedundantAuditorOverride is the audit result name given when an override label is used to disable an auditor, but that auditor found no security issues so the label is redundant

Variables

This section is empty.

Functions

This section is empty.

Types

type AuditOptions

type AuditOptions = k8sinternal.ClientOptions

type AuditResult

type AuditResult struct {
	Auditor    string        // Auditor name
	Rule       string        // Rule uniquely identifies a type of violation
	Severity   SeverityLevel // Severity is one of Error, Warn, or Info
	Message    string        // Message is a human-readable description of the audit result
	PendingFix PendingFix    // PendingFix is the fix that will be applied to automatically fix the security issue
	Metadata   Metadata      // Metadata includes additional context for an audit result
	FilePath   string        // Manifest file path
}

AuditResult represents a potential security issue. There may be multiple AuditResults per resource and audit

func (*AuditResult) Fix

func (result *AuditResult) Fix(resource k8s.Resource) (newResources []k8s.Resource)

func (*AuditResult) FixPlan

func (result *AuditResult) FixPlan() (ok bool, plan string)

type Auditable

type Auditable interface {
	Audit(resource k8s.Resource, resources []k8s.Resource) ([]*AuditResult, error)
}

Auditable is an interface which is implemented by auditors

type KubeResource

type KubeResource interface {
	// Object is a pointer to a Kubernetes resource. The resource may be modified by multiple auditors
	Object() k8s.Resource
	// Bytes is the original byte representation of the resource
	Bytes() []byte
}

KubeResource is a wrapper around a Kubernetes object

type Kubeaudit

type Kubeaudit struct {
	// contains filtered or unexported fields
}

Kubeaudit provides functions to audit and fix Kubernetes manifests

func New

func New(auditors []Auditable, opts ...Option) (*Kubeaudit, error)

New returns a new Kubeaudit instance

func (*Kubeaudit) AuditCluster

func (a *Kubeaudit) AuditCluster(options AuditOptions) (*Report, error)

AuditCluster audits the Kubernetes resources found in the cluster in which Kubeaudit is running

func (*Kubeaudit) AuditLocal

func (a *Kubeaudit) AuditLocal(configpath string, context string, options AuditOptions) (*Report, error)

AuditLocal audits the Kubernetes resources found in the provided Kubernetes config file

func (*Kubeaudit) AuditManifest

func (a *Kubeaudit) AuditManifest(manifestPath string, manifest io.Reader) (*Report, error)

AuditManifest audits the Kubernetes resources in the provided manifest

func (*Kubeaudit) AuditSingleManifest

func (a *Kubeaudit) AuditSingleManifest(manifest io.Reader) (*Report, error)

AuditSingleManifest audits the Kubernetes resources in the provided manifest

type Metadata

type Metadata = map[string]string

Metadata holds metadata for a potential security issue

type Option

type Option func(*Kubeaudit) error

Option is used to specify the behaviour of Kubeaudit Auditor

func WithLogger

func WithLogger(formatter log.Formatter) Option

WithLogger specifies the log formatter to use

type PendingFix

type PendingFix interface {
	// Plan returns a human-readable description of what Apply() will do
	Plan() string
	// Apply applies the proposed fix to the resource and returns any new resources that were created. Note that
	// Apply is expected to modify the passed in resource
	Apply(k8s.Resource) []k8s.Resource
}

PendingFix includes the logic to automatically fix the issues caught by auditing

type PrintOption

type PrintOption func(p *Printer)

func WithColor

func WithColor(color bool) PrintOption

WithColor specifies whether or not to colorize output. You will likely want to set this to false if not writing to standard out.

func WithFormatter

func WithFormatter(formatter log.Formatter) PrintOption

WithFormatter sets a logrus formatter to use to format results.

func WithMinSeverity

func WithMinSeverity(minSeverity SeverityLevel) PrintOption

WithMinSeverity sets the minimum severity of results that will be printed.

func WithWriter

func WithWriter(writer io.Writer) PrintOption

WithWriter sets the writer where results will be written to.

type Printer

type Printer struct {
	// contains filtered or unexported fields
}

func NewPrinter

func NewPrinter(opts ...PrintOption) Printer

func (*Printer) PrintReport

func (p *Printer) PrintReport(report *Report)

type Report

type Report struct {
	// contains filtered or unexported fields
}

Report contains the results after auditing

func NewReport

func NewReport(results []Result) *Report

func (*Report) Fix

func (r *Report) Fix(writer io.Writer) error

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 (*Report) HasErrors

func (r *Report) HasErrors() (errorsFound bool)

HasErrors returns true if any findings have the level of Error

func (*Report) PrintPlan

func (r *Report) PrintPlan(writer io.Writer)

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 (*Report) PrintResults

func (r *Report) PrintResults(printOptions ...PrintOption)

PrintResults writes the audit results to the specified writer. Defaults to printing results to stdout

func (*Report) RawResults

func (r *Report) RawResults() []Result

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 (*Report) Results

func (r *Report) Results() []Result

Results returns the audit results for each Kubernetes resource

func (*Report) ResultsWithMinSeverity

func (r *Report) ResultsWithMinSeverity(minSeverity SeverityLevel) []Result

ResultsWithMinSeverity returns the audit results for each Kubernetes resource with a minimum severity

type Result

type Result interface {
	GetResource() KubeResource
	GetAuditResults() []*AuditResult
}

Result contains the audit results for a single Kubernetes resource

type SeverityLevel

type SeverityLevel int
const (
	// Info is used for informational audit results where no action is required
	Info SeverityLevel = 0
	// Warn is used for audit results where there may be security concerns. If an auditor is disabled for a resource
	// using an override label, the audit results will be warnings instead of errors. Kubeaudit will NOT attempt to
	// fix these
	Warn SeverityLevel = 1
	// Error is used for audit results where action is required. Kubeaudit will attempt to fix these
	Error SeverityLevel = 2
)

AuditResult severity levels. They also correspond to log levels

func (SeverityLevel) String

func (s SeverityLevel) String() string

type WorkloadResult

type WorkloadResult struct {
	Resource     KubeResource
	AuditResults []*AuditResult
}

Implements Result

func (*WorkloadResult) GetAuditResults

func (wlResult *WorkloadResult) GetAuditResults() []*AuditResult

func (*WorkloadResult) GetResource

func (wlResult *WorkloadResult) GetResource() KubeResource

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL