Cloud-Native Security
Cloud-native systems trade long-lived servers for short-lived, identical, networked fragments â containers, pods, functions, sidecars â and that trade changes where security work belongs. Perimeter controls barely see the traffic, because most of it is east-west between services that were deployed minutes ago by an automated pipeline. The useful mental shift is from protecting machines to protecting workloads: every pod gets its own identity, its own network rules, its own least-privilege service account, and its own blast radius. Get that right and an attacker who compromises one container still faces a different identity, a different policy set and an alerting boundary at the next hop.
Four layers, four different failure modes
Each layer in the stack fails differently and needs its own owner. Confusing them is how teams end up with a hardened base image sitting behind a cluster whose API server accepts anonymous requests.
| Layer | What typically breaks | Primary control | Owner |
|---|---|---|---|
| Supply chain | Typosquatted package, poisoned base image | Provenance, SBOM, pinned digests | Platform engineering |
| Workload | Container running as root, writable filesystem | Pod security standards, non-root, read-only mounts | Application team |
| Orchestration | Over-permissive RBAC, unguarded API server | Admission policy, RBAC review, audit logging | Platform team |
| Network and identity | Flat pod network, static shared keys | Network policy, workload identity, mTLS | Platform plus security |
| Runtime | Unexpected process, outbound beacon | Runtime detection, egress policy | Security operations |
The table is also a triage guide. A critical CVE in a base image matters less than a pod that can reach the metadata service with instance-admin credentials, because the second one needs no vulnerability at all â only an SSRF bug and a misconfigured role.
Hardening workloads before the scheduler touches them
Most container escapes and privilege escalations come from convenience settings rather than kernel bugs: running as root, allowing privilege escalation, mounting a docker socket, or granting every Linux capability by default. Encode the minimum as policy and reject non-compliant pods at admission rather than hoping reviews catch them.
apiVersion: v1
kind: Pod
metadata:
name: payments-api
labels:
app: payments-api
tier: backend
spec:
automountServiceAccountToken: false
securityContext:
runAsNonRoot: true
runAsUser: 10001
runAsGroup: 10001
fsGroup: 10001
seccompProfile:
type: RuntimeDefault
containers:
- name: api
image: registry.example.com/payments-api@sha256:9f41c2a77b3e5d8f0a1c6b4d2e7f3a5c8b0d1e2f3a4b5c6d7e8f9a0b1c2d3e4f
ports:
- containerPort: 8080
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
resources:
requests: { cpu: "100m", memory: "128Mi" }
limits: { cpu: "500m", memory: "512Mi" }
volumeMounts:
- name: tmp
mountPath: /tmp
volumes:
- name: tmp
emptyDir: {}
Pair admission enforcement with image provenance: only signed images from your registry may run, digests are pinned so a floating tag cannot swap the contents, and a scheduled rebuild absorbs base-layer patches. The read-only filesystem plus an explicit writable tmp directory removes a whole class of persistence tricks attackers use once inside a container.
Network policy: segmentation that follows the pod
In a cluster, the default is open â every pod can reach every other pod until a policy says otherwise. Network policy is where that default is reversed, and because policies select pods by label rather than by IP, segmentation survives every rescheduling and autoscaling event.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: backend-default-deny
namespace: production
spec:
podSelector:
matchLabels:
tier: backend
policyTypes: [Ingress, Egress]
ingress:
- from:
- podSelector:
matchLabels:
tier: frontend
ports:
- protocol: TCP
port: 8080
egress:
- to:
- podSelector:
matchLabels:
app: postgres
ports:
- protocol: TCP
port: 5432
- to:
- namespaceSelector:
matchLabels:
name: kube-system
ports:
- protocol: UDP
port: 53
- to:
- ipBlock:
cidr: 10.0.0.0/8
Two omissions cause most production incidents here. DNS egress is forgotten, and pods silently stop resolving names, which is usually caught in testing; metadata service access is forgotten, and an attacker walks straight into cloud instance credentials, which is usually not. Deny the link-local metadata range explicitly, or configure the workload to require session tokens on every metadata call.
Service identity instead of shared secrets
Static API keys stored in environment variables fail two ways at once: they leak through logs and dumps, and they cannot be revoked per caller because everyone uses the same one. Cloud-native stacks solve this with workload identity â a pod authenticates with a short-lived credential issued by the platform, and authorization is expressed in terms of that identity.
apiVersion: security.istio.io/v1
kind: AuthorizationPolicy
metadata:
name: frontend-to-backend
namespace: production
spec:
selector:
matchLabels:
app: payments-api
action: ALLOW
rules:
- from:
- source:
principals:
- cluster.local/ns/production/sa/web-frontend
to:
- operation:
methods: ["POST", "GET"]
paths: ["/api/v1/charges*"]
Authorizing on service accounts rather than on network location means the same policy works whether traffic arrives through a mesh, a service mesh bypassed by mistake, or a direct pod-to-pod call. Rotate automatically, never print the credential, and treat any long-lived secret found in a deployment manifest as a finding with an expiry.
Serverless: short-lived and still worth attacking
Functions compress the attack surface in time but not in privilege. A Lambda or Cloud Function often runs with a broad execution role, an internet-facing trigger and access to a queue, which makes it an attractive pivot: compromise the function through a malformed event and you inherit its permissions. The lifecycle is short, so prevention and input validation matter more than detection.
import json, os, hmac, hashlib
SHARED_SECRET = os.environ["WEBHOOK_SECRET"].encode()
def handler(event, context):
# 1. verify the caller before touching any payload field
supplied = event.get("headers", {}).get("x-signature", "")
body = event.get("body", "") or ""
expected = hmac.new(SHARED_SECRET, body.encode(), hashlib.sha256).hexdigest()
if not hmac.compare_digest(supplied, expected):
return {"statusCode": 401, "body": json.dumps({"error": "bad signature"})}
# 2. validate shape; never pass raw input through to downstream calls
try:
payload = json.loads(body)
order_id = str(payload["order_id"])
if not order_id.isalnum() or len(order_id) > 64:
raise ValueError("order_id out of range")
except (ValueError, KeyError, TypeError):
return {"statusCode": 400, "body": json.dumps({"error": "invalid payload"})}
# 3. least privilege: assume a role scoped to this one action, not the account
client = boto3.client("dynamodb")
client.put_item(
TableName=os.environ["ORDERS_TABLE"],
Item={"order_id": {"S": order_id}, "state": {"S": "received"}},
ConditionExpression="attribute_not_exists(order_id)",
)
return {"statusCode": 202, "body": json.dumps({"order_id": order_id})}
Validate before parsing deeply, bound every downstream call to a narrow role, and make the function idempotent on an external key so a replayed event updates rather than duplicates. Those three habits cover most of what an attacker would exploit in an event-driven pipeline.
Guarding the control plane itself
The cluster control plane holds more power than any single workload: whoever can create pods, read secrets or modify roles can take the cluster. Restrict administrative access to a small, audited group through short-lived credentials and a jump path, disable anonymous and public access on the API server, and enable audit logging with a webhook that ships records off the cluster so a compromised administrator cannot rewrite history. Review role bindings on a schedule, because cluster-admin granted during a migration two years ago is the most common finding in any Kubernetes review.
Separate build and runtime privileges as well. A CI service account that can create cluster-admin bindings turns a pipeline compromise into full cluster ownership, so scope it to image pushes and namespace-scoped deployments only. Treat every change to RBAC, admission policy and secrets as a security-relevant event: alert on it, route it to the same queue as authentication anomalies, and require review when the binding is added rather than months later when someone audits the cluster.
Scanning and runtime detection close the loop
Static scanning catches known issues in artifacts; runtime detection catches behavior. Use both, because the container with zero CVEs can still be the one curling a command-and-control domain at 4am.
| Tool class | Answers | Cadence |
|---|---|---|
| Image and registry scan | Are there known vulnerable packages? | On build and on schedule |
| IaC and admission policy | Does this deployment meet the standard? | Every pull request |
| Runtime sensor | Is a process doing something no pod should? | Continuous |
| Egress monitoring | Where is traffic actually going? | Continuous, with alerts on new destinations |
| Cluster audit log | Who changed policy, RBAC or secrets? | Continuous, reviewed weekly |
Feed the alerts back into admission policy: when runtime detection discovers a pod writing to an unexpected path, the durable fix is a policy that prevents the same image from doing it again, not a ticket asking a team to remember.
đĄStart with the deny-by-default experiment
Common Mistakes
Relying on a hardened image while leaving the cluster API server and RBAC untouched
Fix: Review cluster admission policy, RBAC bindings and audit logging with the same rigor as image contents.
Leaving the cloud metadata service reachable from every pod
Fix: Deny link-local metadata access in egress policy or require session credentials on every metadata call.
Storing static API keys in environment variables for service-to-service calls
Fix: Adopt workload identity with short-lived credentials and per-service authorization rules.
Scanning images once at build and never again
Fix: Rescan on a schedule so newly published CVEs in existing artifacts raise tickets automatically.
Treating network policy as complete once ingress is restricted
Fix: Write egress rules explicitly, including DNS, update paths and the metadata range, with logging on denials.
Best Practices
- Pin image digests and require signed provenance before admission
- Run pods as non-root with a read-only filesystem and drop all capabilities
- Select network policy by label so segmentation survives rescheduling and autoscaling
- Authorize on service identity, and treat any long-lived secret in a manifest as a finding with a deadline
- Close the loop from runtime detection back into admission policy so fixes are structural
Key Takeaways
- Cloud-native security protects workloads with identities and policies, not machines with firewalls
- Admission-time enforcement of pod security is cheaper than any review process
- Default-deny network policy with explicit egress, including DNS and metadata, is the single highest-value cluster control
- Workload identity removes the shared-secret failure mode entirely
- Static scanning finds known issues; runtime detection finds intent, and both feed back into policy