[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M78BF55Q1T26VXTZ69SRDPW3":3,"skill-same:01M78BF55Q1T26VXTZ69SRDPW3":64},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":29,"commitSha":30,"skillDirectory":31,"forksCount":14,"repositoryHtmlUrl":32,"repositoryHomepageUrl":33,"ownerHtmlUrl":34,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":35,"install":36,"resources":49},"01M78BF55Q1T26VXTZ69SRDPW3","container-security-hardening",null,"Harden Docker\u002Fcontainer images and runtime deployments with secure base images, non-root users, CVE scanning, SBOM\u002Fsigning, seccomp\u002FAppArmor, and Kubernetes pod security controls. Use for Dockerfile security reviews, container CVEs, image scanning, distroless images, or production hardening.","princepatel04477-web\u002Ftrivoxa-group","princepatel04477-web","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F227740714?v=4","01M788ZAJ2KECD5KXVP55PZXKS","Prince Patel","01M788ZAJTCN8YSD737MRSKC5Q",0,"MIT","https:\u002F\u002Fgithub.com\u002Fprincepatel04477-web\u002Ftrivoxa-group\u002Fblob\u002Fmaster\u002F.github\u002Fskills\u002Fcontainer-security-hardening\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: container-security-hardening\ndescription: >\n  Harden Docker\u002Fcontainer images and runtime deployments with secure base images,\n  non-root users, CVE scanning, SBOM\u002Fsigning, seccomp\u002FAppArmor, and Kubernetes\n  pod security controls. Use for Dockerfile security reviews, container CVEs,\n  image scanning, distroless images, or production hardening.\ncategory: security\nrisk: safe\nsource: community\ndate_added: \"2026-05-30\"\n---\n\n# Container Security Hardening Skill\n\nA production-focused guide for building, scanning, and running containers securely — from Dockerfile authoring through runtime enforcement and supply chain integrity.\n\n---\n\n## When to Use This Skill\n\n- User mentions Docker security, container hardening, or Dockerfile security review\n- User asks about distroless images, non-root containers, or read-only filesystems\n- User wants to scan images for CVEs with Trivy, Grype, or Snyk\n- User mentions seccomp, AppArmor, Linux capabilities, or runtime security\n- User asks \"is my Dockerfile secure?\" or \"how do I reduce my image attack surface?\"\n- User wants to sign\u002Fverify images with Cosign or generate SBOMs\n- User asks about Kubernetes pod security, NetworkPolicy, or RBAC hardening\n- User says \"fix container CVEs\" or \"harden my container for production\"\n\n## When NOT to Use This Skill\n\n- The user is primarily asking about GitHub Actions CI\u002FCD → recommend `github-actions-advanced`\n- The user needs general Docker usage help (not security) → recommend `docker-expert`\n- The user is working with Kubernetes orchestration beyond security → recommend `kubernetes-architect`\n- The user needs application-level security (SQL injection, XSS) → recommend `api-security-best-practices`\n\n---\n\n## Step 1: Understand Context Before Responding\n\nWhen invoked, first detect the current state:\n\n```bash\n# Find Dockerfiles in the project\nfind . -name \"Dockerfile*\" -not -path \"*\u002Fnode_modules\u002F*\" | head -10\n\n# Check for existing security tooling\nls .trivyignore .hadolint.yaml .snyk docker-compose*.yml 2>\u002Fdev\u002Fnull\n\n# Inspect base images currently in use\ngrep -r \"^FROM\" $(find . -name \"Dockerfile*\") 2>\u002Fdev\u002Fnull\n\n# Check if Kubernetes manifests exist\nfind . -name \"*.yaml\" -path \"*\u002Fk8s\u002F*\" -o -name \"*.yaml\" -path \"*\u002Fmanifests\u002F*\" | head -10\n```\n\nThen adapt recommendations to:\n- The tech stack (Node, Python, Go, Java — affects base image choice)\n- Whether this is Docker-only or Kubernetes-deployed\n- The CI platform in use (for scanner integration)\n- The existing base images and how far they are from best practice\n\n---\n\n## The Five Layers of Container Security\n\n```\n1. Image Build        → Minimal base, no secrets, non-root, read-only FS\n2. Image Scanning     → CVE scanning, SBOM, secret detection, Dockerfile lint\n3. Runtime Security   → Capabilities, seccomp, AppArmor, resource limits\n4. Supply Chain       → Signed images, pinned digests, trusted registries\n5. Kubernetes Layer   → Pod Security Admission, NetworkPolicy, RBAC, Kyverno\n```\n\n> Work through layers in order — hardening the image first gives the most leverage.\n> See `references\u002Fbase-image-comparison.md` for a full size\u002FCVE trade-off table.\n\n---\n\n## Layer 1: Dockerfile Hardening\n\n### 1.1 Use a Minimal Base Image\n\n```dockerfile\n# ❌ AVOID — massive attack surface (~100–200 CVEs typical)\nFROM ubuntu:latest\nFROM node:20\n\n# ✅ BETTER — slim variants (glibc, smaller apt footprint)\nFROM node:20-slim\nFROM python:3.12-slim\n\n# ✅ BEST — distroless (no shell, no package manager, built-in nonroot user)\nFROM gcr.io\u002Fdistroless\u002Fnodejs20-debian12\nFROM gcr.io\u002Fdistroless\u002Fpython3-debian12\nFROM gcr.io\u002Fdistroless\u002Fstatic-debian12   # Go\u002FRust fully-static binaries\n\n# ✅ ALSO GREAT — Alpine (musl libc; verify app compatibility first)\nFROM alpine:3.20\n\n# ✅ ZERO ATTACK SURFACE — for fully static binaries only\nFROM scratch\n```\n\nSee `references\u002Fbase-image-comparison.md` for the full trade-off matrix.\n\n### 1.2 Multi-Stage Build — Separate Build from Runtime\n\nNever ship build tools, compilers, or dev dependencies in a production image.\n\n```dockerfile\n# syntax=docker\u002Fdockerfile:1\n\n# ── Stage 1: Install & Build ──────────────────────────────\nFROM node:20-slim AS builder\nWORKDIR \u002Fbuild\nCOPY package*.json .\u002F\nRUN npm ci                          # Install all deps (including devDeps)\nCOPY . .\nRUN npm run build && npm prune --production\n\n# ── Stage 2: Runtime — minimal, no build tools ────────────\nFROM gcr.io\u002Fdistroless\u002Fnodejs20-debian12@sha256:\u003Cdigest>\nLABEL org.opencontainers.image.source=\"https:\u002F\u002Fgithub.com\u002Forg\u002Frepo\"\nLABEL org.opencontainers.image.revision=\"${BUILD_SHA}\"\nLABEL org.opencontainers.image.licenses=\"MIT\"\nWORKDIR \u002Fapp\nCOPY --from=builder --chown=nonroot:nonroot \u002Fbuild\u002Fdist        .\u002Fdist\nCOPY --from=builder --chown=nonroot:nonroot \u002Fbuild\u002Fnode_modules .\u002Fnode_modules\nUSER nonroot:nonroot                # UID 65532 — built into distroless\nEXPOSE 3000\nCMD [\"dist\u002Fserver.js\"]\n```\n\n**Go \u002F Rust static binary pattern:**\n```dockerfile\nFROM golang:1.22-alpine AS builder\nWORKDIR \u002Fbuild\nCOPY go.* .\u002F\nRUN go mod download\nCOPY . .\nRUN CGO_ENABLED=0 GOOS=linux go build -ldflags=\"-s -w\" -o app .\n\nFROM scratch                        # Zero attack surface\nCOPY --from=builder \u002Fetc\u002Fssl\u002Fcerts\u002Fca-certificates.crt \u002Fetc\u002Fssl\u002Fcerts\u002F\nCOPY --from=builder \u002Fbuild\u002Fapp \u002Fapp\nUSER 65532:65532\nENTRYPOINT [\"\u002Fapp\"]\n```\n\n### 1.3 Run as Non-Root User\n\n```dockerfile\n# For debian\u002Fubuntu-based images — create dedicated user\nRUN groupadd -r appgroup --gid 10001 && \\\n    useradd -r -g appgroup --uid 10001 --no-log-init appuser\n\nCOPY --chown=appuser:appgroup . \u002Fapp\n\nUSER appuser    # Switch before CMD\u002FENTRYPOINT — never run as root\n\n# ─────────────────────────────────────────────────────────\n# For Alpine-based images\nRUN addgroup -g 10001 -S appgroup && \\\n    adduser -u 10001 -S appuser -G appgroup\n\n# For distroless — nonroot (UID 65532) is already built in\nUSER nonroot:nonroot\n```\n\n### 1.4 Pin Base Images to Digest\n\n```dockerfile\n# ❌ UNSAFE — tags are mutable; image can be silently overwritten (supply chain attack)\nFROM node:20-slim\n\n# ✅ SAFE — SHA256 digest is cryptographically immutable\nFROM node:20-slim@sha256:a1b2c3d4e5f6789abcdef0123456789abcdef0123456789abcdef0123456789ab\n```\n\n**Get the current digest:**\n```bash\ndocker pull node:20-slim\ndocker inspect node:20-slim --format='{{index .RepoDigests 0}}'\n```\n\n**Automate digest pinning** with Renovate or Dependabot:\n```json\n\u002F\u002F .renovaterc.json\n{\n  \"extends\": [\"config:base\"],\n  \"dockerfile\": { \"enabled\": true },\n  \"pinDigests\": true\n}\n```\n\n### 1.5 Never Bake Secrets into Images\n\n```dockerfile\n# ❌ NEVER — secret in ENV or RUN; visible in `docker history` and layer cache\nENV AWS_SECRET_ACCESS_KEY=supersecret\nRUN curl -H \"Authorization: Bearer $TOKEN\" https:\u002F\u002Fapi.example.com > config.json\nARG API_KEY                         # Also unsafe — visible in build args history\n\n# ✅ CORRECT — BuildKit secret mount (never persisted in any layer)\n# syntax=docker\u002Fdockerfile:1\nRUN --mount=type=secret,id=api_token \\\n    curl -H \"Authorization: Bearer $(cat \u002Frun\u002Fsecrets\u002Fapi_token)\" \\\n    https:\u002F\u002Fapi.example.com\u002Fconfig > config.json\n```\n\nBuild with: `docker build --secret id=api_token,src=.\u002Ftoken.txt .`\n\n**Check your image for leaked secrets:**\n```bash\ndocker history --no-trunc myapp:latest | grep -iE \"secret|key|password|token\"\ntrivy image --scanners secret myapp:latest\n```\n\n### 1.6 Read-Only Filesystem & No New Privileges\n\n```dockerfile\n# In the Dockerfile — use exec form (no shell interpretation)\nENTRYPOINT [\"node\", \"server.js\"]    # ✅ exec form\n# ENTRYPOINT \u002Fbin\u002Fsh -c \"node...\"  # ❌ shell form — spawns extra process\n\n# Define a HEALTHCHECK\nHEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \\\n  CMD [\"node\", \"-e\", \"require('http').get('http:\u002F\u002Flocalhost:3000\u002Fhealth', r => process.exit(r.statusCode === 200 ? 0 : 1))\"]\n```\n\nEnforce read-only at runtime (see Layer 3).\n\n### 1.7 Minimal .dockerignore\n\n```dockerignore\n# Always exclude these from build context\n.git\n.github\n.env\n.env.*\n*.pem\n*.key\nnode_modules\n__pycache__\n.pytest_cache\ncoverage\u002F\ndist\u002F\n*.log\n.DS_Store\nDockerfile*\ndocker-compose*\nREADME.md\ndocs\u002F\ntests\u002F\n```\n\n### 1.8 Full Hardened Dockerfile Example\n\n```dockerfile\n# syntax=docker\u002Fdockerfile:1\n\n# ── Build stage ───────────────────────────────────────────\nFROM node:20-slim AS builder\nWORKDIR \u002Fbuild\nCOPY package*.json .\u002F\nRUN --mount=type=cache,target=\u002Froot\u002F.npm \\\n    npm ci\nCOPY . .\nRUN npm run build && npm prune --production\n\n# ── Runtime stage ─────────────────────────────────────────\nFROM gcr.io\u002Fdistroless\u002Fnodejs20-debian12@sha256:\u003Cpin-digest-here>\n\nLABEL org.opencontainers.image.source=\"https:\u002F\u002Fgithub.com\u002Forg\u002Frepo\"\nLABEL org.opencontainers.image.revision=\"${BUILD_SHA}\"\nLABEL org.opencontainers.image.licenses=\"MIT\"\n\nWORKDIR \u002Fapp\nCOPY --from=builder --chown=nonroot:nonroot \u002Fbuild\u002Fdist        .\u002Fdist\nCOPY --from=builder --chown=nonroot:nonroot \u002Fbuild\u002Fnode_modules .\u002Fnode_modules\n\nUSER nonroot:nonroot\nEXPOSE 3000\n\nHEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \\\n  CMD [\"node\", \"-e\", \"require('http').get('http:\u002F\u002Flocalhost:3000\u002Fhealth', r => process.exit(r.statusCode===200?0:1))\"]\n\nCMD [\"dist\u002Fserver.js\"]\n```\n\n---\n\n## Layer 2: Image Scanning\n\n### 2.1 Trivy (Recommended — Fast, Comprehensive)\n\n```bash\n# Install\nbrew install trivy                              # macOS\napt install trivy                               # Debian\u002FUbuntu\ntmpdir=\"$(mktemp -d)\"\ntrap 'rm -rf \"$tmpdir\"' EXIT\ncurl -sfL https:\u002F\u002Fraw.githubusercontent.com\u002Faquasecurity\u002Ftrivy\u002Fmain\u002Fcontrib\u002Finstall.sh \\\n  -o \"$tmpdir\u002Ftrivy-install.sh\"\nsed -n '1,160p' \"$tmpdir\u002Ftrivy-install.sh\"\nsh \"$tmpdir\u002Ftrivy-install.sh\"\n\n# Scan an image for CVEs\ntrivy image myapp:latest\n\n# Fail CI on HIGH\u002FCRITICAL severity\ntrivy image --exit-code 1 --severity HIGH,CRITICAL myapp:latest\n\n# Scan Dockerfile for misconfigurations\ntrivy config .\u002FDockerfile\n\n# Scan entire repo (vulnerabilities + secrets + misconfigs)\ntrivy fs --scanners vuln,secret,misconfig .\n\n# Generate SBOM (CycloneDX or SPDX)\ntrivy image --format cyclonedx --output sbom.json myapp:latest\ntrivy image --format spdx-json  --output sbom.spdx.json myapp:latest\n\n# Ignore specific CVEs (add justification comments)\ntrivy image --ignorefile .trivyignore myapp:latest\n```\n\n**.trivyignore example:**\n```\n# CVE-2023-1234 — only exploitable via X feature, not used in this app\nCVE-2023-1234\n\n# CVE-2023-5678 — fix not yet available; tracked in issue #42\nCVE-2023-5678\n```\n\n### 2.2 Grype (Anchore Alternative)\n\n```bash\n# Install\ntmpdir=\"$(mktemp -d)\"\ntrap 'rm -rf \"$tmpdir\"' EXIT\ncurl -sSfL https:\u002F\u002Fraw.githubusercontent.com\u002Fanchore\u002Fgrype\u002Fmain\u002Finstall.sh \\\n  -o \"$tmpdir\u002Fgrype-install.sh\"\nsed -n '1,160p' \"$tmpdir\u002Fgrype-install.sh\"\nsh \"$tmpdir\u002Fgrype-install.sh\"\n\n# Scan image\ngrype myapp:latest\n\n# Fail on critical\ngrype myapp:latest --fail-on critical\n\n# Output SARIF for GitHub Security tab\ngrype myapp:latest -o sarif > results.sarif\n\n# Pair with Syft for SBOM generation\nsyft myapp:latest -o cyclonedx-json > sbom.json\ngrype sbom:sbom.json                            # Scan the SBOM directly\n```\n\n### 2.3 Hadolint — Dockerfile Linting\n\n```bash\n# Run directly\ndocker run --rm -i hadolint\u002Fhadolint \u003C Dockerfile\n\n# With config file\nhadolint --config .hadolint.yaml --failure-threshold warning Dockerfile\n```\n\n**.hadolint.yaml:**\n```yaml\nfailure-threshold: warning\nignore:\n  - DL3008   # Pin versions in apt-get (allow floating for base layer)\ntrustedRegistries:\n  - gcr.io\n  - ghcr.io\n  - public.ecr.aws\n```\n\n### 2.4 Secret Scanning in Images\n\n```bash\n# Trivy covers secrets too\ntrivy image --scanners secret myapp:latest\n\n# Dedicated: TruffleHog\ntrufflehog docker --image myapp:latest\n\n# git-secrets to prevent committing secrets\ngit secrets --scan\n```\n\n### 2.5 CI Integration (GitHub Actions — SHA-Pinned)\n\n```yaml\npermissions:\n  contents: read\n  security-events: write      # Required for uploading SARIF\n\njobs:\n  security-scan:\n    runs-on: ubuntu-24.04\n    timeout-minutes: 20\n    steps:\n      - uses: actions\u002Fcheckout@11bd71901bbe5b1630ceea73d27597364c9af683  # v4.2.2\n\n      - name: Build image\n        run: docker build -t myapp:${{ github.sha }} .\n\n      - name: Lint Dockerfile\n        uses: hadolint\u002Fhadolint-action@54c9adbab1582c2ef04b2016b760714a4bfde3cf  # v3.1.0\n        with:\n          dockerfile: Dockerfile\n          failure-threshold: warning\n\n      - name: Scan with Trivy\n        uses: aquasecurity\u002Ftrivy-action@6e7b7d1fd3e4fef0c5fa8cce1229c54b2c9bd0d8  # v0.28.0\n        with:\n          image-ref: myapp:${{ github.sha }}\n          format: sarif\n          output: trivy-results.sarif\n          severity: HIGH,CRITICAL\n          exit-code: '1'\n\n      - name: Upload results to GitHub Security tab\n        uses: github\u002Fcodeql-action\u002Fupload-sarif@4f3212b61783c3c68e8309a0f18a699764811cda  # v3.27.1\n        if: always()          # Upload even if scan found issues\n        with:\n          sarif_file: trivy-results.sarif\n```\n\n---\n\n## Layer 3: Runtime Security\n\n### 3.1 docker run Hardening Flags\n\n```bash\ndocker run \\\n  --read-only \\                              # Read-only root filesystem\n  --tmpfs \u002Ftmp:noexec,nosuid,size=100m \\     # Writable tmpfs for \u002Ftmp only\n  --tmpfs \u002Fvar\u002Frun \\                         # For PID files if needed\n  --user 10001:10001 \\                       # Non-root UID:GID\n  --cap-drop ALL \\                           # Drop ALL Linux capabilities\n  --cap-add NET_BIND_SERVICE \\               # Re-add only what's truly needed\n  --security-opt no-new-privileges:true \\    # Prevent privilege escalation via setuid\n  --security-opt seccomp=seccomp.json \\      # Custom seccomp profile\n  --security-opt apparmor=docker-default \\   # AppArmor profile\n  --pids-limit 100 \\                         # Prevent fork bombs\n  --memory 512m \\                            # OOM protection\n  --memory-swap 512m \\                       # Disable swap\n  --cpus 1.0 \\                               # CPU limit\n  --network none \\                           # No network (if not needed)\n  --health-cmd \"curl -f http:\u002F\u002Flocalhost:3000\u002Fhealth || exit 1\" \\\n  --health-interval 30s \\\n  myapp:latest\n```\n\n### 3.2 Linux Capabilities — What to Drop and Keep\n\nDrop ALL, then explicitly add only what your app requires:\n\n| Capability | Purpose | Keep? |\n|---|---|---|\n| `NET_BIND_SERVICE` | Bind ports \u003C 1024 | Only if binding a privileged port |\n| `CHOWN` | Change file ownership | No — set ownership at build time |\n| `SETUID` \u002F `SETGID` | Switch user identity | No — drop always |\n| `SYS_ADMIN` | Broad privileged operations | No — most dangerous capability |\n| `NET_ADMIN` | Configure network interfaces | No (only network tools) |\n| `SYS_PTRACE` | Debug\u002Ftrace processes | No (only debugger containers) |\n| `DAC_OVERRIDE` | Override file permissions | No — runs as correct user |\n| `NET_RAW` | Raw sockets (ping) | No (blocked by default seccomp anyway) |\n\n> **Most web apps need zero capabilities.** `--cap-drop ALL` alone is often sufficient.\n\n### 3.3 Docker Compose Hardening\n\n```yaml\nservices:\n  app:\n    image: myapp:latest\n    read_only: true\n    user: \"10001:10001\"\n    tmpfs:\n      - \u002Ftmp:noexec,nosuid,size=100m\n      - \u002Fvar\u002Frun:noexec,nosuid,size=10m\n    cap_drop:\n      - ALL\n    cap_add:\n      - NET_BIND_SERVICE    # Only if binding port \u003C 1024\n    security_opt:\n      - no-new-privileges:true\n      - seccomp:.\u002Freferences\u002Fseccomp-profile-template.json\n    pids_limit: 100\n    mem_limit: 512m\n    memswap_limit: 512m\n    cpus: 1.0\n    healthcheck:\n      test: [\"CMD\", \"curl\", \"-f\", \"http:\u002F\u002Flocalhost:3000\u002Fhealth\"]\n      interval: 30s\n      timeout: 5s\n      retries: 3\n      start_period: 10s\n    networks:\n      - backend\n    # Only expose externally if truly required\n    # ports: [\"8080:8080\"]\n    restart: unless-stopped\n    logging:\n      driver: json-file\n      options:\n        max-size: \"10m\"\n        max-file: \"3\"\n\nnetworks:\n  backend:\n    driver: bridge\n    internal: true    # No external connectivity unless needed\n```\n\n### 3.4 Seccomp Profiles\n\nThe Docker default seccomp profile blocks ~44 dangerous syscalls. For stricter control:\n\n```bash\n# Step 1: Audit syscalls your app actually makes\ndocker run --security-opt seccomp=unconfined \\\n  --name audit-run myapp:latest &\n\n# Capture with strace\nstrace -c -p $(docker inspect --format '{{.State.Pid}}' audit-run)\n\n# Or with sysdig (more container-friendly)\nsysdig -p \"%syscall.type\" container.name=audit-run | sort -u\n\n# Step 2: Build a custom profile from references\u002Fseccomp-profile-template.json\n# Step 3: Apply it\ndocker run --security-opt seccomp=references\u002Fseccomp-profile-template.json myapp:latest\n```\n\nSee `references\u002Fseccomp-profile-template.json` for a minimal starting allowlist for typical web servers.\n\n### 3.5 AppArmor Profile (Linux hosts)\n\n```bash\n# Load Docker's default AppArmor profile\nsudo apparmor_parser -r \u002Fetc\u002Fapparmor.d\u002Fdocker-default\n\n# Apply at runtime\ndocker run --security-opt apparmor=docker-default myapp:latest\n\n# Generate a custom profile\naa-genprof myapp   # Interactive — run app under aa-complain mode first\n```\n\n---\n\n## Layer 4: Supply Chain Security\n\n### 4.1 Sign Images with Cosign (Sigstore — Keyless)\n\n```bash\n# Install cosign\nbrew install cosign    # macOS\n# or: https:\u002F\u002Fgithub.com\u002Fsigstore\u002Fcosign\u002Freleases\n\n# Sign after push — keyless via OIDC (no long-lived keys)\ncosign sign ghcr.io\u002Forg\u002Fmyapp:latest\n\n# Verify before deploy\ncosign verify ghcr.io\u002Forg\u002Fmyapp:latest \\\n  --certificate-identity-regexp=\"https:\u002F\u002Fgithub.com\u002Forg\u002Frepo\" \\\n  --certificate-oidc-issuer=\"https:\u002F\u002Ftoken.actions.githubusercontent.com\"\n```\n\n**GitHub Actions — Sign & Verify Pipeline:**\n```yaml\npermissions:\n  id-token: write     # Required for OIDC keyless signing\n  packages: write\n\nsteps:\n  - uses: sigstore\u002Fcosign-installer@dc72c7d5c4d10cd6bcb8cf6e3fd625a9e5e537da  # v3.7.0\n\n  - name: Sign image (keyless via OIDC)\n    run: |\n      cosign sign --yes \\\n        ghcr.io\u002F${{ github.repository }}:${{ github.sha }}\n    env:\n      COSIGN_EXPERIMENTAL: \"true\"\n\n  - name: Attach SBOM attestation\n    run: |\n      cosign attest --yes \\\n        --predicate sbom.json \\\n        --type cyclonedx \\\n        ghcr.io\u002F${{ github.repository }}:${{ github.sha }}\n```\n\n### 4.2 SBOM Generation & Attestation\n\n```bash\n# Generate SBOM with Syft\nsyft myapp:latest -o cyclonedx-json > sbom.json\nsyft myapp:latest -o spdx-json > sbom.spdx.json\n\n# Attach to image as attestation\ncosign attest --predicate sbom.json --type cyclonedx ghcr.io\u002Forg\u002Fmyapp:latest\n\n# Verify SBOM attestation before deployment\ncosign verify-attestation \\\n  --type cyclonedx \\\n  --certificate-identity-regexp=\"https:\u002F\u002Fgithub.com\u002Forg\u002Frepo\" \\\n  --certificate-oidc-issuer=\"https:\u002F\u002Ftoken.actions.githubusercontent.com\" \\\n  ghcr.io\u002Forg\u002Fmyapp:latest\n```\n\n### 4.3 Use Trusted Registries & Enable Registry Scanning\n\n| Registry | Built-in Scanning | Notes |\n|---|---|---|\n| GHCR (GitHub Container Registry) | No (use Trivy in CI) | Best for OSS, OIDC auth |\n| AWS ECR | Yes (enhanced scanning via Inspector) | Enable per-repo |\n| GCP Artifact Registry | Yes (Container Analysis) | Enabled by default |\n| Azure ACR | Yes (Defender for Containers) | Premium tier |\n| Docker Hub | Yes (limited on free tier) | Avoid for private images |\n\n```bash\n# Enable ECR enhanced scanning\naws ecr put-registry-scanning-configuration \\\n  --scan-type ENHANCED \\\n  --rules '[{\"repositoryFilters\":[{\"filter\":\"*\",\"filterType\":\"WILDCARD\"}],\"scanFrequency\":\"CONTINUOUS_SCAN\"}]'\n```\n\n### 4.4 Admission Control — Block Unsigned\u002FUnscanned Images\n\n```yaml\n# Kyverno policy — require signed images before admission\napiVersion: kyverno.io\u002Fv1\nkind: ClusterPolicy\nmetadata:\n  name: require-signed-images\nspec:\n  validationFailureAction: Enforce\n  rules:\n    - name: verify-image-signature\n      match:\n        resources:\n          kinds: [Pod]\n      verifyImages:\n        - imageReferences:\n            - \"ghcr.io\u002Forg\u002F*\"\n          attestors:\n            - entries:\n                - keyless:\n                    subject: \"https:\u002F\u002Fgithub.com\u002Forg\u002Frepo\u002F.github\u002Fworkflows\u002F*\"\n                    issuer: \"https:\u002F\u002Ftoken.actions.githubusercontent.com\"\n```\n\n---\n\n## Layer 5: Kubernetes Pod Security\n\n> Full reference: `references\u002Fkubernetes-pod-security.md`\n\n### 5.1 Pod Security Context\n\n```yaml\napiVersion: apps\u002Fv1\nkind: Deployment\nmetadata:\n  name: myapp\n  namespace: production\nspec:\n  replicas: 3\n  template:\n    spec:\n      # ── Pod-level security context ─────────────────────\n      securityContext:\n        runAsNonRoot: true\n        runAsUser: 10001\n        runAsGroup: 10001\n        fsGroup: 10001\n        fsGroupChangePolicy: OnRootMismatch\n        seccompProfile:\n          type: RuntimeDefault    # Use containerd\u002Frunc default seccomp\n        supplementalGroups: []\n\n      automountServiceAccountToken: false   # Disable unless needed\n\n      # ── Container-level security context ──────────────\n      containers:\n        - name: app\n          image: ghcr.io\u002Forg\u002Fmyapp@sha256:\u003Cdigest>   # Always use digest\n          securityContext:\n            allowPrivilegeEscalation: false\n            readOnlyRootFilesystem: true\n            capabilities:\n              drop: [\"ALL\"]\n              add: []              # Add nothing unless absolutely required\n            runAsNonRoot: true\n            runAsUser: 10001\n            seccompProfile:\n              type: RuntimeDefault\n\n          # ── Resource limits (required for restricted PSA) ──\n          resources:\n            requests:\n              memory: \"128Mi\"\n              cpu: \"100m\"\n            limits:\n              memory: \"512Mi\"\n              cpu: \"500m\"\n\n          # ── Writable tmpfs mounts ──────────────────────\n          volumeMounts:\n            - name: tmp\n              mountPath: \u002Ftmp\n            - name: varrun\n              mountPath: \u002Fvar\u002Frun\n\n      volumes:\n        - name: tmp\n          emptyDir:\n            medium: Memory\n            sizeLimit: 100Mi\n        - name: varrun\n          emptyDir:\n            medium: Memory\n            sizeLimit: 10Mi\n```\n\n### 5.2 Pod Security Admission (K8s 1.25+)\n\n```bash\n# Audit existing workloads before enforcing\nkubectl label namespace production \\\n  pod-security.kubernetes.io\u002Faudit=restricted \\\n  pod-security.kubernetes.io\u002Faudit-version=latest\n\n# Warn in staging, enforce in production\nkubectl label namespace staging \\\n  pod-security.kubernetes.io\u002Fwarn=restricted\n\nkubectl label namespace production \\\n  pod-security.kubernetes.io\u002Fenforce=restricted \\\n  pod-security.kubernetes.io\u002Fenforce-version=latest\n```\n\n| PSA Level | What It Blocks |\n|---|---|\n| `privileged` | No restrictions |\n| `baseline` | Blocks hostNetwork, hostPID, privileged containers, hostPath |\n| `restricted` | Also requires non-root, read-only FS, drops capabilities, seccomp |\n\n### 5.3 NetworkPolicy — Zero-Trust Networking\n\n```yaml\n# Step 1: Deny all ingress and egress by default in the namespace\napiVersion: networking.k8s.io\u002Fv1\nkind: NetworkPolicy\nmetadata:\n  name: default-deny-all\n  namespace: production\nspec:\n  podSelector: {}\n  policyTypes: [Ingress, Egress]\n\n---\n# Step 2: Selectively allow only required traffic\napiVersion: networking.k8s.io\u002Fv1\nkind: NetworkPolicy\nmetadata:\n  name: allow-app\n  namespace: production\nspec:\n  podSelector:\n    matchLabels:\n      app: myapp\n  policyTypes: [Ingress, Egress]\n  ingress:\n    - from:\n        - namespaceSelector:\n            matchLabels:\n              kubernetes.io\u002Fmetadata.name: ingress-nginx\n          podSelector:\n            matchLabels:\n              app.kubernetes.io\u002Fname: ingress-nginx\n      ports:\n        - port: 3000\n  egress:\n    - to:\n        - podSelector:\n            matchLabels:\n              app: postgres\n      ports:\n        - port: 5432\n    - to:                 # Allow only cluster DNS\n        - namespaceSelector:\n            matchLabels:\n              kubernetes.io\u002Fmetadata.name: kube-system\n          podSelector:\n            matchLabels:\n              k8s-app: kube-dns\n      ports:\n        - port: 53\n          protocol: UDP\n        - port: 53\n          protocol: TCP\n```\n\n### 5.4 RBAC — Least Privilege\n\n```yaml\n# Create minimal role — never use wildcards\napiVersion: rbac.authorization.k8s.io\u002Fv1\nkind: Role\nmetadata:\n  name: app-reader\n  namespace: production\nrules:\n  - apiGroups: [\"\"]\n    resources: [\"configmaps\", \"secrets\"]\n    resourceNames: [\"myapp-config\"]    # Lock to specific resource names\n    verbs: [\"get\"]                     # Never [\"*\"]\n\n---\napiVersion: rbac.authorization.k8s.io\u002Fv1\nkind: RoleBinding\nmetadata:\n  name: app-reader-binding\n  namespace: production\nsubjects:\n  - kind: ServiceAccount\n    name: myapp-sa\n    namespace: production\nroleRef:\n  kind: Role\n  name: app-reader\n  apiGroup: rbac.authorization.k8s.io\n```\n\n```bash\n# Audit what permissions a service account has\nkubectl auth can-i --list --as=system:serviceaccount:production:myapp-sa\n\n# Find overly-permissive cluster roles\nkubectl get clusterrolebindings -o json | \\\n  jq '.items[] | select(.roleRef.name == \"cluster-admin\") | .subjects'\n```\n\n### 5.5 Kyverno Policy Examples\n\n```yaml\n# Require non-root containers\napiVersion: kyverno.io\u002Fv1\nkind: ClusterPolicy\nmetadata:\n  name: require-non-root\nspec:\n  validationFailureAction: Enforce\n  rules:\n    - name: check-run-as-non-root\n      match:\n        resources:\n          kinds: [Pod]\n      validate:\n        message: \"Containers must not run as root (runAsNonRoot: true required)\"\n        pattern:\n          spec:\n            containers:\n              - securityContext:\n                  runAsNonRoot: true\n\n---\n# Require image digest pinning\napiVersion: kyverno.io\u002Fv1\nkind: ClusterPolicy\nmetadata:\n  name: require-image-digest\nspec:\n  validationFailureAction: Enforce\n  rules:\n    - name: check-digest\n      match:\n        resources:\n          kinds: [Pod]\n      validate:\n        message: \"Images must be pinned to a SHA256 digest, not just a tag\"\n        pattern:\n          spec:\n            containers:\n              - image: \"*@sha256:*\"\n\n---\n# Block privileged containers\napiVersion: kyverno.io\u002Fv1\nkind: ClusterPolicy\nmetadata:\n  name: disallow-privileged\nspec:\n  validationFailureAction: Enforce\n  rules:\n    - name: check-privileged\n      match:\n        resources:\n          kinds: [Pod]\n      validate:\n        message: \"Privileged containers are not allowed\"\n        pattern:\n          spec:\n            containers:\n              - =(securityContext):\n                  =(privileged): \"false\"\n```\n\n---\n\n## Common Pitfalls & Fixes\n\n| Problem | Root Cause | Fix |\n|---|---|---|\n| Image runs as root | No `USER` directive | Add `RUN useradd ...` and `USER appuser` |\n| Secret in `docker history` | `ENV` or `RUN curl -H \"Bearer $TOKEN\"` | Use `RUN --mount=type=secret` |\n| Large image with many CVEs | Full base image (`node:20`, `ubuntu`) | Switch to `node:20-slim` or `distroless` |\n| App crashes with `--read-only` | Writes to `\u002Ftmp` or app directory | Add `--tmpfs \u002Ftmp` for writable temp space |\n| Trivy scan blocks CI on unfixable CVEs | No ignore file | Add `.trivyignore` with justified entries |\n| Container needs `SYS_ADMIN` | Missing `--cap-drop` context | Investigate why — almost always avoidable |\n| Tag-based images drift over time | Mutable tags | Pin to `@sha256:` digest; use Renovate to update |\n| K8s pod rejected by PSA | Missing security context fields | Add `runAsNonRoot`, `readOnlyRootFilesystem`, `allowPrivilegeEscalation: false` |\n| App can't write to filesystem | `readOnlyRootFilesystem: true` | Mount `emptyDir` volumes for writable paths |\n\n---\n\n## Security Checklist\n\n### Dockerfile\n- [ ] Minimal base image (distroless, slim, or alpine — not full debian\u002Fubuntu)\n- [ ] Multi-stage build — no build tools, devDependencies, or compilers in runtime image\n- [ ] Non-root `USER` declared before `CMD`\u002F`ENTRYPOINT`\n- [ ] Base image pinned to `@sha256:...` digest (not just tag)\n- [ ] No secrets in `ENV`, `ARG`, or `RUN` commands\n- [ ] `HEALTHCHECK` defined\n- [ ] OCI labels present (`org.opencontainers.image.*`)\n- [ ] `.dockerignore` excludes `.git`, `.env`, secrets, tests\n- [ ] `ENTRYPOINT` uses exec form, not shell form\n\n### Image Scanning\n- [ ] Trivy or Grype scan in CI (fails on HIGH\u002FCRITICAL)\n- [ ] Hadolint passes with no warnings\n- [ ] Secret scan run on image (`trivy --scanners secret`)\n- [ ] SBOM generated and stored\n- [ ] `.trivyignore` has justified entries for accepted CVEs\n\n### Runtime\n- [ ] `--read-only` filesystem\n- [ ] `--cap-drop ALL` (add back only what's documented as required)\n- [ ] `--security-opt no-new-privileges:true`\n- [ ] `--security-opt seccomp=\u003Cprofile>` applied\n- [ ] Resource limits set (`--memory`, `--cpus`, `--pids-limit`)\n- [ ] Image signed with Cosign; verified before deploy\n\n### Kubernetes\n- [ ] `readOnlyRootFilesystem: true`\n- [ ] `allowPrivilegeEscalation: false`\n- [ ] `runAsNonRoot: true` with explicit UID\n- [ ] `capabilities.drop: [\"ALL\"]`\n- [ ] Resource `requests` and `limits` defined\n- [ ] `automountServiceAccountToken: false`\n- [ ] Namespace PSA enforced at `restricted` level\n- [ ] `NetworkPolicy` default-deny applied\n- [ ] RBAC uses specific resource names and minimal verbs\n\n---\n\n## Reference Files\n\n- `references\u002Fbase-image-comparison.md` — Size, CVE count, shell\u002Fpkg-manager trade-offs: distroless vs alpine vs slim vs scratch\n- `references\u002Fseccomp-profile-template.json` — Minimal syscall allowlist for typical web servers; start here and extend\n- `references\u002Fkubernetes-pod-security.md` — NetworkPolicy, RBAC, OPA\u002FKyverno policies, service account hardening, PSA\n\n## Related Skills\n\n- `docker-expert` — General Docker usage, Compose orchestration, image optimization\n- `gha-security-review` — Security audit of GitHub Actions workflows\n- `github-actions-advanced` — CI pipeline patterns including scanner integration\n- `kubernetes-architect` — Full Kubernetes architecture, not just security\n- `api-security-best-practices` — Application-level security (injection, auth, OWASP)\n- `k8s-security-policies` — Extended Kubernetes security policies\n\n## Limitations\n\n- Use this skill only when the task clearly matches the scope described above.\n- Do not treat the output as a substitute for environment-specific penetration testing or a formal security audit.\n- Seccomp profiles and AppArmor are Linux-only; macOS\u002FWindows Docker Desktop uses different mechanisms.\n- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.\n","# Container Security Hardening Skill\n\nA production-focused guide for building, scanning, and running containers securely — from Dockerfile authoring through runtime enforcement and supply chain integrity.\n\n---\n\n## When to Use This Skill\n\n- User mentions Docker security, container hardening, or Dockerfile security review\n- User asks about distroless images, non-root containers, or read-only filesystems\n- User wants to scan images for CVEs with Trivy, Grype, or Snyk\n- User mentions seccomp, AppArmor, Linux capabilities, or runtime security\n- User asks \"is my Dockerfile secure?\" or \"how do I reduce my image attack surface?\"\n- User wants to sign\u002Fverify images with Cosign or generate SBOMs\n- User asks about Kubernetes pod security, NetworkPolicy, or RBAC hardening\n- User says \"fix container CVEs\" or \"harden my container for production\"\n\n## When NOT to Use This Skill\n\n- The user is primarily asking about GitHub Actions CI\u002FCD → recommend `github-actions-advanced`\n- The user needs general Docker usage help (not security) → recommend `docker-expert`\n- The user is working with Kubernetes orchestration beyond security → recommend `kubernetes-architect`\n- The user needs application-level security (SQL injection, XSS) → recommend `api-security-best-practices`\n\n---\n\n## Step 1: Understand Context Before Responding\n\nWhen invoked, first detect the current state:\n\n```bash\n# Find Dockerfiles in the project\nfind . -name \"Dockerfile*\" -not -path \"*\u002Fnode_modules\u002F*\" | head -10\n\n# Check for existing security tooling\nls .trivyignore .hadolint.yaml .snyk docker-compose*.yml 2>\u002Fdev\u002Fnull\n\n# Inspect base images currently in use\ngrep -r \"^FROM\" $(find . -name \"Dockerfile*\") 2>\u002Fdev\u002Fnull\n\n# Check if Kubernetes manifests exist\nfind . -name \"*.yaml\" -path \"*\u002Fk8s\u002F*\" -o -name \"*.yaml\" -path \"*\u002Fmanifests\u002F*\" | head -10\n```\n\nThen adapt recommendations to:\n- The tech stack (Node, Python, Go, Java — affects base image choice)\n- Whether this is Docker-only or Kubernetes-deployed\n- The CI platform in use (for scanner integration)\n- The existing base images and how far they are from best practice\n\n---\n\n## The Five Layers of Container Security\n\n```\n1. Image Build        → Minimal base, no secrets, non-root, read-only FS\n2. Image Scanning     → CVE scanning, SBOM, secret detection, Dockerfile lint\n3. Runtime Security   → Capabilities, seccomp, AppArmor, resource limits\n4. Supply Chain       → Signed images, pinned digests, trusted registries\n5. Kubernetes Layer   → Pod Security Admission, NetworkPolicy, RBAC, Kyverno\n```\n\n> Work through layers in order — hardening the image first gives the most leverage.\n> See `references\u002Fbase-image-comparison.md` for a full size\u002FCVE trade-off table.\n\n---\n\n## Layer 1: Dockerfile Hardening\n\n### 1.1 Use a Minimal Base Image\n\n```dockerfile\n# ❌ AVOID — massive attack surface (~100–200 CVEs typical)\nFROM ubuntu:latest\nFROM node:20\n\n# ✅ BETTER — slim variants (glibc, smaller apt footprint)\nFROM node:20-slim\nFROM python:3.12-slim\n\n# ✅ BEST — distroless (no shell, no package manager, built-in nonroot user)\nFROM gcr.io\u002Fdistroless\u002Fnodejs20-debian12\nFROM gcr.io\u002Fdistroless\u002Fpython3-debian12\nFROM gcr.io\u002Fdistroless\u002Fstatic-debian12   # Go\u002FRust fully-static binaries\n\n# ✅ ALSO GREAT — Alpine (musl libc; verify app compatibility first)\nFROM alpine:3.20\n\n# ✅ ZERO ATTACK SURFACE — for fully static binaries only\nFROM scratch\n```\n\nSee `references\u002Fbase-image-comparison.md` for the full trade-off matrix.\n\n### 1.2 Multi-Stage Build — Separate Build from Runtime\n\nNever ship build tools, compilers, or dev dependencies in a production image.\n\n```dockerfile\n# syntax=docker\u002Fdockerfile:1\n\n# ── Stage 1: Install & Build ──────────────────────────────\nFROM node:20-slim AS builder\nWORKDIR \u002Fbuild\nCOPY package*.json .\u002F\nRUN npm ci                          # Install all deps (including devDeps)\nCOPY . .\nRUN npm run build && npm prune --production\n\n# ── Stage 2: Runtime — minimal, no build tools ────────────\nFROM gcr.io\u002Fdistroless\u002Fnodejs20-debian12@sha256:\u003Cdigest>\nLABEL org.opencontainers.image.source=\"https:\u002F\u002Fgithub.com\u002Forg\u002Frepo\"\nLABEL org.opencontainers.image.revision=\"${BUILD_SHA}\"\nLABEL org.opencontainers.image.licenses=\"MIT\"\nWORKDIR \u002Fapp\nCOPY --from=builder --chown=nonroot:nonroot \u002Fbuild\u002Fdist        .\u002Fdist\nCOPY --from=builder --chown=nonroot:nonroot \u002Fbuild\u002Fnode_modules .\u002Fnode_modules\nUSER nonroot:nonroot                # UID 65532 — built into distroless\nEXPOSE 3000\nCMD [\"dist\u002Fserver.js\"]\n```\n\n**Go \u002F Rust static binary pattern:**\n```dockerfile\nFROM golang:1.22-alpine AS builder\nWORKDIR \u002Fbuild\nCOPY go.* .\u002F\nRUN go mod download\nCOPY . .\nRUN CGO_ENABLED=0 GOOS=linux go build -ldflags=\"-s -w\" -o app .\n\nFROM scratch                        # Zero attack surface\nCOPY --from=builder \u002Fetc\u002Fssl\u002Fcerts\u002Fca-certificates.crt \u002Fetc\u002Fssl\u002Fcerts\u002F\nCOPY --from=builder \u002Fbuild\u002Fapp \u002Fapp\nUSER 65532:65532\nENTRYPOINT [\"\u002Fapp\"]\n```\n\n### 1.3 Run as Non-Root User\n\n```dockerfile\n# For debian\u002Fubuntu-based images — create dedicated user\nRUN groupadd -r appgroup --gid 10001 && \\\n    useradd -r -g appgroup --uid 10001 --no-log-init appuser\n\nCOPY --chown=appuser:appgroup . \u002Fapp\n\nUSER appuser    # Switch before CMD\u002FENTRYPOINT — never run as root\n\n# ─────────────────────────────────────────────────────────\n# For Alpine-based images\nRUN addgroup -g 10001 -S appgroup && \\\n    adduser -u 10001 -S appuser -G appgroup\n\n# For distroless — nonroot (UID 65532) is already built in\nUSER nonroot:nonroot\n```\n\n### 1.4 Pin Base Images to Digest\n\n```dockerfile\n# ❌ UNSAFE — tags are mutable; image can be silently overwritten (supply chain attack)\nFROM node:20-slim\n\n# ✅ SAFE — SHA256 digest is cryptographically immutable\nFROM node:20-slim@sha256:a1b2c3d4e5f6789abcdef0123456789abcdef0123456789abcdef0123456789ab\n```\n\n**Get the current digest:**\n```bash\ndocker pull node:20-slim\ndocker inspect node:20-slim --format='{{index .RepoDigests 0}}'\n```\n\n**Automate digest pinning** with Renovate or Dependabot:\n```json\n\u002F\u002F .renovaterc.json\n{\n  \"extends\": [\"config:base\"],\n  \"dockerfile\": { \"enabled\": true },\n  \"pinDigests\": true\n}\n```\n\n### 1.5 Never Bake Secrets into Images\n\n```dockerfile\n# ❌ NEVER — secret in ENV or RUN; visible in `docker history` and layer cache\nENV AWS_SECRET_ACCESS_KEY=supersecret\nRUN curl -H \"Authorization: Bearer $TOKEN\" https:\u002F\u002Fapi.example.com > config.json\nARG API_KEY                         # Also unsafe — visible in build args history\n\n# ✅ CORRECT — BuildKit secret mount (never persisted in any layer)\n# syntax=docker\u002Fdockerfile:1\nRUN --mount=type=secret,id=api_token \\\n    curl -H \"Authorization: Bearer $(cat \u002Frun\u002Fsecrets\u002Fapi_token)\" \\\n    https:\u002F\u002Fapi.example.com\u002Fconfig > config.json\n```\n\nBuild with: `docker build --secret id=api_token,src=.\u002Ftoken.txt .`\n\n**Check your image for leaked secrets:**\n```bash\ndocker history --no-trunc myapp:latest | grep -iE \"secret|key|password|token\"\ntrivy image --scanners secret myapp:latest\n```\n\n### 1.6 Read-Only Filesystem & No New Privileges\n\n```dockerfile\n# In the Dockerfile — use exec form (no shell interpretation)\nENTRYPOINT [\"node\", \"server.js\"]    # ✅ exec form\n# ENTRYPOINT \u002Fbin\u002Fsh -c \"node...\"  # ❌ shell form — spawns extra process\n\n# Define a HEALTHCHECK\nHEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \\\n  CMD [\"node\", \"-e\", \"require('http').get('http:\u002F\u002Flocalhost:3000\u002Fhealth', r => process.exit(r.statusCode === 200 ? 0 : 1))\"]\n```\n\nEnforce read-only at runtime (see Layer 3).\n\n### 1.7 Minimal .dockerignore\n\n```dockerignore\n# Always exclude these from build context\n.git\n.github\n.env\n.env.*\n*.pem\n*.key\nnode_modules\n__pycache__\n.pytest_cache\ncoverage\u002F\ndist\u002F\n*.log\n.DS_Store\nDockerfile*\ndocker-compose*\nREADME.md\ndocs\u002F\ntests\u002F\n```\n\n### 1.8 Full Hardened Dockerfile Example\n\n```dockerfile\n# syntax=docker\u002Fdockerfile:1\n\n# ── Build stage ───────────────────────────────────────────\nFROM node:20-slim AS builder\nWORKDIR \u002Fbuild\nCOPY package*.json .\u002F\nRUN --mount=type=cache,target=\u002Froot\u002F.npm \\\n    npm ci\nCOPY . .\nRUN npm run build && npm prune --production\n\n# ── Runtime stage ─────────────────────────────────────────\nFROM gcr.io\u002Fdistroless\u002Fnodejs20-debian12@sha256:\u003Cpin-digest-here>\n\nLABEL org.opencontainers.image.source=\"https:\u002F\u002Fgithub.com\u002Forg\u002Frepo\"\nLABEL org.opencontainers.image.revision=\"${BUILD_SHA}\"\nLABEL org.opencontainers.image.licenses=\"MIT\"\n\nWORKDIR \u002Fapp\nCOPY --from=builder --chown=nonroot:nonroot \u002Fbuild\u002Fdist        .\u002Fdist\nCOPY --from=builder --chown=nonroot:nonroot \u002Fbuild\u002Fnode_modules .\u002Fnode_modules\n\nUSER nonroot:nonroot\nEXPOSE 3000\n\nHEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \\\n  CMD [\"node\", \"-e\", \"require('http').get('http:\u002F\u002Flocalhost:3000\u002Fhealth', r => process.exit(r.statusCode===200?0:1))\"]\n\nCMD [\"dist\u002Fserver.js\"]\n```\n\n---\n\n## Layer 2: Image Scanning\n\n### 2.1 Trivy (Recommended — Fast, Comprehensive)\n\n```bash\n# Install\nbrew install trivy                              # macOS\napt install trivy                               # Debian\u002FUbuntu\ntmpdir=\"$(mktemp -d)\"\ntrap 'rm -rf \"$tmpdir\"' EXIT\ncurl -sfL https:\u002F\u002Fraw.githubusercontent.com\u002Faquasecurity\u002Ftrivy\u002Fmain\u002Fcontrib\u002Finstall.sh \\\n  -o \"$tmpdir\u002Ftrivy-install.sh\"\nsed -n '1,160p' \"$tmpdir\u002Ftrivy-install.sh\"\nsh \"$tmpdir\u002Ftrivy-install.sh\"\n\n# Scan an image for CVEs\ntrivy image myapp:latest\n\n# Fail CI on HIGH\u002FCRITICAL severity\ntrivy image --exit-code 1 --severity HIGH,CRITICAL myapp:latest\n\n# Scan Dockerfile for misconfigurations\ntrivy config .\u002FDockerfile\n\n# Scan entire repo (vulnerabilities + secrets + misconfigs)\ntrivy fs --scanners vuln,secret,misconfig .\n\n# Generate SBOM (CycloneDX or SPDX)\ntrivy image --format cyclonedx --output sbom.json myapp:latest\ntrivy image --format spdx-json  --output sbom.spdx.json myapp:latest\n\n# Ignore specific CVEs (add justification comments)\ntrivy image --ignorefile .trivyignore myapp:latest\n```\n\n**.trivyignore example:**\n```\n# CVE-2023-1234 — only exploitable via X feature, not used in this app\nCVE-2023-1234\n\n# CVE-2023-5678 — fix not yet available; tracked in issue #42\nCVE-2023-5678\n```\n\n### 2.2 Grype (Anchore Alternative)\n\n```bash\n# Install\ntmpdir=\"$(mktemp -d)\"\ntrap 'rm -rf \"$tmpdir\"' EXIT\ncurl -sSfL https:\u002F\u002Fraw.githubusercontent.com\u002Fanchore\u002Fgrype\u002Fmain\u002Finstall.sh \\\n  -o \"$tmpdir\u002Fgrype-install.sh\"\nsed -n '1,160p' \"$tmpdir\u002Fgrype-install.sh\"\nsh \"$tmpdir\u002Fgrype-install.sh\"\n\n# Scan image\ngrype myapp:latest\n\n# Fail on critical\ngrype myapp:latest --fail-on critical\n\n# Output SARIF for GitHub Security tab\ngrype myapp:latest -o sarif > results.sarif\n\n# Pair with Syft for SBOM generation\nsyft myapp:latest -o cyclonedx-json > sbom.json\ngrype sbom:sbom.json                            # Scan the SBOM directly\n```\n\n### 2.3 Hadolint — Dockerfile Linting\n\n```bash\n# Run directly\ndocker run --rm -i hadolint\u002Fhadolint \u003C Dockerfile\n\n# With config file\nhadolint --config .hadolint.yaml --failure-threshold warning Dockerfile\n```\n\n**.hadolint.yaml:**\n```yaml\nfailure-threshold: warning\nignore:\n  - DL3008   # Pin versions in apt-get (allow floating for base layer)\ntrustedRegistries:\n  - gcr.io\n  - ghcr.io\n  - public.ecr.aws\n```\n\n### 2.4 Secret Scanning in Images\n\n```bash\n# Trivy covers secrets too\ntrivy image --scanners secret myapp:latest\n\n# Dedicated: TruffleHog\ntrufflehog docker --image myapp:latest\n\n# git-secrets to prevent committing secrets\ngit secrets --scan\n```\n\n### 2.5 CI Integration (GitHub Actions — SHA-Pinned)\n\n```yaml\npermissions:\n  contents: read\n  security-events: write      # Required for uploading SARIF\n\njobs:\n  security-scan:\n    runs-on: ubuntu-24.04\n    timeout-minutes: 20\n    steps:\n      - uses: actions\u002Fcheckout@11bd71901bbe5b1630ceea73d27597364c9af683  # v4.2.2\n\n      - name: Build image\n        run: docker build -t myapp:${{ github.sha }} .\n\n      - name: Lint Dockerfile\n        uses: hadolint\u002Fhadolint-action@54c9adbab1582c2ef04b2016b760714a4bfde3cf  # v3.1.0\n        with:\n          dockerfile: Dockerfile\n          failure-threshold: warning\n\n      - name: Scan with Trivy\n        uses: aquasecurity\u002Ftrivy-action@6e7b7d1fd3e4fef0c5fa8cce1229c54b2c9bd0d8  # v0.28.0\n        with:\n          image-ref: myapp:${{ github.sha }}\n          format: sarif\n          output: trivy-results.sarif\n          severity: HIGH,CRITICAL\n          exit-code: '1'\n\n      - name: Upload results to GitHub Security tab\n        uses: github\u002Fcodeql-action\u002Fupload-sarif@4f3212b61783c3c68e8309a0f18a699764811cda  # v3.27.1\n        if: always()          # Upload even if scan found issues\n        with:\n          sarif_file: trivy-results.sarif\n```\n\n---\n\n## Layer 3: Runtime Security\n\n### 3.1 docker run Hardening Flags\n\n```bash\ndocker run \\\n  --read-only \\                              # Read-only root filesystem\n  --tmpfs \u002Ftmp:noexec,nosuid,size=100m \\     # Writable tmpfs for \u002Ftmp only\n  --tmpfs \u002Fvar\u002Frun \\                         # For PID files if needed\n  --user 10001:10001 \\                       # Non-root UID:GID\n  --cap-drop ALL \\                           # Drop ALL Linux capabilities\n  --cap-add NET_BIND_SERVICE \\               # Re-add only what's truly needed\n  --security-opt no-new-privileges:true \\    # Prevent privilege escalation via setuid\n  --security-opt seccomp=seccomp.json \\      # Custom seccomp profile\n  --security-opt apparmor=docker-default \\   # AppArmor profile\n  --pids-limit 100 \\                         # Prevent fork bombs\n  --memory 512m \\                            # OOM protection\n  --memory-swap 512m \\                       # Disable swap\n  --cpus 1.0 \\                               # CPU limit\n  --network none \\                           # No network (if not needed)\n  --health-cmd \"curl -f http:\u002F\u002Flocalhost:3000\u002Fhealth || exit 1\" \\\n  --health-interval 30s \\\n  myapp:latest\n```\n\n### 3.2 Linux Capabilities — What to Drop and Keep\n\nDrop ALL, then explicitly add only what your app requires:\n\n| Capability | Purpose | Keep? |\n|---|---|---|\n| `NET_BIND_SERVICE` | Bind ports \u003C 1024 | Only if binding a privileged port |\n| `CHOWN` | Change file ownership | No — set ownership at build time |\n| `SETUID` \u002F `SETGID` | Switch user identity | No — drop always |\n| `SYS_ADMIN` | Broad privileged operations | No — most dangerous capability |\n| `NET_ADMIN` | Configure network interfaces | No (only network tools) |\n| `SYS_PTRACE` | Debug\u002Ftrace processes | No (only debugger containers) |\n| `DAC_OVERRIDE` | Override file permissions | No — runs as correct user |\n| `NET_RAW` | Raw sockets (ping) | No (blocked by default seccomp anyway) |\n\n> **Most web apps need zero capabilities.** `--cap-drop ALL` alone is often sufficient.\n\n### 3.3 Docker Compose Hardening\n\n```yaml\nservices:\n  app:\n    image: myapp:latest\n    read_only: true\n    user: \"10001:10001\"\n    tmpfs:\n      - \u002Ftmp:noexec,nosuid,size=100m\n      - \u002Fvar\u002Frun:noexec,nosuid,size=10m\n    cap_drop:\n      - ALL\n    cap_add:\n      - NET_BIND_SERVICE    # Only if binding port \u003C 1024\n    security_opt:\n      - no-new-privileges:true\n      - seccomp:.\u002Freferences\u002Fseccomp-profile-template.json\n    pids_limit: 100\n    mem_limit: 512m\n    memswap_limit: 512m\n    cpus: 1.0\n    healthcheck:\n      test: [\"CMD\", \"curl\", \"-f\", \"http:\u002F\u002Flocalhost:3000\u002Fhealth\"]\n      interval: 30s\n      timeout: 5s\n      retries: 3\n      start_period: 10s\n    networks:\n      - backend\n    # Only expose externally if truly required\n    # ports: [\"8080:8080\"]\n    restart: unless-stopped\n    logging:\n      driver: json-file\n      options:\n        max-size: \"10m\"\n        max-file: \"3\"\n\nnetworks:\n  backend:\n    driver: bridge\n    internal: true    # No external connectivity unless needed\n```\n\n### 3.4 Seccomp Profiles\n\nThe Docker default seccomp profile blocks ~44 dangerous syscalls. For stricter control:\n\n```bash\n# Step 1: Audit syscalls your app actually makes\ndocker run --security-opt seccomp=unconfined \\\n  --name audit-run myapp:latest &\n\n# Capture with strace\nstrace -c -p $(docker inspect --format '{{.State.Pid}}' audit-run)\n\n# Or with sysdig (more container-friendly)\nsysdig -p \"%syscall.type\" container.name=audit-run | sort -u\n\n# Step 2: Build a custom profile from references\u002Fseccomp-profile-template.json\n# Step 3: Apply it\ndocker run --security-opt seccomp=references\u002Fseccomp-profile-template.json myapp:latest\n```\n\nSee `references\u002Fseccomp-profile-template.json` for a minimal starting allowlist for typical web servers.\n\n### 3.5 AppArmor Profile (Linux hosts)\n\n```bash\n# Load Docker's default AppArmor profile\nsudo apparmor_parser -r \u002Fetc\u002Fapparmor.d\u002Fdocker-default\n\n# Apply at runtime\ndocker run --security-opt apparmor=docker-default myapp:latest\n\n# Generate a custom profile\naa-genprof myapp   # Interactive — run app under aa-complain mode first\n```\n\n---\n\n## Layer 4: Supply Chain Security\n\n### 4.1 Sign Images with Cosign (Sigstore — Keyless)\n\n```bash\n# Install cosign\nbrew install cosign    # macOS\n# or: https:\u002F\u002Fgithub.com\u002Fsigstore\u002Fcosign\u002Freleases\n\n# Sign after push — keyless via OIDC (no long-lived keys)\ncosign sign ghcr.io\u002Forg\u002Fmyapp:latest\n\n# Verify before deploy\ncosign verify ghcr.io\u002Forg\u002Fmyapp:latest \\\n  --certificate-identity-regexp=\"https:\u002F\u002Fgithub.com\u002Forg\u002Frepo\" \\\n  --certificate-oidc-issuer=\"https:\u002F\u002Ftoken.actions.githubusercontent.com\"\n```\n\n**GitHub Actions — Sign & Verify Pipeline:**\n```yaml\npermissions:\n  id-token: write     # Required for OIDC keyless signing\n  packages: write\n\nsteps:\n  - uses: sigstore\u002Fcosign-installer@dc72c7d5c4d10cd6bcb8cf6e3fd625a9e5e537da  # v3.7.0\n\n  - name: Sign image (keyless via OIDC)\n    run: |\n      cosign sign --yes \\\n        ghcr.io\u002F${{ github.repository }}:${{ github.sha }}\n    env:\n      COSIGN_EXPERIMENTAL: \"true\"\n\n  - name: Attach SBOM attestation\n    run: |\n      cosign attest --yes \\\n        --predicate sbom.json \\\n        --type cyclonedx \\\n        ghcr.io\u002F${{ github.repository }}:${{ github.sha }}\n```\n\n### 4.2 SBOM Generation & Attestation\n\n```bash\n# Generate SBOM with Syft\nsyft myapp:latest -o cyclonedx-json > sbom.json\nsyft myapp:latest -o spdx-json > sbom.spdx.json\n\n# Attach to image as attestation\ncosign attest --predicate sbom.json --type cyclonedx ghcr.io\u002Forg\u002Fmyapp:latest\n\n# Verify SBOM attestation before deployment\ncosign verify-attestation \\\n  --type cyclonedx \\\n  --certificate-identity-regexp=\"https:\u002F\u002Fgithub.com\u002Forg\u002Frepo\" \\\n  --certificate-oidc-issuer=\"https:\u002F\u002Ftoken.actions.githubusercontent.com\" \\\n  ghcr.io\u002Forg\u002Fmyapp:latest\n```\n\n### 4.3 Use Trusted Registries & Enable Registry Scanning\n\n| Registry | Built-in Scanning | Notes |\n|---|---|---|\n| GHCR (GitHub Container Registry) | No (use Trivy in CI) | Best for OSS, OIDC auth |\n| AWS ECR | Yes (enhanced scanning via Inspector) | Enable per-repo |\n| GCP Artifact Registry | Yes (Container Analysis) | Enabled by default |\n| Azure ACR | Yes (Defender for Containers) | Premium tier |\n| Docker Hub | Yes (limited on free tier) | Avoid for private images |\n\n```bash\n# Enable ECR enhanced scanning\naws ecr put-registry-scanning-configuration \\\n  --scan-type ENHANCED \\\n  --rules '[{\"repositoryFilters\":[{\"filter\":\"*\",\"filterType\":\"WILDCARD\"}],\"scanFrequency\":\"CONTINUOUS_SCAN\"}]'\n```\n\n### 4.4 Admission Control — Block Unsigned\u002FUnscanned Images\n\n```yaml\n# Kyverno policy — require signed images before admission\napiVersion: kyverno.io\u002Fv1\nkind: ClusterPolicy\nmetadata:\n  name: require-signed-images\nspec:\n  validationFailureAction: Enforce\n  rules:\n    - name: verify-image-signature\n      match:\n        resources:\n          kinds: [Pod]\n      verifyImages:\n        - imageReferences:\n            - \"ghcr.io\u002Forg\u002F*\"\n          attestors:\n            - entries:\n                - keyless:\n                    subject: \"https:\u002F\u002Fgithub.com\u002Forg\u002Frepo\u002F.github\u002Fworkflows\u002F*\"\n                    issuer: \"https:\u002F\u002Ftoken.actions.githubusercontent.com\"\n```\n\n---\n\n## Layer 5: Kubernetes Pod Security\n\n> Full reference: `references\u002Fkubernetes-pod-security.md`\n\n### 5.1 Pod Security Context\n\n```yaml\napiVersion: apps\u002Fv1\nkind: Deployment\nmetadata:\n  name: myapp\n  namespace: production\nspec:\n  replicas: 3\n  template:\n    spec:\n      # ── Pod-level security context ─────────────────────\n      securityContext:\n        runAsNonRoot: true\n        runAsUser: 10001\n        runAsGroup: 10001\n        fsGroup: 10001\n        fsGroupChangePolicy: OnRootMismatch\n        seccompProfile:\n          type: RuntimeDefault    # Use containerd\u002Frunc default seccomp\n        supplementalGroups: []\n\n      automountServiceAccountToken: false   # Disable unless needed\n\n      # ── Container-level security context ──────────────\n      containers:\n        - name: app\n          image: ghcr.io\u002Forg\u002Fmyapp@sha256:\u003Cdigest>   # Always use digest\n          securityContext:\n            allowPrivilegeEscalation: false\n            readOnlyRootFilesystem: true\n            capabilities:\n              drop: [\"ALL\"]\n              add: []              # Add nothing unless absolutely required\n            runAsNonRoot: true\n            runAsUser: 10001\n            seccompProfile:\n              type: RuntimeDefault\n\n          # ── Resource limits (required for restricted PSA) ──\n          resources:\n            requests:\n              memory: \"128Mi\"\n              cpu: \"100m\"\n            limits:\n              memory: \"512Mi\"\n              cpu: \"500m\"\n\n          # ── Writable tmpfs mounts ──────────────────────\n          volumeMounts:\n            - name: tmp\n              mountPath: \u002Ftmp\n            - name: varrun\n              mountPath: \u002Fvar\u002Frun\n\n      volumes:\n        - name: tmp\n          emptyDir:\n            medium: Memory\n            sizeLimit: 100Mi\n        - name: varrun\n          emptyDir:\n            medium: Memory\n            sizeLimit: 10Mi\n```\n\n### 5.2 Pod Security Admission (K8s 1.25+)\n\n```bash\n# Audit existing workloads before enforcing\nkubectl label namespace production \\\n  pod-security.kubernetes.io\u002Faudit=restricted \\\n  pod-security.kubernetes.io\u002Faudit-version=latest\n\n# Warn in staging, enforce in production\nkubectl label namespace staging \\\n  pod-security.kubernetes.io\u002Fwarn=restricted\n\nkubectl label namespace production \\\n  pod-security.kubernetes.io\u002Fenforce=restricted \\\n  pod-security.kubernetes.io\u002Fenforce-version=latest\n```\n\n| PSA Level | What It Blocks |\n|---|---|\n| `privileged` | No restrictions |\n| `baseline` | Blocks hostNetwork, hostPID, privileged containers, hostPath |\n| `restricted` | Also requires non-root, read-only FS, drops capabilities, seccomp |\n\n### 5.3 NetworkPolicy — Zero-Trust Networking\n\n```yaml\n# Step 1: Deny all ingress and egress by default in the namespace\napiVersion: networking.k8s.io\u002Fv1\nkind: NetworkPolicy\nmetadata:\n  name: default-deny-all\n  namespace: production\nspec:\n  podSelector: {}\n  policyTypes: [Ingress, Egress]\n\n---\n# Step 2: Selectively allow only required traffic\napiVersion: networking.k8s.io\u002Fv1\nkind: NetworkPolicy\nmetadata:\n  name: allow-app\n  namespace: production\nspec:\n  podSelector:\n    matchLabels:\n      app: myapp\n  policyTypes: [Ingress, Egress]\n  ingress:\n    - from:\n        - namespaceSelector:\n            matchLabels:\n              kubernetes.io\u002Fmetadata.name: ingress-nginx\n          podSelector:\n            matchLabels:\n              app.kubernetes.io\u002Fname: ingress-nginx\n      ports:\n        - port: 3000\n  egress:\n    - to:\n        - podSelector:\n            matchLabels:\n              app: postgres\n      ports:\n        - port: 5432\n    - to:                 # Allow only cluster DNS\n        - namespaceSelector:\n            matchLabels:\n              kubernetes.io\u002Fmetadata.name: kube-system\n          podSelector:\n            matchLabels:\n              k8s-app: kube-dns\n      ports:\n        - port: 53\n          protocol: UDP\n        - port: 53\n          protocol: TCP\n```\n\n### 5.4 RBAC — Least Privilege\n\n```yaml\n# Create minimal role — never use wildcards\napiVersion: rbac.authorization.k8s.io\u002Fv1\nkind: Role\nmetadata:\n  name: app-reader\n  namespace: production\nrules:\n  - apiGroups: [\"\"]\n    resources: [\"configmaps\", \"secrets\"]\n    resourceNames: [\"myapp-config\"]    # Lock to specific resource names\n    verbs: [\"get\"]                     # Never [\"*\"]\n\n---\napiVersion: rbac.authorization.k8s.io\u002Fv1\nkind: RoleBinding\nmetadata:\n  name: app-reader-binding\n  namespace: production\nsubjects:\n  - kind: ServiceAccount\n    name: myapp-sa\n    namespace: production\nroleRef:\n  kind: Role\n  name: app-reader\n  apiGroup: rbac.authorization.k8s.io\n```\n\n```bash\n# Audit what permissions a service account has\nkubectl auth can-i --list --as=system:serviceaccount:production:myapp-sa\n\n# Find overly-permissive cluster roles\nkubectl get clusterrolebindings -o json | \\\n  jq '.items[] | select(.roleRef.name == \"cluster-admin\") | .subjects'\n```\n\n### 5.5 Kyverno Policy Examples\n\n```yaml\n# Require non-root containers\napiVersion: kyverno.io\u002Fv1\nkind: ClusterPolicy\nmetadata:\n  name: require-non-root\nspec:\n  validationFailureAction: Enforce\n  rules:\n    - name: check-run-as-non-root\n      match:\n        resources:\n          kinds: [Pod]\n      validate:\n        message: \"Containers must not run as root (runAsNonRoot: true required)\"\n        pattern:\n          spec:\n            containers:\n              - securityContext:\n                  runAsNonRoot: true\n\n---\n# Require image digest pinning\napiVersion: kyverno.io\u002Fv1\nkind: ClusterPolicy\nmetadata:\n  name: require-image-digest\nspec:\n  validationFailureAction: Enforce\n  rules:\n    - name: check-digest\n      match:\n        resources:\n          kinds: [Pod]\n      validate:\n        message: \"Images must be pinned to a SHA256 digest, not just a tag\"\n        pattern:\n          spec:\n            containers:\n              - image: \"*@sha256:*\"\n\n---\n# Block privileged containers\napiVersion: kyverno.io\u002Fv1\nkind: ClusterPolicy\nmetadata:\n  name: disallow-privileged\nspec:\n  validationFailureAction: Enforce\n  rules:\n    - name: check-privileged\n      match:\n        resources:\n          kinds: [Pod]\n      validate:\n        message: \"Privileged containers are not allowed\"\n        pattern:\n          spec:\n            containers:\n              - =(securityContext):\n                  =(privileged): \"false\"\n```\n\n---\n\n## Common Pitfalls & Fixes\n\n| Problem | Root Cause | Fix |\n|---|---|---|\n| Image runs as root | No `USER` directive | Add `RUN useradd ...` and `USER appuser` |\n| Secret in `docker history` | `ENV` or `RUN curl -H \"Bearer $TOKEN\"` | Use `RUN --mount=type=secret` |\n| Large image with many CVEs | Full base image (`node:20`, `ubuntu`) | Switch to `node:20-slim` or `distroless` |\n| App crashes with `--read-only` | Writes to `\u002Ftmp` or app directory | Add `--tmpfs \u002Ftmp` for writable temp space |\n| Trivy scan blocks CI on unfixable CVEs | No ignore file | Add `.trivyignore` with justified entries |\n| Container needs `SYS_ADMIN` | Missing `--cap-drop` context | Investigate why — almost always avoidable |\n| Tag-based images drift over time | Mutable tags | Pin to `@sha256:` digest; use Renovate to update |\n| K8s pod rejected by PSA | Missing security context fields | Add `runAsNonRoot`, `readOnlyRootFilesystem`, `allowPrivilegeEscalation: false` |\n| App can't write to filesystem | `readOnlyRootFilesystem: true` | Mount `emptyDir` volumes for writable paths |\n\n---\n\n## Security Checklist\n\n### Dockerfile\n- [ ] Minimal base image (distroless, slim, or alpine — not full debian\u002Fubuntu)\n- [ ] Multi-stage build — no build tools, devDependencies, or compilers in runtime image\n- [ ] Non-root `USER` declared before `CMD`\u002F`ENTRYPOINT`\n- [ ] Base image pinned to `@sha256:...` digest (not just tag)\n- [ ] No secrets in `ENV`, `ARG`, or `RUN` commands\n- [ ] `HEALTHCHECK` defined\n- [ ] OCI labels present (`org.opencontainers.image.*`)\n- [ ] `.dockerignore` excludes `.git`, `.env`, secrets, tests\n- [ ] `ENTRYPOINT` uses exec form, not shell form\n\n### Image Scanning\n- [ ] Trivy or Grype scan in CI (fails on HIGH\u002FCRITICAL)\n- [ ] Hadolint passes with no warnings\n- [ ] Secret scan run on image (`trivy --scanners secret`)\n- [ ] SBOM generated and stored\n- [ ] `.trivyignore` has justified entries for accepted CVEs\n\n### Runtime\n- [ ] `--read-only` filesystem\n- [ ] `--cap-drop ALL` (add back only what's documented as required)\n- [ ] `--security-opt no-new-privileges:true`\n- [ ] `--security-opt seccomp=\u003Cprofile>` applied\n- [ ] Resource limits set (`--memory`, `--cpus`, `--pids-limit`)\n- [ ] Image signed with Cosign; verified before deploy\n\n### Kubernetes\n- [ ] `readOnlyRootFilesystem: true`\n- [ ] `allowPrivilegeEscalation: false`\n- [ ] `runAsNonRoot: true` with explicit UID\n- [ ] `capabilities.drop: [\"ALL\"]`\n- [ ] Resource `requests` and `limits` defined\n- [ ] `automountServiceAccountToken: false`\n- [ ] Namespace PSA enforced at `restricted` level\n- [ ] `NetworkPolicy` default-deny applied\n- [ ] RBAC uses specific resource names and minimal verbs\n\n---\n\n## Reference Files\n\n- `references\u002Fbase-image-comparison.md` — Size, CVE count, shell\u002Fpkg-manager trade-offs: distroless vs alpine vs slim vs scratch\n- `references\u002Fseccomp-profile-template.json` — Minimal syscall allowlist for typical web servers; start here and extend\n- `references\u002Fkubernetes-pod-security.md` — NetworkPolicy, RBAC, OPA\u002FKyverno policies, service account hardening, PSA\n\n## Related Skills\n\n- `docker-expert` — General Docker usage, Compose orchestration, image optimization\n- `gha-security-review` — Security audit of GitHub Actions workflows\n- `github-actions-advanced` — CI pipeline patterns including scanner integration\n- `kubernetes-architect` — Full Kubernetes architecture, not just security\n- `api-security-best-practices` — Application-level security (injection, auth, OWASP)\n- `k8s-security-policies` — Extended Kubernetes security policies\n\n## Limitations\n\n- Use this skill only when the task clearly matches the scope described above.\n- Do not treat the output as a substitute for environment-specific penetration testing or a formal security audit.\n- Seccomp profiles and AppArmor are Linux-only; macOS\u002FWindows Docker Desktop uses different mechanisms.\n- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.\n",{"name":5,"risk":24,"source":25,"category":26,"date_added":27,"description":28},"safe","community","security","2026-05-30","Harden Docker\u002Fcontainer images and runtime deployments with secure base images, non-root users, CVE scanning, SBOM\u002Fsigning, seccomp\u002FAppArmor, and Kubernetes pod security controls. Use for Dockerfile security reviews, container CVEs, image scanning, distroless images, or production hardening.\n","master","877653a671c51fae6476bd9f0d34ee6c408d68b9",".github\u002Fskills\u002Fcontainer-security-hardening","https:\u002F\u002Fgithub.com\u002Fprincepatel04477-web\u002Ftrivoxa-group","https:\u002F\u002Ftrivoxa-group.vercel.app","https:\u002F\u002Fgithub.com\u002Fprincepatel04477-web","2026-08-01 17:29:31",{"source":8,"skillName":5,"commands":37,"prompt":47,"zipAvailable":48},[38,41,44],{"tool":39,"command":40},"npx","npx skills add princepatel04477-web\u002Ftrivoxa-group --skill container-security-hardening",{"tool":42,"command":43},"bunx","bunx skills add princepatel04477-web\u002Ftrivoxa-group --skill container-security-hardening",{"tool":45,"command":46},"pnpm","pnpm dlx skills add princepatel04477-web\u002Ftrivoxa-group --skill container-security-hardening","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fprincepatel04477-web\u002Ftrivoxa-group\u002Fblob\u002Fmaster\u002F.github\u002Fskills\u002Fcontainer-security-hardening\u002FSKILL.md",true,[50,56,60],{"path":51,"resourceType":52,"resourceTypeDesc":53,"sizeBytes":54,"sourceHtmlUrl":55},"references\u002Fbase-image-comparison.md","REFERENCE","参考文档",8368,"https:\u002F\u002Fgithub.com\u002Fprincepatel04477-web\u002Ftrivoxa-group\u002Fblob\u002Fmaster\u002F.github\u002Fskills\u002Fcontainer-security-hardening\u002Freferences\u002Fbase-image-comparison.md",{"path":57,"resourceType":52,"resourceTypeDesc":53,"sizeBytes":58,"sourceHtmlUrl":59},"references\u002Fkubernetes-pod-security.md",14546,"https:\u002F\u002Fgithub.com\u002Fprincepatel04477-web\u002Ftrivoxa-group\u002Fblob\u002Fmaster\u002F.github\u002Fskills\u002Fcontainer-security-hardening\u002Freferences\u002Fkubernetes-pod-security.md",{"path":61,"resourceType":52,"resourceTypeDesc":53,"sizeBytes":62,"sourceHtmlUrl":63},"references\u002Fseccomp-profile-template.json",8607,"https:\u002F\u002Fgithub.com\u002Fprincepatel04477-web\u002Ftrivoxa-group\u002Fblob\u002Fmaster\u002F.github\u002Fskills\u002Fcontainer-security-hardening\u002Freferences\u002Fseccomp-profile-template.json",[65,72,79,86,93,100],{"skillNo":66,"name":67,"nameZh":6,"description":68,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":69,"categories":70,"keywords":71,"publishedAt":19},"01M78G4Z5RFJ72G536XYPC77PG","zustand-store-ts","Create Zustand stores following established patterns with proper TypeScript types and middleware.","https:\u002F\u002Fgithub.com\u002Fprincepatel04477-web\u002Ftrivoxa-group\u002Fblob\u002Fmaster\u002F.github\u002Fskills\u002Fzustand-store-ts\u002FSKILL.md",[],[],{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":78,"publishedAt":19},"01M78G4WQMHRST36KDP7AV3NR3","zoom-automation","Automate Zoom meeting creation, management, recordings, webinars, and participant tracking via Rube MCP (Composio). Always search tools first for current schemas.","https:\u002F\u002Fgithub.com\u002Fprincepatel04477-web\u002Ftrivoxa-group\u002Fblob\u002Fmaster\u002F.github\u002Fskills\u002Fzoom-automation\u002FSKILL.md",[],[],{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":19},"01M78G4T37F4SPS7M4KT0A8JJB","zoho-crm-automation","Automate Zoho CRM tasks via Rube MCP (Composio): create\u002Fupdate records, search contacts, manage leads, and convert leads. Always search tools first for current schemas.","https:\u002F\u002Fgithub.com\u002Fprincepatel04477-web\u002Ftrivoxa-group\u002Fblob\u002Fmaster\u002F.github\u002Fskills\u002Fzoho-crm-automation\u002FSKILL.md",[],[],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":19},"01M78G4QAJMF71KD1G38MNDQYK","zod-validation-expert","Expert in Zod — TypeScript-first schema validation. Covers parsing, custom errors, refinements, type inference, and integration with React Hook Form, Next.js, and tRPC.","https:\u002F\u002Fgithub.com\u002Fprincepatel04477-web\u002Ftrivoxa-group\u002Fblob\u002Fmaster\u002F.github\u002Fskills\u002Fzod-validation-expert\u002FSKILL.md",[],[],{"skillNo":94,"name":95,"nameZh":6,"description":96,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":97,"categories":98,"keywords":99,"publishedAt":19},"01M78G4MS3WE96MH5P561KFY95","zipai-optimizer","Adaptive token optimizer: intelligent filtering, surgical output, ambiguity-first, context-window-aware, VCS-aware, MCP-aware.","https:\u002F\u002Fgithub.com\u002Fprincepatel04477-web\u002Ftrivoxa-group\u002Fblob\u002Fmaster\u002F.github\u002Fskills\u002Fzipai-optimizer\u002FSKILL.md",[],[],{"skillNo":101,"name":102,"nameZh":6,"description":103,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":104,"categories":105,"keywords":106,"publishedAt":19},"01M78G4GZ0T47C6929V9CVH1AK","zeroize-audit","Detects missing zeroization of sensitive data in source code and identifies zeroization removed by compiler optimizations, with assembly-level analysis, and control-flow verification. Use for auditing C\u002FC++\u002FRust code handling secrets, keys, passwords, or other sensitive data.","https:\u002F\u002Fgithub.com\u002Fprincepatel04477-web\u002Ftrivoxa-group\u002Fblob\u002Fmaster\u002F.github\u002Fskills\u002Fzeroize-audit\u002FSKILL.md",[],[]]