Skip to content

Conversation

Copy link

Copilot AI commented Sep 26, 2025

This PR creates a comprehensive demonstration of GitHub Advanced Security CodeQL Code Scanning using reusable workflows that accept custom query pack suggestions and support flexible build modes. This addresses scenarios where organizations want to standardize CodeQL analysis across repositories while allowing customization of security queries and build configurations.

Demo Components

Java Application with Security Vulnerabilities

Created a Spring Boot web application (src/main/java/com/example/demo/) that intentionally contains common security vulnerabilities for CodeQL to detect:

  • SQL Injection (CWE-89): Direct string concatenation in database queries
  • Cross-Site Scripting (CWE-79): Unescaped user input in HTML responses
  • Path Traversal (CWE-22): User-controlled file path access
  • Command Injection (CWE-78): User input passed to system commands
  • Error Message Exposure: Detailed error information leaked to users

The application includes REST endpoints that demonstrate each vulnerability type, along with database initialization and basic integration tests.

Reusable CodeQL Workflow with Build Mode Support

The reusable workflow (.github/workflows/codeql-reusable.yml) provides flexible CodeQL analysis capabilities with configurable build modes:

uses: ./.github/workflows/codeql-reusable.yml
with:
  query-packs: 'codeql/java-queries:cwe-079,codeql/java-queries:cwe-089'
  query-suite: 'security-extended'
  java-version: '11'
  build-mode: 'none'  # Default for compiled languages like Java/C#
  debug-logging: true

Key Features:

  • Accepts comma-separated query pack specifications
  • Supports multiple query suites (default, security-extended, security-and-quality)
  • Build Mode Options:
    • 'none' (default): No build required - fastest analysis, recommended for Java/C#
    • 'autobuild': Let CodeQL automatically detect and build the project
    • 'manual': Use custom build commands for full control
  • Configurable Java version and custom build commands
  • Optional debug logging for troubleshooting
  • Automatic Maven/Gradle project detection
  • Comprehensive error handling and artifact uploads

Calling Workflow Examples

The main workflow (.github/workflows/codeql-analysis.yml) demonstrates four different analysis approaches:

  1. Standard Analysis: Basic security scanning with build mode "none" (default)
  2. Enhanced Analysis: Additional query packs with autobuild mode
  3. Manual Build Analysis: Custom build commands with manual build mode
  4. Manual Analysis: User-triggered scans with configurable build mode selection

Documentation and Examples

  • README.md: Complete usage guide with build mode explanations, troubleshooting section and security warnings
  • examples/custom-workflow.yml: Organization-specific workflow template with scheduled scans and build mode examples
  • examples/query-pack-examples.md: Comprehensive guide to built-in and custom query packs, plus build mode best practices

Query Pack Integration

The solution demonstrates how to pass various query pack combinations:

# Specific vulnerability types
query-packs: 'codeql/java-queries:cwe-079,codeql/java-queries:cwe-089,codeql/java-queries:cwe-078'

# Broader security analysis  
query-packs: 'codeql/java-queries:security,codeql/java-queries:quality'

# Custom organizational packs
query-packs: 'my-org/security-queries,codeql/java-queries:owasp-top10'

Build Mode Configuration

The workflow supports three build modes for optimal performance and flexibility:

# Default: No build needed (fastest for compiled languages)
build-mode: 'none'

# Automatic build detection
build-mode: 'autobuild'

# Custom build commands
build-mode: 'manual'
build-command: 'mvn clean compile -DskipTests -Dmaven.compiler.debug=true'

Validation

CodeQL analysis successfully detects all 7 intentional security vulnerabilities in the demo application, confirming the effectiveness of the scanning configuration. The implementation follows GitHub Actions best practices with proper permissions, error handling, and artifact management.

⚠️ Security Notice: This application contains deliberate vulnerabilities for educational purposes and should never be deployed to production environments.

Fixes #1

Original prompt

This section details on the original issue you should resolve

<issue_title>Create a demo where CodeQL runs in a reusable workflow and accepts query pack suggestions</issue_title>
<issue_description>I'm working with a customer on using GitHub Advanced Security CodeQL Code Scanning. The customer has created a reusable workflow does the code scanning, that they then call from a workflow in the developer's repo.

