mirror of
https://github.com/mukul975/Anthropic-Cybersecurity-Skills.git
synced 2026-07-15 04:05:17 +03:00
Initial commit - 611 cybersecurity skills across all subdomains
This commit is contained in:
@@ -0,0 +1,187 @@
|
||||
---
|
||||
name: implementing-container-image-minimal-base-with-distroless
|
||||
description: Reduce container attack surface by building application images on Google distroless base images that contain only the application runtime with no shell, package manager, or unnecessary OS utilities.
|
||||
domain: cybersecurity
|
||||
subdomain: container-security
|
||||
tags: [distroless, container-images, minimal-base, attack-surface, docker, security-hardening, supply-chain, kubernetes]
|
||||
version: "1.0"
|
||||
author: mahipal
|
||||
license: MIT
|
||||
---
|
||||
|
||||
# Implementing Container Image Minimal Base with Distroless
|
||||
|
||||
## Overview
|
||||
|
||||
Google distroless images contain only your application and its runtime dependencies, without package managers, shells, or other programs found in standard Linux distributions. By eliminating unnecessary OS components, distroless images achieve up to 95% reduction in attack surface compared to traditional base images like ubuntu or debian. Major projects including Kubernetes itself, Knative, and Tekton use distroless images in production. As of 2025, Docker also offers Hardened Images (DHI) as an open-source alternative for minimal container bases.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Docker 20.10+ or compatible container build tool (Buildah, Kaniko)
|
||||
- Multi-stage Dockerfile knowledge
|
||||
- Application compiled as a static binary or with runtime bundled
|
||||
- Container registry for image storage
|
||||
|
||||
## Available Distroless Images
|
||||
|
||||
| Image | Use Case | Size |
|
||||
|-------|----------|------|
|
||||
| `gcr.io/distroless/static-debian12` | Statically compiled binaries (Go, Rust) | ~2MB |
|
||||
| `gcr.io/distroless/base-debian12` | Dynamically linked binaries needing glibc | ~20MB |
|
||||
| `gcr.io/distroless/cc-debian12` | C/C++ applications needing libstdc++ | ~25MB |
|
||||
| `gcr.io/distroless/java21-debian12` | Java 21 applications | ~220MB |
|
||||
| `gcr.io/distroless/python3-debian12` | Python 3 applications | ~50MB |
|
||||
| `gcr.io/distroless/nodejs22-debian12` | Node.js 22 applications | ~130MB |
|
||||
|
||||
## Multi-Stage Build Patterns
|
||||
|
||||
### Go Application
|
||||
|
||||
```dockerfile
|
||||
# Build stage
|
||||
FROM golang:1.22-bookworm AS builder
|
||||
WORKDIR /app
|
||||
COPY go.mod go.sum ./
|
||||
RUN go mod download
|
||||
COPY . .
|
||||
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /server ./cmd/server
|
||||
|
||||
# Runtime stage - static distroless
|
||||
FROM gcr.io/distroless/static-debian12:nonroot
|
||||
COPY --from=builder /server /server
|
||||
USER nonroot:nonroot
|
||||
ENTRYPOINT ["/server"]
|
||||
```
|
||||
|
||||
### Java Application
|
||||
|
||||
```dockerfile
|
||||
# Build stage
|
||||
FROM maven:3.9-eclipse-temurin-21 AS builder
|
||||
WORKDIR /app
|
||||
COPY pom.xml .
|
||||
RUN mvn dependency:go-offline
|
||||
COPY src ./src
|
||||
RUN mvn package -DskipTests
|
||||
|
||||
# Runtime stage - Java distroless
|
||||
FROM gcr.io/distroless/java21-debian12:nonroot
|
||||
COPY --from=builder /app/target/app.jar /app.jar
|
||||
USER nonroot:nonroot
|
||||
ENTRYPOINT ["java", "-jar", "/app.jar"]
|
||||
```
|
||||
|
||||
### Python Application
|
||||
|
||||
```dockerfile
|
||||
# Build stage
|
||||
FROM python:3.12-bookworm AS builder
|
||||
WORKDIR /app
|
||||
COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir --target=/deps -r requirements.txt
|
||||
COPY . .
|
||||
|
||||
# Runtime stage - Python distroless
|
||||
FROM gcr.io/distroless/python3-debian12:nonroot
|
||||
WORKDIR /app
|
||||
COPY --from=builder /deps /deps
|
||||
COPY --from=builder /app /app
|
||||
ENV PYTHONPATH=/deps
|
||||
USER nonroot:nonroot
|
||||
ENTRYPOINT ["python3", "/app/main.py"]
|
||||
```
|
||||
|
||||
### Node.js Application
|
||||
|
||||
```dockerfile
|
||||
# Build stage
|
||||
FROM node:22-bookworm AS builder
|
||||
WORKDIR /app
|
||||
COPY package*.json ./
|
||||
RUN npm ci --production
|
||||
COPY . .
|
||||
|
||||
# Runtime stage - Node distroless
|
||||
FROM gcr.io/distroless/nodejs22-debian12:nonroot
|
||||
WORKDIR /app
|
||||
COPY --from=builder /app .
|
||||
USER nonroot:nonroot
|
||||
CMD ["server.js"]
|
||||
```
|
||||
|
||||
## Security Benefits
|
||||
|
||||
### Attack Surface Comparison
|
||||
|
||||
| Component | Ubuntu | Alpine | Distroless |
|
||||
|-----------|--------|--------|-----------|
|
||||
| Shell (bash/sh) | Yes | Yes | No |
|
||||
| Package manager | apt | apk | No |
|
||||
| coreutils | Full | BusyBox | No |
|
||||
| curl/wget | Yes | Yes | No |
|
||||
| User management | Yes | Yes | No |
|
||||
| Known CVEs (typical) | 50-200+ | 5-20 | 0-5 |
|
||||
| Image size (base) | ~77MB | ~7MB | ~2-20MB |
|
||||
|
||||
### Security Implications
|
||||
|
||||
- **No shell**: Attackers cannot exec into containers to run commands
|
||||
- **No package manager**: Cannot install additional tools or malware
|
||||
- **No coreutils**: No `cat`, `ls`, `find`, `curl` for reconnaissance
|
||||
- **Minimal CVEs**: Fewer packages means fewer vulnerabilities to patch
|
||||
- **Non-root by default**: `:nonroot` tag runs as UID 65534
|
||||
|
||||
## Debugging Distroless Containers
|
||||
|
||||
Since distroless has no shell, use these techniques for debugging:
|
||||
|
||||
### Debug Image Variant
|
||||
|
||||
```dockerfile
|
||||
# Use debug variant in non-production environments only
|
||||
FROM gcr.io/distroless/base-debian12:debug
|
||||
# Includes busybox shell at /busybox/sh
|
||||
```
|
||||
|
||||
```bash
|
||||
# Exec into debug variant
|
||||
kubectl exec -it pod-name -- /busybox/sh
|
||||
```
|
||||
|
||||
### Ephemeral Debug Containers (Kubernetes 1.25+)
|
||||
|
||||
```bash
|
||||
# Attach a debug container with full tooling
|
||||
kubectl debug -it pod-name --image=busybox:1.36 --target=app-container
|
||||
```
|
||||
|
||||
### Crane/Dive for Image Inspection
|
||||
|
||||
```bash
|
||||
# Inspect image layers without running
|
||||
crane export gcr.io/distroless/static-debian12 - | tar -tf - | head -50
|
||||
|
||||
# Analyze image layers
|
||||
dive gcr.io/distroless/static-debian12
|
||||
```
|
||||
|
||||
## Image Scanning Results
|
||||
|
||||
Typical vulnerability comparison using Trivy:
|
||||
|
||||
```bash
|
||||
# Scan Ubuntu-based image
|
||||
trivy image myapp:ubuntu
|
||||
# Result: 47 vulnerabilities (3 CRITICAL, 12 HIGH)
|
||||
|
||||
# Scan Distroless-based image
|
||||
trivy image myapp:distroless
|
||||
# Result: 2 vulnerabilities (0 CRITICAL, 0 HIGH)
|
||||
```
|
||||
|
||||
## References
|
||||
|
||||
- [GoogleContainerTools/distroless GitHub](https://github.com/GoogleContainerTools/distroless)
|
||||
- [Distroless Images - Docker Documentation](https://docs.docker.com/dhi/core-concepts/distroless/)
|
||||
- [Alpine, Distroless, or Scratch? - Google Cloud](https://medium.com/google-cloud/alpine-distroless-or-scratch-caac35250e0b)
|
||||
- [Docker Hardened Images](https://www.infoq.com/news/2025/12/docker-hardened-images/)
|
||||
@@ -0,0 +1,31 @@
|
||||
# Distroless Migration Assessment Template
|
||||
|
||||
## Application Information
|
||||
| Field | Value |
|
||||
|-------|-------|
|
||||
| Application Name | |
|
||||
| Current Base Image | |
|
||||
| Runtime | |
|
||||
| Target Distroless Image | |
|
||||
|
||||
## Migration Checklist
|
||||
- [ ] Multi-stage Dockerfile created
|
||||
- [ ] Application tested with distroless base
|
||||
- [ ] Image scanned for vulnerabilities (before/after comparison)
|
||||
- [ ] Non-root user configured
|
||||
- [ ] Debug procedures documented
|
||||
- [ ] CI/CD pipeline updated
|
||||
|
||||
## Vulnerability Comparison
|
||||
| Metric | Before | After |
|
||||
|--------|--------|-------|
|
||||
| Image Size | | |
|
||||
| Critical CVEs | | |
|
||||
| High CVEs | | |
|
||||
| Total CVEs | | |
|
||||
|
||||
## Sign-Off
|
||||
| Role | Name | Date |
|
||||
|------|------|------|
|
||||
| Developer | | |
|
||||
| Security Engineer | | |
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
# Standards - Distroless Container Images
|
||||
|
||||
## NIST SP 800-190
|
||||
- Section 3.1.1: Minimize image content to reduce attack surface
|
||||
- Section 4.1.1: Use minimal base images for container builds
|
||||
|
||||
## CIS Docker Benchmark v1.6
|
||||
- 4.1: Ensure a user for the container has been created
|
||||
- 4.2: Ensure containers use trusted base images
|
||||
- 4.6: Ensure HEALTHCHECK instructions have been added
|
||||
- 4.9: Ensure COPY is used instead of ADD
|
||||
|
||||
## OWASP Docker Security
|
||||
- D2: Patch Management Strategies (fewer packages = fewer patches)
|
||||
- D3: Network Segmentation and Firewalling
|
||||
- D4: Secure Defaults and Hardening (no shell = hardened by default)
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
# Workflows - Distroless Container Images
|
||||
|
||||
## Migration Workflow
|
||||
1. Identify current base image and its package footprint
|
||||
2. Select appropriate distroless variant for your runtime
|
||||
3. Create multi-stage Dockerfile with build and runtime stages
|
||||
4. Test application functionality with distroless base
|
||||
5. Scan both old and new images to compare CVE counts
|
||||
6. Update debugging procedures (ephemeral containers, debug variants)
|
||||
7. Deploy to staging and validate
|
||||
8. Roll out to production
|
||||
|
||||
## Image Build Pipeline
|
||||
1. Build application in builder stage (full SDK image)
|
||||
2. Copy only runtime artifacts to distroless stage
|
||||
3. Set non-root user via `:nonroot` tag
|
||||
4. Scan final image with Trivy/Grype
|
||||
5. Sign image with cosign
|
||||
6. Push to registry with digest pinning
|
||||
@@ -0,0 +1,195 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Container Image Base Analysis Tool
|
||||
|
||||
Analyzes container images to identify non-minimal base images and
|
||||
recommends distroless alternatives based on the application runtime.
|
||||
"""
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import argparse
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
DISTROLESS_RECOMMENDATIONS = {
|
||||
"golang": "gcr.io/distroless/static-debian12:nonroot",
|
||||
"go": "gcr.io/distroless/static-debian12:nonroot",
|
||||
"rust": "gcr.io/distroless/static-debian12:nonroot",
|
||||
"java": "gcr.io/distroless/java21-debian12:nonroot",
|
||||
"openjdk": "gcr.io/distroless/java21-debian12:nonroot",
|
||||
"python": "gcr.io/distroless/python3-debian12:nonroot",
|
||||
"node": "gcr.io/distroless/nodejs22-debian12:nonroot",
|
||||
"nodejs": "gcr.io/distroless/nodejs22-debian12:nonroot",
|
||||
"dotnet": "mcr.microsoft.com/dotnet/runtime-deps:8.0-noble-chiseled",
|
||||
"ruby": "gcr.io/distroless/base-debian12:nonroot",
|
||||
"c": "gcr.io/distroless/cc-debian12:nonroot",
|
||||
"cpp": "gcr.io/distroless/cc-debian12:nonroot",
|
||||
}
|
||||
|
||||
BLOATED_BASES = {"ubuntu", "debian", "centos", "fedora", "amazonlinux", "oraclelinux"}
|
||||
|
||||
|
||||
def run_command(cmd: list[str], timeout: int = 60) -> str:
|
||||
try:
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
|
||||
return result.stdout.strip()
|
||||
except (subprocess.TimeoutExpired, FileNotFoundError):
|
||||
return ""
|
||||
|
||||
|
||||
def get_image_info(image: str) -> dict:
|
||||
"""Get image metadata using docker inspect or crane."""
|
||||
output = run_command(["docker", "inspect", image])
|
||||
if output:
|
||||
try:
|
||||
data = json.loads(output)
|
||||
if data:
|
||||
return data[0]
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
return {}
|
||||
|
||||
|
||||
def analyze_image_layers(image: str) -> dict:
|
||||
"""Analyze image layers and size."""
|
||||
info = get_image_info(image)
|
||||
if not info:
|
||||
return {"error": f"Cannot inspect image: {image}"}
|
||||
|
||||
return {
|
||||
"image": image,
|
||||
"size_bytes": info.get("Size", 0),
|
||||
"size_mb": round(info.get("Size", 0) / 1024 / 1024, 1),
|
||||
"layers": len(info.get("RootFS", {}).get("Layers", [])),
|
||||
"os": info.get("Os", ""),
|
||||
"architecture": info.get("Architecture", ""),
|
||||
"user": info.get("Config", {}).get("User", "root"),
|
||||
"entrypoint": info.get("Config", {}).get("Entrypoint", []),
|
||||
"cmd": info.get("Config", {}).get("Cmd", []),
|
||||
"env": info.get("Config", {}).get("Env", []),
|
||||
"has_shell": check_shell_exists(image),
|
||||
}
|
||||
|
||||
|
||||
def check_shell_exists(image: str) -> bool:
|
||||
"""Check if the image contains a shell."""
|
||||
for shell in ["/bin/sh", "/bin/bash", "/bin/dash"]:
|
||||
output = run_command(["docker", "run", "--rm", "--entrypoint", "",
|
||||
image, "test", "-f", shell])
|
||||
# If command succeeds, shell exists
|
||||
output = run_command(["docker", "run", "--rm", "--entrypoint", "",
|
||||
image, "ls", "/bin/sh"], timeout=10)
|
||||
return bool(output)
|
||||
|
||||
|
||||
def scan_vulnerabilities(image: str) -> dict:
|
||||
"""Scan image for vulnerabilities using trivy."""
|
||||
output = run_command(["trivy", "image", "--format", "json", "--quiet", image], timeout=120)
|
||||
if not output:
|
||||
return {"total": -1, "critical": -1, "high": -1, "medium": -1, "low": -1}
|
||||
|
||||
try:
|
||||
data = json.loads(output)
|
||||
counts = {"total": 0, "critical": 0, "high": 0, "medium": 0, "low": 0}
|
||||
for result in data.get("Results", []):
|
||||
for vuln in result.get("Vulnerabilities", []):
|
||||
counts["total"] += 1
|
||||
sev = vuln.get("Severity", "").lower()
|
||||
if sev in counts:
|
||||
counts[sev] += 1
|
||||
return counts
|
||||
except json.JSONDecodeError:
|
||||
return {"total": -1, "critical": -1, "high": -1, "medium": -1, "low": -1}
|
||||
|
||||
|
||||
def recommend_distroless(image: str) -> str:
|
||||
"""Recommend a distroless base image based on current image."""
|
||||
image_lower = image.lower()
|
||||
for runtime, distroless in DISTROLESS_RECOMMENDATIONS.items():
|
||||
if runtime in image_lower:
|
||||
return distroless
|
||||
return "gcr.io/distroless/base-debian12:nonroot"
|
||||
|
||||
|
||||
def analyze_kubernetes_images(namespace: str = "") -> list[dict]:
|
||||
"""Analyze all container images in a Kubernetes cluster."""
|
||||
cmd = ["kubectl", "get", "pods", "-o", "json"]
|
||||
if namespace:
|
||||
cmd.extend(["-n", namespace])
|
||||
else:
|
||||
cmd.append("--all-namespaces")
|
||||
|
||||
output = run_command(cmd)
|
||||
if not output:
|
||||
return []
|
||||
|
||||
images = set()
|
||||
try:
|
||||
data = json.loads(output)
|
||||
for pod in data.get("items", []):
|
||||
for cs in pod.get("status", {}).get("containerStatuses", []):
|
||||
images.add(cs.get("image", ""))
|
||||
except json.JSONDecodeError:
|
||||
return []
|
||||
|
||||
results = []
|
||||
for image in sorted(images):
|
||||
if not image:
|
||||
continue
|
||||
is_distroless = "distroless" in image or "chiseled" in image
|
||||
is_bloated = any(base in image.lower() for base in BLOATED_BASES)
|
||||
|
||||
results.append({
|
||||
"image": image,
|
||||
"is_distroless": is_distroless,
|
||||
"is_bloated_base": is_bloated,
|
||||
"recommendation": "Already minimal" if is_distroless else recommend_distroless(image)
|
||||
})
|
||||
|
||||
return results
|
||||
|
||||
|
||||
def generate_report(results: list[dict], output_format: str = "text") -> str:
|
||||
if output_format == "json":
|
||||
return json.dumps({"timestamp": datetime.utcnow().isoformat(),
|
||||
"results": results}, indent=2)
|
||||
|
||||
lines = ["=" * 70, "CONTAINER IMAGE BASE ANALYSIS REPORT",
|
||||
f"Generated: {datetime.utcnow().isoformat()}", "=" * 70]
|
||||
|
||||
minimal = [r for r in results if r.get("is_distroless")]
|
||||
bloated = [r for r in results if r.get("is_bloated_base")]
|
||||
lines.append(f"\nImages Analyzed: {len(results)}")
|
||||
lines.append(f"Minimal/Distroless: {len(minimal)}")
|
||||
lines.append(f"Bloated Base: {len(bloated)}")
|
||||
|
||||
if bloated:
|
||||
lines.append("\n## Images Needing Migration")
|
||||
for r in bloated:
|
||||
lines.append(f" {r['image']}")
|
||||
lines.append(f" Recommended: {r['recommendation']}")
|
||||
|
||||
lines.append("\n" + "=" * 70)
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Container Image Base Analyzer")
|
||||
parser.add_argument("--image", help="Analyze a specific image")
|
||||
parser.add_argument("--namespace", default="", help="K8s namespace to scan")
|
||||
parser.add_argument("--format", choices=["text", "json"], default="text")
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.image:
|
||||
info = analyze_image_layers(args.image)
|
||||
info["recommendation"] = recommend_distroless(args.image)
|
||||
print(generate_report([info], args.format))
|
||||
else:
|
||||
results = analyze_kubernetes_images(args.namespace)
|
||||
print(generate_report(results, args.format))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user