Fix directory traversal issue while renaming static file (#2207)

pull/2209/head
John Niang 2022-07-04 11:16:18 +08:00 committed by GitHub
parent 2a5277a33f
commit b926fd0ebe
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 16 additions and 0 deletions

View File

@ -107,6 +107,12 @@ public class FileUtils {
Assert.notNull(newName, "New name must not be null");
Path newPath = pathToRename.resolveSibling(newName);
var parent = pathToRename.getParent();
if (parent == null) {
parent = pathToRename;
}
checkDirectoryTraversal(parent, newPath);
log.info("Rename [{}] to [{}]", pathToRename, newPath);
Files.move(pathToRename, newPath);

View File

@ -3,6 +3,7 @@ package run.halo.app.utils;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayInputStream;
@ -22,6 +23,7 @@ import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import run.halo.app.exception.ForbiddenException;
import run.halo.app.model.support.HaloConst;
/**
@ -134,6 +136,14 @@ class FileUtilsTest {
assertEquals(content, new String(Files.readAllBytes(newPath)));
}
@Test
void shouldThrowErrorIfNewNameIsInvalidWhenRenaming() {
final var target = tempDirectory.resolve("fake.file");
assertThrows(ForbiddenException.class, () -> FileUtils.rename(target, "../fake.file"));
assertThrows(ForbiddenException.class, () -> FileUtils.rename(target, "../../fake.file"));
assertThrows(ForbiddenException.class, () -> FileUtils.rename(target, "/fake.file"));
}
@Test
void testRenameFolder() throws IOException {
Path testPath = tempDirectory.resolve("test/test");