DevSecOps & Security Hardening
Security at every stage. Scan images in CI. Enforce policies at admission time. Detect runtime anomalies. Encrypt secrets. Implement zero-trust networking.
Lesson objective
- What it teaches
- Architecture & How It Works · Core Components · WSL Hands-On Lab · Real-World Project · Troubleshooting · Deep Dive: Supply Chain Security · Predict the Result: Container Runtime Hardening
- Why it matters
- A required lesson for DevSecOps Engineer, DevOps / Platform Architect. Recommended for DevOps Engineer, Cloud Engineer, Platform Engineer, Container/Kubernetes Engineer, Release / CI-CD Engineer, MLOps / LLMOps Engineer. See the role paths
- What you demonstrate
-
- Simulated lab: Run the first command shown in the section “WSL Hands-On Lab”. Recorded as lab evidence.
- Predict 3 results this lesson prints. You mark each one yourself.
- Optional, real environment: 5 hands-on tasks on your own machine or an external lab site (checklist). Not tracked as evidence.
Architecture & How It Works 10.1
Defense-in-depth layers: code scanning → image scanning → admission control → runtime detection → network segmentation → access control. Shift left reduces blast radius.
Core Components 10.2
| Tool | Role | Primary Command |
|---|---|---|
| Trivy | Vulnerability scanner | trivy image |
| Falco | Runtime threat detection | falco -r custom-rules.yaml |
| Gatekeeper / OPA | Admission webhook policies | kubectl apply -f constraint.yaml |
| SOPS + age | Secret encryption | sops --encrypt |
| NetworkPolicy | Pod traffic control | kubectl apply -f netpol.yaml |
WSL Hands-On Lab 10.3
Trivy → Falco on kind → OPA Constraint → SOPS → NetworkPolicy
$ trivy image --severity CRITICAL myapp:latest $ helm repo add falcosecurity https://falcosecurity.github.io/charts $ helm install falco falcosecurity/falco -n falco --create-namespace $ sops --encrypt --in-place secrets/production.yaml
- Scan a deliberately vulnerable image and fix findings
- Deploy Falco and trigger a runtime rule
- Create and test OPA Gatekeeper constraint denying privileged pods
- Encrypt a Helm values file using SOPS + age
- Apply a NetworkPolicy that isolates a namespace
Real-World Project 10.4
Trivy scan step inside GitHub Actions
OPA policies + NetworkPolicies + encrypted secrets with SOPS
Falco + SIEM integration + Cosign image signing + SLSA provenance + SOC2 controls
Troubleshooting 10.5
Falco false positives
Create exceptions or custom rules that match your legitimate workloads.
OPA constraint blocking valid workloads
Start with dryRun: true mode. Review audit logs before switching to deny.
NetworkPolicy locking out services
Always test with a wide allow policy first. Use namespace selectors carefully.
30-Day Roadmap 10.6
- Trivy / Grype workflows
- Distroless images
- Fixing CVEs fast
- RBAC least privilege
- Pod Security Standards
- NetworkPolicy
- Falco rules
- OPA Gatekeeper
- Admission controllers
- Cosign signing
- SLSA + SBOM
- Compliance automation
Deep Dive: Supply Chain Security 10.7
Cosign + SLSA
Sign every image in CI. Verify signatures in admission controller or at deploy time. Generate SBOMs and attach them. Meet SLSA level 2+ for high-trust environments.
Runtime + Admission Synergy
Falco catches what static analysis misses. OPA prevents bad configurations from ever reaching the cluster. Together they provide full defense in depth.
Predict the Result: Container Runtime Hardening 10.8
Recorded from a real run of scripts/recordings/security.sh; every output below is pasted from scripts/recordings/security.out. Cover the output, predict it, then compare.
Environment: Docker Engine 26.1.5 on Linux, image alpine:3.20. The same controls exist in Kubernetes as runAsUser, readOnlyRootFilesystem and capabilities.drop.
# Which user does a container run as by default? $ docker run --rm alpine:3.20 id -u 0 # Run as an unprivileged user $ docker run --rm --user 65534:65534 alpine:3.20 id uid=65534(nobody) gid=65534(nobody) groups=65534(nobody) # Write to a read-only root filesystem $ docker run --rm --read-only alpine:3.20 touch /tmp/x touch: /tmp/x: Read-only file system # Root, but with every Linux capability dropped $ docker run --rm --cap-drop ALL alpine:3.20 chown 65534 /etc/hostname chown: /etc/hostname: Operation not permitted
Images without a USER run as root. Dropping all capabilities takes away most of what root can do inside the container, such as changing file ownership, even though id -u still says 0. Combine a non-root user, a read-only root filesystem and --cap-drop ALL, then add back only the capability the process needs.
Falco Custom Rules, Gatekeeper Constraints & Cosign Image Signing
Defense-in-depth requires verifying artifact integrity at build time, blocking misconfigurations at admission, and catching anomalies at runtime. According to Falco Rules Reference, OPA Gatekeeper How-To, and Sigstore Cosign Documentation (Falco v0.38+, Gatekeeper v3.16+, Cosign v2.4+):
# 1. Falco Custom Rule: Detect Interactive Shells Spawned in Production Pods
- rule: Production Interactive Shell Spawned
desc: Detect interactive shell execution within a production workload container
condition: spawned_process and container and (proc.name in (bash, sh, zsh, ash)) and container.name != "forensics-sidecar"
output: >
Notice: Shell execution inside container
(user=%user.name uid=%user.uid container_id=%container.id container_name=%container.name command=%proc.cmdline)
priority: WARNING
tags: [container, mitre_execution]
---
# 2. OPA Gatekeeper ConstraintTemplate: Deny Privileged Containers (Including Init & Ephemeral)
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
name: k8sblockprivileged
spec:
crd:
spec:
names:
kind: K8sBlockPrivileged
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package k8sblockprivileged
all_containers[c] {
c := input.review.object.spec.containers[_]
}
all_containers[c] {
c := input.review.object.spec.initContainers[_]
}
all_containers[c] {
c := input.review.object.spec.ephemeralContainers[_]
}
violation[{"msg": msg}] {
c := all_containers[_]
c.securityContext.privileged == true
msg := sprintf("Privileged container %v is forbidden in production", [c.name])
}
---
# 3. OPA Gatekeeper Constraint: Enforced on Production Namespace
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sBlockPrivileged
metadata:
name: block-privileged-containers
spec:
enforcementAction: deny
match:
kinds:
- apiGroups: [""]
kinds: ["Pod"]
namespaces:
- "production"Cosign Supply Chain Verification Workflow:
# 1. Generate keypair with password stored in secure environment or KMS
cosign generate-key-pair
# 2. Sign the immutable image digest built during CI
cosign sign --key cosign.key registry.internal/payment-api:v2.4.0
# 3. Verify cryptographic signature against trusted public key before deployment
cosign verify --key cosign.pub registry.internal/payment-api:v2.4.0
Fail-Closed Security Design: Unsigned images or images signed with untrusted keys fail admission verification immediately. While cosign verify validates signatures during CI/CD promotion gates, Kubernetes clusters enforce admission using admission controllers (such as Sigstore Policy Controller or Kyverno with Cosign key validation), preventing unauthorized binaries from reaching production nodes.
Gatekeeper Dryrun Staging & NetworkPolicy Egress Lockout Recovery
Enforcing strict zero-trust rules without staged rollout risks catastrophic self-inflicted lockouts (e.g. blocking DNS egress or crashing running daemonsets). According to Gatekeeper Enforcement Actions and Kubernetes Network Policies Guide:
# 1. Stage Gatekeeper in dryrun mode before full enforcement
kubectl patch k8sblockprivileged block-privileged-containers --type=merge -p '{"spec":{"enforcementAction":"dryrun"}}'
# 2. Inspect audit violations to identify non-compliant workloads before breaking production
kubectl get k8sblockprivileged block-privileged-containers -o jsonpath='{.status.violations}' | jq .
# 3. Simulate Egress Lockout: Accidental default-deny NetworkPolicy drops CoreDNS port 53
# Workloads report 'getaddrinfo EAI_AGAIN' or 'dial tcp: lookup failed'
# 4. Immediate Safe Rollback: delete erroneous policy or patch targeted egress allow rule
kubectl delete networkpolicy default-deny-all -n production
# 5. Apply hardened NetworkPolicy that explicitly permits cluster CoreDNS resolution
cat <<EOF | kubectl apply -f -
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-dns-and-ingress
namespace: production
spec:
podSelector: {}
policyTypes: [Egress]
egress:
- to:
- namespaceSelector: {}
podSelector:
matchLabels:
k8s-app: kube-dns
ports:
- protocol: UDP
port: 53
- protocol: TCP
port: 53
EOF
Staged Rollout Principle: Never introduce admission rules directly in deny mode. Always configure enforcementAction: dryrun and observe telemetry across at least one deployment cycle, verifying zero legitimate violations before enabling active blocking.
Runtime Threat Containment, Forensic Evidence & Key Revocation Walkthrough
When Falco detects unauthorized runtime execution, panic-restarting the container destroys transient forensic artifacts. SRE and security engineers follow a deterministic 4-phase incident response based on NIST SP 800-61 Incident Response Guidelines. (Simulated offline exercise; no credentials, paid cloud resources, or host-destructive experiments are used; simulated results are labeled and live-run limitations remain in curriculum gaps).
# PHASE 1: DETECTION & EVIDENCE PRESERVATION
# Capture pod metadata, container PID, and active socket connections without killing process
kubectl get pod payment-api-6b79fd-x2n8q -n production -o json > evidence-pod.json
kubectl logs payment-api-6b79fd-x2n8q -n production --all-containers=true > evidence-logs.txt
# PHASE 2: CONTAINMENT & ISOLATION
# 1. Label pod out of Service endpoints to cut ingress customer traffic
kubectl label pod payment-api-6b79fd-x2n8q -n production app=quarantined --overwrite
# 2. Notice on additive policies: Any baseline policy with podSelector: {} still applies.
# Narrow overlapping allow policies or remove them before relying on quarantine isolation.
# Apply quarantine NetworkPolicy cutting off inbound/outbound workload access
cat <<EOF | kubectl apply -f -
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: isolate-quarantined-pod
namespace: production
spec:
podSelector:
matchLabels:
app: quarantined
policyTypes: [Ingress, Egress]
EOF
# PHASE 3: CREDENTIAL ROTATION & REVOCATION
# Invalidate compromised service account tokens and rotate database secrets
kubectl delete serviceaccount payment-api-sa -n production
vault lease revoke -prefix database/creds/payment-api-role
# Recreate clean service account and rolebindings before restarting workloads
kubectl create serviceaccount payment-api-sa -n production
kubectl apply -f payment-api-rbac.yaml -n production
# PHASE 4: ERADICATION & RECOVERY
# Terminate quarantined pod and deploy verified, signed container image
kubectl delete pod payment-api-6b79fd-x2n8q -n production --grace-period=0 --force
kubectl rollout restart deployment/payment-api -n production// Deterministic Falco Rule Evaluator
export function evaluateFalcoRule(event) {
if (!event || !event.proc || !event.container) return { triggered: false, rule: null };
const shellBinaries = new Set(['bash', 'sh', 'zsh', 'ash']);
if (event.container.id && event.spawned && shellBinaries.has(event.proc.name) && event.container.name !== 'forensics-sidecar') {
return {
triggered: true,
rule: 'Production Interactive Shell Spawned',
priority: 'WARNING',
user: event.user?.name || 'unknown'
};
}
return { triggered: false, rule: null };
}
// Deterministic Gatekeeper Privilege Evaluator (containers + initContainers + ephemeralContainers)
export function evaluateGatekeeperPolicy(pod) {
const containers = [
...(pod?.spec?.containers || []),
...(pod?.spec?.initContainers || []),
...(pod?.spec?.ephemeralContainers || [])
];
for (const c of containers) {
if (c.securityContext?.privileged === true) {
return { allowed: false, violation: 'Privileged container ' + c.name + ' is forbidden in production' };
}
}
return { allowed: true, violation: null };
}
// Deterministic NetworkPolicy Egress Evaluator
export function evaluateEgressPolicy(destinationPort, destinationProtocol, isDnsAllowConfigured) {
if (destinationPort === 53 && (destinationProtocol === 'UDP' || destinationProtocol === 'TCP')) {
return { allowed: isDnsAllowConfigured, reason: isDnsAllowConfigured ? 'DNS egress permitted' : 'Dropped by default-deny egress' };
}
return { allowed: false, reason: 'Egress traffic dropped' };
}