This text covers Docker and Kubernetes security. Docker uses Namespaces and Cgroups for isolation, but its core risk is that access to the Docker socket grants root privileges. Container escape occurs when excessive permissions break isolation, through privileged containers, Docker socket mounts, or capabilities like CAPSYSADMIN. Image security involves scanning for CVEs and following secure Dockerfile practices. Kubernetes security focuses on RBAC, with high risks from wildcard permissions, default ServiceAccounts bound to cluster-admin, and pod creation with exec access. Pod security configurations and cluster hardening measures are detailed. CICD security addresses pipeline attack surfaces, credential scanning, and secure build/deploy practices.
Chapter 1: Docker Security
1.1 Docker Core Concepts and Architecture
Docker is the most widely adopted containerization platform today. Containerization is not virtualization—it leverages Linux kernel features like Namespaces and Cgroups to achieve lightweight process isolation.
Core Concepts
Image: A read-only template containing everything an application needs to run—code, runtime, libraries, and environment variables. Images are built in layers, each layer representing a single Dockerfile instruction. Images are immutable—once built, they cannot be modified.
Container: A running instance of an image. A writable layer is added on top of the image's read-only layers. Containers are isolated from each other but share the host kernel.
Registry: A storage and distribution hub for images. Docker Hub is the default public registry. Enterprises typically set up private registries (e.g., Harbor).
dockerd runs with root privileges. Any user or process that can access the Docker socket (/var/run/docker.sock) effectively has root access on the host—this is the single biggest security risk in Docker.
1.2 Docker Security Isolation Mechanisms
Docker is not a "secure VM"—it is a packaged combination of Linux kernel features.
**Namespaces—Isolating What a Container Can See**
Namespace
What It Isolates
Security Implication
PID
Process tree
A container can only see its own processes
Network
Network stack
A container gets its own NIC, IP, and routing table
Mount
Mount points
A container has its own filesystem tree
UTS
Hostname and domain name
A container can have its own hostname
IPC
Inter-process communication
Shared memory and semaphores are isolated between containers
User
User and group IDs
Root inside a container can be mapped to an unprivileged host user (not enabled by default)
Cgroup
Control group view
A container sees its own resource limits
**Cgroups (Control Groups)—Limiting Resources**
Restricts how many CPU cores, how much memory, and what disk I/O rate a container can use. Prevents a single container from exhausting all host resources.
Capabilities—Splitting Root's Power into Pieces
In traditional Linux, root has absolute power. Capabilities break that power into fine-grained units. By default, Docker drops the following dangerous capabilities when starting a container:
Limits which Linux system calls a process inside a container can invoke. Docker's default Seccomp profile blocks around 44 dangerous syscalls (such as reboot, kexec_load, and clock_settime).
1.3 Container Escape
Container escape means breaking through multiple isolation mechanisms from inside a container to gain access to the host. At its core, it happens because the user granted the container too many privileges, undermining the isolation.
Path 1: Privileged Containers (--privileged)
BASH
# 启动特权容器
docker run -d --privileged --name test nginx:1.25
--privileged does not just give the container "a few more capabilities"—it lets the container do anything the host can do. This includes loading kernel modules, accessing all devices (/dev/), modifying kernel parameters, and more.
docker run -d -v /var/run/docker.sock:/var/run/docker.sock --name test nginx:1.25
The Docker socket (/var/run/docker.sock) is the API entry point for dockerd. Any process that can talk to this socket has full control over Docker—creating containers, deleting containers, pulling images, executing commands. Mounting it into a container = handing over control of the host's Docker to that container.
This is currently the most common and most easily exploited escape path in Kubernetes clusters.
1. Why Is This Socket So Powerful? /var/run/docker.sock is the UNIX socket for the Docker daemon (dockerd). dockerd always runs as rootroot. Accessing this socket means you have root-level API access on the host.
4. Defensive Measures If your workload requires mounting this socket (e.g., CI/CD containers), apply the following mitigations to reduce risk:
Disable the root user: inside the container, use USER 1000 to run processes. (The socket is still mounted, but non-root users have limited permissions and cannot execute destructive API calls.)
**Use --group-add**: add the container user to the host's docker group (still dangerous; only appropriate for low-risk environments).
Ultimate solution: use Rootless Docker or Podman to remove root privileges from the daemon entirely.
Path 3: CAP_SYS_ADMIN + cgroup
If a container has the CAP_SYS_ADMIN capability and cgroup is writable, an attacker can use the cgroup notify_on_release mechanism to execute arbitrary commands on the host. This path involves fairly complex kernel internals, but it is extremely dangerous when the conditions are met.
1.4 Image Security
CVE Vulnerability Scanning
Docker images are built on Linux distributions (like Debian or Alpine) that contain hundreds of system packages. Outdated images may harbor known critical vulnerabilities.
Real-World Case—Dependency Confusion Attack: In 2023, an attacker uploaded a malicious package named python-dateutil to PyPI (differing from the popular python-dateutil by just one hyphen). A developer mistakenly ran pip install python-dateutil, causing the malicious code to be baked into an image and deployed to production.
Kubernetes (K8s for short—there are 8 letters between K and s) is a container orchestration platform. When your application needs to run across dozens or even thousands of servers, manually managing Docker containers becomes impossible. K8s automates scheduling, scaling, load balancing, and self-healing for containers. You just tell it how many replicas you want, and it automatically finds machines, starts containers, and restarts them if they crash.
Control Plane (also called Master Nodes)—the brain of the cluster
Component
Function
Security Concern
kube-apiserver
The single entry point for all operations; handles every REST API request
Authentication, authorization, and audit—three core security functions live here
etcd
Distributed key-value store holding all cluster configuration and state
Lose etcd = lose the cluster. It must be encrypted, backed up, and access-restricted
kube-scheduler
Decides which Node a Pod runs on
Scheduling policies can impact security (e.g., steering sensitive Pods to specific nodes)
kube-controller-manager
Runs various controller loops (Deployment, ReplicaSet, Node, etc.)
—
Worker Nodes—where actual applications run
Component
Function
kubelet
The "steward" on each Node; receives instructions from the API Server and manages Pods
kube-proxy
Implements network proxying for Services (iptables/IPVS)
The smallest scheduling unit. A Pod can contain one or more tightly coupled containers
Service
svc
Provides a stable access point (IP + port) for Pods; Pod IPs change on restart, the Service IP stays the same
Deployment
deploy
Declares a desired number of Pod replicas; the controller automatically maintains that count
ConfigMap
cm
Stores non-sensitive configuration data (environment variables, config files)
Secret
—
Stores sensitive data. **Base64-encoded by default only—not encrypted**
Namespace
ns
Logical grouping of resources. Not a security boundary—by default, Pods across all Namespaces can talk to each other
ServiceAccount
sa
The identity a Pod uses to access the API Server. Every Pod gets a SA Token mounted by default
Role
—
Defines "what you can do" (which operations on which resources). Scoped to a single Namespace
ClusterRole
—
Same as Role, but cluster-wide
RoleBinding
—
Grants a Role to a user, group, or ServiceAccount
ClusterRoleBinding
—
Grants a ClusterRole at the cluster level
2.3 RBAC Security Audit
RBAC (Role-Based Access Control) is the permission management system in K8s. Core principle: Who (Subject) + What Action (Verb) + On What (Resource) + Where (Namespace/Cluster).
If the output contains system:serviceaccount:default:default or something similar, it means the default ServiceAccount in the default namespace (shared by all Pods that don't specify a custom SA) has cluster-admin privileges. Anyone inside such a Pod can control the entire cluster.
Chapter 1: Docker Security
1.1 Docker Core Concepts and Architecture
Docker is the most widely adopted containerization platform today. Containerization is not virtualization—it leverages Linux kernel features like Namespaces and Cgroups to achieve lightweight process isolation.
Core Concepts
Image: A read-only template containing everything an application needs to run—code, runtime, libraries, and environment variables. Images are built in layers, each layer representing a single Dockerfile instruction. Images are immutable—once built, they cannot be modified.
Container: A running instance of an image. A writable layer is added on top of the image's read-only layers. Containers are isolated from each other but share the host kernel.
Registry: A storage and distribution hub for images. Docker Hub is the default public registry. Enterprises typically set up private registries (e.g., Harbor).
Architecture Layers
dockerd runs with root privileges. Any user or process that can access the Docker socket (/var/run/docker.sock) effectively has root access on the host—this is the single biggest security risk in Docker.
1.2 Docker Security Isolation Mechanisms
Docker is not a "secure VM"—it is a packaged combination of Linux kernel features.
**Namespaces—Isolating What a Container Can See**
Namespace
What It Isolates
Security Implication
PID
Process tree
A container can only see its own processes
Network
Network stack
A container gets its own NIC, IP, and routing table
Mount
Mount points
A container has its own filesystem tree
UTS
Hostname and domain name
A container can have its own hostname
IPC
Inter-process communication
Shared memory and semaphores are isolated between containers
User
User and group IDs
Root inside a container can be mapped to an unprivileged host user (not enabled by default)
Cgroup
Control group view
A container sees its own resource limits
**Cgroups (Control Groups)—Limiting Resources**
Restricts how many CPU cores, how much memory, and what disk I/O rate a container can use. Prevents a single container from exhausting all host resources.
Capabilities—Splitting Root's Power into Pieces
In traditional Linux, root has absolute power. Capabilities break that power into fine-grained units. By default, Docker drops the following dangerous capabilities when starting a container:
Seccomp (Secure Computing Mode)—System Call Filtering
Limits which Linux system calls a process inside a container can invoke. Docker's default Seccomp profile blocks around 44 dangerous syscalls (such as reboot, kexec_load, and clock_settime).
1.3 Container Escape
Container escape means breaking through multiple isolation mechanisms from inside a container to gain access to the host. At its core, it happens because the user granted the container too many privileges, undermining the isolation.
Path 1: Privileged Containers (--privileged)
--privileged does not just give the container "a few more capabilities"—it lets the container do anything the host can do. This includes loading kernel modules, accessing all devices (/dev/), modifying kernel parameters, and more.
Inside a privileged container:
Quick detection script:
Path 2: Mounting the Docker Socket
The Docker socket (/var/run/docker.sock) is the API entry point for dockerd. Any process that can talk to this socket has full control over Docker—creating containers, deleting containers, pulling images, executing commands. Mounting it into a container = handing over control of the host's Docker to that container.
This is currently the most common and most easily exploited escape path in Kubernetes clusters.
1. Why Is This Socket So Powerful?
/var/run/docker.sock is the UNIX socket for the Docker daemon (dockerd). dockerd always runs as rootroot. Accessing this socket means you have root-level API access on the host.
Exploiting it from inside a container:
4. Defensive Measures
If your workload requires mounting this socket (e.g., CI/CD containers), apply the following mitigations to reduce risk:
Path 3: CAP_SYS_ADMIN + cgroup
If a container has the CAP_SYS_ADMIN capability and cgroup is writable, an attacker can use the cgroup notify_on_release mechanism to execute arbitrary commands on the host. This path involves fairly complex kernel internals, but it is extremely dangerous when the conditions are met.
1.4 Image Security
CVE Vulnerability Scanning
Docker images are built on Linux distributions (like Debian or Alpine) that contain hundreds of system packages. Outdated images may harbor known critical vulnerabilities.
Real-World Case—Dependency Confusion Attack: In 2023, an attacker uploaded a malicious package named python-dateutil to PyPI (differing from the popular python-dateutil by just one hyphen). A developer mistakenly ran pip install python-dateutil, causing the malicious code to be baked into an image and deployed to production.
Dockerfile Security Principles
Principle
Bad Practice
Secure Practice
Rationale
Pin versions
`FROM ubuntu:latest`
`FROM ubuntu:22.04`
The `latest` tag can pull in untested changes
Non-root user
Run as root by default
`USER appuser`
Root inside a container can threaten the host under certain conditions
Clean up cache
No cleanup
`rm -rf /var/lib/apt/lists/*`
Reduces the attack surface and image size
Secrets management
`ENV SECRET=xxx`
Inject at runtime (`--env-file` or K8s Secret)
Secrets written into image layers can be extracted
Minimal install
`apt install -y nginx vim curl ...`
`apt install -y --no-install-recommends nginx`
Unnecessary packages = unnecessary vulnerabilities
1.5 Unauthorized Registry Access
Docker Registry is a repository service for storing and distributing Docker images. When misconfigured (no authentication enabled), an attacker can:
This vulnerability is a high-severity configuration flaw (CWE-284: Improper Access Control).
Chapter 2: Kubernetes Security
2.1 K8s Architecture and Core Concepts
Kubernetes (K8s for short—there are 8 letters between K and s) is a container orchestration platform. When your application needs to run across dozens or even thousands of servers, manually managing Docker containers becomes impossible. K8s automates scheduling, scaling, load balancing, and self-healing for containers. You just tell it how many replicas you want, and it automatically finds machines, starts containers, and restarts them if they crash.
Control Plane (also called Master Nodes)—the brain of the cluster
Component
Function
Security Concern
kube-apiserver
The single entry point for all operations; handles every REST API request
Authentication, authorization, and audit—three core security functions live here
etcd
Distributed key-value store holding all cluster configuration and state
Lose etcd = lose the cluster. It must be encrypted, backed up, and access-restricted
kube-scheduler
Decides which Node a Pod runs on
Scheduling policies can impact security (e.g., steering sensitive Pods to specific nodes)
kube-controller-manager
Runs various controller loops (Deployment, ReplicaSet, Node, etc.)
—
Worker Nodes—where actual applications run
Component
Function
kubelet
The "steward" on each Node; receives instructions from the API Server and manages Pods
kube-proxy
Implements network proxying for Services (iptables/IPVS)
Container Runtime
Actually runs containers (Docker/containerd/CRI-O)
2.2 Core Resource Objects
Resource
Short Name
One-Liner
Pod
po
The smallest scheduling unit. A Pod can contain one or more tightly coupled containers
Service
svc
Provides a stable access point (IP + port) for Pods; Pod IPs change on restart, the Service IP stays the same
Deployment
deploy
Declares a desired number of Pod replicas; the controller automatically maintains that count
ConfigMap
cm
Stores non-sensitive configuration data (environment variables, config files)
Secret
—
Stores sensitive data. **Base64-encoded by default only—not encrypted**
Namespace
ns
Logical grouping of resources. Not a security boundary—by default, Pods across all Namespaces can talk to each other
ServiceAccount
sa
The identity a Pod uses to access the API Server. Every Pod gets a SA Token mounted by default
Role
—
Defines "what you can do" (which operations on which resources). Scoped to a single Namespace
ClusterRole
—
Same as Role, but cluster-wide
RoleBinding
—
Grants a Role to a user, group, or ServiceAccount
ClusterRoleBinding
—
Grants a ClusterRole at the cluster level
2.3 RBAC Security Audit
RBAC (Role-Based Access Control) is the permission management system in K8s. Core principle: Who (Subject) + What Action (Verb) + On What (Resource) + Where (Namespace/Cluster).
Three High-Risk Configurations
High Risk 1: Wildcard *:*:*
This single rule grants every possible operation on every resource across all API groups—equivalent to cluster-admin.
High Risk 2: Default SA Bound to cluster-admin
If the output contains system:serviceaccount:default:default or something similar, it means the default ServiceAccount in the default namespace (shared by all Pods that don't specify a custom SA) has cluster-admin privileges. Anyone inside such a Pod can control the entire cluster.
High Risk 3: Pod Create + Exec Permissions
An attacker with create pods + exec pods permissions can create a privileged Pod and escape.
2.4 Accessing the API Server from Inside a Pod
By default, every Pod has three files mounted at the following paths:
Using the Token to Access the API Server
2.5 Pod Security Configuration
Complete Secure Pod Template
Quickly Check for Dangerous Pods in the Cluster
2.6 K8s Hardening Checklist
Component
Hardening Measure
Corresponding Flag or Configuration
API Server
Disable anonymous access
`--anonymous-auth=false`
API Server
Enable RBAC authorization
`--authorization-mode=Node,RBAC`
API Server
Enable audit logging
`--audit-log-path=/var/log/kube-audit.log`
etcd
Certificate-based authentication
Only allow mTLS-authenticated clients
etcd
Data encryption at rest
Configure `EncryptionConfiguration` to encrypt Secrets
kubelet
Disable anonymous access
`--anonymous-auth=false`
Chapter 3: CI/CD Security
3.1 Pipeline Attack Surface
3.2 Source Code Security—Credential Scanning
3.3 Build and Deployment Security
Chapter 4: Local Lab Environment
All labs run on your personal machine, at zero cost