К основному содержанию
скилл CX Codex

hardening-docker-containers-for-production — скилл для Claude Code

Скилл укрепляет Dockerfile, образы и настройки контейнеров по CIS Docker Benchmark v1.8.0. Пригодится перед production-развёртыванием и аудитом.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add mukul975/Anthropic-Cybersecurity-Skills --skill hardening-docker-containers-for-production -a claude-code
Открыть на GitHub

Что делает hardening-docker-containers-for-production

Скилл проверяет и предлагает усилить Dockerfile, собранные образы и параметры запуска контейнеров. В фокусе запуск от непривилегированного пользователя, удаление capabilities, read-only root filesystem, ограничения ресурсов, seccomp и AppArmor. Для сборки используются минимальные multi-stage-образы, а доверие к образам можно проверять через Docker Content Trust.

Результат проверяется инструментами docker-bench-security, Hadolint и Dockle; отдельно предусмотрены команды для аудита контейнеров, запущенных от root. Скилл ориентирован на CIS Docker Benchmark v1.8.0 и per-container настройки. Конфигурацию самого Docker daemon он не заменяет: для неё нужен hardening-docker-daemon-configuration.

Перед запуском проверьте Docker Engine 24.0+, Docker Compose v2 и Linux host с kernel 5.10+. Нужны root или sudo-доступ, а также docker-bench-security, Hadolint и Dockle. Это повод заранее проверить окружение, особенно если проверки должны выполняться на Linux-хосте.

Какие задачи решает

  • усилить Dockerfile перед production-сборкой
  • запустить контейнер с read-only root filesystem
  • убрать лишние capabilities и права root
  • проверить образ через Hadolint и Dockle
  • сопоставить настройки контейнера с CIS Docker Benchmark

Примеры запросов агенту

  • Проверь мой Dockerfile по CIS Docker Benchmark v1.8.0 и предложи правки для запуска без root.
  • Проведи аудит образа myapp:latest через Hadolint и Dockle, затем перечисли найденные проблемы.
  • Подготовь безопасную команду docker run для production-контейнера с --cap-drop ALL, seccomp и AppArmor.

Как установить hardening-docker-containers-for-production

1Через Skills CLI (Vercel)

npx skills add mukul975/Anthropic-Cybersecurity-Skills --skill hardening-docker-containers-for-production -a claude-code

2Вручную: положить файлы

~/.claude/skills/hardening-docker-containers-for-production/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/hardening-docker-containers-for-production/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Из того же набора87

testing-websocket-api-security Проверяет безопасность WebSocket API: аутентификацию при рукопожатии, токены и уязвимость к CSWSH. Пригодится при аудите защищённости сокетов. CX Codex +1 328установок analyzing-mft-for-deleted-file-recovery Скилл для криминалистического анализа NTFS: разбирает $MFT, $LogFile, $UsnJrnl и slack space, чтобы восстановить метаданные и содержимое удалённых файлов. CX Codex +1 326установок analyzing-memory-forensics-with-lime-and-volatility Скилл помогает выгрузить память ядра Linux через модуль LiME и разобрать дамп во фреймворке Volatility 3 при расследовании инцидентов. CX Codex +1 321установок bypassing-authentication-with-forced-browsing Скилл для пентеста веб-приложений: ищет незакрытые страницы, API и админки перебором URL и проверяет, где аутентификация не enforced. CX Codex +1 321установок conducting-external-reconnaissance-with-osint Скилл собирает профиль цели по открытым источникам: DNS, логи сертификатов, поиск, соцсети, репозитории и утечки. Для пассивной фазы пентеста. CX Codex +1 319установок analyzing-persistence-mechanisms-in-linux Ищет следы закрепления злоумышленника в Linux через cron, службы systemd, LD_PRELOAD и SSH-ключи, сопоставляя находки с auditd. CX Codex +1 319установок analyzing-pdf-malware-with-pdfid Разбирает подозрительный PDF по структуре: находит встроенный JavaScript, шеллкод и эксплойты, не открывая документ. CX Codex +1 317установок analyzing-threat-intelligence-feeds Разбирает коммерческие и открытые фиды киберразведки: вытаскивает индикаторы, тактики противника и контекст кампаний, приводит данные к STIX 2.1. CX Codex +1 316установок

