fix(api): stricter SSRF protections (#2357)
This commit is contained in:
@@ -4,6 +4,8 @@ import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@ConfigurationProperties(prefix = "app")
|
||||
@Getter
|
||||
@Setter
|
||||
@@ -12,6 +14,7 @@ public class AppProperties {
|
||||
private String bookdropFolder;
|
||||
private String version;
|
||||
private RemoteAuth remoteAuth;
|
||||
private OutboundRequests outbound;
|
||||
private Boolean forceDisableOidc = false;
|
||||
|
||||
/**
|
||||
@@ -38,4 +41,12 @@ public class AppProperties {
|
||||
private String adminGroup;
|
||||
private String groupsDelimiter = "\\s+"; // Default to whitespace for backward compatibility
|
||||
}
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public static class OutboundRequests {
|
||||
private int connectTimeout = 15;
|
||||
private int readTimeout = 15;
|
||||
private List<String> restrictedRanges = List.of();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,36 +1,65 @@
|
||||
package org.booklore.config;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.boot.http.client.ClientHttpRequestFactoryBuilder;
|
||||
import org.springframework.boot.http.client.HttpClientSettings;
|
||||
import org.springframework.boot.http.client.InetAddressFilter;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.http.client.ClientHttpRequestFactory;
|
||||
import org.springframework.http.client.JdkClientHttpRequestFactory;
|
||||
import org.springframework.http.client.SimpleClientHttpRequestFactory;
|
||||
import org.springframework.web.client.RestClient;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
import java.net.http.HttpClient;
|
||||
import java.time.Duration;
|
||||
|
||||
@Configuration
|
||||
@RequiredArgsConstructor
|
||||
public class RestClientConfig {
|
||||
private ClientHttpRequestFactory getRequestFactory(HttpClient httpClient) {
|
||||
JdkClientHttpRequestFactory factory = new JdkClientHttpRequestFactory(httpClient);
|
||||
factory.setReadTimeout(Duration.ofSeconds(15));
|
||||
return factory;
|
||||
private final AppProperties appProperties;
|
||||
|
||||
@Bean
|
||||
public InetAddressFilter outboundInetAddressFilter() {
|
||||
var filter = InetAddressFilter
|
||||
.not(InetAddressFilter.multicast());
|
||||
|
||||
var restrictedRanges = appProperties.getOutbound().getRestrictedRanges();
|
||||
|
||||
if (!restrictedRanges.isEmpty()) {
|
||||
filter = filter.andNot(restrictedRanges.toArray(new String[]{}));
|
||||
}
|
||||
|
||||
return filter;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public RestClient restClient(HttpClient httpClient) {
|
||||
public ClientHttpRequestFactory clientHttpRequestFactory(InetAddressFilter outboundInetAddressFilter) {
|
||||
var outbound = appProperties.getOutbound();
|
||||
int connectTimeout = outbound.getConnectTimeout();
|
||||
int readTimeout = outbound.getReadTimeout();
|
||||
|
||||
HttpClientSettings settings = HttpClientSettings.defaults()
|
||||
.withConnectTimeout(Duration.ofSeconds(connectTimeout))
|
||||
.withReadTimeout(Duration.ofSeconds(readTimeout))
|
||||
.withInetAddressFilter(outboundInetAddressFilter);
|
||||
|
||||
return ClientHttpRequestFactoryBuilder
|
||||
.jdk()
|
||||
.build(settings);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public RestClient restClient(ClientHttpRequestFactory clientHttpRequestFactory) {
|
||||
return RestClient.builder()
|
||||
.requestFactory(getRequestFactory(httpClient))
|
||||
.requestFactory(clientHttpRequestFactory)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Primary
|
||||
public RestTemplate restTemplate(HttpClient httpClient) {
|
||||
return new RestTemplate(getRequestFactory(httpClient));
|
||||
public RestTemplate restTemplate(ClientHttpRequestFactory clientHttpRequestFactory) {
|
||||
return new RestTemplate(clientHttpRequestFactory);
|
||||
}
|
||||
|
||||
@Bean
|
||||
|
||||
@@ -328,14 +328,6 @@ public class SecurityConfig {
|
||||
return auth.build();
|
||||
}
|
||||
|
||||
@Bean("noRedirectRestTemplate")
|
||||
public RestTemplate noRedirectRestTemplate() {
|
||||
HttpClient httpClient = HttpClient.newBuilder()
|
||||
.followRedirects(HttpClient.Redirect.NEVER)
|
||||
.build();
|
||||
return new RestTemplate(new JdkClientHttpRequestFactory(httpClient));
|
||||
}
|
||||
|
||||
@Bean
|
||||
public CorsConfigurationSource corsConfigurationSource() {
|
||||
CorsConfiguration configuration = new CorsConfiguration();
|
||||
|
||||
@@ -8,12 +8,8 @@ import org.booklore.model.entity.BookMetadataEntity;
|
||||
import org.booklore.service.appsettings.AppSettingService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
import org.springframework.web.client.RestClient;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
@@ -25,9 +21,6 @@ import java.io.ByteArrayInputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.InetAddress;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
@@ -36,7 +29,6 @@ import java.util.Comparator;
|
||||
import java.util.Iterator;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Stream;
|
||||
import java.net.UnknownHostException;
|
||||
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
@@ -44,12 +36,8 @@ import java.net.UnknownHostException;
|
||||
public class FileService {
|
||||
|
||||
private final AppProperties appProperties;
|
||||
private final RestTemplate restTemplate;
|
||||
private final AppSettingService appSettingService;
|
||||
private final RestTemplate noRedirectRestTemplate;
|
||||
|
||||
private static final int MAX_REDIRECTS = 5;
|
||||
|
||||
private final RestClient restClient;
|
||||
|
||||
private static final double TARGET_COVER_ASPECT_RATIO = 1.5;
|
||||
private static final int SMART_CROP_COLOR_TOLERANCE = 30;
|
||||
@@ -293,7 +281,12 @@ public class FileService {
|
||||
|
||||
public BufferedImage downloadImageFromUrl(String imageUrl) throws IOException {
|
||||
try {
|
||||
return downloadImageFromUrlInternal(imageUrl);
|
||||
return readImage(
|
||||
restClient.get()
|
||||
.uri(imageUrl)
|
||||
.retrieve()
|
||||
.body(byte[].class)
|
||||
);
|
||||
} catch (Exception e) {
|
||||
log.warn("Failed to download image from {}: {}", imageUrl, e.getMessage());
|
||||
if (e instanceof IOException ioException) {
|
||||
@@ -303,144 +296,6 @@ public class FileService {
|
||||
}
|
||||
}
|
||||
|
||||
private BufferedImage downloadImageFromUrlInternal(String imageUrl) throws IOException {
|
||||
String currentUrl = imageUrl;
|
||||
int redirectCount = 0;
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
// 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() + ")");
|
||||
}
|
||||
}
|
||||
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.set(HttpHeaders.USER_AGENT, "Grimmory/1.0 (Book and Comic Metadata Fetcher; +https://github.com/grimmory-tools/grimmory)");
|
||||
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");
|
||||
}
|
||||
URI redirectUri = uri.resolve(location);
|
||||
|
||||
// When a CDN redirects to a raw IP (e.g. CloudFront -> 3.168.64.124),
|
||||
// the Host header would become the bare IP, which the CDN rejects with
|
||||
// 400. Rewrite the URL to keep the previous hostname so the JDK
|
||||
// HttpClient sets the correct Host header automatically.
|
||||
if (isRawIpAddress(redirectUri.getHost())) {
|
||||
try {
|
||||
redirectUri = new URI(
|
||||
redirectUri.getScheme(),
|
||||
redirectUri.getUserInfo(),
|
||||
host,
|
||||
redirectUri.getPort(),
|
||||
redirectUri.getPath(),
|
||||
redirectUri.getQuery(),
|
||||
redirectUri.getFragment()
|
||||
);
|
||||
} catch (URISyntaxException e) {
|
||||
throw new IOException("Invalid redirect URI: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
currentUrl = redirectUri.toString();
|
||||
redirectCount++;
|
||||
} else {
|
||||
throw new IOException("Failed to download image. HTTP Status: " + response.getStatusCode());
|
||||
}
|
||||
}
|
||||
|
||||
throw new IOException("Too many redirects (max " + MAX_REDIRECTS + ")");
|
||||
}
|
||||
|
||||
private boolean isRawIpAddress(String host) {
|
||||
if (host == null) {
|
||||
return false;
|
||||
}
|
||||
// IPv6 in URI brackets
|
||||
if (host.startsWith("[")) {
|
||||
return true;
|
||||
}
|
||||
// IPv4: all segments are digits
|
||||
String[] parts = host.split("\\.");
|
||||
if (parts.length == 4) {
|
||||
for (String part : parts) {
|
||||
if (!part.chars().allMatch(Character::isDigit)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean isInternalAddress(InetAddress address) {
|
||||
if (address.isLoopbackAddress() || address.isLinkLocalAddress() ||
|
||||
address.isSiteLocalAddress() || address.isAnyLocalAddress()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
byte[] addr = address.getAddress();
|
||||
// Check for IPv6 Unique Local Address (fc00::/7)
|
||||
if (addr.length == 16) {
|
||||
if ((addr[0] & 0xFE) == (byte) 0xFC) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Handle IPv4-mapped IPv6 addresses (::ffff:127.0.0.1)
|
||||
if (isIpv4MappedAddress(addr)) {
|
||||
try {
|
||||
byte[] ipv4Bytes = new byte[4];
|
||||
System.arraycopy(addr, 12, ipv4Bytes, 0, 4);
|
||||
InetAddress ipv4Addr = InetAddress.getByAddress(ipv4Bytes);
|
||||
return isInternalAddress(ipv4Addr);
|
||||
} catch (UnknownHostException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private boolean isIpv4MappedAddress(byte[] addr) {
|
||||
if (addr.length != 16) return false;
|
||||
for (int i = 0; i < 10; i++) {
|
||||
if (addr[i] != 0) return false;
|
||||
}
|
||||
return (addr[10] == (byte) 0xFF) && (addr[11] == (byte) 0xFF);
|
||||
}
|
||||
|
||||
// ========================================
|
||||
// COVER OPERATIONS
|
||||
// ========================================
|
||||
|
||||
@@ -22,6 +22,40 @@ app:
|
||||
force-disable-oidc: ${FORCE_DISABLE_OIDC:false}
|
||||
disk-type: ${DISK_TYPE:LOCAL}
|
||||
|
||||
outbound:
|
||||
connect-timeout: 15
|
||||
read-timeout: 15
|
||||
restricted-ranges:
|
||||
- "0.0.0.0/8" # "This host on this network" - RFC 6890 - https://datatracker.ietf.org/doc/html/rfc6890
|
||||
- "10.0.0.0/8" # Private Network Prefix - RFC 1918 - https://datatracker.ietf.org/doc/html/rfc1918
|
||||
- "100::/64" # IPv6 Discard Prefix - RFC 6666 - https://datatracker.ietf.org/doc/html/rfc6666
|
||||
- "100.64.0.0/10" # Shared Address Space - RFC 6890 - https://datatracker.ietf.org/doc/html/rfc6890
|
||||
- "::1/128" # IPv6 Loopback - RFC 4291 - https://datatracker.ietf.org/doc/html/rfc4291
|
||||
- "127.0.0.0/8" # Loopback - RFC 6890 - https://datatracker.ietf.org/doc/html/rfc6890
|
||||
- "::/128" # "Unspecified" - RFC 4291 - https://datatracker.ietf.org/doc/html/rfc4291
|
||||
- "169.254.0.0/16" # Link Local - RFC 6890 - https://datatracker.ietf.org/doc/html/rfc6890
|
||||
- "172.16.0.0/12" # Private Use - RFC 6890 - https://datatracker.ietf.org/doc/html/rfc6890
|
||||
- "192.0.0.0/24" # IETF Protocol Assignments - RFC 6890 - https://datatracker.ietf.org/doc/html/rfc6890
|
||||
- "192.0.0.0/29" # DS-Lite - RFC 6333 - https://datatracker.ietf.org/doc/html/rfc6333
|
||||
- "192.0.2.0/24" # TEST-NET-1 - RFC 5737 - https://datatracker.ietf.org/doc/html/rfc5737
|
||||
- "192.168.0.0/16" # Private Use - RFC 6890 - https://datatracker.ietf.org/doc/html/rfc6890
|
||||
- "192.88.99.0/24" # An Anycast Prefix for 6to4 Relay Routers - RFC 3068 - https://datatracker.ietf.org/doc/html/rfc3068
|
||||
- "198.18.0.0/15" # Network Interconnect Device Benchmark Testing - RFC 2544 - https://datatracker.ietf.org/doc/html/rfc2544
|
||||
- "198.51.100.0/24" # TEST-NET-2 - RFC 5737 - https://datatracker.ietf.org/doc/html/rfc5737
|
||||
- "2001:10::/28" # IPv6 ORCHID Prefix - RFC 7343 - https://datatracker.ietf.org/doc/html/rfc7343
|
||||
- "2001::/23" # Initial IPv6 Sub-TLA ID Assignments - RFC 2928 - https://datatracker.ietf.org/doc/html/rfc2928
|
||||
- "2001:0200::/48" # IPv6 Benchmarking Prefix - RFC 5180 - https://datatracker.ietf.org/doc/html/rfc5180
|
||||
- "2001::/32" # IPv6 Global Teredo Prefix - RFC 4380 - https://datatracker.ietf.org/doc/html/rfc4380
|
||||
- "2001:db8::/32" # IPv6 Documentation Prefix - RFC 3849 - https://datatracker.ietf.org/doc/html/rfc3849
|
||||
- "2002::/16" # Connection of IPv6 Domains via IPv4 Clouds - RFC 3056 - https://datatracker.ietf.org/doc/html/rfc3056
|
||||
- "203.0.113.0/24" # TEST-NET-3 - RFC 5737 - https://datatracker.ietf.org/doc/html/rfc5737
|
||||
- "240.0.0.0/4" # Reserved - RFC 6890 - https://datatracker.ietf.org/doc/html/rfc6890
|
||||
- "255.255.255.255/32" # Limited Broadcast - RFC 0919 - https://datatracker.ietf.org/doc/html/rfc0919
|
||||
- "64:ff9b:1::/48" # Local-Use IPv4/IPv6 Translation Prefix - RFC 8215 - https://datatracker.ietf.org/doc/html/rfc8215
|
||||
- "64:ff9b::/96" # IPv6 Addressing of IPv4/IPv6 Translators - RFC 6052 - https://datatracker.ietf.org/doc/html/rfc6052
|
||||
- "fc00::/7" # Unique Local IPv6 Unicast Addresses - RFC 4193 - https://datatracker.ietf.org/doc/html/rfc4193
|
||||
- "fe80::/10" # Link-Local unicast - RFC 4291 - https://datatracker.ietf.org/doc/html/rfc4291
|
||||
|
||||
server:
|
||||
forward-headers-strategy: native
|
||||
port: ${SERVER_PORT:${BOOKLORE_PORT:6060}}
|
||||
|
||||
Reference in New Issue
Block a user