My customer is saying that when they try and pass additional query packs into the reusable workflow, that it doesn't work, and it says it can't find the query packs. I have not seen their code yet so I can't verify this is happening.

So, I'd like you to help create me a demo of this scenario. The language we are using should be Java. I'll need you to do the following:

  • Create a simple java application. I don't know java, so don't make it too complex. But make sure it will throw at least a couple of CodeQL alerts.
  • Create a simple workflow file. That workflow file should just call the reusable workflow you are going to create that does teh CodeQL scanning
  • Create a reusable workflow that sets up the tooling, builds the code, and does the codeql scanning.
    • I want to be able to pass in the query packs that I want the code scanning to use into the reusable workflow
  • Make sure all the code is well documented
  • Create a README.md that describes all of what we are doing</issue_description>

Comments on the Issue (you are @copilot in this section)

Fixes #1

✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

Copilot AI and others added 2 commits September 26, 2025 13:29
Co-authored-by: mickeygousset <20031479+mickeygousset@users.noreply.github.com>
Co-authored-by: mickeygousset <20031479+mickeygousset@users.noreply.github.com>
Copilot AI changed the title [WIP] Create a demo where CodeQL runs in a reusable workflow and accepts query pack suggestions Create CodeQL demo with reusable workflow supporting query pack suggestions Sep 26, 2025
Copilot AI requested a review from mickeygousset September 26, 2025 13:41
Copilot finished work on behalf of mickeygousset September 26, 2025 13:41
@mickeygousset
Copy link
Contributor

@copilot

