설명
ZIP 항목 이름으로 파일을 만들기 전에 실제 쓰기 위치를 추출 디렉터리 안으로 제한하세요. 절대 경로, 상위 디렉터리, 심볼릭 링크는 저장 위치를 바꿀 수 있습니다.
잠재적 영향
서비스 계정이 쓸 수 있는 파일이 손상되어 설정이 바뀌거나 서비스가 중단될 수 있습니다. 더 높은 권한의 프로세스가 해당 파일을 읽거나 실행하면 정보 유출이나 권한 상승으로도 이어질 수 있습니다.
해결 방법
- 신뢰할 수 있는 부모 아래에 새 비공개 디렉터리를 만들고 필요한 파일 구조만 허용하세요. 링크 항목은 복원하지 마세요.
- 절대 경로와 상위 이동을 거부하고
base.resolve(entryName).normalize()결과를Path.startsWith(base)로 확인하세요. 하위 경로가 필요하면 디렉터리를 기준으로 각 부모를 열어 링크를 따르지 않는지 확인한 뒤 디렉터리나 파일을 만드세요. - 최소 권한으로 추출하고
CREATE_NEW와NOFOLLOW_LINKS로 새 파일만 만드세요.
예시
변경 전
java
import java.io.*;
import java.util.zip.*;
public class UnsafeUnzipper {
public void extract(InputStream zipStream, File destDir) throws IOException {
ZipInputStream zis = new ZipInputStream(zipStream);
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
// 취약: 엔트리 이름을 그대로 결합
File outFile = new File(destDir, entry.getName());
if (entry.isDirectory()) {
outFile.mkdirs();
continue;
}
outFile.getParentFile().mkdirs();
try (OutputStream os = new FileOutputStream(outFile)) {
byte[] buf = new byte[8192];
int len;
while ((len = zis.read(buf)) != -1) {
os.write(buf, 0, len);
}
}
}
}
}
변경 후
Java 11 이상에서 사용하는 예시입니다. 다른 사용자가 destDir를 변경할 수 없게 하세요. 압축 해제 후 실제 바이트 수와 항목 수는 별도로 제한하세요.
java
import java.io.*;
import java.nio.channels.*;
import java.nio.file.*;
import java.util.*;
import java.util.zip.*;
public class SafeUnzipper {
public void extract(InputStream zipStream, File destDir) throws IOException {
// 애플리케이션이 소유한 위치 아래에 이번 추출 전용 비공개 디렉터리를 만듭니다.
Path serviceRoot = destDir.toPath().toRealPath();
Path base = Files.createTempDirectory(serviceRoot, "extract-")
.toRealPath();
try (ZipInputStream zis = new ZipInputStream(zipStream)) {
ZipEntry entry;
byte[] buf = new byte[8192];
while ((entry = zis.getNextEntry()) != null) {
String name = entry.getName();
Path entryPath = Path.of(name);
// 이 예시는 하위 디렉터리 없는 일반 파일 이름만 허용해 심볼릭 링크 부모 경로를 만들지 않습니다.
if (entry.isDirectory() || name.isBlank() || entryPath.isAbsolute()
|| name.indexOf('/') >= 0 || name.indexOf('\\') >= 0
|| name.equals(".") || name.equals("..")) {
throw new IOException("Invalid zip entry name: " + name);
}
Path target = base.resolve(entryPath).normalize();
if (!target.startsWith(base) || !target.getParent().equals(base)) {
throw new IOException("Zip Slip detected: " + name);
}
Set<OpenOption> options = Set.of(
StandardOpenOption.CREATE_NEW,
StandardOpenOption.WRITE,
LinkOption.NOFOLLOW_LINKS);
try (SeekableByteChannel channel = Files.newByteChannel(target, options);
OutputStream os = Channels.newOutputStream(channel)) {
int len;
while ((len = zis.read(buf)) != -1) {
os.write(buf, 0, len);
}
}
}
}
}
}
각 항목은 하위 경로가 없는 파일명이어야 합니다. 파일은 새 디렉터리 바로 아래에 만듭니다. 이름이 겹치면 CREATE_NEW가 생성을 거부합니다.