
JavaScript, 인라인 이벤트 핸들러, 스크립트 태그를 제거하고 외부 리소스 로딩을 차단하여 XSS를 방지함으로써 SVG 파일을 정제하는 Java 라이브러리입니다.
SVG Sanitizer는 잠재적으로 위험한 JavaScript를 제거하고, 외부 리소스 로딩을 차단하며, XSS(Cross-Site Scripting) 취약점을 방지하여 SVG 파일을 정리하도록 설계된 Java 라이브러리입니다. 웹 환경을 비롯한 다양한 애플리케이션에서 SVG 파일을 안전하게 사용할 수 있도록 보장하는 데 유용합니다.
<script> 태그를 포함한 SVG 파일 내의 JavaScript를 제거합니다.Java 프로젝트에서 SVG Sanitizer를 사용하려면 io.github.borewit:svg-sanitizer Maven 의존성을 포함하세요.
public class SVGSanitizerExample {
public static void main(String[] args) {
String dirtySvgContent = """
<svg xmlns="http://www.w3.org/2000/svg" width="400" height="400" viewBox="0 0 124 124" fill="none">
<rect width="124" height="124" rx="24" fill="#000000"/>
<script type="text/javascript">
alert(0x539);
</script>
</svg>""";
try {
String sanitizedSvg = SVGSanitizer.sanitize(dirtySvgContent);
System.out.println(sanitizedSvg);
} catch (Exception e) {
e.printStackTrace();
}
}
}
정제된 SVG를 출력합니다:
<svg xmlns="http://www.w3.org/2000/svg" fill="none" height="400" viewBox="0 0 124 124" width="400">
<rect fill="#000000" height="124" rx="24" width="124"/>
</svg>
InputStream에서 OutputStream으로 정제:
import java.io.*;
public class SVGSanitizerExample {
public static void main(String[] args) throws Exception {
File inputFile = new File("unsafe.svg");
File outputFile = new File("sanitized.svg");
try (InputStream inputStream = new FileInputStream(inputFile)) {
try (OutputStream outputStream = new FileOutputStream(outputFile)) {
SVGSanitizer.sanitize(inputStream, outputStream);
}
}
System.out.println("Sanitized SVG has been saved to " + outputFile.getAbsolutePath());
}
}
InputStream에서 InputStream으로 정제:
import java.io.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
public class SVGSanitizerExample {
public static void main(String[] args) throws Exception {
File inputFile = new File("unsafe.svg"); // Potentially unsafe SVG file
try (InputStream inputStream = new FileInputStream(inputFile);
InputStream sanitizedStream = SVGSanitizer.sanitize(inputStream)) {
// Pass the sanitized stream to an XML parser (without converting it to a String)
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(sanitizedStream);
System.out.println("SVG file successfully parsed after sanitization.");
}
}
}
public static String sanitize(String svgContent)
이 방법은 전체 SVG를 메모리에 로드하는 것이 문제가 되지 않는 경우에만 사용해야 합니다.
public static void sanitize(InputStream inputStream, OutputStream outputStream)
주어진 outputStream에 정제된 SVG를 기록합니다
public static InputStream sanitize(InputStream inputStream)
필터 역할을 하여 정제된 SVG를 담은 새로운 InputStream을 반환합니다.
사용자가 업로드한 SVG에는 브라우저 컨텍스트에서 실행될 수 있는 악성 콘텐츠가 포함될 수 있습니다. SVG 정제는 중요한 단계이지만, 완전한 보호를 위해서는 다른 조치와 함께 결합해야 합니다. 더 넓은 개요는 SVG 보안 모범 사례를 참조하세요.
이 프로젝트는 MIT 라이선스에 따라 라이선스가 부여됩니다.