Skip to content

[NEW DATA EXTENSION] Java: add path-injection sinks for Spring MultipartFile.transferTo and servlet Part.write (CWE-22) - #62

Draft
felickz with Copilot wants to merge 3 commits into
mainfrom
copilot/cwe-22-java-username-upload
Draft

felickz with Copilot wants to merge 3 commits into
mainfrom
copilot/cwe-22-java-username-upload

Conversation

Copilot AI commented Oct 9, 2026 •

Copy link
Copy Markdown

📝 Data Extension Information

  • Language: java
  • Extension Name(s): languages/java/custom/models/path-injection.model.yml, in the new model pack languages-java-custom-models
  • Extension Types: sinkModel
  • Target Library/Framework: Spring Web multipart, Java Servlet API (javax and jakarta)
  • Library Modules Covered: org.springframework.web.multipart, javax.servlet.http, jakarta.servlet.http

🎯 Description

What This Data Extension Models

java/path-injection misses a request username that gets concatenated into an upload destination path. The issue suspected a missing summary. That is not the cause.

Step Status in codeql/java-all 9.3.2
@RequestParam / getParameter source ✅ modeled
new File(String), new File(File,String), Paths.get, Path.resolve taint steps ✅ modeled
MultipartFile.transferTo(File|Path), Part.write(String) sink ❌ missing

This PR adds the missing sinks only. No summary rows are needed.

  • New model pack languages/java/custom/models/: library: true, with extensionTargets: codeql/java-all. Its qlpack.yml matches the one in [NEW DATA EXTENSION] http4k request sources and response sinks (Java/Kotlin) #7, so expect a trivial conflict if both merge.
  • Java test pack now depends on codeql/java-queries and languages-java-custom-models.
  • Regression test languages/java/custom/test/PathInjectionUsernameUpload/: uses TaintedPath.qlref with inline expectations and minimal Spring and servlet stubs.

Threat Model

remote

Example Vulnerable Code

@RequestMapping("/profile")
public String processProfile(@RequestParam("username") String username, MultipartFile file) throws IOException {
    File dest = new File(uploadDir + "/" + username + ".png");
    file.transferTo(dest);                                   // flagged
    file.transferTo(Paths.get(uploadDir, username + ".png")); // flagged
}

String username = request.getParameter("username");
part.write(uploadDir + "/" + username + ".png");             // flagged (javax + jakarta)

The test also covers the original app's pattern: an if (!username.equals(current)) branch followed by the upload. The equals guard only sanitizes its true branch, so the alert is still reported.

Example Safe Code

file.transferTo(new File(uploadDir + "/avatar.png"));                     // constant
file.transferTo(new File(uploadDir + "/" + storedUsername + ".png"));     // not request-derived
if (username.contains("..") || username.contains("/") || username.contains("\\")) return "error";
file.transferTo(new File(uploadDir + "/" + username + ".png"));           // sanitized by built-in PathSanitizer

📦 Extension Details

Extension YAML

extensions:
  - addsTo:
      pack: codeql/java-all
      extensible: sinkModel
    data:
      - ["jakarta.servlet.http", "Part", True, "write", "(String)", "", "Argument[0]", "path-injection", "manual"]
      - ["javax.servlet.http", "Part", True, "write", "(String)", "", "Argument[0]", "path-injection", "manual"]
      - ["org.springframework.web.multipart", "MultipartFile", True, "transferTo", "(File)", "", "Argument[0]", "path-injection", "manual"]
      - ["org.springframework.web.multipart", "MultipartFile", True, "transferTo", "(Path)", "", "Argument[0]", "path-injection", "manual"]

Access Path Explanation

  • In every row, Argument[0] is the destination path or file that the uploaded content is written to.
  • subtypes: True makes the rows apply to framework implementations such as StandardMultipartFile and CommonsMultipartFile.
  • transferTo(Path) is a default interface method (Spring 5.1+), so it gets its own row.

