算法艺术创作
algorithmic-art
通过代码和可调参数创作生成艺术与交互式视觉效果。
security-container-security【设计与创意】Use this skill when asked about container security, image scanning, Trivy, Grype, Clair, Snyk, Dockerfile security, admission control, Kyverno, OPA, runtime security, Falco, Tracee, CVE management, container signing, Cosign, SBOM, or distroless images. This skill enforces: image scanning in CI with severity gates, Dockerfile hardening with multi-stag…
独立 GitHub 快照 · 自动分类 · 以原作者文档为准
Build a container security program spanning image scanning (Trivy, Grype, Clair, Snyk), Dockerfile hardening (distroless, multi-stage, non-root), admission control (Kyverno, OPA/Gatekeeper), runtime monitoring (Falco, Tracee), image signing (Cosign), and SBOM generation.
Exact user phrases: "container security", "image scanning", "Trivy", "Grype", "Clair", "Snyk", "Dockerfile security", "admission control", "Kyverno", "OPA", "runtime security", "Falco", "Tracee", "container CVE", "distroless", "multi-stage build", "image hardening", "K8s security", "container vulnerability", "Cosign", "image signing", "SBOM", "container admission", "pod security".
Before activating, verify:
Container security policy with image scanning config, admission rules, runtime monitoring as YAML files.
# Trivy scan config
# Dockerfile best practice rules
# Kyverno admission policies
# Falco rules
# Cosign signing config
No preamble. No postamble. No explanations. No filler/hedging/transitions. Compress output -- why use many token when few do trick.
300 lines of configuration.
Trivy: primary scanner for container images. Fast, offline capable, broad CVE coverage. trivy image --severity CRITICAL,HIGH --exit-code 1 --format sarif <image>.
Grype: secondary scanner for cross-reference. Integrates with Syft for SBOM-based scanning. grype myapp:latest --only-fixed --fail-on critical.
Clair: registry-based scanning via Clair v4 and Quay. Scans on push and on schedule.
Snyk: developer-friendly with IDE integration. Provides fix advice and reachability analysis.
Policy gates: CRITICAL -> block build, fix immediately. HIGH -> block if fixable version exists. MEDIUM -> warn with PR comment. LOW -> info, log only.
Scan at build time and rescan daily for new CVEs. Store results as attestation in registry. Output SARIF for GitHub Code Scanning integration.
Base image selection: Distroless for production: gcr.io/distroless/base. Scratch for statically linked Go binaries. Alpine for tooling and utility images.
Multi-stage pattern: Builder stage with full SDK and build tools. Runtime stage with minimal dependencies only. Builder stage never ships to registry.
User: USER 10001:10001 -- never root. Filesystem: COPY --chown=10001:10001. Packages: pin exact versions, clean cache. rm -rf /var/cache/apk/* for Alpine.
HEALTHCHECK: 30s interval, 3s timeout. Labels for provenance tracking: org.opencontainers.image.source, org.opencontainers.image.revision.
Security: RUN --mount=type=bind for secrets. Never use build args for secrets. .dockerignore excludes node_modules, .git, .env, test.
Syft: generate SBOM as build artifact. syft packages <image> -o cyclonedx-json > sbom.cdx.json.
Store SBOM in registry alongside image. Attest with Cosign for non-repudiation.
Grype scans SBOM directly without pulling image: grype sbom:sbom.cdx.json.
Formats: CycloneDX and SPDX supported. Use SBOM for vulnerability matching, license checks, supply chain transparency, software inventory. Policy: no image deployable without SBOM.
Sign image digest after scan passes. cosign sign --keyless <image>.
Keyless mode uses OIDC from CI provider. GitHub, GitLab, Google identities supported. No key management burden.
Signature stored in registry alongside image. Verify before admission: cosign verify --keyless <image>.
Attest scan results and SBOM: cosign attest --keyless --type cyclonedx sbom.cdx.json <image>.
Policy: only signed images with passing scans deployable. Key-based signing for air-gapped environments.
Kyverno: Kubernetes-native admission policies. Policy types: Validate (deny if violated), Mutate (auto-modify spec), Generate (create resources), VerifyImages (require Cosign).
Key policies:
OPA/Gatekeeper: alternative using Rego language. Better for complex cross-resource policies.
Dry-run mode: 7 days before enforcement. Audit violations, tune rules, then enforce.
Pod Security Standards: Restricted profile. Audit -> warn -> enforce rollout sequence.
Falco: syscall-level monitoring. Driver: driver.kind=modern-bpf for performance.
Default rules:
Tracee: eBPF-based runtime security. Signature detection for kernel exploits. Behavioral analysis for fileless execution. Container breakout detection.
Alert pipeline: Falco -> Falcosidekick -> AlertManager -> Slack or PagerDuty. Critical alerts trigger automatic pod termination.
CRITICAL: patch within 24 hours. Mitigate with WAF rule or network policy if no fix. HIGH: patch within 7 days. MEDIUM: patch within 30 days. LOW: patch within 90 days.
Exception process: Documented justification with compensating control. Expiry date of max 30 days. Approval from security lead.
Tracking dashboard: Vulnerability age by severity. Image count affected. Fixable vs unfixable breakdown. Exception count and age.
Daily scan of deployed images for new CVEs. Alert on new critical or high findings. Auto-create tickets for fixable vulnerabilities.
| Architecture | Pros | Cons | Best For |
|---|---|---|---|
| Shift-left (CI scanning only) | Fast, developer-owned | No runtime coverage | Startups, small teams |
| Runtime + CI | Full coverage, defense in depth | Higher ops cost | Regulated, enterprise |
| Registry scanning only | No CI integration, passive | Delayed detection | Existing registries |
| Admission control only | Enforces at deploy time | Blocks bad images without finding them | Compliance enforcement |
| Tool | Speed | Coverage | Integration | Best For |
|---|---|---|---|---|
| Trivy | Fast | OS + language libs | CI, CD, registry | Primary scanner |
| Grype | Medium | OS + language libs | CLI, SBOM | Secondary cross-ref |
| Clair | Slow (registry) | OS packages | Quay, registry | Registry-based orgs |
| Snyk | Fast | OS + libs + IaC | IDE, CI, registry | Developer experience |
| Docker Scout | Fast | OS + libs | Docker only | Docker Hub users |
| Tool | Mechanism | Performance Impact | Detection | Best For |
|---|---|---|---|---|
| Falco | Syscall (kernel module/eBPF) | < 5% CPU | System calls, file access | General container security |
| Tracee | eBPF | < 3% CPU | Signatures, behavior | Advanced threat detection |
| Aqua | Agent + eBPF | < 5% CPU | Full stack (K8s, network) | Enterprise security platform |
| Sysdig Secure | Agent + eBPF | < 5% CPU | Falco-based + forensics | Performance monitoring + security |
| Tool | Language | Complexity | Best For |
|---|---|---|---|
| Kyverno | YAML | Low | Kubernetes-native teams |
| OPA/Gatekeeper | Rego | Medium | Complex policies, multi-platform |
| Custom webhook | Any | High | Special requirements |
Images scanned at build time can have new CVEs discovered hours later. Daily rescan of registry is mandatory. Deployed images must be rescanned. Alert on new critical vulnerabilities in running images.
Using the same base image for months accumulates vulnerabilities. Update base images monthly minimum. Use automated base image update tools. Pin base image SHA for reproducibility.
Enforcing admission policies without dry-run breaks existing workloads. Use dry-run mode for 7-14 days before enforcement. Audit violations, tune rules, notify teams.
Falco detects events but they go to /var/log/syslog by default. Without alert pipeline, events are invisible. Configure Falcosidekick. Route critical alerts to PagerDuty.
Blocking every CVE with a gate causes deployment delays. Gate on CRITICAL/HIGH only. Allow MEDIUM/LOW with warnings. Have exception process for false positives.
Signing after deployment is too late -- unsigned images already running. Sign images as post-scan step in CI. Verify signatures in admission controller.
Root in container has unnecessary privileges. If container is compromised, attacker gets root on host kernel. Always use non-root USER. Drop all capabilities.
SBOM generated once and forgotten. SBOM must be generated per build, stored alongside image, used for vulnerability scanning. Attest SBOM with Cosign.
Container security: image scanning, admission control, runtime security within containers, registry security. Host security: OS hardening, kernel patches, network security at host level. Containers share host kernel, so host security is foundational. Both needed for defense in depth.
Trivy: fastest, broadest CVE coverage, offline-capable, free, MIT license. Snyk: best developer experience, IDE integration, fix advice, commercial. Grype: SBOM-native, Syft integration, air-gapped capable, free, Apache license. Use Trivy as primary, Grype for cross-ref, Snyk for developer workflows.
Kyverno: K8s-native YAML policies, simpler, auto-generation, mutate support. OPA/Gatekeeper: Rego language, more expressive, cross-platform, larger community. Kyverno for K8s-only. OPA for multi-platform.
Keyless (Cosign OIDC): no key management, CI provider identity, cloud CI suitable. Key-based: full control, air-gapped, offline verification, key management overhead. Keyless for cloud-native. Key-based for regulated/air-gapped.
# .github/workflows/container-scan.yml
name: Container Security
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
build-and-scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Build Image
run: docker build -t app:${{ github.sha }} .
- name: Trivy Scan
uses: aquasecurity/trivy-action@master
with:
image-ref: app:${{ github.sha }}
format: sarif
severity: CRITICAL,HIGH
exit-code: 1
- name: Generate SBOM
uses: anchore/sbom-action@v0
with:
image: app:${{ github.sha }}
format: cyclonedx-json
- name: Sign Image
run: |
cosign sign --keyless \
--identity-token ${{ secrets.ID_TOKEN }} \
registry.example.com/app@${{ steps.digest.outputs.digest }}
- name: Push to Registry
run: docker push registry.example.com/app:${{ github.sha }}
container-scan:
stage: test
image:
name: aquasec/trivy:latest
entrypoint: [""]
script:
- trivy image --severity CRITICAL,HIGH --exit-code 1 $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA
- syft packages $CI_REGISTRY_IMAGE:$CI_COMMIT_SHA -o cyclonedx-json > sbom.json
artifacts:
reports:
cyclonedx: sbom.json
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: require-non-root
spec:
validationFailureAction: Enforce
rules:
- name: check-run-as-non-root
match:
any:
- resources:
kinds: ["Pod"]
validate:
message: "Containers must run as non-root user"
pattern:
spec:
securityContext:
runAsNonRoot: true
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
name: block-privileged
spec:
validationFailureAction: Enforce
rules:
- name: check-privileged
match:
any:
- resources:
kinds: ["Pod"]
validate:
message: "Privileged containers are not allowed"
pattern:
spec:
containers:
- securityContext:
privileged: false
latest tag is ambiguous — point to different images over time. No traceability, no rollback, no audit. Use semantic versioning (v1.2.3) or commit SHA (sha-abc123) for immutable references. Enforce with admission controller blocking latest.
Pulling base images from Docker Hub without verification. Base images can contain malware, outdated packages, or backdoors. Use only verified official images. Pin to digest. Scan base images before building. Use Docker Content Trust or Cosign verification.
New CVEs discovered daily. An image passing scan at build time may have critical vulnerabilities hours later. Rescan deployed images daily. Alert on new critical findings in running workloads. Auto-create tickets.
Containers without CPU/memory limits can DoS the host node. One compromised container can starve others. Always set resource requests and limits. Admission policy should require resource specifications.
Using ENV or build args for secrets embeds them in image layers. Anyone with docker history or registry access can extract secrets. Use RUN --mount=type=secret for build-time secrets. Inject runtime secrets via volumes, env-from, or secrets manager.
Not all CVEs are exploitable in your context. A CVE in a library function never called from application code is low risk. Use reachability analysis (Snyk, Mend) to prioritize fixable and reachable vulnerabilities. Gate only on reachable critical/high.
Blocking every CVE without exceptions causes deployment paralysis. Establish a documented exception process with compensating controls, owner approval, and expiry dates. Track exception metrics and reduce over time.
Manual triage does not scale beyond 10-20 images. Automate vulnerability scanning results correlation with reachability, fixability, and exploitability (EPSS score). Auto-assign findings to service teams based on image ownership.
latest tags used in productionsecurity-secrets-management for credential injection security-api-security for gateway and service mesh policies