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(TLS): HTTPS client truststore #448

Merged
merged 23 commits into from
Aug 7, 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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,7 @@ and how it advertises itself to a Cryostat server instance. Properties that requ
- [ ] `cryostat.agent.webclient.tls.version` [`String`]: the version of TLS used for the Agent's client SSL context. Default `TLSv1.2`.
- [ ] `cryostat.agent.webclient.tls.trust-all` [`boolean`]: control whether the agent trusts all certificates presented by the Cryostat server. Default `false`. This should only be overridden for development and testing purposes, never in production.
- [ ] `cryostat.agent.webclient.tls.verify-hostname` [`boolean`]: control whether the agent verifies hostnames on certificates presented by the Cryostat server. Default `true`. This should only be overridden for development and testing purposes, never in production.
- [ ] `cryostat.agent.webclient.tls.certs` [`list`]: the list of truststoreConfig objects with alias, path, and type properties for certificates to be stored in the agent's truststore. For example, 'cryostat.agent.webclient.tls.certs[0].type' would be the type of the first certificate in this list. A truststoreConfig object must contain all three properties to be a valid certificate entry.
- [ ] `cryostat.agent.webclient.connect.timeout-ms` [`long`]: the duration in milliseconds to wait for HTTP requests to the Cryostat server to connect. Default `1000`.
- [ ] `cryostat.agent.webclient.response.timeout-ms` [`long`]: the duration in milliseconds to wait for HTTP requests to the Cryostat server to respond. Default `1000`.
- [ ] `cryostat.agent.webserver.host` [`String`]: the internal hostname or IP address for the embedded webserver to bind to. Default `0.0.0.0`.
Expand Down
69 changes: 69 additions & 0 deletions src/main/java/io/cryostat/agent/ConfigModule.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,18 @@
import java.security.NoSuchAlgorithmException;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

import javax.inject.Named;
import javax.inject.Singleton;
Expand Down Expand Up @@ -70,6 +76,11 @@ public abstract class ConfigModule {
"cryostat.agent.webclient.connect.timeout-ms";
public static final String CRYOSTAT_AGENT_WEBCLIENT_RESPONSE_TIMEOUT_MS =
"cryostat.agent.webclient.response.timeout-ms";
public static final String CRYOSTAT_AGENT_WEBCLIENT_TLS_TRUSTSTORES =
"cryostat.agent.webclient.tls.truststore.cert";
public static final Pattern CRYOSTAT_AGENT_TRUSTSTORE_PATTERN =
Pattern.compile(
"^(?:cryostat\\.agent\\.webclient\\.tls\\.truststore\\.cert)\\[(?<index>\\d+)\\]\\.(?<property>.*)$");

public static final String CRYOSTAT_AGENT_WEBSERVER_HOST = "cryostat.agent.webserver.host";
public static final String CRYOSTAT_AGENT_WEBSERVER_PORT = "cryostat.agent.webserver.port";
Expand Down Expand Up @@ -159,6 +170,64 @@ public static Config provideConfig() {
}
}

