설명
파일을 업로드한 뒤 서버가 코드를 실행하거나 브라우저가 파일을 웹페이지로 해석할 수 있습니다. 어떤 형식을 받아 어디에 저장하고 어떻게 제공할지 정하세요.
잠재적 영향
서버가 업로드를 JSP, ASP 또는 PHP 스크립트로 처리하면 코드가 실행될 수 있습니다. 인터프리터가 파일을 읽을 수 있으면 파일 자체에 실행 권한이 없어도 실행될 수 있습니다.
해결 방법
- 서버에서 저장 이름을 생성하고 크기와 실제 파일 형식을 확인하세요. 클라이언트가 보낸 파일명과 MIME 타입만으로 형식을 판단하지 마세요.
- 웹 루트 밖에 저장하고 쓰기 권한을 제한하세요. 웹 서버와 후속 처리기가 업로드 파일을 실행하지 않게 설정하세요. 디렉터리에는 파일을 찾는 데 필요한 접근 권한을 유지하세요.
- 정규화한 경로의 구성 요소를 비교해 저장 대상이 업로드 디렉터리 안에 있는지 확인하고, 새 파일만 원자적으로 생성하세요.
- 추가 처리가 필요하면 악성 코드를 검사하고 격리된 환경에서 처리하세요.
예시
변경 전
java
@PostMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file) throws IOException {
// 파일을 서버에 저장하는 위험한 코드
String fileName = file.getOriginalFilename();
File destinationFile = new File("/uploads/" + fileName);
file.transferTo(destinationFile);
return "uploadSuccess";
}
변경 후
Java 11 이상 예시입니다. 업로드 디렉터리를 미리 만들고 애플리케이션이 그 안에 파일을 쓸 수 있게 하세요. 다른 사용자가 이 디렉터리나 상위 경로를 바꿔 저장 위치를 변경하지 못하게 하세요. Spring의 multipart 요청 크기도 제한하고 저장한 텍스트를 실행하거나 HTML로 그대로 제공하지 마세요.
java
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.UUID;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
@RestController
public final class SafeUploadController {
private static final Path UPLOAD_ROOT =
Path.of("/var/lib/myapp/uploads").toAbsolutePath().normalize();
private static final long MAX_TEXT_SIZE = 1024 * 1024;
@PostMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file) throws IOException {
if (file.isEmpty() || file.getSize() > MAX_TEXT_SIZE) {
throw new IOException("Invalid file size");
}
byte[] content = file.getBytes();
String text;
try {
text = StandardCharsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT)
.decode(ByteBuffer.wrap(content))
.toString();
} catch (CharacterCodingException e) {
throw new IOException("The upload is not valid UTF-8 text", e);
}
if (text.codePoints().anyMatch(c -> c == 0
|| (Character.isISOControl(c) && c != '\n' && c != '\r' && c != '\t'))) {
throw new IOException("Invalid text content");
}
String storedName = UUID.randomUUID() + ".txt";
Path target = UPLOAD_ROOT.resolve(storedName).normalize();
if (!target.startsWith(UPLOAD_ROOT)) {
throw new IOException("Invalid upload destination");
}
// UPLOAD_ROOT를 웹 루트 밖에 미리 만들고, 업로드 파일의 코드 실행을 막습니다.
Files.write(target, content, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
return "uploadSuccess";
}
}
변경 후에는 1 MiB 이하의 비어 있지 않은 UTF-8 텍스트만 받으며, 허용하지 않은 제어 문자를 거부합니다. 저장 경로를 확인한 뒤 UUID 기반 .txt 파일을 CREATE_NEW로 만듭니다. 형식 검사와 악성 코드 검사는 별개입니다.
관련 CVE
- CVE-2023-5227: PHP-based FAQ management app does not check the MIME type for uploaded images
- CVE-2001-0901: Web-based mail product stores ".shtml" attachments that could contain SSI
- CVE-2002-1841: PHP upload does not restrict file types