Skip to content

Commit 6c27518

Browse files
authored
Fix path attack when loading snapshot of IoTConsensus (#16098)
(cherry picked from commit f907bd3)
1 parent 21a2e9d commit 6c27518

1 file changed

Lines changed: 19 additions & 3 deletions

File tree

iotdb-core/consensus/src/main/java/org/apache/iotdb/consensus/iot/IoTConsensusServerImpl.java

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -358,7 +358,7 @@ public void receiveSnapshotFragment(
358358
throws ConsensusGroupModifyPeerException {
359359
try {
360360
String targetFilePath = calculateSnapshotPath(snapshotId, originalFilePath);
361-
File targetFile = new File(storageDir, targetFilePath);
361+
File targetFile = getSnapshotPath(targetFilePath);
362362
Path parentDir = Paths.get(targetFile.getParent());
363363
if (!Files.exists(parentDir)) {
364364
Files.createDirectories(parentDir);
@@ -405,7 +405,23 @@ private void clearOldSnapshot() {
405405

406406
public void loadSnapshot(String snapshotId) {
407407
// TODO: (xingtanzjr) throw exception if the snapshot load failed
408-
stateMachine.loadSnapshot(new File(storageDir, snapshotId));
408+
stateMachine.loadSnapshot(getSnapshotPath(snapshotId));
409+
}
410+
411+
private File getSnapshotPath(String snapshotRelativePath) {
412+
File storageDirFile = new File(storageDir);
413+
File snapshotDir = new File(storageDir, snapshotRelativePath);
414+
try {
415+
if (!snapshotDir
416+
.getCanonicalFile()
417+
.toPath()
418+
.startsWith(storageDirFile.getCanonicalFile().toPath())) {
419+
throw new IllegalArgumentException("Invalid snapshotRelativePath: " + snapshotRelativePath);
420+
}
421+
} catch (IOException e) {
422+
throw new IllegalArgumentException(e);
423+
}
424+
return snapshotDir;
409425
}
410426

411427
@FunctionalInterface
@@ -816,7 +832,7 @@ public void cleanupRemoteSnapshot(Peer targetPeer) throws ConsensusGroupModifyPe
816832
}
817833

818834
public void cleanupSnapshot(String snapshotId) throws ConsensusGroupModifyPeerException {
819-
File snapshotDir = new File(storageDir, snapshotId);
835+
File snapshotDir = getSnapshotPath(snapshotId);
820836
if (snapshotDir.exists()) {
821837
try {
822838
FileUtils.deleteDirectory(snapshotDir);

0 commit comments

Comments
 (0)