diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..f69f982 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,58 @@ +name: 'Continuous Integration' + +# Simple CI workflow to build and test the Java application +# This runs independently of CodeQL analysis + +on: + push: + branches: [ "main", "develop" ] + pull_request: + branches: [ "main" ] + +jobs: + build-and-test: + name: 'Build and Test' + runs-on: ubuntu-latest + + steps: + - name: 'Checkout code' + uses: actions/checkout@v4 + + - name: 'Set up Java 11' + uses: actions/setup-java@v4 + with: + java-version: '11' + distribution: 'temurin' + cache: 'maven' + + - name: 'Build application' + run: | + mvn clean compile + echo "✅ Application built successfully" + + - name: 'Run basic validation' + run: | + # Check that main classes were compiled + if [ -f "target/classes/com/example/demo/DemoApplication.class" ]; then + echo "✅ Main application class compiled" + else + echo "❌ Main application class not found" + exit 1 + fi + + if [ -f "target/classes/com/example/demo/VulnerableController.class" ]; then + echo "✅ Vulnerable controller compiled (contains security issues for demo)" + else + echo "❌ Vulnerable controller not found" + exit 1 + fi + + - name: 'Run tests' + run: | + mvn test + echo "✅ Tests completed successfully" + + - name: 'Package application' + run: | + mvn package -DskipTests + echo "✅ Application packaged successfully" \ No newline at end of file diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml new file mode 100644 index 0000000..34cacee --- /dev/null +++ b/.github/workflows/codeql-analysis.yml @@ -0,0 +1,113 @@ +name: 'CodeQL Security Analysis' + +# This workflow demonstrates how to call the reusable CodeQL workflow +# and pass custom query packs for enhanced security scanning. + +on: + # Trigger on pushes to main branch + push: + branches: [ "main", "develop" ] + + # Trigger on pull requests to main branch + pull_request: + branches: [ "main" ] + + # Allow manual triggering + workflow_dispatch: + inputs: + custom-query-packs: + description: 'Additional query packs to run (comma-separated)' + required: false + default: '' + query-suite: + description: 'Query suite to use' + required: false + default: 'security-extended' + type: choice + options: + - 'default' + - 'security-extended' + - 'security-and-quality' + build-mode: + description: 'Build mode to use' + required: false + default: 'none' + type: choice + options: + - 'none' + - 'autobuild' + - 'manual' + custom-build-command: + description: 'Custom build command (only used with manual build mode)' + required: false + default: '' + +# Set permissions for the workflow +permissions: + contents: read + security-events: write + actions: read + +jobs: + # Job 1: Standard CodeQL analysis with build mode "none" (default) + standard-analysis: + name: 'Standard Security Analysis (Build Mode: None)' + uses: ./.github/workflows/codeql-reusable.yml + with: + language: 'java' + #query-suite: 'security-extended' + # Specify additional query packs for more comprehensive analysis + # These packs focus on specific vulnerability types + query-packs: 'codeql/java-queries@1.8.0' + #query-suite: 'security-and-quality' + java-version: '11' + # Use default build mode "none" - no explicit build needed + build-mode: 'none' + # Pass secrets if needed (none required for this demo) + secrets: inherit + + # Job 2: Enhanced analysis with autobuild mode + #enhanced-analysis: + # name: 'Enhanced Security Analysis (Build Mode: Autobuild)' + # uses: ./.github/workflows/codeql-reusable.yml + # with: + # language: 'java' + # # Specify additional query packs for more comprehensive analysis + # # These packs focus on specific vulnerability types + # query-packs: 'codeql/java-queries:cwe-079,codeql/java-queries:cwe-089,codeql/java-queries:cwe-078' + # query-suite: 'security-and-quality' + # java-version: '11' + # # Use autobuild mode - let CodeQL automatically build the project + # build-mode: 'autobuild' + # secrets: inherit + + # Job 3: Manual build with custom build command + #manual-build-analysis: + # name: 'Manual Build Analysis (Build Mode: Manual)' + # uses: ./.github/workflows/codeql-reusable.yml + # with: + # language: 'java' + # query-packs: 'codeql/java-queries:cwe-079,codeql/java-queries:cwe-089' + # query-suite: 'security-extended' + # java-version: '11' + # # Use manual build mode with custom build command + # build-mode: 'manual' + # build-command: 'mvn clean compile -DskipTests -Dmaven.compiler.debug=true' + # secrets: inherit + + # Job 4: Manual trigger analysis (only runs on workflow_dispatch) + manual-analysis: + name: 'Manual Analysis with Custom Configuration' + if: github.event_name == 'workflow_dispatch' + uses: ./.github/workflows/codeql-reusable.yml + with: + language: 'java' + query-packs: ${{ github.event.inputs.custom-query-packs }} + query-suite: ${{ github.event.inputs.query-suite }} + java-version: '11' + # Use user-selected build mode + build-mode: ${{ github.event.inputs.build-mode }} + build-command: ${{ github.event.inputs.custom-build-command }} + # Enable debug logging for manual analysis to help with troubleshooting + debug-logging: true + secrets: inherit diff --git a/.github/workflows/codeql-reusable.yml b/.github/workflows/codeql-reusable.yml new file mode 100644 index 0000000..21ad59a --- /dev/null +++ b/.github/workflows/codeql-reusable.yml @@ -0,0 +1,167 @@ +name: 'CodeQL Analysis - Reusable Workflow' + +# This is a reusable workflow that performs CodeQL analysis on Java code. +# It accepts query pack suggestions as input parameters, allowing calling +# workflows to specify additional security queries to run beyond the defaults. +# +# Key Features: +# - Configurable build modes: "none" (default), "autobuild", or "manual" +# - Custom query pack support +# - Flexible build configuration +# - Debug logging options + +on: + workflow_call: + inputs: + # Language to analyze (default: java) + language: + description: 'Programming language to analyze' + required: false + type: string + default: 'java' + + # Query packs to use in addition to the default security queries + query-packs: + description: 'Comma-separated list of CodeQL query packs to use (e.g., "codeql/java-queries:cwe-079,codeql/java-queries:cwe-089")' + required: false + type: string + default: '' + + # Query suite to use (options: default, security-extended, security-and-quality) + query-suite: + description: 'CodeQL query suite to use' + required: false + type: string + default: 'security-extended' + + # Build mode configuration + build-mode: + description: 'CodeQL build mode: "none" (no build needed - fastest, recommended for Java/C#), "autobuild" (automatic detection), or "manual" (requires build-command)' + required: false + type: string + default: 'none' + + # Build command (only used when build-mode is "manual") + build-command: + description: 'Custom build command (only used when build-mode is "manual")' + required: false + type: string + default: '' + + # Java version to use + java-version: + description: 'Java version to use for build' + required: false + type: string + default: '11' + + # Debug logging toggle + debug-logging: + description: 'Enable verbose debug logging for troubleshooting' + required: false + type: boolean + default: false + +jobs: + codeql-analysis: + name: 'CodeQL Analysis' + runs-on: ubuntu-latest + + # Required permissions for CodeQL analysis + permissions: + actions: read + contents: read + security-events: write + + steps: + # Step 1: Checkout the repository code + - name: 'Checkout repository' + uses: actions/checkout@v4 + with: + # Fetch full history for better analysis + fetch-depth: 0 + + # Step 2: Set up Java environment + - name: 'Set up Java' + uses: actions/setup-java@v4 + with: + java-version: ${{ inputs.java-version }} + distribution: 'temurin' + cache: 'maven' + + # Step 2.5 : Debugging + #- name: Debugging + # run: | + # ls -al /opt/hostedtoolcache/CodeQL/2.23.1/x64/codeql/qlpacks/codeql/java-queries/1.8.0 + + # Step 3: Initialize CodeQL with specified configuration + - name: 'Initialize CodeQL' + uses: github/codeql-action/init@v3 + with: + languages: ${{ inputs.language }} + # Use the specified query suite + # I AM COMMENTING THIS OUT TO MAKE SURE IT ONLY USES MY PACK. THIS WILL BREAK OTHER THINGS THAT USE THIS PARAM + # ULTIMATELY I SHOULD UPDATE MY CODE TO HANDLE THE SCENARIO + # queries: ${{ inputs.query-suite }} + # Add query packs if specified + packs: ${{ inputs.query-packs }} + # Set build mode based on input parameter + build-mode: ${{ inputs.build-mode }} + env: + # Increase memory for CodeQL analysis + CODEQL_ACTION_EXTRA_OPTIONS: '{"database": {"interpret-results": {"max-paths": 4}}}' + + # Step 4: Build the application (only for manual build mode) + - name: 'Build application' + if: inputs.build-mode == 'manual' + run: | + if [ -n "${{ inputs.build-command }}" ]; then + echo "Using custom build command: ${{ inputs.build-command }}" + ${{ inputs.build-command }} + else + echo "Manual build mode selected but no build command provided, attempting auto-detection" + if [ -f "pom.xml" ]; then + echo "Detected Maven project - using default Maven build" + mvn clean compile -DskipTests + elif [ -f "build.gradle" ] || [ -f "build.gradle.kts" ]; then + echo "Detected Gradle project - using default Gradle build" + ./gradlew build -x test + else + echo "No recognized build file found - cannot build in manual mode" + exit 1 + fi + fi + + # Step 4b: Build note for other build modes + - name: 'Build mode information' + if: inputs.build-mode != 'manual' + run: | + if [ "${{ inputs.build-mode }}" == "none" ]; then + echo "Using build mode 'none' - CodeQL will analyze without building the project" + echo "This is recommended for compiled languages like Java and C# when source code analysis is sufficient" + elif [ "${{ inputs.build-mode }}" == "autobuild" ]; then + echo "Using build mode 'autobuild' - CodeQL will automatically detect and build the project" + fi + + # Step 5: Perform CodeQL Analysis + - name: 'Perform CodeQL Analysis' + uses: github/codeql-action/analyze@v3 + with: + # Upload results even if there are errors + upload: true + # Set analysis category for tracking + category: 'java-security-analysis' + env: + # Enable verbose logging for troubleshooting (configurable) + CODEQL_ACTION_DEBUG: ${{ inputs.debug-logging }} + + # Step 6: Upload analysis results as artifacts (optional) + - name: 'Upload CodeQL results' + uses: actions/upload-artifact@v4 + if: always() + with: + name: codeql-results-${{ inputs.language }} + path: | + ${{ runner.temp }}/codeql_databases/ + !${{ runner.temp }}/codeql_databases/**/*.zip + retention-days: 30 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..901890f --- /dev/null +++ b/.gitignore @@ -0,0 +1,42 @@ +# Maven build artifacts +target/ +pom.xml.tag +pom.xml.releaseBackup +pom.xml.versionsBackup +pom.xml.next +release.properties +dependency-reduced-pom.xml +buildNumber.properties +.mvn/timing.properties +.mvn/wrapper/maven-wrapper.jar + +# IDE files +.idea/ +*.iml +*.ipr +*.iws +.vscode/ +.settings/ +.project +.classpath + +# OS files +.DS_Store +Thumbs.db + +# Temporary files +*.tmp +*.temp +*.swp +*.swo +*~ + +# Logs +*.log +logs/ + +# Spring Boot +application-*.properties +application-*.yml +!application.properties +!application.yml \ No newline at end of file diff --git a/README.md b/README.md index 599a26e..589ca7e 100644 --- a/README.md +++ b/README.md @@ -1 +1,235 @@ -# coding-agent-example-codeql \ No newline at end of file +# CodeQL Reusable Workflow Demo + +This repository demonstrates how to use GitHub Advanced Security CodeQL Code Scanning with reusable workflows that accept query pack suggestions. It includes a Java application with intentional security vulnerabilities to showcase CodeQL's detection capabilities. + +## 🎯 Purpose + +This demo addresses a common scenario where teams want to: +- Use reusable workflows for CodeQL analysis across multiple repositories +- Pass custom query packs to enhance security scanning +- Maintain consistency in security analysis while allowing customization + +## 📁 Repository Structure + +``` +├── src/main/java/com/example/demo/ # Java application source code +│ ├── DemoApplication.java # Main Spring Boot application +│ ├── VulnerableController.java # REST controller with security vulnerabilities +│ └── DatabaseInitializer.java # Database setup component +├── src/main/resources/ +│ └── application.properties # Spring Boot configuration +├── .github/workflows/ +│ ├── codeql-reusable.yml # Reusable CodeQL workflow +│ ├── codeql-analysis.yml # Calling workflow with query pack examples +│ └── ci.yml # Basic CI workflow +├── examples/ +│ ├── custom-workflow.yml # Example organization-specific workflow +│ └── query-pack-examples.md # Query pack usage examples +├── pom.xml # Maven build configuration +└── README.md # This documentation +``` + +## 🔧 Components + +### Java Application +A simple Spring Boot web application that intentionally contains security vulnerabilities: + +- **SQL Injection (CWE-89)**: Direct string concatenation in SQL queries +- **Cross-Site Scripting (CWE-79)**: Unescaped user input in HTML output +- **Path Traversal (CWE-22)**: User input directly used in file paths +- **Command Injection (CWE-78)**: User input passed to system commands + +⚠️ **WARNING**: This application contains deliberate security vulnerabilities and should NEVER be deployed to production. + +### Reusable Workflow (`.github/workflows/codeql-reusable.yml`) + +A flexible, reusable workflow that: +- Accepts custom query packs as input parameters +- Supports different query suites (default, security-extended, security-and-quality) +- Handles Java project builds automatically (Maven/Gradle) +- Provides comprehensive error handling and logging +- Uploads analysis results as artifacts + +**Key Input Parameters:** +- `query-packs`: Comma-separated list of CodeQL query packs +- `query-suite`: CodeQL query suite to use +- `language`: Programming language (default: java) +- `java-version`: Java version for builds (default: 11) +- `build-mode`: CodeQL build mode - "none", "autobuild", or "manual" (default: "none") +- `build-command`: Custom build command (only used when build-mode is "manual") +- `debug-logging`: Enable verbose debug logging (default: false) + +### Calling Workflow (`.github/workflows/codeql-analysis.yml`) + +Demonstrates four different analysis approaches: +1. **Standard Analysis**: Basic security scanning using build mode "none" (default) +2. **Enhanced Analysis**: Additional query packs with autobuild mode +3. **Manual Build Analysis**: Custom build command with manual build mode +4. **Manual Analysis**: User-triggered analysis with configurable build mode + +### Build Modes + +The reusable workflow supports three different CodeQL build modes: + +#### Build Mode: "none" (Default, Recommended) +- **When to use**: For compiled languages like Java and C# when source code analysis is sufficient +- **Benefits**: Faster analysis, no build dependencies required +- **Example**: +```yaml +uses: ./.github/workflows/codeql-reusable.yml +with: + build-mode: 'none' # Default - no build needed +``` + +#### Build Mode: "autobuild" +- **When to use**: When you want CodeQL to automatically detect and build your project +- **Benefits**: Automatic build detection, good for most standard projects +- **Example**: +```yaml +uses: ./.github/workflows/codeql-reusable.yml +with: + build-mode: 'autobuild' # Let CodeQL build automatically +``` + +#### Build Mode: "manual" +- **When to use**: When you need specific build commands or custom build configurations +- **Benefits**: Full control over the build process +- **Example**: +```yaml +uses: ./.github/workflows/codeql-reusable.yml +with: + build-mode: 'manual' + build-command: 'mvn clean compile -DskipTests -Dmaven.compiler.debug=true' +``` + +## 🚀 Usage + +### Basic Usage + +The workflows will automatically run on: +- Pushes to `main` or `develop` branches +- Pull requests to `main` branch + +### Manual Triggering + +You can manually trigger enhanced analysis: + +1. Go to **Actions** tab in your GitHub repository +2. Select **CodeQL Security Analysis** workflow +3. Click **Run workflow** +4. Optionally specify custom query packs and suite + +### Custom Query Packs + +Examples of query pack specifications: + +```yaml +# Specific vulnerability types +query-packs: 'codeql/java-queries:cwe-079,codeql/java-queries:cwe-089' + +# Security and quality analysis +query-packs: 'codeql/java-queries:security,codeql/java-queries:quality' + +# Third-party query packs (if available) +query-packs: 'my-org/custom-security-queries,codeql/java-queries:cwe-078' +``` + +### Available Query Suites + +- `default`: Standard security queries +- `security-extended`: Enhanced security analysis (recommended) +- `security-and-quality`: Security + code quality analysis + +## 🔍 Expected CodeQL Findings + +When you run CodeQL analysis on this repository, you should see alerts for: + +1. **SQL Injection** in `VulnerableController.getUser()` and `searchUsers()` +2. **Cross-Site Scripting** in `VulnerableController.welcomeUser()` +3. **Path Traversal** in `VulnerableController.readFile()` +4. **Command Injection** in `VulnerableController.pingHost()` + +## 🛠️ Building Locally + +To build and run the application locally: + +```bash +# Build the application +mvn clean compile + +# Package the application +mvn package + +# Run the application (optional - contains vulnerabilities!) +mvn spring-boot:run +``` + +The application will start on `http://localhost:8080` with the following endpoints: +- `/api/users/{userId}` - SQL injection vulnerability +- `/api/search?name=` - SQL injection vulnerability +- `/api/welcome?username=` - XSS vulnerability +- `/api/files/{filename}` - Path traversal vulnerability +- `/api/ping?host=` - Command injection vulnerability + +## 📁 Example Files + +The `examples/` directory contains additional resources: + +- **`custom-workflow.yml`**: Example of how an organization might structure their CodeQL workflow with scheduled scans and different analysis levels +- **`query-pack-examples.md`**: Comprehensive guide to using different query packs, including built-in and custom options + +## 📚 Learning Resources + +### CodeQL Documentation +- [CodeQL Documentation](https://codeql.github.com/docs/) +- [CodeQL Query Packs](https://docs.github.com/en/code-security/codeql-cli/using-the-codeql-cli/publishing-and-using-codeql-packs) +- [GitHub Advanced Security](https://docs.github.com/en/get-started/learning-about-github/about-github-advanced-security) + +### Reusable Workflows +- [Reusing Workflows](https://docs.github.com/en/actions/using-workflows/reusing-workflows) +- [Workflow Syntax](https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions) + +## 🔧 Troubleshooting + +### Common Issues + +**Issue**: "Cannot find query pack" +- **Solution**: Ensure query pack names are correct and accessible to your repository +- **Check**: Verify the query pack exists in the CodeQL registry +- **Alternative**: Use built-in query suites instead of custom packs + +**Issue**: Build failures in reusable workflow +- **Solution**: Check the `build-command` parameter or ensure auto-detection works +- **Debug**: Enable verbose logging by setting `CODEQL_ACTION_DEBUG: true` + +**Issue**: No security alerts generated +- **Solution**: Verify the code contains detectable vulnerabilities +- **Check**: Ensure CodeQL is analyzing the correct language and files + +### Debugging Tips + +1. **Enable Debug Logging**: Set `debug-logging: true` when calling the reusable workflow +2. **Check Build Logs**: Review the "Build application" step for compilation errors +3. **Verify Query Packs**: Ensure specified query packs are publicly available +4. **Review Permissions**: Confirm the workflow has `security-events: write` permission + +## 🤝 Contributing + +This is a demonstration repository. If you find issues or have suggestions for improvement: + +1. Open an issue describing the problem or enhancement +2. Include steps to reproduce any issues +3. Provide context about your use case + +## ⚠️ Security Notice + +This repository contains intentionally vulnerable code for educational purposes. Do not: +- Deploy this application to production environments +- Use the vulnerable code patterns in real applications +- Expose this application to untrusted networks + +The vulnerabilities are designed to demonstrate CodeQL's detection capabilities and should be treated as examples of what NOT to do in secure coding practices. + +## 📄 License + +This project is provided as-is for educational and demonstration purposes. \ No newline at end of file diff --git a/examples/custom-workflow.yml b/examples/custom-workflow.yml new file mode 100644 index 0000000..3768892 --- /dev/null +++ b/examples/custom-workflow.yml @@ -0,0 +1,44 @@ +# Example: Custom workflow that calls the reusable CodeQL workflow +# with organization-specific query packs and configurations + +name: 'Organization CodeQL Analysis' + +on: + push: + branches: [ "main", "develop", "release/*" ] + pull_request: + branches: [ "main" ] + schedule: + # Run weekly security scans on Sundays at 2 AM UTC + - cron: '0 2 * * 0' + +jobs: + # Standard security analysis for all code changes + security-scan: + name: 'Security Analysis' + uses: ./.github/workflows/codeql-reusable.yml + with: + language: 'java' + query-suite: 'security-extended' + # Focus on critical security vulnerabilities + query-packs: 'codeql/java-queries:cwe-089,codeql/java-queries:cwe-079,codeql/java-queries:cwe-078' + java-version: '11' + # Use default build mode "none" for faster analysis + build-mode: 'none' + secrets: inherit + + # Comprehensive analysis (scheduled and manual only) + comprehensive-scan: + name: 'Comprehensive Analysis' + if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' + uses: ./.github/workflows/codeql-reusable.yml + with: + language: 'java' + query-suite: 'security-and-quality' + # Include broader set of queries for comprehensive analysis + query-packs: 'codeql/java-queries:security,codeql/java-queries:quality,codeql/java-queries:maintainability' + java-version: '11' + # Use manual build for more thorough analysis with custom build configuration + build-mode: 'manual' + build-command: 'mvn clean compile -DskipTests -Dmaven.compiler.debug=true -Dmaven.compiler.debuglevel=lines,vars,source' + secrets: inherit \ No newline at end of file diff --git a/examples/query-pack-examples.md b/examples/query-pack-examples.md new file mode 100644 index 0000000..3b8e901 --- /dev/null +++ b/examples/query-pack-examples.md @@ -0,0 +1,148 @@ +# CodeQL Query Pack Examples + +This document provides examples of commonly used CodeQL query packs that can be passed to the reusable workflow. + +## Built-in Query Packs + +### Security-Focused Packs + +```yaml +# SQL Injection queries +query-packs: 'codeql/java-queries:cwe-089' + +# Cross-Site Scripting queries +query-packs: 'codeql/java-queries:cwe-079' + +# Command Injection queries +query-packs: 'codeql/java-queries:cwe-078' + +# Path Traversal queries +query-packs: 'codeql/java-queries:cwe-022' + +# All OWASP Top 10 related queries +query-packs: 'codeql/java-queries:owasp-top10' +``` + +### Quality and Maintainability + +```yaml +# Code quality queries +query-packs: 'codeql/java-queries:quality' + +# Maintainability queries +query-packs: 'codeql/java-queries:maintainability' + +# Performance-related queries +query-packs: 'codeql/java-queries:performance' +``` + +### Combined Examples + +```yaml +# Security + Quality analysis +query-packs: 'codeql/java-queries:security,codeql/java-queries:quality' + +# Specific vulnerability types +query-packs: 'codeql/java-queries:cwe-079,codeql/java-queries:cwe-089,codeql/java-queries:cwe-078' + +# Comprehensive analysis +query-packs: 'codeql/java-queries:security,codeql/java-queries:quality,codeql/java-queries:maintainability' +``` + +## Custom Query Packs + +If your organization has custom query packs, you can specify them: + +```yaml +# Organization-specific pack +query-packs: 'my-org/security-queries' + +# Mix of custom and built-in packs +query-packs: 'my-org/security-queries,codeql/java-queries:cwe-089' + +# Version-specific packs +query-packs: 'my-org/security-queries@1.2.0,codeql/java-queries:security' +``` + +## Query Suites vs Query Packs + +**Query Suites** (use `query-suite` parameter): +- `default`: Standard security queries +- `security-extended`: Enhanced security analysis +- `security-and-quality`: Security + code quality + +**Query Packs** (use `query-packs` parameter): +- More granular control +- Can specify multiple packs +- Can target specific vulnerability types +- Can include custom organizational packs + +## Build Modes + +CodeQL supports different build modes for compiled languages: + +### Build Mode: "none" (Recommended Default) +```yaml +uses: ./.github/workflows/codeql-reusable.yml +with: + build-mode: 'none' +``` +- **Best for**: Java, C#, and other compiled languages +- **Performance**: Fastest analysis time +- **Use case**: Source code analysis without compilation +- **Dependencies**: No build tools required in the environment + +### Build Mode: "autobuild" +```yaml +uses: ./.github/workflows/codeql-reusable.yml +with: + build-mode: 'autobuild' +``` +- **Best for**: Standard projects with conventional build setups +- **Performance**: Moderate analysis time +- **Use case**: When CodeQL can automatically detect and build your project +- **Dependencies**: Build tools must be available in the environment + +### Build Mode: "manual" +```yaml +uses: ./.github/workflows/codeql-reusable.yml +with: + build-mode: 'manual' + build-command: 'mvn clean compile -DskipTests -Dmaven.compiler.debug=true' +``` +- **Best for**: Custom build configurations, complex projects +- **Performance**: Variable (depends on build complexity) +- **Use case**: When you need full control over the build process +- **Dependencies**: All build dependencies must be configured + +## Best Practices + +### Build Mode Selection +1. **Start with "none"**: For Java/C# projects, begin with build mode "none" +2. **Use "autobuild"**: If "none" doesn't provide sufficient analysis coverage +3. **Choose "manual"**: Only when you need specific build configurations +4. **Performance**: "none" > "autobuild" > "manual" in terms of speed + +### Query Pack Selection +1. **Start Simple**: Begin with `security-extended` suite +2. **Add Gradually**: Add specific query packs as needed +3. **Performance**: More queries = longer analysis time +4. **Relevance**: Choose packs relevant to your codebase +5. **Testing**: Test new query packs on smaller repositories first + +## Troubleshooting + +**Pack Not Found Error**: +- Verify pack name spelling +- Ensure pack is publicly available +- Check if authentication is required + +**Long Analysis Times**: +- Reduce number of query packs +- Use more specific packs instead of broad ones +- Consider running comprehensive analysis only on schedule + +**No Results**: +- Verify the code contains detectable issues +- Check if the pack targets the right language +- Review CodeQL analysis logs for errors \ No newline at end of file diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..e46b0f5 --- /dev/null +++ b/pom.xml @@ -0,0 +1,71 @@ + + + 4.0.0 + + com.example + codeql-demo + 1.0.0 + jar + + CodeQL Demo Application + A simple Java application with intentional security vulnerabilities for CodeQL demonstration + + + 11 + 11 + UTF-8 + + + + + + org.springframework.boot + spring-boot-starter-web + 2.7.0 + + + + + com.h2database + h2 + 2.1.214 + + + + + org.springframework.boot + spring-boot-starter-jdbc + 2.7.0 + + + + + org.springframework.boot + spring-boot-starter-test + 2.7.0 + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + 2.7.0 + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + 11 + 11 + + + + + \ No newline at end of file diff --git a/src/main/java/com/example/demo/DatabaseInitializer.java b/src/main/java/com/example/demo/DatabaseInitializer.java new file mode 100644 index 0000000..ec03d19 --- /dev/null +++ b/src/main/java/com/example/demo/DatabaseInitializer.java @@ -0,0 +1,54 @@ +package com.example.demo; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Component; + +import javax.annotation.PostConstruct; + +/** + * Component to initialize the database with sample data for demonstration. + * This creates a simple users table and populates it with test data. + */ +@Component +public class DatabaseInitializer { + + @Autowired + private JdbcTemplate jdbcTemplate; + + /** + * Initialize the database schema and sample data after bean construction + */ + @PostConstruct + public void initializeDatabase() { + try { + // Create users table + jdbcTemplate.execute( + "CREATE TABLE IF NOT EXISTS users (" + + "id INT PRIMARY KEY, " + + "name VARCHAR(255), " + + "email VARCHAR(255)" + + ")" + ); + + // Insert sample data + jdbcTemplate.update( + "INSERT INTO users (id, name, email) VALUES (?, ?, ?)", + 1, "John Doe", "john.doe@example.com" + ); + + jdbcTemplate.update( + "INSERT INTO users (id, name, email) VALUES (?, ?, ?)", + 2, "Jane Smith", "jane.smith@example.com" + ); + + jdbcTemplate.update( + "INSERT INTO users (id, name, email) VALUES (?, ?, ?)", + 3, "Bob Johnson", "bob.johnson@example.com" + ); + + } catch (Exception e) { + System.err.println("Error initializing database: " + e.getMessage()); + } + } +} \ No newline at end of file diff --git a/src/main/java/com/example/demo/DemoApplication.java b/src/main/java/com/example/demo/DemoApplication.java new file mode 100644 index 0000000..fc09836 --- /dev/null +++ b/src/main/java/com/example/demo/DemoApplication.java @@ -0,0 +1,17 @@ +package com.example.demo; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +/** + * Main application class for the CodeQL security demo. + * This application intentionally contains security vulnerabilities + * that will be detected by CodeQL scanning. + */ +@SpringBootApplication +public class DemoApplication { + + public static void main(String[] args) { + SpringApplication.run(DemoApplication.class, args); + } +} \ No newline at end of file diff --git a/src/main/java/com/example/demo/VulnerableController.java b/src/main/java/com/example/demo/VulnerableController.java new file mode 100644 index 0000000..d932bbb --- /dev/null +++ b/src/main/java/com/example/demo/VulnerableController.java @@ -0,0 +1,108 @@ +package com.example.demo; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.web.bind.annotation.*; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.PrintWriter; +import java.util.List; +import java.util.Map; + +/** + * REST Controller with intentional security vulnerabilities for CodeQL demonstration. + * + * WARNING: This code contains deliberate security vulnerabilities and should NEVER + * be used in production. It is designed solely for educational purposes to demonstrate + * how CodeQL can detect common security issues. + * + * Vulnerabilities included: + * 1. SQL Injection + * 2. Cross-Site Scripting (XSS) + * 3. Path Traversal + * 4. Command Injection + */ +@RestController +@RequestMapping("/api") +public class VulnerableController { + + @Autowired + private JdbcTemplate jdbcTemplate; + + /** + * SQL Injection vulnerability: Direct concatenation of user input into SQL query + * CodeQL should detect this as CWE-89: SQL Injection + */ + @GetMapping("/users/{userId}") + public List> getUser(@PathVariable String userId) { + // VULNERABLE: Direct string concatenation creates SQL injection risk + String sql = "SELECT * FROM users WHERE id = '" + userId + "'"; + return jdbcTemplate.queryForList(sql); + } + + /** + * Another SQL Injection vulnerability with search functionality + * CodeQL should detect this as CWE-89: SQL Injection + */ + @GetMapping("/search") + public List> searchUsers(@RequestParam String name) { + // VULNERABLE: User input directly embedded in SQL query + String sql = "SELECT * FROM users WHERE name LIKE '%" + name + "%'"; + return jdbcTemplate.queryForList(sql); + } + + /** + * Cross-Site Scripting (XSS) vulnerability + * CodeQL should detect this as CWE-79: Cross-site Scripting + */ + @GetMapping("/welcome") + public void welcomeUser(@RequestParam String username, HttpServletResponse response) + throws IOException { + response.setContentType("text/html"); + PrintWriter out = response.getWriter(); + + // VULNERABLE: User input directly written to HTML output without encoding + out.println(""); + out.println("

