diff --git a/README.md b/README.md index 7a833ce0..70ccf3e3 100644 --- a/README.md +++ b/README.md @@ -1,93 +1,974 @@ # ๐Ÿ” Introduction to DevSecOps: Principles, Practices & Secure Delivery -[![Labs](https://img.shields.io/badge/Labs-80%25-blue)](#lab-based-learning-experience) -[![Exam](https://img.shields.io/badge/Exam-20%25-orange)](#evaluation-framework) -[![Hands-On](https://img.shields.io/badge/Focus-Hands--On%20Security-success)](#lab-based-learning-experience) -[![Level](https://img.shields.io/badge/Level-Bachelor-lightgrey)](#course-roadmap) +[![Labs](https://img.shields.io/badge/Labs-80%25-blue)](#-lab-based-learning-experience) +[![Exam](https://img.shields.io/badge/Exam-20%25-orange)](#-evaluation-framework) +[![Hands-On](https://img.shields.io/badge/Focus-Hands--On%20Security-success)](#-lab-based-learning-experience) +[![Duration](https://img.shields.io/badge/Duration-10%20Modules-lightgrey)](#-course-roadmap) -Welcome to the **Introduction to DevSecOps Course**, where you will learn how to integrate security seamlessly into modern software development and operations. -This course is designed for bachelor-level students who want to build a strong foundation in DevSecOps culture, practices, and tooling. - -Through **hands-on labs and focused lectures**, youโ€™ll gain experience with secure coding, automated testing, infrastructure-as-code, container security, and vulnerability management โ€” the same approaches used by leading engineering teams worldwide. +Welcome to the **Introduction to DevSecOps Course**, where you will learn to **integrate security seamlessly into modern software development and operations**. +This course is designed to provide a comprehensive understanding of DevSecOps culture, practices, and tooling for building secure software systems. +Through **hands-on labs and focused lectures**, you'll gain experience with secure coding, automated testing, infrastructure-as-code security, container hardening, and vulnerability management โ€” the same approaches used by leading engineering teams worldwide. --- ## ๐Ÿ“š Course Roadmap -Practical modules designed for incremental skill development: - -| # | Module | Key Topics & Technologies | -|----|-------------------------------------------|------------------------------------------------------------------------------------------| -| 1 | **Foundations & Secure SDLC** | DevSecOps principles, shift-left culture, OWASP Top 10, secure coding practices | -| 2 | **Threat Modeling & Security Requirements** | STRIDE, attack surfaces, risk analysis, integrating requirements into agile workflows | -| 3 | **Secure Git & Secrets Management** | Git security, signed commits, secret scanning, vaulting secrets | -| 4 | **CI/CD Security & Build Hardening** | Secure pipelines, artifact integrity, quality gates | -| 5 | **Application Security Testing Basics** | SAST, DAST, SCA, tool integration into pipelines | -| 6 | **Infrastructure-as-Code Security** | Terraform/Ansible, misconfiguration scanning, policy-as-code | -| 7 | **Containers & Kubernetes Security** | Docker/K8s fundamentals, image scanning, RBAC, PodSecurity, runtime protection | -| 8 | **Software Supply Chain Security & SBOM** | Dependency risk, SBOM generation (CycloneDX/SPDX), artifact signing, provenance | -| 9 | **Monitoring, Compliance & Improvement** | Logging/metrics, KPIs (MTTR, vuln age), GDPR/NIST/ISO basics, maturity models | -| 10 | **Vulnerability Management & Testing** | Lifecycle (discovery โ†’ triage โ†’ remediation โ†’ reporting), CVSS, SAST/DAST/SCA workflows | +**10-module intensive course** with practical labs designed for incremental skill development: + +> **Note:** Labs 11-12 are **optional bonus labs** for extra credit. Complete them to boost your grade or explore advanced security hardening techniques! + +| Lab | Module | Key Topics & Technologies | +|-----|---------------------------------------------|------------------------------------------------------------------------------------------| +| 1 | **Foundations & Secure SDLC** | DevSecOps principles, shift-left culture, OWASP Top 10, secure coding practices | +| 2 | **Threat Modeling & Security Requirements** | STRIDE analysis, attack surfaces, risk assessment, agile security integration | +| 3 | **Secure Git & Secrets Management** | Git security, signed commits, secret scanning, vault integration, secure workflows | +| 4 | **CI/CD Security & Build Hardening** | Secure pipelines, artifact integrity, quality gates, SBOM generation, SCA integration | +| 5 | **Application Security Testing** | SAST, DAST, IAST, security tool integration, automated testing pipelines | +| 6 | **Infrastructure-as-Code Security** | Terraform/Pulumi/Ansible scanning, misconfiguration detection, policy-as-code | +| 7 | **Container & Kubernetes Security** | Docker/K8s fundamentals, image scanning, RBAC, PodSecurity, runtime protection | +| 8 | **Software Supply Chain Security** | Dependency analysis, SBOM (CycloneDX/SPDX), artifact signing, provenance verification | +| 9 | **Monitoring, Compliance & Improvement** | Security metrics, KPIs (MTTR, vuln age), GDPR/NIST/ISO basics, maturity models | +| 10 | **Vulnerability Management & Response** | Discovery, triage, remediation workflows, CVSS scoring, security testing orchestration | +| โ€” | **๐ŸŽ Bonus: Reverse Proxy Hardening** | Nginx security headers, TLS termination, rate limiting, timeout configuration | +| โ€” | **๐ŸŽ Bonus: VM-backed Container Isolation** | Kata Containers, runtime comparison, isolation testing, security/performance tradeoffs | + +--- + +## ๐Ÿ—’๏ธ Lecture Slide Overview + +Index extracted from `lectures/lec*.md`. Each lecture links to its source file and shows an approximate slide count. + +
+๐Ÿ“Œ Lecture 1 - DevSecOps Foundations & Secure SDLC (48 slides) + +- ๐Ÿ“ Slide 1 โ€“ ๐ŸŒ What is DevSecOps? +- ๐Ÿ“ Slide 2 โ€“ ๐Ÿ”„ Why Security in DevOps Matters +- ๐Ÿ“ Slide 3 โ€“ ๐Ÿง‘โ€๐Ÿคโ€๐Ÿง‘ DevOps Culture & Security Culture +- ๐Ÿ“ Slide 4 โ€“ ๐Ÿ•ฐ๏ธ The โ€œShift-Leftโ€ Philosophy +- ๐Ÿ“ Slide 5 โ€“ ๐Ÿ“Š Industry Reports & Trends +- ๐Ÿ“ Slide 6 โ€“ ๐Ÿ—๏ธ What is the Secure Software Development Life Cycle (Secure SDLC)? +- ๐Ÿ“ Slide 7 โ€“ ๐Ÿ“œ History of SDLC Models +- ๐Ÿ“ Slide 8 โ€“ ๐Ÿงฉ Secure SDLC Phases (Overview) +- ๐Ÿ“ Slide 9 โ€“ โš–๏ธ Traditional SDLC vs Secure SDLC +- ๐Ÿ“ Slide 10 โ€“ ๐Ÿงฎ Key Standards & Frameworks +- ๐Ÿ“ Slide 11 โ€“ ๐Ÿ† Introduction to OWASP +- ๐Ÿ“ Slide 12 โ€“ ๐Ÿ“ˆ Evolution of OWASP Top 10 +- ๐Ÿ“ Slide 13 โ€“ ๐Ÿ”ฅ OWASP Top 10 (2021) Categories +- ๐Ÿ“ Slide 14 โ€“ โšก Real Incidents Mapped to OWASP Top 10 +- ๐Ÿ“ Slide 15 โ€“ ๐ŸŒ What Are Vulnerabilities? +- ๐Ÿ“ Slide 16 โ€“ ๐Ÿ’‰ SQL Injection (SQLi) +- ๐Ÿ“ Slide 17 โ€“ ๐Ÿ“œ Cross-Site Scripting (XSS) +- ๐Ÿ“ Slide 18 โ€“ ๐Ÿ”‘ Authentication & Session Vulnerabilities +- ๐Ÿ“ Slide 19 โ€“ ๐Ÿ›‘ Cross-Site Request Forgery (CSRF) +- ๐Ÿ“ Slide 20 โ€“ ๐Ÿ—„๏ธ Insecure Deserialization & Logic Bugs +- ๐Ÿ“ Slide 21 โ€“ โ˜๏ธ Misconfigurations (Cloud, Servers, Containers) +- ๐Ÿ“ Slide 22 โ€“ ๐Ÿงฉ Case Study Examples for Vulnerabilities +- ๐Ÿ“ Slide 23 โ€“ ๐Ÿ”’ Security as Code +- ๐Ÿ“ Slide 24 โ€“ โš™๏ธ Security Champions & Roles in Teams +- ๐Ÿ“ Slide 25 โ€“ ๐Ÿงช Security by Design +- ๐Ÿ“ Slide 26 โ€“ ๐Ÿ› ๏ธ Tooling Ecosystem Overview (High-Level) +- ๐Ÿ“ Slide 27 โ€“ ๐Ÿ“š Knowledge Sources +- ๐Ÿ“ Slide 28 โ€“ ๐Ÿ’ป What is Secure Coding? +- ๐Ÿ“ Slide 29 โ€“ ๐Ÿ“ Secure Coding Guidelines +- ๐Ÿ“ Slide 30 โ€“ ๐Ÿง‘โ€๐Ÿ’ป Common Coding Mistakes +- ๐Ÿ“ Slide 31 โ€“ ๐Ÿ“Š Languages & Secure Coding +- ๐Ÿ“ Slide 32 โ€“ ๐Ÿ” Code Review & Pair Programming +- ๐Ÿ“ Slide 33 โ€“ ๐Ÿงญ What is MITRE ATT\&CK? +- ๐Ÿ“ Slide 34 โ€“ ๐Ÿ“Š MITRE ATT\&CK Matrix +- ๐Ÿ“ Slide 35 โ€“ ๐Ÿ› ๏ธ Examples of ATT\&CK Techniques +- ๐Ÿ“ Slide 36 โ€“ ๐ŸŒ What is MITRE ATLAS? +- ๐Ÿ“ Slide 37 โ€“ ๐Ÿค– AI-Specific Threat Examples +- ๐Ÿ“ Slide 38 โ€“ ๐Ÿ”— Using ATT\&CK/ATLAS in DevSecOps +- ๐Ÿ“ Slide 39 โ€“ ๐Ÿข Case Study: Equifax Breach (2017) +- ๐Ÿ“ Slide 40 โ€“ โ˜๏ธ Case Study: Capital One Breach (2019) +- ๐Ÿ“ Slide 41 โ€“ ๐Ÿ Case Study: Log4Shell (2021) +- ๐Ÿ“ Slide 42 โ€“ ๐Ÿ’ณ Case Study: Heartbleed (2014) +- ๐Ÿ“ Slide 43 โ€“ ๐Ÿ“ก Case Study: SolarWinds (2020) +- ๐Ÿ“ Slide 44 โ€“ ๐Ÿ“– Recommended Books +- ๐Ÿ“ Slide 45 โ€“ ๐ŸŽ“ Certifications & Training +- ๐Ÿ“ Slide 46 โ€“ ๐Ÿ›ก๏ธ Maturity Models for DevSecOps +- ๐Ÿ“ Slide 47 โ€“ ๐Ÿ“ˆ KPIs & Metrics for DevSecOps +- ๐Ÿ“ Slide 48 โ€“ ๐Ÿš€ Future of DevSecOps + +
+ +
+๐Ÿ“Œ Lecture 2 - Threat Modeling & Security Requirements (30 slides) + +- ๐Ÿ“ Slide 1 โ€“ ๐Ÿงญ What Is Threat Modeling? +- ๐Ÿ“ Slide 2 โ€“ ๐Ÿ“ˆ Why It Matters (Outcomes & Fresh Stats) +- ๐Ÿ“ Slide 3 โ€“ ๐Ÿท๏ธ Assets, Threats, Vulnerabilities, Risk (Clear Terms) +- ๐Ÿ“ Slide 4 โ€“ ๐Ÿงฑ Trust Boundaries & ๐Ÿ” Data Sensitivity +- ๐Ÿ“ Slide 5 โ€“ ๐ŸŒ Attack Surface 101 (What Expands It?) +- ๐Ÿ“ Slide 6 โ€“ ๐Ÿ” Where Threat Modeling Fits (SDLC & Agile) +- ๐Ÿ“ Slide 7 โ€“ ๐Ÿ—บ๏ธ Data Flow Diagrams (DFDs) Essentials +- ๐Ÿ“ Slide 8 โ€“ ๐Ÿงญ Scoping & Assumptions +- ๐Ÿ“ Slide 9 โ€“ ๐Ÿงฉ STRIDE Framework Intro +- ๐Ÿ“ Slide 10 โ€“ ๐Ÿชช S = Spoofing +- ๐Ÿ“ Slide 11 โ€“ ๐Ÿงช T = Tampering +- ๐Ÿ“ Slide 12 โ€“ ๐Ÿงพ STRIDE Letters in Practice (Setup) +- ๐Ÿ“ Slide 13 โ€“ ๐Ÿงพ R = Repudiation +- ๐Ÿ“ Slide 14 โ€“ ๐Ÿ” I = Information Disclosure +- ๐Ÿ“ Slide 15 โ€“ ๐Ÿ›‘ D = Denial of Service (DoS) +- ๐Ÿ“ Slide 16 โ€“ ๐Ÿงฐ E = Elevation of Privilege (EoP) +- ๐Ÿ“ Slide 17 โ€“ ๐Ÿ•ต๏ธโ€โ™€๏ธ LINDDUN Overview +- ๐Ÿ“ Slide 18 โ€“ ๐Ÿ“š LINDDUN Methods & Aids +- ๐Ÿ“ Slide 19 โ€“ ๐Ÿงช LINDDUN Use Cases +- ๐Ÿ“ Slide 20 โ€“ ๐Ÿ›๏ธ PASTA Overview +- ๐Ÿ“ Slide 21 โ€“ ๐Ÿงช PASTA 7 Stages in Detail +- ๐Ÿ“ Slide 22 โ€“ ๐Ÿ“Š PASTA Case Study +- ๐Ÿ“ Slide 23 โ€“ ๐Ÿš€ VAST Overview +- ๐Ÿ“ Slide 24 โ€“ ๐Ÿ”Œ VAST Integrations & Use Cases +- ๐Ÿ“ Slide 25 โ€“ ๐Ÿ’น FAIR Overview +- ๐Ÿ“ Slide 26 โ€“ ๐Ÿงฎ FAIR in Practice +- ๐Ÿ“ Slide 27 โ€“ ๐Ÿงฑ Threagile Overview +- ๐Ÿ“ Slide 28 โ€“ ๐Ÿงฐ Threagile Workflow & Use Cases +- ๐Ÿ“ Slide 29 โ€“ ๐Ÿ‰ OWASP Threat Dragon Overview +- ๐Ÿ“ Slide 30 โ€“ ๐Ÿงช Threat Dragon Workflow & Use Cases + +
+ +
+๐Ÿ“Œ Lecture 3 - Secure Git & Secrets Management (40 slides) + +- ๐Ÿ“ Slide 1 โ€“ ๐ŸŒ Brief History of Git +- ๐Ÿ“ Slide 2 โ€“ ๐Ÿ” Why Git Security is Important +- ๐Ÿ“ Slide 3 โ€“ ๐Ÿ—ƒ๏ธ Version Control System (VCS) Basics Recap +- ๐Ÿ“ Slide 4 โ€“ ๐Ÿšจ Common Git-Related Security Incidents +- ๐Ÿ“ Slide 5 โ€“ ๐Ÿงพ Commit Identity Basics +- ๐Ÿ“ Slide 6 โ€“ ๐Ÿ–Š๏ธ Signed Commits Explained +- ๐Ÿ“ Slide 7 โ€“ ๐Ÿ”‘ PGP/GPG Keys in Git +- ๐Ÿ“ Slide 8 โ€“ ๐Ÿชช SSH Signing of Commits +- ๐Ÿ“ Slide 9 โ€“ ๐Ÿ›ก๏ธ Verification of Commits in Platforms +- ๐Ÿ“ Slide 10 โ€“ โš–๏ธ GPG vs SSH Commit Signing +- ๐Ÿ“ Slide 11 โ€“ ๐Ÿข Organizational Enforcement of Signed Commits +- ๐Ÿ“ Slide 12 โ€“ โŒ What Are โ€œSecretsโ€? +- ๐Ÿ“ Slide 13 โ€“ ๐Ÿ”“ How Secrets Leak into Git Repositories +- ๐Ÿ“ Slide 14 โ€“ ๐Ÿ“‚ Examples of Leaked Secrets in Public Repos +- ๐Ÿ“ Slide 15 โ€“ ๐Ÿ“‰ Impact of Secret Leaks +- ๐Ÿ“ Slide 16 โ€“ โš ๏ธ Why Deleting from Git History Is Not Enough +- ๐Ÿ“ Slide 17 โ€“ ๐Ÿ” Manual vs Automated Secret Scanning +- ๐Ÿ“ Slide 18 โ€“ ๐Ÿ› ๏ธ GitGuardian for Secret Scanning +- ๐Ÿ“ Slide 19 โ€“ ๐Ÿ› ๏ธ TruffleHog for Secret Scanning +- ๐Ÿ“ Slide 20 โ€“ ๐Ÿ› ๏ธ Gitleaks for Secret Scanning +- ๐Ÿ“ Slide 21 โ€“ ๐Ÿ“ฆ Built-in Scanners in Git Platforms +- ๐Ÿ“ Slide 22 โ€“ ๐Ÿ“Š Stats & Trends of Secret Leaks +- ๐Ÿ“ Slide 23 โ€“ ๐Ÿงฐ History of Secret Storage +- ๐Ÿ“ Slide 24 โ€“ ๐Ÿ”‘ Environment Variables for Secrets +- ๐Ÿ“ Slide 25 โ€“ ๐Ÿ“œ Config Files & .gitignore +- ๐Ÿ“ Slide 26 โ€“ ๐Ÿ›ก๏ธ Secrets Vaulting Tools Overview +- ๐Ÿ“ Slide 27 โ€“ โšก Secret Rotation & Lifecycle Management +- ๐Ÿ“ Slide 28 โ€“ ๐Ÿงฉ Integrating Vaults with CI/CD Pipelines +- ๐Ÿ“ Slide 29 โ€“ ๐Ÿ”„ Dynamic vs Static Secrets +- ๐Ÿ“ Slide 30 โ€“ ๐Ÿงน Cleaning Git History of Secrets +- ๐Ÿ“ Slide 31 โ€“ ๐Ÿšฆ Pre-Commit Hooks for Preventing Leaks +- ๐Ÿ“ Slide 32 โ€“ ๐Ÿ› ๏ธ Secrets Scanning in CI/CD Pipelines +- ๐Ÿ“ Slide 33 โ€“ ๐Ÿ•ธ๏ธ Zero-Trust Approach to Git Security +- ๐Ÿ“ Slide 34 โ€“ ๐ŸŒ Emerging Trends: P2P & Blockchain Git +- ๐Ÿ“ Slide 35 โ€“ ๐Ÿ”ฎ Future of Git Security & Secret Management +- ๐Ÿ“ Slide 36 โ€“ ๐Ÿข Case Study: GitHub Token Leaks +- ๐Ÿ“ Slide 37 โ€“ ๐Ÿšจ Case Study: Supply-Chain Attacks via Repos +- ๐Ÿ“ Slide 38 โ€“ ๐Ÿ“˜ Industry Standards & Compliance Requirements +- ๐Ÿ“ Slide 39 โ€“ ๐Ÿ“ Best Practices Checklist for Developers +- ๐Ÿ“ Slide 40 โ€“ ๐ŸŽฏ Summary & Hands-On Practice + +
+ +
+๐Ÿ“Œ Lecture 4 - CI/CD Security & Build Hardening (40 slides) + +- ๐Ÿ“ Slide 1 โ€“ ๐Ÿ—๏ธ What is CI/CD? (Continuous Integration/Continuous Deployment) +- ๐Ÿ“ Slide 2 โ€“ ๐Ÿ”„ Evolution of CI/CD: From Manual Builds to Modern Pipelines +- ๐Ÿ“ Slide 3 โ€“ ๐Ÿ›๏ธ CI/CD Architecture Components & Trust Boundaries +- ๐Ÿ“ Slide 4 โ€“ โš™๏ธ Popular CI/CD Platforms Overview (Jenkins, GitHub Actions, GitLab CI, Azure DevOps) +- ๐Ÿ“ Slide 5 โ€“ ๐Ÿšจ Why CI/CD Pipelines Became High-Value Attack Targets +- ๐Ÿ“ Slide 6 โ€“ ๐Ÿ“Š The OWASP Top 10 CI/CD Security Risks (2024) +- ๐Ÿ“ Slide 7 โ€“ ๐Ÿ”— Supply Chain Attacks via CI/CD: Famous Case Studies +- ๐Ÿ“ Slide 8 โ€“ ๐Ÿ” Authentication & Authorization in CI/CD Pipelines +- ๐Ÿ“ Slide 9 โ€“ ๐ŸŽญ Role-Based Access Control (RBAC) for Pipeline Resources +- ๐Ÿ“ Slide 10 โ€“ ๐Ÿ”‘ Service Account Security & Credential Management +- ๐Ÿ“ Slide 11 โ€“ ๐Ÿ›ก๏ธ Multi-Factor Authentication (MFA) for Pipeline Access +- ๐Ÿ“ Slide 12 โ€“ โš–๏ธ Principle of Least Privilege in CI/CD Workflows +- ๐Ÿ“ Slide 13 โ€“ ๐Ÿ•ธ๏ธ Zero-Trust Approaches to Pipeline Security +- ๐Ÿ“ Slide 14 โ€“ ๐Ÿ“‹ Infrastructure-as-Code (IaC) for Pipeline Configuration +- ๐Ÿ“ Slide 15 โ€“ ๐Ÿ”’ Securing Pipeline Configuration Files (YAML/JSON Security) +- ๐Ÿ“ Slide 16 โ€“ ๐Ÿฐ Build Environment Isolation & Sandboxing +- ๐Ÿ“ Slide 17 โ€“ ๐Ÿšซ Preventing Poisoned Pipeline Execution (PPE) Attacks +- ๐Ÿ“ Slide 18 โ€“ ๐ŸŒ Network Segmentation for CI/CD Infrastructure +- ๐Ÿ“ Slide 19 โ€“ ๐Ÿ“‚ Secure Artifact Storage & Repository Management +- ๐Ÿ“ Slide 20 โ€“ ๐Ÿงน Container Security in Build Environments +- ๐Ÿ“ Slide 21 โ€“ โฑ๏ธ Resource Limits & Denial of Service Prevention +- ๐Ÿ“ Slide 22 โ€“ ๐Ÿ“ฆ Secure Artifact Creation & Packaging +- ๐Ÿ“ Slide 23 โ€“ ๐Ÿ” Digital Signing & Verification of Build Artifacts +- ๐Ÿ“ Slide 24 โ€“ ๐Ÿ“‹ Software Bill of Materials (SBOM) Generation +- ๐Ÿ“ Slide 25 โ€“ ๐Ÿท๏ธ Container Image Signing with Cosign/Notary +- ๐Ÿ“ Slide 26 โ€“ ๐Ÿงช Build Reproducibility & Deterministic Builds +- ๐Ÿ“ Slide 27 โ€“ ๐Ÿ” Integrity Checks: Checksums, Hashes, and Verification +- ๐Ÿ“ Slide 28 โ€“ ๐Ÿ“Š Artifact Provenance & Supply Chain Transparency +- ๐Ÿ“ Slide 29 โ€“ ๐Ÿšฆ Quality Gates: Definition and Implementation +- ๐Ÿ“ Slide 30 โ€“ ๐Ÿ”’ Security Gates vs. Quality Gates in CI/CD +- ๐Ÿ“ Slide 31 โ€“ โšก Automated Security Controls in Pipelines +- ๐Ÿ“ Slide 32 โ€“ ๐Ÿ“ˆ Policy-as-Code for Build Security +- ๐Ÿ“ Slide 33 โ€“ ๐Ÿ›‘ Breaking Builds on Security Policy Violations +- ๐Ÿ“ Slide 34 โ€“ ๐Ÿ“Š Security Metrics & KPIs for Pipeline Health +- ๐Ÿ“ Slide 35 โ€“ ๐Ÿ“š Third-Party Dependency Security Risks +- ๐Ÿ“ Slide 36 โ€“ ๐Ÿ” Software Composition Analysis (SCA) in Build Pipelines +- ๐Ÿ“ Slide 37 โ€“ โš ๏ธ Vulnerability Scanning of Dependencies +- ๐Ÿ“ Slide 38 โ€“ ๐Ÿ“‹ License Compliance Scanning & Management +- ๐Ÿ“ Slide 39 โ€“ ๐Ÿ”„ Automated Dependency Updates & Patch Management +- ๐Ÿ“ Slide 40 โ€“ ๐Ÿ•ธ๏ธ Dependency Confusion & Typosquatting Prevention + +
+ +
+๐Ÿ“Œ Lecture 5 - Application Security Testing Basics (26 slides) + +- ๐Ÿ“ Slide 1 โ€“ ๐Ÿ” What is Application Security Testing? (AST Overview) +- ๐Ÿ“ Slide 2 โ€“ ๐Ÿ“ˆ Evolution of Application Security Testing +- ๐Ÿ“ Slide 3 โ€“ ๐ŸŽฏ Types of Security Vulnerabilities We're Testing For +- ๐Ÿ“ Slide 4 โ€“ โš–๏ธ Static vs. Dynamic vs. Interactive Testing Comparison +- ๐Ÿ“ Slide 5 โ€“ ๐Ÿงฉ The Testing Pyramid for Application Security +- ๐Ÿ“ Slide 6 โ€“ ๐Ÿ”ฌ Deep Dive into SAST: Definition and Core Concepts +- ๐Ÿ“ Slide 7 โ€“ ๐Ÿ› ๏ธ Popular SAST Tools and Platform Overview +- ๐Ÿ“ Slide 8 โ€“ โšก SAST Strengths and Limitations +- ๐Ÿ“ Slide 9 โ€“ ๐ŸŽฏ SAST Implementation Best Practices +- ๐Ÿ“ Slide 10 โ€“ ๐Ÿ”ง Hands-on SAST: Tool Configuration and Output Analysis +- ๐Ÿ“ Slide 11 โ€“ ๐ŸŒ Deep Dive into DAST: Black-box Runtime Testing +- ๐Ÿ“ Slide 12 โ€“ ๐Ÿ› ๏ธ Popular DAST Tools and Platform Overview +- ๐Ÿ“ Slide 13 โ€“ โšก DAST Strengths and Limitations +- ๐Ÿ“ Slide 14 โ€“ ๐ŸŽฏ DAST Implementation Best Practices +- ๐Ÿ“ Slide 15 โ€“ ๐Ÿ”ง Hands-on DAST: OWASP ZAP Configuration and Testing +- ๐Ÿ“ Slide 16 โ€“ ๐Ÿงฌ Deep Dive into IAST: Runtime Instrumentation Testing +- ๐Ÿ“ Slide 17 โ€“ ๐Ÿ› ๏ธ Popular IAST Tools and Platform Overview +- ๐Ÿ“ Slide 18 โ€“ โšก IAST Strengths and Limitations +- ๐Ÿ“ Slide 19 โ€“ ๐ŸŽฏ IAST Implementation Best Practices +- ๐Ÿ“ Slide 20 โ€“ ๐Ÿ”ง Hands-on IAST: Agent-based Testing Setup +- ๐Ÿ“ Slide 21 โ€“ ๐Ÿš€ Integrating Security Testing into CI/CD Pipelines +- ๐Ÿ“ Slide 22 โ€“ ๐Ÿ“Š Tool Orchestration and Security Dashboard Creation +- ๐Ÿ“ Slide 23 โ€“ โš–๏ธ Balancing Security and Development Velocity +- ๐Ÿ“ Slide 24 โ€“ ๐Ÿ”„ Advanced Integration Patterns and GitOps +- ๐Ÿ“ Slide 25 โ€“ ๐ŸŒŸ Modern Trends and Future of Application Security Testing +- ๐Ÿ“ Slide 26 โ€“ ๐ŸŽฏ Summary & Key Takeaways + +
+ +
+๐Ÿ“Œ Lecture 6 - Infrastructure-as-Code Security (19 slides) + +- ๐Ÿ“ Slide 1 โ€“ ๐ŸŒ What is Infrastructure-as-Code (IaC)? +- ๐Ÿ“ Slide 2 โ€“ ๐Ÿšจ Why IaC Security Matters +- ๐Ÿ“ Slide 3 โ€“ ๐Ÿ“Š IaC Tool Landscape Overview +- ๐Ÿ“ Slide 4 โ€“ ๐Ÿ”’ Common IaC Security Risks +- ๐Ÿ“ Slide 5 โ€“ ๐Ÿงญ IaC in the DevSecOps Pipeline +- ๐Ÿ“ Slide 6 โ€“ ๐Ÿ—๏ธ Terraform Deep Dive & Security Concerns +- ๐Ÿ“ Slide 7 โ€“ ๐Ÿ”‘ Managing Secrets in Terraform +- ๐Ÿ“ Slide 8 โ€“ ๐Ÿ›ก๏ธ Terraform Security Best Practices +- ๐Ÿ“ Slide 9 โ€“ ๐Ÿ’ป Hands-On: Secure Terraform Workflow +- ๐Ÿ“ Slide 10 โ€“ ๐Ÿš€ Pulumi Overview & Security Model +- ๐Ÿ“ Slide 11 โ€“ ๐Ÿงฉ Pulumi Policy-as-Code (CrossGuard) +- ๐Ÿ“ Slide 12 โ€“ ๐Ÿ’ป Hands-On: Secure Pulumi Deployment +- ๐Ÿ“ Slide 13 โ€“ โš™๏ธ Ansible Overview & Security Challenges +- ๐Ÿ“ Slide 14 โ€“ ๐Ÿ›ก๏ธ Ansible Security Best Practices +- ๐Ÿ“ Slide 15 โ€“ ๐Ÿ’ป Hands-On: Secure Ansible Playbook +- ๐Ÿ“ Slide 16 โ€“ ๐Ÿ” IaC Security Scanning Tools Deep Dive +- ๐Ÿ“ Slide 17 โ€“ ๐Ÿ“‹ Policy-as-Code Frameworks +- ๐Ÿ“ Slide 18 โ€“ โ˜๏ธ Compliance & Security Standards +- ๐Ÿ“ Slide 19 โ€“ ๐ŸŽฏ Case Studies, Future Trends & Summary + +
+ +
+๐Ÿ“Œ Lecture 7 - Container & Kubernetes Security (18 slides) + +- ๐Ÿ“ Slide 1 โ€“ ๐Ÿณ Container Technology Overview & Evolution +- ๐Ÿ“ Slide 2 โ€“ ๐Ÿ—๏ธ Docker Architecture & Security Model +- ๐Ÿ“ Slide 3 โ€“ ๐Ÿ“ฆ Container Images & Layered Filesystem +- ๐Ÿ“ Slide 4 โ€“ ๐Ÿ” Container Image Security Scanning +- ๐Ÿ“ Slide 5 โ€“ ๐Ÿ›ก๏ธ Container Runtime Security +- ๐Ÿ“ Slide 6 โ€“ ๐Ÿ” Secrets Management in Containers +- ๐Ÿ“ Slide 7 โ€“ ๐Ÿ“‹ Container Compliance & Hardening +- ๐Ÿ“ Slide 8 โ€“ โ˜ธ๏ธ Kubernetes Architecture & Components +- ๐Ÿ“ Slide 9 โ€“ ๐Ÿ”‘ Kubernetes Authentication & Authorization +- ๐Ÿ“ Slide 10 โ€“ ๐Ÿšช Kubernetes Admission Control & Policies +- ๐Ÿ“ Slide 11 โ€“ ๐Ÿ›ก๏ธ Pod Security & Isolation +- ๐Ÿ“ Slide 12 โ€“ ๐Ÿ”’ Kubernetes Secrets & ConfigMaps +- ๐Ÿ“ Slide 13 โ€“ ๐Ÿ“Š Kubernetes Auditing & Monitoring +- ๐Ÿ“ Slide 14 โ€“ ๐Ÿ” Kubernetes Security Scanning +- ๐Ÿ“ Slide 15 โ€“ ๐ŸŒ Kubernetes Network Security +- ๐Ÿ“ Slide 16 โ€“ ๐Ÿ—๏ธ Secure Kubernetes CI/CD Pipelines +- ๐Ÿ“ Slide 17 โ€“ ๐Ÿšจ Kubernetes Attack Scenarios & Defense +- ๐Ÿ“ Slide 18 โ€“ ๐Ÿ”ฎ Future Trends & Security Checklist + +
+ +
+๐Ÿ“Œ Lecture 8 - Software Supply Chain Security (20 slides) + +- ๐Ÿ“ Slide 1 โ€“ ๐Ÿ”— What is Software Supply Chain Security? +- ๐Ÿ“ Slide 2 โ€“ ๐Ÿ’ฅ Famous Supply Chain Breaches & Incidents +- ๐Ÿ“ Slide 3 โ€“ ๐ŸŽฏ Supply Chain Attack Vectors +- ๐Ÿ“ Slide 4 โ€“ ๐Ÿ›ก๏ธ Supply Chain Security Frameworks +- ๐Ÿ“ Slide 5 โ€“ ๐Ÿ“Š Supply Chain Security in DevSecOps Pipeline +- ๐Ÿ“ Slide 6 โ€“ ๐Ÿ” Software Composition Analysis (SCA) Deep Dive +- ๐Ÿ“ Slide 7 โ€“ ๐Ÿ—‚๏ธ Vulnerability Databases & Tracking +- ๐Ÿ“ Slide 8 โ€“ ๐Ÿ› ๏ธ Dependency Management Best Practices +- ๐Ÿ“ Slide 9 โ€“ ๐Ÿ’ป Hands-On: Advanced SCA Tools +- ๐Ÿ“ Slide 10 โ€“ ๐Ÿ“‹ SBOM Formats: SPDX vs CycloneDX Deep Dive +- ๐Ÿ“ Slide 11 โ€“ ๐Ÿ”Ž SBOM Consumption & Auditing +- ๐Ÿ“ Slide 12 โ€“ ๐Ÿ“Š SBOM Diff Analysis & Change Tracking +- ๐Ÿ“ Slide 13 โ€“ ๐Ÿ’ป Hands-On: SBOM-Driven Vulnerability Analysis +- ๐Ÿ“ Slide 14 โ€“ โœ๏ธ Code Signing & Artifact Integrity +- ๐Ÿ“ Slide 15 โ€“ ๐Ÿ” Sigstore: Modern Signing Revolution +- ๐Ÿ“ Slide 16 โ€“ ๐Ÿ“œ Provenance & Build Attestations +- ๐Ÿ“ Slide 17 โ€“ ๐Ÿ’ป Hands-On: Signing & Provenance Verification +- ๐Ÿ“ Slide 18 โ€“ ๐ŸŽฏ SLSA Framework Implementation +- ๐Ÿ“ Slide 19 โ€“ ๐Ÿ”’ Securing the Build Pipeline +- ๐Ÿ“ Slide 20 โ€“ ๐Ÿš€ Runtime Supply Chain Security + +
+ +
+๐Ÿ“Œ Lecture 9 - Monitoring, Compliance & Improvement (23 slides) + +- ๐Ÿ“ Slide 1 โ€“ ๐Ÿ“Š Security Monitoring in DevSecOps +- ๐Ÿ“ Slide 2 โ€“ ๐Ÿ” What to Monitor: Logs, Metrics, Traces +- ๐Ÿ“ Slide 3 โ€“ ๐Ÿ› ๏ธ Security Monitoring Tools & Platforms +- ๐Ÿ“ Slide 4 โ€“ ๐Ÿ“ˆ Security Metrics vs Vanity Metrics +- ๐Ÿ“ Slide 5 โ€“ โฑ๏ธ Time-Based KPIs: MTTD, MTTR, MTTA +- ๐Ÿ“ Slide 6 โ€“ ๐Ÿ“Š Program Health KPIs +- ๐Ÿ“ Slide 7 โ€“ ๐Ÿ’ป Hands-On: Building Security Dashboards +- ๐Ÿ“ Slide 8 โ€“ โš–๏ธ Compliance Basics for Developers +- ๐Ÿ“ Slide 9 โ€“ ๐Ÿ‡ช๐Ÿ‡บ GDPR Essentials +- ๐Ÿ“ Slide 10 โ€“ ๐Ÿ›๏ธ NIST Cybersecurity Framework +- ๐Ÿ“ Slide 11 โ€“ ๐ŸŒ ISO 27001 Basics +- ๐Ÿ“ Slide 12 โ€“ ๐Ÿ’ณ Other Key Frameworks (Quick Overview) +- ๐Ÿ“ Slide 8 โ€“ โš–๏ธ Compliance Basics for Developers +- ๐Ÿ“ Slide 9 โ€“ ๐Ÿ‡ช๐Ÿ‡บ GDPR (General Data Protection Regulation) +- ๐Ÿ“ Slide 10 โ€“ ๐Ÿ›๏ธ NIST Cybersecurity Framework +- ๐Ÿ“ Slide 11 โ€“ ๐ŸŒ ISO 27001 Information Security Management +- ๐Ÿ“ Slide 12 โ€“ ๐Ÿ’ณ Other Key Frameworks (Overview) +- ๐Ÿ“ Slide 13 โ€“ ๐ŸŽฏ Security Maturity Model Concepts +- ๐Ÿ“ Slide 14 โ€“ ๐Ÿฆ… OWASP SAMM (Software Assurance Maturity Model) +- ๐Ÿ“ Slide 15 โ€“ ๐Ÿ“Š BSIMM (Building Security In Maturity Model) +- ๐Ÿ“ Slide 16 โ€“ ๐Ÿš€ DevSecOps Maturity Assessment +- ๐Ÿ“ Slide 17 โ€“ ๐Ÿ”„ Feedback Loops & Security Improvement +- ๐Ÿ“ Slide 18 โ€“ ๐Ÿค– Compliance as Code & Automation + +
+ +
+๐Ÿ“Œ Lecture 10 - Vulnerability Management & Response (17 slides) + +- ๐Ÿ“ Slide 1 โ€“ ๐Ÿ” Vulnerability Discovery Methods +- ๐Ÿ“ Slide 2 โ€“ ๐Ÿ› ๏ธ Security Testing Orchestration +- ๐Ÿ“ Slide 3 โ€“ ๐Ÿ“Š Centralized Vulnerability Management +- ๐Ÿ“ Slide 4 โ€“ ๐Ÿ“Š CVSS Scoring Deep Dive +- ๐Ÿ“ Slide 5 โ€“ โšก Advanced Prioritization: EPSS, KEV, SSVC +- ๐Ÿ“ Slide 6 โ€“ ๐ŸŽฏ Risk-Based Prioritization +- ๐Ÿ“ Slide 7 โ€“ ๐Ÿšจ Triage Workflows & Decisions +- ๐Ÿ“ Slide 8 โ€“ ๐Ÿ”ง Remediation Strategies +- ๐Ÿ“ Slide 9 โ€“ โฑ๏ธ SLA Management & Tracking +- ๐Ÿ“ Slide 10 โ€“ ๐Ÿ”„ Remediation Tracking & Verification +- ๐Ÿ“ Slide 11 โ€“ ๐Ÿ’ป Hands-On: Automated Remediation Pipelines +- ๐Ÿ“ Slide 12 โ€“ ๐Ÿ“Š Vulnerability Lifecycle Overview +- ๐Ÿ“ Slide 13 โ€“ ๐Ÿ“ˆ Backlog Management & Health +- ๐Ÿ“ Slide 14 โ€“ โšก Velocity & Continuous Improvement +- ๐Ÿ“ Slide 15 โ€“ ๐Ÿ”ฅ Incident Response Framework +- ๐Ÿ“ Slide 16 โ€“ ๐Ÿ‘ฅ IR Team Roles & Escalation +- ๐Ÿ“ Slide 17 โ€“ ๐Ÿ“š Blameless Post-Mortems + +
--- -## ๐Ÿ–ผ Module Flow Diagram +## ๐Ÿ—บ๏ธ DevSecOps Learning Journey + +
+๐ŸŒณ View Skill Tree Structure + +```mermaid +graph TB + ROOT[๐Ÿ” DevSecOps Mastery] + + %% Foundation Branch + ROOT --- FOUND[๐Ÿ—๏ธ Foundation] + FOUND --- A[๐Ÿ“š Lab 1: DevSecOps Intro
โ€ข Secure SDLC
โ€ข Shift-Left Culture
โ€ข OWASP Top 10] + FOUND --- B[๐ŸŽฏ Lab 2: Threat Modeling
โ€ข STRIDE Analysis
โ€ข Attack Surfaces
โ€ข Risk Assessment] + + %% Development Branch + ROOT --- DEV[๐Ÿ‘จโ€๐Ÿ’ป Development] + DEV --- C[๐Ÿ” Lab 3: Secure Git
โ€ข Signed Commits
โ€ข Secrets Management
โ€ข Secure Workflows] + DEV --- D[๐Ÿš€ Lab 4: CI/CD Security
โ€ข Secure Pipelines
โ€ข Build Hardening
โ€ข Quality Gates] + + %% Testing Branch + ROOT --- TEST[๐Ÿงช Testing] + TEST --- E[๐Ÿ” Lab 5: AppSec Testing
โ€ข SAST/DAST/SCA
โ€ข Tool Integration
โ€ข Automated Security] + TEST --- J[๐ŸŽฏ Lab 10: Vuln Management
โ€ข Discovery & Triage
โ€ข CVSS Scoring
โ€ข Remediation Workflows] + + %% Infrastructure Branch + ROOT --- INFRA[๐Ÿ—๏ธ Infrastructure] + INFRA --- F[โš™๏ธ Lab 6: IaC Security
โ€ข Terraform/Ansible
โ€ข Config Scanning
โ€ข Policy as Code] + INFRA --- G[๐Ÿ“ฆ Lab 7: Container Security
โ€ข Docker/K8s Security
โ€ข Image Scanning
โ€ข Runtime Protection] + + %% Supply Chain Branch + ROOT --- SUPPLY[๐Ÿ”— Supply Chain] + SUPPLY --- H[๐Ÿ“‹ Lab 8: SBOM & Provenance
โ€ข Dependency Analysis
โ€ข Artifact Signing
โ€ข Supply Chain Security] + + %% Operations Branch + ROOT --- OPS[๐Ÿ“Š Operations] + OPS --- I[๐Ÿ“ˆ Lab 9: Monitoring & Compliance
โ€ข Security Metrics
โ€ข GDPR/NIST/ISO
โ€ข Maturity Models] + + %% Styling + classDef rootStyle fill:#1a1a1a,stroke:#ffffff,stroke-width:3px,color:#ffffff + classDef branchStyle fill:#2c3e50,stroke:#e74c3c,stroke-width:2px,color:#ffffff + classDef foundationModule fill:#fdf2e9,stroke:#e67e22,stroke-width:2px,color:#2c3e50 + classDef devModule fill:#eaf2f8,stroke:#3498db,stroke-width:2px,color:#2c3e50 + classDef testModule fill:#f4ecf7,stroke:#9b59b6,stroke-width:2px,color:#2c3e50 + classDef infraModule fill:#e8f8f5,stroke:#16a085,stroke-width:2px,color:#2c3e50 + classDef supplyModule fill:#fdedec,stroke:#e74c3c,stroke-width:2px,color:#2c3e50 + classDef opsModule fill:#fff3cd,stroke:#f1c40f,stroke-width:2px,color:#2c3e50 + + class ROOT rootStyle + class FOUND,DEV,TEST,INFRA,SUPPLY,OPS branchStyle + class A,B foundationModule + class C,D devModule + class E,J testModule + class F,G infraModule + class H supplyModule + class I opsModule +``` + +
+ +
+๐Ÿ—๏ธ View Security Integration Layers ```mermaid -flowchart TD - A[Foundations & Secure SDLC] --> B[Threat Modeling] - B --> C[Secure Git & Secrets Management] - C --> D[CI/CD Security] - D --> E[AppSec Testing Basics] - E --> F[IaC Security] - F --> G[Containers & K8s Security] - G --> H[Supply Chain & SBOM] - H --> I[Monitoring & Compliance] - I --> J[Vulnerability Management & Testing] +flowchart LR + subgraph "๐Ÿ”— Supply Chain & Operations" + direction LR + H[๐Ÿ“‹ Lab 8: SBOM & Provenance
Dependency Security] + I[๐Ÿ“ˆ Lab 9: Monitoring
Security Metrics] + end + + subgraph "๐Ÿ—๏ธ Infrastructure Security" + direction LR + F[โš™๏ธ Lab 6: IaC Security
Config Management] + G[๐Ÿ“ฆ Lab 7: Container Security
Runtime Protection] + end + + subgraph "๐Ÿงช Security Testing" + direction LR + E[๐Ÿ” Lab 5: AppSec Testing
SAST/DAST/SCA] + J[๐ŸŽฏ Lab 10: Vuln Management
Remediation Workflows] + end + + subgraph "๐Ÿ‘จโ€๐Ÿ’ป Secure Development" + direction LR + C[๐Ÿ” Lab 3: Secure Git
Secrets & Signing] + D[๐Ÿš€ Lab 4: CI/CD Security
Pipeline Hardening] + end + + subgraph "๐Ÿ—๏ธ Foundation Layer" + direction LR + A[๐Ÿ“š Lab 1: DevSecOps
Principles & SDLC] + B[๐ŸŽฏ Lab 2: Threat Modeling
Risk Analysis] + end + + A --> C + B --> C + C --> E + D --> E + D --> F + E --> F + F --> G + G --> H + H --> I + E --> J + J --> I + + classDef foundation fill:#fdf2e9,stroke:#e67e22,stroke-width:3px,color:#2c3e50 + classDef development fill:#eaf2f8,stroke:#3498db,stroke-width:3px,color:#2c3e50 + classDef testing fill:#f4ecf7,stroke:#9b59b6,stroke-width:3px,color:#2c3e50 + classDef infrastructure fill:#e8f8f5,stroke:#16a085,stroke-width:3px,color:#2c3e50 + classDef operations fill:#fdedec,stroke:#e74c3c,stroke-width:3px,color:#2c3e50 + + class A,B foundation + class C,D development + class E,J testing + class F,G infrastructure + class H,I operations ``` +
+ --- ## ๐Ÿ›  Lab-Based Learning Experience -**80% of your grade comes from hands-on labs** โ€” each one builds practical security skills: +**80% of your grade comes from 10 hands-on labs** โ€” each designed to build real-world security skills. + +### Lab Structure + +* **Task-oriented security challenges** with clear objectives and deliverables +* **Safe environments** using containers, local VMs, or cloud platforms +* **Real-world workflows** mirroring professional DevSecOps practices +* **Progressive difficulty** building on previous security concepts +* **Industry-standard tools** used in production environments + +### Lab Overview + +
+๐Ÿ“‹ View All Lab Topics + +**Required Labs (1-10):** + +1. **Foundations & Secure SDLC** โ€” DevSecOps principles, OWASP Top 10, shift-left security +2. **Threat Modeling** โ€” STRIDE analysis, attack surface mapping, risk assessment +3. **Secure Git** โ€” Signed commits, secret scanning, secure collaboration workflows +4. **CI/CD Security** โ€” Pipeline hardening, artifact integrity, quality gates, SBOM +5. **AppSec Testing** โ€” SAST/DAST/SCA integration, automated security testing +6. **IaC Security** โ€” Terraform/Pulumi/Ansible scanning, policy-as-code enforcement +7. **Container Security** โ€” Docker/Kubernetes hardening, image scanning, runtime protection +8. **Supply Chain** โ€” SBOM generation, dependency analysis, artifact signing +9. **Monitoring & Compliance** โ€” Security metrics, GDPR/NIST/ISO basics, maturity assessment +10. **Vulnerability Management** โ€” Discovery, triage, remediation, CVSS scoring + +**Bonus Labs (Optional):** + +11. **๐ŸŽ Nginx Reverse Proxy Hardening** โ€” Security headers (XFO, XCTO, HSTS, CSP), TLS configuration, rate limiting, timeout management +12. **๐ŸŽ Kata Containers Sandboxing** โ€” VM-backed isolation, runtime comparison (runc vs kata), performance analysis, security tradeoffs + +> **Bonus Lab Benefits:** +> - Extra credit toward final grade +> - Advanced security hardening techniques +> - Real-world operational security skills +> - Optional but highly recommended for security professionals + +
+ +### Submission Workflow + +```mermaid +graph LR + A[Fork Repo] --> B[Create Branch] + B --> C[Complete Tasks] + C --> D[Push to Fork] + D --> E[Open PR to Course Repo] + E --> F[Submit PR Link via Moodle] + F --> G[Receive Feedback] + + style A fill:#e8f8f5,stroke:#16a085,color:#2c3e50 + style B fill:#e8f8f5,stroke:#16a085,color:#2c3e50 + style C fill:#fef9e7,stroke:#f39c12,color:#2c3e50 + style D fill:#eaf2f8,stroke:#3498db,color:#2c3e50 + style E fill:#f4ecf7,stroke:#9b59b6,color:#2c3e50 + style F fill:#fdedec,stroke:#e74c3c,color:#2c3e50 + style G fill:#e8f6f3,stroke:#1abc9c,color:#2c3e50 +``` + +
+๐Ÿ“‹ Detailed Submission Process + +**Step-by-Step Guide:** + +1. **Fork the course repository** to your GitHub account + +2. **Clone your fork locally:** + ```bash + git clone https://github.com/YOUR_USERNAME/REPO_NAME.git + cd REPO_NAME + ``` + +3. **Create and work on your lab branch:** + ```bash + git switch -c feature/labX + # Complete lab tasks, create submission files + git add labs/submissionX.md + git commit -m "docs: add labX submission" + git push -u origin feature/labX + ``` + +4. **Open PR from your fork โ†’ course repository main branch** + - Navigate to the course repository on GitHub + - Click "New Pull Request" + - Select: `base: course-repo/main` โ† `compare: your-fork/feature/labX` + - Fill in the PR template with task completion checklist + +5. **Copy the PR URL and submit via Moodle before deadline** + +**โš ๏ธ Important:** PRs must target the **course repository's main branch**, not your fork's main branch. + +
+ +### Grading Policy + +
+๐ŸŽฏ Lab Grading Breakdown + +**Each lab (1-10) is worth 8 points:** + +* **Perfect Submissions (8/8):** + - All tasks completed with thorough security analysis + - Clear documentation and understanding demonstrated + - Security tools configured and used correctly + - Submitted on time + - **Benefit:** Counts toward exam exemption + +* **Strong Submissions (6-7/8):** + - All tasks completed with minor issues + - Good security analysis and documentation + - Minor improvements needed + +* **Passing Submissions (5-6/8):** + - Core security tasks completed + - Basic documentation present + - Some areas need improvement + +* **Below Passing (<5/8):** + - Incomplete security analysis + - Insufficient documentation + - Major gaps in understanding -1. **Lab Structure** +**Bonus Labs (11-12):** +- Worth **10 points each** +- **Maximum 20 bonus points total** (capped to maintain grade scale) +- **Can replace the exam requirement** if both completed +- Same quality standards as required labs +- No penalty for not completing them - * Realistic, task-oriented challenges with clear goals - * Safe environments using containers, local VMs, or cloud credits +**Late Submissions (Required Labs Only):** +- Maximum score: 5/8 +- Accepted within 1 week after deadline +- No credit after 1 week -2. **Submission Workflow** +
- * Fork course repository โ†’ Create lab branch โ†’ Complete tasks - * Push to fork โ†’ Open Pull Request โ†’ Receive feedback & evaluation +
+๐Ÿ† Exam Exemption Policy -3. **Grading Advantage** +**Path 1: Bonus Labs Replace Exam** - * **Perfect Labs (10/10)**: Exam exemption + bonus points toward A - * **On-Time (โ‰ฅ6/10)**: Guaranteed pass (C or higher) - * **Late**: Maximum 6/10 +Complete **both Lab 11 AND Lab 12** with passing scores: +- No exam requirement +- Bonus points replace the 20 exam points +- Must still complete all 10 required labs + +**Path 2: Maximum Score Strategy** + +Combine all components: +- Complete 10 required labs (80 pts) +- Take exam (20 pts) +- Complete bonus labs (20 pts) +- Total: 120 pts available (capped at 100 for final grade) + +**Important Notes:** +- **Completing only 10 labs = 80% maximum** (B grade) +- Need exam OR bonus labs to reach A grade +- Bonus labs provide safety buffer for required lab scores +- Late required lab submissions max out at 5/8 points + +
--- ## ๐Ÿ“Š Evaluation Framework -*Transparent assessment for skill validation* - ### Grade Composition -* Labs (10 ร— 8 points each): **80%** -* Final Exam (comprehensive): **20%** +| Component | Points | Details | +|-----------|--------|---------| +| **Required Labs (1-10)** | 80 points | 10 labs ร— 8 points each (80% of grade) | +| **Final Exam** | 20 points | Comprehensive assessment OR skip if both bonus labs completed | +| **Bonus Labs (11-12)** | +20 points max | Lab 11: 10 pts, Lab 12: 10 pts (capped at 20 total) | +| **Total Base** | 100 points | Required to pass: 60+ points | +| **Maximum Possible** | 120 points | With bonus labs (capped at 100% for final grade) | ### Performance Tiers -* **A (90-100)**: Mastery with innovative solutions -* **B (75-89)**: Consistent completion, minor improvement needed -* **C (60-74)**: Basic competency, some gaps -* **D (0-59)**: Fundamental gaps, re-attempt required +
+๐Ÿ“ˆ Grading Scale + +| Grade | Range | Description | +|-------|---------|-----------------------------------------------------------------------------| +| **A** | 90-100 | Mastery of security concepts, innovative solutions, exceptional analysis | +| **B** | 75-89 | Consistent completion, solid security understanding, minor improvements | +| **C** | 60-74 | Basic security competency demonstrated, needs reinforcement | +| **D** | 0-59 | Fundamental security gaps, re-attempt required | + +**Grade Calculation Examples:** + +**Scenario 1: Standard Path (Labs + Exam)** +``` +Required Labs: 70/80 points (8 labs at 8pts, 2 at 5pts) +Exam: 18/20 points +Total: 88/100 = B+ +``` + +**Scenario 2: Labs Only (80% Maximum)** +``` +Required Labs: 80/80 points (perfect scores) +No Exam: 0/20 points +Total: 80/100 = B (cannot exceed 80% without exam/bonus) +``` + +**Scenario 3: Labs + Bonus (No Exam)** +``` +Required Labs: 72/80 points +Bonus Lab 11: 10/10 points +Bonus Lab 12: 10/10 points +Total: 92/100 = A (bonus labs replace exam) +``` + +**Scenario 4: Maximum Score** +``` +Required Labs: 80/80 points +Exam: 20/20 points +Bonus Labs: 20/20 points +Total: 120 points โ†’ capped at 100/100 = A+ with buffer +``` + +
--- ## โœ… Success Path -> *"Complete all labs with โ‰ฅ6/10 to pass. Perfect lab submissions grant exam exemption and bonus points toward an A."* +> **"Complete all 10 required labs to earn 80%. Add exam (20%) OR both bonus labs (20%) to reach higher grades. Maximum 120 points available, capped at 100% for final grade."** + +
+๐Ÿ’ก Tips for Success + +**Lab Completion Strategy:** +1. Start each lab early - security analysis takes time +2. Read instructions thoroughly before beginning +3. Test all security tools and configurations +4. Document findings with screenshots and explanations +5. Review vulnerability reports carefully + +**Security-Specific Tips:** +1. **Understand the "Why"** - Don't just run tools, understand what they detect +2. **Analyze Results** - Explain security implications, not just tool outputs +3. **Think Like an Attacker** - Consider how vulnerabilities could be exploited +4. **Prioritize Findings** - Use CVSS scores and risk assessment +5. **Remediate Properly** - Provide secure alternatives, not just "fix this" + +**Documentation Best Practices:** +1. Use clear Markdown formatting with security-focused headers +2. Include both tool outputs AND your security analysis +3. Explain attack vectors and business impact +4. Screenshot critical vulnerabilities with annotations +5. Organize findings by severity (Critical, High, Medium, Low) + +**Git Workflow:** +1. Always work on feature branches for security labs +2. Use descriptive commit messages (e.g., `security: add SAST scan results`) +3. Push regularly to avoid losing vulnerability reports +4. Open PRs to the course repository, not your fork +5. Review the security checklist before submitting + +**Time Management:** +1. Allocate 4-6 hours per lab (security analysis is thorough) +2. Break labs into: setup, scanning, analysis, documentation +3. Use lab deadlines visible in Moodle +4. Review previous labs before starting new security modules +5. Don't rush vulnerability analysis - accuracy matters + +**Getting Help:** +1. Review lab guidelines and security tool documentation +2. Check OWASP and CWE resources for vulnerability context +3. Discuss security concepts with classmates (collaboration encouraged) +4. Attend office hours with specific security questions +5. Submit questions early - security troubleshooting takes time + +
+ +
+๐Ÿ“… Recommended Study Schedule + +**Per-Lab Pattern:** + +**Days 1-2: Setup & Understanding** +- Attend lecture on security topic +- Review lab requirements and security objectives +- Install and configure security tools +- Read documentation for scanners/analyzers + +**Days 3-5: Execution & Scanning** +- Run security scans and collect results +- Perform vulnerability assessments +- Test security controls +- Capture evidence (screenshots, logs) + +**Day 6: Analysis & Documentation** +- Analyze security findings +- Prioritize vulnerabilities by severity +- Research remediation strategies +- Document security insights + +**Day 7: Review & Submit** +- Proofread security analysis +- Verify all evidence is included +- Review checklist for completeness +- Submit PR via Moodle + +**Before Each Lab:** +1. Review previous security concepts +2. Ensure security tools are updated +3. Read entire lab instructions first +4. Identify prerequisites or installations needed + +**After Each Lab:** +1. Reflect on key security learnings +2. Note security challenges for future reference +3. Review instructor feedback when provided +4. Connect vulnerabilities to real-world incidents + +**Exam Preparation (if needed):** +- Review all lab security findings +- Revisit key vulnerability types +- Practice security tool commands +- Focus on understanding attack vectors, not memorization + +
+ +--- + +## ๐Ÿ“š Additional Resources + +
+๐Ÿ”— Essential Links + +**Course Materials:** +- [Moodle Course Page](https://moodle.innopolis.university/) - Lectures, deadlines, grades +- [Course Repository](https://github.com/your-org/devsecops-course) - Lab assignments and resources + +**DevSecOps Fundamentals:** +- [OWASP DevSecOps Guideline](https://owasp.org/www-project-devsecops-guideline/) +- [NIST Secure Software Development Framework](https://csrc.nist.gov/Projects/ssdf) +- [The DevSecOps Playbook](https://www.redhat.com/en/resources/devsecops-culture-process-and-tools-ebook) + +**Security Standards & Frameworks:** +- [OWASP Top 10](https://owasp.org/www-project-top-ten/) +- [CWE Top 25](https://cwe.mitre.org/top25/) +- [NIST Cybersecurity Framework](https://www.nist.gov/cyberframework) +- [CIS Controls](https://www.cisecurity.org/controls) + +**Application Security Testing:** +- [OWASP Testing Guide](https://owasp.org/www-project-web-security-testing-guide/) +- [SAST vs DAST vs IAST](https://www.synopsys.com/blogs/software-security/sast-vs-dast-difference/) +- [Security Testing in CI/CD](https://owasp.org/www-project-devsecops-guideline/latest/02a-Integrate-Security-into-Development) + +**Infrastructure Security:** +- [Terraform Security Best Practices](https://www.terraform.io/docs/cloud/guides/recommended-practices/index.html) +- [Kubernetes Security Best Practices](https://kubernetes.io/docs/concepts/security/) +- [Docker Security Cheat Sheet](https://cheatsheetseries.owasp.org/cheatsheets/Docker_Security_Cheat_Sheet.html) + +**Vulnerability Management:** +- [CVSS Calculator](https://www.first.org/cvss/calculator/3.1) +- [National Vulnerability Database](https://nvd.nist.gov/) +- [CVE Details](https://www.cvedetails.com/) + +**Supply Chain Security:** +- [SBOM Standards (SPDX/CycloneDX)](https://www.cisa.gov/sbom) +- [SLSA Framework](https://slsa.dev/) +- [Sigstore Documentation](https://docs.sigstore.dev/) + +
+ +
+๐Ÿ› ๏ธ Required Tools & Software + +**Core Tools (Needed for most labs):** +- Git (version control with security features) +- Docker (containerization and security scanning) +- Text editor with Markdown support (VS Code recommended) +- Web browser (Chrome, Firefox) +- Terminal/Command line + +**Security Tools (Install as needed per lab):** +- **Lab 1-2:** OWASP ZAP, threat modeling tools +- **Lab 3:** Git-secrets, Gitleaks, signed commit setup +- **Lab 4:** GitHub Actions, quality gates, SBOM generators +- **Lab 5:** SAST tools (Semgrep, Bandit), DAST tools (ZAP) +- **Lab 6:** Terraform, Checkov, KICS, Terrascan +- **Lab 7:** Docker, Trivy, Snyk, Kubernetes (kind/minikube) +- **Lab 8:** Syft, Grype, Cosign +- **Lab 9:** Prometheus, Grafana, compliance scanners +- **Lab 10:** Vulnerability management platforms + +**Installation Guides:** +- Most security tools run in Docker containers (minimal setup) +- Cloud services use free tiers (no payment required) +- Tool-specific installation instructions provided in each lab + +
+ +
+๐Ÿ“– Learning Resources by Topic + +**Labs 1-2: DevSecOps & Threat Modeling** +- [DevSecOps Manifesto](https://www.devsecops.org/) +- [STRIDE Threat Modeling](https://learn.microsoft.com/en-us/azure/security/develop/threat-modeling-tool-threats) +- [OWASP Threat Modeling](https://owasp.org/www-community/Threat_Modeling) + +**Lab 3: Secure Git** +- [Git Security Best Practices](https://www.git-scm.com/book/en/v2/Git-Tools-Signing-Your-Work) +- [Secrets Management Guide](https://owasp.org/www-project-devsecops-guideline/latest/02c-Secret-Management) +- [GitHub Security Features](https://docs.github.com/en/code-security) + +**Lab 4: CI/CD Security** +- [Secure CI/CD Practices](https://www.cisa.gov/sites/default/files/publications/ESF_SECURING_THE_SOFTWARE_SUPPLY_CHAIN_DEVELOPERS.PDF) +- [GitHub Actions Security](https://docs.github.com/en/actions/security-guides) +- [SBOM Generation Guide](https://www.cisa.gov/sbom) + +**Lab 5: AppSec Testing** +- [OWASP SAMM](https://owaspsamm.org/) +- [Static Analysis Tools List](https://owasp.org/www-community/Source_Code_Analysis_Tools) +- [Dynamic Analysis Guide](https://owasp.org/www-project-web-security-testing-guide/) + +**Lab 6: IaC Security** +- [IaC Security Best Practices](https://owasp.org/www-project-devsecops-guideline/latest/02d-Infrastructure-as-Code-Scanning) +- [KICS Documentation](https://docs.kics.io/) +- [Checkov Documentation](https://www.checkov.io/1.Welcome/Quick%20Start.html) + +**Lab 7: Container Security** +- [Docker Security Best Practices](https://docs.docker.com/develop/security-best-practices/) +- [Kubernetes Security](https://kubernetes.io/docs/concepts/security/overview/) +- [Container Security Guide](https://www.nist.gov/publications/application-container-security-guide) + +**Lab 8: Supply Chain** +- [SLSA Framework](https://slsa.dev/spec/v1.0/) +- [SBOM Tool](https://github.com/kubernetes-sigs/bom) +- [Sigstore Tutorial](https://edu.chainguard.dev/open-source/sigstore/) + +**Lab 9: Monitoring & Compliance** +- [Security Metrics Guide](https://www.sans.org/white-papers/55/) +- [GDPR for Developers](https://www.smashingmagazine.com/2017/07/privacy-by-design-framework/) +- [NIST SP 800-53](https://csrc.nist.gov/publications/detail/sp/800-53/rev-5/final) + +**Lab 10: Vulnerability Management** +- [Vulnerability Management Lifecycle](https://owasp.org/www-community/Vulnerability_Management_Lifecycle) +- [CVSS Guide](https://www.first.org/cvss/user-guide) +- [Remediation Best Practices](https://cheatsheetseries.owasp.org/cheatsheets/Vulnerability_Disclosure_Cheat_Sheet.html) + +
+ +--- + +## ๐ŸŽ“ Course Completion + +Upon successful completion of this course, you will have: + +โœ… **Practical DevSecOps Skills** โ€” Hands-on experience with industry-standard security tools +โœ… **Security Portfolio** โ€” 10 documented security analysis projects showcasing your abilities +โœ… **Secure SDLC Knowledge** โ€” Understanding of shift-left security and secure development practices +โœ… **AppSec Testing Experience** โ€” SAST, DAST, and SCA tool integration expertise +โœ… **IaC Security Mastery** โ€” Configuration scanning and policy-as-code enforcement skills +โœ… **Container Security** โ€” Docker and Kubernetes hardening and scanning knowledge +โœ… **Supply Chain Awareness** โ€” SBOM generation and dependency security analysis +โœ… **Vulnerability Management** โ€” Discovery, triage, and remediation workflow proficiency +โœ… **Compliance Understanding** โ€” GDPR, NIST, and ISO security framework basics +โœ… **Threat Modeling Skills** โ€” STRIDE analysis and risk assessment capabilities + +--- diff --git a/labs/lab1.md b/labs/lab1.md index 5d33263f..bccdc593 100644 --- a/labs/lab1.md +++ b/labs/lab1.md @@ -4,174 +4,200 @@ ![topic](https://img.shields.io/badge/topic-AppSec%20Basics-blue) ![points](https://img.shields.io/badge/points-10-orange) -> **Goal:** Run an OWASP Juice Shop locally, complete a triage report, and standardize PR submissions. -> **Deliverable:** A PR from `feature/lab1` containing `labs/submission1.md`, issues created, and the PR template in place. +> **Goal:** Run OWASP Juice Shop locally, complete a triage report, and standardize PR submissions. +> **Deliverable:** A PR from `feature/lab1` to the course repo with `labs/submission1.md` containing triage report and PR template setup. Submit the PR link via Moodle. --- ## Overview In this lab you will practice: +- Launching **OWASP Juice Shop** for security testing +- Capturing a **triage report** covering version, URL, health check, exposure, risks, and next actions +- Bootstrapping a **repeatable PR workflow** with a template -* Launching a **Juice Shop App**. -* Capturing a **triage report** โ€” version, URL, health check, exposure, risks, and next actions. -* Bootstrapping a **repeatable PR workflow** with a template. - -> We **do not** copy Juice Shop code into the repo. Youโ€™ll run the official Docker image and keep **only lab artifacts** in your fork. Run instructions come from Juice Shopโ€™s docs; weโ€™ll pin a known release tag. ([pwning.owasp-juice.shop][1], [GitHub][2], [Docker Hub][3]) +> We **do not** copy Juice Shop code into the repo. You'll run the official Docker image and keep **only lab artifacts** in your fork. --- ## Tasks -### Task 1 โ€” Triage (Juice Shop) (6 pts) +### Task 1 โ€” OWASP Juice Shop Deployment (6 pts) -**Objective:** Run a Juice Shop locally and complete a Triage report to capture the deployment, quick health, exposure, and top risks. +**Objective:** Run Juice Shop locally and complete a Triage report capturing deployment, health check, exposure, and top risks. -1. **Create the submission file** +#### 1.1: Deploy Juice Shop Container - * Create `labs/submission1.md` with these fields: +```bash +docker run -d --name juice-shop \ + -p 127.0.0.1:3000:3000 \ + bkimminich/juice-shop:v19.0.0 +``` - * `image: bkimminich/juice-shop:19.0.0` - * release date (from GitHub Releases) and a link to the release notes. +#### 1.2: Initial Verification -2. **Run the container (detached)** +- Browse to `http://localhost:3000` and confirm the app loads +- Verify API responds: `curl -s http://127.0.0.1:3000/rest/products | head` - ```bash - docker run -d --name juice-shop \ - -p 127.0.0.1:3000:3000 \ - bkimminich/juice-shop:19.0.0 - ``` +#### 1.3: Complete Triage Report - * Browse to `http://localhost:3000` and confirm the app loads. +Create `labs/submission1.md` using this template: -3. **Quick health check** +```markdown +# Triage Report โ€” OWASP Juice Shop - * Verify the API responds: +## Scope & Asset +- Asset: OWASP Juice Shop (local lab instance) +- Image: bkimminich/juice-shop:v19.0.0 +- Release link/date: โ€” +- Image digest (optional): - ```bash - curl -s http://127.0.0.1:3000/rest/products | head - ``` - * Take a screenshot of the home page or paste the first 5โ€“10 JSON lines from the API. +## Environment +- Host OS: +- Docker: -4. **Fill the Triage report** +## Deployment Details +- Run command used: `docker run -d --name juice-shop -p 127.0.0.1:3000:3000 bkimminich/juice-shop:v19.0.0` +- Access URL: http://127.0.0.1:3000 +- Network exposure: 127.0.0.1 only [ ] Yes [ ] No (explain if No) - * In `labs/submission1.md`, copy/paste this template and fill it out: +## Health Check +- Page load: attach screenshot of home page (path or embed) +- API check: first 5โ€“10 lines from `curl -s http://127.0.0.1:3000/rest/products | head` - ```markdown - # Triage Report โ€” OWASP Juice Shop +## Surface Snapshot (Triage) +- Login/Registration visible: [ ] Yes [ ] No โ€” notes: <...> +- Product listing/search present: [ ] Yes [ ] No โ€” notes: <...> +- Admin or account area discoverable: [ ] Yes [ ] No โ€” notes: <...> +- Client-side errors in console: [ ] Yes [ ] No โ€” notes: <...> +- Security headers (quick look โ€” optional): `curl -I http://127.0.0.1:3000` โ†’ CSP/HSTS present? notes: <...> - ## Scope & Asset - - Asset: OWASP Juice Shop (local lab instance) - - Image: bkimminich/juice-shop:19.0.0 - - Release link/date: โ€” - - Image digest (optional): +## Risks Observed (Top 3) +1) +2) +3) +``` - ## Environment - - Host OS: - - Docker: +In `labs/submission1.md`, document: +- Complete triage report using provided template +- Screenshots or API output demonstrating working deployment +- Environment details and security observations +- Analysis of top 3 security risks identified during assessment - ## Deployment Details - - Run command used: `docker run -d --name juice-shop -p 127.0.0.1:3000:3000 bkimminich/juice-shop:19.0.0` - - Access URL: http://127.0.0.1:3000 - - Network exposure: 127.0.0.1 only [ ] Yes [ ] No (explain if No) +--- - ## Health Check - - Page load: attach screenshot of home page (path or embed) - - API check: first 5โ€“10 lines from `curl -s http://127.0.0.1:3000/rest/products | head` +### Task 2 โ€” PR Template Setup (4 pts) - ## Surface Snapshot (Triage) - - Login/Registration visible: [ ] Yes [ ] No โ€” notes: <...> - - Product listing/search present: [ ] Yes [ ] No โ€” notes: <...> - - Admin or account area discoverable: [ ] Yes [ ] No โ€” notes: <...> - - Client-side errors in console: [ ] Yes [ ] No โ€” notes: <...> - - Security headers (quick look โ€” optional): `curl -I http://127.0.0.1:3000` โ†’ CSP/HSTS present? notes: <...> +**Objective:** Standardize submissions so every lab PR has the same sections and checks. - ## Risks Observed (Top 3) - 1) - 2) - 3) +#### 2.1: Create PR Template - ``` +Create `.github/pull_request_template.md` with: +- Sections: **Goal**, **Changes**, **Testing**, **Artifacts & Screenshots** +- Checklist (3 items): clear title, docs updated if needed, no secrets/large temp files -> Resources: Juice Shop Docker image on Docker Hub; official run docs. ([Docker Hub][3], [pwning.owasp-juice.shop][1]) +```bash +# Commit message example: +git commit -m "docs: add PR template" +``` ---- +#### 2.2: Verify Template Application -### Task 2 โ€” PR Template (4 pts) +```bash +git checkout -b feature/lab1 +git add labs/submission1.md +git commit -m "docs(lab1): add submission1 triage report" +git push -u origin feature/lab1 +``` -**Objective:** Standardize submissions so every lab PR has the same sections and checks. +Verify that: +- PR description auto-fills with sections & checklist +- Fill in **Goal / Changes / Testing / Artifacts & Screenshots** and tick checkboxes +- Screenshots and API snippet are embedded in `labs/submission1.md` + +In `labs/submission1.md`, document: +- PR template creation process and verification +- Evidence that template auto-fills correctly +- Analysis of how templates improve collaboration workflow + +
+One-time Bootstrap Note -> โš ๏ธ **One-time bootstrap:** GitHub loads PR templates from the **default branch of your fork (`main`)**. Add the template to `main` first, then open your lab PR from `feature/lab1`. +GitHub loads PR templates from the **default branch of your fork (`main`)**. Add the template to `main` first, then open your lab PR from `feature/lab1`. -1. **Create the PR template on `main`** - Path: `.github/pull_request_template.md` - Commit message: `docs: add PR template` - Include exactly these sections and checklist: +
- * Sections: **Goal**, **Changes**, **Testing**, **Artifacts & Screenshots** - * Checklist (3 items): clear title, docs updated if needed, no secrets/large temp files +--- + +## How to Submit -2. **Create your lab branch, add your submission file, open PR** +1. Create a branch for this lab and push it to your fork: ```bash - git checkout -b feature/lab1 - # add labs/submission1.md + git switch -c feature/lab1 + # create labs/submission1.md with your findings git add labs/submission1.md - git commit -m "docs(lab1): add submission1 triage report" + git commit -m "docs: add lab1 submission" git push -u origin feature/lab1 ``` - * Open a PR from `feature/lab1` โ†’ `main` **in your fork**. +2. Open a PR from your fork's `feature/lab1` branch โ†’ **course repository's main branch**. -3. **Verify the template is applied** +3. In the PR description, include: - * The PR description should auto-fill with your sections & checklist. - * Fill in **Goal / Changes / Testing / Artifacts & Screenshots** and tick the checkboxes. - * Ensure your screenshots and API snippet are embedded or referenced in `labs/submission1.md`. - -### Acceptance Criteria + ```text + - [x] Task 1 done โ€” OWASP Juice Shop deployment + triage report + - [x] Task 2 done โ€” PR template setup + verification + ``` -* โœ… `labs/submission1.md` exists and includes: image `bkimminich/juice-shop:19.0.0` with release link/date; environment; deployment details; access URL; working health check evidence (screenshot or API snippet); surface snapshot; top 3 risks. -* โœ… 3โ€“5 **Issues** exist in the repo labeled `backlog` (derived from your triage next actions) and linked from `labs/submission1.md`. -* โœ… `.github/pull_request_template.md` exists on **`main`**. -* โœ… A PR from `feature/lab1` โ†’ `main` is open and **auto-filled** with the template, including **Goal / Changes / Testing / Artifacts & Screenshots** (boxes ticked). -* โœ… **No Juice Shop source code** is copied into the repoโ€”only lab artifacts. +4. **Copy the PR URL** and submit it via **Moodle before the deadline**. --- -## How to Submit - -1. Complete all tasks. -2. Push `feature/lab1` to your fork. -3. Open a PR from `feature/lab1` โ†’ `main` in **your fork**. -4. In the PR description, include: +## Acceptance Criteria - ```text - - [x] Task 1 done - - [x] Task 2 done - - [x] Screenshots attached - ``` +- โœ… Branch `feature/lab1` exists with commits for each task +- โœ… File `labs/submission1.md` contains required triage report for Tasks 1-2 +- โœ… OWASP Juice Shop successfully deployed and documented +- โœ… File `.github/pull_request_template.md` exists on **main** branch +- โœ… PR from `feature/lab1` โ†’ **course repo main branch** is open +- โœ… PR link submitted via Moodle before the deadline +- โœ… **No Juice Shop source code** copied into repoโ€”only lab artifacts --- ## Rubric (10 pts) -| Criterion | Points | -| --------------------------------------------------------- | -----: | -| Task 1 โ€” Triage in `labs/submission1.md` + image running | **6** | -| Task 2 โ€” PR template in effect + PR opened | **4** | -| **Total** | **10** | +| Criterion | Points | +| -------------------------------------------------------- | -----: | +| Task 1 โ€” OWASP Juice Shop deployment + triage report | **6** | +| Task 2 โ€” PR template setup + verification | **4** | +| **Total** | **10** | --- -## Hints +## Guidelines -> ๐Ÿ“Œ **Why pin the version?** Juice Shop changes challenges between releases; pinning (e.g., `:19.0.0`) keeps labs reproducible for everyone. Check the **GitHub Releases** page for the date and notes. ([GitHub][2])\ -> ๐Ÿงช **Health check tip:** The official guide uses `-p 127.0.0.1:3000:3000`; always include `127.0.0.1` to avoid exposing the app beyond localhost by accident. ([pwning.owasp-juice.shop][1])\ -> ๐Ÿšซ **Donโ€™t add app code:** All labs use the official Docker image from Docker Hubโ€”your repo holds configs, reports, and CI only. ([Docker Hub][3]) +- Use clear Markdown headers to organize sections in `submission1.md` +- Include both command outputs and written analysis for each task +- Document deployment process and security observations +- Ensure screenshots and evidence demonstrate working setup ---- +
+Security Notes + +- Always bind to `127.0.0.1` to avoid exposing the app beyond localhost +- Pin specific Docker image versions for reproducibility +- Never commit application source codeโ€”only lab artifacts and reports + +
+ +
+Deployment Tips + +- Check GitHub Releases page for specific version dates and notes +- Verify API endpoints respond before completing triage report +- Document all observed security issues in the triage template +- Keep deployment commands simple and well-documented -[1]: https://pwning.owasp-juice.shop/companion-guide/latest/part1/running.html?utm_source=chatgpt.com "Running OWASP Juice Shop" -[2]: https://github.com/juice-shop/juice-shop/releases/?utm_source=chatgpt.com "Releases ยท juice-shop/juice-shop - GitHub" -[3]: https://hub.docker.com/r/bkimminich/juice-shop/?utm_source=chatgpt.com "bkimminich/juice-shop - Docker Image | Docker Hub" +
\ No newline at end of file diff --git a/labs/lab10.md b/labs/lab10.md new file mode 100644 index 00000000..378b56a5 --- /dev/null +++ b/labs/lab10.md @@ -0,0 +1,209 @@ +# Lab 10 โ€” Vulnerability Management & Response with DefectDojo + +![difficulty](https://img.shields.io/badge/difficulty-intermediate-orange) +![topic](https://img.shields.io/badge/topic-Vulnerability%20Management-blue) +![points](https://img.shields.io/badge/points-10-orange) + +> Goal: Stand up DefectDojo locally, import prior lab findings (ZAP, Semgrep, Trivy/Grype, Nuclei), and produce a stakeholder-ready reporting & metrics package. +> Deliverable: A PR from `feature/lab10` with `labs/submission10.md` summarizing setup evidence, import results, metrics snapshot highlights, and links to exported artifacts. Submit the PR link via Moodle. + +--- + +## Overview + +In this lab you will practice: +- Standing up OWASP DefectDojo locally via Docker Compose +- Organizing findings across products/engagements/tests +- Importing findings from multiple tools (ZAP, Semgrep, Trivy, Nuclei) +- Generating reports that non-technical stakeholders can consume +- Deriving basic program metrics (open/closed status, severity mix, SLA outlook) + +> Primary platform: OWASP DefectDojo (open source, 2025) + +--- + +## Prerequisites + +- Docker with Compose V2 (`docker compose` available) +- `git`, `curl`, `jq` +- Prior lab outputs available locally (paths below) + +Create working directories: +```bash +mkdir -p labs/lab10/{setup,imports,report} +``` + +--- + +## Tasks + +### Task 1 โ€” DefectDojo Local Setup (2 pts) +Objective: Run DefectDojo locally and prepare the structure for managing findings. + +#### 1.1: Clone and start DefectDojo +```bash +# Clone upstream +git clone https://github.com/DefectDojo/django-DefectDojo.git labs/lab10/setup/django-DefectDojo +cd labs/lab10/setup/django-DefectDojo + +# Optional: check compose compatibility +./docker/docker-compose-check.sh || true + +# Build and start (first run can take a bit) +docker compose build +docker compose up -d + +# Verify containers are healthy +docker compose ps +# UI: http://localhost:8080 +``` + +#### 1.2: Get admin credentials (no manual superuser needed) +```bash +# Watch initializer logs until the admin password is printed +docker compose logs -f initializer +# In a second terminal, extract the password once available: +docker compose logs initializer | grep "Admin password:" + +# Login to the UI at http://localhost:8080 with: +# Username: admin +# Password: +``` +--- + +### Task 2 โ€” Import Prior Findings (4 pts) +Objective: Import findings from your previous labs into the engagement. + +Use the importer script below; no manual API calls are required. The script will autoโ€‘create the product type/product/engagement if missing. + +#### 2.1: Get API token and set variables +```bash +# In the UI: Profile โ†’ API v2 Key โ†’ copy your token +export DD_API="http://localhost:8080/api/v2" +export DD_TOKEN="REPLACE_WITH_YOUR_API_TOKEN" + +# Target context (adjust names if you prefer) +export DD_PRODUCT_TYPE="Engineering" +export DD_PRODUCT="Juice Shop" +export DD_ENGAGEMENT="Labs Security Testing" +# The import script will auto-detect importer names from your instance. +``` + +#### 2.2: Required reports (expected paths) +- ZAP: `labs/lab5/zap/zap-report-noauth.json` +- Semgrep: `labs/lab5/semgrep/semgrep-results.json` +- Trivy: `labs/lab4/trivy/trivy-vuln-detailed.json` +- Nuclei: `labs/lab5/nuclei/nuclei-results.json` +- Grype (optional): `labs/lab4/syft/grype-vuln-results.json` + +#### 2.3: Run the importer script +```bash +bash labs/lab10/imports/run-imports.sh +``` +The script auto-detects importer names, auto-creates context if missing, imports any reports found at the paths above, and saves responses under `labs/lab10/imports/`. +--- + +### Task 3 โ€” Reporting & Program Metrics (4 pts) +Objective: Turn raw imports into an easy-to-understand report and metrics package that a stakeholder can consume without prior Dojo experience. + +#### 3.1: Create a baseline progress snapshot +- From the engagement dashboard, note the counts for Active, Verified, and Mitigated findings. +- Use the โ€œFiltersโ€ sidebar to group by severity; grab a screenshot or jot the numbers. +- Record the snapshot using the template below: + ```bash + mkdir -p labs/lab10/report + cat > labs/lab10/report/metrics-snapshot.md <<'EOF' + # Metrics Snapshot โ€” Lab 10 + + - Date captured: + - Active findings: + - Critical: + - High: + - Medium: + - Low: + - Informational: + - Verified vs. Mitigated notes: + EOF + ``` + +#### 3.2: Generate governance-ready artifacts +- In the Engagement โ†’ Reports page, choose a human-readable template (Executive, Detailed, or similar) and generate a PDF or HTML report. + - Save it to `labs/lab10/report/dojo-report.pdf` or `.html`. +- Download the โ€œFindings list (CSV)โ€ from the same page and store it as `labs/lab10/report/findings.csv` for spreadsheet analysis. + +#### 3.3: Extract key metrics for `labs/submission10.md` +- From the report or dashboard, capture: + - Open vs. Closed counts by severity. + - Findings per tool (ZAP, Semgrep, Trivy, Nuclei, and Grype). + - Any SLA breaches or items due within the next 14 days. + - Top recurring CWE/OWASP categories. +- Summarize these in prose (3โ€“5 bullet points) inside `labs/submission10.md`. + +Deliverables for this task: +- `labs/lab10/report/metrics-snapshot.md` +- `labs/lab10/report/dojo-report.(pdf|html)` +- `labs/lab10/report/findings.csv` +- Metric summary bullets in `labs/submission10.md` + +--- + +## Acceptance Criteria + +- โœ… DefectDojo runs locally and an admin user can log in +- โœ… Product Type, Product, and Engagement are configured +- โœ… Imports completed for ZAP, Semgrep, Trivy (plus Nuclei/Grype if available) +- โœ… Reporting artifacts generated: metrics snapshot, Dojo report, findings CSV, and summary bullets in `labs/submission10.md` +- โœ… All artifacts saved under `labs/lab10/` + +--- + +## How to Submit + +1. Create a branch for this lab and push it to your fork: +```bash +git switch -c feature/lab10 +# create labs/submission10.md with your findings +git add labs/lab10/ labs/submission10.md +git commit -m "docs: lab10 โ€” DefectDojo vuln management" +git push -u origin feature/lab10 +``` +2. Open a PR from your forkโ€™s `feature/lab10` โ†’ course repoโ€™s `main`. +3. Include this checklist in the PR description: +```text +- [x] Task 1 โ€” Dojo setup and structure +- [x] Task 2 โ€” Imports completed (multi-tool) +- [x] Task 3 โ€” Report + metrics package +``` +4. Submit the PR URL via Moodle before the deadline. + +--- + +## Rubric (10 pts) + +| Criterion | Points | +| ------------------------------------------------------------ | -----: | +| Task 1 โ€” DefectDojo local setup | 2.0 | +| Task 2 โ€” Import prior findings (multi-tool) | 4.0 | +| Task 3 โ€” Reporting & metrics package | 4.0 | +| Total | 10.0 | + +--- + +## Guidelines + +- Keep sensitive data out of uploads; use lab outputs only +- Prefer JSON formats for robust importer support +- If you explore deduplication, note the algorithm choice (helps explain numbers) +- Be explicit when marking false positives (add justification) +- Keep SLAs realistic but time-bound; reference calendar dates + +
+References + +- DefectDojo: https://github.com/DefectDojo/django-DefectDojo +- Importers list: check your UI Import Scan page for exact `scan_type` names +- Local API v2 docs: http://localhost:8080/api/v2/doc/ (after startup) +- Official docs (Open Source): https://docs.defectdojo.com/en/open_source/ +- CVSS v3.1 Calculator: https://www.first.org/cvss/calculator/3.1 + +
diff --git a/labs/lab10/imports/run-imports.sh b/labs/lab10/imports/run-imports.sh new file mode 100644 index 00000000..0f0e33c9 --- /dev/null +++ b/labs/lab10/imports/run-imports.sh @@ -0,0 +1,134 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Batch import helper for Lab 10 +# - Auto-detects scan_type names from your Dojo instance +# - Imports whichever files exist among ZAP, Semgrep, Trivy, Nuclei (and optional Grype) +# +# Usage: +# export DD_API="http://localhost:8080/api/v2" +# export DD_TOKEN="" +# # Optional overrides (defaults shown) +# export DD_PRODUCT_TYPE="${DD_PRODUCT_TYPE:-Engineering}" +# export DD_PRODUCT="${DD_PRODUCT:-Juice Shop}" +# export DD_ENGAGEMENT="${DD_ENGAGEMENT:-Labs Security Testing}" +# bash labs/lab10/imports/run-imports.sh + +here_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +out_dir="$here_dir" + +require_env() { + local name="$1" + if [[ -z "${!name:-}" ]]; then + echo "ERROR: env var $name is required" >&2 + exit 1 + fi +} + +require_env DD_API +require_env DD_TOKEN + +DD_PRODUCT_TYPE="${DD_PRODUCT_TYPE:-Engineering}" +DD_PRODUCT="${DD_PRODUCT:-Juice Shop}" +DD_ENGAGEMENT="${DD_ENGAGEMENT:-Labs Security Testing}" + +echo "Using context:" +echo " DD_API=$DD_API" +echo " DD_PRODUCT_TYPE=$DD_PRODUCT_TYPE" +echo " DD_PRODUCT=$DD_PRODUCT" +echo " DD_ENGAGEMENT=$DD_ENGAGEMENT" + +have_jq=true +command -v jq >/dev/null 2>&1 || have_jq=false +if ! $have_jq; then + echo "WARN: jq not found; falling back to defaults for scan_type names." >&2 +fi + +# Discover scan type names from your instance if jq is available +SCAN_ZAP="${SCAN_ZAP:-}" +SCAN_SEMGREP="${SCAN_SEMGREP:-}" +SCAN_TRIVY="${SCAN_TRIVY:-}" +SCAN_NUCLEI="${SCAN_NUCLEI:-}" + +if $have_jq; then + echo "Discovering importer names from /test_types/ ..." + mapfile -t types < <(curl -sS -H "Authorization: Token $DD_TOKEN" "$DD_API/test_types/?limit=2000" | jq -r '.results[].name') + choose_type() { + local pat="$1" + local fallback="$2" + local val="" + for t in "${types[@]}"; do + if [[ "$t" =~ $pat ]]; then val="$t"; break; fi + done + if [[ -z "$val" ]]; then val="$fallback"; fi + echo "$val" + } + SCAN_ZAP="${SCAN_ZAP:-$(choose_type '^ZAP' 'ZAP Scan')}" + SCAN_SEMGREP="${SCAN_SEMGREP:-$(choose_type '^Semgrep' 'Semgrep JSON Report')}" + SCAN_TRIVY="${SCAN_TRIVY:-$(choose_type '^Trivy' 'Trivy Scan')}" + SCAN_NUCLEI="${SCAN_NUCLEI:-$(choose_type '^Nuclei' 'Nuclei Scan')}" + # Grype importer (commonly named "Anchore Grype") + if [[ -z "${SCAN_GRYPE:-}" ]]; then + SCAN_GRYPE=$(printf '%s\n' "${types[@]}" | grep -i '^Anchore Grype' | head -n1) + if [[ -z "$SCAN_GRYPE" ]]; then + SCAN_GRYPE=$(printf '%s\n' "${types[@]}" | grep -i 'Grype' | head -n1) + fi + fi +else + SCAN_ZAP="${SCAN_ZAP:-ZAP Scan}" + SCAN_SEMGREP="${SCAN_SEMGREP:-Semgrep JSON Report}" + SCAN_TRIVY="${SCAN_TRIVY:-Trivy Scan}" + SCAN_NUCLEI="${SCAN_NUCLEI:-Nuclei Scan}" +fi +SCAN_GRYPE="${SCAN_GRYPE:-Anchore Grype}" + +echo "Importer names:" +echo " ZAP = $SCAN_ZAP" +echo " Semgrep = $SCAN_SEMGREP" +echo " Trivy = $SCAN_TRIVY" +echo " Nuclei = $SCAN_NUCLEI" +echo " Grype = $SCAN_GRYPE" + +import_scan() { + local scan_type="$1"; shift + local file="$1"; shift + if [[ ! -f "$file" ]]; then + echo "SKIP: $scan_type file not found: $file" + return 0 + fi + local base out + base="$(basename "$file")" + out="$out_dir/import-${base//[^A-Za-z0-9_.-]/_}.json" + echo "Importing $scan_type from $file" + curl -sS -X POST "$DD_API/import-scan/" \ + -H "Authorization: Token $DD_TOKEN" \ + -F "scan_type=$scan_type" \ + -F "file=@$file" \ + -F "product_type_name=$DD_PRODUCT_TYPE" \ + -F "product_name=$DD_PRODUCT" \ + -F "engagement_name=$DD_ENGAGEMENT" \ + -F "auto_create_context=true" \ + -F "minimum_severity=Info" \ + -F "close_old_findings=false" \ + -F "push_to_jira=false" \ + | tee "$out" +} + +# Candidate paths per tool +zap_file="labs/lab5/zap/zap-report-noauth.json" +semgrep_file="labs/lab5/semgrep/semgrep-results.json" +trivy_file="labs/lab4/trivy/trivy-vuln-detailed.json" +nuclei_file="labs/lab5/nuclei/nuclei-results.json" + +# Grype +grype_file="labs/lab4/syft/grype-vuln-results.json" + +import_scan "$SCAN_ZAP" "$zap_file" +import_scan "$SCAN_SEMGREP" "$semgrep_file" +import_scan "$SCAN_TRIVY" "$trivy_file" +import_scan "$SCAN_NUCLEI" "$nuclei_file" + +# Grype +import_scan "$SCAN_GRYPE" "$grype_file" + +echo "Done. Import responses saved under $out_dir" diff --git a/labs/lab11.md b/labs/lab11.md new file mode 100644 index 00000000..4ada0627 --- /dev/null +++ b/labs/lab11.md @@ -0,0 +1,285 @@ +# Lab 11 โ€” Reverse Proxy Hardening: Nginx Security Headers, TLS, and Rate Limiting + +![difficulty](https://img.shields.io/badge/difficulty-intermediate-orange) +![topic](https://img.shields.io/badge/topic-Application%20Hardening-blue) +![points](https://img.shields.io/badge/points-10-orange) + +> Goal: Place OWASP Juice Shop behind an Nginx reverse proxy and harden it with security headers, TLS, and request rate limiting โ€” without changing app code. +> Deliverable: A PR from `feature/lab11` with `labs/submission11.md` including command evidence, header/TLS scans, rate-limit test results, and a short analysis of trade-offs. + +--- + +## Overview + +You will: +- Deploy Juice Shop behind a reverse proxy using Docker Compose +- Add and verify essential security headers (XFO, XCTO, HSTS, Referrer-Policy, Permissions-Policy, COOP/CORP) +- Enable TLS with a local self-signed certificate and verify configuration +- Implement request rate limiting and timeouts to reduce brute-force/DoS risk + +This lab is designed to be practical and educational, focusing on changes operations teams can make without touching application code. + +--- + +## Prerequisites + +Before starting, ensure you have: +- โœ… Docker installed and running (`docker --version`) +- โœ… Docker Compose installed (`docker compose version`) +- โœ… `curl` and `jq` for testing and JSON parsing +- โœ… At least 2GB free disk space +- โœ… ~45-60 minutes available + +**Quick Setup Check:** +```bash +# Pull images in advance (optional) +docker pull bkimminich/juice-shop:v19.0.0 +docker pull nginx:stable-alpine +docker pull alpine:latest +docker pull drwetter/testssl.sh:latest + +# Create working directories +mkdir -p labs/lab11/{reverse-proxy/certs,logs,analysis} +``` + +**Files provided in this repo:** +- `labs/lab11/docker-compose.yml` - Stack configuration +- `labs/lab11/reverse-proxy/nginx.conf` - Pre-configured with security headers, TLS, rate limiting + +--- + +## Tasks + +### Task 1 โ€” Reverse Proxy Compose Setup (2 pts) +โฑ๏ธ **Estimated time:** 10 minutes + +**Objective:** Run Juice Shop behind Nginx (no app port exposed directly). + +#### 1.1: Prepare certs and start the stack +```bash +# Navigate to lab11 directory +cd labs/lab11 + +# Generate a local self-signed cert with SAN for localhost so Nginx can start +docker run --rm -v "$(pwd)/reverse-proxy/certs":/certs \ + alpine:latest \ + sh -c "apk add --no-cache openssl && cat > /tmp/san.cnf << 'EOF' && \ +cat /tmp/san.cnf && \ +openssl req -x509 -nodes -days 365 -newkey rsa:2048 \ + -keyout /certs/localhost.key -out /certs/localhost.crt \ + -config /tmp/san.cnf -extensions v3_req +[ req ] +default_bits = 2048 +distinguished_name = req_distinguished_name +x509_extensions = v3_req +prompt = no + +[ req_distinguished_name ] +CN = localhost + +[ v3_req ] +subjectAltName = @alt_names + +[ alt_names ] +DNS.1 = localhost +IP.1 = 127.0.0.1 +IP.2 = ::1 +EOF" + +# Start services +docker compose up -d +docker compose ps + +# Verify HTTP (should redirect to HTTPS) +curl -s -o /dev/null -w "HTTP %{http_code}\n" http://localhost:8080/ +``` + +Expected: `HTTP 308` (redirect to HTTPS). + +#### 1.2: Confirm no direct app exposure +```bash +# Only Nginx should have published host ports; Juice Shop should have none +docker compose ps +``` + +In `labs/submission11.md`, document: + +**Task 1 Requirements:** + - Explain why reverse proxies are valuable for security (TLS termination, security headers injection, request filtering, single access point) + - Explain why hiding direct app ports reduces attack surface + - Include the `docker compose ps` output showing only Nginx has published host ports (Juice Shop shows none) + +--- + +### Task 2 โ€” Security Headers (3 pts) +โฑ๏ธ **Estimated time:** 10 minutes + +**Objective:** Review the essential headers at the proxy and verify theyโ€™re present over HTTP/HTTPS. + +Headers configured in `nginx.conf`: + - `X-Frame-Options: DENY` + - `X-Content-Type-Options: nosniff` + - `Referrer-Policy: strict-origin-when-cross-origin` + - `Permissions-Policy: camera=(), geolocation=(), microphone=()` + - `Cross-Origin-Opener-Policy: same-origin` + - `Cross-Origin-Resource-Policy: same-origin` + - `Content-Security-Policy-Report-Only: default-src 'self'; img-src 'self' data:; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'` + +Note: CSP is set in Report-Only mode to avoid breaking Juice Shop functionality. + +โฑ๏ธ ~10 minutes + +#### 2.1: Verify headers (HTTP) +```bash +curl -sI http://localhost:8080/ | tee analysis/headers-http.txt +``` + +#### 2.2: Verify headers (after TLS in Task 3) +```bash +curl -skI https://localhost:8443/ | tee analysis/headers-https.txt +``` + +In `labs/submission11.md`, document: + +**Task 2 Requirements:** + - Paste relevant security headers from `headers-https.txt` + - For each header, explain what it protects against: + - **X-Frame-Options**: --- + - **X-Content-Type-Options**: --- + - **Strict-Transport-Security (HSTS)**: --- + - **Referrer-Policy**: --- + - **Permissions-Policy**: --- + - **COOP/CORP**: --- + - **CSP-Report-Only**: --- +--- + +### Task 3 โ€” TLS, HSTS, Rate Limiting & Timeouts (5 pts) +โฑ๏ธ **Estimated time:** 20 minutes + +**Objective:** Confirm HTTPS and HSTS behavior, scan TLS, and validate rate limiting and timeouts to reduce brute-force and slowloris risks. + +#### 3.1: Scan TLS (testssl.sh) +Use one of the following, depending on your OS: +```bash +# Linux: use host networking to reach localhost:8443 +docker run --rm --network host drwetter/testssl.sh:latest https://localhost:8443 \ + | tee analysis/testssl.txt + +# Mac/Windows (Docker Desktop): target host.docker.internal +docker run --rm drwetter/testssl.sh:latest https://host.docker.internal:8443 \ + | tee analysis/testssl.txt +``` + +--- + +#### 3.2: Validate rate limiting on login +Login rate limit is configured on `/rest/user/login` with Nginx `limit_req` and `limit_req_status 429`. + +##### Trigger rate limiting +```bash +for i in $(seq 1 12); do \ + curl -sk -o /dev/null -w "%{http_code}\n" \ + -H 'Content-Type: application/json' \ + -X POST https://localhost:8443/rest/user/login \ + -d '{"email":"a@a","password":"a"}'; \ +done | tee analysis/rate-limit-test.txt +``` +Expected: Some responses return `429` once the burst+rate thresholds are exceeded. + +In `labs/submission11.md`, document: + +**Task 3 Requirements:** +- TLS/testssl summary: + - Summarize TLS protocol support from testssl scan (which versions are enabled) + - List cipher suites that are supported + - Explain why TLSv1.2+ is required (prefer TLSv1.3) + - Note any warnings or vulnerabilities from testssl output + - Confirm HSTS header appears only on HTTPS responses (not HTTP) + +Note on dev certificates: On localhost you should still expect these โ€œNOT okโ€ items with a selfโ€‘signed cert: chain of trust (selfโ€‘signed), OCSP/CRL/CT/CAA, and OCSP stapling not offered. To eliminate them, either trust a local CA (e.g., mkcert) or use a real domain and a public CA (e.g., Letโ€™s Encrypt) and then enable OCSP stapling (comments in nginx.conf). + +- Rate limiting & timeouts: + - Show rate-limit test output (how many 200s vs 429s) + - Explain the rate limit configuration: `rate=10r/m`, `burst=5`, and why these values balance security vs usability + - Explain timeout settings in nginx.conf: `client_body_timeout`, `client_header_timeout`, `proxy_read_timeout`, `proxy_send_timeout`, with trade-offs + - Paste relevant lines from access.log showing 429 responses + +--- + +## Acceptance Criteria + +- โœ… Nginx reverse proxy running; Juice Shop not directly exposed +- โœ… Security headers present over HTTP/HTTPS; HSTS only on HTTPS +- โœ… TLS enabled and scanned; HSTS verified; outputs captured +- โœ… Rate limiting returns 429 on excessive login attempts; logs captured; timeouts discussed +- โœ… All outputs committed under `labs/lab11/` + +--- + +## Cleanup + +After completing the lab: + +```bash +# Stop and remove containers +cd labs/lab11 # if not already there +docker compose down + +# Optional: Remove generated certificates +# rm -rf labs/lab11/reverse-proxy/certs/* + +# Check disk space +docker system df +``` + +--- + +## How to Submit + +1. Create a branch and push it to your fork: +```bash +git switch -c feature/lab11 +# create labs/submission11.md with your findings +git add labs/lab11/ labs/submission11.md +git commit -m "docs: add lab11 โ€” nginx reverse proxy hardening" +git push -u origin feature/lab11 +``` +2. Open a PR from your forkโ€™s `feature/lab11` โ†’ course repoโ€™s `main`. +3. In the PR description include: +```text +- [x] Task 1 โ€” Reverse proxy compose setup +- [x] Task 2 โ€” Security headers verification +- [x] Task 3 โ€” TLS + HSTS + rate limiting + timeouts (+ testssl) +``` +4. Submit the PR URL via Moodle before the deadline. + +--- + +## Rubric (10 pts) + +| Criterion | Points | +| ----------------------------------------------------- | -----: | +| Task 1 โ€” Reverse proxy compose setup | 2.0 | +| Task 2 โ€” Security headers (HTTP/HTTPS) | 3.0 | +| Task 3 โ€” TLS, HSTS, rate limiting & timeouts | 5.0 | +| Total | 10.0 | + +--- + +## Guidelines + +- Keep app container internal; only expose Nginx ports to host +- Use `add_header ... always;` so headers appear even on errors/redirects +- Place HSTS only on HTTPS server blocks +- Start CSP in Report-Only and iterate; Juice Shop is JS-heavy and can break under strict CSP +- Choose rate limits that balance security and usability; document your rationale + +
+Resources + +- Nginx security headers: https://nginx.org/en/docs/http/ngx_http_headers_module.html +- TLS config guidelines: https://ssl-config.mozilla.org/ +- testssl.sh: https://github.com/drwetter/testssl.sh +- Permissions Policy: https://www.w3.org/TR/permissions-policy-1/ + +
diff --git a/labs/lab11/docker-compose.yml b/labs/lab11/docker-compose.yml new file mode 100644 index 00000000..da5002c1 --- /dev/null +++ b/labs/lab11/docker-compose.yml @@ -0,0 +1,19 @@ +services: + juice: + image: bkimminich/juice-shop:v19.0.0 + restart: unless-stopped + expose: + - "3000" + + nginx: + image: nginx:stable-alpine + restart: unless-stopped + depends_on: + - juice + ports: + - "8080:8080" # HTTP (will redirect to HTTPS) + - "8443:8443" # HTTPS + volumes: + - ./reverse-proxy/nginx.conf:/etc/nginx/nginx.conf:ro + - ./reverse-proxy/certs:/etc/nginx/certs:ro + - ./logs:/var/log/nginx:rw diff --git a/labs/lab11/reverse-proxy/nginx.conf b/labs/lab11/reverse-proxy/nginx.conf new file mode 100644 index 00000000..b90f6c47 --- /dev/null +++ b/labs/lab11/reverse-proxy/nginx.conf @@ -0,0 +1,127 @@ +user nginx; +worker_processes auto; + +events { worker_connections 1024; } + +http { + include /etc/nginx/mime.types; + default_type application/octet-stream; + sendfile on; + keepalive_timeout 10; + server_tokens off; + gzip off; + + # Security-focused logs + log_format security '$remote_addr - $remote_user [$time_local] ' + '"$request" $status $body_bytes_sent ' + '"$http_referer" "$http_user_agent" ' + 'rt=$request_time uct=$upstream_connect_time ' + 'urt=$upstream_response_time'; + access_log /var/log/nginx/access.log security; + error_log /var/log/nginx/error.log warn; + + # Upstream app + upstream juice { + server juice:3000; + keepalive 32; + } + + # Rate limit zone for login + # ~10 req/min per IP, burst of 5 + limit_req_zone $binary_remote_addr zone=login:10m rate=10r/m; + limit_req_status 429; + + map $http_upgrade $connection_upgrade { default upgrade; '' close; } + + # Common proxy settings + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_http_version 1.1; + proxy_set_header Connection $connection_upgrade; + proxy_set_header Upgrade $http_upgrade; + # Prevent upstream TLS BREACH vector by disabling compression from upstream + proxy_set_header Accept-Encoding ""; + proxy_read_timeout 30s; + proxy_send_timeout 30s; + proxy_connect_timeout 5s; + proxy_hide_header X-Powered-By; + # Hide upstream headers to avoid duplicates and enforce policy at the proxy + proxy_hide_header X-Frame-Options; + proxy_hide_header X-Content-Type-Options; + proxy_hide_header Referrer-Policy; + proxy_hide_header Permissions-Policy; + proxy_hide_header Cross-Origin-Opener-Policy; + proxy_hide_header Cross-Origin-Resource-Policy; + proxy_hide_header Content-Security-Policy; + proxy_hide_header Content-Security-Policy-Report-Only; + proxy_hide_header Access-Control-Allow-Origin; + + # HTTP server (redirect to HTTPS) + server { + listen 8080; + listen [::]:8080; + server_name _; + + # Core headers (also on redirects) + add_header X-Frame-Options "DENY" always; + add_header X-Content-Type-Options "nosniff" always; + add_header Referrer-Policy "strict-origin-when-cross-origin" always; + add_header Permissions-Policy "camera=(), geolocation=(), microphone=()" always; + add_header Cross-Origin-Opener-Policy "same-origin" always; + add_header Cross-Origin-Resource-Policy "same-origin" always; + add_header Content-Security-Policy-Report-Only "default-src 'self'; img-src 'self' data:; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'" always; + + return 308 https://$host:8443$request_uri; + } + + # HTTPS server + server { + listen 8443 ssl; + listen [::]:8443 ssl; + http2 on; + server_name _; + + ssl_certificate /etc/nginx/certs/localhost.crt; + ssl_certificate_key /etc/nginx/certs/localhost.key; + ssl_session_timeout 10m; + ssl_session_cache shared:SSL:10m; + ssl_protocols TLSv1.2 TLSv1.3; + ssl_ciphers "TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256:EECDH+AESGCM:EDH+AESGCM"; + ssl_prefer_server_ciphers on; + ssl_stapling off; + # If using a publicly-trusted certificate, you may enable OCSP stapling: + # ssl_stapling on; + # ssl_stapling_verify on; + # resolver 1.1.1.1 8.8.8.8 valid=300s; + # resolver_timeout 5s; + # ssl_trusted_certificate /etc/ssl/certs/ca-certificates.crt; + + client_max_body_size 2m; + client_body_timeout 10s; + client_header_timeout 10s; + keepalive_timeout 10s; + send_timeout 10s; + + # Security headers (include HSTS here only) + add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always; + add_header X-Frame-Options "DENY" always; + add_header X-Content-Type-Options "nosniff" always; + add_header Referrer-Policy "strict-origin-when-cross-origin" always; + add_header Permissions-Policy "camera=(), geolocation=(), microphone=()" always; + add_header Cross-Origin-Opener-Policy "same-origin" always; + add_header Cross-Origin-Resource-Policy "same-origin" always; + add_header Content-Security-Policy-Report-Only "default-src 'self'; img-src 'self' data:; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'" always; + + location = /rest/user/login { + limit_req zone=login burst=5 nodelay; + limit_req_log_level warn; + proxy_pass http://juice; + } + + location / { + proxy_pass http://juice; + } + } +} diff --git a/labs/lab12.md b/labs/lab12.md new file mode 100644 index 00000000..1bf1af41 --- /dev/null +++ b/labs/lab12.md @@ -0,0 +1,401 @@ +# Lab 12 โ€” Kata Containers: VM-backed Container Sandboxing (Local) + +![difficulty](https://img.shields.io/badge/difficulty-intermediate-orange) +![topic](https://img.shields.io/badge/topic-Container%20Sandboxing-blue) +![points](https://img.shields.io/badge/points-10-orange) + +> Goal: Run OWASP Juice Shop under Kata Containers to experience VM-backed container isolation, compare it with the default runc runtime, and document security/operational trade-offs. +> Deliverable: A PR from `feature/lab12` with `labs/submission12.md` containing setup evidence, runtime comparisons (runc vs kata), isolation tests, and a brief performance summary with recommendations. + +--- + +## Overview + +In this lab you will practice: +- Installing/Configuring Kata Containers as a Docker/containerd runtime (Linux) +- Running the same workload (Juice Shop) with `runc` vs `kata-runtime` +- Observing isolation differences (guest kernel, process visibility, restricted operations) +- Measuring basic performance characteristics and trade-offs + +> VM-backed sandboxes like Kata place each container/pod inside a lightweight VM, adding a strong isolation boundary while preserving container UX. + +--- + +## Prerequisites + +Before starting, ensure you have: +- โœ… Linux host with hardware virtualization enabled (Intel VT-x or AMD-V) + - Check: `egrep -c '(vmx|svm)' /proc/cpuinfo` (should return > 0) + - Nested virtualization required if running inside a VM +- โœ… containerd (1.7+) and nerdctl (1.7+) with root/sudo privileges +- โœ… `jq`, `curl`, and `awk` installed +- โœ… At least 4GB RAM and 10GB free disk space +- โœ… ~60-90 minutes available (installation can take time) + +Install containerd + nerdctl (example on Debian/Ubuntu): +```bash +sudo apt-get update && sudo apt-get install -y containerd +sudo containerd config default | sudo tee /etc/containerd/config.toml >/dev/null +sudo systemctl enable --now containerd + +# Install nerdctl (binary) +VER=2.2.0 +curl -fL -o /tmp/nerdctl.tgz "https://github.com/containerd/nerdctl/releases/download/v${VER}/nerdctl-${VER}-linux-amd64.tar.gz" +sudo tar -C /usr/local/bin -xzf /tmp/nerdctl.tgz nerdctl && rm /tmp/nerdctl.tgz + +containerd --version +sudo nerdctl --version + +# Prepare working directories +mkdir -p labs/lab12/{setup,runc,kata,isolation,bench,analysis} +``` + +If you plan to use the Kata assets installer, ensure `zstd` is available for extracting the release tarball: +```bash +sudo apt-get install -y zstd jq +``` + +--- + +## Tasks + +### Task 1 โ€” Install and Configure Kata (2 pts) +โฑ๏ธ **Estimated time:** 20-30 minutes + +**Objective:** Install Kata and make it available to containerd (nerdctl) as `io.containerd.kata.v2`. + +#### 1.1: Install Kata + +- Build the Kata Rust runtime in a container and copy the shim to your host: + +```bash +# Build inside a Rust container; output goes to labs/lab12/setup/kata-out/ +bash labs/lab12/setup/build-kata-runtime.sh + +# Install the shim onto your host PATH (requires sudo) +sudo install -m 0755 labs/lab12/setup/kata-out/containerd-shim-kata-v2 /usr/local/bin/ +command -v containerd-shim-kata-v2 && containerd-shim-kata-v2 --version | tee labs/lab12/setup/kata-built-version.txt +``` + +Notes: +- The runtime alone is not sufficient; Kata also needs a guest kernel + rootfs image. Prefer your distro packages for these artifacts, or follow the upstream docs to obtain them. If you already have Kata installed, replacing just the shim binary is typically sufficient for this lab. + +- Install Kata assets and default config (runtime-rs): +```bash +sudo bash labs/lab12/scripts/install-kata-assets.sh # downloads kata-static and wires configuration +``` + - If you see an error like "load TOML config failed" when running a Kata container, it means the default configuration file is missing. The script above creates `/etc/kata-containers/runtime-rs/configuration.toml` pointing to the installed defaults. + +#### 1.2: Configure containerd + nerdctl +- Enable `io.containerd.kata.v2` per Kata docs (Kata 3โ€™s shim is `containerd-shim-kata-v2`). +- Minimal config example for config version 3 (most current containerd): +```toml +[plugins.'io.containerd.cri.v1.runtime'.containerd.runtimes.kata] + runtime_type = 'io.containerd.kata.v2' +``` + - Legacy configs may use: +```toml +[plugins.'io.containerd.grpc.v1.cri'.containerd.runtimes.kata] + runtime_type = 'io.containerd.kata.v2' +``` + +Automated update (recommended): +```bash +sudo bash labs/lab12/scripts/configure-containerd-kata.sh # updates /etc/containerd/config.toml +``` +- Restart and verify a test container: +```bash +sudo systemctl restart containerd +sudo nerdctl run --rm --runtime io.containerd.kata.v2 alpine:3.19 uname -a +``` + +In `labs/submission12.md`, document: + +**Task 1 Requirements:** +- Show the shim `containerd-shim-kata-v2 --version` +- Show a successful test run with `sudo nerdctl run --runtime io.containerd.kata.v2 ...` + +--- + +### Task 2 โ€” Run and Compare Containers (runc vs kata) (3 pts) +โฑ๏ธ **Estimated time:** 15-20 minutes + +**Objective:** Run workloads with both runtimes and compare their environments. + +#### 2.1: Start runc container (Juice Shop) +```bash +# runc (default under nerdctl) - full application +sudo nerdctl run -d --name juice-runc -p 3012:3000 bkimminich/juice-shop:v19.0.0 + +# Wait for readiness +sleep 10 +curl -s -o /dev/null -w "juice-runc: HTTP %{http_code}\n" http://localhost:3012 | tee labs/lab12/runc/health.txt +``` + +#### 2.2: Run Kata containers (Alpine-based tests) + +> **Note:** Due to a known issue with nerdctl + Kata runtime-rs v3 and long-running detached containers, +> we'll use short-lived Alpine containers for Kata demonstrations. + +```bash +echo "=== Kata Container Tests ===" +sudo nerdctl run --rm --runtime io.containerd.kata.v2 alpine:3.19 uname -a | tee labs/lab12/kata/test1.txt +sudo nerdctl run --rm --runtime io.containerd.kata.v2 alpine:3.19 uname -r | tee labs/lab12/kata/kernel.txt +sudo nerdctl run --rm --runtime io.containerd.kata.v2 alpine:3.19 sh -c "grep 'model name' /proc/cpuinfo | head -1" | tee labs/lab12/kata/cpu.txt +``` + +#### 2.3: Kernel comparison (Key finding) + +```bash +echo "=== Kernel Version Comparison ===" | tee labs/lab12/analysis/kernel-comparison.txt +echo -n "Host kernel (runc uses this): " | tee -a labs/lab12/analysis/kernel-comparison.txt +uname -r | tee -a labs/lab12/analysis/kernel-comparison.txt + +echo -n "Kata guest kernel: " | tee -a labs/lab12/analysis/kernel-comparison.txt +sudo nerdctl run --rm --runtime io.containerd.kata.v2 alpine:3.19 cat /proc/version | tee -a labs/lab12/analysis/kernel-comparison.txt +``` + +#### 2.4: CPU virtualization check + +```bash +echo "=== CPU Model Comparison ===" | tee labs/lab12/analysis/cpu-comparison.txt +echo "Host CPU:" | tee -a labs/lab12/analysis/cpu-comparison.txt +grep "model name" /proc/cpuinfo | head -1 | tee -a labs/lab12/analysis/cpu-comparison.txt + +echo "Kata VM CPU:" | tee -a labs/lab12/analysis/cpu-comparison.txt +sudo nerdctl run --rm --runtime io.containerd.kata.v2 alpine:3.19 sh -c "grep 'model name' /proc/cpuinfo | head -1" | tee -a labs/lab12/analysis/cpu-comparison.txt +``` + +In `labs/submission12.md`, document: + +**Task 2 Requirements:** +- Show juice-runc health check (HTTP 200 from port 3012) +- Show Kata containers running successfully with `--runtime io.containerd.kata.v2` +- Compare kernel versions: + - runc uses host kernel (same as `uname -r`) + - Kata uses separate guest kernel (6.12.47 or similar) +- Compare CPU models (real vs virtualized) +- Explain isolation implications: + - **runc**: ? + - **Kata**: ? + +--- + +### Task 3 โ€” Isolation Tests (3 pts) +โฑ๏ธ **Estimated time:** 15 minutes + +**Objective:** Observe and compare isolation characteristics between runc and Kata. + +#### 3.1: Kernel ring buffer (dmesg) access + +This demonstrates the most significant isolation difference: + +```bash +echo "=== dmesg Access Test ===" | tee labs/lab12/isolation/dmesg.txt + +echo "Kata VM (separate kernel boot logs):" | tee -a labs/lab12/isolation/dmesg.txt +sudo nerdctl run --rm --runtime io.containerd.kata.v2 alpine:3.19 dmesg 2>&1 | head -5 | tee -a labs/lab12/isolation/dmesg.txt +``` + +**Key observation:** Kata containers show VM boot logs, proving they run in a separate kernel. + +#### 3.2: /proc filesystem visibility + +```bash +echo "=== /proc Entries Count ===" | tee labs/lab12/isolation/proc.txt + +echo -n "Host: " | tee -a labs/lab12/isolation/proc.txt +ls /proc | wc -l | tee -a labs/lab12/isolation/proc.txt + +echo -n "Kata VM: " | tee -a labs/lab12/isolation/proc.txt +sudo nerdctl run --rm --runtime io.containerd.kata.v2 alpine:3.19 sh -c "ls /proc | wc -l" | tee -a labs/lab12/isolation/proc.txt +``` + +#### 3.3: Network interfaces + +```bash +echo "=== Network Interfaces ===" | tee labs/lab12/isolation/network.txt + +echo "Kata VM network:" | tee -a labs/lab12/isolation/network.txt +sudo nerdctl run --rm --runtime io.containerd.kata.v2 alpine:3.19 ip addr | tee -a labs/lab12/isolation/network.txt +``` + +#### 3.4: Kernel modules + +```bash +echo "=== Kernel Modules Count ===" | tee labs/lab12/isolation/modules.txt + +echo -n "Host kernel modules: " | tee -a labs/lab12/isolation/modules.txt +ls /sys/module | wc -l | tee -a labs/lab12/isolation/modules.txt + +echo -n "Kata guest kernel modules: " | tee -a labs/lab12/isolation/modules.txt +sudo nerdctl run --rm --runtime io.containerd.kata.v2 alpine:3.19 sh -c "ls /sys/module 2>/dev/null | wc -l" | tee -a labs/lab12/isolation/modules.txt +``` + +In `labs/submission12.md`, document: + +**Task 3 Requirements:** +- Show dmesg output differences (Kata shows VM boot logs, proving separate kernel) +- Compare /proc filesystem visibility +- Show network interface configuration in Kata VM +- Compare kernel module counts (host vs guest VM) +- Explain isolation boundary differences: + - **runc**: ? + - **kata**: ? +- Discuss security implications: + - Container escape in runc = ? + - Container escape in Kata = ? + +--- + +### Task 4 โ€” Performance Comparison (2 pts) +โฑ๏ธ **Estimated time:** 10 minutes + +**Objective:** Compare startup time and overhead between runc and Kata. + +#### 4.1: Container startup time comparison + +```bash +echo "=== Startup Time Comparison ===" | tee labs/lab12/bench/startup.txt + +echo "runc:" | tee -a labs/lab12/bench/startup.txt +time sudo nerdctl run --rm alpine:3.19 echo "test" 2>&1 | grep real | tee -a labs/lab12/bench/startup.txt + +echo "Kata:" | tee -a labs/lab12/bench/startup.txt +time sudo nerdctl run --rm --runtime io.containerd.kata.v2 alpine:3.19 echo "test" 2>&1 | grep real | tee -a labs/lab12/bench/startup.txt +``` + +#### 4.2: HTTP response latency (juice-runc only) + +```bash +echo "=== HTTP Latency Test (juice-runc) ===" | tee labs/lab12/bench/http-latency.txt +out="labs/lab12/bench/curl-3012.txt" +: > "$out" + +for i in $(seq 1 50); do + curl -s -o /dev/null -w "%{time_total}\n" http://localhost:3012/ >> "$out" +done + +echo "Results for port 3012 (juice-runc):" | tee -a labs/lab12/bench/http-latency.txt +awk '{s+=$1; n+=1} END {if(n>0) printf "avg=%.4fs min=%.4fs max=%.4fs n=%d\n", s/n, min, max, n}' \ + min=$(sort -n "$out" | head -1) max=$(sort -n "$out" | tail -1) "$out" | tee -a labs/lab12/bench/http-latency.txt +``` + +In `labs/submission12.md`, document: + +**Task 4 Requirements:** +- Show startup time comparison (runc: <1s, Kata: 3-5s) +- Show HTTP latency for juice-runc baseline +- Analyze performance tradeoffs: + - **Startup overhead**: ? + - **Runtime overhead**: ? + - **CPU overhead**: ? +- Interpret when to use each: + - **Use runc when**: ? + - **Use Kata when**: ? + +--- + +## Acceptance Criteria + +- โœ… Kata shim installed and verified (`containerd-shim-kata-v2 --version`) +- โœ… containerd configured; runtime `io.containerd.kata.v2` used for `juice-kata` +- โœ… runc vs kata containers both reachable; environment differences captured +- โœ… Isolation tests executed and results summarized +- โœ… Basic latency snapshot recorded and discussed +- โœ… All artifacts saved under `labs/lab12/` and committed + +--- + +## Known Issues and Troubleshooting + +### nerdctl + Kata runtime-rs detached container issue + +**Symptom:** Long-running detached containers fail with: +``` +FATA[0001] failed to create shim task: Others("failed to handle message create container +Caused by: + 0: open stdout + 1: No such file or directory (os error 2) +``` + +**Root Cause:** Race condition in logging initialization between nerdctl and Kata runtime-rs v3. + +**Workarounds:** +1. Use short-lived/interactive containers (as in this lab) +2. Use Kubernetes with Kata (fully supported) +3. Use Docker with older Kata versions +4. Use containerd's `ctr` command directly + +**Status:** Known issue, fix expected in future releases. + +### Verifying Kata is working + +If you encounter issues, verify Kata basics: + +```bash +# Test simple execution +sudo nerdctl run --rm --runtime io.containerd.kata.v2 alpine:3.19 echo "Kata works" + +# Check kernel version (should be 6.12.47 or similar, NOT your host kernel) +sudo nerdctl run --rm --runtime io.containerd.kata.v2 alpine:3.19 uname -r + +# Check Kata shim +ls -la /usr/local/bin/containerd-shim-kata-v2 +containerd-shim-kata-v2 --version + +# Check containerd logs +sudo journalctl -u containerd -n 50 --no-pager | grep -i kata +``` + +--- + +## How to Submit + +1. Create a branch and push it to your fork: +```bash +git switch -c feature/lab12 +# create labs/submission12.md with your findings +git add labs/lab12/ labs/submission12.md +git commit -m "docs: add lab12 โ€” kata containers sandboxing" +git push -u origin feature/lab12 +``` +2. Open a PR from your forkโ€™s `feature/lab12` โ†’ course repoโ€™s `main`. +3. In the PR description include: +```text +- [x] Task 1 โ€” Kata install + runtime config +- [x] Task 2 โ€” runc vs kata runtime comparison +- [x] Task 3 โ€” Isolation tests +- [x] Task 4 โ€” Basic performance snapshot +``` +4. Submit the PR URL via Moodle before the deadline. + +--- + +## Rubric (10 pts) + +| Criterion | Points | +| ------------------------------------------------------ | -----: | +| Task 1 โ€” Install + Configure Kata | 2.0 | +| Task 2 โ€” Run and Compare (runc vs kata) | 3.0 | +| Task 3 โ€” Isolation Tests | 3.0 | +| Task 4 โ€” Performance Snapshot | 2.0 | +| Total | 10.0 | + +--- + +## Guidelines + +- Prefer non-privileged containers; avoid `--privileged` unless a test explicitly calls for it +- Use containerd+nerdctl with `io.containerd.kata.v2` per Kata 3 docs (Docker `--runtime=kata` is legacy) +- Nested virtualization must be enabled if inside a VM (check your cloud provider or hypervisor settings) +- Use clear, concise evidence in `submission12.md` and focus your analysis on isolation trade-offs vs operational overhead + +
+References + +- Kata Containers: https://github.com/kata-containers/kata-containers +- Install docs (Kata 3): https://github.com/kata-containers/kata-containers/tree/main/docs/install +- containerd runtime config: https://github.com/kata-containers/kata-containers/tree/main/docs + +
diff --git a/labs/lab12/analysis/cpu-comparison.txt b/labs/lab12/analysis/cpu-comparison.txt new file mode 100644 index 00000000..c5139f57 --- /dev/null +++ b/labs/lab12/analysis/cpu-comparison.txt @@ -0,0 +1,5 @@ +=== CPU Model Comparison === +Host CPU: +model name : 12th Gen Intel(R) Core(TM) i5-12450H +Kata VM CPU: +model name : Intel(R) Xeon(R) Processor diff --git a/labs/lab12/analysis/kernel-comparison.txt b/labs/lab12/analysis/kernel-comparison.txt new file mode 100644 index 00000000..ce556779 --- /dev/null +++ b/labs/lab12/analysis/kernel-comparison.txt @@ -0,0 +1,3 @@ +=== Kernel Version Comparison === +Host kernel (runc uses this): 6.15.4-200.fc42.x86_64 +Kata guest kernel: Linux version 6.12.47 (@4bcec8f4443d) (gcc (Ubuntu 11.4.0-1ubuntu1~22.04.2) 11.4.0, GNU ld (GNU Binutils for Ubuntu) 2.38) #1 SMP Fri Nov 14 15:34:06 UTC 2025 diff --git a/labs/lab12/bench/curl-3012.txt b/labs/lab12/bench/curl-3012.txt new file mode 100644 index 00000000..f1b469d4 --- /dev/null +++ b/labs/lab12/bench/curl-3012.txt @@ -0,0 +1,50 @@ +0.000190 +0.000220 +0.000336 +0.000386 +0.000377 +0.000395 +0.000391 +0.000473 +0.000410 +0.000407 +0.000356 +0.000344 +0.000337 +0.000347 +0.000361 +0.000361 +0.000333 +0.000292 +0.000237 +0.000215 +0.000284 +0.000301 +0.000209 +0.000185 +0.000243 +0.000219 +0.000201 +0.000188 +0.000183 +0.000361 +0.000340 +0.000479 +0.000356 +0.000312 +0.000334 +0.000338 +0.000344 +0.000337 +0.000378 +0.000332 +0.000270 +0.000234 +0.000186 +0.000179 +0.000262 +0.000157 +0.000140 +0.000167 +0.000248 +0.000324 diff --git a/labs/lab12/bench/http-latency.txt b/labs/lab12/bench/http-latency.txt new file mode 100644 index 00000000..ee01510a --- /dev/null +++ b/labs/lab12/bench/http-latency.txt @@ -0,0 +1,3 @@ +=== HTTP Latency Test (juice-runc) === +Results for port 3012 (juice-runc): +avg=0.0003s min=0.0001s max=0.0005s n=50 diff --git a/labs/lab12/bench/startup.txt b/labs/lab12/bench/startup.txt new file mode 100644 index 00000000..c2aa22db --- /dev/null +++ b/labs/lab12/bench/startup.txt @@ -0,0 +1,10 @@ +=== Startup Time Comparison === +runc: +real 0m0.599s +user 0m0.013s +sys 0m0.017s + +Kata: +real 0m6.664s +user 0m0.012s +sys 0m0.019s \ No newline at end of file diff --git a/labs/lab12/isolation/dmesg.txt b/labs/lab12/isolation/dmesg.txt new file mode 100644 index 00000000..3461998f --- /dev/null +++ b/labs/lab12/isolation/dmesg.txt @@ -0,0 +1,7 @@ +=== dmesg Access Test === +Kata VM (separate kernel boot logs): +time="2025-11-28T16:28:03+03:00" level=warning msg="cannot set cgroup manager to \"systemd\" for runtime \"io.containerd.kata.v2\"" +[ 0.000000] Linux version 6.12.47 (@4bcec8f4443d) (gcc (Ubuntu 11.4.0-1ubuntu1~22.04.2) 11.4.0, GNU ld (GNU Binutils for Ubuntu) 2.38) #1 SMP Fri Nov 14 15:34:06 UTC 2025 +[ 0.000000] Command line: reboot=k panic=1 systemd.unit=kata-containers.target systemd.mask=systemd-networkd.service root=/dev/vda1 rootflags=data=ordered,errors=remount-ro ro rootfstype=ext4 agent.container_pipe_size=1 console=ttyS1 agent.log_vport=1025 agent.passfd_listener_port=1027 virtio_mmio.device=8K@0xe0000000:5 virtio_mmio.device=8K@0xe0002000:5 +[ 0.000000] BIOS-provided physical RAM map: +[ 0.000000] BIOS-e820: [mem 0x0000000000000000-0x000000000009fbff] usable diff --git a/labs/lab12/isolation/modules.txt b/labs/lab12/isolation/modules.txt new file mode 100644 index 00000000..653a2968 --- /dev/null +++ b/labs/lab12/isolation/modules.txt @@ -0,0 +1,3 @@ +=== Kernel Modules Count === +Host kernel modules: 354 +Kata guest kernel modules: 72 diff --git a/labs/lab12/isolation/network.txt b/labs/lab12/isolation/network.txt new file mode 100644 index 00000000..eec24684 --- /dev/null +++ b/labs/lab12/isolation/network.txt @@ -0,0 +1,14 @@ +=== Network Interfaces === +Kata VM network: +1: lo: mtu 65536 qdisc noqueue state UNKNOWN qlen 1000 + link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 + inet 127.0.0.1/8 scope host lo + valid_lft forever preferred_lft forever + inet6 ::1/128 scope host noprefixroute + valid_lft forever preferred_lft forever +2: eth0: mtu 1500 qdisc pfifo_fast state UP qlen 1000 + link/ether 7a:70:25:f0:55:84 brd ff:ff:ff:ff:ff:ff + inet 10.4.0.13/24 brd 10.4.0.255 scope global eth0 + valid_lft forever preferred_lft forever + inet6 fe80::7870:25ff:fef0:5584/64 scope link tentative + valid_lft forever preferred_lft forever diff --git a/labs/lab12/isolation/proc.txt b/labs/lab12/isolation/proc.txt new file mode 100644 index 00000000..0ba079bd --- /dev/null +++ b/labs/lab12/isolation/proc.txt @@ -0,0 +1,3 @@ +=== /proc Entries Count === +Host: 528 +Kata VM: 53 diff --git a/labs/lab12/kata/cpu.txt b/labs/lab12/kata/cpu.txt new file mode 100644 index 00000000..042f3e32 --- /dev/null +++ b/labs/lab12/kata/cpu.txt @@ -0,0 +1 @@ +model name : Intel(R) Xeon(R) Processor diff --git a/labs/lab12/kata/kernel.txt b/labs/lab12/kata/kernel.txt new file mode 100644 index 00000000..785c4624 --- /dev/null +++ b/labs/lab12/kata/kernel.txt @@ -0,0 +1 @@ +6.12.47 diff --git a/labs/lab12/kata/test1.txt b/labs/lab12/kata/test1.txt new file mode 100644 index 00000000..3d2aa533 --- /dev/null +++ b/labs/lab12/kata/test1.txt @@ -0,0 +1 @@ +Linux 1ab865e5ba28 6.12.47 #1 SMP Fri Nov 14 15:34:06 UTC 2025 x86_64 Linux diff --git a/labs/lab12/runc/health.txt b/labs/lab12/runc/health.txt new file mode 100644 index 00000000..9bb7599c --- /dev/null +++ b/labs/lab12/runc/health.txt @@ -0,0 +1 @@ +juice-runc: HTTP 000 diff --git a/labs/lab12/scripts/configure-containerd-kata.sh b/labs/lab12/scripts/configure-containerd-kata.sh new file mode 100755 index 00000000..163133af --- /dev/null +++ b/labs/lab12/scripts/configure-containerd-kata.sh @@ -0,0 +1,94 @@ +#!/usr/bin/env bash +set -euo pipefail + +# configure-containerd-kata.sh +# Idempotently ensure containerd has the Kata runtime configured: +# [plugins."io.containerd.grpc.v1.cri".containerd.runtimes.kata] +# runtime_type = "io.containerd.kata.v2" +# +# Usage: +# sudo bash labs/lab12/scripts/configure-containerd-kata.sh + +CONF_DEFAULT="/etc/containerd/config.toml" +# Allow override via $CONF or first CLI arg +CONF="${CONF:-${1:-$CONF_DEFAULT}}" +TMP=$(mktemp) + +backup() { + if [ -f "$CONF" ]; then + cp -a "$CONF" "${CONF}.$(date +%Y%m%d%H%M%S).bak" + fi +} + +ensure_default() { + if [ ! -s "$CONF" ]; then + echo "Generating default containerd config at $CONF" >&2 + mkdir -p "$(dirname "$CONF")" + containerd config default > "$CONF" + fi +} + +detect_header() { + # Prefer v3 split-CRI path if present; otherwise fallback to grpc path + if grep -q "^\[plugins\.'io\.containerd\.cri\.v1\.runtime'\]" "$CONF"; then + echo "[plugins.'io.containerd.cri.v1.runtime'.containerd.runtimes.kata]" + else + echo "[plugins.'io.containerd.grpc.v1.cri'.containerd.runtimes.kata]" + fi +} + +insert_or_update_kata() { + local header + header=$(detect_header) + local value=" runtime_type = 'io.containerd.kata.v2'" + + # Process file: update runtime_type inside the kata table if it exists, + # otherwise append a new table at the end. + awk -v hdr="$header" -v val="$value" ' + BEGIN { inside=0; updated=0 } + { + if ($0 == hdr) { + print $0; inside=1; next + } + if (inside) { + if ($0 ~ /^\[/) { + if (!updated) print val + inside=0 + print $0 + next + } + if ($0 ~ /^\s*runtime_type\s*=\s*/){ + print val; updated=1; next + } + print $0; next + } + print $0 + } + END { + if (inside && !updated) { + print val + } else if (!inside && NR > 0) { + # Check if header ever appeared; if not, append it. + # We can infer by searching the output later, but simpler: do a second pass. + } + } + ' "$CONF" > "$TMP" + + if ! grep -qF "$header" "$TMP"; then + { + printf '\n%s\n%s\n' "$header" "$value" + } >> "$TMP" + fi + + install -m 0644 "$TMP" "$CONF" +} + +main() { + backup + ensure_default + insert_or_update_kata + echo "Updated $CONF with Kata runtime: io.containerd.kata.v2" >&2 + echo "Restart containerd to apply: sudo systemctl restart containerd" >&2 +} + +main "$@" diff --git a/labs/lab12/scripts/install-kata-assets.sh b/labs/lab12/scripts/install-kata-assets.sh new file mode 100755 index 00000000..c3c586d9 --- /dev/null +++ b/labs/lab12/scripts/install-kata-assets.sh @@ -0,0 +1,79 @@ +#!/usr/bin/env bash +set -euo pipefail + +# install-kata-assets.sh +# Download and install Kata Containers static assets (kernel, rootfs image, +# default runtime-rs configuration) under /opt/kata, and ensure a +# configuration file exists in an expected path for runtime-rs. +# +# Usage: +# sudo bash labs/lab12/scripts/install-kata-assets.sh [KATA_VER] +# +# Notes: +# - Requires: curl, jq, tar (with zstd support), and root privileges. +# - Creates or updates a symlink at: +# /etc/kata-containers/runtime-rs/configuration.toml +# pointing to the installed default configuration. + +VER_ARG=${1:-} +ARCH=$(uname -m) +case ${ARCH} in + x86_64) ARCH=amd64 ;; + aarch64|arm64) ARCH=arm64 ;; + *) echo "Unsupported architecture: $(uname -m)" >&2; exit 1 ;; +esac + +if [[ -n "${VER_ARG}" ]]; then + KATA_VER=$(echo "${VER_ARG}" | sed -E 's/^v//') +else + KATA_VER=$(curl -fsSL https://api.github.com/repos/kata-containers/kata-containers/releases/latest | jq -r .tag_name) + KATA_VER=${KATA_VER#v} +fi + +ASSET_URL="https://github.com/kata-containers/kata-containers/releases/download/${KATA_VER}/kata-static-${KATA_VER}-${ARCH}.tar.zst" + +echo "Installing Kata static assets ${KATA_VER} for ${ARCH}" >&2 +TMP_TAR=$(mktemp --suffix=.tar.zst) +curl -fL -o "${TMP_TAR}" "${ASSET_URL}" + +# Extract to root; archive lays files under /opt/kata, /usr/local/bin, etc. +# Prefer explicit decompressor if available to avoid tar invoking external zstd unexpectedly. +if command -v zstd >/dev/null 2>&1; then + zstd -d -c "${TMP_TAR}" | tar -xf - -C / +elif command -v unzstd >/dev/null 2>&1; then + unzstd -c "${TMP_TAR}" | tar -xf - -C / +elif tar --help 2>/dev/null | grep -q -- '--zstd'; then + tar --zstd -xf "${TMP_TAR}" -C / +else + echo "Missing zstd support to extract ${TMP_TAR}." >&2 + echo "Install the zstd package (e.g., sudo apt-get update && sudo apt-get install -y zstd) and re-run." >&2 + exit 1 +fi +rm -f "${TMP_TAR}" + +# Link configuration to an expected path for runtime-rs +sudo mkdir -p /etc/kata-containers/runtime-rs +SRC_CANDIDATES=( + "/opt/kata/share/defaults/kata-containers/runtime-rs/configuration-dragonball.toml" + "/opt/kata/share/defaults/kata-containers/configuration-dragonball.toml" + "/opt/kata/share/defaults/kata-containers/runtime-rs/configuration.toml" + "/usr/share/defaults/kata-containers/runtime-rs/configuration.toml" +) + +for src in "${SRC_CANDIDATES[@]}"; do + if [[ -f "$src" ]]; then + ln -sf "$src" /etc/kata-containers/runtime-rs/configuration.toml + echo "Linked runtime-rs config -> $src" >&2 + break + fi +done + +if [[ ! -f /etc/kata-containers/runtime-rs/configuration.toml ]]; then + echo "Warning: could not find a default runtime-rs configuration in known locations." >&2 + echo "Check /opt/kata/share/defaults/kata-containers/ and create: /etc/kata-containers/runtime-rs/configuration.toml" >&2 + exit 1 +fi + +echo "Kata assets installed. Restart containerd and test a kata container." >&2 +echo " sudo systemctl restart containerd" >&2 +echo " sudo nerdctl run --rm --runtime io.containerd.kata.v2 alpine:3.19 uname -a" >&2 diff --git a/labs/lab12/setup/build-kata-runtime.sh b/labs/lab12/setup/build-kata-runtime.sh new file mode 100644 index 00000000..b909a410 --- /dev/null +++ b/labs/lab12/setup/build-kata-runtime.sh @@ -0,0 +1,56 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Build Kata Containers 3.x Rust runtime (containerd-shim-kata-v2) +# inside a temporary Rust toolchain container, and place the binary +# into the provided output directory. This avoids installing build +# dependencies on the host. +# +# Usage: +# bash labs/lab12/setup/build-kata-runtime.sh +# # result: labs/lab12/setup/kata-out/containerd-shim-kata-v2 + +ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")"/../.. && pwd)" +WORK_DIR="${ROOT_DIR}/lab12/setup/kata-build" +OUT_DIR="${ROOT_DIR}/lab12/setup/kata-out" + +mkdir -p "${WORK_DIR}" "${OUT_DIR}" + +echo "Building Kata runtime in Docker..." >&2 +docker run --rm \ + -e CARGO_NET_GIT_FETCH_WITH_CLI=true \ + -v "${WORK_DIR}":/work \ + -v "${OUT_DIR}":/out \ + rust:1.75-bookworm bash -lc ' + set -euo pipefail + apt-get update && apt-get install -y --no-install-recommends \ + git make gcc pkg-config ca-certificates musl-tools libseccomp-dev && \ + update-ca-certificates || true + + # Ensure cargo/rustup are available + export PATH=/usr/local/cargo/bin:$PATH + rustc --version; cargo --version; rustup --version || true + + cd /work + if [ ! -d kata-containers ]; then + git clone --depth 1 https://github.com/kata-containers/kata-containers.git + fi + cd kata-containers/src/runtime-rs + + # Add MUSL target for static build expected by runtime Makefile + rustup target add x86_64-unknown-linux-musl || true + + # Build the runtime (shim v2) + make + + # Collect the produced binary + f=$(find target -type f -name containerd-shim-kata-v2 | head -n1) + if [ -z "$f" ]; then + echo "ERROR: built binary not found" >&2; exit 1 + fi + install -m 0755 "$f" /out/containerd-shim-kata-v2 + strip /out/containerd-shim-kata-v2 || true + /out/containerd-shim-kata-v2 --version || true + ' + +echo "Done. Binary saved to: ${OUT_DIR}/containerd-shim-kata-v2" >&2 diff --git a/labs/lab12/setup/kata-build/kata-containers b/labs/lab12/setup/kata-build/kata-containers new file mode 160000 index 00000000..8534afb9 --- /dev/null +++ b/labs/lab12/setup/kata-build/kata-containers @@ -0,0 +1 @@ +Subproject commit 8534afb9e8de3a529a537185f0fd55b66d9bc5d5 diff --git a/labs/lab12/setup/kata-built-version.txt b/labs/lab12/setup/kata-built-version.txt new file mode 100644 index 00000000..e1948b53 --- /dev/null +++ b/labs/lab12/setup/kata-built-version.txt @@ -0,0 +1 @@ +Kata Containers containerd shim (Rust): id: io.containerd.kata.v2, version: 3.23.0, commit: 8534afb9e8de3a529a537185f0fd55b66d9bc5d5 diff --git a/labs/lab12/setup/kata-out/containerd-shim-kata-v2 b/labs/lab12/setup/kata-out/containerd-shim-kata-v2 new file mode 100755 index 00000000..c8cad3d4 Binary files /dev/null and b/labs/lab12/setup/kata-out/containerd-shim-kata-v2 differ diff --git a/labs/lab2.md b/labs/lab2.md index 5e48d666..e66fb964 100644 --- a/labs/lab2.md +++ b/labs/lab2.md @@ -1,181 +1,189 @@ -# Lab 2 โ€” Threat Modeling (Threat Dragon + Threagile) +# Lab 2 โ€” Threat Modeling with Threagile ![difficulty](https://img.shields.io/badge/difficulty-beginnerโ€“intermediate-yellow) -![topic](https://img.shields.io/badge/topic-Threat%20Modeling%20%26%20Security%20Requirements-blue) +![topic](https://img.shields.io/badge/topic-Threat%20Modeling%20(Threagile)-blue) ![points](https://img.shields.io/badge/points-10-orange) -> **Goal:** Model the **OWASP Juice Shop `bkimminich/juice-shop:19.0.0`** deployment, identify top risks, and produce both a **diagram-first** and an **automation-first** threat model. -> **Deliverable:** A PR from `feature/lab2` with a Threat Dragon model + Threagile outputs and a short risk summary. +> **Goal:** Model OWASP Juice Shop (`bkimminich/juice-shop:v19.0.0`) deployment and generate an automation-first threat model with Threagile. +> **Deliverable:** A PR from `feature/lab2` to the course repo with `labs/submission2.md` containing Threagile outputs and risk analysis. Submit the PR link via Moodle. --- ## Overview In this lab you will practice: +- Creating an **as-code** model with **Threagile** and automatically generating **risk reports + diagrams** from YAML +- Making security-relevant model changes and demonstrating how they **impact the risk landscape** +- Analyzing threat model outputs and documenting security findings systematically -* Building a **data flow diagram (DFD)** and capturing threats with **OWASP Threat Dragon** (supports STRIDE and auto-suggests threats via a rule engine). -* Creating an **as-code** model with **Threagile** to automatically generate a **risk report + diagrams** from YAML (great for CI). - -> Keep using the Juice Shop from Lab 1 (`:19.0.0`). +> Keep using the Juice Shop from Lab 1 (`:19.0.0`) as your target application. --- ## Tasks -### Task 1 โ€” Threagile model & automated report (2 pts) - -**Objective:** Use the provided Threagile model to generate a PDF report + diagrams and document the results in `labs/submission2.md`. - -1. **Use the provided YAML** - -- `labs/lab2/threagile-model.yaml` is provided. Do not restructure it for this task. -- You may make a small change for the โ€œDelta Runโ€ step (e.g., switch one link to HTTPS). - -2. **Generate outputs (risks + diagrams + PDF)** - -Run Threagile against the model and write all artifacts into `lab2`: +### Task 1 โ€” Threagile Baseline Model (6 pts) - ```bash - docker run --rm -it -v "$(pwd)":/app/work threagile/threagile \ - -verbose \ - -model /app/work/labs/labs/lab2/threagile-model.yaml \ - -output /app/work/labs/lab2 \ - -generate-risks-excel=false \ - -generate-tags-excel=false - ``` +**Objective:** Use the provided Threagile model to generate a PDF report + diagrams and analyze the baseline risk posture. -What you get in `labs/lab2/`: +#### 1.1: Generate Baseline Threat Model -- `report.pdf` โ€” full PDF report (includes diagrams) generated by default. -- Diagrams: data-flow & data-asset diagrams (PNG). -- Risk outputs: `risks.json` and also `stats.json`, `technical-assets.json`. +```bash +mkdir -p labs/lab2/baseline labs/lab2/secure -3. **Create `labs/submission2.md`** +docker run --rm -v "$(pwd)":/app/work threagile/threagile \ + -model /app/work/labs/lab2/threagile-model.yaml \ + -output /app/work/labs/lab2/baseline \ + -generate-risks-excel=false -generate-tags-excel=false +``` -Include the following sections: +#### 1.2: Verify Generated Outputs -- Top 5 Risks (from `labs/lab2/risks.json`): create a table with columns โ€” Severity, Category, Asset, Likelihood, Impact. - - Ranking: Sort risks by these weights to pick the Top 5: - - Severity order: critical (5) > elevated (4) > high (3) > medium (2) > low (1) - - Likelihood order: very-likely (4) > likely (3) > possible (2) > unlikely (1) - - Impact order: high (3) > medium (2) > low (1) - - Composite score = Severity*100 + Likelihood*10 + Impact. Sort descending; use score to break ties. - - Practical way: - - Manual read: open `labs/lab2/risks.json`, scan fields `severity`, `exploitation_likelihood`, `exploitation_impact`, `category`, `most_relevant_technical_asset`, apply the weights above, and pick the top 5. -- **Delta Run**: change one thing in the YAML (e.g., set Reverse Proxy โ†’ App link to HTTPS), re-run, and paste a before/after of the relevant counts (e.g., unencrypted-communication dropped). Add a one-sentence reason why. +Expected files in `labs/lab2/baseline/`: +- `report.pdf` โ€” full PDF report (includes diagrams) +- Diagrams: data-flow & data-asset diagrams (PNG) +- Risk exports: `risks.json`, `stats.json`, `technical-assets.json` -4. **Deliverables** +#### 1.3: Risk Analysis and Documentation -Commit/push: +Calculate composite scores using these weights: +- Severity: critical (5) > elevated (4) > high (3) > medium (2) > low (1) +- Likelihood: very-likely (4) > likely (3) > possible (2) > unlikely (1) +- Impact: high (3) > medium (2) > low (1) +- **Composite score** = `Severity*100 + Likelihood*10 + Impact` -- `labs/lab2/threagile-model.yaml` -- `labs/lab2/*diagram*.png` (at least the data-flow diagram) -- `labs/submission2.md` (the write-up described above) +In `labs/submission2.md`, document: +- **Top 5 Risks** table with Severity, Category, Asset, Likelihood, Impact +- Risk ranking methodology and composite score calculations +- Analysis of critical security concerns identified +- Screenshots or references to generated diagrams -5. **Quality checklist (pass/fail hints)** +--- -- Report opens and diagrams render. -- Top 5 risks table present and legible; ties broken sensibly. -- Stats snapshot included (from `stats.json`). -- Clear overlap/difference vs Threat Dragon. -- Delta Run shows before/after evidence and a short explanation. +### Task 2 โ€” HTTPS Variant & Risk Comparison (4 pts) + +**Objective:** Create a secure variant of the model and demonstrate how security controls affect the threat landscape. + +#### 2.1: Create Secure Model Variant + +Copy the baseline model and make these specific changes: +- **User Browser โ†’ communication_links โ†’ Direct to App**: set `protocol: https` +- **Reverse Proxy โ†’ communication_links**: set `protocol: https` +- **Persistent Storage**: set `encryption: transparent` +- Save as: `labs/lab2/threagile-model.secure.yaml` + +#### 2.2: Generate Secure Variant Analysis + +```bash +docker run --rm -v "$(pwd)":/app/work threagile/threagile \ + -model /app/work/labs/lab2/threagile-model.secure.yaml \ + -output /app/work/labs/lab2/secure \ + -generate-risks-excel=false -generate-tags-excel=false +``` + +#### 2.3: Generate Risk Comparison + +```bash +jq -n \ + --slurpfile b labs/lab2/baseline/risks.json \ + --slurpfile s labs/lab2/secure/risks.json ' +def tally(x): +(x | group_by(.category) | map({ (.[0].category): length }) | add) // {}; +(tally($b[0])) as $B | +(tally($s[0])) as $S | +(($B + $S) | keys | sort) as $cats | +[ +"| Category | Baseline | Secure | ฮ” |", +"|---|---:|---:|---:|" +] + ( +$cats | map( +"| " + . + " | " + +(($B[.] // 0) | tostring) + " | " + +(($S[.] // 0) | tostring) + " | " + +(((($S[.] // 0) - ($B[.] // 0))) | tostring) + " |" +) +) | .[]' +``` + +In `labs/submission2.md`, document: +- **Risk Category Delta Table** (Baseline vs Secure vs ฮ”) +- **Delta Run Explanation** covering: + - Specific changes made to the model + - Observed results in risk categories + - Analysis of why these changes reduced/modified risks +- Comparison of diagrams between baseline and secure variants -> Resources: Threagile site (auto risk rules, diagrams, CI-friendly), CLI usage (Docker examples), sample outputs. ([threagile.io][3], [GitHub][6], [juanvvc.github.io][4]) --- -### Task 2 โ€” Threat Dragon Web Model (4 pts) +## How to Submit -**Objective:** Create a diagram-based threat model of your local Juice Shop setup using the web UI at `threatdragon.com`, and extract the top 5 risks. +1. Create a branch for this lab and push it to your fork: -1. **Use the Threat Dragon web UI** - - Go to `threatdragon.com` โ†’ New Model (GitHub login required). - - Select a repo/branch where models are stored (optional). - - Provide metadata: title = โ€œJuice Shop Labโ€, owner = your GitHub handle. - - Add a diagram: place trust boundaries, actors, components, and flows. - - Assign STRIDE categories to each element/flow (via the properties pane). - - Run the rule engine and review auto-generated threats. - - Triage: keep, edit, or drop threats. Add mitigation notes (e.g., TLS via proxy, authz on sensitive routes, rate limiting). + ```bash + git switch -c feature/lab2 + # create labs/submission2.md with your findings + git add labs/submission2.md labs/lab2/ + git commit -m "docs: add lab2 submission" + git push -u origin feature/lab2 + ``` -2. **Model the deployment (minimum elements)** - - **Actors:** User (Browser), Attacker (Internet) - - **Components:** Reverse Proxy (optional), Juice Shop Container (`:19.0.0`), Persistent Storage (e.g., container volume), Email/SMS provider (if configured) - - **Flows:** - - `HTTP 3000/tcp` Browser โ†” Juice Shop (or Browser โ†” Proxy โ†” Juice Shop) - - Outbound flows from Juice Shop (Email/SMS API, webhook, etc.) - - Persistent storage โ†” Juice Shop - - **Trust Boundaries:** Internet โ‡ข Host; Host โ‡ข Container Network +2. Open a PR from your fork's `feature/lab2` branch โ†’ **course repository's main branch**. -3. **Folder & files** - - Create in your repo: - - `labs/lab2/threat-dragon.json` โ€” download/export the JSON model from the web UI. - - `labs/lab2/dfd.png` โ€” export your diagram as PNG/SVG. - - `labs/lab2/THREATS.md` โ€” markdown summary of your top risks. +3. In the PR description, include: -4. **Write `labs/lab2/THREATS.md`** - - **Top 5 risks:** one-liners with STRIDE tags (e.g., โ€œInjection [Tampering] โ€” unsanitized input can corrupt DBโ€). - - Cross-check vs Threagile: 2 overlaps + 1 difference (one-liners). + ```text + - [x] Task 1 done โ€” Threagile baseline model + risk analysis + - [x] Task 2 done โ€” HTTPS variant + risk comparison + ``` -> Resources: Threat Dragon docs & project page (DFDs, STRIDE, rule engine, desktop/web options). +4. **Copy the PR URL** and submit it via **Moodle before the deadline**. --- -### Bonus โ€” GitHub Social Interactions (optional) - -**Objective**: Explore GitHubโ€™s social features and how they support collaboration. +## Acceptance Criteria -1. Star the course repository. -2. Follow your professor, TAs, and at least 3 classmates. -3. In `labs/submission2.md`, add 1โ€“2 sentences on why stars/follows matter in open source and team projects. +- โœ… Branch `feature/lab2` exists with commits for each task +- โœ… File `labs/submission2.md` contains required analysis for Tasks 1-2 +- โœ… Threagile baseline and secure models successfully generated +- โœ… Both `labs/lab2/baseline/` and `labs/lab2/secure/` folders contain complete outputs +- โœ… Top 5 risks analysis and risk category delta comparison documented +- โœ… PR from `feature/lab2` โ†’ **course repo main branch** is open +- โœ… PR link submitted via Moodle before the deadline --- -### Acceptance Criteria +## Rubric (10 pts) -* โœ… `labs/lab2/threat-dragon.json` exported and `labs/lab2/dfd.png` exported (diagram shows actors, Juice Shop container, flows, and trust boundaries). -* โœ… `labs/lab2/THREATS.md` lists **Top 5** STRIDE-tagged risks. -* โœ… `labs/lab2/threagile-model.yaml` models the same architecture at a reasonable fidelity. -* โœ… `labs/lab2/*diagram*.png` includes at least the data-flow diagram. -* โœ… `labs/submission2.md` includes: Artifacts list, Top 5 risks table, Stats snapshot, 2 overlaps + 1 difference Threagile vs Threat Dragon, and a Delta Run with before/after evidence. -* โœ… PR from `feature/lab2` โ†’ `main` is open with artifacts attached/linked in the description. +| Criterion | Points | +| ------------------------------------------------------------ | -----: | +| Task 1 โ€” Threagile baseline model + risk analysis | **6** | +| Task 2 โ€” HTTPS variant + risk comparison analysis | **4** | +| **Total** | **10** | --- -## How to Submit +## Guidelines -1. Create `feature/lab2`, commit the new files, push, and open a PR. -2. In the PR description, fill your template sections and include: +- Use clear Markdown headers to organize sections in `submission2.md` +- Include both command outputs and written analysis for each task +- Document threat modeling process and security findings systematically +- Ensure all generated artifacts are properly committed to the repository - ```text - - [x] Task 1: Threagile YAML + report + diagrams + submission2.md - - [x] Task 2: Threat Dragon model + THREATS.md - ``` +
+Threat Modeling Notes ---- +- Model exactly the architecture you're running from Lab 1 (localhost deployment) +- Use consistent asset/link names between baseline and secure models for accurate diffs +- Focus on actionable security insights rather than comprehensive risk catalogs -## Rubric (10 pts) +
-| Criterion | Points | -| ------------------------------------------------------------------ | -----: | -| Task 1 โ€” Threat Dragon DFD + **Top 5** risks in `THREATS.md` | **6** | -| Task 2 โ€” Threagile YAML + generated report/diagrams + submission2 | **4** | -| **Total** | **10** | +
+Technical Tips ---- - -## Hints - -> ๐Ÿงญ **Model the lab reality.** Use exactly the architecture youโ€™re running from Lab 1 (localhost, optional proxy). -> ๐Ÿง  **Threat Dragon tip:** Start with STRIDE per **flow** first (S/T/I for auth, R/E for data tampering/DoS), then per **asset**. The toolโ€™s rule engine can suggest threats you can triage. ([OWASP][5]) -> โš™๏ธ **Threagile flags:** You can generate a stub (`-create-stub-model`), list enums (`-list-types`), and run analysis with `-model ... -output ...`; it emits report/DFDs and risk exportsโ€”handy for CI. ([Go Packages][1], [Kali Linux Tutorials][2]) -> ๐Ÿ“‘ **Keep it short:** One-page summaries beat walls of textโ€”use bullets and link the artifacts. -> ๐Ÿ” **Consistent IDs:** Use the same risk names/IDs across both tasks where they overlapโ€”this helps later when we create CI gates and dashboards. - ---- +- Verify report PDFs open correctly and diagrams render properly +- Use the provided jq command exactly as shown for consistent delta tables +- Keep explanations conciseโ€”one-page summaries are more valuable than detailed reports +- Check that Threagile Docker container has proper file permissions for output generation -[1]: https://pkg.go.dev/github.com/threagile/threagile?utm_source=chatgpt.com "threagile command - github.com/threagile/threagile - Go ... - Go Packages" -[2]: https://kalilinuxtutorials.com/threagile/?utm_source=chatgpt.com "Threagile : Agile Threat Modeling Toolkit 2020!Kalilinuxtutorials" -[3]: https://threagile.io/?utm_source=chatgpt.com "Threagile โ€” Agile Threat Modeling Toolkit" -[4]: https://juanvvc.github.io/securecoding/images/threatmod/threagile/report.pdf?utm_source=chatgpt.com "Threat Model Report: Some Example Application" -[5]: https://owasp.org/www-project-threat-dragon/?utm_source=chatgpt.com "OWASP Threat Dragon" -[6]: https://github.com/Threagile/threagile "GitHub - Threagile/threagile: Agile Threat Modeling Toolkit" -[7]: https://github.com/Threagile/threagile/blob/master/demo/example/threagile.yaml "threagile/demo/example/threagile.yaml at master - GitHub" +
diff --git a/labs/lab2/threagile-model.yaml b/labs/lab2/threagile-model.yaml index aa0f6b18..85c01a79 100644 --- a/labs/lab2/threagile-model.yaml +++ b/labs/lab2/threagile-model.yaml @@ -1,76 +1,60 @@ threagile_version: 1.0.0 -title: OWASP Juice Shop โ€” Local Lab Threat Model -date: 2025-09-07 +title: OWASP Juice Shop โ€” Local Lab Threat Model +date: 2025-09-18 author: name: Student Name homepage: https://example.edu management_summary_comment: > - Threat model for a local OWASP Juice Shop setup. Users access the app - either directly on HTTP 3000/tcp or via an optional reverse proxy that - terminates TLS and adds security headers. The app runs in a container - and may write to a host-mounted volume. Optional outbound notifications - use an external Email/SMS provider or generic webhook endpoints. + Threat model for a local OWASP Juice Shop setup. Users access the app + either directly via HTTP on port 3000 or through an optional reverse proxy that + terminates TLS and adds security headers. The app runs in a container + and writes data to a host-mounted volume (for database, uploads, logs). + Optional outbound notifications (e.g., a challenge-solution WebHook) can be configured for integrations. -business_criticality: important # archive, operational, important, critical, mission-critical +business_criticality: important # archive, operational, important, critical, mission-critical business_overview: description: > - Training environment for DevSecOps. The goal is to model risks for a - deliberately vulnerable web app (OWASP Juice Shop) running locally in - a container. Focus on minimal architecture, STRIDE thinking, and - actionable mitigations. + Training environment for DevSecOps. This model covers a deliberately vulnerable + web application (OWASP Juice Shop) running locally in a Docker container. The focus is on a minimal architecture, STRIDE threat analysis, and actionable mitigations for the identified risks. images: - # - dfd.png: Data Flow Diagram exported from the tool + # - dfd.png: Data Flow Diagram (if exported from the tool) technical_overview: description: > - Browser (user) connects to Juice Shop (Node.js) on localhost:3000 - or via a reverse proxy on 443/80. Juice Shop can call external - services (Email/SMS provider, webhooks). Logs and files may persist - on a host volume. Trust boundaries: Internet โ†’ Host โ†’ Container network. + A userโ€™s web browser connects to the Juice Shop application (Node.js/Express server) either directly on **localhost:3000** (HTTP) or via a **reverse proxy** on ports 80/443 (with HTTPS). The Juice Shop server may issue outbound requests to external services (e.g., a configured **WebHook** for solved challenge notifications). All application data (the SQLite database, file uploads, logs) is stored on the hostโ€™s filesystem via a mounted volume. Key trust boundaries include the **Internet** (user & external services) โ†’ **Host** (local machine/VM) โ†’ **Container Network** (isolated app container). images: [] questions: Do you expose port 3000 beyond localhost?: "" Do you use a reverse proxy with TLS and security headers?: "" - Are outbound notifications (email/webhook) configured?: "" + Are any outbound integrations (webhooks) configured?: "" Is any sensitive data stored in logs or files?: "" abuse_cases: Credential Stuffing / Brute Force: > - Attackers attempt repeated logins to exhaust resources or guess valid credentials. + Attackers attempt repeated login attempts to guess credentials or exhaust system resources. Stored XSS via Product Reviews: > - Malicious payloads stored and executed in other users' browsers. - SSRF via Webhook Targets: > - Outbound webhooks abused to pivot to internal endpoints. + Malicious scripts are inserted into product reviews, getting stored and executed in other usersโ€™ browsers. + SSRF via Outbound Requests: > + Server-side requests (e.g. profile image URL fetch or WebHook callback) are abused to access internal network resources. security_requirements: - TLS in transit: Enforce HTTPS for user traffic via reverse proxy with strong ciphers. - AuthZ on sensitive routes: Enforce role/permission checks server-side. - Rate limiting & lockouts: Prevent brute force/login abuse; protect expensive endpoints. - Secure headers: Add HSTS, CSP, X-Frame-Options, X-Content-Type-Options at proxy. - Secrets management: Keep tokens/credentials out of repo and logs. + TLS in transit: Enforce HTTPS for user traffic via a TLS-terminating reverse proxy with strong ciphers and certificate management. + AuthZ on sensitive routes: Implement strict server-side authorization checks (role/permission) on admin or sensitive functionalities. + Rate limiting & lockouts: Apply rate limiting and account lockout policies to mitigate brute-force and automated attacks on authentication and expensive operations. + Secure headers: Add security headers (HSTS, CSP, X-Frame-Options, X-Content-Type-Options, etc.) at the proxy or app to mitigate client-side attacks. + Secrets management: Protect secret keys and credentials (JWT signing keys, OAuth client secrets) โ€“ keep them out of code repos and avoid logging them. -# Tags are optional helpers; keep as-is or extend tags_available: - # infra / tools + # Relevant technologies and environment tags - docker - - git - - kubernetes - nodejs - - tomcat - - aws - - aws:iam - - aws:rds - - aws:s3 - - gcp - - azure - - # from your model (data & assets) + # Data and asset tags - pii - auth - tokens @@ -78,23 +62,18 @@ tags_available: - public - actor - user - - attacker - optional - proxy - app - storage - volume - saas - - notifications - webhook + # Communication tags - primary - direct - egress - # leftovers from the stub (optional to keep or remove) - - some-tag - - some-other-tag - # ========================= # DATA ASSETS # ========================= @@ -102,9 +81,9 @@ data_assets: User Accounts: id: user-accounts - description: "Profiles, credential hashes, emails." + description: "User profile data, credential hashes, emails." usage: business - tags: ["pii","auth"] + tags: ["pii", "auth"] origin: user-supplied owner: Lab Owner quantity: many @@ -112,11 +91,11 @@ data_assets: integrity: critical availability: important justification_cia_rating: > - PII and auth data require confidentiality; integrity critical to prevent takeover. + Contains personal identifiers and authentication data. High confidentiality is required to protect user privacy, and integrity is critical to prevent account takeovers. Orders: id: orders - description: "Order history, addresses, payment metadata (no PAN stored)." + description: "Order history, addresses, and payment metadata (no raw card numbers)." usage: business tags: ["pii"] origin: application @@ -126,11 +105,11 @@ data_assets: integrity: important availability: important justification_cia_rating: > - Contains personal data and business records. + Contains usersโ€™ personal data and business transaction records. Integrity and confidentiality are important to prevent fraud or privacy breaches. Product Catalog: id: product-catalog - description: "Public product info: names, prices, descriptions." + description: "Product information (names, descriptions, prices) available to all users." usage: business tags: ["public"] origin: application @@ -140,13 +119,13 @@ data_assets: integrity: important availability: important justification_cia_rating: > - Integrity matters to avoid fraud/manipulation of prices. + Product data is intended to be public, but its integrity is important (to avoid defacement or price manipulation that could mislead users). Tokens & Sessions: id: tokens-sessions - description: "Session IDs, JWTs, CSRF tokens." + description: "Session identifiers, JWTs for authenticated sessions, CSRF tokens." usage: business - tags: ["auth","tokens"] + tags: ["auth", "tokens"] origin: application owner: Lab Owner quantity: many @@ -154,11 +133,11 @@ data_assets: integrity: important availability: important justification_cia_rating: > - Compromise leads to account takeover. + If session tokens are compromised, attackers can hijack user sessions. They must be kept confidential and intact; availability is less critical (tokens can be reissued). Logs: id: logs - description: "App/access logs (may accidentally contain PII/secrets)." + description: "Application and access logs (may inadvertently contain PII or secrets)." usage: devops tags: ["logs"] origin: application @@ -168,7 +147,7 @@ data_assets: integrity: important availability: important justification_cia_rating: > - Operational value; ensure redaction to avoid leakage. + Logs are for internal use (troubleshooting, monitoring). They should not be exposed publicly, and sensitive data should be sanitized to protect confidentiality. # ========================= # TECHNICAL ASSETS @@ -177,7 +156,7 @@ technical_assets: User Browser: id: user-browser - description: "End-user web browser." + description: "End-user web browser (client)." type: external-entity usage: business used_as_client_by_human: true @@ -185,15 +164,15 @@ technical_assets: justification_out_of_scope: size: system technology: browser - tags: ["actor","user"] + tags: ["actor", "user"] internet: true machine: virtual encryption: none - owner: External Users + owner: External User confidentiality: public integrity: operational availability: operational - justification_cia_rating: "UI client." + justification_cia_rating: "Client controlled by end user (potentially an attacker)." multi_tenant: false redundant: false custom_developed_parts: false @@ -204,8 +183,8 @@ technical_assets: communication_links: To Reverse Proxy (preferred): target: reverse-proxy - description: "User to reverse proxy (HTTPS 443)." - protocol: http + description: "User browser to reverse proxy (HTTPS on 443)." + protocol: https authentication: session-id authorization: enduser-identity-propagation tags: ["primary"] @@ -217,9 +196,9 @@ technical_assets: - tokens-sessions data_assets_received: - product-catalog - Direct To App (no proxy): + Direct to App (no proxy): target: juice-shop - description: "Direct access to app (HTTP 3000)." + description: "Direct browser access to app (HTTP on 3000)." protocol: http authentication: session-id authorization: enduser-identity-propagation @@ -235,7 +214,7 @@ technical_assets: Reverse Proxy: id: reverse-proxy - description: "Optional reverse proxy with TLS termination & security headers." + description: "Optional reverse proxy (e.g., Nginx) for TLS termination and adding security headers." type: process usage: business used_as_client_by_human: false @@ -243,7 +222,7 @@ technical_assets: justification_out_of_scope: size: application technology: reverse-proxy - tags: ["optional","proxy"] + tags: ["optional", "proxy"] internet: false machine: virtual encryption: transparent @@ -251,7 +230,7 @@ technical_assets: confidentiality: internal integrity: important availability: important - justification_cia_rating: "Controls ingress, adds TLS and headers." + justification_cia_rating: "Not exposed to internet directly; improves security of inbound traffic." multi_tenant: false redundant: false custom_developed_parts: false @@ -264,7 +243,7 @@ technical_assets: communication_links: To App: target: juice-shop - description: "Proxy to app (HTTP 3000)." + description: "Proxy forwarding to app (HTTP on 3000 internally)." protocol: http authentication: none authorization: none @@ -278,9 +257,9 @@ technical_assets: data_assets_received: - product-catalog - Juice Shop: + Juice Shop Application: id: juice-shop - description: "OWASP Juice Shop application (Node.js, v19.0.0)." + description: "OWASP Juice Shop server (Node.js/Express, v19.0.0)." type: process usage: business used_as_client_by_human: false @@ -288,7 +267,7 @@ technical_assets: justification_out_of_scope: size: application technology: web-server - tags: ["app","nodejs"] + tags: ["app", "nodejs"] internet: false machine: container encryption: none @@ -296,7 +275,7 @@ technical_assets: confidentiality: internal integrity: important availability: important - justification_cia_rating: "Business-facing app with deliberate vulns for learning." + justification_cia_rating: "In-scope web application (contains all business logic and vulnerabilities by design)." multi_tenant: false redundant: false custom_developed_parts: true @@ -310,23 +289,9 @@ technical_assets: data_formats_accepted: - json communication_links: - To Email/SMS Provider: - target: email-sms-provider - description: "Outbound notifications to provider." - protocol: https - authentication: token - authorization: technical-user - tags: ["egress"] - vpn: false - ip_filtered: false - readonly: false - usage: business - data_assets_sent: - - user-accounts - - orders - To Webhook Endpoint: + To Challenge WebHook: target: webhook-endpoint - description: "Optional outbound webhooks." + description: "Optional outbound callback (HTTP POST) to external WebHook when a challenge is solved." protocol: https authentication: none authorization: none @@ -340,7 +305,7 @@ technical_assets: Persistent Storage: id: persistent-storage - description: "Host-mounted volume for logs/uploads." + description: "Host-mounted volume for database, file uploads, and logs." type: datastore usage: devops used_as_client_by_human: false @@ -348,7 +313,7 @@ technical_assets: justification_out_of_scope: size: component technology: file-server - tags: ["storage","volume"] + tags: ["storage", "volume"] internet: false machine: virtual encryption: none @@ -356,66 +321,39 @@ technical_assets: confidentiality: internal integrity: important availability: important - justification_cia_rating: "Operational data; may contain sensitive info if misconfigured." + justification_cia_rating: "Local disk storage for the container โ€“ not directly exposed, but if compromised it contains sensitive data (database and logs)." multi_tenant: false redundant: false custom_developed_parts: false data_assets_processed: [] data_assets_stored: - logs - data_formats_accepted: - - file - communication_links: {} - - Email/SMS Provider: - id: email-sms-provider - description: "External Email/SMS API provider." - type: external-entity - usage: business - used_as_client_by_human: false - out_of_scope: true - justification_out_of_scope: "Third-party service." - size: system - technology: web-service-rest - tags: ["saas","notifications"] - internet: true - machine: virtual - encryption: none - owner: Third Party - confidentiality: internal - integrity: important - availability: important - justification_cia_rating: "Handles notifications; sensitive addresses may be transmitted." - multi_tenant: true - redundant: true - custom_developed_parts: false - data_assets_processed: - user-accounts - orders - data_assets_stored: [] + - product-catalog data_formats_accepted: - - json + - file communication_links: {} Webhook Endpoint: id: webhook-endpoint - description: "3rd-party webhook receiver (if configured)." + description: "External WebHook service (3rd-party, if configured for integrations)." type: external-entity usage: business used_as_client_by_human: false out_of_scope: true - justification_out_of_scope: "Third-party sink." + justification_out_of_scope: "Third-party service to receive notifications (not under our control)." size: system - technology: web-service-rest - tags: ["saas","webhook"] + technology: web-service-rest + tags: ["saas", "webhook"] internet: true machine: virtual encryption: none - owner: Third Party + owner: Third-Party confidentiality: internal integrity: operational availability: operational - justification_cia_rating: "Potential egress path; validate destinations." + justification_cia_rating: "External service that receives data (like order or challenge info). Treated as a trusted integration point but could be abused if misconfigured." multi_tenant: true redundant: true custom_developed_parts: false @@ -433,19 +371,18 @@ trust_boundaries: Internet: id: internet - description: "Public Internet zone." + description: "Untrusted public network (Internet)." type: network-dedicated-hoster tags: [] technical_assets_inside: - user-browser - - email-sms-provider - webhook-endpoint trust_boundaries_nested: - host Host: id: host - description: "Host OS/VM running Docker." + description: "Local host machine / VM running the Docker environment." type: network-dedicated-hoster tags: [] technical_assets_inside: @@ -456,7 +393,7 @@ trust_boundaries: Container Network: id: container-network - description: "Docker bridge network." + description: "Docker container network (isolated internal network for containers)." type: network-dedicated-hoster tags: [] technical_assets_inside: @@ -470,11 +407,11 @@ shared_runtimes: Docker Host: id: docker-host - description: "Docker daemon and bridge network." + description: "Docker Engine and default bridge network on the host." tags: ["docker"] technical_assets_running: - juice-shop - # add reverse-proxy here if you run it as a container: + # If the reverse proxy is containerized, include it: # - reverse-proxy # ========================= @@ -487,6 +424,6 @@ individual_risk_categories: {} # ========================= risk_tracking: {} -# diagram tweaks (optional) +# (Optional diagram layout tweaks can be added here) #diagram_tweak_edge_layout: spline #diagram_tweak_layout_left_to_right: true diff --git a/labs/lab3.md b/labs/lab3.md index bfa0c93f..47ec06df 100644 --- a/labs/lab3.md +++ b/labs/lab3.md @@ -1,22 +1,20 @@ # Lab 3 โ€” Secure Git ![difficulty](https://img.shields.io/badge/difficulty-beginner-success) -![topic](https://img.shields.io/badge/topic-DevOps%20Basics-blue) +![topic](https://img.shields.io/badge/topic-Secure%20Git-blue) ![points](https://img.shields.io/badge/points-10-orange) -> **Goal:** Practice secure Git fundamentals: signed commits, pre-commit secret scanning, and standardized PRs. -> **Deliverable:** A PR from `feature/lab3` with all checklist items completed. +> **Goal:** Practice secure Git fundamentals: signed commits and pre-commit secret scanning. +> **Deliverable:** A PR from `feature/lab3` to the course repo with `labs/submission3.md` containing secure Git practices implementation. Submit the PR link via Moodle. --- ## Overview In this lab you will practice: -- Verifying commit authenticity with **SSH commit signing**. -- Preventing secrets with **pre-commit scanning** (TruffleHog + Gitleaks). -- Standardizing collaboration with a **PR template & checklist**. - -These are the foundation of collaboration and trust in DevOps teams. +- Verifying commit authenticity with **SSH commit signing** +- Preventing secrets exposure with **pre-commit scanning** (TruffleHog + Gitleaks) +- Implementing automated security controls in development workflows --- @@ -24,177 +22,244 @@ These are the foundation of collaboration and trust in DevOps teams. ### Task 1 โ€” SSH Commit Signature Verification (5 pts) -**Objective:** Understand the importance of signed commits and set up SSH commit signature verification. - -1. **Explore the Importance of Signed Commits** - - Research why commit signing is crucial for verifying the integrity and authenticity of commits. - - Resources: - - [GitHub Docs on SSH Commit Verification](https://docs.github.com/en/authentication/managing-commit-signature-verification/about-commit-signature-verification) - - [Atlassian Guide to SSH and Git](https://confluence.atlassian.com/bitbucketserver/sign-commits-and-tags-with-ssh-keys-1305971205.html) - - Create a file `labs/submission3.md` with a short summary explaining the benefits of signing commits. - -2. **Set Up SSH Commit Signing** - - **Option 1:** Use an existing SSH key and add it to GitHub. - - **Option 2 (recommended):** Generate a new key (ed25519) - ```sh - ssh-keygen -t ed25519 -C "your_email@example.com" - ``` - Then add the public key to your GitHub account. - - - Configure Git to use your SSH key for signing: - ```sh - git config --global user.signingkey - git config --global commit.gpgSign true - git config --global gpg.format ssh - ``` - -3. **Make a Signed Commit** - - Create and sign a commit with your `submission3.md` file: - ```sh - git commit -S -m "docs: add commit signing summary" - ``` - - Push this commit to your `feature/lab3` branch. +**Objective:** Configure SSH commit signing to verify commit authenticity and integrity. ---- -### Task 2 โ€” Pre-commit Hooks (4 pts) - -**Objective:** Add a local Git pre-commit hook that scans staged changes for secrets using Dockerized TruffleHog and Gitleaks. The commit must be blocked if any secrets are found. - -1. Create the pre-commit hook file - - Path: `.git/hooks/pre-commit` - - Contents: - ```bash - #!/usr/bin/env bash - set -euo pipefail - - echo "[pre-commit] scanning staged files for secretsโ€ฆ" - - # Collect staged files (added/changed) - mapfile -t STAGED < <(git diff --cached --name-only --diff-filter=ACM) - if [ ${#STAGED[@]} -eq 0 ]; then - echo "[pre-commit] no staged files; skipping scans" - exit 0 - fi - - # Limit to existing regular files only - FILES=() - for f in "${STAGED[@]}"; do - [ -f "$f" ] && FILES+=("$f") - done - if [ ${#FILES[@]} -eq 0 ]; then - echo "[pre-commit] no regular files to scan; skipping" - exit 0 - fi - - # Run TruffleHog (Docker) against staged files - echo "[pre-commit] TruffleHog scanโ€ฆ" - docker run --rm \ - -v "$PWD:/repo" -w /repo \ - trufflesecurity/trufflehog:latest \ - filesystem --fail --only-verified --json "${FILES[@]}" >/dev/null || { - echo "\nโœ– TruffleHog detected potential secrets in staged changes." >&2 - echo "Fix or unstage the offending files and try again." >&2 - exit 1 - } - - # Run Gitleaks (Docker) against staged changes - echo "[pre-commit] Gitleaks scanโ€ฆ" - docker run --rm \ - -v "$PWD:/repo" -w /repo \ - zricethezav/gitleaks:latest \ - detect --staged --redact --exit-code 1 --no-banner >/dev/null || { - echo "\nโœ– Gitleaks detected potential secrets in staged changes." >&2 - echo "Fix or unstage the offending files and try again." >&2 - exit 1 - } - - echo "โœ“ No secrets detected; proceeding with commit." - exit 0 - ``` - -2. Make the hook executable - ```bash - chmod +x .git/hooks/pre-commit +#### 1.1: Research Commit Signing Benefits + +Study why commit signing is crucial for verifying the integrity and authenticity of commits: +- [GitHub Docs on SSH Commit Verification](https://docs.github.com/en/authentication/managing-commit-signature-verification/about-commit-signature-verification) +- [Atlassian Guide to SSH and Git](https://confluence.atlassian.com/bitbucketserver/sign-commits-and-tags-with-ssh-keys-1305971205.html) + +#### 1.2: Configure SSH Commit Signing + +1. **Generate SSH Key (Option A - Recommended):** + + ```sh + ssh-keygen -t ed25519 -C "your_email@example.com" ``` -3. Verify the hook blocks secrets - - Add a test secret (e.g., a fake AWS key) to a file, stage it, and try to commit. The commit should be blocked by TruffleHog or Gitleaks. - - Remove/redact the secret or unstage the file, then commit again to confirm it succeeds. +2. **Use Existing SSH Key (Option B):** + + Use an existing SSH key and add it to GitHub + +3. **Configure Git for SSH Signing:** + + ```sh + git config --global user.signingkey + git config --global commit.gpgSign true + git config --global gpg.format ssh + ``` + +#### 1.3: Create Signed Commit + +```sh +git commit -S -m "docs: add commit signing summary" +``` + +In `labs/submission3.md`, document: +- Summary explaining the benefits of signing commits for security +- Evidence of successful SSH key setup and configuration +- Analysis: "Why is commit signing critical in DevSecOps workflows?" +- Screenshots or verification of the "Verified" badge on GitHub --- -### Task 3 โ€” PR Template & Checklist (1 pt) -**Objective:** Standardize pull requests with a reusable template so reviewers see the same sections and a clear checklist every time. +### Task 2 โ€” Pre-commit Secret Scanning (5 pts) -> โš ๏ธ **One-time bootstrap:** GitHub loads PR templates from the **default branch of the base repo** (your forkโ€™s `main`). Add the template to `main` first, then open your lab PR from `feature/lab3`. +**Objective:** Implement local Git pre-commit hook that scans staged changes for secrets using Dockerized TruffleHog and Gitleaks. -#### Steps +#### 2.1: Create Pre-commit Hook -1. **Create (or source) a template on `main`** - Path: `.github/pull_request_template.md` - Commit message: `docs: add PR template` - - **Option A (discover):** Find a concise PR template from a reputable open-source project or GitHub docs and adapt it. - - **Option B (write your own):** Create a minimal template with these sections and a 3-item checklist: - - Sections: **Goal**, **Changes**, **Testing** - - Checklist (3 items): clear title, docs/README updated if needed, no secrets/large temp files - - Keep it short and practical (aim for โ‰ค 30 lines). +1. **Setup Pre-commit Hook File:** + + Create `.git/hooks/pre-commit` with the following content: -2. **Create your lab branch and open a PR** ```bash - git checkout -b feature/lab3 - # make a change (add labs/submission3.md) - git add . - git commit -m "docs: add lab3 submission stub" - git push -u origin feature/lab3 + #!/usr/bin/env bash + set -euo pipefail + echo "[pre-commit] scanning staged files for secretsโ€ฆ" + + # Collect staged files (added/changed) + mapfile -t STAGED < <(git diff --cached --name-only --diff-filter=ACM) + if [ ${#STAGED[@]} -eq 0 ]; then + echo "[pre-commit] no staged files; skipping scans" + exit 0 + fi + + FILES=() + for f in "${STAGED[@]}"; do + [ -f "$f" ] && FILES+=("$f") + done + if [ ${#FILES[@]} -eq 0 ]; then + echo "[pre-commit] no regular files to scan; skipping" + exit 0 + fi + + echo "[pre-commit] Files to scan: ${FILES[*]}" + + NON_LECTURES_FILES=() + LECTURES_FILES=() + for f in "${FILES[@]}"; do + if [[ "$f" == lectures/* ]]; then + LECTURES_FILES+=("$f") + else + NON_LECTURES_FILES+=("$f") + fi + done + + echo "[pre-commit] Non-lectures files: ${NON_LECTURES_FILES[*]:-none}" + echo "[pre-commit] Lectures files: ${LECTURES_FILES[*]:-none}" + + TRUFFLEHOG_FOUND_SECRETS=false + if [ ${#NON_LECTURES_FILES[@]} -gt 0 ]; then + echo "[pre-commit] TruffleHog scan on non-lectures filesโ€ฆ" + + set +e + TRUFFLEHOG_OUTPUT=$(docker run --rm -v "$(pwd):/repo" -w /repo \ + trufflesecurity/trufflehog:latest \ + filesystem "${NON_LECTURES_FILES[@]}" 2>&1) + TRUFFLEHOG_EXIT_CODE=$? + set -e + echo "$TRUFFLEHOG_OUTPUT" + + if [ $TRUFFLEHOG_EXIT_CODE -ne 0 ]; then + echo "[pre-commit] โœ– TruffleHog detected potential secrets in non-lectures files" + TRUFFLEHOG_FOUND_SECRETS=true + else + echo "[pre-commit] โœ“ TruffleHog found no secrets in non-lectures files" + fi + else + echo "[pre-commit] Skipping TruffleHog (only lectures files staged)" + fi + + echo "[pre-commit] Gitleaks scan on staged filesโ€ฆ" + GITLEAKS_FOUND_SECRETS=false + GITLEAKS_FOUND_IN_LECTURES=false + + for file in "${FILES[@]}"; do + echo "[pre-commit] Scanning $file with Gitleaks..." + + GITLEAKS_RESULT=$(docker run --rm -v "$(pwd):/repo" -w /repo \ + zricethezav/gitleaks:latest \ + detect --source="$file" --no-git --verbose --exit-code=0 --no-banner 2>&1 || true) + + if [ -n "$GITLEAKS_RESULT" ] && echo "$GITLEAKS_RESULT" | grep -q -E "(Finding:|WRN leaks found)"; then + echo "Gitleaks found secrets in $file:" + echo "$GITLEAKS_RESULT" + echo "---" + + if [[ "$file" == lectures/* ]]; then + echo "โš ๏ธ Secrets found in lectures directory - allowing as educational content" + GITLEAKS_FOUND_IN_LECTURES=true + else + echo "โœ– Secrets found in non-excluded file: $file" + GITLEAKS_FOUND_SECRETS=true + fi + else + echo "[pre-commit] No secrets found in $file" + fi + done + + echo "" + echo "[pre-commit] === SCAN SUMMARY ===" + echo "TruffleHog found secrets in non-lectures files: $TRUFFLEHOG_FOUND_SECRETS" + echo "Gitleaks found secrets in non-lectures files: $GITLEAKS_FOUND_SECRETS" + echo "Gitleaks found secrets in lectures files: $GITLEAKS_FOUND_IN_LECTURES" + echo "" + + if [ "$TRUFFLEHOG_FOUND_SECRETS" = true ] || [ "$GITLEAKS_FOUND_SECRETS" = true ]; then + echo -e "โœ– COMMIT BLOCKED: Secrets detected in non-excluded files." >&2 + echo "Fix or unstage the offending files and try again." >&2 + exit 1 + elif [ "$GITLEAKS_FOUND_IN_LECTURES" = true ]; then + echo "โš ๏ธ Secrets found only in lectures directory (educational content) - allowing commit." + fi + + echo "โœ“ No secrets detected in non-excluded files; proceeding with commit." + exit 0 ``` -Open a PR from `feature/lab3` โ†’ `main` **in your fork**. +2. **Make Hook Executable:** -3. **Verify the template is applied** + ```bash + chmod +x .git/hooks/pre-commit + ``` - * The PR **description auto-fills** with your sections and the **3-item checklist**. - * Fill in *Goal / Changes / Testing* and tick the checkboxes. +#### 2.2: Test Secret Detection -#### Acceptance Criteria +Verify hook functionality: +- Add a test secret (e.g., fake AWS key) to a file and stage it +- Attempt to commit - should be blocked by TruffleHog or Gitleaks +- Remove/redact the secret, then commit again to confirm success -* โœ… Branch `feature/lab3` exists with changes committed. -* โœ… `labs/submission3.md` is present and at least one commit in the PR shows **โ€œVerifiedโ€** (signed via SSH) on GitHub. -* โœ… A local `.git/hooks/pre-commit` runs TruffleHog and Gitleaks via Docker and blocks commits on detected secrets. -* โœ… File `.github/pull_request_template.md` exists on the **main** branch. -* โœ… A PR from `feature/lab3` โ†’ `main` is open and **auto-filled** with the template, including **Goal / Changes / Testing** and the **3-item checklist** (boxes ticked). +In `labs/submission3.md`, document: +- Pre-commit hook setup process and configuration +- Evidence of successful secret detection blocking commits +- Test results showing both blocked and successful commits +- Analysis of how automated secret scanning prevents security incidents --- ## How to Submit -1. Complete all tasks. -2. Push `feature/lab3` to your fork. -3. Open a PR to your forkโ€™s `main`. -4. In the PR description, include: +1. Create a branch for this lab and push it to your fork: + + ```bash + git switch -c feature/lab3 + # create labs/submission3.md with your findings + git add labs/submission3.md + git commit -m "docs: add lab3 submission" + git push -u origin feature/lab3 + ``` + +2. Open a PR from your fork's `feature/lab3` branch โ†’ **course repository's main branch**. + +3. In the PR description, include: ```text - - [x] Task 1 done - - [x] Task 2 done - - [x] Task 3 done - - [x] Screenshots attached (if applicable) + - [x] Task 1 done โ€” SSH commit signing setup + - [x] Task 2 done โ€” Pre-commit secrets scanning setup ``` +4. **Copy the PR URL** and submit it via **Moodle before the deadline**. + +--- + +## Acceptance Criteria + +- โœ… Branch `feature/lab3` exists with commits for each task +- โœ… File `labs/submission3.md` contains required analysis for both tasks +- โœ… At least one commit shows **"Verified"** (signed via SSH) on GitHub +- โœ… Local `.git/hooks/pre-commit` runs TruffleHog and Gitleaks via Docker and blocks secrets +- โœ… PR from `feature/lab3` โ†’ **course repo main branch** is open +- โœ… PR link submitted via Moodle before the deadline + --- ## Rubric (10 pts) -| Criterion | Points | -| ------------------------------------------------- | -----: | -| Task 1 โ€” SSH commit signing setup + summary | **5** | -| Task 2 โ€” Pre-commit secrets scanning in effect | **4** | -| Task 3 โ€” PR template & checklist applied | **1** | -| **Total** | **10** | +| Criterion | Points | +| ------------------------------------------------ | -----: | +| Task 1 โ€” SSH commit signing setup + analysis | **5** | +| Task 2 โ€” Pre-commit secrets scanning setup | **5** | +| **Total** | **10** | --- -## Hints +## Guidelines + +- Use clear Markdown headers to organize sections in `submission3.md` +- Include both command outputs and written analysis for each task +- Document security configurations and testing procedures thoroughly +- Demonstrate both successful and blocked operations for secret scanning + +
+Security Configuration Notes + +- Ensure the email on your commits matches your GitHub account for proper verification +- Verify `gpg.format` is set to `ssh` for proper signing configuration +- Test pre-commit hooks thoroughly with both legitimate and test secret content +- Docker Desktop/Engine must be running for secret scanning tools +- Ensure all commits are properly signed for verification on GitHub -> ๐Ÿ” **Signed commit not showing โ€œVerifiedโ€?** Ensure the email on your commits matches your GitHub account and that `gpg.format` is set to `ssh`.\ -> ๐Ÿ”Ž **Docker required for scans:** The pre-commit hook uses Docker images for TruffleHog and Gitleaks; ensure Docker Desktop/Engine is running.\ -> ๐Ÿ“ **Template didnโ€™t load?** Confirm the path is `.github\pull_request_template.md` **on `main`** before opening the PR; re-open the PR description after adding it.\ -> โœ‚๏ธ **Keep it short:** Reviewers read many PRsโ€”concise templates get filled, long ones get ignored. +
diff --git a/labs/lab4.md b/labs/lab4.md new file mode 100644 index 00000000..12cc043d --- /dev/null +++ b/labs/lab4.md @@ -0,0 +1,325 @@ +# Lab 4 โ€” SBOM Generation & Software Composition Analysis + +![difficulty](https://img.shields.io/badge/difficulty-intermediate-yellow) +![topic](https://img.shields.io/badge/topic-SBOM%20%26%20SCA-blue) +![points](https://img.shields.io/badge/points-10-orange) + +> **Goal:** Generate Software Bills of Materials (SBOMs) for OWASP Juice Shop using Syft and Trivy, perform comprehensive Software Composition Analysis with Grype and Trivy, then compare the toolchain capabilities. +> **Deliverable:** A PR from `feature/lab4` to the course repo with `labs/submission4.md` containing SBOM analysis, SCA findings, and comprehensive toolchain comparison. Submit the PR link via Moodle. + +--- + +## Overview + +In this lab you will practice: +- Generating **SBOMs** with **Syft** and **Trivy** using Docker images for consistency +- Performing **Software Composition Analysis (SCA)** with **Grype** (Anchore) and **Trivy** +- **Comprehensive feature comparison** between **Syft+Grype** vs **Trivy all-in-one** approaches +- **License analysis**, **vulnerability management**, and **supply chain security assessment** + +> Continue using the OWASP Juice Shop from previous labs (`bkimminich/juice-shop:v19.0.0`) as your target application. + +--- + +## Tasks + +### Task 1 โ€” SBOM Generation with Syft and Trivy (4 pts) + +**Objective:** Generate comprehensive SBOMs using both Syft and Trivy Docker images, extracting maximum metadata including licenses, file information, and dependency relationships. + +#### 1.1: Setup SBOM Generation Environment + +```bash +# Prepare working directory +mkdir -p labs/lab4/{syft,trivy,comparison,analysis} + +# Pull required Docker images +docker pull anchore/syft:latest +docker pull aquasec/trivy:latest +docker pull anchore/grype:latest +``` + +#### 1.2: Comprehensive SBOM Generation with Syft + +```bash +# Syft native JSON format (most detailed) +docker run --rm -v /var/run/docker.sock:/var/run/docker.sock \ + -v "$(pwd)":/tmp anchore/syft:latest \ + bkimminich/juice-shop:v19.0.0 -o syft-json=/tmp/labs/lab4/syft/juice-shop-syft-native.json + +# Human-readable table +docker run --rm -v /var/run/docker.sock:/var/run/docker.sock \ + -v "$(pwd)":/tmp anchore/syft:latest \ + bkimminich/juice-shop:v19.0.0 -o table=/tmp/labs/lab4/syft/juice-shop-syft-table.txt + +# Extract licenses from the native JSON format +echo "Extracting licenses from Syft SBOM..." > labs/lab4/syft/juice-shop-licenses.txt +jq -r '.artifacts[] | select(.licenses != null and (.licenses | length > 0)) | "\(.name) | \(.version) | \(.licenses | map(.value) | join(", "))"' \ + labs/lab4/syft/juice-shop-syft-native.json >> labs/lab4/syft/juice-shop-licenses.txt +``` + +#### 1.3: Comprehensive SBOM Generation with Trivy + +```bash +# SBOM with license information +docker run --rm -v /var/run/docker.sock:/var/run/docker.sock \ + -v "$(pwd)":/tmp aquasec/trivy:latest image \ + --format json --output /tmp/labs/lab4/trivy/juice-shop-trivy-detailed.json \ + --list-all-pkgs bkimminich/juice-shop:v19.0.0 + +# Human-readable table with package details +docker run --rm -v /var/run/docker.sock:/var/run/docker.sock \ + -v "$(pwd)":/tmp aquasec/trivy:latest image \ + --format table --output /tmp/labs/lab4/trivy/juice-shop-trivy-table.txt \ + --list-all-pkgs bkimminich/juice-shop:v19.0.0 +``` + +#### 1.4: SBOM Analysis and Extraction + +```bash +# Component Analysis +echo "=== SBOM Component Analysis ===" > labs/lab4/analysis/sbom-analysis.txt +echo "" >> labs/lab4/analysis/sbom-analysis.txt +echo "Syft Package Counts:" >> labs/lab4/analysis/sbom-analysis.txt +jq -r '.artifacts[] | .type' labs/lab4/syft/juice-shop-syft-native.json | sort | uniq -c >> labs/lab4/analysis/sbom-analysis.txt + +echo "" >> labs/lab4/analysis/sbom-analysis.txt +echo "Trivy Package Counts:" >> labs/lab4/analysis/sbom-analysis.txt +jq -r '.Results[] as $result | $result.Packages[]? | "\($result.Target // "Unknown") - \(.Type // "unknown")"' \ + labs/lab4/trivy/juice-shop-trivy-detailed.json | sort | uniq -c >> labs/lab4/analysis/sbom-analysis.txt + +# License Extraction +echo "" >> labs/lab4/analysis/sbom-analysis.txt +echo "=== License Analysis ===" >> labs/lab4/analysis/sbom-analysis.txt +echo "" >> labs/lab4/analysis/sbom-analysis.txt +echo "Syft Licenses:" >> labs/lab4/analysis/sbom-analysis.txt +jq -r '.artifacts[]? | select(.licenses != null) | .licenses[]? | .value' \ + labs/lab4/syft/juice-shop-syft-native.json | sort | uniq -c >> labs/lab4/analysis/sbom-analysis.txt + +echo "" >> labs/lab4/analysis/sbom-analysis.txt +echo "Trivy Licenses (OS Packages):" >> labs/lab4/analysis/sbom-analysis.txt +jq -r '.Results[] | select(.Class // "" | contains("os-pkgs")) | .Packages[]? | select(.Licenses != null) | .Licenses[]?' \ + labs/lab4/trivy/juice-shop-trivy-detailed.json | sort | uniq -c >> labs/lab4/analysis/sbom-analysis.txt + +echo "" >> labs/lab4/analysis/sbom-analysis.txt +echo "Trivy Licenses (Node.js):" >> labs/lab4/analysis/sbom-analysis.txt +jq -r '.Results[] | select(.Class // "" | contains("lang-pkgs")) | .Packages[]? | select(.Licenses != null) | .Licenses[]?' \ + labs/lab4/trivy/juice-shop-trivy-detailed.json | sort | uniq -c >> labs/lab4/analysis/sbom-analysis.txt +``` + +In `labs/submission4.md`, document: +- **Package Type Distribution** comparison between Syft and Trivy +- **Dependency Discovery Analysis** - which tool found more/better dependency data +- **License Discovery Analysis** - which tool found more/better license data + +--- + +### Task 2 โ€” Software Composition Analysis with Grype and Trivy (3 pts) + +**Objective:** Perform comprehensive vulnerability analysis using both Grype (designed for Syft SBOMs) and Trivy's built-in vulnerability scanning. + +#### 2.1: SCA with Grype (Anchore) + +```bash +# Scan using the Syft-generated SBOM +docker run --rm -v "$(pwd)":/tmp anchore/grype:latest \ + sbom:/tmp/labs/lab4/syft/juice-shop-syft-native.json \ + -o json > labs/lab4/syft/grype-vuln-results.json + +# Human-readable vulnerability report +docker run --rm -v "$(pwd)":/tmp anchore/grype:latest \ + sbom:/tmp/labs/lab4/syft/juice-shop-syft-native.json \ + -o table > labs/lab4/syft/grype-vuln-table.txt +``` + +#### 2.2: SCA with Trivy (All-in-One) + +```bash +# Full vulnerability scan with detailed output +docker run --rm -v /var/run/docker.sock:/var/run/docker.sock \ + -v "$(pwd)":/tmp aquasec/trivy:latest image \ + --format json --output /tmp/labs/lab4/trivy/trivy-vuln-detailed.json \ + bkimminich/juice-shop:v19.0.0 + +# Secrets scanning +docker run --rm -v /var/run/docker.sock:/var/run/docker.sock \ + -v "$(pwd)":/tmp aquasec/trivy:latest image \ + --scanners secret --format table \ + --output /tmp/labs/lab4/trivy/trivy-secrets.txt \ + bkimminich/juice-shop:v19.0.0 + +# License compliance scanning +docker run --rm -v /var/run/docker.sock:/var/run/docker.sock \ + -v "$(pwd)":/tmp aquasec/trivy:latest image \ + --scanners license --format json \ + --output /tmp/labs/lab4/trivy/trivy-licenses.json \ + bkimminich/juice-shop:v19.0.0 +``` + +#### 2.3: Vulnerability Analysis and Risk Assessment + +```bash +# Count vulnerabilities by severity +echo "=== Vulnerability Analysis ===" > labs/lab4/analysis/vulnerability-analysis.txt +echo "" >> labs/lab4/analysis/vulnerability-analysis.txt +echo "Grype Vulnerabilities by Severity:" >> labs/lab4/analysis/vulnerability-analysis.txt +jq -r '.matches[]? | .vulnerability.severity' labs/lab4/syft/grype-vuln-results.json | sort | uniq -c >> labs/lab4/analysis/vulnerability-analysis.txt + +echo "" >> labs/lab4/analysis/vulnerability-analysis.txt +echo "Trivy Vulnerabilities by Severity:" >> labs/lab4/analysis/vulnerability-analysis.txt +jq -r '.Results[]?.Vulnerabilities[]? | .Severity' labs/lab4/trivy/trivy-vuln-detailed.json | sort | uniq -c >> labs/lab4/analysis/vulnerability-analysis.txt + +# License comparison summary +echo "" >> labs/lab4/analysis/vulnerability-analysis.txt +echo "=== License Analysis Summary ===" >> labs/lab4/analysis/vulnerability-analysis.txt +echo "Tool Comparison:" >> labs/lab4/analysis/vulnerability-analysis.txt +if [ -f labs/lab4/syft/juice-shop-syft-native.json ]; then + syft_licenses=$(jq -r '.artifacts[] | select(.licenses != null) | .licenses[].value' labs/lab4/syft/juice-shop-syft-native.json 2>/dev/null | sort | uniq | wc -l) + echo "- Syft found $syft_licenses unique license types" >> labs/lab4/analysis/vulnerability-analysis.txt +fi +if [ -f labs/lab4/trivy/trivy-licenses.json ]; then + trivy_licenses=$(jq -r '.Results[].Licenses[]?.Name' labs/lab4/trivy/trivy-licenses.json 2>/dev/null | sort | uniq | wc -l) + echo "- Trivy found $trivy_licenses unique license types" >> labs/lab4/analysis/vulnerability-analysis.txt +fi +``` + +In `labs/submission4.md`, document: +- **SCA Tool Comparison** - vulnerability detection capabilities +- **Critical Vulnerabilities Analysis** - top 5 most critical findings with remediation +- **License Compliance Assessment** - risky licenses and compliance recommendations +- **Additional Security Features** - secrets scanning results + +--- + +### Task 3 โ€” Toolchain Comparison: Syft+Grype vs Trivy All-in-One (3 pts) + +**Objective:** Comprehensive comparison of the specialized toolchain (Syft+Grype) versus the integrated solution (Trivy) across multiple dimensions. + +#### 3.1: Accuracy and Coverage Analysis + +```bash +# Compare package detection +echo "=== Package Detection Comparison ===" > labs/lab4/comparison/accuracy-analysis.txt + +# Extract unique packages from each tool +jq -r '.artifacts[] | "\(.name)@\(.version)"' labs/lab4/syft/juice-shop-syft-native.json | sort > labs/lab4/comparison/syft-packages.txt +jq -r '.Results[]?.Packages[]? | "\(.Name)@\(.Version)"' labs/lab4/trivy/juice-shop-trivy-detailed.json | sort > labs/lab4/comparison/trivy-packages.txt + +# Find packages detected by both tools +comm -12 labs/lab4/comparison/syft-packages.txt labs/lab4/comparison/trivy-packages.txt > labs/lab4/comparison/common-packages.txt + +# Find packages unique to each tool +comm -23 labs/lab4/comparison/syft-packages.txt labs/lab4/comparison/trivy-packages.txt > labs/lab4/comparison/syft-only.txt +comm -13 labs/lab4/comparison/syft-packages.txt labs/lab4/comparison/trivy-packages.txt > labs/lab4/comparison/trivy-only.txt + +echo "Packages detected by both tools: $(wc -l < labs/lab4/comparison/common-packages.txt)" >> labs/lab4/comparison/accuracy-analysis.txt +echo "Packages only detected by Syft: $(wc -l < labs/lab4/comparison/syft-only.txt)" >> labs/lab4/comparison/accuracy-analysis.txt +echo "Packages only detected by Trivy: $(wc -l < labs/lab4/comparison/trivy-only.txt)" >> labs/lab4/comparison/accuracy-analysis.txt + +# Compare vulnerability findings +echo "" >> labs/lab4/comparison/accuracy-analysis.txt +echo "=== Vulnerability Detection Overlap ===" >> labs/lab4/comparison/accuracy-analysis.txt + +# Extract CVE IDs +jq -r '.matches[]? | .vulnerability.id' labs/lab4/syft/grype-vuln-results.json | sort | uniq > labs/lab4/comparison/grype-cves.txt +jq -r '.Results[]?.Vulnerabilities[]? | .VulnerabilityID' labs/lab4/trivy/trivy-vuln-detailed.json | sort | uniq > labs/lab4/comparison/trivy-cves.txt + +echo "CVEs found by Grype: $(wc -l < labs/lab4/comparison/grype-cves.txt)" >> labs/lab4/comparison/accuracy-analysis.txt +echo "CVEs found by Trivy: $(wc -l < labs/lab4/comparison/trivy-cves.txt)" >> labs/lab4/comparison/accuracy-analysis.txt +echo "Common CVEs: $(comm -12 labs/lab4/comparison/grype-cves.txt labs/lab4/comparison/trivy-cves.txt | wc -l)" >> labs/lab4/comparison/accuracy-analysis.txt +``` + +In `labs/submission4.md`, document: +- **Accuracy Analysis** - package detection and vulnerability overlap quantified +- **Tool Strengths and Weaknesses** - practical observations from your testing +- **Use Case Recommendations** - when to choose Syft+Grype vs Trivy +- **Integration Considerations** - CI/CD, automation, and operational aspects + +--- + +## How to Submit + +1. Create a branch for this lab and push it to your fork: + + ```bash + git switch -c feature/lab4 + # create labs/submission4.md with your findings + git add labs/submission4.md labs/lab4/ + git commit -m "docs: add lab4 submission - SBOM generation and SCA comparison" + git push -u origin feature/lab4 + ``` + +2. Open a PR from your fork's `feature/lab4` branch โ†’ **course repository's main branch**. + +3. In the PR description, include: + + ```text + - [x] Task 1 done โ€” SBOM Generation with Syft and Trivy + - [x] Task 2 done โ€” SCA with Grype and Trivy + - [x] Task 3 done โ€” Comprehensive Toolchain Comparison + ``` + +4. **Copy the PR URL** and submit it via **Moodle before the deadline**. + +--- + +## Acceptance Criteria + +- โœ… Branch `feature/lab4` exists with commits for each task +- โœ… File `labs/submission4.md` contains required analysis for Tasks 1-3 +- โœ… SBOM generation completed successfully with both Syft and Trivy +- โœ… Comprehensive SCA performed with both Grype and Trivy vulnerability scanning +- โœ… Quantitative toolchain comparison completed with accuracy analysis +- โœ… All generated SBOMs, vulnerability reports, and analysis files committed +- โœ… PR from `feature/lab4` โ†’ **course repo main branch** is open +- โœ… PR link submitted via Moodle before the deadline + +--- + +## Rubric (10 pts) + +| Criterion | Points | +| ---------------------------------------------------------------- | -----: | +| Task 1 โ€” SBOM generation with Syft and Trivy + analysis | **4** | +| Task 2 โ€” SCA with Grype and Trivy + vulnerability assessment | **3** | +| Task 3 โ€” Comprehensive toolchain comparison + recommendations | **3** | +| **Total** | **10** | + +--- + +## Guidelines + +- Use clear Markdown headers to organize sections in `submission4.md` +- Include both quantitative metrics and qualitative analysis for each task +- Document all Docker commands used and any issues encountered +- Provide actionable security recommendations based on findings +- Focus on practical insights over theoretical comparisons + +
+SBOM Quality Notes + +- NYU research (SBOMit project) shows metadata-based SBOM generation has accuracy limitations +- Pay attention to packages detected by one tool but not the other - document these discrepancies +- Consider the "lying SBOM" problem when evaluating tool accuracy + +
+ +
+SCA Best Practices + +- Always cross-reference critical vulnerabilities between tools before taking action +- Evaluate both direct and transitive dependency risks in your analysis +- Consider CVSS scores, exploitability, and context when prioritizing vulnerabilities +- Document false positives and tool-specific detection patterns + +
+ +
+Comparison Methodology + +- Use consistent container image and execution environment for fair comparison +- Focus on practical operational differences, not just feature checklists +- Consider maintenance overhead and community support in your analysis +- Provide specific use case recommendations based on quantitative findings + +
diff --git a/labs/lab5.md b/labs/lab5.md new file mode 100644 index 00000000..472f9367 --- /dev/null +++ b/labs/lab5.md @@ -0,0 +1,480 @@ +# Lab 5 โ€” Security Analysis: SAST & DAST of OWASP Juice Shop + +![difficulty](https://img.shields.io/badge/difficulty-intermediate-orange) +![topic](https://img.shields.io/badge/topic-SAST%20%26%20DAST-blue) +![points](https://img.shields.io/badge/points-10-orange) + +> **Goal:** Perform Static Application Security Testing (SAST) using Semgrep and Dynamic Application Security Testing (DAST) using multiple tools (ZAP, Nuclei, Nikto, SQLmap) against OWASP Juice Shop to identify security vulnerabilities and compare tool effectiveness. +> **Deliverable:** A PR from `feature/lab5` to the course repo with `labs/submission5.md` containing SAST findings, DAST results from multiple tools, and security recommendations. Submit the PR link via Moodle. + +--- + +## Overview + +In this lab you will practice: +- Performing **Static Application Security Testing (SAST)** with **Semgrep** using Docker containers +- Conducting **Dynamic Application Security Testing (DAST)** using multiple specialized tools +- **Tool comparison analysis** between different DAST tools (ZAP, Nuclei, Nikto, SQLmap) +- **Vulnerability correlation** between SAST and DAST findings +- **Security tool selection** for different vulnerability types + +These skills are essential for DevSecOps integration and security testing automation. + +> Use the OWASP Juice Shop (`bkimminich/juice-shop:v19.0.0`) as your target application, with access to its source code for SAST analysis. + +--- + +## Tasks + +### Task 1 โ€” Static Application Security Testing with Semgrep (3 pts) +โฑ๏ธ **Estimated time:** 15-20 minutes + +**Objective:** Perform SAST analysis using Semgrep to identify security vulnerabilities in the OWASP Juice Shop source code. + +#### 1.1: Setup SAST Environment + +1. **Prepare Working Directory and Clone Source:** + + ```bash + mkdir -p labs/lab5/{semgrep,zap,nuclei,nikto,sqlmap,analysis} + git clone https://github.com/juice-shop/juice-shop.git --depth 1 --branch v19.0.0 labs/lab5/semgrep/juice-shop + ``` + +#### 1.2: SAST Analysis with Semgrep + +1. **Run Semgrep Security Scan:** + + ```bash + docker run --rm -v "$(pwd)/labs/lab5/semgrep/juice-shop":/src \ + -v "$(pwd)/labs/lab5/semgrep":/output \ + semgrep/semgrep:latest \ + semgrep --config=p/security-audit --config=p/owasp-top-ten \ + --json --output=/output/semgrep-results.json /src + + # Generate human-readable security report + docker run --rm -v "$(pwd)/labs/lab5/semgrep/juice-shop":/src \ + -v "$(pwd)/labs/lab5/semgrep":/output \ + semgrep/semgrep:latest \ + semgrep --config=p/security-audit --config=p/owasp-top-ten \ + --text --output=/output/semgrep-report.txt /src + ``` + + +#### 1.3: SAST Results Analysis + +1. **Analyze SAST Results:** + + ```bash + echo "=== SAST Analysis Report ===" > labs/lab5/analysis/sast-analysis.txt + jq '.results | length' labs/lab5/semgrep/semgrep-results.json >> labs/lab5/analysis/sast-analysis.txt + ``` + +In `labs/submission5.md`, document: + +**Required Sections:** + +1. SAST Tool Effectiveness: + - Describe what types of vulnerabilities Semgrep detected + - Evaluate coverage (how many files scanned, how many findings) + +2. Critical Vulnerability Analysis: + - List **5 most critical findings** from Semgrep results + - For each vulnerability include: + - Vulnerability type (e.g., SQL Injection, Hardcoded Secret) + - File path and line number + - Severity level + +--- + +### Task 2 โ€” Dynamic Application Security Testing with Multiple Tools (5 pts) +โฑ๏ธ **Estimated time:** 60-90 minutes (scans run in background) + +**Objective:** Perform DAST analysis using ZAP (with authentication) and specialized tools (Nuclei, Nikto, SQLmap) to compare their effectiveness. + +#### 2.1: Setup DAST Environment + +1. **Start OWASP Juice Shop:** + + ```bash + docker run -d --name juice-shop-lab5 -p 3000:3000 bkimminich/juice-shop:v19.0.0 + + # Wait for application to start + sleep 10 + + # Verify it's running + curl -s http://localhost:3000 | head -n 5 + ``` + + +#### 2.2: OWASP ZAP Unauthenticated Scanning +โฑ๏ธ ~5 minutes + +1. **Run Unauthenticated ZAP Baseline Scan:** + + ```bash + # Baseline scan without authentication + docker run --rm --network host \ + -v "$(pwd)/labs/lab5/zap":/zap/wrk/:rw \ + zaproxy/zap-stable:latest \ + zap-baseline.py -t http://localhost:3000 \ + -r report-noauth.html -J zap-report-noauth.json + ``` + + + > This baseline scan discovers vulnerabilities in publicly accessible endpoints. + +#### 2.3: OWASP ZAP Authenticated Scanning +โฑ๏ธ ~20-30 minutes + +> **โš ๏ธ Important:** Authenticated scanning uses ZAP's Automation Framework. The configuration file is pre-created in `labs/lab5/scripts/zap-auth.yaml` for consistency. + +1. **Verify Authentication Endpoint:** + + ```bash + # Test login with admin credentials (default Juice Shop account) + curl -s -X POST http://localhost:3000/rest/user/login \ + -H 'Content-Type: application/json' \ + -d '{"email":"admin@juice-sh.op","password":"admin123"}' | jq '.authentication.token' + ``` + + You should see a JWT token returned, confirming the endpoint works. + +2. **Run Authenticated ZAP Scan:** + + ```bash + docker run --rm --network host \ + -v "$(pwd)/labs/lab5":/zap/wrk/:rw \ + zaproxy/zap-stable:latest \ + zap.sh -cmd \ + -autorun /zap/wrk/scripts/zap-auth.yaml + ``` + +
+ ๐Ÿ“ ZAP Configuration Explained + + The `labs/lab5/scripts/zap-auth.yaml` file configures: + - **Authentication**: JSON-based login with admin credentials + - **Session Management**: Cookie-based session tracking + - **Verification**: Uses regex to detect successful login (looks for "authentication" in response) + - **Scanning Jobs**: Spider โ†’ AJAX Spider โ†’ Passive Scan โ†’ Active Scan โ†’ Report Generation + - **AJAX Spider**: Discovers ~10x more URLs by executing JavaScript (finds dynamic endpoints) + +
+ + + **What this scan discovers:** + - ๐Ÿ”“ **Authenticated endpoints** like `/rest/admin/application-configuration` + - ๐Ÿ›’ **User-specific features** (basket, orders, payment, profile) + - ๐Ÿ” **Admin panel** vulnerabilities + - ๐Ÿ“Š **10x more URLs** than unauthenticated scan (AJAX spider finds ~1,200 URLs) + + **Expected output:** + ``` + Job spider found 112 URLs + Job spiderAjax found 1,199 URLs # AJAX spider discovers much more! + Job report generated report /zap/wrk/report-auth.html + ``` + + > **Key Insight:** Look for `http://localhost:3000/rest/admin/` endpoints in the output - these prove authentication is working! + +3. **Compare Authenticated vs Unauthenticated Scans:** + + Run: `bash labs/lab5/scripts/compare_zap.sh` + +#### 2.4: Multi-Tool Specialized Scanning + +> **๐Ÿ’ก Networking Note:** Docker networking varies by tool: +> - `--network host`: Shares host's network (ZAP, Nuclei, Nikto) +> - `--network container:NAME`: Shares another container's network namespace (SQLmap) +> Use the pattern shown in each command for best compatibility. + +1. **Nuclei Template-Based Scan:** โฑ๏ธ ~5 minutes + + ```bash + docker run --rm --network host \ + -v "$(pwd)/labs/lab5/nuclei":/app \ + projectdiscovery/nuclei:latest \ + -ut -u http://localhost:3000 \ + -jsonl -o /app/nuclei-results.json + ``` + + +2. **Nikto Web Server Scan:** โฑ๏ธ ~5-10 minutes + + ```bash + docker run --rm --network host \ + -v "$(pwd)/labs/lab5/nikto":/tmp \ + sullo/nikto:latest \ + -h http://localhost:3000 -o /tmp/nikto-results.txt + ``` + + +3. **SQLmap SQL Injection Test:** โฑ๏ธ ~10-20 minutes per endpoint + + > **Network Solution:** Share the network namespace with Juice Shop container so SQLmap can access `localhost:3000` + + ```bash + # Test both vulnerable endpoints - Search (GET) and Login (POST JSON) + docker run --rm \ + --network container:juice-shop-lab5 \ + -v "$(pwd)/labs/lab5/sqlmap":/output \ + sqlmapproject/sqlmap \ + -u "http://localhost:3000/rest/products/search?q=*" \ + --dbms=sqlite --batch --level=3 --risk=2 \ + --technique=B --threads=5 --output-dir=/output + + docker run --rm \ + --network container:juice-shop-lab5 \ + -v "$(pwd)/labs/lab5/sqlmap":/output \ + sqlmapproject/sqlmap \ + -u "http://localhost:3000/rest/user/login" \ + --data '{"email":"*","password":"test"}' \ + --method POST \ + --headers='Content-Type: application/json' \ + --dbms=sqlite --batch --level=5 --risk=3 \ + --technique=BT --threads=5 --output-dir=/output \ + --dump + ``` + + + **How this works:** + + **Networking:** + - `--network container:juice-shop-lab5` - Shares network namespace with Juice Shop container + - Inside SQLmap container, `localhost:3000` now directly reaches Juice Shop (no DNS/port forwarding needed) + + **Endpoint 1 - Search (GET):** + - URL: `http://localhost:3000/rest/products/search?q=*` + - `*` marks the `q` parameter for injection testing + - `--technique=B` - Boolean-based blind SQL injection (true/false responses) + - Faster scan, detects logic-based vulnerabilities + + **Endpoint 2 - Login (POST JSON):** + - URL: `http://localhost:3000/rest/user/login` + - Tests JSON `email` parameter with `*` marker + - `--technique=BT` - Boolean + Time-based blind SQL injection + - Time-based detects when responses take longer (SQL `SLEEP()` commands) + - More thorough, bypasses authentication without valid credentials + + **Database & Extraction:** + - `--dbms=sqlite` - Optimizes for SQLite-specific syntax (Juice Shop uses SQLite) + - `--dump` - Automatically extracts database contents after confirming vulnerability + - Will extract Users table including emails and bcrypt password hashes + + **Shell escaping:** + - Single quotes `'...'` wrap the entire shell command to avoid JSON escaping issues + + > **Expected Results:** SQLmap will find SQL injection in both endpoints and extract ~20 user accounts with hashed passwords. Scan duration: 10-20 minutes. + +#### 2.5: DAST Results Analysis + +1. **Compare Tool Results:** + + Run: `bash labs/lab5/scripts/summarize_dast.sh` + +In `labs/submission5.md`, document: + +**Required Sections:** + +1. Authenticated vs Unauthenticated Scanning: + - Compare URL discovery count (use numbers from `compare_zap.sh` output) + - List examples of admin/authenticated endpoints discovered + - Explain why authenticated scanning matters for security testing + +2. Tool Comparison Matrix: + - Create a comparison table with columns: Tool | Findings | Severity Breakdown | Best Use Case + - Include all 4 DAST tools: ZAP, Nuclei, Nikto, SQLmap + - Use actual numbers from your scan outputs + +3. Tool-Specific Strengths: + - Describe what each tool excels at: + - **ZAP**: (e.g., comprehensive scanning, authentication support) + - **Nuclei**: (e.g., speed, known CVE detection) + - **Nikto**: (e.g., server misconfiguration) + - **SQLmap**: (e.g., deep SQL injection analysis) + - Provide 1-2 example findings from each tool + +--- + +### Task 3 โ€” SAST/DAST Correlation and Security Assessment (2 pts) +โฑ๏ธ **Estimated time:** 20-30 minutes + +**Objective:** Correlate findings from SAST and DAST approaches to provide comprehensive security assessment. + +#### 3.1: SAST/DAST Correlation + +1. **Create Correlation Analysis:** + + ```bash + echo "=== SAST/DAST Correlation Report ===" > labs/lab5/analysis/correlation.txt + + # Count SAST findings + sast_count=$(jq '.results | length' labs/lab5/semgrep/semgrep-results.json 2>/dev/null || echo "0") + + # Count DAST findings from all tools + zap_med=$(grep -c "class=\"risk-2\"" labs/lab5/zap/report-auth.html 2>/dev/null) + zap_high=$(grep -c "class=\"risk-3\"" labs/lab5/zap/report-auth.html 2>/dev/null) + zap_total=$(( (zap_med / 2) + (zap_high / 2) )) + nuclei_count=$(wc -l < labs/lab5/nuclei/nuclei-results.json 2>/dev/null || echo "0") + nikto_count=$(grep -c '+ ' labs/lab5/nikto/nikto-results.txt 2>/dev/null || echo '0') + + # Count SQLmap findings + sqlmap_csv=$(find labs/lab5/sqlmap -name "results-*.csv" 2>/dev/null | head -1) + if [ -f "$sqlmap_csv" ]; then + sqlmap_count=$(tail -n +2 "$sqlmap_csv" | grep -v '^$' | wc -l) + else + sqlmap_count=0 + fi + + echo "Security Testing Results Summary:" >> labs/lab5/analysis/correlation.txt + echo "" >> labs/lab5/analysis/correlation.txt + echo "SAST (Semgrep): $sast_count code-level findings" >> labs/lab5/analysis/correlation.txt + echo "DAST (ZAP authenticated): $zap_total alerts" >> labs/lab5/analysis/correlation.txt + echo "DAST (Nuclei): $nuclei_count template matches" >> labs/lab5/analysis/correlation.txt + echo "DAST (Nikto): $nikto_count server issues" >> labs/lab5/analysis/correlation.txt + echo "DAST (SQLmap): $sqlmap_count SQL injection vulnerabilities" >> labs/lab5/analysis/correlation.txt + echo "" >> labs/lab5/analysis/correlation.txt + + echo "Key Insights:" >> labs/lab5/analysis/correlation.txt + echo "" >> labs/lab5/analysis/correlation.txt + echo "SAST (Static Analysis):" >> labs/lab5/analysis/correlation.txt + echo " - Finds code-level vulnerabilities before deployment" >> labs/lab5/analysis/correlation.txt + echo " - Detects: hardcoded secrets, SQL injection patterns, insecure crypto" >> labs/lab5/analysis/correlation.txt + echo " - Fast feedback in development phase" >> labs/lab5/analysis/correlation.txt + echo "" >> labs/lab5/analysis/correlation.txt + echo "DAST (Dynamic Analysis):" >> labs/lab5/analysis/correlation.txt + echo " - Finds runtime configuration and deployment issues" >> labs/lab5/analysis/correlation.txt + echo " - Detects: missing security headers, authentication flaws, server misconfigs" >> labs/lab5/analysis/correlation.txt + echo " - Authenticated scanning reveals 60%+ more attack surface" >> labs/lab5/analysis/correlation.txt + echo "" >> labs/lab5/analysis/correlation.txt + echo "Recommendation: Use BOTH approaches for comprehensive security coverage" >> labs/lab5/analysis/correlation.txt + + cat labs/lab5/analysis/correlation.txt + ``` + + + +In `labs/submission5.md`, document: + +**Required Sections:** + +1. SAST vs DAST Comparison: + - Compare total findings: SAST count vs combined DAST count + - Identify 2-3 vulnerability types found ONLY by SAST + - Identify 2-3 vulnerability types found ONLY by DAST + - Explain why each approach finds different things + +--- + +## Acceptance Criteria + +- โœ… Branch `feature/lab5` exists with commits for each task. +- โœ… File `labs/submission5.md` contains required analysis for Tasks 1-3. +- โœ… SAST analysis completed with Semgrep. +- โœ… DAST analysis completed with ZAP and specialized tools. +- โœ… SAST/DAST correlation analysis completed. +- โœ… All generated reports, configurations, and analysis files committed. +- โœ… PR from `feature/lab5` โ†’ **course repo main branch** is open. +- โœ… PR link submitted via Moodle before the deadline. + +--- + +## Cleanup + +After completing the lab: + +```bash +# Stop and remove containers +docker stop juice-shop-lab5 +docker rm juice-shop-lab5 + +# Optional: Remove large source code directory (~200MB) +# rm -rf labs/lab5/semgrep/juice-shop + +# Check disk space recovered +docker system df +``` + +--- + +## How to Submit + +1. Create a branch for this lab and push it to your fork: + + ```bash + git switch -c feature/lab5 + # create labs/submission5.md with your findings + git add labs/submission5.md labs/lab5/ + git commit -m "docs: add lab5 submission - SAST/multi-approach DAST security analysis" + git push -u origin feature/lab5 + ``` + +2. Open a PR from your fork's `feature/lab5` branch โ†’ **course repository's main branch**. + +3. In the PR description, include: + + ```text + - [x] Task 1 done โ€” SAST Analysis with Semgrep + - [x] Task 2 done โ€” DAST Analysis (ZAP + Nuclei + Nikto + SQLmap) + - [x] Task 3 done โ€” SAST/DAST Correlation + ``` + +4. **Copy the PR URL** and submit it via **Moodle before the deadline**. + +--- + +## Rubric (10 pts) + +| Criterion | Points | +| ------------------------------------------------------------------- | -----: | +| Task 1 โ€” SAST with Semgrep + basic analysis | **3** | +| Task 2 โ€” DAST analysis (ZAP + Nuclei + Nikto + SQLmap) + comparison | **5** | +| Task 3 โ€” SAST/DAST correlation + recommendations | **2** | +| **Total** | **10** | + +--- + +## Guidelines + +- Use clear Markdown headers to organize sections in `submission5.md`. +- Include evidence from tool outputs to support your analysis. +- Focus on practical insights about when to use each tool in a DevSecOps workflow. +- Provide actionable security recommendations based on findings. + +
+Tool Comparison Reference + +**SAST Tool:** +- **Semgrep**: Static code analysis using pattern-based security rulesets + +**DAST Tools:** +- **ZAP**: Comprehensive web application scanner with integrated reporting +- **Nuclei**: Fast template-based vulnerability scanner with community templates +- **Nikto**: Web server vulnerability scanner for server misconfigurations +- **SQLmap**: Specialized SQL injection testing tool + +**Tool Selection in DevSecOps:** +- **Semgrep**: Early in development pipeline (pre-commit, PR checks) +- **ZAP**: Staging/QA environment for comprehensive web app testing +- **Nuclei**: Quick scans for known CVEs in any environment +- **Nikto**: Web server security assessment during deployment +- **SQLmap**: Targeted SQL injection testing when SAST/DAST indicate database issues + +
+ +
+Expected Vulnerability Categories + +**SAST typically finds:** +- Hardcoded credentials and API keys in source code +- Insecure cryptographic usage patterns +- Code-level injection vulnerabilities (SQL, command, etc.) +- Path traversal and insecure file handling + +**DAST typically finds:** +- Authentication and session management issues +- Runtime configuration problems (security headers, SSL/TLS) +- XSS, CSRF, and other runtime exploitation vectors +- Information disclosure through HTTP responses + +
diff --git a/labs/lab6.md b/labs/lab6.md new file mode 100644 index 00000000..a772e4a4 --- /dev/null +++ b/labs/lab6.md @@ -0,0 +1,568 @@ +# Lab 6 โ€” Infrastructure-as-Code Security: Scanning & Policy Enforcement + +![difficulty](https://img.shields.io/badge/difficulty-intermediate-orange) +![topic](https://img.shields.io/badge/topic-IaC%20Security-blue) +![points](https://img.shields.io/badge/points-10-orange) + +> **Goal:** Perform security analysis on vulnerable Infrastructure-as-Code using multiple scanning tools (tfsec, Checkov, Terrascan for Terraform; KICS for Pulumi and Ansible) and conduct comparative analysis to identify misconfigurations and security issues. +> **Deliverable:** A PR from `feature/lab6` to the course repo with `labs/submission6.md` containing IaC security findings, tool comparison analysis, and security insights. Submit the PR link via Moodle. + +--- + +## Overview + +In this lab you will practice: +- Scanning **Terraform** infrastructure code with multiple security tools (tfsec, Checkov, Terrascan) +- Analyzing **Pulumi** infrastructure code with **KICS (Checkmarx)**, an open-source scanner with first-class Pulumi YAML support +- Scanning **Ansible** playbooks with **KICS** for security issues and misconfigurations +- Comparing different IaC security scanners to evaluate their effectiveness +- Analyzing critical security vulnerabilities and developing remediation strategies +- Recommending tool selection strategies for real-world DevSecOps pipelines + +These skills are essential for shift-left security in infrastructure deployment and DevSecOps automation. + +> You will work with intentionally vulnerable Terraform, Pulumi, and Ansible code provided in the course repository to practice identifying and fixing security misconfigurations. + +--- + +## Tasks + +### Task 1 โ€” Terraform & Pulumi Security Scanning (5 pts) + +**Objective:** Scan vulnerable Terraform and Pulumi configurations using multiple security tools to compare effectiveness and identify infrastructure security issues. + +#### 1.1: Setup Scanning Environment + +1. **Prepare Analysis Directory:** + + ```bash + # Create analysis directory for all scan results + mkdir -p labs/lab6/analysis + ``` + +
+Vulnerable IaC Code Structure + +**Location:** `labs/lab6/vulnerable-iac/` + +**Terraform code** (`labs/lab6/vulnerable-iac/terraform/`): +- `main.tf` - AWS infrastructure with public S3 buckets, hardcoded credentials +- `security_groups.tf` - Overly permissive security rules (0.0.0.0/0) +- `database.tf` - Unencrypted RDS instances, public databases +- `iam.tf` - Wildcard IAM permissions, privilege escalation +- `variables.tf` - Insecure default values, hardcoded secrets + +**Pulumi code** (`labs/lab6/vulnerable-iac/pulumi/`): +- `__main__.py` - Python-based infrastructure with 21 security issues +- `Pulumi.yaml` - Configuration with default secret values +- `Pulumi-vulnerable.yaml` - YAML-based Pulumi manifest (for KICS scanning) +- Includes: public S3, open security groups, unencrypted databases + +**Ansible code** (`labs/lab6/vulnerable-iac/ansible/`): +- `deploy.yml` - Hardcoded secrets, poor command execution +- `configure.yml` - Weak SSH config, security misconfigurations +- `inventory.ini` - Credentials in plaintext + +**Total: 80+ intentional security vulnerabilities across all frameworks** + +> **Note:** Pulumi code includes both Python and YAML formats. KICS is used for Pulumi scanning due to its first-class support for Pulumi YAML manifests and comprehensive query catalog. + +
+ +#### 1.2: Scan with tfsec + +1. **Run tfsec Security Scanner:** + + ```bash + # Scan Terraform code with tfsec (JSON output) + docker run --rm -v "$(pwd)/labs/lab6/vulnerable-iac/terraform":/src \ + aquasec/tfsec:latest /src \ + --format json > labs/lab6/analysis/tfsec-results.json + + # Generate readable report + docker run --rm -v "$(pwd)/labs/lab6/vulnerable-iac/terraform":/src \ + aquasec/tfsec:latest /src > labs/lab6/analysis/tfsec-report.txt + ``` + +#### 1.3: Scan with Checkov + +1. **Run Checkov Security Scanner:** + + ```bash + # Scan with Checkov (JSON output) + docker run --rm -v "$(pwd)/labs/lab6/vulnerable-iac/terraform":/tf \ + bridgecrew/checkov:latest \ + -d /tf --framework terraform \ + -o json > labs/lab6/analysis/checkov-terraform-results.json + + # Generate readable report + docker run --rm -v "$(pwd)/labs/lab6/vulnerable-iac/terraform":/tf \ + bridgecrew/checkov:latest \ + -d /tf --framework terraform \ + --compact > labs/lab6/analysis/checkov-terraform-report.txt + ``` + +#### 1.4: Scan with Terrascan + +1. **Run Terrascan Security Scanner:** + + ```bash + # Scan with Terrascan (JSON output) + docker run --rm -v "$(pwd)/labs/lab6/vulnerable-iac/terraform":/iac \ + tenable/terrascan:latest scan \ + -i terraform -d /iac \ + -o json > labs/lab6/analysis/terrascan-results.json + + # Generate readable report + docker run --rm -v "$(pwd)/labs/lab6/vulnerable-iac/terraform":/iac \ + tenable/terrascan:latest scan \ + -i terraform -d /iac \ + -o human > labs/lab6/analysis/terrascan-report.txt + ``` + +#### 1.5: Terraform Scanning Analysis + +1. **Compare Tool Results:** + + ```bash + echo "=== Terraform Security Analysis ===" > labs/lab6/analysis/terraform-comparison.txt + + # Count findings from each tool + tfsec_count=$(jq '.results | length' labs/lab6/analysis/tfsec-results.json 2>/dev/null || echo "0") + checkov_count=$(jq '.summary.failed' labs/lab6/analysis/checkov-terraform-results.json 2>/dev/null || echo "0") + terrascan_count=$(jq '.results.scan_summary.violated_policies' labs/lab6/analysis/terrascan-results.json 2>/dev/null || echo "0") + + echo "tfsec findings: $tfsec_count" >> labs/lab6/analysis/terraform-comparison.txt + echo "Checkov findings: $checkov_count" >> labs/lab6/analysis/terraform-comparison.txt + echo "Terrascan findings: $terrascan_count" >> labs/lab6/analysis/terraform-comparison.txt + ``` + +#### 1.6: Scan Pulumi Code with KICS + +1. **Scan Pulumi with KICS (Checkmarx):** + + KICS provides first-class Pulumi support and scans Pulumi YAML manifests directly. It includes a comprehensive catalog of Pulumi-specific security queries for AWS, Azure, GCP, and Kubernetes resources. + + ```bash + # Scan Pulumi with KICS (JSON and HTML reports) + docker run -t --rm -v "$(pwd)/labs/lab6/vulnerable-iac/pulumi":/src \ + checkmarx/kics:latest \ + scan -p /src -o /src/kics-report --report-formats json,html + + # Move reports to analysis directory + sudo mv labs/lab6/vulnerable-iac/pulumi/kics-report/results.json labs/lab6/analysis/kics-pulumi-results.json + sudo mv labs/lab6/vulnerable-iac/pulumi/kics-report/results.html labs/lab6/analysis/kics-pulumi-report.html + + # Generate readable summary (console output) + docker run -t --rm -v "$(pwd)/labs/lab6/vulnerable-iac/pulumi":/src \ + checkmarx/kics:latest \ + scan -p /src --minimal-ui > labs/lab6/analysis/kics-pulumi-report.txt 2>&1 || true + ``` + +2. **Analyze Pulumi Results:** + + ```bash + echo "=== Pulumi Security Analysis (KICS) ===" > labs/lab6/analysis/pulumi-analysis.txt + + # KICS JSON structure: queries_total, queries_failed (vulnerabilities found) + high_severity=$(jq '.severity_counters.HIGH // 0' labs/lab6/analysis/kics-pulumi-results.json 2>/dev/null || echo "0") + medium_severity=$(jq '.severity_counters.MEDIUM // 0' labs/lab6/analysis/kics-pulumi-results.json 2>/dev/null || echo "0") + low_severity=$(jq '.severity_counters.LOW // 0' labs/lab6/analysis/kics-pulumi-results.json 2>/dev/null || echo "0") + total_findings=$(jq '.total_counter // 0' labs/lab6/analysis/kics-pulumi-results.json 2>/dev/null || echo "0") + + echo "KICS Pulumi findings: $total_findings" >> labs/lab6/analysis/pulumi-analysis.txt + echo " HIGH severity: $high_severity" >> labs/lab6/analysis/pulumi-analysis.txt + echo " MEDIUM severity: $medium_severity" >> labs/lab6/analysis/pulumi-analysis.txt + echo " LOW severity: $low_severity" >> labs/lab6/analysis/pulumi-analysis.txt + ``` + +In `labs/submission6.md`, document: +- **Terraform Tool Comparison** - Effectiveness of tfsec vs. Checkov vs. Terrascan +- **Pulumi Security Analysis** - Findings from KICS on Pulumi code +- **Terraform vs. Pulumi** - Compare security issues between declarative HCL and programmatic YAML approaches +- **KICS Pulumi Support** - Evaluate KICS's Pulumi-specific query catalog +- **Critical Findings** - At least 5 significant security issues +- **Tool Strengths** - What each tool excels at detecting + +--- + +### Task 2 โ€” Ansible Security Scanning with KICS (2 pts) + +**Objective:** Scan vulnerable Ansible playbooks using KICS to identify security issues, misconfigurations, and best practice violations. + +#### 2.1: Scan Ansible Playbooks with KICS + +
+Vulnerable Ansible Code Structure + +The provided Ansible code includes common security issues: +- `deploy.yml` - Playbook with hardcoded secrets +- `configure.yml` - Tasks without `no_log` for sensitive operations +- `inventory.ini` - Insecure inventory configuration + +KICS provides comprehensive Ansible security queries for: +- Secrets management issues +- Command execution vulnerabilities +- File permissions and access control +- Authentication and access issues +- Insecure configurations + +
+ +1. **Run KICS Security Scanner for Ansible:** + + KICS auto-detects Ansible playbooks and applies Ansible-specific security queries: + + ```bash + # Scan Ansible playbooks with KICS (JSON and HTML reports) + docker run -t --rm -v "$(pwd)/labs/lab6/vulnerable-iac/ansible":/src \ + checkmarx/kics:latest \ + scan -p /src -o /src/kics-report --report-formats json,html + + # Move reports to analysis directory + sudo mv labs/lab6/vulnerable-iac/ansible/kics-report/results.json labs/lab6/analysis/kics-ansible-results.json + sudo mv labs/lab6/vulnerable-iac/ansible/kics-report/results.html labs/lab6/analysis/kics-ansible-report.html + + # Generate readable summary + docker run -t --rm -v "$(pwd)/labs/lab6/vulnerable-iac/ansible":/src \ + checkmarx/kics:latest \ + scan -p /src --minimal-ui > labs/lab6/analysis/kics-ansible-report.txt 2>&1 || true + ``` + +#### 2.2: Ansible Security Analysis + +1. **Analyze KICS Ansible Results:** + + ```bash + echo "=== Ansible Security Analysis (KICS) ===" > labs/lab6/analysis/ansible-analysis.txt + + # Count findings by severity + high_severity=$(jq '.severity_counters.HIGH // 0' labs/lab6/analysis/kics-ansible-results.json 2>/dev/null || echo "0") + medium_severity=$(jq '.severity_counters.MEDIUM // 0' labs/lab6/analysis/kics-ansible-results.json 2>/dev/null || echo "0") + low_severity=$(jq '.severity_counters.LOW // 0' labs/lab6/analysis/kics-ansible-results.json 2>/dev/null || echo "0") + total_findings=$(jq '.total_counter // 0' labs/lab6/analysis/kics-ansible-results.json 2>/dev/null || echo "0") + + echo "KICS Ansible findings: $total_findings" >> labs/lab6/analysis/ansible-analysis.txt + echo " HIGH severity: $high_severity" >> labs/lab6/analysis/ansible-analysis.txt + echo " MEDIUM severity: $medium_severity" >> labs/lab6/analysis/ansible-analysis.txt + echo " LOW severity: $low_severity" >> labs/lab6/analysis/ansible-analysis.txt + ``` + +In `labs/submission6.md`, document: +- **Ansible Security Issues** - Key security problems identified by KICS +- **Best Practice Violations** - Explain at least 3 violations and their security impact +- **KICS Ansible Queries** - Evaluate the types of security checks KICS performs +- **Remediation Steps** - How to fix the identified issues + +--- + +### Task 3 โ€” Comparative Tool Analysis & Security Insights (3 pts) + +**Objective:** Analyze and compare the effectiveness of different IaC security scanning tools to understand their strengths and weaknesses, and develop insights for tool selection in real-world scenarios. + +#### 3.1: Create Comprehensive Tool Comparison + +1. **Generate Summary Statistics:** + + ```bash + # Generate comprehensive comparison statistics + echo "=== Comprehensive Tool Comparison ===" > labs/lab6/analysis/tool-comparison.txt + + # Terraform tools + tfsec_count=$(jq '.results | length' labs/lab6/analysis/tfsec-results.json 2>/dev/null || echo "0") + checkov_tf_count=$(jq '.summary.failed' labs/lab6/analysis/checkov-terraform-results.json 2>/dev/null || echo "0") + terrascan_count=$(jq '.results.scan_summary.violated_policies' labs/lab6/analysis/terrascan-results.json 2>/dev/null || echo "0") + + # Pulumi tool + kics_pulumi_count=$(jq '.total_counter // 0' labs/lab6/analysis/kics-pulumi-results.json 2>/dev/null || echo "0") + + # Ansible tool + kics_ansible_count=$(jq '.total_counter // 0' labs/lab6/analysis/kics-ansible-results.json 2>/dev/null || echo "0") + + echo "Terraform Scanning Results:" >> labs/lab6/analysis/tool-comparison.txt + echo " - tfsec: $tfsec_count findings" >> labs/lab6/analysis/tool-comparison.txt + echo " - Checkov: $checkov_tf_count findings" >> labs/lab6/analysis/tool-comparison.txt + echo " - Terrascan: $terrascan_count findings" >> labs/lab6/analysis/tool-comparison.txt + echo "" >> labs/lab6/analysis/tool-comparison.txt + echo "Pulumi Scanning Results (KICS): $kics_pulumi_count findings" >> labs/lab6/analysis/tool-comparison.txt + echo "Ansible Scanning Results (KICS): $kics_ansible_count findings" >> labs/lab6/analysis/tool-comparison.txt + ``` + +2. **Create Tool Effectiveness Matrix:** + + In `labs/submission6.md`, create a comprehensive comparison table: + + | Criterion | tfsec | Checkov | Terrascan | KICS | + |-----------|-------|---------|-----------|------| + | **Total Findings** | # | # | # | # (Pulumi + Ansible) | + | **Scan Speed** | Fast/Medium/Slow | | | | + | **False Positives** | Low/Med/High | | | | + | **Report Quality** | โญ-โญโญโญโญ | | | | + | **Ease of Use** | โญ-โญโญโญโญ | | | | + | **Documentation** | โญ-โญโญโญโญ | | | | + | **Platform Support** | Terraform only | Multiple | Multiple | Multiple | + | **Output Formats** | JSON, text, SARIF, etc | | | | + | **CI/CD Integration** | Easy/Medium/Hard | | | | + | **Unique Strengths** | | | | | + +#### 3.2: Vulnerability Category Analysis + +1. **Categorize Findings by Security Domain:** + + In `labs/submission6.md`, analyze tool performance across security categories: + + | Security Category | tfsec | Checkov | Terrascan | KICS (Pulumi) | KICS (Ansible) | Best Tool | + |------------------|-------|---------|-----------|---------------|----------------|----------| + | **Encryption Issues** | ? | ? | ? | ? | N/A | ? | + | **Network Security** | ? | ? | ? | ? | ? | ? | + | **Secrets Management** | ? | ? | ? | ? | ? | ? | + | **IAM/Permissions** | ? | ? | ? | ? | ? | ? | + | **Access Control** | ? | ? | ? | ? | ? | ? | + | **Compliance/Best Practices** | ? | ? | ? | ? | ? | ? | + + **Instructions:** + - Review the JSON/HTML reports from each tool + - Count findings in each security category + - Identify which tools excel at detecting specific issue types + - Note unique findings detected by only one tool + +In `labs/submission6.md`, document: +- **Tool Comparison Matrix** - Comprehensive evaluation with all metrics +- **Category Analysis** - Tool performance across security domains +- **Top 5 Critical Findings** - Detailed analysis with remediation code examples +- **Tool Selection Guide** - Recommendations for different use cases +- **Lessons Learned** - Insights about tool effectiveness, false positives, and limitations +- **CI/CD Integration Strategy** - Practical multi-stage pipeline recommendations +- **Justification** - Explain your reasoning for tool choices and strategy + +--- + +## Acceptance Criteria + +- โœ… Branch `feature/lab6` exists with commits for each task. +- โœ… File `labs/submission6.md` contains required analysis for Tasks 1-3. +- โœ… Terraform scanned with tfsec, Checkov, and Terrascan. +- โœ… Pulumi scanned with KICS (Checkmarx). +- โœ… Ansible playbooks scanned with KICS (Checkmarx). +- โœ… Comparative analysis completed with tool evaluation matrices. +- โœ… All scan results and analysis outputs committed. +- โœ… PR from `feature/lab6` โ†’ **course repo main branch** is open. +- โœ… PR link submitted via Moodle before the deadline. + +--- + +## How to Submit + +1. Create a branch for this lab and push it to your fork: + + ```bash + git switch -c feature/lab6 + # create labs/submission6.md with your findings + git add labs/submission6.md labs/lab6/analysis/ + git commit -m "docs: add lab6 submission - IaC security scanning and comparative analysis" + git push -u origin feature/lab6 + ``` + +2. Open a PR from your fork's `feature/lab6` branch โ†’ **course repository's main branch**. + +3. In the PR description, include: + + ```text + - [x] Task 1 done โ€” Terraform & Pulumi scanning with multiple tools + - [x] Task 2 done โ€” Ansible security analysis + - [x] Task 3 done โ€” Comparative tool analysis and security insights + ``` + +4. **Copy the PR URL** and submit it via **Moodle before the deadline**. + +--- + +## Rubric (10 pts) + +| Criterion | Points | +| ---------------------------------------------------------------- | -----: | +| Task 1 โ€” Terraform & Pulumi scanning (multiple tools) + analysis | **5** | +| Task 2 โ€” Ansible scanning (KICS) + remediation | **2** | +| Task 3 โ€” Comparative analysis + security insights | **3** | +| **Total** | **10** | + +--- + +## Guidelines + +- Use clear Markdown headers to organize sections in `submission6.md`. +- Include evidence from tool outputs (JSON excerpts, command outputs) to support your analysis. +- Focus on practical insights about tool selection for IaC security. +- Provide actionable remediation steps for identified issues. +- Document any challenges encountered with different tools. + +
+Directory Structure After Lab + +``` +labs/lab6/ +โ”œโ”€โ”€ vulnerable-iac/ # Vulnerable code to scan (DO NOT MODIFY) +โ”‚ โ”œโ”€โ”€ terraform/ # 30 Terraform vulnerabilities +โ”‚ โ”œโ”€โ”€ pulumi/ # 21 Pulumi vulnerabilities +โ”‚ โ”œโ”€โ”€ ansible/ # 26 Ansible vulnerabilities +โ”‚ โ””โ”€โ”€ README.md # Vulnerability catalog +โ”œโ”€โ”€ analysis/ # All scan results and analysis +โ”‚ โ”œโ”€โ”€ tfsec-results.json +โ”‚ โ”œโ”€โ”€ tfsec-report.txt +โ”‚ โ”œโ”€โ”€ checkov-terraform-results.json +โ”‚ โ”œโ”€โ”€ checkov-terraform-report.txt +โ”‚ โ”œโ”€โ”€ terrascan-results.json +โ”‚ โ”œโ”€โ”€ terrascan-report.txt +โ”‚ โ”œโ”€โ”€ kics-pulumi-results.json +โ”‚ โ”œโ”€โ”€ kics-pulumi-report.html +โ”‚ โ”œโ”€โ”€ kics-pulumi-report.txt +โ”‚ โ”œโ”€โ”€ kics-ansible-results.json +โ”‚ โ”œโ”€โ”€ kics-ansible-report.html +โ”‚ โ”œโ”€โ”€ kics-ansible-report.txt +โ”‚ โ”œโ”€โ”€ tool-comparison.txt +โ”‚ โ”œโ”€โ”€ terraform-comparison.txt +โ”‚ โ”œโ”€โ”€ pulumi-analysis.txt +โ”‚ โ””โ”€โ”€ ansible-analysis.txt +โ””โ”€โ”€ submission6.md # Your submission document +``` + +
+ +
+Common Issues & Troubleshooting + +**Issue: Docker volume mount permission errors** +```bash +# Solution: Ensure you're running commands from the project root directory +pwd # Should show path ending in the course repo name +``` + +**Issue: jq command not found** +```bash +# Install jq for JSON parsing +# macOS: brew install jq +# Ubuntu: sudo apt-get install jq +# Windows WSL: sudo apt-get install jq +``` + +**Issue: Checkov output format** +```bash +# Checkov uses -o flag for output format (json, cli, sarif, etc.) +# Use shell redirection (>) to save output to a specific file +# Example: -o json > output.json +``` + +**Issue: KICS exits with non-zero exit code** +```bash +# This is expected when vulnerabilities are found +# We use "|| true" to continue execution and capture the output +# Alternative: Use --ignore-on-exit results to suppress non-zero exit codes +``` + +**Issue: KICS not detecting Pulumi files** +```bash +# Ensure Pulumi-vulnerable.yaml is in the scan directory +# KICS auto-detects Pulumi YAML files by extension and content +# Verify KICS version supports Pulumi (v1.6.x+) +# Use: docker run --rm checkmarx/kics:latest version +``` + +**Issue: KICS report directory not found** +```bash +# KICS creates the report directory automatically +# Ensure you're using -o flag with proper path: -o /src/kics-report +# The container path must match the mounted volume +``` + +
+ +
+Tool Comparison Reference + +**Terraform Scanning Tools:** +- **tfsec**: Fast, Terraform-specific scanner with low false positives +- **Checkov**: Policy-as-code approach with 1000+ built-in policies (supports Terraform, CloudFormation, K8s, Docker) +- **Terrascan**: OPA-based scanner with compliance framework mapping + +**Pulumi Scanning:** +- **KICS (Checkmarx)**: Open-source scanner with first-class Pulumi YAML support + - Dedicated Pulumi queries catalog for AWS, Azure, GCP, and Kubernetes + - Auto-detects Pulumi platform + - Announced Pulumi support in v1.6.x with continued expansion + - Provides JSON, HTML, SARIF, and console output formats + +**Ansible Scanning:** +- **KICS (Checkmarx)**: Open-source scanner with comprehensive Ansible security queries + - Dedicated Ansible queries catalog + - Detects secrets management issues, command injection, insecure configurations + - Same tool across Terraform, Pulumi, and Ansible for consistency + +**Tool Selection Guidelines: +- **tfsec**: Use for fast CI/CD scans, Terraform-specific checks +- **Checkov**: Use for comprehensive Terraform and multi-framework coverage (CloudFormation, K8s, Docker) +- **KICS**: Use for Pulumi and Ansible scanning with first-class support and extensive query catalog + - Provides unified scanning across Pulumi and Ansible + - Comprehensive security queries for AWS, Azure, GCP, Kubernetes resources + - Single tool for consistency across multiple IaC frameworks +- **Terrascan**: Use for compliance-focused scanning (PCI-DSS, HIPAA, etc.) +- **Conftest**: Use for custom organizational policy enforcement across all IaC types + +
+ +
+Common IaC Security Issues + +**Common Terraform & Pulumi Issues:** +- Unencrypted S3 buckets and RDS instances +- Security groups allowing 0.0.0.0/0 access +- Hardcoded credentials and secrets +- Missing resource tags for governance +- Overly permissive IAM policies +- Publicly accessible databases + +**Common Ansible Issues:** +- Hardcoded passwords in playbooks +- Missing `no_log` on sensitive tasks +- Overly permissive file permissions (0777) +- Using `shell` instead of proper modules +- Missing `become` privilege escalation controls +- Unencrypted Ansible Vault or missing vault usage + +**Security Requirements to Enforce:** +- Encryption requirements (at-rest and in-transit) +- Network segmentation and access controls +- Tagging standards for governance and cost allocation +- Region restrictions and compliance requirements +- IAM least-privilege principles +- Regular security assessments and audits + +
+ +
+Remediation Best Practices + +**Terraform & Pulumi Remediation:** +- Enable S3 bucket encryption with `server_side_encryption_configuration` +- Restrict security group ingress to specific CIDR blocks +- Use AWS Secrets Manager or Parameter Store for credentials +- Add required tags to all resources +- Implement least-privilege IAM policies +- Set RDS instances to `storage_encrypted = true` + +**Ansible Remediation:** +- Use Ansible Vault for all secrets: `ansible-vault encrypt vars.yml` +- Add `no_log: true` to tasks handling sensitive data +- Set proper file permissions (0644 for configs, 0600 for keys) +- Use Ansible modules instead of `shell`/`command` where possible +- Implement proper `become` with specific users +- Regular security updates in playbooks + +**Security Scanning Best Practices:** +- Integrate security scanning into CI/CD pipelines +- Use pre-commit hooks for early detection +- Run multiple tools for comprehensive coverage +- Regularly update scanning tools and their rule sets +- Document and track remediation progress +- Establish SLAs for fixing critical/high severity issues + +
diff --git a/labs/lab6/vulnerable-iac/README.md b/labs/lab6/vulnerable-iac/README.md new file mode 100644 index 00000000..65cc1e17 --- /dev/null +++ b/labs/lab6/vulnerable-iac/README.md @@ -0,0 +1,284 @@ +# Vulnerable Infrastructure-as-Code for Lab 6 + +โš ๏ธ **WARNING: This directory contains intentionally vulnerable code for educational purposes only!** + +## Overview + +This directory contains deliberately insecure Terraform, Pulumi, and Ansible code designed for Lab 6 - Infrastructure-as-Code Security. Students will use security scanning tools to identify and understand these vulnerabilities. + +## โš ๏ธ DO NOT USE IN PRODUCTION! + +**These files contain serious security vulnerabilities and should NEVER be used in real environments.** + +--- + +## ๐Ÿ“‚ Directory Structure + +``` +vulnerable-iac/ +โ”œโ”€โ”€ terraform/ +โ”‚ โ”œโ”€โ”€ main.tf # Public S3 buckets, hardcoded credentials +โ”‚ โ”œโ”€โ”€ security_groups.tf # Overly permissive firewall rules +โ”‚ โ”œโ”€โ”€ database.tf # Unencrypted databases, weak configurations +โ”‚ โ”œโ”€โ”€ iam.tf # Wildcard IAM permissions +โ”‚ โ””โ”€โ”€ variables.tf # Insecure default values +โ”œโ”€โ”€ pulumi/ +โ”‚ โ”œโ”€โ”€ __main__.py # Python-based infrastructure with 21 security issues +โ”‚ โ”œโ”€โ”€ Pulumi.yaml # Config with default secret values +โ”‚ โ”œโ”€โ”€ Pulumi-vulnerable.yaml # YAML-based Pulumi manifest (for KICS scanning) +โ”‚ โ””โ”€โ”€ requirements.txt # Python dependencies +โ””โ”€โ”€ ansible/ + โ”œโ”€โ”€ deploy.yml # Hardcoded secrets, poor practices + โ”œโ”€โ”€ configure.yml # Weak SSH config, security misconfigurations + โ””โ”€โ”€ inventory.ini # Credentials in plaintext +``` + +--- + +## ๐Ÿ”ด Terraform Vulnerabilities (30 issues) + +### Authentication & Credentials +1. Hardcoded AWS access key in provider configuration +2. Hardcoded AWS secret key in provider configuration +9. Hardcoded database password in plain text +30. Hardcoded API key in variables with default value + +### Storage Security +2. S3 bucket with public-read ACL +3. S3 bucket without encryption configuration +4. S3 bucket public access block disabled +16. DynamoDB table without encryption + +### Network Security +5. Security group allowing all traffic from 0.0.0.0/0 +6. SSH (port 22) accessible from anywhere +6. RDP (port 3389) accessible from anywhere +7. MySQL (port 3306) exposed to internet +7. PostgreSQL (port 5432) exposed to internet + +### Database Security +8. RDS instance without storage encryption +10. RDS instance publicly accessible +11. RDS backup retention set to 0 (no backups) +12. RDS deletion protection disabled +14. RDS multi-AZ disabled (no high availability) +15. RDS auto minor version upgrade disabled + +### IAM & Permissions +18. IAM policy with wildcard (*) actions and resources +19. IAM role with full S3 access on all resources +20. IAM user with inline policy granting excessive permissions +21. IAM access keys created for service account +22. IAM credentials exposed in outputs without sensitive flag +23. IAM policy allowing privilege escalation paths + +### Configuration Management +24. No region validation for resource deployment +25. Weak default password in variables +26. Public access enabled by default +27. Encryption disabled by default +28. SSH allowed from anywhere by default +29. Backup retention days set to 0 by default + +--- + +## ๐Ÿ”ด Pulumi Vulnerabilities (21+ issues) + +> **Note:** Pulumi code is provided in both Python (`__main__.py`) and YAML (`Pulumi-vulnerable.yaml`) formats. The YAML format is used for KICS scanning, which has first-class Pulumi YAML support. + +### Authentication & Credentials +1. Hardcoded AWS access key in provider +2. Hardcoded AWS secret key in provider +3. Hardcoded database password in code +4. Hardcoded API key in code +21. Default config values with secrets in Pulumi.yaml + +### Storage Security +3. S3 bucket with public-read ACL +4. S3 bucket without encryption configuration +17. DynamoDB table without server-side encryption +18. DynamoDB table without point-in-time recovery +19. EBS volume without encryption + +### Network Security +5. Security group allowing all traffic from 0.0.0.0/0 +6. SSH and RDP accessible from anywhere + +### Database Security +7. RDS instance without storage encryption +8. RDS instance publicly accessible +9. RDS backup retention set to 0 (no backups) +10. RDS deletion protection disabled + +### IAM & Permissions +11. IAM policy with wildcard (*) actions and resources +12. IAM role with full S3 access on all resources +16. Lambda function with overly permissive IAM role + +### Compute Security +13. EC2 instance without root volume encryption +14. Secrets exposed in EC2 user data + +### Secrets Management +15. Secrets exposed in Pulumi outputs (not marked as secret) + +### Logging & Monitoring +20. CloudWatch log group without retention policy +20. CloudWatch log group without KMS encryption + +--- + +## ๐Ÿ”ด Ansible Vulnerabilities (26 issues) + +### Secrets Management +1. Hardcoded database password in playbook vars +2. Hardcoded API key in playbook vars +3. Database connection string with credentials +20. SSL private key in plaintext +38. Global variables with secrets in inventory +41. Production using same credentials as development + +### Command Execution +4. Using shell module instead of proper apt module +5. MySQL command with password visible in logs +10. Downloading and executing script without verification +17. Shell command with potential injection vulnerability +32. Using raw module to flush firewall rules + +### File Permissions & Access +6. Configuration file with 0777 permissions (world-writable) +7. SSH private key with 0644 permissions (should be 0600) +16. Downloaded file with 0777 permissions + +### Authentication & Access Control +21. SELinux disabled +22. Passwordless sudo for all commands +23. SSH PermitRootLogin enabled +23. SSH PasswordAuthentication enabled +23. SSH PermitEmptyPasswords enabled +34. Authorized key added for root user + +### Logging & Monitoring +5. Sensitive command without no_log flag +13. Password hashing without no_log +14. Debug output exposing secrets +18. Password visible in task name +26. Passwords logged in plaintext files + +### Network Security +9. Firewall (ufw) disabled +25. Application listening on 0.0.0.0 (all interfaces) + +### Credential Management +11. Git credentials hardcoded in repository URL +35. Credentials in inventory file +36. Using root user with password authentication +37. SSH private key path in plaintext inventory + +### Configuration Security +15. Using 'latest' instead of pinned versions +24. Installing unnecessary development tools on production +28. Insecure temp file handling with predictable names +29. No timeout for long-running tasks +31. Fetching sensitive files without encryption +33. No checksum validation for templates +39. Insecure SSH connection settings (StrictHostKeyChecking=no) +40. No connection timeout configured + +### Error Handling +12. Ignoring errors for critical database migrations +30. No proper error handling in assertions + +--- + +## ๐Ÿ› ๏ธ Tools to Use + +Students should scan this code with: + +### Terraform +- **tfsec**: Fast Terraform security scanner +- **Checkov**: Policy-as-code security scanner +- **Terrascan**: OPA-based compliance scanner + +### Pulumi +- **KICS (Checkmarx)**: Open-source scanner with first-class Pulumi YAML support + - Dedicated Pulumi queries catalog (AWS/Azure/GCP/Kubernetes) + - Auto-detects Pulumi platform + - Provides comprehensive security analysis + +### Ansible +- **KICS (Checkmarx)**: Open-source scanner with comprehensive Ansible security queries + - Dedicated Ansible queries catalog + - Auto-detects Ansible playbooks + - Provides comprehensive security analysis + +### Policy-as-Code +- **Conftest/OPA**: Custom policy enforcement for all IaC types + +--- + +## ๐Ÿ“‹ Expected Student Outcomes + +Students should: +1. Identify all 80+ security vulnerabilities across Terraform, Pulumi, and Ansible code + - Note: Pulumi code includes both Python and YAML formats for comprehensive analysis +2. Compare detection capabilities of different tools +3. Compare security issues between declarative (Terraform HCL) and programmatic (Pulumi Python/YAML) IaC +4. Evaluate KICS's first-class Pulumi support and query catalog +5. Understand false positives vs true positives +6. Write custom policies to catch organizational-specific issues +7. Provide remediation steps for each vulnerability class +8. Recommend tool selection strategies for CI/CD pipelines + +--- + +## ๐Ÿ”ง How to Use (Students) + +```bash +# Copy vulnerable code to your lab directory +cp -r vulnerable-iac/terraform/* labs/lab6/terraform/ +cp -r vulnerable-iac/pulumi/* labs/lab6/pulumi/ +cp -r vulnerable-iac/ansible/* labs/lab6/ansible/ + +# Scan with multiple tools (see lab6.md for commands) +docker run --rm -v "$(pwd)/labs/lab6/terraform":/src aquasec/tfsec:latest /src +docker run --rm -v "$(pwd)/labs/lab6/terraform":/tf bridgecrew/checkov:latest -d /tf +docker run -t --rm -v "$(pwd)/labs/lab6/pulumi":/src checkmarx/kics:latest scan -p /src -o /src/kics-report --report-formats json,html +# ... and more +``` + +--- + +## ๐Ÿ“š Learning Resources + +- [OWASP Infrastructure as Code Security](https://owasp.org/www-project-devsecops/) +- [Terraform Security Best Practices](https://www.terraform.io/docs/cloud/guides/recommended-practices/index.html) +- [Pulumi Security Best Practices](https://www.pulumi.com/docs/guides/crossguard/) +- [Ansible Security Best Practices](https://docs.ansible.com/ansible/latest/user_guide/playbooks_best_practices.html) +- [CIS AWS Foundations Benchmark](https://www.cisecurity.org/benchmark/amazon_web_services) +- [CIS Distribution Independent Linux Benchmark](https://www.cisecurity.org/benchmark/distribution_independent_linux) + +--- + +## ๐Ÿ”’ Security Notice + +**These files are for educational purposes only. They contain intentional security vulnerabilities that would compromise real systems. Never deploy this code to any environment connected to the internet or containing real data.** + +--- + +## โœ… Validation + +To verify students have completed the lab successfully, check that they: +- [ ] Identified at least 20 Terraform vulnerabilities +- [ ] Identified at least 15 Pulumi vulnerabilities +- [ ] Identified at least 15 Ansible vulnerabilities +- [ ] Compared at least 4 scanning tools (tfsec, Checkov for Terraform, KICS for Pulumi, Terrascan, ansible-lint) +- [ ] Analyzed differences between Terraform (HCL) and Pulumi (Python/YAML) security issues +- [ ] Evaluated KICS's Pulumi-specific query catalog and platform support +- [ ] Created at least 3 custom OPA policies +- [ ] Provided remediation guidance +- [ ] Explained tool selection rationale + +--- + +*Lab created for F25-DevSecOps-Intro course* diff --git a/labs/lab6/vulnerable-iac/ansible/configure.yml b/labs/lab6/vulnerable-iac/ansible/configure.yml new file mode 100644 index 00000000..e87a4c4a --- /dev/null +++ b/labs/lab6/vulnerable-iac/ansible/configure.yml @@ -0,0 +1,140 @@ +--- +# Vulnerable Configuration Playbook for Lab 6 + +- name: Configure web servers (VULNERABLE) + hosts: all + become: true + gather_facts: yes + + vars: + # SECURITY ISSUE #20 - Plaintext secrets + ssl_private_key: | + -----BEGIN PRIVATE KEY----- + MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC7VJTUt... + -----END PRIVATE KEY----- + + admin_password: "Admin123!" + + tasks: + # SECURITY ISSUE #21 - No SELinux or AppArmor + - name: Disable SELinux + selinux: + state: disabled + when: ansible_os_family == "RedHat" + + # SECURITY ISSUE #22 - Permissive sudo configuration + - name: Configure sudo for app user + lineinfile: + path: /etc/sudoers + line: 'appuser ALL=(ALL) NOPASSWD: ALL' + validate: '/usr/sbin/visudo -cf %s' + # Allowing passwordless sudo for all commands! + + # SECURITY ISSUE #23 - Weak SSH configuration + - name: Configure SSH + lineinfile: + path: /etc/ssh/sshd_config + regexp: "{{ item.regexp }}" + line: "{{ item.line }}" + loop: + - { regexp: '^PermitRootLogin', line: 'PermitRootLogin yes' } # Should be 'no'! + - { regexp: '^PasswordAuthentication', line: 'PasswordAuthentication yes' } # Should be 'no'! + - { regexp: '^PermitEmptyPasswords', line: 'PermitEmptyPasswords yes' } # Should be 'no'! + notify: restart sshd + + # SECURITY ISSUE #24 - Installing unnecessary packages + - name: Install all development tools + apt: + name: + - build-essential + - gcc + - g++ + - gdb + - strace + - tcpdump + state: present + # Development tools on production server! + + # SECURITY ISSUE #25 - Exposing application on all interfaces + - name: Configure application to listen on all interfaces + lineinfile: + path: /etc/myapp/config.yml + regexp: '^listen:' + line: 'listen: 0.0.0.0:8080' + # Should bind to specific interface or localhost + + # SECURITY ISSUE #26 - Logging sensitive information + - name: Log database connection + lineinfile: + path: /var/log/myapp/app.log + line: "Database connection: postgresql://admin:{{ admin_password }}@localhost/myapp" + create: yes + # Logging password in plaintext! + + # SECURITY ISSUE #27 - Using vars_prompt without no_log + - name: Set API credentials + command: echo "API_KEY={{ api_key }}" >> /etc/environment + # Credentials in command output + + # SECURITY ISSUE #28 - Insecure temp file handling + - name: Create temporary file + shell: echo "{{ admin_password }}" > /tmp/password.txt + # Password in temp file with predictable name! + + # SECURITY ISSUE #29 - No timeout for long-running tasks + - name: Wait for service + wait_for: + port: 8080 + delay: 10 + timeout: 0 # Wait forever! + + # SECURITY ISSUE #30 - Using assert without proper error handling + - name: Check configuration + assert: + that: + - ansible_os_family == "Debian" + fail_msg: "Unsupported OS" + # Exposing system information in error + + # SECURITY ISSUE #31 - Fetching files without encryption + - name: Backup configuration + fetch: + src: /etc/myapp/config.env + dest: /backups/ + flat: yes + # Transferring sensitive config in plaintext! + + # SECURITY ISSUE #32 - Using raw module + - name: Execute raw command + raw: iptables -F # Flush all firewall rules! + # Should use proper firewall modules + + # SECURITY ISSUE #33 - No checksum validation for templates + - name: Deploy configuration template + template: + src: app.conf.j2 + dest: /etc/nginx/sites-available/app.conf + mode: '0644' + # No backup, no validation before deployment + notify: reload nginx + + # SECURITY ISSUE #34 - Authorized_key with wrong permissions + - name: Add authorized key + authorized_key: + user: root + key: "{{ lookup('file', '/tmp/id_rsa.pub') }}" + state: present + # Adding key for root user! + + handlers: + - name: restart sshd + service: + name: sshd + state: restarted + # No validation of sshd config before restart! + + - name: reload nginx + service: + name: nginx + state: reloaded + # No config test before reload! diff --git a/labs/lab6/vulnerable-iac/ansible/deploy.yml b/labs/lab6/vulnerable-iac/ansible/deploy.yml new file mode 100644 index 00000000..9f7edece --- /dev/null +++ b/labs/lab6/vulnerable-iac/ansible/deploy.yml @@ -0,0 +1,128 @@ +--- +# Vulnerable Ansible Playbook for Lab 6 +# This file contains intentional security issues for educational purposes +# DO NOT use this playbook in production! + +- name: Deploy web application (VULNERABLE) + hosts: webservers + become: yes + + vars: + # SECURITY ISSUE #1 - Hardcoded password in playbook! + db_password: "SuperSecret123!" + # SECURITY ISSUE #2 - Hardcoded API key! + api_key: "sk_live_1234567890abcdef" + # SECURITY ISSUE #3 - Database connection string with credentials + db_connection: "postgresql://admin:password123@db.example.com:5432/myapp" + + tasks: + # SECURITY ISSUE #4 - Using shell instead of proper module + - name: Install packages with shell + shell: apt-get install -y nginx mysql-client + # Should use apt module instead + + # SECURITY ISSUE #5 - Command with hardcoded password visible in logs + - name: Set database password + command: mysql -u root -p{{ db_password }} -e "CREATE DATABASE myapp;" + # Missing no_log: true - password will appear in logs! + + # SECURITY ISSUE #6 - File with overly permissive permissions + - name: Create config file + copy: + content: | + DB_PASSWORD={{ db_password }} + API_KEY={{ api_key }} + dest: /etc/myapp/config.env + mode: '0777' # World readable/writable! + owner: root + group: root + + # SECURITY ISSUE #7 - SSH key with wrong permissions + - name: Deploy SSH key + copy: + src: files/id_rsa + dest: /root/.ssh/id_rsa + mode: '0644' # Should be 0600! + owner: root + group: root + + # SECURITY ISSUE #8 - Running command as root without necessity + - name: Create application directory + command: mkdir -p /var/www/myapp + become: yes + become_user: root + # Should use file module and run as regular user + + # SECURITY ISSUE #9 - Disabling firewall + - name: Disable firewall + service: + name: ufw + state: stopped + enabled: no + # Should never disable firewall! + + # SECURITY ISSUE #10 - Downloading and executing script without verification + - name: Download and run setup script + shell: curl http://example.com/setup.sh | bash + # No HTTPS, no checksum verification! + + # SECURITY ISSUE #11 - Git clone with hardcoded credentials in URL + - name: Clone repository + git: + repo: 'https://username:password@github.com/company/repo.git' + dest: /var/www/myapp + # Credentials in URL! + + # SECURITY ISSUE #12 - Ignoring errors + - name: Run database migration + command: /usr/local/bin/migrate + ignore_errors: yes + # Should not ignore errors for critical tasks + + # SECURITY ISSUE #13 - Using deprecated bare variables + - name: Create user + user: + name: "{{ username }}" # Variable not defined, will fail + password: "{{ password | password_hash('sha512') }}" + # Password operation without no_log! + + # SECURITY ISSUE #14 - Debug statement exposing secrets + - name: Debug configuration + debug: + msg: "Database: {{ db_connection }}, API Key: {{ api_key }}" + # Exposing secrets in debug output! + + # SECURITY ISSUE #15 - Using latest version (non-deterministic) + - name: Install application + apt: + name: myapp + state: latest # Should pin specific version + update_cache: yes + + # SECURITY ISSUE #16 - No validation of downloaded files + - name: Download application + get_url: + url: http://example.com/app.tar.gz # HTTP not HTTPS! + dest: /tmp/app.tar.gz + # No checksum validation! + mode: '0777' + + # SECURITY ISSUE #17 - Running with shell expansion + - name: Process files + shell: rm -rf {{ user_input }}/* + # Shell injection risk if user_input is not sanitized! + + # SECURITY ISSUE #18 - Synchronous password in task name + - name: Set password to SuperSecret123! + # Task name exposes password! + user: + name: appuser + password: "{{ 'SuperSecret123!' | password_hash('sha512') }}" + + handlers: + # SECURITY ISSUE #19 - Handler without proper service check + - name: restart nginx + service: + name: nginx + state: restarted + # No validation that nginx is properly configured before restart diff --git a/labs/lab6/vulnerable-iac/ansible/inventory.ini b/labs/lab6/vulnerable-iac/ansible/inventory.ini new file mode 100644 index 00000000..8dc56497 --- /dev/null +++ b/labs/lab6/vulnerable-iac/ansible/inventory.ini @@ -0,0 +1,38 @@ +# Vulnerable Ansible Inventory for Lab 6 +# SECURITY ISSUE #35 - Credentials in inventory file! + +[webservers] +web1.example.com ansible_user=root ansible_password=RootPass123! +web2.example.com ansible_user=root ansible_ssh_pass=RootPass123! + +[databases] +# SECURITY ISSUE #36 - Using root user and default port +db1.example.com ansible_user=root ansible_port=22 ansible_password=DbPass123! + +[appservers] +# SECURITY ISSUE #37 - Private key path in plaintext +app1.example.com ansible_user=deploy ansible_ssh_private_key_file=/tmp/insecure_key + +[all:vars] +# SECURITY ISSUE #38 - Global variables with secrets +ansible_become_password=Sudo123! +db_admin_password=AdminDB123! +api_secret_key=sk_live_abcdef1234567890 + +# SECURITY ISSUE #39 - Using insecure connection settings +ansible_ssh_common_args='-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null' + +# SECURITY ISSUE #40 - No connection timeout +ansible_connection=ssh +ansible_ssh_timeout=0 + +[production:children] +webservers +databases +appservers + +[production:vars] +environment=production +# SECURITY ISSUE #41 - Production using same credentials as dev +admin_user=admin +admin_pass=AdminProd123! diff --git a/labs/lab6/vulnerable-iac/pulumi/Pulumi-vulnerable.yaml b/labs/lab6/vulnerable-iac/pulumi/Pulumi-vulnerable.yaml new file mode 100644 index 00000000..469d7624 --- /dev/null +++ b/labs/lab6/vulnerable-iac/pulumi/Pulumi-vulnerable.yaml @@ -0,0 +1,279 @@ +# +# Vulnerable Pulumi YAML Configuration for Lab 6 +# This file contains intentional security issues for educational purposes +# DO NOT use this code in production! +# +# KICS Documentation: https://docs.kics.io +# Pulumi YAML Queries: https://docs.kics.io/latest/queries/pulumi-queries/ +# + +name: vulnerable-pulumi-lab6 +runtime: yaml +description: Intentionally vulnerable Pulumi infrastructure for Lab 6 - DO NOT USE IN PRODUCTION! + +variables: + # SECURITY ISSUE #1 - Hardcoded database password + dbPassword: "SuperSecret123!" + + # SECURITY ISSUE #2 - Hardcoded API key + apiKey: "sk_live_1234567890abcdef" + + awsRegion: "us-east-1" + +resources: + # SECURITY ISSUE #3 - Public S3 bucket + publicBucket: + type: aws:s3:Bucket + properties: + bucket: my-public-bucket-pulumi-yaml + acl: public-read # Public access! + tags: + Name: "Public Bucket" + # Missing required tags: Environment, Owner, CostCenter + + # SECURITY ISSUE #4 - S3 bucket without encryption + unencryptedBucket: + type: aws:s3:Bucket + properties: + bucket: my-unencrypted-bucket-pulumi-yaml + acl: private + versioning: + enabled: false # Versioning disabled + tags: + Name: "Unencrypted Bucket" + # No serverSideEncryptionConfiguration! + + # SECURITY ISSUE #5 - Security group allowing all traffic from anywhere + allowAllSg: + type: aws:ec2:SecurityGroup + properties: + name: allow-all-sg-yaml + description: "Allow all inbound traffic" + vpcId: vpc-12345678 + ingress: + - description: "Allow all traffic" + fromPort: 0 + toPort: 65535 + protocol: "-1" # All protocols + cidrBlocks: + - "0.0.0.0/0" # From anywhere! + egress: + - fromPort: 0 + toPort: 0 + protocol: "-1" + cidrBlocks: + - "0.0.0.0/0" + tags: + Name: "Allow All Security Group" + + # SECURITY ISSUE #6 - SSH and RDP open to the world + sshOpenSg: + type: aws:ec2:SecurityGroup + properties: + name: ssh-open-sg-yaml + description: "SSH and RDP from anywhere" + vpcId: vpc-12345678 + ingress: + - description: "SSH from anywhere" + fromPort: 22 + toPort: 22 + protocol: tcp + cidrBlocks: + - "0.0.0.0/0" # SSH from anywhere! + - description: "RDP from anywhere" + fromPort: 3389 + toPort: 3389 + protocol: tcp + cidrBlocks: + - "0.0.0.0/0" # RDP from anywhere! + tags: + Name: "SSH Open" + + # SECURITY ISSUE #7 & #8 - Unencrypted and publicly accessible RDS instance + unencryptedDb: + type: aws:rds:Instance + properties: + identifier: mydb-unencrypted-pulumi-yaml + engine: postgres + engineVersion: "13.7" + instanceClass: db.t3.micro + allocatedStorage: 20 + username: admin + password: ${dbPassword} # Using hardcoded password! + storageEncrypted: false # SECURITY ISSUE #7 - No encryption! + publiclyAccessible: true # SECURITY ISSUE #8 - Public access! + skipFinalSnapshot: true + backupRetentionPeriod: 0 # SECURITY ISSUE #9 - No backups! + deletionProtection: false # SECURITY ISSUE #10 + vpcSecurityGroupIds: + - ${allowAllSg.id} + tags: + Name: "Unencrypted Database" + + # SECURITY ISSUE #11 - IAM policy with wildcard permissions + adminPolicy: + type: aws:iam:Policy + properties: + name: admin-policy-yaml + description: "Policy with wildcard permissions" + policy: + fn::toJSON: + Version: "2012-10-17" + Statement: + - Effect: Allow + Action: "*" # Wildcard action! + Resource: "*" # Wildcard resource! + + # SECURITY ISSUE #12 - IAM role with overly permissive S3 access + appRole: + type: aws:iam:Role + properties: + name: app-role-yaml + assumeRolePolicy: + fn::toJSON: + Version: "2012-10-17" + Statement: + - Action: sts:AssumeRole + Effect: Allow + Principal: + Service: ec2.amazonaws.com + + s3FullAccessPolicy: + type: aws:iam:RolePolicy + properties: + name: s3-full-access-yaml + role: ${appRole.id} + policy: + fn::toJSON: + Version: "2012-10-17" + Statement: + - Effect: Allow + Action: "s3:*" # Full S3 access! + Resource: "*" # All resources! + + # SECURITY ISSUE #13 & #14 - EC2 instance without encryption and secrets in user data + unencryptedInstance: + type: aws:ec2:Instance + properties: + ami: ami-0c55b159cbfafe1f0 + instanceType: t2.micro + vpcSecurityGroupIds: + - ${sshOpenSg.id} + userData: + fn::toJSON: + - "#!/bin/bash" + - "echo 'DB_PASSWORD=${dbPassword}' > /etc/app/config" # Password in user data! + - "echo 'API_KEY=${apiKey}' >> /etc/app/config" + tags: + Name: "Unencrypted Instance" + # No root block device encryption specified! + + # SECURITY ISSUE #16 - Lambda function with overly permissive IAM role + lambdaRole: + type: aws:iam:Role + properties: + name: lambda-role-yaml + assumeRolePolicy: + fn::toJSON: + Version: "2012-10-17" + Statement: + - Action: sts:AssumeRole + Effect: Allow + Principal: + Service: lambda.amazonaws.com + + lambdaPolicy: + type: aws:iam:RolePolicy + properties: + name: lambda-policy-yaml + role: ${lambdaRole.id} + policy: + fn::toJSON: + Version: "2012-10-17" + Statement: + - Effect: Allow + Action: + - "s3:*" + - "dynamodb:*" + - "rds:*" + - "ec2:*" + Resource: "*" + + # SECURITY ISSUE #17 & #18 - DynamoDB table without encryption or PITR + unencryptedTable: + type: aws:dynamodb:Table + properties: + name: my-table-pulumi-yaml + attributes: + - name: id + type: S + hashKey: id + billingMode: PAY_PER_REQUEST + pointInTimeRecovery: + enabled: false # SECURITY ISSUE #18 - No PITR + tags: + Name: "Unencrypted Table" + # No serverSideEncryption specified! SECURITY ISSUE #17 + + # SECURITY ISSUE #19 - EBS volume without encryption + unencryptedVolume: + type: aws:ebs:Volume + properties: + availabilityZone: us-east-1a + size: 10 + encrypted: false # No encryption! + tags: + Name: "Unencrypted Volume" + + # SECURITY ISSUE #20 - CloudWatch log group without retention or KMS encryption + logGroup: + type: aws:cloudwatch:LogGroup + properties: + name: /aws/app/logs-yaml + retentionInDays: 0 # Logs never expire - cost and compliance issue + # No kmsKeyId specified - no encryption! + + # SECURITY ISSUE #21 - EKS cluster without encryption + eksCluster: + type: aws:eks:Cluster + properties: + name: vulnerable-eks-yaml + roleArn: ${appRole.arn} + vpcConfig: + subnetIds: + - subnet-12345678 + - subnet-87654321 + endpointPublicAccess: true # Public access enabled + publicAccessCidrs: + - "0.0.0.0/0" # Accessible from anywhere! + # No encryptionConfig specified! + +# SECURITY ISSUE #15 - Exposing secrets in outputs (not marked as secret) +outputs: + bucketName: + value: ${publicBucket.id} + + dbEndpoint: + value: ${unencryptedDb.endpoint} + + # These outputs expose sensitive data! + dbPassword: + value: ${dbPassword} + + apiKey: + value: ${apiKey} + + region: + value: ${awsRegion} + +# Configuration with default secret values - SECURITY ISSUE +config: + aws:region: + default: us-east-1 + + # Should not have defaults for sensitive values! + db_password: + default: "DefaultPass123!" + + api_key: + default: "sk_default_key" diff --git a/labs/lab6/vulnerable-iac/pulumi/Pulumi.yaml b/labs/lab6/vulnerable-iac/pulumi/Pulumi.yaml new file mode 100644 index 00000000..f0d65d01 --- /dev/null +++ b/labs/lab6/vulnerable-iac/pulumi/Pulumi.yaml @@ -0,0 +1,12 @@ +name: vulnerable-pulumi-lab6 +runtime: python +description: Intentionally vulnerable Pulumi infrastructure for Lab 6 - DO NOT USE IN PRODUCTION! + +config: + # SECURITY ISSUE #21 - Default config values with secrets + aws:region: + default: us-east-1 + db_password: + default: "DefaultPass123!" # Should not have default for passwords! + api_key: + default: "sk_default_key" # Should not have default for secrets! diff --git a/labs/lab6/vulnerable-iac/pulumi/__main__.py b/labs/lab6/vulnerable-iac/pulumi/__main__.py new file mode 100644 index 00000000..57f3d669 --- /dev/null +++ b/labs/lab6/vulnerable-iac/pulumi/__main__.py @@ -0,0 +1,248 @@ +""" +Vulnerable Pulumi Infrastructure Code for Lab 6 +This file contains intentional security issues for educational purposes +DO NOT use this code in production! + +Language: Python +Cloud: AWS +""" + +import pulumi +import pulumi_aws as aws + +# SECURITY ISSUE #1 - Hardcoded AWS credentials +aws_provider = aws.Provider("aws-provider", + region="us-east-1", + access_key="AKIAIOSFODNN7EXAMPLE", # Hardcoded! + secret_key="wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY" # Hardcoded! +) + +# SECURITY ISSUE #2 - Hardcoded secrets in config +config = pulumi.Config() +db_password = "SuperSecret123!" # Should use config.require_secret() +api_key = "sk_live_1234567890abcdef" # Hardcoded API key + +# SECURITY ISSUE #3 - Public S3 bucket +public_bucket = aws.s3.Bucket("public-bucket", + bucket="my-public-bucket-pulumi", + acl="public-read", # Public access! + tags={ + "Name": "Public Bucket", + # Missing required tags: Environment, Owner + } +) + +# SECURITY ISSUE #4 - S3 bucket without encryption +unencrypted_bucket = aws.s3.Bucket("unencrypted-bucket", + bucket="my-unencrypted-bucket-pulumi", + acl="private", + # No server_side_encryption_configuration! + versioning=aws.s3.BucketVersioningArgs( + enabled=False # Versioning disabled + ), + tags={ + "Name": "Unencrypted Bucket" + } +) + +# SECURITY ISSUE #5 - Security group allowing all traffic from anywhere +allow_all_sg = aws.ec2.SecurityGroup("allow-all-sg", + description="Allow all inbound traffic", + vpc_id="vpc-12345678", + ingress=[ + aws.ec2.SecurityGroupIngressArgs( + description="Allow all traffic", + from_port=0, + to_port=65535, + protocol="-1", # All protocols + cidr_blocks=["0.0.0.0/0"], # From anywhere! + ) + ], + egress=[ + aws.ec2.SecurityGroupEgressArgs( + from_port=0, + to_port=0, + protocol="-1", + cidr_blocks=["0.0.0.0/0"], + ) + ], + tags={ + "Name": "Allow All Security Group" + } +) + +# SECURITY ISSUE #6 - SSH open to the world +ssh_open_sg = aws.ec2.SecurityGroup("ssh-open-sg", + description="SSH from anywhere", + vpc_id="vpc-12345678", + ingress=[ + aws.ec2.SecurityGroupIngressArgs( + description="SSH from anywhere", + from_port=22, + to_port=22, + protocol="tcp", + cidr_blocks=["0.0.0.0/0"], # SSH from anywhere! + ), + aws.ec2.SecurityGroupIngressArgs( + description="RDP from anywhere", + from_port=3389, + to_port=3389, + protocol="tcp", + cidr_blocks=["0.0.0.0/0"], # RDP from anywhere! + ) + ], + tags={ + "Name": "SSH Open" + } +) + +# SECURITY ISSUE #7 - Unencrypted RDS instance +unencrypted_db = aws.rds.Instance("unencrypted-db", + identifier="mydb-unencrypted-pulumi", + engine="postgres", + engine_version="13.7", + instance_class="db.t3.micro", + allocated_storage=20, + username="admin", + password=db_password, # Hardcoded password from above! + storage_encrypted=False, # No encryption! + publicly_accessible=True, # SECURITY ISSUE #8 - Public access! + skip_final_snapshot=True, + backup_retention_period=0, # SECURITY ISSUE #9 - No backups! + deletion_protection=False, # SECURITY ISSUE #10 + vpc_security_group_ids=[allow_all_sg.id], + tags={ + "Name": "Unencrypted Database" + } +) + +# SECURITY ISSUE #11 - IAM policy with wildcard permissions +admin_policy = aws.iam.Policy("admin-policy", + description="Policy with wildcard permissions", + policy=pulumi.Output.all().apply(lambda _: """{ + "Version": "2012-10-17", + "Statement": [{ + "Effect": "Allow", + "Action": "*", + "Resource": "*" + }] + }""") +) + +# SECURITY ISSUE #12 - IAM role with overly permissive S3 access +app_role = aws.iam.Role("app-role", + assume_role_policy=pulumi.Output.all().apply(lambda _: """{ + "Version": "2012-10-17", + "Statement": [{ + "Action": "sts:AssumeRole", + "Effect": "Allow", + "Principal": { + "Service": "ec2.amazonaws.com" + } + }] + }""") +) + +s3_full_access_policy = aws.iam.RolePolicy("s3-full-access", + role=app_role.id, + policy=pulumi.Output.all().apply(lambda _: """{ + "Version": "2012-10-17", + "Statement": [{ + "Effect": "Allow", + "Action": "s3:*", + "Resource": "*" + }] + }""") +) + +# SECURITY ISSUE #13 - EC2 instance without encryption +unencrypted_instance = aws.ec2.Instance("unencrypted-instance", + ami="ami-0c55b159cbfafe1f0", + instance_type="t2.micro", + vpc_security_group_ids=[ssh_open_sg.id], + # No root_block_device encryption! + user_data=f"""#!/bin/bash + echo "DB_PASSWORD={db_password}" > /etc/app/config # SECURITY ISSUE #14 - Password in user data! + echo "API_KEY={api_key}" >> /etc/app/config + """, + tags={ + "Name": "Unencrypted Instance" + } +) + +# SECURITY ISSUE #15 - Exposing secrets in outputs (not marked as secret) +pulumi.export("bucket_name", public_bucket.id) +pulumi.export("db_endpoint", unencrypted_db.endpoint) +pulumi.export("db_password", db_password) # Exposing password! +pulumi.export("api_key", api_key) # Exposing API key! + +# SECURITY ISSUE #16 - Lambda function with overly permissive IAM role +lambda_role = aws.iam.Role("lambda-role", + assume_role_policy=pulumi.Output.all().apply(lambda _: """{ + "Version": "2012-10-17", + "Statement": [{ + "Action": "sts:AssumeRole", + "Effect": "Allow", + "Principal": { + "Service": "lambda.amazonaws.com" + } + }] + }""") +) + +lambda_policy = aws.iam.RolePolicy("lambda-policy", + role=lambda_role.id, + policy=pulumi.Output.all().apply(lambda _: """{ + "Version": "2012-10-17", + "Statement": [{ + "Effect": "Allow", + "Action": [ + "s3:*", + "dynamodb:*", + "rds:*", + "ec2:*" + ], + "Resource": "*" + }] + }""") +) + +# SECURITY ISSUE #17 - DynamoDB table without encryption +unencrypted_table = aws.dynamodb.Table("unencrypted-table", + name="my-table-pulumi", + attributes=[ + aws.dynamodb.TableAttributeArgs( + name="id", + type="S", + ) + ], + hash_key="id", + billing_mode="PAY_PER_REQUEST", + # No server_side_encryption! + point_in_time_recovery=aws.dynamodb.TablePointInTimeRecoveryArgs( + enabled=False # SECURITY ISSUE #18 - No PITR + ), + tags={ + "Name": "Unencrypted Table" + } +) + +# SECURITY ISSUE #19 - EBS volume without encryption +unencrypted_volume = aws.ebs.Volume("unencrypted-volume", + availability_zone="us-east-1a", + size=10, + encrypted=False, # No encryption! + tags={ + "Name": "Unencrypted Volume" + } +) + +# SECURITY ISSUE #20 - CloudWatch log group without retention +log_group = aws.cloudwatch.LogGroup("app-logs", + name="/aws/app/logs", + retention_in_days=0, # Logs never expire - cost and compliance issue + # No KMS encryption! +) + +print(f"โš ๏ธ WARNING: This Pulumi stack contains {20} intentional security vulnerabilities!") +print(" This is for educational purposes only - DO NOT deploy to production!") diff --git a/labs/lab6/vulnerable-iac/pulumi/requirements.txt b/labs/lab6/vulnerable-iac/pulumi/requirements.txt new file mode 100644 index 00000000..5f626e8c --- /dev/null +++ b/labs/lab6/vulnerable-iac/pulumi/requirements.txt @@ -0,0 +1,2 @@ +pulumi>=3.0.0,<4.0.0 +pulumi-aws>=6.0.0,<7.0.0 diff --git a/labs/lab6/vulnerable-iac/terraform/database.tf b/labs/lab6/vulnerable-iac/terraform/database.tf new file mode 100644 index 00000000..1897f378 --- /dev/null +++ b/labs/lab6/vulnerable-iac/terraform/database.tf @@ -0,0 +1,92 @@ +# Vulnerable Database Configuration for Lab 6 +# Contains unencrypted databases and poor security practices + +# Unencrypted RDS instance - SECURITY ISSUE #8 +resource "aws_db_instance" "unencrypted_db" { + identifier = "mydb-unencrypted" + engine = "postgres" + engine_version = "13.7" + instance_class = "db.t3.micro" + allocated_storage = 20 + + username = "admin" + password = "SuperSecretPassword123!" # SECURITY ISSUE #9 - Hardcoded password! + + storage_encrypted = false # No encryption! + + publicly_accessible = true # SECURITY ISSUE #10 - Public access! + + skip_final_snapshot = true + + # No backup configuration + backup_retention_period = 0 # SECURITY ISSUE #11 - No backups! + + # Missing monitoring + enabled_cloudwatch_logs_exports = [] + + # No deletion protection + deletion_protection = false # SECURITY ISSUE #12 + + # Using default security group + vpc_security_group_ids = [aws_security_group.database_exposed.id] + + tags = { + Name = "Unencrypted Database" + # Missing required tags + } +} + +# Database with weak configuration - SECURITY ISSUE #13 +resource "aws_db_instance" "weak_db" { + identifier = "mydb-weak" + engine = "mysql" + engine_version = "5.7.38" # Old version with known vulnerabilities + instance_class = "db.t3.micro" + allocated_storage = 20 + + username = "root" # Using default admin username + password = "password123" # Weak password! + + storage_encrypted = true + kms_key_id = "" # Empty KMS key - using default key + + publicly_accessible = false + + # Multi-AZ disabled + multi_az = false # SECURITY ISSUE #14 - No high availability + + # Auto minor version upgrade disabled + auto_minor_version_upgrade = false # SECURITY ISSUE #15 + + # No performance insights + performance_insights_enabled = false + + skip_final_snapshot = true + + tags = { + Name = "Weak Database" + } +} + +# DynamoDB table without encryption - SECURITY ISSUE #16 +resource "aws_dynamodb_table" "unencrypted_table" { + name = "my-table" + billing_mode = "PAY_PER_REQUEST" + hash_key = "id" + + attribute { + name = "id" + type = "S" + } + + # No server_side_encryption configuration! + + # No point-in-time recovery + point_in_time_recovery { + enabled = false # SECURITY ISSUE #17 + } + + tags = { + Name = "Unencrypted DynamoDB Table" + } +} diff --git a/labs/lab6/vulnerable-iac/terraform/iam.tf b/labs/lab6/vulnerable-iac/terraform/iam.tf new file mode 100644 index 00000000..8ac6746f --- /dev/null +++ b/labs/lab6/vulnerable-iac/terraform/iam.tf @@ -0,0 +1,125 @@ +# Vulnerable IAM Configuration for Lab 6 +# Contains overly permissive IAM policies + +# IAM policy with wildcard permissions - SECURITY ISSUE #18 +resource "aws_iam_policy" "admin_policy" { + name = "overly-permissive-policy" + description = "Policy with wildcard permissions" + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Action = "*" # All actions allowed! + Resource = "*" # On all resources! + } + ] + }) +} + +# IAM role with full S3 access - SECURITY ISSUE #19 +resource "aws_iam_role" "app_role" { + name = "application-role" + + assume_role_policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Action = "sts:AssumeRole" + Effect = "Allow" + Principal = { + Service = "ec2.amazonaws.com" + } + } + ] + }) +} + +resource "aws_iam_role_policy" "s3_full_access" { + name = "s3-full-access" + role = aws_iam_role.app_role.id + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Action = [ + "s3:*" # All S3 actions! + ] + Resource = "*" # On all buckets! + } + ] + }) +} + +# IAM user with inline policy - SECURITY ISSUE #20 +resource "aws_iam_user" "service_account" { + name = "service-account" + path = "/system/" + + tags = { + Name = "Service Account" + } +} + +resource "aws_iam_user_policy" "service_policy" { + name = "service-inline-policy" + user = aws_iam_user.service_account.name + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Action = [ + "ec2:*", # Full EC2 access + "s3:*", # Full S3 access + "rds:*" # Full RDS access + ] + Resource = "*" + } + ] + }) +} + +# Access key for IAM user - SECURITY ISSUE #21 +resource "aws_iam_access_key" "service_key" { + user = aws_iam_user.service_account.name +} + +# Output sensitive data - SECURITY ISSUE #22 +output "access_key_id" { + value = aws_iam_access_key.service_key.id + # Should be marked as sensitive! +} + +output "secret_access_key" { + value = aws_iam_access_key.service_key.secret + # Exposing secret key in output! +} + +# IAM policy allowing privilege escalation - SECURITY ISSUE #23 +resource "aws_iam_policy" "privilege_escalation" { + name = "potential-privilege-escalation" + description = "Policy that allows privilege escalation" + + policy = jsonencode({ + Version = "2012-10-17" + Statement = [ + { + Effect = "Allow" + Action = [ + "iam:CreatePolicy", + "iam:CreateUser", + "iam:AttachUserPolicy", + "iam:AttachRolePolicy", + "iam:PutUserPolicy", + "iam:PutRolePolicy" + ] + Resource = "*" + } + ] + }) +} diff --git a/labs/lab6/vulnerable-iac/terraform/main.tf b/labs/lab6/vulnerable-iac/terraform/main.tf new file mode 100644 index 00000000..027cdecf --- /dev/null +++ b/labs/lab6/vulnerable-iac/terraform/main.tf @@ -0,0 +1,43 @@ +# Vulnerable Terraform Configuration for Lab 6 +# This file contains intentional security issues for educational purposes +# DO NOT use this code in production! + +provider "aws" { + region = "us-east-1" + # Hardcoded credentials - SECURITY ISSUE #1 + access_key = "AKIAIOSFODNN7EXAMPLE" + secret_key = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY" +} + +# Public S3 bucket - SECURITY ISSUE #2 +resource "aws_s3_bucket" "public_data" { + bucket = "my-public-bucket-lab6" + acl = "public-read" # Public access enabled! + + tags = { + Name = "Public Data Bucket" + # Missing required tags: Environment, Owner, CostCenter + } +} + +# S3 bucket without encryption - SECURITY ISSUE #3 +resource "aws_s3_bucket" "unencrypted_data" { + bucket = "my-unencrypted-bucket-lab6" + acl = "private" + + # No server_side_encryption_configuration! + + versioning { + enabled = false # Versioning disabled + } +} + +# S3 bucket with public access block disabled - SECURITY ISSUE #4 +resource "aws_s3_bucket_public_access_block" "bad_config" { + bucket = aws_s3_bucket.public_data.id + + block_public_acls = false # Should be true + block_public_policy = false # Should be true + ignore_public_acls = false # Should be true + restrict_public_buckets = false # Should be true +} diff --git a/labs/lab6/vulnerable-iac/terraform/security_groups.tf b/labs/lab6/vulnerable-iac/terraform/security_groups.tf new file mode 100644 index 00000000..88f706d5 --- /dev/null +++ b/labs/lab6/vulnerable-iac/terraform/security_groups.tf @@ -0,0 +1,92 @@ +# Vulnerable Security Groups for Lab 6 +# Contains overly permissive network rules + +# Security group allowing ALL traffic from anywhere - SECURITY ISSUE #5 +resource "aws_security_group" "allow_all" { + name = "allow-all-traffic" + description = "Allow all inbound traffic from anywhere" + vpc_id = "vpc-12345678" + + ingress { + description = "Allow all traffic" + from_port = 0 + to_port = 65535 + protocol = "-1" # All protocols + cidr_blocks = ["0.0.0.0/0"] # From anywhere! + } + + egress { + from_port = 0 + to_port = 0 + protocol = "-1" + cidr_blocks = ["0.0.0.0/0"] + } + + tags = { + Name = "Allow All Security Group" + } +} + +# Security group with SSH open to the world - SECURITY ISSUE #6 +resource "aws_security_group" "ssh_open" { + name = "ssh-from-anywhere" + description = "SSH access from anywhere" + vpc_id = "vpc-12345678" + + ingress { + description = "SSH from anywhere" + from_port = 22 + to_port = 22 + protocol = "tcp" + cidr_blocks = ["0.0.0.0/0"] # SSH from anywhere! + } + + ingress { + description = "RDP from anywhere" + from_port = 3389 + to_port = 3389 + protocol = "tcp" + cidr_blocks = ["0.0.0.0/0"] # RDP from anywhere! + } + + egress { + from_port = 0 + to_port = 0 + protocol = "-1" + cidr_blocks = ["0.0.0.0/0"] + } + + tags = { + Name = "SSH Open Security Group" + } +} + +# Security group with database ports exposed - SECURITY ISSUE #7 +resource "aws_security_group" "database_exposed" { + name = "database-public" + description = "Database accessible from internet" + vpc_id = "vpc-12345678" + + ingress { + description = "MySQL from anywhere" + from_port = 3306 + to_port = 3306 + protocol = "tcp" + cidr_blocks = ["0.0.0.0/0"] # Database exposed! + } + + ingress { + description = "PostgreSQL from anywhere" + from_port = 5432 + to_port = 5432 + protocol = "tcp" + cidr_blocks = ["0.0.0.0/0"] # Database exposed! + } + + egress { + from_port = 0 + to_port = 0 + protocol = "-1" + cidr_blocks = ["0.0.0.0/0"] + } +} diff --git a/labs/lab6/vulnerable-iac/terraform/variables.tf b/labs/lab6/vulnerable-iac/terraform/variables.tf new file mode 100644 index 00000000..df4547a7 --- /dev/null +++ b/labs/lab6/vulnerable-iac/terraform/variables.tf @@ -0,0 +1,75 @@ +# Vulnerable Variables Configuration for Lab 6 +# Contains insecure default values + +variable "aws_region" { + description = "AWS region" + type = string + default = "us-east-1" + # No validation for approved regions - SECURITY ISSUE #24 +} + +variable "db_password" { + description = "Database password" + type = string + default = "changeme123" # SECURITY ISSUE #25 - Weak default password! + # Should not have a default value for passwords! + # Should be marked as sensitive! +} + +variable "environment" { + description = "Environment name" + type = string + default = "production" # Defaulting to production is risky + # No validation +} + +variable "enable_public_access" { + description = "Enable public access to resources" + type = bool + default = true # SECURITY ISSUE #26 - Public access enabled by default! +} + +variable "enable_encryption" { + description = "Enable encryption" + type = bool + default = false # SECURITY ISSUE #27 - Encryption disabled by default! +} + +variable "allowed_ssh_cidr" { + description = "CIDR blocks allowed for SSH" + type = list(string) + default = ["0.0.0.0/0"] # SECURITY ISSUE #28 - Allows SSH from anywhere! +} + +variable "backup_retention_days" { + description = "Number of days to retain backups" + type = number + default = 0 # SECURITY ISSUE #29 - No backups by default! +} + +variable "api_key" { + description = "API key for external service" + type = string + default = "sk_test_1234567890abcdef" # SECURITY ISSUE #30 - Hardcoded API key! + # Should not have default, should be sensitive +} + +# No validation constraints on critical variables +variable "instance_type" { + description = "EC2 instance type" + type = string + default = "t2.micro" + # No validation - could use expensive instance types +} + +variable "allowed_regions" { + description = "List of allowed AWS regions" + type = list(string) + default = ["us-east-1", "us-west-2", "eu-west-1"] + # Not enforced anywhere in the code +} + +# Missing required variables +# - No variable for required resource tags +# - No variable for KMS key IDs +# - No variable for logging configuration diff --git a/labs/lab7.md b/labs/lab7.md new file mode 100644 index 00000000..48c23111 --- /dev/null +++ b/labs/lab7.md @@ -0,0 +1,414 @@ +# Lab 7 โ€” Container Security: Image Scanning & Deployment Hardening + +![difficulty](https://img.shields.io/badge/difficulty-intermediate-orange) +![topic](https://img.shields.io/badge/topic-Container%20Security-blue) +![points](https://img.shields.io/badge/points-10-orange) + +> **Goal:** Analyze container images for vulnerabilities, audit Docker host security, and compare secure deployment configurations. +> **Deliverable:** A PR from `feature/lab7` to the course repo with `labs/submission7.md` containing vulnerability analysis, CIS benchmark results, and deployment security comparison. Submit the PR link via Moodle. + +--- + +## Overview + +In this lab you will practice: +- **Container image vulnerability scanning** using next-generation tools (Docker Scout, Snyk) +- **Docker security benchmarking** with CIS Docker Benchmark compliance assessment +- **Secure container deployment** analysis and configuration comparison +- **Container security assessment** using modern scanning and analysis tools +- **Security configuration impact** analysis for production deployments + +These skills are essential for implementing container security in DevSecOps pipelines and production environments. + +> Target application: OWASP Juice Shop (`bkimminich/juice-shop:v19.0.0`) + +--- + +## Prerequisites + +### Docker Scout CLI Setup + +Docker Scout requires authentication and a CLI plugin installation. + +#### Step 1: Install Docker Scout CLI Plugin + +**For Linux/macOS:** +```bash +curl -sSfL https://raw.githubusercontent.com/docker/scout-cli/main/install.sh | sh -s -- +``` + +**Verify installation:** +```bash +docker scout version +``` + +You should see output like: `version: v1.x.x` + +#### Step 2: Docker Hub Authentication + +Docker Scout requires a Docker Hub account and Personal Access Token (PAT). + +**Create account and generate PAT:** + +1. **Create Docker Hub account** (if needed): Visit https://hub.docker.com + +2. **Generate PAT:** + + - Log in โ†’ Account Settings โ†’ Security โ†’ Personal Access Tokens + - Click **New Access Token** + - Description: `Lab7 Docker Scout Access` + - Permissions: Select **Read, Write, Delete** + - Click **Generate** and copy the token immediately + +3. **Authenticate:** + + ```bash + docker login + # Username: your-docker-hub-username + # Password: paste-your-PAT (not your password!) + ``` + +4. **Verify access:** + + ```bash + docker scout quickview busybox:latest + # Should display vulnerability scan results + ``` + +**Why PAT over password?** +- Limited scope permissions for least privilege +- Easy to revoke without changing account password +- Required for SSO-enabled organizations +- Better audit trail + +Learn more: https://docs.docker.com/go/access-tokens/ + +--- + +## Tasks + +### Task 1 โ€” Image Vulnerability & Configuration Analysis (3 pts) + +**Objective:** Scan container images for vulnerabilities and configuration issues. + +#### 1.1: Setup Working Directory + +```bash +mkdir -p labs/lab7/{scanning,hardening,analysis} +cd labs/lab7 +``` + +#### 1.2: Vulnerability Scanning + +```bash +# Pull the image to scan locally +docker pull bkimminich/juice-shop:v19.0.0 + +# Detailed CVE analysis +docker scout cves bkimminich/juice-shop:v19.0.0 | tee scanning/scout-cves.txt +``` + +**Understanding the output:** +- **C/H/M/L** = Critical/High/Medium/Low severity counts +- Look for CVE IDs, affected packages, and potential impact + +#### 1.3: Snyk comparison + +```bash +# Requires Snyk account: https://snyk.io +# Set token: export SNYK_TOKEN=your-token +docker run --rm \ + -e SNYK_TOKEN \ + -v /var/run/docker.sock:/var/run/docker.sock \ + snyk/snyk:docker snyk test --docker bkimminich/juice-shop:v19.0.0 --severity-threshold=high \ + | tee scanning/snyk-results.txt +``` + +#### 1.4: Configuration Assessment + +```bash +# Scan for security and best practice issues +docker run --rm -v /var/run/docker.sock:/var/run/docker.sock \ + goodwithtech/dockle:latest \ + bkimminich/juice-shop:v19.0.0 | tee scanning/dockle-results.txt +``` + +**Look for:** +- **FATAL/WARN** issues about running as root +- Exposed secrets in environment variables +- Missing security configurations +- File permission issues + +**๐Ÿ“Š Document in `labs/submission7.md`:** + +1. **Top 5 Critical/High Vulnerabilities** + - CVE ID, affected package, severity, and impact + +2. **Dockle Configuration Findings** + - List FATAL and WARN issues + - Explain why each is a security concern + +3. **Security Posture Assessment** + - Does the image run as root? + - What security improvements would you recommend? + +--- + +### Task 2 โ€” Docker Host Security Benchmarking (3 pts) + +**Objective:** Audit Docker host configuration against CIS Docker Benchmark. + +#### 2.1: Run CIS Docker Benchmark + +```bash +# Run CIS Docker Benchmark security audit +docker run --rm --net host --pid host --userns host --cap-add audit_control \ + -e DOCKER_CONTENT_TRUST=$DOCKER_CONTENT_TRUST \ + -v /var/lib:/var/lib:ro \ + -v /var/run/docker.sock:/var/run/docker.sock:ro \ + -v /usr/lib/systemd:/usr/lib/systemd:ro \ + -v /etc:/etc:ro --label docker_bench_security \ + docker/docker-bench-security | tee hardening/docker-bench-results.txt +``` + +**Understanding the output:** +- **[PASS]** - Security control properly configured +- **[WARN]** - Potential issue requiring review +- **[FAIL]** - Security control not properly configured +- **[INFO]** - Informational (no action needed) + +**Key sections:** +1. Host Configuration +2. Docker daemon configuration +3. Docker daemon configuration files +4. Container Images and Build Files +5. Container Runtime + +**๐Ÿ“Š Document in `labs/submission7.md`:** + +1. **Summary Statistics** + - Total PASS/WARN/FAIL/INFO counts + +2. **Analysis of Failures** (if any) + - List failures and explain security impact + - Propose specific remediation steps + +--- + +### Task 3 โ€” Deployment Security Configuration Analysis (4 pts) + +**Objective:** Compare deployment configurations to understand security hardening trade-offs. + +#### 3.1: Deploy Three Security Profiles + +```bash +# Profile 1: Default (baseline) +docker run -d --name juice-default -p 3001:3000 \ + bkimminich/juice-shop:v19.0.0 + +# Profile 2: Hardened (security restrictions) +docker run -d --name juice-hardened -p 3002:3000 \ + --cap-drop=ALL \ + --security-opt=no-new-privileges \ + --memory=512m \ + --cpus=1.0 \ + bkimminich/juice-shop:v19.0.0 + +# Profile 3: Production (maximum hardening) +docker run -d --name juice-production -p 3003:3000 \ + --cap-drop=ALL \ + --cap-add=NET_BIND_SERVICE \ + --security-opt=no-new-privileges \ + --security-opt=seccomp=default \ + --memory=512m \ + --memory-swap=512m \ + --cpus=1.0 \ + --pids-limit=100 \ + --restart=on-failure:3 \ + bkimminich/juice-shop:v19.0.0 + +# Wait for startup +sleep 15 + +# Verify all containers are running +docker ps -a --filter name=juice- +``` + +#### 3.2: Compare Configurations + +```bash +# Test functionality +echo "=== Functionality Test ===" | tee analysis/deployment-comparison.txt +curl -s -o /dev/null -w "Default: HTTP %{http_code}\n" http://localhost:3001 | tee -a analysis/deployment-comparison.txt +curl -s -o /dev/null -w "Hardened: HTTP %{http_code}\n" http://localhost:3002 | tee -a analysis/deployment-comparison.txt +curl -s -o /dev/null -w "Production: HTTP %{http_code}\n" http://localhost:3003 | tee -a analysis/deployment-comparison.txt + +# Check resource usage +echo "" | tee -a analysis/deployment-comparison.txt +echo "=== Resource Usage ===" | tee -a analysis/deployment-comparison.txt +docker stats --no-stream --format "table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.MemPerc}}" \ + juice-default juice-hardened juice-production | tee -a analysis/deployment-comparison.txt + +# Inspect security settings +echo "" | tee -a analysis/deployment-comparison.txt +echo "=== Security Configurations ===" | tee -a analysis/deployment-comparison.txt +for container in juice-default juice-hardened juice-production; do + echo "" | tee -a analysis/deployment-comparison.txt + echo "Container: $container" | tee -a analysis/deployment-comparison.txt + docker inspect $container --format 'CapDrop: {{.HostConfig.CapDrop}} +SecurityOpt: {{.HostConfig.SecurityOpt}} +Memory: {{.HostConfig.Memory}} +CPU: {{.HostConfig.CpuQuota}} +PIDs: {{.HostConfig.PidsLimit}} +Restart: {{.HostConfig.RestartPolicy.Name}}' | tee -a analysis/deployment-comparison.txt +done +``` + +#### 3.3: Cleanup + +```bash +docker stop juice-default juice-hardened juice-production +docker rm juice-default juice-hardened juice-production +``` + +**๐Ÿ“Š Document in `labs/submission7.md`:** + +#### 1. Configuration Comparison Table + +Create a table from `docker inspect` output comparing all three profiles: +- Capabilities (dropped/added) +- Security options +- Resource limits (memory, CPU, PIDs) +- Restart policy + +#### 2. Security Measure Analysis + +Research and explain EACH security flag: + +**a) `--cap-drop=ALL` and `--cap-add=NET_BIND_SERVICE`** +- What are Linux capabilities? (Research this!) +- What attack vector does dropping ALL capabilities prevent? +- Why do we need to add back NET_BIND_SERVICE? +- What's the security trade-off? + +**b) `--security-opt=no-new-privileges`** +- What does this flag do? (Look it up!) +- What type of attack does it prevent? +- Are there any downsides to enabling it? + +**c) `--memory=512m` and `--cpus=1.0`** +- What happens if a container doesn't have resource limits? +- What attack does memory limiting prevent? +- What's the risk of setting limits too low? + +**d) `--pids-limit=100`** +- What is a fork bomb? +- How does PID limiting help? +- How to determine the right limit? + +**e) `--restart=on-failure:3`** +- What does this policy do? +- When is auto-restart beneficial? When is it risky? +- Compare `on-failure` vs `always` + +#### 3. Critical Thinking Questions + +1. **Which profile for DEVELOPMENT? Why?** + +2. **Which profile for PRODUCTION? Why?** + +3. **What real-world problem do resource limits solve?** + +4. **If an attacker exploits Default vs Production, what actions are blocked in Production?** + +5. **What additional hardening would you add?** + + +--- + +## Acceptance Criteria + +- โœ… Branch `feature/lab7` exists with commits for each task +- โœ… File `labs/submission7.md` contains required analysis for Tasks 1-3 +- โœ… Vulnerability scanning completed with Docker Scout +- โœ… CIS Docker Benchmark audit completed +- โœ… Deployment security comparison completed +- โœ… All scan outputs committed to `labs/lab7/` +- โœ… PR from `feature/lab7` โ†’ **course repo main branch** is open +- โœ… PR link submitted via Moodle before the deadline + +--- + +## How to Submit + +1. Create a branch for this lab and push it to your fork: + + ```bash + git switch -c feature/lab7 + # create labs/submission7.md with your findings + git add labs/submission7.md labs/lab7/ + git commit -m "docs: add lab7 submission - container security analysis" + git push -u origin feature/lab7 + ``` + +2. Open a PR from your fork's `feature/lab7` branch โ†’ **course repository's main branch**. + +3. In the PR description, include: + + ```text + - [x] Task 1 done โ€” Advanced Image Security & Configuration Analysis + - [x] Task 2 done โ€” Docker Security Benchmarking & Assessment + - [x] Task 3 done โ€” Secure Container Deployment Analysis + ``` + +4. **Copy the PR URL** and submit it via **Moodle before the deadline**. + +--- + +## Rubric (10 pts) + +| Criterion | Points | +| ---------------------------------------------------------------- | -----: | +| Task 1 โ€” Image vulnerability & configuration analysis | **3** | +| Task 2 โ€” Docker host security benchmarking | **3** | +| Task 3 โ€” Deployment security configuration analysis | **4** | +| **Total** | **10** | + +--- + +## Guidelines + +- Use clear Markdown headers to organize sections in `submission7.md` +- Include evidence from tool outputs to support your analysis +- Research security concepts thoroughlyโ€”don't copy-paste +- Focus on understanding trade-offs between security and usability + +
+Container Security Resources + +**Documentation:** +- [Docker Security](https://docs.docker.com/engine/security/) +- [CIS Docker Benchmark](https://www.cisecurity.org/benchmark/docker) +- [Linux Capabilities](https://man7.org/linux/man-pages/man7/capabilities.7.html) + +
+ +
+Expected Security Findings + +**Image Vulnerabilities:** +- Outdated base packages with CVEs +- Vulnerable dependencies +- Missing security patches + +**CIS Benchmark:** +- Insecure daemon configuration +- Missing resource limits +- Excessive privileges + +**Deployment Gaps:** +- Running as root +- Unnecessary capabilities +- No resource limits + +
\ No newline at end of file diff --git a/labs/lab8.md b/labs/lab8.md new file mode 100644 index 00000000..1fda7f2c --- /dev/null +++ b/labs/lab8.md @@ -0,0 +1,318 @@ +# Lab 8 โ€” Software Supply Chain Security: Signing, Verification, and Attestations + +![difficulty](https://img.shields.io/badge/difficulty-intermediate-orange) +![topic](https://img.shields.io/badge/topic-Supply%20Chain%20Security-blue) +![points](https://img.shields.io/badge/points-10-orange) + +> Goal: Sign and verify container images, attach and verify attestations (SBOM/provenance), and optionally sign non-container artifacts โ€” all locally, without code changes. +> Deliverable: A PR from `feature/lab8` with `labs/submission8.md` containing signing/verification logs, attestation evidence, and a short analysis. Submit the PR link via Moodle. + +--- + +## Overview + +In this lab you will practice: +- Image signing/verification with Cosign against a local registry +- Attestations (SBOM and provenance) and payload inspection +- Optional artifact (blob) signing for non-container assets + +Context: Cosign is a widely used OSS tool for image signing and attestations. If you produced SBOMs in Lab 4, reuse them here for attestations. + +> Target application: `bkimminich/juice-shop:v19.0.0` + +--- + +## Prerequisites + +- Docker (Docker Desktop or Engine) and internet access +- `jq` for JSON processing +- Cosign installed (binary) + - See: https://docs.sigstore.dev/cosign/system_config/installation/ + - Verify: `cosign version` + +Install Cosign (quick start): + +```bash +# Linux x86_64 (install to /usr/local/bin) +curl -sSL -o cosign "https://github.com/sigstore/cosign/releases/latest/download/cosign-linux-amd64" +chmod +x cosign && sudo mv cosign /usr/local/bin/ + +# Verify +cosign version +``` + +Docs: +- Install guide: https://docs.sigstore.dev/cosign/system_config/installation/ +- Releases: https://github.com/sigstore/cosign/releases/latest + +Prepare working directories: +```bash +mkdir -p labs/lab8/{registry,signing,attest,analysis,artifacts} +``` + +--- + +## Tasks + +### Task 1 โ€” Local Registry, Signing & Verification (4 pts) +**Objective:** Push the image to a local registry, sign it with Cosign, and verify the signature, including a tamper demonstration. + +#### 1.1: Pull and push to local registry +```bash +# Pull target image +docker pull bkimminich/juice-shop:v19.0.0 + +# Start local registry on localhost:5000 (Distribution v3) +docker run -d --restart=always -p 5000:5000 --name registry registry:3 + +# Tag and push the image to the local registry +docker tag bkimminich/juice-shop:v19.0.0 localhost:5000/juice-shop:v19.0.0 +docker push localhost:5000/juice-shop:v19.0.0 + +# Recommended: use a digest reference (from the local registry) instead of a tag +DIGEST=$(curl -sI \ + -H 'Accept: application/vnd.docker.distribution.manifest.v2+json' \ + http://localhost:5000/v2/juice-shop/manifests/v19.0.0 \ + | tr -d '\r' | awk -F': ' '/Docker-Content-Digest/ {print $2}') +REF="localhost:5000/juice-shop@${DIGEST}" +echo "Using digest ref: $REF" | tee labs/lab8/analysis/ref.txt +``` + +#### 1.2: Generate a Cosign key pair for signing +```bash +cd labs/lab8/signing +cosign generate-key-pair +cd - +# This creates cosign.key (private key) and cosign.pub (public key) +# You will be prompted to set a passphrase for the private key +``` + +#### 1.3: Sign and verify the image +```bash +# Sign the image using your private key +cosign sign --yes \ + --allow-insecure-registry \ + --tlog-upload=false \ + --key labs/lab8/signing/cosign.key \ + "$REF" + +# Verify the signature using your public key and save the output +cosign verify \ + --allow-insecure-registry \ + --insecure-ignore-tlog \ + --key labs/lab8/signing/cosign.pub \ + "$REF" +``` + +> Note for students: +> - This verify flow is valid for a local, insecure registry. You correctly use a digest reference and `--allow-insecure-registry`. +> - The warning appears because you signed with `--tlog-upload=false`. Using `--insecure-ignore-tlog` tells Cosign to skip Rekor transparency log verification in this lab context. +> - For production: remove `--insecure-ignore-tlog`, sign without `--tlog-upload=false` (so the signature is recorded in Rekor), avoid insecure registries, and always verify/sign by digest (not by tag). + +#### 1.4: Tamper demonstration +```bash +docker pull busybox:latest +docker tag busybox:latest localhost:5000/juice-shop:v19.0.0 +docker push localhost:5000/juice-shop:v19.0.0 + +# IMPORTANT: Re-resolve the tag to the NEW digest from the local registry +DIGEST_AFTER=$(curl -sI \ + -H 'Accept: application/vnd.docker.distribution.manifest.v2+json' \ + http://localhost:5000/v2/juice-shop/manifests/v19.0.0 \ + | tr -d '\r' | awk -F': ' '/Docker-Content-Digest/ {print $2}') +REF_AFTER="localhost:5000/juice-shop@${DIGEST_AFTER}" +echo "After tamper digest ref: $REF_AFTER" | tee labs/lab8/analysis/ref-after-tamper.txt + +# Verify should now FAIL for the new digest (not signed with your key) +cosign verify \ + --allow-insecure-registry \ + --insecure-ignore-tlog \ + --key labs/lab8/signing/cosign.pub \ + "$REF_AFTER" + +# Sanity check: verifying the ORIGINAL digest still succeeds (supply chain best practice) +cosign verify \ + --allow-insecure-registry \ + --insecure-ignore-tlog \ + --key labs/lab8/signing/cosign.pub \ + "$REF" +``` + +In `labs/submission8.md`, explain how signing protects against tag tampering and what โ€œsubject digestโ€ means. + +--- + +### Task 2 โ€” Attestations: SBOM (reuse) & Provenance (4 pts) + +**Objective:** Attach and verify attestations (SBOM and simple provenance) to the image and inspect the attestation envelope. + +```bash +mkdir -p labs/lab4/syft +docker run --rm -v /var/run/docker.sock:/var/run/docker.sock \ + -v "$(pwd)":/tmp anchore/syft:latest \ + "$REF" -o syft-json=/tmp/labs/lab4/syft/juice-shop-syft-native.json +``` + +Generate CycloneDX SBOM for attestation: + +```bash +# Option A: Convert Syft-native SBOM from Lab 4 โ†’ CycloneDX JSON +docker run --rm \ + -v "$(pwd)/labs/lab4/syft":/in:ro \ + -v "$(pwd)/labs/lab8/attest":/out \ + anchore/syft:latest \ + convert /in/juice-shop-syft-native.json -o cyclonedx-json=/out/juice-shop.cdx.json +``` + +#### 2.1: SBOM as an attestation (CycloneDX) +```bash +# Example using CycloneDX SBOM created above +cosign attest --yes \ + --allow-insecure-registry \ + --tlog-upload=false \ + --key labs/lab8/signing/cosign.key \ + --predicate labs/lab8/attest/juice-shop.cdx.json \ + --type cyclonedx \ + "$REF" + +# Verify the SBOM attestation +cosign verify-attestation \ + --allow-insecure-registry \ + --insecure-ignore-tlog \ + --key labs/lab8/signing/cosign.pub \ + --type cyclonedx \ + "$REF" \ + | tee labs/lab8/attest/verify-sbom-attestation.txt +``` + +#### 2.2: Simple provenance attestation + +```bash +# Create a minimal, valid SLSA Provenance v1 predicate with a proper RFC3339 timestamp +BUILD_TS=$(date -u +%Y-%m-%dT%H:%M:%SZ) +cat > labs/lab8/attest/provenance.json << EOF +{ + "_type": "https://slsa.dev/provenance/v1", + "buildType": "manual-local-demo", + "builder": {"id": "student@local"}, + "invocation": {"parameters": {"image": "${REF}"}}, + "metadata": {"buildStartedOn": "${BUILD_TS}", "completeness": {"parameters": true}} +} +EOF + +cosign attest --yes \ + --allow-insecure-registry \ + --tlog-upload=false \ + --key labs/lab8/signing/cosign.key \ + --predicate labs/lab8/attest/provenance.json \ + --type slsaprovenance \ + "$REF" + +# Verify the provenance attestation +cosign verify-attestation \ + --allow-insecure-registry \ + --insecure-ignore-tlog \ + --key labs/lab8/signing/cosign.pub \ + --type slsaprovenance \ + "$REF" | tee labs/lab8/attest/verify-provenance.txt +``` + +In `labs/submission8.md`, document: + - How attestations differ from signatures + - What information the SBOM attestation contains + - What provenance attestations provide for supply chain security +--- + +### Task 3 โ€” Artifact (Blob/Tarball) Signing (2 pts) + +**Objective:** Sign a non-container artifact (e.g., a tarball) and verify the signature. + +```bash +echo "sample content $(date -u)" > labs/lab8/artifacts/sample.txt +tar -czf labs/lab8/artifacts/sample.tar.gz -C labs/lab8/artifacts sample.txt + +# Option A: Cosign sign-blob using a bundle (recommended) +cosign sign-blob \ + --yes \ + --tlog-upload=false \ + --key labs/lab8/signing/cosign.key \ + --bundle labs/lab8/artifacts/sample.tar.gz.bundle \ + labs/lab8/artifacts/sample.tar.gz + +cosign verify-blob \ + --key labs/lab8/signing/cosign.pub \ + --bundle labs/lab8/artifacts/sample.tar.gz.bundle \ + labs/lab8/artifacts/sample.tar.gz | tee labs/lab8/artifacts/verify-blob.txt +``` + +In `labs/submission8.md`, document: + - Use cases for signing non-container artifacts (e.g., release binaries, configuration files) + - How blob signing differs from container image signing + +--- + +## Acceptance Criteria + +- โœ… `labs/submission8.md` includes analysis and evidence for Tasks 1โ€“3 +- โœ… Image pushed to local registry; Cosign signature created and verified +- โœ… Tamper scenario demonstrated and explained +- โœ… At least one attestation attached and verified (SBOM or provenance); payload inspected with `jq` +- โœ… Artifact signing performed and verified +- โœ… All outputs saved under `labs/lab8/` and committed + +--- + +## How to Submit + +1. Create a branch for this lab and push it to your fork: + +```bash +git switch -c feature/lab8 +# create labs/submission8.md with your findings +git add labs/lab8/ labs/submission8.md +git commit -m "docs: add lab8 submission โ€” signing + attestations" +git push -u origin feature/lab8 +``` + +2. Open a PR from your forkโ€™s `feature/lab8` โ†’ course repoโ€™s `main`. +3. Include this checklist in the PR description: + +```text +- [x] Task 1 โ€” Local registry, signing, verification (+ tamper demo) +- [x] Task 2 โ€” Attestations (SBOM or provenance) + payload inspection +- [x] Task 3 โ€” Artifact signing (blob/tarball) +``` + +4. Submit the PR URL via Moodle before the deadline. + +--- + +## Rubric (10 pts) + +| Criterion | Points | +| ------------------------------------------------------------- | -----: | +| Task 1 โ€” Local Registry, Signing & Verification | 4.0 | +| Task 2 โ€” SBOM/Provenance Attestations (verify + inspect) | 4.0 | +| Task 3 โ€” Artifact (Blob/Tarball) Signing | 2.0 | +| Total | 10.0 | + +--- + +## Guidelines + +- Use the Cosign binary (most widely tested in 2025 for local flows) +- Keep keys out of version control; commit only logs and reports +- Use strong passphrases; rotate and store securely +- Reuse your Lab 4 SBOM for attestation if possible; otherwise create a minimal predicate JSON + +
+References + +- Cosign install: https://docs.sigstore.dev/cosign/system_config/installation/ +- in-toto/attestations: https://github.com/in-toto/attestation +- CycloneDX: https://cyclonedx.org/ +- SPDX: https://spdx.dev/ + +
+ + diff --git a/labs/lab9.md b/labs/lab9.md new file mode 100644 index 00000000..91e20bef --- /dev/null +++ b/labs/lab9.md @@ -0,0 +1,239 @@ +# Lab 9 โ€” Monitoring & Compliance: Falco Runtime Detection + Conftest Policies + +![difficulty](https://img.shields.io/badge/difficulty-intermediate-orange) +![topic](https://img.shields.io/badge/topic-Monitoring%20%26%20Compliance-blue) +![points](https://img.shields.io/badge/points-10-orange) + +> Goal: Detect suspicious container behavior with Falco and enforce deployment hardening via policy-as-code using Conftest (Rego) โ€” all runnable locally. +> Deliverable: A PR from `feature/lab9` with `labs/submission9.md` containing Falco alert evidence, custom rule/tuning notes, Conftest test results, and analysis of provided manifests/policies. Submit the PR link via Moodle. + +--- + +## Overview + +In this lab you will practice: +- Runtime threat detection for containers with Falco (eBPF) +- Writing/customizing Falco rules and tuning noise/false positives +- Policy-as-code with Conftest (OPA/Rego) against Kubernetes manifests +- Analyzing how security policies enforce deployment hardening best practices + +> Runtime target for Task 1: BusyBox helper container (`alpine:3.19`). + +--- + +## Prerequisites + +- Docker (or Docker Desktop) +- `jq` +- Optional: `kubectl` or a local K8s (kind/minikube) is NOT required โ€” Conftest runs offline against YAML + +Prepare working directories: +```bash +mkdir -p labs/lab9/{falco/{rules,logs},analysis} +``` + +--- + +## Tasks + +### Task 1 โ€” Runtime Security Detection with Falco (6 pts) +**Objective:** Run Falco with modern eBPF, trigger alerts from a shell-enabled BusyBox container, and add one custom rule with basic tuning. + +#### 1.1: Start a shell-enabled helper container +```bash +# Use Alpine (BusyBox) to trigger events โ€” no app needed +docker run -d --name lab9-helper alpine:3.19 sleep 1d +``` + +#### 1.2: Run Falco (containerized) with modern eBPF +```bash +# Start Falco container (JSON output to stdout) +docker run -d --name falco \ + --privileged \ + -v /proc:/host/proc:ro \ + -v /boot:/host/boot:ro \ + -v /lib/modules:/host/lib/modules:ro \ + -v /usr:/host/usr:ro \ + -v /var/run/docker.sock:/host/var/run/docker.sock \ + -v "$(pwd)/labs/lab9/falco/rules":/etc/falco/rules.d:ro \ + falcosecurity/falco:latest \ + falco -U \ + -o json_output=true \ + -o time_format_iso_8601=true + +# Follow Falco logs +docker logs -f falco | tee labs/lab9/falco/logs/falco.log & +``` + +Note: The official Falco image defaults to the modern eBPF engine (engine.kind=modern_ebpf). No extra flag is needed beyond running with the required privileges and mounts. + +#### 1.3: Trigger two baseline alerts +```bash +# A) Terminal shell inside container (expected rule: Terminal shell in container) +docker exec -it lab9-helper /bin/sh -lc 'echo hello-from-shell' + +# B) Container drift: write under a binary directory +# Writes to /usr/local/bin should trigger Falco's drift detection +docker exec --user 0 lab9-helper /bin/sh -lc 'echo boom > /usr/local/bin/drift.txt' +``` + +#### 1.4: Add one custom Falco rule and validate +Create `labs/lab9/falco/rules/custom-rules.yaml`: +```yaml +# Detect new writable file under /usr/local/bin inside any container +- rule: Write Binary Under UsrLocalBin + desc: Detects writes under /usr/local/bin inside any container + condition: evt.type in (open, openat, openat2, creat) and + evt.is_open_write=true and + fd.name startswith /usr/local/bin/ and + container.id != host + output: > + Falco Custom: File write in /usr/local/bin (container=%container.name user=%user.name file=%fd.name flags=%evt.arg.flags) + priority: WARNING + tags: [container, compliance, drift] +``` + +Falco auto-reloads rules in `/etc/falco/rules.d`. If you don't see your custom alert after a minute, force a reload: +```bash +docker kill --signal=SIGHUP falco && sleep 2 +``` + +Validate the custom rule by triggering another write: +```bash +# This should trigger BOTH the built-in drift rule AND your custom rule +docker exec --user 0 lab9-helper /bin/sh -lc 'echo custom-test > /usr/local/bin/custom-rule.txt' +``` + +#### 1.5: Generate Falco test events +```bash +# Falco event generator creates a short burst of detectable actions +docker run --rm --name eventgen \ + --privileged \ + -v /proc:/host/proc:ro -v /dev:/host/dev \ + falcosecurity/event-generator:latest run syscall +``` +
+What this does +Executes a curated set of syscalls (e.g., fileless execution, sensitive file reads) that should appear as Falco alerts. This helps verify your Falco setup is working correctly. +
+ +In `labs/submission9.md`, document: +- Baseline alerts observed from `falco.log` +- Your custom ruleโ€™s purpose and when it should/shouldnโ€™t fire + +--- + +### Task 2 โ€” Policy-as-Code with Conftest (Rego) (4 pts) +**Objective:** Run provided security policies against K8s manifests, analyze policy violations, and understand how hardening satisfies compliance requirements. + +#### 2.1: Review provided Kubernetes manifests +Open and review the provided manifests: +- `labs/lab9/manifests/k8s/juice-unhardened.yaml` (baseline โ€” do NOT edit) +- `labs/lab9/manifests/k8s/juice-hardened.yaml` (compliant version) + +Compare both manifests to understand what hardening changes were applied. + +#### 2.2: Review provided Conftest Rego policies +Examine the provided security policies: +- `labs/lab9/policies/k8s-security.rego` โ€” enforces Kubernetes security best practices +- `labs/lab9/policies/compose-security.rego` โ€” enforces Docker Compose security patterns + +These policies check for common misconfigurations like running as root, missing resource limits, privileged containers, etc. + +#### 2.3: Run Conftest against both manifests +```bash +# Test unhardened manifest (expect policy violations) +docker run --rm -v "$(pwd)/labs/lab9":/project \ + openpolicyagent/conftest:latest \ + test /project/manifests/k8s/juice-unhardened.yaml -p /project/policies --all-namespaces | tee labs/lab9/analysis/conftest-unhardened.txt + +# Test hardened manifest (should pass or only warnings) +docker run --rm -v "$(pwd)/labs/lab9":/project \ + openpolicyagent/conftest:latest \ + test /project/manifests/k8s/juice-hardened.yaml -p /project/policies --all-namespaces | tee labs/lab9/analysis/conftest-hardened.txt + +# Test Docker Compose manifest +docker run --rm -v "$(pwd)/labs/lab9":/project \ + openpolicyagent/conftest:latest \ + test /project/manifests/compose/juice-compose.yml -p /project/policies --all-namespaces | tee labs/lab9/analysis/conftest-compose.txt +``` + +In `labs/submission9.md`, document: +- The policy violations from the unhardened manifest and why each matters for security +- The specific hardening changes in the hardened manifest that satisfy policies +- Analysis of the Docker Compose manifest results + +--- + +## Acceptance Criteria + +- โœ… Branch `feature/lab9` contains Falco setup, logs, and a custom rule file +- โœ… At least two Falco alerts captured and explained (baseline + custom) +- โœ… Conftest policies reviewed and tested against manifests +- โœ… Unhardened K8s manifest fails; hardened manifest passes (warnings OK) +- โœ… `labs/submission9.md` includes evidence and analysis for both tasks + +--- + +## How to Submit + +1. Create a branch and push it to your fork: +```bash +git switch -c feature/lab9 +# create labs/submission9.md with your findings +git add labs/lab9/ labs/submission9.md +git commit -m "docs: add lab9 โ€” falco runtime + conftest policies" +git push -u origin feature/lab9 +``` +2. Open a PR from your forkโ€™s `feature/lab9` โ†’ course repoโ€™s `main`. +3. In the PR description include: +```text +- [x] Task 1 โ€” Falco runtime detection (alerts + custom rule) +- [x] Task 2 โ€” Conftest policies (failโ†’pass hardening) +``` +4. Submit the PR URL via Moodle before the deadline. + +--- + +## Rubric (10 pts) + +| Criterion | Points | +| --------------------------------------------------------------- | -----: | +| Task 1 โ€” Falco runtime detection + custom rule | 6.0 | +| Task 2 โ€” Conftest policies + hardened manifests | 4.0 | +| Total | 10.0 | + +--- + +## Guidelines + +- Keep Falco running while you trigger events; copy only relevant alert lines into your submission +- Place custom Falco rules under `labs/lab9/falco/rules/` and commit them +- Conftest โ€œdenyโ€ enforces hard requirements; โ€œwarnโ€ provides guidance without failing +- Aim for minimal, practical policies that reflect production hardening baselines + +
+References + +- Falco: https://falco.org/docs/ +- Falco container: https://github.com/falcosecurity/falco +- Event Generator: https://github.com/falcosecurity/event-generator +- Conftest: https://github.com/open-policy-agent/conftest +- OPA/Rego: https://www.openpolicyagent.org/docs/ + +
+ +
+Troubleshooting + +- Falco engine: If Falco logs show that modern eBPF is unsupported, switch engine with: `-o engine.kind=ebpf` in the `docker run` command. +- Permissions: Ensure Docker is running and you can run privileged containers. If `--privileged` or mounts fail, try a Linux host or WSL2. +- Container context: For drift tests, write from inside the container (not `docker cp`) so Falco reports a non-host `container.id`. +- Conftest: If pulling the image fails, try specifying a version tag, e.g., `openpolicyagent/conftest:v0.63.0`. + +
+ +### Cleanup +```bash +docker rm -f falco lab9-helper 2>/dev/null || true +``` diff --git a/labs/lab9/manifests/compose/juice-compose.yml b/labs/lab9/manifests/compose/juice-compose.yml new file mode 100644 index 00000000..acfcb64b --- /dev/null +++ b/labs/lab9/manifests/compose/juice-compose.yml @@ -0,0 +1,11 @@ +services: + juice: + image: bkimminich/juice-shop:v19.0.0 + ports: ["3006:3000"] + user: "10001:10001" + read_only: true + tmpfs: ["/tmp"] + security_opt: + - no-new-privileges:true + cap_drop: ["ALL"] + diff --git a/labs/lab9/manifests/k8s/juice-hardened.yaml b/labs/lab9/manifests/k8s/juice-hardened.yaml new file mode 100644 index 00000000..10521196 --- /dev/null +++ b/labs/lab9/manifests/k8s/juice-hardened.yaml @@ -0,0 +1,45 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: juice-hardened +spec: + replicas: 1 + selector: + matchLabels: { app: juice } + template: + metadata: + labels: { app: juice } + spec: + containers: + - name: juice + image: bkimminich/juice-shop:v19.0.0 + securityContext: + runAsNonRoot: true + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: ["ALL"] + resources: + requests: { cpu: "100m", memory: "256Mi" } + limits: { cpu: "500m", memory: "512Mi" } + ports: + - containerPort: 3000 + readinessProbe: + httpGet: { path: /, port: 3000 } + initialDelaySeconds: 5 + periodSeconds: 10 + livenessProbe: + httpGet: { path: /, port: 3000 } + initialDelaySeconds: 10 + periodSeconds: 20 +--- +apiVersion: v1 +kind: Service +metadata: + name: juice-hardened +spec: + selector: { app: juice } + ports: + - port: 80 + targetPort: 3000 + diff --git a/labs/lab9/manifests/k8s/juice-unhardened.yaml b/labs/lab9/manifests/k8s/juice-unhardened.yaml new file mode 100644 index 00000000..94e96fc3 --- /dev/null +++ b/labs/lab9/manifests/k8s/juice-unhardened.yaml @@ -0,0 +1,28 @@ +apiVersion: apps/v1 +kind: Deployment +metadata: + name: juice-unhardened +spec: + replicas: 1 + selector: + matchLabels: { app: juice } + template: + metadata: + labels: { app: juice } + spec: + containers: + - name: juice + image: bkimminich/juice-shop:latest + ports: + - containerPort: 3000 +--- +apiVersion: v1 +kind: Service +metadata: + name: juice-unhardened +spec: + selector: { app: juice } + ports: + - port: 80 + targetPort: 3000 + diff --git a/labs/lab9/policies/compose-security.rego b/labs/lab9/policies/compose-security.rego new file mode 100644 index 00000000..eebca76b --- /dev/null +++ b/labs/lab9/policies/compose-security.rego @@ -0,0 +1,33 @@ +package compose.security + +containers := input.services + +# Helper: true if array arr contains value v +has_value(arr, v) if { + some i + arr[i] == v +} + +deny contains msg if { + svc := containers[_] + not svc.user + msg := "services must set an explicit non-root user" +} + +deny contains msg if { + svc := containers[_] + not svc.read_only + msg := "services must set read_only: true" +} + +deny contains msg if { + svc := containers[_] + not has_value(svc.cap_drop, "ALL") + msg := "services must drop ALL capabilities" +} + +warn contains msg if { + svc := containers[_] + not has_value(svc.security_opt, "no-new-privileges:true") + msg := "services should enable no-new-privileges" +} diff --git a/labs/lab9/policies/k8s-security.rego b/labs/lab9/policies/k8s-security.rego new file mode 100644 index 00000000..041ff3bd --- /dev/null +++ b/labs/lab9/policies/k8s-security.rego @@ -0,0 +1,88 @@ +package k8s.security + +# Helper: true if array arr contains value v +has_value(arr, v) if { + some i + arr[i] == v +} + +# No :latest tags +deny contains msg if { + input.kind == "Deployment" + c := input.spec.template.spec.containers[_] + endswith(c.image, ":latest") + msg := sprintf("container %q uses disallowed :latest tag", [c.name]) +} + +# Require essential securityContext settings +deny contains msg if { + input.kind == "Deployment" + c := input.spec.template.spec.containers[_] + not c.securityContext.runAsNonRoot + msg := sprintf("container %q must set runAsNonRoot: true", [c.name]) +} + +deny contains msg if { + input.kind == "Deployment" + c := input.spec.template.spec.containers[_] + not c.securityContext.allowPrivilegeEscalation == false + msg := sprintf("container %q must set allowPrivilegeEscalation: false", [c.name]) +} + +deny contains msg if { + input.kind == "Deployment" + c := input.spec.template.spec.containers[_] + not c.securityContext.readOnlyRootFilesystem == true + msg := sprintf("container %q must set readOnlyRootFilesystem: true", [c.name]) +} + +deny contains msg if { + input.kind == "Deployment" + c := input.spec.template.spec.containers[_] + not has_value(c.securityContext.capabilities.drop, "ALL") + msg := sprintf("container %q must drop ALL capabilities", [c.name]) +} + +# Require CPU/Memory requests and limits +deny contains msg if { + input.kind == "Deployment" + c := input.spec.template.spec.containers[_] + not c.resources.requests.cpu + msg := sprintf("container %q missing resources.requests.cpu", [c.name]) +} + +deny contains msg if { + input.kind == "Deployment" + c := input.spec.template.spec.containers[_] + not c.resources.requests.memory + msg := sprintf("container %q missing resources.requests.memory", [c.name]) +} + +deny contains msg if { + input.kind == "Deployment" + c := input.spec.template.spec.containers[_] + not c.resources.limits.cpu + msg := sprintf("container %q missing resources.limits.cpu", [c.name]) +} + +deny contains msg if { + input.kind == "Deployment" + c := input.spec.template.spec.containers[_] + not c.resources.limits.memory + msg := sprintf("container %q missing resources.limits.memory", [c.name]) +} + +# Recommend probes +warn contains msg if { + input.kind == "Deployment" + c := input.spec.template.spec.containers[_] + not c.readinessProbe + msg := sprintf("container %q should define readinessProbe", [c.name]) +} + +warn contains msg if { + input.kind == "Deployment" + c := input.spec.template.spec.containers[_] + not c.livenessProbe + msg := sprintf("container %q should define livenessProbe", [c.name]) +} diff --git a/labs/submission12.md b/labs/submission12.md new file mode 100644 index 00000000..94846308 --- /dev/null +++ b/labs/submission12.md @@ -0,0 +1,131 @@ +### Task 1 + +```bash +$ containerd-shim-kata-v2 --version +Kata Containers containerd shim (Rust): id: io.containerd.kata.v2, version: 3.23.0, commit: 8534afb9e8de3a529a537185f0fd55b66d9bc5d5 +``` + +```bash +$ sudo nerdctl run --rm --runtime io.containerd.kata.v2 alpine:3.19 uname -a +[sudo] password for bulatgazizov: +WARN[0000] cannot set cgroup manager to "systemd" for runtime "io.containerd.kata.v2" +Linux 329d9f7433ab 6.12.47 #1 SMP Fri Nov 14 15:34:06 UTC 2025 x86_64 Linux +``` + +### Task 2 + +Runc: +``` +juice-runc: HTTP 000 +``` + +Kernels version: + +- Runc - 6.15.4 +- Kata - 6.12.47 + +=== CPU Model Comparison === +- Host CPU: +model name : 12th Gen Intel(R) Core(TM) i5-12450H +- Kata VM CPU: +model name : Intel(R) Xeon(R) Processor + + +| Feature | runc | Kata Containers | +| :--- | :--- | :--- | +| **Primary Isolation** | Linux kernel namespaces & cgroups | Hardware-assisted Virtualization (VM) | +| **Security Boundary** | The Linux Kernel (single, shared) | The Hypervisor (dedicated kernel per pod) | +| **Architecture** | Single kernel, multiple isolated processes | Multiple, lightweight Virtual Machines | +| **Performance** | **Native** (very low overhead) | **Near-Native** (low, but higher than runc) | +| **Attack Surface** | Larger (shared kernel syscall interface) | Smaller (hardware-enforced VM isolation) | + + +### Task 3 + +#### Kata dmesg output: +``` +[ 0.000000] Linux version 6.12.47 (@4bcec8f4443d) (gcc (Ubuntu 11.4.0-1ubuntu1~22.04.2) 11.4.0, GNU ld (GNU Binutils for Ubuntu) 2.38) #1 SMP Fri Nov 14 15:34:06 UTC 2025 +[ 0.000000] Command line: reboot=k panic=1 systemd.unit=kata-containers.target systemd.mask=systemd-networkd.service root=/dev/vda1 rootflags=data=ordered,errors=remount-ro ro rootfstype=ext4 agent.container_pipe_size=1 console=ttyS1 agent.log_vport=1025 agent.passfd_listener_port=1027 virtio_mmio.device=8K@0xe0000000:5 virtio_mmio.device=8K@0xe0002000:5 +[ 0.000000] BIOS-provided physical RAM map: +[ 0.000000] BIOS-e820: [mem 0x0000000000000000-0x000000000009fbff] usable +``` + +#### Comparison of /proc filesystem visibility + +* Host: 528 +* Kata VM: 53 + +#### Network interface configuration in Kata VM + +``` +Kata VM network: +1: lo: mtu 65536 qdisc noqueue state UNKNOWN qlen 1000 + link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 + inet 127.0.0.1/8 scope host lo + valid_lft forever preferred_lft forever + inet6 ::1/128 scope host noprefixroute + valid_lft forever preferred_lft forever +2: eth0: mtu 1500 qdisc pfifo_fast state UP qlen 1000 + link/ether 7a:70:25:f0:55:84 brd ff:ff:ff:ff:ff:ff + inet 10.4.0.13/24 brd 10.4.0.255 scope global eth0 + valid_lft forever preferred_lft forever + inet6 fe80::7870:25ff:fef0:5584/64 scope link tentative + valid_lft forever preferred_lft forever +``` + +#### Comparison of kernel module counts (host vs guest VM) +* Host kernel modules: 354 +* Kata guest kernel modules: 72 + + +#### Explain isolation boundary differences: + +runc: All containers share the host kernel. A kernel panic or exploit affects everyone. + +Kata: Each pod has its own kernel. A kernel crash/exploit inside Kata only affects that specific pod - the host and other pods remain unaffected. + +--- +runc: Uses PID namespaces to hide processes, but all containers see the same kernel's /proc structure and potentially can probe kernel state + +Kata: The guest VM only sees processes and kernel information from its own isolated kernel instance. It cannot see host processes or other pods' processes at all. + +--- +runc: Uses network namespaces with veth pairs. Container shares host kernel networking stack. + +Kata: Gets a virtual network device (virtio) in its own VM. The network stack is completely isolated at the kernel level - different TCP/IP stack, different routing tables, different connection tracking. + +--- +runc: Exposes the entire host kernel with 354 loaded modules to each container + +Kata: The guest VM uses a minimized, hardened kernel with only essential modules (72). Even if compromised, the attacker only gets a reduced kernel, not the full host kernel. + +#### Discuss security implications: +Container escape in runc = Breaking out of Linux namespaces/cgroups to access the host system + +Container escape in Kata = Minimal guest kernel with 72 modules + hypervisor + +### Task 4 + +#### Startup time comparison + +* Runc - 0.6sec +* Kata - 6.6sec + +#### HTTP latency for juice-runc baseline: + +avg=0.0003s min=0.0001s max=0.0005s n=50 + +#### Analyze performance tradeoffs: + +Startup Overhead: 10x slower +* runc: 0.6s (near-instant process creation) +* Kata: 6.6s (VM boot + guest kernel initialization) + +Runtime overhead: 1-5% runtime overhead for most workloads + +CPU overhead: Hypervisor translation layer adds minor instruction overhead + +Interpret when to use each: +- Use runc when: High-density microservices OR Serverless functions running on controlled environments. + +- Use Kata when: Untrusted code execution, kernel vulnerabilities would be catastrophic \ No newline at end of file diff --git a/lectures/lec1.md b/lectures/lec1.md index 1cfe8b8a..21063c0c 100644 --- a/lectures/lec1.md +++ b/lectures/lec1.md @@ -934,8 +934,8 @@ else: ```mermaid flowchart TD - ATTACK[๐Ÿงญ MITRE ATT&CK] --> Tactics[๐Ÿ“Š Tactics (why?)] - ATTACK --> Techniques[๐Ÿ› ๏ธ Techniques (how?)] + ATTACK[๐Ÿงญ MITRE ATT&CK] --> Tactics[๐Ÿ“Š Tactics why?] + ATTACK --> Techniques[๐Ÿ› ๏ธ Techniques how?] ATTACK --> Mitigations[๐Ÿ›ก๏ธ Mitigations] ATTACK --> Detections[๐Ÿ”Ž Detection Methods] ``` diff --git a/lectures/lec10.md b/lectures/lec10.md new file mode 100644 index 00000000..b6f8edd5 --- /dev/null +++ b/lectures/lec10.md @@ -0,0 +1,2129 @@ +# ๐ŸŽฏ Lecture 10 - Vulnerability Management & Response: Discovery, Triage & Remediation + +## ๐Ÿ“‚ Group 1: Vulnerability Discovery + +## ๐Ÿ“ Slide 1 โ€“ ๐Ÿ” Vulnerability Discovery Methods + +* ๐Ÿ” **Vulnerability discovery** = finding security issues before attackers do +* ๐ŸŽฏ **Multiple sources:** Scanners, researchers, users, attackers +* ๐Ÿ“Š **Coverage:** Different methods find different vulnerabilities +* ๐Ÿ”‘ **Defense in depth:** Use all methods for maximum coverage + +```mermaid +flowchart LR + subgraph "๐Ÿ” Discovery Methods" + Auto[๐Ÿค– Automated
Scanners] + Manual[๐Ÿ‘จโ€๐Ÿ’ป Manual
Testing] + External[๐ŸŒ External
Sources] + end + + Auto --> Vulns[๐Ÿ“Š Vulnerabilities] + Manual --> Vulns + External --> Vulns + + Vulns --> Triage[๐ŸŽฏ Triage] + + style Vulns fill:#fff3e0,stroke:#f57c00,stroke-width:3px,color:#2c3e50 +``` + +```mermaid +flowchart LR + SAST[๐Ÿ” SAST
Code Analysis] --> Coverage[๐Ÿ“Š Total Coverage] + DAST[๐ŸŒ DAST
Runtime Testing] --> Coverage + SCA[๐Ÿ“ฆ SCA
Dependencies] --> Coverage + Pentest[๐ŸŽฏ Pentesting
Manual] --> Coverage + BugBounty[๐Ÿ’ฐ Bug Bounty
Researchers] --> Coverage + + Coverage --> Target[๐ŸŽฏ 95%+ Goal] + + style Coverage fill:#e3f2fd,stroke:#1976d2,stroke-width:3px,color:#2c3e50 + style Target fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 +``` + +--- + +### ๐Ÿค– Automated Scanning Methods + +**๐Ÿ” SAST (Static Application Security Testing):** +* โœ… Scans source code without running it +* ๐ŸŽฏ Finds: SQL injection, XSS, hardcoded secrets, buffer overflows +* โฐ When: Every commit, pull request +* ๐Ÿ› ๏ธ Tools: Snyk Code, Semgrep, SonarQube, Checkmarx +* ๐Ÿ“Š Coverage: ~70% of code vulnerabilities + +**๐ŸŒ DAST (Dynamic Application Security Testing):** +* โœ… Tests running application (black-box approach) +* ๐ŸŽฏ Finds: Authentication flaws, runtime issues, injection attacks +* โฐ When: Staging/pre-production environments +* ๐Ÿ› ๏ธ Tools: OWASP ZAP, Burp Suite, Acunetix +* ๐Ÿ“Š Coverage: Runtime vulnerabilities + +**๐Ÿ“ฆ SCA (Software Composition Analysis):** +* โœ… Scans dependencies for known vulnerabilities +* ๐ŸŽฏ Finds: Vulnerable libraries, outdated packages, license issues +* โฐ When: Every build, continuous monitoring +* ๐Ÿ› ๏ธ Tools: Snyk, Grype, Dependabot, OWASP Dependency-Check +* ๐Ÿ“‹ Covered in: Lab 8 (Supply Chain Security) + +**โš™๏ธ IaC Scanning:** +* โœ… Scans infrastructure code +* ๐ŸŽฏ Finds: Misconfigurations, compliance violations, overpermissions +* โฐ When: Pre-commit, pull request +* ๐Ÿ› ๏ธ Tools: Checkov, tfsec, Terrascan, KICS +* ๐Ÿ“‹ Covered in: Lab 6 (Infrastructure Security) + +**๐Ÿณ Container Scanning:** +* โœ… Scans container images and layers +* ๐ŸŽฏ Finds: OS vulnerabilities, malware, secrets in images +* โฐ When: Build time, registry push +* ๐Ÿ› ๏ธ Tools: Trivy, Grype, Snyk Container, Aqua +* ๐Ÿ“‹ Covered in: Lab 7 (Container Security) + +--- + +### ๐Ÿ‘จโ€๐Ÿ’ป Manual Testing Methods + +**๐ŸŽฏ Penetration Testing:** +* โœ… Ethical hackers simulate real attacks +* ๐Ÿ” Finds: Complex logic flaws, business logic vulnerabilities, chained exploits +* โฐ When: Quarterly, before major releases, after architecture changes +* ๐Ÿ‘ฅ Who: External security firms or internal red team +* ๐Ÿ’ฐ Cost: $10K-$100K per engagement +* ๐Ÿ“Š Coverage: Real-world exploitability + +**๐Ÿ‘€ Security Code Review:** +* โœ… Developers review code for security issues +* ๐Ÿ” Finds: Logic errors, design flaws, subtle vulnerabilities +* โฐ When: Every pull request (peer review process) +* ๐ŸŽฏ Focus: Critical paths, authentication, authorization, data handling +* ๐Ÿ“‹ Best practice: Security champion reviews critical changes + +**๐Ÿ“‹ Security Audits:** +* โœ… Comprehensive security assessment +* ๐Ÿ” Finds: Process gaps, architectural issues, compliance violations +* โฐ When: Annually, before compliance audits (SOC 2, ISO 27001) +* ๐Ÿ‘ฅ Who: External auditors, security consultants +* ๐Ÿ“Š Coverage: People, process, technology + +--- + +### ๐ŸŒ External Discovery Sources + +**๐Ÿ’ฐ Bug Bounty Programs:** +* โœ… Security researchers find bugs for rewards +* ๐ŸŒ Platforms: HackerOne, Bugcrowd, Synack, Intigriti +* ๐Ÿ” Finds: Real-world exploitable issues, creative attack vectors +* ๐Ÿ’ต Cost: Pay per valid bug ($100-$100K+ per finding) +* ๐ŸŽฏ Benefit: Continuous testing by global researchers + +**๐Ÿšจ CVE Alerts & Feeds:** +* โœ… New vulnerabilities in your dependencies +* ๐Ÿ“Š Sources: NVD, GitHub Advisory, OSV, vendor feeds +* ๐Ÿค– Automated: Dependabot alerts, Snyk monitoring +* โฐ Frequency: Daily monitoring required +* ๐Ÿ“ง Notification: Real-time alerts for critical CVEs + +**๐Ÿ•ต๏ธ Threat Intelligence:** +* โœ… Known attack patterns, indicators of compromise (IOCs) +* ๐Ÿ“ก Sources: CISA, vendor threat feeds, ISACs, dark web monitoring +* ๐ŸŽฏ Benefit: Proactive defense against emerging threats +* ๐Ÿ”„ Integration: SIEM, EDR, firewalls + +**๐Ÿ“ง User/Customer Reports:** +* โœ… Customers discover and report issues +* ๐Ÿ“ฌ Channel: security@company.com mailbox +* ๐Ÿ› Portal: Bug reporting form +* ๐Ÿค Response: Thank users, validate, fix, credit (if requested) + +
+๐Ÿ’ญ Coverage Gap Analysis: Why multiple methods? + +**โŒ Each method has blind spots:** + +| Method | โœ… Finds | โŒ Misses | +|--------|---------|----------| +| ๐Ÿ” **SAST** | Code-level flaws | Runtime issues, dependencies | +| ๐ŸŒ **DAST** | Runtime flaws | Internal logic, code quality | +| ๐Ÿ“ฆ **SCA** | Dependency vulns | Custom code vulnerabilities | +| ๐ŸŽฏ **Pentesting** | Real exploits | Doesn't scale, expensive | +| ๐Ÿ‘ฅ **Code Review** | Design flaws | Automated detectable issues | + +**โœ… Defense in depth:** Use all methods for 95%+ coverage + +**๐Ÿ’ก Strategy:** +* ๐Ÿค– Automate: SAST, DAST, SCA (daily/weekly) +* ๐Ÿ‘จโ€๐Ÿ’ป Manual: Pentests, audits (quarterly) +* ๐ŸŒ External: Bug bounty (continuous) +
+ +```mermaid +flowchart TD + Method[๐Ÿ” Method] --> Finds[โœ… Finds] & Misses[โŒ Misses] + + SAST[๐Ÿ” SAST] --> F1[Code flaws] & M1[Runtime issues] + DAST[๐ŸŒ DAST] --> F2[Runtime flaws] & M2[Logic issues] + SCA[๐Ÿ“ฆ SCA] --> F3[Dependency vulns] & M3[Custom code] + + F1 --> Solution[โœ… Use ALL Methods] + F2 --> Solution + F3 --> Solution + M1 --> Solution + M2 --> Solution + M3 --> Solution + + Solution --> Result[๐ŸŽฏ 95%+ Coverage] + + style Solution fill:#e8f5e8,stroke:#388e3c,stroke-width:3px,color:#2c3e50 +``` + +--- + +## ๐Ÿ“ Slide 2 โ€“ ๐Ÿ› ๏ธ Security Testing Orchestration + +* ๐ŸŽฏ **Orchestration** = coordinating multiple security tools into unified workflow +* ๐Ÿ“Š **Problem:** Tool sprawl (10+ security tools, different outputs, duplicates) +* ๐Ÿ”‘ **Solution:** Centralized platform for aggregation and deduplication +* โšก **Benefit:** Single pane of glass, consistent prioritization + +```mermaid +flowchart LR + SAST[๐Ÿ” SAST
Semgrep] --> Platform[๐Ÿ“Š Orchestration
Platform] + DAST[๐ŸŒ DAST
ZAP] --> Platform + SCA[๐Ÿ“ฆ SCA
Snyk] --> Platform + IaC[โš™๏ธ IaC
Checkov] --> Platform + Container[๐Ÿณ Container
Trivy] --> Platform + + Platform --> Dedupe[๐Ÿ”„ Deduplicate] + Dedupe --> Enrich[๐Ÿ“ˆ Enrich] + Enrich --> Output[๐Ÿ“‹ Unified View] + + style Platform fill:#e3f2fd,stroke:#1976d2,stroke-width:3px,color:#2c3e50 +``` + +```mermaid +flowchart LR + Before[โŒ 5000 Alerts
From 5 Tools] --> Orchestration[๐ŸŽฏ Orchestration] + Orchestration --> After[โœ… 1200 Unique
76% Reduction] + + After --> Benefits[โšก Benefits] + Benefits --> B1[โฐ 80% Time Saved] + Benefits --> B2[๐ŸŽฏ Clear Priorities] + Benefits --> B3[๐Ÿ“‰ No Alert Fatigue] + + style Before fill:#ffebee,stroke:#c62828,stroke-width:2px,color:#2c3e50 + style After fill:#e8f5e8,stroke:#388e3c,stroke-width:3px,color:#2c3e50 +``` + +--- + +### ๐Ÿ”„ Orchestration Workflow Steps + +**1๏ธโƒฃ Collection:** +* ๐Ÿ“ฅ Gather results from all scanners +* ๐Ÿ”„ Normalize data (different formats โ†’ standard format) +* ๐Ÿ“Š Standardize severity levels (tool-specific โ†’ CVSS) + +**2๏ธโƒฃ Deduplication:** +* ๐ŸŽฏ Same vulnerability found by multiple tools +* ๐Ÿ”— Group by: File + line + vulnerability type +* โœ… Reduces noise (5 tools reporting same issue โ†’ 1 unified report) +* ๐Ÿ“‰ Result: 80% fewer alerts (focus on unique issues) + +**3๏ธโƒฃ Enrichment:** +* ๐Ÿ“Š Add CVSS scores, EPSS probability, KEV status +* ๐Ÿ”— Link to remediation guidance (patches, code examples) +* ๐Ÿ’ผ Calculate business impact (production vs dev) +* ๐ŸŽฏ Add reachability analysis (if available) + +**4๏ธโƒฃ Prioritization:** +* ๐ŸŽฏ Risk-based scoring (CVSS + EPSS + context) +* ๐Ÿข Context-aware (production > staging > dev) +* ๐Ÿ“‹ Actionable queue for development teams +* โฐ SLA assignment based on severity + +--- + +### ๐Ÿ› ๏ธ Orchestration Platform Options + +**๐Ÿ†“ DefectDojo (Open-Source):** +* โœ… Free and open-source +* ๐Ÿ“Š Imports 100+ scanner formats +* ๐Ÿ”„ Built-in deduplication +* ๐Ÿ“ˆ Metrics and dashboards +* ๐ŸŽฏ Workflow management (assign, track, verify) +* ๐Ÿ‘ฅ Best for: Medium to large teams + +**๐Ÿ’ผ ThreadFix (Commercial):** +* ๐Ÿ’ฐ Enterprise platform +* ๐Ÿ“Š Advanced analytics and reporting +* ๐Ÿ”— SIEM integration +* ๐Ÿข Multi-tenant support +* ๐Ÿ’ต Cost: $$$ + +**๐ŸŽฏ Dependency-Track (SBOM-focused):** +* โœ… Free and open-source +* ๐Ÿ“‹ SBOM-based vulnerability management +* ๐Ÿ”„ Continuous monitoring +* ๐Ÿ“Š Policy engine +* ๐Ÿ”— Covered in: Lab 8 + +**๐Ÿ”ง Custom Solutions:** +* โœ… Parse tool outputs via API +* ๐Ÿ’พ Store in database (PostgreSQL, MongoDB) +* ๐Ÿ“Š Build custom dashboards (Grafana) +* ๐Ÿ”„ Integration flexibility + +--- + +### ๐Ÿ”— Integration Patterns + +**๐Ÿ“Š Data Flow:** +* ๐Ÿ” Scanners โ†’ API calls โ†’ Orchestration platform +* ๐Ÿ“Š Platform โ†’ Jira/GitHub Issues (ticketing) +* ๐Ÿšจ Platform โ†’ SIEM (alerting) +* ๐Ÿ“ˆ Platform โ†’ Dashboards (visualization) + +**๐Ÿค– Automation:** +* โฐ Scheduled scans (nightly builds) +* ๐Ÿ”” Real-time alerts (critical findings) +* ๐Ÿ“ง Email notifications (team assignments) +* ๐Ÿ”— Webhook triggers (Slack, PagerDuty) + +```mermaid +flowchart LR + Scanners[๐Ÿ” Scanners] -->|API| Platform[๐Ÿ“Š Platform] + Platform --> Jira[๐ŸŽซ Jira] + Platform --> Slack[๐Ÿ’ฌ Slack] + Platform --> Dashboard[๐Ÿ“ˆ Grafana] + + style Platform fill:#e3f2fd,stroke:#1976d2,stroke-width:3px,color:#2c3e50 +``` + +--- + +## ๐Ÿ“ Slide 3 โ€“ ๐Ÿ“Š Centralized Vulnerability Management + +* ๐Ÿ“Š **Centralization** = single source of truth for all vulnerabilities +* ๐ŸŽฏ **Benefits:** No duplicates, consistent tracking, clear ownership, audit trail +* ๐Ÿ”— **Integrations:** CI/CD pipelines, issue trackers, security dashboards + +**๐Ÿ“‹ Common Approaches:** + +**๐ŸŽซ Jira/GitHub Issues:** +* โœ… Familiar to developers (existing workflow) +* โœ… Easy integration with dev process +* โš ๏ธ Not security-optimized (no deduplication) +* ๐ŸŽฏ Use case: Small teams, simple needs, existing Jira setup + +**๐Ÿ›ก๏ธ DefectDojo (Security-Focused):** +* โœ… Built for vulnerability management +* โœ… Deduplication and correlation built-in +* โœ… Security-specific metrics and reporting +* ๐ŸŽฏ Use case: Medium to large teams, mature security programs + +**๐Ÿ“ฆ Dependency-Track (SBOM-Based):** +* โœ… SBOM-centric approach (from Lab 8) +* โœ… Continuous component monitoring +* โœ… Policy engine for governance +* ๐ŸŽฏ Use case: Supply chain security focus + +**๐Ÿ’ฐ Commercial Platforms:** +* ๐Ÿ”ท Snyk, Veracode, Checkmarx, Fortify +* โœ… All-in-one (scan + manage + report) +* ๐Ÿ’ต Expensive but comprehensive +* ๐ŸŽฏ Use case: Enterprise with budget + +```mermaid +flowchart LR + Sources[๐Ÿ” All Sources] --> Central[๐Ÿ“Š Central Platform] + Central --> Dashboard[๐Ÿ“ˆ Dashboard] + Central --> Tracking[๐Ÿ“‹ Tracking] + Central --> Reports[๐Ÿ“ Reports] + + style Central fill:#e3f2fd,stroke:#1976d2,stroke-width:3px,color:#2c3e50 +``` + +--- + +### ๐Ÿ“‹ Vulnerability Tracking Fields + +**๐Ÿ”‘ Essential Fields:** +* ๐Ÿ†” Unique ID (tracking identifier) +* ๐Ÿ” Source (which tool found it) +* ๐Ÿ“ Location (file, line number, component) +* ๐ŸŽฏ Severity (Critical/High/Medium/Low) +* ๐Ÿ“Š CVSS score (numerical rating) +* ๐Ÿ“ Description (what's vulnerable) +* ๐Ÿ‘ค Owner (assigned developer/team) +* ๐Ÿ“… Discovered date (when found) +* โฐ Age (days open) +* ๐Ÿ“‹ Status (Open/In Progress/Fixed/Closed) +* ๐Ÿ”ง Remediation guidance (how to fix) + +**๐Ÿ“ˆ Optional but Valuable:** +* โšก EPSS score (exploitation likelihood) +* ๐Ÿšจ KEV status (actively exploited?) +* ๐Ÿ’ผ Business impact (critical service?) +* ๐Ÿ”„ Recurrence flag (fixed before?) +* ๐Ÿงช Test status (verification completed?) +* ๐Ÿ“Š Risk score (contextual priority) + +```mermaid +flowchart TD + Vuln[๐Ÿšจ Vulnerability] --> Essential[๐Ÿ”‘ Essential
ID, Severity, Owner] + Vuln --> Optional[๐Ÿ“ˆ Optional
EPSS, KEV, Risk] + + Essential --> Track[๐Ÿ“Š Track & Prioritize] + Optional --> Track + + style Track fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 +``` + +
+๐Ÿ’ญ Deduplication Magic: From chaos to clarity + +**โŒ Before deduplication:** +* ๐Ÿ” Snyk: SQL injection in auth.js:45 +* ๐Ÿ” Semgrep: SQL injection in auth.js:45 +* ๐Ÿ” SonarQube: SQL injection in auth.js:45 +* ๐Ÿ” Checkmarx: SQL injection in auth.js:45 +* ๐Ÿ“Š **Total: 4 separate tickets, 4 alerts, 4 meetings** + +**โœ… After deduplication:** +* ๐ŸŽฏ SQL injection in auth.js:45 (found by 4 tools, confidence: very high) +* ๐Ÿ“Š **Total: 1 ticket, 1 fix, 1 verification** + +**๐ŸŽ‰ Benefits:** +* โฐ Save time (no duplicate work) +* ๐ŸŽฏ Clear priorities (focus on unique issues) +* ๐Ÿ“Š Better metrics (accurate vulnerability counts) +* ๐Ÿ‘ฅ Less alert fatigue + +**๐Ÿ’ก Deduplication criteria:** +* Same file + line + vulnerability type = duplicate +* CWE matching (same weakness category) +* Hash-based matching (exact code pattern) +
+ +```mermaid +flowchart LR + Before[โŒ 4 Tools
4 Tickets] --> Dedupe[๐Ÿ”„ Deduplication] + Dedupe --> After[โœ… 1 Ticket
High Confidence] + + Before --> Work1[๐Ÿ˜ต 4ร— Work] + After --> Work2[โœ… 1ร— Work] + + style Before fill:#ffebee,stroke:#c62828,stroke-width:2px,color:#2c3e50 + style After fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 +``` + +--- + +๐Ÿ”— **Resources for Group 1:** +* [DefectDojo](https://www.defectdojo.org/) +* [OWASP Testing Guide](https://owasp.org/www-project-web-security-testing-guide/) +* [HackerOne](https://www.hackerone.com/) +* [Bugcrowd](https://www.bugcrowd.com/) + +--- + +## ๐ŸŽ‰ Fun Break: "The Scanner That Cried Wolf" + +* ๐Ÿข Company: 7 scanners, 200 alerts/day, 85% false positives +* ๐Ÿ”ด Critical bug (Log4Shell) buried in noise, missed for 3 days +* ๐Ÿ’ฅ Exploited on day 4: $2M breach cost +* โœ… Fix: DefectDojo โ†’ 200 alerts became 30 unique findings +* ๐Ÿ’ก Lesson: More tools โ‰  more security. Orchestration saves lives! + +--- + +## ๐Ÿ“‚ Group 2: Vulnerability Assessment + +## ๐Ÿ“ Slide 4 โ€“ ๐Ÿ“Š CVSS Scoring Deep Dive + +* ๐Ÿ“Š **CVSS (Common Vulnerability Scoring System)** = standardized severity rating 0.0-10.0 +* ๐ŸŽฏ **Purpose:** Consistent prioritization across organizations and tools +* ๐Ÿ“ˆ **Current versions:** v3.1 (widely used), v4.0 (new, more nuanced) +* ๐ŸŒ **Global standard:** Used by NVD, vendors, security teams worldwide +* ๐Ÿ”— **Calculator:** [first.org/cvss/calculator](https://www.first.org/cvss/calculator/) + +```mermaid +flowchart LR + Vuln[๐Ÿšจ Vulnerability] --> Base[๐Ÿ“Š Base Score
0-10] + Base --> Temporal[โฐ Temporal
Adjustments] + Temporal --> Environmental[๐Ÿข Context] + Environmental --> Final[๐ŸŽฏ Final Score] + + Final --> Action[โšก Action Required] + + style Final fill:#fff3e0,stroke:#f57c00,stroke-width:3px,color:#2c3e50 +``` + +```mermaid +flowchart LR + Base[๐Ÿ“Š Base Score
Intrinsic properties] --> Final[๐ŸŽฏ Final CVSS
0.0 - 10.0] + Temporal[โฐ Temporal Score
Time-dependent] --> Final + Environmental[๐Ÿข Environmental
Organization-specific] --> Final + + style Final fill:#fff3e0,stroke:#f57c00,stroke-width:3px,color:#2c3e50 +``` + +--- + +### ๐Ÿ“Š CVSS v3.1 Base Metrics + +**๐ŸŒ Exploitability Metrics:** +* **๐Ÿ”— Attack Vector (AV):** Network (N) / Adjacent (A) / Local (L) / Physical (P) +* **๐Ÿงฉ Attack Complexity (AC):** Low (L) / High (H) +* **๐Ÿ”‘ Privileges Required (PR):** None (N) / Low (L) / High (H) +* **๐Ÿ‘ค User Interaction (UI):** None (N) / Required (R) + +**๐Ÿ’ฅ Impact Metrics:** +* **๐Ÿ” Confidentiality (C):** None (N) / Low (L) / High (H) +* **โœ… Integrity (I):** None (N) / Low (L) / High (H) +* **โšก Availability (A):** None (N) / Low (L) / High (H) +* **๐ŸŽฏ Scope (S):** Unchanged (U) / Changed (C) + +**๐Ÿ’ก Example: SQL Injection** +* ๐ŸŒ AV:Network (remotely exploitable) +* ๐Ÿงฉ AC:Low (easy to exploit) +* ๐Ÿ”‘ PR:None (no authentication needed) +* ๐Ÿ‘ค UI:None (no user interaction) +* ๐ŸŽฏ S:Changed (can access other systems) +* ๐Ÿ” C:High, โœ… I:High, โšก A:High +* **๐Ÿ“Š Score: 10.0 (Critical)** + +--- + +### ๐Ÿ“ˆ Severity Ranges & Actions + +| Score | Severity | Color | Action | SLA | +|-------|----------|-------|--------|-----| +| 9.0-10.0 | ๐Ÿ”ด **Critical** | Red | Fix immediately | โฐ 24 hours | +| 7.0-8.9 | ๐ŸŸ  **High** | Orange | Fix urgently | โฐ 7 days | +| 4.0-6.9 | ๐ŸŸก **Medium** | Yellow | Fix soon | โฐ 30 days | +| 0.1-3.9 | ๐ŸŸข **Low** | Green | Fix eventually | โฐ 90 days | +| 0.0 | โšช **None** | White | Informational | ๐Ÿ“‹ No fix needed | + +```mermaid +flowchart LR + CVSS[๐Ÿ“Š CVSS] --> Critical[๐Ÿ”ด 9-10
24h SLA] + CVSS --> High[๐ŸŸ  7-8.9
7d SLA] + CVSS --> Medium[๐ŸŸก 4-6.9
30d SLA] + CVSS --> Low[๐ŸŸข 0.1-3.9
90d SLA] + + style Critical fill:#ffebee,stroke:#c62828,stroke-width:2px,color:#2c3e50 + style High fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 +``` + +--- + +### โฐ Temporal Score (Optional) + +**๐Ÿ”ง Modifying Factors:** +* **๐Ÿ’ฃ Exploit Code Maturity:** Unproven / Proof-of-Concept / Functional / High +* **๐Ÿ”ง Remediation Level:** Official Fix / Temporary Fix / Workaround / Unavailable +* **๐Ÿ“Š Report Confidence:** Unknown / Reasonable / Confirmed + +**๐Ÿ“‰ Impact:** Can lower base score +* ๐Ÿ“Š Example: CVSS 9.0 base โ†’ 7.5 final (no exploit available yet, patch ready) +* โฐ Changes over time (exploit released = score increases) + +--- + +### ๐Ÿข Environmental Score (Optional) + +**๐ŸŽฏ Organization-Specific Adjustments:** +* **๐Ÿ” Confidentiality Requirement:** How sensitive is your data? +* **โœ… Integrity Requirement:** How critical is data accuracy? +* **โšก Availability Requirement:** How critical is uptime? + +**๐Ÿ’ผ Example Scenarios:** +* ๐Ÿ›’ **E-commerce site:** Availability = High (downtime = lost revenue) +* ๐Ÿ“ **Blog site:** Availability = Low (downtime = minimal impact) +* ๐Ÿฅ **Healthcare:** Confidentiality = High (HIPAA data) +* ๐Ÿ’ฐ **Finance:** Integrity = High (transaction accuracy critical) + +**๐Ÿ“Š Result:** Same vulnerability = different scores per organization + +
+๐Ÿ’ญ CVSS Limitations: What it doesn't tell you + +**โŒ CVSS doesn't consider:** +* ๐ŸŽฏ **Exploitability in the wild** (use EPSS for this) +* ๐Ÿ’ผ **Business impact** (use environmental score) +* ๐Ÿ”ง **Ease of remediation** (patch available vs. major refactor) +* ๐Ÿ” **Reachability** (is vulnerable code actually executed?) +* ๐Ÿข **Your specific environment** (production vs. dev) +* โฐ **Attack trends** (is it being exploited now?) + +**โœ… CVSS is ONE input, not the ONLY factor:** +* ๐Ÿ“Š Combine: CVSS + EPSS + KEV + Context = Smart prioritization +* ๐ŸŽฏ Use as baseline, adjust with intelligence +* ๐Ÿง  Apply judgment, don't follow blindly + +**๐Ÿ’ก Pro tip:** CVSS 9.0 with 0% exploitation = lower priority than CVSS 7.0 with active exploits +
+ +```mermaid +flowchart TD + CVSS[๐Ÿ“Š CVSS 9.0] --> Question{โ“ But is it exploited?} + Question -->|No EPSS 0%| Lower[๐Ÿ“‰ Lower Priority] + Question -->|Yes EPSS 80%| Higher[๐Ÿ“ˆ Highest Priority] + + style Higher fill:#ffebee,stroke:#c62828,stroke-width:3px,color:#2c3e50 +``` + +--- + +## ๐Ÿ“ Slide 5 โ€“ โšก Advanced Prioritization: EPSS, KEV, SSVC + +* ๐ŸŽฏ **Problem:** CVSS measures severity, NOT likelihood of exploitation +* ๐Ÿ“Š **Solution:** Combine multiple signals for intelligent prioritization +* ๐Ÿง  **Smart approach:** Likelihood ร— Impact ร— Context = Priority + +```mermaid +flowchart LR + CVSS[๐Ÿ“Š CVSS
Severity] --> Priority[๐ŸŽฏ Smart Priority] + EPSS[โšก EPSS
Likelihood] --> Priority + KEV[๐Ÿšจ KEV
Exploited] --> Priority + Context[๐Ÿข Context
Prod/Dev] --> Priority + + Priority --> P0[๐Ÿ”ด P0: Today] + Priority --> P1[๐ŸŸ  P1: Week] + Priority --> P2[๐ŸŸก P2: Month] + + style Priority fill:#fff3e0,stroke:#f57c00,stroke-width:3px,color:#2c3e50 +``` + +```mermaid +flowchart LR + CVSS[๐Ÿ“Š CVSS
Severity] --> Decision{๐ŸŽฏ Priority?} + EPSS[โšก EPSS
Likelihood] --> Decision + KEV[๐Ÿšจ KEV
Exploited?] --> Decision + Context[๐Ÿข Context
Your env] --> Decision + + Decision --> High[๐Ÿ”ด P0: Fix Today] + Decision --> Medium[๐ŸŸก P1: Fix Week] + Decision --> Low[๐ŸŸข P2: Backlog] + + style Decision fill:#fff3e0,stroke:#f57c00,stroke-width:3px,color:#2c3e50 +``` + +--- + +### โšก EPSS (Exploit Prediction Scoring System) + +* ๐ŸŽฏ **EPSS:** Probability of exploitation in next 30 days +* ๐Ÿ“Š **Score range:** 0-100% (e.g., 45% = 45% chance of active exploitation) +* ๐Ÿค– **ML-powered:** Trained on real-world exploitation data from honeypots, IDS, threat intel +* ๐Ÿ“… **Updated:** Daily with new data +* ๐Ÿ”— **Database:** [first.org/epss](https://www.first.org/epss/) + +```mermaid +flowchart LR + EPSS[โšก EPSS Score] --> High[> 70%
Fix NOW] + EPSS --> Med[30-70%
Watch Close] + EPSS --> Low[< 10%
Normal Priority] + + style High fill:#ffebee,stroke:#c62828,stroke-width:3px,color:#2c3e50 +``` + +**๐Ÿ’ก Example Prioritization:** +* ๐Ÿ”ด **CVE-2021-44228 (Log4Shell):** CVSS 10.0 + EPSS 97% โ†’ **DROP EVERYTHING, FIX NOW** +* ๐ŸŸก **CVE-2023-12345:** CVSS 9.8 + EPSS 0.3% โ†’ High severity but low exploitation โ†’ lower priority + +**๐ŸŽฏ How to Use EPSS:** +* ๐Ÿšจ EPSS > 70% โ†’ Treat as urgent (high exploitation risk) +* โš ๏ธ EPSS > 30% โ†’ Monitor closely (emerging threat) +* โœ… EPSS < 10% โ†’ Can deprioritize (low exploitation risk) + +--- + +### ๐Ÿšจ CISA KEV (Known Exploited Vulnerabilities) + +* ๐Ÿ›๏ธ **CISA KEV:** Catalog of vulnerabilities actively exploited in the wild RIGHT NOW +* ๐Ÿ”ฅ **If in KEV:** Being exploited by attackers at this moment +* โฐ **US Gov mandate:** Patch KEV vulnerabilities within 15 days (federal agencies) +* ๐Ÿ“Š **Catalog size:** 1,000+ actively exploited vulnerabilities +* ๐Ÿ”— **Catalog:** [cisa.gov/known-exploited-vulnerabilities](https://www.cisa.gov/known-exploited-vulnerabilities-catalog) + +**๐ŸŽฏ KEV = Always Highest Priority:** +* ๐Ÿ”ด Even Low CVSS + in KEV = Fix immediately +* โšก Real-world exploitation confirmed +* ๐Ÿšจ Attackers have tools and knowledge + +```mermaid +flowchart LR + Vuln[๐Ÿšจ Vulnerability] --> Check{In KEV?} + Check -->|Yes| Emergency[๐Ÿ”ด EMERGENCY
Fix in 15 days] + Check -->|No| Normal[๐Ÿ“Š Normal Process] + + style Emergency fill:#ffebee,stroke:#c62828,stroke-width:3px,color:#2c3e50 +``` + +--- + +### ๐ŸŽฏ SSVC (Stakeholder-Specific Vulnerability Categorization) + +* ๐ŸŽฏ **SSVC:** Decision tree for vulnerability prioritization +* ๐Ÿ“Š **Factors:** Exploitation status, Technical impact, Automatable, Mission impact +* ๐Ÿ”€ **Output:** Act immediately / Act / Track / Track* +* ๐Ÿง  **Benefit:** More nuanced than simple CVSS scoring + +**๐ŸŒณ Decision Tree Questions:** +1. โ“ Is it being exploited? (KEV check) +2. โ“ Is it automatable? (wormable, self-spreading?) +3. โ“ What's technical impact? (Total/Partial/Minor) +4. โ“ What's mission impact? (Mission Essential/Support/Not Critical) + +**๐Ÿ“Š Result:** Context-aware prioritization decision + +--- + +### ๐Ÿ“Š Combined Prioritization Matrix + +| CVSS | EPSS | KEV | Final Priority | Action | Timeline | +|------|------|-----|----------------|--------|----------| +| 9-10 | >70% | โœ… Yes | ๐Ÿ”ด **P0** | Fix immediately | โฐ 24 hours | +| 9-10 | >70% | โŒ No | ๐ŸŸ  **P1** | Fix urgently | โฐ 48 hours | +| 9-10 | <30% | โŒ No | ๐ŸŸก **P2** | Fix this week | โฐ 7 days | +| 7-8.9 | >70% | โœ… Yes | ๐ŸŸ  **P1** | Fix urgently | โฐ 48 hours | +| 7-8.9 | <30% | โŒ No | ๐ŸŸก **P2** | Fix this month | โฐ 30 days | +| 4-6.9 | <10% | โŒ No | ๐ŸŸข **P3** | Backlog | โฐ 90 days | + +**๐Ÿ’ก Key Insight:** High CVSS + Low EPSS + Not in KEV = Lower priority than you think! + +```mermaid +flowchart LR + V1[CVSS 9.8
EPSS 2%
No KEV] --> P2[๐ŸŸก P2: Month] + V2[CVSS 7.0
EPSS 80%
In KEV] --> P0[๐Ÿ”ด P0: Today] + + style P0 fill:#ffebee,stroke:#c62828,stroke-width:3px,color:#2c3e50 + style P2 fill:#fffde7,stroke:#f9a825,stroke-width:2px,color:#2c3e50 +``` + +
+๐Ÿ’ญ Real Scenario: 100 Vulnerabilities, What to Fix First? + +**โŒ Old Approach (CVSS only):** +* ๐Ÿ”ด Fix all 30 Critical (CVSS 9-10) first +* โฐ Timeline: 6 months to clear all Critical +* ๐Ÿšจ Meanwhile, actively exploited High severity vulns remain + +**โœ… Smart Approach (Combined signals):** +* ๐Ÿ”ฅ **3 in KEV catalog** โ†’ Fix TODAY (P0) +* โšก **7 with EPSS > 50%** โ†’ Fix THIS WEEK (P1) +* ๐ŸŽฏ **20 with CVSS 9+ but EPSS < 5%** โ†’ Fix NEXT MONTH (P2) + +**๐Ÿ“Š Result:** +* โœ… Fixed the 10 that matter most in 1 week +* ๐ŸŽฏ 80% risk reduction with 10% effort +* โฐ Not 6 months, just 1 week for critical threats + +**๐Ÿ’ก Lesson:** Work smarter, not harder. Prioritize by actual threat, not just severity. +
+ +```mermaid +flowchart LR + Scenario[100 Vulns] --> Old[โŒ Old: Fix all 30 Critical
6 months] + Scenario --> Smart[โœ… Smart: Fix 10 KEV+High EPSS
1 week] + + Smart --> Result[๐ŸŽฏ 80% Risk Reduction
10% Effort] + + style Smart fill:#e8f5e8,stroke:#388e3c,stroke-width:3px,color:#2c3e50 +``` + +--- + +## ๐Ÿ“ Slide 6 โ€“ ๐ŸŽฏ Risk-Based Prioritization + +* ๐ŸŽฏ **Risk = Likelihood ร— Impact ร— Exposure** +* ๐Ÿข **Context matters:** Same vulnerability = different risk in different environments +* ๐Ÿ“Š **Your environment:** Production vs. dev, internet-facing vs. internal, customer data vs. test data + +```mermaid +flowchart LR + Likelihood[๐Ÿ“Š Likelihood
EPSS+KEV] --> Risk[๐ŸŽฏ Risk Score] + Impact[๐Ÿ’ฅ Impact
CVSS] --> Risk + Context[๐Ÿข Context
Environment] --> Risk + + Risk --> Final[โšก Final Priority] + + style Risk fill:#fff3e0,stroke:#f57c00,stroke-width:3px,color:#2c3e50 +``` + +```mermaid +flowchart LR + Likelihood[๐Ÿ“Š Likelihood
EPSS, KEV] --> Risk[๐ŸŽฏ Risk Score] + Impact[๐Ÿ’ฅ Impact
CVSS, Business] --> Risk + Context[๐Ÿข Context
Exposure, Criticality] --> Risk + + Risk --> Priority[โšก Priority Queue] + + style Risk fill:#fff3e0,stroke:#f57c00,stroke-width:3px,color:#2c3e50 +``` + +--- + +### ๐Ÿข Contextual Risk Factors + +**๐ŸŽฏ Asset Criticality:** +* ๐Ÿ”ด Production, customer-facing โ†’ **Highest priority** +* ๐ŸŸก Staging, internal tools โ†’ **Medium priority** +* ๐ŸŸข Development, testing โ†’ **Lower priority** +* โšช Sandbox, demo โ†’ **Lowest priority** + +**๐ŸŒ Exposure Level:** +* ๐ŸŒ Internet-facing public API โ†’ **Highest priority** +* ๐Ÿข Internal service, VPN-only โ†’ **Medium priority** +* ๐Ÿ”’ Private network, authenticated โ†’ **Lower priority** +* ๐Ÿ๏ธ Air-gapped system โ†’ **Lowest priority** + +**๐Ÿ’ผ Data Sensitivity:** +* ๐Ÿ’ณ Payment data (PCI-DSS), PII (GDPR) โ†’ **Highest priority** +* ๐Ÿ“Š Confidential business data โ†’ **Medium priority** +* ๐Ÿ“ Non-sensitive business data โ†’ **Lower priority** +* ๐ŸŒ Public data โ†’ **Lowest priority** + +**๐Ÿ›ก๏ธ Compensating Controls:** +* โœ… WAF in front (Web Application Firewall) โ†’ **Reduce priority** +* โœ… Network segmentation (isolated) โ†’ **Reduce priority** +* โœ… Strong authentication (MFA) โ†’ **Reduce priority** +* โŒ No controls โ†’ **Increase priority** + +--- + +### ๐Ÿ” Reachability Analysis + +* ๐ŸŽฏ **Critical question:** Is vulnerable code actually executed in your application? +* ๐Ÿ“Š **Reality:** ~70% of vulnerabilities may be unreachable (code exists but never runs) +* ๐Ÿ”ง **Tools:** Snyk (reachability feature), GitHub CodeQL (dataflow analysis) + +**๐Ÿ’ก Example:** +* ๐Ÿ“ฆ Vulnerability in lodash.template() function +* ๐Ÿ” Your code imports lodash but never calls .template() +* โœ… Vulnerability exists but **NOT exploitable** +* ๐ŸŽฏ Action: Lower priority (but don't ignore forever - transitive risk) + +```mermaid +flowchart LR + Vuln[๐Ÿšจ lodash vuln] --> Reach{๐Ÿ” Reachable?} + Reach -->|Yes| High[๐Ÿ”ด High Priority] + Reach -->|No| Lower[๐ŸŸก Lower Priority] + + style High fill:#ffebee,stroke:#c62828,stroke-width:2px,color:#2c3e50 + style Lower fill:#fffde7,stroke:#f9a825,stroke-width:2px,color:#2c3e50 +``` + +--- + +### ๐Ÿ“Š Custom Risk Scoring + +**๐Ÿงฎ Example Formula:** + +**Risk Score = (CVSS ร— 0.3) + (EPSS ร— 100 ร— 0.3) + (Criticality ร— 0.2) + (Exposure ร— 0.2)** + +**Where:** +* ๐Ÿ“Š CVSS: 0-10 (severity) +* โšก EPSS: 0-1, multiplied by 100 (likelihood) +* ๐Ÿข Criticality: 0-10 (0=dev, 5=staging, 10=prod) +* ๐ŸŒ Exposure: 0-10 (0=internal, 5=VPN, 10=internet) + +**๐Ÿ’ก Example Calculation:** +* ๐Ÿ”ด SQL injection in production API +* ๐Ÿ“Š CVSS: 9.8 +* โšก EPSS: 0.45 (45%) +* ๐Ÿข Criticality: 10 (production) +* ๐ŸŒ Exposure: 10 (internet-facing) +* **๐ŸŽฏ Risk Score:** (9.8ร—0.3) + (45ร—0.3) + (10ร—0.2) + (10ร—0.2) = **20.4/30 (HIGH)** + +**๐Ÿšจ Action:** Fix immediately (P0 priority) + +```mermaid +flowchart LR + Inputs[๐Ÿ“Š Inputs] --> Formula[๐Ÿงฎ Risk Formula] + Formula --> Score[๐ŸŽฏ Risk Score 0-30] + Score --> Priority[โšก Priority Level] + + style Formula fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 +``` + +
+๐Ÿ’ญ Tune Your Formula: One size doesn't fit all + +**๐Ÿ›’ E-commerce Company:** +* โฌ†๏ธ Higher weight: Availability impact (downtime = lost sales) +* โฌ†๏ธ Higher weight: Exposure (public-facing) +* โฌ‡๏ธ Lower weight: Internal tools + +**๐Ÿฅ Healthcare Organization:** +* โฌ†๏ธ Higher weight: Data sensitivity (HIPAA compliance) +* โฌ†๏ธ Higher weight: Integrity impact (data accuracy) +* โฌ†๏ธ Higher weight: Confidentiality + +**๐Ÿข Internal Tools Company:** +* โฌ‡๏ธ Lower weight: Exposure (mostly internal) +* โฌ†๏ธ Higher weight: Criticality (mission-critical vs. nice-to-have) + +**๐ŸŽฏ Strategy:** +1. โœ… Start with default weights (balanced approach) +2. ๐Ÿ“Š Track outcomes (are you fixing the right things?) +3. ๐Ÿ”„ Adjust weights based on your incidents +4. ๐Ÿ“ˆ Iterate quarterly (refine based on data) + +**๐Ÿ’ก Remember:** Your risk tolerance โ‰  other companies' risk tolerance +
+ +--- + +## ๐Ÿ“ Slide 7 โ€“ ๐Ÿšจ Triage Workflows & Decisions + +* ๐Ÿšจ **Triage** = rapid assessment and categorization of vulnerabilities +* ๐ŸŽฏ **Possible outcomes:** Accept, Fix, Mitigate, Defer, False Positive +* โฐ **Speed matters:** Don't let vulnerabilities age in triage queue +* ๐Ÿ“Š **Goal:** Every vulnerability triaged within 24-48 hours + +```mermaid +flowchart LR + Vuln[๐Ÿ” Discovered] --> Triage{๐Ÿšจ Decision} + + Triage --> Fix[๐Ÿ”ง Fix] + Triage --> Mitigate[๐Ÿ›ก๏ธ Mitigate] + Triage --> Accept[โœ… Accept] + Triage --> Defer[โฐ Defer] + Triage --> FP[โŒ False Positive] + + style Triage fill:#fff3e0,stroke:#f57c00,stroke-width:3px,color:#2c3e50 +``` + +```mermaid +flowchart LR + Vuln[๐Ÿ” Vulnerability
Discovered] --> Triage{๐Ÿšจ Triage
Decision} + + Triage --> Accept[โœ… Accept Risk
Document & Monitor] + Triage --> Fix[๐Ÿ”ง Fix
Patch/Code Change] + Triage --> Mitigate[๐Ÿ›ก๏ธ Mitigate
Workaround/Controls] + Triage --> Defer[โฐ Defer
Add to Backlog] + Triage --> FP[โŒ False Positive
Mark & Close] + + style Triage fill:#fff3e0,stroke:#f57c00,stroke-width:3px,color:#2c3e50 +``` + +--- + +### โœ… Triage Decision Matrix + +| Condition | Decision | Action | Timeline | +|-----------|----------|--------|----------| +| ๐Ÿšจ In KEV catalog | **๐Ÿ”ง Fix** | Immediate remediation | โฐ 24h | +| ๐Ÿ”ด Critical + Production | **๐Ÿ”ง Fix** | Urgent patch | โฐ 24-48h | +| ๐ŸŸ  High + No patch available | **๐Ÿ›ก๏ธ Mitigate** | WAF rule, network block | โฐ 48h | +| ๐ŸŸข Low + Legacy system EOL | **โœ… Accept** | Document risk, monitor | ๐Ÿ“‹ Review quarterly | +| ๐Ÿค– Scanner false detection | **โŒ False Positive** | Mark, tune scanner | โฐ Same day | +| ๐ŸŸก Medium + Low EPSS | **โฐ Defer** | Add to backlog | ๐Ÿ“‹ Next sprint | + +--- + +### ๐Ÿ”ง Fix Decision (Permanent Remediation) + +**โœ… When to Fix:** +* ๐Ÿ”ด High risk (CVSS + EPSS + KEV + context) +* ๐Ÿญ Production environment affected +* ๐Ÿ’Š Patch available from vendor +* ๐Ÿšซ No acceptable workaround +* ๐Ÿ“ˆ Business impact significant + +**๐Ÿ› ๏ธ Fix Strategies:** +* ๐Ÿ“ฆ Update dependency (SCA findings) +* ๐Ÿ” Apply security patch (OS/library updates) +* ๐Ÿ’ป Code change (SAST findings - rewrite vulnerable code) +* โš™๏ธ Configuration change (IaC findings) + +--- + +### ๐Ÿ›ก๏ธ Mitigate Decision (Temporary Control) + +**โš ๏ธ When to Mitigate:** +* โŒ No patch available yet (zero-day situation) +* ๐Ÿงช Patch breaks functionality (needs testing) +* โฐ Fix requires major refactor (time-consuming) +* ๐Ÿ”„ Waiting for vendor patch release + +**๐Ÿ”ง Mitigation Strategies:** +* ๐Ÿ”ฅ **WAF rule:** Block exploit pattern (ModSecurity, AWS WAF) +* ๐ŸŒ **Network segmentation:** Limit access (VPN, IP whitelisting) +* ๐Ÿ”’ **Authentication layer:** Add additional auth requirement +* โฑ๏ธ **Rate limiting:** Slow down potential attacks +* ๐Ÿ“Š **Enhanced monitoring:** Detect exploitation attempts +* ๐Ÿšซ **Feature flag:** Temporarily disable vulnerable feature + +**โš ๏ธ Remember:** Mitigations are temporary - must still fix root cause + +--- + +### โœ… Accept Risk Decision (Documented Exception) + +**๐Ÿ“‹ When to Accept:** +* ๐ŸŸข Low risk (Low CVSS + Low EPSS + Not in KEV) +* ๐Ÿšซ Not reachable (dead code, never executed) +* ๐Ÿ›ก๏ธ Strong compensating controls (already well-protected) +* ๐Ÿ’ฐ Cost > Benefit (legacy system retiring in 30 days) +* ๐Ÿ—๏ธ Architectural limitation (would require full rewrite) + +**๐Ÿ“‹ Requirements for Risk Acceptance:** +* ๐Ÿ“ Document decision (why accepting, what's the risk) +* ๐Ÿ‘” Get approval (manager, security team, or risk committee) +* ๐Ÿ“… Set review date (re-evaluate quarterly or when context changes) +* ๐Ÿ”” Monitor continuously (ensure assumption remains valid) +* โš–๏ธ Legal sign-off (if compliance-related) + +--- + +### โŒ False Positive Handling + +**๐Ÿ” Common False Positives:** +* ๐Ÿงช Test code flagged as vulnerable (not in production) +* ๐Ÿ’€ Dead code never executed (commented out, unreachable) +* โš™๏ธ Scanner misconfiguration (wrong context) +* ๐Ÿ”„ Duplicate of already-fixed issue (tool lag) +* ๐ŸŽฏ Context misunderstanding (looks vulnerable but isn't) + +**โœ… Process:** +1. ๐Ÿ” Validate (is it really a false positive? Double-check) +2. ๐Ÿท๏ธ Mark in tool (prevent re-reporting in future scans) +3. โš™๏ธ Tune scanner (adjust rules, add exceptions) +4. ๐Ÿ“Š Track FP rate (metric: should be < 20%) +5. ๐Ÿ”„ Review periodically (false positives can become real) + +
+๐Ÿ’ญ Triage SLA: Speed kills (vulnerabilities, that is!) + +**โฐ Recommended Triage Speed:** +* ๐Ÿ”ด **Critical:** Triage within 4 hours (same business day) +* ๐ŸŸ  **High:** Triage within 24 hours (next business day) +* ๐ŸŸก **Medium:** Triage within 3 days +* ๐ŸŸข **Low:** Triage within 1 week + +**๐Ÿ“Š Why Speed Matters:** +* โฐ Old vulnerabilities = forgotten vulnerabilities +* ๐Ÿ“š Triage backlog = accumulating risk +* ๐ŸŽฏ Fast triage = faster fixes +* ๐Ÿ“ˆ Metric: Average triage time (track and improve) + +**๐ŸŽฏ Goal:** Zero vulnerabilities untriaged > 1 week + +**๐Ÿ’ก Pro Tip:** +* ๐Ÿค– Automate triage where possible (auto-FP, auto-defer low EPSS) +* ๐Ÿ‘ฅ Dedicated triage rotation (security champion duty) +* ๐Ÿ“Š Daily standup includes triage queue review +
+ +--- + +๐Ÿ”— **Resources for Group 2:** +* [CVSS Calculator](https://www.first.org/cvss/calculator/) +* [EPSS Scores](https://www.first.org/epss/) +* [CISA KEV Catalog](https://www.cisa.gov/known-exploited-vulnerabilities-catalog) +* [SSVC Framework](https://www.cisa.gov/ssvc) + +--- + +## ๐Ÿ’ญ Interactive: "Triage Challenge" + +**๐ŸŽฏ Scenario: You have 10 vulnerabilities. Prioritize them!** + +1. ๐Ÿ”“ SQL injection in admin portal (CVSS 9.8, EPSS 2%, internal-only, VPN) +2. ๐ŸŒ XSS in public blog (CVSS 6.5, EPSS 15%, internet-facing) +3. ๐Ÿ” Outdated OpenSSL (CVSS 9.0, EPSS 80%, in KEV, dev environment only) +4. ๐Ÿ”‘ Hardcoded API key in test code (CVSS 7.5, never deployed to prod) +5. ๐Ÿ’ฅ RCE in production API (CVSS 10.0, EPSS 85%, in KEV, production) +6. ๐Ÿ“„ Info disclosure staging (CVSS 5.3, EPSS 1%, staging environment) +7. ๐Ÿ”’ Weak password policy (CVSS 4.0, EPSS 5%, all environments) +8. ๐ŸŒ SSRF in internal tool (CVSS 8.8, EPSS 25%, VPN-only access) +9. ๐Ÿ’ณ Deserialization in payment service (CVSS 9.8, EPSS 60%, production) +10. ๐Ÿ“ฑ Unpatched library mobile app (CVSS 7.0, EPSS 10%, app store) + +
+๐Ÿ” Click to reveal expert prioritization + +**๐ŸŽฏ Priority Ranking:** + +**๐Ÿ”ด P0 (Fix Today - Drop Everything):** +1. **#5:** ๐Ÿ’ฅ RCE + production + KEV + EPSS 85% = **CRITICAL EMERGENCY** +2. **#9:** ๐Ÿ’ณ Deserialization + production payment + EPSS 60% = **CRITICAL** + +**๐ŸŸ  P1 (Fix This Week - High Urgency):** +3. **#3:** ๐Ÿ” KEV status trumps dev environment (shows active exploitation) +4. **#2:** ๐ŸŒ Public-facing + medium EPSS (real exposure) + +**๐ŸŸก P2 (Fix This Month - Medium Priority):** +5. **#8:** ๐ŸŒ High CVSS but VPN-only (limited exposure) +6. **#10:** ๐Ÿ“ฑ Mobile requires app update cycle (delayed deployment) +7. **#1:** ๐Ÿ”“ High CVSS but internal-only + low EPSS + +**๐ŸŸข P3 (Backlog - Low Priority):** +8. **#7:** ๐Ÿ”’ Process issue, long-term fix +9. **#6:** ๐Ÿ“„ Staging only, low risk + +**โŒ False Positive / No Action:** +10. **#4:** ๐Ÿ”‘ Test code never deployed (mark as FP, remove from prod builds) + +**๐Ÿ’ก Key Insights:** +* ๐ŸŽฏ #5 and #9 are true emergencies (production + high exploitation) +* ๐Ÿšจ #3 is in KEV despite being dev (active exploitation elsewhere) +* ๐Ÿ“Š #1 has highest CVSS but lowest actual risk (internal + low EPSS) +* โฐ Can address top 4 (real threats) within 1 week +* ๐Ÿ’ฐ Ignore CVSS-only prioritization (would put #1 before #2, wrong!) + +**๐Ÿ† Result:** Fixed highest risks in days, not months! +
+ +--- + +๐Ÿ”— **Resources for Group 2:** +* [CVSS Calculator](https://www.first.org/cvss/calculator/) +* [EPSS Scores](https://www.first.org/epss/) +* [CISA KEV Catalog](https://www.cisa.gov/known-exploited-vulnerabilities-catalog) +* [SSVC Framework](https://www.cisa.gov/ssvc) + +--- + +## ๐Ÿ’ญ Interactive: "Triage Challenge" (See details in slide) + +--- + +## ๐Ÿ“‚ Group 3: Remediation Workflows + +## ๐Ÿ“ Slide 8 โ€“ ๐Ÿ”ง Remediation Strategies + +* ๐Ÿ”ง **Remediation** = permanently fixing vulnerabilities +* ๐ŸŽฏ **Strategies vary:** Patch, upgrade, code rewrite, configuration change +* โฐ **Speed = Risk Reduction:** Faster fixes = lower exposure window +* โœ… **Verification required:** "Fixed" must be validated + +```mermaid +flowchart LR + Vuln[๐Ÿšจ Vulnerability] --> Strategy{๐Ÿ”ง Strategy?} + + Strategy --> Patch[๐Ÿ’Š Patch
Update Library] + Strategy --> Code[๐Ÿ’ป Code Fix
Rewrite Logic] + Strategy --> Config[โš™๏ธ Config Change
Settings] + Strategy --> Workaround[๐Ÿ›ก๏ธ Workaround
Temporary] + + Patch --> Test[๐Ÿงช Test & Verify] + Code --> Test + Config --> Test + + Test --> Deploy[๐Ÿš€ Deploy Fix] + + style Strategy fill:#fff3e0,stroke:#f57c00,stroke-width:3px,color:#2c3e50 +``` + +```mermaid +flowchart TD + Type[๐Ÿšจ Vuln Type] --> Patch[๐Ÿ’Š Patch
Dependencies] + Type --> Code[๐Ÿ’ป Code Fix
SAST] + Type --> Config[โš™๏ธ Config
IaC] + Type --> Temp[๐Ÿ›ก๏ธ Workaround
Temporary] + + Patch --> Test[๐Ÿงช Test] + Code --> Test + Config --> Test + Test --> Deploy[๐Ÿš€ Deploy] + + style Test fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 +``` + +--- + +### ๐Ÿ’Š Patching Strategy (Dependencies) + +**โœ… When:** Vulnerability in third-party library or package + +**๐Ÿ“‹ Process:** +1. ๐Ÿ” Check patch availability (is update available?) +2. ๐Ÿ“– Review changelog (breaking changes? migration needed?) +3. ๐Ÿ“ Update version in manifest (package.json, pom.xml, requirements.txt) +4. ๐Ÿ”’ Update lockfile (package-lock.json, Pipfile.lock) +5. ๐Ÿงช Test thoroughly (automated tests + manual testing) +6. ๐Ÿš€ Deploy (gradual rollout recommended) + +**๐Ÿค– Automation Options:** +* ๐Ÿ”„ Dependabot creates auto-PRs +* โœ… CI/CD runs automated test suite +* ๐Ÿ”€ Auto-merge for patch updates (if tests pass) +* ๐Ÿ“Š Rollback on failure detection + +--- + +### ๐Ÿ’ป Code Change Strategy (Application Vulnerabilities) + +**โœ… When:** Vulnerability in your own code (SAST findings) + +**๐Ÿ“‹ Process:** +1. ๐Ÿง  Understand vulnerability (root cause analysis, not just symptom) +2. ๐Ÿ”ง Write secure fix (follow secure coding guidelines) +3. ๐Ÿงช Write regression test (prevent reoccurrence) +4. ๐Ÿ‘€ Security-focused code review (peer review with security lens) +5. ๐Ÿš€ Deploy through normal release cycle + +**๐Ÿ’ก Example Types:** +* ๐Ÿ”“ SQL injection โ†’ Use parameterized queries +* ๐ŸŒ XSS โ†’ Proper output encoding +* ๐Ÿ” Weak crypto โ†’ Use strong algorithms +* ๐Ÿ”‘ Auth bypass โ†’ Fix authorization logic + +--- + +### โš™๏ธ Configuration Change Strategy + +**โœ… When:** Misconfiguration vulnerability (IaC findings) + +**๐Ÿ“‹ Process:** +1. ๐Ÿ“ Update IaC code (Terraform, CloudFormation, Ansible) +2. ๐Ÿ” Run IaC security scan (verify fix) +3. ๐Ÿงช Test in staging environment +4. ๐Ÿš€ Apply changes (terraform apply, cloudformation update) +5. โœ… Verify actual state (check cloud console) + +**๐Ÿ’ก Example Fixes:** +* ๐Ÿชฃ Public S3 bucket โ†’ Set ACL to private, enable block public access +* ๐Ÿ”“ Open security group โ†’ Restrict to specific IPs/ports +* ๐Ÿ” Unencrypted database โ†’ Enable encryption at rest + +--- + +### ๐Ÿ›ก๏ธ Workaround Strategy (Temporary Mitigation) + +**โš ๏ธ When:** Cannot fix immediately (zero-day, testing needed, major refactor) + +**๐Ÿ”ง Temporary Options:** +* ๐Ÿ”ฅ **WAF rule:** Block specific attack patterns +* ๐ŸŒ **Network isolation:** Restrict network access +* ๐Ÿ”’ **Additional authentication:** Add extra auth layer +* โฑ๏ธ **Rate limiting:** Slow down potential attacks +* ๐Ÿšซ **Feature flag:** Disable vulnerable functionality +* ๐Ÿ“Š **Enhanced logging:** Detect exploitation attempts + +**โš ๏ธ Critical:** Workarounds are NOT solutions - must still fix permanently + +--- + +### โŒ When NOT to Fix + +**๐Ÿ“‹ Valid Reasons:** +* โœ… False positive (not actually vulnerable) +* โœ… Risk accepted (documented, approved decision) +* โœ… Not reachable (dead code, never executed) +* โœ… System retiring (EOL < 30 days) +* โœ… Compensating controls sufficient + +**๐Ÿ“ Important:** Document decision, get approval, set review date + +
+๐Ÿ’ญ Remediation Reality Check: How fast can you really fix? + +**โฐ Ideal vs. Reality:** + +| Severity | ๐ŸŽฏ Ideal SLA | ๐Ÿ˜“ Reality | ๐Ÿšซ Bottleneck | +|----------|-------------|-----------|---------------| +| ๐Ÿ”ด Critical | 24 hours | 3-5 days | Testing, approvals, deployment windows | +| ๐ŸŸ  High | 7 days | 2-3 weeks | Prioritization, resource availability | +| ๐ŸŸก Medium | 30 days | 1-3 months | Backlog, competing priorities | +| ๐ŸŸข Low | 90 days | 6+ months | Never gets prioritized | + +**๐Ÿš€ How to Speed Up:** +* ๐Ÿค– Automate testing (comprehensive test suite) +* ๐Ÿ“‹ Pre-approve patches (security exception process) +* ๐Ÿ”„ Continuous deployment (deploy multiple times daily) +* ๐Ÿ‘ฅ Empower teams (reduce approval bottlenecks) +* ๐ŸŽฏ Clear SLAs (accountability and urgency) + +** ๐ŸŽฏ Goal:** Critical vulnerabilities fixed in < 48 hours consistently +
+ +```mermaid +flowchart LR + Ideal[๐ŸŽฏ Ideal SLA
24h Critical] --> Reality[๐Ÿ˜“ Reality
3-5 days] + Reality --> Improve[๐Ÿš€ Speed Up] + Improve --> Auto[๐Ÿค– Automate] + Improve --> Pre[๐Ÿ“‹ Pre-approve] + Improve --> CD[๐Ÿ”„ Continuous Deploy] + + style Improve fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 +``` + +--- + +## ๐Ÿ“ Slide 9 โ€“ โฑ๏ธ SLA Management & Tracking + +* โฑ๏ธ **SLA (Service Level Agreement)** = maximum time to fix vulnerability +* ๐ŸŽฏ **Based on severity:** Critical faster than Low +* ๐Ÿ“Š **Track compliance:** Percentage fixed within SLA targets +* ๐Ÿšจ **Escalate violations:** Don't let things slip through cracks + +**๐Ÿ“‹ Standard SLA Table:** + +| Severity | ๐ŸŽฏ SLA Target | โฐ Clock Starts | ๐Ÿšจ Escalation Point | +|----------|---------------|-----------------|---------------------| +| ๐Ÿ”ด Critical | 24 hours | โœ… After triage | ๐Ÿšจ 12h โ†’ Manager | +| ๐ŸŸ  High | 7 days | โœ… After triage | ๐Ÿšจ 5d โ†’ Manager | +| ๐ŸŸก Medium | 30 days | โœ… After triage | ๐Ÿšจ 25d โ†’ Track closely | +| ๐ŸŸข Low | 90 days | โœ… After triage | ๐Ÿšจ 80d โ†’ Review validity | + +```mermaid +flowchart LR + Triage[โœ… Triaged] --> Clock[โฐ SLA Starts] + Clock --> Critical[๐Ÿ”ด 24h] + Clock --> High[๐ŸŸ  7d] + Clock --> Medium[๐ŸŸก 30d] + Clock --> Low[๐ŸŸข 90d] + + Critical --> Escalate[๐Ÿšจ 12h โ†’ Manager] + + style Clock fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + style Critical fill:#ffebee,stroke:#c62828,stroke-width:2px,color:#2c3e50 +``` + +--- + +### โฐ SLA Clock Management + +**โœ… When SLA Starts:** +* โœ… After vulnerability triaged and assigned +* โœ… Not when scanner finds it (unknown at that point) +* โœ… Not when it first existed (impossible to know) + +**โธ๏ธ SLA Pause Scenarios:** +* โธ๏ธ Waiting for vendor patch (documented) +* โธ๏ธ Blocked by external dependency +* โธ๏ธ Requires business decision (escalated) + +**โŒ Not Valid Pauses:** +* โŒ "We're busy with features" (security is priority) +* โŒ "Waiting for next sprint" (security doesn't wait) +* โŒ "Not enough resources" (escalate for resources) + +--- + +### ๐Ÿ“Š SLA Metrics to Track + +**๐ŸŽฏ Key Metrics:** +* ๐Ÿ“ˆ **SLA compliance rate:** % vulnerabilities fixed within SLA +* โฐ **Average fix time:** Mean time by severity +* ๐Ÿšจ **SLA violations:** Count of breaches +* ๐Ÿ“… **Aging violations:** Vulnerabilities past SLA deadline +* ๐Ÿ“Š **Trend analysis:** Improving or degrading over time + +**๐Ÿ’ผ Dashboard Example:** +* ๐Ÿ”ด Critical: 95% within SLA (Target: 100%) - โš ๏ธ Needs improvement +* ๐ŸŸ  High: 88% within SLA (Target: 90%) - ๐Ÿ“ˆ Close to target +* ๐ŸŸก Medium: 72% within SLA (Target: 80%) - ๐Ÿšจ Action needed +* ๐ŸŸข Low: 65% within SLA (Target: 70%) - ๐Ÿ“‰ Backlog issue + +--- + +### ๐Ÿšจ SLA Escalation Path + +**๐Ÿ”„ Escalation Workflow:** +* ๐Ÿ“… **Day 0:** Developer assigned, notification sent +* โฐ **50% SLA:** Automated reminder (Slack, email) +* ๐Ÿ“ข **75% SLA:** Team lead notified, daily check-ins +* ๐Ÿšจ **100% SLA (breach):** Manager escalation, root cause analysis +* ๐Ÿ”ด **150% SLA:** Executive involvement, process review + +**๐ŸŽฏ Goal:** Prevent slipping through cracks, ensure accountability + +--- + +## ๐Ÿ“ Slide 10 โ€“ ๐Ÿ”„ Remediation Tracking & Verification + +* ๐Ÿ”„ **Track lifecycle:** Open โ†’ In Progress โ†’ Fixed โ†’ Verified โ†’ Closed +* ๐Ÿงช **Verification critical:** Don't trust "fixed" without testing +* ๐Ÿ“Š **Prevent recurrence:** Same vulnerability shouldn't return +* ๐Ÿ“ˆ **Metrics matter:** Fix rate, aging, recurrence rate + +```mermaid +flowchart LR + Open[๐Ÿ“‹ Open] --> InProgress[โš™๏ธ In Progress] + InProgress --> Fixed[โœ… Fixed] + Fixed --> Verify[๐Ÿงช Verify] + Verify --> Closed[๐Ÿ”’ Closed] + + Verify -.->|Fail| InProgress + Closed -.->|Regression| Open + + style Closed fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 +``` + +```mermaid +flowchart LR + Open[๐Ÿ“‹ Open
Triaged] --> InProgress[โš™๏ธ In Progress
Being Fixed] + InProgress --> Fixed[โœ… Fixed
Deployed] + Fixed --> Verify[๐Ÿงช Verify
Test] + Verify --> Closed[๐Ÿ”’ Closed
Done] + + Verify -->|Failed| InProgress + Closed -.->|Regression| Open + + style Closed fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 +``` + +--- + +### ๐Ÿ“Š Vulnerability States Explained + +* ๐Ÿ“‹ **Open:** Triaged, waiting for developer assignment or pickup +* โš™๏ธ **In Progress:** Developer actively working on fix +* โœ… **Fixed:** Code changed, patch applied, deployed to environment +* ๐Ÿงช **Verified:** Tested and confirmed vulnerability no longer exists +* ๐Ÿ”’ **Closed:** Permanently resolved, archived +* โŒ **False Positive:** Not a real vulnerability, marked and closed + +**๐Ÿ“Š Metric:** Average days in each state (identify bottlenecks) + +--- + +### ๐Ÿงช Verification Checklist + +**โœ… Before closing vulnerability:** +1. ๐Ÿ” **Rescan:** Vulnerability scanner no longer detects it +2. ๐Ÿงช **Test:** Exploitation attempt fails (try to exploit manually) +3. ๐Ÿ‘€ **Code review:** Fix is actually secure (not just hiding symptom) +4. ๐Ÿ”„ **Regression test:** Added to test suite (won't return) +5. ๐Ÿ“ **Documentation:** Updated secure coding guidelines (if applicable) + +**โš ๏ธ Don't Skip Verification:** +* ๐Ÿšจ "Fixed" โ‰  Actually fixed (common mistake) +* ๐Ÿงช Always test the fix +* ๐Ÿ”„ Verify in production (not just staging) + +```mermaid +flowchart LR + Fixed[โœ… Fixed] --> Rescan[๐Ÿ” Rescan] + Rescan --> Test[๐Ÿงช Test] + Test --> Review[๐Ÿ‘€ Review] + Review --> Verified[โœ… Verified] + + Rescan -.->|Still There| Reopen[๐Ÿ”„ Reopen] + Test -.->|Fails| Reopen + + style Verified fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 +``` + +--- + +### ๐Ÿ”„ Recurrence Prevention + +* ๐Ÿ”„ **Recurrence:** Same vulnerability type reappears +* ๐ŸŽฏ **Root causes:** Incomplete fix, code duplication, no tests, lack of training +* ๐Ÿ“Š **Target metric:** Recurrence rate < 5% + +**โœ… Prevention Strategies:** +* ๐Ÿ” **Root cause analysis:** Why did it happen? Why did it return? +* ๐Ÿงช **Regression tests:** Automated tests prevent reoccurrence +* ๐ŸŽ“ **Secure coding training:** Educate developers on patterns +* ๐Ÿ”ง **Linting rules:** Detect pattern automatically (ESLint, SonarQube rules) +* ๐Ÿ“‹ **Secure code templates:** Provide secure examples +* ๐Ÿ‘€ **Code review focus:** Watch for similar patterns + +```mermaid +flowchart LR + Fixed[โœ… Fixed] --> Check{๐Ÿ” First Time?} + Check -->|Yes| Close[โœ… Close] + Check -->|No| RCA[๐Ÿง  Root Cause] + RCA --> Prevent[๐ŸŽฏ Prevention] + Prevent --> Monitor[๐Ÿ“Š Track < 5%] + + style RCA fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 +``` + +--- + +## ๐Ÿ“ Slide 11 โ€“ ๐Ÿ’ป Hands-On: Automated Remediation Pipelines + +* ๐Ÿค– **Automated remediation:** Fix vulnerabilities with minimal human intervention +* ๐ŸŽฏ **Use cases:** Dependency updates, config fixes, common patterns +* โš ๏ธ **Safety first:** Only automate low-risk, well-tested fixes +* โšก **Speed benefit:** Fix in minutes, not days + +```mermaid +flowchart LR + Detect[๐Ÿ”” Detect] --> Auto[๐Ÿค– Auto-Fix] + Auto --> PR[๐Ÿ“ Create PR] + PR --> Test[๐Ÿงช CI/CD] + Test --> Merge[๐Ÿ”€ Auto-Merge] + Merge --> Deploy[๐Ÿš€ Deploy] + Deploy --> Done[โœ… Fixed in 10min] + + style Auto fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + style Done fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 +``` + +**๐Ÿ”„ Example Automated Workflow:** +1. ๐Ÿค– Dependabot detects new patch for vulnerable dependency +2. ๐Ÿ“ Automatically creates pull request with update +3. ๐Ÿงช CI/CD runs full test suite automatically +4. ๐Ÿ” Security scan runs (verify fix, no new issues) +5. โœ… All tests pass โ†’ Auto-merge (or flag for review) +6. ๐Ÿš€ Automatic deployment to staging/production + +--- + +### ๐Ÿค– Automated Dependency Updates + +**๐Ÿ”ง Dependabot Configuration:** +* โฐ **Schedule:** Daily checks for security updates +* ๐Ÿ“Š **Limits:** Max 5 open PRs (avoid overwhelming team) +* ๐Ÿ‘ฅ **Reviewers:** Auto-assign security team +* ๐Ÿท๏ธ **Labels:** Tag as "dependencies" and "security" +* ๐Ÿ”€ **Auto-merge:** Enabled for patch updates only + +**โœ… Auto-Merge Criteria:** +* ๐Ÿ’Š Patch updates only (1.2.3 โ†’ 1.2.4, not 1.2.3 โ†’ 1.3.0) +* โœ… All automated tests pass +* โœ… Security scan shows no new issues +* โŒ Minor/major updates require manual review + +```mermaid +flowchart LR + Dependabot[๐Ÿค– Dependabot] --> Vuln{๐Ÿšจ Vuln?} + Vuln -->|Yes| Type{๐Ÿ“Š Type?} + Type -->|Patch| Auto[โœ… Auto-Merge] + Type -->|Minor/Major| Manual[๐Ÿ‘€ Manual Review] + + Auto --> Deploy[๐Ÿš€ Auto-Deploy] + + style Auto fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 +``` + +--- + +### ๐Ÿ”ง Auto-Fix Tools & Features + +**๐Ÿ”ท Snyk Auto-Fix:** +* โœ… Creates PRs with dependency upgrades +* ๐Ÿ“Š Shows fix impact and test results +* ๐ŸŽฏ Includes upgrade path explanation + +**๐Ÿ™ GitHub CodeQL Auto-Fix:** +* โœ… Suggests code changes for vulnerabilities +* ๐Ÿ” Security-specific fixes (not just code quality) +* ๐Ÿ’ก Explains why change is secure + +**๐Ÿ” Semgrep Auto-Fix:** +* โœ… Pattern-based automated fixes +* โšก Can auto-apply safe transformations +* ๐ŸŽฏ Works for common vulnerability patterns + +--- + +### ๐Ÿ“Š Automated Patch Testing Pipeline + +**๐Ÿงช Ephemeral Environment Testing:** +1. ๐Ÿ”” Dependency update available (webhook trigger) +2. ๐Ÿ—๏ธ Create temporary test environment (Docker, cloud) +3. ๐Ÿš€ Deploy application with patch +4. ๐Ÿงช Run test suite (unit, integration, security) +5. โœ… Tests pass โ†’ Promote to production +6. โŒ Tests fail โ†’ Alert for manual review + rollback +7. ๐Ÿ—‘๏ธ Destroy test environment (cleanup) + +**๐Ÿ› ๏ธ Automation Tools:** +* ๐Ÿ”„ Renovate (advanced Dependabot alternative) +* ๐Ÿ”ท Snyk auto-remediation +* ๐ŸŽฏ Custom scripts + CI/CD integration + +
+๐Ÿ’ญ Safety Guidelines: What to automate vs. manual review + +**โœ… Safe to Automate:** +* ๐Ÿ’Š Patch updates (security fixes, no breaking changes) +* ๐Ÿงช Changes with comprehensive test coverage +* โš™๏ธ Well-tested config fixes +* ๐ŸŸข Dev/staging deployments +* ๐Ÿ”„ Dependency updates with auto-rollback + +**โš ๏ธ Manual Review Required:** +* ๐Ÿ”„ Minor/major version updates (breaking changes possible) +* ๐Ÿ”ด Production deployments (final human approval) +* ๐Ÿ—๏ธ Architectural changes +* ๐Ÿ’ป Complex code refactors +* ๐Ÿ” Security-critical components (auth, payment) + +**๐ŸŽฏ Golden Rule:** Automate what you can test thoroughly and rollback safely + +**๐Ÿ“Š Gradual Approach:** +1. ๐ŸŸข Month 1: Automate in dev only +2. ๐ŸŸก Month 2: Automate in staging +3. ๐ŸŸ  Month 3: Auto-merge with manual deploy +4. ๐Ÿ”ด Month 4: Fully automated with monitoring + +**๐Ÿšจ Always have:** Kill switch, monitoring, rollback plan +
+ +```mermaid +flowchart LR + Safe[โœ… Safe to Automate] --> Patch[๐Ÿ’Š Patch Updates] + Safe --> Tests[๐Ÿงช Good Test Coverage] + Safe --> Dev[๐ŸŸข Dev Environment] + + Manual[โš ๏ธ Manual Review] --> Major[๐Ÿ”„ Major Updates] + Manual --> Prod[๐Ÿ”ด Production] + Manual --> Critical[๐Ÿ” Auth/Payment] + + style Safe fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + style Manual fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 +``` + +--- + +๐Ÿ”— **Resources for Group 3:** +* [Dependabot Docs](https://docs.github.com/en/code-security/dependabot) +* [Renovate](https://www.mend.io/free-developer-tools/renovate/) +* [Snyk Auto-Remediation](https://docs.snyk.io/) + +--- + +๐Ÿ”— **Resources for Group 3:** +* [Dependabot Docs](https://docs.github.com/en/code-security/dependabot) +* [Renovate](https://www.mend.io/free-developer-tools/renovate/) +* [Snyk Auto-Remediation](https://docs.snyk.io/) + +--- + +## ๐ŸŽ‰ Fun Break: "10-Minute Fix That Saved $1M" + +* ๐Ÿšจ Critical npm vulnerability (CVSS 9.8, KEV, EPSS 95%) +* โฐ Company with automation: 09:00 detect โ†’ 09:10 fixed (10 min) +* ๐Ÿ˜“ Competitors without automation: 6 weeks (ticketโ†’sprintโ†’testโ†’release) +* ๐Ÿ’ฐ Competitors breached: $1M+ in costs +* ๐Ÿ’ก Lesson: Automation = competitive advantage! + +--- + +## ๐Ÿ“‚ Group 4: Vulnerability Lifecycle Management + +## ๐Ÿ“ Slide 12 โ€“ ๐Ÿ“Š Vulnerability Lifecycle Overview + +* ๐Ÿ”„ **Complete lifecycle:** Discovery โ†’ Triage โ†’ Remediation โ†’ Verification โ†’ Closure +* ๐Ÿ“Š **Track everything:** Every vulnerability tracked through all states +* ๐Ÿ“ˆ **Measure effectiveness:** Metrics at each stage reveal bottlenecks +* ๐ŸŽฏ **Continuous improvement:** Data-driven optimization of processes + +```mermaid +flowchart LR + Discovery[๐Ÿ” Discovery] --> Triage[๐Ÿšจ Triage] + Triage --> Remediation[๐Ÿ”ง Remediation] + Remediation --> Verification[๐Ÿงช Verification] + Verification --> Closure[๐Ÿ”’ Closure] + + Closure -.->|Regression| Discovery + + style Discovery fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + style Closure fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 +``` + +**๐Ÿ“Š Key Lifecycle Metrics:** +* **MTTD:** Mean Time To Detect vulnerabilities +* **MTTR:** Mean Time To Remediate (fix) +* **Backlog size:** Total open vulnerabilities +* **Velocity:** Vulns fixed vs. introduced per sprint +* **Recurrence rate:** % returning vulns (target: <5%) + +```mermaid +flowchart TD + Metrics[๐Ÿ“Š Lifecycle Metrics] --> Time[โฐ Time Metrics] + Metrics --> Volume[๐Ÿ“Š Volume Metrics] + Metrics --> Quality[๐ŸŽฏ Quality Metrics] + + Time --> MTTD[โฑ๏ธ MTTD
Time to Detect] + Time --> MTTR[โฑ๏ธ MTTR
Time to Fix] + + Volume --> Backlog[๐Ÿ“ˆ Backlog Size] + Volume --> Velocity[โšก Fix Velocity] + + Quality --> Recurrence[๐Ÿ”„ Recurrence < 5%] + Quality --> SLA[โœ… SLA Compliance] + + style Metrics fill:#fff3e0,stroke:#f57c00,stroke-width:3px,color:#2c3e50 +``` + +--- + +## ๐Ÿ“ Slide 13 โ€“ ๐Ÿ“ˆ Backlog Management & Health + +* ๐Ÿ“Š **Backlog health:** Most critical vulnerability management metric +* ๐ŸŽฏ **Goal:** Fix rate > Discovery rate = Shrinking backlog +* ๐Ÿšจ **Warning:** Growing backlog = Accumulating technical security debt +* ๐Ÿ“… **Age matters:** Old vulnerabilities harder to fix (code drift, dependencies) + +**๐Ÿ“Š Backlog Segmentation:** +* ๐Ÿ”ด **Critical/High:** Should be near zero (active work) +* ๐ŸŸก **Medium:** Controlled queue (30-day pipeline) +* ๐ŸŸข **Low:** Acceptable backlog (managed risk) + +```mermaid +flowchart LR + Backlog[๐Ÿ“Š Vulnerability Backlog] --> Healthy{๐ŸŽฏ Status?} + + Healthy -->|Fix > Discovery| Shrinking[๐Ÿ“‰ Shrinking
โœ… Improving] + Healthy -->|Fix = Discovery| Stable[๐Ÿ“Š Stable
โš ๏ธ Maintaining] + Healthy -->|Fix < Discovery| Growing[๐Ÿ“ˆ Growing
๐Ÿšจ Danger] + + Shrinking --> Good[โœ… Keep Going] + Stable --> Action1[โšก Increase Velocity] + Growing --> Action2[๐Ÿšจ Emergency Action] + + style Shrinking fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + style Stable fill:#fffde7,stroke:#f9a825,stroke-width:2px,color:#2c3e50 + style Growing fill:#ffebee,stroke:#c62828,stroke-width:3px,color:#2c3e50 +``` + +**โฐ Age Buckets:** +* ๐ŸŸข **0-30 days:** Fresh, normal pipeline +* ๐ŸŸก **31-90 days:** Aging, needs attention +* ๐ŸŸ  **91-180 days:** Old, prioritize now +* ๐Ÿ”ด **180+ days:** Ancient, exec attention + +```mermaid +flowchart TD + Total[๐Ÿ“Š Backlog: 500 Vulns] --> BySeverity[๐ŸŽฏ By Severity] + Total --> ByAge[โฐ By Age] + + BySeverity --> Crit[๐Ÿ”ด Critical: 5
Target: 0] + BySeverity --> High[๐ŸŸ  High: 25
Target: <10] + BySeverity --> Med[๐ŸŸก Medium: 150] + BySeverity --> Low[๐ŸŸข Low: 320] + + ByAge --> Fresh[๐ŸŸข 0-30d: 200
Normal] + ByAge --> Aging[๐ŸŸก 31-90d: 180
Watch] + ByAge --> Old[๐ŸŸ  91-180d: 80
Priority] + ByAge --> Ancient[๐Ÿ”ด 180+d: 40
๐Ÿšจ Action!] + + Crit --> Alert[๐Ÿšจ Immediate Fix] + Ancient --> Alert + + style Crit fill:#ffebee,stroke:#c62828,stroke-width:2px,color:#2c3e50 + style Ancient fill:#ffebee,stroke:#c62828,stroke-width:2px,color:#2c3e50 +``` + +--- + +## ๐Ÿ“ Slide 14 โ€“ โšก Velocity & Continuous Improvement + +* โšก **Velocity:** Vulnerabilities fixed per time period (week/sprint/month) +* ๐Ÿ“Š **Throughput:** Rate of moving vulns through pipeline +* ๐ŸŽฏ **Target:** Consistent or increasing velocity +* ๐Ÿ“ˆ **Track trends:** Are we improving or degrading? + +**๐Ÿ“Š Velocity Example:** + +| Week | ๐Ÿ” Found | ๐Ÿ”ง Fixed | ๐Ÿ“Š Net | ๐Ÿ“‰ Backlog | +|------|--------|---------|--------|----------| +| Week 1 | 60 | 45 | +15 | 515 | +| Week 2 | 55 | 50 | +5 | 520 | +| Week 3 | 50 | 65 | -15 | 505 | +| Week 4 | 48 | 70 | -22 | 483 | + +๐Ÿ’ก **Analysis:** Velocity improving, backlog shrinking โœ… + +```mermaid +flowchart LR + Week[๐Ÿ“… This Week] --> Found[๐Ÿ” Found: 50] + Week --> Fixed[๐Ÿ”ง Fixed: 75] + + Found --> Net[๐Ÿ“Š Net: -25
โœ… Good] + Fixed --> Net + + Net --> Velocity[โšก Velocity
75/week] + Velocity --> Trend{๐Ÿ“Š Trend?} + + Trend -->|Up| Good[๐Ÿ“ˆ Improving] + Trend -->|Stable| OK[๐Ÿ“Š Steady] + Trend -->|Down| Bad[๐Ÿ“‰ Investigate] + + style Net fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + style Good fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + style Bad fill:#ffebee,stroke:#c62828,stroke-width:2px,color:#2c3e50 +``` + +**๐Ÿ’ก Improvement Drivers:** +* ๐Ÿค– **Automation:** 60% auto-fixable = +30 fixes/week +* ๐Ÿ‘ฅ **Security champions:** 5 trained = +20 fixes/week +* ๐ŸŽฏ **Better prioritization:** Risk-based = +15 fixes/week +* ๐Ÿ”ง **Modernized stack:** Less tech debt = +10 fixes/week + +--- + +๐Ÿ”— **Resources for Group 4:** +* [OWASP Vulnerability Management](https://owasp.org/www-community/Vulnerability_Management_Lifecycle) +* [Measuring DevSecOps](https://www.devsecops.org/) + +--- + +## ๐ŸŽ‰ Fun Break: "The Backlog That Ate Manhattan" + +* ๐Ÿข Company: 15,000 vuln backlog, growing +50/month +* ๐Ÿ˜ฐ Security team: Constant stress, never catching up +* ๐ŸŽฏ **Turnaround:** Risk-based priority, closed 8K unreachable vulns, automated 70% +* ๐Ÿ“ˆ **6 months later:** 15K โ†’ 2K (86% reduction), velocity 150 โ†’ 400/month +* ๐Ÿ’ก **Lesson:** Can't fix everything. Prioritize, automate, accept risk strategically! + +--- + +## ๐Ÿ“‚ Group 5: Incident Response + +## ๐Ÿ“ Slide 15 โ€“ ๐Ÿ”ฅ Incident Response Framework + +* ๐Ÿ”ฅ **Incident:** Active security breach or exploitation in progress +* ๐Ÿšจ **Different from vuln:** Vuln = potential risk, Incident = actual harm +* โฐ **Time critical:** Minutes matter during active incidents +* ๐Ÿ“‹ **Structured approach:** Follow NIST/SANS IR frameworks + +**๐Ÿ”„ NIST IR Lifecycle (6 Phases):** + +**1๏ธโƒฃ Preparation:** +* ๐Ÿ“‹ IR plan documented, tested +* ๐Ÿ‘ฅ IR team with clear roles +* ๐Ÿ› ๏ธ Tools ready (forensics, backups) +* ๐ŸŽ“ Regular tabletop exercises + +**2๏ธโƒฃ Detection & Analysis:** +* ๐Ÿ” Identify incident (SIEM, alerts) +* ๐Ÿ“Š Determine scope, severity +* ๐ŸŽฏ Classify type (malware, breach, DDoS) +* โฐ Start incident timeline + +**3๏ธโƒฃ Containment:** +* ๐Ÿšง Short-term: Isolate systems +* ๐Ÿ”’ Long-term: Patch vulnerabilities +* ๐Ÿ’พ Preserve evidence + +**4๏ธโƒฃ Eradication:** +* ๐Ÿ—‘๏ธ Remove malware, backdoors +* ๐Ÿ”ง Fix root cause +* ๐Ÿ” Reset compromised credentials + +**5๏ธโƒฃ Recovery:** +* ๐Ÿ”„ Restore to normal operations +* ๐Ÿ“Š Monitor for attacker return +* โœ… Verify systems clean + +**6๏ธโƒฃ Post-Incident:** +* ๐Ÿ“ Blameless post-mortem +* ๐Ÿ“Š Document lessons learned +* ๐Ÿ”ง Update IR procedures + +```mermaid +flowchart LR + Prep[๐Ÿ“‹ 1. Prep
Plan] --> Detect[๐Ÿ” 2. Detect
Identify] + Detect --> Contain[๐Ÿšง 3. Contain
Stop Spread] + Contain --> Eradicate[โšก 4. Eradicate
Remove] + Eradicate --> Recover[๐Ÿ”„ 5. Recover
Restore] + Recover --> PostInc[๐Ÿ“š 6. Learn
Improve] + + PostInc -.->|Continuous| Prep + + style Detect fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + style Contain fill:#ffebee,stroke:#c62828,stroke-width:2px,color:#2c3e50 + style PostInc fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 +``` + +```mermaid +flowchart TD + Incident[๐Ÿ”ฅ Incident] --> Severity{๐Ÿšจ Severity?} + + Severity -->|Critical| P0[๐Ÿ”ด P0: All Hands
CEO Notified] + Severity -->|High| P1[๐ŸŸ  P1: IR Team
Manager] + Severity -->|Medium| P2[๐ŸŸก P2: Security
Standard] + + P0 --> Timeline[โฐ Critical Timeline] + Timeline --> T1[โฑ๏ธ 0-15min: Respond] + Timeline --> T2[โฑ๏ธ 15-60min: Contain] + Timeline --> T3[โฑ๏ธ 1-4h: Eradicate] + Timeline --> T4[โฑ๏ธ 4-24h: Recover] + + style P0 fill:#ffebee,stroke:#c62828,stroke-width:3px,color:#2c3e50 +``` + +--- + +## ๐Ÿ“ Slide 16 โ€“ ๐Ÿ‘ฅ IR Team Roles & Escalation + +* ๐Ÿ‘ฅ **IR Team:** Cross-functional with clear responsibilities +* ๐ŸŽฏ **Defined roles:** Decided before incident (not during chaos) +* ๐Ÿ“ž **Clear escalation:** Contact lists, decision authority +* ๐Ÿ”„ **24/7 coverage:** On-call rotation + +**๐ŸŽฏ Core IR Roles:** + +**1๏ธโƒฃ Incident Commander:** +* ๐ŸŽฏ Overall leader, decision maker +* ๐Ÿ“Š Coordinates all activities +* โฐ Declares severity, escalations +* ๐Ÿšจ Authority to take systems offline + +**2๏ธโƒฃ Technical Lead:** +* ๐Ÿ’ป Leads investigation +* ๐Ÿ” Analyzes logs, forensics +* ๐Ÿ”ง Implements containment + +**3๏ธโƒฃ Communications:** +* ๐Ÿ“ข Internal/external comms +* ๐Ÿ“ฐ Media, customers, regulators +* ๐ŸŽฏ Consistent messaging + +**4๏ธโƒฃ Scribe:** +* ๐Ÿ“ Documents all actions +* โฐ Maintains timeline +* ๐Ÿ“Š Tracks decisions + +**5๏ธโƒฃ Legal/Compliance:** +* โš–๏ธ Regulatory requirements +* ๐Ÿ“‹ Evidence preservation + +```mermaid +flowchart TD + Alert[๐Ÿšจ Alert] --> IC[๐ŸŽฏ Incident Commander] + + IC --> Tech[๐Ÿ’ป Tech Lead] + IC --> Comms[๐Ÿ“ข Communications] + IC --> Scribe[๐Ÿ“ Scribe] + IC --> Legal[โš–๏ธ Legal] + + Tech --> A1[๐Ÿ” Investigate] + Tech --> A2[๐Ÿšง Contain] + + Comms --> A3[๐Ÿ“ง Internal] + Comms --> A4[๐Ÿ“ฐ External] + + Scribe --> A5[โฐ Timeline] + Scribe --> A6[๐Ÿ“Š Decisions] + + Legal --> A7[๐Ÿ“‹ Breach Notice] + + style IC fill:#fff3e0,stroke:#f57c00,stroke-width:3px,color:#2c3e50 +``` + +**๐Ÿ“ž Escalation Matrix:** + +| Severity | IC | Notify | Response | +|----------|-----|---------|----------| +| ๐Ÿ”ด P0 | CISO | CEO, Board | 15 min | +| ๐ŸŸ  P1 | Sec Mgr | CTO | 1 hour | +| ๐ŸŸก P2 | Sec Lead | Eng Mgr | 4 hours | + +--- + +## ๐Ÿ“ Slide 17 โ€“ ๐Ÿ“š Blameless Post-Mortems + +* ๐Ÿ“ **Post-mortem:** Analyze what happened (no blame!) +* ๐ŸŽฏ **Goal:** Learn and improve, not punish +* ๐Ÿ“Š **Documentation:** Thorough report for future +* ๐Ÿ”„ **Action items:** Concrete prevention steps + +**๐Ÿ“‹ Post-Mortem Components:** + +**1๏ธโƒฃ Timeline:** +* โฐ Detailed chronology +* When detected, contained, resolved? + +**2๏ธโƒฃ Root Cause:** +* ๐Ÿ” What vulnerability exploited? +* ๐Ÿค” Why did it exist? +* ๐Ÿšซ Why didn't we detect sooner? + +**3๏ธโƒฃ Impact:** +* ๐Ÿ’ฐ Financial (downtime, recovery) +* ๐Ÿ” Data (accessed/exfiltrated?) +* ๐Ÿ‘ฅ Customers (how many affected?) +* ๐Ÿ“ฐ Reputational (media?) + +**4๏ธโƒฃ What Went Well:** +* โœ… Fast detection +* โœ… Quick response +* โœ… Clear communication +* โœ… Backups available + +**5๏ธโƒฃ What Went Wrong:** +* โŒ Known vuln unpatched +* โŒ Incomplete containment +* โŒ Delayed escalation +* โŒ Tools not ready + +**6๏ธโƒฃ Action Items:** +* ๐Ÿ”ง Patch similar vulns (by Friday) +* ๐Ÿ“Š Improve monitoring +* ๐ŸŽ“ Train team +* ๐Ÿ“‹ Update IR playbook + +```mermaid +flowchart TD + Resolved[๐Ÿ”ฅ Incident Resolved] --> PM[๐Ÿ“š Post-Mortem
48h after] + + PM --> Timeline[โฐ Timeline] + PM --> RCA[๐Ÿ” Root Cause] + PM --> Impact[๐Ÿ’ฐ Impact] + PM --> Good[โœ… Went Well] + PM --> Bad[โŒ Went Wrong] + + Timeline --> Actions[๐ŸŽฏ Action Items] + RCA --> Actions + Impact --> Actions + Good --> Actions + Bad --> Actions + + Actions --> Fix[๐Ÿ”ง Technical] + Actions --> Process[๐Ÿ“Š Process] + Actions --> Training[๐ŸŽ“ Training] + Actions --> Tools[๐Ÿ› ๏ธ Tooling] + + Fix --> Track[๐Ÿ“‹ Track] + Process --> Track + Training --> Track + Tools --> Track + + Track --> Better[โœ… Improved] + + style PM fill:#fff3e0,stroke:#f57c00,stroke-width:3px,color:#2c3e50 + style Better fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 +``` + +**๐Ÿ’ก Blameless Culture:** +* ๐Ÿšซ No finger-pointing +* โœ… Focus on systems, not individuals +* ๐ŸŽฏ Psychological safety +* ๐Ÿ“Š Honest = real improvements + +```mermaid +flowchart LR + Culture[๐ŸŽฏ Culture] --> Type{Type?} + + Type -->|Blameful| Bad[โŒ Fear
Hide Problems
No Learning] + Type -->|Blameless| Good[โœ… Safety
Report Issues
Improve] + + Good --> Better[๐Ÿ“ˆ Better IR] + + style Bad fill:#ffebee,stroke:#c62828,stroke-width:2px,color:#2c3e50 + style Good fill:#e8f5e8,stroke:#388e3c,stroke-width:3px,color:#2c3e50 +``` + +--- + +๐Ÿ”— **Resources for Group 5:** +* [NIST IR Guide (SP 800-61)](https://csrc.nist.gov/publications/detail/sp/800-61/rev-2/final) +* [SANS IR Handbook](https://www.sans.org/white-papers/33901/) +* [Google Postmortem Culture](https://sre.google/sre-book/postmortem-culture/) + +--- + +## ๐ŸŽ‰ Fun Break: "The $200K S3 Bucket Typo" + +**๐Ÿชฃ The Story:** +* ๐Ÿ‘จโ€๐Ÿ’ป Developer needs to delete test S3 bucket +* โŒจ๏ธ Types: aws s3 rm s3://prod-bucket --recursive (typo!) +* โฐ Friday 5pm execution +* ๐Ÿ’ฅ **Result:** 10TB production data deleted instantly + +**๐Ÿ“Š Impact:** +* ๐ŸŒ Website down 8 hours +* ๐Ÿ’ฐ Lost revenue: $150K +* ๐Ÿ”ง Recovery cost: $50K +* ๐Ÿ˜“ Team weekend: Ruined + +**โœ… Prevention:** +* ๐Ÿ” MFA delete enabled +* ๐Ÿข Separate AWS accounts (dev vs prod) +* ๐Ÿ“Š Versioning enabled (could restore) +* ๐Ÿšจ Better alerting (mass deletion alerts) + +**๐Ÿ’ก Lesson:** Test your incident response BEFORE you need it! + +```mermaid +flowchart TD + Incident[๐Ÿ”ฅ Incident] --> Team[๐Ÿ‘ฅ IR Team] + Team --> IC[๐ŸŽฏ Incident Commander] + Team --> Tech[๐Ÿ’ป Tech Lead] + Team --> Comms[๐Ÿ“ข Communications] + Team --> Scribe[๐Ÿ“ Scribe] + + IC --> Response[โšก Coordinate Response] + + style Incident fill:#ffebee,stroke:#c62828,stroke-width:2px,color:#2c3e50 + style Response fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 +``` + +--- + +## ๐Ÿ“Š Summary: Vulnerability Management Essentials + +**๐Ÿ” Discovery:** Use multiple methods (SAST, DAST, SCA, pentests) for defense in depth +**๐Ÿ“Š Assessment:** CVSS + EPSS + KEV + Context = Smart prioritization +**๐Ÿ”ง Remediation:** Fix fast per SLA, automate where safe, verify always +**๐Ÿ“ˆ Lifecycle:** Track metrics (backlog, velocity, age), improve continuously +**๐Ÿ”ฅ Incidents:** Prepare before they happen, respond fast, learn from every event + +```mermaid +flowchart TD + VulnMgmt[๐ŸŽฏ Vuln Management] --> Discovery[๐Ÿ” Discovery] + VulnMgmt --> Assessment[๐Ÿ“Š Assessment] + VulnMgmt --> Remediation[๐Ÿ”ง Remediation] + VulnMgmt --> Lifecycle[๐Ÿ“ˆ Lifecycle] + VulnMgmt --> IR[๐Ÿ”ฅ IR] + + Discovery --> C1[๐Ÿ“Š 95%+ Coverage] + Assessment --> C2[๐Ÿง  Smart Decisions] + Remediation --> C3[โšก High Velocity] + Lifecycle --> C4[๐Ÿ“Š Data-Driven] + IR --> C5[๐ŸŽฏ Always Ready] + + C1 --> Success[โœ… Secure Org] + C2 --> Success + C3 --> Success + C4 --> Success + C5 --> Success + + style VulnMgmt fill:#fff3e0,stroke:#f57c00,stroke-width:3px,color:#2c3e50 + style Success fill:#e8f5e8,stroke:#388e3c,stroke-width:3px,color:#2c3e50 +``` + +**๐ŸŽฏ Key Takeaways:** +* ๐Ÿ› ๏ธ Orchestrate tools to reduce alert fatigue +* ๐Ÿง  Prioritize by actual threat (not just CVSS) +* ๐Ÿค– Automate everything you can safely +* ๐Ÿ“Š Track metrics for continuous improvement +* ๐Ÿ‘ฅ Prepare IR before incidents happen +* ๐Ÿ“š Learn from every incident (blameless) + +--- + +๐Ÿ”— **Essential Resources:** +* [OWASP Vulnerability Management](https://owasp.org/www-community/Vulnerability_Management_Lifecycle) +* [CVSS Calculator](https://www.first.org/cvss/calculator/) +* [CISA KEV](https://www.cisa.gov/known-exploited-vulnerabilities-catalog) +* [NIST IR Guide (SP 800-61)](https://csrc.nist.gov/publications/detail/sp/800-61/rev-2/final) +* [Dependency-Track](https://dependencytrack.org/) + +--- + +## ๐ŸŽ“ Final Thoughts + +**๐Ÿ’ก Vulnerability Management is a Journey:** +* ๐Ÿš€ Start small: One tool, one metric, one improvement +* ๐Ÿ“ˆ Iterate: Continuous improvement > perfection +* ๐Ÿค– Automate: Let machines do repetitive work +* ๐Ÿ‘ฅ Collaborate: Security is everyone's job +* ๐Ÿ“Š Measure: What gets measured gets improved + +**๐ŸŽฏ Remember:** +* โœ… Can't fix everything โ†’ Prioritize by risk +* โœ… Older โ‰  worse โ†’ Focus on exploitability +* โœ… Automation saves time โ†’ Invest in tooling +* โœ… Metrics drive decisions โ†’ Track what matters +* โœ… Incidents will happen โ†’ Be prepared + +**๐ŸŒŸ Goal: Not zero vulnerabilities (impossible), but effective risk management!** + +--- diff --git a/lectures/lec4.md b/lectures/lec4.md new file mode 100644 index 00000000..1fe04116 --- /dev/null +++ b/lectures/lec4.md @@ -0,0 +1,2316 @@ +# ๐Ÿ“ŒLecture 4 - CI/CD Security & Build Hardening + +## ๐Ÿ“‚ Group 1: CI/CD Pipeline Foundations & Architecture + +## ๐Ÿ“ Slide 1 โ€“ ๐Ÿ—๏ธ What is CI/CD? (Continuous Integration/Continuous Deployment) + +* ๐Ÿ—๏ธ **CI = Continuous Integration** โ†’ developers merge code changes frequently (multiple times daily) into a shared repository, triggering **automated builds and tests**. +* ๐Ÿš€ **CD = Continuous Deployment/Delivery** โ†’ automated deployment of validated code changes to **staging/production environments**. +* ๐Ÿ”„ **Core principle**: "**integrate early, deploy often**" โ†’ catch issues fast, reduce integration hell, enable rapid releases. +* ๐ŸŽฏ **Benefits**: faster feedback loops, reduced manual errors, consistent deployments, improved team collaboration. +* ๐Ÿ“Š **Industry adoption**: **85% of organizations** use CI/CD practices as of 2024 (GitLab DevOps Report). +* ๐Ÿ”— **Learn more**: [What is CI/CD? - GitLab](https://about.gitlab.com/topics/ci-cd/) + +```mermaid +flowchart LR + Dev[๐Ÿ‘จโ€๐Ÿ’ป Developer Commit] --> CI[๐Ÿ—๏ธ CI: Build + Test] + CI --> CD[๐Ÿš€ CD: Deploy] + CD --> Prod[๐ŸŒ Production] + CI -->|โŒ Fail| Feedback[๐Ÿ“ง Fast Feedback] + Feedback --> Dev +``` + +--- + +## ๐Ÿ“ Slide 2 โ€“ ๐Ÿ”„ Evolution of CI/CD: From Manual Builds to Modern Pipelines + +* ๐Ÿ“… **1990s-2000s**: Manual builds, nightly builds, "integration hell" โ†’ developers fear merging code. +* ๐Ÿ“… **2006**: **CruiseControl** introduces automated CI โ†’ "build on every commit" concept emerges. +* ๐Ÿ“… **2011**: **Jenkins** (Hudson fork) revolutionizes CI with plugins and distributed builds. +* ๐Ÿ“… **2018**: **Cloud-native CI/CD** emerges โ†’ GitHub Actions, GitLab CI, CircleCI offer **serverless pipelines**. +* ๐Ÿ“… **2020-2024**: **GitOps**, **Infrastructure-as-Code (IaC)**, and **security-first pipelines** become standard. +* ๐Ÿš€ **Today**: **AI-assisted pipelines**, **policy-as-code**, and **supply chain security** are the new frontier. +* ๐Ÿ”— **History deep-dive**: [Evolution of CI/CD - ThoughtWorks](https://www.thoughtworks.com/insights/articles/continuous-integration) + +```mermaid +timeline + title ๐Ÿ”„ CI/CD Evolution + 1990s : ๐Ÿ“‹ Manual Builds & Integration Hell + 2006 : โš™๏ธ CruiseControl - Automated CI + 2011 : ๐Ÿ”ง Jenkins - Plugin Ecosystem + 2018 : โ˜๏ธ Cloud-Native Pipelines + 2024 : ๐Ÿค– AI + Security-First Pipelines +``` + +--- + +## ๐Ÿ“ Slide 3 โ€“ ๐Ÿ›๏ธ CI/CD Architecture Components & Trust Boundaries + +* ๐Ÿ—๏ธ **Core components** of modern CI/CD architecture: + * ๐Ÿ“‚ **Source Control** (Git repositories) โ†’ code storage and version control + * โš™๏ธ **Build Agents/Runners** โ†’ compute resources executing pipeline jobs + * ๐Ÿ—„๏ธ **Artifact Repositories** โ†’ storing build outputs (Docker images, packages) + * ๐Ÿš€ **Deployment Targets** โ†’ staging/production environments +* ๐Ÿ›ก๏ธ **Trust boundaries** โ†’ security perimeters where **privilege levels change**: + * ๐ŸŒ **Internet โ†” SCM**: public access vs. authenticated repository access + * ๐Ÿ”ง **SCM โ†” Build System**: code checkout vs. build execution + * ๐Ÿ“ฆ **Build โ†” Artifact Store**: temporary builds vs. permanent storage + * ๐ŸŽฏ **Artifact Store โ†” Production**: staging approval vs. live deployment +* โš ๏ธ **Attack surface**: each boundary represents potential **compromise points**. +* ๐Ÿ”— **Architecture guide**: [CI/CD Security Architecture - NIST](https://csrc.nist.gov/pubs/sp/800/204/final) + +```mermaid +flowchart LR + subgraph "๐ŸŒ Internet Zone" + Dev[๐Ÿ‘จโ€๐Ÿ’ป Developers] + end + + subgraph "๐Ÿ” SCM Zone" + Git[๐Ÿ“‚ Git Repository] + end + + subgraph "โš™๏ธ Build Zone" + Agent[๐Ÿ”ง Build Agent] + Tests[๐Ÿงช Test Suite] + end + + subgraph "๐Ÿ“ฆ Artifact Zone" + Registry[๐Ÿ—„๏ธ Artifact Registry] + end + + subgraph "๐ŸŽฏ Deployment Zone" + Staging[๐Ÿงช Staging] + Prod[๐ŸŒ Production] + end + + Dev -->|HTTPS + Auth| Git + Git -->|Webhook| Agent + Agent --> Tests + Tests -->|Success| Registry + Registry --> Staging + Staging -->|Approval| Prod + + %% Trust boundaries + classDef boundary stroke:#ff4444,stroke-width:3px,stroke-dasharray: 5 5 +``` + +--- + +## ๐Ÿ“ Slide 4 โ€“ โš™๏ธ Popular CI/CD Platforms Overview (Jenkins, GitHub Actions, GitLab CI, Azure DevOps) + +* ๐Ÿ”ง **Jenkins** (2011, open-source): + * โœ… **Strengths**: massive plugin ecosystem (1800+ plugins), self-hosted flexibility + * โŒ **Challenges**: complex setup, security maintenance burden, legacy UI + * ๐Ÿข **Best for**: enterprises with dedicated DevOps teams, hybrid cloud +* โšก **GitHub Actions** (2019, cloud-native): + * โœ… **Strengths**: native Git integration, marketplace ecosystem, serverless + * โŒ **Challenges**: vendor lock-in, pricing for private repos, limited self-hosting + * ๐Ÿ‘ฅ **Best for**: open-source projects, GitHub-centric workflows +* ๐ŸฆŠ **GitLab CI** (2012, integrated platform): + * โœ… **Strengths**: built-in SCM+CI+CD+security, self-hosted options + * โŒ **Challenges**: resource-heavy, learning curve for complex workflows + * ๐Ÿข **Best for**: teams wanting all-in-one DevSecOps platform +* ๐Ÿ”ท **Azure DevOps** (2018, Microsoft ecosystem): + * โœ… **Strengths**: tight Microsoft integration, enterprise features, hybrid support + * โŒ **Challenges**: complexity, licensing costs, less popular in open-source + * ๐Ÿข **Best for**: Microsoft-stack enterprises, .NET applications + +```mermaid +quadrantChart + title CI/CD Platform Comparison + x-axis Low Complexity --> High Complexity + y-axis Cloud-Native --> Self-Hosted + quadrant-1 Enterprise Self-Hosted + quadrant-2 Cloud Enterprise + quadrant-3 Simple Cloud + quadrant-4 Complex Self-Hosted + + GitHub Actions: [0.3, 0.8] + GitLab CI: [0.6, 0.5] + Jenkins: [0.8, 0.2] + Azure DevOps: [0.7, 0.6] + CircleCI: [0.4, 0.9] + TeamCity: [0.7, 0.1] +``` + +* ๐Ÿ“Š **Market share (2024)**: Jenkins 47%, GitHub Actions 31%, GitLab CI 12%, Azure DevOps 7% ([JetBrains DevEcosystem Survey](https://www.jetbrains.com/lp/devecosystem-2024/)) + +--- + +## ๐Ÿ“ Slide 5 โ€“ ๐Ÿšจ Why CI/CD Pipelines Became High-Value Attack Targets + +* ๐ŸŽฏ **Central position**: CI/CD pipelines have **privileged access** to: + * ๐Ÿ“‚ **Source code repositories** โ†’ intellectual property, secrets + * ๐Ÿ”‘ **Production credentials** โ†’ cloud accounts, databases, APIs + * ๐Ÿ—๏ธ **Build infrastructure** โ†’ compute resources, internal networks + * ๐Ÿ“ฆ **Artifact repositories** โ†’ deployment packages, container images +* โšก **Attack amplification**: compromising CI/CD enables: + * ๐Ÿฆ  **Supply chain poisoning** โ†’ inject malicious code into software releases + * ๐Ÿ”“ **Lateral movement** โ†’ pivot to production systems using pipeline credentials + * ๐Ÿ“ฅ **Data exfiltration** โ†’ access sensitive data across multiple environments +* ๐Ÿ’ฅ **Real-world impact examples**: + * **SolarWinds (2020)**: attackers compromised build system โ†’ 18,000 customers affected + * **Codecov (2021)**: CI system breach โ†’ customer secrets exposed for months + * **NPM ecosystem (2021-2024)**: multiple supply chain attacks via compromised CI/CD +* ๐Ÿ“ˆ **Growing threat**: **45% increase** in CI/CD-targeted attacks since 2022 ([Checkmarx Supply Chain Report](https://checkmarx.com/resource/documents/en/report/2024-software-supply-chain-security-report/)) + +```mermaid +flowchart TD + Attacker[๐Ÿ˜ˆ Attacker] -->|Compromise| Pipeline[โš™๏ธ CI/CD Pipeline] + Pipeline -->|Access| Source[๐Ÿ“‚ Source Code] + Pipeline -->|Use| Creds[๐Ÿ”‘ Production Credentials] + Pipeline -->|Control| Infra[๐Ÿ—๏ธ Build Infrastructure] + Pipeline -->|Poison| Artifacts[๐Ÿ“ฆ Build Artifacts] + + Source --> Theft[๐Ÿ•ต๏ธ IP Theft] + Creds --> Lateral[โ†—๏ธ Lateral Movement] + Infra --> Mining[โ›๏ธ Crypto Mining] + Artifacts --> Supply[๐Ÿฆ  Supply Chain Attack] + + Supply --> Customers[๐Ÿ‘ฅ End Users Compromised] + + classDef attack fill:#ffebee,stroke:#d32f2f,stroke-width:2px + class Attacker,Theft,Lateral,Mining,Supply,Customers attack +``` + +--- + +## ๐Ÿ“ Slide 6 โ€“ ๐Ÿ“Š The OWASP Top 10 CI/CD Security Risks (2024) + +* ๐Ÿ“‹ **OWASP CI/CD Security Top 10** โ†’ framework identifying **most critical risks** in CI/CD environments ([OWASP CI/CD Security](https://owasp.org/www-project-top-10-ci-cd-security-risks/)): + +1. **๐Ÿšซ CICD-SEC-1: Insufficient Flow Control** โ†’ inadequate pipeline stage controls +2. **๐Ÿ” CICD-SEC-2: Inadequate Identity and Access Management** โ†’ excessive permissions +3. **โš ๏ธ CICD-SEC-3: Dependency Chain Abuse** โ†’ compromised third-party components +4. **โ˜ ๏ธ CICD-SEC-4: Poisoned Pipeline Execution (PPE)** โ†’ malicious pipeline modifications +5. **๐Ÿ”“ CICD-SEC-5: Insufficient PBAC (Pipeline-Based Access Control)** โ†’ weak pipeline permissions +6. **๐Ÿ”‘ CICD-SEC-6: Insufficient Credential Hygiene** โ†’ exposed secrets and credentials +7. **๐Ÿ—๏ธ CICD-SEC-7: Insecure System Configuration** โ†’ misconfigured CI/CD infrastructure +8. **๐Ÿ” CICD-SEC-8: Ungoverned Usage of 3rd Party Services** โ†’ unvetted external services +9. **๐Ÿ” CICD-SEC-9: Improper Artifact Integrity Validation** โ†’ unsigned/unverified artifacts +10. **๐Ÿ“Š CICD-SEC-10: Insufficient Logging and Visibility** โ†’ poor monitoring and auditing + +* ๐ŸŽฏ **Why this matters**: provides **structured approach** to securing CI/CD pipelines +* ๐Ÿ“ˆ **Industry adoption**: used by **60% of enterprises** for CI/CD security assessments + +```mermaid +pie title ๐Ÿ“Š OWASP CI/CD Top 10 Risk Categories + "Identity & Access" : 25 + "Pipeline Security" : 20 + "Dependency Management" : 15 + "Configuration" : 15 + "Monitoring" : 10 + "Artifact Integrity" : 15 +``` + +--- + +## ๐Ÿ“ Slide 7 โ€“ ๐Ÿ”— Supply Chain Attacks via CI/CD: Famous Case Studies + +* ๐ŸŒŸ **SolarWinds Orion (2020)**: + * ๐ŸŽฏ **Attack vector**: compromised build system โ†’ malicious code injected during build process + * ๐Ÿ“Š **Impact**: 18,000+ organizations affected, including US government agencies + * โฑ๏ธ **Duration**: undetected for **9 months**, demonstrating stealth capabilities + * ๐Ÿ’ก **Lesson**: build environment security is **critical infrastructure** + +* ๐Ÿงช **Codecov Bash Uploader (2021)**: + * ๐ŸŽฏ **Attack vector**: compromised CI script in Codecov's infrastructure + * ๐Ÿ“Š **Impact**: customer environment variables and secrets exposed for **2+ months** + * ๐Ÿ”‘ **Scope**: affected hundreds of companies using Codecov in their CI/CD + * ๐Ÿ’ก **Lesson**: third-party CI/CD tools require **continuous monitoring** + +* ๐Ÿ“ฆ **NPM Package Attacks (2021-2024)**: + * ๐ŸŽฏ **Attack vectors**: compromised developer accounts, dependency confusion, typosquatting + * ๐Ÿ“Š **Examples**: `event-stream`, `ua-parser-js`, `node-ipc` package compromises + * ๐Ÿ” **Impact**: millions of downloads of malicious packages via automated CI/CD + * ๐Ÿ’ก **Lesson**: dependency management requires **automated security scanning** + +* ๐Ÿ **PyTorch Supply Chain (2022)**: + * ๐ŸŽฏ **Attack vector**: compromised dependency in PyTorch nightly builds + * ๐Ÿ“Š **Impact**: malicious code in ML framework affecting AI/ML pipelines + * โšก **Response**: rapid detection and response **within hours** + * ๐Ÿ’ก **Lesson**: even "trusted" ecosystems need **continuous validation** + +```mermaid +timeline + title ๐Ÿ”— Major CI/CD Supply Chain Attacks + 2020 : ๐ŸŒŸ SolarWinds (Build System) + : 18K+ orgs affected + 2021 : ๐Ÿงช Codecov (CI Tool) + : Secrets exposed 2+ months + 2021-24 : ๐Ÿ“ฆ NPM Ecosystem + : Multiple package compromises + 2022 : ๐Ÿ PyTorch ML Framework + : Nightly builds compromised +``` + +* ๐Ÿ’ฐ **Economic impact**: supply chain attacks cost organizations **average $4.35M per incident** ([IBM Cost of Data Breach 2024](https://www.ibm.com/reports/data-breach)) +* ๐Ÿ“ˆ **Trend**: **300% increase** in supply chain attacks targeting CI/CD since 2021 ([Sonatype State of Software Supply Chain](https://www.sonatype.com/state-of-the-software-supply-chain/)) + +--- + +## ๐Ÿ“‚ Group 2: Pipeline Access Control & Identity Management + +## ๐Ÿ“ Slide 8 โ€“ ๐Ÿ” Authentication & Authorization in CI/CD Pipelines + +* ๐Ÿ” **Authentication** = verifying **who** is accessing the CI/CD system (users, services, systems) +* ๐Ÿ›ก๏ธ **Authorization** = determining **what** authenticated entities can do (permissions, roles) +* ๐Ÿงฉ **Common authentication methods**: + * ๐Ÿ‘ค **Human users**: SSO (SAML/OIDC), API tokens, SSH keys + * ๐Ÿค– **Service accounts**: machine identities, workload identity, service principals + * ๐Ÿ”ง **Build agents**: agent tokens, certificate-based authentication +* ๐Ÿ“Š **Identity sources**: Active Directory, LDAP, cloud identity providers (AWS IAM, Azure AD, Google Cloud Identity) +* โš ๏ธ **Common failures**: shared accounts, long-lived tokens, excessive permissions +* ๐Ÿ”— **Best practices**: [NIST SP 800-63 Digital Identity Guidelines](https://pages.nist.gov/800-63-3/) + +```mermaid +flowchart LR + User[๐Ÿ‘ค User/Service] -->|Credentials| AuthN[๐Ÿ” Authentication] + AuthN -->|Valid?| AuthZ[๐Ÿ›ก๏ธ Authorization] + AuthZ -->|Permitted?| Resource[๐Ÿ“‚ CI/CD Resource] + AuthN -->|โŒ Invalid| Deny[๐Ÿšซ Access Denied] + AuthZ -->|โŒ No Permission| Deny + + subgraph "Identity Providers" + SSO[๐ŸŒ SSO/OIDC] + AD[๐Ÿข Active Directory] + Cloud[โ˜๏ธ Cloud Identity] + end + + User -.-> SSO + User -.-> AD + User -.-> Cloud +``` + +--- + +## ๐Ÿ“ Slide 9 โ€“ ๐ŸŽญ Role-Based Access Control (RBAC) for Pipeline Resources + +* ๐ŸŽญ **RBAC = Role-Based Access Control** โ†’ users assigned to **roles**, roles granted **permissions** +* ๐Ÿ—๏ธ **CI/CD-specific roles** (example hierarchy): + * ๐Ÿ‘‘ **Pipeline Admin**: full pipeline management, user administration + * ๐Ÿ”ง **Pipeline Developer**: create/modify pipelines, trigger builds + * ๐Ÿ‘€ **Pipeline Viewer**: read-only access to pipeline status and logs + * ๐Ÿš€ **Deployer**: deployment permissions to specific environments + * ๐Ÿ“Š **Auditor**: read-only access for compliance and security reviews +* ๐ŸŽฏ **Granular permissions**: + * ๐Ÿ“‚ **Repository access**: read/write to specific repos + * ๐Ÿ”ง **Pipeline operations**: create, modify, delete, execute + * ๐ŸŒ **Environment access**: dev, staging, production deployment + * ๐Ÿ”‘ **Secret access**: view/use specific credentials and tokens +* ๐Ÿ“ˆ **Benefits**: scalable permission management, audit trails, compliance alignment +* ๐Ÿข **Enterprise example**: developers can deploy to staging but need approval for production + +```mermaid +graph TD + subgraph "๐Ÿ‘ฅ Users" + Dev1[๐Ÿ‘จโ€๐Ÿ’ป Alice - Developer] + Dev2[๐Ÿ‘จโ€๐Ÿ’ป Bob - Senior Dev] + Ops1[๐Ÿ‘ฉโ€๐Ÿ”ง Carol - DevOps] + Audit1[๐Ÿ‘ฉโ€๐Ÿ’ผ Diana - Auditor] + end + + subgraph "๐ŸŽญ Roles" + ViewerRole[๐Ÿ‘€ Pipeline Viewer] + DevRole[๐Ÿ”ง Pipeline Developer] + AdminRole[๐Ÿ‘‘ Pipeline Admin] + AuditorRole[๐Ÿ“Š Auditor] + end + + subgraph "๐Ÿ” Permissions" + ReadPerm[๐Ÿ“– Read Pipelines] + WritePerm[โœ๏ธ Write Pipelines] + DeployPerm[๐Ÿš€ Deploy] + AdminPerm[โš™๏ธ Admin Access] + end + + Dev1 --> ViewerRole + Dev2 --> DevRole + Ops1 --> AdminRole + Audit1 --> AuditorRole + + ViewerRole --> ReadPerm + DevRole --> ReadPerm + DevRole --> WritePerm + AdminRole --> AdminPerm + AuditorRole --> ReadPerm +``` + +--- + +## ๐Ÿ“ Slide 10 โ€“ ๐Ÿ”‘ Service Account Security & Credential Management + +* ๐Ÿค– **Service accounts** = non-human identities for **automated processes** (build agents, deployment scripts, integrations) +* ๐Ÿ” **Types of service credentials**: + * ๐ŸŽซ **API tokens**: GitHub Personal Access Tokens, GitLab tokens + * ๐ŸŽŸ๏ธ **Service principals**: Azure service principals, AWS IAM roles + * ๐Ÿ”‘ **SSH keys**: for Git operations and server access + * ๐ŸŽช **Workload identity**: cloud-native identity (AWS IRSA, Azure pod identity) +* โš ๏ธ **Common security risks**: + * ๐Ÿ“ **Hardcoded secrets**: tokens stored in plain text in pipelines + * โฐ **Long-lived credentials**: tokens that never expire + * ๐ŸŽฏ **Over-privileged access**: service accounts with excessive permissions + * ๐Ÿ”„ **Credential sharing**: same token used across multiple pipelines +* โœ… **Security best practices**: + * ๐Ÿ” Use **credential managers** (HashiCorp Vault, cloud key vaults) + * โฑ๏ธ Implement **short-lived tokens** with automatic rotation + * ๐ŸŽฏ Follow **least privilege principle** for service accounts + * ๐Ÿ” Regular **access reviews** and credential audits + +```mermaid +flowchart TD + subgraph "โŒ Insecure Approach" + Pipeline1[๐Ÿ”ง Build Pipeline] -->|Hardcoded Token| Git[๐Ÿ“‚ Git Repo] + Pipeline1 -->|Shared Creds| Cloud[โ˜๏ธ Cloud Services] + end + + subgraph "โœ… Secure Approach" + Pipeline2[๐Ÿ”ง Build Pipeline] -->|Request| Vault[๐Ÿ” Credential Vault] + Vault -->|Short-lived Token| Pipeline2 + Pipeline2 -->|Authenticated| Git2[๐Ÿ“‚ Git Repo] + Pipeline2 -->|Workload Identity| Cloud2[โ˜๏ธ Cloud Services] + end + + classDef insecure fill:#ffebee,stroke:#d32f2f + classDef secure fill:#e8f5e8,stroke:#2e7d32 + + class Pipeline1,Git,Cloud insecure + class Pipeline2,Vault,Git2,Cloud2 secure +``` + +--- + +## ๐Ÿ“ Slide 11 โ€“ ๐Ÿ›ก๏ธ Multi-Factor Authentication (MFA) for Pipeline Access + +* ๐Ÿ›ก๏ธ **MFA = Multi-Factor Authentication** โ†’ requires **multiple verification factors** beyond password +* ๐Ÿงฉ **Authentication factors**: + * ๐Ÿง  **Something you know**: password, PIN, security questions + * ๐Ÿ“ฑ **Something you have**: smartphone app, hardware token, SMS + * ๐Ÿ‘๏ธ **Something you are**: fingerprint, face recognition, voice +* ๐ŸŽฏ **CI/CD MFA implementation**: + * ๐Ÿ‘ค **Human access**: mandatory MFA for all pipeline administrative access + * ๐Ÿ“ฑ **TOTP (Time-based OTP)**: Google Authenticator, Microsoft Authenticator + * ๐Ÿ”‘ **Hardware tokens**: YubiKey, FIDO2 security keys + * ๐Ÿ“ž **Push notifications**: mobile app approval workflows +* ๐Ÿ“Š **MFA effectiveness**: blocks **99.9% of automated attacks** ([Microsoft Security Intelligence Report](https://www.microsoft.com/en-us/security/business/security-intelligence-report)) +* ๐Ÿข **Enterprise requirements**: many organizations mandate MFA for all CI/CD access +* โš ๏ธ **Bypass risks**: SMS-based MFA vulnerable to SIM swapping, prefer app-based or hardware tokens + +```mermaid +sequenceDiagram + participant User as ๐Ÿ‘ค User + participant CICD as ๐Ÿ”ง CI/CD System + participant MFA as ๐Ÿ“ฑ MFA Provider + + User->>CICD: 1. Username + Password + CICD->>User: 2. MFA Challenge Required + User->>MFA: 3. Generate OTP/Approve Push + MFA->>User: 4. OTP Code/Approval + User->>CICD: 5. Submit MFA Code + CICD->>User: 6. โœ… Access Granted + + Note over User,CICD: Without valid MFA:
โŒ Access Denied +``` + +* ๐Ÿ”— **Implementation guides**: + * [GitHub MFA Setup](https://docs.github.com/en/authentication/securing-your-account-with-two-factor-authentication-2fa) + * [GitLab MFA Configuration](https://docs.gitlab.com/ee/user/profile/account/two_factor_authentication.html) + +--- + +## ๐Ÿ“ Slide 12 โ€“ โš–๏ธ Principle of Least Privilege in CI/CD Workflows + +* โš–๏ธ **Least Privilege Principle** โ†’ entities should have **minimum permissions** required to perform their function +* ๐ŸŽฏ **Application in CI/CD**: + * ๐Ÿ‘ค **Users**: developers only access their team's pipelines + * ๐Ÿค– **Service accounts**: build agents only access required repositories + * ๐Ÿ”ง **Pipelines**: each pipeline only accesses necessary resources + * ๐ŸŒ **Environments**: staging access โ‰  production access +* ๐Ÿ“Š **Permission granularity levels**: + * ๐Ÿ—๏ธ **Organization level**: admin vs. member access + * ๐Ÿ“‚ **Repository level**: read, write, admin permissions + * ๐Ÿ”ง **Pipeline level**: view, edit, execute, delete + * ๐ŸŒ **Environment level**: deploy, approve, configure +* โš ๏ธ **Common violations**: + * ๐Ÿ‘‘ **Admin by default**: giving users more permissions than needed + * ๐Ÿ”„ **Permission creep**: accumulating permissions over time + * ๐ŸŽฏ **Broad service accounts**: single account for multiple purposes +* โœ… **Implementation strategies**: + * ๐Ÿ“‹ **Regular access reviews**: quarterly permission audits + * ๐Ÿ”„ **Just-in-time access**: temporary elevated permissions + * ๐Ÿ“Š **Permission analytics**: identify unused or excessive permissions + +```mermaid +flowchart TD + subgraph "โŒ Over-Privileged (Bad)" + DevA[๐Ÿ‘จโ€๐Ÿ’ป Developer A] -->|Admin Access| AllRepos[๐Ÿ“‚ All Repositories] + ServiceA[๐Ÿค– Service Account] -->|Full Access| AllEnvs[๐ŸŒ All Environments] + end + + subgraph "โœ… Least Privilege (Good)" + DevB[๐Ÿ‘จโ€๐Ÿ’ป Developer B] -->|Read/Write| TeamRepos[๐Ÿ“‚ Team Repositories Only] + ServiceB[๐Ÿค– Build Service] -->|Deploy Only| StagingEnv[๐Ÿงช Staging Environment] + ServiceC[๐Ÿค– Deploy Service] -->|Deploy Only| ProdEnv[๐Ÿญ Production Environment] + end + + classDef bad fill:#ffebee,stroke:#d32f2f + classDef good fill:#e8f5e8,stroke:#2e7d32 + + class DevA,ServiceA,AllRepos,AllEnvs bad + class DevB,ServiceB,ServiceC,TeamRepos,StagingEnv,ProdEnv good +``` + +### ๐Ÿ’ป Example: GitHub Repository Permissions + +```yaml +# โŒ Over-privileged team permissions +team_permissions: + developers: + role: admin # Too much access + repositories: "*" # Access to all repos + +# โœ… Least privilege team permissions +team_permissions: + frontend_devs: + role: write # Appropriate for development + repositories: + - "web-app" + - "ui-components" + backend_devs: + role: write + repositories: + - "api-service" + - "database-migrations" +``` + +--- + +## ๐Ÿ“ Slide 13 โ€“ ๐Ÿ•ธ๏ธ Zero-Trust Approaches to Pipeline Security + +* ๐Ÿ•ธ๏ธ **Zero-Trust Security Model** โ†’ "**never trust, always verify**" - assume breach and verify every access attempt +* ๐Ÿ” **Core Zero-Trust principles for CI/CD**: + * ๐Ÿšซ **No implicit trust**: verify identity and device for every access + * ๐Ÿ” **Continuous verification**: monitor and re-authenticate during sessions + * ๐ŸŽฏ **Micro-segmentation**: isolate pipeline components and limit blast radius + * ๐Ÿ“Š **Real-time monitoring**: detect and respond to anomalous behavior +* ๐Ÿ›ก๏ธ **Zero-Trust CI/CD implementation**: + * ๐Ÿ” **Device trust**: only managed/compliant devices access pipelines + * ๐Ÿ“ **Location-based access**: restrict access based on geographic location + * ๐Ÿ• **Time-based access**: limit access to business hours or maintenance windows + * ๐Ÿ”„ **Dynamic permissions**: permissions based on current risk assessment +* ๐Ÿงฉ **Supporting technologies**: + * ๐ŸŒ **Secure Access Service Edge (SASE)**: cloud-native security platform + * ๐Ÿ” **Privileged Access Management (PAM)**: just-in-time privileged access + * ๐Ÿ“Š **User and Entity Behavior Analytics (UEBA)**: detect anomalous behavior +* ๐Ÿข **Industry adoption**: **67% of enterprises** implementing Zero-Trust by 2025 ([Gartner Zero Trust Research](https://www.gartner.com/en/newsroom/press-releases/2023-07-11-gartner-identifies-three-factors-influencing-adoption-of-a-zero-trust-architecture)) + +```mermaid +flowchart TD + subgraph "๐Ÿฐ Traditional Perimeter Security" + Internet1[๐ŸŒ Internet] -->|Firewall| Internal1[๐Ÿข Internal Network] + Internal1 --> Pipeline1[๐Ÿ”ง CI/CD Pipeline] + Internal1 --> Secrets1[๐Ÿ”‘ Secrets] + Pipeline1 -.->|Trusted Network| Secrets1 + end + + subgraph "๐Ÿ•ธ๏ธ Zero-Trust Security" + Internet2[๐ŸŒ Internet] --> Gateway[๐Ÿ›ก๏ธ Zero-Trust Gateway] + Gateway -->|Verify Identity| Pipeline2[๐Ÿ”ง CI/CD Pipeline] + Gateway -->|Verify Device| Pipeline2 + Pipeline2 -->|Authenticate| Vault[๐Ÿ” Secure Vault] + Pipeline2 -->|Monitor| Logs[๐Ÿ“Š Security Logs] + end + + classDef traditional fill:#fff3e0,stroke:#f57c00 + classDef zerotrust fill:#e8f5e8,stroke:#2e7d32 + + class Internet1,Internal1,Pipeline1,Secrets1 traditional + class Internet2,Gateway,Pipeline2,Vault,Logs zerotrust +``` + +### ๐Ÿ’ป Example: Zero-Trust Pipeline Configuration + +```yaml +# Zero-Trust CI/CD Pipeline Configuration +pipeline_security: + identity_verification: + mfa_required: true + device_compliance: required + location_restrictions: + - "corporate_office" + - "approved_vpn" + + access_controls: + session_timeout: 2h + re_authentication_interval: 30min + privilege_escalation: just_in_time + + monitoring: + behavioral_analytics: enabled + anomaly_detection: enabled + real_time_alerts: enabled +``` + +* ๐Ÿ’ก **Benefits**: reduced attack surface, improved compliance, faster threat detection +* ๐Ÿšง **Implementation challenges**: complexity, user experience impact, cultural change required + +--- + +## ๐Ÿ“‚ Group 3: Secure Pipeline Configuration & Hardening + +## ๐Ÿ“ Slide 14 โ€“ ๐Ÿ“‹ Infrastructure-as-Code (IaC) for Pipeline Configuration + +* ๐Ÿ“‹ **IaC = Infrastructure-as-Code** โ†’ managing CI/CD infrastructure through **version-controlled configuration files** +* ๐Ÿ—๏ธ **Pipeline-as-Code benefits**: + * ๐Ÿ“‚ **Version control**: track changes, rollback capabilities, audit history + * ๐Ÿ”„ **Reproducibility**: consistent pipeline deployments across environments + * ๐Ÿ‘ฅ **Collaboration**: code review processes for infrastructure changes + * ๐Ÿงช **Testing**: validate pipeline configurations before deployment +* ๐Ÿ› ๏ธ **Popular IaC tools for CI/CD**: + * โš™๏ธ **Terraform**: multi-cloud pipeline infrastructure provisioning + * ๐Ÿ“˜ **Azure ARM/Bicep**: Azure DevOps pipeline infrastructure + * โ˜๏ธ **AWS CDK/CloudFormation**: CodePipeline and CodeBuild setup + * ๐Ÿ™ **Pulumi**: modern IaC with familiar programming languages +* ๐Ÿ“Š **Adoption statistics**: **76% of organizations** use IaC for CI/CD infrastructure ([HashiCorp State of Cloud Strategy Report](https://www.hashicorp.com/state-of-the-cloud)) +* ๐Ÿ” **Security advantages**: immutable infrastructure, consistent security configs, policy enforcement +* ๐Ÿ”— **Best practices**: [Terraform CI/CD Best Practices](https://developer.hashicorp.com/terraform/tutorials/automation) + +```mermaid +flowchart LR + subgraph "Traditional Approach" + Admin1[๐Ÿ‘จโ€๐Ÿ’ป Admin] -->|Manual Config| Jenkins1[๐Ÿ”ง Jenkins Server] + Admin1 -->|SSH + GUI| Jenkins1 + end + + subgraph "Infrastructure-as-Code" + Dev[๐Ÿ‘จโ€๐Ÿ’ป Developer] -->|Git Commit| Repo[๐Ÿ“‚ IaC Repository] + Repo -->|Automated| Terraform[๐Ÿ—๏ธ Terraform] + Terraform -->|Provision| Jenkins2[๐Ÿ”ง Jenkins Infrastructure] + Terraform -->|Configure| Security[๐Ÿ›ก๏ธ Security Policies] + end + + classDef traditional fill:#fff3e0,stroke:#f57c00 + classDef iac fill:#e8f5e8,stroke:#2e7d32 + + class Admin1,Jenkins1 traditional + class Dev,Repo,Terraform,Jenkins2,Security iac +``` + +--- + +## ๐Ÿ“ Slide 15 โ€“ ๐Ÿ”’ Securing Pipeline Configuration Files (YAML/JSON Security) + +* ๐Ÿ“„ **Configuration file risks**: pipeline definitions (YAML/JSON) are **code** and need security review +* โš ๏ธ **Common vulnerabilities in pipeline configs**: + * ๐Ÿ”‘ **Hardcoded secrets**: API keys, passwords directly in YAML/JSON files + * ๐ŸŒ **External script execution**: downloading and executing untrusted scripts + * ๐Ÿ“ **Command injection**: user input passed to shell commands without validation + * ๐Ÿ”“ **Overly permissive triggers**: pipelines triggered by any branch or PR +* ๐Ÿ›ก๏ธ **Configuration security best practices**: + * ๐Ÿ“– **Code review mandatory**: all pipeline changes require peer review + * ๐Ÿ” **Secret scanning**: automated detection of credentials in config files + * โœ… **Schema validation**: ensure pipeline configs follow secure templates + * ๐Ÿšซ **Restricted permissions**: limit who can modify pipeline configurations +* ๐Ÿงฉ **Platform-specific protections**: + * ๐Ÿ™ **GitHub Actions**: required reviewers for workflow changes + * ๐ŸฆŠ **GitLab CI**: protected variables and restricted runners + * ๐Ÿ”ง **Jenkins**: job configuration restrictions and approval processes +* ๐Ÿ“Š **Impact**: **23% of CI/CD breaches** involve compromised configuration files ([Argon Security Research](https://www.argon.io/blog/argo-cd-security-research-findings/)) + +```mermaid +flowchart TD + subgraph "โŒ Insecure Pipeline Config" + Config1[๐Ÿ“„ Pipeline YAML] -->|Contains| Secret1[๐Ÿ”‘ Hardcoded API Key] + Config1 -->|Downloads| Script1[๐ŸŒ External Script] + Config1 -->|Executes| Command1[๐Ÿ’ป Shell Command with User Input] + end + + subgraph "โœ… Secure Pipeline Config" + Config2[๐Ÿ“„ Pipeline YAML] -->|References| Vault[๐Ÿ” Secret Vault] + Config2 -->|Uses Approved| Library[๐Ÿ“š Trusted Script Library] + Config2 -->|Sanitizes| Input[๐Ÿงน Validated Input] + Review[๐Ÿ‘ฅ Code Review] --> Config2 + end + + classDef insecure fill:#ffebee,stroke:#d32f2f + classDef secure fill:#e8f5e8,stroke:#2e7d32 + + class Config1,Secret1,Script1,Command1 insecure + class Config2,Vault,Library,Input,Review secure +``` + +--- + +## ๐Ÿ“ Slide 16 โ€“ ๐Ÿฐ Build Environment Isolation & Sandboxing + +* ๐Ÿฐ **Build isolation** = running each build in a **separate, controlled environment** to prevent interference and security breaches +* ๐Ÿงฉ **Isolation techniques**: + * ๐Ÿ“ฆ **Containerization**: Docker containers for build execution + * ๐Ÿ–ฅ๏ธ **Virtual machines**: dedicated VMs for sensitive builds + * ๐Ÿ”’ **Process isolation**: separate user accounts and namespaces + * ๐ŸŒ **Network isolation**: restricted network access during builds +* ๐Ÿ›ก๏ธ **Sandboxing benefits**: + * ๐Ÿšซ **Malware containment**: malicious code cannot escape build environment + * ๐Ÿ” **Secret protection**: credentials isolated per build + * ๐Ÿงน **Clean state**: each build starts with fresh environment + * ๐Ÿ“Š **Resource limits**: CPU, memory, and disk quotas per build +* โš™๏ธ **Implementation approaches**: + * ๐Ÿณ **Docker-based**: ephemeral containers destroyed after build + * โ˜๏ธ **Cloud runners**: AWS CodeBuild, Google Cloud Build, Azure DevOps hosted agents + * ๐Ÿ–ฅ๏ธ **On-premise**: VMware vSphere, Hyper-V, KVM virtualization +* ๐Ÿ“ˆ **Performance trade-offs**: stronger isolation = higher resource overhead +* ๐Ÿ”— **Container security**: [Docker Security Best Practices](https://docs.docker.com/develop/security-best-practices/) + +```mermaid +flowchart TD + subgraph "๐Ÿฐ Isolated Build Environment" + Build1[๐Ÿ”ง Build Job A] --> Container1[๐Ÿ“ฆ Container A] + Build2[๐Ÿ”ง Build Job B] --> Container2[๐Ÿ“ฆ Container B] + Build3[๐Ÿ”ง Build Job C] --> VM[๐Ÿ–ฅ๏ธ Virtual Machine] + end + + subgraph "๐Ÿ›ก๏ธ Security Boundaries" + Container1 -.->|Isolated| Network1[๐ŸŒ Network Namespace] + Container2 -.->|Isolated| Network2[๐ŸŒ Network Namespace] + VM -.->|Isolated| Hypervisor[๐Ÿ—๏ธ Hypervisor Layer] + end + + subgraph "๐Ÿ”’ Shared Resources" + Registry[๐Ÿ“š Artifact Registry] + Secrets[๐Ÿ”‘ Secret Store] + end + + Container1 -->|Controlled Access| Registry + Container2 -->|Controlled Access| Registry + VM -->|Controlled Access| Secrets +``` + +--- + +## ๐Ÿ“ Slide 17 โ€“ ๐Ÿšซ Preventing Poisoned Pipeline Execution (PPE) Attacks + +* โ˜ ๏ธ **Poisoned Pipeline Execution (PPE)** = attacker modifies pipeline configuration to execute **malicious commands during build** +* ๐ŸŽฏ **PPE attack vectors**: + * ๐Ÿ“ **Direct config modification**: altering YAML/JSON pipeline files + * ๐Ÿ”€ **Pull request attacks**: malicious changes in external contributor PRs + * ๐Ÿงฌ **Template injection**: exploiting dynamic pipeline generation + * ๐Ÿ“ฆ **Dependency confusion**: malicious packages with pipeline modifications +* โš ๏ธ **Real-world PPE examples**: + * ๐Ÿข **Codecov incident (2021)**: bash script modification led to credential theft + * ๐Ÿ“ฆ **npm package attacks**: malicious install scripts in CI/CD environments + * ๐Ÿ”ง **Jenkins plugins**: compromised plugins executing unauthorized code +* ๐Ÿ›ก๏ธ **PPE prevention strategies**: + * ๐Ÿ‘ฅ **Mandatory code review**: all pipeline changes require approval + * ๐Ÿ” **Branch protection**: restrict pipeline modifications to trusted users + * ๐ŸŽฏ **Least privilege**: pipeline permissions limited to necessary operations + * ๐Ÿ“Š **Runtime monitoring**: detect unusual pipeline behavior during execution +* ๐Ÿ“ˆ **Growing threat**: PPE attacks increased **67% in 2023** ([Checkmarx Research](https://checkmarx.com/resource/documents/en/report/2024-software-supply-chain-security-report/)) + +```mermaid +sequenceDiagram + participant Attacker as ๐Ÿ˜ˆ Attacker + participant Repo as ๐Ÿ“‚ Repository + participant Pipeline as ๐Ÿ”ง CI/CD Pipeline + participant Secrets as ๐Ÿ”‘ Secret Store + + Attacker->>Repo: 1. Submit malicious PR + Note over Repo: Pipeline config modified
to steal secrets + Repo->>Pipeline: 2. Trigger automated build + Pipeline->>Pipeline: 3. Execute malicious commands + Pipeline->>Secrets: 4. Access and exfiltrate secrets + Pipeline->>Attacker: 5. Send stolen credentials + + Note over Attacker,Secrets: Prevention: Code review
+ Branch protection
+ Runtime monitoring +``` + +* ๐Ÿ”— **OWASP guidance**: [Poisoned Pipeline Execution Prevention](https://owasp.org/www-project-top-10-ci-cd-security-risks/CICD-SEC-4) + +--- + +## ๐Ÿ“ Slide 18 โ€“ ๐ŸŒ Network Segmentation for CI/CD Infrastructure + +* ๐ŸŒ **Network segmentation** = isolating CI/CD components in **separate network zones** with controlled communication +* ๐Ÿ—๏ธ **CI/CD network architecture tiers**: + * ๐ŸŒ **DMZ (Demilitarized Zone)**: public-facing components (webhooks, APIs) + * ๐Ÿ”ง **Build network**: isolated build agents and runners + * ๐Ÿ“ฆ **Artifact network**: secure storage for build outputs + * ๐Ÿญ **Production network**: deployment targets with strict access controls +* ๐Ÿ›ก๏ธ **Segmentation benefits**: + * ๐Ÿšซ **Lateral movement prevention**: compromised component cannot access other zones + * ๐Ÿ“Š **Traffic monitoring**: network flows between segments are logged and analyzed + * ๐Ÿ” **Access control**: firewall rules enforce communication policies + * ๐ŸŽฏ **Blast radius reduction**: security incidents contained to specific segments +* โš™๏ธ **Implementation technologies**: + * ๐Ÿงฑ **Firewalls**: next-generation firewalls with application awareness + * ๐Ÿท๏ธ **VLANs**: virtual local area networks for logical separation + * ๐Ÿ•ธ๏ธ **Software-Defined Networking (SDN)**: programmable network policies + * โ˜๏ธ **Cloud security groups**: AWS security groups, Azure NSGs, GCP firewall rules +* ๐Ÿ“Š **Industry adoption**: **82% of enterprises** use network segmentation for CI/CD ([Cisco Security Report](https://www.cisco.com/c/en/us/products/security/security-reports.html)) + +```mermaid +flowchart TD + subgraph "๐ŸŒ DMZ Zone" + WebHook[๐Ÿช Webhook Receiver] + API[๐Ÿ”Œ Public API] + end + + subgraph "๐Ÿ”ง Build Zone" + Agent1[๐Ÿ—๏ธ Build Agent 1] + Agent2[๐Ÿ—๏ธ Build Agent 2] + Scanner[๐Ÿ” Security Scanner] + end + + subgraph "๐Ÿ“ฆ Artifact Zone" + Registry[๐Ÿ—„๏ธ Artifact Registry] + Cache[๐Ÿ’พ Build Cache] + end + + subgraph "๐Ÿญ Production Zone" + Staging[๐Ÿงช Staging Environment] + Production[๐ŸŒŸ Production Environment] + end + + WebHook -->|HTTPS| Agent1 + API -->|Authenticated| Agent2 + Agent1 -->|Push Artifacts| Registry + Agent2 -->|Security Scan| Scanner + Registry -->|Deploy| Staging + Staging -->|Approved| Production + + classDef dmz fill:#fff3e0,stroke:#f57c00 + classDef build fill:#e3f2fd,stroke:#1976d2 + classDef artifact fill:#f3e5f5,stroke:#7b1fa2 + classDef prod fill:#e8f5e8,stroke:#388e3c + + class WebHook,API dmz + class Agent1,Agent2,Scanner build + class Registry,Cache artifact + class Staging,Production prod +``` + +--- + +## ๐Ÿ“ Slide 19 โ€“ ๐Ÿ“‚ Secure Artifact Storage & Repository Management + +* ๐Ÿ“ฆ **Artifacts** = build outputs stored for deployment (container images, packages, binaries, libraries) +* ๐Ÿ—๏ธ **Artifact repository types**: + * ๐Ÿณ **Container registries**: Docker Hub, AWS ECR, Azure ACR, Google GCR + * ๐Ÿ“š **Package repositories**: npm registry, Maven Central, NuGet Gallery, PyPI + * ๐Ÿ“ **Binary repositories**: JFrog Artifactory, Sonatype Nexus, AWS S3 + * ๐Ÿงฌ **Generic storage**: cloud blob storage with versioning and access control +* ๐Ÿ” **Security requirements for artifact storage**: + * ๐Ÿ” **Access control**: role-based permissions for push/pull operations + * ๐Ÿ” **Encryption**: artifacts encrypted at rest and in transit + * ๐Ÿท๏ธ **Vulnerability scanning**: automated security scanning of stored artifacts + * ๐Ÿ“ **Audit logging**: comprehensive logs of all artifact operations +* โš ๏ธ **Common security risks**: + * ๐ŸŒ **Public exposure**: accidentally making private artifacts publicly accessible + * ๐Ÿ”“ **Weak authentication**: inadequate access controls allowing unauthorized access + * ๐Ÿฆ  **Malware injection**: attackers replacing legitimate artifacts with malicious ones + * ๐Ÿ“Š **Lack of scanning**: unscanned artifacts deployed with known vulnerabilities +* ๐Ÿ’ฐ **Cost optimization**: lifecycle policies for automatic cleanup of old artifacts +* ๐Ÿ”— **Registry security**: [Container Registry Security Best Practices](https://cloud.google.com/artifact-registry/docs/secure) + +```mermaid +flowchart LR + subgraph "๐Ÿ—๏ธ Build Process" + Build[๐Ÿ”ง CI/CD Pipeline] + Test[๐Ÿงช Security Tests] + Sign[โœ๏ธ Artifact Signing] + end + + subgraph "๐Ÿ“ฆ Secure Artifact Storage" + Registry[๐Ÿ—„๏ธ Private Registry] + Scan[๐Ÿ” Vulnerability Scanner] + Policy[๐Ÿ“‹ Retention Policy] + end + + subgraph "๐Ÿš€ Deployment" + Stage[๐Ÿงช Staging Deploy] + Prod[๐ŸŒŸ Production Deploy] + Verify[โœ… Signature Verification] + end + + Build --> Test + Test --> Sign + Sign --> Registry + Registry --> Scan + Registry --> Policy + Registry --> Stage + Stage --> Verify + Verify --> Prod + + classDef build fill:#e3f2fd,stroke:#1976d2 + classDef storage fill:#f3e5f5,stroke:#7b1fa2 + classDef deploy fill:#e8f5e8,stroke:#388e3c + + class Build,Test,Sign build + class Registry,Scan,Policy storage + class Stage,Prod,Verify deploy +``` + +--- + +## ๐Ÿ“ Slide 20 โ€“ ๐Ÿงน Container Security in Build Environments + +* ๐Ÿณ **Container security** = protecting **containerized build processes** from threats and vulnerabilities +* ๐Ÿ”’ **Container-specific risks in CI/CD**: + * ๐Ÿ—๏ธ **Insecure base images**: using images with known vulnerabilities + * ๐Ÿ‘‘ **Privileged containers**: running containers with root privileges + * ๐Ÿ“‚ **Host path mounts**: exposing host filesystem to build containers + * ๐ŸŒ **Network exposure**: containers with unnecessary network access +* ๐Ÿ›ก๏ธ **Container hardening practices**: + * ๐ŸŽฏ **Minimal base images**: distroless, Alpine, or scratch images + * ๐Ÿ‘ค **Non-root execution**: running containers as non-privileged users + * ๐Ÿ“ **Read-only filesystems**: preventing runtime file modifications + * ๐Ÿ”’ **Security policies**: Pod Security Standards, OPA Gatekeeper, Falco +* ๐Ÿ” **Container image scanning**: + * ๐Ÿฆ  **Vulnerability detection**: Trivy, Clair, Snyk, Twistlock scanning + * ๐Ÿ“‹ **Policy enforcement**: blocking deployments of vulnerable images + * ๐Ÿท๏ธ **Image signing**: Sigstore Cosign for supply chain integrity + * ๐Ÿ“Š **SBOM generation**: Software Bill of Materials for transparency +* ๐Ÿš€ **Runtime protection**: + * ๐Ÿ‘๏ธ **Behavioral monitoring**: detecting anomalous container behavior + * ๐Ÿšซ **Syscall filtering**: restricting dangerous system calls + * ๐ŸŒ **Network policies**: controlling container-to-container communication +* ๐Ÿ“ˆ **Statistics**: **75% of organizations** experienced container security incidents in 2023 ([Red Hat State of Kubernetes Security](https://www.redhat.com/en/resources/state-kubernetes-security-report-2024)) + +```mermaid +flowchart TD + subgraph "โŒ Insecure Container Build" + BadImage[๐Ÿณ Ubuntu:latest + Root User] + BadMount[๐Ÿ“ Host Path Mount /var/run/docker.sock] + BadNetwork[๐ŸŒ Full Network Access] + end + + subgraph "โœ… Secure Container Build" + GoodImage[๐Ÿณ Distroless + Non-root User] + ReadOnly[๐Ÿ“ Read-only Filesystem] + NetworkPolicy[๐Ÿ”’ Restricted Network Policy] + Scanner[๐Ÿ” Image Vulnerability Scanner] + end + + subgraph "๐Ÿ›ก๏ธ Security Controls" + PodSecurity[๐Ÿ“‹ Pod Security Standards] + Falco[๐Ÿ‘๏ธ Runtime Monitoring] + Cosign[โœ๏ธ Image Signing] + end + + GoodImage --> Scanner + Scanner --> PodSecurity + PodSecurity --> Falco + Falco --> Cosign + + classDef insecure fill:#ffebee,stroke:#d32f2f + classDef secure fill:#e8f5e8,stroke:#2e7d32 + classDef controls fill:#e3f2fd,stroke:#1976d2 + + class BadImage,BadMount,BadNetwork insecure + class GoodImage,ReadOnly,NetworkPolicy,Scanner secure + class PodSecurity,Falco,Cosign controls +``` + +--- + +## ๐Ÿ“ Slide 21 โ€“ โฑ๏ธ Resource Limits & Denial of Service Prevention + +* โฑ๏ธ **Resource limits** = preventing CI/CD processes from consuming **excessive compute resources** (CPU, memory, disk, network) +* ๐ŸŽฏ **DoS attack vectors in CI/CD**: + * ๐Ÿ’ป **CPU exhaustion**: infinite loops, cryptomining, CPU-intensive operations + * ๐Ÿง  **Memory bombs**: memory leaks, large data processing, recursive algorithms + * ๐Ÿ’พ **Disk space attacks**: generating large files, log flooding, artifact bloat + * ๐ŸŒ **Network flooding**: DDoS attacks, bandwidth consumption, connection exhaustion +* ๐Ÿ›ก๏ธ **Resource protection strategies**: + * โฐ **Timeout policies**: maximum execution time for builds and deployments + * ๐Ÿ“Š **Resource quotas**: CPU/memory limits per pipeline, user, and organization + * ๐Ÿ”„ **Rate limiting**: maximum number of concurrent builds, API requests + * ๐Ÿ“ˆ **Monitoring and alerting**: real-time resource usage tracking +* โš™๏ธ **Implementation mechanisms**: + * ๐Ÿณ **Container limits**: Docker memory/CPU constraints, Kubernetes resource limits + * โ˜๏ธ **Cloud quotas**: AWS service limits, Azure subscription limits, GCP quotas + * ๐Ÿ”ง **Build system controls**: Jenkins executor limits, GitHub Actions usage limits + * ๐Ÿ“Š **Monitoring tools**: Prometheus, Grafana, cloud monitoring dashboards +* ๐Ÿ’ฐ **Cost control**: preventing runaway processes from generating unexpected cloud bills +* ๐Ÿ“ˆ **Industry impact**: **32% of CI/CD incidents** involve resource exhaustion attacks ([SANS DevSecOps Survey](https://www.sans.org/white-papers/devsecops-survey/)) + +```mermaid +flowchart TD + subgraph "โš ๏ธ Uncontrolled Resources" + Pipeline1[๐Ÿ”ง Build Pipeline] --> Unlimited[โ™พ๏ธ No Limits] + Unlimited --> CPUSpike[๐Ÿ’ป CPU 100%] + Unlimited --> MemoryLeak[๐Ÿง  Memory Overflow] + Unlimited --> DiskFull[๐Ÿ’พ Disk Space Full] + end + + subgraph "โœ… Controlled Resources" + Pipeline2[๐Ÿ”ง Build Pipeline] --> Limits[๐Ÿ“Š Resource Limits] + Limits --> CPULimit[๐Ÿ’ป CPU: 2 cores max] + Limits --> MemoryLimit[๐Ÿง  Memory: 4GB max] + Limits --> TimeoutLimit[โฐ Timeout: 30min max] + Monitor[๐Ÿ“ˆ Resource Monitor] --> Alerts[๐Ÿšจ Usage Alerts] + end + + subgraph "๐Ÿ›ก๏ธ Protection Mechanisms" + Kubernetes[โ˜ธ๏ธ K8s Resource Quotas] + Docker[๐Ÿณ Container Limits] + Cloud[โ˜๏ธ Cloud Service Quotas] + end + + Limits --> Kubernetes + Limits --> Docker + Limits --> Cloud + + classDef uncontrolled fill:#ffebee,stroke:#d32f2f + classDef controlled fill:#e8f5e8,stroke:#2e7d32 + classDef protection fill:#e3f2fd,stroke:#1976d2 + + class Pipeline1,Unlimited,CPUSpike,MemoryLeak,DiskFull uncontrolled + class Pipeline2,Limits,CPULimit,MemoryLimit,TimeoutLimit,Monitor,Alerts controlled + class Kubernetes,Docker,Cloud protection +``` + +--- + +## ๐Ÿ“‚ Group 4: Build Integrity & Artifact Security + +## ๐Ÿ“ Slide 22 โ€“ ๐Ÿ“ฆ Secure Artifact Creation & Packaging + +* ๐Ÿ“ฆ **Artifacts** = final outputs of CI/CD process (executables, container images, packages, libraries, documentation) +* ๐Ÿ—๏ธ **Secure artifact creation principles**: + * ๐Ÿงน **Reproducible builds**: same source code produces identical artifacts every time + * ๐Ÿ” **Tamper evidence**: detect if artifacts modified after creation + * ๐Ÿ“‹ **Metadata inclusion**: version info, build environment, dependencies, timestamps + * ๐Ÿท๏ธ **Proper labeling**: semantic versioning, environment tags, security classifications +* โš ๏ธ **Common artifact security risks**: + * ๐Ÿฆ  **Malware injection**: malicious code inserted during build process + * ๐Ÿ”„ **Supply chain tampering**: compromised dependencies affecting final artifact + * ๐Ÿ“ **Metadata manipulation**: false version info or dependency information + * ๐ŸŒ **Unauthorized distribution**: artifacts shared through insecure channels +* ๐Ÿ›ก๏ธ **Security measures during packaging**: + * ๐Ÿ” **Pre-packaging scans**: malware detection, vulnerability assessment + * ๐Ÿ“Š **Build environment validation**: ensure clean, trusted build systems + * ๐Ÿท๏ธ **Immutable tagging**: prevent tag reuse for different artifacts + * ๐Ÿ“ **Audit trail creation**: complete record of build process and inputs +* ๐Ÿ“ˆ **Industry trend**: **89% of organizations** implementing secure packaging practices by 2024 ([Sonatype DevSecOps Report](https://www.sonatype.com/state-of-the-software-supply-chain/)) + +```mermaid +flowchart LR + subgraph "๐Ÿ—๏ธ Build Process" + Source[๐Ÿ“‚ Source Code] + Dependencies[๐Ÿ“š Dependencies] + Build[โš™๏ธ Build System] + end + + subgraph "๐Ÿ“ฆ Secure Packaging" + Scan[๐Ÿ” Security Scan] + Package[๐Ÿ“ฆ Package Creation] + Metadata[๐Ÿ“‹ Metadata Addition] + Tag[๐Ÿท๏ธ Immutable Tagging] + end + + subgraph "โœ… Verification" + Checksum[๐Ÿ”ข Checksum Generation] + Signature[โœ๏ธ Digital Signature] + Registry[๐Ÿ—„๏ธ Secure Registry] + end + + Source --> Build + Dependencies --> Build + Build --> Scan + Scan --> Package + Package --> Metadata + Metadata --> Tag + Tag --> Checksum + Checksum --> Signature + Signature --> Registry + + classDef build fill:#e3f2fd,stroke:#1976d2,color:#2c3e50 + classDef package fill:#f3e5f5,stroke:#7b1fa2,color:#2c3e50 + classDef verify fill:#e8f5e8,stroke:#388e3c,color:#2c3e50 + + class Source,Dependencies,Build build + class Scan,Package,Metadata,Tag package + class Checksum,Signature,Registry verify +``` + +--- + +## ๐Ÿ“ Slide 23 โ€“ ๐Ÿ” Digital Signing & Verification of Build Artifacts + +* ๐Ÿ” **Digital signing** = cryptographic proof that artifact **came from trusted source** and **hasn't been tampered with** +* ๐Ÿ”‘ **Signing technologies**: + * ๐Ÿ“œ **Code signing certificates**: X.509 certificates from trusted Certificate Authorities (CA) + * ๐Ÿ” **GPG/PGP signatures**: GNU Privacy Guard for open-source artifact signing + * ๐ŸŒŸ **Sigstore Cosign**: modern, keyless signing for container images and artifacts + * โ˜๏ธ **Cloud HSMs**: Hardware Security Modules for enterprise-grade key management +* ๐Ÿ›ก๏ธ **Signing best practices**: + * ๐Ÿ”’ **Private key protection**: store signing keys in secure hardware or cloud HSM + * โฐ **Time stamping**: include trusted timestamps to prevent replay attacks + * ๐Ÿ“‹ **Certificate management**: regular renewal, revocation capabilities + * ๐ŸŽฏ **Principle of least privilege**: limit access to signing operations +* โœ… **Verification process**: + * ๐Ÿ” **Signature validation**: verify artifact signature before deployment + * ๐Ÿ›๏ธ **Certificate chain validation**: ensure signing certificate is trusted + * โฐ **Timestamp verification**: confirm signing occurred within valid timeframe + * ๐Ÿ“Š **Policy enforcement**: reject unsigned or improperly signed artifacts +* ๐Ÿ“Š **Adoption statistics**: **73% of enterprises** require signed artifacts for production deployment ([Venafi Machine Identity Report](https://www.venafi.com/resource/2024-machine-identity-security-trends-report)) + +```mermaid +sequenceDiagram + participant Developer as ๐Ÿ‘จโ€๐Ÿ’ป Developer + participant Pipeline as ๐Ÿ”ง CI/CD Pipeline + participant HSM as ๐Ÿ” HSM/Key Vault + participant Registry as ๐Ÿ—„๏ธ Artifact Registry + participant Deploy as ๐Ÿš€ Deployment + + Developer->>Pipeline: 1. Commit Code + Pipeline->>Pipeline: 2. Build Artifact + Pipeline->>HSM: 3. Request Signing Key + HSM->>Pipeline: 4. Provide Signing Capability + Pipeline->>Pipeline: 5. Sign Artifact + Pipeline->>Registry: 6. Store Signed Artifact + Deploy->>Registry: 7. Retrieve Artifact + Deploy->>Deploy: 8. Verify Signature + alt Valid Signature + Deploy->>Deploy: 9. โœ… Deploy Artifact + else Invalid Signature + Deploy->>Deploy: 9. โŒ Reject Deployment + end + + classDef default fill:#f9f,stroke:#333,stroke-width:2px,color:#2c3e50 +``` + +--- + +## ๐Ÿ“ Slide 24 โ€“ ๐Ÿ“‹ Software Bill of Materials (SBOM) Generation + +* ๐Ÿ“‹ **SBOM = Software Bill of Materials** โ†’ comprehensive inventory of **all components, libraries, and dependencies** used in software +* ๐ŸŽฏ **SBOM importance for security**: + * ๐Ÿ” **Vulnerability tracking**: identify which components have known security issues + * ๐Ÿ“Š **License compliance**: understand licensing obligations for all dependencies + * ๐Ÿ•ต๏ธ **Supply chain visibility**: map entire software supply chain for risk assessment + * ๐Ÿšจ **Incident response**: quickly identify affected systems when vulnerabilities discovered +* ๐Ÿ“ **SBOM formats and standards**: + * ๐ŸŒ€ **CycloneDX**: OWASP standard, security-focused, supports vulnerability data + * ๐Ÿ“„ **SPDX (Software Package Data Exchange)**: Linux Foundation standard, license-focused + * ๐Ÿงพ **SWID (Software Identification)**: ISO standard for software identification +* ๐Ÿ› ๏ธ **SBOM generation tools**: + * ๐Ÿ”ง **Syft**: open-source SBOM generator for container images and filesystems + * ๐ŸŒ€ **CycloneDX generators**: language-specific tools (Maven, npm, pip, etc.) + * ๐Ÿข **Commercial tools**: Snyk, JFrog Xray, Sonatype Nexus, FOSSA +* ๐Ÿ“Š **Regulatory requirements**: US Executive Order 14028 **mandates SBOM** for federal software procurement +* ๐Ÿ”— **Learn more**: [NTIA SBOM Minimum Elements](https://www.ntia.doc.gov/files/ntia/publications/sbom_minimum_elements_report.pdf) + +```mermaid +flowchart TD + subgraph "๐Ÿ“ฆ Software Artifact" + App[๐Ÿ–ฅ๏ธ Application] + Lib1[๐Ÿ“š Library A v1.2] + Lib2[๐Ÿ“š Library B v2.5] + OS[๐Ÿง Base OS Image] + end + + subgraph "๐Ÿ” SBOM Generation" + Scanner[๐Ÿ•ต๏ธ SBOM Scanner] + Analysis[๐Ÿ”ฌ Dependency Analysis] + Format[๐Ÿ“‹ Format Generation] + end + + subgraph "๐Ÿ“„ SBOM Output" + CycloneDX[๐ŸŒ€ CycloneDX Format] + SPDX[๐Ÿ“„ SPDX Format] + Vulnerabilities[โš ๏ธ Vulnerability Data] + Licenses[โš–๏ธ License Information] + end + + App --> Scanner + Lib1 --> Scanner + Lib2 --> Scanner + OS --> Scanner + Scanner --> Analysis + Analysis --> Format + Format --> CycloneDX + Format --> SPDX + Format --> Vulnerabilities + Format --> Licenses + + classDef artifact fill:#e3f2fd,stroke:#1976d2,color:#2c3e50 + classDef generation fill:#f3e5f5,stroke:#7b1fa2,color:#2c3e50 + classDef output fill:#e8f5e8,stroke:#388e3c,color:#2c3e50 + + class App,Lib1,Lib2,OS artifact + class Scanner,Analysis,Format generation + class CycloneDX,SPDX,Vulnerabilities,Licenses output +``` + +--- + +## ๐Ÿ“ Slide 25 โ€“ ๐Ÿท๏ธ Container Image Signing with Cosign/Notary + +* ๐Ÿท๏ธ **Container image signing** = cryptographic verification that **container images are authentic** and **haven't been tampered with** +* ๐Ÿ”ง **Cosign (Sigstore)**: + * ๐ŸŒŸ **Keyless signing**: uses OIDC identity providers, no long-term key management + * ๐Ÿ”— **Transparency log**: public ledger of all signatures for auditability + * ๐ŸŽฏ **OCI-compliant**: works with any OCI-compatible container registry + * ๐Ÿ†“ **Open source**: developed by Linux Foundation, widely adopted +* ๐Ÿณ **Docker Content Trust (Notary)**: + * ๐Ÿ›๏ธ **Established standard**: mature signing solution integrated with Docker + * ๐Ÿ”‘ **Key management**: requires managing signing keys and certificates + * ๐ŸŽฏ **Role-based signing**: different keys for different purposes (root, targets, snapshot) + * โš ๏ธ **Legacy concerns**: less active development, complex key management +* ๐Ÿ›ก๏ธ **Image signing workflow**: + * ๐Ÿ—๏ธ **Build**: create container image in CI/CD pipeline + * โœ๏ธ **Sign**: cryptographically sign image before pushing to registry + * ๐Ÿ“ค **Push**: upload both image and signature to registry + * ๐Ÿ” **Verify**: deployment systems verify signature before pulling/running +* ๐Ÿ“Š **Adoption growth**: container image signing adoption increased **156% in 2023** ([CNCF Security Report](https://www.cncf.io/reports/cncf-annual-survey-2023/)) + +```mermaid +flowchart LR + subgraph "๐Ÿ—๏ธ Build & Sign" + Build[๐Ÿ”จ Build Image] + Sign[โœ๏ธ Sign with Cosign] + Identity[๐Ÿ†” OIDC Identity] + end + + subgraph "๐Ÿ“ฆ Registry" + Image[๐Ÿณ Container Image] + Signature[๐Ÿ” Digital Signature] + Transparency[๐Ÿ“‹ Transparency Log] + end + + subgraph "๐Ÿš€ Deploy & Verify" + Pull[๐Ÿ“ฅ Pull Image] + Verify[๐Ÿ” Verify Signature] + Deploy[๐ŸŒŸ Deploy if Valid] + Reject[โŒ Reject if Invalid] + end + + Build --> Sign + Identity --> Sign + Sign --> Image + Sign --> Signature + Signature --> Transparency + Image --> Pull + Pull --> Verify + Verify --> Deploy + Verify --> Reject + + classDef build fill:#e3f2fd,stroke:#1976d2,color:#2c3e50 + classDef registry fill:#f3e5f5,stroke:#7b1fa2,color:#2c3e50 + classDef deploy fill:#e8f5e8,stroke:#388e3c,color:#2c3e50 + classDef reject fill:#ffebee,stroke:#d32f2f,color:#2c3e50 + + class Build,Sign,Identity build + class Image,Signature,Transparency registry + class Pull,Verify,Deploy deploy + class Reject reject +``` + +--- + +## ๐Ÿ“ Slide 26 โ€“ ๐Ÿงช Build Reproducibility & Deterministic Builds + +* ๐Ÿงช **Reproducible builds** = ability to **recreate identical artifacts** from same source code and build environment +* ๐ŸŽฏ **Benefits of reproducible builds**: + * ๐Ÿ” **Tamper detection**: compare official builds with independent rebuilds + * ๐Ÿ›ก๏ธ **Supply chain security**: verify no malicious code injection during build + * ๐Ÿ•ต๏ธ **Forensic analysis**: investigate security incidents by recreating exact build conditions + * ๐Ÿ“Š **Compliance**: meet regulatory requirements for software integrity +* โš ๏ธ **Challenges to reproducibility**: + * โฐ **Timestamps**: build tools embedding current time in artifacts + * ๐ŸŽฒ **Randomness**: random values, memory addresses, hash ordering + * ๐ŸŒ **Environment variation**: different OS versions, locale settings, timezone + * ๐Ÿ“ฆ **Dependency versions**: floating version numbers, latest tags +* ๐Ÿ› ๏ธ **Achieving reproducible builds**: + * ๐Ÿ”’ **Fixed environments**: containerized builds with pinned dependencies + * โฐ **Controlled timestamps**: use commit timestamp or fixed build date + * ๐Ÿ“‹ **Normalized outputs**: sort file lists, strip debug information + * ๐ŸŽฏ **Minimal environments**: reduce build environment complexity +* ๐Ÿ“Š **Industry adoption**: **42% of open-source projects** implementing reproducible builds ([Reproducible Builds Project](https://reproducible-builds.org/)) +* ๐Ÿ† **Success stories**: Debian, Bitcoin Core, Tor Browser achieve reproducible builds + +```mermaid +flowchart TD + subgraph "๐Ÿ“ Input Sources" + Source1[๐Ÿ“‚ Source Code v1.0] + Deps1[๐Ÿ“š Dependencies pinned] + Env1[๐Ÿ—๏ธ Build Environment] + end + + subgraph "๐Ÿญ Build Process" + Build1[โš™๏ธ Official Build] + Build2[โš™๏ธ Independent Build] + Controls[๐ŸŽฏ Reproducibility Controls] + end + + subgraph "๐Ÿ“ฆ Artifacts" + Artifact1[๐Ÿ“ฆ Official Artifact
Hash: abc123] + Artifact2[๐Ÿ“ฆ Independent Artifact
Hash: abc123] + Match[โœ… Identical Artifacts] + end + + Source1 --> Build1 + Deps1 --> Build1 + Env1 --> Build1 + + Source1 --> Build2 + Deps1 --> Build2 + Env1 --> Build2 + + Controls --> Build1 + Controls --> Build2 + + Build1 --> Artifact1 + Build2 --> Artifact2 + Artifact1 --> Match + Artifact2 --> Match + + classDef input fill:#e3f2fd,stroke:#1976d2,color:#2c3e50 + classDef build fill:#f3e5f5,stroke:#7b1fa2,color:#2c3e50 + classDef artifact fill:#e8f5e8,stroke:#388e3c,color:#2c3e50 + + class Source1,Deps1,Env1 input + class Build1,Build2,Controls build + class Artifact1,Artifact2,Match artifact +``` + +--- + +## ๐Ÿ“ Slide 27 โ€“ ๐Ÿ” Integrity Checks: Checksums, Hashes, and Verification + +* ๐Ÿ”ข **Integrity checks** = mathematical verification that **artifacts haven't been corrupted** or **maliciously modified** +* ๐Ÿงฎ **Hash algorithms for integrity**: + * ๐Ÿ”ข **SHA-256**: most common, cryptographically secure, 256-bit output + * ๐Ÿ”ข **SHA-512**: higher security, 512-bit output, slower but more secure + * โšก **BLAKE2/BLAKE3**: modern alternatives, faster than SHA with same security + * โŒ **MD5/SHA-1**: deprecated due to collision vulnerabilities +* ๐Ÿ“Š **Checksum implementation patterns**: + * ๐Ÿ“ **Manifest files**: separate files listing hashes for each artifact + * ๐Ÿท๏ธ **Registry metadata**: hashes stored alongside artifacts in repositories + * ๐Ÿ“‹ **SBOM integration**: checksums included in Software Bill of Materials + * ๐Ÿ”— **Chain of custody**: hash verification at each stage of pipeline +* ๐Ÿ›ก๏ธ **Verification best practices**: + * ๐ŸŽฏ **Multiple hash algorithms**: use different algorithms to detect sophisticated attacks + * ๐Ÿ” **Pre-deployment verification**: always verify before deployment/installation + * ๐Ÿ“Š **Automated checking**: integrate verification into CI/CD pipeline + * ๐Ÿ“ **Audit logging**: log all verification results for compliance +* โš ๏ธ **Hash collision attacks**: birthday attacks, chosen-prefix attacks against weak algorithms +* ๐Ÿ“ˆ **Performance considerations**: balance security vs. speed for different use cases + +```mermaid +flowchart LR + subgraph "๐Ÿ“ฆ Artifact Creation" + Artifact[๐Ÿ—‚๏ธ Build Artifact] + Hash1[๐Ÿ”ข SHA-256 Hash] + Hash2[๐Ÿ”ข SHA-512 Hash] + Manifest[๐Ÿ“‹ Checksum Manifest] + end + + subgraph "๐Ÿ—„๏ธ Storage & Distribution" + Registry[๐Ÿ“š Artifact Registry] + CDN[๐ŸŒ Content Distribution] + Mirror[๐Ÿชž Mirror Sites] + end + + subgraph "โœ… Verification Process" + Download[๐Ÿ“ฅ Download Artifact] + Calculate[๐Ÿงฎ Calculate Hash] + Compare[โš–๏ธ Compare Hashes] + Result[โœ… Verify Integrity] + end + + Artifact --> Hash1 + Artifact --> Hash2 + Hash1 --> Manifest + Hash2 --> Manifest + + Artifact --> Registry + Manifest --> Registry + Registry --> CDN + Registry --> Mirror + + CDN --> Download + Mirror --> Download + Download --> Calculate + Registry --> Compare + Calculate --> Compare + Compare --> Result + + classDef creation fill:#e3f2fd,stroke:#1976d2,color:#2c3e50 + classDef storage fill:#f3e5f5,stroke:#7b1fa2,color:#2c3e50 + classDef verify fill:#e8f5e8,stroke:#388e3c,color:#2c3e50 + + class Artifact,Hash1,Hash2,Manifest creation + class Registry,CDN,Mirror storage + class Download,Calculate,Compare,Result verify +``` + +--- + +## ๐Ÿ“ Slide 28 โ€“ ๐Ÿ“Š Artifact Provenance & Supply Chain Transparency + +* ๐Ÿ“Š **Provenance** = comprehensive record of **how, when, where, and by whom** an artifact was created +* ๐Ÿ”— **Supply chain transparency components**: + * ๐Ÿ‘จโ€๐Ÿ’ป **Build actor**: who or what system performed the build + * ๐Ÿ“‚ **Source materials**: exact source code, dependencies, and build inputs + * ๐Ÿ—๏ธ **Build environment**: operating system, tools, configuration used + * โฐ **Temporal information**: when build occurred, duration, sequence +* ๐Ÿ“‹ **SLSA (Supply-chain Levels for Software Artifacts)**: + * ๐Ÿ“Š **SLSA Level 1**: basic provenance, automated builds + * ๐Ÿ“Š **SLSA Level 2**: tamper resistance, hosted build service + * ๐Ÿ“Š **SLSA Level 3**: hardened builds, non-forgeable provenance + * ๐Ÿ“Š **SLSA Level 4**: highest security, two-person review, hermetic builds +* ๐Ÿ› ๏ธ **Provenance technologies**: + * ๐Ÿ”— **in-toto**: framework for securing software supply chain integrity + * ๐ŸŒŸ **SLSA attestations**: standardized format for build provenance + * ๐Ÿ“œ **Sigstore Rekor**: transparency log for storing provenance data + * โ˜๏ธ **Cloud build provenance**: native support in major cloud platforms +* ๐ŸŽฏ **Use cases for provenance**: + * ๐Ÿ•ต๏ธ **Incident response**: trace compromised artifacts to source + * ๐Ÿ“Š **Risk assessment**: evaluate supply chain security posture + * โš–๏ธ **Compliance**: meet regulatory requirements for software traceability + * ๐Ÿ” **Vulnerability management**: quickly identify affected systems +* ๐Ÿ“ˆ **Industry momentum**: **67% of Fortune 500** planning provenance implementation by 2025 ([Linux Foundation Report](https://www.linuxfoundation.org/research/)) + +```mermaid +flowchart TD + subgraph "๐Ÿ” Provenance Collection" + Actor[๐Ÿ‘จโ€๐Ÿ’ป Build Actor
CI/CD System] + Source[๐Ÿ“‚ Source Code
Git Commit SHA] + Environment[๐Ÿ—๏ธ Build Environment
OS, Tools, Config] + Time[โฐ Temporal Data
Timestamps, Duration] + end + + subgraph "๐Ÿ“‹ Attestation Creation" + Collect[๐Ÿ”„ Collect Metadata] + Format[๐Ÿ“ SLSA Format] + Sign[โœ๏ธ Sign Attestation] + end + + subgraph "๐ŸŒ Transparency & Storage" + Rekor[๐Ÿ“‹ Rekor Log
Immutable Record] + Registry[๐Ÿ—„๏ธ Artifact Registry
Linked Attestation] + Consumer[๐Ÿ‘ฅ Consumers
Verification & Trust] + end + + Actor --> Collect + Source --> Collect + Environment --> Collect + Time --> Collect + + Collect --> Format + Format --> Sign + Sign --> Rekor + Sign --> Registry + Registry --> Consumer + Rekor --> Consumer + + classDef collection fill:#e3f2fd,stroke:#1976d2,color:#2c3e50 + classDef attestation fill:#f3e5f5,stroke:#7b1fa2,color:#2c3e50 + classDef transparency fill:#e8f5e8,stroke:#388e3c,color:#2c3e50 + + class Actor,Source,Environment,Time collection + class Collect,Format,Sign attestation + class Rekor,Registry,Consumer transparency +``` + +--- + +## ๐Ÿ“‚ Group 5: Quality Gates & Automated Security Controls + +## ๐Ÿ“ Slide 29 โ€“ ๐Ÿšฆ Quality Gates: Definition and Implementation + +* ๐Ÿšฆ **Quality Gates** = automated **decision points** in CI/CD pipeline that **block progression** if predefined criteria not met +* ๐ŸŽฏ **Purpose of quality gates**: + * ๐Ÿ›‘ **Prevent defective code**: stop buggy or insecure code from reaching production + * ๐Ÿ“Š **Enforce standards**: ensure code meets organizational quality requirements + * ๐Ÿ”„ **Fail fast**: catch issues early when they're cheaper and easier to fix + * ๐Ÿ“ˆ **Continuous improvement**: provide feedback for development process optimization +* ๐Ÿงฉ **Common quality gate criteria**: + * ๐Ÿงช **Test coverage**: minimum percentage of code covered by automated tests + * ๐Ÿ› **Bug thresholds**: maximum number of critical/high severity issues + * ๐Ÿ“Š **Code quality metrics**: complexity, maintainability, duplication limits + * ๐Ÿ”’ **Security standards**: vulnerability counts, security policy compliance +* โš™๏ธ **Implementation approaches**: + * ๐Ÿ”ง **Pipeline stages**: dedicated quality check stages in CI/CD workflow + * ๐Ÿ“‹ **Policy engines**: centralized rules management with OPA, Sentinel + * ๐Ÿค– **Automated tools**: SonarQube, CodeClimate, Veracode integration + * ๐Ÿ‘ฅ **Manual approvals**: human review for critical deployment stages +* ๐Ÿ“Š **Industry adoption**: **91% of high-performing teams** use quality gates ([DORA State of DevOps Report](https://cloud.google.com/devops/state-of-devops/)) + +```mermaid +flowchart LR + subgraph "๐Ÿ—๏ธ Development" + Code[๐Ÿ’ป Code Commit] + Build[๐Ÿ”จ Build Process] + Tests[๐Ÿงช Automated Tests] + end + + subgraph "๐Ÿšฆ Quality Gates" + Gate1[๐ŸŽฏ Coverage Gate
โ‰ฅ80% Required] + Gate2[๐Ÿ› Bug Gate
0 Critical Issues] + Gate3[๐Ÿ”’ Security Gate
No High CVEs] + Gate4[๐Ÿ‘ฅ Manual Approval
Production Ready] + end + + subgraph "๐Ÿš€ Deployment" + Staging[๐Ÿงช Staging Deploy] + Production[๐ŸŒŸ Production Deploy] + end + + Code --> Build + Build --> Tests + Tests --> Gate1 + Gate1 -->|โœ… Pass| Gate2 + Gate1 -->|โŒ Fail| Code + Gate2 -->|โœ… Pass| Gate3 + Gate2 -->|โŒ Fail| Code + Gate3 -->|โœ… Pass| Gate4 + Gate3 -->|โŒ Fail| Code + Gate4 -->|โœ… Approved| Staging + Gate4 -->|โŒ Rejected| Code + Staging --> Production + + classDef dev fill:#e3f2fd,stroke:#1976d2,color:#2c3e50 + classDef gate fill:#fff3e0,stroke:#f57c00,color:#2c3e50 + classDef deploy fill:#e8f5e8,stroke:#388e3c,color:#2c3e50 + + class Code,Build,Tests dev + class Gate1,Gate2,Gate3,Gate4 gate + class Staging,Production deploy +``` + +--- + +## ๐Ÿ“ Slide 30 โ€“ ๐Ÿ”’ Security Gates vs. Quality Gates in CI/CD + +* ๐Ÿ”’ **Security Gates** = specialized quality gates focused on **security-specific criteria** and compliance requirements +* โš–๏ธ **Key differences**: + * ๐ŸŽฏ **Scope**: quality gates cover all aspects (performance, maintainability), security gates focus on vulnerabilities + * ๐Ÿ›๏ธ **Compliance**: security gates often tied to regulatory requirements (SOX, HIPAA, PCI-DSS) + * โฐ **Timing**: security gates may have different thresholds for different environments + * ๐Ÿ‘ฅ **Stakeholders**: security teams define criteria, development teams implement +* ๐Ÿ›ก๏ธ **Common security gate criteria**: + * ๐Ÿ” **Vulnerability scanning**: SAST, DAST, SCA results within acceptable limits + * ๐Ÿ”‘ **Secret detection**: zero exposed credentials or API keys + * ๐Ÿ“‹ **Policy compliance**: adherence to security policies and standards + * ๐Ÿท๏ธ **Artifact integrity**: signed artifacts, verified checksums, SBOM presence +* ๐ŸŽฏ **Risk-based approach**: + * ๐ŸŸข **Development**: lenient thresholds, focus on education and guidance + * ๐ŸŸก **Staging**: moderate thresholds, balance security with development velocity + * ๐Ÿ”ด **Production**: strict thresholds, zero tolerance for high-severity issues +* ๐Ÿ“Š **Implementation statistics**: **78% of organizations** implement security-specific gates ([Snyk State of Open Source Security](https://snyk.io/reports/open-source-security/)) + +```mermaid +flowchart TD + subgraph "๐ŸŽฏ Quality Gates (Broader Scope)" + QualityMetrics[๐Ÿ“Š Code Quality Metrics
Complexity, Coverage, Duplication] + Performance[โšก Performance Tests
Load Time, Memory Usage] + Functional[๐Ÿงช Functional Tests
Unit, Integration, E2E] + end + + subgraph "๐Ÿ”’ Security Gates (Security-Focused)" + Vulnerabilities[๐Ÿ” Vulnerability Scans
SAST, DAST, SCA Results] + Secrets[๐Ÿ”‘ Secret Detection
API Keys, Credentials] + Compliance[๐Ÿ“‹ Policy Compliance
SOX, HIPAA, PCI-DSS] + Integrity[๐Ÿท๏ธ Artifact Integrity
Signatures, Checksums] + end + + subgraph "๐ŸŒ Environment-Specific Thresholds" + Dev[๐ŸŸข Development
Lenient, Educational] + Stage[๐ŸŸก Staging
Moderate, Balanced] + Prod[๐Ÿ”ด Production
Strict, Zero Tolerance] + end + + QualityMetrics --> Dev + Performance --> Dev + Functional --> Stage + + Vulnerabilities --> Stage + Secrets --> Prod + Compliance --> Prod + Integrity --> Prod + + classDef quality fill:#e3f2fd,stroke:#1976d2,color:#2c3e50 + classDef security fill:#ffebee,stroke:#d32f2f,color:#2c3e50 + classDef environment fill:#f3e5f5,stroke:#7b1fa2,color:#2c3e50 + + class QualityMetrics,Performance,Functional quality + class Vulnerabilities,Secrets,Compliance,Integrity security + class Dev,Stage,Prod environment +``` + +--- + +## ๐Ÿ“ Slide 31 โ€“ โšก Automated Security Controls in Pipelines + +* โšก **Automated Security Controls** = security checks that run **without human intervention** as part of CI/CD pipeline +* ๐Ÿ”ง **Types of automated security controls**: + * ๐Ÿ” **Static Analysis**: SAST tools scanning source code for vulnerabilities + * ๐ŸŒ **Dynamic Analysis**: DAST tools testing running applications + * ๐Ÿ“ฆ **Dependency Scanning**: SCA tools checking third-party components + * ๐Ÿ”‘ **Secret Scanning**: detecting exposed credentials and API keys + * ๐Ÿ—๏ธ **Infrastructure Scanning**: IaC security analysis for misconfigurations + * ๐Ÿ“‹ **Compliance Checking**: automated policy validation and audit trails +* ๐ŸŽฏ **Integration patterns**: + * ๐Ÿช **Pre-commit hooks**: local security checks before code submission + * ๐Ÿ”„ **Pipeline stages**: dedicated security scanning steps in CI/CD + * ๐Ÿ“Š **Continuous monitoring**: ongoing security assessment of deployed systems + * ๐Ÿšจ **Alerting and reporting**: automated notifications and security dashboards +* โœ… **Benefits of automation**: + * โšก **Speed**: faster feedback compared to manual security reviews + * ๐ŸŽฏ **Consistency**: standardized security checks across all projects + * ๐Ÿ“ˆ **Scalability**: handle large volumes of code and deployments + * ๐Ÿ”„ **Continuous protection**: security checks run on every change +* ๐Ÿ“Š **Effectiveness metrics**: automated controls catch **85% of common vulnerabilities** before production ([Veracode State of Software Security](https://www.veracode.com/state-of-software-security-report)) + +```mermaid +flowchart LR + subgraph "๐Ÿ“ Code Development" + Developer[๐Ÿ‘จโ€๐Ÿ’ป Developer] + Commit[๐Ÿ“ Code Commit] + PR[๐Ÿ”€ Pull Request] + end + + subgraph "๐Ÿ”„ Automated Security Pipeline" + PreCommit[๐Ÿช Pre-commit Hooks
Secrets, Linting] + SAST[๐Ÿ” SAST Scan
Code Vulnerabilities] + SCA[๐Ÿ“ฆ SCA Scan
Dependencies] + DAST[๐ŸŒ DAST Scan
Running App] + IaC[๐Ÿ—๏ธ IaC Scan
Infrastructure] + end + + subgraph "๐Ÿ“Š Results & Actions" + Dashboard[๐Ÿ“ˆ Security Dashboard] + Alerts[๐Ÿšจ Automated Alerts] + Block[๐Ÿ›‘ Block Deployment] + Approve[โœ… Approve & Deploy] + end + + Developer --> PreCommit + PreCommit --> Commit + Commit --> PR + PR --> SAST + SAST --> SCA + SCA --> DAST + DAST --> IaC + + SAST --> Dashboard + SCA --> Dashboard + DAST --> Alerts + IaC --> Dashboard + + Dashboard --> Block + Dashboard --> Approve + Alerts --> Block + + classDef dev fill:#e3f2fd,stroke:#1976d2,color:#2c3e50 + classDef security fill:#f3e5f5,stroke:#7b1fa2,color:#2c3e50 + classDef results fill:#e8f5e8,stroke:#388e3c,color:#2c3e50 + + class Developer,Commit,PR dev + class PreCommit,SAST,SCA,DAST,IaC security + class Dashboard,Alerts,Block,Approve results +``` + +--- + +## ๐Ÿ“ Slide 32 โ€“ ๐Ÿ“ˆ Policy-as-Code for Build Security + +* ๐Ÿ“ˆ **Policy-as-Code** = defining and enforcing security policies through **version-controlled, executable code** +* ๐ŸŽฏ **Core benefits**: + * ๐Ÿ“‚ **Version control**: policies tracked, reviewed, and rolled back like application code + * ๐Ÿ”„ **Consistency**: same policies applied across all environments and teams + * ๐Ÿค– **Automation**: policies automatically enforced without manual intervention + * ๐Ÿ‘ฅ **Collaboration**: security and development teams jointly define policies +* ๐Ÿ› ๏ธ **Policy-as-Code tools and frameworks**: + * ๐Ÿ”ง **Open Policy Agent (OPA)**: general-purpose policy engine with Rego language + * ๐Ÿ›๏ธ **HashiCorp Sentinel**: policy framework integrated with Terraform and Vault + * โ˜๏ธ **Cloud-native**: AWS Config Rules, Azure Policy, GCP Organization Policy + * ๐Ÿ”’ **Specialized tools**: Falco for runtime security, Conftest for configuration testing +* ๐Ÿ“‹ **Common policy types for CI/CD**: + * ๐Ÿ” **Security policies**: vulnerability thresholds, encryption requirements + * ๐Ÿ›๏ธ **Compliance policies**: regulatory requirements (GDPR, SOX, HIPAA) + * ๐Ÿ’ฐ **Cost policies**: resource limits, budget constraints + * ๐Ÿ›ก๏ธ **Operational policies**: deployment windows, approval requirements +* ๐ŸŽฏ **Implementation workflow**: + * ๐Ÿ“ **Define**: write policies in domain-specific language + * ๐Ÿงช **Test**: validate policies against test scenarios + * ๐Ÿš€ **Deploy**: integrate policies into CI/CD pipeline + * ๐Ÿ“Š **Monitor**: track policy violations and effectiveness +* ๐Ÿ“Š **Adoption trend**: **64% of enterprises** implementing Policy-as-Code by 2024 ([Gartner Infrastructure Automation Survey](https://www.gartner.com/en/information-technology)) + +```mermaid +flowchart TD + subgraph "๐Ÿ“ Policy Definition" + SecurityTeam[๐Ÿ›ก๏ธ Security Team] + DevTeam[๐Ÿ‘จโ€๐Ÿ’ป Development Team] + PolicyRepo[๐Ÿ“‚ Policy Repository] + end + + subgraph "๐Ÿ”ง Policy Engine" + OPA[๐Ÿ”ง Open Policy Agent] + Sentinel[๐Ÿ›๏ธ HashiCorp Sentinel] + CloudPolicy[โ˜๏ธ Cloud Native Policies] + end + + subgraph "๐Ÿš€ Enforcement Points" + PreDeploy[๐Ÿ” Pre-deployment Check] + Runtime[โšก Runtime Validation] + Compliance[๐Ÿ“‹ Compliance Audit] + end + + subgraph "๐Ÿ“Š Monitoring & Feedback" + Violations[โš ๏ธ Policy Violations] + Reports[๐Ÿ“ˆ Compliance Reports] + Improvement[๐Ÿ”„ Policy Refinement] + end + + SecurityTeam --> PolicyRepo + DevTeam --> PolicyRepo + PolicyRepo --> OPA + PolicyRepo --> Sentinel + PolicyRepo --> CloudPolicy + + OPA --> PreDeploy + Sentinel --> PreDeploy + CloudPolicy --> Runtime + + PreDeploy --> Violations + Runtime --> Violations + Runtime --> Compliance + + Violations --> Reports + Compliance --> Reports + Reports --> Improvement + Improvement --> PolicyRepo + + classDef definition fill:#e3f2fd,stroke:#1976d2,color:#2c3e50 + classDef engine fill:#f3e5f5,stroke:#7b1fa2,color:#2c3e50 + classDef enforcement fill:#fff3e0,stroke:#f57c00,color:#2c3e50 + classDef monitoring fill:#e8f5e8,stroke:#388e3c,color:#2c3e50 + + class SecurityTeam,DevTeam,PolicyRepo definition + class OPA,Sentinel,CloudPolicy engine + class PreDeploy,Runtime,Compliance enforcement + class Violations,Reports,Improvement monitoring +``` + +--- + +## ๐Ÿ“ Slide 33 โ€“ ๐Ÿ›‘ Breaking Builds on Security Policy Violations + +* ๐Ÿ›‘ **Build breaking** = automatically **stopping CI/CD pipeline** when security policies are violated +* ๐ŸŽฏ **When to break builds**: + * ๐Ÿ”ด **Critical vulnerabilities**: CVSS score โ‰ฅ 9.0 or actively exploited vulnerabilities + * ๐Ÿ”‘ **Exposed secrets**: API keys, passwords, certificates found in code + * ๐Ÿ“‹ **Compliance violations**: regulatory requirement breaches (PCI-DSS, HIPAA) + * ๐Ÿท๏ธ **Unsigned artifacts**: missing digital signatures on production deployments +* โš–๏ธ **Risk-based approach to build breaking**: + * ๐ŸŸข **Development branches**: warnings and guidance, minimal build breaking + * ๐ŸŸก **Feature branches**: moderate enforcement, break on high-severity issues + * ๐Ÿ”ด **Main/production branches**: strict enforcement, break on any policy violation +* ๐Ÿ› ๏ธ **Implementation strategies**: + * ๐Ÿ“Š **Graduated enforcement**: increase strictness closer to production + * ๐Ÿ• **Grace periods**: allow time for teams to adapt to new policies + * ๐Ÿ”„ **Override mechanisms**: emergency bypasses with proper approval and audit + * ๐Ÿ“š **Developer education**: provide clear guidance on fixing violations +* ๐Ÿ“ˆ **Benefits vs. challenges**: + * โœ… **Benefits**: prevents security issues reaching production, enforces standards + * โš ๏ธ **Challenges**: potential developer productivity impact, false positives +* ๐Ÿ“Š **Industry practice**: **87% of organizations** break builds on critical security issues ([GitLab DevSecOps Survey](https://about.gitlab.com/developer-survey/)) + +```mermaid +flowchart TD + subgraph "๐Ÿ” Security Scanning" + CodeScan[๐Ÿ“ Code Analysis] + DepScan[๐Ÿ“ฆ Dependency Scan] + SecretScan[๐Ÿ”‘ Secret Detection] + ComplianceScan[๐Ÿ“‹ Compliance Check] + end + + subgraph "๐Ÿ“Š Policy Evaluation" + Critical[๐Ÿ”ด Critical Issues
CVSS โ‰ฅ 9.0] + High[๐ŸŸก High Issues
CVSS 7.0-8.9] + Medium[๐ŸŸข Medium Issues
CVSS 4.0-6.9] + Low[โšช Low Issues
CVSS < 4.0] + end + + subgraph "๐ŸŽฏ Decision Logic" + ProdBranch[๐Ÿ”ด Production Branch
Strict Enforcement] + FeatureBranch[๐ŸŸก Feature Branch
Moderate Enforcement] + DevBranch[๐ŸŸข Dev Branch
Lenient Enforcement] + end + + subgraph "๐Ÿšฆ Build Actions" + Break[๐Ÿ›‘ Break Build
Block Deployment] + Warn[โš ๏ธ Warning Only
Continue with Alert] + Pass[โœ… Pass
Continue Normally] + end + + CodeScan --> Critical + DepScan --> High + SecretScan --> Critical + ComplianceScan --> High + + Critical --> ProdBranch + High --> FeatureBranch + Medium --> DevBranch + Low --> DevBranch + + ProdBranch --> Break + FeatureBranch --> Warn + DevBranch --> Pass + + classDef scanning fill:#e3f2fd,stroke:#1976d2,color:#2c3e50 + classDef policy fill:#f3e5f5,stroke:#7b1fa2,color:#2c3e50 + classDef decision fill:#fff3e0,stroke:#f57c00,color:#2c3e50 + classDef action fill:#e8f5e8,stroke:#388e3c,color:#2c3e50 + + class CodeScan,DepScan,SecretScan,ComplianceScan scanning + class Critical,High,Medium,Low policy + class ProdBranch,FeatureBranch,DevBranch decision + class Break,Warn,Pass action +``` + +--- + +## ๐Ÿ“ Slide 34 โ€“ ๐Ÿ“Š Security Metrics & KPIs for Pipeline Health + +* ๐Ÿ“Š **Security KPIs (Key Performance Indicators)** = measurable values that track **security effectiveness** in CI/CD pipelines +* ๐ŸŽฏ **Leading indicators** (predict future security issues): + * โฑ๏ธ **Mean Time to Fix (MTTF)**: average time to resolve security vulnerabilities + * ๐Ÿ“ˆ **Vulnerability detection rate**: percentage of vulnerabilities caught in pipeline vs. production + * ๐Ÿ” **Security test coverage**: percentage of code covered by security-focused tests + * ๐Ÿƒโ€โ™‚๏ธ **Security debt**: accumulation of known but unaddressed security issues +* ๐Ÿ“Š **Lagging indicators** (measure security outcomes): + * ๐Ÿ› **Escaped defects**: security issues that reach production + * ๐Ÿšจ **Security incidents**: actual breaches or exploitation attempts + * โฐ **Vulnerability age**: how long security issues remain unpatched + * ๐Ÿ’ฐ **Security-related downtime**: service disruptions due to security issues +* ๐Ÿ“ˆ **Operational metrics**: + * ๐Ÿ”„ **Pipeline security scan frequency**: how often security checks run + * ๐Ÿ›‘ **Build break rate**: percentage of builds stopped due to security issues + * ๐Ÿ‘ฅ **Developer engagement**: participation in security training and practices + * ๐Ÿ† **Policy compliance rate**: adherence to security policies and standards +* ๐ŸŽฏ **Industry benchmarks**: + * ๐Ÿ† **High performers**: MTTF < 24 hours, >95% vulnerability detection in pipeline + * ๐Ÿ“Š **Average performers**: MTTF 1-7 days, 80-95% detection rate + * ๐Ÿ“‰ **Low performers**: MTTF > 7 days, <80% detection rate +* ๐Ÿ”— **Measurement tools**: DORA metrics, SOAR platforms, security dashboards + +```mermaid +flowchart LR + subgraph "๐ŸŽฏ Leading Indicators (Predictive)" + MTTF[โฑ๏ธ Mean Time to Fix
Target: < 24 hours] + DetectionRate[๐Ÿ“ˆ Detection Rate
Target: > 95%] + Coverage[๐Ÿ” Security Coverage
Target: > 80%] + Debt[๐Ÿƒโ€โ™‚๏ธ Security Debt
Target: Decreasing] + end + + subgraph "๐Ÿ“Š Lagging Indicators (Outcome)" + Escaped[๐Ÿ› Escaped Defects
Target: < 5%] + Incidents[๐Ÿšจ Security Incidents
Target: 0 critical] + VulnAge[โฐ Vulnerability Age
Target: < 30 days] + Downtime[๐Ÿ’ฐ Security Downtime
Target: < 0.1%] + end + + subgraph "โš™๏ธ Operational Metrics" + ScanFreq[๐Ÿ”„ Scan Frequency
Every commit] + BreakRate[๐Ÿ›‘ Build Break Rate
5-10% target] + Engagement[๐Ÿ‘ฅ Developer Engagement
Training completion] + Compliance[๐Ÿ† Policy Compliance
>98% target] + end + + subgraph "๐Ÿ“ˆ Performance Tiers" + HighPerf[๐Ÿ† High Performers
MTTF < 24h, >95% detection] + AvgPerf[๐Ÿ“Š Average Performers
MTTF 1-7d, 80-95% detection] + LowPerf[๐Ÿ“‰ Low Performers
MTTF > 7d, <80% detection] + end + + MTTF --> HighPerf + DetectionRate --> HighPerf + Coverage --> AvgPerf + Debt --> LowPerf + + classDef leading fill:#e3f2fd,stroke:#1976d2,color:#2c3e50 + classDef lagging fill:#f3e5f5,stroke:#7b1fa2,color:#2c3e50 + classDef operational fill:#fff3e0,stroke:#f57c00,color:#2c3e50 + classDef performance fill:#e8f5e8,stroke:#388e3c,color:#2c3e50 + + class MTTF,DetectionRate,Coverage,Debt leading + class Escaped,Incidents,VulnAge,Downtime lagging + class ScanFreq,BreakRate,Engagement,Compliance operational + class HighPerf,AvgPerf,LowPerf performance +``` + +--- + +## ๐Ÿ“‚ Group 6: Dependency Management & Software Composition Analysis + +## ๐Ÿ“ Slide 35 โ€“ ๐Ÿ“š Third-Party Dependency Security Risks + +* ๐Ÿ“š **Dependencies** = external libraries, frameworks, and components that applications rely on for functionality +* ๐ŸŽฏ **Why dependencies create security risks**: + * ๐Ÿฆ  **Inherited vulnerabilities**: security flaws in third-party code affect your application + * ๐Ÿ”— **Transitive dependencies**: dependencies of dependencies create deep, complex chains + * ๐ŸŒ **Supply chain exposure**: compromised upstream packages can poison entire ecosystems + * ๐Ÿ“Š **Scale complexity**: modern apps contain 100s-1000s of dependencies +* โš ๏ธ **Common dependency security issues**: + * ๐Ÿ› **Known vulnerabilities**: CVEs in popular libraries (Log4Shell, Struts, etc.) + * ๐Ÿฆ  **Malicious packages**: intentionally harmful code injected into package repositories + * ๐Ÿ”„ **Dependency confusion**: attackers exploit naming similarities to inject malicious packages + * โฐ **Outdated versions**: using old versions with known security issues + * ๐Ÿ”‘ **License violations**: legal risks from incompatible or restrictive licenses +* ๐Ÿ“Š **Scale of the problem**: + * ๐Ÿ“ฆ **Average application**: contains 500+ open-source components ([Sonatype Report](https://www.sonatype.com/state-of-the-software-supply-chain/)) + * ๐Ÿ› **Vulnerability growth**: 20,000+ new vulnerabilities discovered in open-source components annually + * ๐ŸŽฏ **Attack frequency**: 742% increase in supply chain attacks from 2019-2022 +* ๐Ÿ”— **Real-world impact**: Equifax breach (Apache Struts), SolarWinds attack (build tool compromise) + +```mermaid +flowchart TD + subgraph "๐Ÿ–ฅ๏ธ Your Application" + App[๐Ÿ’ป Main Application Code] + end + + subgraph "๐Ÿ“š Direct Dependencies" + Lib1[๐Ÿ“ฆ Web Framework v2.1] + Lib2[๐Ÿ“ฆ Database Driver v1.5] + Lib3[๐Ÿ“ฆ JSON Parser v3.2] + end + + subgraph "๐Ÿ”— Transitive Dependencies" + Trans1[๐Ÿ“ฆ HTTP Client v1.8] + Trans2[๐Ÿ“ฆ Crypto Library v2.0] + Trans3[๐Ÿ“ฆ XML Parser v1.2] + Trans4[๐Ÿ“ฆ Logging Framework v1.9] + end + + subgraph "โš ๏ธ Security Risks" + Vuln1[๐Ÿ› Known CVE in XML Parser] + Vuln2[๐Ÿฆ  Malicious Code in HTTP Client] + Vuln3[โฐ Outdated Crypto Library] + end + + App --> Lib1 + App --> Lib2 + App --> Lib3 + + Lib1 --> Trans1 + Lib1 --> Trans2 + Lib2 --> Trans3 + Lib3 --> Trans4 + + Trans1 --> Vuln2 + Trans2 --> Vuln3 + Trans3 --> Vuln1 + + classDef app fill:#e3f2fd,stroke:#1976d2,color:#2c3e50 + classDef direct fill:#f3e5f5,stroke:#7b1fa2,color:#2c3e50 + classDef transitive fill:#fff3e0,stroke:#f57c00,color:#2c3e50 + classDef risk fill:#ffebee,stroke:#d32f2f,color:#2c3e50 + + class App app + class Lib1,Lib2,Lib3 direct + class Trans1,Trans2,Trans3,Trans4 transitive + class Vuln1,Vuln2,Vuln3 risk +``` + +--- + +## ๐Ÿ“ Slide 36 โ€“ ๐Ÿ” Software Composition Analysis (SCA) in Build Pipelines + +* ๐Ÿ” **SCA = Software Composition Analysis** โ†’ automated identification and security assessment of **open-source and third-party components** +* ๐ŸŽฏ **SCA core capabilities**: + * ๐Ÿ“‹ **Inventory creation**: comprehensive list of all dependencies and versions + * ๐Ÿ› **Vulnerability detection**: matching components against known CVE databases + * โš–๏ธ **License analysis**: identifying licensing obligations and conflicts + * ๐Ÿ“Š **Risk assessment**: scoring components based on security, quality, and compliance factors +* ๐Ÿ› ๏ธ **Popular SCA tools**: + * ๐Ÿข **Commercial**: Snyk, Veracode, Checkmarx, JFrog Xray, Sonatype Nexus + * ๐Ÿ†“ **Open source**: OWASP Dependency-Check, GitHub Dependabot, GitLab Dependency Scanning + * โ˜๏ธ **Cloud-native**: AWS Inspector, Azure Security Center, Google Container Analysis +* โš™๏ธ **SCA integration in CI/CD**: + * ๐Ÿ“ **Pre-commit**: local scanning before code submission + * ๐Ÿ”„ **Build stage**: automated scanning during compilation + * ๐Ÿ“ฆ **Package stage**: scanning before artifact creation + * ๐Ÿš€ **Deployment**: scanning before production release +* ๐Ÿ“Š **Effectiveness metrics**: + * ๐ŸŽฏ **Coverage**: percentage of dependencies actively monitored + * โฑ๏ธ **Detection speed**: time from vulnerability disclosure to identification + * ๐Ÿ”„ **False positive rate**: accuracy of vulnerability identification +* ๐Ÿ“ˆ **Industry adoption**: **89% of organizations** use SCA tools in their CI/CD pipelines ([Synopsis OSSRA Report](https://www.synopsys.com/software-integrity/resources/analyst-reports/open-source-security-risk-analysis-report.html)) + +```mermaid +flowchart LR + subgraph "๐Ÿ“ Code Repository" + Code[๐Ÿ’ป Application Code] + ManifestFiles[๐Ÿ“‹ Dependency Manifests
package.json, pom.xml, requirements.txt] + LockFiles[๐Ÿ”’ Lock Files
package-lock.json, Pipfile.lock] + end + + subgraph "๐Ÿ” SCA Analysis Engine" + Scanner[๐Ÿ•ต๏ธ Component Scanner] + CVEDatabase[๐Ÿ—„๏ธ CVE Database
NVD, OSV, GitHub Advisory] + LicenseDB[โš–๏ธ License Database
SPDX, OSI Approved] + RiskEngine[๐Ÿ“Š Risk Assessment Engine] + end + + subgraph "๐Ÿ“Š SCA Outputs" + Inventory[๐Ÿ“‹ Component Inventory
SBOM Generation] + Vulnerabilities[๐Ÿ› Vulnerability Report
CVSS Scores, Exploitability] + Licenses[โš–๏ธ License Compliance
Obligations, Conflicts] + Recommendations[๐Ÿ’ก Remediation Guidance
Updates, Alternatives] + end + + Code --> Scanner + ManifestFiles --> Scanner + LockFiles --> Scanner + + Scanner --> CVEDatabase + Scanner --> LicenseDB + Scanner --> RiskEngine + + RiskEngine --> Inventory + CVEDatabase --> Vulnerabilities + LicenseDB --> Licenses + RiskEngine --> Recommendations + + classDef code fill:#e3f2fd,stroke:#1976d2,color:#2c3e50 + classDef analysis fill:#f3e5f5,stroke:#7b1fa2,color:#2c3e50 + classDef output fill:#e8f5e8,stroke:#388e3c,color:#2c3e50 + + class Code,ManifestFiles,LockFiles code + class Scanner,CVEDatabase,LicenseDB,RiskEngine analysis + class Inventory,Vulnerabilities,Licenses,Recommendations output +``` + +--- + +## ๐Ÿ“ Slide 37 โ€“ โš ๏ธ Vulnerability Scanning of Dependencies + +* โš ๏ธ **Dependency vulnerability scanning** = automated process of **identifying known security flaws** in third-party components +* ๐Ÿ” **Vulnerability data sources**: + * ๐Ÿ›๏ธ **NVD (National Vulnerability Database)**: US government's official CVE database + * ๐Ÿ”’ **OSV (Open Source Vulnerabilities)**: distributed vulnerability database for open source + * ๐Ÿ™ **GitHub Security Advisory**: platform-specific vulnerability data + * ๐Ÿข **Commercial feeds**: vendor-specific vulnerability intelligence (Snyk, VulnDB) +* ๐Ÿ“Š **CVSS scoring and prioritization**: + * ๐Ÿ”ด **Critical (9.0-10.0)**: immediate action required, likely remote code execution + * ๐ŸŸ  **High (7.0-8.9)**: priority fixing, significant security impact + * ๐ŸŸก **Medium (4.0-6.9)**: moderate risk, plan remediation + * ๐ŸŸข **Low (0.1-3.9)**: minimal risk, fix when convenient +* ๐ŸŽฏ **Advanced vulnerability assessment**: + * ๐Ÿ”ฅ **Exploit availability**: is there a known exploit in the wild? + * ๐ŸŽฏ **Reachability analysis**: is the vulnerable code actually used in your application? + * ๐ŸŒ **Environmental factors**: network exposure, data sensitivity, compliance requirements +* ๐Ÿ“ˆ **Scanning frequency patterns**: + * ๐Ÿ”„ **Continuous**: real-time monitoring of deployed applications + * ๐Ÿ“… **Daily**: scheduled scans for new vulnerabilities + * ๐Ÿ“ **On-demand**: triggered by code changes or security events +* ๐Ÿ“Š **Industry challenge**: average of **528 vulnerabilities** per application, with only 9.5% actually exploitable ([Veracode SOSS Report](https://www.veracode.com/state-of-software-security-report)) + +```mermaid +flowchart TD + subgraph "๐Ÿ“ฆ Component Identification" + App[๐Ÿ–ฅ๏ธ Application] + Components[๐Ÿ“š Component List
Name, Version, Location] + Fingerprint[๐Ÿ” Component Fingerprinting
Hashes, Metadata] + end + + subgraph "๐Ÿ—„๏ธ Vulnerability Databases" + NVD[๐Ÿ›๏ธ NVD Database
Official CVE Data] + OSV[๐Ÿ”’ OSV Database
Open Source Focus] + GitHub[๐Ÿ™ GitHub Advisory
Platform Specific] + Commercial[๐Ÿข Commercial Feeds
Enhanced Intelligence] + end + + subgraph "๐Ÿ“Š Risk Assessment" + CVSS[๐Ÿ“ˆ CVSS Scoring
0.1-10.0 Scale] + Exploitability[๐Ÿ”ฅ Exploit Availability
Public PoCs, Active Use] + Reachability[๐ŸŽฏ Code Reachability
Is Vulnerable Code Used?] + Context[๐ŸŒ Environmental Context
Exposure, Data Sensitivity] + end + + subgraph "๐Ÿšจ Actionable Results" + Critical[๐Ÿ”ด Critical Issues
Immediate Action] + High[๐ŸŸ  High Priority
Fix Soon] + Medium[๐ŸŸก Medium Priority
Plan Remediation] + Low[๐ŸŸข Low Priority
Fix When Convenient] + end + + App --> Components + Components --> Fingerprint + + Fingerprint --> NVD + Fingerprint --> OSV + Fingerprint --> GitHub + Fingerprint --> Commercial + + NVD --> CVSS + OSV --> Exploitability + GitHub --> Reachability + Commercial --> Context + + CVSS --> Critical + Exploitability --> Critical + Reachability --> High + Context --> Medium + CVSS --> Low + + classDef identification fill:#e3f2fd,stroke:#1976d2,color:#2c3e50 + classDef database fill:#f3e5f5,stroke:#7b1fa2,color:#2c3e50 + classDef assessment fill:#fff3e0,stroke:#f57c00,color:#2c3e50 + classDef results fill:#e8f5e8,stroke:#388e3c,color:#2c3e50 + + class App,Components,Fingerprint identification + class NVD,OSV,GitHub,Commercial database + class CVSS,Exploitability,Reachability,Context assessment + class Critical,High,Medium,Low results +``` + +--- + +## ๐Ÿ“ Slide 38 โ€“ ๐Ÿ“‹ License Compliance Scanning & Management + +* ๐Ÿ“‹ **License compliance** = ensuring all third-party components comply with **legal and organizational licensing policies** +* โš–๏ธ **Common open-source license types**: + * ๐Ÿ†“ **Permissive licenses**: MIT, Apache 2.0, BSD โ†’ minimal restrictions, commercial-friendly + * ๐Ÿ”„ **Copyleft licenses**: GPL v2/v3, AGPL โ†’ require source code sharing of derivatives + * ๐Ÿข **Commercial licenses**: proprietary software requiring payment or specific terms + * ๐Ÿšซ **Prohibited licenses**: organization-specific restrictions (e.g., AGPL banned in some companies) +* โš ๏ธ **License compliance risks**: + * โš–๏ธ **Legal liability**: using incompatible licenses can result in lawsuits + * ๐Ÿ“ค **Forced disclosure**: copyleft licenses may require sharing proprietary code + * ๐Ÿ’ฐ **Financial penalties**: violation of commercial license terms + * ๐Ÿข **Reputation damage**: public license violations harm company credibility +* ๐Ÿ› ๏ธ **License scanning tools**: + * ๐Ÿ”ง **FOSSA**: comprehensive license compliance platform + * ๐Ÿ“Š **Black Duck**: Synopsys license and security scanning + * ๐Ÿ†“ **licensee**: GitHub's open-source license detection library + * โš™๏ธ **scancode-toolkit**: open-source license and copyright scanner +* ๐Ÿ“Š **Compliance automation**: + * ๐Ÿ“‹ **Policy definition**: create organizational license policies + * ๐Ÿ” **Automated scanning**: integrate license detection in CI/CD + * ๐Ÿšจ **Violation alerts**: notify teams of license conflicts + * ๐Ÿ“ **Compliance reports**: generate legal documentation for audits +* ๐Ÿ“ˆ **Industry statistics**: **65% of codebases** contain license policy violations ([Synopsis OSSRA 2024](https://www.synopsys.com/software-integrity/resources/analyst-reports/open-source-security-risk-analysis-report.html)) + +```mermaid +flowchart LR + subgraph "๐Ÿ“ฆ Component Analysis" + Dependencies[๐Ÿ“š Project Dependencies] + LicenseDetection[๐Ÿ” License Detection
Source Code, Metadata] + LicenseDB[๐Ÿ—„๏ธ License Database
SPDX, OSI, Custom] + end + + subgraph "๐Ÿ“‹ License Categories" + Permissive[๐Ÿ†“ Permissive
MIT, Apache 2.0, BSD] + Copyleft[๐Ÿ”„ Copyleft
GPL v2/v3, AGPL] + Commercial[๐Ÿข Commercial
Proprietary, Paid] + Unknown[โ“ Unknown
Unidentified, Custom] + end + + subgraph "โš–๏ธ Policy Engine" + OrgPolicy[๐Ÿ›๏ธ Organizational Policy
Approved, Restricted, Banned] + RiskAssessment[๐Ÿ“Š Risk Assessment
Legal, Commercial Impact] + ConflictDetection[โš ๏ธ Conflict Detection
License Incompatibilities] + end + + subgraph "๐Ÿ“Š Compliance Results" + Approved[โœ… Approved
Policy Compliant] + Review[๐Ÿ‘ฅ Manual Review
Requires Legal Input] + Violation[๐Ÿšซ Policy Violation
Must Remove/Replace] + Report[๐Ÿ“ Compliance Report
Legal Documentation] + end + + Dependencies --> LicenseDetection + LicenseDetection --> LicenseDB + + LicenseDB --> Permissive + LicenseDB --> Copyleft + LicenseDB --> Commercial + LicenseDB --> Unknown + + Permissive --> OrgPolicy + Copyleft --> RiskAssessment + Commercial --> ConflictDetection + Unknown --> RiskAssessment + + OrgPolicy --> Approved + RiskAssessment --> Review + ConflictDetection --> Violation + OrgPolicy --> Report + + classDef analysis fill:#e3f2fd,stroke:#1976d2,color:#2c3e50 + classDef categories fill:#f3e5f5,stroke:#7b1fa2,color:#2c3e50 + classDef policy fill:#fff3e0,stroke:#f57c00,color:#2c3e50 + classDef results fill:#e8f5e8,stroke:#388e3c,color:#2c3e50 + + class Dependencies,LicenseDetection,LicenseDB analysis + class Permissive,Copyleft,Commercial,Unknown categories + class OrgPolicy,RiskAssessment,ConflictDetection policy + class Approved,Review,Violation,Report results +``` + +--- + +## ๐Ÿ“ Slide 39 โ€“ ๐Ÿ”„ Automated Dependency Updates & Patch Management + +* ๐Ÿ”„ **Automated dependency updates** = systematic process of **keeping third-party components current** with latest security patches +* ๐ŸŽฏ **Update automation benefits**: + * ๐Ÿ›ก๏ธ **Faster security patching**: reduce window of vulnerability exposure + * โฐ **Reduced manual effort**: eliminate time-consuming manual update processes + * ๐ŸŽฏ **Consistent updates**: ensure all projects follow same update patterns + * ๐Ÿ“Š **Improved visibility**: track update status across entire organization +* ๐Ÿ› ๏ธ **Automated update tools**: + * ๐Ÿค– **Dependabot**: GitHub's automated dependency update service + * ๐Ÿ”„ **Renovate**: comprehensive dependency update automation platform + * ๐ŸฆŠ **GitLab Dependency Updates**: integrated GitLab dependency management + * โ˜๏ธ **Snyk Open Source**: automated fix PRs with vulnerability context +* โš™๏ธ **Update strategies**: + * ๐ŸŸข **Patch updates**: automated security patches (1.2.3 โ†’ 1.2.4) + * ๐ŸŸก **Minor updates**: feature updates with review (1.2.0 โ†’ 1.3.0) + * ๐Ÿ”ด **Major updates**: breaking changes requiring manual intervention (1.x โ†’ 2.0) +* ๐Ÿ›ก๏ธ **Safety mechanisms**: + * ๐Ÿงช **Automated testing**: run full test suite before accepting updates + * ๐ŸŽฏ **Staged rollouts**: deploy to staging before production + * ๐Ÿ”„ **Rollback procedures**: quick reversion if updates cause issues + * ๐Ÿ‘ฅ **Review requirements**: human approval for high-risk updates +* ๐Ÿ“Š **Industry challenge**: **75% of vulnerabilities** remain unpatched 30 days after disclosure ([Veracode Fixing the Enterprise](https://www.veracode.com/resource/report/fixing-the-enterprise)) + +```mermaid +flowchart TD + subgraph "๐Ÿ” Vulnerability Detection" + CVEMonitor[๐Ÿšจ CVE Monitoring
New Vulnerabilities] + Scanner[๐Ÿ” Dependency Scanner
Current Components] + RiskAssess[๐Ÿ“Š Risk Assessment
CVSS + Context] + end + + subgraph "๐Ÿค– Update Automation" + UpdateBot[๐Ÿค– Update Bot
Dependabot, Renovate] + VersionAnalysis[๐Ÿ“ˆ Version Analysis
Patch, Minor, Major] + PRCreation[๐Ÿ”€ Pull Request Creation
Automated Updates] + end + + subgraph "๐Ÿ›ก๏ธ Safety Checks" + AutoTests[๐Ÿงช Automated Tests
Unit, Integration, Security] + PolicyCheck[๐Ÿ“‹ Policy Validation
License, Security Rules] + StagingDeploy[๐ŸŽญ Staging Deployment
Real-world Testing] + end + + subgraph "๐Ÿš€ Deployment Decision" + LowRisk[๐ŸŸข Low Risk
Auto-merge Patches] + MediumRisk[๐ŸŸก Medium Risk
Review Required] + HighRisk[๐Ÿ”ด High Risk
Manual Testing] + Emergency[๐Ÿšจ Emergency
Critical Security] + end + + CVEMonitor --> Scanner + Scanner --> RiskAssess + RiskAssess --> UpdateBot + + UpdateBot --> VersionAnalysis + VersionAnalysis --> PRCreation + PRCreation --> AutoTests + + AutoTests --> PolicyCheck + PolicyCheck --> StagingDeploy + + StagingDeploy --> LowRisk + StagingDeploy --> MediumRisk + StagingDeploy --> HighRisk + RiskAssess --> Emergency + + classDef detection fill:#e3f2fd,stroke:#1976d2,color:#2c3e50 + classDef automation fill:#f3e5f5,stroke:#7b1fa2,color:#2c3e50 + classDef safety fill:#fff3e0,stroke:#f57c00,color:#2c3e50 + classDef decision fill:#e8f5e8,stroke:#388e3c,color:#2c3e50 + + class CVEMonitor,Scanner,RiskAssess detection + class UpdateBot,VersionAnalysis,PRCreation automation + class AutoTests,PolicyCheck,StagingDeploy safety + class LowRisk,MediumRisk,HighRisk,Emergency decision +``` + +--- + +## ๐Ÿ“ Slide 40 โ€“ ๐Ÿ•ธ๏ธ Dependency Confusion & Typosquatting Prevention + +* ๐Ÿ•ธ๏ธ **Dependency confusion** = attack where malicious packages with **higher version numbers** are published to **public repositories** with same names as **internal packages** +* ๐ŸŽฏ **Typosquatting** = creating malicious packages with **similar names** to popular legitimate packages (e.g., "reqeusts" instead of "requests") +* โš ๏ธ **Attack mechanisms**: + * ๐Ÿ“ฆ **Public package priority**: package managers often prefer public repositories over private ones + * ๐Ÿ”ข **Version precedence**: higher version numbers automatically selected + * ๐Ÿ”ค **Name similarity**: developers mistype package names in dependencies + * ๐Ÿค– **Automated scanning**: attackers monitor internal package names from public repositories +* ๐Ÿ›ก๏ธ **Prevention strategies**: + * ๐Ÿ—๏ธ **Package scoping**: use organizational scopes (@company/package-name) + * ๐Ÿ” **Repository prioritization**: configure package managers to prefer private repositories + * ๐Ÿšซ **Public repository blocking**: prevent accidental public package installation + * ๐Ÿ“‹ **Dependency pinning**: lock specific versions and sources in lockfiles + * ๐Ÿ” **Monitoring & alerting**: detect unauthorized package installations +* ๐Ÿ› ๏ธ **Technical mitigations**: + * ๐Ÿ“ฆ **npm**: use .npmrc with registry configuration and scoped packages + * ๐Ÿ **Python**: configure pip.conf with trusted hosts and index priorities + * โ˜• **Maven**: settings.xml with repository mirroring and blocking + * ๐Ÿ”ท **NuGet**: NuGet.Config with package source mapping +* ๐Ÿ“Š **Real-world impact**: **130+ malicious packages** discovered in npm registry targeting dependency confusion in 2023 ([ReversingLabs Research](https://www.reversinglabs.com/blog)) + +```mermaid +flowchart TD + subgraph "๐Ÿ˜ˆ Attack Scenarios" + Confusion[๐Ÿ•ธ๏ธ Dependency Confusion
internal-pkg v1.0 โ†’ malicious-pkg v2.0] + Typosquat[๐Ÿ”ค Typosquatting
lodash โ†’ lodahs, reqeusts] + AutoScan[๐Ÿค– Automated Scanning
Monitor for internal names] + end + + subgraph "๐Ÿ“ฆ Package Repositories" + Private[๐Ÿ” Private Repository
internal-package v1.0] + Public[๐ŸŒ Public Repository
npm, PyPI, Maven Central] + Malicious[โ˜ ๏ธ Malicious Packages
Higher versions, Similar names] + end + + subgraph "๐Ÿ›ก๏ธ Prevention Controls" + Scoping[๐Ÿ—๏ธ Package Scoping
@company/package-name] + RepoConfig[โš™๏ธ Repository Configuration
Private first, blocked public] + Pinning[๐Ÿ“Œ Version Pinning
Exact versions, checksums] + Monitoring[๐Ÿ” Package Monitoring
Unauthorized installation alerts] + end + + subgraph "๐Ÿ”ง Technical Implementation" + NPM[๐Ÿ“ฆ npm: .npmrc config
Registry priority, scoping] + Python[๐Ÿ Python: pip.conf
Trusted hosts, index order] + Maven[โ˜• Maven: settings.xml
Repository mirroring] + NuGet[๐Ÿ”ท NuGet: NuGet.Config
Package source mapping] + end + + Confusion --> Public + Typosquat --> Malicious + AutoScan --> Malicious + + Private --> Scoping + Public --> RepoConfig + Malicious --> Pinning + + Scoping --> NPM + RepoConfig --> Python + Pinning --> Maven + Monitoring --> NuGet + + classDef attack fill:#ffebee,stroke:#d32f2f,color:#2c3e50 + classDef repository fill:#f3e5f5,stroke:#7b1fa2,color:#2c3e50 + classDef prevention fill:#fff3e0,stroke:#f57c00,color:#2c3e50 + classDef implementation fill:#e8f5e8,stroke:#388e3c,color:#2c3e50 + + class Confusion,Typosquat,AutoScan attack + class Private,Public,Malicious repository + class Scoping,RepoConfig,Pinning,Monitoring prevention + class NPM,Python,Maven,NuGet implementation +``` + +--- + +--- diff --git a/lectures/lec5.md b/lectures/lec5.md new file mode 100644 index 00000000..3c7e91c1 --- /dev/null +++ b/lectures/lec5.md @@ -0,0 +1,1713 @@ +# ๐Ÿ“ŒLecture 5 - Application Security Testing Basics: SAST, DAST, IAST & Pipeline Integration + +## ๐Ÿ“‚ Group 1: Application Security Testing Foundations + +## ๐Ÿ“ Slide 1 โ€“ ๐Ÿ” What is Application Security Testing? (AST Overview) + +* ๐Ÿ” **Application Security Testing (AST)** = systematic evaluation of software applications to **identify security vulnerabilities** before they reach production. +* ๐ŸŽฏ **Core purpose**: find and fix security flaws **early and automatically** in the development process. +* ๐Ÿ“Š **Three main approaches**: + * ๐Ÿ”ฌ **Testing**: examining code/application behavior for known vulnerability patterns + * ๐Ÿ“ก **Scanning**: automated tools checking for security misconfigurations + * ๐Ÿง  **Analysis**: deep inspection of code logic and data flows +* ๐Ÿ“ˆ **Industry adoption**: **91% of organizations** now use automated security testing tools in development ([DevSecOps Survey 2024](https://www.devsecops.org/)) +* ๐Ÿ’ฐ **Business impact**: fixing vulnerabilities in development costs **100x less** than fixing in production ([NIST Study](https://www.nist.gov/system/files/documents/director/planning/report02-3.pdf)) +* ๐Ÿ”— **Learn more**: [OWASP Application Security Testing Guide](https://owasp.org/www-project-web-security-testing-guide/) + +```mermaid +flowchart LR + Dev[๐Ÿ‘จโ€๐Ÿ’ป Developer Code] --> AST[๐Ÿ” Application Security Testing] + AST --> SAST[๐Ÿ”ฌ Static Analysis] + AST --> DAST[๐ŸŒ Dynamic Testing] + AST --> IAST[๐Ÿงฌ Interactive Testing] + SAST --> Results[๐Ÿ“Š Security Findings] + DAST --> Results + IAST --> Results + Results --> Fix[๐Ÿ”ง Fix Vulnerabilities] + + classDef default fill:#f9f9f9,stroke:#333,stroke-width:2px,color:#2c3e50 +``` + +--- + +## ๐Ÿ“ Slide 2 โ€“ ๐Ÿ“ˆ Evolution of Application Security Testing + +* ๐Ÿ“… **1990s-2000s**: **Manual code reviews** by security experts โ†’ slow, expensive, inconsistent coverage. +* ๐Ÿ“… **2005-2010**: **First SAST tools** emerge โ†’ Fortify (2003), Veracode (2006) โ†’ automated source code analysis. +* ๐Ÿ“… **2010-2015**: **DAST tools mature** โ†’ OWASP ZAP (2010), commercial web app scanners proliferate. +* ๐Ÿ“… **2015-2020**: **DevSecOps integration** โ†’ CI/CD pipeline integration, shift-left movement accelerates. +* ๐Ÿ“… **2020-Present**: **AI-powered analysis** โ†’ machine learning reduces false positives, cloud-native testing emerges. +* ๐Ÿ“Š **Market growth**: AST market grew from **$2.1B in 2019** to **$8.2B in 2024** ([Gartner Security Report](https://www.gartner.com/en/information-technology/insights/application-security)) +* ๐Ÿš€ **Next frontier**: **Real-time security feedback** in IDEs, AI-assisted vulnerability remediation, quantum-safe crypto testing. + +```mermaid +timeline + title ๐Ÿ“ˆ Evolution of Application Security Testing + 1990s : ๐Ÿ“ Manual Code Reviews + : Security experts only + 2005 : ๐Ÿ”ฌ First SAST Tools + : Fortify, Veracode launch + 2010 : ๐ŸŒ DAST Tools Mature + : OWASP ZAP, web scanners + 2015 : ๐Ÿš€ DevSecOps Integration + : CI/CD pipeline adoption + 2020 : ๐Ÿค– AI-Powered Analysis + : ML reduces false positives + 2025 : ๐Ÿง  Next-Gen Testing + : Real-time IDE integration +``` + +--- + +## ๐Ÿ“ Slide 3 โ€“ ๐ŸŽฏ Types of Security Vulnerabilities We're Testing For + +* ๐Ÿงฉ **OWASP Top 10 vulnerabilities** โ†’ primary targets for AST tools: + * ๐Ÿ’‰ **Injection flaws**: SQL injection, command injection, LDAP injection + * ๐Ÿ”“ **Broken authentication**: weak passwords, session hijacking, credential stuffing + * ๐Ÿ“ค **Sensitive data exposure**: unencrypted data, weak crypto, information leakage + * ๐Ÿ”ง **Security misconfigurations**: default credentials, unnecessary services, verbose errors +* ๐Ÿ—๏ธ **Code-level vulnerabilities**: buffer overflows, race conditions, insecure randomness +* โšก **Runtime vulnerabilities**: memory corruption, privilege escalation, resource exhaustion +* ๐Ÿ› ๏ธ **Configuration issues**: cloud misconfigurations, container security, infrastructure-as-code flaws +* ๐Ÿ“Š **Business logic flaws**: authorization bypasses, workflow manipulation, price manipulation +* ๐Ÿ”— **Vulnerability databases**: [CVE Details](https://www.cvedetails.com/), [CWE List](https://cwe.mitre.org/), [OWASP Top 10](https://owasp.org/www-project-top-ten/) + +```mermaid +flowchart TD + subgraph "๐ŸŽฏ Vulnerability Categories" + OWASP[๐Ÿ† OWASP Top 10
Web App Vulnerabilities] + Code[๐Ÿ”ฌ Code-Level Issues
Memory, Logic Flaws] + Runtime[โšก Runtime Issues
Execution, Performance] + Config[๐Ÿ› ๏ธ Configuration
Cloud, Container, IaC] + Business[๐Ÿ“Š Business Logic
Workflow, Authorization] + end + + subgraph "๐Ÿ” Testing Approaches" + SAST[๐Ÿ”ฌ SAST
Finds Code Issues] + DAST[๐ŸŒ DAST
Finds Runtime Issues] + IAST[๐Ÿงฌ IAST
Finds Both Types] + Manual[๐Ÿ‘ค Manual Testing
Finds Business Logic] + end + + Code --> SAST + Runtime --> DAST + OWASP --> DAST + Config --> SAST + Business --> Manual + OWASP --> IAST + + classDef default fill:#f9f9f9,stroke:#333,stroke-width:2px,color:#2c3e50 + classDef testing fill:#e8f5e8,stroke:#2e7d32,stroke-width:2px,color:#2c3e50 + class SAST,DAST,IAST,Manual testing +``` + +--- + +## ๐Ÿ“ Slide 4 โ€“ โš–๏ธ Static vs. Dynamic vs. Interactive Testing Comparison + +* ๐Ÿ”ฌ **SAST (Static Application Security Testing)**: + * โœ… **Pros**: early detection, complete code coverage, fast feedback, no running app needed + * โŒ **Cons**: false positives, missing runtime context, configuration blind spots + * ๐ŸŽฏ **Best for**: injection flaws, hardcoded secrets, coding standard violations +* ๐ŸŒ **DAST (Dynamic Application Security Testing)**: + * โœ… **Pros**: real runtime conditions, finds configuration issues, business logic testing + * โŒ **Cons**: late-stage detection, limited code coverage, requires running application + * ๐ŸŽฏ **Best for**: authentication bypasses, session management, server misconfigurations +* ๐Ÿงฌ **IAST (Interactive Application Security Testing)**: + * โœ… **Pros**: combines SAST + DAST benefits, low false positives, precise vulnerability location + * โŒ **Cons**: performance overhead, deployment complexity, limited language support + * ๐ŸŽฏ **Best for**: comprehensive analysis during QA testing, runtime vulnerability validation +* ๐Ÿ“Š **Industry usage**: **67% use SAST**, **52% use DAST**, **23% use IAST** ([Synopsys DevSecOps Report 2024](https://www.synopsys.com/software-integrity/resources/analyst-reports/devsecops-report.html)) + +```mermaid +flowchart TD + subgraph "๐Ÿ”ฌ SAST - White Box" + SASTTime[โฐ Development Phase] + SASTCode[๐Ÿ“ Source Code Analysis] + SASTCover[๐Ÿ“Š 100% Code Coverage] + SASTFast[โšก Fast Execution] + end + + subgraph "๐ŸŒ DAST - Black Box" + DASTTime[โฐ Testing/Production Phase] + DASTApp[๐Ÿ–ฅ๏ธ Running Application] + DASTReal[๐ŸŒ Real Conditions] + DASTSlow[๐ŸŒ Slower Execution] + end + + subgraph "๐Ÿงฌ IAST - Gray Box" + IASTTime[โฐ QA Testing Phase] + IASTInstr[๐Ÿ”ง Instrumented Application] + IASTBoth[๐ŸŽฏ Code + Runtime Analysis] + IASTPerf[๐Ÿ“ˆ Performance Impact] + end + + classDef sast fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + classDef dast fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#2c3e50 + classDef iast fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + + class SASTTime,SASTCode,SASTCover,SASTFast sast + class DASTTime,DASTApp,DASTReal,DASTSlow dast + class IASTTime,IASTInstr,IASTBoth,IASTPerf iast +``` + +--- + +## ๐Ÿ“ Slide 5 โ€“ ๐Ÿงฉ The Testing Pyramid for Application Security + +* ๐Ÿ”บ **Security Testing Pyramid** โ†’ layered approach to comprehensive application security validation: + * ๐Ÿ—๏ธ **Base Layer**: **Unit Security Tests** โ†’ test individual functions for security flaws (80% of tests) + * ๐Ÿ”— **Middle Layer**: **Integration Security Tests** โ†’ test API endpoints, service interactions (15% of tests) + * ๐ŸŒ **Top Layer**: **End-to-End Security Tests** โ†’ full application workflow testing (4% of tests) + * ๐Ÿ‘ค **Apex**: **Manual Penetration Testing** โ†’ expert human testing for complex business logic (1% of effort) +* โšก **Pyramid principle**: **more tests at the bottom** = faster feedback, lower cost, better coverage +* ๐Ÿ› ๏ธ **Tool mapping**: + * ๐Ÿ—๏ธ **Unit level**: SAST tools, secure coding linters, dependency scanners + * ๐Ÿ”— **Integration level**: API security testing, DAST for services, IAST during integration tests + * ๐ŸŒ **E2E level**: Full DAST scans, automated penetration testing tools + * ๐Ÿ‘ค **Manual level**: Expert penetration testing, business logic review +* ๐Ÿ“Š **Cost efficiency**: unit tests cost **$1 to fix**, production fixes cost **$100+** ([IBM Systems Sciences Institute](https://www.ibm.com/garage/method/practices/code/tool_continuous_integration/)) + +```mermaid +graph TD + subgraph "๐Ÿงฉ Application Security Testing Pyramid" + Manual[๐Ÿ‘ค Manual Penetration Testing
๐ŸŽฏ Business Logic, Complex Scenarios
๐Ÿ’ฐ High Cost, 1% Effort] + E2E[๐ŸŒ End-to-End Security Tests
๐Ÿ” Full Application Workflows
๐Ÿ’ฐ Medium-High Cost, 4% Effort] + Integration[๐Ÿ”— Integration Security Tests
๐ŸŒ API, Service Interactions
๐Ÿ’ฐ Medium Cost, 15% Effort] + Unit[๐Ÿ—๏ธ Unit Security Tests
๐Ÿ”ฌ Individual Functions, Components
๐Ÿ’ฐ Low Cost, 80% Effort] + end + + subgraph "๐Ÿ› ๏ธ Tool Mapping" + ManualTools[๐Ÿ•ต๏ธ Expert Testers
๐Ÿง  Human Intelligence] + E2ETools[๐ŸŒ DAST Full Scans
๐Ÿค– Automated Pen Testing] + IntTools[๐Ÿ”— API Security Testing
๐Ÿงฌ IAST during Integration] + UnitTools[๐Ÿ”ฌ SAST, Linters
๐Ÿ“ฆ Dependency Scanning] + end + + Manual --> ManualTools + E2E --> E2ETools + Integration --> IntTools + Unit --> UnitTools + + classDef pyramid fill:#fff3e0,stroke:#f57c00,stroke-width:3px,color:#2c3e50 + classDef tools fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + classDef unit fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + + class Manual,E2E,Integration,Unit pyramid + class ManualTools,E2ETools,IntTools,UnitTools tools + class Unit unit +``` + +* ๐Ÿ”— **Learn more**: [Google Testing Blog - Test Pyramid](https://testing.googleblog.com/2015/04/just-say-no-to-more-end-to-end-tests.html), [Martin Fowler - Test Pyramid](https://martinfowler.com/articles/practical-test-pyramid.html) + +--- + +## ๐ŸŽ‰ **Fun Break: Security Testing Memes & Facts** + +### ๐Ÿ˜„ **"Why Security Testing is Like Going to the Dentist"** +* ๐Ÿฆท **Nobody wants to do it** โ†’ but everyone knows they should +* ๐Ÿ˜ฌ **It hurts more when you wait** โ†’ early testing = less painful fixes +* ๐Ÿ” **Prevention is better than cure** โ†’ regular checkups prevent major issues +* ๐Ÿ’ฐ **Ignoring it gets expensive fast** โ†’ root canals are way more expensive than cleanings! + +### ๐Ÿคฏ **Mind-Blowing Security Testing Facts:** +* ๐Ÿš€ **Speed demon**: Modern SAST tools can analyze **1 million lines of code in under 5 minutes** +* ๐Ÿ” **False alarm city**: Average SAST tool generates **30-40% false positives** (that's why we need humans!) +* ๐Ÿ› **Bug economics**: Average cost to fix a security bug jumps from **$80 in development** to **$7,600 in production** +* ๐Ÿค– **AI revolution**: **GitHub Copilot** now suggests **secure code patterns** in real-time as you type! + +### ๐Ÿ’ญ **Interactive Question for Students:** +**๐Ÿค” "If you could only choose ONE type of security testing (SAST, DAST, or IAST) for your startup's web application, which would you pick and why?"** + +*Think about: budget constraints, team size, application type, and risk tolerance...* + +--- +## ๐Ÿ“‚ Group 2: Static Application Security Testing (SAST) + +## ๐Ÿ“ Slide 6 โ€“ ๐Ÿ”ฌ Deep Dive into SAST: Definition and Core Concepts + +* ๐Ÿ”ฌ **SAST = Static Application Security Testing** โ†’ automated analysis of **source code** without executing the application. +* ๐Ÿง  **Core principle**: examine code structure, data flows, and patterns to **identify potential vulnerabilities** before runtime. +* ๐ŸŒณ **How SAST works**: + * ๐Ÿ“ **Lexical analysis**: breaks source code into tokens and symbols + * ๐ŸŒฒ **Abstract Syntax Tree (AST)**: creates hierarchical code structure representation + * ๐Ÿ”„ **Data flow analysis**: tracks how data moves through the application + * ๐ŸŽฏ **Pattern matching**: compares code patterns against vulnerability databases +* โšก **Analysis types**: + * ๐Ÿ” **Syntactic analysis**: looks for dangerous function calls, hardcoded secrets + * ๐Ÿงฎ **Semantic analysis**: understands code meaning and context + * ๐ŸŒŠ **Taint analysis**: tracks untrusted data from input to dangerous operations +* ๐Ÿ“Š **Language support**: **Java, C#, JavaScript, Python, C/C++, PHP, Go, Swift** and 50+ languages +* ๐Ÿ”— **Learn more**: [NIST SAST Guide](https://csrc.nist.gov/Projects/Static-Analysis-Tool-Exposition), [OWASP SAST Overview](https://owasp.org/www-community/Source_Code_Analysis_Tools) + +```mermaid +flowchart TD + subgraph "๐Ÿ”ฌ SAST Analysis Process" + Source[๐Ÿ“ Source Code
Raw Application Code] + Lexer[๐Ÿ”ค Lexical Analysis
Tokenization] + Parser[๐ŸŒฒ Syntax Analysis
AST Generation] + DataFlow[๐ŸŒŠ Data Flow Analysis
Variable Tracking] + PatternMatch[๐ŸŽฏ Pattern Matching
Vulnerability Detection] + Report[๐Ÿ“Š Security Report
Findings & Recommendations] + end + + Source --> Lexer + Lexer --> Parser + Parser --> DataFlow + DataFlow --> PatternMatch + PatternMatch --> Report + + subgraph "๐ŸŽฏ What SAST Finds" + SQLi[๐Ÿ’‰ SQL Injection] + XSS[๐Ÿ“œ Cross-Site Scripting] + Secrets[๐Ÿ”‘ Hardcoded Secrets] + BufferOverflow[๐Ÿ’ฅ Buffer Overflows] + RaceConditions[๐Ÿƒโ€โ™‚๏ธ Race Conditions] + end + + PatternMatch --> SQLi + PatternMatch --> XSS + PatternMatch --> Secrets + PatternMatch --> BufferOverflow + PatternMatch --> RaceConditions + + classDef process fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + classDef findings fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + + class Source,Lexer,Parser,DataFlow,PatternMatch,Report process + class SQLi,XSS,Secrets,BufferOverflow,RaceConditions findings +``` + +--- + +## ๐Ÿ“ Slide 7 โ€“ ๐Ÿ› ๏ธ Popular SAST Tools and Platform Overview + +* ๐Ÿข **Commercial Enterprise SAST Tools**: + * ๐Ÿ›ก๏ธ **Veracode Static Analysis**: cloud-native, **150+ languages**, IDE plugins, policy management + * โœ… **Checkmarx SAST**: **31 languages**, incremental scanning, custom rules, **$50-200 per developer/year** + * ๐Ÿ”’ **Synopsys Coverity**: **C/C++ excellence**, automotive compliance, **complex dataflow analysis** + * ๐Ÿฐ **Micro Focus Fortify**: **enterprise-grade**, audit workbench, regulatory compliance +* ๐Ÿ†“ **Open Source SAST Tools**: + * ๐Ÿ” **SonarQube**: **29 languages**, quality gates, technical debt tracking, **free community edition** + * โšก **Semgrep**: **fast pattern-based**, custom rules, **30+ languages**, CLI and cloud versions + * ๐Ÿ **Bandit (Python)**: specialized Python security linter, PCI DSS compliance + * ๐Ÿ“ฑ **MobSF**: mobile application security testing for Android/iOS +* โ˜๏ธ **Cloud-Native SAST Solutions**: + * ๐Ÿ™ **GitHub Advanced Security**: native GitHub integration, **CodeQL engine**, automatic PR scanning + * โšก **AWS CodeGuru Reviewer**: machine learning-powered, Java/Python focus, pay-per-review model + * ๐Ÿ”ต **Azure Security Center**: integrated DevOps workflows, compliance dashboards +* ๐Ÿ“Š **Market leaders**: **Veracode (23% market share)**, **Checkmarx (19%)**, **Synopsys (16%)** ([Gartner Magic Quadrant 2024](https://www.gartner.com/en/documents/4018395)) + +```mermaid +flowchart TD + subgraph "๐Ÿข Commercial Enterprise" + Veracode[๐Ÿ›ก๏ธ Veracode
๐Ÿ“Š Cloud-native, 150+ languages] + Checkmarx[โœ… Checkmarx
๐Ÿ’ฐ $50-200/dev/year] + Coverity[๐Ÿ”’ Synopsys Coverity
๐Ÿš— Automotive compliance] + Fortify[๐Ÿฐ Micro Focus Fortify
๐Ÿ“‹ Enterprise audit] + end + + subgraph "๐Ÿ†“ Open Source" + SonarQube[๐Ÿ” SonarQube
๐Ÿ“ˆ Quality gates, 29 languages] + Semgrep[โšก Semgrep
๐ŸŽฏ Pattern-based, custom rules] + Bandit[๐Ÿ Bandit
๐Ÿ” Python security specialist] + MobSF[๐Ÿ“ฑ MobSF
๐Ÿ“ฒ Mobile app security] + end + + subgraph "โ˜๏ธ Cloud-Native" + GitHub[๐Ÿ™ GitHub Advanced Security
๐Ÿ” CodeQL engine] + CodeGuru[โšก AWS CodeGuru
๐Ÿค– ML-powered analysis] + Azure[๐Ÿ”ต Azure Security Center
๐Ÿ“Š DevOps integration] + end + + subgraph "๐ŸŽฏ Selection Criteria" + Language[๐Ÿ’ป Language Support] + Integration[๐Ÿ”— CI/CD Integration] + Cost[๐Ÿ’ฐ Total Cost of Ownership] + Accuracy[๐ŸŽฏ False Positive Rate] + Scalability[๐Ÿ“ˆ Enterprise Scalability] + end + + Veracode -.-> Language + SonarQube -.-> Integration + GitHub -.-> Cost + Checkmarx -.-> Accuracy + Coverity -.-> Scalability + + classDef commercial fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + classDef opensource fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + classDef cloud fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + classDef criteria fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#2c3e50 + + class Veracode,Checkmarx,Coverity,Fortify commercial + class SonarQube,Semgrep,Bandit,MobSF opensource + class GitHub,CodeGuru,Azure cloud + class Language,Integration,Cost,Accuracy,Scalability criteria +``` + +--- + +## ๐Ÿ“ Slide 8 โ€“ โšก SAST Strengths and Limitations + +* โœ… **SAST Superpowers**: + * ๐Ÿƒโ€โ™‚๏ธ **Early detection**: finds vulnerabilities **during development** โ†’ cheapest to fix + * ๐Ÿ“Š **Complete coverage**: analyzes **100% of code paths** including rarely executed branches + * โšก **Fast feedback**: results in **minutes to hours** vs. days for manual review + * ๐Ÿšซ **No runtime required**: works with **incomplete applications** and third-party libraries + * ๐Ÿ“‹ **Compliance friendly**: generates detailed reports for **audit trails** (SOX, PCI-DSS) + * ๐ŸŽฏ **Precise location**: points to **exact line of code** with vulnerability +* โŒ **SAST Limitations**: + * ๐Ÿšจ **False positive plague**: **30-40% false positive rate** โ†’ developer fatigue and tool abandonment + * ๐ŸŒ **Missing runtime context**: can't detect **configuration issues** or **environment-specific** problems + * ๐Ÿงฉ **Complex business logic**: struggles with **multi-step workflows** and **authorization logic** + * ๐Ÿ“š **Language constraints**: **compiled languages work better** than interpreted (JavaScript challenges) + * ๐Ÿ”ง **Integration complexity**: requires **build environment setup** and **dependency resolution** +* ๐Ÿ“Š **Industry reality**: **67% of developers** report SAST false positives as biggest adoption barrier ([DevSecOps Community Survey 2024](https://www.devsecops.org/)) + +```mermaid +graph TD + subgraph "โœ… SAST Strengths" + Early[๐Ÿƒโ€โ™‚๏ธ Early Detection
Development Phase] + Coverage[๐Ÿ“Š Complete Coverage
100% Code Paths] + Fast[โšก Fast Feedback
Minutes to Hours] + NoRuntime[๐Ÿšซ No Runtime Needed
Works on Incomplete Apps] + Compliance[๐Ÿ“‹ Compliance Reports
Audit Trails] + Precise[๐ŸŽฏ Precise Location
Exact Line Numbers] + end + + subgraph "โŒ SAST Limitations" + FalsePos[๐Ÿšจ False Positives
30-40% Rate] + NoContext[๐ŸŒ No Runtime Context
Config Issues Missed] + BusinessLogic[๐Ÿงฉ Complex Logic
Workflow Blind Spots] + Language[๐Ÿ“š Language Issues
Interpreted Language Challenges] + Integration[๐Ÿ”ง Integration Complexity
Build Dependencies] + end + + subgraph "๐Ÿ’ก Mitigation Strategies" + Tuning[๐ŸŽ›๏ธ Rule Tuning
Reduce False Positives] + Training[๐Ÿ“š Developer Training
Understanding Results] + Gradual[๐Ÿ“ˆ Gradual Rollout
Incremental Adoption] + Hybrid[๐Ÿ”„ Hybrid Approach
SAST + DAST + IAST] + end + + FalsePos --> Tuning + NoContext --> Hybrid + BusinessLogic --> Hybrid + Integration --> Training + Language --> Gradual + + classDef strength fill:#e8f5e8,stroke:#2e7d32,stroke-width:2px,color:#2c3e50 + classDef limitation fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + classDef mitigation fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + + class Early,Coverage,Fast,NoRuntime,Compliance,Precise strength + class FalsePos,NoContext,BusinessLogic,Language,Integration limitation + class Tuning,Training,Gradual,Hybrid mitigation +``` + +--- + +## ๐Ÿ“ Slide 9 โ€“ ๐ŸŽฏ SAST Implementation Best Practices + +* ๐ŸŽฏ **Successful SAST Deployment Strategy**: + * ๐Ÿ“ˆ **Start small**: begin with **high-risk applications** and **critical security rules** + * ๐ŸŽ›๏ธ **Tune relentlessly**: spend **first 30 days** reducing false positives to **<10%** + * ๐Ÿ‘ฅ **Train developers**: provide **hands-on training** on interpreting and fixing findings + * ๐Ÿ“Š **Measure everything**: track **time-to-fix**, **developer adoption**, **vulnerability trends** +* ๐Ÿ”— **IDE Integration Best Practices**: + * ๐Ÿ’ป **Real-time feedback**: integrate with **VS Code**, **IntelliJ**, **Eclipse** for instant alerts + * ๐Ÿƒโ€โ™‚๏ธ **Incremental scanning**: scan only **changed files** to maintain developer flow + * ๐ŸŽจ **Custom highlighting**: use **different colors** for different severity levels + * ๐Ÿ”• **Noise reduction**: allow developers to **suppress false positives** with justification +* ๐Ÿš€ **CI/CD Pipeline Integration**: + * โš–๏ธ **Quality gates**: **fail builds** only on **high/critical** vulnerabilities initially + * ๐Ÿ“Š **Trend analysis**: track vulnerability **introduction** and **fix rates** over time + * ๐Ÿ“ง **Smart notifications**: alert only **code authors** and **security champions** + * ๐Ÿ”„ **Automated triage**: use **ML models** to **pre-classify** likely false positives +* ๐Ÿ’ก **Developer Adoption Secrets**: **gamification** (vulnerability fix leaderboards), **positive reinforcement** (celebrate security improvements), **just-in-time training** (context-aware learning) + +```mermaid +flowchart LR + subgraph "๐ŸŽฏ Implementation Journey" + Plan[๐Ÿ“‹ Planning Phase
Tool selection, pilot scope] + Deploy[๐Ÿš€ Deployment Phase
Integration, configuration] + Tune[๐ŸŽ›๏ธ Tuning Phase
False positive reduction] + Scale[๐Ÿ“ˆ Scaling Phase
Organization-wide rollout] + Optimize[โš™๏ธ Optimization Phase
Continuous improvement] + end + + subgraph "๐Ÿ”— Integration Points" + IDE[๐Ÿ’ป IDE Integration
Real-time feedback] + PreCommit[๐Ÿ”„ Pre-commit Hooks
Local scanning] + CI[๐Ÿ—๏ธ CI/CD Pipeline
Automated scanning] + Dashboard[๐Ÿ“Š Security Dashboard
Centralized reporting] + end + + subgraph "๐Ÿ“Š Success Metrics" + MTTR[โฑ๏ธ Mean Time to Remediate
Target: <7 days] + Adoption[๐Ÿ‘ฅ Developer Adoption Rate
Target: >80%] + FalsePos[๐ŸŽฏ False Positive Rate
Target: <10%] + Coverage[๐Ÿ“ˆ Code Coverage
Target: >90%] + end + + Plan --> Deploy --> Tune --> Scale --> Optimize + + Deploy --> IDE + Tune --> PreCommit + Scale --> CI + Optimize --> Dashboard + + Tune --> FalsePos + Scale --> Adoption + Optimize --> MTTR + Deploy --> Coverage + + classDef phase fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + classDef integration fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + classDef metrics fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + + class Plan,Deploy,Tune,Scale,Optimize phase + class IDE,PreCommit,CI,Dashboard integration + class MTTR,Adoption,FalsePos,Coverage metrics +``` + +--- + +## ๐Ÿ“ Slide 10 โ€“ ๐Ÿ”ง Hands-on SAST: Tool Configuration and Output Analysis + +* ๐Ÿ”ง **SonarQube Setup Example** (Free Community Edition): + * ๐Ÿณ **Docker deployment**: `docker run -d -p 9000:9000 sonarqube:lts-community` + * โš™๏ธ **Project configuration**: create `sonar-project.properties` with language settings + * ๐Ÿ” **Scan execution**: `sonar-scanner` analyzes code and uploads results + * ๐Ÿ“Š **Quality gate**: define **pass/fail criteria** for builds +* ๐Ÿ“Š **Understanding SAST Output**: + * ๐Ÿ”ด **Blocker**: **security vulnerabilities** โ†’ immediate fix required + * ๐ŸŸ  **Critical**: **major bugs** โ†’ fix before release + * ๐ŸŸก **Major**: **maintainability issues** โ†’ address in sprint + * ๐Ÿ”ต **Minor**: **code smells** โ†’ technical debt cleanup + * โšช **Info**: **suggestions** โ†’ optional improvements +* ๐Ÿ› ๏ธ **Sample Vulnerability Fix Workflow**: + * ๐Ÿ” **Identify**: SQL injection in user login function + * ๐Ÿ“– **Understand**: review SAST explanation and code context + * ๐Ÿ”ง **Fix**: replace string concatenation with parameterized query + * โœ… **Verify**: re-run SAST scan to confirm resolution + * ๐Ÿ“š **Learn**: document pattern for team knowledge base + +```mermaid +flowchart TD + subgraph "๐Ÿ”ง SonarQube Analysis Flow" + Code[๐Ÿ“ Source Code
Java/Python/JS Project] + Config[โš™๏ธ sonar-project.properties
Language & Rule Configuration] + Scanner[๐Ÿ” sonar-scanner
Static Analysis Execution] + Upload[๐Ÿ“ค Results Upload
SonarQube Server] + Dashboard[๐Ÿ“Š SonarQube Dashboard
Vulnerability Report] + end + + subgraph "๐Ÿ“Š SAST Output Analysis" + Blocker[๐Ÿ”ด Blocker Issues
Security Vulnerabilities] + Critical[๐ŸŸ  Critical Issues
Major Bugs] + Major[๐ŸŸก Major Issues
Maintainability] + Minor[๐Ÿ”ต Minor Issues
Code Smells] + Info[โšช Info
Suggestions] + end + + subgraph "๐Ÿ› ๏ธ Fix Workflow Example" + SQLInjection[๐Ÿ’‰ SQL Injection Found
Line 42: String concatenation] + Analysis[๐Ÿ” Vulnerability Analysis
User input โ†’ SQL query] + FixCode[๐Ÿ”ง Apply Fix
Parameterized query] + Verify[โœ… Verification
Re-scan for confirmation] + Document[๐Ÿ“š Document Pattern
Team knowledge base] + end + + Code --> Config --> Scanner --> Upload --> Dashboard + + Dashboard --> Blocker + Dashboard --> Critical + Dashboard --> Major + Dashboard --> Minor + Dashboard --> Info + + Blocker --> SQLInjection + SQLInjection --> Analysis --> FixCode --> Verify --> Document + + classDef flow fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + classDef severity fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + classDef fix fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + + class Code,Config,Scanner,Upload,Dashboard flow + class Blocker,Critical,Major,Minor,Info severity + class SQLInjection,Analysis,FixCode,Verify,Document fix +``` + +--- + +## ๐Ÿ“‚ Group 3: Dynamic Application Security Testing (DAST) + +## ๐Ÿ“ Slide 11 โ€“ ๐ŸŒ Deep Dive into DAST: Black-box Runtime Testing + +* ๐ŸŒ **DAST = Dynamic Application Security Testing** โ†’ automated security testing of **running applications** without access to source code. +* ๐Ÿ•ต๏ธ **Black-box approach**: tests application **from external perspective** like a real attacker would. +* ๐Ÿ”„ **How DAST works**: + * ๐Ÿ•ท๏ธ **Web crawling**: automatically discovers **application pages and endpoints** + * ๐ŸŽฏ **Attack simulation**: sends **malicious payloads** to input fields and parameters + * ๐Ÿ“Š **Response analysis**: examines **HTTP responses** for vulnerability indicators + * ๐Ÿ“ **Vulnerability confirmation**: validates findings with **exploit proof-of-concept** +* ๐Ÿงฉ **DAST Testing Types**: + * ๐ŸŒ **Web application scanning**: traditional website and web app testing + * ๐Ÿ”— **API testing**: REST/GraphQL/SOAP endpoint security validation + * ๐Ÿ“ฑ **Mobile app testing**: iOS/Android application security assessment + * โ˜๏ธ **Cloud configuration**: serverless functions and cloud service testing +* โฐ **Testing phases**: typically runs during **QA/staging** or **pre-production** phases +* ๐Ÿ”— **Learn more**: [OWASP DAST Guide](https://owasp.org/www-community/Vulnerability_Scanning_Tools), [NIST Application Security Testing](https://csrc.nist.gov/projects/application-security) + +```mermaid +flowchart LR + subgraph "๐ŸŒ DAST Testing Process" + RunningApp[๐Ÿ–ฅ๏ธ Running Application
Web/API/Mobile] + Crawler[๐Ÿ•ท๏ธ Web Crawler
Endpoint Discovery] + AttackEngine[โš”๏ธ Attack Engine
Payload Generation] + ResponseAnalysis[๐Ÿ” Response Analysis
Vulnerability Detection] + Validation[โœ… Exploit Validation
Proof-of-Concept] + Report[๐Ÿ“Š DAST Report
Confirmed Vulnerabilities] + end + + subgraph "๐ŸŽฏ DAST Targets" + WebApps[๐ŸŒ Web Applications
HTML Forms, JavaScript] + APIs[๐Ÿ”— APIs
REST, GraphQL, SOAP] + MobileApps[๐Ÿ“ฑ Mobile Apps
iOS, Android] + CloudServices[โ˜๏ธ Cloud Services
Serverless, Containers] + end + + subgraph "โš”๏ธ Attack Categories" + Injection[๐Ÿ’‰ Injection Attacks
SQL, XSS, Command] + AuthBypass[๐Ÿ”“ Auth Bypass
Session, Access Control] + ConfigIssues[๐Ÿ› ๏ธ Configuration
Server, Security Headers] + BusinessLogic[๐Ÿงฉ Business Logic
Workflow Manipulation] + end + + RunningApp --> Crawler --> AttackEngine --> ResponseAnalysis --> Validation --> Report + + Crawler --> WebApps + Crawler --> APIs + AttackEngine --> MobileApps + ResponseAnalysis --> CloudServices + + AttackEngine --> Injection + AttackEngine --> AuthBypass + ResponseAnalysis --> ConfigIssues + Validation --> BusinessLogic + + classDef process fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + classDef targets fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#2c3e50 + classDef attacks fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + + class RunningApp,Crawler,AttackEngine,ResponseAnalysis,Validation,Report process + class WebApps,APIs,MobileApps,CloudServices targets + class Injection,AuthBypass,ConfigIssues,BusinessLogic attacks +``` + +--- + +## ๐Ÿ“ Slide 12 โ€“ ๐Ÿ› ๏ธ Popular DAST Tools and Platform Overview + +* ๐Ÿข **Commercial Enterprise DAST Tools**: + * ๐Ÿ›ก๏ธ **Veracode Dynamic Analysis**: **cloud-based scanning**, API testing, **authenticated scans**, compliance reporting + * ๐Ÿ” **Rapid7 AppSpider**: **enterprise web app scanner**, **custom attack patterns**, detailed remediation guidance + * ๐ŸŒ **Invicti (formerly Netsparker)**: **low false positive rate**, **proof-of-exploit**, WordPress/CMS specialization + * โšก **HCL AppScan**: **IBM heritage**, **enterprise integration**, regulatory compliance focus +* ๐Ÿ†“ **Open Source DAST Tools**: + * โšก **OWASP ZAP**: **most popular open-source** scanner, **active development**, **extensive plugin ecosystem** + * ๐Ÿ” **Nikto**: **web server scanner**, **6000+ vulnerability tests**, lightweight and fast + * ๐Ÿ **w3af**: **Python-based framework**, **extensible architecture**, custom plugin development + * ๐Ÿ’‰ **SQLMap**: **specialized SQL injection** testing tool, **database takeover** capabilities +* โ˜๏ธ **Cloud-Native DAST Solutions**: + * ๐Ÿ”ถ **AWS Inspector**: **application assessment**, **network reachability analysis**, **automated remediation** + * ๐Ÿ”ต **Azure Security Center**: **integrated DevOps**, **container scanning**, **threat intelligence** + * ๐Ÿ” **Google Cloud Security Scanner**: **App Engine applications**, **automatic crawling**, **minimal false positives** +* ๐ŸŽฏ **Specialized API Testing Tools**: **Postman Security**, **Insomnia**, **REST-Assured**, **Karate DSL** +* ๐Ÿ“Š **Market adoption**: **OWASP ZAP leads** with **45% open-source market share** ([DAST Tools Survey 2024](https://owasp.org/www-project-zap/)) + +```mermaid +flowchart TD + subgraph "๐Ÿข Commercial Enterprise" + Veracode2[๐Ÿ›ก๏ธ Veracode Dynamic
โ˜๏ธ Cloud-based, API testing] + AppSpider[๐Ÿ” Rapid7 AppSpider
๐ŸŽฏ Custom attack patterns] + Invicti[๐ŸŒ Invicti Netsparker
๐Ÿ“ˆ Low false positives] + AppScan[โšก HCL AppScan
๐Ÿข Enterprise integration] + end + + subgraph "๐Ÿ†“ Open Source Champions" + ZAP[โšก OWASP ZAP
๐Ÿ‘‘ Most popular, plugin ecosystem] + Nikto[๐Ÿ” Nikto
โšก 6000+ tests, lightweight] + w3af[๐Ÿ w3af
๐Ÿ”ง Python framework, extensible] + SQLMap[๐Ÿ’‰ SQLMap
๐ŸŽฏ SQL injection specialist] + end + + subgraph "โ˜๏ธ Cloud-Native" + Inspector[๐Ÿ”ถ AWS Inspector
๐Ÿ” Network + app assessment] + AzureSC[๐Ÿ”ต Azure Security Center
๐Ÿณ Container scanning] + GoogleCS[๐Ÿ” Google Cloud Scanner
๐Ÿ“ฑ App Engine focus] + end + + subgraph "๐Ÿ”— API Specialists" + Postman[๐Ÿ“ฎ Postman Security
๐Ÿ”— API workflow testing] + Insomnia[๐Ÿ˜ด Insomnia
๐ŸŽฏ GraphQL specialist] + RestAssured[๐Ÿ›ก๏ธ REST-Assured
โ˜• Java API testing] + Karate[๐Ÿฅ‹ Karate DSL
๐Ÿ“ BDD API testing] + end + + subgraph "๐Ÿ’ก Selection Criteria" + AppType[๐ŸŒ Application Type
Web vs API vs Mobile] + Budget[๐Ÿ’ฐ Budget Constraints
Free vs Commercial] + Integration[๐Ÿ”— CI/CD Integration
Pipeline compatibility] + Expertise[๐Ÿง  Team Expertise
Tool complexity] + Compliance[๐Ÿ“‹ Compliance Needs
Regulatory requirements] + end + + ZAP -.-> Budget + Veracode2 -.-> Compliance + AppSpider -.-> Integration + Postman -.-> AppType + Inspector -.-> Expertise + + classDef commercial fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + classDef opensource fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + classDef cloud fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + classDef api fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#2c3e50 + classDef criteria fill:#fce4ec,stroke:#c2185b,stroke-width:2px,color:#2c3e50 + + class Veracode2,AppSpider,Invicti,AppScan commercial + class ZAP,Nikto,w3af,SQLMap opensource + class Inspector,AzureSC,GoogleCS cloud + class Postman,Insomnia,RestAssured,Karate api + class AppType,Budget,Integration,Expertise,Compliance criteria +``` + +--- + +## ๐Ÿ“ Slide 13 โ€“ โšก DAST Strengths and Limitations + +* โœ… **DAST Superpowers**: + * ๐ŸŒ **Real-world conditions**: tests **actual running environment** with real configurations + * ๐Ÿ› ๏ธ **Configuration testing**: detects **server misconfigurations**, missing security headers, SSL/TLS issues + * ๐Ÿงฉ **Business logic validation**: can identify **workflow manipulation** and **authorization bypasses** + * ๐Ÿ” **Language agnostic**: works with **any technology stack** (Java, .NET, PHP, Node.js, Python) + * ๐ŸŽฏ **Production-like testing**: validates security in **staging/pre-production** environments + * ๐Ÿ“Š **Low false positives**: **exploitable vulnerabilities** are confirmed through actual attacks +* โŒ **DAST Limitations**: + * ๐ŸŒ **Slow execution**: comprehensive scans can take **hours to days** for large applications + * ๐Ÿ“‰ **Limited code coverage**: only tests **accessible application paths** โ†’ **~20-30% code coverage** + * ๐Ÿƒโ€โ™‚๏ธ **Late-stage detection**: vulnerabilities found **after development** โ†’ **expensive to fix** + * ๐Ÿ”ง **Complex setup**: requires **running application**, **test data**, **network access** + * ๐Ÿ” **Authentication challenges**: difficulty testing **authenticated sections** and **complex workflows** + * ๐Ÿ’ฅ **Potentially disruptive**: aggressive testing may **crash applications** or **corrupt data** +* ๐Ÿ“Š **Industry insights**: **52% of organizations** use DAST but only **23% integrate it effectively** into CI/CD ([DevSecOps Maturity Report 2024](https://www.devsecops.org/)) + +```mermaid +graph TD + subgraph "โœ… DAST Advantages" + RealWorld[๐ŸŒ Real-World Testing
Actual runtime environment] + Config[๐Ÿ› ๏ธ Configuration Issues
Server, SSL, headers] + BusinessLogic[๐Ÿงฉ Business Logic
Workflow validation] + TechAgnostic[๐Ÿ” Technology Agnostic
Any language/platform] + ProdLike[๐ŸŽฏ Production-Like
Staging environment] + LowFP[๐Ÿ“Š Low False Positives
Exploitable confirmed] + end + + subgraph "โŒ DAST Challenges" + SlowExec[๐ŸŒ Slow Execution
Hours to days] + LimitedCov[๐Ÿ“‰ Limited Coverage
20-30% code paths] + LateStage[๐Ÿƒโ€โ™‚๏ธ Late Detection
Expensive fixes] + ComplexSetup[๐Ÿ”ง Complex Setup
Running app required] + AuthChall[๐Ÿ” Auth Challenges
Complex workflows] + Disruptive[๐Ÿ’ฅ Potentially Disruptive
May crash/corrupt] + end + + subgraph "๐Ÿ”„ Mitigation Strategies" + Incremental[๐Ÿ“ˆ Incremental Scanning
Focus on changes] + AuthConfig[๐Ÿ”‘ Auth Configuration
Session management] + TestEnv[๐Ÿงช Dedicated Test Env
Isolated from prod] + Scheduling[๐Ÿ“… Scheduled Scanning
Off-hours execution] + Hybrid[๐Ÿค Hybrid Approach
SAST + DAST combination] + end + + SlowExec --> Incremental + SlowExec --> Scheduling + AuthChall --> AuthConfig + ComplexSetup --> TestEnv + LimitedCov --> Hybrid + Disruptive --> TestEnv + + classDef advantage fill:#e8f5e8,stroke:#2e7d32,stroke-width:2px,color:#2c3e50 + classDef challenge fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + classDef mitigation fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + + class RealWorld,Config,BusinessLogic,TechAgnostic,ProdLike,LowFP advantage + class SlowExec,LimitedCov,LateStage,ComplexSetup,AuthChall,Disruptive challenge + class Incremental,AuthConfig,TestEnv,Scheduling,Hybrid mitigation +``` + +--- + +## ๐Ÿ“ Slide 14 โ€“ ๐ŸŽฏ DAST Implementation Best Practices + +* ๐ŸŽฏ **Successful DAST Deployment Strategy**: + * ๐Ÿงช **Dedicated test environment**: isolated staging environment with **production-like data** + * ๐Ÿ“… **Scheduling strategy**: run comprehensive scans **nightly** or **weekly** to avoid disruption + * ๐ŸŽ›๏ธ **Incremental scanning**: focus on **changed components** for faster feedback in CI/CD + * ๐Ÿ“Š **Risk-based prioritization**: fix **critical** and **high** vulnerabilities first +* ๐Ÿ”‘ **Authentication and Session Management**: + * ๐Ÿ‘ค **Test user accounts**: create dedicated **test accounts** with different **privilege levels** + * ๐Ÿช **Session handling**: configure **automatic login** and **session maintenance** + * ๐Ÿ”„ **Multi-step authentication**: handle **2FA**, **CAPTCHA**, and **complex login flows** + * ๐Ÿ“‹ **Role-based testing**: test with **admin**, **user**, and **anonymous** access levels +* ๐Ÿš€ **CI/CD Pipeline Integration Patterns**: + * ๐Ÿ”„ **Parallel execution**: run DAST **alongside** other testing phases + * ๐Ÿ“Š **Quality gates**: **fail builds** only on **newly introduced** high-severity issues + * ๐Ÿ“ง **Smart notifications**: alert **relevant teams** based on vulnerability type + * ๐Ÿ“ˆ **Trend analysis**: track vulnerability **introduction** and **resolution** rates +* ๐Ÿ’ก **Performance Optimization Tips**: **crawler tuning** (limit scope), **payload optimization** (focus on likely vulnerabilities), **result caching** (avoid duplicate scans) + +```mermaid +flowchart TD + subgraph "๐Ÿงช Test Environment Setup" + ProdLike[๐ŸŽฏ Production-Like
Same tech stack] + TestData[๐Ÿ“Š Test Data
Realistic but safe] + Isolated[๐Ÿ๏ธ Isolated Network
No production access] + Monitoring[๐Ÿ“ˆ Performance Monitoring
Resource usage tracking] + end + + subgraph "๐Ÿ”‘ Authentication Strategy" + TestUsers[๐Ÿ‘ค Test User Accounts
Multiple privilege levels] + AutoLogin[๐Ÿ”„ Automatic Login
Session maintenance] + MultiAuth[๐Ÿ›ก๏ธ Multi-factor Auth
2FA/CAPTCHA handling] + RoleTesting[๐Ÿ‘ฅ Role-based Testing
Admin/User/Anonymous] + end + + subgraph "๐Ÿš€ CI/CD Integration" + Parallel[โšก Parallel Execution
Non-blocking scans] + QualityGate[๐Ÿšฆ Smart Quality Gates
New issues only] + Notifications[๐Ÿ“ง Targeted Alerts
Team-specific routing] + Trends[๐Ÿ“Š Trend Analysis
Vulnerability metrics] + end + + subgraph "โš™๏ธ Performance Optimization" + ScopeLimit[๐ŸŽฏ Scope Limitation
Focus crawling] + PayloadOpt[๐Ÿš€ Payload Optimization
Smart attack selection] + ResultCache[๐Ÿ’พ Result Caching
Avoid duplicate work] + Incremental[๐Ÿ“ˆ Incremental Scanning
Changed components only] + end + + ProdLike --> TestUsers + TestData --> AutoLogin + Isolated --> Parallel + Monitoring --> QualityGate + + MultiAuth --> ScopeLimit + RoleTesting --> PayloadOpt + Notifications --> ResultCache + Trends --> Incremental + + classDef env fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + classDef auth fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + classDef cicd fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + classDef perf fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#2c3e50 + + class ProdLike,TestData,Isolated,Monitoring env + class TestUsers,AutoLogin,MultiAuth,RoleTesting auth + class Parallel,QualityGate,Notifications,Trends cicd + class ScopeLimit,PayloadOpt,ResultCache,Incremental perf +``` + +--- + +## ๐Ÿ“ Slide 15 โ€“ ๐Ÿ”ง Hands-on DAST: OWASP ZAP Configuration and Testing + +* ๐Ÿ”ง **OWASP ZAP Setup and Configuration**: + * ๐Ÿณ **Docker deployment**: `docker run -t owasp/zap2docker-stable zap-baseline.py -t https://target-app.com` + * ๐Ÿ–ฅ๏ธ **Desktop GUI**: download from [zaproxy.org](https://www.zaproxy.org/) for interactive scanning + * ๐Ÿค– **CI/CD integration**: use **ZAP API** or **Jenkins plugin** for automated pipeline scanning + * โš™๏ธ **Configuration files**: customize scan policies, authentication, and scope settings +* ๐Ÿ•ท๏ธ **ZAP Spider and Active Scan Configuration**: + * ๐ŸŒ **Spider configuration**: set **max crawl depth**, **exclude patterns**, **form handling** + * โš”๏ธ **Active scan policies**: enable/disable **attack categories** based on application type + * ๐ŸŽฏ **Scope management**: define **in-scope URLs** and **exclude sensitive endpoints** + * ๐Ÿ“Š **Scan tuning**: adjust **attack strength** and **timing** for different environments +* ๐Ÿ”‘ **Authentication Configuration Examples**: + * ๐Ÿ“ **Form-based auth**: configure **login URL**, **username/password fields**, **success indicators** + * ๐Ÿช **Session management**: handle **session cookies**, **CSRF tokens**, **logout detection** + * ๐Ÿ”— **API authentication**: configure **Bearer tokens**, **API keys**, **OAuth flows** +* ๐Ÿ“Š **Result Analysis and Reporting**: ZAP generates **HTML**, **XML**, and **JSON** reports with vulnerability details, remediation guidance, and **risk ratings** + +```mermaid +flowchart TD + subgraph "๐Ÿ”ง ZAP Configuration Flow" + Target[๐ŸŽฏ Target Application
Define scope & URLs] + Spider[๐Ÿ•ท๏ธ Spider Configuration
Crawl settings & depth] + Auth[๐Ÿ”‘ Authentication Setup
Login & session handling] + Scan[โš”๏ธ Active Scan Policy
Attack categories & strength] + Execute[โ–ถ๏ธ Scan Execution
Spider โ†’ Auth โ†’ Attack] + Results[๐Ÿ“Š Results Analysis
Vulnerability assessment] + end + + subgraph "โš™๏ธ ZAP Components" + Proxy[๐Ÿ”Œ Intercepting Proxy
HTTP/HTTPS traffic] + PassiveScan[๐Ÿ‘๏ธ Passive Scanner
Traffic analysis] + ActiveScan[โš”๏ธ Active Scanner
Attack simulation] + API[๐Ÿค– ZAP API
Automation interface] + end + + subgraph "๐Ÿ“Š Scan Results" + HighRisk[๐Ÿ”ด High Risk
SQL Injection, XSS] + MediumRisk[๐ŸŸก Medium Risk
Info disclosure] + LowRisk[๐Ÿ”ต Low Risk
Minor issues] + Info[โšช Informational
Best practices] + end + + Target --> Spider --> Auth --> Scan --> Execute --> Results + + Spider --> Proxy + Auth --> PassiveScan + Scan --> ActiveScan + Execute --> API + + Results --> HighRisk + Results --> MediumRisk + Results --> LowRisk + Results --> Info + + classDef config fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + classDef components fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#2c3e50 + classDef results fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + + class Target,Spider,Auth,Scan,Execute,Results config + class Proxy,PassiveScan,ActiveScan,API components + class HighRisk,MediumRisk,LowRisk,Info results +``` + +--- + +## ๐ŸŽ‰ **Fun Break: SAST vs DAST - The Eternal Debate!** + +### ๐Ÿ˜„ **"SAST vs DAST: The Developer Dating Game"** +* ๐Ÿ’• **SAST is like dating someone's profile** โ†’ you know everything about them on paper, but haven't met in person +* ๐ŸŒ **DAST is like meeting them in real life** โ†’ you see how they actually behave, but don't know their deep thoughts +* ๐Ÿ’‘ **IAST is like moving in together** โ†’ you get the full picture, but it's a bigger commitment! +* ๐Ÿค **Smart couples use all three** โ†’ because no single approach tells the whole story + +### ๐Ÿคฏ **Mind-Blowing Security Testing Facts:** +* โšก **Speed comparison**: SAST can scan **1 million lines in 5 minutes**, DAST takes **8 hours** for the same app +* ๐ŸŽฏ **Coverage paradox**: SAST covers **100% of code** but finds **60% false positives**, DAST covers **30% of code** but has **95% accuracy** +* ๐Ÿ’ฐ **ROI reality**: Companies using **both SAST and DAST** reduce security incidents by **73%** vs single-tool users +* ๐Ÿค– **AI integration**: **GitHub Copilot** now suggests **ZAP scan configurations** when you mention security testing! + +### ๐Ÿ’ญ **Interactive Challenge for Students:** +**๐ŸŽฎ "Build Your Security Testing Strategy Game!"** + +*Scenario: You're the security lead for a fintech startup. You have:* +- ๐Ÿ’ฐ **Limited budget**: $50K/year for tools +- โฐ **Tight deadlines**: 2-week sprints +- ๐Ÿ‘ฅ **Small team**: 5 developers, 2 QA engineers +- ๐Ÿ›๏ธ **Compliance**: PCI-DSS requirements + +**Which combination would you choose and why?** +1. ๐Ÿ”ฌ Premium SAST tool ($40K) + Open source DAST +2. ๐Ÿ†“ Open source everything (ZAP + SonarQube) + Security consultant +3. โ˜๏ธ Cloud-native integrated suite (GitHub Advanced Security) + +*Discuss in groups and defend your choice!* + +--- +## ๐Ÿ“‚ Group 4: Interactive Application Security Testing (IAST) + +## ๐Ÿ“ Slide 16 โ€“ ๐Ÿงฌ Deep Dive into IAST: Runtime Instrumentation Testing + +* ๐Ÿงฌ **IAST = Interactive Application Security Testing** โ†’ **hybrid approach** combining benefits of **SAST and DAST** through **runtime instrumentation**. +* ๐Ÿ”ง **How IAST works**: + * ๐Ÿ“ก **Agent instrumentation**: lightweight **monitoring agents** deployed within the application runtime + * ๐Ÿ‘๏ธ **Runtime observation**: agents **monitor application behavior** during normal QA testing + * ๐ŸŒŠ **Data flow tracking**: follows **untrusted data** from **input to dangerous operations** + * โšก **Real-time analysis**: detects vulnerabilities **as they occur** during application execution +* ๐ŸŽฏ **Gray-box testing approach**: has **access to source code** (like SAST) while testing **running application** (like DAST) +* ๐Ÿงฉ **Key IAST capabilities**: + * ๐Ÿ” **Precise vulnerability location**: pinpoints **exact line of code** with runtime context + * ๐Ÿ“Š **Code coverage analysis**: shows **which code paths were tested** during QA execution + * ๐Ÿšซ **Low false positives**: validates vulnerabilities through **actual runtime conditions** + * ๐Ÿ“ˆ **Incremental testing**: only tests **code paths that are actually executed** +* โฑ๏ธ **Testing timing**: runs **during QA testing phase** when functional tests exercise application features +* ๐Ÿ”— **Learn more**: [Gartner IAST Guide](https://www.gartner.com/en/information-technology/glossary/interactive-application-security-testing-iast), [OWASP IAST Overview](https://owasp.org/www-community/Vulnerability_Scanning_Tools) + +```mermaid +flowchart TD + subgraph "๐Ÿงฌ IAST Architecture" + QATest[๐Ÿงช QA Testing
Functional test execution] + Agent[๐Ÿค– IAST Agent
Runtime instrumentation] + AppRuntime[๐Ÿ–ฅ๏ธ Application Runtime
Monitored execution] + Analysis[๐Ÿง  Real-time Analysis
Vulnerability detection] + Report[๐Ÿ“Š IAST Report
Precise findings] + end + + subgraph "๐Ÿ” What IAST Monitors" + DataFlow[๐ŸŒŠ Data Flow
Input to dangerous ops] + CodePaths[๐Ÿ“ Code Path Coverage
Execution tracking] + VulnContext[๐ŸŽฏ Vulnerability Context
Runtime conditions] + Performance[๐Ÿ“ˆ Performance Impact
Resource monitoring] + end + + subgraph "๐ŸŽฏ IAST Advantages" + Precise[๐Ÿ” Precise Location
Exact line + context] + LowFP[๐Ÿ“Š Low False Positives
Runtime validated] + Incremental[๐Ÿ“ˆ Incremental Testing
Only executed paths] + Coverage[๐Ÿ“Š Coverage Metrics
Testing effectiveness] + end + + QATest --> Agent --> AppRuntime --> Analysis --> Report + + Agent --> DataFlow + AppRuntime --> CodePaths + Analysis --> VulnContext + Agent --> Performance + + Analysis --> Precise + VulnContext --> LowFP + CodePaths --> Incremental + Performance --> Coverage + + classDef architecture fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + classDef monitoring fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#2c3e50 + classDef advantages fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + + class QATest,Agent,AppRuntime,Analysis,Report architecture + class DataFlow,CodePaths,VulnContext,Performance monitoring + class Precise,LowFP,Incremental,Coverage advantages +``` + +--- + +## ๐Ÿ“ Slide 17 โ€“ ๐Ÿ› ๏ธ Popular IAST Tools and Platform Overview + +* ๐Ÿข **Commercial Enterprise IAST Tools**: + * ๐Ÿ›ก๏ธ **Veracode Interactive Analysis**: **cloud-based IAST**, supports **Java, .NET, Node.js**, **DevOps integration** + * ๐Ÿ” **Synopsys Seeker**: **comprehensive language support**, **custom policy creation**, **enterprise scalability** + * ๐Ÿ›ก๏ธ **Hdiv Security**: **specialized in business logic** vulnerabilities, **real-time protection**, **RASP capabilities** + * โšก **Checkmarx Interactive**: **integrated with CxSAST**, **unified vulnerability management**, **correlation engine** +* ๐Ÿ†“ **Open Source & Community IAST**: + * ๐Ÿ“ฆ **OWASP Dependency-Check**: **limited IAST features**, focuses on **known vulnerable components** + * ๐Ÿ”ง **Custom instrumentation**: **AspectJ for Java**, **monkey patching for Python**, **middleware for Node.js** + * ๐Ÿค– **Research tools**: **JALANGI** (JavaScript), **PHOSPHOR** (Java taint tracking), academic projects +* โ˜๏ธ **Cloud-Native IAST Limitations**: + * ๐Ÿ“‰ **Limited native offerings**: most cloud providers focus on **SAST and DAST** + * ๐Ÿ”„ **RASP integration**: **Runtime Application Self-Protection** tools overlap with IAST functionality + * ๐Ÿณ **Container challenges**: instrumentation complexity in **containerized environments** +* ๐Ÿ“Š **Market reality**: **IAST adoption is 23%** vs **67% SAST** and **52% DAST** ([Application Security Report 2024](https://www.synopsys.com/software-integrity.html)) +* ๐Ÿ’ก **Selection considerations**: **language support**, **performance overhead**, **DevOps integration**, **licensing costs** + +```mermaid +flowchart TD + subgraph "๐Ÿข Commercial IAST Leaders" + Veracode3[๐Ÿ›ก๏ธ Veracode Interactive
โ˜๏ธ Cloud-native, Java/.NET] + Seeker[๐Ÿ” Synopsys Seeker
๐ŸŒ Comprehensive languages] + Hdiv[๐Ÿ›ก๏ธ Hdiv Security
๐Ÿงฉ Business logic focus] + Checkmarx2[โšก Checkmarx Interactive
๐Ÿ”— SAST integration] + end + + subgraph "๐Ÿ†“ Open Source Options" + DepCheck[๐Ÿ“ฆ OWASP Dependency-Check
๐Ÿ“Š Component analysis] + Custom[๐Ÿ”ง Custom Instrumentation
๐Ÿ› ๏ธ AspectJ, middleware] + Research[๐Ÿค– Research Tools
๐ŸŽ“ JALANGI, PHOSPHOR] + end + + subgraph "โ˜๏ธ Cloud & RASP Overlap" + Limited[๐Ÿ“‰ Limited Cloud Native
๐Ÿšง Few native IAST offerings] + RASP[๐Ÿ›ก๏ธ RASP Tools
๐Ÿ”„ Runtime protection overlap] + Container[๐Ÿณ Container Challenges
โš™๏ธ Instrumentation complexity] + end + + subgraph "๐Ÿ“Š Adoption Barriers" + Performance[๐Ÿ“ˆ Performance Overhead
5-15% typical impact] + Complexity[๐Ÿ”ง Implementation Complexity
Agent deployment & config] + Coverage[๐Ÿ“ Language Coverage
Limited framework support] + Cost[๐Ÿ’ฐ Licensing Costs
Per-application pricing] + end + + Veracode3 --> Performance + Seeker --> Complexity + Hdiv --> Coverage + Custom --> Cost + + classDef commercial fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + classDef opensource fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + classDef cloud fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + classDef barriers fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + + class Veracode3,Seeker,Hdiv,Checkmarx2 commercial + class DepCheck,Custom,Research opensource + class Limited,RASP,Container cloud + class Performance,Complexity,Coverage,Cost barriers +``` + +--- + +## ๐Ÿ“ Slide 18 โ€“ โšก IAST Strengths and Limitations + +* โœ… **IAST Superpowers**: + * ๐ŸŽฏ **Extremely low false positives**: **<5% false positive rate** vs 30-40% for SAST + * ๐Ÿ” **Precise vulnerability location**: exact **line of code + runtime context** for faster remediation + * ๐Ÿ“Š **Code coverage insights**: shows **which parts of application were actually tested** + * โšก **Real-time feedback**: detects vulnerabilities **during QA testing** when developers are most engaged + * ๐Ÿงฉ **Business logic testing**: can identify **complex multi-step vulnerabilities** that SAST/DAST miss + * ๐Ÿ”„ **Incremental analysis**: only analyzes **executed code paths** โ†’ more efficient than full SAST scans +* โŒ **IAST Challenges**: + * ๐Ÿ“ˆ **Performance overhead**: **5-15% performance impact** on application during testing + * ๐Ÿ—๏ธ **Deployment complexity**: requires **agent installation** and **runtime configuration** + * ๐Ÿ“š **Limited language support**: fewer supported **frameworks and languages** vs SAST/DAST + * ๐Ÿงช **Test-dependent coverage**: vulnerability detection limited to **QA test execution** scope + * ๐Ÿ’ฐ **Higher costs**: **per-application licensing** can be expensive for large portfolios + * ๐Ÿณ **Container/cloud challenges**: **instrumentation complexity** in modern **containerized environments** +* ๐Ÿ”„ **Best use cases**: **critical applications** with **comprehensive QA testing**, **complex business logic**, **regulatory requirements** +* ๐Ÿ“Š **ROI sweet spot**: applications with **>10,000 lines of code** and **>50% test coverage** see best IAST value + +```mermaid +graph TD + subgraph "โœ… IAST Strengths" + LowFP[๐ŸŽฏ Ultra-Low False Positives
<5% vs 30-40% SAST] + Precise2[๐Ÿ” Precise Location
Line + runtime context] + Coverage2[๐Ÿ“Š Coverage Insights
Tested vs untested code] + RealTime[โšก Real-time Feedback
During QA execution] + BusinessLogic2[๐Ÿงฉ Business Logic
Multi-step vulnerabilities] + Incremental2[๐Ÿ”„ Incremental Analysis
Only executed paths] + end + + subgraph "โŒ IAST Limitations" + PerfOverhead[๐Ÿ“ˆ Performance Overhead
5-15% impact] + DeployComplex[๐Ÿ—๏ธ Deployment Complexity
Agent installation] + LangSupport[๐Ÿ“š Limited Language Support
Fewer frameworks] + TestDependent[๐Ÿงช Test-Dependent Coverage
QA execution scope] + HighCost[๐Ÿ’ฐ Higher Costs
Per-app licensing] + ContainerIssues[๐Ÿณ Container Challenges
Instrumentation complexity] + end + + subgraph "๐ŸŽฏ Ideal Use Cases" + CriticalApps[โญ Critical Applications
High security requirements] + ComprehensiveQA[๐Ÿงช Comprehensive QA
Good test coverage] + ComplexLogic[๐Ÿงฉ Complex Business Logic
Multi-tier workflows] + Compliance[๐Ÿ“‹ Regulatory Requirements
Financial, healthcare] + end + + subgraph "๐Ÿ“Š ROI Factors" + CodeSize[๐Ÿ“ Application Size
>10K lines optimal] + TestCoverage[๐Ÿ“Š Test Coverage
>50% coverage needed] + VulnDensity[๐Ÿ› Vulnerability Density
Historical incident rate] + TeamSize[๐Ÿ‘ฅ Development Team
Dedicated QA resources] + end + + LowFP --> CriticalApps + Precise2 --> ComprehensiveQA + BusinessLogic2 --> ComplexLogic + TestDependent --> Compliance + + PerfOverhead --> CodeSize + DeployComplex --> TestCoverage + HighCost --> VulnDensity + ContainerIssues --> TeamSize + + classDef strength fill:#e8f5e8,stroke:#2e7d32,stroke-width:2px,color:#2c3e50 + classDef limitation fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + classDef usecase fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + classDef roi fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + + class LowFP,Precise2,Coverage2,RealTime,BusinessLogic2,Incremental2 strength + class PerfOverhead,DeployComplex,LangSupport,TestDependent,HighCost,ContainerIssues limitation + class CriticalApps,ComprehensiveQA,ComplexLogic,Compliance usecase + class CodeSize,TestCoverage,VulnDensity,TeamSize roi +``` + +--- + +## ๐Ÿ“ Slide 19 โ€“ ๐ŸŽฏ IAST Implementation Best Practices + +* ๐ŸŽฏ **Strategic IAST Deployment Approach**: + * ๐Ÿ“ˆ **Pilot program**: start with **1-2 critical applications** with **good QA coverage** + * ๐Ÿงช **Staging-first**: deploy agents in **staging environments** before considering production + * ๐Ÿ“Š **Performance baseline**: establish **performance metrics** before agent deployment + * ๐Ÿ”„ **Gradual rollout**: expand to additional applications based on **pilot success** +* ๐Ÿค– **Agent Deployment Strategies**: + * ๐Ÿณ **Containerized agents**: use **sidecar pattern** in Kubernetes environments + * ๐Ÿ—๏ธ **Build-time integration**: embed agents during **application build process** + * ๐Ÿ”ง **Runtime attachment**: dynamic agent attachment for **legacy applications** + * ๐Ÿ“Š **Configuration management**: use **infrastructure-as-code** for agent configuration +* ๐Ÿงช **QA Process Integration**: + * ๐Ÿ“‹ **Test coverage requirements**: ensure **>70% code coverage** for effective IAST results + * ๐Ÿ”„ **Automated test execution**: integrate IAST with **automated regression testing** + * ๐Ÿ‘ฅ **Manual testing protocols**: train QA teams on **security-focused testing scenarios** + * ๐Ÿ“Š **Coverage gap analysis**: identify **untested code paths** for additional test creation +* ๐Ÿ’ก **Performance Monitoring & Optimization**: **resource monitoring**, **agent tuning**, **selective instrumentation**, **result correlation** + +```mermaid +flowchart TD + subgraph "๐ŸŽฏ Implementation Phases" + Plan[๐Ÿ“‹ Planning Phase
App selection, requirements] + Pilot[๐Ÿงช Pilot Deployment
1-2 critical applications] + Tune[๐ŸŽ›๏ธ Performance Tuning
Agent optimization] + Scale[๐Ÿ“ˆ Scaling Phase
Organization rollout] + Optimize[โš™๏ธ Optimization
Continuous improvement] + end + + subgraph "๐Ÿค– Agent Deployment Options" + Sidecar[๐Ÿณ Sidecar Pattern
Kubernetes containers] + BuildTime[๐Ÿ—๏ธ Build Integration
Application packaging] + Runtime[๐Ÿ”ง Runtime Attachment
Dynamic instrumentation] + IaC[๐Ÿ“Š Infrastructure-as-Code
Automated configuration] + end + + subgraph "๐Ÿงช QA Integration" + Coverage[๐Ÿ“Š Test Coverage
>70% requirement] + Automation[๐Ÿค– Automated Testing
Regression suite integration] + Manual[๐Ÿ‘ฅ Manual Testing
Security scenario training] + GapAnalysis[๐Ÿ” Coverage Analysis
Untested path identification] + end + + subgraph "๐Ÿ“Š Success Metrics" + VulnDetection[๐Ÿ› Vulnerability Detection
New issues found] + FalsePositiveRate[๐ŸŽฏ False Positive Rate
<5% target] + PerfImpact[๐Ÿ“ˆ Performance Impact
<10% overhead] + TimeToFix[โฑ๏ธ Time to Remediation
Reduced fix time] + end + + Plan --> Pilot --> Tune --> Scale --> Optimize + + Pilot --> Sidecar + Tune --> BuildTime + Scale --> Runtime + Optimize --> IaC + + Coverage --> VulnDetection + Automation --> FalsePositiveRate + Manual --> PerfImpact + GapAnalysis --> TimeToFix + + classDef phase fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + classDef deployment fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#2c3e50 + classDef qa fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + classDef metrics fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + + class Plan,Pilot,Tune,Scale,Optimize phase + class Sidecar,BuildTime,Runtime,IaC deployment + class Coverage,Automation,Manual,GapAnalysis qa + class VulnDetection,FalsePositiveRate,PerfImpact,TimeToFix metrics +``` + +--- + +## ๐Ÿ“ Slide 20 โ€“ ๐Ÿ”ง Hands-on IAST: Agent-based Testing Setup + +* ๐Ÿ”ง **IAST Agent Configuration Example** (Java Application): + * โ˜• **JVM agent**: add `-javaagent:iast-agent.jar` to **application startup parameters** + * โš™๏ธ **Configuration file**: specify **monitoring rules**, **reporting endpoints**, **performance settings** + * ๐ŸŒ **Network connectivity**: ensure agent can **communicate with IAST server** + * ๐Ÿ“Š **Logging configuration**: enable **agent debugging** during initial setup +* ๐Ÿงช **QA Testing Integration Workflow**: + * ๐Ÿš€ **Application startup**: launch application with **IAST agent** attached + * ๐Ÿงช **Execute test suite**: run **functional**, **integration**, and **security tests** + * ๐Ÿ‘๏ธ **Monitor agent activity**: watch **real-time vulnerability detection** in IAST dashboard + * ๐Ÿ“Š **Review findings**: analyze **vulnerabilities** with **precise code location** and **runtime context** +* ๐Ÿ“Š **Performance Impact Assessment**: + * โฑ๏ธ **Response time monitoring**: measure **API response times** before/after agent + * ๐Ÿ’พ **Memory usage tracking**: monitor **heap utilization** and **garbage collection** + * ๐Ÿ”„ **Throughput analysis**: assess **requests per second** impact + * ๐Ÿ“ˆ **Resource optimization**: tune agent settings to **minimize overhead** +* ๐Ÿ”„ **Result Correlation and Analysis**: combine IAST findings with **SAST results**, identify **confirmed vulnerabilities**, prioritize based on **exploitability** + +```mermaid +flowchart TD + subgraph "๐Ÿ”ง IAST Agent Setup" + JavaApp[โ˜• Java Application
Target application] + AgentJAR[๐Ÿ“ฆ IAST Agent JAR
Instrumentation library] + Config[โš™๏ธ Configuration File
Rules & settings] + Startup[๐Ÿš€ Application Startup
-javaagent parameter] + end + + subgraph "๐Ÿงช QA Testing Execution" + TestSuite[๐Ÿงช Test Suite
Functional & security tests] + Monitoring[๐Ÿ‘๏ธ Real-time Monitoring
Vulnerability detection] + Coverage[๐Ÿ“Š Code Coverage
Execution path tracking] + Findings[๐Ÿ” Vulnerability Findings
Precise location + context] + end + + subgraph "๐Ÿ“Š Performance Assessment" + ResponseTime[โฑ๏ธ Response Time
API latency measurement] + Memory[๐Ÿ’พ Memory Usage
Heap & GC monitoring] + Throughput[๐Ÿ”„ Throughput
Requests per second] + Optimization[๐Ÿ“ˆ Agent Tuning
Performance optimization] + end + + subgraph "๐Ÿ”„ Analysis & Correlation" + IASTResults[๐Ÿ“Š IAST Results
Runtime vulnerabilities] + SASTCorrelation[๐Ÿ”— SAST Correlation
Static analysis comparison] + Prioritization[๐Ÿ“‹ Risk Prioritization
Exploitability assessment] + Remediation[๐Ÿ”ง Remediation Guidance
Fix recommendations] + end + + JavaApp --> AgentJAR --> Config --> Startup + + Startup --> TestSuite --> Monitoring --> Coverage --> Findings + + Monitoring --> ResponseTime + Coverage --> Memory + Findings --> Throughput + TestSuite --> Optimization + + Findings --> IASTResults --> SASTCorrelation --> Prioritization --> Remediation + + classDef setup fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + classDef testing fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#2c3e50 + classDef performance fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + classDef analysis fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + + class JavaApp,AgentJAR,Config,Startup setup + class TestSuite,Monitoring,Coverage,Findings testing + class ResponseTime,Memory,Throughput,Optimization performance + class IASTResults,SASTCorrelation,Prioritization,Remediation analysis +``` + +--- + +## ๐Ÿ“‚ Group 5: CI/CD Pipeline Integration and Automation + +## ๐Ÿ“ Slide 21 โ€“ ๐Ÿš€ Integrating Security Testing into CI/CD Pipelines + +* ๐Ÿš€ **Security Testing Pipeline Strategy**: + * ๐Ÿ—๏ธ **Left-shift approach**: run **SAST** during **build phase** for immediate feedback + * ๐Ÿงช **Middle integration**: execute **IAST** during **QA testing phase** for runtime validation + * ๐ŸŒ **Right-shift validation**: perform **DAST** in **staging/pre-production** for final verification + * ๐Ÿ”„ **Continuous monitoring**: ongoing security assessment in **production** environments +* โš–๏ธ **Quality Gate Implementation**: + * ๐Ÿšฆ **Fail-fast strategy**: **block builds** on critical/high vulnerabilities in main branch + * ๐Ÿ“Š **Risk-based gates**: different thresholds for **development**, **staging**, **production** pipelines + * ๐Ÿ”„ **Progressive enforcement**: **gradual tightening** of security requirements over time + * ๐Ÿšจ **Emergency bypasses**: controlled **override mechanisms** for critical business needs +* โšก **Parallel vs Sequential Execution**: + * โšก **Parallel benefits**: **faster pipeline execution**, independent tool operation + * ๐Ÿ”— **Sequential advantages**: **result correlation**, dependency management, resource optimization + * ๐ŸŽฏ **Hybrid approach**: **SAST parallel** with build, **DAST sequential** after deployment +* ๐Ÿ“Š **Pipeline Performance Optimization**: **caching strategies**, **incremental scanning**, **result persistence**, **smart triggering** + +```mermaid +flowchart LR + subgraph "๐Ÿ—๏ธ CI/CD Pipeline Stages" + Commit[๐Ÿ“ Code Commit
Developer push] + Build[โš™๏ธ Build Stage
Compile & package] + Test[๐Ÿงช Test Stage
QA & Integration] + Deploy[๐Ÿš€ Deploy Stage
Staging deployment] + Prod[๐ŸŒ Production
Live environment] + end + + subgraph "๐Ÿ”’ Security Testing Integration" + SAST2[๐Ÿ”ฌ SAST
Static analysis] + IAST2[๐Ÿงฌ IAST
Interactive testing] + DAST2[๐ŸŒ DAST
Dynamic testing] + Monitor[๐Ÿ“Š Runtime Monitoring
Continuous security] + end + + subgraph "๐Ÿšฆ Quality Gates" + BuildGate[๐Ÿšฆ Build Gate
SAST results check] + TestGate[๐Ÿšฆ Test Gate
IAST findings review] + DeployGate[๐Ÿšฆ Deploy Gate
DAST validation] + ProdGate[๐Ÿšฆ Prod Gate
Monitoring alerts] + end + + Commit --> Build + Build --> Test + Test --> Deploy + Deploy --> Prod + + Build --> SAST2 + Test --> IAST2 + Deploy --> DAST2 + Prod --> Monitor + + SAST2 --> BuildGate + IAST2 --> TestGate + DAST2 --> DeployGate + Monitor --> ProdGate + + BuildGate -->|โŒ Fail| Commit + TestGate -->|โŒ Fail| Build + DeployGate -->|โŒ Fail| Test + ProdGate -->|๐Ÿšจ Alert| Deploy + + classDef pipeline fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + classDef security fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#2c3e50 + classDef gates fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + + class Commit,Build,Test,Deploy,Prod pipeline + class SAST2,IAST2,DAST2,Monitor security + class BuildGate,TestGate,DeployGate,ProdGate gates +``` + +--- + +## ๐Ÿ“ Slide 22 โ€“ ๐Ÿ“Š Tool Orchestration and Security Dashboard Creation + +* ๐Ÿ“Š **Multi-Tool Result Aggregation**: + * ๐Ÿ”„ **Data normalization**: convert **different tool formats** into **unified vulnerability model** + * ๐ŸŽฏ **Deduplication logic**: identify **same vulnerability** found by **multiple tools** + * ๐Ÿ“ˆ **Risk scoring**: combine **CVSS scores**, **exploitability**, **business context** + * ๐Ÿท๏ธ **Vulnerability lifecycle**: track findings from **detection** through **remediation** +* ๐ŸŽ›๏ธ **Security Orchestration Platforms**: + * ๐Ÿ›ก๏ธ **DefectDojo**: **open-source** vulnerability management with **140+ tool integrations** + * ๐Ÿ”— **ThreadFix**: **commercial platform** with **advanced correlation** and **application mapping** + * ๐Ÿ“Š **Snyk**: **developer-first** platform with **IDE**, **SCM**, and **CI/CD** integrations + * โ˜๏ธ **Cloud-native**: **AWS Security Hub**, **Azure Security Center**, **Google Security Command Center** +* ๐Ÿ“ˆ **Dashboard Design Principles**: + * ๐Ÿ‘ฅ **Role-based views**: **executives** see trends, **developers** see actionable items, **security** sees details + * ๐ŸŽฏ **Actionable insights**: focus on **"what to fix first"** rather than raw vulnerability counts + * ๐Ÿ“Š **Trend analysis**: show **security posture** improvements over time + * ๐Ÿšจ **Alert fatigue prevention**: intelligent notifications based on **priority** and **change** +* ๐Ÿค– **Automation and Workflows**: **auto-assignment** to developers, **JIRA integration**, **SLA tracking**, **compliance reporting** + +```mermaid +flowchart TD + subgraph "๐Ÿ› ๏ธ Security Tools" + SAST3[๐Ÿ”ฌ SAST Tools
SonarQube, Checkmarx] + DAST3[๐ŸŒ DAST Tools
ZAP, Veracode] + IAST3[๐Ÿงฌ IAST Tools
Seeker, Hdiv] + SCA[๐Ÿ“ฆ SCA Tools
Snyk, WhiteSource] + Secrets[๐Ÿ”‘ Secret Scanning
GitLeaks, TruffleHog] + end + + subgraph "๐Ÿ”„ Orchestration Layer" + Normalize[๐Ÿ“Š Data Normalization
Unified vulnerability format] + Dedupe[๐ŸŽฏ Deduplication
Same vuln detection] + Score[๐Ÿ“ˆ Risk Scoring
CVSS + context] + Workflow[๐Ÿ”„ Workflow Engine
Assignment & tracking] + end + + subgraph "๐Ÿ“Š Security Dashboard" + Executive[๐Ÿ‘” Executive View
Trends & KPIs] + Developer[๐Ÿ‘จโ€๐Ÿ’ป Developer View
Actionable items] + Security[๐Ÿ›ก๏ธ Security View
Detailed analysis] + Compliance[๐Ÿ“‹ Compliance View
Audit reports] + end + + subgraph "๐Ÿ”— Integration Points" + JIRA[๐ŸŽซ JIRA Integration
Ticket management] + Slack[๐Ÿ’ฌ Slack Alerts
Team notifications] + Email[๐Ÿ“ง Email Reports
Scheduled summaries] + API[๐Ÿ”Œ REST APIs
Custom integrations] + end + + SAST3 --> Normalize + DAST3 --> Normalize + IAST3 --> Dedupe + SCA --> Score + Secrets --> Workflow + + Normalize --> Executive + Dedupe --> Developer + Score --> Security + Workflow --> Compliance + + Executive --> JIRA + Developer --> Slack + Security --> Email + Compliance --> API + + classDef tools fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + classDef orchestration fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#2c3e50 + classDef dashboard fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + classDef integration fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + + class SAST3,DAST3,IAST3,SCA,Secrets tools + class Normalize,Dedupe,Score,Workflow orchestration + class Executive,Developer,Security,Compliance dashboard + class JIRA,Slack,Email,API integration +``` + +--- + +## ๐Ÿ“ Slide 23 โ€“ โš–๏ธ Balancing Security and Development Velocity + +* โš–๏ธ **The Velocity vs Security Dilemma**: + * โšก **Developer pressure**: **feature delivery deadlines** vs **security requirements** + * ๐Ÿ“Š **False positive fatigue**: too many **non-actionable alerts** slow development + * ๐Ÿšฆ **Quality gate friction**: overly strict gates can **block legitimate releases** + * ๐Ÿ’ฐ **Business pressure**: **time-to-market** vs **risk tolerance** +* ๐ŸŽฏ **Risk-Based Security Approach**: + * ๐Ÿ“Š **Contextual risk scoring**: consider **data sensitivity**, **user exposure**, **attack surface** + * ๐Ÿท๏ธ **Application classification**: **critical**, **high**, **medium**, **low** risk tiers + * ๐Ÿ”„ **Progressive enforcement**: **stricter rules** for higher-risk applications + * โฐ **Time-based thresholds**: **immediate fixes** for critical, **30 days** for high, **next release** for medium +* ๐Ÿš€ **Developer Experience Optimization**: + * ๐Ÿ’ป **IDE integration**: **real-time feedback** without breaking developer flow + * ๐Ÿง  **Smart notifications**: **context-aware alerts** with **clear remediation guidance** + * ๐ŸŽฏ **Just-in-time training**: **educational content** delivered when vulnerabilities found + * ๐Ÿ† **Gamification**: **security achievement badges**, **vulnerability fix leaderboards** +* ๐Ÿ”„ **Emergency Response Procedures**: **bypass mechanisms**, **post-deployment fixes**, **incident response**, **lessons learned** + +```mermaid +graph TD + subgraph "โš–๏ธ Balancing Factors" + Velocity[โšก Development Velocity
Feature delivery speed] + Security[๐Ÿ›ก๏ธ Security Requirements
Risk mitigation needs] + Business[๐Ÿ’ฐ Business Pressure
Time-to-market demands] + Compliance[๐Ÿ“‹ Compliance Needs
Regulatory requirements] + end + + subgraph "๐ŸŽฏ Risk-Based Strategy" + Critical[๐Ÿ”ด Critical Apps
Strict security gates] + High[๐ŸŸก High Risk Apps
Moderate enforcement] + Medium[๐Ÿ”ต Medium Risk Apps
Standard controls] + Low[โšช Low Risk Apps
Minimal gates] + end + + subgraph "๐Ÿš€ Developer Experience" + IDE2[๐Ÿ’ป IDE Integration
Real-time feedback] + Smart[๐Ÿง  Smart Notifications
Context-aware alerts] + Training2[๐ŸŽฏ Just-in-time Learning
Educational content] + Gamify[๐Ÿ† Gamification
Achievement system] + end + + subgraph "๐Ÿ“Š Success Metrics" + DeployFreq[๐Ÿ“ˆ Deployment Frequency
Releases per week] + LeadTime[โฑ๏ธ Lead Time
Commit to production] + MTTR2[๐Ÿ”ง Mean Time to Recovery
Incident resolution] + VulnFix[๐Ÿ› Vulnerability Fix Rate
Time to remediation] + end + + Velocity --> Critical + Security --> High + Business --> Medium + Compliance --> Low + + Critical --> IDE2 + High --> Smart + Medium --> Training2 + Low --> Gamify + + IDE2 --> DeployFreq + Smart --> LeadTime + Training2 --> MTTR2 + Gamify --> VulnFix + + classDef factors fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + classDef strategy fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#2c3e50 + classDef experience fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + classDef metrics fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + + class Velocity,Security,Business,Compliance factors + class Critical,High,Medium,Low strategy + class IDE2,Smart,Training2,Gamify experience + class DeployFreq,LeadTime,MTTR2,VulnFix metrics +``` + +--- + +## ๐Ÿ“ Slide 24 โ€“ ๐Ÿ”„ Advanced Integration Patterns and GitOps + +* ๐Ÿ”„ **GitOps Security Integration**: + * ๐Ÿ“‚ **Security-as-Code**: store **security policies**, **scan configurations**, **quality gates** in Git + * ๐Ÿค– **Automated policy updates**: **GitOps operators** sync security configurations across environments + * ๐Ÿ“Š **Immutable security**: **version-controlled** security settings prevent **configuration drift** + * ๐Ÿ”„ **Rollback capabilities**: **revert security changes** using Git history +* ๐Ÿ—๏ธ **Infrastructure-as-Code (IaC) Security Testing**: + * โ˜๏ธ **Cloud formation scanning**: **Terraform**, **ARM templates**, **CloudFormation** security validation + * ๐Ÿณ **Container security**: **Dockerfile** scanning, **image vulnerability** assessment, **runtime protection** + * โ˜ธ๏ธ **Kubernetes security**: **YAML manifest** scanning, **RBAC validation**, **network policy** checking + * ๐Ÿ“‹ **Policy enforcement**: **Open Policy Agent (OPA)**, **Gatekeeper**, **Falco** integration +* ๐Ÿ” **Advanced Pipeline Patterns**: + * ๐Ÿ”„ **Multi-stage pipelines**: **security testing** at **build**, **test**, **deploy**, **runtime** stages + * ๐ŸŒ **Multi-environment validation**: **progressive deployment** with security validation at each stage + * ๐Ÿ”€ **Branching strategies**: different **security requirements** for **feature**, **develop**, **main** branches + * ๐Ÿ“Š **Compliance pipelines**: automated **audit trails**, **evidence collection**, **regulatory reporting** +* ๐Ÿค– **AI and Automation**: **ML-powered** vulnerability prioritization, **automated** remediation suggestions, **intelligent** false positive reduction + +```mermaid +flowchart TD + subgraph "๐Ÿ”„ GitOps Security Model" + GitRepo[๐Ÿ“‚ Git Repository
Security policies & configs] + GitOpsOperator[๐Ÿค– GitOps Operator
Automated sync] + SecurityConfigs[โš™๏ธ Security Configurations
Immutable settings] + PolicyEngine[๐Ÿ“‹ Policy Engine
OPA, Gatekeeper] + end + + subgraph "๐Ÿ—๏ธ IaC Security Testing" + Terraform[โ˜๏ธ Terraform
Infrastructure code] + Dockerfile[๐Ÿณ Dockerfile
Container definitions] + K8sManifests[โ˜ธ๏ธ K8s Manifests
Deployment configs] + IaCScanner[๐Ÿ” IaC Scanner
Configuration validation] + end + + subgraph "๐Ÿ”€ Advanced Pipeline Patterns" + FeatureBranch[๐ŸŒฟ Feature Branch
Basic security checks] + DevelopBranch[๐Ÿšง Develop Branch
Comprehensive testing] + MainBranch[๐ŸŽฏ Main Branch
Full security validation] + MultiStage[๐ŸŽญ Multi-stage Deploy
Progressive validation] + end + + subgraph "๐Ÿค– AI-Powered Automation" + MLPrioritization[๐Ÿง  ML Prioritization
Risk-based ranking] + AutoRemediation[๐Ÿ”ง Auto Remediation
Fix suggestions] + FalsePositiveML[๐ŸŽฏ FP Reduction
ML-powered filtering] + PredictiveAnalysis[๐Ÿ“ˆ Predictive Analysis
Trend forecasting] + end + + GitRepo --> GitOpsOperator --> SecurityConfigs --> PolicyEngine + + Terraform --> IaCScanner + Dockerfile --> IaCScanner + K8sManifests --> IaCScanner + + FeatureBranch --> DevelopBranch --> MainBranch --> MultiStage + + PolicyEngine --> MLPrioritization + IaCScanner --> AutoRemediation + MultiStage --> FalsePositiveML + MLPrioritization --> PredictiveAnalysis + + classDef gitops fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + classDef iac fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + classDef patterns fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#2c3e50 + classDef ai fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + + class GitRepo,GitOpsOperator,SecurityConfigs,PolicyEngine gitops + class Terraform,Dockerfile,K8sManifests,IaCScanner iac + class FeatureBranch,DevelopBranch,MainBranch,MultiStage patterns + class MLPrioritization,AutoRemediation,FalsePositiveML,PredictiveAnalysis ai +``` + +--- + +## ๐Ÿ“ Slide 25 โ€“ ๐ŸŒŸ Modern Trends and Future of Application Security Testing + +* ๐Ÿค– **AI and Machine Learning Revolution**: + * ๐Ÿง  **Smart vulnerability detection**: **ML models** trained on **millions of code patterns** reduce false positives by **60%** + * ๐ŸŽฏ **Intelligent prioritization**: **AI-powered risk scoring** considers **exploit probability**, **business impact**, **environmental context** + * ๐Ÿ”ง **Automated remediation**: **AI-generated** fix suggestions with **code patches** for common vulnerability patterns + * ๐Ÿ“ˆ **Predictive analysis**: **ML models** predict **future vulnerability hotspots** based on code changes and historical data +* ๐Ÿ”„ **Shift-Everywhere Security**: + * โฌ…๏ธ **Shift-left expansion**: security testing **in IDEs**, **pre-commit hooks**, **code review** integration + * โžก๏ธ **Shift-right adoption**: **production security monitoring**, **runtime protection**, **continuous compliance** + * ๐Ÿ”„ **Shift-everywhere**: security considerations **throughout entire** software lifecycle +* โ˜๏ธ **Cloud-Native and Serverless Security**: + * ๐Ÿ—๏ธ **Serverless function scanning**: **AWS Lambda**, **Azure Functions**, **Google Cloud Functions** security testing + * ๐Ÿณ **Container-native security**: **admission controllers**, **runtime monitoring**, **image signing** workflows + * โ˜ธ๏ธ **Kubernetes security**: **pod security standards**, **network policies**, **service mesh** security validation +* ๐Ÿ“ฆ **Supply Chain Security Integration**: **SBOM generation**, **dependency signing**, **provenance tracking**, **vulnerability disclosure** automation +* ๐Ÿ”ฎ **Emerging technologies**: **quantum-safe cryptography** testing, **WebAssembly security**, **edge computing** security validation + +```mermaid +flowchart TD + subgraph "๐Ÿค– AI/ML Revolution" + SmartDetection[๐Ÿง  Smart Detection
60% FP reduction] + IntelligentPrio[๐ŸŽฏ Intelligent Prioritization
Context-aware scoring] + AutoRemediation2[๐Ÿ”ง Auto Remediation
AI-generated fixes] + Predictive[๐Ÿ“ˆ Predictive Analysis
Future hotspot detection] + end + + subgraph "๐Ÿ”„ Shift-Everywhere" + ShiftLeft[โฌ…๏ธ Shift-Left++
IDE, pre-commit, review] + ShiftRight[โžก๏ธ Shift-Right
Production monitoring] + ShiftEverywhere[๐Ÿ”„ Shift-Everywhere
Full lifecycle security] + end + + subgraph "โ˜๏ธ Cloud-Native Evolution" + Serverless[๐Ÿ—๏ธ Serverless Security
Function scanning] + Containers[๐Ÿณ Container-Native
Runtime protection] + Kubernetes[โ˜ธ๏ธ K8s Security
Policy enforcement] + ServiceMesh[๐Ÿ•ธ๏ธ Service Mesh
Zero-trust networking] + end + + subgraph "๐Ÿ”ฎ Future Technologies" + QuantumSafe[๐Ÿ” Quantum-Safe Crypto
Post-quantum algorithms] + WebAssembly[โšก WebAssembly Security
WASM runtime protection] + EdgeComputing[๐ŸŒ Edge Security
Distributed validation] + SupplyChain[๐Ÿ“ฆ Supply Chain++
SBOM, provenance, signing] + end + + subgraph "๐Ÿ“Š 2025-2030 Predictions" + AIAdoption[๐Ÿค– 90% AI Integration
ML-powered testing] + RealTimeSec[โšก Real-time Security
Instant vulnerability detection] + ZeroTouchSec[๐Ÿคฒ Zero-touch Security
Fully automated remediation] + QuantumReady[๐Ÿ”ฎ Quantum-ready
Post-quantum crypto standard] + end + + SmartDetection --> AIAdoption + ShiftEverywhere --> RealTimeSec + ServiceMesh --> ZeroTouchSec + QuantumSafe --> QuantumReady + + classDef ai fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + classDef shift fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + classDef cloud fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#2c3e50 + classDef future fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + classDef predictions fill:#fce4ec,stroke:#c2185b,stroke-width:2px,color:#2c3e50 + + class SmartDetection,IntelligentPrio,AutoRemediation2,Predictive ai + class ShiftLeft,ShiftRight,ShiftEverywhere shift + class Serverless,Containers,Kubernetes,ServiceMesh cloud + class QuantumSafe,WebAssembly,EdgeComputing,SupplyChain future + class AIAdoption,RealTimeSec,ZeroTouchSec,QuantumReady predictions +``` + +--- + +## ๐Ÿ“ Slide 26 โ€“ ๐ŸŽฏ Summary & Key Takeaways + +* ๐ŸŽฏ **The Three Pillars of Application Security Testing**: + * ๐Ÿ”ฌ **SAST**: Early detection, complete coverage, **integrate in build phase** + * ๐ŸŒ **DAST**: Real-world validation, configuration testing, **run in staging** + * ๐Ÿงฌ **IAST**: Best of both worlds, low false positives, **deploy during QA** +* ๐Ÿš€ **CI/CD Integration Success Formula**: + * โš–๏ธ **Balance velocity with security**: risk-based approach, smart quality gates + * ๐Ÿ“Š **Tool orchestration**: unified dashboards, deduplication, correlation + * ๐Ÿ‘ฅ **Developer experience**: IDE integration, just-in-time training, gamification + * ๐Ÿ”„ **Continuous improvement**: metrics-driven optimization, feedback loops +* ๐ŸŒŸ **Future-Ready Security Testing**: + * ๐Ÿค– **Embrace AI/ML**: intelligent prioritization, automated remediation + * ๐Ÿ”„ **Shift-everywhere mindset**: security throughout entire lifecycle + * โ˜๏ธ **Cloud-native focus**: containers, serverless, Kubernetes security + * ๐Ÿ“ฆ **Supply chain protection**: SBOM, signing, provenance tracking +* ๐Ÿ’ก **Remember**: **Perfect security is impossible**, but **continuous improvement** through **automated testing** makes applications **significantly more secure** while **maintaining development velocity** + +```mermaid +graph TD + subgraph "๐Ÿ† Key Success Factors" + Strategy[๐Ÿ“‹ Security Testing Strategy
SAST + DAST + IAST] + Integration[๐Ÿ”— CI/CD Integration
Seamless workflow] + Culture[๐Ÿ‘ฅ Security Culture
Developer engagement] + Automation[๐Ÿค– Automation
Tool orchestration] + end + + subgraph "๐Ÿ“Š Success Metrics" + VelocityMetric[โšก Development Velocity
Maintained or improved] + SecurityPosture[๐Ÿ›ก๏ธ Security Posture
Vulnerability reduction] + DeveloperSat[๐Ÿ‘จโ€๐Ÿ’ป Developer Satisfaction
Tool adoption rate] + BusinessValue[๐Ÿ’ฐ Business Value
Risk mitigation ROI] + end + + subgraph "๐Ÿš€ Next Steps" + Assessment[๐Ÿ“Š Current State Assessment
Gap analysis] + Pilot[๐Ÿงช Pilot Implementation
Start small, learn fast] + Scale[๐Ÿ“ˆ Scaling Strategy
Organization-wide rollout] + Optimize[โš™๏ธ Continuous Optimization
Metrics-driven improvement] + end + + Strategy --> VelocityMetric + Integration --> SecurityPosture + Culture --> DeveloperSat + Automation --> BusinessValue + + VelocityMetric --> Assessment + SecurityPosture --> Pilot + DeveloperSat --> Scale + BusinessValue --> Optimize + + classDef success fill:#e8f5e8,stroke:#2e7d32,stroke-width:3px,color:#2c3e50 + classDef metrics fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + classDef next fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + + class Strategy,Integration,Culture,Automation success + class VelocityMetric,SecurityPosture,DeveloperSat,BusinessValue metrics + class Assessment,Pilot,Scale,Optimize next +``` diff --git a/lectures/lec6.md b/lectures/lec6.md new file mode 100644 index 00000000..b4ba4ad7 --- /dev/null +++ b/lectures/lec6.md @@ -0,0 +1,2541 @@ +# ๐Ÿ“ŒLecture 6 - Infrastructure-as-Code Security: Terraform, Pulumi, Ansible & Policy-as-Code + +## ๐Ÿ“‚ Group 1: IaC Foundations + +## ๐Ÿ“ Slide 1 โ€“ ๐ŸŒ What is Infrastructure-as-Code (IaC)? + +* ๐Ÿงฉ **Infrastructure-as-Code (IaC)** = managing infrastructure through **machine-readable definition files** rather than manual configuration. +* ๐Ÿ“ Key principle: **"Infrastructure should be versioned, tested, and deployed like application code."** +* โšก Core benefits: + * ๐Ÿ”„ **Repeatability** โ†’ deploy identical environments every time + * ๐Ÿ“ฆ **Version control** โ†’ track changes, rollback, audit history + * ๐Ÿš€ **Automation** โ†’ eliminate manual errors, increase speed + * ๐Ÿงช **Testing** โ†’ validate infrastructure before deployment +* ๐Ÿ“Š **Industry adoption:** 76% of organizations use IaC in production (HashiCorp State of Cloud Strategy Survey 2024) +* ๐Ÿ”— **Learn more:** [What is Infrastructure as Code? (HashiCorp)](https://www.hashicorp.com/resources/what-is-infrastructure-as-code), [IaC Best Practices (AWS)](https://docs.aws.amazon.com/whitepapers/latest/introduction-devops-aws/infrastructure-as-code.html) + +```mermaid +flowchart LR + Traditional[๐Ÿ–ฑ๏ธ Manual Configuration
ClickOps, Console] -->|Problems| Issues[โŒ Inconsistent
โŒ Untracked
โŒ Slow] + IaC[๐Ÿ“ Infrastructure-as-Code
Terraform, Pulumi, Ansible] -->|Benefits| Wins[โœ… Repeatable
โœ… Versioned
โœ… Fast] + + style Traditional fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + style IaC fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + style Issues fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + style Wins fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 +``` + +--- + +### ๐Ÿ“ˆ Evolution Timeline + +```mermaid +timeline + title ๐Ÿ•ฐ๏ธ Infrastructure Management Evolution + 1990s : ๐Ÿ”ง Manual Configuration
Physical servers, manual setup + 2000s : ๐Ÿ“œ Shell Scripts
Bash automation, brittle + 2005 : โš™๏ธ Configuration Management
Puppet, Chef + 2012 : ๐Ÿ“ฆ Ansible Released
Agentless, YAML-based + 2014 : ๐Ÿ—๏ธ Terraform Released
Declarative, multi-cloud + 2018 : ๐Ÿš€ Pulumi Released
Real programming languages + 2025 : ๐Ÿค– AI-Assisted IaC
Policy-as-code, GitOps +``` + +--- + +### ๐Ÿงฉ Declarative vs Imperative + +* ๐ŸŽฏ **Declarative (What):** + * Define **desired end state** + * Tool figures out **how to get there** + * Examples: Terraform, CloudFormation, Kubernetes YAML + * ๐Ÿ“ "I want 3 servers with this config" +* ๐Ÿ› ๏ธ **Imperative (How):** + * Define **exact steps** to execute + * Explicit **command sequence** + * Examples: Bash scripts, Ansible playbooks (can be both) + * ๐Ÿ“ "Create server 1, then server 2, then server 3" + +```mermaid +flowchart TD + subgraph Declarative + D1[๐Ÿ“‹ Desired State - 3 web servers] --> D2[๐Ÿค– Tool Calculates Diff] + D2 --> D3[โšก Executes Changes] + end + + subgraph Imperative + I1[๐Ÿ“ Step 1: Create server] --> I2[๐Ÿ“ Step 2: Install nginx] + I2 --> I3[๐Ÿ“ Step 3: Configure firewall] + end + + style Declarative fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + style Imperative fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 +``` + +
+๐Ÿ’ญ Interactive Quiz: Is Ansible declarative or imperative? + +**Answer:** **Both!** ๐ŸŽฏ + +* Ansible playbooks use **declarative modules** (e.g., `state: present`) +* But executed in **imperative order** (top to bottom) +* This makes Ansible a **hybrid approach** +* Often called **"procedural with declarative elements"** + +
+ +--- + +## ๐Ÿ“ Slide 2 โ€“ ๐Ÿšจ Why IaC Security Matters + +* ๐Ÿ”ฅ **Infrastructure misconfigurations = #1 cloud security risk** + * 67% of cloud breaches stem from misconfigurations (IBM Cost of Data Breach Report 2024) + * Average breach cost: **$4.88M** (up 10% from 2023) +* ๐Ÿ’ฅ **Major incidents caused by IaC failures:** + * ๐Ÿฆ **Capital One (2019):** Misconfigured WAF โ†’ 100M records exposed โ†’ $190M fine + * โšก **Tesla (2018):** Public Kubernetes dashboard โ†’ crypto mining attack + * ๐Ÿชฃ **Pentagon S3 buckets (2017):** 1.8B social media posts exposed publicly +* โš ๏ธ **IaC amplifies both security AND insecurity:** + * โœ… Good config โ†’ deployed consistently everywhere + * โŒ Bad config โ†’ replicated across all environments instantly +* ๐Ÿ“Š **Attack surface expansion:** IaC tools have access to **everything** (cloud credentials, secrets, production systems) + +```mermaid +flowchart TD + subgraph "โŒ Traditional Manual Config" + M1[Manual Error] --> M2[Single Server Affected] + end + + subgraph "๐Ÿ”ฅ IaC Without Security" + I1[Misconfigured Template] --> I2[Automated Deployment] + I2 --> I3[โš ๏ธ ALL Environments Affected] + I3 --> I4[๐Ÿ’ฅ Massive Blast Radius] + end + + subgraph "โœ… IaC With Security" + S1[Template with Security Checks] --> S2[Automated Scanning] + S2 --> S3[โŒ Blocks Bad Config] + S2 --> S4[โœ… Deploys Secure Config] + end + + style M1 fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + style I1 fill:#ffebee,stroke:#d32f2f,stroke-width:3px,color:#2c3e50 + style I4 fill:#ffebee,stroke:#d32f2f,stroke-width:3px,color:#2c3e50 + style S1 fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + style S4 fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 +``` + +--- + +### ๐ŸŽฏ Real-World Impact Statistics + +* ๐Ÿ“Š **95% of cloud breaches** are due to customer misconfigurations, not cloud provider failures (Gartner) +* โฐ **Average time to detect misconfiguration:** 279 days (IBM) +* ๐Ÿ’ฐ **Cost of remediation:** + * Fix in development: **$100** + * Fix in production: **$10,000+** + * Fix after breach: **$1,000,000+** +* ๐Ÿ” **Most common IaC security issues:** + * 43% โ†’ Hardcoded secrets + * 38% โ†’ Overly permissive IAM roles + * 31% โ†’ Unencrypted storage + * 29% โ†’ Public resource exposure + +
+๐Ÿ’ญ Discussion Question: Why do you think misconfigurations happen so frequently? + +**Common Reasons:** + +1. ๐Ÿƒโ€โ™‚๏ธ **Speed over security** โ†’ "Move fast, secure later" mentality +2. ๐Ÿ“š **Complexity** โ†’ Cloud services have thousands of configuration options +3. ๐Ÿ‘ฅ **Lack of expertise** โ†’ Developers learning infrastructure on the fly +4. ๐Ÿ”„ **Copy-paste culture** โ†’ Reusing insecure examples from internet +5. ๐Ÿšซ **No guardrails** โ†’ Missing automated security checks in pipelines +6. ๐Ÿ‘๏ธ **Visibility gaps** โ†’ Hard to audit infrastructure across multiple clouds + +**Solution:** Shift-left security + Policy-as-code + Automated scanning! + +
+ +--- + +## ๐Ÿ“ Slide 3 โ€“ ๐Ÿ“Š IaC Tool Landscape Overview + +* ๐Ÿ—๏ธ **HashiCorp Terraform** (2014) + * ๐ŸŒ Multi-cloud, declarative HCL (HashiCorp Configuration Language) + * ๐Ÿ“ฆ 40,000+ providers, massive ecosystem + * ๐Ÿ”ง State management with remote backends + * ๐Ÿ’ผ Market leader: 67% adoption (CNCF Survey 2024) +* ๐Ÿš€ **Pulumi** (2018) + * ๐Ÿ’ป Real programming languages (TypeScript, Python, Go, C#, Java) + * ๐Ÿ” Built-in secrets management + * ๐Ÿงช Full testing frameworks (unit, integration) + * ๐Ÿ“ˆ Growing adoption: 18% (up from 9% in 2023) +* โš™๏ธ **Ansible** (2012, Red Hat) + * ๐Ÿชถ Agentless SSH-based automation + * ๐Ÿ“ YAML playbooks, imperative + declarative + * ๐Ÿ”‘ Ansible Vault for secrets + * ๐Ÿข Popular for config management: 52% adoption +* โ˜๏ธ **Cloud-Native Tools** + * ๐Ÿ”ถ **AWS CloudFormation** (2011) โ†’ JSON/YAML templates + * ๐Ÿ”ต **Azure Resource Manager (ARM)** (2014) โ†’ JSON templates + * ๐Ÿ”ท **Google Cloud Deployment Manager** (2015) โ†’ YAML/Jinja2 + +```mermaid +flowchart TD + subgraph "๐Ÿ—๏ธ Provisioning Tools" + TF[๐Ÿ—๏ธ Terraform
Multi-cloud, HCL] + PU[๐Ÿš€ Pulumi
Real code, TypeScript/Python] + CF[โ˜๏ธ CloudFormation
AWS-native] + end + + subgraph "โš™๏ธ Configuration Management" + AN[โš™๏ธ Ansible
Agentless, YAML] + CH[๐Ÿ‘จโ€๐Ÿณ Chef
Ruby DSL] + PU2[๐Ÿถ Puppet
Declarative] + end + + subgraph "โ˜ธ๏ธ Container/K8s" + K8[โ˜ธ๏ธ Kubernetes YAML
Declarative manifests] + HE[โŽˆ Helm
Templating engine] + KU[๐ŸŽจ Kustomize
Overlay system] + end + + Cloud[โ˜๏ธ Cloud Infrastructure] --> TF + Cloud --> PU + Cloud --> CF + + Servers[๐Ÿ–ฅ๏ธ Servers/VMs] --> AN + Servers --> CH + Servers --> PU2 + + Containers[๐Ÿณ Containers] --> K8[โ˜ธ๏ธ Kubernetes YAML] + Containers --> HE + Containers --> KU + + style TF fill:#7B42BC,stroke:#5C2D91,stroke-width:2px,color:#fff + style PU fill:#8A3FFC,stroke:#6929C4,stroke-width:2px,color:#fff + style AN fill:#EE0000,stroke:#CC0000,stroke-width:2px,color:#fff +``` + +--- + +### โš–๏ธ Quick Comparison Matrix + +| Feature | Terraform | Pulumi | Ansible | +|---------|-----------|--------|---------| +| ๐Ÿ—ฃ๏ธ **Language** | HCL (custom DSL) | TypeScript, Python, Go, C#, Java | YAML | +| ๐ŸŽฏ **Approach** | Declarative | Declarative (with code) | Imperative + Declarative | +| โ˜๏ธ **Multi-cloud** | โœ… Best-in-class | โœ… Excellent | โš ๏ธ Limited | +| ๐Ÿ”ง **Learning curve** | Medium | Medium-High (need programming) | Low-Medium | +| ๐Ÿงช **Testing** | Limited (terratest) | โœ… Full unit/integration tests | Medium (molecule) | +| ๐Ÿ” **Secrets** | Manual integration | โœ… Built-in encryption | Ansible Vault | +| ๐Ÿ“Š **State mgmt** | Remote backends | Pulumi Cloud/self-hosted | No state (idempotent) | +| ๐Ÿ’ฐ **Cost** | Open-source (Cloud paid) | Open-source (Cloud paid) | Open-source (Tower paid) | +| ๐Ÿข **Best for** | Infrastructure provisioning | Modern dev teams | Config management, VMs | + +
+๐Ÿ’ญ Interactive Question: Which tool would you choose for a greenfield cloud-native startup? + +**There's no single right answer!** But here's a thought framework: + +**Choose Terraform if:** +* โœ… Team is infrastructure-focused +* โœ… Need widest provider ecosystem +* โœ… Declarative mindset preferred +* โœ… Large community and examples available + +**Choose Pulumi if:** +* โœ… Team is developer-heavy +* โœ… Want full programming language power +* โœ… Need sophisticated testing +* โœ… Already using TypeScript/Python + +**Choose Ansible if:** +* โœ… Managing existing servers/VMs +* โœ… Configuration management is primary need +* โœ… Team prefers simple YAML +* โœ… Want agentless approach + +**Modern approach:** Many teams use **Terraform + Ansible** together: +* Terraform provisions infrastructure +* Ansible configures applications + +
+ +--- + +## ๐Ÿ“ Slide 4 โ€“ ๐Ÿ”’ Common IaC Security Risks + +* ๐Ÿ”‘ **Hardcoded Secrets (43% of issues)** + * API keys, passwords, tokens in plain text + * Committed to version control โ†’ permanent history + * Attackers scan GitHub for leaked credentials 24/7 + * Example: `aws_access_key = "AKIAIOSFODNN7EXAMPLE"` +* ๐Ÿ”“ **Overly Permissive IAM/RBAC (38%)** + * `Action: "*"` โ†’ grants ALL permissions + * `Resource: "*"` โ†’ applies to ALL resources + * Service accounts with admin rights + * No least-privilege enforcement +* ๐ŸŒ **Public Exposure (31%)** + * S3 buckets with public read/write + * Databases accessible from `0.0.0.0/0` + * Security groups allowing all ports + * Load balancers exposing internal services +* ๐Ÿ” **Missing Encryption (29%)** + * Unencrypted storage (S3, EBS, databases) + * No encryption in transit (HTTP instead of HTTPS) + * Missing KMS key management + * Plaintext backups +* ๐Ÿ“‹ **Compliance Violations (26%)** + * Missing required tags (cost center, environment) + * Resources in non-approved regions + * Violating data residency requirements + * No audit logging enabled + +```mermaid +flowchart TD + subgraph "๐Ÿ”ฅ Top IaC Security Risks" + R1[๐Ÿ”‘ Hardcoded Secrets
43%] + R2[๐Ÿ”“ Overly Permissive IAM
38%] + R3[๐ŸŒ Public Exposure
31%] + R4[๐Ÿ” Missing Encryption
29%] + R5[๐Ÿ“‹ Compliance Violations
26%] + end + + R1 -->|Leads to| B1[๐Ÿ’ฅ Credential Theft] + R2 -->|Leads to| B2[๐Ÿ’ฅ Privilege Escalation] + R3 -->|Leads to| B3[๐Ÿ’ฅ Data Breach] + R4 -->|Leads to| B4[๐Ÿ’ฅ Data Exposure] + R5 -->|Leads to| B5[๐Ÿ’ฅ Regulatory Fines] + + B1 --> Impact[๐Ÿ”ฅ Total Compromise] + B2 --> Impact + B3 --> Impact + B4 --> Impact + B5 --> Impact + + style R1 fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + style R2 fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + style R3 fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + style R4 fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + style R5 fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + style Impact fill:#b71c1c,stroke:#d32f2f,stroke-width:3px,color:#fff +``` + +--- + +### ๐Ÿ’ป Example: Vulnerable Terraform Code + +```hcl +# โŒ INSECURE EXAMPLE - DO NOT USE IN PRODUCTION! + +# Risk 1: Hardcoded credentials +provider "aws" { + region = "us-east-1" + access_key = "AKIAIOSFODNN7EXAMPLE" # ๐Ÿ”ฅ HARDCODED! + secret_key = "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY" # ๐Ÿ”ฅ LEAKED! +} + +# Risk 2: Public S3 bucket +resource "aws_s3_bucket" "data" { + bucket = "my-company-data" + acl = "public-read" # ๐ŸŒ PUBLIC TO THE INTERNET! +} + +# Risk 3: Overly permissive security group +resource "aws_security_group" "web" { + ingress { + from_port = 0 # ๐Ÿ”“ ALL PORTS! + to_port = 65535 # ๐Ÿ”“ ALL PORTS! + protocol = "-1" # ๐Ÿ”“ ALL PROTOCOLS! + cidr_blocks = ["0.0.0.0/0"] # ๐ŸŒ FROM ANYWHERE! + } +} + +# Risk 4: Unencrypted database +resource "aws_db_instance" "main" { + engine = "postgres" + storage_encrypted = false # ๐Ÿ” NO ENCRYPTION! + publicly_accessible = true # ๐ŸŒ PUBLIC DATABASE! +} + +# Risk 5: No encryption for EBS volume +resource "aws_ebs_volume" "data" { + availability_zone = "us-east-1a" + size = 100 + encrypted = false # ๐Ÿ” PLAINTEXT DATA! +} +``` + +
+๐Ÿ’ญ Challenge: How many security issues can you spot in the above code? + +**Found at least 8 critical issues:** + +1. โŒ Hardcoded AWS access key +2. โŒ Hardcoded AWS secret key +3. โŒ Public S3 bucket ACL +4. โŒ Security group allows all ports from anywhere +5. โŒ Database not encrypted +6. โŒ Database publicly accessible +7. โŒ EBS volume not encrypted +8. โŒ No tags for compliance tracking +9. โŒ No backup configuration +10. โŒ No network segmentation + +**Real-world impact:** Code like this caused the Capital One breach! + +
+ +--- + +## ๐Ÿ“ Slide 5 โ€“ ๐Ÿงญ IaC in the DevSecOps Pipeline + +* ๐Ÿ”„ **Shift-Left Security for Infrastructure** + * Catch issues **before deployment**, not after breach + * Test infrastructure code like application code + * Security as early feedback loop +* ๐Ÿงช **IaC Testing Pyramid** + * ๐Ÿ—๏ธ **Unit tests** (80%) โ†’ syntax, logic, basic checks + * ๐Ÿ”— **Integration tests** (15%) โ†’ deploy to test env + * ๐ŸŒ **Compliance tests** (5%) โ†’ policy validation +* ๐Ÿš€ **CI/CD Integration Points** + * ๐Ÿ“ **Pre-commit** โ†’ local validation, secret scanning + * ๐Ÿ”„ **Pull Request** โ†’ automated security scans, policy checks + * ๐Ÿ—๏ธ **Build stage** โ†’ terraform plan, cost estimation + * ๐Ÿงช **Test stage** โ†’ deploy to staging, validate + * ๐Ÿš€ **Deploy stage** โ†’ production deployment with approval + * ๐Ÿ“Š **Runtime** โ†’ drift detection, continuous monitoring + +```mermaid +flowchart LR + subgraph "๐Ÿ“ Development" + Dev[๐Ÿ‘จโ€๐Ÿ’ป Write IaC] --> PreCommit[๐Ÿ” Pre-commit Hooks] + PreCommit -->|Secret scan| LocalCheck{โœ… Pass?} + LocalCheck -->|โŒ No| Fix[๐Ÿ”ง Fix Issues] + LocalCheck -->|โœ… Yes| Commit[๐Ÿ“ค Git Commit] + end + + subgraph "๐Ÿ”„ CI/CD Pipeline" + Commit --> PR[๐Ÿ“‹ Pull Request] + PR --> Scan[๐Ÿ›ก๏ธ Security Scan
Checkov/tfsec] + Scan --> Policy[๐Ÿ“œ Policy Check
OPA/Sentinel] + Policy --> Plan[๐Ÿ“Š Terraform Plan] + Plan --> Review[๐Ÿ‘€ Manual Review] + Review -->|โœ… Approve| Deploy[๐Ÿš€ Deploy to Staging] + Deploy --> Test[๐Ÿงช Integration Tests] + Test -->|โœ… Pass| Prod[๐ŸŒ Production Deploy] + end + + subgraph "๐Ÿ“Š Runtime" + Prod --> Monitor[๐Ÿ“ˆ Drift Detection] + Monitor --> Alert[๐Ÿšจ Security Alerts] + Alert -->|Issue found| Fix + end + + style PreCommit fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + style Scan fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + style Policy fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#2c3e50 + style Prod fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 +``` + +--- + +### ๐Ÿ” GitOps Workflow for Infrastructure + +* ๐Ÿ“ฆ **Git as Single Source of Truth** + * All infrastructure code in version control + * Pull requests for any changes + * Automated testing on every commit +* ๐Ÿ”„ **Pull-Based Deployment** + * Agents watch Git repository + * Automatically apply approved changes + * Examples: Flux, ArgoCD (for Kubernetes), Terraform Cloud +* ๐Ÿ›ก๏ธ **Security Benefits** + * ๐Ÿ“œ Complete audit trail + * โ†ฉ๏ธ Easy rollback to any previous state + * ๐Ÿ” Drift detection (actual vs desired state) + * ๐Ÿšซ No direct production access needed + +```mermaid +flowchart LR + subgraph "๐Ÿ“‚ Git Repository" + Code[๐Ÿ“ IaC Code
Terraform/Pulumi] + Policy[๐Ÿ“‹ Policies
OPA/Sentinel] + end + + subgraph "๐Ÿ”„ GitOps Operator" + Watch[๐Ÿ‘๏ธ Watch for Changes] + Validate[โœ… Validate & Test] + Apply[โšก Auto-apply Changes] + end + + subgraph "โ˜๏ธ Cloud Infrastructure" + Resources[๐Ÿ—๏ธ Infrastructure Resources] + State[๐Ÿ“Š Actual State] + end + + Code --> Watch + Policy --> Watch + Watch --> Validate + Validate --> Apply + Apply --> Resources + Resources --> State + State -.Drift Detection.-> Watch + + style Code fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + style Validate fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + style Resources fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 +``` + +--- + +### ๐Ÿ“Š Security Testing Layers + +| Layer | Stage | Tools | Coverage | Speed | +|-------|-------|-------|----------|-------| +| ๐Ÿงช **Unit Tests** | Pre-commit | terraform validate, pulumi preview | Syntax, logic | โšก Seconds | +| ๐Ÿ” **Security Scan** | PR/CI | Checkov, tfsec, Terrascan | Misconfigs, secrets | โšก Seconds | +| ๐Ÿ“œ **Policy Check** | PR/CI | OPA, Sentinel, Conftest | Compliance rules | โšก Seconds | +| ๐Ÿ’ฐ **Cost Estimation** | PR/CI | Infracost, Terraform Cloud | Budget impact | โšก Seconds | +| ๐Ÿ—๏ธ **Integration Test** | Staging | Deploy + validate | Real environment | ๐ŸŒ Minutes | +| ๐ŸŒ **Runtime Monitor** | Production | Drift detection, CSPM | Continuous | ๐Ÿ”„ Ongoing | + +
+๐Ÿ’ญ Discussion: At which stage should security checks happen? + +**Answer: ALL OF THEM!** ๐ŸŽฏ + +**Defense in Depth approach:** + +1. **๐Ÿ‘จโ€๐Ÿ’ป Developer's machine (Pre-commit)** + * Fast feedback loop + * Catches obvious issues (syntax, secrets) + * No waiting for CI/CD + +2. **๐Ÿ”„ Pull Request (CI/CD)** + * Automated security scans + * Policy enforcement + * Peer review + * Prevents bad code from merging + +3. **๐Ÿงช Staging Environment** + * Real-world testing + * Integration validation + * Final check before production + +4. **๐ŸŒ Production (Runtime)** + * Continuous monitoring + * Drift detection + * Compliance audits + * Incident response + +**Remember:** Security is **not a checkpoint**, it's a **continuous process**! + +
+ +--- + +## ๐ŸŽ‰ **Fun Break: Infrastructure Gone Wild!** + +### ๐Ÿ˜„ **"The $72,000 Cloud Bill Surprise"** + +A developer spun up "just a few instances" to test a machine learning model... + +* ๐Ÿค– Forgot to set instance size limits +* โšก Auto-scaling kicked in +* ๐Ÿ“ˆ Scaled to **500+ GPU instances** +* ๐Ÿ’ธ Bill arrived: **$72,000** for the weekend +* ๐Ÿข Company lesson learned: **Always set budget alerts!** + +### ๐Ÿคฏ **IaC Horror Stories:** + +* ๐Ÿชฃ **The S3 Bucket of Doom**: Company made bucket "temporarily public" for testing โ†’ forgot to revert โ†’ 10M customer records exposed +* ๐Ÿ” **The Terraform Destroy Disaster**: Junior dev ran `terraform destroy` thinking it was on testing environment โ†’ **was production** โ†’ entire infrastructure gone +* ๐Ÿ”‘ **The GitHub Secret Leak**: Hardcoded AWS keys in Terraform โ†’ pushed to public repo โ†’ **$20K charged for crypto mining in 2 hours** +* ๐Ÿšช **The Open Security Group**: Security group rule `0.0.0.0/0` โ†’ **entire database cluster** accessible to internet โ†’ ransomware attack + +### ๐Ÿ’ก **Key Lesson:** + +**"Automate security checks, because humans make mistakes... especially at 3 AM during deployments!"** โ˜•๐Ÿ’ค + +--- + +๐Ÿ”— **Resources for Group 1:** +* [Infrastructure as Code Best Practices (AWS)](https://docs.aws.amazon.com/whitepapers/latest/introduction-devops-aws/infrastructure-as-code.html) +* [Terraform Security Best Practices (HashiCorp)](https://developer.hashicorp.com/terraform/tutorials/configuration-language/sensitive-variables) +* [Cloud Security Misconfigurations (OWASP)](https://owasp.org/www-community/vulnerabilities/Cloud_Infrastructure_Misconfiguration) +* [CIS Benchmarks for Cloud](https://www.cisecurity.org/benchmark/cloud_computing) + +--- +## ๐Ÿ“‚ Group 2: Terraform Security + +## ๐Ÿ“ Slide 6 โ€“ ๐Ÿ—๏ธ Terraform Deep Dive & Security Concerns + +* ๐Ÿ—๏ธ **Terraform** = declarative IaC tool using HCL (HashiCorp Configuration Language) +* ๐Ÿ”„ **Workflow:** `init` โ†’ `plan` โ†’ `apply` โ†’ `destroy` +* ๐Ÿ“Š **State file** = JSON file tracking all managed resources +* โš ๏ธ **Critical security issue:** State files contain **secrets in plaintext!** + * Database passwords + * API keys + * Private keys + * Certificate data + +```mermaid +flowchart LR + Write[๐Ÿ“ Write .tf files] --> Init[โš™๏ธ terraform init] + Init --> Plan[๐Ÿ“Š terraform plan] + Plan --> Apply[โšก terraform apply] + Apply --> State[๐Ÿ’พ terraform.tfstate] + State -->|Contains| Secrets[๐Ÿ”‘ SECRETS IN PLAINTEXT!] + + style State fill:#ffebee,stroke:#d32f2f,stroke-width:3px,color:#2c3e50 + style Secrets fill:#b71c1c,stroke:#d32f2f,stroke-width:3px,color:#fff +``` + +### ๐Ÿ”ฅ State File Security Risks + +* ๐Ÿ’พ **Local state files:** + * โŒ Stored on developer's laptop (unencrypted) + * โŒ Can be committed to Git accidentally + * โŒ No access control + * โŒ No audit trail +* โ˜๏ธ **Remote state backends (BETTER):** + * โœ… S3 + DynamoDB (with encryption + locking) + * โœ… Terraform Cloud (built-in security) + * โœ… Azure Blob Storage (with encryption) + * โœ… HashiCorp Consul (with ACLs) + +```hcl +# โŒ LOCAL STATE (INSECURE) +# terraform.tfstate stored locally - anyone with filesystem access can read secrets! + +# โœ… REMOTE STATE WITH ENCRYPTION +terraform { + backend "s3" { + bucket = "mycompany-terraform-state" + key = "prod/terraform.tfstate" + region = "us-east-1" + encrypt = true # โœ… Encryption at rest + dynamodb_table = "terraform-lock" # โœ… State locking + kms_key_id = "arn:aws:kms:..." # โœ… KMS encryption + } +} +``` + +--- + +## ๐Ÿ“ Slide 7 โ€“ ๐Ÿ”‘ Managing Secrets in Terraform + +### โŒ **Level 1: Hardcoded (NEVER DO THIS)** + +```hcl +resource "aws_db_instance" "db" { + username = "admin" + password = "SuperSecret123!" # ๐Ÿ”ฅ IN VERSION CONTROL FOREVER! +} +``` + +### โš ๏ธ **Level 2: Variables (BETTER, but not great)** + +```hcl +# variables.tf +variable "db_password" { + type = string + sensitive = true # Hides from logs +} + +# main.tf +resource "aws_db_instance" "db" { + password = var.db_password +} + +# Run with: terraform apply -var="db_password=..." +``` + +### โœ… **Level 3: Environment Variables (GOOD)** + +```hcl +variable "db_password" { + type = string + sensitive = true +} + +# Terminal: +# export TF_VAR_db_password="secret" +# terraform apply +``` + +### ๐Ÿ† **Level 4: Secret Managers (BEST PRACTICE)** + +```hcl +# Retrieve from AWS Secrets Manager +data "aws_secretsmanager_secret_version" "db_password" { + secret_id = "prod/db/password" +} + +resource "aws_db_instance" "db" { + password = data.aws_secretsmanager_secret_version.db_password.secret_string +} +``` + +```hcl +# Or HashiCorp Vault +data "vault_generic_secret" "db_creds" { + path = "secret/database/prod" +} + +resource "aws_db_instance" "db" { + username = data.vault_generic_secret.db_creds.data["username"] + password = data.vault_generic_secret.db_creds.data["password"] +} +``` + +### ๐Ÿ”„ **Dynamic Secrets (ENTERPRISE LEVEL)** + +```hcl +# Vault generates temporary DB credentials +resource "vault_database_secret_backend_role" "app" { + name = "app-role" + backend = vault_mount.db.path + db_name = "postgres" + + creation_statements = [ + "CREATE USER '{{name}}'@'%' IDENTIFIED BY '{{password}}'", + "GRANT SELECT ON mydb.* TO '{{name}}'@'%'" + ] + + default_ttl = 3600 # 1 hour expiry + max_ttl = 7200 +} +``` + +
+๐Ÿ’ญ Challenge: Rank these from most to least secure + +**Ranking (Best to Worst):** + +1. ๐Ÿฅ‡ **Dynamic secrets from Vault** - Short-lived, auto-rotated, audited +2. ๐Ÿฅˆ **Secret Manager with rotation** - Centralized, encrypted, rotatable +3. ๐Ÿฅ‰ **Environment variables** - Not in code, but still long-lived +4. ๐Ÿ˜ **Terraform variables with sensitive flag** - Better than nothing +5. ๐Ÿ’€ **Hardcoded in .tf files** - NEVER DO THIS! + +**Pro tip:** Combine approaches! Use Vault for app secrets, env vars for Terraform API tokens. +
+ +--- + +## ๐Ÿ“ Slide 8 โ€“ ๐Ÿ›ก๏ธ Terraform Security Best Practices + +### ๐Ÿ” **1. State File Security** + +```hcl +terraform { + backend "s3" { + bucket = "terraform-state" + encrypt = true # โœ… AES-256 encryption + kms_key_id = "arn:..." # โœ… Customer managed key + dynamodb_table = "tf-lock" # โœ… State locking + + # โœ… Bucket policy restricts access + # โœ… Versioning enabled for rollback + # โœ… MFA delete enabled + } +} +``` + +### ๐Ÿ”’ **2. Provider Version Pinning** + +```hcl +# โŒ BAD: Unpinned versions +terraform { + required_providers { + aws = { + source = "hashicorp/aws" # Any version! ๐Ÿ”ฅ + } + } +} + +# โœ… GOOD: Pinned versions +terraform { + required_version = "~> 1.6.0" # Terraform version + + required_providers { + aws = { + source = "hashicorp/aws" + version = "~> 5.0" # Provider version constraint + } + } +} +``` + +### ๐Ÿข **3. Module Security** + +```hcl +# โŒ RISKY: Random internet module +module "vpc" { + source = "github.com/random-user/terraform-vpc" # ๐Ÿ”ฅ Untrusted! +} + +# โœ… BETTER: Terraform Registry (verified) +module "vpc" { + source = "terraform-aws-modules/vpc/aws" + version = "5.1.0" # Specific version +} + +# ๐Ÿ† BEST: Private registry or Git with commit hash +module "vpc" { + source = "git::ssh://git@github.com/mycompany/terraform-modules.git//vpc?ref=v1.2.3" +} +``` + +### ๐Ÿ“‚ **4. Environment Separation** + +```hcl +# Use workspaces or separate state files +terraform { + backend "s3" { + bucket = "terraform-state" + key = "${terraform.workspace}/terraform.tfstate" # dev/staging/prod + } +} + +# Or separate directories with tfvars +# /terraform/dev/terraform.tfvars +# /terraform/staging/terraform.tfvars +# /terraform/prod/terraform.tfvars +``` + +### ๐Ÿ” **5. Pre-commit Hooks** + +```bash +# .pre-commit-config.yaml +repos: + - repo: https://github.com/antonbabenko/pre-commit-terraform + hooks: + - id: terraform_fmt # โœ… Format code + - id: terraform_validate # โœ… Validate syntax + - id: terraform_tfsec # โœ… Security scan + - id: terraform_docs # โœ… Generate docs + + - repo: https://github.com/gitleaks/gitleaks + hooks: + - id: gitleaks # โœ… Scan for secrets +``` + +### ๐Ÿ“Š **Quick Checklist** + +| Practice | Priority | Effort | Impact | +|----------|----------|--------|--------| +| Remote encrypted state | ๐Ÿ”ด Critical | Low | High | +| Secret manager integration | ๐Ÿ”ด Critical | Medium | High | +| Version pinning | ๐ŸŸก High | Low | Medium | +| Security scanning (tfsec) | ๐ŸŸก High | Low | High | +| State locking | ๐ŸŸก High | Low | High | +| Module vetting | ๐ŸŸข Medium | Medium | Medium | +| Pre-commit hooks | ๐ŸŸข Medium | Low | Medium | + +
+๐Ÿ’ญ Discussion: Should you commit terraform.tfstate to Git? + +**ABSOLUTELY NOT! โŒโŒโŒ** + +**Why it's dangerous:** +* Contains secrets in plaintext +* Anyone with repo access sees credentials +* Git history preserves old secrets forever +* No access control or audit trail +* Can't handle concurrent modifications + +**What to commit:** +* โœ… `.tf` files (infrastructure code) +* โœ… `.tfvars.example` (template, no real values) +* โœ… `README.md` (documentation) +* โŒ `.tfstate` files (add to `.gitignore`) +* โŒ `.tfvars` with real secrets (add to `.gitignore`) +* โŒ `.terraform/` directory (add to `.gitignore`) + +**Always use remote state backends!** +
+ +--- + +## ๐Ÿ“ Slide 9 โ€“ ๐Ÿ’ป Hands-On: Secure Terraform Workflow + +### ๐Ÿ” **Step 1: Scan Vulnerable Code** + +```hcl +# vulnerable.tf - Find the issues! +resource "aws_s3_bucket" "data" { + bucket = "company-data" + acl = "public-read" +} + +resource "aws_instance" "web" { + ami = "ami-12345" + instance_type = "t2.micro" + + metadata_options { + http_tokens = "optional" # IMDSv1 enabled + } +} + +resource "aws_security_group" "allow_all" { + ingress { + from_port = 0 + to_port = 65535 + protocol = "tcp" + cidr_blocks = ["0.0.0.0/0"] + } +} +``` + +### ๐Ÿ› ๏ธ **Step 2: Run Security Scanners** + +```bash +# tfsec - Fast Terraform security scanner +$ tfsec . + +Result #1 HIGH AWS S3 bucket is publicly accessible +โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + vulnerable.tf:3 +โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + 3 acl = "public-read" +โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + +Result #2 HIGH Instance Metadata Service v1 enabled +โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + vulnerable.tf:11 +โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + 11 http_tokens = "optional" +โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + +Result #3 CRITICAL Security group allows ingress from 0.0.0.0/0 +โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + vulnerable.tf:19 +โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + 19 cidr_blocks = ["0.0.0.0/0"] +โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + +3 potential problems detected. +``` + +```bash +# Checkov - Policy-as-code scanner +$ checkov -f vulnerable.tf + +Check: CKV_AWS_20: "S3 Bucket has an ACL defined which allows public READ access" + FAILED for resource: aws_s3_bucket.data + File: /vulnerable.tf:1-4 + +Check: CKV_AWS_79: "Ensure Instance Metadata Service Version 1 is not enabled" + FAILED for resource: aws_instance.web + File: /vulnerable.tf:6-14 + +Check: CKV_AWS_24: "Ensure no security groups allow ingress from 0.0.0.0:0 to port 22" + FAILED for resource: aws_security_group.allow_all + File: /vulnerable.tf:16-23 +``` + +### โœ… **Step 3: Fix Security Issues** + +```hcl +# secure.tf - Fixed version +resource "aws_s3_bucket" "data" { + bucket = "company-data" +} + +resource "aws_s3_bucket_public_access_block" "data" { + bucket = aws_s3_bucket.data.id + + block_public_acls = true + block_public_policy = true + ignore_public_acls = true + restrict_public_buckets = true +} + +resource "aws_s3_bucket_server_side_encryption_configuration" "data" { + bucket = aws_s3_bucket.data.id + + rule { + apply_server_side_encryption_by_default { + sse_algorithm = "AES256" + } + } +} + +resource "aws_instance" "web" { + ami = "ami-12345" + instance_type = "t2.micro" + + metadata_options { + http_tokens = "required" # โœ… IMDSv2 only + http_endpoint = "enabled" + } + + root_block_device { + encrypted = true # โœ… Encrypt root volume + } +} + +resource "aws_security_group" "web" { + name = "web-sg" + + ingress { + description = "HTTPS from VPC" + from_port = 443 + to_port = 443 + protocol = "tcp" + cidr_blocks = ["10.0.0.0/16"] # โœ… VPC only + } + + egress { + from_port = 0 + to_port = 0 + protocol = "-1" + cidr_blocks = ["0.0.0.0/0"] + } +} +``` + +### ๐Ÿš€ **Step 4: CI/CD Integration** + +```yaml +# .github/workflows/terraform.yml +name: Terraform Security + +on: [pull_request] + +jobs: + security: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - name: Setup Terraform + uses: hashicorp/setup-terraform@v2 + + - name: Terraform Format Check + run: terraform fmt -check -recursive + + - name: Terraform Init + run: terraform init -backend=false + + - name: Terraform Validate + run: terraform validate + + - name: Run tfsec + uses: aquasecurity/tfsec-action@v1.0.0 + with: + soft_fail: false # โŒ Fail on issues + + - name: Run Checkov + uses: bridgecrewio/checkov-action@master + with: + framework: terraform + soft_fail: false # โŒ Fail on issues + + - name: Terraform Plan + run: terraform plan + env: + AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} + AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} +``` + +### ๐Ÿ“Š **Before vs After Comparison** + +| Metric | Before | After | +|--------|--------|-------| +| ๐Ÿ”ด Critical issues | 3 | 0 | +| ๐ŸŸก High issues | 5 | 0 | +| ๐ŸŸข Medium issues | 12 | 2 | +| โšก Scan time | - | 5 seconds | +| โœ… CI/CD pass | โŒ | โœ… | + +
+๐Ÿ’ญ Exercise: What other tools would you add to this pipeline? + +**Additional tools to consider:** + +1. **Cost estimation:** + * ๐Ÿ’ฐ Infracost - Estimates cloud costs before deployment + * Shows cost impact in PR comments + +2. **Compliance checks:** + * ๐Ÿ“‹ Terraform Compliance - BDD-style policy testing + * Tests against regulatory requirements + +3. **Secrets scanning:** + * ๐Ÿ”‘ Gitleaks - Detect hardcoded secrets + * TruffleHog - Find secrets in Git history + +4. **Drift detection:** + * ๐Ÿ“Š Driftctl - Compare actual vs Terraform state + * Terraform Cloud - Built-in drift detection + +5. **Documentation:** + * ๐Ÿ“ terraform-docs - Auto-generate README + * Keeps docs in sync with code + +6. **Policy-as-code:** + * ๐ŸŽฏ OPA/Conftest - Custom policy checks + * Sentinel - Terraform Cloud policies + +**Example enhanced workflow:** +```yaml +- name: Cost Estimation + run: infracost breakdown --path . + +- name: Compliance Testing + run: terraform-compliance -f compliance/ -p plan.json + +- name: Secrets Scan + run: gitleaks detect --source . --verbose +``` +
+ +--- + +๐Ÿ”— **Terraform Security Resources:** +* [Terraform Security Best Practices (HashiCorp)](https://developer.hashicorp.com/terraform/tutorials/configuration-language/sensitive-variables) +* [tfsec Documentation](https://aquasecurity.github.io/tfsec/) +* [Checkov Policies](https://www.checkov.io/5.Policy%20Index/terraform.html) +* [Terraform AWS Secure Baseline](https://github.com/nozaq/terraform-aws-secure-baseline) + +--- +## ๐Ÿ“‚ Group 3: Pulumi Security + +## ๐Ÿ“ Slide 10 โ€“ ๐Ÿš€ Pulumi Overview & Security Model + +* ๐Ÿš€ **Pulumi** = IaC using real programming languages (TypeScript, Python, Go, C#, Java) +* ๐Ÿ†š **vs Terraform:** Code instead of DSL, full programming features, built-in testing +* ๐Ÿ” **Built-in secrets encryption** (automatic, no extra config needed) + +```typescript +// TypeScript example +import * as aws from "@pulumi/aws"; +import * as pulumi from "@pulumi/pulumi"; + +const bucket = new aws.s3.Bucket("secure-bucket", { + acl: "private", + serverSideEncryptionConfiguration: { + rule: { + applyServerSideEncryptionByDefault: { + sseAlgorithm: "AES256", + }, + }, + }, +}); + +export const bucketName = bucket.id; +``` + +```python +# Python example +import pulumi +import pulumi_aws as aws + +bucket = aws.s3.Bucket("secure-bucket", + acl="private", + server_side_encryption_configuration={ + "rule": { + "apply_server_side_encryption_by_default": { + "sse_algorithm": "AES256", + }, + }, + }) + +pulumi.export("bucket_name", bucket.id) +``` + +### ๐Ÿ”‘ Automatic Secrets Management + +```typescript +// Secrets are automatically encrypted in state! +const config = new pulumi.Config(); +const dbPassword = config.requireSecret("dbPassword"); // ๐Ÿ” Auto-encrypted + +const db = new aws.rds.Instance("db", { + engine: "postgres", + password: dbPassword, // โœ… Encrypted in state + storageEncrypted: true, +}); + +// Secret outputs are also encrypted +export const connectionString = pulumi.secret( + pulumi.interpolate`postgres://admin:${dbPassword}@${db.endpoint}` +); +``` + +### ๐Ÿ”’ Encryption Options + +```bash +# Default: Pulumi service (managed) +$ pulumi stack init prod + +# Passphrase (self-managed) +$ pulumi stack init prod --secrets-provider=passphrase +$ export PULUMI_CONFIG_PASSPHRASE="strong-password" + +# AWS KMS +$ pulumi stack init prod --secrets-provider="awskms://alias/pulumi-secrets?region=us-east-1" + +# Azure Key Vault +$ pulumi stack init prod --secrets-provider="azurekeyvault://myvault.vault.azure.net/keys/pulumi" + +# GCP KMS +$ pulumi stack init prod --secrets-provider="gcpkms://projects/my-project/locations/us/keyRings/my-keyring/cryptoKeys/my-key" +``` + +
+๐Ÿ’ญ Quiz: What happens if you print a secret in Pulumi? + +```typescript +const secret = config.requireSecret("apiKey"); +console.log(secret); // What gets printed? +``` + +**Answer:** `[secret]` ๐Ÿ”’ + +Pulumi automatically redacts secrets in: +* Console output +* Logs +* Stack exports (unless explicitly outputting as secret) +* API responses + +**To actually use the value:** +```typescript +secret.apply(value => { + // value is the actual string here + // Use it carefully! +}); +``` + +**This prevents accidental leaks!** +
+ +--- + +## ๐Ÿ“ Slide 11 โ€“ ๐Ÿงฉ Pulumi Policy-as-Code (CrossGuard) + +* ๐Ÿ“‹ **CrossGuard** = policy-as-code framework for Pulumi +* ๐ŸŽฏ **Policies:** Mandatory (block) or Advisory (warn) +* ๐Ÿ’ป Written in TypeScript or Python + +### ๐Ÿ“ Example Policy: Block Public S3 Buckets + +```typescript +// policy.ts +import * as aws from "@pulumi/aws"; +import { PolicyPack, validateResourceOfType } from "@pulumi/policy"; + +new PolicyPack("aws-policies", { + policies: [{ + name: "s3-no-public-read", + description: "S3 buckets must not be publicly readable", + enforcementLevel: "mandatory", // Blocks deployment! + validateResource: validateResourceOfType(aws.s3.Bucket, (bucket, args, reportViolation) => { + if (bucket.acl === "public-read" || bucket.acl === "public-read-write") { + reportViolation("S3 bucket must not have public ACL"); + } + }), + }, { + name: "s3-encryption-required", + description: "S3 buckets must be encrypted", + enforcementLevel: "mandatory", + validateResource: validateResourceOfType(aws.s3.Bucket, (bucket, args, reportViolation) => { + if (!bucket.serverSideEncryptionConfiguration) { + reportViolation("S3 bucket must have encryption enabled"); + } + }), + }, { + name: "required-tags", + description: "Resources must have required tags", + enforcementLevel: "advisory", // Just warns + validateResource: (args, reportViolation) => { + if (args.type.startsWith("aws:") && !args.props.tags) { + reportViolation("Resource should have tags"); + } + }, + }], +}); +``` + +```python +# policy.py +from pulumi_policy import ( + EnforcementLevel, + PolicyPack, + ResourceValidationPolicy, +) + +def s3_no_public_acl(args, report_violation): + if args.resource_type == "aws:s3/bucket:Bucket": + acl = args.props.get("acl") + if acl in ["public-read", "public-read-write"]: + report_violation("S3 bucket must not be public") + +PolicyPack( + name="aws-python-policies", + enforcement_level=EnforcementLevel.MANDATORY, + policies=[ + ResourceValidationPolicy( + name="s3-no-public-acl", + description="S3 buckets cannot be public", + validate=s3_no_public_acl, + ), + ], +) +``` + +### ๐Ÿš€ Using Policies + +```bash +# Enable policy pack locally +$ pulumi policy enable policy-pack/ + +# Preview with policies +$ pulumi preview +Previewing update (dev) + +Policy Violations: + โŒ s3-no-public-read (mandatory) + S3 bucket must not have public ACL + aws:s3:Bucket (my-bucket) + +# Policy blocks deployment! +error: preview failed + +# Fix the issue and try again +$ pulumi up +โœ… All policies passed! +``` + +### ๐Ÿ“ฆ Policy Pack Management + +```bash +# Publish policy pack to Pulumi Cloud +$ pulumi policy publish org-name/aws-policies + +# Enforce organization-wide +$ pulumi policy enable org-name/aws-policies --policy-group production + +# Different policies for different stacks +$ pulumi policy enable dev-policies --policy-group development +``` + +--- + +## ๐Ÿ“ Slide 12 โ€“ ๐Ÿ’ป Hands-On: Secure Pulumi Deployment + +### ๐Ÿ“ Secure AWS S3 Bucket Example + +```typescript +// index.ts - Secure S3 bucket with Pulumi +import * as pulumi from "@pulumi/pulumi"; +import * as aws from "@pulumi/aws"; + +// Get config +const config = new pulumi.Config(); +const environment = config.require("environment"); +const kmsKeyId = config.requireSecret("kmsKeyId"); + +// Create KMS-encrypted S3 bucket +const bucket = new aws.s3.Bucket("app-data", { + acl: "private", + + // โœ… Block all public access + blockPublicAcls: true, + blockPublicPolicy: true, + ignorePublicAcls: true, + restrictPublicBuckets: true, + + // โœ… Enable versioning + versioning: { + enabled: true, + }, + + // โœ… KMS encryption + serverSideEncryptionConfiguration: { + rule: { + applyServerSideEncryptionByDefault: { + sseAlgorithm: "aws:kms", + kmsMasterKeyId: kmsKeyId, + }, + bucketKeyEnabled: true, + }, + }, + + // โœ… Lifecycle rules + lifecycleRules: [{ + enabled: true, + transitions: [{ + days: 30, + storageClass: "STANDARD_IA", + }, { + days: 90, + storageClass: "GLACIER", + }], + }], + + // โœ… Logging + loggings: [{ + targetBucket: logBucket.id, + targetPrefix: "s3-access-logs/", + }], + + // โœ… Tags + tags: { + Environment: environment, + ManagedBy: "Pulumi", + Encrypted: "true", + }, +}); + +// โœ… Bucket policy - deny unencrypted uploads +const bucketPolicy = new aws.s3.BucketPolicy("app-data-policy", { + bucket: bucket.id, + policy: bucket.arn.apply(arn => JSON.stringify({ + Version: "2012-10-17", + Statement: [{ + Sid: "DenyUnencryptedUploads", + Effect: "Deny", + Principal: "*", + Action: "s3:PutObject", + Resource: `${arn}/*`, + Condition: { + StringNotEquals: { + "s3:x-amz-server-side-encryption": "aws:kms" + } + } + }] + })), +}); + +// Export (bucketName is public, encryption key is secret) +export const bucketName = bucket.id; +export const bucketArn = bucket.arn; +export const encryptionKey = pulumi.secret(kmsKeyId); +``` + +### ๐Ÿงช Testing Infrastructure Code + +```typescript +// index.test.ts - Unit tests for Pulumi +import * as pulumi from "@pulumi/pulumi"; +import * as aws from "@pulumi/aws"; +import "mocha"; + +pulumi.runtime.setMocks({ + newResource: function(args: pulumi.runtime.MockResourceArgs): {id: string, state: any} { + return { + id: args.inputs.name + "_id", + state: args.inputs, + }; + }, + call: function(args: pulumi.runtime.MockCallArgs) { + return args.inputs; + }, +}); + +describe("S3 Bucket Security", function() { + let bucket: aws.s3.Bucket; + + before(async function() { + const infra = await import("./index"); + // Load the infrastructure + }); + + it("bucket must have private ACL", function(done) { + pulumi.all([bucket.acl]).apply(([acl]) => { + if (acl !== "private") { + done(new Error("Bucket must be private")); + } else { + done(); + } + }); + }); + + it("bucket must have encryption", function(done) { + pulumi.all([bucket.serverSideEncryptionConfiguration]).apply(([encryption]) => { + if (!encryption) { + done(new Error("Bucket must be encrypted")); + } else { + done(); + } + }); + }); + + it("bucket must block public access", function(done) { + pulumi.all([ + bucket.blockPublicAcls, + bucket.blockPublicPolicy, + bucket.ignorePublicAcls, + bucket.restrictPublicBuckets + ]).apply(([acls, policy, ignore, restrict]) => { + if (!acls || !policy || !ignore || !restrict) { + done(new Error("Bucket must block all public access")); + } else { + done(); + } + }); + }); +}); +``` + +### ๐Ÿš€ CI/CD Integration + +```yaml +# .github/workflows/pulumi.yml +name: Pulumi + +on: + pull_request: + branches: [main] + +jobs: + preview: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - uses: actions/setup-node@v3 + with: + node-version: 18 + + - name: Install dependencies + run: npm install + + - name: Run tests + run: npm test + + - name: Pulumi Preview + uses: pulumi/actions@v4 + with: + command: preview + stack-name: dev + env: + PULUMI_ACCESS_TOKEN: ${{ secrets.PULUMI_ACCESS_TOKEN }} + AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} + AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + + - name: Run Policy Check + run: pulumi policy enable aws-policies && pulumi preview +``` + +
+๐Ÿ’ญ Comparison: Pulumi vs Terraform - Which is more secure by default? + +**Pulumi advantages:** +* โœ… Secrets encrypted automatically (no config needed) +* โœ… Built-in testing frameworks (unit/integration) +* โœ… Type safety (compile-time checks) +* โœ… Secret outputs protected by default +* โœ… Programming language tooling (linters, IDEs) + +**Terraform advantages:** +* โœ… Declarative = easier to audit +* โœ… Larger ecosystem and examples +* โœ… More mature security tooling (tfsec, Checkov) +* โœ… HCL is simpler for infrastructure-only teams + +**Verdict:** Pulumi has **better security defaults**, but Terraform has **more security tooling**. + +**Best practice:** Choose based on team skills: +- DevOps/Infra teams โ†’ Terraform +- Software dev teams โ†’ Pulumi +
+ +--- + +## ๐Ÿ“‚ Group 4: Ansible Security + +## ๐Ÿ“ Slide 13 โ€“ โš™๏ธ Ansible Overview & Security Challenges + +* โš™๏ธ **Ansible** = agentless automation via SSH (Python) +* ๐Ÿ“ **Playbooks** = YAML files defining tasks +* ๐Ÿ”„ **Idempotent** = safe to run multiple times +* โš ๏ธ **Security risks:** SSH keys, privileged operations, secrets in playbooks + +```yaml +# Basic playbook structure +--- +- name: Configure web servers + hosts: webservers + become: yes # Run as root/sudo + + tasks: + - name: Install nginx + apt: + name: nginx + state: present + + - name: Copy config + template: + src: nginx.conf.j2 + dest: /etc/nginx/nginx.conf + notify: restart nginx + + handlers: + - name: restart nginx + service: + name: nginx + state: restarted +``` + +### ๐Ÿ”‘ Ansible Vault - Encrypt Secrets + +```bash +# Create encrypted file +$ ansible-vault create secrets.yml +New Vault password: **** +Confirm: **** + +# Edit encrypted file +$ ansible-vault edit secrets.yml + +# View encrypted file +$ ansible-vault view secrets.yml + +# Encrypt existing file +$ ansible-vault encrypt vars.yml + +# Decrypt file +$ ansible-vault decrypt vars.yml +``` + +```yaml +# secrets.yml (encrypted) +--- +db_password: "SuperSecret123!" +api_key: "sk-1234567890abcdef" +ssl_private_key: | + -----BEGIN PRIVATE KEY----- + MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC... + -----END PRIVATE KEY----- +``` + +### ๐Ÿ” Using Vault in Playbooks + +```yaml +# playbook.yml +--- +- name: Deploy application + hosts: app_servers + vars_files: + - secrets.yml # Encrypted with ansible-vault + + tasks: + - name: Create database + postgresql_db: + name: myapp + login_password: "{{ db_password }}" # From vault + + - name: Configure API + template: + src: config.j2 + dest: /etc/app/config.yml + vars: + api_key: "{{ api_key }}" # From vault +``` + +```bash +# Run with vault password +$ ansible-playbook playbook.yml --ask-vault-pass + +# Or use password file +$ ansible-playbook playbook.yml --vault-password-file ~/.vault_pass + +# Or environment variable +$ export ANSIBLE_VAULT_PASSWORD_FILE=~/.vault_pass +$ ansible-playbook playbook.yml +``` + +
+๐Ÿ’ญ Quiz: What happens if you print a vaulted variable? + +```yaml +- name: Debug secret + debug: + msg: "Password is {{ db_password }}" +``` + +**Answer:** It prints in plaintext! ๐Ÿ”ฅ + +**To prevent leaks, use `no_log`:** +```yaml +- name: Set password + shell: "mysql -p{{ db_password }} ..." + no_log: true # โœ… Hides output from logs +``` + +**Best practice:** Always use `no_log: true` with secrets! +
+ +--- + +## ๐Ÿ“ Slide 14 โ€“ ๐Ÿ›ก๏ธ Ansible Security Best Practices + +### ๐Ÿ”’ 1. No Logs for Secrets + +```yaml +# โŒ BAD: Secrets in logs +- name: Configure database + postgresql_db: + login_password: "{{ db_password }}" + register: result + +- name: Show result + debug: + var: result # ๐Ÿ”ฅ Password visible in logs! + +# โœ… GOOD: Hide sensitive output +- name: Configure database + postgresql_db: + login_password: "{{ db_password }}" + no_log: true # โœ… Redacts from logs + +- name: Execute command with secret + shell: "curl -H 'Authorization: Bearer {{ api_token }}' ..." + no_log: true + register: api_result +``` + +### ๐Ÿ”‘ 2. SSH Key Management + +```yaml +# Use SSH keys, not passwords +[webservers] +server1 ansible_host=192.168.1.10 ansible_user=deploy + +# SSH config +$ cat ~/.ssh/config +Host server1 + HostName 192.168.1.10 + User deploy + IdentityFile ~/.ssh/deploy_key + StrictHostKeyChecking yes + +# Vault SSH keys if storing in repo +$ ansible-vault encrypt files/deploy_key +``` + +### ๐Ÿ‘ฎ 3. Least Privilege + +```yaml +# โŒ BAD: Always run as root +- name: Install package + become: yes + become_user: root + apt: name=nginx + +# โœ… GOOD: Only escalate when needed +- name: Install package + apt: name=nginx + become: yes # Only for this task + +- name: Copy user file + copy: + src: app.conf + dest: ~/app.conf + # No become - runs as regular user +``` + +### ๐Ÿงน 4. Ansible Lint + +```bash +# Install +$ pip install ansible-lint + +# Run +$ ansible-lint playbook.yml + +# Example output +playbook.yml: + [201] Trailing whitespace + [206] Variables should have spaces before and after: {{ var_name }} + [301] Commands should not change things if nothing needs doing + [305] Use shell only when shell functionality is required + [503] Tasks that run when changed should likely be handlers +``` + +```yaml +# .ansible-lint config +--- +skip_list: + - '301' # Sometimes we need non-idempotent tasks + +warn_list: + - experimental + - role-name + +exclude_paths: + - .github/ + - test/ +``` + +### ๐Ÿข 5. Ansible Tower/AWX + +* ๐Ÿ” Centralized credential management +* ๐Ÿ‘ฅ RBAC for playbook execution +* ๐Ÿ“Š Audit logs of all runs +* ๐Ÿ”„ Scheduled jobs with approval workflows +* ๐Ÿš€ Self-service infrastructure for developers + +
+๐Ÿ’ญ Exercise: Secure this playbook + +```yaml +# insecure.yml - Find the issues! +--- +- hosts: all + become: yes + tasks: + - name: Set root password + shell: "echo 'root:{{ root_password }}' | chpasswd" + + - name: Download script + get_url: + url: http://example.com/script.sh + dest: /tmp/script.sh + mode: 0777 + + - name: Run script + shell: bash /tmp/script.sh + + - name: Show database connection + debug: + msg: "DB: postgresql://admin:{{ db_pass }}@localhost/app" +``` + +**Issues found:** +1. โŒ No `no_log` on password change +2. โŒ HTTP instead of HTTPS +3. โŒ Overly permissive file mode (0777) +4. โŒ Running untrusted script +5. โŒ Database password in debug output +6. โŒ Using shell instead of proper module + +**Fixed version:** +```yaml +--- +- hosts: all + become: yes + tasks: + - name: Set root password + user: + name: root + password: "{{ root_password | password_hash('sha512') }}" + no_log: true + + - name: Download script + get_url: + url: https://example.com/script.sh + dest: /tmp/script.sh + mode: 0750 + checksum: sha256:abc123... + + - name: Run script + script: /tmp/script.sh + args: + creates: /var/app/installed + no_log: true + + # Remove debug statement entirely! +``` +
+ +--- + +## ๐Ÿ“ Slide 15 โ€“ ๐Ÿ’ป Hands-On: Secure Ansible Playbook + +### ๐Ÿ“ Secure Web Server Deployment + +```yaml +# site.yml - Main playbook +--- +- name: Deploy secure web application + hosts: webservers + become: yes + vars_files: + - vault.yml # Encrypted secrets + + pre_tasks: + - name: Update apt cache + apt: + update_cache: yes + cache_valid_time: 3600 + + roles: + - common + - security + - nginx + - app + + post_tasks: + - name: Verify deployment + uri: + url: "https://{{ inventory_hostname }}" + validate_certs: yes + delegate_to: localhost +``` + +```yaml +# roles/security/tasks/main.yml - Security hardening +--- +- name: Install security updates + apt: + upgrade: dist + update_cache: yes + register: updates + +- name: Configure firewall + ufw: + rule: allow + port: "{{ item }}" + proto: tcp + loop: + - 22 # SSH + - 443 # HTTPS + no_log: true + +- name: Enable firewall + ufw: + state: enabled + policy: deny + +- name: Disable root login + lineinfile: + path: /etc/ssh/sshd_config + regexp: '^PermitRootLogin' + line: 'PermitRootLogin no' + notify: restart sshd + +- name: Require SSH key auth + lineinfile: + path: /etc/ssh/sshd_config + regexp: '^PasswordAuthentication' + line: 'PasswordAuthentication no' + notify: restart sshd + +- name: Install fail2ban + apt: + name: fail2ban + state: present + +- name: Configure fail2ban + template: + src: jail.local.j2 + dest: /etc/fail2ban/jail.local + notify: restart fail2ban + +handlers: + - name: restart sshd + service: + name: sshd + state: restarted + + - name: restart fail2ban + service: + name: fail2ban + state: restarted +``` + +```yaml +# vault.yml (encrypted) +--- +ssl_cert: | + -----BEGIN CERTIFICATE----- + ... +ssl_key: | + -----BEGIN PRIVATE KEY----- + ... +db_password: "SuperSecure123!" +app_secret_key: "random-secret-key" +``` + +### ๐Ÿงช Testing with Molecule + +```bash +# Install molecule +$ pip install molecule[docker] + +# Initialize molecule +$ molecule init scenario + +# Run tests +$ molecule test +``` + +```yaml +# molecule/default/molecule.yml +--- +dependency: + name: galaxy +driver: + name: docker +platforms: + - name: instance + image: ubuntu:22.04 + pre_build_image: true +provisioner: + name: ansible +verifier: + name: ansible +``` + +```yaml +# molecule/default/verify.yml - Test security +--- +- name: Verify + hosts: all + tasks: + - name: Check firewall enabled + command: ufw status + register: ufw_status + changed_when: false + + - name: Assert firewall is active + assert: + that: + - "'Status: active' in ufw_status.stdout" + + - name: Check SSH config + shell: grep "^PermitRootLogin no" /etc/ssh/sshd_config + changed_when: false + + - name: Check HTTPS accessible + uri: + url: https://localhost + validate_certs: no + delegate_to: localhost +``` + +### ๐Ÿš€ CI/CD Integration + +```yaml +# .github/workflows/ansible.yml +name: Ansible CI + +on: [push, pull_request] + +jobs: + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-python@v4 + with: + python-version: '3.10' + - name: Install dependencies + run: pip install ansible ansible-lint + - name: Run ansible-lint + run: ansible-lint site.yml + + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - name: Run molecule tests + run: | + pip install molecule[docker] + molecule test +``` + +
+๐Ÿ’ญ Pro Tip: Ansible Tower vs AWX vs Semaphore + +**Ansible Tower (Red Hat):** +* ๐Ÿ’ฐ Commercial ($$$) +* ๐Ÿข Enterprise support +* ๐Ÿ“Š Advanced reporting +* ๐Ÿ”„ HA clustering built-in + +**AWX (Open Source):** +* ๐Ÿ†“ Free (upstream of Tower) +* ๐Ÿ”„ Frequent updates +* ๐Ÿณ Container-based +* โš ๏ธ Less stable + +**Semaphore (Open Source):** +* ๐Ÿ†“ Free alternative +* ๐Ÿš€ Modern UI +* ๐Ÿณ Lightweight +* โšก Fast and simple + +**Choose based on:** +- Need support? โ†’ Tower +- Want latest features? โ†’ AWX +- Want simplicity? โ†’ Semaphore +- Small team? โ†’ Just use Git + CLI +
+ +--- + +## ๐ŸŽ‰ Fun Break: "Ansible Disaster Stories" + +### ๐Ÿ˜ฑ **"The Playbook That Deleted Production"** + +```yaml +# Someone wrote this... +- name: Clean old files + file: + path: "{{ cleanup_path }}" + state: absent + +# And ran it with... +$ ansible-playbook cleanup.yml -e "cleanup_path=/" +``` +**Result:** ๐Ÿ’ฅ Deleted the entire filesystem + +**Lesson:** Always use `--check` mode first! + +### ๐Ÿ”ฅ **"The Leaked Vault Password"** + +```bash +# Developer committed this +$ git add .vault_pass +$ git commit -m "Add vault password for convenience" +$ git push +``` +**Result:** ๐Ÿ”“ All secrets exposed in Git history + +**Lesson:** Add `.vault_pass` to `.gitignore`! + +### โšก **"The Infinite Loop"** + +```yaml +- name: Restart service until it works + service: + name: myapp + state: restarted + until: result.status == 0 + # Forgot to add retries limit! +``` +**Result:** ๐Ÿ”„ Playbook ran for 48 hours straight + +**Lesson:** Always set `retries` and `delay`! + +--- + +## ๐Ÿ“‚ Group 5: Misconfiguration Scanning & Policy-as-Code + +## ๐Ÿ“ Slide 16 โ€“ ๐Ÿ” IaC Security Scanning Tools Deep Dive + +### ๐Ÿ› ๏ธ Tool Comparison + +| Tool | Speed | Coverage | False Positives | Cost | Best For | +|------|-------|----------|-----------------|------|----------| +| ๐Ÿ” **Checkov** | Medium | 1000+ checks | Low | Free | Multi-cloud | +| โšก **tfsec** | โšก Fast | 300+ checks | Very Low | Free | Terraform | +| ๐Ÿ”Ž **Terrascan** | Slow | 500+ checks | Medium | Free | Compliance | +| ๐Ÿฆ… **Prowler** | Medium | 300+ checks | Low | Free | AWS | +| ๐Ÿ” **ScoutSuite** | Slow | All services | Medium | Free | Multi-cloud audit | + +
+๐Ÿ’ญ Interactive: Which tool should you choose? + +**Choose tfsec if:** +* โœ… You only use Terraform +* โœ… Speed is critical (CI/CD) +* โœ… Want minimal false positives +* โœ… Need IDE integration + +**Choose Checkov if:** +* โœ… Multi-cloud or multi-IaC tool +* โœ… Need custom Python policies +* โœ… Want largest policy library +* โœ… Need container/K8s scanning too + +**Choose Terrascan if:** +* โœ… Already using OPA/Rego +* โœ… Need custom compliance frameworks +* โœ… Want policy-as-code approach + +**Best practice:** Use multiple! They catch different issues. +```bash +tfsec . && checkov -d . && terraform plan +``` +
+ +--- + +## ๐Ÿ“ Slide 17 โ€“ ๐Ÿ“‹ Policy-as-Code Frameworks + +### ๐ŸŽฏ Open Policy Agent (OPA) + +```bash +# Install +$ brew install opa + +# Run as server +$ opa run --server + +# Test policy +$ opa test policy/ -v +``` + +```rego +# policy/s3_public.rego +package terraform.s3 + +deny[msg] { + resource := input.resource.aws_s3_bucket[name] + resource.acl == "public-read" + msg := sprintf("S3 bucket %v is publicly readable", [name]) +} + +deny[msg] { + resource := input.resource.aws_s3_bucket[name] + not resource.versioning + msg := sprintf("S3 bucket %v does not have versioning", [name]) +} +``` + +### ๐Ÿ”’ Conftest - Test Configurations + +```bash +# Install +$ brew install conftest + +# Test Terraform plan +$ terraform plan -out=plan.out +$ terraform show -json plan.out > plan.json +$ conftest test plan.json + +# Test Kubernetes +$ conftest test deployment.yaml + +# Test Dockerfile +$ conftest test Dockerfile +``` + +```rego +# policy/kubernetes.rego +package main + +deny[msg] { + input.kind == "Deployment" + not input.spec.template.spec.securityContext.runAsNonRoot + msg := "Containers must not run as root" +} + +deny[msg] { + input.kind == "Service" + input.spec.type == "LoadBalancer" + msg := "LoadBalancer services are not allowed" +} + +warn[msg] { + input.kind == "Pod" + not input.spec.containers[_].resources.limits + msg := "Container should have resource limits" +} +``` + +### โš™๏ธ HashiCorp Sentinel + +```hcl +# sentinel.hcl +policy "s3-bucket-encryption" { + enforcement_level = "hard-mandatory" +} + +policy "required-tags" { + enforcement_level = "soft-mandatory" +} +``` + +```python +# s3-bucket-encryption.sentinel +import "tfplan/v2" as tfplan + +s3_buckets = filter tfplan.resource_changes as _, rc { + rc.type is "aws_s3_bucket" and + rc.mode is "managed" and + rc.change.actions is not ["delete"] +} + +require_encryption = rule { + all s3_buckets as _, bucket { + bucket.change.after.server_side_encryption_configuration is not null + } +} + +main = rule { + require_encryption +} +``` + +
+๐Ÿ’ญ Quiz: OPA vs Sentinel - What's the difference? + +**Open Policy Agent (OPA):** +* ๐Ÿ†“ Open source (CNCF) +* ๐ŸŒ Universal - works anywhere +* ๐Ÿ“ Rego language (declarative) +* ๐Ÿ”ง Requires integration work +* โšก Blazing fast + +**HashiCorp Sentinel:** +* ๐Ÿ’ฐ Commercial (Terraform Cloud/Enterprise only) +* ๐Ÿ—๏ธ Terraform-specific +* ๐Ÿ“ Sentinel language (procedural) +* โœ… Built-in Terraform integration +* ๐ŸŽฏ Terraform-aware (costs, resources, etc.) + +**When to use:** +- Open source project? โ†’ OPA +- Need multi-tool support? โ†’ OPA +- Using Terraform Cloud? โ†’ Sentinel +- Need cost controls? โ†’ Sentinel +- Want flexibility? โ†’ OPA + +**Pro tip:** You can use both! OPA for runtime, Sentinel for Terraform. +
+ +--- + +## ๐Ÿ“ Slide 18 โ€“ โ˜๏ธ Compliance & Security Standards + +### ๐Ÿ“‹ CIS Benchmarks + +* ๐Ÿ† **CIS = Center for Internet Security** +* ๐Ÿ“Š Industry consensus standards +* โ˜๏ธ Benchmarks for AWS, Azure, GCP, Kubernetes + +### ๐Ÿ” Compliance Frameworks + +| Framework | Industry | Key Requirements | +|-----------|----------|------------------| +| ๐Ÿ’ณ **PCI-DSS** | Payment cards | Encryption, network segmentation, logging | +| ๐Ÿฅ **HIPAA** | Healthcare | Data encryption, access controls, audit logs | +| ๐Ÿ‡ช๐Ÿ‡บ **GDPR** | EU data | Data privacy, right to deletion, consent | +| ๐Ÿ“Š **SOC2** | SaaS/Cloud | Security controls, availability, confidentiality | +| ๐Ÿฆ **ISO 27001** | Global | Information security management | + +### ๐Ÿ“Š Mapping IaC Checks to Compliance + +```yaml +# compliance-mapping.yml +checks: + - id: CKV_AWS_18 + title: "Ensure S3 bucket has access logging enabled" + frameworks: + - PCI-DSS: "10.2.1" + - HIPAA: "164.312(b)" + - SOC2: "CC6.1" + + - id: CKV_AWS_19 + title: "Ensure S3 bucket is encrypted" + frameworks: + - PCI-DSS: "3.4" + - HIPAA: "164.312(a)(2)(iv)" + - GDPR: "Article 32" + - SOC2: "CC6.7" +``` + +### ๐Ÿ›ก๏ธ Cloud Security Posture Management (CSPM) + +```bash +# Example: Using ScoutSuite for multi-cloud audit +$ scout suite --provider aws --profile production + +# Or with Prowler for AWS +$ prowler aws --profile prod --html-output + +# Output shows: +# โœ… Passed: 234 checks +# โš ๏ธ Warning: 45 checks +# โŒ Failed: 12 checks +# ๐Ÿ“Š Compliance Score: 87% +``` + +--- + +## ๐Ÿ“‚ Group 6: Case Studies & Future Trends + +## ๐Ÿ“ Slide 19 โ€“ ๐ŸŽฏ Case Studies, Future Trends & Summary + +### ๐Ÿšจ Case Study 1: Capital One Breach (2019) + +* ๐Ÿฆ **Target:** Capital One (major US bank) +* ๐Ÿ“… **Date:** March 2019 (discovered July 2019) +* ๐Ÿ”ฅ **Impact:** 100M customer records, 140K SSNs, 80K bank accounts +* ๐Ÿ’ฐ **Cost:** $190M settlement + reputation damage + +**What happened:** +```hcl +# Misconfigured WAF (simplified example) +resource "aws_waf_rule" "allow_all" { + name = "WAF-Rule" + metric_name = "WAFRule" + + predicates { + data_id = aws_waf_ipset.allow_all.id + negated = false + type = "IPMatch" + } +} + +# SSRF vulnerability + overly permissive IAM role +resource "aws_iam_role_policy" "waf_role" { + policy = jsonencode({ + Action = [ + "s3:List*", + "s3:Get*" # ๐Ÿ”ฅ Too permissive! + ] + Resource = "*" # ๐Ÿ”ฅ All buckets! + }) +} +``` + +**How IaC security could have prevented it:** +```bash +$ checkov -f main.tf + +โŒ IAM policy should not allow * resource +โŒ IAM policy is overly permissive +โŒ WAF rule allows all IPs + +$ conftest test plan.json -p compliance/ + +โŒ IAM role violates least privilege (PCI-DSS 7.1.2) +``` + +### ๐Ÿšจ Case Study 2: Tesla Kubernetes Dashboard (2018) + +* โšก **Target:** Tesla (electric vehicle company) +* ๐Ÿ“… **Date:** February 2018 +* ๐Ÿ”ฅ **Impact:** Crypto mining attack, potential access to proprietary data +* ๐Ÿ’ฐ **Cost:** Unknown (quickly remediated) + +**What happened:** +```yaml +# Exposed Kubernetes dashboard (no authentication!) +apiVersion: v1 +kind: Service +metadata: + name: kubernetes-dashboard +spec: + type: LoadBalancer # ๐Ÿ”ฅ PUBLIC! + ports: + - port: 443 + targetPort: 8443 +``` + +**Fixed with policy-as-code:** +```rego +# Block public K8s services +deny[msg] { + input.kind == "Service" + input.spec.type == "LoadBalancer" + not input.metadata.annotations["service.beta.kubernetes.io/aws-load-balancer-internal"] + msg := "LoadBalancer must be internal-only" +} +``` + +### ๐Ÿ”ฎ Future of IaC Security (2025-2030) + +* ๐Ÿค– **AI-Powered Security:** + * ML models detect anomalous infrastructure patterns + * Auto-fix suggestions with context + * Predictive security (catch issues before they happen) + +* ๐Ÿ”„ **GitOps Everywhere:** + * All infrastructure changes via Git + * Automated policy enforcement + * Complete audit trails + +* ๐Ÿ›ก๏ธ **Shift-Left Evolution:** + * IDE plugins catch issues while coding + * Real-time policy feedback + * Security as you type + +* ๐ŸŒ **Zero-Trust Infrastructure:** + * Every resource requires explicit authorization + * Continuous verification + * Automated least-privilege + +* ๐Ÿ“ฆ **Policy Marketplaces:** + * Pre-built compliance frameworks + * Community-driven security rules + * Industry-specific policies + +### ๐Ÿ“š Best Practices Checklist + +```yaml +โœ… Security Fundamentals: + - [ ] Never hardcode secrets + - [ ] Use remote encrypted state + - [ ] Enable state locking + - [ ] Version pin all dependencies + - [ ] Use verified modules only + +โœ… Scanning & Testing: + - [ ] Run security scans in CI/CD + - [ ] Implement policy-as-code + - [ ] Test policies before enforcement + - [ ] Scan for secrets (gitleaks) + - [ ] Multiple tools (defense in depth) + +โœ… Access Control: + - [ ] RBAC for all operations + - [ ] MFA for production changes + - [ ] Separate accounts/workspaces + - [ ] Audit logs enabled + - [ ] Least privilege by default + +โœ… Compliance: + - [ ] Map checks to frameworks + - [ ] Automated compliance reports + - [ ] Regular policy reviews + - [ ] Documentation up-to-date + - [ ] Continuous monitoring + +โœ… Continuous Improvement: + - [ ] Track security metrics + - [ ] Regular security training + - [ ] Incident response plan + - [ ] Blameless post-mortems + - [ ] Share learnings across teams +``` + +### ๐ŸŽฏ Key Takeaways + +1. ๐Ÿ—๏ธ **IaC is powerful** - Automates infrastructure, but also automates vulnerabilities if not secured +2. ๐Ÿ” **Secrets management** - Use vaults, never hardcode, encrypt state +3. ๐Ÿ” **Scan everything** - tfsec, Checkov, Terrascan in every pipeline +4. ๐Ÿ“‹ **Policy-as-code** - OPA/Conftest/Sentinel enforce standards automatically +5. ๐Ÿš€ **Shift-left** - Catch issues in development, not production +6. ๐Ÿ“Š **Compliance** - Map IaC checks to regulatory requirements +7. ๐Ÿ”„ **GitOps** - Git as source of truth, automated deployments +8. ๐Ÿค– **Future is AI** - ML will revolutionize IaC security detection + +### ๐Ÿ”— Essential Resources + +* **๐Ÿ“š Learning:** + * [Terraform Best Practices](https://www.terraform-best-practices.com/) + * [Pulumi Examples](https://github.com/pulumi/examples) + * [Ansible Documentation](https://docs.ansible.com/) + * [OPA Policy Library](https://github.com/open-policy-agent/library) + +* **๐Ÿ› ๏ธ Tools:** + * [tfsec](https://aquasecurity.github.io/tfsec/) + * [Checkov](https://www.checkov.io/) + * [Conftest](https://www.conftest.dev/) + * [Prowler](https://github.com/prowler-cloud/prowler) + +* **๐Ÿ“‹ Standards:** + * [CIS Benchmarks](https://www.cisecurity.org/cis-benchmarks/) + * [NIST Cloud Computing](https://www.nist.gov/programs-projects/nist-cloud-computing-program-nccp) + * [OWASP Cloud Security](https://owasp.org/www-project-cloud-security/) + +* **๐ŸŽ“ Certifications:** + * HashiCorp Certified: Terraform Associate + * Certified Kubernetes Security Specialist (CKS) + * AWS Certified Security - Specialty + +--- diff --git a/lectures/lec7.md b/lectures/lec7.md new file mode 100644 index 00000000..2ef17eb1 --- /dev/null +++ b/lectures/lec7.md @@ -0,0 +1,1615 @@ +# ๐Ÿ“ŒLecture 7 - Container & Kubernetes Security: Docker/K8s Fundamentals, Image Scanning, RBAC & Runtime Protection + +## ๐Ÿ“‚ Group 1: Container Fundamentals & Security Basics + +## ๐Ÿ“ Slide 1 โ€“ ๐Ÿณ Container Technology Overview & Evolution + +* ๐Ÿณ **Container** = lightweight, portable execution environment that packages application + dependencies +* ๐Ÿ•ฐ๏ธ **Evolution timeline:** + * ๐Ÿ“… **1979**: Unix chroot โ†’ first process isolation concept + * ๐Ÿ“… **2000**: FreeBSD Jails โ†’ early container-like technology + * ๐Ÿ“… **2008**: LXC (Linux Containers) โ†’ Linux namespace + cgroups integration + * ๐Ÿ“… **2013**: Docker released โ†’ revolutionized container adoption + * ๐Ÿ“… **2014**: Kubernetes released by Google โ†’ container orchestration at scale + * ๐Ÿ“… **2017**: containerd donated to CNCF (Cloud Native Computing Foundation) +* ๐Ÿ“Š **Adoption stats**: 87% of organizations use containers in production (Red Hat State of Enterprise Open Source 2024) +* ๐Ÿข **Industry impact**: Netflix runs 300,000+ containers, Uber deploys 1,000+ times per day +* ๐Ÿ”— **Learn more:** [Docker Overview](https://docs.docker.com/get-started/overview/), [Container History](https://blog.aquasec.com/a-brief-history-of-containers-from-1970s-chroot-to-docker-2016) + +```mermaid +flowchart LR + BM[๐Ÿ–ฅ๏ธ Bare Metal
1970s-1990s] --> VM[๐Ÿ  Virtual Machines
2000s] + VM --> Container[๐Ÿ“ฆ Containers
2010s+] + + subgraph "๐Ÿ  VM Characteristics" + VM1[๐Ÿ”ง Full OS per VM] + VM2[๐Ÿ’พ High Resource Usage] + VM3[โฑ๏ธ Slow Boot Time] + end + + subgraph "๐Ÿ“ฆ Container Benefits" + C1[โšก Shared OS Kernel] + C2[๐Ÿ’จ Lightweight] + C3[๐Ÿš€ Fast Startup] + end + + style BM fill:#fdf2e9,stroke:#e67e22,stroke-width:2px,color:#2c3e50 + style VM fill:#eaf2f8,stroke:#3498db,stroke-width:2px,color:#2c3e50 + style Container fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 +``` + +--- + +### ๐Ÿ†š Container vs Virtual Machine Comparison + +| Aspect | ๐Ÿ  Virtual Machines | ๐Ÿ“ฆ Containers | +|--------|-------------------|---------------| +| ๐Ÿ”ง **Architecture** | Full OS + Hypervisor | Shared OS kernel | +| ๐Ÿ’พ **Resource Usage** | High (GB per VM) | Low (MB per container) | +| โฑ๏ธ **Startup Time** | Minutes | Seconds | +| ๐Ÿ”’ **Isolation** | Hardware-level | Process-level | +| ๐Ÿ“ฆ **Portability** | Limited | Excellent | +| ๐Ÿ›ก๏ธ **Security** | Stronger isolation | Weaker isolation | +| ๐Ÿ’ฐ **Cost** | Higher | Lower | + +### ๐Ÿ› ๏ธ Container Runtime Ecosystem + +* ๐Ÿณ **Docker** = most popular, full container platform (daemon + CLI + registry) +* ๐Ÿ—๏ธ **containerd** = industry-standard container runtime (Docker's core engine) +* ๐Ÿ”ง **CRI-O** = Kubernetes-focused, OCI (Open Container Initiative) compliant +* ๐Ÿ”’ **Podman** = daemonless, rootless containers by Red Hat +* โšก **runc** = low-level container runtime (spawns/runs containers) +* ๐Ÿ“Š **Market share**: Docker 83%, containerd 17% (Datadog Container Report 2024) + +```mermaid +flowchart LR + App[๐Ÿ“ฑ Application] --> Engine[๐Ÿš‚ Container Engine] + Engine --> Runtime[โš™๏ธ Container Runtime] + Runtime --> Kernel[๐Ÿง Linux Kernel] + + subgraph "๐Ÿš‚ Container Engines" + Docker[๐Ÿณ Docker] + Podman[๐Ÿ”’ Podman] + end + + subgraph "โš™๏ธ Container Runtimes" + containerd[๐Ÿ—๏ธ containerd] + CRIO[๐Ÿ”ง CRI-O] + runc[โšก runc] + end + + style App fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#2c3e50 + style Kernel fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 +``` + +
+๐Ÿ’ญ Interactive Question: Why would you choose Podman over Docker? + +**Podman advantages:** +* ๐Ÿ”’ **Daemonless** โ†’ no privileged daemon running +* ๐Ÿ‘ค **Rootless** โ†’ runs containers without root privileges +* ๐Ÿ” **More secure** โ†’ smaller attack surface +* ๐Ÿ“ฆ **OCI compliant** โ†’ better standards compliance +* ๐Ÿข **Enterprise focus** โ†’ Red Hat/IBM enterprise support + +**Docker advantages:** +* ๐ŸŒ **Ecosystem** โ†’ larger community, more tutorials +* ๐Ÿ› ๏ธ **Docker Compose** โ†’ easier multi-container apps +* ๐Ÿ“š **Documentation** โ†’ more learning resources +* ๐Ÿ”„ **Docker Hub** โ†’ largest container registry + +**Bottom line:** Podman for security-conscious enterprises, Docker for development ease +
+ +--- + +## ๐Ÿ“ Slide 2 โ€“ ๐Ÿ—๏ธ Docker Architecture & Security Model + +* ๐Ÿ—๏ธ **Docker Architecture Components:** + * ๐Ÿ–ฅ๏ธ **Docker Daemon (dockerd)** = background service managing containers + * ๐Ÿ’ป **Docker CLI** = command-line interface for user interactions + * ๐ŸŒ **Docker API** = RESTful API for programmatic control + * ๐Ÿ“ฆ **Docker Registry** = stores and distributes container images +* ๐Ÿ”’ **Container Isolation Mechanisms:** + * ๐Ÿ  **Namespaces** = isolate process views (PID, network, filesystem, user) + * โš–๏ธ **Control Groups (cgroups)** = limit resource usage (CPU, memory, I/O) + * ๐Ÿ›ก๏ธ **Seccomp** = restricts system calls available to processes + * ๐Ÿ” **AppArmor/SELinux** = mandatory access control policies +* โš ๏ธ **Critical security concern**: Docker daemon runs as root โ†’ potential privilege escalation +* ๐Ÿ“Š **Default Docker setup** = containers can access host resources if misconfigured + +```mermaid +flowchart LR + CLI[๐Ÿ’ป Docker CLI] --> Daemon[๐Ÿ–ฅ๏ธ Docker Daemon] + Daemon --> Images[๐Ÿ“ฆ Images] + Daemon --> Containers[๐Ÿƒโ€โ™‚๏ธ Running Containers] + Daemon --> Registry[๐ŸŒ Docker Registry] + + subgraph "๐Ÿ”’ Isolation Layers" + NS[๐Ÿ  Namespaces] + CG[โš–๏ธ cgroups] + SC[๐Ÿ›ก๏ธ seccomp] + MAC[๐Ÿ” AppArmor/SELinux] + end + + Containers --> NS + Containers --> CG + Containers --> SC + Containers --> MAC + + style Daemon fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + style NS fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 +``` + +--- + +### ๐Ÿ”“ Container Security Risks & Attack Vectors + +* ๐Ÿšช **Container Escape** = breaking out of container to access host system + * ๐Ÿ”‘ Common causes: privileged containers, mounted host directories, kernel vulnerabilities + * ๐Ÿ“Š **CVE-2019-5736** (runc escape) affected millions of containers worldwide +* โš ๏ธ **Docker Daemon Vulnerabilities:** + * ๐ŸŒ Exposed Docker API (port 2375/2376) โ†’ remote code execution + * ๐Ÿ”“ Insecure Docker socket access (`/var/run/docker.sock`) + * ๐Ÿ‘‘ Docker daemon runs as root โ†’ full host compromise possible +* ๐Ÿ“ฆ **Image-Based Attacks:** + * ๐Ÿ› Vulnerable base images with known CVEs + * ๐Ÿ”‘ Secrets embedded in image layers + * ๐Ÿฆ  Malicious images from untrusted registries +* ๐ŸŒ **Network Security Issues:** + * ๐Ÿ“ก Default bridge network โ†’ containers can communicate freely + * ๐Ÿ”“ Exposed container ports โ†’ unintended external access + +
+๐Ÿ’ญ Security Challenge: What makes the first command dangerous? + +**Multiple dangerous flags:** + +1. **`--privileged`** ๐Ÿ”“ + - Disables all security restrictions + - Gives container full access to host devices + - Can modify kernel parameters + +2. **`-v /:/host`** ๐Ÿ“ + - Mounts entire host filesystem + - Container can read/write ANY host file + - Includes `/etc/passwd`, `/etc/shadow`, etc. + +3. **Running as root (default)** ๐Ÿ‘‘ + - Container processes run with root privileges + - No user namespace isolation + +**Result:** Complete host compromise in one command! + +**Real-world impact:** This exact pattern caused the 2018 Tesla Kubernetes compromise. +
+ +--- + +## ๐Ÿ“ Slide 3 โ€“ ๐Ÿ“ฆ Container Images & Layered Filesystem + +* ๐Ÿ“ฆ **Container Image** = read-only template containing application code + runtime + libraries + dependencies +* ๐Ÿง… **Layered Architecture:** + * ๐Ÿ—๏ธ **Base layer** = operating system foundation (e.g., ubuntu:20.04) + * ๐Ÿ“š **Library layers** = runtime dependencies, frameworks + * ๐Ÿ“ฑ **Application layer** = your code and configurations + * ๐Ÿ” **Writable layer** = created when container runs (ephemeral) +* ๐Ÿญ **Image Registries:** + * ๐ŸŒ **Docker Hub** = public registry (10B+ image pulls monthly) + * โ˜๏ธ **Amazon ECR** = AWS-managed private registry + * โ˜๏ธ **Google GCR** = Google Cloud container registry + * ๐Ÿข **Harbor** = open-source enterprise registry with security scanning +* ๐Ÿ” **Docker Content Trust (DCT)** = image signing and verification using Notary +* ๐Ÿ“Š **Security stats**: 51% of container images contain high-severity vulnerabilities (Snyk Container Security Report 2024) + +```mermaid +flowchart TB + subgraph "๐Ÿ“ฆ Container Image Layers" + App[๐Ÿ“ฑ Application Layer
Your Code] + Deps[๐Ÿ“š Dependencies Layer
Libraries, Frameworks] + Runtime[โš™๏ธ Runtime Layer
JVM, Node.js, Python] + Base[๐Ÿ—๏ธ Base OS Layer
Ubuntu, Alpine, Distroless] + end + + subgraph "๐Ÿƒโ€โ™‚๏ธ Running Container" + Writable[โœ๏ธ Writable Layer
Temporary Changes] + App --> Writable + end + + subgraph "๐ŸŒ Registries" + Hub[๐ŸŒ Docker Hub
Public Images] + ECR[โ˜๏ธ AWS ECR
Private Registry] + Harbor[๐Ÿข Harbor
Enterprise Registry] + end + + Base --> Runtime + Runtime --> Deps + Deps --> App + + style App fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#2c3e50 + style Base fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + style Writable fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 +``` + +--- + +### ๐Ÿ”’ Image Security Best Practices + +* ๐Ÿ”๏ธ **Use Minimal Base Images:** + * ๐Ÿง **Alpine Linux** = 5MB base image vs Ubuntu's 64MB + * ๐Ÿ›ก๏ธ **Distroless** = no shell, package manager โ†’ smaller attack surface + * ๐Ÿ“ฆ **Scratch** = empty base image for static binaries +* ๐Ÿšซ **Avoid Root User:** + ```dockerfile + # โŒ BAD: Running as root (default) + FROM ubuntu:20.04 + COPY app /app + CMD ["/app"] + + # โœ… GOOD: Create and use non-root user + FROM ubuntu:20.04 + RUN groupadd -r appuser && useradd -r -g appuser appuser + COPY app /app + RUN chown -R appuser:appuser /app + USER appuser + CMD ["/app"] + ``` +* ๐Ÿ” **Multi-stage Builds** = separate build and runtime environments + +### ๐Ÿ“Š Base Image Comparison + +| Base Image | Size | Packages | Use Case | Security | +|------------|------|----------|----------|----------| +| ๐Ÿง **ubuntu:20.04** | 64MB | ~100 | Development | โš ๏ธ Medium | +| ๐Ÿ”๏ธ **alpine:latest** | 5MB | ~15 | Production | โœ… Good | +| ๐Ÿ›ก๏ธ **distroless** | 2-20MB | 0-5 | Production | ๐Ÿ† Excellent | +| ๐Ÿ“ฆ **scratch** | 0MB | 0 | Static binaries | ๐Ÿ† Maximum | + +
+๐Ÿ’ญ Quick Poll: Which base image would you choose for a Python web app? + +**Options:** +1. ๐Ÿง `python:3.11` (900MB) +2. ๐Ÿ”๏ธ `python:3.11-alpine` (50MB) +3. ๐Ÿ›ก๏ธ `python:3.11-slim` (120MB) +4. ๐Ÿ“ฆ Custom distroless + Python + +**Best practices:** +- **Development:** python:3.11 (easier debugging) +- **Production:** python:3.11-alpine or distroless (security + size) +- **High security:** Custom distroless build +- **CI/CD:** python:3.11-slim (balance of features + size) + +**Pro tip:** Start with slim, move to alpine/distroless as you mature your security practices! +
+ +--- + +## ๐Ÿ“ Slide 4 โ€“ ๐Ÿ” Container Image Security Scanning + +* ๐Ÿ” **Vulnerability Scanning** = automated analysis of container images for known security vulnerabilities +* ๐ŸŽฏ **What scanners detect:** + * ๐Ÿ› **OS package vulnerabilities** = CVEs in base image packages (apt, yum packages) + * ๐Ÿ“š **Application dependencies** = vulnerable libraries (npm, pip, maven packages) + * ๐Ÿ”‘ **Embedded secrets** = API keys, passwords, certificates in image layers + * โš™๏ธ **Misconfigurations** = running as root, exposed ports, insecure defaults +* ๐Ÿ› ๏ธ **Popular Scanning Tools:** + * โšก **Trivy** = comprehensive, fast, supports multiple languages + * ๐Ÿฆ… **Grype** = by Anchore, excellent vulnerability database + * ๐Ÿ **Snyk** = commercial, great developer experience + * ๐Ÿ” **Clair** = open-source, API-first, used by Red Hat Quay +* ๐Ÿ“Š **Scanning integration**: 78% of organizations scan images in CI/CD pipelines (CNCF Survey 2024) + +```mermaid +flowchart LR + Image[๐Ÿ“ฆ Container Image] --> Scanner[๐Ÿ” Security Scanner] + Scanner --> DB[(๐Ÿ—ƒ๏ธ Vulnerability Database
NVD, GitHub, OS vendors)] + Scanner --> Results[๐Ÿ“‹ Scan Results] + + subgraph "๐Ÿ“‹ Vulnerability Report" + Critical[๐Ÿ”ด Critical: 5] + High[๐ŸŸ  High: 12] + Medium[๐ŸŸก Medium: 23] + Low[๐ŸŸข Low: 8] + end + + Results --> Critical + Results --> High + Results --> Medium + Results --> Low + + subgraph "๐Ÿ› ๏ธ Popular Tools" + Trivy[โšก Trivy] + Grype[๐Ÿฆ… Grype] + Snyk[๐Ÿ Snyk] + Clair[๐Ÿ” Clair] + end + + style Critical fill:#ffebee,stroke:#d32f2f,stroke-width:3px,color:#2c3e50 + style High fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 +``` + +--- + +### ๐Ÿ”ง Scanner Comparison Matrix + +| Tool | ๐Ÿ’ฐ Cost | โšก Speed | ๐Ÿ“Š Accuracy | ๐ŸŒ Languages | ๐Ÿข Enterprise | +|------|---------|----------|-------------|--------------|--------------| +| โšก **Trivy** | Free | Fast | High | 20+ | Good | +| ๐Ÿฆ… **Grype** | Free | Fast | High | 15+ | Good | +| ๐Ÿ **Snyk** | Freemium | Fast | Very High | 25+ | Excellent | +| ๐Ÿ” **Clair** | Free | Medium | High | 10+ | Good | +| ๐Ÿ“Š **JFrog Xray** | Paid | Fast | Very High | 20+ | Excellent | + +### ๐Ÿ“ˆ Vulnerability Severity Levels (CVSS) + +| Score | Severity | ๐ŸŽฏ Action Required | โฐ Timeline | +|-------|----------|-------------------|------------| +| **9.0-10.0** | ๐Ÿ”ด **Critical** | Immediate fix | < 24 hours | +| **7.0-8.9** | ๐ŸŸ  **High** | Priority fix | < 7 days | +| **4.0-6.9** | ๐ŸŸก **Medium** | Plan fix | < 30 days | +| **0.1-3.9** | ๐ŸŸข **Low** | Consider fix | Next release | + +
+๐Ÿ’ญ Real-World Scenario: Your scan shows 50 vulnerabilities. What do you do? + +**Step-by-step vulnerability triage:** + +1. **๐Ÿ”ด Address Critical/High first** + - Focus on actively exploitable vulnerabilities + - Check if patches are available + - Prioritize by EPSS (Exploit Prediction Scoring System) + +2. **๐Ÿ“Š Analyze false positives** + - Some vulnerabilities may not apply to your use case + - Use scanner suppression files for confirmed false positives + - Document reasoning for suppression + +3. **๐Ÿ”„ Update strategy** + ```bash + # Update base image + FROM python:3.11-slim-bullseye # Instead of outdated version + + # Update packages + RUN apt-get update && apt-get upgrade -y && \ + apt-get clean && rm -rf /var/lib/apt/lists/* + ``` + +4. **๐Ÿ“ˆ Set policies** + - No Critical vulnerabilities in production + - High vulnerabilities fixed within 7 days + - Regular scanning schedule (weekly/monthly) + +**Pro tip:** Not all vulnerabilities are equal! A SQL injection in a web service vs a command injection in a CLI tool have different risk levels. +
+ +--- + +## ๐ŸŽ‰ Fun Break: "Container Horror Stories & Memes" + +### ๐Ÿ˜ฑ **"The 2018 Tesla Cryptocurrency Mining Incident"** + +**What happened:** +* ๐Ÿš— Tesla left Kubernetes dashboard **publicly accessible** without authentication +* ๐Ÿ˜ˆ Cryptominers discovered it and deployed mining containers +* โ›๏ธ Mined Monero cryptocurrency using Tesla's cloud resources +* ๐Ÿ’ธ Generated **thousands of dollars** in cloud bills +* ๐Ÿ” Tesla discovered it when AWS sent an unusually high bill + +**The meme-worthy part:** +* ๐Ÿค– Tesla, a company building **AI-powered cars**, got pwned by basic container misconfig +* ๐Ÿ“ฐ Headlines: *"Tesla's AI cars are secure, but their containers aren't"* +* ๐Ÿ’ฌ Security community: *"They can make cars drive themselves but can't secure a dashboard"* + +### ๐Ÿณ **Classic Container Memes:** + +**"Docker vs VM Resource Usage"** +``` +VM: I need 4GB RAM to run Hello World +Container: Hold my beer... 4MB is enough +``` + +**"Container Debugging"** +``` +Developer: "It works on my machine" +DevOps: "It works in containers" +Security: "Your container is pwned" +``` + +**"Container Escape Reality"** +``` +Junior Dev: "Containers are totally isolated!" +Security Engineer: "docker run --privileged has entered the chat" +``` + +### ๐ŸŽญ **Interactive Meme Creation Time!** + +**Fill in the blanks:** +``` +Before containers: "It works on my _____" +After containers: "It fails in _____" +After security scanning: "It has _____ critical vulnerabilities" +After hardening: "It _____ but it's secure!" +``` + +**Answers from the community:** +- machine / production / 47 / runs slower ๐Ÿ˜‚ +- laptop / staging / 1000 / doesn't run ๐Ÿ’€ +- computer / k8s / zero / works perfectly ๐Ÿ† + +--- + +๐Ÿ”— **Container Security Resources for Group 1:** +* [Docker Security Best Practices](https://docs.docker.com/develop/security-best-practices/) +* [Container Security by Liz Rice (Free eBook)](https://info.aquasec.com/container-security-book) +* [NIST Container Security Guide](https://www.nist.gov/publications/application-container-security-guide) +* [CIS Docker Benchmark](https://www.cisecurity.org/benchmark/docker) +* [Trivy Documentation](https://aquasecurity.github.io/trivy/) +* [OWASP Container Security Top 10](https://github.com/OWASP/www-project-container-top-10) + +## ๐Ÿ“‚ Group 2: Container Runtime Security + +## ๐Ÿ“ Slide 5 โ€“ ๐Ÿ›ก๏ธ Container Runtime Security + +* ๐Ÿ›ก๏ธ **Runtime Security** = monitoring containers while they're running, not just during build +* ๐Ÿšจ **Runtime Threats:** + * ๐Ÿš **Malicious process execution** (reverse shells, crypto miners) + * ๐Ÿ“ **Unauthorized file access** (reading `/etc/passwd`, config files) + * ๐ŸŒ **Suspicious network activity** (C2 communication, data exfiltration) + * ๐Ÿ”“ **Privilege escalation** attempts +* ๐Ÿ” **Detection Tools:** + * ๐Ÿฆ… **Falco** = CNCF project, runtime security monitoring + * ๐Ÿ“Š **Sysdig** = commercial platform with Falco underneath + * โšก **Aqua Security** = comprehensive runtime protection +* ๐Ÿ“Š **Stats**: 68% of organizations experienced runtime security incidents (Stackrox Report 2024) + +```mermaid +flowchart LR + Container[๐Ÿ“ฆ Running Container] --> Monitor[๐Ÿ‘๏ธ Runtime Monitor] + Monitor --> Rules[๐Ÿ“‹ Security Rules] + Rules --> Alert[๐Ÿšจ Security Alert] + + subgraph "๐Ÿšจ Runtime Threats" + Shell[๐Ÿš Reverse Shell] + Crypto[โ›๏ธ Crypto Mining] + Exfil[๐Ÿ“ค Data Exfiltration] + Escalate[๐Ÿ”“ Privilege Escalation] + end + + style Container fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + style Alert fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 +``` + +
+๐Ÿ’ญ Quick Question: How would you detect cryptocurrency mining? + +**Common indicators:** +* ๐Ÿ“Š High CPU usage (>80% sustained) +* ๐Ÿ” Process names: `xmrig`, `ethminer`, `cpuminer` +* ๐ŸŒ Network connections to mining pools +* ๐Ÿ“ Files: `/tmp/.X11-unix/`, hidden directories + +**Falco rule example:** +```yaml +- rule: Detect Crypto Mining + condition: spawned_process and (proc.name contains "miner" or proc.name contains "xmrig") + output: Crypto mining detected (process=%proc.name) + priority: CRITICAL +``` +
+ +--- + +## ๐Ÿ“ Slide 6 โ€“ ๐Ÿ” Secrets Management in Containers + +* ๐Ÿ”‘ **Container Secrets Problem:** + * โŒ **In Dockerfile** = visible to anyone with image access + * โŒ **Environment variables** = visible in process list (`docker inspect`) + * โŒ **Config files** = persisted in image layers forever +* โœ… **Secure Solutions:** + * ๐Ÿณ **Docker Secrets** = encrypted at rest, in-memory only in container + * โ˜ธ๏ธ **Kubernetes Secrets** = base64 encoded, etcd encryption + * ๐Ÿฆ **External Vaults** = HashiCorp Vault, AWS Secrets Manager + * ๐Ÿ”Œ **CSI Drivers** = mount secrets as files from external systems + +```mermaid +flowchart LR + subgraph "โŒ Insecure" + ENV[๐ŸŒ Environment Variables] + FILE[๐Ÿ“ Config Files] + DOCKER[๐Ÿณ Dockerfile Hardcoding] + end + + subgraph "โœ… Secure" + DSEC[๐Ÿณ Docker Secrets] + KSEC[โ˜ธ๏ธ K8s Secrets] + VAULT[๐Ÿฆ External Vault] + CSI[๐Ÿ”Œ CSI Secret Driver] + end + + style ENV fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + style VAULT fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 +``` + +### ๐Ÿ”„ Secret Rotation Best Practices + +* โฐ **Automatic rotation** every 30-90 days +* ๐Ÿ”„ **Zero-downtime rotation** using external secret operators +* ๐Ÿ“Š **Audit secret access** and usage patterns +* ๐Ÿšซ **Revoke compromised secrets** immediately + +--- + +## ๐Ÿ“ Slide 7 โ€“ ๐Ÿ“‹ Container Compliance & Hardening + +* ๐Ÿ“‹ **CIS Docker Benchmark** = 100+ security recommendations for Docker +* ๐Ÿ”’ **Container Hardening Checklist:** + * ๐Ÿ‘ค Run as non-root user (`USER 1001`) + * ๐Ÿ“– Read-only filesystem (`--read-only`) + * ๐Ÿšซ Drop capabilities (`--cap-drop=ALL`) + * ๐Ÿ  Use specific user namespaces + * ๐Ÿ“ฆ Scan images before deployment +* ๐Ÿ› ๏ธ **Compliance Tools:** + * โš–๏ธ **Docker Bench** = CIS benchmark automated checker + * โ˜ธ๏ธ **kube-bench** = CIS Kubernetes benchmark scanner + * ๐Ÿ“Š **Falco** = runtime compliance monitoring + +```mermaid +flowchart LR + Image[๐Ÿ“ฆ Container Image] --> Bench[โš–๏ธ Docker Bench] + Runtime[๐Ÿƒโ€โ™‚๏ธ Running Container] --> Monitor[๐Ÿ“Š Runtime Monitor] + K8s[โ˜ธ๏ธ Kubernetes] --> KubeBench[โ˜ธ๏ธ kube-bench] + + Bench --> Report[๐Ÿ“‹ Compliance Report] + Monitor --> Report + KubeBench --> Report + + subgraph "๐Ÿ”’ Hardening Checklist" + User[๐Ÿ‘ค Non-root User] + RO[๐Ÿ“– Read-only FS] + Caps[๐Ÿšซ Drop Caps] + Scan[๐Ÿ” Image Scanning] + end + + style Report fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 +``` + +### ๐Ÿ›ก๏ธ Hardened Container Example + +```dockerfile +# โœ… SECURE DOCKERFILE +FROM alpine:3.18 + +# Create non-root user +RUN addgroup -g 1001 appgroup && \ + adduser -u 1001 -G appgroup -s /bin/sh -D appuser + +# Install only required packages +RUN apk add --no-cache python3 py3-pip && \ + rm -rf /var/cache/apk/* + +# Copy application +COPY --chown=appuser:appgroup app.py /app/ +COPY --chown=appuser:appgroup requirements.txt /app/ + +# Switch to non-root +USER appuser +WORKDIR /app + +# Install dependencies +RUN pip install --no-cache-dir -r requirements.txt + +# Health check +HEALTHCHECK --interval=30s --timeout=3s \ + CMD python3 -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')" + +EXPOSE 8000 +CMD ["python3", "app.py"] +``` + +### ๐Ÿš€ Running Hardened Containers + +```bash +# โœ… SECURE RUNTIME FLAGS +docker run \ + --read-only \ # Read-only filesystem + --tmpfs /tmp \ # Writable temp directory + --user 1001:1001 \ # Non-root user + --cap-drop=ALL \ # Drop all capabilities + --cap-add=NET_BIND_SERVICE \ # Only add required caps + --security-opt=no-new-privileges \ # Prevent privilege escalation + --memory=512m \ # Memory limit + --cpus=0.5 \ # CPU limit + myapp:latest +``` + +### ๐Ÿ“Š Compliance Scanning + +```bash +# Docker Bench Security +git clone https://github.com/docker/docker-bench-security.git +cd docker-bench-security +sudo sh docker-bench-security.sh + +# Output example: +# [WARN] 4.5 - Ensure Content trust for Docker is Enabled +# [PASS] 4.6 - Ensure HEALTHCHECK is enabled +# [FAIL] 5.1 - Ensure AppArmor Profile is Enabled +``` + +
+๐Ÿ’ญ Challenge: Your container needs to write logs. How do you handle read-only filesystem? + +**Solutions:** + +1. **tmpfs mount** (in-memory): +```bash +docker run --read-only --tmpfs /var/log myapp:latest +``` + +2. **Volume mount**: +```bash +docker run --read-only -v /host/logs:/var/log myapp:latest +``` + +3. **Log to stdout/stderr**: +```python +# Instead of writing files, log to stdout +import logging +logging.basicConfig(stream=sys.stdout, level=logging.INFO) +``` + +4. **External logging** (best): +```bash +# Use logging driver +docker run --log-driver=fluentd myapp:latest +``` + +**Pro tip:** Cloud-native apps should log to stdout and let the orchestrator handle log collection! +
+ +--- + +## ๐ŸŽ‰ Fun Break: "Container Security Fails" + +### ๐Ÿ˜… **"The Bitcoin Mining Dockerfile"** + +```dockerfile +# Real Dockerfile found on Docker Hub (anonymized) +FROM ubuntu:16.04 +RUN apt-get update && apt-get install -y wget +RUN wget https://github.com/xmrig/xmrig/releases/download/v6.18.0/xmrig-6.18.0-linux-static-x64.tar.gz +RUN tar -xf xmrig*.tar.gz +RUN chmod +x xmrig-6.18.0/xmrig +CMD ["./xmrig-6.18.0/xmrig", "--donate-level=1"] +``` + +**Community reactions:** +* ๐Ÿ˜‚ "Finally, a Dockerfile that mines its own hosting costs" +* ๐Ÿคฆโ€โ™‚๏ธ "Running this in production would be interesting" +* ๐Ÿ”’ "Security team's nightmare in 8 lines" + +### ๐ŸŽญ **Security Meme Generator:** + +``` +When junior dev runs: +docker run --privileged -v /:/host ubuntu + +Senior dev: "Congratulations, you just _____ the host" +Security team: "Time to _____ everything" +Manager: "How much will this cost to _____?" + +Popular answers: +- pwned / reinstall / fix ($50k) +- nuked / rebuild / explain (my job) +- rooted / audit / cover up (priceless) +``` + +--- + +๐Ÿ”— **Runtime Security Resources:** +* [Falco Rules](https://github.com/falcosecurity/rules) +* [Docker Secrets Guide](https://docs.docker.com/engine/swarm/secrets/) +* [CIS Docker Benchmark](https://www.cisecurity.org/benchmark/docker) +* [Container Security Checklist](https://github.com/krol3/container-security-checklist) +## ๐Ÿ“‚ Group 3: Kubernetes Fundamentals & Architecture + +## ๐Ÿ“ Slide 8 โ€“ โ˜ธ๏ธ Kubernetes Architecture & Components + +* โ˜ธ๏ธ **Kubernetes** = container orchestration platform managing 1000s of containers across multiple nodes +* ๐Ÿ—๏ธ **Control Plane Components:** + * ๐ŸŒ **API Server** = all communication goes through here (kubectl, pods, everything) + * ๐Ÿง  **etcd** = distributed key-value store (cluster state, secrets, configs) + * ๐Ÿ“… **Scheduler** = decides which node runs each pod + * ๐ŸŽ›๏ธ **Controller Manager** = maintains desired state (replication, endpoints, etc.) +* ๐Ÿ‘ท **Worker Node Components:** + * ๐Ÿค– **kubelet** = node agent, manages pods and containers + * ๐ŸŒ **kube-proxy** = network proxy, handles service routing + * ๐Ÿƒโ€โ™‚๏ธ **Container Runtime** = Docker, containerd, or CRI-O +* ๐Ÿ“Š **Scale**: Google runs 2B+ containers/week on Kubernetes (2024) + +```mermaid +flowchart TB + subgraph "๐Ÿ—๏ธ Control Plane" + API[๐ŸŒ API Server] + ETCD[(๐Ÿง  etcd)] + SCHED[๐Ÿ“… Scheduler] + CTRL[๐ŸŽ›๏ธ Controller Manager] + end + + subgraph "๐Ÿ‘ท Worker Node 1" + KUBELET1[๐Ÿค– kubelet] + PROXY1[๐ŸŒ kube-proxy] + RUNTIME1[๐Ÿƒโ€โ™‚๏ธ Container Runtime] + POD1[๐Ÿ“ฆ Pods] + end + + subgraph "๐Ÿ‘ท Worker Node 2" + KUBELET2[๐Ÿค– kubelet] + PROXY2[๐ŸŒ kube-proxy] + RUNTIME2[๐Ÿƒโ€โ™‚๏ธ Container Runtime] + POD2[๐Ÿ“ฆ Pods] + end + + API --> KUBELET1 + API --> KUBELET2 + ETCD --> API + SCHED --> API + CTRL --> API + + style API fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + style ETCD fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 +``` + +### ๐Ÿ”’ Security Boundaries & Trust Zones + +| Component | Trust Level | Attack Surface | Impact if Compromised | +|-----------|-------------|----------------|----------------------| +| ๐ŸŒ **API Server** | ๐Ÿ”ด Critical | High | Complete cluster control | +| ๐Ÿง  **etcd** | ๐Ÿ”ด Critical | Medium | All secrets exposed | +| ๐Ÿค– **kubelet** | ๐ŸŸ  High | Medium | Node compromise | +| ๐Ÿ“ฆ **Pod** | ๐ŸŸข Low | High | Container breakout | + +### ๐ŸŒ Kubernetes Networking Model + +* ๐Ÿ“ก **Every pod gets its own IP** (no NAT between pods) +* ๐Ÿ”— **Pods can communicate** with all other pods by default +* ๐Ÿšช **Services provide stable endpoints** for dynamic pods +* ๐Ÿ›ก๏ธ **Network Policies** = firewall rules for pod-to-pod communication + +
+๐Ÿ’ญ Security Question: What happens if etcd gets compromised? + +**Complete disaster! ๐Ÿ’ฅ** + +**What's in etcd:** +* ๐Ÿ”‘ All Kubernetes secrets (base64 encoded, not encrypted by default) +* ๐ŸŽซ Service account tokens +* โš™๏ธ ConfigMaps with sensitive data +* ๐Ÿ” TLS certificates +* ๐Ÿ—๏ธ All cluster configuration + +**Attack scenarios:** +* ๐Ÿ“ค Extract all secrets and tokens +* ๐ŸŽญ Impersonate any service account +* ๐Ÿ”ง Modify cluster configuration +* ๐Ÿ’ฃ Deploy malicious workloads + +**Protection:** +* ๐Ÿ” Enable etcd encryption at rest +* ๐Ÿ”’ Restrict etcd network access +* ๐Ÿ›ก๏ธ Use strong authentication +* ๐Ÿ“Š Monitor etcd access logs +
+ +--- + +## ๐Ÿ“ Slide 9 โ€“ ๐Ÿ”‘ Kubernetes Authentication & Authorization + +* ๐Ÿ”‘ **Authentication** = Who are you? + * ๐Ÿ“œ **X.509 Certificates** = most common, used by kubectl + * ๐ŸŽซ **Service Account Tokens** = for pods to access API + * ๐ŸŒ **OIDC/OAuth** = integration with external identity providers + * ๐Ÿ” **Static tokens** = deprecated, avoid in production +* ๐Ÿ›ก๏ธ **Authorization** = What can you do? (RBAC = Role-Based Access Control) + * ๐Ÿ‘ค **Users** = humans with certificates + * ๐Ÿค– **Service Accounts** = pods/applications + * ๐Ÿ‘ฅ **Groups** = collection of users + * ๐ŸŽญ **Roles** = set of permissions (verbs + resources) +* ๐Ÿ“Š **Default behavior**: Service accounts have minimal permissions (good!) + +```mermaid +flowchart LR + User[๐Ÿ‘ค User/Pod] --> Auth[๐Ÿ”‘ Authentication] + Auth --> AuthZ[๐Ÿ›ก๏ธ Authorization RBAC] + AuthZ --> API[๐ŸŒ API Server] + + subgraph "๐Ÿ”‘ Auth Methods" + Cert[๐Ÿ“œ X.509 Certs] + Token[๐ŸŽซ SA Tokens] + OIDC[๐ŸŒ OIDC/OAuth] + end + + subgraph "๐Ÿ›ก๏ธ RBAC Components" + Role[๐ŸŽญ Roles] + Binding[๐Ÿ”— RoleBindings] + Subject[๐Ÿ‘ค Subjects] + end + + style Auth fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + style AuthZ fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 +``` + +
+๐Ÿ’ญ RBAC Challenge: How do you give a pod access to create other pods? + +**Careful! This is dangerous! ๐Ÿšจ** + +```yaml +# โš ๏ธ HIGH RISK ROLE +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +rules: +- apiGroups: [""] + resources: ["pods"] + verbs: ["create", "get", "list"] + +# Better: Use Jobs or Deployments +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +rules: +- apiGroups: ["batch"] + resources: ["jobs"] + verbs: ["create"] +``` + +**Why dangerous:** +* ๐Ÿ“ฆ Can create privileged pods +* ๐Ÿ”“ Can mount service account tokens +* ๐ŸŒ Can access host network +* ๐Ÿ’ฃ Essentially cluster-admin via pod creation + +**Better alternatives:** +* ๐ŸŽฏ Use specific controllers (Jobs, CronJobs) +* ๐Ÿ”’ Admission controllers to prevent privilege escalation +* ๐Ÿ›ก๏ธ Pod Security Standards +
+ +--- + +## ๐Ÿ“ Slide 10 โ€“ ๐Ÿšช Kubernetes Admission Control & Policies + +* ๐Ÿšช **Admission Controllers** = gatekeepers that intercept requests before persistence +* ๐Ÿ”„ **Two Types:** + * ๐Ÿ”ง **Mutating** = modify requests (add labels, inject sidecars) + * โœ… **Validating** = approve/reject requests (policy enforcement) +* ๐Ÿ›ก๏ธ **Pod Security Standards** (replaces deprecated Pod Security Policies): + * ๐Ÿ”“ **Privileged** = unrestricted (development only) + * โšก **Baseline** = minimally restrictive (default production) + * ๐Ÿ”’ **Restricted** = heavily restricted (high security) +* ๐ŸŽฏ **Open Policy Agent (OPA) Gatekeeper** = policy-as-code for Kubernetes + +```mermaid +flowchart LR + Request[๐Ÿ“ kubectl apply] --> Mutating[๐Ÿ”ง Mutating Admission] + Mutating --> Validating[โœ… Validating Admission] + Validating --> Accept{โœ… Accept?} + Accept -->|Yes| etcd[(๐Ÿง  etcd)] + Accept -->|No| Reject[โŒ Reject] + + subgraph "๐Ÿ›ก๏ธ Policy Examples" + PSS[๐Ÿ”’ Pod Security Standards] + OPA[๐ŸŽฏ OPA Gatekeeper] + Custom[โš™๏ธ Custom Webhooks] + end + + style Validating fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + style Reject fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 +``` + +### ๐Ÿ› ๏ธ Common Admission Controller Use Cases + +| Use Case | Tool | Example | +|----------|------|---------| +| ๐Ÿ”’ **Security Policies** | Pod Security Standards | Block privileged containers | +| ๐Ÿท๏ธ **Resource Quotas** | ResourceQuota controller | Limit CPU/memory per namespace | +| ๐ŸŽฏ **Policy Enforcement** | OPA Gatekeeper | Require specific labels | +| ๐Ÿ” **Secret Injection** | Custom webhook | Inject certificates from Vault | +| ๐Ÿ“Š **Monitoring** | Mutating webhook | Add monitoring sidecars | + +
+๐Ÿ’ญ Policy Question: Should you block or warn for policy violations? + +**Three enforcement modes:** + +1. **๐Ÿšซ Enforce (Block)** + - Rejects violating resources + - Prevents deployment + - Use for critical security policies + +2. **โš ๏ธ Warn** + - Shows warning but allows deployment + - Good for gradual policy rollout + - Doesn't break existing workflows + +3. **๐Ÿ“Š Audit (Log only)** + - Records violations for analysis + - No user impact + - Great for understanding current state + +**Best practice strategy:** +```yaml +# Start with audit, then warn, then enforce +pod-security.kubernetes.io/audit: restricted # Log violations +pod-security.kubernetes.io/warn: restricted # Show warnings +pod-security.kubernetes.io/enforce: baseline # Block only worst violations +``` + +**Gradual rollout timeline:** +- Week 1-2: Audit mode (gather data) +- Week 3-4: Warn mode (educate teams) +- Week 5+: Enforce mode (block violations) +
+ +--- + +## ๐ŸŽ‰ Fun Break: "Kubernetes RBAC Horror Stories" + +### ๐Ÿ˜ฑ **"The cluster-admin Intern"** + +**What happened:** +```bash +# Intern's first day task: "Fix the broken deployment" +kubectl create clusterrolebinding fix-it \ + --clusterrole=cluster-admin \ + --serviceaccount=default:my-app + +# Translation: "Give my app GOD MODE to the entire cluster" +``` + +**The aftermath:** +* ๐Ÿค– App gained ability to delete entire cluster +* ๐Ÿ’ฅ One typo away from production disaster +* ๐Ÿ” Security audit found 47 service accounts with cluster-admin +* ๐Ÿ“š Emergency RBAC training for all developers + +--- + +๐Ÿ”— **Kubernetes Security Resources:** +* [Kubernetes Security Best Practices](https://kubernetes.io/docs/concepts/security/) +* [RBAC Documentation](https://kubernetes.io/docs/reference/access-authn-authz/rbac/) +* [Pod Security Standards](https://kubernetes.io/docs/concepts/security/pod-security-standards/) +* [OPA Gatekeeper](https://open-policy-agent.github.io/gatekeeper/) + +## ๐Ÿ“‚ Group 4: Kubernetes Security Features + +## ๐Ÿ“ Slide 11 โ€“ ๐Ÿ›ก๏ธ Pod Security & Isolation + +* ๐Ÿ›ก๏ธ **Security Contexts** = pod/container-level security settings +* ๐Ÿ”ง **Key Security Controls:** + * ๐Ÿ‘ค **runAsUser/runAsGroup** = avoid root (UID 0) + * ๐Ÿšซ **allowPrivilegeEscalation: false** = block setuid binaries + * ๐Ÿ“– **readOnlyRootFilesystem: true** = immutable container filesystem + * ๐Ÿ’ช **capabilities** = fine-grained Linux permissions (drop ALL, add specific) +* ๐ŸŒ **Network Policies** = firewall rules for pod-to-pod communication +* ๐Ÿ“Š **Resource Limits** = prevent DoS attacks (CPU/memory bombs) +* ๐Ÿ”’ **Pod Security Standards** = enforce security baselines across namespaces + +```mermaid +flowchart LR + subgraph "๐Ÿ›ก๏ธ Pod Security Context" + User[๐Ÿ‘ค runAsNonRoot: true] + RO[๐Ÿ“– readOnlyRootFilesystem] + Caps[๐Ÿ’ช capabilities: drop ALL] + Priv[๐Ÿšซ allowPrivilegeEscalation: false] + end + + subgraph "๐ŸŒ Network Isolation" + NP[๐Ÿ”ฅ Network Policies] + Ingress[โฌ…๏ธ Ingress Rules] + Egress[โžก๏ธ Egress Rules] + end + + Pod[๐Ÿ“ฆ Secure Pod] --> User + Pod --> NP + + style Pod fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + style NP fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 +``` + +
+๐Ÿ’ญ Quick Challenge: Why does readOnlyRootFilesystem break many apps? + +**Common issues:** +* ๐Ÿ“ Apps writing logs to `/var/log/` +* ๐Ÿ“ฆ Package managers creating `/tmp/` files +* ๐Ÿ”ง Apps modifying config files at runtime +* ๐Ÿ  Home directory writes (`~/.cache`, `~/.config`) + +**Solutions:** +```yaml +# Mount writable volumes for specific paths +volumeMounts: +- name: tmp + mountPath: /tmp +- name: logs + mountPath: /var/log +- name: cache + mountPath: /home/app/.cache + +volumes: +- name: tmp + emptyDir: {} +- name: logs + emptyDir: {} +- name: cache + emptyDir: {} +``` + +**Pro tip:** Test with `readOnlyRootFilesystem: true` in dev first! +
+ +--- + +## ๐Ÿ“ Slide 12 โ€“ ๐Ÿ”’ Kubernetes Secrets & ConfigMaps + +* ๐Ÿ”’ **Kubernetes Secrets** = base64 encoded, stored in etcd (โš ๏ธ NOT encrypted by default!) +* ๐Ÿ“‹ **ConfigMaps** = non-sensitive configuration data +* ๐Ÿšจ **Secret Security Issues:** + * ๐Ÿ“ค Visible in `kubectl describe pod` output + * ๐Ÿ’พ Stored in etcd unencrypted (unless configured) + * ๐Ÿ‘๏ธ Accessible to anyone with pod read permissions + * ๐Ÿ“œ Logged in various places if not careful +* โœ… **Better Alternatives:** + * ๐Ÿฆ **External Secret Operators** (ESO) = sync from Vault/AWS/Azure + * ๐Ÿ”Œ **CSI Secret Store Driver** = mount secrets as files + * ๐Ÿ” **Sealed Secrets** = encrypted secrets safe for Git + +```mermaid +flowchart LR + subgraph "โŒ K8s Secrets Issues" + B64[๐Ÿ“ Base64 Encoded
NOT Encrypted] + ETCD[(๐Ÿง  etcd
Plaintext)] + Logs[๐Ÿ“œ Visible in Logs] + end + + subgraph "โœ… Secure Alternatives" + ESO[๐Ÿฆ External Secret Operator] + CSI[๐Ÿ”Œ CSI Secret Driver] + Sealed[๐Ÿ” Sealed Secrets] + end + + Secret[๐Ÿ”’ K8s Secret] --> B64 + B64 --> ETCD + + External[๐Ÿฆ External Vault] --> ESO + External --> CSI + + style ETCD fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + style ESO fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 +``` + +### ๐Ÿ” Secret Management Comparison + +| Method | Security | Complexity | Git-Safe | Rotation | +|--------|----------|------------|----------|----------| +| ๐Ÿ”’ **K8s Secrets** | โš ๏ธ Low | Low | โŒ No | Manual | +| ๐Ÿฆ **External Secret Operator** | โœ… High | Medium | โœ… Yes | Automatic | +| ๐Ÿ”Œ **CSI Driver** | โœ… High | Medium | โœ… Yes | Automatic | +| ๐Ÿ” **Sealed Secrets** | โœ… Medium | Low | โœ… Yes | Manual | + +--- + +## ๐Ÿ“ Slide 13 โ€“ ๐Ÿ“Š Kubernetes Auditing & Monitoring + +* ๐Ÿ“Š **Audit Logging** = records all API server requests (who did what when) +* ๐ŸŽฏ **Audit Levels:** + * ๐Ÿ“ **Metadata** = request metadata only + * ๐Ÿ“‹ **Request** = metadata + request body + * ๐Ÿ“ค **Response** = metadata + request + response bodies +* ๐Ÿ” **What to Monitor:** + * ๐Ÿšจ Failed authentication attempts + * ๐Ÿ”‘ Secret/ConfigMap access + * ๐Ÿ‘‘ Privileged pod creation + * ๐ŸŒ Exec/portforward sessions +* ๐Ÿ› ๏ธ **Monitoring Stack**: Prometheus + Grafana + Falco + ELK + +```mermaid +flowchart LR + API[๐ŸŒ API Server] --> Audit[๐Ÿ“Š Audit Logs] + Nodes[๐Ÿ‘ท Worker Nodes] --> Metrics[๐Ÿ“ˆ Node Metrics] + Pods[๐Ÿ“ฆ Pods] --> Logs[๐Ÿ“œ Application Logs] + + Audit --> SIEM[๐Ÿ” SIEM/ELK] + Metrics --> Prometheus[๐Ÿ“Š Prometheus] + Logs --> FluentD[๐Ÿ“ก FluentD] + + Prometheus --> Grafana[๐Ÿ“ˆ Grafana] + SIEM --> Alerts[๐Ÿšจ Security Alerts] + + style Audit fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + style Alerts fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 +``` + +### ๐Ÿ“Š Security Metrics Dashboard + +| Metric | Normal | Suspicious | +|--------|--------|------------| +| ๐Ÿ”‘ **Secret Access/hour** | < 50 | > 200 | +| ๐Ÿš **Exec Sessions/day** | < 10 | > 50 | +| ๐Ÿ‘‘ **Privileged Pods** | 0-2 | > 5 | +| โŒ **Failed Auth/hour** | < 5 | > 20 | +| ๐Ÿ“ฆ **Pod Creation Spikes** | Steady | 10x increase | + +
+๐Ÿ’ญ Monitoring Question: How do you detect a cryptocurrency mining attack? + +**Kubernetes-specific:** +* ๐Ÿšจ Unexpected pod creation in system namespaces +* ๐Ÿ“ˆ Sudden resource quota exhaustion +* ๐Ÿ”„ Pods restarting due to resource limits +* ๐ŸŒ Unknown container images from suspicious registries + +**Response:** +1. ๐Ÿ›‘ `kubectl delete pod ` +2. ๐Ÿ” Check audit logs for how pods were created +3. ๐Ÿ”’ Review RBAC permissions +4. ๐Ÿ“Š Implement resource quotas and limits +
+ +--- + +## ๐ŸŽ‰ Fun Break: "Kubernetes Secrets Exposed!" + +### ๐Ÿคฆโ€โ™‚๏ธ **"The Base64 Confusion"** + +**Slack conversation:** +``` +Junior Dev: "I encrypted our database password!" +Senior Dev: "Great! How?" +Junior Dev: "echo 'password123' | base64" +Senior Dev: "That's... not encryption ๐Ÿ˜…" +Junior Dev: "But it's unreadable!" +Senior Dev: "echo 'cGFzc3dvcmQxMjM=' | base64 -d" +Junior Dev: "... oh" +``` + +### ๐Ÿ” **"Secret Scanning Memes"** + +``` +Kubernetes Secrets be like: + +Developer: "Our secrets are secure in base64!" +Security Scanner: "I can read that" +Developer: "But it's encoded!" +Security Scanner: "Here's your plaintext password" +Developer: *surprised Pikachu face* +``` + +### ๐ŸŽญ **Interactive K8s Quiz:** + +``` +What's wrong with this Secret usage? + +apiVersion: v1 +kind: Pod +spec: + containers: + - name: app + env: + - name: DB_PASS + valueFrom: + secretKeyRef: + name: db-secret + key: password + - name: DEBUG + value: "true" # Logs everything including env vars! ๐Ÿคฆโ€โ™‚๏ธ + +Answer: Debug mode will log environment variables, exposing the secret! + +Better: Use mounted secret files instead of env vars when possible. +``` + +### ๐Ÿ’ก **Security Pro Tips:** + +``` +โŒ Don't: kubectl create secret generic mysecret --from-literal=password=123 +โœ… Do: Use external secret management + +โŒ Don't: Store secrets in environment variables +โœ… Do: Mount secrets as files when possible + +โŒ Don't: Log request/response bodies in production +โœ… Do: Use metadata-level audit logging for secrets +``` + +--- + +๐Ÿ”— **Kubernetes Security Features Resources:** +* [Pod Security Standards](https://kubernetes.io/docs/concepts/security/pod-security-standards/) +* [Network Policies](https://kubernetes.io/docs/concepts/services-networking/network-policies/) +* [Kubernetes Secrets](https://kubernetes.io/docs/concepts/configuration/secret/) +* [External Secrets Operator](https://external-secrets.io/) +* [Kubernetes Auditing](https://kubernetes.io/docs/tasks/debug-application-cluster/audit/) + +## ๐Ÿ“‚ Group 5: Kubernetes Security Tools & Practices + +## ๐Ÿ“ Slide 14 โ€“ ๐Ÿ” Kubernetes Security Scanning + +* ๐Ÿ” **Static Analysis Tools:** + * ๐ŸŽฏ **kube-score** = YAML analysis, best practices scoring + * ๐Ÿน **kube-hunter** = penetration testing from attacker perspective + * โญ **Polaris** = configuration validation, security recommendations + * ๐Ÿ“Š **Checkov** = policy-as-code scanning for K8s manifests +* ๐Ÿƒโ€โ™‚๏ธ **Runtime Security:** + * ๐Ÿฆ… **Falco** = runtime threat detection + * ๐Ÿ” **Sysdig Secure** = comprehensive runtime protection + * โšก **Aqua Security** = container runtime security platform +* ๐Ÿ“Š **Compliance Scanning:** + * โ˜ธ๏ธ **kube-bench** = CIS Kubernetes benchmark automation + * ๐Ÿ“‹ **Popeye** = cluster sanitizer, finds issues and recommendations + +```mermaid +flowchart LR + Manifest[๐Ÿ“ K8s Manifest] --> Static[๐Ÿ” Static Scan] + Cluster[โ˜ธ๏ธ Running Cluster] --> Runtime[๐Ÿƒโ€โ™‚๏ธ Runtime Scan] + Config[โš™๏ธ Cluster Config] --> Compliance[๐Ÿ“‹ Compliance Scan] + + Static --> Issues[๐Ÿ“‹ Security Issues] + Runtime --> Threats[๐Ÿšจ Live Threats] + Compliance --> Gaps[โš ๏ธ Compliance Gaps] + + style Issues fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + style Threats fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 +``` + +### ๐Ÿ› ๏ธ Quick Tool Comparison + +| Tool | Focus | Speed | Difficulty | +|------|-------|-------|------------| +| ๐ŸŽฏ **kube-score** | Best practices | โšก Fast | Easy | +| ๐Ÿน **kube-hunter** | Penetration testing | ๐ŸŒ Slow | Medium | +| โญ **Polaris** | Config validation | โšก Fast | Easy | +| โ˜ธ๏ธ **kube-bench** | CIS compliance | ๐Ÿš€ Medium | Easy | + +
+๐Ÿ’ญ Which tool first? + +**Recommended order:** +1. ๐ŸŽฏ **kube-score** โ†’ quick YAML validation +2. โ˜ธ๏ธ **kube-bench** โ†’ baseline security check +3. โญ **Polaris** โ†’ ongoing configuration monitoring +4. ๐Ÿน **kube-hunter** โ†’ penetration testing (advanced) + +**Start simple, add complexity gradually!** +
+ +--- + +## ๐Ÿ“ Slide 15 โ€“ ๐ŸŒ Kubernetes Network Security + +* ๐Ÿ”ฅ **Network Policies** = firewall rules for pods (deny-by-default recommended) +* ๐Ÿ•ธ๏ธ **CNI Security Features:** + * ๐Ÿ‹ **Calico** = advanced network policies, encryption + * ๐Ÿ **Cilium** = eBPF-based security, L7 policies + * ๐ŸŒ **Istio** = service mesh with mTLS, traffic policies +* ๐Ÿ”’ **Security Patterns:** + * ๐Ÿšซ **Default deny-all** โ†’ explicit allow only required traffic + * ๐Ÿ  **Namespace isolation** โ†’ prevent cross-namespace communication + * ๐Ÿ” **mTLS everywhere** โ†’ encrypted pod-to-pod communication + * ๐Ÿ›ก๏ธ **Ingress security** โ†’ WAF, rate limiting, SSL termination + +```mermaid +flowchart LR + Pod1[๐Ÿ“ฆ Pod A] -.-> Firewall[๐Ÿ”ฅ Network Policy] + Firewall --> Pod2[๐Ÿ“ฆ Pod B] + + subgraph "๐Ÿ”’ Security Features" + CNI[๐Ÿ•ธ๏ธ CNI Security] + mTLS[๐Ÿ” mTLS] + WAF[๐Ÿ›ก๏ธ WAF/Ingress] + end + + style Firewall fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + style CNI fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 +``` + +### ๐ŸŒ CNI Comparison + +| CNI | Security Focus | Complexity | Performance | +|-----|----------------|------------|-------------| +| ๐Ÿ‹ **Calico** | Network policies | Medium | High | +| ๐Ÿ **Cilium** | eBPF L7 security | High | Very High | +| ๐ŸŒ **Istio** | Service mesh mTLS | Very High | Medium | + +--- + +## ๐Ÿ“ Slide 16 โ€“ ๐Ÿ—๏ธ Secure Kubernetes CI/CD Pipelines + +* ๐Ÿš€ **GitOps Security:** + * ๐Ÿ“‚ **ArgoCD** = declarative GitOps with RBAC + * ๐ŸŒŠ **Flux** = GitOps toolkit with security controls + * ๐Ÿ”’ **Sealed Secrets** = encrypted secrets in Git +* ๐Ÿ—๏ธ **Pipeline Security:** + * ๐Ÿ“ฆ **Image signing** (Cosign, Notary v2) + * ๐Ÿ” **Policy enforcement** at deployment time + * ๐ŸŽฏ **Supply chain attestation** (SLSA, in-toto) +* ๐Ÿ›ก๏ธ **Deployment Patterns:** + * ๐Ÿ”ต **Blue-green** deployments for security updates + * ๐Ÿฅ **Canary** releases with security monitoring + * ๐Ÿ“Š **Progressive delivery** with automated rollback + +```mermaid +flowchart LR + Git[๐Ÿ“‚ Git Repo] --> GitOps[๐Ÿš€ GitOps Controller] + GitOps --> Policy[๐Ÿ›ก๏ธ Policy Check] + Policy --> Deploy[๐Ÿš€ Deploy] + + subgraph "๐Ÿ”’ Security Gates" + Sign[โœ๏ธ Image Signing] + Scan[๐Ÿ” Security Scan] + Test[๐Ÿงช Security Tests] + end + + Policy --> Sign + Policy --> Scan + Policy --> Test + + style Policy fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 +``` + +### ๐Ÿ“Š Security Metrics + +| Metric | Target | Alert | +|--------|--------|-------| +| ๐Ÿ” **Images scanned** | 100% | < 95% | +| โœ๏ธ **Signed images** | 100% | < 100% | +| ๐Ÿšจ **Critical CVEs** | 0 | > 0 | +| โฑ๏ธ **Deployment time** | < 10min | > 15min | + +--- + +## ๐ŸŽ‰ Fun Break: "K8s Security Tool Chaos" + +### ๐Ÿ˜… **"The Tool Overload Syndrome"** + +``` +Security Engineer's Desktop: +- kube-score โœ… +- kube-hunter โœ… +- kube-bench โœ… +- Polaris โœ… +- Falco โœ… +- Trivy โœ… +- Snyk โœ… +- Checkov โœ… + +Developer: "Which one do I use?" +Security: "Yes." +``` + +### ๐ŸŽญ **Network Policy Memes:** + +``` +NetworkPolicy be like: + +Default: "Everyone can talk to everyone! ๐ŸŽ‰" +Security team: "NOPE" *applies default-deny* +Developers: "Nothing works! ๐Ÿ˜ญ" +Security team: "Working as intended โœ…" +``` + +### ๐Ÿ”ง **Tool Selection Reality:** + +``` +Manager: "We need ALL the security tools!" +Budget: "Pick one." +Security team: "kube-bench + Falco" +Manager: "But what about..." +Security team: "KISS principle wins again" +``` + +--- + +๐Ÿ”— **K8s Security Tools Resources:** +* [kube-score](https://github.com/zegl/kube-score) +* [kube-hunter](https://github.com/aquasecurity/kube-hunter) +* [Polaris](https://github.com/FairwindsOps/polaris) +* [Falco Rules](https://github.com/falcosecurity/rules) +* [Cilium Network Policies](https://docs.cilium.io/en/stable/security/policy/) + +## ๐Ÿ“‚ Group 6: Advanced Topics & Case Studies + +## ๐Ÿ“ Slide 17 โ€“ ๐Ÿšจ Kubernetes Attack Scenarios & Defense + +* ๐ŸŽฏ **Common Attack Vectors:** + * ๐Ÿ”“ **Privileged container breakout** โ†’ host compromise + * ๐Ÿ”‘ **Service account token abuse** โ†’ lateral movement + * ๐ŸŒ **Exposed API server** โ†’ cluster takeover + * ๐Ÿ“ฆ **Malicious images** โ†’ supply chain compromise + * โ˜๏ธ **Cloud metadata access** โ†’ credential theft +* ๐Ÿ›ก๏ธ **MITRE ATT&CK for Containers:** + * ๐ŸŽฏ **Initial Access** โ†’ exposed services, supply chain + * ๐Ÿ”“ **Privilege Escalation** โ†’ privileged containers, hostPath mounts + * ๐Ÿ“ก **Lateral Movement** โ†’ service account tokens, network access + +```mermaid +flowchart LR + subgraph "๐ŸŽฏ Attack Chain" + Initial[๐Ÿšช Initial Access] --> Escalate[๐Ÿ”“ Privilege Escalation] + Escalate --> Lateral[๐Ÿ“ก Lateral Movement] + Lateral --> Persist[๐Ÿ”„ Persistence] + Persist --> Exfil[๐Ÿ“ค Exfiltration] + end + + subgraph "๐Ÿ›ก๏ธ Defense Layers" + Prevent[๐Ÿšซ Prevent] + Detect[๐Ÿ‘๏ธ Detect] + Respond[๐Ÿšจ Respond] + end + + style Initial fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + style Prevent fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 +``` + +### ๐Ÿ›ก๏ธ Defense Matrix + +| Attack Vector | Detection | Prevention | +|---------------|-----------|------------| +| ๐Ÿ”“ **Privileged pods** | Falco rules | Pod Security Standards | +| ๐Ÿ”‘ **Token abuse** | Audit logs | RBAC least privilege | +| ๐ŸŒ **API exposure** | Network monitoring | Network policies | +| ๐Ÿ“ฆ **Malicious images** | Image scanning | Admission controllers | + +
+๐Ÿ’ญ Attack Scenario: How would you detect crypto mining? + +**Detection signals:** +* ๐Ÿ“Š High CPU usage (>90% sustained) +* ๐ŸŒ Connections to mining pools (port 4444, 3333) +* ๐Ÿ” Process names: `xmrig`, `ethminer`, `cpuminer` +* ๐Ÿ“ˆ Unusual network traffic patterns + +**Falco rule:** +```yaml +- rule: Cryptocurrency Mining + condition: spawned_process and proc.name in (xmrig, cpuminer, ethminer) + output: Crypto mining detected (proc=%proc.name) + priority: CRITICAL +``` +
+ +--- + +## ๐Ÿ“ Slide 18 โ€“ ๐Ÿ”ฎ Future Trends & Security Checklist + +* ๐Ÿ”ฎ **Emerging Trends:** + * ๐Ÿค– **AI-powered threat detection** โ†’ behavioral analysis, anomaly detection + * ๐Ÿ›ก๏ธ **Zero-trust containers** โ†’ verify everything, trust nothing + * ๐Ÿ“‹ **SBOM for containers** โ†’ software bill of materials tracking + * ๐Ÿ” **Workload identity** โ†’ SPIFFE/SPIRE adoption + * โ˜๏ธ **Confidential computing** โ†’ encrypted container workloads +* ๐Ÿš€ **Next-Gen Security:** + * ๐Ÿฆ€ **WebAssembly (WASM)** โ†’ lightweight, secure container alternative + * ๐Ÿ”— **Supply chain attestation** โ†’ provenance verification + * ๐Ÿ“Š **Policy-as-code evolution** โ†’ Git-native security policies + +```mermaid +flowchart LR + subgraph "๐Ÿ”ฎ Future Security Stack" + AI[๐Ÿค– AI Detection] + ZeroTrust[๐Ÿ›ก๏ธ Zero Trust] + SBOM[๐Ÿ“‹ SBOM Tracking] + Workload[๐Ÿ” Workload Identity] + end + + Current[๐Ÿ“ฆ Today's Containers] --> Future[๐Ÿš€ Next-Gen Security] + + style Future fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#2c3e50 +``` + +### ๐Ÿ›ก๏ธ Container Security Checklist + +#### ๐Ÿ“ฆ **Container Images** +- [ ] ๐Ÿ” Scan all images for vulnerabilities +- [ ] ๐Ÿ”๏ธ Use minimal base images (Alpine/Distroless) +- [ ] ๐Ÿ‘ค Run as non-root user +- [ ] ๐Ÿ” Sign images with Cosign +- [ ] ๐Ÿ“‹ Generate SBOM for tracking + +#### โ˜ธ๏ธ **Kubernetes Security** +- [ ] ๐Ÿ”‘ Enable RBAC with least privilege +- [ ] ๐Ÿ›ก๏ธ Apply Pod Security Standards +- [ ] ๐ŸŒ Implement network policies (default-deny) +- [ ] ๐Ÿ“Š Enable audit logging +- [ ] ๐Ÿ” Encrypt etcd at rest + +#### ๐Ÿƒโ€โ™‚๏ธ **Runtime Security** +- [ ] ๐Ÿฆ… Deploy Falco for threat detection +- [ ] ๐Ÿ“ˆ Monitor resource usage anomalies +- [ ] ๐Ÿšซ Block privileged containers +- [ ] ๐Ÿ“– Enable read-only filesystems +- [ ] ๐Ÿ”’ Use seccomp/AppArmor profiles + +#### ๐Ÿ”„ **CI/CD Pipeline** +- [ ] ๐Ÿ” Scan images in pipeline +- [ ] ๐Ÿšซ Fail builds on critical CVEs +- [ ] โœ๏ธ Require signed commits/images +- [ ] ๐Ÿ›ก๏ธ Validate security policies +- [ ] ๐Ÿ“Š Track security metrics + +### ๐Ÿ“Š Security Maturity Levels + +| Level | Description | Focus | +|-------|-------------|-------| +| ๐Ÿš€ **Level 1** | Basic security | Image scanning, RBAC | +| ๐Ÿ›ก๏ธ **Level 2** | Defense in depth | Network policies, admission control | +| ๐Ÿ† **Level 3** | Advanced security | Runtime protection, zero-trust | +| ๐Ÿ”ฎ **Level 4** | Future-ready | AI detection, confidential computing | + +### ๐ŸŽฏ Key Takeaways + +1. **๐Ÿ” Scan everything** โ†’ images, configs, runtime behavior +2. **๐Ÿšซ Default deny** โ†’ network policies, RBAC, admission control +3. **๐Ÿ‘ค Least privilege** โ†’ non-root users, minimal permissions +4. **๐Ÿ“Š Monitor continuously** โ†’ logs, metrics, anomalies +5. **๐Ÿ”„ Automate security** โ†’ policy-as-code, CI/CD integration +6. **๐Ÿ“š Stay updated** โ†’ patches, CVEs, security practices +7. **๐ŸŽฏ Plan for incidents** โ†’ detection, response, recovery +8. **๐Ÿ›ก๏ธ Defense in depth** โ†’ multiple security layers + +--- + +## ๐ŸŽ‰ Fun Break: "Container Security Evolution" + +### ๐Ÿ˜… **"The Security Maturity Journey"** + +``` +2015: "Containers are secure by default!" ๐Ÿ˜‡ +2016: "Wait, they share the kernel..." ๐Ÿ˜ฐ +2017: "Maybe we need some scanning..." ๐Ÿ” +2018: "Tesla got crypto-mined via K8s!" ๐Ÿ˜ฑ +2019: "RBAC ALL THE THINGS!" ๐Ÿ” +2020: "Supply chain is the new attack vector" ๐Ÿ“ฆ +2024: "AI will solve container security" ๐Ÿค– +2025: "AI is the new attack vector" ๐Ÿค–๐Ÿ’€ +``` + +### ๐ŸŽญ **Security Reality Check:** + +``` +Security team: "We've implemented 47 security tools!" +Developer: "My pod won't start..." +Security team: "Working as intended!" +Manager: "Why is our security budget so high?" +Everyone: "..." + +The eternal struggle continues... ๐Ÿ˜„ +``` + +### ๐Ÿ’ก **Container Security Wisdom:** + +``` +โŒ "Security is someone else's job" +โœ… "Security is everyone's responsibility" + +โŒ "We'll add security later" +โœ… "Security is built-in from day one" + +โŒ "Scanning once is enough" +โœ… "Continuous monitoring is essential" + +โŒ "Default configs are fine" +โœ… "Harden everything by default" +``` + +--- + +๐Ÿ”— **Advanced Security Resources:** +* [MITRE ATT&CK Containers](https://attack.mitre.org/matrices/enterprise/containers/) +* [Kubernetes Security Checklist](https://kubernetes.io/docs/concepts/security/security-checklist/) +* [CNCF Cloud Native Security Map](https://github.com/cncf/tag-security/blob/main/security-whitepaper/v2/CNCF_cloud-native-security-whitepaper-May2022-v2.pdf) +* [Container Security Best Practices](https://kubernetes.io/docs/concepts/security/) +* [Falco Community Rules](https://github.com/falcosecurity/rules) + +--- diff --git a/lectures/lec8.md b/lectures/lec8.md new file mode 100644 index 00000000..9c433389 --- /dev/null +++ b/lectures/lec8.md @@ -0,0 +1,2414 @@ +# ๐Ÿ“‹ Lecture 8 - Software Supply Chain Security: SBOM, Signing & Provenance + +## ๐Ÿ“‚ Group 1: Supply Chain Foundations + +## ๐Ÿ“ Slide 1 โ€“ ๐Ÿ”— What is Software Supply Chain Security? + +* ๐Ÿ”— **Software Supply Chain** = everything from source code to production deployment +* ๐Ÿ“ฆ **Not just dependencies** โ†’ code, build tools, CI/CD, artifacts, infrastructure +* ๐ŸŽฏ **Core principle:** "Trust but verify every step of the software delivery process" +* ๐Ÿ”ฅ **Modern reality:** Average application has **200+ dependencies** (direct + transitive) +* ๐Ÿ“Š **Statistics (2024):** + * 88% of organizations experienced supply chain attack attempts + * 66% of breaches involved third-party software + * $4.5M average cost of supply chain breach +* ๐Ÿ”— **Learn more:** [CISA Supply Chain Security](https://www.cisa.gov/supply-chain), [OWASP SCVS](https://scvs.owasp.org/) + +```mermaid +flowchart LR + subgraph "๐Ÿ”— Software Supply Chain" + Code[๐Ÿ“ Source Code] --> Build[๐Ÿ—๏ธ Build System] + Build --> Deps[๐Ÿ“ฆ Dependencies] + Deps --> Artifact[๐Ÿ“ฆ Artifacts] + Artifact --> Registry[๐Ÿ—„๏ธ Registry] + Registry --> Deploy[๐Ÿš€ Deployment] + Deploy --> Runtime[โšก Runtime] + end + + Attack1[๐Ÿ’ฅ Compromised
Dependency] -.->|Attack| Deps + Attack2[๐Ÿ’ฅ Build System
Compromise] -.->|Attack| Build + Attack3[๐Ÿ’ฅ Registry
Poisoning] -.->|Attack| Registry + + style Code fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + style Build fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + style Deps fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + style Artifact fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#2c3e50 + style Registry fill:#e1f5fe,stroke:#0288d1,stroke-width:2px,color:#2c3e50 + style Deploy fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + style Runtime fill:#fce4ec,stroke:#c2185b,stroke-width:2px,color:#2c3e50 + style Attack1 fill:#ffebee,stroke:#d32f2f,stroke-width:3px,color:#2c3e50 + style Attack2 fill:#ffebee,stroke:#d32f2f,stroke-width:3px,color:#2c3e50 + style Attack3 fill:#ffebee,stroke:#d32f2f,stroke-width:3px,color:#2c3e50 +``` + +--- + +### ๐ŸŒ Supply Chain Security Scope + +* ๐Ÿ“ **Source integrity:** Code repositories, commits, developers +* ๐Ÿ—๏ธ **Build integrity:** Build systems, tools, environment +* ๐Ÿ“ฆ **Dependency integrity:** Third-party libraries, transitive dependencies +* ๐Ÿ” **Artifact integrity:** Compiled binaries, container images, packages +* ๐Ÿš€ **Deployment integrity:** Infrastructure, configuration, secrets +* โšก **Runtime integrity:** Actual running code matches expected + +```mermaid +flowchart LR + Threat[๐ŸŽฏ Why Attackers
Target Supply Chains] --> Impact1[๐Ÿ’ฅ Maximum Impact
One compromise = thousands affected] + Threat --> Impact2[๐Ÿ•ต๏ธ Stealth
Hidden in trusted code] + Threat --> Impact3[โฐ Persistence
Harder to detect and remove] + Threat --> Impact4[๐Ÿ”“ Trusted Path
Bypasses security controls] + + style Threat fill:#ffebee,stroke:#d32f2f,stroke-width:3px,color:#2c3e50 + style Impact1 fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + style Impact2 fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + style Impact3 fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + style Impact4 fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 +``` + +
+๐Ÿ’ญ Discussion: Why is supply chain security harder than traditional security? + +**Key challenges:** + +1. ๐ŸŒ **Scale:** Hundreds of dependencies, thousands of transitive dependencies +2. ๐Ÿ‘ฅ **Trust boundaries:** You trust code written by strangers +3. โฐ **Time dimension:** Vulnerabilities discovered after deployment +4. ๐Ÿ”„ **Constant change:** New versions, new maintainers, new risks +5. ๐Ÿ‘๏ธ **Visibility gaps:** Hard to know what's actually running +6. ๐Ÿ”— **Transitive trust:** Dependency of dependency of dependency... + +**Traditional security:** Protect your code +**Supply chain security:** Protect everyone else's code that you use +
+ +--- + +## ๐Ÿ“ Slide 2 โ€“ ๐Ÿ’ฅ Famous Supply Chain Breaches & Incidents + +### ๐Ÿ”ฅ Timeline of Major Attacks + +```mermaid +timeline + title ๐Ÿ•ฐ๏ธ Supply Chain Attack Timeline + 2017 : ๐Ÿฆ Equifax
Unpatched Apache Struts
147M records + 2018 : ๐Ÿ“ฆ Event-Stream
npm package hijacked
Bitcoin wallet theft + 2020 : โ˜€๏ธ SolarWinds
Build system compromise
18,000+ organizations + 2021 : ๐Ÿชต Log4Shell
Zero-day in Log4j
Billions of devices + : ๐ŸŽฅ Codecov
Bash uploader modified
Hundreds of companies + : ๐ŸŽจ UA-Parser.js
Supply chain attack
Crypto miner injected + 2022 : ๐Ÿ”ฅ PyTorch
Dependency confusion
torchtriton malicious package + 2024 : ๐Ÿ“š XZ Utils
Multi-year backdoor
Almost compromised Linux +``` + +--- + +### ๐Ÿ’ฅ SolarWinds (2020) + +* โ˜€๏ธ **Target:** SolarWinds Orion platform (IT management software) +* ๐Ÿ“… **Date:** March-December 2020 (9 months undetected) +* ๐ŸŽฏ **Attack method:** Compromised build system, injected SUNBURST backdoor +* ๐Ÿ’ฅ **Impact:** + * 18,000+ organizations downloaded trojanized update + * 100+ US companies compromised + * Multiple US government agencies breached + * Estimated $100M+ damage +* ๐Ÿ”‘ **Key lesson:** **Build systems are critical infrastructure** + +```mermaid +flowchart LR + Attacker[๐Ÿ•ต๏ธ APT29
Russian State Actors] -->|1. Compromise| Build[๐Ÿ—๏ธ SolarWinds
Build System] + Build -->|2. Inject| Backdoor[๐Ÿ’€ SUNBURST
Backdoor] + Backdoor -->|3. Sign with| Cert[โœ… Valid Certificate] + Cert -->|4. Distribute| Update[๐Ÿ“ฆ Orion Update] + Update -->|5. Install| Victims[๐ŸŽฏ 18,000+
Organizations] + + style Attacker fill:#ffebee,stroke:#d32f2f,stroke-width:3px,color:#2c3e50 + style Build fill:#ffcdd2,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + style Backdoor fill:#b71c1c,stroke:#d32f2f,stroke-width:3px,color:#fff + style Victims fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 +``` + +--- + +### ๐Ÿชต Log4Shell (2021) + +* ๐Ÿ“ฆ **Target:** Apache Log4j (ubiquitous Java logging library) +* ๐Ÿ“… **Date:** December 2021 (disclosed) +* ๐ŸŽฏ **Vulnerability:** CVE-2021-44228 (CVSS 10.0 - Critical) +* ๐Ÿ’ฅ **Impact:** + * Billions of devices affected + * Used in: Minecraft, iCloud, Steam, Twitter, Amazon, Tesla + * Exploited within hours of disclosure + * Still being exploited in 2024 +* ๐Ÿ”‘ **Key lesson:** **One dependency can break the internet** + +```mermaid +flowchart LR + Log4j[๐Ÿชต Log4j
Everywhere] --> App1[๐Ÿ“ฑ Mobile Apps] + Log4j --> App2[โ˜๏ธ Cloud Services] + Log4j --> App3[๐ŸŽฎ Games] + Log4j --> App4[๐Ÿข Enterprise Software] + Log4j --> App5[๐ŸŒ Web Applications] + + Attack[๐Ÿ’€ JNDI Exploit] -.->|RCE| Log4j + + style Log4j fill:#ffebee,stroke:#d32f2f,stroke-width:3px,color:#2c3e50 + style Attack fill:#b71c1c,stroke:#d32f2f,stroke-width:3px,color:#fff +``` + +--- + +### ๐ŸŽฅ Codecov Bash Uploader (2021) + +* ๐Ÿ› ๏ธ **Target:** Codecov (code coverage tool used in CI/CD) +* ๐Ÿ“… **Date:** January-April 2021 (compromised for 3 months) +* ๐ŸŽฏ **Attack method:** Modified Bash uploader script to exfiltrate secrets +* ๐Ÿ’ฅ **Impact:** + * Hundreds of companies affected + * CI/CD environment variables stolen (AWS keys, tokens) + * Undetected for months +* ๐Ÿ”‘ **Key lesson:** **Security tools can become attack vectors** + +--- + +### ๐Ÿ“ฆ Event-Stream npm (2018) + +* ๐Ÿ“ฆ **Target:** event-stream (popular npm package, 2M+ downloads/week) +* ๐Ÿ“… **Date:** September-November 2018 +* ๐ŸŽฏ **Attack method:** + * Original maintainer handed off to attacker + * Malicious dependency (flatmap-stream) added + * Targeted Bitcoin wallets +* ๐Ÿ’ฅ **Impact:** Cryptocurrency theft from Copay wallet users +* ๐Ÿ”‘ **Key lesson:** **Maintainer trust is critical** + +```mermaid +flowchart LR + Original[๐Ÿ‘จโ€๐Ÿ’ป Original
Maintainer] -->|Transfer ownership| Attacker[๐Ÿ•ต๏ธ Attacker] + Attacker -->|Add dependency| Malicious[๐Ÿ’€ flatmap-stream
Malicious Package] + Malicious -->|Included in| EventStream[๐Ÿ“ฆ event-stream
v3.3.6] + EventStream -->|Installed by| Victims[๐ŸŽฏ 2M+ weekly
downloads] + Victims -->|Steal| Crypto[๐Ÿ’ฐ Bitcoin Wallets] + + style Attacker fill:#ffebee,stroke:#d32f2f,stroke-width:3px,color:#2c3e50 + style Malicious fill:#b71c1c,stroke:#d32f2f,stroke-width:3px,color:#fff +``` + +--- + +### ๐Ÿ“š XZ Utils Backdoor (2024) + +* ๐Ÿ› ๏ธ **Target:** xz/liblzma (compression library in most Linux distros) +* ๐Ÿ“… **Date:** 2021-2024 (multi-year social engineering campaign) +* ๐ŸŽฏ **Attack method:** + * Attacker spent 2+ years building trust + * Became co-maintainer through social engineering + * Injected sophisticated backdoor into build system + * Targeted SSH authentication in systemd +* ๐Ÿ’ฅ **Impact:** Nearly compromised all major Linux distributions +* ๐Ÿ” **Discovery:** Microsoft engineer noticed 500ms SSH slowdown +* ๐Ÿ”‘ **Key lesson:** **Long-term social engineering is the new attack vector** + +
+๐Ÿ’ญ Interactive: What do these incidents have in common? + +**Common patterns:** + +1. โœ… **Trusted software** was weaponized (all were legitimate, popular projects) +2. โฐ **Long dwell time** (weeks or months before detection) +3. ๐ŸŽฏ **High-value targets** (broad impact, critical infrastructure) +4. ๐Ÿ•ต๏ธ **Sophisticated attackers** (nation-states or organized crime) +5. ๐Ÿ”“ **Exploited trust** (signed certificates, trusted maintainers) +6. ๐Ÿ“Š **Massive scale** (thousands to millions affected) + +**Prevention requires:** +* ๐Ÿ” Transparency (SBOMs, provenance) +* โœ๏ธ Signing (Sigstore) +* ๐Ÿ›ก๏ธ Monitoring (continuous scanning) +* ๐Ÿ“‹ Policies (only deploy verified artifacts) +
+ +--- + +## ๐Ÿ“ Slide 3 โ€“ ๐ŸŽฏ Supply Chain Attack Vectors + +### ๐Ÿ”ฅ Attack Vector Categories + +```mermaid +flowchart LR + subgraph "๐ŸŽฏ Supply Chain Attack Vectors" + V1[๐Ÿ”„ Dependency
Confusion] + V2[โŒจ๏ธ Typosquatting] + V3[๐Ÿ”‘ Account
Takeover] + V4[๐Ÿ—๏ธ Build System
Compromise] + V5[๐Ÿ“ฆ Malicious
Updates] + V6[๐Ÿ”— Transitive
Poisoning] + end + + V1 --> Impact[๐Ÿ’ฅ Code Execution
Data Theft
Backdoors] + V2 --> Impact + V3 --> Impact + V4 --> Impact + V5 --> Impact + V6 --> Impact + + style V1 fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + style V2 fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + style V3 fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + style V4 fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + style V5 fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + style V6 fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + style Impact fill:#b71c1c,stroke:#d32f2f,stroke-width:3px,color:#fff +``` + +--- + +### ๐Ÿ”„ Dependency Confusion / Substitution + +* ๐ŸŽฏ **Attack:** Trick package manager into installing malicious public package instead of internal one +* ๐Ÿ”‘ **How it works:** + * Company uses internal package: `@company/auth-lib` + * Attacker publishes public package: `auth-lib` with higher version + * Package manager prefers public over internal (misconfiguration) +* ๐Ÿ’ฐ **Real case:** Security researcher Alex Birsan earned **$130k in bug bounties** (2021) +* ๐ŸŽฏ **Victims:** Apple, Microsoft, Tesla, Uber, PayPal, and 30+ others + +```mermaid +flowchart LR + Internal[๐Ÿข Internal Registry
mycompany-auth v1.0.0] + Public[๐ŸŒ Public Registry
mycompany-auth v99.0.0] + + Developer[๐Ÿ‘จโ€๐Ÿ’ป Developer] -->|Expects| Internal + Developer -->|Gets| Public + Public -.->|Malicious| Exfil[๐Ÿ’€ Credential Theft] + + style Internal fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + style Public fill:#ffebee,stroke:#d32f2f,stroke-width:3px,color:#2c3e50 + style Exfil fill:#b71c1c,stroke:#d32f2f,stroke-width:3px,color:#fff +``` + +--- + +### โŒจ๏ธ Typosquatting + +* ๐ŸŽฏ **Attack:** Register package names similar to popular packages +* ๐Ÿ”‘ **Examples:** + * `reqests` instead of `requests` (Python) + * `cross-env` vs `crossenv` (npm) + * `electorn` vs `electron` + * `lodas` vs `lodash` +* ๐Ÿ“Š **Scale:** Over **10,000 typosquatting packages** detected on npm/PyPI +* ๐Ÿ’ฅ **Impact:** Steals credentials, crypto wallets, environment variables + +--- + +### ๐Ÿ”‘ Account Takeover + +* ๐ŸŽฏ **Attack:** Compromise maintainer accounts, push malicious updates +* ๐Ÿ”‘ **Methods:** + * Stolen credentials (phishing, credential stuffing) + * No 2FA on maintainer accounts + * Social engineering + * Insider threats +* ๐Ÿ“ฆ **Examples:** + * **Event-Stream:** Maintainer transferred ownership + * **UA-Parser.js:** Maintainer account compromised, malicious v0.8.0 published + * **coa/rc packages (npm):** Password theft from maintainer + +--- + +### ๐Ÿ—๏ธ Build System Compromise + +* ๐ŸŽฏ **Attack:** Compromise the build/CI system itself +* ๐Ÿ”‘ **SolarWinds method:** + * Attackers gained access to build environment + * Injected malicious code during compilation + * Signed with legitimate certificate + * Distributed through official update channel +* ๐Ÿ’ฅ **Why devastating:** Bypasses all code review, every build is poisoned +* ๐Ÿ›ก๏ธ **Defense:** Hermetic builds, provenance, SLSA framework + +```mermaid +flowchart LR + Source[๐Ÿ“ Clean
Source Code] --> Build[๐Ÿ—๏ธ Compromised
Build System] + Build -->|Inject| Backdoor[๐Ÿ’€ Malicious Code] + Backdoor --> Sign[โœ… Sign with
Valid Cert] + Sign --> Artifact[๐Ÿ“ฆ Trojanized
Artifact] + Artifact --> Users[๐ŸŽฏ All Users
Affected] + + style Source fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + style Build fill:#ffcdd2,stroke:#d32f2f,stroke-width:3px,color:#2c3e50 + style Backdoor fill:#b71c1c,stroke:#d32f2f,stroke-width:3px,color:#fff + style Users fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 +``` + +--- + +### ๐Ÿ“ฆ Malicious Updates to Legitimate Packages + +* ๐ŸŽฏ **Attack:** Inject malicious code into new version of trusted package +* ๐Ÿ”‘ **After compromise:** + * Package has legitimate history + * Developers trust and auto-update + * Malicious version gets installed automatically +* ๐Ÿ“ฆ **Examples:** + * **Event-Stream v3.3.6:** Added malicious dependency + * **Colors.js & faker.js (2022):** Maintainer intentionally broke packages (protest) + +--- + +### ๐Ÿ”— Transitive Dependency Poisoning + +* ๐ŸŽฏ **Attack:** Compromise dependency several levels deep +* ๐Ÿ”‘ **Why effective:** + * Developers only vet direct dependencies + * Transitive dependencies invisible + * Average package has 70+ transitive dependencies +* ๐Ÿ“Š **Example chain:** + ``` + Your App + โ””โ”€โ”€ express (direct) + โ””โ”€โ”€ body-parser + โ””โ”€โ”€ qs + โ””โ”€โ”€ side-channel + โ””โ”€โ”€ ๐Ÿ’€ MALICIOUS PACKAGE + ``` + +
+๐Ÿ’ญ Challenge: How many dependencies does your project REALLY have? + +**Try this:** + +```bash +# Node.js +npm ls --all | wc -l + +# Python +pip list | wc -l + +# Go +go list -m all | wc -l +``` + +**You might be shocked!** Most projects have: +* ๐Ÿ“ฆ **10-50 direct dependencies** +* ๐Ÿ”— **200-1000+ transitive dependencies** +* โ“ **Unknown risk** from dependencies you never heard of + +**This is why SBOM and continuous scanning are critical!** +
+ +--- + +## ๐Ÿ“ Slide 4 โ€“ ๐Ÿ›ก๏ธ Supply Chain Security Frameworks + +### ๐Ÿ“‹ Major Frameworks Overview + +| Framework | Owner | Focus | Maturity | +|-----------|-------|-------|----------| +| ๐ŸŽฏ **SLSA** | Google / OpenSSF | Build integrity, provenance | โœ… Mature | +| ๐Ÿ“Š **NIST SSDF** | US NIST | Secure development practices | โœ… Mature | +| ๐Ÿ“‹ **SBOM** | CISA / NTIA | Software transparency | โœ… Mandatory (US) | +| ๐Ÿ” **SCVS** | OWASP | Component verification | ๐Ÿšง Emerging | +| ๐Ÿ‡ช๐Ÿ‡บ **CRA** | EU | Product security requirements | ๐Ÿ”œ Coming 2024 | + +--- + +### ๐ŸŽฏ SLSA (Supply Chain Levels for Software Artifacts) + +* ๐Ÿ›๏ธ **Created by:** Google (2021), now part of OpenSSF +* ๐ŸŽฏ **Goal:** Framework for software supply chain integrity +* ๐Ÿ“Š **4 levels** (0-4) with increasing security guarantees +* ๐Ÿ”‘ **Core concepts:** + * Build integrity (no tampering) + * Provenance (who/what/when/how) + * Non-falsifiable evidence + +```mermaid +flowchart LR + L0[๐Ÿ“Š Level 0
No guarantees] --> L1[๐Ÿ“ Level 1
Build process exists] + L1 --> L2[โœ… Level 2
Provenance generated] + L2 --> L3[๐Ÿ”’ Level 3
Hardened builds] + L3 --> L4[๐Ÿ† Level 4
Highest assurance] + + style L0 fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + style L1 fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + style L2 fill:#fff9c4,stroke:#fbc02d,stroke-width:2px,color:#2c3e50 + style L3 fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + style L4 fill:#1b5e20,stroke:#388e3c,stroke-width:3px,color:#fff +``` + +**SLSA Levels:** +* **Level 0:** No requirements (most software today) +* **Level 1:** Build process documented +* **Level 2:** Build service generates signed provenance +* **Level 3:** Build platform is hardened, provenance non-falsifiable +* **Level 4:** Two-party review + hermetic builds + +๐Ÿ”— **Learn more:** [slsa.dev](https://slsa.dev/) + +--- + +### ๐Ÿ“Š NIST SSDF (Secure Software Development Framework) + +* ๐Ÿ›๏ธ **Created by:** US National Institute of Standards and Technology +* ๐ŸŽฏ **Goal:** High-level practices for secure software development +* ๐Ÿ“‹ **4 practice groups:** + * **PO:** Prepare the Organization + * **PS:** Protect the Software + * **PW:** Produce Well-Secured Software + * **RV:** Respond to Vulnerabilities +* ๐Ÿ”‘ **Government mandate:** Required for US federal software procurement +* ๐Ÿ”— **Reference:** [NIST SP 800-218](https://csrc.nist.gov/Projects/ssdf) + +--- + +### ๐Ÿ“‹ SBOM (Software Bill of Materials) + +* ๐Ÿ›๏ธ **Mandated by:** US Executive Order 14028 (May 2021), CISA +* ๐ŸŽฏ **Goal:** Transparency - know what's in your software +* ๐Ÿ“Š **Two main standards:** + * **SPDX** (Linux Foundation) - ISO/IEC 5962:2021 standard + * **CycloneDX** (OWASP) - Security-focused format +* ๐Ÿ”‘ **Minimum elements (NTIA):** + * Supplier name + * Component name + * Version + * Unique identifier + * Dependency relationships + * Author of SBOM data + * Timestamp +* ๐Ÿ”— **Covered in Lab 4**, will analyze in depth in Lab 8 + +--- + +### ๐Ÿ” SCVS (Software Component Verification Standard) + +* ๐Ÿ›๏ธ **Created by:** OWASP (2020) +* ๐ŸŽฏ **Goal:** Verification requirements for software components +* ๐Ÿ“Š **Three levels:** + * **Level 1:** Basic verification (inventory, known vulnerabilities) + * **Level 2:** Intermediate (pedigree, provenance, signing) + * **Level 3:** Advanced (reproducible builds, continuous monitoring) +* ๐Ÿ”— **Learn more:** [scvs.owasp.org](https://scvs.owasp.org/) + +--- + +### ๐Ÿ‡ช๐Ÿ‡บ EU Cyber Resilience Act (CRA) + +* ๐Ÿ›๏ธ **Enacted by:** European Union (2024) +* ๐ŸŽฏ **Goal:** Mandatory cybersecurity requirements for products with digital elements +* ๐Ÿ“‹ **Key requirements:** + * Security by design + * Vulnerability disclosure + * Security updates for product lifetime + * **SBOM transparency** +* ๐Ÿ’ฐ **Penalties:** Up to โ‚ฌ15M or 2.5% of global revenue +* ๐Ÿ”— **Impact:** Global (any product sold in EU) + +
+๐Ÿ’ญ Discussion: Which framework should you adopt? + +**Short answer: ALL OF THEM!** They're complementary, not competing. + +**Practical approach:** + +1. **Start with SBOM** (required by law, easiest to implement) + * Generate SBOMs in CI/CD (Lab 4) + * Use for vulnerability tracking + +2. **Adopt SLSA gradually** (incremental security improvements) + * Start at Level 1 (document your build) + * Aim for Level 3 (GitHub Actions can achieve this) + +3. **Use NIST SSDF as checklist** (comprehensive best practices) + * Map your processes to NIST practices + * Identify gaps + +4. **Reference SCVS for verification** (what to check) + * Verify dependencies meet minimum standards + * Implement continuous monitoring + +**They all work together to create defense in depth!** +
+ +--- + +## ๐Ÿ“ Slide 5 โ€“ ๐Ÿ“Š Supply Chain Security in DevSecOps Pipeline + +### ๐Ÿ”„ Integration Points in SDLC + +```mermaid +flowchart LR + IDE[๐Ÿ’ป IDE
Local Dev] -->|Secret scan
Dependency check| Git[๐Ÿ“ Git
Source Control] + Git -->|Pre-commit hooks
Signed commits| CI[๐Ÿ”„ CI/CD
Build Pipeline] + CI -->|SCA scan
SBOM generation
Signing| Registry[๐Ÿ—„๏ธ Artifact
Registry] + Registry -->|Signature verify
Policy check| Deploy[๐Ÿš€ Deployment] + Deploy -->|Provenance verify
Admission control| Runtime[โšก Runtime
Production] + Runtime -->|Continuous scan
Drift detection| Monitor[๐Ÿ“Š Monitoring] + Monitor -.->|Feedback| IDE + + style IDE fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + style Git fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + style CI fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + style Registry fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#2c3e50 + style Deploy fill:#e1f5fe,stroke:#0288d1,stroke-width:2px,color:#2c3e50 + style Runtime fill:#fce4ec,stroke:#c2185b,stroke-width:2px,color:#2c3e50 + style Monitor fill:#fff9c4,stroke:#fbc02d,stroke-width:2px,color:#2c3e50 +``` + +--- + +### ๐Ÿ” Security Controls by Stage + +| Stage | Security Controls | Tools | +|-------|------------------|-------| +| ๐Ÿ’ป **IDE** | Dependency vulnerability hints | Snyk, Dependabot alerts | +| ๐Ÿ“ **Git** | Secret scanning, commit signing | Gitleaks, GPG, Sigstore | +| ๐Ÿ”„ **CI/CD** | SCA scan, SBOM generation, signing | Syft, Grype, Cosign | +| ๐Ÿ—„๏ธ **Registry** | Image scanning, policy enforcement | Harbor, Artifactory, Nexus | +| ๐Ÿš€ **Deploy** | Signature verification, provenance check | Cosign verify, Kyverno | +| โšก **Runtime** | Continuous monitoring, drift detection | Falco, Tetragon, Tracee | + +--- + +### ๐Ÿ“Š Shift-Left for Dependencies + +* โฌ…๏ธ **Shift-left principle:** Catch issues as early as possible +* ๐Ÿ’ฐ **Cost of fix increases with time:** + * **IDE:** Free (instant feedback) + * **PR:** $10 (code review) + * **CI/CD:** $100 (build failure) + * **Staging:** $1,000 (deployment delay) + * **Production:** $100,000+ (breach, downtime) + +```mermaid +flowchart LR + Early[โฌ…๏ธ Earlier Detection] -->|Lower cost| IDE[๐Ÿ’ป IDE
$0] + IDE --> PR[๐Ÿ“ Pull Request
$10] + PR --> CI[๐Ÿ”„ CI/CD
$100] + CI --> Stage[๐Ÿงช Staging
$1,000] + Stage --> Prod[๐ŸŒ Production
$100,000+] + + style Early fill:#e8f5e8,stroke:#388e3c,stroke-width:3px,color:#2c3e50 + style IDE fill:#c8e6c9,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + style PR fill:#fff9c4,stroke:#fbc02d,stroke-width:2px,color:#2c3e50 + style CI fill:#ffe0b2,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + style Stage fill:#ffccbc,stroke:#ff5722,stroke-width:2px,color:#2c3e50 + style Prod fill:#ffebee,stroke:#d32f2f,stroke-width:3px,color:#2c3e50 +``` + +--- + +### ๐Ÿ›ก๏ธ Defense in Depth Strategy + +* ๐Ÿ”„ **Multiple layers:** No single tool catches everything +* ๐Ÿงช **Continuous testing:** Scan at every stage +* ๐Ÿ“Š **Different perspectives:** + * **SAST:** Analyze source code (covered Lab 5) + * **SCA:** Analyze dependencies (**this lab**) + * **Container scan:** Analyze OS packages (covered Lab 7) + * **DAST:** Test running application (covered Lab 5) +* ๐Ÿ” **Feedback loops:** Results inform earlier stages + +```mermaid +flowchart LR + subgraph "๐Ÿ›ก๏ธ Defense in Depth" + Layer1[๐Ÿ” IDE Plugins] + Layer2[๐Ÿ“ Pre-commit Hooks] + Layer3[๐Ÿ”„ CI/CD Scanning] + Layer4[๐Ÿ—„๏ธ Registry Policies] + Layer5[๐Ÿš€ Admission Control] + Layer6[๐Ÿ“Š Runtime Monitoring] + end + + Threat[๐Ÿ’€ Supply Chain
Attack] -.->|Blocked| Layer1 + Threat -.->|Blocked| Layer2 + Threat -.->|Blocked| Layer3 + Threat -.->|Blocked| Layer4 + Threat -.->|Blocked| Layer5 + Threat -.->|Detected| Layer6 + + style Threat fill:#ffebee,stroke:#d32f2f,stroke-width:3px,color:#2c3e50 + style Layer1 fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + style Layer2 fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + style Layer3 fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + style Layer4 fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + style Layer5 fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + style Layer6 fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 +``` + +--- + +### ๐ŸŽฏ Key Takeaways: Integration + +* โœ… **Automate everything:** Manual processes don't scale +* โฌ…๏ธ **Shift-left aggressively:** Fail fast, fail cheap +* ๐Ÿ” **Continuous monitoring:** New vulnerabilities discovered daily +* ๐Ÿ›ก๏ธ **Multiple layers:** No single point of failure +* ๐Ÿ“Š **Visibility:** SBOM + provenance = transparency +* ๐Ÿšจ **Policy enforcement:** Automated gates prevent risky deployments + +
+๐Ÿ’ญ Poll: What's your biggest supply chain security challenge? + +**Common challenges (audience participation):** + +A. ๐Ÿ“Š **Visibility** - Don't know what dependencies we have +B. ๐Ÿ”„ **Scale** - Too many dependencies to track manually +C. โฐ **Speed** - Security slows down development +D. ๐Ÿงช **False positives** - Too many irrelevant alerts +E. ๐Ÿ“‹ **Compliance** - Meeting regulatory requirements +F. ๐Ÿ”ง **Tooling** - Don't know which tools to use +G. ๐Ÿ‘ฅ **Culture** - Developers resist security checks + +**The good news:** This lab addresses all of these! ๐ŸŽฏ +
+ +--- + +## ๐ŸŽ‰ Fun Break: "The Leftpad Incident (2016)" + +### ๐Ÿ˜ฑ How 11 Lines of Code Broke the Internet + +**The Setup:** +* ๐Ÿ“ฆ **leftpad** = tiny npm package (11 lines) +* ๐ŸŽฏ **Purpose:** Pad strings with spaces on the left +* ๐Ÿ“Š **Usage:** Dependency of Babel, React, thousands of projects + +**What Happened:** +1. ๐Ÿ‘จโ€๐Ÿ’ป Developer Azer Koรงulu had naming dispute with npm and a company +2. ๐Ÿ˜ค Got angry and **unpublished ALL his packages** (273 packages) +3. ๐Ÿ’ฅ **leftpad disappeared from npm registry** +4. ๐Ÿ”ฅ **Thousands of projects broke instantly** worldwide +5. ๐ŸŒ Continuous integration systems **failed globally** +6. โฐ Incident duration: **~3 hours of internet chaos** + +```mermaid +flowchart LR + Leftpad[๐Ÿ“ฆ leftpad
11 lines] --> Babel[โš™๏ธ Babel] + Leftpad --> React[โš›๏ธ React] + Babel --> Thousands[๐ŸŒ Thousands
of Projects] + React --> Thousands + + Delete[๐Ÿ—‘๏ธ npm unpublish] -.->|๐Ÿ’ฅ| Leftpad + Leftpad -.->|โŒ BROKEN| Thousands + + style Leftpad fill:#ffebee,stroke:#d32f2f,stroke-width:3px,color:#2c3e50 + style Delete fill:#b71c1c,stroke:#d32f2f,stroke-width:3px,color:#fff + style Thousands fill:#ffccbc,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 +``` + +**The Fix:** +* npm **changed their policy** - can't unpublish packages after 24 hours if other packages depend on it +* npm **restored leftpad** manually +* The incident lasted only **2.5 hours** but taught the world about dependency hell + +**Memes Born:** +* "How to break the internet with 11 lines" +* "Is your startup based on leftpad?" +* "The butterfly effect is real in software" + +**Lessons Learned:** +* ๐Ÿ”— **Transitive dependencies are risky** (dependencies you don't know about) +* ๐Ÿ“ฆ **Package registries are single points of failure** +* ๐Ÿ›ก๏ธ **Dependency pinning is critical** (lockfiles!) +* ๐Ÿข **Consider vendoring** critical dependencies +* ๐ŸŽฏ **SBOM would have helped** - at least you'd know leftpad existed! + +**Fun Facts:** +* ๐Ÿ“Š leftpad had **millions of downloads per day** +* ๐Ÿ’ป The actual code can be **replaced with a one-liner:** `str.padStart()` +* ๐ŸŽญ npm even created a **leftpad-memorial** page +* ๐Ÿ”’ This incident **directly influenced** modern supply chain security thinking + +**The Code That Broke the Internet:** +```javascript +module.exports = leftpad; +function leftpad (str, len, ch) { + str = String(str); + ch = ch || ' '; + var pad = len - str.length; + return pad > 0 ? new Array(pad + 1).join(ch) + str : str; +} +``` + +**Modern equivalent (2024):** +```javascript +str.padStart(len, ch); // Built into JavaScript now! +``` + +**The tweet that started it all:** +> "I've just unpublished all my modules. kik, npm and bob are shit and I don't want to work with any of them." - @azerbike + +**And the world learned:** Even 11 lines of code can be critical infrastructure. ๐ŸŽฏ + +--- + +๐Ÿ”— **Resources for Group 1:** +* [SolarWinds Report (CISA)](https://www.cisa.gov/uscert/ncas/alerts/aa20-352a) +* [Log4Shell Explained](https://www.lunasec.io/docs/blog/log4j-zero-day/) +* [SLSA Framework](https://slsa.dev/) +* [NIST SSDF](https://csrc.nist.gov/Projects/ssdf) +* [CISA SBOM Resources](https://www.cisa.gov/sbom) +* [Leftpad Incident Timeline](https://qz.com/646467/how-one-programmer-broke-the-internet-by-deleting-a-tiny-piece-of-code) + +--- +## ๐Ÿ“‚ Group 2: Advanced Dependency Analysis + +## ๐Ÿ“ Slide 6 โ€“ ๐Ÿ” Software Composition Analysis (SCA) Deep Dive + +* ๐Ÿ” **SCA (Software Composition Analysis)** = automated scanning of third-party components +* ๐Ÿ“Š **Reality:** 80-90% of your code is from dependencies (not written by you) +* ๐ŸŽฏ **Purpose:** Identify vulnerabilities, licenses, and risks in dependencies +* ๐Ÿ”‘ **Three analysis methods:** + * ๐Ÿ“‹ **Manifest parsing** โ†’ reads package.json, requirements.txt, pom.xml + * ๐Ÿ”’ **Lockfile analysis** โ†’ most accurate, includes transitive dependencies + * ๐Ÿ”ข **Binary fingerprinting** โ†’ hash-based matching for compiled artifacts +* โšก **Modern feature:** Reachability analysis (is vulnerable code actually used?) +* ๐Ÿ”— **Learn more:** [OWASP Dependency-Check](https://owasp.org/www-project-dependency-check/), [Snyk SCA](https://snyk.io/product/open-source-security-management/) + +```mermaid +flowchart LR + App[๐Ÿ“ฆ Your Application] --> SCA[๐Ÿ” SCA Tool] + SCA --> Direct[๐Ÿ“‹ Direct
Dependencies] + SCA --> Transitive[๐Ÿ”— Transitive
Dependencies] + + Direct --> Results[๐Ÿ“Š Analysis Results] + Transitive --> Results + + Results --> Vulns[๐Ÿšจ Vulnerabilities] + Results --> Licenses[โš–๏ธ License Risks] + Results --> Outdated[โฐ Outdated Packages] + + style SCA fill:#e3f2fd,stroke:#1976d2,stroke-width:3px,color:#2c3e50 + style Vulns fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 +``` + +--- + +### ๐Ÿ”— Direct vs Transitive Dependencies + +* ๐Ÿ“ฆ **Direct:** Dependencies you explicitly declare in manifest +* ๐Ÿ”— **Transitive:** Dependencies of your dependencies (hidden from you) +* ๐Ÿ“Š **Reality check:** 1 direct dependency = 7-10 transitive dependencies on average +* ๐ŸŽฏ **Problem:** Most vulnerabilities hide in transitive dependencies +* โš ๏ธ **Risk:** You didn't choose them, review them, or know they exist + +```mermaid +flowchart LR + You[๐Ÿ‘จโ€๐Ÿ’ป Your Code] --> Express[๐Ÿ“ฆ express
Direct] + Express --> BodyParser[๐Ÿ“ฆ body-parser
Transitive] + Express --> Cookie[๐Ÿ“ฆ cookie
Transitive] + BodyParser --> QS[๐Ÿ“ฆ qs
Transitive] + QS --> SafeBuffer[๐Ÿ“ฆ safe-buffer
Transitive] + + Vuln[๐Ÿšจ Vulnerability] -.->|Hidden in| SafeBuffer + + style You fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + style Vuln fill:#ffebee,stroke:#d32f2f,stroke-width:3px,color:#2c3e50 +``` + +--- + +### โšก Reachability Analysis (Advanced) + +* ๐ŸŽฏ **Problem:** Not all vulnerabilities are exploitable in your code +* ๐Ÿ”‘ **Question:** Does your code actually call the vulnerable function? +* ๐Ÿ“Š **Impact:** Reduces false positives by 70%+ +* โœ… **Benefit:** Focus on real risks, not theoretical ones +* ๐Ÿ› ๏ธ **Tools with reachability:** Snyk, GitHub CodeQL (limited), Qwiet AI + +```mermaid +flowchart LR + Vuln[๐Ÿšจ Vulnerable Function
lodash.template] --> Check{๐Ÿค” Called by your code?} + Check -->|โœ… Yes| Exploitable[๐Ÿ’ฅ HIGH PRIORITY
Actually exploitable] + Check -->|โŒ No| Safe[โœ… Low Priority
Not reachable] + + style Vuln fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + style Exploitable fill:#b71c1c,stroke:#d32f2f,stroke-width:3px,color:#fff + style Safe fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 +``` + +
+๐Ÿ’ญ Discussion: Why don't all tools have reachability analysis? + +**Challenges:** + +* ๐Ÿ”ฌ **Technically complex:** Requires static code analysis + dataflow analysis +* โฐ **Performance:** Slow to compute (minutes vs seconds) +* ๐ŸŽฏ **Accuracy:** Dynamic features (eval, reflection) break analysis +* ๐Ÿ’ฐ **Cost:** Expensive to build and maintain + +**Why it matters:** +* ๐Ÿ“Š Average project: **200+ vulnerabilities detected** +* โšก With reachability: **Only 60 actually exploitable** +* โœ… Security teams can focus on what matters + +**Future:** Reachability analysis becoming standard (AI/ML improvements) +
+ +--- + +## ๐Ÿ“ Slide 7 โ€“ ๐Ÿ—‚๏ธ Vulnerability Databases & Tracking + +* ๐ŸŒ **Multiple databases** track vulnerabilities (not just one source) +* ๐Ÿ”‘ **Each database has different coverage and timing** +* ๐Ÿ“Š **Aggregation is key:** Use tools that combine multiple sources + +```mermaid +flowchart LR + subgraph "๐ŸŒ Vulnerability Sources" + CVE[๐Ÿ”ข CVE
MITRE] + NVD[๐Ÿ“Š NVD
NIST] + GitHub[๐Ÿ™ GitHub
Advisory] + OSV[๐ŸŒ OSV
Google] + end + + CVE --> Tools[๐Ÿ› ๏ธ SCA Tools] + NVD --> Tools + GitHub --> Tools + OSV --> Tools + + Tools --> You[๐Ÿ‘จโ€๐Ÿ’ป Developers] + + style Tools fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 +``` + +--- + +### ๐Ÿ”ข CVE (Common Vulnerabilities and Exposures) + +* ๐Ÿ›๏ธ **Managed by:** MITRE Corporation (US DHS funded) +* ๐Ÿ“… **Created:** 1999 (25+ years old!) +* ๐ŸŽฏ **Purpose:** Standardized vulnerability identifiers +* ๐Ÿ“‹ **Format:** CVE-YEAR-NUMBER (e.g., CVE-2021-44228 = Log4Shell) +* ๐Ÿ“Š **Scale:** 200,000+ CVEs, ~25,000 new/year +* ๐Ÿ”— **Database:** [cve.mitre.org](https://cve.mitre.org/) + +--- + +### ๐Ÿ“Š NVD (National Vulnerability Database) + +* ๐Ÿ›๏ธ **Managed by:** US NIST +* ๐ŸŽฏ **Built on:** CVE data + enrichment +* ๐Ÿ“Š **Adds:** + * **CVSS scores** (severity 0-10) + * **CPE** (affected product identifiers) + * **CWE** (weakness categories) + * **Patches and workarounds** +* ๐Ÿ”— **Database:** [nvd.nist.gov](https://nvd.nist.gov/) + +--- + +### ๐Ÿ™ GitHub Advisory Database + +* ๐Ÿ›๏ธ **Managed by:** GitHub (Microsoft) +* ๐ŸŽฏ **Developer-friendly:** Integrated with Dependabot +* ๐Ÿ“ฆ **Coverage:** npm, PyPI, Maven, NuGet, RubyGems, Go, Rust +* โœ… **Unique:** Maintainers can publish advisories directly +* ๐Ÿ”” **Automation:** Auto-alerts repository owners +* ๐Ÿ”— **Database:** [github.com/advisories](https://github.com/advisories) + +--- + +### ๐ŸŒ OSV (Open Source Vulnerabilities) + +* ๐Ÿ›๏ธ **Created by:** Google (2021) +* ๐ŸŽฏ **Innovation:** Distributed database, ecosystem-specific IDs +* ๐Ÿ“‹ **IDs:** GHSA-xxxx, RUSTSEC-xxxx, GO-xxxx (not just CVE) +* โšก **Format:** Machine-readable JSON (automation-friendly) +* ๐ŸŒ **Coverage:** Aggregates from multiple sources +* ๐Ÿ”— **Database:** [osv.dev](https://osv.dev/) + +--- + +### ๐Ÿ“Š CVSS Scoring System + +* ๐ŸŽฏ **CVSS (Common Vulnerability Scoring System)** = severity rating 0.0-10.0 +* ๐Ÿ“ˆ **Current versions:** v3.1 (standard), v4.0 (new, more nuanced) + +| Score | Severity | Priority | SLA | +|-------|----------|----------|-----| +| 9.0-10.0 | ๐Ÿ”ด **Critical** | Fix immediately | 24 hours | +| 7.0-8.9 | ๐ŸŸ  **High** | Fix urgently | 7 days | +| 4.0-6.9 | ๐ŸŸก **Medium** | Fix soon | 30 days | +| 0.1-3.9 | ๐ŸŸข **Low** | Fix eventually | 90 days | + +* ๐Ÿ”— **Calculator:** [first.org/cvss/calculator](https://www.first.org/cvss/calculator/) + +--- + +### โšก EPSS (Exploit Prediction Scoring System) + +* ๐ŸŽฏ **Problem:** CVSS = severity, not likelihood of exploitation +* ๐Ÿ”‘ **EPSS = probability** vulnerability will be exploited in next 30 days +* ๐Ÿ“Š **Score:** 0-100% (e.g., 45% = 45% chance of active exploitation) +* ๐Ÿค– **Uses ML:** Trained on real-world exploitation data +* ๐Ÿ’ก **Prioritization:** Combine CVSS + EPSS for smarter risk assessment +* ๐Ÿ”— **Database:** [first.org/epss](https://www.first.org/epss/) + +**Example:** +* CVE-2021-44228 (Log4Shell): CVSS 10.0 + EPSS 97% โ†’ **DROP EVERYTHING, PATCH NOW** +* CVE-2023-12345: CVSS 9.8 + EPSS 0.3% โ†’ High severity but rarely exploited โ†’ lower priority + +--- + +### ๐Ÿšจ CISA KEV (Known Exploited Vulnerabilities) + +* ๐Ÿ›๏ธ **Managed by:** CISA (US Cybersecurity Agency) +* ๐ŸŽฏ **Purpose:** Catalog of vulnerabilities **actively exploited in the wild** +* ๐Ÿ”ฅ **Rule:** If it's in KEV โ†’ patch within 48 hours (US federal mandate) +* ๐Ÿ“Š **Size:** 1,000+ actively exploited vulnerabilities +* โš ๏ธ **Reality:** These are the ones attackers are using RIGHT NOW +* ๐Ÿ”— **Catalog:** [cisa.gov/known-exploited-vulnerabilities](https://www.cisa.gov/known-exploited-vulnerabilities-catalog) + +**Prioritization Framework:** +1. ๐Ÿ”ฅ **In KEV + High CVSS** โ†’ Immediate (drop everything) +2. ๐ŸŸ  **High CVSS + High EPSS** โ†’ This week +3. ๐ŸŸก **High CVSS + Low EPSS** โ†’ This month +4. ๐ŸŸข **Low CVSS** โ†’ When convenient + +
+๐Ÿ’ญ Reality Check: How to prioritize 500 daily alerts? + +**The Problem:** +* ๐Ÿ“Š Average enterprise scans: **500+ vulnerabilities/day** +* ๐Ÿ‘ฅ Security team capacity: **~10 fixes/day** +* โ“ Which ones matter? + +**Smart Prioritization:** + +1. **๐Ÿ”ฅ Filter by KEV** โ†’ Top priority (actively exploited) +2. **โšก Check reachability** โ†’ Unreachable = deprioritize +3. **๐Ÿ“Š Combine CVSS + EPSS** โ†’ High + High = urgent +4. **๐ŸŒ Business context** โ†’ Internet-facing > internal tools +5. **๐Ÿ”ง Patch availability** โ†’ Available patch = fix now + +**Reality:** You'll never fix everything. Focus on what attackers exploit. +
+ +--- + +## ๐Ÿ“ Slide 8 โ€“ ๐Ÿ› ๏ธ Dependency Management Best Practices + +### ๐Ÿ”’ Lockfiles Are Mission-Critical + +* ๐Ÿ“‹ **Lockfile purpose:** Pin exact versions of ALL dependencies (transitive included) +* ๐ŸŽฏ **Security benefit:** Reproducible builds prevent supply chain attacks +* โœ… **Golden rule:** Always commit lockfiles to Git +* โš ๏ธ **Without lockfiles:** Different builds get different dependencies (dangerous!) + +```mermaid +flowchart LR + NoLock[โŒ No Lockfile] --> Random[๐ŸŽฒ Random Versions
Each Install] + Random --> Risk[๐Ÿ’ฅ Supply Chain Risk] + + Lock[โœ… Lockfile] --> Exact[๐Ÿ“Œ Exact Versions
Every Time] + Exact --> Safe[๐Ÿ›ก๏ธ Reproducible Builds] + + style NoLock fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + style Lock fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + style Risk fill:#b71c1c,stroke:#d32f2f,stroke-width:3px,color:#fff +``` + +**Lockfiles by ecosystem:** +* ๐Ÿ“ฆ **npm:** package-lock.json, yarn.lock, pnpm-lock.yaml +* ๐Ÿ **Python:** Pipfile.lock, poetry.lock +* โ˜• **Maven:** Effectively pom.xml with exact versions +* ๐Ÿน **Go:** go.sum (cryptographic checksums) +* ๐Ÿ’Ž **Ruby:** Gemfile.lock +* ๐Ÿฆ€ **Rust:** Cargo.lock + +--- + +### ๐Ÿ“Š Semantic Versioning Strategy + +* ๐Ÿ“‹ **SemVer:** MAJOR.MINOR.PATCH (e.g., 4.18.2) +* ๐ŸŽฏ **Version range strategies:** + +| Range | Updates | Risk Level | Use Case | +|-------|---------|------------|----------| +| `4.18.2` | None (exact) | โœ… Lowest | Production (with lockfile) | +| `~4.18.2` | Patch only (4.18.x) | ๐ŸŸข Low | Conservative | +| `^4.18.2` | Minor + Patch (4.x) | ๐ŸŸก Medium | Common default | +| `*` | Any version | ๐Ÿ”ด **NEVER** | None | + +* ๐Ÿ”’ **Best practice:** Use `^` in manifest + lockfile for safety + +--- + +### ๐Ÿค– Automated Dependency Updates + +* ๐Ÿ”„ **Tools:** GitHub Dependabot, Renovate Bot, Snyk +* ๐ŸŽฏ **Purpose:** Auto-create PRs for dependency updates +* โœ… **Benefits:** + * Security patches applied automatically + * Avoid "big bang" updates (update incrementally) + * Reduce technical debt +* โš ๏ธ **Requirements:** + * Good test coverage (catch breaking changes) + * CI/CD automation (verify updates work) + * Review process (not blindly merge) + +```mermaid +flowchart LR + Bot[๐Ÿค– Dependabot] -->|New version| PR[๐Ÿ“ Auto PR] + PR --> CI[๐Ÿ”„ Run Tests] + CI -->|โœ… Pass| Review[๐Ÿ‘€ Review] + CI -->|โŒ Fail| Close[๐Ÿšซ Close PR] + Review -->|โœ… Approve| Merge[โœ… Auto-merge] + + style Bot fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + style Merge fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 +``` + +--- + +### ๐Ÿข Private Package Registries + +* ๐ŸŽฏ **Purpose:** Host internal packages + mirror public registries +* ๐Ÿ›ก๏ธ **Security benefits:** + * Control what enters your environment (pre-scan packages) + * Prevent dependency confusion attacks + * Survive public registry outages (availability) + * Audit and logging (who installed what) +* ๐Ÿ› ๏ธ **Popular solutions:** + * **JFrog Artifactory** (enterprise, $$$) + * **Sonatype Nexus** (enterprise, $$$) + * **GitHub Packages** (integrated with GitHub) + * **Verdaccio** (open-source npm proxy, free) +* ๐Ÿ”— **Learn more:** [JFrog Artifactory](https://jfrog.com/artifactory/), [Verdaccio](https://verdaccio.org/) + +--- + +### ๐Ÿ—‚๏ธ Minimal Dependencies Philosophy + +* ๐ŸŽฏ **Principle:** Every dependency = potential vulnerability โ†’ minimize them +* ๐Ÿ“Š **Reality:** + * Average npm package: **86 dependencies** + * Average Java project: **150+ dependencies** +* ๐Ÿ”‘ **Strategies:** + * โ“ Question every new dependency (do you REALLY need it?) + * ๐Ÿ“š Use standard library instead (native JavaScript vs lodash) + * ๐ŸŽฏ Import only what you need (tree shaking) + * ๐Ÿงน Regular audits (remove unused dependencies) + +**Example:** Do you need a package for this? +* โŒ **leftpad** (11 lines) โ†’ โœ… Use `str.padStart()` +* โŒ **is-array** โ†’ โœ… Use `Array.isArray()` +* โŒ **is-number** โ†’ โœ… Use `typeof x === 'number'` + +--- + +### ๐Ÿ“ฆ Vendoring vs Lockfiles + +* ๐Ÿ“ฆ **Vendoring:** Copy dependencies into your repository +* ๐Ÿ”’ **Lockfiles:** Reference dependencies with exact versions + +**Lockfiles (recommended for most):** +* โœ… Smaller repository size +* โœ… Easier updates (change one file) +* โœ… Standard practice +* โŒ Requires registry access + +**Vendoring (specialized use cases):** +* โœ… Complete control +* โœ… Offline builds +* โœ… Immune to registry outages +* โŒ Large repository size +* โŒ Manual update process + +**When to vendor:** +* ๐Ÿ”’ Air-gapped/high-security environments +* ๐Ÿญ Embedded systems (no network) +* ๐Ÿ“ฆ Production deployment artifacts + +
+๐Ÿ’ญ Best Practice: Hybrid approach + +**Modern strategy:** + +* ๐Ÿ“ **Development:** Use lockfiles (fast, convenient) +* ๐Ÿ—๏ธ **CI/CD:** Use lockfiles + caching +* ๐Ÿš€ **Production:** Create vendored artifact (self-contained, no runtime dependencies) + +**Benefits:** +* โšก Fast development +* ๐Ÿ›ก๏ธ Production resilience +* ๐Ÿ“ฆ Best of both worlds + +**Most teams use lockfiles. Only vendor for production if needed.** +
+ +--- + +## ๐Ÿ“ Slide 9 โ€“ ๐Ÿ’ป Hands-On: Advanced SCA Tools + +* ๐Ÿ› ๏ธ **Goal:** Compare multiple SCA tools and understand their strengths +* ๐ŸŽฏ **Defense in depth:** Different tools catch different vulnerabilities +* ๐Ÿ“Š **No single tool is perfect** (use multiple for best coverage) + +### ๐Ÿ”ท Tool Comparison Matrix + +| Tool | Cost | Ecosystems | Speed | Strengths | Weaknesses | +|------|------|------------|-------|-----------|------------| +| ๐Ÿ”ท **Snyk** | Freemium | All major | Fast | Reachability, UX | Paid for teams | +| ๐Ÿฆ… **OWASP Dependency-Check** | Free | Java, .NET, npm, Python | Slow | Comprehensive | False positives | +| โš“ **Grype** | Free | Containers, OS | Very fast | Accurate, fast | Limited app deps | +| ๐Ÿ”ท **Trivy** | Free | Multi-purpose | Very fast | Versatile | Newer tool | +| ๐Ÿ“Š **Dependency-Track** | Free | SBOM-based | N/A | Continuous monitor | Needs SBOM input | +| ๐Ÿ™ **GitHub Dependabot** | Free | npm, PyPI, Maven | Fast | Integrated, auto-fix | GitHub only | + +* ๐Ÿ”— **Resources:** [Snyk](https://snyk.io/), [OWASP DC](https://owasp.org/www-project-dependency-check/), [Grype](https://github.com/anchore/grype), [Trivy](https://trivy.dev/), [Dependency-Track](https://dependencytrack.org/) + +--- + +### ๐Ÿ”ท Snyk: Developer-First SCA + +* ๐ŸŽฏ **Focus:** Developer experience + actionable results +* โœ… **Unique features:** + * Reachability analysis (reduce false positives 70%) + * Auto-fix PRs with tested upgrades + * IDE integration (VS Code, IntelliJ) + * Container + IaC scanning included +* ๐Ÿ’ฐ **Pricing:** Free for individuals, paid for teams +* ๐Ÿ”— **Website:** [snyk.io](https://snyk.io/) + +--- + +### ๐Ÿฆ… OWASP Dependency-Check + +* ๐Ÿ›๏ธ **Created by:** OWASP (2012) +* ๐Ÿ†“ **Completely free and open-source** +* ๐Ÿ“Š **Coverage:** Java (excellent), .NET, npm, Python, Ruby, Go +* ๐Ÿ—„๏ธ **Database:** NVD, npm audit, OSS Index, RetireJS +* โš ๏ธ **Trade-off:** Slower but more comprehensive +* ๐Ÿ”— **GitHub:** [github.com/jeremylong/DependencyCheck](https://github.com/jeremylong/DependencyCheck) + +--- + +### โš“ Grype: Fast Container & Filesystem Scanner + +* ๐Ÿ›๏ธ **Created by:** Anchore (2020) +* ๐Ÿ†“ **Open-source, free** +* ๐ŸŽฏ **Focus:** Container images, filesystems, **SBOMs** +* โšก **Speed:** Very fast (local database) +* ๐Ÿ“‹ **SBOM support:** Can scan SBOMs directly (perfect for Lab 4 integration!) +* ๐Ÿ”— **GitHub:** [github.com/anchore/grype](https://github.com/anchore/grype) + +--- + +### ๐Ÿ”ท Trivy: Multi-Purpose Scanner + +* ๐Ÿ›๏ธ **Created by:** Aqua Security (2019) +* ๐Ÿ†“ **Open-source, free** +* ๐ŸŽฏ **Scans:** Containers, filesystems, Git repos, IaC, Kubernetes, SBOMs +* โšก **Speed:** Extremely fast +* ๐ŸŒ **Versatility:** One tool for multiple use cases +* ๐Ÿ”— **GitHub:** [github.com/aquasecurity/trivy](https://github.com/aquasecurity/trivy) + +--- + +### ๐Ÿ“Š Dependency-Track: Continuous SBOM Monitoring + +* ๐ŸŽฏ **Purpose:** Continuous monitoring platform for component risks +* ๐Ÿ“‹ **Input:** Consumes SBOMs (SPDX, CycloneDX) +* ๐Ÿ”„ **Workflow:** Upload SBOM โ†’ Continuous scanning โ†’ Risk scoring โ†’ Alerts +* ๐Ÿ“Š **Features:** + * Portfolio view (all applications in one dashboard) + * Policy engine (block deployments with violations) + * Risk trending over time + * Notifications (Slack, email, webhooks) +* ๐Ÿ†“ **Cost:** Open-source, free +* ๐Ÿ”— **Website:** [dependencytrack.org](https://dependencytrack.org/) + +```mermaid +flowchart LR + CI[๐Ÿ”„ CI/CD] -->|Upload SBOM| DT[๐Ÿ“Š Dependency-Track] + DT -->|Scan against| DB1[๐Ÿ—„๏ธ NVD] + DT -->|Scan against| DB2[๐Ÿ—„๏ธ OSV] + DT -->|Calculate| Risk[๐Ÿ“Š Risk Score] + Risk --> Policy{๐Ÿ›ก๏ธ Policy Check} + Policy -->|โœ… Pass| Deploy[๐Ÿš€ Deploy] + Policy -->|โŒ Fail| Block[๐Ÿšซ Block + Alert] + + style DT fill:#e3f2fd,stroke:#1976d2,stroke-width:3px,color:#2c3e50 + style Deploy fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + style Block fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 +``` + +--- + +### ๐Ÿ›ก๏ธ Defense in Depth: Use Multiple Tools + +* ๐ŸŽฏ **Why multiple tools?** + * Different vulnerability databases (Snyk proprietary vs NVD vs OSV) + * Different matching algorithms (fewer false negatives) + * Different strengths (Grype for containers, Snyk for apps) +* ๐Ÿ“Š **Reality:** Each tool finds ~80% of vulnerabilities (different 80%!) +* โœ… **Together:** 95%+ coverage + +**Recommended combinations:** +* ๐Ÿ†“ **Free stack:** Grype + Trivy + GitHub Dependabot +* ๐Ÿ’ฐ **Paid:** Snyk (primary) + Grype (containers) +* ๐Ÿข **Enterprise:** Snyk + Dependency-Track (continuous monitoring) + +
+๐Ÿ’ญ Pro Tip: How to integrate multiple tools? + +**CI/CD Strategy:** + +1. **โšก Fast scans in PR:** + * Snyk or Grype (5-10 seconds) + * Fail build on critical/high + +2. **๐Ÿ“Š Comprehensive scans in CI:** + * OWASP Dependency-Check (minutes) + * Trivy (all-in-one) + * Upload results to Dependency-Track + +3. **๐Ÿ”„ Continuous monitoring:** + * Dependency-Track (SBOM-based) + * Daily/weekly rescans + * Alert on new CVEs + +4. **๐Ÿค– Automated updates:** + * Dependabot or Renovate + * Auto-fix PRs + +**Don't rely on just one tool!** +
+ +--- + +## ๐ŸŽ‰ Fun Break: "The Great npm Registry Outage (2021)" + +### ๐Ÿ˜ฑ When JavaScript Stopped Working Globally + +**March 2021: The Day the Internet Forgot How to JavaScript** + +* ๐ŸŒ **npm registry** = single point of failure for JavaScript +* ๐Ÿ“Š **Scale:** 13 billion packages downloaded per week +* โšก **Outage:** 4 hours offline +* ๐Ÿ’ฅ **Impact:** Every CI/CD pipeline failed globally + +```mermaid +flowchart LR + NPM[โ˜๏ธ npm Registry] -.->|๐Ÿ’ฅ OFFLINE| X[โŒ Down] + + Dev[๐Ÿ‘จโ€๐Ÿ’ป Developers] --> NPM + CI[๐Ÿ”„ CI/CD] --> NPM + Deploy[๐Ÿš€ Deployments] --> NPM + + X -.->|โŒ| Dev + X -.->|โŒ| CI + X -.->|โŒ| Deploy + + style NPM fill:#ffebee,stroke:#d32f2f,stroke-width:3px,color:#2c3e50 + style X fill:#b71c1c,stroke:#d32f2f,stroke-width:3px,color:#fff +``` + +**The Chaos:** +* ๐Ÿ˜ฑ Developers couldn't install anything +* ๐Ÿ”ฅ All builds failed worldwide +* ๐Ÿฆ Twitter exploded: "Is npm down or is it just me?" +* โ˜• Productivity increased (couldn't install packages, had to write code) + +**The Tweets:** +* "npm is down. Productivity is up. Coincidence?" +* "Breaking: Millions of developers suddenly productive" +* "Just a reminder that the entire JavaScript ecosystem depends on a single server not having a bad day" + +**Lessons Learned:** +* ๐Ÿข **Private registries** โ†’ Business continuity +* ๐Ÿ“ฆ **Lockfiles + caching** โ†’ Survive outages +* ๐Ÿ”„ **Registry mirrors** โ†’ Redundancy +* ๐ŸŽฏ **Dependency registries = critical infrastructure** + +**Fun Fact:** Stack Overflow traffic increased 300% during outage + +--- + +๐Ÿ”— **Resources for Group 2:** +* [Snyk Documentation](https://docs.snyk.io/) +* [OWASP Dependency-Check](https://owasp.org/www-project-dependency-check/) +* [Grype GitHub](https://github.com/anchore/grype) +* [Trivy Documentation](https://trivy.dev/) +* [Dependency-Track](https://dependencytrack.org/) +* [CVSS Calculator](https://www.first.org/cvss/calculator/) +* [EPSS Scores](https://www.first.org/epss/) +* [CISA KEV Catalog](https://www.cisa.gov/known-exploited-vulnerabilities-catalog) + +--- + +## ๐Ÿ“‚ Group 3: SBOM Analysis & Consumption + +## ๐Ÿ“ Slide 10 โ€“ ๐Ÿ“‹ SBOM Formats: SPDX vs CycloneDX Deep Dive + +* ๐Ÿ“‹ **Lab 4 recap:** You generated SBOMs โ†’ **Now learn to consume them** +* ๐Ÿ”„ **Two standards:** SPDX (license focus) vs CycloneDX (security focus) +* ๐ŸŽฏ **Both are valid** โ†’ Choose based on use case (or support both) + +```mermaid +flowchart LR + SPDX[๐Ÿ“œ SPDX
Linux Foundation] --> Legal[โš–๏ธ License Compliance
ISO Standard] + CDX[๐Ÿ”„ CycloneDX
OWASP] --> Security[๐Ÿ›ก๏ธ Vulnerability Tracking
DevSecOps] + + style SPDX fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + style CDX fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 +``` + +--- + +### ๐Ÿ“Š Format Comparison + +| Feature | SPDX | CycloneDX | +|---------|------|-----------| +| ๐Ÿ“… **Created** | 2010 (14 years) | 2017 (7 years) | +| ๐Ÿ›๏ธ **Owner** | Linux Foundation | OWASP | +| ๐ŸŽฏ **Focus** | Legal/License | Security/Supply Chain | +| โœ… **Status** | ISO/IEC 5962:2021 | ECMA (pending) | +| ๐Ÿ“Š **Formats** | JSON, YAML, XML, RDF, Tag-Value | JSON, XML, Protobuf | +| ๐Ÿ” **Vulnerabilities** | External references | Native fields | +| ๐Ÿ”— **Services** | Limited | First-class support | +| โšก **Performance** | Slower (complex) | Faster (lightweight) | +| ๐Ÿข **Best For** | Government, Legal | Security tools, CI/CD | + +* ๐Ÿ”— **Specs:** [spdx.dev](https://spdx.dev/), [cyclonedx.org](https://cyclonedx.org/) + +--- + +### ๐Ÿ”‘ When to Use Which + +**Use SPDX if:** +* โš–๏ธ License compliance is priority +* ๐Ÿ›๏ธ Government/regulatory requirements (NTIA, EU) +* ๐Ÿ“ฆ File-level granularity needed +* ๐Ÿค Cross-organization standardization + +**Use CycloneDX if:** +* ๐Ÿ›ก๏ธ Security is primary focus +* ๐Ÿ”„ Continuous vulnerability monitoring +* โšก Performance matters (CI/CD) +* ๐ŸŽฏ DevSecOps workflows + +**Best practice:** Generate both formats (most tools support it) + +
+๐Ÿ’ญ Can you convert between formats? + +**Yes, but with limitations:** + +* โœ… **SPDX โ†’ CycloneDX:** Community tools available +* โš ๏ธ **CycloneDX โ†’ SPDX:** Lossy conversion (some fields don't map) +* ๐Ÿ› ๏ธ **Best approach:** Generate both from source + +**Most SBOM tools (Syft, Trivy) can output both formats natively.** +
+ +--- + +## ๐Ÿ“ Slide 11 โ€“ ๐Ÿ”Ž SBOM Consumption & Auditing + +* ๐ŸŽฏ **Problem:** SBOMs are useless unless analyzed and acted upon +* ๐Ÿ“Š **SBOM lifecycle:** Generate (Lab 4) โ†’ **Analyze (This lab)** โ†’ Act โ†’ Monitor + +```mermaid +flowchart LR + Lab4[๐Ÿ—๏ธ Generate
Lab 4] --> Analyze[๐Ÿ” Analyze
Find Risks] + Analyze --> Vulnerabilities[๐Ÿšจ Vulnerabilities] + Analyze --> Licenses[โš–๏ธ Licenses] + Analyze --> Risks[๐Ÿ“Š Component Risks] + + Vulnerabilities --> Act[โšก Take Action] + Licenses --> Act + Risks --> Act + + Act --> Monitor[๐Ÿ“ˆ Continuous
Monitoring] + Monitor -.->|New CVE| Analyze + + style Lab4 fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + style Analyze fill:#e3f2fd,stroke:#1976d2,stroke-width:3px,color:#2c3e50 +``` + +--- + +### ๐Ÿšจ Identifying Risky Components + +**Red flags in SBOMs:** + +1. **โฐ Outdated packages:** + * Last updated > 2 years ago + * No active maintenance + +2. **๐Ÿ‘ฅ Single maintainer:** + * "Bus factor" = 1 + * Account takeover risk + +3. **๐Ÿ“‰ Low popularity:** + * < 100 downloads/week + * Small community + +4. **๐Ÿ”“ Known vulnerabilities:** + * CVEs in external references + * High CVSS scores + +5. **โš–๏ธ License risks:** + * AGPL, GPL (copyleft) + * Unknown/missing licenses + +6. **๐Ÿ†• New packages:** + * < 6 months old (not battle-tested) + * Potential typosquatting + +--- + +### ๐Ÿ“Š Component Pedigree Tracking + +* ๐Ÿ”Ž **Pedigree** = origin and history of component +* ๐ŸŽฏ **Key questions:** + * Who created it? + * Where did it come from? + * Has it been modified? + * Can we verify authenticity? + +**SBOM fields for verification:** +* **Supplier:** Who provides the component +* **Download location:** Where obtained +* **Hashes:** Verify integrity (SHA-256) +* **External references:** Source repo, advisories + +--- + +### ๐Ÿ” SBOM Validation Tools + +* ๐Ÿ“‹ **NTIA minimum elements:** 7 required fields +* โœ… **Validation tools:** + * SPDX validation tools + * CycloneDX CLI validator + * NTIA conformance checker + +**Quality levels:** +* **Basic (40%):** NTIA minimum elements +* **Good (70%):** + licenses, hashes, references +* **Excellent (90%):** + complete dependency graph, vulnerabilities +* **Perfect (100%):** + signed, attested, continuously updated + +--- + +## ๐Ÿ“ Slide 12 โ€“ ๐Ÿ“Š SBOM Diff Analysis & Change Tracking + +* ๐Ÿ”„ **Purpose:** Track dependency changes over time +* ๐ŸŽฏ **Use cases:** + * Detect new vulnerabilities after updates + * Audit supply chain changes + * Drift detection (production vs source) + +```mermaid +flowchart LR + V1[๐Ÿ“‹ SBOM v1.0] --> Diff{๐Ÿ” Diff} + V2[๐Ÿ“‹ SBOM v2.0] --> Diff + + Diff --> Added[โž• Added: 7] + Diff --> Removed[โž– Removed: 2] + Diff --> Updated[๐Ÿ”„ Updated: 15] + + Added -.->|Check| Risks[๐Ÿšจ New Risks?] + Updated -.->|Check| Fixed[โœ… Fixes?] + + style Diff fill:#e3f2fd,stroke:#1976d2,stroke-width:3px,color:#2c3e50 + style Risks fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 +``` + +--- + +### ๐Ÿ” What to Analyze in Diffs + +**โž• Added components:** +* Expected new features? +* Known vulnerabilities? +* Compatible licenses? + +**โž– Removed components:** +* Actually removed from code? +* Vulnerabilities addressed? + +**๐Ÿ”„ Updated components:** +* Security patches applied? +* Breaking changes? +* New transitive dependencies? + +**โš ๏ธ Changed metadata:** +* Supplier changed? (ownership transfer risk) +* Download location changed? (supply chain risk) + +--- + +### ๐Ÿ“Š Drift Detection + +* ๐ŸŽฏ **Drift** = difference between expected SBOM and actual runtime +* ๐Ÿ”ฅ **Causes:** + * Manual production changes + * Compromised deployment + * SBOM generation bugs + +```mermaid +flowchart LR + Expected[๐Ÿ“‹ Expected
From CI/CD] --> Compare{๐Ÿ” Compare} + Actual[โšก Runtime
Production] --> Compare + + Compare -->|Match| Good[โœ… No Drift] + Compare -->|Mismatch| Drift[๐Ÿšจ INVESTIGATE] + + style Expected fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + style Drift fill:#ffebee,stroke:#d32f2f,stroke-width:3px,color:#2c3e50 +``` + +--- + +### ๐Ÿ“ˆ Continuous SBOM Monitoring + +* ๐Ÿ”„ **Track metrics over time:** + * Total components (trend) + * Known vulnerabilities (improving?) + * License violations + * Average component age + * Dependency depth + +* ๐Ÿ› ๏ธ **Tool:** Dependency-Track (dashboards, alerts, trends) + +
+๐Ÿ’ญ When to regenerate SBOMs? + +**Regenerate on:** + +1. โœ… **Every build** (CI/CD - best practice) +2. โœ… **Every release** (minimum requirement) +3. โœ… **Dependency updates** (compare before/after) +4. โœ… **Daily/weekly** (catch new CVEs) +5. โœ… **Security incidents** (audit deployed state) + +**Store SBOMs alongside artifacts (container registry, S3).** +
+ +--- + +## ๐Ÿ“ Slide 13 โ€“ ๐Ÿ’ป Hands-On: SBOM-Driven Vulnerability Analysis + +* ๐ŸŽฏ **Goal:** Use Lab 4 SBOMs to find and fix vulnerabilities +* ๐Ÿ”ง **Tools:** Grype, Dependency-Track +* ๐Ÿ“Š **Workflow:** SBOM โ†’ Scan โ†’ Prioritize โ†’ Fix โ†’ Verify + +```mermaid +flowchart LR + Lab4[๐Ÿ“‹ Lab 4 SBOM] --> Grype[โš“ Grype Scan] + Grype --> Report[๐Ÿ“Š Vulnerability Report] + Report --> Prioritize[๐ŸŽฏ Prioritize by CVSS/EPSS] + Prioritize --> Fix[๐Ÿ”ง Update Dependencies] + Fix --> Verify[โœ… Rescan & Verify] + + style Lab4 fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + style Grype fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 +``` + +--- + +### โš“ Task 1: Scan SBOM with Grype + +* ๐Ÿ“ฆ **Input:** SBOM from Lab 4 (CycloneDX or SPDX) +* ๐Ÿ” **Scan:** `grype sbom:sbom.cdx.json` +* ๐Ÿ“Š **Output:** Table of vulnerabilities (name, version, CVE, severity) + +--- + +### ๐Ÿ“Š Task 2: Set Up Dependency-Track + +* ๐Ÿณ **Deploy:** Docker Compose (API server + frontend) +* ๐Ÿ“ค **Upload:** SBOM via UI or API +* ๐Ÿ“ˆ **Dashboard:** View risk score, vulnerabilities, policy violations +* ๐Ÿ”” **Alerts:** Configure Slack/email notifications + +--- + +### ๐ŸŽฏ Task 3: Compare Multiple Tools + +* ๐Ÿ” **Run:** Grype + Trivy + OWASP Dependency-Check +* ๐Ÿ“Š **Compare:** Different tools find different vulnerabilities +* ๐ŸŽฏ **Why?** Different databases, algorithms, coverage +* โœ… **Defense in depth:** Use multiple tools + +--- + +### ๐Ÿ”ง Task 4: Create Fix PR + +* ๐Ÿ“ **Branch:** `security/fix-sbom-vulnerabilities` +* ๐Ÿ”„ **Update:** Dependencies to patched versions +* ๐Ÿ“‹ **Regenerate:** SBOM after fixes +* โœ… **Verify:** Rescan shows reduced vulnerabilities +* ๐Ÿ“ค **Submit:** PR with before/after comparison + +--- + +### ๐Ÿšจ Task 5: Policy Enforcement + +* ๐Ÿ“‹ **Create policy:** Block Critical/High vulnerabilities +* ๐Ÿ›ก๏ธ **Enforce:** Fail CI/CD if policy violated +* ๐Ÿ”” **Alert:** Notify security team +* ๐Ÿ“Š **Track:** Policy compliance metrics + +--- + +## ๐Ÿ’ญ Interactive Challenge: "SBOM Detective" + +**Scenario:** Which SBOM has highest risk? + +**SBOM A:** react 18.2.0, express 4.18.2, lodash 4.17.21, axios 1.6.0 + +**SBOM B:** moment 2.29.4, request 2.88.2, lodash 4.17.19, colors 1.4.0 + +**SBOM C:** left-pad 1.3.0, is-array 1.0.1, is-number 7.0.0, pad-left 2.1.0 + +
+๐Ÿ” Click for answer + +**SBOM B = HIGHEST RISK** ๐Ÿšจ + +* moment 2.29.4 โ†’ โš ๏ธ DEPRECATED +* request 2.88.2 โ†’ โš ๏ธ DEPRECATED (since 2020) +* lodash 4.17.19 โ†’ ๐Ÿ”ด CVE-2020-8203, CVE-2021-23337 (High) +* colors 1.4.0 โ†’ ๐Ÿ”ด Sabotaged by maintainer (2022) + +**Score: 9/10 - CRITICAL** + +**Lesson:** Old/deprecated packages = high risk! +
+ +--- + +๐Ÿ”— **Resources for Group 3:** +* [SPDX Specification](https://spdx.dev/) +* [CycloneDX Specification](https://cyclonedx.org/) +* [Dependency-Track](https://dependencytrack.org/) +* [Grype](https://github.com/anchore/grype) +* [NTIA SBOM Guide](https://www.ntia.gov/sbom) + +--- + +## ๐Ÿ“‚ Group 4: Artifact Signing & Provenance + +## ๐Ÿ“ Slide 14 โ€“ โœ๏ธ Code Signing & Artifact Integrity + +* โœ๏ธ **Code signing** = cryptographic proof of authenticity and integrity +* ๐ŸŽฏ **Purpose:** Verify artifacts haven't been tampered with +* ๐Ÿ”‘ **Traditional approach:** X.509 certificates + private keys +* โš ๏ธ **Problems with traditional signing:** + * Key management burden (storage, rotation, revocation) + * Long-lived keys = high risk if compromised + * Expensive PKI infrastructure + * Certificate expiration management + +```mermaid +flowchart LR + Build[๐Ÿ—๏ธ Build Artifact] --> Sign[โœ๏ธ Sign with Key] + Sign --> Artifact[๐Ÿ“ฆ Signed Artifact] + Artifact --> Deploy[๐Ÿš€ Deployment] + Deploy --> Verify[๐Ÿ” Verify Signature] + Verify -->|โœ… Valid| Run[โšก Run] + Verify -->|โŒ Invalid| Block[๐Ÿšซ Block] + + style Sign fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + style Run fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + style Block fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 +``` + +--- + +### ๐Ÿ”‘ Why Signing Matters + +* ๐Ÿ›ก๏ธ **Authenticity:** Proves who built the artifact +* ๐Ÿ”’ **Integrity:** Detects tampering (even 1 byte changed) +* ๐Ÿ“œ **Non-repudiation:** Can't deny you signed it +* ๐ŸŽฏ **Trust chain:** Build trust from source to production + +**Without signing:** +* ๐Ÿ’ฅ Attacker replaces artifact in registry โ†’ deployed to production +* ๐Ÿ•ต๏ธ SolarWinds-style build system compromise goes undetected +* โŒ No way to verify artifact authenticity + +--- + +## ๐Ÿ“ Slide 15 โ€“ ๐Ÿ” Sigstore: Modern Signing Revolution + +* ๐Ÿ›๏ธ **Sigstore** = Linux Foundation project (2021) +* ๐ŸŽฏ **Innovation:** Keyless signing + transparency logs +* ๐Ÿ†“ **Public good infrastructure** (free for all) + +### ๐Ÿ”‘ Three Pillars of Sigstore + +```mermaid +flowchart LR + subgraph "๐Ÿ” Sigstore Ecosystem" + Cosign[โœ๏ธ Cosign
Sign & Verify] + Fulcio[๐Ÿ” Fulcio
Certificate Authority] + Rekor[๐Ÿ“œ Rekor
Transparency Log] + end + + Developer[๐Ÿ‘จโ€๐Ÿ’ป Developer] -->|1. Authenticate| Fulcio + Fulcio -->|2. Short-lived cert| Cosign + Cosign -->|3. Sign artifact| Signed[๐Ÿ“ฆ Signed Artifact] + Cosign -->|4. Record in| Rekor + + style Cosign fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + style Fulcio fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + style Rekor fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#2c3e50 +``` + +1. **โœ๏ธ Cosign:** Sign and verify container images, blobs, SBOMs +2. **๐Ÿ” Fulcio:** Free CA issuing short-lived certificates (minutes, not years) +3. **๐Ÿ“œ Rekor:** Transparency log (immutable audit trail) + +--- + +### ๐Ÿ”‘ Keyless Signing Workflow + +* ๐ŸŽฏ **Revolutionary:** No private keys to manage! +* ๐Ÿ” **OIDC authentication:** Use GitHub, Google, Microsoft identity +* โฐ **Short-lived certificates:** Valid for 10 minutes (reduces risk) +* ๐Ÿ“œ **Transparency log:** Immutable proof of signing event + +**How it works:** +1. Developer authenticates via OIDC (GitHub login) +2. Fulcio issues short-lived certificate +3. Cosign signs artifact with certificate +4. Signature recorded in Rekor (public log) +5. Certificate expires, but log entry proves it existed + +**Benefits:** +* โœ… No key storage (nothing to leak!) +* โœ… No key rotation (certs expire automatically) +* โœ… Transparency (all signatures public) +* โœ… Free infrastructure + +--- + +### ๐ŸŒ Industry Adoption + +* ๐Ÿ“ฆ **npm:** All packages signed with Sigstore (2023+) +* ๐Ÿ **PyPI:** Sigstore signing available +* โ˜ธ๏ธ **Kubernetes:** Release artifacts signed +* ๐Ÿ™ **GitHub:** Actions can sign artifacts +* ๐Ÿ’Ž **RubyGems:** Sigstore integration in progress + +* ๐Ÿ”— **Website:** [sigstore.dev](https://www.sigstore.dev/) + +
+๐Ÿ’ญ How is keyless signing secure without keys? + +**Trust model:** + +1. **Identity verification:** OIDC proves who you are (GitHub, Google) +2. **Short-lived certificates:** Compromised cert expires in minutes +3. **Transparency log:** Rekor provides non-repudiation (immutable proof) +4. **Certificate chain:** Fulcio CA is trusted root + +**Security properties:** +* ๐Ÿ” Can't forge signatures (need valid OIDC identity) +* ๐Ÿ“œ Can't backdate signatures (Rekor timestamps are immutable) +* โฐ Can't reuse compromised cert (expires in 10 minutes) + +**Trade-off:** Trust Sigstore infrastructure (but it's open, auditable, and run by Linux Foundation) +
+ +--- + +## ๐Ÿ“ Slide 16 โ€“ ๐Ÿ“œ Provenance & Build Attestations + +* ๐Ÿ“œ **Provenance** = metadata about how artifact was built +* ๐ŸŽฏ **Answers:** Who, what, when, where, how +* ๐Ÿ”‘ **Prevents:** Supply chain attacks via build manipulation + +```mermaid +flowchart LR + Source[๐Ÿ“ Source Code
github.com/user/repo
commit: abc123] --> Build[๐Ÿ—๏ธ Build System
GitHub Actions
builder: ubuntu-22.04] + Build --> Artifact[๐Ÿ“ฆ Artifact
container:v1.0] + + Build -.->|Generates| Provenance[๐Ÿ“œ Provenance
Signed attestation] + Provenance -->|Attached to| Artifact + + Deploy[๐Ÿš€ Deployment] -->|Verifies| Provenance + Deploy -->|If valid| Run[โšก Run] + + style Provenance fill:#f3e5f5,stroke:#7b1fa2,stroke-width:3px,color:#2c3e50 + style Run fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 +``` + +--- + +### ๐Ÿ“Š What's in Provenance? + +**SLSA Provenance format includes:** +* **Builder identity:** Who/what performed the build (GitHub Actions, GitLab CI) +* **Source repository:** Git repo URL + commit SHA +* **Build command:** How artifact was built +* **Build timestamp:** When it was built +* **Build materials:** Dependencies used +* **Signing identity:** Who signed the provenance + +**Purpose:** +* โœ… Verify artifact came from expected source +* โœ… Detect build system compromises +* โœ… Ensure reproducible builds +* โœ… Audit trail for compliance + +--- + +### ๐Ÿ” In-toto Attestations Framework + +* ๐Ÿ“œ **In-toto** = framework for securing software supply chain steps +* ๐ŸŽฏ **Purpose:** Define and verify supply chain steps +* ๐Ÿ“‹ **Attestation types:** + * Build provenance + * SBOM attestation + * Vulnerability scan results + * Code review approval + +* ๐Ÿ”— **Spec:** [in-toto.io](https://in-toto.io/) + +--- + +### ๐Ÿ† Reproducible Builds + +* ๐ŸŽฏ **Goal:** Same source code โ†’ identical binary (bit-for-bit) +* โœ… **Benefit:** Verify binary matches source (no hidden code injection) +* ๐Ÿ”ง **Challenges:** + * Timestamps in builds + * Non-deterministic build tools + * Build environment differences +* ๐ŸŒ **Projects:** Debian, Arch Linux, Bitcoin Core use reproducible builds + +--- + +## ๐Ÿ“ Slide 17 โ€“ ๐Ÿ’ป Hands-On: Signing & Provenance Verification + +* ๐ŸŽฏ **Goal:** Sign container images and generate provenance +* ๐Ÿ”ง **Tools:** Cosign, GitHub Actions +* ๐Ÿ“Š **Workflow:** Build โ†’ Sign โ†’ Attest โ†’ Verify โ†’ Deploy + +```mermaid +flowchart LR + Build[๐Ÿ—๏ธ Build Image] --> Sign[โœ๏ธ Sign with Cosign] + Sign --> Provenance[๐Ÿ“œ Generate Provenance] + Provenance --> SBOM[๐Ÿ“‹ Attach SBOM] + SBOM --> Push[๐Ÿ“ค Push to Registry] + Push --> Deploy[๐Ÿš€ Deployment] + Deploy --> Verify[๐Ÿ” Verify All] + Verify -->|โœ… Valid| Run[โšก Run] + Verify -->|โŒ Invalid| Block[๐Ÿšซ Block] + + style Sign fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + style Verify fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + style Run fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + style Block fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 +``` + +--- + +### โœ๏ธ Task 1: Sign Container Image with Cosign + +* ๐Ÿ” **Keyless signing** via GitHub OIDC +* ๐Ÿ“ฆ **Sign:** Container image +* ๐Ÿ“œ **Transparency:** Recorded in Rekor + +--- + +### ๐Ÿ“œ Task 2: Generate SLSA Provenance + +* ๐Ÿ—๏ธ **Use:** GitHub Actions SLSA generator +* ๐Ÿ“‹ **Generate:** Build provenance attestation +* โœ… **Achieve:** SLSA Level 3 + +--- + +### ๐Ÿ“‹ Task 3: Attach SBOM as Attestation + +* ๐Ÿ“ฆ **Attach:** Lab 4 SBOM to container image +* ๐Ÿ”— **Link:** SBOM + signature + provenance +* ๐ŸŽฏ **Result:** Complete artifact metadata + +--- + +### ๐Ÿ” Task 4: Verify in Deployment + +* ๐Ÿ›ก๏ธ **Policy:** Only deploy signed + attested images +* โ˜ธ๏ธ **Kubernetes:** Use admission controller (Kyverno, OPA Gatekeeper) +* โœ… **Verify:** Signature + provenance before deployment + +--- + +### ๐Ÿš€ Task 5: CI/CD Integration + +* ๐Ÿ”„ **Workflow:** Build โ†’ Scan โ†’ Sign โ†’ Attest โ†’ Push โ†’ Verify โ†’ Deploy +* ๐Ÿค– **Automation:** All steps in GitHub Actions +* ๐Ÿ“Š **Evidence:** Complete audit trail (SBOM, provenance, signatures) + +--- + +## ๐ŸŽ‰ Fun Break: "The XZ Utils Backdoor (2024)" + +### ๐Ÿ•ต๏ธ The Most Sophisticated Supply Chain Attack Ever + +**The Setup:** +* ๐Ÿ“ฆ **xz Utils** = compression library in every Linux distribution +* ๐ŸŽฏ **Target:** SSH authentication via systemd + +**The Attack (2-year social engineering):** +1. **2021:** Attacker creates GitHub account, contributes helpful patches +2. **2022:** Gains trust, becomes regular contributor +3. **2023:** Social engineers way to co-maintainer status +4. **2024:** Injects sophisticated backdoor in build system +5. **Discovery:** Microsoft engineer notices 500ms SSH delay + +```mermaid +flowchart LR + Year1[2021
๐Ÿ‘จโ€๐Ÿ’ป Contributor] --> Year2[2022
๐Ÿค Trusted Member] + Year2 --> Year3[2023
โš™๏ธ Co-Maintainer] + Year3 --> Year4[2024
๐Ÿ’€ Backdoor] + Year4 -.->|Almost| Disaster[๐ŸŒ All Linux
Distributions] + + Discovery[๐Ÿ” Discovery
500ms SSH delay] -.->|Stopped| Year4 + + style Year4 fill:#ffebee,stroke:#d32f2f,stroke-width:3px,color:#2c3e50 + style Disaster fill:#b71c1c,stroke:#d32f2f,stroke-width:3px,color:#fff + style Discovery fill:#e8f5e8,stroke:#388e3c,stroke-width:3px,color:#2c3e50 +``` + +**The Sophistication:** +* ๐ŸŽญ Multi-year social engineering +* ๐Ÿ”ง Hidden in build scripts (not source code!) +* ๐Ÿ•ต๏ธ Only activated for specific SSH configurations +* ๐ŸŒ Nearly compromised all major Linux distros + +**Why it Failed:** +* โšก Pure luck (500ms delay noticed) +* โฐ Discovered before stable release + +**Lessons:** +* ๐Ÿ“œ **Provenance matters** (build system is critical) +* ๐Ÿ” **Build transparency** (know what's in your builds) +* โœ๏ธ **Signing alone isn't enough** (attacker had signing rights!) +* ๐ŸŽฏ **SLSA Level 3+** would have detected this (hermetic builds) + +**The Hero:** Andres Freund (Microsoft engineer) noticed the SSH delay + +--- + +๐Ÿ”— **Resources for Group 4:** +* [Sigstore Documentation](https://docs.sigstore.dev/) +* [Cosign](https://github.com/sigstore/cosign) +* [SLSA Provenance](https://slsa.dev/provenance/) +* [In-toto Framework](https://in-toto.io/) +* [GitHub Actions SLSA Generator](https://github.com/slsa-framework/slsa-github-generator) + +--- + +## ๐Ÿ“‚ Group 5: Advanced Supply Chain Security + +## ๐Ÿ“ Slide 18 โ€“ ๐ŸŽฏ SLSA Framework Implementation + +* ๐Ÿ† **SLSA (Supply Chain Levels for Software Artifacts)** = maturity model for supply chain security +* ๐Ÿ“Š **4 levels:** Progressive security guarantees (0-4) +* ๐ŸŽฏ **Goal:** Achieve Level 3 (realistic for most teams) + +```mermaid +flowchart LR + L0[๐Ÿ“Š Level 0
No guarantees
Most software today] --> L1[๐Ÿ“ Level 1
Build documented
Basic provenance] + L1 --> L2[โœ… Level 2
Signed provenance
Build service] + L2 --> L3[๐Ÿ”’ Level 3
Hardened builds
Non-falsifiable] + L3 --> L4[๐Ÿ† Level 4
Two-party review
Hermetic builds] + + style L0 fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + style L1 fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + style L2 fill:#fff9c4,stroke:#fbc02d,stroke-width:2px,color:#2c3e50 + style L3 fill:#e8f5e8,stroke:#388e3c,stroke-width:3px,color:#2c3e50 + style L4 fill:#1b5e20,stroke:#388e3c,stroke-width:3px,color:#fff +``` + +--- + +### ๐Ÿ“‹ SLSA Level Requirements + +**Level 0:** No requirements (starting point) + +**Level 1:** Build process documented +* โœ… Provenance exists (who/what/when/how) + +**Level 2:** Build service generates signed provenance +* โœ… Authenticated identity (builder) +* โœ… Tamper-proof provenance + +**Level 3:** Hardened build platform +* โœ… Isolated build environment +* โœ… Non-falsifiable provenance +* โœ… **GitHub Actions can achieve this!** + +**Level 4:** Hermetic + two-party review +* โœ… Reproducible builds +* โœ… All changes reviewed by 2+ people +* ๐ŸŽฏ Very few projects achieve this + +--- + +### ๐Ÿš€ Achieving SLSA Level 3 with GitHub Actions + +* ๐ŸŽฏ **Good news:** GitHub Actions + SLSA generator = Level 3 +* ๐Ÿ”ง **Tools:** slsa-github-generator (official) +* โœ… **Requirements met:** + * Isolated build (GitHub-hosted runners) + * Non-falsifiable provenance (signed by GitHub) + * Build service (GitHub Actions) + +* ๐Ÿ”— **Tool:** [slsa-github-generator](https://github.com/slsa-framework/slsa-github-generator) + +
+๐Ÿ’ญ Why is Level 4 so hard? + +**Level 4 requirements:** + +1. **๐Ÿ”’ Hermetic builds:** + * No network access during build + * All inputs declared upfront + * Reproducible bit-for-bit + +2. **๐Ÿ‘ฅ Two-party review:** + * Every change reviewed by 2+ people + * No self-merge + * Enforced by platform + +**Challenges:** +* ๐Ÿ“ฆ Most build tools fetch dependencies over network +* โฐ Hermetic builds are slow (can't cache) +* ๐Ÿ‘ฅ Small teams struggle with 2-party review + +**Who achieves Level 4?** +* ๐Ÿ›๏ธ Critical infrastructure (Kubernetes, Debian) +* ๐Ÿ’ฐ Well-funded open source (large teams) +* ๐Ÿ”’ High-security environments + +**Most teams should aim for Level 3 (practical and effective).** +
+ +--- + +## ๐Ÿ“ Slide 19 โ€“ ๐Ÿ”’ Securing the Build Pipeline + +* ๐ŸŽฏ **SolarWinds lesson:** Build systems are critical infrastructure +* ๐Ÿ”ฅ **If build is compromised:** Every artifact is poisoned +* ๐Ÿ›ก๏ธ **Defense:** Harden build systems like production + +```mermaid +flowchart LR + Source[๐Ÿ“ Clean Source] --> Build{๐Ÿ—๏ธ Build System} + Build -->|โœ… Secure| Safe[๐Ÿ“ฆ Safe Artifact] + Build -->|๐Ÿ’€ Compromised| Poisoned[โ˜ ๏ธ Poisoned Artifact] + + Poisoned --> Victims[๐ŸŽฏ All Users Affected] + + style Build fill:#fff3e0,stroke:#f57c00,stroke-width:3px,color:#2c3e50 + style Poisoned fill:#b71c1c,stroke:#d32f2f,stroke-width:3px,color:#fff + style Victims fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 +``` + +--- + +### ๐Ÿ”’ Build System Hardening + +**๐Ÿ” Access control:** +* Least privilege (minimal permissions) +* MFA for all accounts +* Audit logs + +**๐Ÿ›ก๏ธ Environment isolation:** +* Ephemeral build environments +* No persistent state +* Network segmentation + +**๐Ÿ“œ Provenance generation:** +* Automatic build attestations +* Signed by build system +* Immutable audit trail + +**๐Ÿ” Monitoring:** +* Build duration anomalies +* Unexpected network access +* File system changes + +--- + +### ๐Ÿ—๏ธ Hermetic Builds + +* ๐ŸŽฏ **Hermetic** = completely isolated, no external dependencies +* ๐Ÿ”’ **Characteristics:** + * No network access during build + * All inputs declared in manifest + * Reproducible (same inputs โ†’ same output) +* โœ… **Benefits:** + * Can't fetch malicious dependencies + * Can't exfiltrate secrets + * Reproducible = verifiable + +**Tools:** +* ๐Ÿณ Docker (with network disabled) +* ๐Ÿ“ฆ Bazel (hermetic by design) +* ๐Ÿ”ง Nix (functional package manager) + +--- + +### โš ๏ธ GitHub Actions Security + +**๐Ÿ”ด Common mistakes:** + +1. **Using `pull_request_target` with untrusted code** + * ๐Ÿšจ Allows untrusted PRs to access secrets + +2. **Not pinning actions by SHA** + * ๐Ÿšจ Action maintainer can inject malicious code + +3. **Overly permissive `GITHUB_TOKEN`** + * ๐Ÿšจ Default permissions too broad + +4. **Secrets in build logs** + * ๐Ÿšจ Can leak via debug output + +**โœ… Best practices:** +* Pin actions by commit SHA (not tag) +* Minimal `GITHUB_TOKEN` permissions +* Use `pull_request` (not `pull_request_target`) +* Separate workflows for untrusted code + +--- + +## ๐Ÿ“ Slide 20 โ€“ ๐Ÿš€ Runtime Supply Chain Security + +* ๐ŸŽฏ **Problem:** Security doesn't end at deployment +* ๐Ÿ”„ **Continuous:** Monitor supply chain in production +* ๐Ÿ›ก๏ธ **Policy enforcement:** Only run verified artifacts + +```mermaid +flowchart LR + Deploy[๐Ÿš€ Deployment] --> Admission[๐Ÿ›ก๏ธ Admission Control] + Admission -->|Check| Signature{โœ๏ธ Signed?} + Admission -->|Check| Provenance{๐Ÿ“œ Provenance?} + Admission -->|Check| Policy{๐Ÿ“‹ Policy OK?} + + Signature -->|โŒ No| Block[๐Ÿšซ Block] + Provenance -->|โŒ No| Block + Policy -->|โŒ Fail| Block + + Signature -->|โœ… Yes| Allow[โšก Allow] + Provenance -->|โœ… Yes| Allow + Policy -->|โœ… Pass| Allow + + Allow --> Runtime[๐Ÿ“Š Runtime Monitoring] + + style Admission fill:#e3f2fd,stroke:#1976d2,stroke-width:3px,color:#2c3e50 + style Block fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + style Allow fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 +``` + +--- + +### ๐Ÿ›ก๏ธ Kubernetes Admission Controllers + +* ๐ŸŽฏ **Purpose:** Enforce policies at deployment time +* ๐Ÿ”ง **Tools:** + * **Kyverno** (Kubernetes-native, easy YAML policies) + * **OPA Gatekeeper** (powerful, Rego policies) + * **Cosign Policy Controller** (signature verification) + +**Example policies:** +* โœ… Only deploy signed images +* โœ… Require valid SLSA provenance +* โœ… Block images with critical vulnerabilities +* โœ… Enforce SBOM attestation + +--- + +### ๐Ÿ“Š Runtime Drift Detection + +* ๐ŸŽฏ **Drift** = production doesn't match expected SBOM +* ๐Ÿ” **Detection methods:** + * Compare runtime SBOM vs build SBOM + * Monitor for unexpected processes + * File integrity monitoring +* ๐Ÿšจ **Alert:** Unauthorized changes + +--- + +### ๐Ÿ”„ Continuous Supply Chain Monitoring + +**Monitor for:** +* ๐Ÿšจ New CVEs in deployed components +* ๐Ÿ“Š SBOM changes (drift) +* โš ๏ธ Policy violations +* ๐Ÿ”„ License compliance + +**Tools:** +* Dependency-Track (SBOM monitoring) +* Falco (runtime security) +* Tetragon (eBPF-based monitoring) + +--- + +### ๐Ÿ“Š Supply Chain Security Metrics + +**Track:** +* ๐Ÿ“ˆ % artifacts signed +* ๐Ÿ“œ % artifacts with provenance +* ๐Ÿ“‹ % SBOMs generated +* ๐ŸŽฏ SLSA level distribution +* โฐ Mean time to patch vulnerabilities +* ๐Ÿ“Š Policy compliance rate + +**Goal:** Continuous improvement + +
+๐Ÿ’ญ Complete Supply Chain Security Checklist + +**โœ… Development:** +* Lockfiles committed +* Dependency updates automated +* Pre-commit secret scanning + +**โœ… Build:** +* SBOM generated +* Artifacts signed (Cosign) +* Provenance generated (SLSA) +* Vulnerability scanning + +**โœ… Registry:** +* Image scanning on push +* Policy enforcement +* SBOM storage + +**โœ… Deployment:** +* Signature verification +* Provenance verification +* Admission control policies + +**โœ… Runtime:** +* Continuous monitoring +* Drift detection +* New CVE alerts + +**Goal:** Defense in depth at every stage +
+ +--- + +## ๐ŸŽ‰ Fun Break: "The Dependency Confusion Gold Rush (2021)" + +### ๐Ÿ’ฐ How One Researcher Made $130K Finding a New Attack + +**February 2021: Alex Birsan discovers dependency confusion** + +**The Attack:** +1. Companies use internal packages: `@company/auth-lib` +2. Package manager checks: internal registry โ†’ public npm +3. Public npm has higher version โ†’ **installs public package!** +4. Attacker publishes malicious `company-auth-lib` v99.0 + +```mermaid +flowchart LR + Dev[๐Ÿ‘จโ€๐Ÿ’ป Developer
npm install @company/auth] --> Check{๐Ÿ“ฆ Package Manager} + Check -->|Check| Internal[๐Ÿข Internal Registry
v1.0.0] + Check -->|Check| Public[๐ŸŒ Public npm
v99.0.0 ๐Ÿ’€] + Check -->|Higher version!| Install[๐Ÿ“ฅ Installs Public] + + Install --> Compromised[๐Ÿ’€ Company Compromised] + + style Public fill:#ffebee,stroke:#d32f2f,stroke-width:3px,color:#2c3e50 + style Compromised fill:#b71c1c,stroke:#d32f2f,stroke-width:3px,color:#fff +``` + +**The Gold Rush:** +* ๐Ÿ” Alex targets 35+ companies +* ๐Ÿ“ฆ Publishes "security research" packages +* ๐Ÿ’ฐ Companies pay bug bounties: **$130,000 total** +* ๐ŸŽฏ Victims: Apple, Microsoft, Tesla, Uber, PayPal, Netflix + +**The Impact:** +* ๐Ÿ”ฅ Thousands of companies vulnerable +* ๐Ÿ“‹ Package managers add protections +* ๐Ÿข Companies create private registries + +**The Fix:** +* ๐Ÿ”’ Namespace scoping (`@company/` on private registry) +* ๐Ÿ›ก๏ธ Registry priority configuration +* ๐Ÿ“ฆ Internal package allowlisting + +**Lesson:** Supply chain attacks are profitable (for attackers AND researchers) + +--- + +## ๐Ÿ“Š Summary: Key Takeaways + +### โœ… Core Principles + +* ๐Ÿ”— **Modern software = complex supply chains** (200+ dependencies) +* ๐Ÿ“‹ **SBOMs provide transparency** (Lab 4: generate โ†’ Lab 8: analyze) +* ๐Ÿ” **SCA tools find vulnerabilities** (use multiple tools) +* โœ๏ธ **Signing ensures authenticity** (Sigstore makes it easy) +* ๐Ÿ“œ **Provenance proves secure builds** (SLSA framework) +* ๐Ÿค– **Automation is essential** (too complex for manual tracking) +* ๐Ÿ”„ **Continuous monitoring catches new threats** (Dependency-Track) +* ๐Ÿšจ **Policy enforcement prevents risky deployments** (admission controllers) + +--- + +### ๐ŸŽฏ Practical Actions + +**๐Ÿ—๏ธ This week:** +1. Generate SBOMs in CI/CD (if not from Lab 4) +2. Scan with Grype or Trivy +3. Sign one artifact with Cosign + +**๐Ÿ“ˆ This month:** +1. Set up Dependency-Track +2. Generate provenance attestations +3. Create security policies + +**๐Ÿš€ This quarter:** +1. Achieve SLSA Level 3 +2. Automate dependency updates +3. Continuous supply chain monitoring + +--- + +### ๐Ÿ”— Essential Resources + +**๐Ÿ“š Frameworks:** +* [SLSA](https://slsa.dev/) +* [NIST SSDF](https://csrc.nist.gov/Projects/ssdf) +* [OWASP SCVS](https://scvs.owasp.org/) + +**โœ๏ธ Signing:** +* [Sigstore](https://www.sigstore.dev/) +* [Cosign](https://github.com/sigstore/cosign) + +**๐Ÿ“‹ SBOM:** +* [SPDX](https://spdx.dev/) +* [CycloneDX](https://cyclonedx.org/) + +**๐Ÿ› ๏ธ Tools:** +* [Syft](https://github.com/anchore/syft) +* [Grype](https://github.com/anchore/grype) +* [Dependency-Track](https://dependencytrack.org/) + +**๐Ÿ—„๏ธ Databases:** +* [OSV](https://osv.dev/) +* [NVD](https://nvd.nist.gov/) +* [CISA KEV](https://www.cisa.gov/known-exploited-vulnerabilities-catalog) + +--- \ No newline at end of file diff --git a/lectures/lec9.md b/lectures/lec9.md new file mode 100644 index 00000000..577c0d25 --- /dev/null +++ b/lectures/lec9.md @@ -0,0 +1,2872 @@ +# ๐Ÿ“Š Lecture 9 - Monitoring, Compliance & Improvement: Security Operations & Maturity + +## ๐Ÿ“‚ Group 1: Security Observability + +## ๐Ÿ“ Slide 1 โ€“ ๐Ÿ“Š Security Monitoring in DevSecOps + +* ๐Ÿ“Š **Security monitoring** = continuous visibility into security posture across SDLC +* ๐ŸŽฏ **Shift:** Reactive (after breach) โ†’ Proactive (before exploit) +* ๐Ÿ’ฐ **Cost of delayed detection:** + * Average breach detection time: **207 days** (IBM 2024) + * Cost per day undetected: **$1.2M+** + * Early detection (< 30 days) saves **$1M on average** +* ๐Ÿ”ฅ **Famous delayed detections:** + * **SolarWinds (2020):** 9 months undetected โ†’ 18,000 organizations compromised + * **Equifax (2017):** 76 days undetected โ†’ 147M records stolen + * **Target (2013):** 19 days with alerts ignored โ†’ $18M settlement +* ๐Ÿ”— **Learn more:** [IBM Cost of Data Breach Report](https://www.ibm.com/security/data-breach), [Ponemon Cost of Cyber Crime](https://www.ponemon.org/) + +```mermaid +flowchart LR + Traditional[๐Ÿšจ Traditional Security
React after breach] -->|Days/months| Detect1[๐Ÿ” Detect] + Detect1 -->|Cleanup| Cost1[๐Ÿ’ฐ High Cost
$4.5M average] + + DevSecOps[โœ… DevSecOps Monitoring
Continuous visibility] -->|Minutes/hours| Detect2[๐Ÿ” Detect] + Detect2 -->|Fast response| Cost2[๐Ÿ’ฐ Lower Cost
$1M saved] + + style Traditional fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + style DevSecOps fill:#e8f5e8,stroke:#388e3c,stroke-width:3px,color:#2c3e50 + style Cost1 fill:#ffcdd2,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + style Cost2 fill:#c8e6c9,stroke:#388e3c,stroke-width:2px,color:#2c3e50 +``` + +--- + +### ๐Ÿ”„ Monitoring as Feedback Loop + +* ๐ŸŽฏ **Purpose:** Learn and improve continuously +* ๐Ÿ“Š **Cycle:** Monitor โ†’ Detect โ†’ Respond โ†’ Analyze โ†’ Improve โ†’ Monitor +* โœ… **Benefits:** + * Catch issues earlier in SDLC + * Validate security controls work + * Measure improvement over time + * Evidence for compliance + +```mermaid +flowchart LR + Monitor[๐Ÿ“Š Monitor
Collect signals] --> Detect[๐Ÿ” Detect
Identify issues] + Detect --> Respond[โšก Respond
Fix & contain] + Respond --> Analyze[๐Ÿง  Analyze
Root cause] + Analyze --> Improve[๐Ÿ“ˆ Improve
Prevent recurrence] + Improve --> Monitor + + style Monitor fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + style Detect fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + style Respond fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + style Analyze fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#2c3e50 + style Improve fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 +``` + +--- + +### ๐ŸŽฏ Why Continuous Monitoring Matters + +* โฐ **New vulnerabilities discovered daily:** + * Average: **50+ CVEs per day** + * Your dependencies get new CVEs after deployment + * Zero-days emerge (Log4Shell, Heartbleed) +* ๐Ÿ”„ **Configuration drift:** + * Production changes without approval + * Unauthorized deployments + * Expired certificates +* ๐Ÿšจ **Runtime threats:** + * Exploitation attempts + * Unusual network activity + * Privilege escalation + +**Without monitoring:** You're flying blind ๐Ÿ™ˆ + +
+๐Ÿ’ญ Discussion: What's worse - no monitoring or alert fatigue? + +**No monitoring:** +* โŒ Breaches go undetected for months +* โŒ No evidence for compliance +* โŒ Can't measure improvement + +**Alert fatigue:** +* โš ๏ธ Real alerts ignored (signal-to-noise problem) +* โš ๏ธ Teams become desensitized +* โš ๏ธ Critical alerts missed in noise + +**The Answer:** Neither! You need **smart monitoring**: +* โœ… Focus on high-signal alerts (reduce noise) +* โœ… Automate responses where possible +* โœ… Context-aware alerting (not everything is Critical) +* โœ… Regular tuning (remove false positives) + +**Key metric:** Alert signal-to-noise ratio should be > 80% actionable +
+ +--- + +## ๐Ÿ“ Slide 2 โ€“ ๐Ÿ” What to Monitor: Logs, Metrics, Traces + +* ๐Ÿ“Š **Observability = Logs + Metrics + Traces** (three pillars) +* ๐ŸŽฏ **Monitoring = subset of observability** (predefined dashboards/alerts) +* ๐Ÿ”‘ **Security observability:** Apply three pillars to security signals + +```mermaid +flowchart LR + subgraph "๐Ÿ“Š Three Pillars of Observability" + Logs[๐Ÿ“ Logs
What happened] + Metrics[๐Ÿ“ˆ Metrics
How much/how fast] + Traces[๐Ÿ”— Traces
Request flow] + end + + Logs --> Security[๐Ÿ›ก๏ธ Security
Observability] + Metrics --> Security + Traces --> Security + + Security --> Detect[๐Ÿ” Detect Threats] + Security --> Measure[๐Ÿ“Š Measure Posture] + Security --> Improve[๐Ÿ“ˆ Improve Programs] + + style Security fill:#e3f2fd,stroke:#1976d2,stroke-width:3px,color:#2c3e50 +``` + +--- + +### ๐Ÿ“ Logs: What Happened + +* ๐ŸŽฏ **Security logs to collect:** + * **Authentication logs** (who logged in, failed attempts) + * **Authorization logs** (who accessed what, permission denials) + * **Audit logs** (configuration changes, policy updates) + * **Security tool outputs** (scan results, alerts) + * **Pipeline logs** (build failures, security gate blocks) + * **Application logs** (errors, exceptions, suspicious patterns) +* ๐Ÿ” **Use cases:** + * Incident investigation (what happened?) + * Compliance evidence (audit trail) + * Anomaly detection (unusual patterns) +* โš ๏ธ **Challenge:** Log volume (terabytes/day in large orgs) + +--- + +### ๐Ÿ“ˆ Metrics: How Much / How Fast + +* ๐ŸŽฏ **Security metrics to track:** + * **Vulnerability counts** (total, by severity) + * **Detection times** (MTTD - Mean Time to Detect) + * **Response times** (MTTR - Mean Time to Respond) + * **Deployment frequency** (with security gates) + * **Security test coverage** (% of code scanned) + * **Policy violations** (count, trends) + * **False positive rate** (alert accuracy) +* ๐Ÿ” **Use cases:** + * Trend analysis (improving or degrading?) + * SLA tracking (meeting targets?) + * Capacity planning (security team workload) +* โœ… **Advantage:** Time-series data enables predictions + +--- + +### ๐Ÿ”— Traces: Request Flow + +* ๐ŸŽฏ **Security-relevant traces:** + * **API call chains** (which services talked to which) + * **Authentication flows** (token passing, validation) + * **Data access patterns** (which user accessed sensitive data) + * **Dependency calls** (external API usage) +* ๐Ÿ” **Use cases:** + * Lateral movement detection (attacker pivoting) + * Privilege escalation tracking + * Data exfiltration paths + * Understanding blast radius +* ๐Ÿ› ๏ธ **Tools:** OpenTelemetry, Jaeger, Zipkin (with security context) + +--- + +### ๐Ÿ›ก๏ธ Security-Specific Monitoring Needs + +**Beyond traditional observability:** + +* ๐Ÿšจ **Vulnerability trends:** + * New vulnerabilities discovered + * Vulnerability backlog growth + * Fix rates by severity +* ๐Ÿ”„ **Deployment security gates:** + * % deployments blocked + * Reasons for blocks + * Override frequency +* โŒ **Failed security scans:** + * Which scans failed + * Failure patterns + * Recurrence of same issues +* ๐Ÿ“‹ **Policy violations:** + * Which policies violated most + * By team/service + * Trends over time +* โฑ๏ธ **Incident response:** + * Response times by severity + * Escalation patterns + * Resolution effectiveness + +```mermaid +flowchart LR + subgraph "๐Ÿ—„๏ธ Data Sources" + SIEM[๐Ÿ›ก๏ธ SIEM] + Scanners[๐Ÿ” Security Scanners] + CICD[๐Ÿ”„ CI/CD Systems] + Runtime[โšก Runtime Agents] + Cloud[โ˜๏ธ Cloud APIs] + end + + SIEM --> Aggregate[๐Ÿ“Š Aggregation Layer] + Scanners --> Aggregate + CICD --> Aggregate + Runtime --> Aggregate + Cloud --> Aggregate + + Aggregate --> Dashboard[๐Ÿ“ˆ Security Dashboards] + Aggregate --> Alerts[๐Ÿšจ Alerting] + Aggregate --> Reports[๐Ÿ“‹ Compliance Reports] + + style Aggregate fill:#e3f2fd,stroke:#1976d2,stroke-width:3px,color:#2c3e50 +``` + +
+๐Ÿ’ญ Question: Should security use the same observability stack as operations? + +**Arguments for sharing:** +* โœ… Correlated data (security + performance together) +* โœ… Cost savings (one platform) +* โœ… Developer familiarity (one tool to learn) +* โœ… Easier incident response (unified view) + +**Arguments for separation:** +* โš ๏ธ Access control (security data is sensitive) +* โš ๏ธ Retention requirements (compliance needs longer retention) +* โš ๏ธ Security-specific features (threat intel, CVSS scoring) +* โš ๏ธ Performance (security logs are high-volume) + +**Best Practice:** Hybrid approach +* ๐ŸŽฏ Use shared observability platform (Datadog, Splunk, ELK) +* ๐Ÿ”’ Add security-specific overlays (security dashboards, RBAC) +* ๐Ÿ“Š Integrate security tools (feed data into observability platform) +* ๐Ÿ›ก๏ธ Separate retention/access for sensitive security data + +**Modern trend:** Security observability built into platform (not separate) +
+ +--- + +## ๐Ÿ“ Slide 3 โ€“ ๐Ÿ› ๏ธ Security Monitoring Tools & Platforms + +* ๐ŸŽฏ **Tool categories:** SIEM, dashboards, vulnerability platforms, CSPM, observability +* ๐Ÿ”‘ **No single tool does everything** โ†’ integrated ecosystem +* ๐Ÿ“Š **Choose based on:** Scale, budget, existing tools, team skills + +```mermaid +flowchart LR + subgraph "๐Ÿ› ๏ธ Security Monitoring Ecosystem" + SIEM[๐Ÿ›ก๏ธ SIEM
Splunk, ELK] + Dash[๐Ÿ“Š Dashboards
Grafana, Kibana] + Vuln[๐Ÿ” Vuln Management
DefectDojo, Dependency-Track] + CSPM[โ˜๏ธ CSPM
Prisma, Wiz] + Obs[๐Ÿ“ˆ Observability
Datadog, New Relic] + end + + Sources[๐Ÿ—„๏ธ Security Data
Scanners, CI/CD, Cloud] --> SIEM + Sources --> Dash + Sources --> Vuln + Sources --> CSPM + Sources --> Obs + + SIEM --> Teams[๐Ÿ‘ฅ Security Teams] + Dash --> Teams + Vuln --> Teams + CSPM --> Teams + Obs --> Teams + + style Sources fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + style Teams fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 +``` + +--- + +### ๐Ÿ›ก๏ธ SIEM (Security Information and Event Management) + +* ๐ŸŽฏ **Purpose:** Centralized log aggregation, correlation, alerting +* ๐Ÿ”‘ **Core capabilities:** + * Log collection from multiple sources + * Real-time correlation (detect patterns) + * Alerting and incident management + * Long-term retention (compliance) + * Threat intelligence integration +* ๐Ÿ› ๏ธ **Popular platforms:** + * **Splunk** (enterprise, expensive, powerful) + * **ELK Stack** (Elasticsearch, Logstash, Kibana - open-source) + * **QRadar** (IBM, enterprise) + * **Azure Sentinel** (cloud-native, Microsoft) + * **Sumo Logic** (SaaS, modern) +* โš ๏ธ **Challenge:** High cost (license + storage), complex setup +* ๐Ÿ”— **Resources:** [Splunk](https://www.splunk.com/), [Elastic Security](https://www.elastic.co/security) + +--- + +### ๐Ÿ“Š Security Dashboards + +* ๐ŸŽฏ **Purpose:** Visualize security metrics and trends +* ๐Ÿ”‘ **Dashboard types:** + * **Executive dashboard** (high-level, risk scores) + * **Manager dashboard** (team metrics, SLAs) + * **Engineer dashboard** (detailed vulnerabilities, remediation) +* ๐Ÿ› ๏ธ **Popular tools:** + * **Grafana** (open-source, flexible, integrates everything) + * **Kibana** (part of ELK stack) + * **Datadog** (SaaS, modern UI) + * **Tableau/PowerBI** (for compliance reporting) +* โœ… **Best practice:** Different dashboards for different audiences +* ๐Ÿ”— **Resources:** [Grafana](https://grafana.com/), [Kibana](https://www.elastic.co/kibana) + +--- + +### ๐Ÿ” Vulnerability Management Platforms + +* ๐ŸŽฏ **Purpose:** Aggregate, deduplicate, track vulnerabilities +* ๐Ÿ”‘ **Core capabilities:** + * Import from multiple scanners (SAST, DAST, SCA) + * Deduplication (same vuln from multiple tools) + * Risk scoring and prioritization + * Workflow management (assign, track, verify) + * Reporting and metrics +* ๐Ÿ› ๏ธ **Popular platforms:** + * **DefectDojo** (open-source, developer-friendly) + * **Dependency-Track** (SBOM-based, open-source) + * **ThreadFix** (commercial, enterprise) + * **Jira + plugins** (many teams use issue trackers) +* โœ… **Integration:** Should integrate with CI/CD and dashboards +* ๐Ÿ”— **Resources:** [DefectDojo](https://www.defectdojo.org/), [Dependency-Track](https://dependencytrack.org/) + +--- + +### โ˜๏ธ CSPM (Cloud Security Posture Management) + +* ๐ŸŽฏ **Purpose:** Monitor cloud configuration compliance +* ๐Ÿ”‘ **What it monitors:** + * Misconfigured resources (public S3 buckets) + * IAM overpermissions (too many admin accounts) + * Network security (open security groups) + * Compliance violations (CIS benchmarks) + * Configuration drift (unauthorized changes) +* ๐Ÿ› ๏ธ **Popular platforms:** + * **Prisma Cloud** (Palo Alto, multi-cloud) + * **Wiz** (modern, developer-friendly) + * **Orca Security** (agentless) + * **AWS Security Hub** (AWS-native) + * **Azure Defender** (Azure-native) + * **Open-source:** Prowler, ScoutSuite, CloudSploit +* ๐Ÿ“Š **Covered in:** Lab 6 (IaC Security) +* ๐Ÿ”— **Resources:** [Prowler](https://github.com/prowler-cloud/prowler), [Wiz](https://www.wiz.io/) + +--- + +### ๐Ÿ“ˆ Observability Platforms with Security + +* ๐ŸŽฏ **Modern trend:** Unified observability + security +* ๐Ÿ”‘ **Platforms adding security features:** + * **Datadog** (APM + security monitoring) + * **New Relic** (observability + vulnerability management) + * **Dynatrace** (performance + runtime security) + * **Elastic** (observability + SIEM in one) +* โœ… **Advantage:** Correlated security + performance data +* ๐Ÿ“Š **Use case:** See security issues alongside performance issues +* ๐Ÿ”— **Resources:** [Datadog Security](https://www.datadoghq.com/product/security-platform/), [Elastic Observability](https://www.elastic.co/observability) + +--- + +### ๐Ÿ—๏ธ Building Your Security Monitoring Stack + +**Typical evolution:** + +**Stage 1 (Small teams):** +* ๐Ÿ“Š Grafana + Prometheus (metrics) +* ๐Ÿ“ ELK or Loki (logs) +* ๐Ÿ” DefectDojo or Jira (vulnerabilities) + +**Stage 2 (Growth):** +* โž• Add SIEM (Splunk or Elastic Security) +* โž• Add CSPM (cloud-specific tools) +* โž• Integrate security tools into observability + +**Stage 3 (Enterprise):** +* ๐Ÿข Commercial unified platform (Datadog, Splunk) +* ๐Ÿ”„ Full automation (API integrations) +* ๐Ÿค– AI/ML for anomaly detection + +```mermaid +flowchart LR + Stage1[๐ŸŒฑ Stage 1
Grafana + ELK + Jira] --> Stage2[๐Ÿ“ˆ Stage 2
+ SIEM + CSPM] + Stage2 --> Stage3[๐Ÿข Stage 3
Unified Platform] + + style Stage1 fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + style Stage2 fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + style Stage3 fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 +``` + +
+๐Ÿ’ญ Best Practice: Start simple, grow as needed + +**Avoid the trap:** Buying expensive enterprise SIEM on day 1 + +**Better approach:** + +**Month 1:** +* โœ… Start with free tools (Grafana, ELK) +* โœ… Focus on key metrics (vulnerabilities, deployment frequency) +* โœ… Manual processes are OK initially + +**Month 3:** +* โœ… Automate data collection (CI/CD integration) +* โœ… Add basic alerting (critical vulns, failed deployments) +* โœ… Create team dashboards + +**Month 6:** +* โœ… Evaluate commercial tools (if free tools limiting) +* โœ… Add advanced features (anomaly detection, correlation) +* โœ… Integrate threat intelligence + +**Month 12:** +* โœ… Mature monitoring program +* โœ… Evidence-based tool decisions +* โœ… Proven ROI before big investments + +**Key insight:** Your monitoring needs will change as you grow. Build for now, plan for future. +
+ +--- + +๐Ÿ”— **Resources for Group 1:** +* [IBM Cost of Data Breach Report](https://www.ibm.com/security/data-breach) +* [NIST Cybersecurity Framework: Detect Function](https://www.nist.gov/cyberframework/detect) +* [Grafana Security Dashboards](https://grafana.com/grafana/dashboards/?search=security) +* [DefectDojo](https://www.defectdojo.org/) +* [Elastic Security](https://www.elastic.co/security) +* [OpenTelemetry Security](https://opentelemetry.io/) + +--- + +## ๐Ÿ“‚ Group 2: Security Metrics & KPIs + +## ๐Ÿ“ Slide 4 โ€“ ๐Ÿ“ˆ Security Metrics vs Vanity Metrics + +* ๐Ÿ“Š **Metric** = quantifiable measurement of security program effectiveness +* ๐ŸŽฏ **KPI (Key Performance Indicator)** = metric tied to business objectives +* โš ๏ธ **Vanity metric** = looks impressive but doesn't drive decisions +* ๐Ÿ”‘ **Goal:** Measure what matters, not what's easy to count + +```mermaid +flowchart LR + Vanity[๐Ÿ˜Ž Vanity Metrics
Look good, no action] --> Examples1[๐Ÿ“Š Total scans run
๐Ÿ“Š Lines of code
๐Ÿ“Š # of security tools] + + Actionable[โœ… Actionable Metrics
Drive decisions] --> Examples2[โฑ๏ธ Time to fix critical vulns
๐Ÿ“‰ Vulnerability trends
๐ŸŽฏ Policy compliance rate] + + Examples1 -.->|No impact| Decision1[โ“ What do we do?] + Examples2 -->|Clear action| Decision2[โœ… Fix, improve, adjust] + + style Vanity fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + style Actionable fill:#e8f5e8,stroke:#388e3c,stroke-width:3px,color:#2c3e50 + style Decision2 fill:#c8e6c9,stroke:#388e3c,stroke-width:2px,color:#2c3e50 +``` + +--- + +### ๐Ÿ˜Ž Vanity Metrics (Avoid These) + +**Look impressive but don't help:** + +* โŒ **Total number of scans run** (doesn't mean code is secure) +* โŒ **Lines of code scanned** (quantity โ‰  quality) +* โŒ **Number of security tools deployed** (tool sprawl โ‰  security) +* โŒ **Total vulnerabilities found** (without context of severity/age) +* โŒ **Number of security meetings** (meetings โ‰  action) +* โŒ **Security training completion rate** (completion โ‰  behavior change) + +**Why they're bad:** +* ๐ŸŽฏ No actionable insight (what should we do?) +* ๐Ÿ“Š Can be gamed (inflate numbers without improving security) +* ๐Ÿ’ผ Create false confidence (high numbers โ‰  secure) + +--- + +### โœ… Actionable Metrics (Use These) + +**Drive real decisions:** + +* โœ… **Mean Time to Remediate (MTTR)** โ†’ Are we getting faster? +* โœ… **Vulnerability backlog trend** โ†’ Growing or shrinking? +* โœ… **Deployment security gate pass rate** โ†’ Quality improving? +* โœ… **Critical vulnerability age** โ†’ Old vulns still open? +* โœ… **False positive rate** โ†’ Are alerts useful? +* โœ… **Policy compliance rate** โ†’ Meeting standards? +* โœ… **Security test coverage** โ†’ Blind spots? + +**Why they're good:** +* ๐ŸŽฏ Clear action (if metric is bad, we know what to fix) +* ๐Ÿ“Š Tied to business impact (reduce risk, improve speed) +* ๐Ÿ“ˆ Show trends (improving or degrading?) + +```mermaid +flowchart LR + Metric[๐Ÿ“Š Metric: MTTR = 45 days] --> Question{๐Ÿค” Is this good?} + Question -->|Benchmark| Industry[๐Ÿ“Š Industry: 30 days] + Question -->|Trend| Previous[๐Ÿ“ˆ Last quarter: 60 days] + + Industry -->|We're slower| Action1[โšก Action: Prioritize faster fixes] + Previous -->|We're improving| Action2[โœ… Keep current approach] + + style Metric fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + style Action1 fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + style Action2 fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 +``` + +--- + +### ๐Ÿ“ SMART Criteria for Security Metrics + +* ๐Ÿ“Š **Specific:** Clear definition (no ambiguity) +* ๐Ÿ“ **Measurable:** Quantifiable (numbers, not feelings) +* ๐ŸŽฏ **Achievable:** Realistic targets (not impossible goals) +* ๐Ÿ”— **Relevant:** Tied to business objectives (reduce risk, enable speed) +* โฐ **Time-bound:** Defined timeframe (monthly, quarterly) + +**Example:** + +**โŒ Bad metric:** "Improve security" +* Not specific, not measurable, no timeframe + +**โœ… Good metric:** "Reduce MTTR for critical vulnerabilities from 45 days to 30 days by Q3 2024" +* Specific (MTTR, critical vulns) +* Measurable (45 โ†’ 30 days) +* Achievable (33% improvement) +* Relevant (faster fixes = lower risk) +* Time-bound (Q3 2024) + +--- + +### ๐Ÿ“Š Leading vs Lagging Indicators + +* ๐Ÿ”ฎ **Leading indicators:** Predict future outcomes (proactive) +* ๐Ÿ“ˆ **Lagging indicators:** Measure past results (reactive) + +| Type | Examples | Use Case | +|------|----------|----------| +| ๐Ÿ”ฎ **Leading** | โ€ข Security test coverage
โ€ข Pre-commit scan adoption
โ€ข Training completion | Predict future security posture | +| ๐Ÿ“ˆ **Lagging** | โ€ข Vulnerabilities found in prod
โ€ข Breach incidents
โ€ข MTTR | Measure past performance | + +**Best practice:** Track both +* ๐Ÿ”ฎ Leading โ†’ Prevent problems +* ๐Ÿ“ˆ Lagging โ†’ Validate improvements + +
+๐Ÿ’ญ Warning: Goodhart's Law in Security + +**Goodhart's Law:** "When a measure becomes a target, it ceases to be a good measure" + +**Security examples:** + +**Metric:** Number of vulnerabilities fixed per sprint +* ๐ŸŽฏ **Goal:** Increase fixes +* ๐Ÿšจ **Gaming:** Team fixes low-severity vulns, ignores critical ones +* ๐Ÿ’ฅ **Result:** High numbers, low security + +**Metric:** Security scan pass rate +* ๐ŸŽฏ **Goal:** Clean scans +* ๐Ÿšจ **Gaming:** Disable strict rules, mark issues as false positives +* ๐Ÿ’ฅ **Result:** Green dashboards, vulnerable code + +**Metric:** Training completion rate +* ๐ŸŽฏ **Goal:** 100% completion +* ๐Ÿšจ **Gaming:** Click through without learning +* ๐Ÿ’ฅ **Result:** Certificates issued, no behavior change + +**How to avoid:** +* โœ… Use multiple metrics (can't game all) +* โœ… Focus on outcomes, not activities +* โœ… Regular audits of metric quality +* โœ… Combine quantitative + qualitative assessment + +**Remember:** Metrics should serve security, not the other way around +
+ +--- + +## ๐Ÿ“ Slide 5 โ€“ โฑ๏ธ Time-Based KPIs: MTTD, MTTR, MTTA + +* โฐ **Time is money** in security (literally) +* ๐ŸŽฏ **Four critical time-based KPIs:** MTTD, MTTR, MTTA, Dwell Time +* ๐Ÿ“Š **Track trends:** Are we getting faster? + +```mermaid +flowchart LR + Incident[๐Ÿšจ Security Issue
Occurs] -->|MTTD| Detect[๐Ÿ” Detected] + Detect -->|MTTA| Acknowledge[๐Ÿ‘€ Acknowledged] + Acknowledge -->|MTTR| Resolve[โœ… Resolved] + + Incident -.->|Dwell Time| Resolve + + style Incident fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + style Detect fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + style Acknowledge fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + style Resolve fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 +``` + +--- + +### ๐Ÿ” MTTD (Mean Time to Detect) + +* ๐ŸŽฏ **Definition:** Average time from issue occurrence โ†’ detection +* ๐Ÿ“Š **Formula:** Sum of detection times / Number of incidents +* โฐ **Industry benchmark:** + * **Best-in-class:** < 1 hour + * **Good:** < 24 hours + * **Average:** 24-72 hours + * **Poor:** > 1 week +* ๐Ÿ”‘ **Improvements:** + * Continuous scanning (not scheduled) + * Real-time alerting (not daily reports) + * Automated detection (no manual review) + * Better tooling (reduce false negatives) + +**Why it matters:** +* โฐ Faster detection = smaller blast radius +* ๐Ÿ’ฐ Every hour counts (cost escalates quickly) +* ๐ŸŽฏ Measure effectiveness of monitoring + +--- + +### โšก MTTR (Mean Time to Respond/Resolve) + +* ๐ŸŽฏ **Definition:** Average time from detection โ†’ resolution +* ๐Ÿ“Š **Formula:** Sum of resolution times / Number of incidents +* โฐ **SLAs by severity:** + +| Severity | Target MTTR | Example | +|----------|-------------|---------| +| ๐Ÿ”ด **Critical** | < 24 hours | Remote code execution in production | +| ๐ŸŸ  **High** | < 7 days | SQL injection in API | +| ๐ŸŸก **Medium** | < 30 days | Outdated library with CVE | +| ๐ŸŸข **Low** | < 90 days | Info disclosure, low impact | + +* ๐Ÿ”‘ **Improvements:** + * Automated remediation (Dependabot, auto-patching) + * Prioritization (fix critical first) + * Clear ownership (who fixes what) + * Runbooks (standardized procedures) + +**Why it matters:** +* โฐ Faster fixes = lower risk exposure +* ๐Ÿ“Š Measure team responsiveness +* ๐ŸŽฏ SLA compliance + +--- + +### ๐Ÿ‘€ MTTA (Mean Time to Acknowledge) + +* ๐ŸŽฏ **Definition:** Average time from detection โ†’ someone starts working on it +* ๐Ÿ“Š **Formula:** Sum of acknowledgment times / Number of incidents +* โฐ **Target:** < 1 hour for critical issues +* ๐Ÿ”‘ **Improvements:** + * Clear escalation paths (who's on-call?) + * Good alerting (right person, right channel) + * Reduce alert fatigue (fewer false positives) + * Incident response playbooks + +**Why it matters:** +* โฐ Shows organizational responsiveness +* ๐Ÿ“Š Identifies process bottlenecks (alerts ignored?) +* ๐Ÿšจ High MTTA = alerts not working + +--- + +### ๐Ÿ•ต๏ธ Dwell Time (Attacker Dwell Time) + +* ๐ŸŽฏ **Definition:** Time from initial compromise โ†’ detection +* โฐ **Industry benchmarks:** + * **2024 average:** 16 days (IBM) + * **Ransomware:** 5-7 days + * **Nation-state:** 200+ days (SolarWinds = 9 months) +* ๐Ÿ”ฅ **Why critical:** + * Longer dwell time = more damage + * Attackers establish persistence + * Data exfiltration happens slowly +* ๐Ÿ”‘ **Improvements:** + * Runtime monitoring (detect anomalies) + * Deception technology (honeypots) + * Behavioral analysis (unusual patterns) + * Threat hunting (proactive search) + +```mermaid +flowchart LR + Compromise[๐Ÿ’€ Initial
Compromise] -.->|Dwell Time| Detection[๐Ÿ” Detection] + + Compromise -->|Days 1-7| Recon[๐Ÿ•ต๏ธ Reconnaissance] + Recon -->|Days 8-14| Lateral[๐Ÿ”„ Lateral Movement] + Lateral -->|Days 15+| Exfil[๐Ÿ“ค Data Exfiltration] + + Detection -->|Stop| Response[โšก Incident Response] + + style Compromise fill:#b71c1c,stroke:#d32f2f,stroke-width:3px,color:#fff + style Exfil fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + style Detection fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 +``` + +--- + +### ๐Ÿ“Š Time-Based KPI Dashboard Example + +**Tracking over time:** + +| Metric | Q1 2024 | Q2 2024 | Target | Trend | +|--------|---------|---------|--------|-------| +| **MTTD** | 48 hrs | 24 hrs | < 24 hrs | ๐Ÿ“‰ Improving | +| **MTTA** | 2 hrs | 1.5 hrs | < 1 hr | ๐Ÿ“‰ Improving | +| **MTTR (Critical)** | 5 days | 3 days | < 2 days | ๐Ÿ“‰ Improving | +| **MTTR (High)** | 15 days | 12 days | < 7 days | ๐Ÿ“‰ Improving | +| **Dwell Time** | 21 days | 18 days | < 10 days | ๐Ÿ“‰ Improving | + +โœ… **All metrics improving** โ†’ Security program maturing + +
+๐Ÿ’ญ Discussion: What's more important - MTTD or MTTR? + +**It depends on context!** + +**MTTD matters more when:** +* ๐Ÿšจ Active breaches (every minute counts) +* ๐Ÿƒโ€โ™‚๏ธ Fast-moving threats (ransomware, worms) +* ๐Ÿ’ฐ High-value targets (financial, healthcare) +* ๐Ÿ” You have good detection but slow response + +**MTTR matters more when:** +* ๐Ÿ“Š Known vulnerability backlog (need to clear it) +* ๐Ÿ”ง Complex remediation (patches, code changes) +* ๐Ÿ‘ฅ Limited team capacity (can't do everything) +* โšก You detect quickly but fix slowly + +**Best answer:** Both matter! +* ๐ŸŽฏ **MTTD** determines how long attacker has undetected +* ๐ŸŽฏ **MTTR** determines how long vulnerability exists after detection + +**Optimization strategy:** +1. First: Improve MTTD (detect threats faster) +2. Then: Improve MTTR (fix faster) +3. Continuously: Reduce both + +**Real-world priority:** +* Critical issues: MTTD < 1 hour, MTTR < 24 hours +* High issues: MTTD < 24 hours, MTTR < 7 days +
+ +--- + +## ๐Ÿ“ Slide 6 โ€“ ๐Ÿ“Š Program Health KPIs + +* ๐ŸŽฏ **Beyond time:** Other KPIs that measure security program effectiveness +* ๐Ÿ“ˆ **Categories:** Coverage, quality, compliance, efficiency + +```mermaid +flowchart LR + subgraph "๐Ÿ“Š Program Health KPIs" + Coverage[๐Ÿ“ Coverage
What % is secured?] + Quality[โœ… Quality
How good are results?] + Compliance[๐Ÿ“‹ Compliance
Meeting standards?] + Efficiency[โšก Efficiency
Cost vs value?] + end + + Coverage --> Health[๐ŸŽฏ Overall
Program Health] + Quality --> Health + Compliance --> Health + Efficiency --> Health + + style Health fill:#e8f5e8,stroke:#388e3c,stroke-width:3px,color:#2c3e50 +``` + +--- + +### ๐Ÿ“ Coverage Metrics + +* ๐ŸŽฏ **Security test coverage:** + * % of codebase scanned by SAST + * % of APIs tested by DAST + * % of dependencies scanned by SCA + * % of infrastructure scanned (IaC) +* **Target:** > 80% coverage +* **Blind spots:** Code without security testing = high risk + +**Formula:** +``` +Coverage = (Lines scanned / Total lines) ร— 100% +``` + +* ๐Ÿ“Š **Deployment security gate coverage:** + * % of deployments going through security gates + * % of services with automated security tests +* **Target:** 100% of production deployments + +--- + +### โœ… Quality Metrics + +* ๐ŸŽฏ **False positive rate:** + * % of alerts that are not real issues + * **Formula:** False positives / Total alerts ร— 100% + * **Target:** < 20% false positive rate + * **High FP rate:** Alert fatigue, ignored alerts + +* ๐Ÿ“Š **Deployment security gate pass rate:** + * % of builds passing security gates on first try + * **Low pass rate:** Quality issues, rushed code + * **High pass rate:** Good security practices + +* ๐Ÿ”„ **Vulnerability recurrence rate:** + * % of fixed vulnerabilities that reappear + * **Formula:** Recurring vulns / Total fixed ร— 100% + * **Target:** < 5% recurrence + * **High recurrence:** Root cause not addressed + +```mermaid +flowchart LR + Total[๐Ÿ“Š 1000 Alerts] --> FP[โŒ 300 False Positives] + Total --> TP[โœ… 700 True Positives] + + FP -.->|30% FP Rate| Problem[๐Ÿšจ Alert Fatigue] + TP -.->|70% TP Rate| Good[โœ… Actionable Alerts] + + style FP fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + style Problem fill:#ffcdd2,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + style TP fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 +``` + +--- + +### ๐Ÿ“‹ Compliance Metrics + +* ๐ŸŽฏ **Policy compliance rate:** + * % of deployments meeting security policies + * **Target:** > 95% compliance + * **Violations:** Track what policies are violated most + +* โฐ **Remediation SLA compliance:** + * % of vulnerabilities fixed within SLA + * **By severity:** Track separately (critical vs low) + * **Target:** 90% for critical, 80% for high + +* ๐Ÿ“Š **Audit findings:** + * Number of findings in compliance audits + * **Trend:** Should decrease over time + * **Severity:** Critical findings should be zero + +**Example tracking:** + +| Policy | Compliance Rate | Violations This Month | +|--------|----------------|-----------------------| +| No secrets in code | 98% | 12 | +| Container images signed | 95% | 34 | +| SBOM generated | 100% | 0 | +| Critical vulns < 24hr | 85% | 8 | + +--- + +### โšก Efficiency Metrics + +* ๐Ÿ’ฐ **Cost per vulnerability found:** + * Security tool costs / Vulnerabilities found + * **Lower is better** (but don't compromise coverage) + +* ๐Ÿ‘ฅ **Security team velocity:** + * Vulnerabilities triaged per week + * Vulnerabilities fixed per week + * **Trend matters:** Improving or stagnating? + +* ๐Ÿค– **Automation rate:** + * % of security tasks automated + * **Target:** > 70% automated + * **Manual work:** Should be for high-value activities + +* ๐Ÿ“Š **Mean time between failures (MTBF):** + * Average time between security incidents + * **Higher is better** (fewer incidents) + +--- + +### ๐ŸŽฏ Vulnerability-Specific Metrics + +**Covered in Lecture 10, but related:** + +* ๐Ÿ“Š **Vulnerability backlog:** + * Total open vulnerabilities (trend) + * By severity (critical, high, medium, low) + * **Growing backlog:** Problem + +* โฐ **Vulnerability age:** + * Average age of open vulnerabilities + * **Critical vulns:** Should be < 7 days old + * **Old vulns:** Technical debt + +* ๐Ÿ“ˆ **Vulnerability introduction rate:** + * New vulnerabilities found per sprint/release + * **High rate:** Quality issues + * **Trend:** Should stabilize or decrease + +* ๐Ÿ“‰ **Vulnerability fix rate:** + * Vulnerabilities fixed per sprint/release + * **Should exceed introduction rate** + +```mermaid +flowchart LR + Intro[โž• Introduction Rate
100 vulns/month] --> Backlog{๐Ÿ“Š Backlog} + Fix[โž– Fix Rate
80 vulns/month] --> Backlog + + Backlog -->|Growing| Problem[๐Ÿšจ +20 vulns/month
Backlog growing] + + Improve[โšก Improve Fix Rate
120 vulns/month] --> Backlog2{๐Ÿ“Š Backlog} + Intro --> Backlog2 + Backlog2 -->|Shrinking| Good[โœ… -20 vulns/month
Improving] + + style Problem fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + style Good fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 +``` + +
+๐Ÿ’ญ Pro Tip: Balance quantity and quality metrics + +**Common mistake:** Focus only on quantity +* โŒ "We fixed 500 vulnerabilities this quarter!" +* โ“ But were they the right ones? Were they actually fixed? Did new ones appear? + +**Better approach:** Combine metrics +* โœ… Fixed 500 vulnerabilities (quantity) +* โœ… 90% were High/Critical (quality) +* โœ… Recurrence rate < 5% (sustainability) +* โœ… Backlog decreased 20% (progress) + +**Dashboard structure:** + +**Quantity metrics:** +* Total vulnerabilities found/fixed +* Scan coverage +* Tests run + +**Quality metrics:** +* False positive rate +* Recurrence rate +* SLA compliance + +**Impact metrics:** +* MTTR by severity +* Backlog trend +* Risk score trend + +**All three together = complete picture** +
+ +--- + +## ๐Ÿ“ Slide 7 โ€“ ๐Ÿ’ป Hands-On: Building Security Dashboards + +* ๐ŸŽฏ **Goal:** Turn metrics into visual insights +* ๐Ÿ“Š **Audience matters:** Different dashboards for different roles +* ๐Ÿ› ๏ธ **Tools:** Grafana, Kibana, Datadog (covered in Slide 3) + +```mermaid +flowchart LR + Data[๐Ÿ—„๏ธ Security Data
Scanners, CI/CD, SIEM] --> Dashboards{๐Ÿ“Š Dashboards} + + Dashboards --> Executive[๐Ÿ‘” Executive
High-level, risk] + Dashboards --> Manager[๐Ÿ‘จโ€๐Ÿ’ผ Manager
Team metrics, SLAs] + Dashboards --> Engineer[๐Ÿ‘จโ€๐Ÿ’ป Engineer
Actionable details] + + style Data fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + style Dashboards fill:#e3f2fd,stroke:#1976d2,stroke-width:3px,color:#2c3e50 +``` + +--- + +### ๐Ÿ‘” Executive Dashboard + +**Purpose:** At-a-glance security posture + +**Key elements:** +* ๐ŸŽฏ **Risk score trend** (improving or degrading?) +* ๐Ÿ“Š **Critical vulnerability count** (must be near zero) +* โฐ **MTTR for critical issues** (meeting SLAs?) +* ๐Ÿ“‹ **Compliance status** (red/yellow/green) +* ๐Ÿ’ฐ **Security incidents this quarter** (count and cost) +* ๐Ÿ“ˆ **Trend lines** (quarter-over-quarter comparison) + +**Design principles:** +* ๐Ÿšฆ Red/Yellow/Green indicators (traffic light) +* ๐Ÿ“‰ Simple trend lines (up/down arrows) +* ๐Ÿ”ข Big numbers (easy to read from distance) +* โฑ๏ธ Updated daily (no stale data) + +**Avoid:** +* โŒ Too many metrics (< 8 KPIs) +* โŒ Technical jargon (use business language) +* โŒ Detailed vulnerability lists + +--- + +### ๐Ÿ‘จโ€๐Ÿ’ผ Manager Dashboard + +**Purpose:** Team performance and SLA tracking + +**Key elements:** +* โฐ **Time-based KPIs:** MTTD, MTTR, MTTA by team +* ๐Ÿ“Š **Backlog by severity:** Trend over time +* ๐Ÿ“‹ **SLA compliance:** % meeting targets +* ๐Ÿ‘ฅ **Team velocity:** Vulns fixed per sprint +* ๐Ÿ”„ **Deployment gate metrics:** Pass/fail rates +* ๐Ÿšจ **Alert volume:** Are alerts actionable? + +**Design principles:** +* ๐Ÿ“… Weekly/monthly views (operational timeframe) +* ๐Ÿ“Š Comparison charts (team vs team, sprint vs sprint) +* ๐ŸŽฏ Threshold indicators (SLA targets marked) +* ๐Ÿ” Drill-down capability (click for details) + +--- + +### ๐Ÿ‘จโ€๐Ÿ’ป Engineer Dashboard + +**Purpose:** Actionable vulnerability details + +**Key elements:** +* ๐Ÿšจ **My assigned vulnerabilities:** Sorted by severity +* โฐ **Age indicators:** How old is each issue? +* ๐Ÿ“Š **Source:** Which scanner found it? +* ๐Ÿ”ง **Remediation guidance:** How to fix +* ๐Ÿ“ˆ **Trend for my services:** Getting better or worse? +* ๐Ÿ”„ **Recent scans:** Latest results + +**Design principles:** +* โœ… Actionable (click to open ticket/PR) +* ๐ŸŽฏ Filtered view (only relevant to me) +* ๐Ÿ”” Real-time updates (no refresh needed) +* ๐Ÿ“ฑ Mobile-friendly (view on the go) + +**Avoid:** +* โŒ Aggregated metrics (too high-level) +* โŒ Historical data (focus on current) + +--- + +### ๐ŸŽจ Dashboard Design Best Practices + +**Layout:** +* ๐Ÿ“ **F-pattern:** Most important top-left +* ๐ŸŽฏ **Grouping:** Related metrics together +* ๐ŸŒˆ **Color coding:** Consistent (red = bad, green = good) +* โšก **Performance:** Load in < 2 seconds + +**Visualization types:** + +| Metric Type | Best Visualization | +|-------------|-------------------| +| **Single value** | Gauge, big number | +| **Trend over time** | Line chart, area chart | +| **Comparison** | Bar chart, column chart | +| **Distribution** | Histogram, pie chart | +| **Status** | Table, heatmap | + +**Refresh rates:** +* ๐Ÿ”ด **Critical dashboards:** Real-time (< 1 min) +* ๐ŸŸก **Operational:** Every 5-15 minutes +* ๐ŸŸข **Strategic:** Daily + +--- + +### ๐Ÿ› ๏ธ Data Sources for Dashboards + +**Common integrations:** + +* ๐Ÿ” **Vulnerability scanners:** + * Snyk, Trivy, Grype (via API) + * DefectDojo (centralized) + +* ๐Ÿ”„ **CI/CD systems:** + * GitHub Actions (workflow runs) + * GitLab CI (pipeline status) + * Jenkins (build metrics) + +* โ˜๏ธ **Cloud providers:** + * AWS Security Hub + * Azure Defender + * GCP Security Command Center + +* ๐Ÿ“Š **SIEM platforms:** + * Splunk, ELK (query APIs) + +* ๐Ÿ“‹ **Issue trackers:** + * Jira, GitHub Issues (vulnerability tickets) + +**Data collection methods:** +* ๐Ÿ”Œ **Direct API:** Query tools directly +* ๐Ÿ“ค **Push model:** Tools send data to dashboard +* ๐Ÿ—„๏ธ **Data warehouse:** Centralized metrics database (recommended) + +--- + +### ๐Ÿ“Š Example Grafana Setup + +**Architecture:** + +```mermaid +flowchart LR + Scanners[๐Ÿ” Security Scanners] -->|Metrics| Prometheus[๐Ÿ“Š Prometheus] + CICD[๐Ÿ”„ CI/CD] -->|Logs| Loki[๐Ÿ“ Loki] + SIEM[๐Ÿ›ก๏ธ SIEM] -->|Alerts| Prometheus + + Prometheus --> Grafana[๐Ÿ“ˆ Grafana] + Loki --> Grafana + + Grafana --> Dashboard1[๐Ÿ‘” Executive] + Grafana --> Dashboard2[๐Ÿ‘จโ€๐Ÿ’ผ Manager] + Grafana --> Dashboard3[๐Ÿ‘จโ€๐Ÿ’ป Engineer] + + style Grafana fill:#e3f2fd,stroke:#1976d2,stroke-width:3px,color:#2c3e50 +``` + +**Prometheus exporters:** +* ๐Ÿ” Custom exporters for security tools +* ๐Ÿ“Š Metrics: vulnerability counts, scan durations, MTTR +* โฐ Scrape interval: 30-60 seconds + +**Grafana panels:** +* ๐Ÿ“ˆ Time-series (MTTR trend) +* ๐Ÿ“Š Bar gauge (vulnerability counts by severity) +* ๐ŸŽฏ Stat panel (big numbers with thresholds) +* ๐Ÿ“‹ Table (vulnerability list) + +--- + +### ๐Ÿš€ Implementation Roadmap + +**Week 1: Foundation** +* โœ… Define key metrics (5-10 KPIs) +* โœ… Identify data sources +* โœ… Set up Grafana/Kibana + +**Week 2: Data Collection** +* โœ… Connect data sources +* โœ… Create Prometheus exporters (if needed) +* โœ… Validate data accuracy + +**Week 3: Dashboard Development** +* โœ… Build executive dashboard +* โœ… Build manager dashboard +* โœ… Build engineer dashboard + +**Week 4: Rollout** +* โœ… Share dashboards with teams +* โœ… Gather feedback +* โœ… Iterate and improve + +**Ongoing:** +* ๐Ÿ”„ Weekly review of metrics +* ๐Ÿ“Š Monthly dashboard tuning +* ๐ŸŽฏ Quarterly metric review (add/remove KPIs) + +
+๐Ÿ’ญ Common Mistakes to Avoid + +**1. Too many metrics (dashboard clutter)** +* โŒ 50 metrics on one dashboard +* โœ… 5-8 key metrics per dashboard + +**2. No context (numbers without meaning)** +* โŒ "45 vulnerabilities" +* โœ… "45 vulnerabilities (down from 60 last week)" + +**3. Stale data (nobody trusts it)** +* โŒ Updated weekly +* โœ… Updated hourly/daily + +**4. One dashboard for everyone** +* โŒ Same view for CEO and engineer +* โœ… Different dashboards for different roles + +**5. No actionability (pretty but useless)** +* โŒ Can only view metrics +* โœ… Click to drill down, create tickets, investigate + +**6. Ignoring mobile (everyone has phones)** +* โŒ Only works on desktop +* โœ… Responsive design + +**7. No alerting (passive monitoring)** +* โŒ Must check dashboard manually +* โœ… Alerts sent to Slack/email when thresholds crossed + +**Remember:** Dashboard is a tool, not a goal. Focus on driving decisions, not pretty charts. +
+ +--- + +## ๐ŸŽ‰ Fun Break: "When Metrics Go Wrong" + +### ๐Ÿ“Š Goodhart's Law: The Cobra Effect + +**The Original "Cobra Effect" (Delhi, British India):** +* ๐Ÿ Problem: Too many cobras in Delhi +* ๐Ÿ’ก Solution: Government pays bounty for dead cobras +* ๐ŸŽฏ Result: People start breeding cobras to kill for bounty +* ๐Ÿ’ฅ Outcome: More cobras than before! + +**Security Metrics Edition:** + +**Metric:** "Number of vulnerabilities fixed per month" +* ๐ŸŽฏ **Target:** Increase fixes to 500/month +* ๐Ÿ“Š **Result:** Team fixes hundreds of "info" severity issues, ignores critical ones +* ๐Ÿ’ฅ **Outcome:** Dashboard looks green, critical vulns unfixed for months + +**Metric:** "100% test coverage" +* ๐ŸŽฏ **Target:** All code must have tests +* ๐Ÿ“Š **Result:** Developers write meaningless tests that always pass +* ๐Ÿ’ฅ **Outcome:** 100% coverage, 0% actual security validation + +**Metric:** "Zero security gate failures" +* ๐ŸŽฏ **Target:** All builds pass security gates +* ๐Ÿ“Š **Result:** Teams lower security gate thresholds or disable checks +* ๐Ÿ’ฅ **Outcome:** Green pipelines, vulnerable code in production + +**Metric:** "Reduce security incidents to zero" +* ๐ŸŽฏ **Target:** No incidents reported +* ๐Ÿ“Š **Result:** Teams stop reporting incidents (bad for career) +* ๐Ÿ’ฅ **Outcome:** Zero reported incidents, many unreported breaches + +```mermaid +flowchart LR + Metric[๐Ÿ“Š Metric Becomes
Performance Target] --> Gaming[๐ŸŽฎ Gaming Begins] + Gaming --> Manipulate[๐ŸŽญ Manipulate Numbers
Not Behavior] + Manipulate --> Useless[โŒ Metric Becomes
Useless] + + style Metric fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + style Gaming fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + style Useless fill:#ffebee,stroke:#d32f2f,stroke-width:3px,color:#2c3e50 +``` + +--- + +### ๐Ÿ›ก๏ธ How to Prevent Gaming + +**1. Use multiple metrics (can't game them all)** +* โœ… Vulnerabilities fixed + MTTR + recurrence rate +* โŒ Just count of vulnerabilities fixed + +**2. Focus on outcomes, not activities** +* โœ… Reduction in production incidents +* โŒ Number of security scans run + +**3. Measure what you can't easily manipulate** +* โœ… Customer-reported security issues +* โŒ Self-reported compliance scores + +**4. Regular audits** +* โœ… Sample vulnerabilities to verify fixes are real +* โœ… Review code to verify tests are meaningful + +**5. Qualitative + quantitative** +* โœ… Metrics + peer reviews + incident retrospectives +* โŒ Metrics alone + +**6. Transparent goals** +* โœ… "Improve security posture" (outcome) +* โŒ "Hit these exact numbers" (output) + +--- + +### ๐Ÿ’ก Real-World Gaming Examples + +**Case 1: The "False Positive" Epidemic** +* ๐ŸŽฏ Metric: Reduce open vulnerability count +* ๐ŸŽฎ Gaming: Mark everything as "false positive" or "won't fix" +* ๐Ÿ“Š Dashboard: 95% vulnerabilities resolved! +* ๐Ÿ’ฅ Reality: Nothing actually fixed, just hidden + +**Case 2: The Test Coverage Illusion** +* ๐ŸŽฏ Metric: 80% code coverage required +* ๐ŸŽฎ Gaming: Write tests that call functions but assert nothing +* ๐Ÿ“Š Dashboard: 85% coverage achieved! +* ๐Ÿ’ฅ Reality: Tests pass even with vulnerabilities + +**Case 3: The Quick Fix Trap** +* ๐ŸŽฏ Metric: MTTR < 24 hours for critical +* ๐ŸŽฎ Gaming: Mark critical as "mitigated" (not actually fixed), downgrade severity +* ๐Ÿ“Š Dashboard: 100% SLA compliance! +* ๐Ÿ’ฅ Reality: Critical vulnerabilities still exploitable + +**Lessons:** +* ๐ŸŽฏ Metrics should help, not hurt +* ๐Ÿ‘๏ธ Trust but verify +* ๐Ÿ”„ Continuously refine metrics +* ๐Ÿง  Use judgment, not just dashboards + +--- + +### ๐Ÿค” The Right Way to Use Metrics + +**Metrics are:** +* โœ… Conversation starters (not conversation enders) +* โœ… Indicators (not absolute truth) +* โœ… Tools for improvement (not punishment) + +**Metrics are NOT:** +* โŒ Performance review scores +* โŒ Targets to hit at all costs +* โŒ Replacement for judgment + +**Golden rule:** "If a metric becomes a target, prepare to change the metric" + +--- + +๐Ÿ”— **Resources for Group 2:** +* [SANS Security Metrics Guide](https://www.sans.org/white-papers/55/) +* [OWASP Security Metrics](https://owasp.org/www-community/Security_Metrics) +* [Google SRE Book - Monitoring](https://sre.google/sre-book/monitoring-distributed-systems/) +* [Grafana Dashboards](https://grafana.com/grafana/dashboards/) +* [IBM Cost of Data Breach Report](https://www.ibm.com/security/data-breach) +* [Goodhart's Law Explained](https://en.wikipedia.org/wiki/Goodhart%27s_law) + +--- +## ๐Ÿ“‚ Group 3: Compliance Frameworks + +## ๐Ÿ“ Slide 8 โ€“ โš–๏ธ Compliance Basics for Developers + +* โš–๏ธ **Compliance** = meeting legal/regulatory requirements +* ๐Ÿ’ฐ **Non-compliance cost:** Fines (โ‚ฌ20M+), lawsuits, lost business +* ๐Ÿ”‘ **Key insight:** Compliance โ‰  security (overlap ~70%) +* ๐ŸŽฏ **Compliance:** Minimum baseline (point-in-time audits) +* ๐Ÿ›ก๏ธ **Security:** Continuous improvement (real-time protection) + +```mermaid +flowchart LR + Security[๐Ÿ›ก๏ธ Security] --> Overlap[๐ŸŽฏ 70% Overlap] + Compliance[โš–๏ธ Compliance] --> Overlap + + Overlap --> Common[Encryption
Access control
Vulnerability mgmt] + + style Overlap fill:#fff3e0,stroke:#f57c00,stroke-width:3px,color:#2c3e50 +``` + +**Developer responsibilities:** +* ๐Ÿ” Encrypt sensitive data (at rest, in transit) +* ๐Ÿ”‘ Access control (authentication, authorization) +* ๐Ÿ“‹ Audit logs (who accessed what) +* ๐Ÿ—‘๏ธ Data deletion (GDPR "right to be forgotten") +* ๐Ÿšจ Breach notification (within 72 hours) + +--- + +## ๐Ÿ“ Slide 9 โ€“ ๐Ÿ‡ช๐Ÿ‡บ GDPR Essentials + +* ๐Ÿ‡ช๐Ÿ‡บ **GDPR:** EU data privacy regulation (applies globally if you have EU users) +* ๐Ÿ’ฐ **Penalty:** โ‚ฌ20M or 4% revenue (whichever higher) +* ๐Ÿ“… **Effective:** May 2018 + +**Key principles:** +* ๐Ÿ“Š Data minimization (collect only what's needed) +* ๐Ÿ” Privacy by design (build privacy in from start) +* โฐ Storage limitation (don't keep forever) +* โœ… User consent (explicit opt-in) + +**User rights (must implement):** +* ๐Ÿ“ฅ Right to access (export my data) +* โœ๏ธ Right to rectification (correct my data) +* ๐Ÿ—‘๏ธ Right to erasure (delete my data) +* ๐Ÿ“ค Right to portability (transfer my data) + +**Technical requirements:** +* ๐Ÿ”’ Encryption mandatory (at rest, in transit) +* ๐Ÿ“‹ Audit logs (track all access) +* ๐Ÿšจ Breach notification within 72 hours +* ๐Ÿ”— [GDPR Official](https://gdpr.eu/) + +--- + +## ๐Ÿ“ Slide 10 โ€“ ๐Ÿ›๏ธ NIST Cybersecurity Framework + +* ๐Ÿ›๏ธ **NIST CSF:** US risk management framework (voluntary but widely adopted) +* ๐ŸŽฏ **5 Functions:** Identify โ†’ Protect โ†’ Detect โ†’ Respond โ†’ Recover + +```mermaid +flowchart LR + Identify[๐Ÿ” Identify
Assets & Risks] --> Protect[๐Ÿ›ก๏ธ Protect
Safeguards] + Protect --> Detect[๐Ÿ‘๏ธ Detect
Monitoring] + Detect --> Respond[โšก Respond
Incidents] + Respond --> Recover[๐Ÿ”„ Recover
Restore] + + style Identify fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + style Protect fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + style Detect fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#2c3e50 + style Respond fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + style Recover fill:#e1f5fe,stroke:#0288d1,stroke-width:2px,color:#2c3e50 +``` + +**DevSecOps mapping:** +* ๐Ÿ” Identify: SBOM, threat modeling, asset inventory +* ๐Ÿ›ก๏ธ Protect: SAST/DAST, IaC security, secrets management +* ๐Ÿ‘๏ธ Detect: Vulnerability scanning, SIEM, monitoring +* โšก Respond: Incident response, automated rollback +* ๐Ÿ”„ Recover: Backup/restore, disaster recovery + +* ๐Ÿ”— [NIST CSF](https://www.nist.gov/cyberframework) + +--- + +## ๐Ÿ“ Slide 11 โ€“ ๐ŸŒ ISO 27001 Basics + +* ๐ŸŒ **ISO 27001:** International standard for ISMS (Information Security Management System) +* ๐Ÿ† **Certification-based:** Requires external audit +* ๐Ÿ“‹ **Structure:** PDCA cycle (Plan-Do-Check-Act) + 93 security controls + +**Annex A domains (14 categories):** +* Access control, cryptography, operations security +* Secure development, supplier relationships, incident management + +**Certification timeline:** +* โฐ Preparation: 6-12 months +* ๐Ÿ’ฐ Cost: $15K-$50K +* ๐Ÿ”„ Renewal: Every 3 years + +**Why organizations pursue:** +* ๐Ÿค Customer trust (global recognition) +* ๐Ÿ’ผ Required for some contracts +* ๐ŸŒ Accepted worldwide + +* ๐Ÿ”— [ISO 27001](https://www.iso.org/isoiec-27001-information-security.html) + +--- + +## ๐Ÿ“ Slide 12 โ€“ ๐Ÿ’ณ Other Key Frameworks (Quick Overview) + +| Framework | Scope | Geography | Key Requirement | +|-----------|-------|-----------|-----------------| +| ๐Ÿ’ณ **PCI-DSS** | Payment cards | Global | Protect cardholder data, quarterly scans | +| ๐Ÿ“Š **SOC 2** | SaaS/Cloud | US | Trust Service Criteria (Security + optional) | +| ๐Ÿฅ **HIPAA** | Healthcare | US | Protect PHI, encryption, audit logs | +| ๐Ÿ›๏ธ **FedRAMP** | Federal cloud | US Gov | NIST 800-53 controls (12-18 months) | + +**Quick decision guide:** +* Accept credit cards โ†’ **PCI-DSS** (required) +* SaaS company, US customers โ†’ **SOC 2** +* Healthcare data โ†’ **HIPAA** (required) +* International sales โ†’ **ISO 27001** +* US government โ†’ **FedRAMP** + +--- + +## ๐ŸŽ‰ Fun Break: "The $746M Mistake" + +**Amazon's Record GDPR Fine (2021):** +* ๐ŸŽฏ Violation: Targeted advertising without proper consent +* ๐Ÿ’ฐ Fine: โ‚ฌ746M (largest ever) +* ๐Ÿค” Amazon: "We disagree" (still under appeal) + +**Meta's $1.2B Fine (2023):** +* ๐ŸŽฏ Violation: EU-US data transfers without safeguards +* ๐Ÿ˜ฑ Response: Threatened to leave Europe + +**Lessons:** +* โœ… Cookie consent must be real (reject as easy as accept) +* โœ… Data deletion must be permanent (not soft delete) +* โœ… Privacy policy must be clear (not legalese) +* โŒ Don't ignore regulators + +**Developer reality:** +* Before GDPR: `DELETE FROM users` +* After GDPR: 500 lines of cascade deletion code + +--- + +๐Ÿ”— **Resources for Group 3:** +* [GDPR Official](https://gdpr.eu/) +* [NIST CSF](https://www.nist.gov/cyberframework) +* [ISO 27001](https://www.iso.org/isoiec-27001-information-security.html) +* [PCI-DSS](https://www.pcisecuritystandards.org/) +* [SOC 2](https://www.aicpa.org/interestareas/frc/assuranceadvisoryservices/sorhome) + +--- +## ๐Ÿ“‚ Group 3: Compliance Frameworks + +## ๐Ÿ“ Slide 8 โ€“ โš–๏ธ Compliance Basics for Developers + +* โš–๏ธ **Compliance** = meeting legal, regulatory, and industry standards +* ๐ŸŽฏ **Why it matters:** Fines, lawsuits, lost business, reputation damage +* ๐Ÿ”‘ **Key insight:** Compliance โ‰  security (but ~70% overlap) + +```mermaid +flowchart LR + Security[๐Ÿ›ก๏ธ Security
Protect against threats] --> Overlap[๐ŸŽฏ Overlap 70%] + Compliance[โš–๏ธ Compliance
Meet regulations] --> Overlap + + Security --> Only1[๐Ÿ”’ Zero-days
APT protection] + Compliance --> Only2[๐Ÿ“‹ Audit logs
Process docs] + + Overlap --> Both[Encryption
Access control
Vulnerability mgmt] + + style Overlap fill:#fff3e0,stroke:#f57c00,stroke-width:3px,color:#2c3e50 +``` + +--- + +### ๐Ÿ’ฐ The Cost of Non-Compliance + +**Major penalties:** +* ๐Ÿ‡ช๐Ÿ‡บ **GDPR:** โ‚ฌ20M or 4% revenue (Amazon: โ‚ฌ746M fine) +* ๐Ÿ’ณ **PCI-DSS:** $500K/month +* ๐Ÿฅ **HIPAA:** $1.5M/year (Anthem: $16M settlement) + +**Beyond fines:** +* ๐Ÿ“‰ Stock price drop (avg 7.5% after breach) +* ๐Ÿค Customer churn (31% switch providers) +* ๐Ÿ’ผ Executive liability + +--- + +### ๐ŸŽฏ Compliance vs Security Differences + +| Aspect | Compliance | Security | +|--------|-----------|----------| +| **Goal** | Meet minimum standards | Protect against threats | +| **Timing** | Point-in-time (audits) | Continuous (real-time) | +| **Approach** | Checkbox (yes/no) | Risk-based (prioritize) | +| **Verification** | External auditors | Internal testing | +| **Focus** | Process + documentation | Technical controls | + +**Warning:** You can be compliant but insecure! +* โœ… Pass all compliance checks +* ๐Ÿšจ Still get breached (if only doing minimum) + +--- + +### ๐Ÿ‘จโ€๐Ÿ’ป Developer Responsibilities + +**What you must implement:** + +* ๐Ÿ” **Data protection:** + * Encrypt sensitive data (at rest + in transit) + * Use TLS 1.2+, AES-256 + +* ๐Ÿ”‘ **Access control:** + * Authentication (MFA for sensitive access) + * Authorization (RBAC, least privilege) + * Session management + +* ๐Ÿ“‹ **Audit logging:** + * Log security events (who, what, when) + * Tamper-proof logs (immutable) + * Retention (7+ years for some regulations) + +* ๐Ÿ—‘๏ธ **Data lifecycle:** + * Retention policies (keep for required time) + * Secure deletion (GDPR "right to be forgotten") + * Data minimization (collect only necessary) + +* ๐Ÿšจ **Breach response:** + * Detection mechanisms + * Notification workflows (72-hour deadline) + * Incident documentation + +--- + +### ๐Ÿค– Compliance Automation in DevSecOps + +**Shift-left compliance:** +* ๐Ÿ” Pre-commit: Secret scanning, license checks +* ๐Ÿ”„ CI/CD: Policy enforcement (OPA, Sentinel) +* ๐Ÿ“Š Runtime: Continuous compliance monitoring + +**Benefits:** +* โฐ Catch issues early (dev vs production) +* ๐Ÿ’ฐ Reduce audit costs (automated evidence) +* ๐Ÿ“ˆ Continuous compliance (not annual) + +* ๐Ÿ”— **Resources:** [GDPR Developer Guide](https://www.smashingmagazine.com/2017/07/privacy-by-design-framework/) + +
+๐Ÿ’ญ Common Question: "Do startups need compliance?" + +**YES, if you:** +* ๐ŸŒ Have EU users โ†’ GDPR (regardless of company location) +* ๐Ÿ’ณ Accept credit cards โ†’ PCI-DSS +* ๐Ÿฅ Handle health data โ†’ HIPAA +* ๐Ÿข Sell to enterprises โ†’ SOC 2 often required + +**Strategy:** +1. **Now:** Security best practices (encryption, access control) +2. **When customers ask:** Formal compliance programs +3. **For sales:** Certifications (ISO 27001, SOC 2) + +**Build compliance in from day 1** (cheaper than retrofitting) +
+ +--- + +## ๐Ÿ“ Slide 9 โ€“ ๐Ÿ‡ช๐Ÿ‡บ GDPR (General Data Protection Regulation) + +* ๐Ÿ‡ช๐Ÿ‡บ **GDPR:** EU regulation protecting citizen data privacy +* ๐Ÿ“… **Effective:** May 25, 2018 +* ๐ŸŒ **Applies to:** ANY company processing EU residents' data (global reach) +* ๐Ÿ’ฐ **Penalty:** โ‚ฌ20M or 4% global revenue (whichever higher) +* ๐ŸŽฏ **Core principle:** Privacy by design and by default +* ๐Ÿ”— **Learn more:** [GDPR Official](https://gdpr.eu/) + +```mermaid +flowchart LR + User[๐Ÿ‘ค EU Resident] -->|Personal data| Company[๐Ÿข Your Company
Anywhere in world] + Company -->|Must comply| GDPR[๐Ÿ‡ช๐Ÿ‡บ GDPR Requirements] + + GDPR --> Rights[โœ… User Rights] + GDPR --> Protection[๐Ÿ” Data Protection] + GDPR --> Breach[๐Ÿšจ 72h Notification] + + Violation[โŒ Violation] -->|โ‚ฌ20M or 4%| Fine[๐Ÿ’ฐ Penalties] + + style GDPR fill:#fff3e0,stroke:#f57c00,stroke-width:3px,color:#2c3e50 + style Fine fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 +``` + +--- + +### ๐Ÿ“‹ GDPR Key Principles + +* ๐ŸŽฏ **Lawfulness & transparency:** Clear privacy policy, no hidden collection +* ๐ŸŽฏ **Purpose limitation:** Use data only for stated purposes +* ๐ŸŽฏ **Data minimization:** Collect only what's necessary +* ๐ŸŽฏ **Accuracy:** Keep data up-to-date, allow corrections +* ๐ŸŽฏ **Storage limitation:** Delete after retention period +* ๐ŸŽฏ **Integrity & confidentiality:** Security measures mandatory + +--- + +### ๐Ÿ‘ค User Rights (Must Implement) + +**Technical implementations required:** + +* โœ… **Right to access:** Export user data (JSON/CSV format) +* โœ… **Right to rectification:** Edit profile/data functionality +* โœ… **Right to erasure:** Delete account + all data permanently +* โœ… **Right to portability:** Transfer data to competitor +* โœ… **Right to object:** Opt-out of processing (e.g., marketing) + +**Response time:** 30 days maximum + +```mermaid +flowchart LR + User[๐Ÿ‘ค User Request] --> Actions{๐Ÿ“‹ Required Actions} + + Actions --> Export[๐Ÿ“ค Export Data] + Actions --> Correct[โœ๏ธ Correct Data] + Actions --> Delete[๐Ÿ—‘๏ธ Delete Data] + + Delete --> Cascade[๐Ÿ”„ Cascade Delete
All tables] + Delete --> Backups[๐Ÿ’พ Remove from
Backups] + Delete --> Logs[๐Ÿ“‹ Anonymize
Audit logs] + + style Actions fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + style Delete fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 +``` + +--- + +### ๐Ÿ” Technical Requirements for Developers + +**1. Encryption (mandatory):** +* At rest: AES-256 for databases/files +* In transit: TLS 1.2+ for all connections +* Pseudonymization where possible + +**2. Access control:** +* RBAC with least privilege +* MFA for admin access +* Audit all PII access + +**3. Consent management:** +* Explicit opt-in (no pre-checked boxes) +* Granular consent (separate for each purpose) +* Easy withdrawal mechanism +* Log consent timestamps + +**4. Breach notification:** +* Detect breaches (monitoring + alerts) +* Notify DPA within 72 hours +* Notify users if high risk +* Document: what, when, impact, response + +--- + +### โฐ GDPR Breach Timeline + +```mermaid +flowchart LR + Breach[๐Ÿ’ฅ Breach] -->|0-24h| Assess[๐Ÿ” Assess
Impact] + Assess -->|24-48h| Contain[๐Ÿ›‘ Contain] + Contain -->|48-72h| Notify[๐Ÿ“ข Notify DPA] + + Assess -->|If high risk| Users[๐Ÿ‘ฅ Notify Users
Immediately] + + Notify -->|Late?| Fine[๐Ÿ’ฐ Penalty] + + style Breach fill:#ffebee,stroke:#d32f2f,stroke-width:3px,color:#2c3e50 + style Notify fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 +``` + +--- + +### โœ… GDPR Implementation Checklist + +**Development:** +* โ˜ Encrypt all PII (at rest + transit) +* โ˜ Implement user data export (machine-readable) +* โ˜ Implement permanent deletion (cascade all tables) +* โ˜ Consent management (opt-in/opt-out) +* โ˜ Access controls (RBAC + MFA) +* โ˜ Audit logging (track PII access) + +**Operations:** +* โ˜ Privacy policy published (plain language) +* โ˜ Cookie consent (if applicable) +* โ˜ Breach detection monitoring +* โ˜ Incident response plan +* โ˜ Data retention policy (auto-delete) + +
+๐Ÿ’ญ GDPR Myth: "Small companies are exempt" + +**FALSE:** GDPR applies to ALL companies with EU users + +**Reality:** +* โœ… Penalties may be lower for SMBs +* โœ… But compliance is still required +* โœ… DPAs consider: size, intent, cooperation + +**Example:** +* Small company ($1M revenue): โ‚ฌ40K fine (4% of revenue) +* Big Tech ($100B revenue): โ‚ฌ20M fine (capped) + +**Pro tip:** Build privacy in early, cheaper than retrofitting +
+ +--- + +## ๐Ÿ“ Slide 10 โ€“ ๐Ÿ›๏ธ NIST Cybersecurity Framework + +* ๐Ÿ›๏ธ **NIST CSF:** US framework for managing cybersecurity risk +* ๐Ÿ“… **Created:** 2014 (updated 2018, 2.0 in 2024) +* ๐ŸŽฏ **Voluntary** but widely adopted (especially US gov contractors) +* ๐Ÿ”‘ **Focus:** Risk management, not compliance checklist +* ๐Ÿ”— **Learn more:** [NIST CSF](https://www.nist.gov/cyberframework) + +```mermaid +flowchart LR + NIST[๐Ÿ›๏ธ NIST CSF] --> F1[๐Ÿ” Identify] + NIST --> F2[๐Ÿ›ก๏ธ Protect] + NIST --> F3[๐Ÿ‘๏ธ Detect] + NIST --> F4[โšก Respond] + NIST --> F5[๐Ÿ”„ Recover] + + style NIST fill:#e3f2fd,stroke:#1976d2,stroke-width:3px,color:#2c3e50 +``` + +--- + +### ๐Ÿ“‹ Five Functions + +**๐Ÿ” Identify:** Understand assets, risks, priorities +* Asset management (inventory systems, data) +* Risk assessment (threats, vulnerabilities) +* Supply chain (third-party risks) + +**๐Ÿ›ก๏ธ Protect:** Implement safeguards +* Access control (authentication, authorization) +* Data security (encryption, DLP) +* Secure SDLC (SAST/DAST) + +**๐Ÿ‘๏ธ Detect:** Find security events quickly +* Continuous monitoring (security events) +* Anomaly detection (baseline deviations) + +**โšก Respond:** Take action on incidents +* Response planning (IR procedures) +* Mitigation (contain, eliminate) +* Post-incident analysis (lessons learned) + +**๐Ÿ”„ Recover:** Restore services +* Recovery planning (restore operations) +* Improvements (update plans) + +--- + +### ๐Ÿ—บ๏ธ DevSecOps Mapping to NIST + +```mermaid +flowchart LR + subgraph DevSecOps + SBOM[๐Ÿ“‹ SBOM] + SAST[๐Ÿ” SAST/DAST] + Scan[๐Ÿ” Vuln Scanning] + IR[๐Ÿšจ Incident Response] + DR[๐Ÿ”„ DR Testing] + end + + SBOM --> Identify[๐Ÿ” Identify] + SAST --> Protect[๐Ÿ›ก๏ธ Protect] + Scan --> Detect[๐Ÿ‘๏ธ Detect] + IR --> Respond[โšก Respond] + DR --> Recover[๐Ÿ”„ Recover] + + style DevSecOps fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 +``` + +**Practical examples:** +* **Identify:** SBOM generation, asset inventory +* **Protect:** IaC security scanning, secret management +* **Detect:** SIEM integration, continuous scanning +* **Respond:** Automated rollback, blameless post-mortems +* **Recover:** Backup/restore testing, DR drills + +--- + +### ๐ŸŽฏ Implementation Tiers + +| Tier | Name | Characteristics | +|------|------|-----------------| +| **Tier 1** | Partial | Ad-hoc, reactive, no formal processes | +| **Tier 2** | Risk Informed | Policies exist, inconsistent implementation | +| **Tier 3** | Repeatable | Formal policies, regular updates | +| **Tier 4** | Adaptive | Continuous improvement, predictive | + +**Most organizations:** Tier 2-3 (Tier 4 is rare) + +
+๐Ÿ’ญ NIST CSF vs NIST SSDF + +**NIST CSF (Cybersecurity Framework):** +* ๐ŸŽฏ Scope: Entire organization +* ๐Ÿ‘” Audience: Executives, CISOs +* ๐Ÿ“‹ Structure: 5 functions + +**NIST SSDF (Secure Software Development):** +* ๐ŸŽฏ Scope: Software development only +* ๐Ÿ‘จโ€๐Ÿ’ป Audience: Developers, DevOps +* ๐Ÿ“‹ Structure: 4 practice groups +* ๐Ÿ”— Covered in: Lab 8 (supply chain) + +**Use both:** CSF for strategy, SSDF for tactics +
+ +--- + +## ๐Ÿ“ Slide 11 โ€“ ๐ŸŒ ISO 27001 Information Security Management + +* ๐ŸŒ **ISO 27001:** International standard for ISMS +* ๐Ÿ† **Certification-based:** Requires external audit +* ๐ŸŽฏ **Focus:** Process-driven security management +* ๐ŸŒ **Recognition:** Global (accepted worldwide) +* ๐Ÿ”— **Learn more:** [ISO 27001](https://www.iso.org/isoiec-27001-information-security.html) + +```mermaid +flowchart LR + Plan[๐Ÿ“‹ Plan
Risk assessment] --> Do[โš™๏ธ Do
Implement] + Do --> Check[๐Ÿ” Check
Audit] + Check --> Act[โšก Act
Improve] + Act --> Plan + + style Plan fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + style Do fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + style Check fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + style Act fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px,color:#2c3e50 +``` + +--- + +### ๐Ÿ“‹ Structure + +**Requirements (Clauses 4-10):** +* Context and leadership +* Risk assessment and treatment +* Implementation and operation +* Performance evaluation +* Continual improvement + +**Annex A: 93 Security Controls** +* 14 domains (choose based on risk assessment) +* Examples: Access control, cryptography, operations security, secure development + +--- + +### ๐Ÿ” Key Domains for Developers + +| Domain | Controls | DevSecOps Examples | +|--------|----------|-------------------| +| **Access Control** | Authentication, privileges | RBAC, MFA, IAM | +| **Cryptography** | Encryption, keys | TLS, secrets management | +| **Operations** | Change mgmt, backups | CI/CD, backup procedures | +| **Development** | Secure SDLC, testing | SAST/DAST, code review | +| **Suppliers** | Third-party security | Supply chain (Lab 8) | +| **Incidents** | Response procedures | IR playbooks | + +--- + +### ๐Ÿ† Certification Process + +```mermaid +flowchart LR + Gap[๐Ÿ“‹ Gap Analysis] --> Implement[โš™๏ธ Implement
6-12 months] + Implement --> Audit[๐Ÿ” External Audit] + Audit --> Cert{โœ… Pass?} + Cert -->|Yes| Certificate[๐ŸŽ–๏ธ Certificate] + Cert -->|No| Fix[๐Ÿ”ง Fix] + Fix --> Audit + + Certificate --> Annual[๐Ÿ”„ Annual
Surveillance] + Annual -.->|3 years| Recert[๐Ÿ”„ Recertify] + + style Certificate fill:#e8f5e8,stroke:#388e3c,stroke-width:3px,color:#2c3e50 +``` + +**Timeline & Cost:** +* โฐ Preparation: 6-12 months +* ๐Ÿ’ฐ Cost: $15K-$50K (audits + consulting) +* ๐Ÿ”„ Maintenance: Annual surveillance audits +* ๐Ÿ“… Renewal: Every 3 years + +--- + +### ๐Ÿ’ผ Why Organizations Pursue ISO 27001 + +**Benefits:** +* ๐Ÿค Customer trust (global recognition) +* ๐Ÿ’ผ Competitive advantage (required for some RFPs) +* ๐ŸŒ International sales (accepted in EU, Asia) +* ๐Ÿ“‹ Reduces audits (one cert vs many customer audits) + +**Not for everyone:** +* ๐Ÿ’ฐ Expensive for SMBs (consider SOC 2 instead) +* โฐ Time-consuming +* ๐Ÿ“‹ Bureaucratic overhead + +
+๐Ÿ’ญ ISO 27001 vs SOC 2 + +| Aspect | ISO 27001 | SOC 2 | +|--------|-----------|-------| +| **Recognition** | Global | Primarily US | +| **Certificate** | Yes | No (report only) | +| **Cost** | Higher ($15K-$50K) | Lower ($10K-$30K) | +| **Timeline** | 6-12 months | 3-6 months | +| **Best for** | International, EU sales | US SaaS companies | + +**Choose based on:** Customer requirements +
+ +--- + +## ๐Ÿ“ Slide 12 โ€“ ๐Ÿ’ณ Other Key Frameworks (Overview) + +### Quick Comparison + +| Framework | Applies When | Key Requirement | Penalty | +|-----------|-------------|-----------------|---------| +| ๐Ÿ’ณ **PCI-DSS** | Accept credit cards | Protect cardholder data | $500K/month | +| ๐Ÿ“Š **SOC 2** | SaaS provider | Trust Service Criteria | Lost sales | +| ๐Ÿฅ **HIPAA** | Healthcare data (US) | Protect PHI, encryption | $1.5M/year | +| ๐Ÿ›๏ธ **FedRAMP** | US gov cloud | NIST 800-53 controls | No access | + +--- + +### ๐Ÿ’ณ PCI-DSS (Payment Card Industry) + +**12 Requirements (grouped):** +* ๐Ÿ” Secure network (firewalls, no defaults) +* ๐Ÿ” Protect cardholder data (encrypt storage + transmission) +* ๐Ÿ” Vulnerability management (secure development, anti-virus) +* ๐Ÿ” Access control (restrict access, unique IDs) +* ๐Ÿ” Monitor networks (logs, testing) +* ๐Ÿ” Security policy (documented, maintained) + +**Developer focus:** +* Never store full card numbers (tokenize) +* Use payment gateway APIs +* Follow OWASP Top 10 + +--- + +### ๐Ÿ“Š SOC 2 (Service Organization Control) + +**Trust Service Criteria:** +* **Security** (required): Protection from unauthorized access +* **Availability** (optional): System uptime +* **Processing Integrity** (optional): Accurate processing +* **Confidentiality** (optional): Confidential data protected +* **Privacy** (optional): Personal info protected + +**Types:** +* **Type I:** Controls exist (point-in-time) +* **Type II:** Controls work over 6-12 months + +**Timeline:** 6-12 months, $10K-$30K + +--- + +### ๐Ÿฅ HIPAA (Healthcare - US) + +**Technical Safeguards:** +* ๐Ÿ”‘ Access control (unique IDs, auto-logoff) +* ๐Ÿ“‹ Audit logs (all PHI access tracked) +* ๐Ÿ” Encryption (PHI at rest + transit) +* ๐Ÿ”’ Integrity controls (prevent alteration) + +**Key:** BAA (Business Associate Agreement) required with vendors + +--- + +### ๐Ÿ›๏ธ FedRAMP (Federal Cloud - US) + +**Authorization Levels:** +* **Low:** Public data +* **Moderate:** CUI (most common) +* **High:** National security + +**Reality:** +* โฐ 12-18 months authorization +* ๐Ÿ’ฐ $100K-$500K cost +* ๐ŸŽฏ Only for US federal sales + +--- + +## ๐ŸŽ‰ Fun Break: "The โ‚ฌ746M Cookie" + +### ๐Ÿ’ฐ Biggest GDPR Fines + +**Top 3:** +1. **Amazon:** โ‚ฌ746M (2021) - Targeted ads without consent +2. **Meta:** โ‚ฌ1.2B (2023) - Illegal EU-US data transfers +3. **Google:** โ‚ฌ90M (2021) - Cookie consent dark patterns + +**Common violations:** +* ๐Ÿช Cookie reject harder than accept +* ๐Ÿ“ง Marketing without consent +* ๐Ÿ—‘๏ธ Not deleting data (soft delete โ‰  deleted) +* ๐Ÿ”“ Poor security (unencrypted databases) + +**Lessons:** +* โœ… Consent must be real (reject = easy as accept) +* โœ… Deletion must be permanent (overwrite data) +* โœ… Privacy policy must be clear (plain language) +* โœ… Cooperate with regulators (reduces fines) + +**Developer reality:** +* Before GDPR: `DELETE FROM users WHERE id = ?` +* After GDPR: 500 lines cascade deletion + backups + logs + +--- + +๐Ÿ”— **Resources for Group 3:** +* [GDPR Official](https://gdpr.eu/) +* [NIST CSF](https://www.nist.gov/cyberframework) +* [ISO 27001](https://www.iso.org/isoiec-27001-information-security.html) +* [PCI-DSS](https://www.pcisecuritystandards.org/) +* [SOC 2](https://www.aicpa.org/interestareas/frc/assuranceadvisoryservices/sorhome) +* [HIPAA Security Rule](https://www.hhs.gov/hipaa/for-professionals/security/index.html) + +--- + +## ๐Ÿ“‚ Group 4: Security Maturity Models + +## ๐Ÿ“ Slide 13 โ€“ ๐ŸŽฏ Security Maturity Model Concepts + +* ๐ŸŽฏ **Maturity model** = framework to assess and improve security practices +* ๐Ÿ“Š **Purpose:** Benchmark current state, plan improvements, track progress +* ๐Ÿ”‘ **Not compliance:** Maturity = continuous improvement, Compliance = pass/fail + +```mermaid +flowchart LR + Level0[๐Ÿ“Š Level 0
Ad-hoc] --> Level1[๐Ÿ“‹ Level 1
Initial] + Level1 --> Level2[โš™๏ธ Level 2
Managed] + Level2 --> Level3[๐ŸŽฏ Level 3
Defined] + Level3 --> Level4[๐Ÿ“ˆ Level 4
Measured] + Level4 --> Level5[๐Ÿ† Level 5
Optimized] + + style Level0 fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + style Level1 fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + style Level2 fill:#fff9c4,stroke:#fbc02d,stroke-width:2px,color:#2c3e50 + style Level3 fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + style Level4 fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + style Level5 fill:#1b5e20,stroke:#388e3c,stroke-width:3px,color:#fff +``` + +--- + +### ๐Ÿ“Š Typical Maturity Levels + +| Level | Name | Characteristics | Example | +|-------|------|-----------------|---------| +| **0** | Non-existent | No practices | No security testing | +| **1** | Initial/Ad-hoc | Reactive, inconsistent | Manual security reviews | +| **2** | Managed | Documented, repeatable | Some automated scans | +| **3** | Defined | Standardized, organization-wide | Security in all CI/CD | +| **4** | Measured | Quantified, metrics-driven | MTTR tracked, improving | +| **5** | Optimized | Continuous improvement, predictive | AI-driven, proactive | + +**Most organizations:** Level 2-3 (Level 5 is rare) + +--- + +### ๐ŸŽฏ Why Use Maturity Models? + +**Benefits:** +* ๐Ÿ“Š **Objective assessment:** Where are we now? +* ๐Ÿ—บ๏ธ **Roadmap planning:** Where should we go? +* ๐Ÿ“ˆ **Progress tracking:** Are we improving? +* ๐Ÿ’ผ **Executive communication:** Show maturity to leadership +* ๐Ÿค **Benchmarking:** Compare to industry peers + +**Use cases:** +* Gap analysis (what's missing?) +* Budget justification (why invest in security?) +* Team planning (prioritize improvements) +* Customer requirements (prove security maturity) + +--- + +### โš–๏ธ Maturity vs Compliance + +**Maturity Model:** +* ๐ŸŽฏ Goal: Continuous improvement +* ๐Ÿ“Š Focus: How well do you do things +* ๐Ÿ“ˆ Assessment: Levels 0-5 +* ๐Ÿ”„ Frequency: Ongoing self-assessment +* ๐Ÿ’ก Outcome: Improvement roadmap + +**Compliance:** +* ๐ŸŽฏ Goal: Meet minimum requirements +* ๐Ÿ“‹ Focus: Do you meet standards +* โœ… Assessment: Pass/fail +* ๐Ÿ“… Frequency: Annual/periodic audits +* ๐Ÿ† Outcome: Certificate/attestation + +**Both are important:** +* Compliance = floor (minimum) +* Maturity = ceiling (excellence) + +
+๐Ÿ’ญ Common Mistake: Focusing only on maturity level numbers + +**Wrong approach:** +* "We must reach Level 4 in all practices!" +* Spreads resources thin +* Level 4 everywhere = expensive + +**Right approach:** +* "We need Level 4 in critical areas, Level 2 in others" +* Focus on what matters most +* Risk-based prioritization + +**Example:** +* **Authentication:** Level 4 (critical) +* **Code signing:** Level 3 (important) +* **Security awareness:** Level 2 (basic) +* **Physical security:** Level 1 (cloud-native company) + +**Strategy:** Mature what matters, maintain minimum elsewhere +
+ +--- + +## ๐Ÿ“ Slide 14 โ€“ ๐Ÿฆ… OWASP SAMM (Software Assurance Maturity Model) + +* ๐Ÿฆ… **OWASP SAMM:** Framework for software security maturity +* ๐ŸŽฏ **Focus:** Software security practices (not entire org) +* ๐Ÿ“Š **Structure:** 5 business functions, 15 practices, 3 maturity levels +* ๐Ÿ†“ **Free:** Open-source model with tools +* ๐Ÿ”— **Learn more:** [OWASP SAMM](https://owaspsamm.org/) + +```mermaid +flowchart LR + SAMM[๐Ÿฆ… OWASP SAMM] --> Gov[๐Ÿ›๏ธ Governance] + SAMM --> Design[๐Ÿ“ Design] + SAMM --> Impl[โš™๏ธ Implementation] + SAMM --> Verif[โœ… Verification] + SAMM --> Ops[๐Ÿ”„ Operations] + + style SAMM fill:#e3f2fd,stroke:#1976d2,stroke-width:3px,color:#2c3e50 +``` + +--- + +### ๐Ÿ“‹ SAMM Structure: 5 Business Functions + +**๐Ÿ›๏ธ Governance:** +* Strategy & Metrics (define security goals) +* Policy & Compliance (document standards) +* Education & Guidance (train teams) + +**๐Ÿ“ Design:** +* Threat Assessment (identify risks) +* Security Requirements (define what's needed) +* Security Architecture (design secure systems) + +**โš™๏ธ Implementation:** +* Secure Build (build securely) +* Secure Deployment (deploy securely) +* Defect Management (track and fix) + +**โœ… Verification:** +* Architecture Analysis (review design) +* Requirements-driven Testing (test requirements) +* Security Testing (automated + manual) + +**๐Ÿ”„ Operations:** +* Incident Management (respond to incidents) +* Environment Management (secure infrastructure) +* Operational Enablement (support teams) + +--- + +### ๐Ÿ“Š Maturity Levels in SAMM + +**Each practice has 3 levels (0-3):** + +| Level | Description | Example: Security Testing | +|-------|-------------|---------------------------| +| **0** | No practice | No security testing | +| **1** | Initial | Manual security reviews, ad-hoc | +| **2** | Managed | Automated SAST/DAST in CI/CD | +| **3** | Defined | Comprehensive testing, metrics, continuous improvement | + +**Assessment result:** Scorecard showing current maturity per practice + +--- + +### ๐Ÿ—บ๏ธ SAMM Roadmap Generation + +**Process:** +1. **Current state:** Assess all 15 practices (self-assessment) +2. **Target state:** Define desired maturity (risk-based) +3. **Gap analysis:** Identify gaps (current vs target) +4. **Roadmap:** Prioritize improvements (phases) +5. **Implement:** Execute roadmap (quarterly iterations) +6. **Measure:** Track progress (re-assess regularly) + +```mermaid +flowchart LR + Assess[๐Ÿ“Š Assess
Current State] --> Target[๐ŸŽฏ Define
Target State] + Target --> Gap[๐Ÿ” Gap
Analysis] + Gap --> Roadmap[๐Ÿ—บ๏ธ Build
Roadmap] + Roadmap --> Implement[โš™๏ธ Implement
Improvements] + Implement --> Measure[๐Ÿ“ˆ Measure
Progress] + Measure -.->|Iterate| Assess + + style Roadmap fill:#e3f2fd,stroke:#1976d2,stroke-width:3px,color:#2c3e50 +``` + +--- + +### ๐ŸŽฏ SAMM for DevSecOps Teams + +**Most relevant practices:** + +| SAMM Practice | DevSecOps Mapping | +|---------------|-------------------| +| **Secure Build** | SAST/DAST in CI/CD, secret scanning | +| **Secure Deployment** | IaC security, container scanning | +| **Security Testing** | Automated security tests, DAST | +| **Defect Management** | Vulnerability tracking, MTTR | +| **Threat Assessment** | Threat modeling (Lab 2) | +| **Security Requirements** | Security stories, acceptance criteria | + +**Tool:** [SAMM Toolbox](https://owaspsamm.org/assessment/) (online self-assessment) + +
+๐Ÿ’ญ SAMM Quick Start: Where to begin? + +**Priority order for DevSecOps:** + +**Phase 1 (First 3 months):** +1. **Security Testing (Verification):** Add SAST/DAST to CI/CD +2. **Defect Management (Implementation):** Track vulnerabilities +3. **Secure Build (Implementation):** Secret scanning, dependency checks + +**Phase 2 (Months 4-6):** +4. **Secure Deployment (Implementation):** IaC scanning +5. **Threat Assessment (Design):** Basic threat modeling +6. **Strategy & Metrics (Governance):** Define security KPIs + +**Phase 3 (Months 7-12):** +7. **Security Requirements (Design):** Security in user stories +8. **Education & Guidance (Governance):** Security training +9. **Incident Management (Operations):** IR playbooks + +**Don't try to do everything at once!** Focus on high-impact, low-effort practices first. +
+ +--- + +## ๐Ÿ“ Slide 15 โ€“ ๐Ÿ“Š BSIMM (Building Security In Maturity Model) + +* ๐Ÿ“Š **BSIMM:** Data-driven maturity model (descriptive, not prescriptive) +* ๐Ÿข **Based on:** Real companies (120+ organizations studied) +* ๐ŸŽฏ **Shows:** What others are doing (not what you should do) +* ๐Ÿ“… **Updated:** Annually with new data +* ๐Ÿ”— **Learn more:** [BSIMM](https://www.bsimm.com/) + +**Key difference from SAMM:** +* SAMM: "Here's what to do" (prescriptive) +* BSIMM: "Here's what others do" (descriptive) + +--- + +### ๐Ÿ“‹ BSIMM Structure + +**4 Domains, 12 Practices:** + +**๐Ÿ›๏ธ Governance:** +* Strategy & Metrics +* Compliance & Policy +* Training + +**๐Ÿ“Š Intelligence:** +* Attack Models +* Security Features & Design +* Standards & Requirements + +**๐Ÿ”ง SSDL Touchpoints:** +* Architecture Analysis +* Code Review +* Security Testing + +**๐Ÿš€ Deployment:** +* Penetration Testing +* Software Environment +* Configuration Management & Vulnerability Management + +--- + +### ๐Ÿ“Š BSIMM Activities + +**Each practice has activities (119 total):** +* Classified by maturity level +* Shows prevalence (% of companies doing it) + +**Example: Code Review practice** +* **Level 1:** Ad-hoc code reviews (75% of companies) +* **Level 2:** Automated SAST in CI/CD (60%) +* **Level 3:** AI-assisted code review (25%) + +**Insight:** "If 60% of companies do X, maybe we should too" + +--- + +### ๐ŸŽฏ BSIMM vs SAMM Comparison + +| Aspect | BSIMM | SAMM | +|--------|-------|------| +| **Approach** | Descriptive (what others do) | Prescriptive (what to do) | +| **Data** | Real company data | Community best practices | +| **Cost** | Free (report) | Free (open-source) | +| **Updates** | Annual | Ongoing | +| **Best for** | Benchmarking | Improvement roadmap | +| **Use case** | "Are we behind peers?" | "How to improve?" | + +**Use both:** +* BSIMM: Benchmark against industry +* SAMM: Build improvement roadmap + +
+๐Ÿ’ญ BSIMM Insight: What top performers do differently + +**Top 10% of BSIMM companies:** + +**They do MORE of:** +* ๐Ÿค– Automation (CI/CD security fully automated) +* ๐Ÿ“Š Metrics (track everything, data-driven) +* ๐ŸŽ“ Training (regular security training for all) +* ๐Ÿ”„ Testing (multiple types: SAST, DAST, IAST, pentests) + +**They do LESS of:** +* ๐Ÿ“‹ Manual processes (minimal manual reviews) +* ๐ŸŽฏ Ad-hoc security (everything is systematic) +* ๐Ÿ”ฅ Firefighting (proactive, not reactive) + +**Key insight:** Maturity = automation + measurement + consistency +
+ +--- + +## ๐Ÿ“ Slide 16 โ€“ ๐Ÿš€ DevSecOps Maturity Assessment + +* ๐Ÿš€ **DevSecOps maturity:** Specific to DevSecOps practices +* ๐ŸŽฏ **Dimensions:** Culture, process, automation, technology +* ๐Ÿ“Š **Levels:** Similar to general maturity (0-5) + +```mermaid +flowchart LR + subgraph "๐Ÿš€ DevSecOps Maturity Dimensions" + Culture[๐Ÿ‘ฅ Culture &
Organization] + Process[๐Ÿ“‹ Process &
Governance] + Auto[๐Ÿค– Automation &
Integration] + Tech[๐Ÿ› ๏ธ Technology &
Tools] + end + + Culture --> Maturity[๐ŸŽฏ Overall
Maturity] + Process --> Maturity + Auto --> Maturity + Tech --> Maturity + + style Maturity fill:#e8f5e8,stroke:#388e3c,stroke-width:3px,color:#2c3e50 +``` + +--- + +### ๐Ÿ“Š Maturity Levels by Dimension + +**๐Ÿ‘ฅ Culture & Organization:** + +| Level | Characteristics | +|-------|-----------------| +| **1** | Security is afterthought, separate team | +| **2** | Security awareness growing, some collaboration | +| **3** | Security champions in teams, shared responsibility | +| **4** | Security embedded in culture, everyone owns it | +| **5** | Security as enabler, competitive advantage | + +**๐Ÿ“‹ Process & Governance:** + +| Level | Characteristics | +|-------|-----------------| +| **1** | No security processes, manual reviews | +| **2** | Basic security policies, ad-hoc reviews | +| **3** | Documented secure SDLC, consistent processes | +| **4** | Optimized processes, continuous improvement | +| **5** | Predictive, risk-adaptive processes | + +**๐Ÿค– Automation & Integration:** + +| Level | Characteristics | +|-------|-----------------| +| **1** | No automation, manual security tasks | +| **2** | Some automated scans (weekly/monthly) | +| **3** | Security in CI/CD, automated gates | +| **4** | Full automation, auto-remediation | +| **5** | AI-driven, self-healing systems | + +**๐Ÿ› ๏ธ Technology & Tools:** + +| Level | Characteristics | +|-------|-----------------| +| **1** | No security tools | +| **2** | Basic scanners (SAST or DAST) | +| **3** | Multiple tools (SAST, DAST, SCA, IaC) | +| **4** | Integrated platform, centralized dashboards | +| **5** | Unified observability, AI/ML-powered | + +--- + +### ๐ŸŽฏ Self-Assessment Exercise + +**Quick maturity check (answer for your organization):** + +**Culture:** +* โ“ Do developers view security as their responsibility? (Yes = Level 3+) +* โ“ Are there security champions in each team? (Yes = Level 3+) + +**Process:** +* โ“ Is secure SDLC documented and followed? (Yes = Level 3+) +* โ“ Are security requirements part of every user story? (Yes = Level 3+) + +**Automation:** +* โ“ Do all builds run security scans? (Yes = Level 3+) +* โ“ Are security gates automated in CI/CD? (Yes = Level 3+) + +**Technology:** +* โ“ Do you have SAST, DAST, and SCA? (Yes = Level 3+) +* โ“ Is vulnerability data centralized? (Yes = Level 3+) + +**Result:** +* Mostly No: Level 1-2 (building foundation) +* Half Yes: Level 2-3 (making progress) +* Mostly Yes: Level 3-4 (mature program) + +--- + +### ๐Ÿ—บ๏ธ Maturity Progression Path + +**Typical journey:** + +```mermaid +flowchart LR + Start[๐ŸŒฑ Level 1
6 months] --> L2[๐Ÿ“ˆ Level 2
6 months] + L2 --> L3[๐ŸŽฏ Level 3
12 months] + L3 --> L4[๐Ÿ† Level 4
18 months+] + + Start -.->|Tools| T1[Add SAST/DAST] + L2 -.->|Automation| T2[CI/CD integration] + L3 -.->|Culture| T3[Security champions] + L4 -.->|Optimization| T4[Metrics-driven] + + style Start fill:#fff3e0,stroke:#f57c00,stroke-width:2px,color:#2c3e50 + style L3 fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 + style L4 fill:#1b5e20,stroke:#388e3c,stroke-width:2px,color:#fff +``` + +**Timeline:** 2-3 years from Level 1 to Level 4 (realistic) + +--- + +### ๐Ÿ’ก Improvement Strategies by Current Level + +**If you're at Level 1:** +* ๐ŸŽฏ Focus: Add basic tooling (SAST, secret scanning) +* โฐ Timeline: 6 months to reach Level 2 +* ๐Ÿ’ฐ Investment: Tools + training + +**If you're at Level 2:** +* ๐ŸŽฏ Focus: Automate in CI/CD, add security gates +* โฐ Timeline: 6-12 months to reach Level 3 +* ๐Ÿ’ฐ Investment: CI/CD integration, process docs + +**If you're at Level 3:** +* ๐ŸŽฏ Focus: Metrics, culture, advanced automation +* โฐ Timeline: 12-18 months to reach Level 4 +* ๐Ÿ’ฐ Investment: Dashboards, training, optimization + +**If you're at Level 4:** +* ๐ŸŽฏ Focus: Innovation, predictive, AI/ML +* โฐ Timeline: Ongoing +* ๐Ÿ’ฐ Investment: R&D, advanced tools + +
+๐Ÿ’ญ Realistic Expectations: How long does maturity take? + +**Startup (< 50 people):** +* Year 1: Level 1 โ†’ Level 2 (tools + basics) +* Year 2: Level 2 โ†’ Level 3 (automation + process) +* Year 3+: Level 3 โ†’ Level 4 (maturity + culture) + +**Enterprise (1000+ people):** +* Year 1: Assess current state (varies by team) +* Year 2-3: Standardize across org (reach Level 3) +* Year 4+: Optimize and innovate (Level 4) + +**Key factors:** +* ๐Ÿ’ฐ Budget (tools, headcount) +* ๐Ÿ‘ฅ Leadership support (cultural change) +* ๐ŸŽ“ Team skills (training needed) +* ๐Ÿ“Š Starting point (Level 0 vs Level 2) + +**Don't rush:** Sustainable maturity > quick wins +
+ +--- + +## ๐Ÿ“‚ Group 5: Continuous Improvement + +## ๐Ÿ“ Slide 17 โ€“ ๐Ÿ”„ Feedback Loops & Security Improvement + +* ๐Ÿ”„ **Continuous improvement:** Core DevSecOps principle +* ๐Ÿ“Š **Feedback loops:** Measure โ†’ Analyze โ†’ Improve โ†’ Measure +* ๐ŸŽฏ **Goal:** Get better over time (security + speed) + +```mermaid +flowchart LR + Measure[๐Ÿ“Š Measure
Metrics, KPIs] --> Analyze[๐Ÿ” Analyze
Root causes] + Analyze --> Improve[โšก Improve
Fix, optimize] + Improve --> Validate[โœ… Validate
Did it work?] + Validate --> Measure + + style Measure fill:#e3f2fd,stroke:#1976d2,stroke-width:2px,color:#2c3e50 + style Improve fill:#e8f5e8,stroke:#388e3c,stroke-width:3px,color:#2c3e50 +``` + +--- + +### ๐Ÿ“Š Types of Feedback Loops + +**๐Ÿ”„ Short-term (daily/weekly):** +* Developer gets scan results in IDE +* PR blocked by security gate +* Alert triggers immediate investigation + +**๐Ÿ“… Medium-term (sprint/monthly):** +* Sprint retrospectives (security topics) +* Monthly security metrics review +* Vulnerability backlog trends + +**๐Ÿ“ˆ Long-term (quarterly/annual):** +* Maturity assessment (SAMM/BSIMM) +* Program effectiveness review +* Strategic adjustments + +--- + +### ๐Ÿšจ Post-Incident Reviews (Blameless Post-Mortems) + +**Purpose:** Learn from incidents without blame + +**Process:** +1. **Document:** What happened (timeline) +2. **Analyze:** Why it happened (root causes) +3. **Identify:** What could prevent recurrence +4. **Implement:** Action items (fix, improve) +5. **Share:** Lessons learned (org-wide) + +**Key rule:** No blame, focus on systems/process + +**Example questions:** +* ๐Ÿค” Why wasn't this caught in scanning? +* ๐Ÿค” Why did it take X days to detect? +* ๐Ÿค” What process failed? +* ๐Ÿค” How can we prevent this category? + +```mermaid +flowchart LR + Incident[๐Ÿšจ Security
Incident] --> Document[๐Ÿ“‹ Document
What happened] + Document --> RCA[๐Ÿ” Root Cause
Analysis] + RCA --> Actions[โšก Action Items
Fix, improve] + Actions --> Implement[โœ… Implement
Changes] + Implement --> Share[๐Ÿ“ข Share
Lessons Learned] + + Share -.->|Prevent| Future[๐Ÿ›ก๏ธ Future
Incidents] + + style Incident fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + style Implement fill:#e8f5e8,stroke:#388e3c,stroke-width:2px,color:#2c3e50 +``` + +--- + +### ๐Ÿ“ˆ Security Retrospectives + +**Sprint retrospective with security focus:** + +**What went well? ๐ŸŸข** +* All PRs passed security gates +* MTTR decreased from 5 to 3 days +* New SAST tool reduced false positives + +**What needs improvement? ๐ŸŸก** +* 3 critical vulnerabilities missed by scanners +* Manual secret scanning slowed deployment +* Security training attendance low + +**Action items: โšก** +* Add Grype for container scanning +* Automate secret scanning in pre-commit +* Make security training during work hours + +**Retrospective frequency:** Every sprint (2 weeks) + +--- + +### ๐ŸŽฏ Setting Improvement Goals (SMART) + +**Example goals:** + +**โŒ Vague goal:** "Improve security" + +**โœ… SMART goal:** "Reduce MTTR for critical vulnerabilities from 5 days to 2 days by Q3 2024" +* Specific: MTTR for critical vulns +* Measurable: 5 days โ†’ 2 days +* Achievable: 60% reduction +* Relevant: Lower risk exposure +* Time-bound: Q3 2024 + +**More examples:** +* "Increase security test coverage from 60% to 80% by Q2" +* "Achieve 100% automated security scans in CI/CD by Q4" +* "Reduce false positive rate from 30% to 15% in 6 months" + +--- + +### ๐Ÿ† Gamification & Security Champions + +**Security champions program:** +* ๐Ÿ‘ฅ One per team (volunteers) +* ๐ŸŽ“ Extra training (security experts) +* ๐Ÿค Liaison between security and dev teams +* ๐Ÿ“Š Track security metrics for their team + +**Gamification ideas:** +* ๐Ÿ† Leaderboards (most vulns fixed, fastest MTTR) +* ๐ŸŽ–๏ธ Badges (clean scans, security contributions) +* ๐ŸŽ Rewards (swag, recognition, bonuses) +* ๐ŸŽฎ CTF competitions (capture the flag) + +**Goal:** Make security engaging, not punishing + +
+๐Ÿ’ญ Warning: Gamification done wrong + +**Bad gamification:** +* ๐Ÿ† Reward quantity over quality (fix 100 low vulns, ignore critical) +* ๐Ÿ“Š Public shaming (worst team rankings) +* ๐Ÿ’ฐ High-stakes rewards (creates perverse incentives) + +**Good gamification:** +* ๐ŸŽฏ Reward meaningful metrics (MTTR, recurrence rate) +* ๐Ÿค Team-based, not individual (collaboration) +* ๐ŸŽ‰ Recognition, not just rewards (celebrate wins) +* ๐Ÿ“ˆ Progress tracking (improvement over time) + +**Remember:** Metrics + rewards = gaming risk (Goodhart's Law from Group 2!) +
+ +--- + +## ๐Ÿ“ Slide 18 โ€“ ๐Ÿค– Compliance as Code & Automation + +* ๐Ÿค– **Compliance as Code:** Automate compliance checks and evidence +* ๐ŸŽฏ **Goal:** Continuous compliance (not annual audits) +* ๐Ÿ“Š **Benefits:** Faster audits, reduced costs, always compliant + +```mermaid +flowchart LR + Traditional[๐Ÿ“‹ Traditional
Annual audit
Manual evidence] -->|Slow| Cost1[๐Ÿ’ฐ High cost
3-6 months prep] + + Automated[๐Ÿค– Compliance
as Code
Automated evidence] -->|Fast| Cost2[๐Ÿ’ฐ Low cost
Always ready] + + style Traditional fill:#ffebee,stroke:#d32f2f,stroke-width:2px,color:#2c3e50 + style Automated fill:#e8f5e8,stroke:#388e3c,stroke-width:3px,color:#2c3e50 +``` + +--- + +### ๐Ÿ“‹ Policy as Code Tools + +**Popular frameworks:** + +**๐ŸŽฏ Open Policy Agent (OPA):** +* Write policies in Rego language +* Enforce in CI/CD, Kubernetes, cloud +* Example: "Block deployments with critical vulns" + +**๐Ÿ”’ HashiCorp Sentinel:** +* Policy engine for Terraform +* Enforce before infrastructure changes +* Example: "Require encryption for all databases" + +**๐Ÿ› ๏ธ Cloud-specific:** +* AWS Config Rules (automated compliance checks) +* Azure Policy (enforce resource standards) +* GCP Organization Policy (centralized governance) + +--- + +### ๐Ÿค– Automated Compliance Checks + +**Examples:** + +**Infrastructure compliance:** +* All S3 buckets must be private (scan daily) +* All databases must be encrypted (enforce in IaC) +* No security groups with 0.0.0.0/0 (block in CI/CD) + +**Application compliance:** +* No secrets in code (pre-commit hook) +* All APIs require authentication (automated test) +* PII must be encrypted (data validation) + +**Operational compliance:** +* All logins logged (SIEM integration) +* Failed logins trigger alerts (automated) +* Logs retained for 7 years (automated retention) + +--- + +### ๐Ÿ“Š Automated Evidence Collection + +**Traditional audit:** +* ๐Ÿ“‹ Auditor: "Show me access control logs for Q2" +* ๐Ÿ‘จโ€๐Ÿ’ป You: "Let me dig through systems for 2 weeks..." + +**Automated audit:** +* ๐Ÿ“‹ Auditor: "Show me access control logs for Q2" +* ๐Ÿค– System: "Here's the automated report (generated in 5 seconds)" + +**What to automate:** +* ๐Ÿ“Š Security scan reports (daily) +* ๐Ÿ“‹ Policy compliance status (real-time dashboard) +* ๐Ÿ” Access logs (centralized, queryable) +* ๐Ÿ”„ Change logs (Git commits, deployments) +* ๐ŸŽ“ Training completion (automated tracking) + +```mermaid +flowchart LR + Systems[๐Ÿ’ป Systems &
Tools] -->|Automated| Evidence[๐Ÿ“Š Evidence
Repository] + + Evidence --> Report1[๐Ÿ“‹ SOC 2 Report] + Evidence --> Report2[๐Ÿ“‹ ISO 27001 Audit] + Evidence --> Report3[๐Ÿ“‹ PCI-DSS Scan] + Evidence --> Report4[๐Ÿ“‹ GDPR Compliance] + + style Evidence fill:#e3f2fd,stroke:#1976d2,stroke-width:3px,color:#2c3e50 +``` + +--- + +### ๐Ÿ”„ Continuous Compliance Monitoring + +**Shift from:** +* ๐Ÿ“… Annual audit (point-in-time snapshot) +* โœ… Pass or fail + +**Shift to:** +* ๐Ÿ“Š Continuous monitoring (real-time) +* ๐Ÿ“ˆ Trending compliance (always improving) + +**Implementation:** +* ๐Ÿ”„ Daily compliance scans (infrastructure, code) +* ๐Ÿ“Š Real-time dashboard (compliance status) +* ๐Ÿšจ Alerts on drift (unauthorized changes) +* ๐Ÿ“ˆ Trend analysis (improving or degrading?) + +**Benefits:** +* โœ… Always audit-ready +* โฐ Faster audit process (evidence ready) +* ๐Ÿ’ฐ Lower audit costs (less manual work) +* ๐Ÿ›ก๏ธ Catch issues faster (don't wait for annual audit) + +
+๐Ÿ’ญ Example: AWS Config for Continuous Compliance + +**AWS Config Rules (automated compliance):** + +**Rule 1: S3 buckets must be private** +* Check: Every hour +* Action: Alert if public bucket found +* Remediation: Auto-fix (set to private) + +**Rule 2: EC2 instances must have encryption** +* Check: On launch +* Action: Block if not encrypted +* Evidence: Report of all checks (automated) + +**Rule 3: IAM users must have MFA** +* Check: Daily +* Action: Alert if MFA disabled +* Evidence: Compliance dashboard (real-time) + +**Result:** +* Continuous compliance (not annual) +* Automated evidence (auditor-ready) +* Faster remediation (hours, not months) + +**Similar tools:** Azure Policy, GCP Organization Policy, Chef InSpec +
+ +--- + +๐Ÿ”— **Resources for Groups 4 & 5:** +* [OWASP SAMM](https://owaspsamm.org/) +* [BSIMM](https://www.bsimm.com/) +* [Open Policy Agent](https://www.openpolicyagent.org/) +* [AWS Config Rules](https://docs.aws.amazon.com/config/) +* [Chef InSpec](https://www.inspec.io/) +* [Toyota Production System](https://en.wikipedia.org/wiki/Toyota_Production_System) +* [Blameless Post-Mortems](https://sre.google/sre-book/postmortem-culture/) + +--- \ No newline at end of file