Convert Figma logo to code with AI

controlplaneio logokubesec

Security risk analysis for Kubernetes resources

1,466
107
1,466
27

Top Related Projects

37,228

Find vulnerabilities, misconfigurations, secrets, SBOM in containers, Kubernetes, code repositories, clouds and more

12,737

A vulnerability scanner for container images and filesystems

11,047

Vulnerability Static Analysis for Containers

3,268

Container Image Linter for Security, Helping build the Best-Practice Docker Image, Easy to start

KubeLinter is a static analysis tool that checks Kubernetes YAML files and Helm charts to ensure the applications represented in them adhere to best practices.

Quick Overview

Kubesec is an open-source security risk analysis tool for Kubernetes resources. It scans Kubernetes YAML manifests and Helm charts, providing a risk score and actionable recommendations to improve the security posture of your Kubernetes deployments.

Pros

  • Automated security scanning for Kubernetes manifests
  • Provides a risk score and detailed recommendations for improvement
  • Integrates easily into CI/CD pipelines
  • Supports both YAML manifests and Helm charts

Cons

  • Limited to static analysis of manifests, not runtime security
  • May produce false positives in some scenarios
  • Requires regular updates to stay current with evolving Kubernetes security best practices
  • Limited customization options for security rules

Getting Started

To use Kubesec, follow these steps:

  1. Install Kubesec:
curl -s https://github.com/controlplaneio/kubesec/releases/latest/download/kubesec_linux_amd64.tar.gz | tar xz
sudo mv kubesec /usr/local/bin
  1. Scan a Kubernetes manifest:
kubesec scan /path/to/your/manifest.yaml
  1. Integrate with CI/CD (example for GitLab CI):
kubesec:
  image: docker.io/kubesec/kubesec:v2
  script:
    - kubesec scan /path/to/your/manifest.yaml

For more advanced usage and integration options, refer to the official Kubesec documentation.

Competitor Comparisons

37,228

Find vulnerabilities, misconfigurations, secrets, SBOM in containers, Kubernetes, code repositories, clouds and more

Pros of Trivy

  • Broader scope: Scans containers, filesystems, git repositories, and more
  • Faster scanning speed due to efficient caching mechanisms
  • More comprehensive vulnerability database, including multiple sources

Cons of Trivy

  • Larger resource footprint, potentially slower for small-scale deployments
  • More complex setup and configuration compared to Kubesec's simplicity
  • May produce more false positives due to its extensive scanning capabilities

Code Comparison

Kubesec example:

kubesec scan deployment.yaml

Trivy example:

trivy image myapp:latest
trivy filesystem /path/to/project

Kubesec focuses specifically on Kubernetes manifests, while Trivy offers a wider range of scanning options. Kubesec's output is typically more concise and focused on Kubernetes-specific security issues, whereas Trivy provides more comprehensive results across various security aspects.

Both tools are valuable for different use cases. Kubesec is ideal for quick Kubernetes manifest checks, while Trivy is better suited for comprehensive security scanning across multiple layers of your application and infrastructure.

12,737

A vulnerability scanner for container images and filesystems

Pros of Grype

  • Broader scope: Scans for vulnerabilities in container images, filesystems, and packages
  • More frequent updates: Active development with regular releases
  • Extensive ecosystem integration: Works with various CI/CD tools and container registries

Cons of Grype

  • Higher resource usage: May require more system resources for comprehensive scans
  • Steeper learning curve: More complex configuration options and output formats
  • Less focused on Kubernetes-specific security issues

Code Comparison

Kubesec example:

apiVersion: v1
kind: Pod
metadata:
  name: kubesec-demo
spec:
  securityContext:
    runAsNonRoot: true

Grype example:

grype debian:11 --scope all-layers

Kubesec focuses on analyzing Kubernetes manifests for security best practices, while Grype scans for vulnerabilities in various contexts, including container images. The code examples demonstrate this difference in approach and usage.

Kubesec is more specialized for Kubernetes security auditing, making it easier to use for teams primarily focused on Kubernetes deployments. Grype offers a broader vulnerability scanning capability, making it suitable for diverse environments and use cases beyond Kubernetes.

