Skip to content
devops/architect
10 security 01 01 devsecops & security hardening
0/8 read · lab 0/1
STARTUP TO ENTERPRISE
10 / 14 • SHIFT-LEFT SECURITY

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.

Trivy CI OPA + NetPol Falco + Cosign + SLSA

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.
  1. Orient
  2. Read
  3. Predict
  4. Run
  5. Verify
  6. Reflect
  7. Continue

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.

graph LR Code[Code Repo] --> Trivy[Trivy Scan] Trivy --> Build[Build Image] Build --> Gate[OPA Gatekeeper] Gate --> Runtime[Falco] Runtime --> Net[NetworkPolicy] Net --> Access[RBAC/IRSA]

Core Components 10.2

ToolRolePrimary Command
TrivyVulnerability scannertrivy image
FalcoRuntime threat detectionfalco -r custom-rules.yaml
Gatekeeper / OPAAdmission webhook policieskubectl apply -f constraint.yaml
SOPS + ageSecret encryptionsops --encrypt
NetworkPolicyPod traffic controlkubectl apply -f netpol.yaml

WSL Hands-On Lab 10.3

Trivy → Falco on kind → OPA Constraint → SOPS → NetworkPolicy

security commands
$ 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

WEEK 1
Image Hardening
  • Trivy / Grype workflows
  • Distroless images
  • Fixing CVEs fast
WEEK 2
Kubernetes Security
  • RBAC least privilege
  • Pod Security Standards
  • NetworkPolicy
WEEK 3
Runtime Detection
  • Falco rules
  • OPA Gatekeeper
  • Admission controllers
WEEK 4
Supply Chain
  • 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.

recorded run
# 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.

RUNTIME DETECTION & ADMISSION GATES

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+):

security-rules-and-constraints.yaml (Falco, Gatekeeper & Cosign)
# 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:

cosign-signing-workflow.sh (Artifact Signing & Admission Verification)
# 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.

SAFE ADMISSION & LOCKOUT DRILLS

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:

staged-lockout-recovery.sh (Diagnosis & Rollback Drill)
# 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.

INCIDENT RESPONSE RUNBOOK

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).

runtime-incident-runbook.sh (NIST Incident Response Phases)
# 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
scripts/offline-security-evaluator.mjs (Deterministic Security Evaluator)
// 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' };
}

Predict: results this lesson prints

Write what you expect, then compare with the lesson. You mark each result yourself; it is recorded as predict evidence.

What result does the lesson show for this command?

$ docker run --rm alpine:3.20 id -u
Show the lesson's result

The lesson shows:

0

What result does the lesson show for this command?

$ docker run --rm --user 65534:65534 alpine:3.20 id
Show the lesson's result

The lesson shows:

uid=65534(nobody) gid=65534(nobody) groups=65534(nobody)

What result does the lesson show for this command?

$ docker run --rm --read-only alpine:3.20 touch /tmp/x
Show the lesson's result

The lesson shows:

touch: /tmp/x: Read-only file system

Practice: troubleshoot and decide

Commit to an answer before each result is shown. Finishing a drill or a decision is recorded as evidence for the sections it builds on.

Troubleshooting drill

An image scan that has never failed a build

Output recorded from a real run on Trivy 0.67.2 (aquasec/trivy Docker image) run from Git Bash on Windows, vulnerability database downloaded on 8 Oct 2026. Public nginx images from Docker Hub stand in for the team's image; finding counts change as the database is updated. Nothing runs on your machine.

Builds on WSL Hands-On Lab, Real-World Project.

The CI pipeline has had an image scan step for a year, copied from the lesson: trivy image --severity CRITICAL. The job has never failed. A penetration test now reports that the production image is built on nginx 1.21.0 and carries dozens of critical vulnerabilities. The scan step ran on every one of those builds.

  1. Step 1 of 3: The scan ran on every build and every build stayed green. What do you check first?

Design decision

Blocking unsafe pods across 40 namespaces: Pod Security Admission, Kyverno or Gatekeeper?

Builds on WSL Hands-On Lab, Troubleshooting.

A platform team of two runs three EKS clusters shared by 40 team namespaces. An audit found six workloads running privileged containers or mounting host paths, and several pulling images straight from Docker Hub. Leadership wants unsafe pods blocked at admission, every image pulled from registry.acme.io, and every workload labelled with its owning team.

Constraints

  • Privileged containers and hostPath mounts must be blocked in team namespaces; kube-system and the node monitoring agents still need them
  • Images must come from registry.acme.io, and every pod needs a team label
  • Nobody on the platform team writes Rego today
  • Existing workloads cannot break on day one: violations must be reported before they are denied
Which do you choose?

Lab: simulated terminal, nothing runs on your machine

Simulated nothing runs on your machine

  1. 1 Run the first command shown in the section “WSL Hands-On Lab”
Run the first command shown in the section “WSL Hands-On Lab”

Ready. Type the command for the current goal.

Check yourself

Why does the DevSecOps architecture sequence vulnerability scanning before image building and admission control?

Explanation

In 'Architecture & How It Works 10.1', defense-in-depth layers progress from code scanning to image scanning, admission control, runtime detection, and network segmentation. Shifting left catches defects early to reduce blast radius; it does not replace admission webhooks, runtime detection, or network policies.

An OPA Gatekeeper constraint is planned for production but must not break existing valid workloads. Which rollout step does the lesson recommend?

Explanation

In 'Troubleshooting 10.5', 'OPA constraint blocking valid workloads' advises starting with dryRun mode and reviewing audit logs before switching to deny. Immediate deny risks breaking workloads, while turning off webhooks or converting to NetworkPolicy bypasses admission validation.

After applying a default-deny NetworkPolicy in production, workloads report 'getaddrinfo EAI_AGAIN' errors. What caused this failure?

Explanation

In 'Gatekeeper Dryrun Staging & NetworkPolicy Egress Lockout Recovery', an accidental default-deny NetworkPolicy drops CoreDNS port 53 traffic, resulting in 'getaddrinfo EAI_AGAIN' or lookup failures. Workloads require an explicit egress allow rule to kube-dns on port 53.

When Falco detects unauthorized runtime shell execution in a pod, why does the incident response runbook capture metadata and logs before terminating the container?

Explanation

In 'Runtime Threat Containment, Forensic Evidence & Key Revocation Walkthrough', panic-restarting the container destroys transient forensic artifacts. SRE and security engineers capture pod metadata, container PID, and logs during Phase 1 evidence preservation before containment and eradication.

What primary role does Falco play in Kubernetes security defense-in-depth?

Runtime threat detection by monitoring kernel syscalls against rule conditions.

Space flips the current card.

Capability coverage: L1, L2, L3 covered

No lesson evidence yet. Start reading this lesson, then run its free lab to record demonstrated checks.

Each cell counts this lesson's sections for that skill and level. Complete needs a demonstrated check (today only the lab); reading a section shows Developing. Not covered means the lesson has no material there.

Skills by experience level for this lesson
SkillL1 FoundationL2 PractitionerL3 ProductionL4 Architect
Understand Missing · 3 sections Not covered Not covered Not covered
Operate Not covered Missing · 2 sections Not covered Not covered
Troubleshoot Not covered Not covered Missing · 1 section Not covered
Automate Not covered Not covered Not covered Not covered
Secure Not covered Missing · 2 sections Missing · 1 section Not covered
Observe Not covered Not covered Not covered Not covered
Design Not covered Not covered Not covered Not covered
Make trade-offs Not covered Not covered Not covered Not covered

How this lesson fits each role