Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .jules/sentinel.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,8 @@
**Vulnerability:** In `DownloadGetRequestHandler.java`, `info.getFileName()` derived from user-supplied `Upload-Metadata` was embedded directly into the `Content-Disposition` header without stripping path traversal sequences (`../`, `..\`) or directory paths (`/`, `\`). Downstream clients saving files using the suggested filename could write files outside target directories. Additionally, `X-Content-Type-Options: nosniff` was missing when serving completed downloads, leaving browsers susceptible to MIME sniffing attacks.
**Learning:** File download endpoints that reflect user-supplied filenames in `Content-Disposition` headers can cause path traversal vulnerabilities on consuming clients. Serving user-uploaded content without explicit MIME-sniffing protection allows potential content sniffing / script execution.
**Prevention:** Sanitize filenames before constructing `Content-Disposition` by stripping directory paths (Unix `/` and Windows `\`), removing directory traversal sequences (`..`), and falling back to a safe identifier if the sanitized name is empty. Always include `X-Content-Type-Options: nosniff` when serving user-uploaded files.

## 2026-11-15 - Prevent Path Traversal in UploadInfo.getFileName()
**Vulnerability:** `UploadInfo.getFileName()` returned untrusted client-supplied metadata directly without sanitizing path traversal sequences (`../`, `..\`) or directory delimiters (`/`, `\`). Downstream consumers relying on `uploadInfo.getFileName()` to persist uploaded files were vulnerable to path traversal and arbitrary file overwrite outside the destination directory. Additionally, calling `getFileName()` on an `UploadInfo` with a null ID caused a `NullPointerException`.
**Learning:** Helper methods that extract filenames from untrusted client metadata must enforce path sanitization at the source, preventing downstream consumers from accidentally introducing path traversal vulnerabilities.
**Prevention:** Sanitize filenames at extraction in `UploadInfo.getFileName()` via `Utils.sanitizeFileName(...)`, stripping directory paths, traversal sequences, and null bytes while safely falling back to the upload ID or `"download"` if null.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ See [docs/UPGRADING.md](docs/UPGRADING.md) for details and code examples.
- **`UploadStorageService.cleanupExpiredUploads(UploadLockingService)`**: deprecated in favor of the zero-argument `cleanupExpiredUploads()`.

### Security
- **UploadInfo filename sanitization**: sanitize `UploadInfo.getFileName()` to prevent directory traversal and null-byte injection, stripping directory paths and traversal sequences with safe fallback to the upload ID.
- **Download extension**: sanitize filenames in `Content-Disposition` to prevent client directory traversal and add `X-Content-Type-Options: nosniff`.
- **CORS origin validation**: prevent arbitrary `Origin` header reflection in CORS responses ([#132](https://github.com/tomdesair/tus-java-server/pull/132)).
- **Temporary file permissions**: use `Files.createTempFile` instead of `File.createTempFile` to enforce owner-only permissions (`0600`, CWE-378) ([#131](https://github.com/tomdesair/tus-java-server/pull/131)).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@
import me.desair.tus.server.HttpMethod;
import me.desair.tus.server.exception.TusException;
import me.desair.tus.server.exception.UploadNotFoundException;
import me.desair.tus.server.upload.UploadId;
import me.desair.tus.server.upload.UploadInfo;
import me.desair.tus.server.upload.UploadStorageService;
import me.desair.tus.server.util.AbstractRequestHandler;
import me.desair.tus.server.util.TusServletRequest;
import me.desair.tus.server.util.TusServletResponse;
import me.desair.tus.server.util.Utils;

/** Send the uploaded bytes of finished uploads. */
public class DownloadGetRequestHandler extends AbstractRequestHandler {
Expand Down Expand Up @@ -51,7 +51,9 @@ public void process(

servletResponse.setHeader(HttpHeader.CONTENT_LENGTH, Objects.toString(info.getLength()));

String sanitizedFileName = sanitizeFileName(info.getFileName(), info.getId());
// info.getFileName() is pre-sanitized, but passing through Utils.sanitizeFileName ensures
// idempotent directory traversal protection before generating Content-Disposition headers
String sanitizedFileName = Utils.sanitizeFileName(info.getFileName(), info.getId());
servletResponse.setHeader(
HttpHeader.CONTENT_DISPOSITION,
String.format(
Expand All @@ -67,26 +69,4 @@ public void process(

uploadStorageService.copyUploadTo(info, servletResponse.getOutputStream());
}

/**
* Sanitizes the given filename to prevent directory traversal and header corruption attacks on
* clients consuming the Content-Disposition header.
*/
private String sanitizeFileName(String fileName, UploadId uploadId) {
if (fileName == null || fileName.trim().isEmpty()) {
return uploadId != null ? uploadId.toString() : "download";
}
// Prevent client-side path traversal: strip directory paths across Unix and Windows separators
String sanitized = fileName.trim();
int lastSlash = Math.max(sanitized.lastIndexOf('/'), sanitized.lastIndexOf('\\'));
if (lastSlash >= 0) {
sanitized = sanitized.substring(lastSlash + 1).trim();
}
// Remove directory traversal sequences (..)
sanitized = sanitized.replace("..", "").trim();
if (sanitized.isEmpty()) {
return uploadId != null ? uploadId.toString() : "download";
}
return sanitized;
}
}
17 changes: 12 additions & 5 deletions src/main/java/me/desair/tus/server/upload/UploadInfo.java
Original file line number Diff line number Diff line change
Expand Up @@ -339,20 +339,27 @@ public String getUploadConcatHeaderValue() {

/**
* Try to guess the filename of the uploaded data. If we cannot guess the name we fall back to the
* ID. <br>
* NOTE: This is only a guess, there are no guarantees that the return value is correct
* ID (or {@code "download"} if the ID is not set).
*
* @return A potential file name
* <p>The returned filename is sanitized via {@link Utils#sanitizeFileName(String, UploadId)} to
* strip directory paths and path traversal sequences.
*
* <p>NOTE: This is only a guess, there are no guarantees that the return value is correct.
*
* @return A sanitized potential file name (never null or blank)
*/
public String getFileName() {
Map<String, String> metadata = getMetadata();
for (String fileNameKey : fileNameKeys) {
if (metadata.containsKey(fileNameKey)) {
return metadata.get(fileNameKey);
// Sanitize client-supplied metadata against directory traversal (../, ..\) and null-bytes
// to protect downstream callers who persist uploaded files using getFileName()
return Utils.sanitizeFileName(metadata.get(fileNameKey), getId());
}
}

return getId().toString();
// Safely fall back to the upload ID (or "download" if ID is null) without throwing NPE
return Utils.sanitizeFileName(null, getId());
}

/**
Expand Down
47 changes: 47 additions & 0 deletions src/main/java/me/desair/tus/server/util/Utils.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import me.desair.tus.server.ProtocolVersion;
import me.desair.tus.server.checksum.ChecksumAlgorithm;
import me.desair.tus.server.upload.NoOpUploadLockingService;
import me.desair.tus.server.upload.UploadId;
import me.desair.tus.server.upload.UploadInfo;
import me.desair.tus.server.upload.UploadLockingService;
import me.desair.tus.server.upload.UploadStorageService;
Expand Down Expand Up @@ -817,4 +818,50 @@ public static String sanitizePrefix(String prefix) {
}
return result + "/";
}

/**
* Sanitizes a client-supplied filename to prevent directory traversal and null-byte injection
* when serving downloads or persisting uploaded files.
*
* <p>Strips Unix ({@code /}) and Windows ({@code \}) directory prefixes, removes {@code ..}
* traversal sequences and null bytes ({@code \0}), and falls back to {@code "download"} when the
* resulting name is null or blank.
*
* @param fileName The raw filename string (may be null)
* @return A non-null, non-blank sanitized filename
*/
public static String sanitizeFileName(String fileName) {
return sanitizeFileName(fileName, null);
}

/**
* Sanitizes a client-supplied filename to prevent directory traversal and null-byte injection
* when serving downloads or persisting uploaded files.
*
* <p>Strips Unix ({@code /}) and Windows ({@code \}) directory prefixes, removes {@code ..}
* traversal sequences and null bytes ({@code \0}), and falls back to the provided {@link
* UploadId} (or {@code "download"} if {@code uploadId} is {@code null}) when the resulting name
* is null or blank.
*
* @param fileName The raw filename string (may be null)
* @param uploadId Optional fallback upload ID if the filename is null, blank, or unsafe
* @return A non-null, non-blank sanitized filename
*/
public static String sanitizeFileName(String fileName, UploadId uploadId) {
if (fileName == null || fileName.trim().isEmpty()) {
return uploadId != null ? uploadId.toString() : "download";
}
// Strip Unix and Windows directory segments so only the terminal filename remains
String sanitized = fileName.trim();
int lastSlash = Math.max(sanitized.lastIndexOf('/'), sanitized.lastIndexOf('\\'));
if (lastSlash >= 0) {
sanitized = sanitized.substring(lastSlash + 1).trim();
}
// Remove path traversal sequences and null bytes that could bypass filesystem or header checks
sanitized = sanitized.replace("..", "").replace("\0", "").trim();
if (sanitized.isEmpty() || ".".equals(sanitized)) {
return uploadId != null ? uploadId.toString() : "download";
}
return sanitized;
}
}
15 changes: 15 additions & 0 deletions src/test/java/me/desair/tus/server/CoverageGapTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,21 @@ public void testAbstractTusExtensionHandleError5Args() throws Exception {
DummyAbstractExtension ext = new DummyAbstractExtension();
ext.handleError(HttpMethod.POST, null, null, null, null);
assertThat(ext.handleError8Called, is(true));

// Verify 5-arg validate delegates cleanly
ext.validate(
HttpMethod.POST, new org.springframework.mock.web.MockHttpServletRequest(), null, "owner");

// Verify 5-arg process delegates cleanly
org.springframework.mock.web.MockHttpServletResponse response =
new org.springframework.mock.web.MockHttpServletResponse();
ext.process(
HttpMethod.POST,
new TusServletRequest(new org.springframework.mock.web.MockHttpServletRequest()),
new TusServletResponse(response),
null,
"owner");
assertThat(ext.getName(), is("dummy"));
}

@Test
Expand Down
17 changes: 17 additions & 0 deletions src/test/java/me/desair/tus/server/upload/UploadInfoTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;

import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.util.Base64;
import java.util.Stack;
import java.util.UUID;
import me.desair.tus.server.HttpHeader;
Expand Down Expand Up @@ -194,11 +196,26 @@ public void testGetNameAndTypeWithMetadata() throws Exception {

assertThat(info.getFileName(), is("test.jpg"));
assertThat(info.getFileMimeType(), is("image/jpeg"));

// Untrusted path traversal sequences in filename metadata must be stripped by getFileName()
info.setEncodedMetadata(
"filename "
+ Base64.getEncoder()
.encodeToString("../../etc/passwd".getBytes(StandardCharsets.UTF_8)));
assertThat(info.getFileName(), is("passwd"));

// Traversal-only or directory metadata must safely fall back to the upload ID
info.setId(new UploadId("test-id"));
info.setEncodedMetadata(
"filename " + Base64.getEncoder().encodeToString("../..".getBytes(StandardCharsets.UTF_8)));
assertThat(info.getFileName(), is("test-id"));
}

@Test
public void testGetNameAndTypeWithoutMetadata() throws Exception {
UploadInfo info = new UploadInfo();
assertThat(info.getFileName(), is("download"));

final UploadId id = new UploadId(UUID.randomUUID());
info.setId(id);

Expand Down
18 changes: 18 additions & 0 deletions src/test/java/me/desair/tus/server/util/UtilsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import me.desair.tus.server.HttpHeader;
import me.desair.tus.server.checksum.ChecksumAlgorithm;
import me.desair.tus.server.upload.NoOpUploadLockingService;
import me.desair.tus.server.upload.UploadId;
import me.desair.tus.server.upload.UploadLockingService;
import me.desair.tus.server.upload.UploadStorageService;
import org.apache.commons.io.FileUtils;
Expand Down Expand Up @@ -988,6 +989,23 @@ public void testSanitizePrefix() {
assertEquals("custom/", Utils.sanitizePrefix("/custom///"));
}

@Test
public void testSanitizeFileName() {
UploadId fallbackId = new UploadId("id-1");
assertEquals("download", Utils.sanitizeFileName(null));
assertEquals("download", Utils.sanitizeFileName(""));
assertEquals("id-1", Utils.sanitizeFileName(" ", fallbackId));
assertEquals("passwd", Utils.sanitizeFileName("../../etc/passwd", fallbackId));
assertEquals("secret.pdf", Utils.sanitizeFileName("C:\\Users\\test\\..\\secret.pdf"));
assertEquals("id-1", Utils.sanitizeFileName("../..", fallbackId));
assertEquals("download", Utils.sanitizeFileName("../..", null));
assertEquals("id-1", Utils.sanitizeFileName(".", fallbackId));
assertEquals("download", Utils.sanitizeFileName(".", null));
assertEquals("id-1", Utils.sanitizeFileName(".../...", fallbackId));
assertEquals("filename.txt", Utils.sanitizeFileName("file\0name.txt"));
assertEquals("normal-file.txt", Utils.sanitizeFileName("normal-file.txt", fallbackId));
}

@Test
public void testCreateUploadExecutor() throws Exception {
ThreadPoolExecutor executor = Utils.createUploadExecutor(2, "test-upload");
Expand Down
Loading