avoid path traversal attack

This commit is contained in:
Sebastian Sdorra
2018-11-30 08:11:26 +01:00
parent 0bbe7352c2
commit 53be8b112b
2 changed files with 25 additions and 0 deletions

View File

@@ -1,8 +1,12 @@
package sonia.scm.repository;
import com.google.common.base.CharMatcher;
import java.nio.file.Path;
import java.nio.file.Paths;
import static com.google.common.base.Preconditions.checkArgument;
/**
* A Location Resolver for File based Repository Storage.
* <p>
@@ -19,6 +23,8 @@ public class InitialRepositoryLocationResolver {
private static final String DEFAULT_REPOSITORY_PATH = "repositories";
private static final CharMatcher ID_MATCHER = CharMatcher.anyOf("/\\");
/**
* Returns the initial path to repository.
*
@@ -27,6 +33,8 @@ public class InitialRepositoryLocationResolver {
* @return initial path of repository
*/
public Path getPath(String repositoryId) {
// avoid path traversal attacks
checkArgument(ID_MATCHER.matchesNoneOf(repositoryId), "repository id contains invalid characters");
return Paths.get(DEFAULT_REPOSITORY_PATH, repositoryId);
}

View File

@@ -1,5 +1,6 @@
package sonia.scm.repository;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
@@ -20,4 +21,20 @@ class InitialRepositoryLocationResolverTest {
assertThat(path).isRelative();
assertThat(path.toString()).isEqualTo("repositories" + File.separator + "42");
}
@Test
void shouldThrowIllegalArgumentExceptionIfIdHasASlash() {
InitialRepositoryLocationResolver resolver = new InitialRepositoryLocationResolver();
Assertions.assertThrows(IllegalArgumentException.class, () -> {
resolver.getPath("../../../passwd");
});
}
@Test
void shouldThrowIllegalArgumentExceptionIfIdHasABackSlash() {
InitialRepositoryLocationResolver resolver = new InitialRepositoryLocationResolver();
Assertions.assertThrows(IllegalArgumentException.class, () -> {
resolver.getPath("..\\..\\..\\users.ntlm");
});
}
}