Welcome " + username + "!

"); + out.println(""); + } + + /** + * Path Traversal vulnerability + * CodeQL should detect this as CWE-22: Path Traversal + */ + @GetMapping("/files/{filename}") + public String readFile(@PathVariable String filename) { + try { + // VULNERABLE: User input used directly in file path + java.nio.file.Path path = java.nio.file.Paths.get("/app/data/" + filename); + return java.nio.file.Files.readString(path); + } catch (Exception e) { + return "Error reading file: " + e.getMessage(); + } + } + + /** + * Command Injection vulnerability + * CodeQL should detect this as CWE-78: Command Injection + */ + @GetMapping("/ping") + public String pingHost(@RequestParam String host) { + try { + // VULNERABLE: User input directly used in system command + Process process = Runtime.getRuntime().exec("ping -c 1 " + host); + java.io.BufferedReader reader = new java.io.BufferedReader( + new java.io.InputStreamReader(process.getInputStream())); + + StringBuilder result = new StringBuilder(); + String line; + while ((line = reader.readLine()) != null) { + result.append(line).append("\n"); + } + return result.toString(); + } catch (Exception e) { + return "Error executing ping: " + e.getMessage(); + } + } +} \ No newline at end of file diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties new file mode 100644 index 0000000..4a005f5 --- /dev/null +++ b/src/main/resources/application.properties @@ -0,0 +1,23 @@ +# Spring Boot Application Configuration for CodeQL Demo +# This configuration uses H2 in-memory database for simplicity + +# Server configuration +server.port=8080 + +# H2 Database configuration +spring.datasource.url=jdbc:h2:mem:testdb +spring.datasource.driver-class-name=org.h2.Driver +spring.datasource.username=sa +spring.datasource.password= + +# H2 Console (for debugging - should be disabled in production) +spring.h2.console.enabled=true +spring.h2.console.path=/h2-console + +# JPA/Hibernate configuration +spring.jpa.show-sql=true +spring.jpa.hibernate.ddl-auto=none + +# Logging configuration +logging.level.com.example.demo=DEBUG +logging.level.org.springframework.jdbc=DEBUG \ No newline at end of file diff --git a/src/test/java/com/example/demo/DemoApplicationTest.java b/src/test/java/com/example/demo/DemoApplicationTest.java new file mode 100644 index 0000000..a766f38 --- /dev/null +++ b/src/test/java/com/example/demo/DemoApplicationTest.java @@ -0,0 +1,34 @@ +package com.example.demo; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.TestPropertySource; + +/** + * Basic integration test to verify the Spring Boot application context loads correctly. + * This test ensures the application can start up without errors. + * + * Note: This application contains intentional security vulnerabilities for demonstration + * purposes. In real applications, you would have comprehensive security tests. + */ +@SpringBootTest +@TestPropertySource(properties = { + "spring.datasource.url=jdbc:h2:mem:testdb-test", + "logging.level.com.example.demo=WARN" +}) +class DemoApplicationTest { + + /** + * Test that the Spring Boot application context loads successfully. + * This verifies that: + * - All beans can be created + * - Database initialization works + * - No configuration errors exist + */ + @Test + void contextLoads() { + // Spring Boot will automatically verify the context loads + // If there are any issues with bean creation or configuration, + // this test will fail + } +} \ No newline at end of file