DevSecOps & Container Security Labs

Master container orchestration, CI/CD security, and cloud-native application protection with hands-on labs covering Docker, Kubernetes, and DevSecOps pipelines.

Cloud DevSecOps Labs - Module 3

Build secure container environments and implement DevSecOps practices across cloud platforms.

Lab 7: Kubernetes Security & RBAC Implementation
Kubernetes / Advanced
Scenario: Secure Multi-Tenant Kubernetes Cluster
TechStartup is running a multi-tenant SaaS platform on Kubernetes. Implement comprehensive security controls including RBAC policies, Pod Security Standards, network policies, and secrets management. Configure admission controllers, enable audit logging, and implement runtime security monitoring. The cluster must support isolated environments for 50+ customers with strict security boundaries.

Learning Objectives:

  • RBAC Configuration: Implement role-based access control with least privilege principles
  • Pod Security: Configure Pod Security Standards to enforce restricted security policies
  • Network Policies: Implement micro-segmentation with deny-all default policies
  • Secrets Management: Secure sensitive data with encryption at rest and proper access controls

Step-by-Step Instructions:

  1. Create Isolated Namespace
    Objective: Create a dedicated namespace to isolate tenant resources from other workloads in the cluster.

    Command:
    kubectl create namespace tenant-alpha

    What this does: Creates a virtual cluster boundary that isolates resources, applies network policies, and enables granular RBAC controls specific to tenant-alpha.
    💡 Tip: Namespaces are the foundation of multi-tenancy in Kubernetes, providing logical isolation between different customers or applications.
  2. Configure Pod Security Standards
    Objective: Apply Kubernetes Pod Security Standards to enforce strict security policies on all pods in the namespace.

    Command:
    kubectl label namespace tenant-alpha pod-security.kubernetes.io/enforce=restricted

    What this does: Enforces the "restricted" Pod Security Standard, which prevents privileged containers, requires non-root users, drops dangerous capabilities, and enforces read-only root filesystems.
    💡 Tip: The restricted policy is the most secure tier and aligns with hardening best practices from CIS Kubernetes Benchmark.
  3. Implement Network Policies
    Objective: Create default-deny network policy to block all ingress/egress traffic, then selectively allow required connections.

    Command:
    kubectl create -f deny-all-policy.yaml

    What this does: Implements a zero-trust network model where all traffic is blocked by default. You must explicitly allow specific ingress/egress rules for legitimate communication.
    💡 Tip: Start with deny-all, then whitelist only required connections. This prevents lateral movement in case of pod compromise.
  4. Set Up Service Accounts
    Objective: Create a dedicated service account with minimal permissions following the principle of least privilege.

    Command:
    kubectl create serviceaccount app-sa -n tenant-alpha

    What this does: Creates a unique identity for your application pods that can be bound to specific RBAC roles. Never use the default service account for applications.
    💡 Tip: Service accounts enable fine-grained access control. Grant only the API permissions your app actually needs (e.g., list pods, but not delete).
  5. Configure Secrets Management
    Objective: Create Kubernetes secrets for sensitive data like database passwords, ensuring they are encrypted at rest.

    Command:
    kubectl create secret generic app-secret --from-literal=db_password=secure123 -n tenant-alpha

    What this does: Stores sensitive configuration data in a Secret object. When mounted in pods, secrets are stored in tmpfs (memory-only) and never written to disk.
    💡 Tip: Enable encryption at rest by configuring EncryptionConfiguration in kube-apiserver to encrypt secrets using AES-CBC or KMS.
  6. Enable Audit Logging
    Objective: Configure Kubernetes audit logging to track all API requests for security monitoring and compliance.

    Command:
    kubectl apply -f audit-policy.yaml

    What this does: Enables comprehensive logging of all API server requests including who made the request, what resources were accessed, and what actions were taken. Critical for forensics and compliance (PCI-DSS, SOC2).
    💡 Tip: Configure audit rules to capture metadata, request/response bodies for sensitive resources, and set appropriate retention policies.

After Completing All Steps:

  • Click "Run Security Scan" to analyze the cluster security posture
  • Click "View RBAC Matrix" to see the permission configuration
  • Check the Namespaces panel in the dashboard to verify tenant-alpha was created
  • Use the sidebar to browse RBAC, Policies, and Secrets
  • Click "Validate Security Configuration" to check your final score

Kubernetes Dashboard

prod-cluster

v1.27.3

Resources

Namespaces

default
Active
Pods: 5

kubectl Terminal

kubectl@prod-cluster:~$
Progress: 0/6 tasks completed
Score: 0/100
0%

Lab Completed!

Excellent Kubernetes security implementation!

Lab 8: Docker Security & Image Scanning
Docker / Intermediate
Scenario: Secure Container Registry Pipeline
FinanceApp Corp needs to implement a secure container build and deployment pipeline. Set up Docker image scanning, implement image signing with Docker Content Trust, configure a private registry with vulnerability scanning, create hardened base images following CIS benchmarks, and implement runtime security monitoring. Ensure all containers run with minimal privileges and proper resource constraints.