Can you modify the workflows to allow for the following functionality as well:

  • By default, if it is a language that supports build mode none (such as C# and Java, IIRC) it should use build mode none
  • However, I should have the option to override that to either pass in a build statement or use autobuild like you are doing now.

Can you help with this? And make sure to update the README appropriately of course, along with detailed documentation in all the files.

…ocumentation

Co-authored-by: mickeygousset <20031479+mickeygousset@users.noreply.github.com>
Copy link
Author

Copilot AI commented Sep 26, 2025

@copilot

Can you modify the workflows to allow for the following functionality as well:
...

I've implemented the build mode functionality you requested! The reusable workflow now supports three build modes:

Default: build-mode: 'none' - No build required, fastest analysis (recommended for Java/C#)
Override options:

  • build-mode: 'autobuild' - Let CodeQL automatically build
  • build-mode: 'manual' - Use custom build commands via build-command parameter

The calling workflow demonstrates all three modes, and I've updated the README and examples with comprehensive documentation. The manual trigger workflow also includes a dropdown to select build modes.

Commit: c31de54

Copilot AI changed the title Create CodeQL demo with reusable workflow supporting query pack suggestions Create CodeQL demo with reusable workflow supporting query pack suggestions and flexible build modes Sep 26, 2025
Copilot finished work on behalf of mickeygousset September 26, 2025 14:02
Comment out enhanced and manual build analysis jobs in CodeQL workflow.
@mickeygousset mickeygousset marked this pull request as ready for review September 26, 2025 14:11
Copy link
Contributor

@mickeygousset mickeygousset left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM :shipit:

@github-advanced-security
Copy link

This pull request sets up GitHub code scanning for this repository. Once the scans have completed and the checks have passed, the analysis results for this pull request branch will appear on this overview. Once you merge this pull request, the 'Security' tab will show more code scanning analysis results (for example, for the default branch). Depending on your configuration and choice of analysis tool, future pull requests will be annotated with code scanning analysis results. For more information about GitHub code scanning, check out the documentation.

public List<Map<String, Object>> getUser(@PathVariable String userId) {
// VULNERABLE: Direct string concatenation creates SQL injection risk
String sql = "SELECT * FROM users WHERE id = '" + userId + "'";
return jdbcTemplate.queryForList(sql);

Check failure

Code scanning / CodeQL

Query built from user-controlled sources High

This query depends on a
user-provided value
.

Copilot Autofix

AI about 1 month ago

To remediate the vulnerability, we should avoid direct concatenation of user input into the SQL query string. Instead, use parameterized/prepared queries to safely incorporate the user-supplied value. JdbcTemplate supports this via ? placeholders in the SQL, with the parameters supplied as arguments to queryForList. Change

String sql = "SELECT * FROM users WHERE id = '" + userId + "'";
return jdbcTemplate.queryForList(sql);

to

String sql = "SELECT * FROM users WHERE id = ?";
return jdbcTemplate.queryForList(sql, userId);

No imports or extra methods are needed. Only lines 40 and 41 need to be updated. This preserves existing functionality while removing the SQL Injection risk.


Suggested changeset 1
src/main/java/com/example/demo/VulnerableController.java

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/src/main/java/com/example/demo/VulnerableController.java b/src/main/java/com/example/demo/VulnerableController.java
--- a/src/main/java/com/example/demo/VulnerableController.java
+++ b/src/main/java/com/example/demo/VulnerableController.java
@@ -37,8 +37,8 @@
     @GetMapping("/users/{userId}")
     public List<Map<String, Object>> getUser(@PathVariable String userId) {
         // VULNERABLE: Direct string concatenation creates SQL injection risk
-        String sql = "SELECT * FROM users WHERE id = '" + userId + "'";
-        return jdbcTemplate.queryForList(sql);
+        String sql = "SELECT * FROM users WHERE id = ?";
+        return jdbcTemplate.queryForList(sql, userId);
     }
     
     /**
EOF
@@ -37,8 +37,8 @@
@GetMapping("/users/{userId}")
public List<Map<String, Object>> getUser(@PathVariable String userId) {
// VULNERABLE: Direct string concatenation creates SQL injection risk
String sql = "SELECT * FROM users WHERE id = '" + userId + "'";
return jdbcTemplate.queryForList(sql);
String sql = "SELECT * FROM users WHERE id = ?";
return jdbcTemplate.queryForList(sql, userId);
}

/**
Copilot is powered by AI and may make mistakes. Always verify output.
public List<Map<String, Object>> 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);

Check failure

Code scanning / CodeQL

Query built from user-controlled sources High

This query depends on a
user-provided value
.

Copilot Autofix

AI about 1 month ago

General fix strategy: Replace direct SQL query string concatenation with a parameterized (prepared) query using placeholders (?) and supply user input through query parameters. This safely escapes data and prevents malicious input from altering query structure.

Best fix:
In VulnerableController.java, within the searchUsers method, change the code to:

  • (1) Write the query string with a positional parameter: String sql = "SELECT * FROM users WHERE name LIKE ?".
  • (2) For the LIKE-pattern, construct the pattern as "%"+name+"%" outside the query string.
  • (3) Call jdbcTemplate.queryForList(sql, pattern) instead of passing only the SQL string.

No additional imports or methods are needed; all functionality required is already available via JdbcTemplate.

Only lines within the searchUsers method need changes.


Suggested changeset 1
src/main/java/com/example/demo/VulnerableController.java

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/src/main/java/com/example/demo/VulnerableController.java b/src/main/java/com/example/demo/VulnerableController.java
--- a/src/main/java/com/example/demo/VulnerableController.java
+++ b/src/main/java/com/example/demo/VulnerableController.java
@@ -47,9 +47,10 @@
      */
     @GetMapping("/search")
     public List<Map<String, Object>> 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);
+        // FIXED: Use parameterized query to prevent SQL Injection
+        String sql = "SELECT * FROM users WHERE name LIKE ?";
+        String pattern = "%" + name + "%";
+        return jdbcTemplate.queryForList(sql, pattern);
     }
     
     /**
EOF
@@ -47,9 +47,10 @@
*/
@GetMapping("/search")
public List<Map<String, Object>> 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);
// FIXED: Use parameterized query to prevent SQL Injection
String sql = "SELECT * FROM users WHERE name LIKE ?";
String pattern = "%" + name + "%";
return jdbcTemplate.queryForList(sql, pattern);
}

