잘못된 디렉터리 경로 제한 ('경로 탐색')

허용된 디렉터리 밖의 파일 접근을 막는 경로 검증

설명

파일을 읽거나 쓸 때 요청 값이 지정된 디렉터리 밖을 가리키지 않도록 제한하세요. 부모 디렉터리를 고정해도 사용자가 제공한 경로는 검증해야 합니다.

잠재적 영향

애플리케이션 계정의 권한에 따라 시스템 파일이나 다른 사용자의 데이터가 노출되거나 변경될 수 있습니다. 변경한 파일을 애플리케이션이 실행하면 코드 실행으로 이어질 수 있습니다.

해결 방법

  1. 사용자가 경로를 고를 필요가 없으면 UUID 같은 서버 생성 이름을 사용하세요. 상대 경로를 받는 경우 절대 경로를 거부하세요.
  2. 기준 경로와 Path.resolve()로 결합하고 정규화한 결과를 Path.startsWith(Path)로 비교하세요. 기존 파일은 toRealPath()로 링크를 해석한 뒤 다시 확인하세요.
  3. 검사 후 파일이 바뀌지 않도록 기준 디렉터리와 그 하위 경로의 쓰기 권한을 제한하세요. 신뢰할 수 없는 사용자가 경로를 변경할 수 있다면 지원되는 파일 시스템에서 SecureDirectoryStream으로 디렉터리를 기준으로 각 구성 요소를 안전하게 여세요.

예시

변경 전

java
private static final String BASE_PATH ="/restricted/directory";

public String readFile(String filePath) throws IOException {
    Path file = Paths.get("/restricted/directory/" + filePath);
    return new String(Files.readAllBytes(file));
}

File(parent, child)에서는 child도 경로의 일부입니다. 부모만 지정해서는 최종 파일의 위치를 확인할 수 없습니다.

java
import java.io.File;
import javax.servlet.http.HttpServletRequest;

public final class UnsafeUploadPath {
    private static final File UPLOAD_DIR = new File("/var/app/uploads");

    public File destination(HttpServletRequest request) {
        String child = request.getParameter("name");

        // 취약: 두 번째 생성자 인자도 공격자가 제어하는 경로입니다.
        return new File(UPLOAD_DIR, child);
    }
}

변경 후

이 Java 11 이상 예시는 서버가 디렉터리 트리를 관리한다고 가정합니다. 파일 크기와 잘못된 입력에 대한 오류 응답은 별도로 처리하세요.

java
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;

public final class SafeFileReader {
    private static final Path BASE_PATH = Path.of("/restricted/directory");

    public String readFile(String filePath) throws IOException {
        Path base = BASE_PATH.toRealPath();
        Path supplied = Path.of(filePath);
        if (supplied.isAbsolute()) {
            throw new SecurityException("Absolute paths are not allowed.");
        }

        Path candidate = base.resolve(supplied).normalize();
        if (!candidate.startsWith(base)) {
            throw new SecurityException("Unauthorized access attempt detected.");
        }

        // 기존 파일의 심볼릭 링크까지 해석한 실제 대상도 기준 디렉터리 안이어야 합니다.
        Path requestedPath = candidate.toRealPath();
        if (!requestedPath.startsWith(base)
                || !Files.isRegularFile(requestedPath, LinkOption.NOFOLLOW_LINKS)) {
            throw new SecurityException("Unauthorized access attempt detected.");
        }
        return Files.readString(requestedPath, StandardCharsets.UTF_8);
    }
}

requestedPath가 실제 기준 디렉터리 안의 일반 파일인지 확인한 뒤 그 경로를 읽습니다.

관련 CVE

참조