Learning Objectives:

  • Image Security: Scan container images for vulnerabilities and sign them using Docker Content Trust (DCT)
  • Registry Setup: Configure secure private registry (Harbor) with automated vulnerability scanning
  • Runtime Security: Implement AppArmor/SELinux policies and capability dropping
  • Compliance: Follow CIS Docker Benchmark recommendations for production hardening

Step-by-Step Instructions:

  1. Enable Docker Content Trust
    Objective: Enable Docker Content Trust to ensure only cryptographically signed images can be pulled and run.

    Command:
    export DOCKER_CONTENT_TRUST=1

    What this does: Activates image signature verification using The Update Framework (TUF). Docker will refuse to pull or run unsigned images, preventing supply chain attacks and image tampering.
    💡 Tip: DCT uses Notary for signing. When pushing images, Docker automatically generates signing keys and pushes signatures to the registry. This prevents man-in-the-middle attacks and ensures image provenance.
  2. Build Hardened Base Image
    Objective: Create a minimal, security-hardened base image following container best practices.

    Command:
    docker build -t secure-base:latest -f Dockerfile.secure .

    What this does: Builds a container image with security hardening: uses Alpine Linux (minimal attack surface), removes shell and package managers, creates non-root user, sets read-only filesystem, and drops all Linux capabilities except what's required.
    💡 Tip: Best practices - use distroless or scratch images, run as UID > 10000, use COPY instead of ADD, set USER directive, avoid latest tags, and implement multi-stage builds to exclude build dependencies.
  3. Scan Image for Vulnerabilities
    Objective: Use Trivy (open-source vulnerability scanner) to detect CVEs in OS packages, application dependencies, and misconfigurations.

    Command:
    docker run aquasec/trivy image secure-base:latest

    What this does: Scans all layers of the container image against vulnerability databases (NVD, Red Hat, Debian, Alpine, etc.). Reports CVEs with severity ratings (CRITICAL, HIGH, MEDIUM, LOW) and provides remediation guidance.
    💡 Tip: Integrate Trivy into CI/CD pipelines and fail builds on CRITICAL/HIGH vulnerabilities. Scan regularly as new CVEs are discovered daily. Also scan for secrets (API keys, passwords) accidentally committed.
  4. Deploy Private Harbor Registry
    Objective: Set up Harbor - an enterprise-grade container registry with built-in security scanning, RBAC, and replication.

    Command:
    docker run -d -p 443:443 --name harbor goharbor/harbor:latest

    What this does: Deploys Harbor registry with integrated Trivy scanning, image signing enforcement, vulnerability policy gates, RBAC for multi-tenancy, and audit logging. Supports Docker Content Trust and Notary out of the box.
    💡 Tip: Configure Harbor to automatically scan images on push, create severity-based policies (block CRITICAL CVEs), enable image retention policies, and set up replication for disaster recovery.
  5. Apply Security Policies
    Objective: Run containers with AppArmor/SELinux MAC (Mandatory Access Control) and drop all Linux capabilities.

    Command:
    docker run --security-opt apparmor=docker-default --cap-drop=ALL secure-base

    What this does: Applies AppArmor profile to restrict syscalls and file access. Drops all 38 Linux capabilities (CAP_CHOWN, CAP_NET_RAW, etc.) preventing privilege escalation. Container cannot perform privileged operations even if compromised.
    💡 Tip: Start with --cap-drop=ALL, then add back only required capabilities (e.g., CAP_NET_BIND_SERVICE for ports <1024). Combine with --read-only, --security-opt=no-new-privileges, and user namespaces for defense-in-depth.
  6. Set Up Runtime Monitoring
    Objective: Deploy Falco for runtime threat detection - monitors syscalls to detect anomalous behavior in real-time.

    Command:
    docker run -d --privileged -v /var/run/docker.sock:/host/var/run/docker.sock falcosecurity/falco:latest

    What this does: Installs kernel module to intercept syscalls. Detects threats like: shell spawned in container, sensitive file access, privilege escalation attempts, unexpected network connections, crypto mining, and reverse shells.
    💡 Tip: Customize Falco rules for your environment. Integrate with SIEM for alerting. Falco catches zero-day exploits and post-exploitation activity that static scanning misses.

After Completing All Steps:

  • Click "Scan Image" to run Trivy vulnerability scanner on your image
  • Click "CIS Benchmark" to view the Docker security compliance report
  • Use the Images tab to see your built images
  • Use the Security tab to view scan results
  • Click "Validate Docker Security" to check your final score

Docker Desktop

Docker Desktop

v24.0.2
Containers
Images
Security

Running Containers

No containers running. Build and run a secure container to start.

Docker Terminal

docker@desktop:~$
Progress: 0/6 tasks completed
Score: 0/100
0%

Lab Completed!

Great Docker security implementation!