Both tools have their strengths, and the choice between them depends on the specific security requirements and the scope of the infrastructure being secured.

11,047

Vulnerability Static Analysis for Containers

Pros of Clair

  • Broader scope: Analyzes vulnerabilities in container images, not just Kubernetes manifests
  • More comprehensive: Scans for known vulnerabilities in operating systems and application dependencies
  • Integrates with container registries for continuous scanning

Cons of Clair

  • More complex setup and maintenance compared to Kubesec
  • Requires a database backend for vulnerability data storage
  • May have higher resource requirements for large-scale deployments

Code Comparison

Kubesec (YAML manifest analysis):

apiVersion: v1
kind: Pod
metadata:
  name: example-pod
spec:
  containers:
  - name: example-container
    image: example:latest

Clair (Container image analysis):

{
  "Layer": {
    "Name": "sha256:5f70bf18a086007016e948b04aed3b82103a36bea41755b6cddfaf10ace3c6ef",
    "Path": "path/to/layer.tar",
    "Headers": {
      "Docker-Content-Digest": "sha256:5f70bf18a086007016e948b04aed3b82103a36bea41755b6cddfaf10ace3c6ef"
    }
  }
}

While Kubesec focuses on analyzing Kubernetes YAML manifests for security issues, Clair scans container images for vulnerabilities in the underlying operating system and application dependencies. Kubesec is more lightweight and easier to integrate into CI/CD pipelines for Kubernetes-specific checks, while Clair provides a more comprehensive analysis of container security across different platforms and registries.

3,268

Container Image Linter for Security, Helping build the Best-Practice Docker Image, Easy to start

Pros of Dockle

  • Focuses specifically on Docker image security and best practices
  • Provides a comprehensive set of checks for Dockerfile and image content
  • Offers both CLI and CI/CD integration options

Cons of Dockle

  • Limited to Docker image analysis, not covering Kubernetes manifests
  • May require more setup time for custom rules compared to Kubesec

Code Comparison

Dockle usage:

dockle image_name

Kubesec usage:

kubesec scan kubernetes_manifest.yaml

Key Differences

  • Scope: Dockle focuses on Docker images, while Kubesec analyzes Kubernetes manifests
  • Output: Dockle provides detailed reports on image issues, whereas Kubesec offers security scores for Kubernetes resources
  • Integration: Dockle integrates well with Docker-centric workflows, while Kubesec is more suited for Kubernetes-focused environments

Use Cases

  • Choose Dockle for comprehensive Docker image security analysis and best practice checks
  • Opt for Kubesec when focusing on Kubernetes manifest security and compliance

Both tools can be valuable in a DevSecOps pipeline, with Dockle ensuring secure Docker images and Kubesec validating Kubernetes configurations.

KubeLinter is a static analysis tool that checks Kubernetes YAML files and Helm charts to ensure the applications represented in them adhere to best practices.

Pros of kube-linter

  • More comprehensive set of checks, including security, efficiency, and best practices
  • Actively maintained with regular updates and new features
  • Supports custom checks and configuration via YAML files

Cons of kube-linter

  • Larger codebase and more complex setup compared to kubesec
  • May produce more false positives due to its extensive rule set

Code Comparison

kubesec:

