Kubernetes Network Policies ve Cilium: Gelişmiş Network Security Stratejileri
Kubernetes cluster'larında uygulama sayısı arttıkça, network security katmanı kritik önem kazanıyor. Varsayılan Kubernetes network modelinde tüm pod'lar birbirleriyle iletişim kurabilir - bu durum production ortamlarında ciddi güvenlik riskleri oluşturur. Network Policies ve modern CNI (Container Network Interface) çözümleri olan Cilium, cluster içi trafiği kontrol etmek, mikro-segmentasyon uygulamak ve zero-trust network mimarisi kurmak için güçlü araçlar sunar.
Bu yazıda, Kubernetes Network Policies'in temellerinden başlayarak Cilium ve eBPF teknolojileri ile gelişmiş network security stratejilerine kadar kapsamlı bir rehber sunuyoruz.
İçindekiler
- Kubernetes Network Security'ye Giriş
- Network Policies Temelleri
- Ingress ve Egress Policy'leri
- Cilium Nedir ve eBPF Teknolojisi
- Cilium Kurulumu ve Yapılandırma
- Cilium Network Policies (CNP)
- L7 (Application Layer) Policy'leri
- DNS-Based Policies ve FQDN Filtering
- Service Mesh Integration ve mTLS
- Monitoring ve Observability: Hubble
- Zero-Trust Network Architecture
- Production Best Practices
- Troubleshooting ve Common Issues
Kubernetes Network Security'ye Giriş {#giris}
Varsayılan Kubernetes Network Modeli
Kubernetes'te varsayılan network davranışı:
✓ Her pod bir IP alır
✓ Tüm pod'lar NAT olmadan birbirleriyle iletişim kurabilir
✓ Node'lar tüm pod'larla iletişim kurabilir
✗ Network isolation yok
✗ Micro-segmentation yok
Bu model development için pratik, ancak production security için yetersiz.
Network Security Katmanları
Kubernetes'te network security 3 katmanda uygulanabilir:
1. Infrastructure Layer (L3/L4)
- IP adresi ve port bazlı filtering
- Network Policies ile sağlanır
- Source/destination IP, port, protocol kontrolü
2. Application Layer (L7)
- HTTP/gRPC gibi protokol seviyesinde kontrol
- URL path, HTTP method, header filtering
- Cilium CNP ile sağlanır
3. Identity-Based Security
- Service account ve label bazlı izinler
- mTLS ile encrypted communication
- Zero-trust network mimarisi
Network Policies Temelleri {#network-policies-temelleri}
İlk Network Policy
Network Policy'ler namespace-scoped Kubernetes resource'larıdır:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: deny-all-ingress
namespace: production
spec:
# Hangi pod'lara uygulanacak?
podSelector:
matchLabels:
env: production
# Policy türü
policyTypes:
- Ingress
- Egress
# İzin verilen ingress trafiği (boş = hiçbiri)
ingress: []
# İzin verilen egress trafiği (boş = hiçbiri)
egress: []
Önemli: Network Policy oluşturulduğunda default deny davranışı başlar. Yani hiçbir trafik izni yoksa, tüm trafik bloklanır.
Frontend-Backend Isolation Örneği
Üç katmanlı uygulama için network isolation:
# 1. Backend Policy - Sadece frontend'den gelen trafiğe izin ver
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: backend-policy
namespace: production
spec:
podSelector:
matchLabels:
tier: backend
policyTypes:
- Ingress
- Egress
ingress:
# Frontend'den gelen trafikler
- from:
- podSelector:
matchLabels:
tier: frontend
ports:
- protocol: TCP
port: 8080
egress:
# Database'e giden trafik
- to:
- podSelector:
matchLabels:
tier: database
ports:
- protocol: TCP
port: 5432
# DNS çözümlemesi için
- to:
- namespaceSelector:
matchLabels:
name: kube-system
- podSelector:
matchLabels:
k8s-app: kube-dns
ports:
- protocol: UDP
port: 53
# 2. Database Policy - Sadece backend'den gelen trafiğe izin ver
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: database-policy
namespace: production
spec:
podSelector:
matchLabels:
tier: database
policyTypes:
- Ingress
- Egress
ingress:
- from:
- podSelector:
matchLabels:
tier: backend
ports:
- protocol: TCP
port: 5432
# Database hiçbir egress trafiği yapamaz (backup hariç)
egress: []
# 3. Frontend Policy - Ingress Controller'dan gelir, backend'e gider
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: frontend-policy
namespace: production
spec:
podSelector:
matchLabels:
tier: frontend
policyTypes:
- Ingress
- Egress
ingress:
# Ingress controller namespace'inden gelen trafik
- from:
- namespaceSelector:
matchLabels:
name: ingress-nginx
ports:
- protocol: TCP
port: 80
egress:
# Backend'e giden trafik
- to:
- podSelector:
matchLabels:
tier: backend
ports:
- protocol: TCP
port: 8080
# DNS
- to:
- namespaceSelector:
matchLabels:
name: kube-system
ports:
- protocol: UDP
port: 53
Namespace Isolation
Farklı namespace'ler arasında tam izolasyon:
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: namespace-isolation
namespace: production
spec:
podSelector: {} # Tüm pod'lar
policyTypes:
- Ingress
- Egress
ingress:
# Sadece aynı namespace içinden gelen trafikler
- from:
- podSelector: {}
egress:
# Sadece aynı namespace içine giden trafikler
- to:
- podSelector: {}
# DNS exception
- to:
- namespaceSelector:
matchLabels:
name: kube-system
ports:
- protocol: UDP
port: 53
Ingress ve Egress Policy'leri {#ingress-egress}
Ingress Policy Detayları
Ingress: Pod'a gelen trafiği kontrol eder.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: api-ingress-policy
namespace: production
spec:
podSelector:
matchLabels:
app: api-server
policyTypes:
- Ingress
ingress:
# Rule 1: Belirli namespace'den gelen trafik
- from:
- namespaceSelector:
matchLabels:
environment: production
podSelector:
matchLabels:
role: frontend
ports:
- protocol: TCP
port: 8080
# Rule 2: Belirli IP bloğundan gelen trafik
- from:
- ipBlock:
cidr: 10.0.0.0/16
except:
- 10.0.1.0/24 # Bu subnet hariç
ports:
- protocol: TCP
port: 8443
Önemli: from array'i içindeki her item OR mantığı ile çalışır, ancak aynı item içindeki selector'lar AND mantığı ile çalışır.
Egress Policy Detayları
Egress: Pod'dan çıkan trafiği kontrol eder.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: api-egress-policy
namespace: production
spec:
podSelector:
matchLabels:
app: api-server
policyTypes:
- Egress
egress:
# Internal database
- to:
- podSelector:
matchLabels:
app: postgresql
ports:
- protocol: TCP
port: 5432
# External API (belirli IP)
- to:
- ipBlock:
cidr: 203.0.113.0/24
ports:
- protocol: TCP
port: 443
# DNS
- to:
- namespaceSelector:
matchLabels:
name: kube-system
- podSelector:
matchLabels:
k8s-app: kube-dns
ports:
- protocol: UDP
port: 53
# NTP
- to:
- ipBlock:
cidr: 0.0.0.0/0
ports:
- protocol: UDP
port: 123
Named Ports Kullanımı
Port numarası yerine pod definition'da tanımlı named port kullanabilirsiniz:
# Pod definition
apiVersion: v1
kind: Pod
metadata:
name: api-pod
labels:
app: api-server
spec:
containers:
- name: api
image: api-server:latest
ports:
- name: http
containerPort: 8080
- name: metrics
containerPort: 9090
---
# Network Policy
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: api-named-ports
spec:
podSelector:
matchLabels:
app: api-server
policyTypes:
- Ingress
ingress:
- from:
- podSelector:
matchLabels:
role: frontend
ports:
- protocol: TCP
port: http # Named port kullanımı
- from:
- namespaceSelector:
matchLabels:
name: monitoring
ports:
- protocol: TCP
port: metrics
Cilium Nedir ve eBPF Teknolojisi {#cilium-ebpf}
eBPF (Extended Berkeley Packet Filter)
eBPF, Linux kernel içinde güvenli kod çalıştırmayı sağlayan devrim niteliğinde bir teknoloji:
Traditional Network Stack:
User Space → System Calls → Kernel → iptables → Network Driver
eBPF Network Stack:
User Space → eBPF Program (Kernel Space) → Direct Network Driver
eBPF Avantajları:
- Performance: Kernel space'de çalıştığı için iptables'dan 10-100x daha hızlı
- Programmability: Dinamik olarak kernel behavior'unu değiştirebilir
- Observability: Her network packet'i deep inspection yapılabilir
- Security: Kernel seviyesinde security policy'leri
Cilium Neden Daha İyi?
Cilium, Kubernetes için eBPF tabanlı modern bir CNI:
| Özellik | Traditional CNI (Calico/Flannel) | Cilium |
|---|---|---|
| **Teknoloji** | iptables | eBPF |
| **Performance** | Orta | Çok Yüksek |
| **L7 Filtering** | Yok / Sınırlı | Tam Destek |
| **Service Mesh** | Ayrı tool gerekir | Built-in |
| **Observability** | Kısıtlı | Hubble (Deep Visibility) |
| **Scalability** | 1000'lerce rule'da yavaşlar | 10,000'lerce rule |
| **API-Aware** | Hayır | HTTP/gRPC/Kafka aware |
Gerçek Dünya Benchmark:
Test: 10,000 Network Policy ile 100,000 connection/sec
iptables (Calico):
- Latency: ~15ms
- CPU Usage: %85
- Memory: 4GB
eBPF (Cilium):
- Latency: ~0.5ms (30x faster)
- CPU Usage: %12
- Memory: 800MB
Cilium Architecture
┌─────────────────────────────────────────┐
│ Cilium Agent (DaemonSet) │
│ ┌──────────┐ ┌──────────┐ ┌────────┐│
│ │ eBPF │ │ Network │ │ Hubble ││
│ │ Programs │ │ Policy │ │Observer││
│ └──────────┘ └──────────┘ └────────┘│
└─────────────────────────────────────────┘
│ │
┌──────┴─────┐ ┌─────┴──────┐
│ Linux │ │ Cilium │
│ Kernel │ │ Operator │
│ (eBPF) │ │ (Control) │
└────────────┘ └────────────┘
Cilium Kurulumu ve Yapılandırma {#cilium-kurulum}
Helm ile Kurulum
# Cilium Helm repo ekle
helm repo add cilium https://helm.cilium.io/
helm repo update
# Cilium'u kube-system namespace'ine kur
helm install cilium cilium/cilium \
--namespace kube-system \
--set operator.replicas=1 \
--set hubble.relay.enabled=true \
--set hubble.ui.enabled=true \
--set prometheus.enabled=true \
--set operator.prometheus.enabled=true
# Kurulum durumunu kontrol et
kubectl -n kube-system get pods -l k8s-app=cilium
Cilium CLI Kurulumu
# Cilium CLI (Linux)
CILIUM_CLI_VERSION=$(curl -s https://raw.githubusercontent.com/cilium/cilium-cli/master/stable.txt)
curl -L --remote-name-all https://github.com/cilium/cilium-cli/releases/download/${CILIUM_CLI_VERSION}/cilium-linux-amd64.tar.gz
sudo tar xzvfC cilium-linux-amd64.tar.gz /usr/local/bin
rm cilium-linux-amd64.tar.gz
# Connectivity test
cilium connectivity test
# Status check
cilium status --wait
Beklenen çıktı:
/¯¯\
/¯¯\__/¯¯\ Cilium: OK
\__/¯¯\__/ Operator: OK
/¯¯\__/¯¯\ Hubble: OK
\__/¯¯\__/ ClusterMesh: disabled
\__/
DaemonSet cilium Desired: 3, Ready: 3/3
Deployment cilium-operator Desired: 1, Ready: 1/1
Containers: cilium Running: 3
cilium-operator Running: 1
Mevcut Cluster'a Migrate Etme
Eğer zaten bir CNI kullanıyorsanız (Calico, Flannel vb.):
# 1. Mevcut CNI'ı kaldır
kubectl delete -f /etc/cni/net.d/10-calico.conflist
# 2. Cilium kur (migration mode)
helm install cilium cilium/cilium \
--namespace kube-system \
--set cni.chainingMode=generic-veth \
--set enableIPv4Masquerade=true
# 3. Pod'ları yeniden başlat (rolling restart)
kubectl rollout restart deployment -n production
# 4. Eski CNI daemonset'i kaldır
kubectl delete daemonset -n kube-system calico-node
Cilium Configuration (values.yaml)
Production-ready yapılandırma:
# cilium-values.yaml
cluster:
name: production-cluster
id: 1
# eBPF host routing (fastest datapath)
routingMode: native
autoDirectNodeRoutes: true
ipv4NativeRoutingCIDR: 10.0.0.0/8
# Hubble (observability)
hubble:
enabled: true
relay:
enabled: true
ui:
enabled: true
metrics:
enabled:
- dns
- drop
- tcp
- flow
- icmp
- http
# Prometheus metrics
prometheus:
enabled: true
serviceMonitor:
enabled: true
# Bandwidth Manager (pod QoS)
bandwidthManager: true
# L7 proxy (application-aware filtering)
l7Proxy: true
# Encryption (WireGuard)
encryption:
enabled: true
type: wireguard
# Resources
operator:
replicas: 2
resources:
limits:
cpu: 1000m
memory: 1Gi
requests:
cpu: 100m
memory: 128Mi
resources:
limits:
cpu: 4000m
memory: 4Gi
requests:
cpu: 100m
memory: 512Mi
Uygulama:
helm upgrade cilium cilium/cilium \
--namespace kube-system \
--values cilium-values.yaml
Cilium Network Policies (CNP) {#cilium-network-policies}
Standard vs Cilium Network Policy
Cilium hem standard Kubernetes Network Policy'leri hem de kendi gelişmiş CiliumNetworkPolicy (CNP) resource'unu destekler.
Karşılaştırma:
| Özellik | NetworkPolicy | CiliumNetworkPolicy |
|---|---|---|
| **L3/L4 Filtering** | ✓ | ✓ |
| **L7 HTTP Filtering** | ✗ | ✓ |
| **DNS/FQDN Filtering** | ✗ | ✓ |
| **Kafka Filtering** | ✗ | ✓ |
| **Service-based Rules** | ✗ | ✓ |
| **CIDR Exceptions** | ✓ | ✓ |
| **Deny Rules** | ✗ | ✓ |
Temel CiliumNetworkPolicy
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
name: api-security-policy
namespace: production
spec:
# Endpoint selector (hangi pod'lara uygulanacak)
endpointSelector:
matchLabels:
app: api-server
tier: backend
# Ingress rules
ingress:
- fromEndpoints:
- matchLabels:
app: frontend
tier: frontend
toPorts:
- ports:
- port: "8080"
protocol: TCP
# Egress rules
egress:
- toEndpoints:
- matchLabels:
app: postgresql
tier: database
toPorts:
- ports:
- port: "5432"
protocol: TCP
# DNS egress (domain bazlı)
- toFQDNs:
- matchName: "api.github.com"
toPorts:
- ports:
- port: "443"
protocol: TCP
Service-Based Policies
Cilium, pod selector yerine Kubernetes Service'lere göre policy tanımlamayı destekler:
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
name: service-based-policy
namespace: production
spec:
endpointSelector:
matchLabels:
app: frontend
egress:
# Service name ile referans
- toServices:
- k8sService:
serviceName: backend-api
namespace: production
# External service (LoadBalancer veya NodePort)
- toServices:
- k8sService:
serviceName: external-gateway
namespace: gateway
toPorts:
- ports:
- port: "443"
protocol: TCP
Avantaj: Pod'lar ölüp yeni IP alsa bile service-based policy çalışmaya devam eder.
Deny Policies
Cilium explicit deny rule'ları destekler (standard NetworkPolicy desteklemez):
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
name: deny-external-egress
namespace: production
spec:
endpointSelector:
matchLabels:
security: high
# Önce izin ver
egress:
- toEndpoints:
- matchLabels:
tier: database
# Sonra açıkça reddet
egressDeny:
- toEntities:
- world # Internet'e çıkışı tamamen engelle
Entity types:
world: Cluster dışındaki tüm IP'lerhost: Kubernetes node'larıcluster: Tüm cluster içi pod'larkube-apiserver: API serverall: Her şey
Label-Based L3/L4 Policy
Production ortamında çoklu tier mikro-segmentasyon:
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
name: multi-tier-security
namespace: production
spec:
endpointSelector:
matchLabels:
tier: backend
ingress:
# Tier 1: Public frontend'den gelen trafik (sadece HTTPS)
- fromEndpoints:
- matchLabels:
tier: frontend
zone: public
toPorts:
- ports:
- port: "443"
protocol: TCP
# Tier 2: Internal admin panel (sadece VPN IP'lerinden)
- fromCIDR:
- 10.10.0.0/16 # VPN subnet
toPorts:
- ports:
- port: "8443"
protocol: TCP
# Tier 3: Monitoring (sadece Prometheus)
- fromEndpoints:
- matchLabels:
app: prometheus
namespace: monitoring
toPorts:
- ports:
- port: "9090"
protocol: TCP
egress:
# Database access
- toEndpoints:
- matchLabels:
tier: database
toPorts:
- ports:
- port: "5432"
protocol: TCP
# Redis cache
- toEndpoints:
- matchLabels:
app: redis
toPorts:
- ports:
- port: "6379"
protocol: TCP
# DNS (kube-dns)
- toEndpoints:
- matchLabels:
k8s:io.kubernetes.pod.namespace: kube-system
k8s-app: kube-dns
toPorts:
- ports:
- port: "53"
protocol: UDP
L7 (Application Layer) Policy'leri {#l7-policies}
Cilium'un en güçlü özelliklerinden biri HTTP/gRPC/Kafka gibi protokolleri anlayarak uygulama katmanında filtering yapabilmesidir.
HTTP Path Filtering
REST API endpoint'lerini koruma:
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
name: api-l7-policy
namespace: production
spec:
endpointSelector:
matchLabels:
app: api-server
ingress:
- fromEndpoints:
- matchLabels:
app: frontend
toPorts:
- ports:
- port: "8080"
protocol: TCP
rules:
http:
# Public endpoints (herkese açık)
- method: "GET"
path: "/api/v1/public/.*"
# Health check
- method: "GET"
path: "/health"
# Metrics (sadece monitoring namespace'inden)
- method: "GET"
path: "/metrics"
headers:
- "X-Auth-Token: monitoring-token"
- fromEndpoints:
- matchLabels:
app: admin-panel
toPorts:
- ports:
- port: "8080"
protocol: TCP
rules:
http:
# Admin endpoints (sadece admin panel'den)
- method: "POST"
path: "/api/v1/admin/.*"
- method: "PUT"
path: "/api/v1/admin/.*"
- method: "DELETE"
path: "/api/v1/admin/.*"
HTTP Method ve Header Filtering
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
name: strict-api-policy
namespace: production
spec:
endpointSelector:
matchLabels:
app: payment-api
ingress:
- fromEndpoints:
- matchLabels:
app: checkout-service
toPorts:
- ports:
- port: "443"
protocol: TCP
rules:
http:
# Sadece POST /payment/process izinli
- method: "POST"
path: "/payment/process"
headers:
# API key zorunlu
- "X-API-Key: .*"
# Content-Type kontrolü
- "Content-Type: application/json"
# Health check (GET only)
- method: "GET"
path: "/health"
gRPC Filtering
gRPC service ve method bazlı filtering:
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
name: grpc-policy
namespace: production
spec:
endpointSelector:
matchLabels:
app: user-service
ingress:
- fromEndpoints:
- matchLabels:
app: api-gateway
toPorts:
- ports:
- port: "50051"
protocol: TCP
rules:
http:
# gRPC method filtering
- method: "POST"
path: "/user.UserService/GetUser"
- method: "POST"
path: "/user.UserService/ListUsers"
- fromEndpoints:
- matchLabels:
app: admin-service
toPorts:
- ports:
- port: "50051"
protocol: TCP
rules:
http:
# Admin methods
- method: "POST"
path: "/user.UserService/CreateUser"
- method: "POST"
path: "/user.UserService/DeleteUser"
Kafka Topic Filtering
Kafka message broker için topic seviyesinde güvenlik:
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
name: kafka-policy
namespace: production
spec:
endpointSelector:
matchLabels:
app: kafka-broker
ingress:
# Producer: Order Service
- fromEndpoints:
- matchLabels:
app: order-service
toPorts:
- ports:
- port: "9092"
protocol: TCP
rules:
kafka:
- role: "produce"
topic: "orders"
- role: "produce"
topic: "order-events"
# Consumer: Notification Service
- fromEndpoints:
- matchLabels:
app: notification-service
toPorts:
- ports:
- port: "9092"
protocol: TCP
rules:
kafka:
- role: "consume"
topic: "orders"
# Admin: Management Console
- fromEndpoints:
- matchLabels:
app: kafka-manager
toPorts:
- ports:
- port: "9092"
protocol: TCP
rules:
kafka:
- role: "produce"
topic: ".*"
- role: "consume"
topic: ".*"
DNS-Based Policies ve FQDN Filtering {#dns-policies}
Cilium, domain name bazlı egress filtering yapabilir - bu özellik external API'lere erişim kontrolü için kritik.
FQDN-Based Egress Policy
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
name: external-api-policy
namespace: production
spec:
endpointSelector:
matchLabels:
app: api-client
egress:
# GitHub API
- toFQDNs:
- matchName: "api.github.com"
toPorts:
- ports:
- port: "443"
protocol: TCP
# AWS S3 (wildcard)
- toFQDNs:
- matchPattern: "*.s3.amazonaws.com"
toPorts:
- ports:
- port: "443"
protocol: TCP
# Google APIs (pattern)
- toFQDNs:
- matchPattern: "*.googleapis.com"
toPorts:
- ports:
- port: "443"
protocol: TCP
# DNS resolution için kube-dns
- toEndpoints:
- matchLabels:
k8s:io.kubernetes.pod.namespace: kube-system
k8s-app: kube-dns
toPorts:
- ports:
- port: "53"
protocol: UDP
Önemli: Cilium, DNS response'larını dinleyerek domain'lerin IP adreslerini öğrenir ve dinamik olarak policy'leri günceller.
Wildcard ve Regex Patterns
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
name: cdn-access-policy
namespace: production
spec:
endpointSelector:
matchLabels:
app: web-frontend
egress:
# CDN providers
- toFQDNs:
- matchPattern: "*.cloudfront.net"
- matchPattern: "*.fastly.net"
- matchPattern: "*.akamai.net"
toPorts:
- ports:
- port: "443"
protocol: TCP
# Specific subdomains
- toFQDNs:
- matchName: "fonts.googleapis.com"
- matchName: "fonts.gstatic.com"
toPorts:
- ports:
- port: "443"
protocol: TCP
FQDN TTL ve Caching
Cilium, DNS TTL'leri respekt eder:
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
name: fqdn-ttl-policy
namespace: production
spec:
endpointSelector:
matchLabels:
app: payment-processor
egress:
- toFQDNs:
- matchName: "api.stripe.com"
# DNS cache TTL override (saniye)
# Default: DNS response TTL kullanılır
ttl: 3600 # 1 saat
toPorts:
- ports:
- port: "443"
protocol: TCP
DNS Proxy Mode
Cilium'u DNS proxy olarak yapılandırarak tüm DNS query'lerini intercept edebilirsiniz:
# Helm values
helm upgrade cilium cilium/cilium \
--set dnsProxy.enabled=true \
--namespace kube-system
Service Mesh Integration ve mTLS {#service-mesh}
Cilium, sidecar-free service mesh sunarak Istio/Linkerd gibi ek tool'lara gerek kalmadan service mesh özellikleri sağlar.
mTLS (Mutual TLS) Encryption
Cluster içi pod-to-pod trafiği encrypt etme:
# Cilium Helm values
encryption:
enabled: true
type: wireguard # veya ipsec
WireGuard vs IPsec:
| Özellik | WireGuard | IPsec |
|---|---|---|
| **Performance** | Çok Yüksek | Orta |
| **CPU Overhead** | %2-5 | %15-25 |
| **Kurulum** | Kolay | Karmaşık |
| **Kernel Support** | Linux 5.6+ | Her yerde |
WireGuard encryption test:
# Enable WireGuard encryption
cilium config set enable-wireguard true
# Verify encryption status
cilium status | grep Encryption
# Test encrypted connection
kubectl exec -it pod-a -- curl https://service-b.production.svc.cluster.local
# Check WireGuard interface
kubectl exec -n kube-system ds/cilium -- wg show
Identity-Based Security
Cilium, her pod'a benzersiz bir security identity atar (IP yerine):
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
name: identity-based-policy
namespace: production
spec:
endpointSelector:
matchLabels:
app: api-server
ingress:
# Identity bazlı izin (IP yerine)
- fromEndpoints:
- matchLabels:
app: frontend
version: v2 # Sadece frontend v2
# Service account bazlı izin
- fromEndpoints:
- matchLabels:
k8s:io.kubernetes.pod.namespace: admin
io.kubernetes.serviceaccount.name: admin-sa
Identity görüntüleme:
# Tüm identity'leri listele
cilium identity list
# Belirli bir pod'un identity'sini gör
kubectl get cep -n production api-server-xxxxx -o json | jq .status.identity
Load Balancing ve HA
Cilium, kube-proxy'nin yerine geçerek eBPF-based load balancing sağlar:
# kube-proxy'yi disable et
helm upgrade cilium cilium/cilium \
--set kubeProxyReplacement=strict \
--namespace kube-system
# LB mode: DSR (Direct Server Return)
helm upgrade cilium cilium/cilium \
--set loadBalancer.mode=dsr \
--namespace kube-system
Performance boost:
- %50 daha düşük latency
- %30 daha az CPU kullanımı
- Connection tracking'de %70 iyileşme
Monitoring ve Observability: Hubble {#hubble}
Hubble, Cilium'un built-in observability platform'u. Her network flow'u görselleştirir ve analiz eder.
Hubble UI
# Hubble UI'yi port-forward ile aç
cilium hubble ui
# Browser'da açılır: http://localhost:12000
Hubble UI'de görebilecekleriniz:
- Pod-to-pod communication flows
- HTTP request/response details
- DNS queries
- Dropped packets (policy violations)
- Latency metrics
Hubble CLI
# Hubble CLI kur
export HUBBLE_VERSION=$(curl -s https://raw.githubusercontent.com/cilium/hubble/master/stable.txt)
curl -L --remote-name-all https://github.com/cilium/hubble/releases/download/$HUBBLE_VERSION/hubble-linux-amd64.tar.gz
tar xzvfC hubble-linux-amd64.tar.gz /usr/local/bin
# Port-forward Hubble Relay
cilium hubble port-forward &
# Real-time flow izleme
hubble observe
# Belirli namespace
hubble observe --namespace production
# HTTP flows
hubble observe --protocol http
# Dropped packets (policy violations)
hubble observe --verdict DROPPED
# Belirli pod'dan gelen trafik
hubble observe --from-pod production/api-server-xxxxx
# DNS queries
hubble observe --protocol dns
Hubble Metrics (Prometheus)
Prometheus ile entegrasyon:
# Cilium Helm values
hubble:
metrics:
enabled:
- dns:query;ignoreAAAA
- drop
- tcp
- flow
- icmp
- http
relay:
prometheus:
enabled: true
port: 9091
Prometheus query örnekleri:
# HTTP request rate
rate(hubble_http_requests_total[5m])
# HTTP error rate (4xx, 5xx)
rate(hubble_http_requests_total{status=~"[45].."}[5m])
# Dropped packet rate (policy violations)
rate(hubble_drop_total[5m])
# DNS query latency
histogram_quantile(0.95, rate(hubble_dns_query_duration_seconds_bucket[5m]))
# Top talkers (en çok trafik yapan pod'lar)
topk(10, rate(hubble_flows_total[5m]))
Service Map Grafana Dashboard
Hubble metrics ile Grafana'da service dependency map:
{
"dashboard": {
"title": "Cilium Service Map",
"panels": [
{
"title": "Service Communication",
"type": "nodeGraph",
"targets": [
{
"expr": "sum by (source, destination) (rate(hubble_flows_total[5m]))"
}
]
}
]
}
}
Zero-Trust Network Architecture {#zero-trust}
Zero-trust modeli: "Hiçbir kimseye güvenme, herkesi doğrula"
Default Deny + Explicit Allow
Tüm namespace'lerde varsayılan olarak tüm trafiği reddet:
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
name: default-deny-all
namespace: production
spec:
endpointSelector: {} # Tüm pod'lar
# Hiçbir ingress/egress izni yok
# (Boş bırakarak default deny)
Her servis için explicit allow:
# Frontend → Backend izni
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
name: allow-frontend-to-backend
namespace: production
spec:
endpointSelector:
matchLabels:
app: backend
ingress:
- fromEndpoints:
- matchLabels:
app: frontend
toPorts:
- ports:
- port: "8080"
protocol: TCP
rules:
http:
- method: "GET"
path: "/api/.*"
- method: "POST"
path: "/api/.*"
Namespace-Level Isolation
Her namespace izole, sadece gerekli cross-namespace communication izinli:
# Production namespace: Sadece ingress-nginx'ten trafik kabul eder
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
name: production-namespace-isolation
namespace: production
spec:
endpointSelector: {}
ingress:
# Ingress controller
- fromEndpoints:
- matchLabels:
k8s:io.kubernetes.pod.namespace: ingress-nginx
# Monitoring (metrics scraping)
- fromEndpoints:
- matchLabels:
k8s:io.kubernetes.pod.namespace: monitoring
app: prometheus
toPorts:
- ports:
- port: "9090" # Metrics port
protocol: TCP
egress:
# DNS
- toEndpoints:
- matchLabels:
k8s:io.kubernetes.pod.namespace: kube-system
k8s-app: kube-dns
# Same namespace communication
- toEndpoints:
- {}
ClusterNetworkPolicy (Cluster-Wide)
Tüm namespace'lere uygulanan global policy:
apiVersion: cilium.io/v2
kind: CiliumClusterwideNetworkPolicy
metadata:
name: cluster-wide-egress-deny
spec:
endpointSelector: {} # Tüm pod'lar (tüm namespace'ler)
egressDeny:
# Internet'e çıkışı engelle (DNS hariç)
- toEntities:
- world
egress:
# DNS izni (global)
- toEndpoints:
- matchLabels:
k8s:io.kubernetes.pod.namespace: kube-system
k8s-app: kube-dns
toPorts:
- ports:
- port: "53"
protocol: UDP
# Kubernetes API server
- toEntities:
- kube-apiserver
Least Privilege Principle
Her pod sadece ihtiyacı olan minimum izinlere sahip:
# Payment processor: Sadece Stripe API'ye erişebilir
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
name: payment-processor-strict
namespace: production
spec:
endpointSelector:
matchLabels:
app: payment-processor
ingress:
# Sadece checkout service çağırabilir
- fromEndpoints:
- matchLabels:
app: checkout-service
toPorts:
- ports:
- port: "8080"
protocol: TCP
rules:
http:
- method: "POST"
path: "/process-payment"
egress:
# Sadece Stripe API
- toFQDNs:
- matchName: "api.stripe.com"
toPorts:
- ports:
- port: "443"
protocol: TCP
# Internal database
- toEndpoints:
- matchLabels:
app: payment-db
toPorts:
- ports:
- port: "5432"
protocol: TCP
# DNS
- toEndpoints:
- matchLabels:
k8s:io.kubernetes.pod.namespace: kube-system
k8s-app: kube-dns
toPorts:
- ports:
- port: "53"
protocol: UDP
# HİÇBİR ŞEY DAHA YOK!
Production Best Practices {#best-practices}
1. Policy Development Workflow
Development → Audit Mode → Enforce Mode → Monitor
Audit mode (policy'yi enforce etmeden logla):
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
name: new-policy-audit
namespace: production
annotations:
policy.cilium.io/mode: "audit" # Audit mode
spec:
endpointSelector:
matchLabels:
app: new-service
ingress:
- fromEndpoints:
- matchLabels:
app: client-service
Audit mode'da Hubble ile traffic pattern'leri gözlemleyin:
# Audit edilen policy'nin flow'larını izle
hubble observe --namespace production --pod new-service-xxxxx
2. Incremental Rollout
Policy'leri aşamalı olarak deploy edin:
# Aşama 1: Sadece dev namespace
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
name: strict-policy
namespace: dev
spec:
# ...policy rules...
---
# Aşama 2: Staging (1 hafta sonra)
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
name: strict-policy
namespace: staging
spec:
# ...policy rules...
---
# Aşama 3: Production (2 hafta sonra)
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
name: strict-policy
namespace: production
spec:
# ...policy rules...
3. Policy Labels ve Documentation
Policy'lere anlamlı label ve annotation ekleyin:
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
name: api-security-policy
namespace: production
labels:
team: backend
environment: production
compliance: pci-dss
annotations:
description: "Restricts API server access to frontend pods only"
owner: "backend-team@company.com"
jira-ticket: "SEC-1234"
last-reviewed: "2026-03-01"
spec:
# ...
4. Emergency Break-Glass Procedure
Kritik durumlarda policy'leri hızlıca disable etme:
# Tüm Cilium Network Policy'leri geçici disable et
kubectl patch cnp -n production api-security-policy \
-p '{"spec":{"endpointSelector":{"matchLabels":{"__disabled__":"true"}}}}'
# Veya tüm namespace'deki policy'leri sil
kubectl delete cnp -n production --all
# Emergency break-glass ConfigMap
kubectl create configmap cilium-break-glass \
-n kube-system \
--from-literal=enabled=true
# Cilium agent bu ConfigMap'i kontrol ederse policy enforcement'ı durdurur
5. Policy Testing
Production'a çıkmadan önce policy'leri test edin:
# Test namespace oluştur
kubectl create namespace policy-test
# Policy'yi test namespace'ine deploy et
kubectl apply -f policy.yaml -n policy-test
# Test pod'ları oluştur
kubectl run test-client -n policy-test --image=curlimages/curl --rm -it -- sh
# Connection test
curl http://test-service:8080
6. Monitoring Alerts
Kritik policy violation'lar için alert oluşturun:
# Prometheus AlertManager rule
groups:
- name: cilium-security
interval: 30s
rules:
# Dropped packet spike (policy violation)
- alert: CiliumPolicyViolationSpike
expr: rate(hubble_drop_total{reason="Policy denied"}[5m]) > 10
for: 5m
labels:
severity: warning
annotations:
summary: "High rate of policy violations detected"
description: "{{ $value }} packets/sec dropped due to policy denial"
# L7 policy violations
- alert: CiliumL7PolicyViolation
expr: rate(hubble_http_requests_total{verdict="DENIED"}[5m]) > 5
for: 2m
labels:
severity: critical
annotations:
summary: "L7 HTTP policy violations detected"
# DNS policy violations
- alert: CiliumDNSPolicyViolation
expr: rate(hubble_dns_responses_total{verdict="DENIED"}[5m]) > 1
for: 5m
labels:
severity: warning
7. Backup ve GitOps
Tüm policy'leri Git'te saklayın:
# Tüm Cilium policy'leri backup al
kubectl get cnp,ccnp --all-namespaces -o yaml > cilium-policies-backup.yaml
# Git'e commit et
git add cilium-policies-backup.yaml
git commit -m "Backup Cilium policies - $(date +%Y-%m-%d)"
git push
ArgoCD ile GitOps:
# argocd-app.yaml
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: cilium-policies
namespace: argocd
spec:
project: security
source:
repoURL: https://github.com/company/k8s-policies
targetRevision: main
path: cilium/production
destination:
server: https://kubernetes.default.svc
namespace: production
syncPolicy:
automated:
prune: false # Policy silme işlemini manuel yap
selfHeal: true
Troubleshooting ve Common Issues {#troubleshooting}
Policy Uygulanmıyor
Problem: Policy oluşturdum ama trafik hala geçiyor.
Çözüm:
# 1. Policy'nin doğru pod'lara uygulandığını kontrol et
kubectl get cnp -n production api-policy -o yaml | grep -A5 endpointSelector
# 2. Endpoint'lerin policy'yi aldığını doğrula
kubectl get cep -n production
# 3. Cilium agent log'larını kontrol et
kubectl logs -n kube-system ds/cilium | grep -i policy
# 4. Policy'nin compile edildiğini doğrula
cilium policy get
DNS Resolution Çalışmıyor
Problem: FQDN-based policy uyguladıktan sonra DNS çalışmıyor.
Çözüm:
# DNS egress iznini ekle
egress:
- toEndpoints:
- matchLabels:
k8s:io.kubernetes.pod.namespace: kube-system
k8s-app: kube-dns
toPorts:
- ports:
- port: "53"
protocol: UDP
- port: "53"
protocol: TCP
Performance Degradation
Problem: Cilium kurulumundan sonra network performansı düştü.
Çözüm:
# 1. eBPF host routing'i aktifleştir (en hızlı datapath)
helm upgrade cilium cilium/cilium \
--set routingMode=native \
--set autoDirectNodeRoutes=true
# 2. kube-proxy replacement enable et
helm upgrade cilium cilium/cilium \
--set kubeProxyReplacement=strict
# 3. CPU limits'i artır
helm upgrade cilium cilium/cilium \
--set resources.limits.cpu=4000m
# 4. BPF map sizes'ı artır (büyük cluster'lar için)
helm upgrade cilium cilium/cilium \
--set bpf.ctTcpMax=524288 \
--set bpf.ctAnyMax=262144
Policy Conflict Resolution
Problem: Birden fazla policy aynı pod'a uygulanıyor ve conflict oluşuyor.
Çözüm:
# 1. Endpoint'e uygulanan tüm policy'leri listele
kubectl get cep -n production pod-xxxxx -o jsonpath='{.status.policy}'
# 2. Policy precedence (öncelik):
# - Deny rules > Allow rules
# - Specific selectors > Generic selectors
# - CiliumNetworkPolicy > NetworkPolicy
# 3. Hubble ile hangi policy'nin uygulandığını gör
hubble observe --pod production/pod-xxxxx --verdict DENIED
Hubble UI Bağlanamıyor
Problem: Hubble UI açılmıyor veya data görünmüyor.
Çözüm:
# 1. Hubble Relay'in çalıştığını kontrol et
kubectl get pods -n kube-system -l k8s-app=hubble-relay
# 2. Hubble metrics'in enabled olduğunu doğrula
cilium config view | grep hubble
# 3. Port-forward'ı yeniden başlat
pkill -f "port-forward.*hubble"
cilium hubble ui
# 4. Hubble Relay log'larını kontrol et
kubectl logs -n kube-system deployment/hubble-relay
Sonuç
Kubernetes Network Policies ve Cilium, modern cloud-native uygulamalar için zorunlu security katmanlarıdır. Bu yazıda ele aldığımız stratejiler:
✅ L3/L4 network segmentation ile temel izolasyon
✅ L7 application-aware filtering ile API güvenliği
✅ FQDN-based policies ile external API kontrolü
✅ Zero-trust architecture ile minimum privilege
✅ Hubble observability ile tam network visibility
✅ eBPF performance ile yüksek scalability
Production checklist:
- Tüm namespace'lerde default deny policy
- Critical service'ler için L7 filtering
- External egress için FQDN policies
- WireGuard/IPsec encryption enable
- Hubble monitoring ve alerting kurulu
- Policy backup ve GitOps entegrasyonu
- Regular security audit (quarterly)
Sonraki adımlar:
- Development cluster'da Cilium kurulumu yapın
- Bir namespace'de audit mode ile policy test edin
- Hubble UI ile traffic pattern'leri analiz edin
- Production'a incremental rollout planlayın
Network security, sürekli gelişen bir süreçtir. Policy'lerinizi düzenli olarak gözden geçirin, Hubble metrics'leri izleyin ve yeni tehditler için güncel kalın.
TekTık Yazılım olarak, Kubernetes security ve Cilium implementasyonları konusunda danışmanlık ve eğitim hizmetleri sunuyoruz. Sorularınız için info@tektik.tr adresinden bizimle iletişime geçebilirsiniz.
Faydalı Kaynaklar:
İlgili Blog Yazılarımız:
- GitOps ve ArgoCD: Modern Kubernetes Deployment Stratejisi
- Kubernetes Best Practices: Production Ortamları İçin Kapsamlı Rehber
- DevOps Security: CI/CD Pipeline Güvenliği ve Best Practices
Umarım bu rehber, Kubernetes cluster'larınızda güvenli ve ölçeklenebilir network politikaları uygulamanıza yardımcı olur. Sorularınızı yorumlarda paylaşabilirsiniz! 🚀🔒