Lab 9: Secure CI/CD Pipeline with SAST/DAST
DevSecOps / Advanced
Scenario: End-to-End DevSecOps Pipeline
E-Commerce Platform Inc. needs a secure CI/CD pipeline for their microservices architecture. Implement GitLab CI/CD with integrated security scanning including SAST (Static Application Security Testing), DAST (Dynamic Application Security Testing), dependency scanning, and container scanning. Configure security gates, implement secrets management with HashiCorp Vault, and set up automated compliance checks. The pipeline must prevent vulnerable code from reaching production.

Learning Objectives:

  • Pipeline Security: Implement secure CI/CD workflows with automated security testing at every stage
  • Security Testing: Configure SAST (code analysis), DAST (runtime testing), and SCA (dependency scanning)
  • Secrets Management: Integrate HashiCorp Vault for dynamic secrets and credential rotation
  • Compliance Gates: Implement policy-as-code to automatically block deployments with critical vulnerabilities

Step-by-Step Instructions:

  1. Configure Pipeline Stages
    Objective: Add a security stage to the pipeline so security scans run before deployment.

    How to do it:
    1. In the YAML editor, find the stages: section (lines 1-4)
    2. Add - security on a new line BETWEEN - test and - deploy

    Your stages should look like this:
    stages:
      - build
      - test
      - security
      - deploy
    Then run this command to validate:
    gitlab-ci validate

    💡 Tip: The security stage must come BEFORE deploy so vulnerabilities block deployment.
  2. Implement SAST Scanning
    Objective: Add Static Application Security Testing to scan source code for vulnerabilities.

    How to do it:
    1. In the YAML editor, add a new include: section AFTER the stages block (after line 5)
    2. Add the SAST template as shown below

    Add this code after the stages section:
    include:
      - template: Security/SAST.gitlab-ci.yml
    Then run this command:
    gitlab-ci sast enable

    💡 Tip: SAST scans your source code for SQL injection, XSS, hardcoded secrets, etc.
  3. Configure Dependency Scanning
    Objective: Scan third-party dependencies for known CVEs.

    How to do it:
    1. In the YAML editor, find the include: section you created in Step 2
    2. Add another template line UNDER the SAST template

    Your include section should now look like:
    include:
      - template: Security/SAST.gitlab-ci.yml
      - template: Security/Dependency-Scanning.gitlab-ci.yml
    Then run this command:
    gitlab-ci dependency-scan enable

    💡 Tip: This scans package.json, requirements.txt, etc. for vulnerable packages like Log4Shell.
  4. Set Up DAST Testing
    Objective: Add Dynamic Application Security Testing to test the running app.

    How to do it:
    1. In the YAML editor, find the include: section
    2. Add the DAST template as a third line

    Your include section should now look like:
    include:
      - template: Security/SAST.gitlab-ci.yml
      - template: Security/Dependency-Scanning.gitlab-ci.yml
      - template: Security/DAST.gitlab-ci.yml
    Then run this command:
    gitlab-ci dast configure --target=https://staging.app.com

    💡 Tip: DAST tests your live app like a hacker would - finding XSS, SQL injection, etc.
  5. Integrate HashiCorp Vault
    Objective: Replace hardcoded secrets and environment variables with dynamic secrets from HashiCorp Vault.

    Command:
    gitlab-ci vault configure --url=https://vault.internal --role=ci-cd

    What this does: Configures GitLab Runner to authenticate with Vault using JWT tokens. Pipeline jobs fetch secrets at runtime (DB passwords, API keys) instead of storing them in variables. Vault generates temporary credentials that auto-expire after the job completes.
    💡 Tip: Vault provides credential rotation, audit logging, and fine-grained access control. Never commit secrets to git or store them in CI/CD variables. Use Vault's dynamic database credentials for zero-trust architecture.
  6. Implement Security Gates
    Objective: Create automated policy gates that fail the pipeline if security thresholds are violated.

    Command:
    gitlab-ci security-gate create --critical=0 --high=3

    What this does: Implements policy-as-code: if SAST/DAST/dependency scans find any CRITICAL vulnerabilities or more than 3 HIGH-severity issues, pipeline automatically fails and blocks deployment. Enforces "shift-left" security - catch issues early before they reach production.
    💡 Tip: Set realistic thresholds that balance security and velocity. Too strict = constant build failures. Too loose = vulnerabilities slip through. Start with critical=0, high=5, then tighten over time.

After Completing All Steps:

  • Click "Run Pipeline" to execute the full CI/CD pipeline with security scans
  • Watch the Pipeline Stages panel to see each stage turn green as it passes
  • Check the Security Scan Results panel for vulnerability counts
  • Click "Security Report" button to view the detailed SAST/DAST/Dependency scan report
  • Click "Validate Pipeline Security" to check your final score

GitLab CI/CD Terminal

ecommerce-platform

Pipeline #247

.gitlab-ci.yml Editor

GitLab CI Terminal

gitlab-ci@runner:~$

Pipeline Stages

Build
Test
Security
Deploy

Security Scan Results

Configure pipeline and run commands to see security scan results
Progress: 0/6 tasks completed
Score: 0/100
0%

Lab Completed!

Excellent DevSecOps pipeline implementation!

Alert