Похожие

windows-hardening devops-skills Скилл для агентов, который приводит Windows Server к Microsoft security baselines и CIS benchmarks: пароли, Group Policy, Windows Defender, SMB. CX Codex +1 388установок container-hardening devops-skills Настраивает запуск контейнеров без root-прав, монтирует файловую систему только для чтения и формирует манифесты Kubernetes securityContext. CX Codex +1 433установок docker-expert sickn33 Скилл для ИИ-агента, который разбирает Dockerfile, multi-stage сборки и безопасность контейнеров. Пригодится, когда нужно навести порядок в образах и Compose. CX Codex +1 27 300установок docker-patterns affaan-m Скилл с проверенными шаблонами Dockerfile и Docker Compose: локальная разработка, сети, тома, безопасность контейнеров. CX Codex +1 6 400установок docker-development Alireza Rezvani Скилл анализирует Dockerfile, Docker Compose и контейнеры: ищет проблемы с размером, сборкой и безопасностью. Подойдёт для настройки контейнеризации. 702установок docker-security-guide JosiahSiegel Скилл для ИИ-агента, который проверяет Docker-конфигурации на уязвимости и подсказывает, как закрыть дыры. CX Codex +1 595установок

Рядом в теме «Безопасность»

Всё по теме «Безопасность» →

Вопросы о hardening-docker-containers-for-production

Как установить hardening-docker-containers-for-production в Claude Code?

Выполните npx skills add mukul975/Anthropic-Cybersecurity-Skills --skill hardening-docker-containers-for-production -a claude-code, затем повторите npx skills add mukul975/Anthropic-Cybersecurity-Skills --skill hardening-docker-containers-for-production -a claude-code. Файл скилла находится по пути ~/.claude/skills/hardening-docker-containers-for-production/SKILL.md.

Что делает hardening-docker-containers-for-production?

Он укрепляет Dockerfile, образы и настройки запуска контейнеров: предлагает non-root, read-only rootfs, drop capabilities, seccomp, AppArmor и минимальные multi-stage-сборки. Проверка выполняется через docker-bench-security, Hadolint и Dockle.

Что нужно для работы скилла?

Нужны Docker Engine 24.0+, Docker Compose v2, Linux host с kernel 5.10+, root или sudo-доступ. Также используются docker-bench-security, Hadolint и Dockle.

Исходный текст

SKILL.md · Apache-2.0
---
name: hardening-docker-containers-for-production
description: >-
  Hardens Dockerfiles, images, and per-container runtime settings against the CIS Docker
  Benchmark v1.8.0: non-root users, dropped capabilities, read-only root filesystem, seccomp
  and AppArmor profiles, and minimal multi-stage builds, validated with docker-bench-security,
  Hadolint, and Dockle. Use when preparing a container or Dockerfile for production, or
  auditing images and runtime flags against CIS Docker controls. Keywords: Dockerfile, USER,
  --cap-drop, read-only rootfs, seccomp, AppArmor, multi-stage, Hadolint, Dockle. Do not use
  for the Docker daemon's own configuration - use hardening-docker-daemon-configuration.
domain: cybersecurity
subdomain: container-security
tags:
- containers
- docker
- security
- hardening
- CIS-benchmark
version: '1.0'
author: mahipal
license: Apache-2.0
nist_csf:
- PR.PS-01
- PR.IR-01
- ID.AM-08
- DE.CM-01
mitre_attack:
- T1610
- T1611
- T1609
- T1525
- T1068
---
# 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

```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

```json
{
  "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

```bash
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:latest
```

### Step 4: Enable Docker Content Trust

```bash
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.0
```

### Step 5: Configure Host-Level Auditing

```bash
# 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 auditd
```

## Validation Commands

```bash
# 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

- [CIS Docker Benchmark](https://www.cisecurity.org/benchmark/docker)
- [Docker Security Best Practices](https://docs.docker.com/engine/security/)
- [Docker Bench Security Tool](https://github.com/docker/docker-bench-security)
- [Hadolint - Dockerfile Linter](https://github.com/hadolint/hadolint)

© mahipal · Apache-2.0 · mukul975/Anthropic-Cybersecurity-Skills

Смотрите также

Спонсоры проекта

Компании, которые помогают держать аналитику открытой