
Hardening Docker Containers For Production
- 179 installs
- 27.3k repo stars
- Updated August 2, 2026
- mukul975/anthropic-cybersecurity-skills
Helps with devops & ci/cd tasks.
About
hardening-docker-containers-for-production is a Claude Code skill in the DevOps & CI/CD category.
- hardening-docker-containers-for-production
- DevOps & CI/CD
- AI-coding skill
Hardening Docker Containers For Production by the numbers
- 179 all-time installs (skills.sh)
- +15 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #426 of 1,435 DevOps & CI/CD skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill hardening-docker-containers-for-productionAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 179 |
|---|---|
| repo stars | ★ 27.3k |
| Last updated | August 2, 2026 |
| Repository | mukul975/anthropic-cybersecurity-skills ↗ |
What it does
Helps with devops & ci/cd tasks.
Files
Hardening Docker Containers for Production
Overview
Hardening Docker containers for production involves applying security best practices aligned with CIS Docker Benchmark v1.8.0 to minimize attack surface, prevent privilege escalation, and enforce least-privilege principles across Docker daemon, images, containers, and runtime configurations.
When to Use
- When deploying or configuring hardening docker containers for production capabilities in your environment
- When establishing security controls aligned to compliance requirements
- When building or improving security architecture for this domain
- When conducting security assessments that require this implementation
Prerequisites
- Docker Engine 24.0+ installed
- Docker Compose v2
- Linux host with kernel 5.10+
- Root or sudo access on Docker host
- docker-bench-security tool
- Hadolint for Dockerfile linting
- Dockle for image linting
Core Concepts
CIS Docker Benchmark Sections
1. Host Configuration - Audit Docker daemon files, restrict access to /var/run/docker.sock 2. Docker Daemon Configuration - Enable TLS, restrict inter-container communication, configure logging 3. Docker Daemon Configuration Files - Set ownership and permissions on daemon.json 4. Container Images and Build File - Use trusted base images, scan for vulnerabilities, multi-stage builds 5. Container Runtime - Drop capabilities, read-only rootfs, restrict syscalls 6. Docker Security Operations - Monitor, audit, and rotate credentials
Key Hardening Principles
- Least Privilege: Run containers as non-root, drop all capabilities except required
- Immutability: Use read-only root filesystem, tmpfs for writable directories
- Minimalism: Use distroless or Alpine base images, multi-stage builds
- Isolation: Apply seccomp profiles, AppArmor/SELinux, namespace restrictions
- Auditability: Enable content trust, log all container activity
Workflow
Step 1: Harden the Dockerfile
# Use specific digest for reproducibility
FROM python:3.12-slim@sha256:abc123... AS builder
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir --user -r requirements.txt
# Production stage - minimal image
FROM gcr.io/distroless/python3-debian12
# Copy only necessary artifacts
COPY --from=builder /root/.local /root/.local
COPY --from=builder /app /app
WORKDIR /app
# Create non-root user
USER 65534:65534
# Set read-only filesystem expectation
LABEL org.opencontainers.image.source="https://github.com/org/app"
ENTRYPOINT ["python", "app.py"]Step 2: Harden Docker Daemon Configuration
{
"icc": false,
"log-driver": "json-file",
"log-opts": {
"max-size": "10m",
"max-file": "3"
},
"live-restore": true,
"userland-proxy": false,
"no-new-privileges": true,
"default-ulimits": {
"nofile": {
"Name": "nofile",
"Hard": 64000,
"Soft": 64000
},
"nproc": {
"Name": "nproc",
"Hard": 1024,
"Soft": 1024
}
},
"seccomp-profile": "/etc/docker/seccomp-default.json",
"tls": true,
"tlscacert": "/etc/docker/tls/ca.pem",
"tlscert": "/etc/docker/tls/server-cert.pem",
"tlskey": "/etc/docker/tls/server-key.pem",
"tlsverify": true
}Step 3: Harden Container Runtime
docker run -d \
--name production-app \
--read-only \
--tmpfs /tmp:rw,noexec,nosuid,size=100m \
--tmpfs /var/run:rw,noexec,nosuid,size=10m \
--cap-drop ALL \
--cap-add NET_BIND_SERVICE \
--security-opt no-new-privileges:true \
--security-opt seccomp=/etc/docker/seccomp-default.json \
--security-opt apparmor=docker-default \
--pids-limit 100 \
--memory 512m \
--memory-swap 512m \
--cpus 1.0 \
--user 65534:65534 \
--network custom-bridge \
--restart on-failure:3 \
--health-cmd "curl -f http://localhost:8080/health || exit 1" \
--health-interval 30s \
--health-timeout 10s \
--health-retries 3 \
myapp:latestStep 4: Enable Docker Content Trust
export DOCKER_CONTENT_TRUST=1
export DOCKER_CONTENT_TRUST_SERVER=https://notary.example.com
# Sign and push image
docker trust sign myregistry.com/myapp:v1.0.0
# Verify image signature before pull
docker trust inspect --pretty myregistry.com/myapp:v1.0.0Step 5: Configure Host-Level Auditing
# Add audit rules for Docker files and directories
cat >> /etc/audit/rules.d/docker.rules << 'EOF'
-w /usr/bin/docker -k docker
-w /var/lib/docker -k docker
-w /etc/docker -k docker
-w /lib/systemd/system/docker.service -k docker
-w /lib/systemd/system/docker.socket -k docker
-w /etc/default/docker -k docker
-w /etc/docker/daemon.json -k docker
-w /usr/bin/containerd -k docker
-w /usr/bin/runc -k docker
EOF
systemctl restart auditdValidation Commands
# Run Docker Bench Security
docker run --rm --net host --pid host \
--userns host --cap-add audit_control \
-e DOCKER_CONTENT_TRUST=$DOCKER_CONTENT_TRUST \
-v /etc:/etc:ro \
-v /usr/bin/containerd:/usr/bin/containerd:ro \
-v /usr/bin/runc:/usr/bin/runc:ro \
-v /usr/lib/systemd:/usr/lib/systemd:ro \
-v /var/lib:/var/lib:ro \
-v /var/run/docker.sock:/var/run/docker.sock:ro \
docker/docker-bench-security
# Lint Dockerfile
hadolint Dockerfile
# Lint built image
dockle myapp:latest
# Verify no containers running as root
docker ps -q | xargs docker inspect --format '{{.Id}}: User={{.Config.User}}'Key Security Controls
| Control | Implementation | CIS Section |
|---|---|---|
| Non-root user | USER instruction in Dockerfile | 4.1 |
| Read-only rootfs | --read-only flag | 5.12 |
| Drop capabilities | --cap-drop ALL | 5.3 |
| Resource limits | --memory, --cpus, --pids-limit | 5.10 |
| No new privileges | --security-opt no-new-privileges | 5.25 |
| Content trust | DOCKER_CONTENT_TRUST=1 | 4.5 |
| TLS for daemon | daemon.json TLS config | 2.6 |
| Audit logging | auditd rules | 1.1 |
References
Docker Container Hardening Assessment Template
Project Information
| Field | Value |
|---|---|
| Application Name | |
| Docker Image | |
| Base Image | |
| Environment | Development / Staging / Production |
| Assessment Date | |
| Assessor |
Pre-Hardening Checklist
Dockerfile Security
- [ ] Using minimal base image (distroless, Alpine, scratch)
- [ ] Specific image tag with digest pinning (not :latest)
- [ ] Multi-stage build implemented
- [ ] Non-root USER instruction present
- [ ] COPY used instead of ADD
- [ ] No secrets in Dockerfile or image layers
- [ ] HEALTHCHECK instruction present
- [ ] Unnecessary packages removed
- [ ] setuid/setgid binaries removed
Daemon Configuration (/etc/docker/daemon.json)
- [ ] icc set to false
- [ ] TLS authentication enabled (tlsverify: true)
- [ ] Live restore enabled
- [ ] Userland proxy disabled
- [ ] no-new-privileges enabled
- [ ] Log rotation configured (max-size, max-file)
- [ ] Default ulimits configured
- [ ] Seccomp profile specified
Runtime Security Flags
- [ ] --read-only enabled
- [ ] --cap-drop ALL applied
- [ ] Minimum --cap-add for required capabilities only
- [ ] --security-opt no-new-privileges:true
- [ ] --security-opt seccomp=<profile>
- [ ] --memory limit set
- [ ] --cpus limit set
- [ ] --pids-limit set
- [ ] --user set to non-root UID:GID
- [ ] --tmpfs for writable directories
- [ ] --network set to custom bridge (not host)
- [ ] --restart on-failure with max retries
Host Security
- [ ] Separate partition for /var/lib/docker
- [ ] Docker group membership restricted
- [ ] Audit rules configured for Docker files
- [ ] Docker socket not exposed to containers
- [ ] Content Trust enabled (DOCKER_CONTENT_TRUST=1)
Vulnerability Scan Results
Trivy Scan
trivy image <image-name>| Severity | Count | Action Required |
|---|---|---|
| CRITICAL | Immediate fix | |
| HIGH | Fix before production | |
| MEDIUM | Plan remediation | |
| LOW | Accept or fix |
Docker Bench Score
docker run --rm docker/docker-bench-security| Section | Score | Notes |
|---|---|---|
| Host Configuration | /10 | |
| Daemon Configuration | /10 | |
| Container Images | /10 | |
| Container Runtime | /10 | |
| Docker Security Ops | /10 |
Risk Acceptance
| Finding | Severity | Justification | Approved By | Date |
|---|---|---|---|---|
Remediation Plan
| Priority | Finding | Action | Owner | Target Date | Status |
|---|---|---|---|---|---|
| P1 | |||||
| P2 | |||||
| P3 |
Sign-Off
| Role | Name | Signature | Date |
|---|---|---|---|
| Security Engineer | |||
| DevOps Lead | |||
| Application Owner |
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to the Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by the Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding any notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. Please do not remove or change
the license header comment from a contributed file except when
necessary.
Copyright 2026 mukul975
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
API Reference: Docker Container Hardening
Docker CLI
List Containers
docker ps --format '{{json .}}'Inspect Container
docker inspect <container_id>Key Inspect Fields
| Path | Description |
|---|---|
.HostConfig.Privileged | Privileged mode |
.HostConfig.NetworkMode | Network namespace |
.HostConfig.CapAdd | Added capabilities |
.HostConfig.ReadonlyRootfs | Read-only filesystem |
.HostConfig.Memory | Memory limit (bytes) |
.Config.User | Container user |
CIS Docker Benchmark Checks
| Check | Description | Severity |
|---|---|---|
| 4.1 | Non-root user | HIGH |
| 5.3 | Restrict capabilities | HIGH |
| 5.4 | No privileged containers | CRITICAL |
| 5.5 | No sensitive host mounts | HIGH |
| 5.10 | No host network | HIGH |
| 5.12 | Read-only root FS | MEDIUM |
| 5.13 | CPU limits set | LOW |
| 5.14 | Memory limits set | MEDIUM |
Secure Dockerfile Practices
Non-Root User
FROM alpine:3.18
RUN adduser -D appuser
USER appuserRead-Only Filesystem
docker run --read-only --tmpfs /tmp:rw,noexec,nosuid myimageDrop Capabilities
docker run --cap-drop ALL --cap-add NET_BIND_SERVICE myimageResource Limits
docker run --memory=512m --cpus=1.0 myimageDocker Bench Security
Run Audit
docker run --rm --net host --pid host --userns host \
--cap-add audit_control \
-v /var/lib:/var/lib \
-v /var/run/docker.sock:/var/run/docker.sock \
-v /etc:/etc \
docker/docker-bench-securitySeccomp and AppArmor
Custom Seccomp Profile
docker run --security-opt seccomp=profile.json myimageAppArmor Profile
docker run --security-opt apparmor=docker-default myimageStandards Reference - Docker Container Hardening
CIS Docker Benchmark v1.8.0
Section 1: Host Configuration
- 1.1.1: Ensure a separate partition for containers has been created
- 1.1.2: Ensure only trusted users are allowed to control Docker daemon
- 1.1.3-1.1.18: Ensure Docker daemon audit configuration
Section 2: Docker Daemon Configuration
- 2.1: Run the Docker daemon as non-root user (rootless mode)
- 2.2: Ensure network traffic is restricted between containers (--icc=false)
- 2.3: Ensure logging level is set to info
- 2.4: Ensure Docker is allowed to make changes to iptables
- 2.5: Ensure insecure registries are not used
- 2.6: Ensure aufs storage driver is not used
- 2.7: Ensure TLS authentication for Docker daemon is configured
- 2.8: Ensure default ulimit is configured appropriately
- 2.9: Enable user namespace support
- 2.10: Ensure default cgroup usage has been confirmed
- 2.11: Ensure base device size is not changed until needed
- 2.12: Ensure centralized and remote logging is configured
- 2.13: Ensure live restore is enabled
- 2.14: Ensure Userland Proxy is disabled
- 2.15: Ensure daemon-wide custom seccomp profile is applied
- 2.16: Ensure experimental features are not used in production
- 2.17: Ensure containers are restricted from acquiring new privileges
Section 4: Container Images and Build Files
- 4.1: Ensure that a user for the container has been created
- 4.2: Ensure containers use trusted base images
- 4.3: Ensure unnecessary packages are not installed
- 4.4: Ensure images are scanned for vulnerabilities
- 4.5: Ensure Content trust for Docker is enabled
- 4.6: Ensure HEALTHCHECK instructions have been added to container images
- 4.7: Ensure update instructions are not used alone in the Dockerfile
- 4.8: Ensure setuid and setgid permissions are removed
- 4.9: Ensure COPY is used instead of ADD
- 4.10: Ensure secrets are not stored in Dockerfiles
- 4.11: Ensure only verified packages are installed
Section 5: Container Runtime
- 5.1: Ensure AppArmor profile is enabled
- 5.2: Ensure SELinux security options are set
- 5.3: Ensure Linux kernel capabilities are restricted
- 5.4: Ensure privileged containers are not used
- 5.5: Ensure sensitive host system directories are not mounted
- 5.6: Ensure sshd is not running within containers
- 5.7: Ensure privileged ports are not mapped within containers
- 5.8: Ensure only needed ports are open on the container
- 5.9: Ensure host network mode is not used
- 5.10: Ensure memory usage for container is limited
- 5.11: Ensure CPU priority is set appropriately
- 5.12: Ensure container root filesystem is mounted as read only
- 5.13: Ensure incoming container traffic is bound to a specific host interface
- 5.25: Ensure container is restricted from acquiring additional privileges
NIST SP 800-190 - Application Container Security Guide
Key Recommendations
- Use container-specific host OS (CoreOS, Flatcar, Bottlerocket)
- Segment container networks by sensitivity level
- Use container runtime with minimal attack surface
- Implement image signing and verification
- Harden container registries with access controls
- Monitor container runtime behavior for anomalies
OWASP Docker Security Cheat Sheet
Top Docker Security Risks
1. Unrestricted container access to host resources 2. Running containers in privileged mode 3. Running as root inside containers 4. Unverified or unscanned container images 5. Exposed Docker daemon socket 6. Insecure container networking 7. Secrets stored in images or environment variables 8. Missing resource limits 9. Outdated base images with known vulnerabilities 10. Insufficient logging and monitoring
Workflows - Docker Container Hardening
Workflow 1: New Container Hardening Pipeline
[Dockerfile Created] --> [Hadolint Lint] --> [Build Image] --> [Dockle Scan]
| | | |
v v v v
Use multi-stage Fix warnings Tag with digest Fix findings
Non-root USER No ADD, use COPY Sign image Remove setuid
Minimal base Pin versions Push to registry Drop caps
| | | |
+----------+-----------+--------------------+ |
| |
v v
[Trivy Vulnerability Scan] -----> [Docker Bench Assessment]
| |
v v
Fix HIGH/CRITICAL CVEs Remediate CIS failures
| |
+------------------------------------+
|
v
[Deploy to Production with Hardened Runtime Flags]
|
v
[Continuous Monitoring with Falco]Workflow 2: Existing Container Remediation
Step 1: Assess Current State
- Run docker-bench-security against host
- Run Trivy scan against all running images
- Audit all running containers for root users
- Check daemon.json configuration
Step 2: Prioritize Remediation
- Critical: Privileged containers, root users, exposed daemon socket
- High: Missing seccomp profiles, no resource limits, capability escalation
- Medium: Missing health checks, no content trust, excessive open ports
- Low: Missing labels, audit rules, log rotation
Step 3: Apply Fixes
- Update Dockerfiles with non-root users
- Rebuild images with multi-stage builds
- Update docker-compose or orchestrator configs
- Configure daemon.json with TLS and security options
Step 4: Validate
- Re-run docker-bench-security
- Confirm score improvement
- Document remaining accepted risksWorkflow 3: CI/CD Integration
# GitHub Actions hardening pipeline
name: Container Hardening Pipeline
on: [push]
jobs:
lint-dockerfile:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: hadolint/hadolint-action@v3.1.0
with:
dockerfile: Dockerfile
build-and-scan:
needs: lint-dockerfile
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Build image
run: docker build -t myapp:${{ github.sha }} .
- name: Dockle lint
uses: erzz/dockle-action@v1
with:
image: myapp:${{ github.sha }}
failure-threshold: WARN
- name: Trivy scan
uses: aquasecurity/trivy-action@master
with:
image-ref: myapp:${{ github.sha }}
format: table
exit-code: 1
severity: CRITICAL,HIGH
- name: Sign image with Cosign
if: github.ref == 'refs/heads/main'
uses: sigstore/cosign-installer@v3
run: cosign sign --yes myapp:${{ github.sha }}Workflow 4: Runtime Hardening Checklist
Pre-deployment:
[ ] Image built from minimal base (distroless/Alpine)
[ ] Non-root USER specified in Dockerfile
[ ] No secrets in image layers
[ ] Image signed and verified
[ ] Vulnerability scan shows no CRITICAL/HIGH CVEs
[ ] Hadolint and Dockle pass with zero errors
Runtime configuration:
[ ] --read-only flag enabled
[ ] --cap-drop ALL with minimum cap-add
[ ] --security-opt no-new-privileges:true
[ ] --security-opt seccomp=<profile>
[ ] --memory and --cpus limits set
[ ] --pids-limit configured
[ ] --user flag set to non-root UID
[ ] --tmpfs for writable directories only
[ ] Health check configured
[ ] Restart policy set (on-failure with max retries)
Host configuration:
[ ] Docker daemon TLS enabled
[ ] Inter-container communication disabled (icc=false)
[ ] User namespace remapping enabled
[ ] Audit rules for Docker binaries and directories
[ ] Docker socket not exposed to containers#!/usr/bin/env python3
"""Agent for auditing Docker container security and applying CIS hardening."""
import argparse
import json
import subprocess
import sys
from datetime import datetime, timezone
def get_running_containers():
"""List running Docker containers with details."""
try:
result = subprocess.check_output(
["docker", "ps", "--format", "{{json .}}"],
text=True, errors="replace", timeout=10
)
containers = []
for line in result.strip().splitlines():
if line:
containers.append(json.loads(line))
return containers
except (subprocess.SubprocessError, json.JSONDecodeError):
return []
def inspect_container(container_id):
"""Get detailed container configuration."""
try:
result = subprocess.check_output(
["docker", "inspect", container_id],
text=True, errors="replace", timeout=10
)
return json.loads(result)[0]
except (subprocess.SubprocessError, json.JSONDecodeError):
return {}
def audit_container(container_id):
"""Audit a container against CIS Docker Benchmark checks."""
findings = []
config = inspect_container(container_id)
if not config:
return findings
host_config = config.get("HostConfig", {})
name = config.get("Name", container_id)
if host_config.get("Privileged"):
findings.append({"check": "CIS 5.4", "issue": "Container runs privileged", "severity": "CRITICAL"})
if host_config.get("NetworkMode") == "host":
findings.append({"check": "CIS 5.10", "issue": "Uses host network", "severity": "HIGH"})
if host_config.get("PidMode") == "host":
findings.append({"check": "CIS 5.15", "issue": "Shares host PID namespace", "severity": "HIGH"})
if host_config.get("IpcMode") == "host":
findings.append({"check": "CIS 5.16", "issue": "Shares host IPC namespace", "severity": "HIGH"})
user = config.get("Config", {}).get("User", "")
if not user or user == "root" or user == "0":
findings.append({"check": "CIS 4.1", "issue": "Container runs as root", "severity": "HIGH"})
cap_add = host_config.get("CapAdd") or []
if "SYS_ADMIN" in cap_add:
findings.append({"check": "CIS 5.3", "issue": "SYS_ADMIN capability added", "severity": "CRITICAL"})
if "NET_ADMIN" in cap_add:
findings.append({"check": "CIS 5.3", "issue": "NET_ADMIN capability added", "severity": "HIGH"})
if not host_config.get("ReadonlyRootfs"):
findings.append({"check": "CIS 5.12", "issue": "Root filesystem not read-only", "severity": "MEDIUM"})
memory = host_config.get("Memory", 0)
if memory == 0:
findings.append({"check": "CIS 5.14", "issue": "No memory limit set", "severity": "MEDIUM"})
cpu_shares = host_config.get("CpuShares", 0)
if cpu_shares == 0:
findings.append({"check": "CIS 5.13", "issue": "No CPU limit set", "severity": "LOW"})
restart = host_config.get("RestartPolicy", {}).get("Name", "")
if restart == "always":
findings.append({"check": "CIS 5.14", "issue": "RestartPolicy=always (use on-failure)", "severity": "LOW"})
mounts = host_config.get("Binds") or []
sensitive = ["/", "/etc", "/var/run/docker.sock", "/proc", "/sys"]
for mount in mounts:
src = mount.split(":")[0]
if src in sensitive:
findings.append({"check": "CIS 5.5", "issue": f"Sensitive host mount: {src}", "severity": "HIGH"})
return findings
def main():
parser = argparse.ArgumentParser(
description="Audit Docker containers against CIS benchmarks"
)
parser.add_argument("--container", help="Specific container ID to audit")
parser.add_argument("--all", action="store_true", help="Audit all running containers")
parser.add_argument("--output", "-o", help="Output JSON report")
args = parser.parse_args()
print("[*] Docker Container Hardening Audit Agent")
report = {"timestamp": datetime.now(timezone.utc).isoformat(), "audits": []}
if args.all:
containers = get_running_containers()
print(f"[*] Found {len(containers)} running containers")
for c in containers:
cid = c.get("ID", "")
findings = audit_container(cid)
report["audits"].append({"container": c.get("Names", cid), "findings": findings})
elif args.container:
findings = audit_container(args.container)
report["audits"].append({"container": args.container, "findings": findings})
total = sum(len(a["findings"]) for a in report["audits"])
critical = sum(1 for a in report["audits"] for f in a["findings"] if f["severity"] == "CRITICAL")
print(f"[*] Total findings: {total} (CRITICAL: {critical})")
if args.output:
with open(args.output, "w") as f:
json.dump(report, f, indent=2)
print(f"[*] Report saved to {args.output}")
else:
print(json.dumps(report, indent=2))
if __name__ == "__main__":
main()
#!/usr/bin/env python3
"""
Docker Container Hardening Assessment Tool
Audits Docker daemon configuration, running containers, and images
against CIS Docker Benchmark v1.8.0 hardening requirements.
"""
import subprocess
import json
import sys
import os
import re
from dataclasses import dataclass, field
from typing import Optional
@dataclass
class Finding:
check_id: str
title: str
severity: str # CRITICAL, HIGH, MEDIUM, LOW, INFO
status: str # PASS, FAIL, WARN, INFO
details: str
remediation: str
@dataclass
class HardeningReport:
findings: list = field(default_factory=list)
total_pass: int = 0
total_fail: int = 0
total_warn: int = 0
def add(self, finding: Finding):
self.findings.append(finding)
if finding.status == "PASS":
self.total_pass += 1
elif finding.status == "FAIL":
self.total_fail += 1
elif finding.status == "WARN":
self.total_warn += 1
def run_command(cmd: list, timeout: int = 30) -> tuple:
"""Execute a shell command and return (returncode, stdout, stderr)."""
try:
result = subprocess.run(
cmd, capture_output=True, text=True, timeout=timeout
)
return result.returncode, result.stdout.strip(), result.stderr.strip()
except subprocess.TimeoutExpired:
return -1, "", "Command timed out"
except FileNotFoundError:
return -1, "", f"Command not found: {cmd[0]}"
def check_docker_available() -> bool:
"""Verify Docker is installed and accessible."""
rc, out, _ = run_command(["docker", "version", "--format", "{{.Server.Version}}"])
if rc == 0:
print(f"[*] Docker version: {out}")
return True
print("[!] Docker is not available or not running")
return False
def check_daemon_config(report: HardeningReport):
"""Check Docker daemon.json configuration against CIS benchmarks."""
daemon_config_path = "/etc/docker/daemon.json"
if not os.path.exists(daemon_config_path):
report.add(Finding(
check_id="2.0",
title="Docker daemon configuration file exists",
severity="HIGH",
status="FAIL",
details="daemon.json not found at /etc/docker/daemon.json",
remediation="Create /etc/docker/daemon.json with security-hardened settings"
))
return
with open(daemon_config_path, "r") as f:
try:
config = json.load(f)
except json.JSONDecodeError:
report.add(Finding(
check_id="2.0",
title="Docker daemon configuration is valid JSON",
severity="HIGH",
status="FAIL",
details="daemon.json contains invalid JSON",
remediation="Fix JSON syntax in /etc/docker/daemon.json"
))
return
# Check 2.2: Inter-container communication
icc = config.get("icc", True)
report.add(Finding(
check_id="2.2",
title="Network traffic restricted between containers",
severity="HIGH",
status="PASS" if icc is False else "FAIL",
details=f"icc is set to {icc}",
remediation='Set "icc": false in daemon.json to restrict inter-container communication'
))
# Check 2.7: TLS authentication
tls_verify = config.get("tlsverify", False)
report.add(Finding(
check_id="2.7",
title="TLS authentication for Docker daemon",
severity="CRITICAL",
status="PASS" if tls_verify else "FAIL",
details=f"tlsverify is {tls_verify}",
remediation='Enable TLS: set "tls": true, "tlsverify": true with cert paths in daemon.json'
))
# Check 2.13: Live restore
live_restore = config.get("live-restore", False)
report.add(Finding(
check_id="2.13",
title="Live restore is enabled",
severity="MEDIUM",
status="PASS" if live_restore else "WARN",
details=f"live-restore is {live_restore}",
remediation='Set "live-restore": true in daemon.json'
))
# Check 2.14: Userland proxy disabled
userland_proxy = config.get("userland-proxy", True)
report.add(Finding(
check_id="2.14",
title="Userland Proxy is disabled",
severity="MEDIUM",
status="PASS" if userland_proxy is False else "WARN",
details=f"userland-proxy is {userland_proxy}",
remediation='Set "userland-proxy": false in daemon.json'
))
# Check 2.17: No new privileges
no_new_privs = config.get("no-new-privileges", False)
report.add(Finding(
check_id="2.17",
title="Containers restricted from acquiring new privileges",
severity="HIGH",
status="PASS" if no_new_privs else "FAIL",
details=f"no-new-privileges is {no_new_privs}",
remediation='Set "no-new-privileges": true in daemon.json'
))
# Check logging configuration
log_driver = config.get("log-driver", "json-file")
log_opts = config.get("log-opts", {})
has_log_limits = "max-size" in log_opts and "max-file" in log_opts
report.add(Finding(
check_id="2.12",
title="Logging is properly configured with rotation",
severity="MEDIUM",
status="PASS" if has_log_limits else "WARN",
details=f"log-driver={log_driver}, max-size={log_opts.get('max-size', 'not set')}, max-file={log_opts.get('max-file', 'not set')}",
remediation='Configure log-opts with max-size and max-file in daemon.json'
))
def check_running_containers(report: HardeningReport):
"""Audit running containers against CIS runtime checks."""
rc, out, _ = run_command([
"docker", "ps", "-q"
])
if rc != 0 or not out:
report.add(Finding(
check_id="5.0",
title="Running containers found",
severity="INFO",
status="INFO",
details="No running containers found to audit",
remediation="N/A"
))
return
container_ids = out.split("\n")
print(f"[*] Auditing {len(container_ids)} running containers")
for cid in container_ids:
rc, inspect_out, _ = run_command([
"docker", "inspect", cid
])
if rc != 0:
continue
try:
container = json.loads(inspect_out)[0]
except (json.JSONDecodeError, IndexError):
continue
name = container.get("Name", cid).lstrip("/")
host_config = container.get("HostConfig", {})
config = container.get("Config", {})
# Check 5.4: Privileged mode
privileged = host_config.get("Privileged", False)
report.add(Finding(
check_id="5.4",
title=f"[{name}] Not running in privileged mode",
severity="CRITICAL",
status="PASS" if not privileged else "FAIL",
details=f"Privileged={privileged}",
remediation="Remove --privileged flag. Use specific --cap-add instead."
))
# Check 5.3: Capabilities
cap_add = host_config.get("CapAdd") or []
cap_drop = host_config.get("CapDrop") or []
all_dropped = "ALL" in [c.upper() for c in cap_drop] if cap_drop else False
report.add(Finding(
check_id="5.3",
title=f"[{name}] Linux capabilities are restricted",
severity="HIGH",
status="PASS" if all_dropped else "FAIL",
details=f"CapDrop={cap_drop}, CapAdd={cap_add}",
remediation="Use --cap-drop ALL and only --cap-add specific required capabilities"
))
# Check 5.12: Read-only root filesystem
read_only = host_config.get("ReadonlyRootfs", False)
report.add(Finding(
check_id="5.12",
title=f"[{name}] Root filesystem is read-only",
severity="HIGH",
status="PASS" if read_only else "FAIL",
details=f"ReadonlyRootfs={read_only}",
remediation="Run with --read-only and use --tmpfs for writable directories"
))
# Check 4.1: Non-root user
user = config.get("User", "")
report.add(Finding(
check_id="4.1",
title=f"[{name}] Running as non-root user",
severity="HIGH",
status="PASS" if user and user != "0" and user != "root" else "FAIL",
details=f"User={user if user else 'root (default)'}",
remediation="Set USER in Dockerfile or use --user flag at runtime"
))
# Check 5.10: Memory limit
memory = host_config.get("Memory", 0)
report.add(Finding(
check_id="5.10",
title=f"[{name}] Memory usage is limited",
severity="MEDIUM",
status="PASS" if memory > 0 else "FAIL",
details=f"Memory limit={memory} bytes" if memory > 0 else "No memory limit set",
remediation="Set --memory flag to limit container memory usage"
))
# Check 5.25: No new privileges
security_opts = host_config.get("SecurityOpt") or []
no_new_privs = any("no-new-privileges" in opt for opt in security_opts)
report.add(Finding(
check_id="5.25",
title=f"[{name}] No new privileges restriction",
severity="HIGH",
status="PASS" if no_new_privs else "FAIL",
details=f"SecurityOpt={security_opts}",
remediation="Use --security-opt no-new-privileges:true"
))
# Check 5.28: PID limits
pids_limit = host_config.get("PidsLimit", 0)
report.add(Finding(
check_id="5.28",
title=f"[{name}] PIDs limit is set",
severity="MEDIUM",
status="PASS" if pids_limit and pids_limit > 0 else "WARN",
details=f"PidsLimit={pids_limit}",
remediation="Set --pids-limit to prevent fork bomb attacks"
))
# Check health check
healthcheck = config.get("Healthcheck", {})
has_healthcheck = bool(healthcheck and healthcheck.get("Test"))
report.add(Finding(
check_id="4.6",
title=f"[{name}] Health check is configured",
severity="LOW",
status="PASS" if has_healthcheck else "WARN",
details=f"Healthcheck configured: {has_healthcheck}",
remediation="Add HEALTHCHECK instruction in Dockerfile"
))
def check_docker_socket(report: HardeningReport):
"""Check if Docker socket is exposed to any container."""
rc, out, _ = run_command([
"docker", "ps", "-q"
])
if rc != 0 or not out:
return
for cid in out.split("\n"):
rc, inspect_out, _ = run_command(["docker", "inspect", cid])
if rc != 0:
continue
try:
container = json.loads(inspect_out)[0]
except (json.JSONDecodeError, IndexError):
continue
name = container.get("Name", cid).lstrip("/")
mounts = container.get("Mounts", [])
for mount in mounts:
source = mount.get("Source", "")
if "docker.sock" in source:
report.add(Finding(
check_id="5.31",
title=f"[{name}] Docker socket mounted",
severity="CRITICAL",
status="FAIL",
details=f"Docker socket mounted from {source}",
remediation="Remove Docker socket mount. Use Docker API proxy with restricted access."
))
break
def check_content_trust(report: HardeningReport):
"""Check if Docker Content Trust is enabled."""
dct = os.environ.get("DOCKER_CONTENT_TRUST", "0")
report.add(Finding(
check_id="4.5",
title="Docker Content Trust is enabled",
severity="HIGH",
status="PASS" if dct == "1" else "FAIL",
details=f"DOCKER_CONTENT_TRUST={dct}",
remediation="Set DOCKER_CONTENT_TRUST=1 environment variable"
))
def generate_report(report: HardeningReport) -> dict:
"""Generate JSON report from findings."""
score = (report.total_pass / max(len(report.findings), 1)) * 100
output = {
"tool": "Docker Hardening Assessment",
"framework": "CIS Docker Benchmark v1.8.0",
"summary": {
"total_checks": len(report.findings),
"passed": report.total_pass,
"failed": report.total_fail,
"warnings": report.total_warn,
"score_percent": round(score, 1)
},
"findings": []
}
for f in report.findings:
output["findings"].append({
"check_id": f.check_id,
"title": f.title,
"severity": f.severity,
"status": f.status,
"details": f.details,
"remediation": f.remediation
})
return output
def print_summary(report_data: dict):
"""Print human-readable summary."""
summary = report_data["summary"]
print("\n" + "=" * 70)
print("DOCKER HARDENING ASSESSMENT REPORT")
print(f"Framework: {report_data['framework']}")
print("=" * 70)
print(f"Total Checks: {summary['total_checks']}")
print(f"Passed: {summary['passed']}")
print(f"Failed: {summary['failed']}")
print(f"Warnings: {summary['warnings']}")
print(f"Score: {summary['score_percent']}%")
print("=" * 70)
# Print failures
failures = [f for f in report_data["findings"] if f["status"] == "FAIL"]
if failures:
print("\nFAILED CHECKS:")
print("-" * 70)
for f in sorted(failures, key=lambda x: {"CRITICAL": 0, "HIGH": 1, "MEDIUM": 2, "LOW": 3}.get(x["severity"], 4)):
print(f" [{f['severity']}] {f['check_id']}: {f['title']}")
print(f" Details: {f['details']}")
print(f" Fix: {f['remediation']}")
print()
def main():
print("[*] Docker Container Hardening Assessment Tool")
print("[*] Based on CIS Docker Benchmark v1.8.0\n")
if not check_docker_available():
sys.exit(1)
report = HardeningReport()
print("[*] Checking daemon configuration...")
check_daemon_config(report)
print("[*] Checking Docker Content Trust...")
check_content_trust(report)
print("[*] Auditing running containers...")
check_running_containers(report)
print("[*] Checking Docker socket exposure...")
check_docker_socket(report)
report_data = generate_report(report)
print_summary(report_data)
# Save JSON report
output_file = "docker_hardening_report.json"
with open(output_file, "w") as f:
json.dump(report_data, f, indent=2)
print(f"\n[*] Full report saved to {output_file}")
# Exit with failure if critical/high findings
critical_high_failures = [
f for f in report_data["findings"]
if f["status"] == "FAIL" and f["severity"] in ("CRITICAL", "HIGH")
]
if critical_high_failures:
print(f"\n[!] {len(critical_high_failures)} CRITICAL/HIGH failures found")
sys.exit(1)
print("\n[+] Assessment complete")
if __name__ == "__main__":
main()