/**
Copilot is powered by AI and may make mistakes. Always verify output.

// VULNERABLE: User input directly written to HTML output without encoding
out.println("<html><body>");
out.println("<h1>Welcome " + username + "!</h1>");

Check warning

Code scanning / CodeQL

Cross-site scripting Medium

Cross-site scripting vulnerability due to a
user-provided value
.

Copilot Autofix

AI about 1 month ago

To fix the XSS vulnerability, user input should be properly HTML-encoded before it is included in the output. The most robust and simplest way is to escape special characters in the username (such as <, >, &, ", and ') so that any embedded HTML or scripts are displayed as plain text instead of being interpreted by the browser. In a Spring (Java) application, the Apache Commons Text library provides a convenient StringEscapeUtils.escapeHtml4 method for this purpose.

To implement this:

  • Add an import for org.apache.commons.text.StringEscapeUtils at the top of the file.
  • On line 67, replace the direct use of username with the encoded form using StringEscapeUtils.escapeHtml4(username).

Suggested changeset 2
src/main/java/com/example/demo/VulnerableController.java

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/src/main/java/com/example/demo/VulnerableController.java b/src/main/java/com/example/demo/VulnerableController.java
--- a/src/main/java/com/example/demo/VulnerableController.java
+++ b/src/main/java/com/example/demo/VulnerableController.java
@@ -9,6 +9,7 @@
 import java.io.PrintWriter;
 import java.util.List;
 import java.util.Map;
+import org.apache.commons.text.StringEscapeUtils;
 
 /**
  * REST Controller with intentional security vulnerabilities for CodeQL demonstration.
@@ -64,7 +65,7 @@
         
         // VULNERABLE: User input directly written to HTML output without encoding
         out.println("<html><body>");
-        out.println("<h1>Welcome " + username + "!</h1>");
+        out.println("<h1>Welcome " + StringEscapeUtils.escapeHtml4(username) + "!</h1>");
         out.println("</body></html>");
     }
     
EOF
@@ -9,6 +9,7 @@
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import org.apache.commons.text.StringEscapeUtils;

/**
* REST Controller with intentional security vulnerabilities for CodeQL demonstration.
@@ -64,7 +65,7 @@

// VULNERABLE: User input directly written to HTML output without encoding
out.println("<html><body>");
out.println("<h1>Welcome " + username + "!</h1>");
out.println("<h1>Welcome " + StringEscapeUtils.escapeHtml4(username) + "!</h1>");
out.println("</body></html>");
}

pom.xml
Outside changed files

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/pom.xml b/pom.xml
--- a/pom.xml
+++ b/pom.xml
@@ -48,7 +48,12 @@
             <version>2.7.0</version>
             <scope>test</scope>
         </dependency>
-    </dependencies>
+        <dependency>
+        <groupId>org.apache.commons</groupId>
+        <artifactId>commons-text</artifactId>
+        <version>1.14.0</version>
+    </dependency>
+</dependencies>
     
     <build>
         <plugins>
EOF
@@ -48,7 +48,12 @@
<version>2.7.0</version>
<scope>test</scope>
</dependency>
</dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.14.0</version>
</dependency>
</dependencies>

<build>
<plugins>
This fix introduces these dependencies
Package Version Security advisories
org.apache.commons:commons-text (maven) 1.14.0 None
Copilot is powered by AI and may make mistakes. Always verify output.
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);

Check failure

Code scanning / CodeQL

Uncontrolled data used in path expression High

This path depends on a
user-provided value
.

Copilot Autofix

AI about 1 month ago

To prevent path traversal attacks, ensure that user input (filename) cannot be manipulated to escape the /app/data/ directory. The best practice in this scenario is to:

  1. Combine /app/data/ and the untrusted filename using strong API calls (e.g., Path.resolve()),
  2. Normalize and convert to absolute paths,
  3. Verify that the resulting path is still within the intended /app/data/ directory (using startsWith or a similar check),
  4. Only then read from the file.

Additionally, you might consider restricting filenames with a whitelist, or rejecting any filename containing path separators or ".." sequences. But the canonical solution is to check if the resolved path starts with the canonical base path.

Changes needed:

  • Modify the /files/{filename} handler to implement the above logic.
  • The only file to change is src/main/java/com/example/demo/VulnerableController.java, specifically the readFile method, lines 75–84.
  • You will need appropriate imports if they are not already present (they are: java.nio.file., java.io.).
  • No changes to other code or business logic.

Suggested changeset 1
src/main/java/com/example/demo/VulnerableController.java

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/src/main/java/com/example/demo/VulnerableController.java b/src/main/java/com/example/demo/VulnerableController.java
--- a/src/main/java/com/example/demo/VulnerableController.java
+++ b/src/main/java/com/example/demo/VulnerableController.java
@@ -75,9 +75,13 @@
     @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);
+            // FIXED: Validate that the file stays within /app/data/
+            java.nio.file.Path baseDir = java.nio.file.Paths.get("/app/data").toAbsolutePath().normalize();
+            java.nio.file.Path requestedPath = baseDir.resolve(filename).normalize();
+            if (!requestedPath.startsWith(baseDir)) {
+                return "Invalid filename.";
+            }
+            return java.nio.file.Files.readString(requestedPath);
         } catch (Exception e) {
             return "Error reading file: " + e.getMessage();
         }
EOF
@@ -75,9 +75,13 @@
@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);
// FIXED: Validate that the file stays within /app/data/
java.nio.file.Path baseDir = java.nio.file.Paths.get("/app/data").toAbsolutePath().normalize();
java.nio.file.Path requestedPath = baseDir.resolve(filename).normalize();
if (!requestedPath.startsWith(baseDir)) {
return "Invalid filename.";
}
return java.nio.file.Files.readString(requestedPath);
} catch (Exception e) {
return "Error reading file: " + e.getMessage();
}
Copilot is powered by AI and may make mistakes. Always verify output.
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();

Check warning

Code scanning / CodeQL

Information exposure through an error message Medium

Error information
can be exposed to an external user.

Copilot Autofix

AI about 1 month ago

To fix the problem, we should avoid exposing internal exception details to end users in the HTTP response. Instead, respond with a generic error message (e.g., "Error reading file") and, if desired, log the exception details on the server for later debugging. The changes should only affect the readFile method, specifically its exception handling.

  • Change the return statement inside the catch block to return only a generic message.
  • Optionally, log the exception message on the server side using System.err.println, Logger, or similar.
  • Since no logger is present in the snippet and we cannot assume custom logging configuration, using System.err.println is standard and safe for demonstration/education code.
Suggested changeset 1
src/main/java/com/example/demo/VulnerableController.java

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/src/main/java/com/example/demo/VulnerableController.java b/src/main/java/com/example/demo/VulnerableController.java
--- a/src/main/java/com/example/demo/VulnerableController.java
+++ b/src/main/java/com/example/demo/VulnerableController.java
@@ -79,7 +79,9 @@
             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();
+            // Log the detailed error for server-side diagnostics
+            System.err.println("Error reading file: " + e.getMessage());
+            return "Error reading file"; // Generic message for user
         }
     }
     
EOF
@@ -79,7 +79,9 @@
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();
// Log the detailed error for server-side diagnostics
System.err.println("Error reading file: " + e.getMessage());
return "Error reading file"; // Generic message for user
}
}

Copilot is powered by AI and may make mistakes. Always verify output.
public String pingHost(@RequestParam String host) {
try {
// VULNERABLE: User input directly used in system command
Process process = Runtime.getRuntime().exec("ping -c 1 " + host);

Check failure

Code scanning / CodeQL

Uncontrolled command line Critical

This command line depends on a
user-provided value
.

Copilot Autofix

AI about 1 month ago

To fix this command injection issue:

  • Do not pass raw user input directly as part of the system command.
  • The best resolution is to validate the user input against a strict whitelist of acceptable hostnames/IP addresses, or at minimum, ensure the input does not contain shell metacharacters.
  • Alternatively, use the overload of Runtime.exec that takes a command array, separating the command and its arguments, which helps mitigate, but does not eliminate, command injection risk.
  • For demonstration, we should validate the host parameter using a regex ensuring it is a valid hostname or IP address, and then pass it as an argument array to exec.
  • The fixes are all within the pingHost method: add appropriate input validation, and refactor the call to exec to split arguments.
  • No new imports are required, basic Java features suffice.
Suggested changeset 1
src/main/java/com/example/demo/VulnerableController.java

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/src/main/java/com/example/demo/VulnerableController.java b/src/main/java/com/example/demo/VulnerableController.java
--- a/src/main/java/com/example/demo/VulnerableController.java
+++ b/src/main/java/com/example/demo/VulnerableController.java
@@ -90,8 +90,13 @@
     @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);
+            // FIXED: Validate user input before using in system command
+            // Only allow valid hostnames or IPv4 addresses
+            if (!host.matches("^[a-zA-Z0-9\\-.]+$") && !host.matches("^(\\d{1,3}\\.){3}\\d{1,3}$")) {
+                return "Invalid host parameter.";
+            }
+            // Use exec with argument array to avoid shell interpretation
+            Process process = Runtime.getRuntime().exec(new String[] { "ping", "-c", "1", host });
             java.io.BufferedReader reader = new java.io.BufferedReader(
                 new java.io.InputStreamReader(process.getInputStream()));
             
EOF
@@ -90,8 +90,13 @@
@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);
// FIXED: Validate user input before using in system command
// Only allow valid hostnames or IPv4 addresses
if (!host.matches("^[a-zA-Z0-9\\-.]+$") && !host.matches("^(\\d{1,3}\\.){3}\\d{1,3}$")) {
return "Invalid host parameter.";
}
// Use exec with argument array to avoid shell interpretation
Process process = Runtime.getRuntime().exec(new String[] { "ping", "-c", "1", host });
java.io.BufferedReader reader = new java.io.BufferedReader(
new java.io.InputStreamReader(process.getInputStream()));

Copilot is powered by AI and may make mistakes. Always verify output.
}
return result.toString();
} catch (Exception e) {
return "Error executing ping: " + e.getMessage();

Check warning

Code scanning / CodeQL

Information exposure through an error message Medium

Error information
can be exposed to an external user.

Copilot Autofix

AI about 1 month ago

To fix the vulnerability, we must ensure that sensitive details in error messages are not exposed to end users. Instead of returning e.getMessage() in the HTTP response, we should return a generic error message; however, we should still retain the error information for developers by logging the exception on the server side. This may include logging at the error or warning level, depending on the application's configuration.

Implementation

  • Edit the /ping endpoint (pingHost method, lines 91-107 in VulnerableController.java).
  • In the catch block (lines 104-106), replace return "Error executing ping: " + e.getMessage(); with:
    • Log the exception using System.err.println (since no logging framework is imported in the shown code).
    • Return a generic message, e.g., "Error executing ping".
  • No additional imports or dependencies are required for System.err.println.
Suggested changeset 1
src/main/java/com/example/demo/VulnerableController.java

Autofix patch

Autofix patch
Run the following command in your local git repository to apply this patch
cat << 'EOF' | git apply
diff --git a/src/main/java/com/example/demo/VulnerableController.java b/src/main/java/com/example/demo/VulnerableController.java
--- a/src/main/java/com/example/demo/VulnerableController.java
+++ b/src/main/java/com/example/demo/VulnerableController.java
@@ -102,7 +102,11 @@
             }
             return result.toString();
         } catch (Exception e) {
-            return "Error executing ping: " + e.getMessage();
+            // Log the exception server-side for debugging purposes
+            System.err.println("Exception during ping:");
+            e.printStackTrace();
+            // Return a generic error message to the client
+            return "Error executing ping";
         }
     }
 }
\ No newline at end of file
EOF
@@ -102,7 +102,11 @@
}
return result.toString();
} catch (Exception e) {
return "Error executing ping: " + e.getMessage();
// Log the exception server-side for debugging purposes
System.err.println("Exception during ping:");
e.printStackTrace();
// Return a generic error message to the client
return "Error executing ping";
}
}
}
Copilot is powered by AI and may make mistakes. Always verify output.
Comment out the queries input to prioritize custom pack usage.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Create a demo where CodeQL runs in a reusable workflow and accepts query pack suggestions

2 participants