Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(Custom Targets): restrict Custom Targets domains #444

Merged
merged 17 commits into from
May 29, 2024
Merged
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
2 changes: 2 additions & 0 deletions src/main/java/io/cryostat/ConfigProperties.java
Original file line number Diff line number Diff line change
Expand Up @@ -56,4 +56,6 @@ public class ConfigProperties {

public static final String TEMPLATES_DIR = "templates-dir";
public static final String SSL_TRUSTSTORE_DIR = "ssl.truststore.dir";

public static final String URI_RANGE = "cryostat.target.uri-range";
}
52 changes: 0 additions & 52 deletions src/main/java/io/cryostat/URIUtil.java

This file was deleted.

5 changes: 3 additions & 2 deletions src/main/java/io/cryostat/discovery/ContainerDiscovery.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,12 @@
import javax.management.remote.JMXServiceURL;

import io.cryostat.ConfigProperties;
import io.cryostat.URIUtil;
import io.cryostat.core.net.JFRConnectionToolkit;
import io.cryostat.core.sys.FileSystem;
import io.cryostat.targets.Target;
import io.cryostat.targets.Target.Annotations;
import io.cryostat.targets.Target.EventKind;
import io.cryostat.util.URIUtil;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
Expand Down Expand Up @@ -177,6 +177,7 @@ public abstract class ContainerDiscovery {
@Inject JFRConnectionToolkit connectionToolkit;
@Inject ObjectMapper mapper;
@Inject EventBus bus;
@Inject URIUtil uriUtil;

@ConfigProperty(name = ConfigProperties.CONTAINERS_POLL_PERIOD)
Duration pollPeriod;
Expand Down Expand Up @@ -242,7 +243,7 @@ private Target toTarget(ContainerSpec desc) {
serviceUrl = new JMXServiceURL(desc.Labels.get(JMX_URL_LABEL));
connectUrl = URI.create(serviceUrl.toString());
try {
rmiTarget = URIUtil.getRmiTarget(serviceUrl);
rmiTarget = uriUtil.getRmiTarget(serviceUrl);
hostname = rmiTarget.getHost();
jmxPort = rmiTarget.getPort();
} catch (IllegalArgumentException e) {
Expand Down
33 changes: 32 additions & 1 deletion src/main/java/io/cryostat/discovery/CustomDiscovery.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
import io.cryostat.targets.Target;
import io.cryostat.targets.Target.Annotations;
import io.cryostat.targets.TargetConnectionManager;
import io.cryostat.util.URIUtil;

import io.quarkus.narayana.jta.QuarkusTransaction;
import io.quarkus.runtime.StartupEvent;
Expand Down Expand Up @@ -69,6 +70,7 @@ public class CustomDiscovery {
@Inject Logger logger;
@Inject EventBus bus;
@Inject TargetConnectionManager connectionManager;
@Inject URIUtil uriUtil;

@ConfigProperty(name = ConfigProperties.CONNECTIONS_FAILED_TIMEOUT)
Duration timeout;
Expand All @@ -95,6 +97,23 @@ void onStart(@Observes StartupEvent evt) {
@RolesAllowed("write")
public Response create(
Target target, @RestQuery boolean dryrun, @RestQuery boolean storeCredentials) {
try {
if (!uriUtil.validateUri(target.connectUrl)) {
return Response.status(Response.Status.BAD_REQUEST)
.entity(
String.format(
"The provided URI \"%s\" is unacceptable with the"
+ " current URI range settings.",
target.connectUrl))
.build();
}
// Continue with target creation if URI is valid...
} catch (Exception e) {
andrewazores marked this conversation as resolved.
Show resolved Hide resolved
logger.error("Target validation failed", e);
return Response.status(Response.Status.BAD_REQUEST)
.entity(V2Response.json(Response.Status.BAD_REQUEST, e))
.build();
}
// TODO handle credentials embedded in JSON body
return doV2Create(target, Optional.empty(), dryrun, storeCredentials);
}
Expand Down Expand Up @@ -136,9 +155,20 @@ Response doV2Create(
var beginTx = !QuarkusTransaction.isActive();
if (beginTx) {
QuarkusTransaction.begin();
} else {
// No changes needed for this error
}
try {
target.connectUrl = sanitizeConnectUrl(target.connectUrl.toString());
if (!uriUtil.validateUri(target.connectUrl)) {
return Response.status(Response.Status.BAD_REQUEST)
.entity(
String.format(
"The provided URI \"%s\" is unacceptable with the"
+ " current URI range settings.",
target.connectUrl))
.build();
}

try {
target.jvmId =
Expand Down Expand Up @@ -188,7 +218,8 @@ Response doV2Create(
.entity(V2Response.json(Response.Status.CREATED, target))
.build();
} catch (Exception e) {
// roll back regardless of whether we initiated this database transaction or a caller
// roll back regardless of whether we initiated this database transaction or a
// caller
// did
QuarkusTransaction.rollback();
if (ExceptionUtils.indexOfType(e, ConstraintViolationException.class) >= 0) {
Expand Down
63 changes: 41 additions & 22 deletions src/main/java/io/cryostat/discovery/Discovery.java
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@

import io.cryostat.discovery.DiscoveryPlugin.PluginCallback;
import io.cryostat.targets.TargetConnectionManager;
import io.cryostat.util.URIUtil;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
Expand Down Expand Up @@ -103,6 +104,7 @@ public class Discovery {
@Inject DiscoveryJwtFactory jwtFactory;
@Inject DiscoveryJwtValidator jwtValidator;
@Inject Scheduler scheduler;
@Inject URIUtil uriUtil;

@Transactional
void onStart(@Observes StartupEvent evt) {
Expand Down Expand Up @@ -182,6 +184,7 @@ public RestResponse<Void> checkRegistration(
@SuppressFBWarnings("DLS_DEAD_LOCAL_STORE")
public Response register(@Context RoutingContext ctx, JsonObject body)
throws URISyntaxException,
MalformedURLException,
JOSEException,
UnknownHostException,
SocketException,
Expand All @@ -194,6 +197,17 @@ public Response register(@Context RoutingContext ctx, JsonObject body)
URI callbackUri = new URI(body.getString("callback"));
URI unauthCallback = UriBuilder.fromUri(callbackUri).userInfo(null).build();

// URI range validation
if (!uriUtil.validateUri(callbackUri)) {
return Response.status(Response.Status.BAD_REQUEST)
.entity(
String.format(
"cryostat.target.callback of \"%s\" is unacceptable with the"
+ " current URI range settings",
callbackUri))
.build();
}

// TODO apply URI range validation to the remote address
InetAddress remoteAddress = getRemoteAddress(ctx);
URI location;
Expand All @@ -212,8 +226,10 @@ public Response register(@Context RoutingContext ctx, JsonObject body)
location = jwtFactory.getPluginLocation(plugin);
jwtFactory.parseDiscoveryPluginJwt(plugin, priorToken, location, remoteAddress, false);
} else {
// check if a plugin record with the same callback already exists. If it does, ping it:
// if it's still there reject this request as a duplicate, otherwise delete the previous
// check if a plugin record with the same callback already exists. If it does,
// ping it:
// if it's still there reject this request as a duplicate, otherwise delete the
// previous
// record and accept this new one as a replacement
DiscoveryPlugin.<DiscoveryPlugin>find("callback", unauthCallback)
.singleResultOptional()
Expand Down Expand Up @@ -272,7 +288,8 @@ public Response register(@Context RoutingContext ctx, JsonObject body)

String token = jwtFactory.createDiscoveryPluginJwt(plugin, remoteAddress, location);

// TODO implement more generic env map passing by some platform detection strategy or
// TODO implement more generic env map passing by some platform detection
// strategy or
// generalized config properties
var envMap = new HashMap<String, String>();
String insightsProxy = System.getenv("INSIGHTS_PROXY");
Expand All @@ -283,19 +300,19 @@ public Response register(@Context RoutingContext ctx, JsonObject body)
.entity(
Map.of(
"meta",
Map.of(
"mimeType", "JSON",
"status", "OK"),
Map.of(
"mimeType", "JSON",
"status", "OK"),
"data",
Map.of(
"result",
Map.of(
"result",
Map.of(
"id",
plugin.id.toString(),
"token",
token,
"env",
envMap))))
"id",
plugin.id.toString(),
"token",
token,
"env",
envMap))))
.build();
}

Expand Down Expand Up @@ -331,10 +348,11 @@ public Map<String, Map<String, String>> publish(

return Map.of(
"meta",
Map.of(
"mimeType", "JSON",
"status", "OK"),
"data", Map.of("result", plugin.id.toString()));
Map.of(
"mimeType", "JSON",
"status", "OK"),
"data",
Map.of("result", plugin.id.toString()));
}

@Transactional
Expand Down Expand Up @@ -366,10 +384,11 @@ public Map<String, Map<String, String>> deregister(
plugin.delete();
return Map.of(
"meta",
Map.of(
"mimeType", "JSON",
"status", "OK"),
"data", Map.of("result", plugin.id.toString()));
Map.of(
"mimeType", "JSON",
"status", "OK"),
"data",
Map.of("result", plugin.id.toString()));
}

@GET
Expand Down
5 changes: 3 additions & 2 deletions src/main/java/io/cryostat/discovery/JDPDiscovery.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,11 @@

import javax.management.remote.JMXServiceURL;

import io.cryostat.URIUtil;
import io.cryostat.core.net.discovery.JvmDiscoveryClient;
import io.cryostat.core.net.discovery.JvmDiscoveryClient.JvmDiscoveryEvent;
import io.cryostat.targets.Target;
import io.cryostat.targets.Target.Annotations;
import io.cryostat.util.URIUtil;

import io.quarkus.runtime.ShutdownEvent;
import io.quarkus.runtime.StartupEvent;
Expand Down Expand Up @@ -60,6 +60,7 @@ static JvmDiscoveryClient produceJvmDiscoveryClient() {
@Inject JvmDiscoveryClient jdp;
@Inject Vertx vertx;
@Inject EventBus eventBus;
@Inject URIUtil uriUtil;

@ConfigProperty(name = "cryostat.discovery.jdp.enabled")
boolean enabled;
Expand Down Expand Up @@ -116,7 +117,7 @@ void handleJdpEvent(JvmDiscoveryEvent evt) {
try {
JMXServiceURL serviceUrl = evt.getJvmDescriptor().getJmxServiceUrl();
connectUrl = URI.create(serviceUrl.toString());
rmiTarget = URIUtil.getRmiTarget(serviceUrl);
rmiTarget = uriUtil.getRmiTarget(serviceUrl);
} catch (MalformedURLException | URISyntaxException e) {
logger.warn("Invalid JDP target observed", e);
return;
Expand Down
67 changes: 67 additions & 0 deletions src/main/java/io/cryostat/util/URIRange.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/*
* Copyright The Cryostat Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.cryostat.util;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public enum URIRange {
LOOPBACK(hostname -> check(hostname, InetAddress::isLoopbackAddress)),
LINK_LOCAL(hostname -> check(hostname, InetAddress::isLinkLocalAddress)),
SITE_LOCAL(hostname -> check(hostname, InetAddress::isSiteLocalAddress)),
DNS_LOCAL(hostname -> hostname.endsWith(".local") || hostname.endsWith(".localhost")),
PUBLIC(hostname -> true);

private static final Logger log = LoggerFactory.getLogger(URIRange.class);
private final Predicate<String> fn;

private URIRange(Predicate<String> fn) {
this.fn = fn;
}

private static boolean check(String hostname, Predicate<InetAddress> predicate) {
try {
InetAddress address = InetAddress.getByName(hostname);
return predicate.test(address);
} catch (UnknownHostException uhe) {
log.error("Failed to resolve host", uhe);
return false;
}
}

public boolean validate(String hostname) {
List<URIRange> ranges =
List.of(values()).stream()
.filter(r -> r.ordinal() <= this.ordinal())
.collect(Collectors.toList());
return ranges.stream().anyMatch(range -> range.fn.test(hostname));
}

public static URIRange fromString(String s) {
for (URIRange range : URIRange.values()) {
if (range.name().equalsIgnoreCase(s)) {
return range;
}
}
return SITE_LOCAL;
}
}
Loading
Loading