@Provides
@Singleton
@Named(CRYOSTAT_AGENT_WEBCLIENT_TLS_TRUSTSTORES)
public static List<TruststoreConfig> provideTruststoreConfigs(Config config) {
Map<Integer, TruststoreConfig.Builder> truststoreBuilders = new HashMap<>();
StreamSupport.stream(config.getPropertyNames().spliterator(), false)
.filter(e -> e.startsWith(CRYOSTAT_AGENT_WEBCLIENT_TLS_TRUSTSTORES))
.forEach(
name -> {
Matcher matcher = CRYOSTAT_AGENT_TRUSTSTORE_PATTERN.matcher(name);
if (!matcher.matches()) {
throw new IllegalArgumentException(
String.format(
"Invalid truststore config property name format:"
+ " \"%s\". Make sure the config property"
+ " matches the following pattern:"
+ " 'cryostat.agent.truststore.cert[CERT_NUMBER].CERT_PROPERTY'",
name));
}
int truststoreNumber = Integer.parseInt(matcher.group("index"));
String configProp = matcher.group("property");

TruststoreConfig.Builder truststoreBuilder =
truststoreBuilders.computeIfAbsent(
truststoreNumber, k -> new TruststoreConfig.Builder());

String value = config.getValue(name, String.class);
switch (configProp) {
case "alias":
truststoreBuilder = truststoreBuilder.withAlias(value);
break;
case "path":
truststoreBuilder = truststoreBuilder.withPath(value);
break;
case "type":
truststoreBuilder = truststoreBuilder.withType(value);
break;
default:
throw new IllegalArgumentException(
String.format(
"Truststore config only includes alias, path,"
+ " and type. Rename this config property:"
+ " %s",
name));
}
});

List<TruststoreConfig> truststoreConfigs = new ArrayList<>();
for (TruststoreConfig.Builder builder : truststoreBuilders.values()) {
try {
truststoreConfigs.add(builder.build());
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
return truststoreConfigs;
}

@Provides
@Named(CRYOSTAT_AGENT_BASEURI_RANGE)
public static URIRange provideUriRange(Config config) {
Expand Down
133 changes: 110 additions & 23 deletions src/main/java/io/cryostat/agent/MainModule.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
Expand Down Expand Up @@ -77,10 +78,10 @@

@Module(
includes = {
ConfigModule.class,
RemoteModule.class,
HarvestModule.class,
TriggerModule.class,
ConfigModule.class,
})
public abstract class MainModule {

Expand Down Expand Up @@ -130,34 +131,121 @@ public static WebServer provideWebServer(
@Named(HTTP_CLIENT_SSL_CTX)
public static SSLContext provideClientSslContext(
@Named(ConfigModule.CRYOSTAT_AGENT_WEBCLIENT_TLS_VERSION) String clientTlsVersion,
@Named(ConfigModule.CRYOSTAT_AGENT_WEBCLIENT_TLS_TRUST_ALL) boolean trustAll) {
@Named(ConfigModule.CRYOSTAT_AGENT_WEBCLIENT_TLS_TRUST_ALL) boolean trustAll,
@Named(ConfigModule.CRYOSTAT_AGENT_WEBCLIENT_TLS_TRUSTSTORES)
List<TruststoreConfig> truststores) {
try {
if (!trustAll) {
return SSLContext.getDefault();
if (trustAll) {
SSLContext sslCtx = SSLContext.getInstance(clientTlsVersion);
sslCtx.init(
null,
new TrustManager[] {
new X509TrustManager() {
@Override
public void checkClientTrusted(
X509Certificate[] chain, String authType)
throws CertificateException {}

@Override
public void checkServerTrusted(
X509Certificate[] chain, String authType)
throws CertificateException {}

@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
},
null);
return sslCtx;
}

SSLContext sslCtx = SSLContext.getInstance(clientTlsVersion);
sslCtx.init(
null,
new TrustManager[] {
new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {}

@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {}

@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];

// set up trust manager factory
TrustManagerFactory tmf =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init((KeyStore) null);

X509TrustManager defaultTrustManager = null;
for (TrustManager tm : tmf.getTrustManagers()) {
if (tm instanceof X509TrustManager) {
defaultTrustManager = (X509TrustManager) tm;
break;
}
}

// initialize truststore
KeyStore ts = KeyStore.getInstance(KeyStore.getDefaultType());
ts.load(null, null);

for (TruststoreConfig truststore : truststores) {
// load truststore with certificatesCertificate
InputStream certFile = new FileInputStream(truststore.getPath());
CertificateFactory cf = CertificateFactory.getInstance(truststore.getType());
Certificate cert = cf.generateCertificate(certFile);
if (ts.containsAlias(truststore.getType())) {
throw new IllegalStateException(
String.format(
"truststore already contains a certificate with alias"
+ " \"%s\"",
truststore.getAlias()));
}
ts.setCertificateEntry(truststore.getAlias(), cert);
certFile.close();
}

// set up trust manager factory
tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ts);

X509TrustManager customTrustManager = null;
for (TrustManager tm : tmf.getTrustManagers()) {
if (tm instanceof X509TrustManager) {
customTrustManager = (X509TrustManager) tm;
break;
}
}

final X509TrustManager finalDefaultTM = defaultTrustManager;
final X509TrustManager finalCustomTM = customTrustManager;
X509TrustManager mergedTrustManager =
new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
try {
finalCustomTM.checkClientTrusted(chain, authType);
} catch (CertificateException e) {
finalDefaultTM.checkClientTrusted(chain, authType);
}
}

@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
try {
finalCustomTM.checkServerTrusted(chain, authType);
} catch (CertificateException e) {
finalDefaultTM.checkServerTrusted(chain, authType);
}
}
},
null);

@Override
public X509Certificate[] getAcceptedIssuers() {
return finalDefaultTM.getAcceptedIssuers();
}
};

// set up HTTPS context
sslCtx.init(null, new TrustManager[] {mergedTrustManager}, null);
return sslCtx;
} catch (NoSuchAlgorithmException | KeyManagementException e) {
} catch (NoSuchAlgorithmException
| KeyManagementException
| KeyStoreException
| CertificateException
| IOException e) {
throw new RuntimeException(e);
}
}
Expand Down Expand Up @@ -271,7 +359,6 @@ public static HttpClient provideHttpClient(
if (!verifyHostname) {
builder = builder.setSSLHostnameVerifier((hostname, session) -> true);
}

return builder.build();
}

Expand Down
98 changes: 98 additions & 0 deletions src/main/java/io/cryostat/agent/TruststoreConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
/*
* 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.agent;

import java.util.Objects;

public class TruststoreConfig {
private final String alias;
private final String path;
private final String type;

private TruststoreConfig(Builder builder) {
this.alias =
Objects.requireNonNull(
builder.alias,
"Truststore config properties must include a certificate alias");
this.path =
Objects.requireNonNull(
builder.path,
"Truststore config properties must include a certificate path");
this.type =
Objects.requireNonNull(
builder.type,
"Truststore config properties must include a certificate type");
}

public String getAlias() {
return this.alias;
}

public String getPath() {
return this.path;
}

public String getType() {
return this.type;
}

public static class Builder {
private String alias;
private String path;
private String type;

public Builder withAlias(String alias) {
this.alias = alias;
return this;
}

public Builder withPath(String path) {
this.path = path;
return this;
}

public Builder withType(String type) {
this.type = type;
return this;
}

public TruststoreConfig build() {
return new TruststoreConfig(this);
}
}

@Override
public int hashCode() {
return Objects.hash(alias, path, type);
}

@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
TruststoreConfig other = (TruststoreConfig) obj;
return Objects.equals(alias, other.alias)
&& Objects.equals(path, other.path)
&& Objects.equals(type, other.type);
}
}
Loading