🧪 Testing

  • Extension YAML resolves without errors
  • Database created with sample code (codeql database create or codeql test extract)
  • Single query verified with extension applied (codeql query run --additional-packs=<model-pack-dir>): not run separately. The test pack resolves the model pack through its ${workspace} dependency.
  • Unit tests pass with extension applied (codeql test run; the model pack is applied through the test pack dependency rather than --additional-packs)
  • Positive test cases (vulnerable code detected): the 8 transferTo and Part.write alerts are missing without the model and reported with it
  • Negative test cases (safe code not flagged)

📋 Checklist

  • Extension YAML is valid and properly formatted
  • Extension placed in correct location (languages/[language]/custom/src/): deviates on purpose. It lives in a separate model pack (languages/java/custom/models/), because the custom/src query pack cannot declare extensionTargets. This matches [NEW DATA EXTENSION] http4k request sources and response sinks (Java/Kotlin) #7.
  • qlpack.yml includes dataExtensions configuration
  • Access paths verified via API graph queries: not applicable, since Java uses MaD signatures. Verified through PrettyPrintModels output in TaintedPath.expected.
  • No false positives in test cases
  • Documentation/comments included in YAML

🔗 References


Note: This data extension was developed following CodeQL Models as Data best practices.

…et Part.write

Co-authored-by: felickz <1760475+felickz@users.noreply.github.com>
Copilot AI changed the title [WIP] Add data extension model for path injection vulnerability [NEW DATA EXTENSION] Java: add path-injection sinks for Spring MultipartFile.transferTo and servlet Part.write (CWE-22) Oct 9, 2026
file.transferTo(Paths.get(uploadDir).resolve(username + ".png")); // $ Alert

// Already detected without custom models: `File` constructor summary into a built-in sink
new FileOutputStream(new File(uploadDir + "/" + username + ".png")).close(); // $ Alert
Copilot AI requested a review from felickz October 9, 2026 02:34
@felickz

felickz commented Oct 30, 2026

Copy link
Copy Markdown

@copilot A rescan of the synthetic corpus found additional findings that fit this gap. Please re-run your analysis against them, confirm whether the proposed change covers each scenario, and extend it where it does not.

Repo CWE Severity AI scan alert Summary
VulnerableApp CWE-22 high https://github.com/codeql-forks-felickz/VulnerableApp/security/code-scanning/128 Level 8 stores the upload under contentDispositionRoot using the raw original file name supplied by the client. Traversal characters in that

Please continue on this pull request.

… upload root (Files.copy)

Co-authored-by: felickz <1760475+felickz@users.noreply.github.com>

Copilot AI commented Oct 30, 2026

Copy link
Copy Markdown
Author

@copilot A rescan of the synthetic corpus found additional findings that fit this gap. Please re-run your analysis against them, confirm whether the proposed change covers each scenario, and extend it...

I re-ran the analysis on the VulnerableApp Level 8 finding. It doesn't need new model rows, because stock CodeQL already covers the whole flow.

How the code flows:

  • getVulnerablePayloadLevel8 passes file.getOriginalFilename() into the shared helper genericFileUploadUtility.
  • The helper writes the upload with Files.copy(file.getInputStream(), root.resolve(fileName), REPLACE_EXISTING).

Each step is already modeled in codeql/java-all 9.3.3:

  • Source: MultipartFile.getOriginalFilename() is a remote source.
  • Step: Path.resolve passes taint through to its result.
  • Sink: Files.copy(InputStream,Path,CopyOption[]) treats Argument[1] as a path-injection sink.

I added a cut-down copy of this pattern, ContentDispositionUpload.java, as a regression test in 8c34ced. TaintedPath alerts on it, and the alert comes only from built-in models (Src:MaD getOriginalFilename, MaD Path.resolve, Sink:MaD Files.copy). A UUID-named upload is included as a case that must not alert, and the test passes.

My guess is that this is a location mismatch, not a missed finding. CodeQL reports the alert at the Files.copy/root.resolve(fileName) line inside genericFileUploadUtility. That single alert covers Level 8 together with the other upload levels that call the helper. The AI scan places its finding on the Level 8 method instead. I couldn't confirm this against the baseline code scanning alerts, because the API returned 403 for this integration. To check, look for an existing java/path-injection alert on genericFileUploadUtility.

