
Análisis de riesgos de seguridad para recursos de Kubernetes
Para más ejemplos visita Kubesec.io, que utiliza la API alojada de ControlPlane en v2.kubesec.io/scan.
Crea un archivo de recurso de Kubernetes (p. ej., kubesec-test.yaml) para escanear. Para una prueba rápida, puedes guardar el siguiente manifiesto de Pod:
$ 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
Ejecuta un escaneo contra tu archivo de manifiesto:
# 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] Para ver los resultados en una tabla legible en lugar del formato JSON predeterminado, usa la opción
--format table
kubesec generará una puntuación de seguridad y un análisis detallado de tu recurso.
Kubesec está disponible como:
docker.io/kubesec/kubesec:v2O instala el último commit desde GitHub con:
$ go install github.com/controlplaneio/kubesec/v2@latest
$ GO111MODULE="on" go get github.com/controlplaneio/kubesec/v2
Escanea recursos de Kubernetes desde archivos locales o desde la entrada estándar.
Kubesec puede escanear múltiples documentos YAML en un solo archivo de entrada, o escanear documentos de varios archivos a la vez, siempre que estén formateados correctamente como múltiples documentos separados por ---.
# 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 -
Puedes ejecutar los mismos comandos de escaneo usando la imagen oficial de Docker:
# Scan a file via Docker using standard input
docker run -i kubesec/kubesec:v2 scan /dev/stdin < kubesec-test.yaml
Kubesec admite tres formatos de salida diferentes, especificados mediante la opción --format / -f: json (predeterminado), table y template, y puede escanear múltiples documentos YAML en un solo archivo de entrada.
# 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
# One rule
kubesec scan --rules CapSysAdmin kubesec-test.yaml
# Multiple rules
kubesec scan --rules RunAsNonRoot,SeccompAny,ApparmorAny kubesec-test.yaml
[
{
"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
},
{
// ...
}
]
}
}
]

# 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
[
{
"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
},
...
]
Kubesec utiliza kubeconform (gracias a @yannh) para validar los manifiestos a escanear. Esto implica que especificar diferentes ubicaciones de esquemas sigue las reglas descritas en el README de kubeconform.
# 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
Nota: para limitar las llamadas de red externas y permitir su uso en entornos airgap, la imagen kubesec incluye esquemas integrados. Si deseas cambiar la ubicación de los esquemas, deberás cambiar las variables de entorno K8S_SCHEMA_VER y SCHEMA_LOCATION en tiempo de ejecución.
Kubesec incluye un servidor HTTP integrado que puedes ejecutar localmente o en un contenedor para aceptar solicitudes de escaneo a través de la red.
# 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 %
# 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
No olvides detener el servidor.
Kubesec también está disponible mediante HTTPS en v2.kubesec.io/scan.
No envíes YAML sensible a este servicio público.
El servicio se ofrece de buena fe y con el mejor esfuerzo posible.
# 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"
También puedes definir una función de Bash, por ejemplo:
# 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
Consulta CONTRIBUTING.md para obtener más información.
Si tienes alguna pregunta sobre Kubesec y la seguridad en Kubernetes:
¡Tus comentarios siempre son bienvenidos!
Hecho con ❤ por ControlPlane