Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ public Loader loader(LoaderProperties properties) {
properties.getHttp().getConnectTimeoutSeconds(),
properties.getHttp().getResponseTimeoutSeconds(),
properties.getThreadPool().getSize(),
properties.getHttp().getHeaders()
properties.getHttp().getHeaders(),
properties.isPublicNetworkOnly()
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,23 @@ public class LoaderProperties {
private Http http = new Http();
private ThreadPool threadPool = new ThreadPool();

/**
* Only load http(s) URLs on public internet addresses: reject local files and hosts
* resolving to private, loopback or link-local addresses (including URLs listed in the
* discovery file and redirect targets). On by default, because API callers are untrusted.
* Set loader.public-network-only=false (LOADER_PUBLICNETWORKONLY=false) to validate feeds
* on a private network.
*/
private boolean publicNetworkOnly = true;

public boolean isPublicNetworkOnly() {
return publicNetworkOnly;
}

public void setPublicNetworkOnly(boolean publicNetworkOnly) {
this.publicNetworkOnly = publicNetworkOnly;
}

public Http getHttp() {
return http;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ logging.level.org.mobilitydata.gbfs.validator.api.handler.ValidateApiDelegateHan
server.compression.enabled=true
server.compression.min-response-size=1024

# Only load http(s) URLs on public internet addresses (no local files, no private networks)
loader.public-network-only=true

# Loader HTTP client configuration
loader.http.max-total-connections=50
loader.http.max-connections-per-route=20
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package org.mobilitydata.gbfs.validator.api;

import static org.junit.jupiter.api.Assertions.assertTrue;

import org.junit.jupiter.api.Test;
import org.mobilitydata.gbfs.validator.api.handler.LoaderProperties;
import org.mobilitydata.gbfs.validator.api.handler.OpenApiGeneratorApplication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

/** API callers are untrusted: the loader must refuse local files and private networks unless configured otherwise. */
@SpringBootTest(classes = OpenApiGeneratorApplication.class)
public class LoaderDefaultsTest {

@Autowired
private LoaderProperties loaderProperties;

@Test
void apiLoadsOnlyPublicUrlsByDefault() {
assertTrue(loaderProperties.isPublicNetworkOnly());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,11 @@
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;

@SpringBootTest(classes = OpenApiGeneratorApplication.class)
// The test feeds are local files, which the API refuses by default (loader.public-network-only).
@SpringBootTest(
classes = OpenApiGeneratorApplication.class,
properties = "loader.public-network-only=false"
)
@AutoConfigureMockMvc
public class ValidateIntegrationTest {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
import org.apache.hc.core5.http.HttpHeaders;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
Expand All @@ -67,6 +68,7 @@ public class Loader {
private final CloseableHttpClient httpClient;
private final ExecutorService executorService;
private final Map<String, String> customHeaders;
private final boolean publicNetworkOnly;

private String getFileName(URI uri) {
String path = uri.getPath();
Expand Down Expand Up @@ -101,14 +103,55 @@ public Loader(
int responseTimeoutSeconds,
int threadPoolSize,
Map<String, String> customHeaders
) {
this(
maxTotalConnections,
maxConnectionsPerRoute,
connectTimeoutSeconds,
responseTimeoutSeconds,
threadPoolSize,
customHeaders,
false
);
}

/**
* Creates a Loader with custom configuration.
*
* @param maxTotalConnections maximum number of total HTTP connections in the pool
* @param maxConnectionsPerRoute maximum number of connections per route
* @param connectTimeoutSeconds connection timeout in seconds
* @param responseTimeoutSeconds response timeout in seconds
* @param threadPoolSize number of threads for parallel loading
* @param customHeaders custom HTTP headers to include in all requests
* @param publicNetworkOnly when true, only http(s) URLs on public internet addresses are
* loaded: local files and hosts resolving to private, loopback or link-local addresses
* are rejected, including feed URLs listed in the discovery file and redirect targets.
* Enable it when the URLs come from untrusted callers, as in the HTTP API.
*/
public Loader(
int maxTotalConnections,
int maxConnectionsPerRoute,
int connectTimeoutSeconds,
int responseTimeoutSeconds,
int threadPoolSize,
Map<String, String> customHeaders,
boolean publicNetworkOnly
) {
this.customHeaders =
customHeaders != null ? customHeaders : new HashMap<>();

this.publicNetworkOnly = publicNetworkOnly;

PoolingHttpClientConnectionManagerBuilder connectionManagerBuilder =
PoolingHttpClientConnectionManagerBuilder
.create()
.setMaxConnTotal(maxTotalConnections)
.setMaxConnPerRoute(maxConnectionsPerRoute);
if (publicNetworkOnly) {
connectionManagerBuilder.setDnsResolver(new PublicAddressDnsResolver());
}
PoolingHttpClientConnectionManager connectionManager =
new PoolingHttpClientConnectionManager();
connectionManager.setMaxTotal(maxTotalConnections);
connectionManager.setDefaultMaxPerRoute(maxConnectionsPerRoute);
connectionManagerBuilder.build();

RequestConfig requestConfig = RequestConfig
.custom()
Expand Down Expand Up @@ -301,6 +344,16 @@ private LoadedFile loadFile(URI fileURI, Authentication auth) {
String url = fileURI.toString();

if ("file".equals(fileURI.getScheme())) {
if (publicNetworkOnly) {
List<LoaderError> errors = new ArrayList<>();
errors.add(
new LoaderError(
"UNSUPPORTED_SCHEME",
"Local files are not allowed, use an http or https URL"
)
);
return new LoadedFile(fileName, url, null, null, errors);
}
try {
InputStream stream = getFileInputStream(fileURI);
return new LoadedFile(fileName, url, stream, null, new ArrayList<>());
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
/*
*
* *
* *
* * * Licensed under the EUPL, Version 1.2 or – as soon they will be approved by
* * * the European Commission - subsequent versions of the EUPL (the "Licence");
* * * You may not use this work except in compliance with the Licence.
* * * You may obtain a copy of the Licence at:
* * *
* * * https://joinup.ec.europa.eu/software/page/eupl
* * *
* * * Unless required by applicable law or agreed to in writing, software
* * * distributed under the Licence is distributed on an "AS IS" basis,
* * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * * See the Licence for the specific language governing permissions and
* * * limitations under the Licence.
* *
*
*/

package org.mobilitydata.gbfs.validator.loader;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.apache.hc.client5.http.DnsResolver;
import org.apache.hc.client5.http.SystemDefaultDnsResolver;

/**
* DNS resolver that only returns public internet addresses.
*
* <p>Used by {@link Loader} when it fetches URLs supplied by untrusted callers (the HTTP API):
* a feed URL, every URL listed in its discovery file, the OAuth token URL and every redirect
* target are resolved here, and the connection is made to the address checked here. A host
* resolving to a loopback, private, link-local (cloud metadata), carrier-grade NAT, multicast
* or reserved address is rejected, so the validator cannot be used to reach internal services.
*/
public class PublicAddressDnsResolver implements DnsResolver {

private final DnsResolver delegate;

public PublicAddressDnsResolver() {
this(SystemDefaultDnsResolver.INSTANCE);
}

PublicAddressDnsResolver(DnsResolver delegate) {
this.delegate = delegate;
}

@Override
public InetAddress[] resolve(String host) throws UnknownHostException {
InetAddress[] addresses = delegate.resolve(host);
for (InetAddress address : addresses) {
if (!isPublic(address)) {
throw new UnknownHostException(
host + " resolves to a non-public address, which is not allowed"
);
}
}
return addresses;
}

@Override
public String resolveCanonicalHostname(String host)
throws UnknownHostException {
return delegate.resolveCanonicalHostname(host);
}

/**
* Whether the address is a public internet address.
*
* @param address the resolved address
* @return false for loopback, wildcard, private, link-local, multicast, carrier-grade NAT,
* benchmarking, documentation, IETF-reserved and IPv6 unique local addresses
*/
public static boolean isPublic(InetAddress address) {
if (
address.isAnyLocalAddress() ||
address.isLoopbackAddress() ||
address.isLinkLocalAddress() ||
address.isSiteLocalAddress() ||
address.isMulticastAddress()
) {
return false;
}
byte[] bytes = address.getAddress();
if (address instanceof Inet4Address) {
int a = bytes[0] & 0xff;
int b = bytes[1] & 0xff;
int c = bytes[2] & 0xff;
return !(
a == 0 || // "this" network
(a == 100 && b >= 64 && b <= 127) || // carrier-grade NAT
(a == 192 && b == 0 && c == 0) || // IETF protocol assignments
(a == 192 && b == 0 && c == 2) || // documentation (TEST-NET-1)
(a == 198 && (b == 18 || b == 19)) || // benchmarking
(a == 198 && b == 51 && c == 100) || // documentation (TEST-NET-2)
(a == 203 && b == 0 && c == 113) || // documentation (TEST-NET-3)
a >= 240 // reserved and broadcast
);
}
// IPv6 unique local addresses (fc00::/7). IPv4-mapped addresses are returned as Inet4Address.
return (bytes[0] & 0xfe) != 0xfc;
}
}
Loading
Loading