The rows this PR adds (MultipartFile.transferTo, Part.write) cover the verademo case. Level 8 doesn't need them.

private static String store(Path root, String fileName, Supplier<Boolean> validator, MultipartFile file)
throws IOException {
if (validator.get()) {
Files.copy(file.getInputStream(), root.resolve(fileName), StandardCopyOption.REPLACE_EXISTING); // $ Alert

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟢 Approval recommended

No active review issues are recorded for the upload-destination sink-model changes.

No open issues 🎉

What changed in this PR

Adds Java CodeQL sink models so java/path-injection detects request-controlled upload destinations passed to Spring and servlet APIs. This addresses issue #35 through missing sinks rather than additional taint summaries.

Changes:

  • Introduces a model pack covering both MultipartFile.transferTo overloads and Part.write in javax and jakarta.
  • Adds regression fixtures for vulnerable uploads, constant destinations, and sanitized inputs.
  • Connects the Java test pack to the models and standard queries, with expected alerts and model provenance.
File Description
languages/​java/​custom/​test/​qlpack.yml Adds query and model-pack dependencies.
languages/​java/​custom/​test/​PathInjectionUsernameUpload/​TaintedPath.qlref Runs the path-injection query with test postprocessing.
languages/​java/​custom/​test/​PathInjectionUsernameUpload/​TaintedPath.expected Records expected alerts and model provenance.
languages/​java/​custom/​test/​PathInjectionUsernameUpload/​ProfileController.java Tests Spring upload paths and safe alternatives.
languages/​java/​custom/​test/​PathInjectionUsernameUpload/​org/​springframework/​web/​multipart/​MultipartFile.java Stubs multipart APIs, including both transfer overloads.
languages/​java/​custom/​test/​PathInjectionUsernameUpload/​org/​springframework/​web/​bind/​annotation/​RequestParam.java Stubs request-parameter annotations.
languages/​java/​custom/​test/​PathInjectionUsernameUpload/​org/​springframework/​web/​bind/​annotation/​RequestMapping.java Stubs request-mapping annotations.
languages/​java/​custom/​test/​PathInjectionUsernameUpload/​org/​springframework/​stereotype/​Controller.java Stubs the controller annotation.
languages/​java/​custom/​test/​PathInjectionUsernameUpload/​JavaxServletUpload.java Tests javax upload destinations.
languages/​java/​custom/​test/​PathInjectionUsernameUpload/​javax/​servlet/​ServletRequest.java Stubs javax request-parameter access.
languages/​java/​custom/​test/​PathInjectionUsernameUpload/​javax/​servlet/​http/​Part.java Stubs javax multipart writes.
languages/​java/​custom/​test/​PathInjectionUsernameUpload/​javax/​servlet/​http/​HttpServletRequest.java Stubs javax multipart retrieval.
languages/​java/​custom/​test/​PathInjectionUsernameUpload/​JakartaServletUpload.java Tests jakarta upload destinations.
languages/​java/​custom/​test/​PathInjectionUsernameUpload/​jakarta/​servlet/​ServletRequest.java Stubs jakarta request-parameter access.
languages/​java/​custom/​test/​PathInjectionUsernameUpload/​jakarta/​servlet/​http/​Part.java Stubs jakarta multipart writes.
languages/​java/​custom/​test/​PathInjectionUsernameUpload/​jakarta/​servlet/​http/​HttpServletRequest.java Stubs jakarta multipart retrieval.
languages/​java/​custom/​test/​PathInjectionUsernameUpload/​ContentDispositionUpload.java Tests filename-derived paths through a shared upload helper.
languages/​java/​custom/​models/​qlpack.yml Declares the Java model-extension pack.
languages/​java/​custom/​models/​path-injection.model.yml Adds four upload-destination sink models.

Review effort: Balanced

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.

[Data Extension Create]: CWE-22 CRITICAL - Java: Java summary models so request usernames reach file path sinks in upload handlers

4 participants