simplify image download SSRF protection, remove broken IP-rewriting approach (#3118)

This commit is contained in:
ACX
2026-02-28 13:50:44 -07:00
committed by GitHub
parent 5b5b7c06f4
commit 26497ca790
3 changed files with 52 additions and 169 deletions
@@ -14,10 +14,6 @@ import org.booklore.config.BookmarkProperties;
@SpringBootApplication
public class BookloreApplication {
static {
System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
}
public static void main(String[] args) {
SpringApplication.run(BookloreApplication.class, args);
}
@@ -5,7 +5,7 @@ import org.booklore.config.security.service.OpdsUserDetailsService;
import jakarta.servlet.DispatcherType;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.booklore.util.FileService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
@@ -26,10 +26,9 @@ import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.client.JdkClientHttpRequestFactory;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.http.HttpClient;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
@@ -37,15 +36,6 @@ import java.util.regex.Pattern;
import lombok.extern.slf4j.Slf4j;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SNIHostName;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Collections;
@Slf4j
@AllArgsConstructor
@EnableMethodSecurity
@@ -258,71 +248,10 @@ public class SecurityConfig {
@Bean("noRedirectRestTemplate")
public RestTemplate noRedirectRestTemplate() {
return new RestTemplate(
new SimpleClientHttpRequestFactory() {
@Override
protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
super.prepareConnection(connection, httpMethod);
connection.setInstanceFollowRedirects(false);
String targetHost = FileService.getTargetHost();
if (targetHost != null) {
connection.setRequestProperty("Host", targetHost);
}
if (connection instanceof HttpsURLConnection httpsConnection) {
if (targetHost != null) {
// Set original host for SNI (even if connecting to IP)
SSLSocketFactory defaultFactory = httpsConnection.getSSLSocketFactory();
httpsConnection.setSSLSocketFactory(new SniSSLSocketFactory(defaultFactory, targetHost));
httpsConnection.setHostnameVerifier((hostname, session) -> {
String expectedHost = FileService.getTargetHost();
if (expectedHost != null) {
// Verify certificate against the original expected hostname, even if connecting via IP
return HttpsURLConnection.getDefaultHostnameVerifier().verify(expectedHost, session);
}
// Fallback: use default verifier for the hostname we connected to
return HttpsURLConnection.getDefaultHostnameVerifier().verify(hostname, session);
});
}
}
}
}
);
}
private static class SniSSLSocketFactory extends SSLSocketFactory {
private final SSLSocketFactory delegate;
private final String targetHost;
public SniSSLSocketFactory(SSLSocketFactory delegate, String targetHost) {
this.delegate = delegate;
this.targetHost = targetHost;
}
@Override
public String[] getDefaultCipherSuites() { return delegate.getDefaultCipherSuites(); }
@Override
public String[] getSupportedCipherSuites() { return delegate.getSupportedCipherSuites(); }
@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
// Pass targetHost instead of host (which is the IP) so the internal SSLSession gets the correct peer host
Socket socket = delegate.createSocket(s, targetHost, port, autoClose);
if (socket instanceof SSLSocket sslSocket) {
SNIHostName serverName = new SNIHostName(targetHost);
SSLParameters params = sslSocket.getSSLParameters();
params.setServerNames(Collections.singletonList(serverName));
// Explicitly set EndpointIdentificationAlgorithm so Java verifies the certificate against targetHost
params.setEndpointIdentificationAlgorithm("HTTPS");
sslSocket.setSSLParameters(params);
}
return socket;
}
@Override public Socket createSocket(String host, int port) throws IOException { return delegate.createSocket(host, port); }
@Override public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException { return delegate.createSocket(host, port, localHost, localPort); }
@Override public Socket createSocket(InetAddress host, int port) throws IOException { return delegate.createSocket(host, port); }
@Override public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException { return delegate.createSocket(address, port, localAddress, localPort); }
HttpClient httpClient = HttpClient.newBuilder()
.followRedirects(HttpClient.Redirect.NEVER)
.build();
return new RestTemplate(new JdkClientHttpRequestFactory(httpClient));
}
@Bean
@@ -43,20 +43,6 @@ import java.util.stream.Stream;
@Service
public class FileService {
private static final ThreadLocal<String> TARGET_HOST_THREAD_LOCAL = new ThreadLocal<>();
public static String getTargetHost() {
return TARGET_HOST_THREAD_LOCAL.get();
}
public static void setTargetHost(String host) {
TARGET_HOST_THREAD_LOCAL.set(host);
}
public static void clearTargetHost() {
TARGET_HOST_THREAD_LOCAL.remove();
}
private final AppProperties appProperties;
private final RestTemplate restTemplate;
private final AppSettingService appSettingService;
@@ -280,83 +266,55 @@ public class FileService {
String currentUrl = imageUrl;
int redirectCount = 0;
try {
while (redirectCount <= MAX_REDIRECTS) {
URI uri = URI.create(currentUrl);
// Protocol validation
if (!"http".equalsIgnoreCase(uri.getScheme()) && !"https".equalsIgnoreCase(uri.getScheme())) {
throw new IOException("Only HTTP and HTTPS protocols are allowed");
}
while (redirectCount <= MAX_REDIRECTS) {
URI uri = URI.create(currentUrl);
if (!"http".equalsIgnoreCase(uri.getScheme()) && !"https".equalsIgnoreCase(uri.getScheme())) {
throw new IOException("Only HTTP and HTTPS protocols are allowed");
}
String host = uri.getHost();
if (host == null) {
throw new IOException("Invalid URL: no host found in " + currentUrl);
}
String host = uri.getHost();
if (host == null) {
throw new IOException("Invalid URL: no host found in " + currentUrl);
}
// Resolve host to IP to prevent DNS rebinding (TOCTOU)
InetAddress[] inetAddresses = InetAddress.getAllByName(host);
if (inetAddresses.length == 0) {
throw new IOException("Could not resolve host: " + host);
}
for (InetAddress inetAddress : inetAddresses) {
if (isInternalAddress(inetAddress)) {
throw new SecurityException("URL points to a local or private internal network address: " + host + " (" + inetAddress.getHostAddress() + ")");
}
}
String ipAddress = inetAddresses[0].getHostAddress();
// Set target host for SNI / Hostname verification in RestTemplate/SSLSocketFactory
setTargetHost(host);
// Build request URL with IP address to ensure we connect to the validated address.
// We keep the original URI's path and query.
String portSuffix = (uri.getPort() != -1) ? ":" + uri.getPort() : "";
String path = uri.getRawPath();
if (path == null || path.isEmpty()) path = "/";
String query = uri.getRawQuery();
// Handle IPv6 address formatting in URL
String hostInUrl = ipAddress;
if (ipAddress.contains(":")) {
hostInUrl = "[" + ipAddress + "]";
}
String requestUrl = uri.getScheme() + "://" + hostInUrl + portSuffix + path + (query != null ? "?" + query : "");
HttpHeaders headers = new HttpHeaders();
// Host header is set in prepareConnection via setRequestProperty.
// Do NOT set it here: Spring's addRequestProperty would add a duplicate,
// and duplicate Host headers cause 400 on strict CDNs like CloudFront.
headers.set(HttpHeaders.USER_AGENT, "BookLore/1.0 (Book and Comic Metadata Fetcher; +https://github.com/booklore-app/booklore)");
headers.set(HttpHeaders.ACCEPT, "image/*");
HttpEntity<String> entity = new HttpEntity<>(headers);
log.debug("Downloading image via IP-based URL: {} (Original host: {})", requestUrl, host);
ResponseEntity<byte[]> response = noRedirectRestTemplate.exchange(
requestUrl,
HttpMethod.GET,
entity,
byte[].class
);
if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
return readImage(response.getBody());
} else if (response.getStatusCode().is3xxRedirection()) {
String location = response.getHeaders().getFirst(HttpHeaders.LOCATION);
if (location == null) {
throw new IOException("Redirection response without Location header");
}
// Resolve location against CURRENT URL (which has the hostname)
currentUrl = uri.resolve(location).toString();
redirectCount++;
} else {
throw new IOException("Failed to download image. HTTP Status: " + response.getStatusCode());
// Validate resolved IPs to block SSRF against internal networks
InetAddress[] inetAddresses = InetAddress.getAllByName(host);
if (inetAddresses.length == 0) {
throw new IOException("Could not resolve host: " + host);
}
for (InetAddress inetAddress : inetAddresses) {
if (isInternalAddress(inetAddress)) {
throw new SecurityException("URL points to a local or private internal network address: " + host + " (" + inetAddress.getHostAddress() + ")");
}
}
} finally {
// Ensure thread-local is cleared to prevent leakage to subsequent requests (container thread reuse)
clearTargetHost();
HttpHeaders headers = new HttpHeaders();
headers.set(HttpHeaders.USER_AGENT, "BookLore/1.0 (Book and Comic Metadata Fetcher; +https://github.com/booklore-app/booklore)");
headers.set(HttpHeaders.ACCEPT, "image/*");
HttpEntity<String> entity = new HttpEntity<>(headers);
log.debug("Downloading image from: {}", currentUrl);
ResponseEntity<byte[]> response = noRedirectRestTemplate.exchange(
currentUrl,
HttpMethod.GET,
entity,
byte[].class
);
if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
return readImage(response.getBody());
} else if (response.getStatusCode().is3xxRedirection()) {
String location = response.getHeaders().getFirst(HttpHeaders.LOCATION);
if (location == null) {
throw new IOException("Redirection response without Location header");
}
currentUrl = uri.resolve(location).toString();
redirectCount++;
} else {
throw new IOException("Failed to download image. HTTP Status: " + response.getStatusCode());
}
}
throw new IOException("Too many redirects (max " + MAX_REDIRECTS + ")");