From c1f78d0f9b75d8ef0cbf568cbc8b101f4baa69c6 Mon Sep 17 00:00:00 2001 From: Ludy Date: Mon, 2 Sep 2024 22:03:04 +0200 Subject: [PATCH] Validates the file name (#1793) --- .../database/DatabaseBackupHelper.java | 25 ++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/src/main/java/stirling/software/SPDF/config/security/database/DatabaseBackupHelper.java b/src/main/java/stirling/software/SPDF/config/security/database/DatabaseBackupHelper.java index 3ce4f28a..3fd7993f 100644 --- a/src/main/java/stirling/software/SPDF/config/security/database/DatabaseBackupHelper.java +++ b/src/main/java/stirling/software/SPDF/config/security/database/DatabaseBackupHelper.java @@ -163,6 +163,10 @@ public class DatabaseBackupHelper implements DatabaseBackupInterface { // Deletes a backup file. public boolean deleteBackupFile(String fileName) throws IOException { + if (!isValidFileName(fileName)) { + log.error("Invalid file name: {}", fileName); + return false; + } Path filePath = this.getBackupFilePath(fileName); if (Files.deleteIfExists(filePath)) { log.info("Deleted backup file: {}", fileName); @@ -175,7 +179,11 @@ public class DatabaseBackupHelper implements DatabaseBackupInterface { // Gets the Path object for a given backup file name. public Path getBackupFilePath(String fileName) { - return Paths.get(backupPath.toString(), fileName); + Path filePath = Paths.get(backupPath.toString(), fileName).normalize(); + if (!filePath.startsWith(backupPath)) { + throw new SecurityException("Path traversal detected"); + } + return filePath; } private boolean executeDatabaseScript(Path scriptPath) { @@ -202,4 +210,19 @@ public class DatabaseBackupHelper implements DatabaseBackupInterface { } } } + + private boolean isValidFileName(String fileName) { + // Check for invalid characters or sequences + return fileName != null + && !fileName.contains("..") + && !fileName.contains("/") + && !fileName.contains("\\") + && !fileName.contains(":") + && !fileName.contains("*") + && !fileName.contains("?") + && !fileName.contains("\"") + && !fileName.contains("<") + && !fileName.contains(">") + && !fileName.contains("|"); + } }