func Score(json []byte) ([]byte, error) {
    var manifest k8sRuntime.Object
    _, gvk, err := scheme.Codecs.UniversalDeserializer().Decode(json, nil, &manifest)
    if err != nil {
        return nil, err
    }

kube-linter:

func (l *GenericLinter) Run(objects []k8sutil.Object) ([]diagnostic.Diagnostic, error) {
    var diagnostics []diagnostic.Diagnostic
    for _, object := range objects {
        if err := l.runChecksOnObject(object, &diagnostics); err != nil {
            return nil, err
        }
    }

Both projects aim to improve Kubernetes security, but kube-linter offers a more comprehensive approach with a wider range of checks. kubesec focuses primarily on security scoring, while kube-linter provides a broader set of linting rules. kube-linter's flexibility and active development make it a strong choice for teams looking for an extensive linting solution, while kubesec might be preferred for its simplicity and focused security scoring.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Kubesec

Testing Workflow Security Analysis Workflow Release Workflow

Go Report Card PkgGoDev

🚨 v1 API is deprecated, please read the release notes 🚨

Security risk analysis for Kubernetes resources

🎬 Demo

Kubesec CLI demo

For more examples visit Kubesec.io, which uses ControlPlane's hosted API at v2.kubesec.io/scan.


🚀 Quick Start

1. Prepare Your Manifest

Create a Kubernetes resource file (e.g., kubesec-test.yaml) to scan. For a quick test, you can save the following Pod manifest:

$ cat <<EOF > kubesec-test.yaml
apiVersion: v1
kind: Pod
metadata:
  name: kubesec-demo
spec:
  containers:
  - name: kubesec-demo
    image: gcr.io/google-samples/node-hello:1.0
    securityContext:
      readOnlyRootFilesystem: true
EOF

2. Run Your First Scan

Execute a scan against your manifest file:

# Using the local binary
kubesec scan kubesec-test.yaml

# Or using Docker
docker run -i kubesec/kubesec:v2 scan /dev/stdin < kubesec-test.yaml

# Using the local binary with a human-readable table output format
kubesec scan kubesec-test.yaml --format table

[!TIP] To view the results in a human-readable table instead of the default JSON format, use the --format table flag

kubesec will output a security score and a detailed analysis of your resource.

📦 Download Kubesec

Kubesec is available as a:

Or install the latest commit from GitHub with:

Go 1.16+

$ go install github.com/controlplaneio/kubesec/v2@latest

Go version < 1.16

$ GO111MODULE="on" go get github.com/controlplaneio/kubesec/v2

📖 Usage Examples

Scanning

Scan Kubernetes resources from local files or standard input.

Kubesec can scan multiple YAML documents in a single input file, or scan documents from multiple files at once, as long as they are correctly formatted as multiple documents separated by ---.

# Scan a specific local YAML file
kubesec scan ./deployment.yaml

# Scan from standard input (JSON or YAML)
cat file.json | kubesec scan -

# Scan a rendered Helm chart
helm template -f values.yaml ./chart | kubesec scan /dev/stdin

# Scan multiple YAML documents separated by '---'
{ cat test/asset/multi.yml; echo "---"; cat test/asset/critical.yml; } | kubesec scan -

Docker Usage

You can run the same scanning commands using the official Docker image:

# Scan a file via Docker using standard input
docker run -i kubesec/kubesec:v2 scan /dev/stdin < kubesec-test.yaml

Output Formats

Kubesec supports three different output formats, specified by the --format / -f flag: json (default), table, and template, and can scan multiple YAML documents in a single input file.

# JSON array output (default behaviour)
kubesec scan ./deployment.yaml --format json

# Human-readable table output
kubesec scan ./deployment.yaml --format table

# Use a custom template for the output
kubesec scan ./deployment.yaml --format template --template report-template.tmpl

Scan specific rules

# One rule
kubesec scan --rules CapSysAdmin kubesec-test.yaml

# Multiple rules
kubesec scan --rules RunAsNonRoot,SeccompAny,ApparmorAny kubesec-test.yaml
Example JSON Output
[
  {
    "object": "Pod/security-context-demo.default",
    "valid": true,
    "message": "Failed with a score of -30 points",
    "score": -30,
    "scoring": {
      "critical": [
        {
          "selector": "containers[] .securityContext .capabilities .add == SYS_ADMIN",
          "reason": "CAP_SYS_ADMIN is the most privileged capability and should always be avoided",
          "points": -30
        }
      ],
      "advise": [
        {
          "selector": "containers[] .securityContext .runAsNonRoot == true",
          "reason": "Force the running image to run as a non-root user to ensure least privilege",
          "points": 1
        },
        {
          // ...
        }
      ]
    }
  }
]
Example Table Output

Table output

Print Rules

# Print all scanning rules with their associated point scores
kubesec print-rules

# Print all scanning rules with their associated point scores as a table
kubesec print-rules --format table

Example Rules Output JSON

[
  {
    "id": "AllowPrivilegeEscalation",
    "selector": "containers[] .securityContext .allowPrivilegeEscalation == true",
    "reason": "Ensure a non-root process can not gain more privileges",
    "kinds": [
      "Pod",
      "Deployment",
      "StatefulSet",
      "DaemonSet"
    ],
    "points": -7,
    "advise": 0
  },
...
]

Custom Schemas

Kubesec leverages kubeconform (thanks @yannh) to validate the manifests to scan. This implies that specifying different schema locations follows the rules as described in the kubeconform README.

# Usees the latest schema from upstream
# Schema will be fetched from: https://raw.githubusercontent.com/yannh/kubernetes-json-schema/master/master-standalone-strict/pod-v1.json
kubesec scan ./pod.yaml

# Use a specific schema version from upstream (format x.y.z with no v prefix)
# Schema will be fetched from: https://raw.githubusercontent.com/yannh/kubernetes-json-schema/master/v1.25.3-standalone-strict/pod-v1.json
kubesec scan ./pod.yaml --kubernetes-version 1.25.3

# Use a specific schema version in an airgapped environment over HTTP
# Schema will be fetched from: `https://host.server/v<version>-standalone-strict/pod-v1.json`
kubesec scan ./deployment.yaml --kubernetes-version <version> --schema-location https://host.server

# Use a specific schema version in an airgap environment with local files
# Schema will be read from: `/opt/schemas/v<version>-standalone-strict/pod-v1.json`
kubesec scan ./deployment.yaml --kubernetes-version <version> --schema-location /opt/schemas

Note: in order to limit external network calls and allow usage in airgap environments, the kubesec image embeds schemas. If you are looking to change the schema location, you'll need to change the K8S_SCHEMA_VER and SCHEMA_LOCATION environment variables at runtime.

HTTP Server Mode

Kubesec includes a bundled HTTP server that you can run locally or in a container to accept scan requests over the network.

CLI Usage

# Start the HTTP server in the background on port 8080
kubesec http 8080 &

# Send a file to the running server via POST
curl -sSX POST --data-binary @deployment.yaml http://localhost:8080/scan

# Stop the background local server when finished
kill %

Docker Usage

# Start the HTTP server using Docker
docker run -d -p 8080:8080 kubesec/kubesec:v2 http 8080

# Send a file to the running server via POST
curl -sSX POST --data-binary @deployment.yaml http://localhost:8080/scan

Don't forget to stop the server.

Kubesec-as-a-Service

Kubesec is also available via HTTPS at v2.kubesec.io/scan.

Do not submit sensitive YAML to this public service.

The service is ran on a good faith best effort basis.

# Submit a manifest directly to the hosted v2 API
curl -sSX POST --data-binary @"deployment.yaml" https://v2.kubesec.io/scan

# Parse the API output using jq to return a non-zero exit code if the score is <= 10
curl -sSX POST --data-binary @"deployment.yaml" https://v2.kubesec.io/scan | jq --exit-status '.score > 10'

# Use the "rule" query parameter to scan only specific rules (multiple supported)
curl -sSX POST --data-binary @test/asset/score-0-cap-sys-admin.yml "http://localhost:8080/scan?rule=SeccompAny&rule=ApparmorAny"

You may also define a Bash function, e.g.:

# Define a BASH function
$ kubesec ()
{
    local FILE="${1:-}";
    [[ ! -e "${FILE}" ]] && {
        echo "kubesec: ${FILE}: No such file" >&2;
        return 1
    };
    curl --silent \
      --compressed \
      --connect-timeout 5 \
      -sSX POST \
      --data-binary=@"${FILE}" \
      https://v2.kubesec.io/scan
}


# POST a Kubernetes resource to v2.kubesec.io/scan
$ kubesec ./deployment.yml

# Return non-zero status code is the score is not greater than 10
$ kubesec ./score-9-deployment.yml | jq --exit-status '.score > 10' >/dev/null
# status code 1

Contributing

Check out CONTRIBUTING.md for more information.

Getting Help

If you have any questions about Kubesec and Kubernetes security:

Your feedback is always welcome!


Made with ❤ by ControlPlane