You are viewing a plain text version of this content. The canonical link for it is here.
Posted to pr@cassandra.apache.org by "frankgh (via GitHub)" <gi...@apache.org> on 2024/02/15 21:52:45 UTC
[PR] CASSANDRA-18951: Add option for MutualTlsAuthenticator to restrict the certificate age [cassandra]
frankgh opened a new pull request, #3109:
URL: https://github.com/apache/cassandra/pull/3109
In this commit, we introduce a new parameter option for the `MutualTlsAuthenticator`. The new option is `max_certificate_age`, and it can be configured as a duration configuration parameter as defined by the `DurationSpec` (see CASSANDRA-15234). The resolution for this new property is minutes.
When specified, the certificate validation implementation will take that information and reject certificates that are older than the maximum allowed certificate age, translating into a rejection from the authenticating user.
patch by Francisco Guerrero; reviewed by TBD for CASSANDRA-18951
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-18951: Add option for MutualTlsAuthenticator to restrict the certificate age [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3109:
URL: https://github.com/apache/cassandra/pull/3109#discussion_r1529346996
##########
src/java/org/apache/cassandra/auth/MutualTlsCertificateValidityPeriodValidator.java:
##########
@@ -0,0 +1,90 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cassandra.auth;
+
+import java.security.cert.Certificate;
+import java.security.cert.X509Certificate;
+import java.time.temporal.ChronoUnit;
+import java.util.Date;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+import org.apache.cassandra.config.DurationSpec;
+import org.apache.cassandra.exceptions.AuthenticationException;
+import org.apache.cassandra.utils.FBUtilities;
+
+public class MutualTlsCertificateValidityPeriodValidator
+{
+ @Nonnull
+ private final int maxCertificateValidityPeriodMinutes;
+
+ public MutualTlsCertificateValidityPeriodValidator(@Nullable DurationSpec.IntMinutesBound maxCertificateValidityPeriod)
+ {
+ maxCertificateValidityPeriodMinutes = maxCertificateValidityPeriod != null
+ ? maxCertificateValidityPeriod.toMinutes()
+ // Sufficiently large value that exceeds any reasonable valid configuration
+ : Integer.MAX_VALUE;
+ }
+
+ /**
+ * Validates that the certificate's validity period does not exceed the {@code #maxCertificateValidityPeriod}
+ * and returns the number of minutes to certificate expiration since the verification started.
+ *
+ * @param certificates the certificate chain
+ * @return the number of minutes to certificate expiration since the verification started, or {@code -1}
+ * if no certificate chain was provided
+ * @throws AuthenticationException when the {@link X509Certificate#getNotBefore()} or
+ * {@link X509Certificate#getNotAfter()} dates are null, or when the certificate
+ * validity exceeds the maximum allowed certificate validity
+ */
+ public int validate(Certificate[] certificates) throws AuthenticationException
+ {
+ X509Certificate[] x509Certificates = MutualTlsUtil.castCertsToX509(certificates);
+ if (x509Certificates == null || x509Certificates.length == 0)
+ {
+ return -1;
+ }
+
+ Date notBefore = x509Certificates[0].getNotBefore();
+ Date notAfter = x509Certificates[0].getNotAfter();
+
+ if (notBefore == null || notAfter == null)
+ {
+ throw new AuthenticationException("The provided certificate does not have a notBefore / notAfter field");
Review Comment:
One nit: This would throw an exception even if someone didn't have `max_certificate_validity_period` enabled, which maybe a regression, although I doubt it would be a problem for anyone, but to be on the safe side it may be good to only throw here if the property is configured.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-18951: Add option for MutualTlsAuthenticator to restrict the certificate age [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3109:
URL: https://github.com/apache/cassandra/pull/3109#discussion_r1491823435
##########
src/java/org/apache/cassandra/auth/SpiffeCertificateValidator.java:
##########
@@ -31,27 +32,45 @@
* This class assumes that the identity of a certificate is SPIFFE which is a URI that is present as part of the SAN
* of the client certificate. It has logic to extract identity (Spiffe) out of a certificate & knows how to validate
* the client certificates.
- * <p>
*
- * <p>
- * Example:
+ * <p>Example:
+ * <pre>
* internode_authenticator:
- * class_name : org.apache.cassandra.auth.MutualTlsAuthenticator
- * parameters :
- * validator_class_name: org.apache.cassandra.auth.SpiffeCertificateValidator
+ * class_name: org.apache.cassandra.auth.MutualTlsAuthenticator
+ * parameters:
+ * validator_class_name: org.apache.cassandra.auth.SpiffeCertificateValidator
+ * </pre>
+ *
+ * <pre>
* authenticator:
- * class_name : org.apache.cassandra.auth.MutualTlsInternodeAuthenticator
- * parameters :
- * validator_class_name: org.apache.cassandra.auth.SpiffeCertificateValidator
+ * class_name: org.apache.cassandra.auth.MutualTlsInternodeAuthenticator
+ * parameters:
+ * validator_class_name: org.apache.cassandra.auth.SpiffeCertificateValidator
+ * </pre>
*/
public class SpiffeCertificateValidator implements MutualTlsCertificateValidator
{
+ /**
+ * {@inheritDoc}
+ */
@Override
- public boolean isValidCertificate(Certificate[] clientCertificateChain)
+ public boolean isValidCertificate(Certificate[] clientCertificateChain, int maxCertificateAgeMinutes) throws AuthenticationException
{
+ X509Certificate[] castedCerts = castCertsToX509(clientCertificateChain);
+ int certificateAgeInMinutes = getCertificateAgeInMinutes(castedCerts[0]);
+ if (certificateAgeInMinutes > maxCertificateAgeMinutes)
+ {
+ String errorMessage = String.format("The age of the provided certificate exceeds the maximum allowed age of %d minutes",
Review Comment:
Is there a way to introspect what resolution the given duration is in and report it in that way? e.g. if I configure `max_certificate_age: 5d` , could we have the message be The age of the provided certificate exceeds the maximum allowed age of 5d?.
It would also be useful to include the age of the certificate in the message.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-18951: Add option for MutualTlsAuthenticator to restrict the certificate age [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3109:
URL: https://github.com/apache/cassandra/pull/3109#discussion_r1491830983
##########
conf/cassandra.yaml:
##########
@@ -158,6 +158,7 @@ authenticator:
# class_name : org.apache.cassandra.auth.MutualTlsAuthenticator
# parameters :
# validator_class_name: org.apache.cassandra.auth.SpiffeCertificateValidator
+# max_certificate_age: 365d
Review Comment:
would be good to document that if not explicitly set, this is not validated.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-18951: Add option for MutualTlsAuthenticator to restrict the certificate age [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3109:
URL: https://github.com/apache/cassandra/pull/3109#discussion_r1529344058
##########
src/java/org/apache/cassandra/auth/MutualTlsAuthenticator.java:
##########
@@ -208,9 +224,29 @@ public AuthenticatedUser getAuthenticatedUser() throws AuthenticationException
nospamLogger.error(msg, identity);
throw new AuthenticationException(MessageFormatter.format(msg, identity).getMessage());
}
+
+ // Validates that the certificate validity period does not exceed the maximum certificate configured validity period
+ int minutesToCertificateExpiration = certificateValidityPeriodValidator.validate(clientCertificateChain);
+ int daysToCertificateExpiration = toDays(minutesToCertificateExpiration);
+
+ if (certificateValidityWarnThreshold != null
+ && minutesToCertificateExpiration < certificateValidityWarnThreshold.toMinutes())
+ {
+ nospamLogger.warn("Certificate with identity '{}' will expire in {} minutes",
+ identity, minutesToCertificateExpiration);
+ }
+
+ // Report metrics on client certificate expiration
+ MutualTlsMetrics.instance.clientCertificateExpirationDays.update(daysToCertificateExpiration);
+
return new AuthenticatedUser(role, MTLS, Collections.singletonMap(METADATA_IDENTITY_KEY, identity));
}
+ private int toDays(int minutes)
+ {
+ return (int) TimeUnit.MINUTES.toDays(minutes);
Review Comment:
just realized, something like 30 minutes will convert to 0 days, which may lead someone to believe that they have a certificate that is expired when they are really close on the margin. It's probably fine but could see that possibly be misleading.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-18951: Add option for MutualTlsAuthenticator to restrict the certificate age [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3109:
URL: https://github.com/apache/cassandra/pull/3109#discussion_r1529373319
##########
test/distributed/org/apache/cassandra/distributed/test/auth/MutualTlsCertificateValidityPeriodTest.java:
##########
@@ -0,0 +1,329 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cassandra.distributed.test.auth;
+
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.nio.file.Path;
+import java.time.Instant;
+import java.time.temporal.ChronoUnit;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Optional;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.stream.StreamSupport;
+import javax.net.ssl.SSLException;
+
+import com.google.common.collect.ImmutableMap;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.ClassRule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.datastax.driver.core.PlainTextAuthProvider;
+import com.datastax.driver.core.RemoteEndpointAwareJdkSSLOptions;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Row;
+import com.datastax.driver.core.SSLOptions;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.core.SimpleStatement;
+import com.datastax.driver.core.policies.LoadBalancingPolicy;
+import org.apache.cassandra.config.EncryptionOptions;
+import org.apache.cassandra.distributed.Cluster;
+import org.apache.cassandra.distributed.api.Feature;
+import org.apache.cassandra.distributed.api.ICluster;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.shared.ClusterUtils;
+import org.apache.cassandra.distributed.test.JavaDriverUtils;
+import org.apache.cassandra.distributed.test.TestBaseImpl;
+import org.apache.cassandra.distributed.util.Auth;
+import org.apache.cassandra.distributed.util.SingleHostLoadBalancingPolicy;
+import org.apache.cassandra.security.ISslContextFactory;
+import org.apache.cassandra.transport.SimpleClientSslContextFactory;
+import org.apache.cassandra.utils.tls.CertificateBuilder;
+import org.apache.cassandra.utils.tls.CertificateBundle;
+import org.assertj.core.api.Assertions;
+import org.assertj.core.api.InstanceOfAssertFactories;
+
+import static org.apache.cassandra.auth.CassandraRoleManager.DEFAULT_SUPERUSER_NAME;
+import static org.apache.cassandra.auth.CassandraRoleManager.DEFAULT_SUPERUSER_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.CLIENT_TRUSTSTORE_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.SERVER_KEYSTORE_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.SERVER_TRUSTSTORE_PASSWORD;
+import static org.assertj.core.api.Assertions.as;
+import static org.assertj.core.api.Assertions.fail;
+
+/**
+ * Tests mTLS certificate validity period functionality
+ */
+public class MutualTlsCertificateValidityPeriodTest extends TestBaseImpl
+{
+ private static final Logger LOGGER = LoggerFactory.getLogger(MutualTlsCertificateValidityPeriodTest.class);
+ private static final String IDENTITY = "spiffe://test.cassandra.apache.org/dTest/mtls";
+ private static ICluster<IInvokableInstance> CLUSTER;
+ private static final char[] KEYSTORE_PASSWORD = "cassandra".toCharArray();
+
+ @ClassRule
+ public static TemporaryFolder tempFolder = new TemporaryFolder();
+
+ static CertificateBundle CA;
+ static Path truststorePath;
+
+ @BeforeClass
+ public static void setupClass() throws Exception
+ {
+ LOGGER.info("[test step : @BeforeClass] setupClass");
+ Cluster.Builder builder = Cluster.build(1);
+
+ CA = new CertificateBuilder().subject("CN=Apache Cassandra Root CA, OU=Certification Authority, O=Unknown, C=Unknown")
+ .alias("fakerootca")
+ .isCertificateAuthority(true)
+ .buildSelfSigned();
+
+ truststorePath = CA.toTempKeyStorePath(tempFolder.getRoot().toPath(),
+ SERVER_TRUSTSTORE_PASSWORD.toCharArray(),
+ SERVER_TRUSTSTORE_PASSWORD.toCharArray());
+
+
+ CertificateBundle keystore = new CertificateBuilder().subject("CN=Apache Cassandra, OU=ssl_test, O=Unknown, L=Unknown, ST=Unknown, C=Unknown")
+ .addSanDnsName(InetAddress.getLocalHost().getCanonicalHostName())
+ .addSanDnsName(InetAddress.getLocalHost().getHostName())
+ .buildIssuedBy(CA);
+
+ Path serverKeystorePath = keystore.toTempKeyStorePath(tempFolder.getRoot().toPath(),
+ SERVER_KEYSTORE_PASSWORD.toCharArray(),
+ SERVER_KEYSTORE_PASSWORD.toCharArray());
+
+ builder.withConfig(c -> c.set("authenticator.class_name", "org.apache.cassandra.auth.MutualTlsWithPasswordFallbackAuthenticator")
+ .set("authenticator.parameters", Collections.singletonMap("validator_class_name", "org.apache.cassandra.auth.SpiffeCertificateValidator"))
+ .set("role_manager", "CassandraRoleManager")
+ .set("authorizer", "CassandraAuthorizer")
+ .set("client_encryption_options.enabled", "true")
+ .set("client_encryption_options.require_client_auth", "optional")
+ .set("client_encryption_options.keystore", serverKeystorePath.toString())
+ .set("client_encryption_options.keystore_password", SERVER_KEYSTORE_PASSWORD)
+ .set("client_encryption_options.truststore", truststorePath.toString())
+ .set("client_encryption_options.truststore_password", SERVER_TRUSTSTORE_PASSWORD)
+ .set("client_encryption_options.require_endpoint_verification", "false")
+ .set("client_encryption_options.max_certificate_validity_period", "30d")
+ .set("client_encryption_options.certificate_validity_warn_threshold", "5d")
+ .with(Feature.NATIVE_PROTOCOL, Feature.GOSSIP));
+ CLUSTER = builder.start();
+
+ configureIdentity();
+ }
+
+ @AfterClass
+ public static void teardown() throws Exception
+ {
+ LOGGER.info("[test step : @AfterClass] teardown");
+ if (CLUSTER != null)
+ CLUSTER.close();
+ }
+
+ @Test
+ public void testExpiringCertificate() throws Exception
Review Comment:
Should this be `testValidCertificate`? From what I can tell this generates a valid certificate and verifies it can connect.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-18951: Add option for MutualTlsAuthenticator to restrict the certificate age [cassandra]
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on PR #3109:
URL: https://github.com/apache/cassandra/pull/3109#issuecomment-2014020318
force pushing after rebasing
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-18951: Add option for MutualTlsAuthenticator to restrict the certificate age [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3109:
URL: https://github.com/apache/cassandra/pull/3109#discussion_r1529374787
##########
test/distributed/org/apache/cassandra/distributed/test/auth/MutualTlsCertificateValidityPeriodTest.java:
##########
@@ -0,0 +1,329 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cassandra.distributed.test.auth;
+
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.nio.file.Path;
+import java.time.Instant;
+import java.time.temporal.ChronoUnit;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Optional;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.stream.StreamSupport;
+import javax.net.ssl.SSLException;
+
+import com.google.common.collect.ImmutableMap;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.ClassRule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.datastax.driver.core.PlainTextAuthProvider;
+import com.datastax.driver.core.RemoteEndpointAwareJdkSSLOptions;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Row;
+import com.datastax.driver.core.SSLOptions;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.core.SimpleStatement;
+import com.datastax.driver.core.policies.LoadBalancingPolicy;
+import org.apache.cassandra.config.EncryptionOptions;
+import org.apache.cassandra.distributed.Cluster;
+import org.apache.cassandra.distributed.api.Feature;
+import org.apache.cassandra.distributed.api.ICluster;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.shared.ClusterUtils;
+import org.apache.cassandra.distributed.test.JavaDriverUtils;
+import org.apache.cassandra.distributed.test.TestBaseImpl;
+import org.apache.cassandra.distributed.util.Auth;
+import org.apache.cassandra.distributed.util.SingleHostLoadBalancingPolicy;
+import org.apache.cassandra.security.ISslContextFactory;
+import org.apache.cassandra.transport.SimpleClientSslContextFactory;
+import org.apache.cassandra.utils.tls.CertificateBuilder;
+import org.apache.cassandra.utils.tls.CertificateBundle;
+import org.assertj.core.api.Assertions;
+import org.assertj.core.api.InstanceOfAssertFactories;
+
+import static org.apache.cassandra.auth.CassandraRoleManager.DEFAULT_SUPERUSER_NAME;
+import static org.apache.cassandra.auth.CassandraRoleManager.DEFAULT_SUPERUSER_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.CLIENT_TRUSTSTORE_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.SERVER_KEYSTORE_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.SERVER_TRUSTSTORE_PASSWORD;
+import static org.assertj.core.api.Assertions.as;
+import static org.assertj.core.api.Assertions.fail;
+
+/**
+ * Tests mTLS certificate validity period functionality
+ */
+public class MutualTlsCertificateValidityPeriodTest extends TestBaseImpl
+{
+ private static final Logger LOGGER = LoggerFactory.getLogger(MutualTlsCertificateValidityPeriodTest.class);
+ private static final String IDENTITY = "spiffe://test.cassandra.apache.org/dTest/mtls";
+ private static ICluster<IInvokableInstance> CLUSTER;
+ private static final char[] KEYSTORE_PASSWORD = "cassandra".toCharArray();
+
+ @ClassRule
+ public static TemporaryFolder tempFolder = new TemporaryFolder();
+
+ static CertificateBundle CA;
+ static Path truststorePath;
+
+ @BeforeClass
+ public static void setupClass() throws Exception
+ {
+ LOGGER.info("[test step : @BeforeClass] setupClass");
+ Cluster.Builder builder = Cluster.build(1);
+
+ CA = new CertificateBuilder().subject("CN=Apache Cassandra Root CA, OU=Certification Authority, O=Unknown, C=Unknown")
+ .alias("fakerootca")
+ .isCertificateAuthority(true)
+ .buildSelfSigned();
+
+ truststorePath = CA.toTempKeyStorePath(tempFolder.getRoot().toPath(),
+ SERVER_TRUSTSTORE_PASSWORD.toCharArray(),
+ SERVER_TRUSTSTORE_PASSWORD.toCharArray());
+
+
+ CertificateBundle keystore = new CertificateBuilder().subject("CN=Apache Cassandra, OU=ssl_test, O=Unknown, L=Unknown, ST=Unknown, C=Unknown")
+ .addSanDnsName(InetAddress.getLocalHost().getCanonicalHostName())
+ .addSanDnsName(InetAddress.getLocalHost().getHostName())
+ .buildIssuedBy(CA);
+
+ Path serverKeystorePath = keystore.toTempKeyStorePath(tempFolder.getRoot().toPath(),
+ SERVER_KEYSTORE_PASSWORD.toCharArray(),
+ SERVER_KEYSTORE_PASSWORD.toCharArray());
+
+ builder.withConfig(c -> c.set("authenticator.class_name", "org.apache.cassandra.auth.MutualTlsWithPasswordFallbackAuthenticator")
+ .set("authenticator.parameters", Collections.singletonMap("validator_class_name", "org.apache.cassandra.auth.SpiffeCertificateValidator"))
+ .set("role_manager", "CassandraRoleManager")
+ .set("authorizer", "CassandraAuthorizer")
+ .set("client_encryption_options.enabled", "true")
+ .set("client_encryption_options.require_client_auth", "optional")
+ .set("client_encryption_options.keystore", serverKeystorePath.toString())
+ .set("client_encryption_options.keystore_password", SERVER_KEYSTORE_PASSWORD)
+ .set("client_encryption_options.truststore", truststorePath.toString())
+ .set("client_encryption_options.truststore_password", SERVER_TRUSTSTORE_PASSWORD)
+ .set("client_encryption_options.require_endpoint_verification", "false")
+ .set("client_encryption_options.max_certificate_validity_period", "30d")
+ .set("client_encryption_options.certificate_validity_warn_threshold", "5d")
+ .with(Feature.NATIVE_PROTOCOL, Feature.GOSSIP));
+ CLUSTER = builder.start();
+
+ configureIdentity();
+ }
+
+ @AfterClass
+ public static void teardown() throws Exception
+ {
+ LOGGER.info("[test step : @AfterClass] teardown");
+ if (CLUSTER != null)
+ CLUSTER.close();
+ }
+
+ @Test
+ public void testExpiringCertificate() throws Exception
Review Comment:
I see, expires within a day, should expect it to log something, did you intend to add logging validationh ere?
##########
test/distributed/org/apache/cassandra/distributed/test/auth/MutualTlsCertificateValidityPeriodTest.java:
##########
@@ -0,0 +1,329 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cassandra.distributed.test.auth;
+
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.nio.file.Path;
+import java.time.Instant;
+import java.time.temporal.ChronoUnit;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Optional;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.stream.StreamSupport;
+import javax.net.ssl.SSLException;
+
+import com.google.common.collect.ImmutableMap;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.ClassRule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.datastax.driver.core.PlainTextAuthProvider;
+import com.datastax.driver.core.RemoteEndpointAwareJdkSSLOptions;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Row;
+import com.datastax.driver.core.SSLOptions;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.core.SimpleStatement;
+import com.datastax.driver.core.policies.LoadBalancingPolicy;
+import org.apache.cassandra.config.EncryptionOptions;
+import org.apache.cassandra.distributed.Cluster;
+import org.apache.cassandra.distributed.api.Feature;
+import org.apache.cassandra.distributed.api.ICluster;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.shared.ClusterUtils;
+import org.apache.cassandra.distributed.test.JavaDriverUtils;
+import org.apache.cassandra.distributed.test.TestBaseImpl;
+import org.apache.cassandra.distributed.util.Auth;
+import org.apache.cassandra.distributed.util.SingleHostLoadBalancingPolicy;
+import org.apache.cassandra.security.ISslContextFactory;
+import org.apache.cassandra.transport.SimpleClientSslContextFactory;
+import org.apache.cassandra.utils.tls.CertificateBuilder;
+import org.apache.cassandra.utils.tls.CertificateBundle;
+import org.assertj.core.api.Assertions;
+import org.assertj.core.api.InstanceOfAssertFactories;
+
+import static org.apache.cassandra.auth.CassandraRoleManager.DEFAULT_SUPERUSER_NAME;
+import static org.apache.cassandra.auth.CassandraRoleManager.DEFAULT_SUPERUSER_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.CLIENT_TRUSTSTORE_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.SERVER_KEYSTORE_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.SERVER_TRUSTSTORE_PASSWORD;
+import static org.assertj.core.api.Assertions.as;
+import static org.assertj.core.api.Assertions.fail;
+
+/**
+ * Tests mTLS certificate validity period functionality
+ */
+public class MutualTlsCertificateValidityPeriodTest extends TestBaseImpl
+{
+ private static final Logger LOGGER = LoggerFactory.getLogger(MutualTlsCertificateValidityPeriodTest.class);
+ private static final String IDENTITY = "spiffe://test.cassandra.apache.org/dTest/mtls";
+ private static ICluster<IInvokableInstance> CLUSTER;
+ private static final char[] KEYSTORE_PASSWORD = "cassandra".toCharArray();
+
+ @ClassRule
+ public static TemporaryFolder tempFolder = new TemporaryFolder();
+
+ static CertificateBundle CA;
+ static Path truststorePath;
+
+ @BeforeClass
+ public static void setupClass() throws Exception
+ {
+ LOGGER.info("[test step : @BeforeClass] setupClass");
+ Cluster.Builder builder = Cluster.build(1);
+
+ CA = new CertificateBuilder().subject("CN=Apache Cassandra Root CA, OU=Certification Authority, O=Unknown, C=Unknown")
+ .alias("fakerootca")
+ .isCertificateAuthority(true)
+ .buildSelfSigned();
+
+ truststorePath = CA.toTempKeyStorePath(tempFolder.getRoot().toPath(),
+ SERVER_TRUSTSTORE_PASSWORD.toCharArray(),
+ SERVER_TRUSTSTORE_PASSWORD.toCharArray());
+
+
+ CertificateBundle keystore = new CertificateBuilder().subject("CN=Apache Cassandra, OU=ssl_test, O=Unknown, L=Unknown, ST=Unknown, C=Unknown")
+ .addSanDnsName(InetAddress.getLocalHost().getCanonicalHostName())
+ .addSanDnsName(InetAddress.getLocalHost().getHostName())
+ .buildIssuedBy(CA);
+
+ Path serverKeystorePath = keystore.toTempKeyStorePath(tempFolder.getRoot().toPath(),
+ SERVER_KEYSTORE_PASSWORD.toCharArray(),
+ SERVER_KEYSTORE_PASSWORD.toCharArray());
+
+ builder.withConfig(c -> c.set("authenticator.class_name", "org.apache.cassandra.auth.MutualTlsWithPasswordFallbackAuthenticator")
+ .set("authenticator.parameters", Collections.singletonMap("validator_class_name", "org.apache.cassandra.auth.SpiffeCertificateValidator"))
+ .set("role_manager", "CassandraRoleManager")
+ .set("authorizer", "CassandraAuthorizer")
+ .set("client_encryption_options.enabled", "true")
+ .set("client_encryption_options.require_client_auth", "optional")
+ .set("client_encryption_options.keystore", serverKeystorePath.toString())
+ .set("client_encryption_options.keystore_password", SERVER_KEYSTORE_PASSWORD)
+ .set("client_encryption_options.truststore", truststorePath.toString())
+ .set("client_encryption_options.truststore_password", SERVER_TRUSTSTORE_PASSWORD)
+ .set("client_encryption_options.require_endpoint_verification", "false")
+ .set("client_encryption_options.max_certificate_validity_period", "30d")
+ .set("client_encryption_options.certificate_validity_warn_threshold", "5d")
+ .with(Feature.NATIVE_PROTOCOL, Feature.GOSSIP));
+ CLUSTER = builder.start();
+
+ configureIdentity();
+ }
+
+ @AfterClass
+ public static void teardown() throws Exception
+ {
+ LOGGER.info("[test step : @AfterClass] teardown");
+ if (CLUSTER != null)
+ CLUSTER.close();
+ }
+
+ @Test
+ public void testExpiringCertificate() throws Exception
Review Comment:
I see, expires within a day, should expect it to log something, did you intend to add logging validation here?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-18951: Add option for MutualTlsAuthenticator to restrict the certificate age [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3109:
URL: https://github.com/apache/cassandra/pull/3109#discussion_r1529376125
##########
test/distributed/org/apache/cassandra/distributed/test/auth/MutualTlsCertificateValidityPeriodTest.java:
##########
@@ -0,0 +1,329 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cassandra.distributed.test.auth;
+
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.nio.file.Path;
+import java.time.Instant;
+import java.time.temporal.ChronoUnit;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Optional;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.stream.StreamSupport;
+import javax.net.ssl.SSLException;
+
+import com.google.common.collect.ImmutableMap;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.ClassRule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.datastax.driver.core.PlainTextAuthProvider;
+import com.datastax.driver.core.RemoteEndpointAwareJdkSSLOptions;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Row;
+import com.datastax.driver.core.SSLOptions;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.core.SimpleStatement;
+import com.datastax.driver.core.policies.LoadBalancingPolicy;
+import org.apache.cassandra.config.EncryptionOptions;
+import org.apache.cassandra.distributed.Cluster;
+import org.apache.cassandra.distributed.api.Feature;
+import org.apache.cassandra.distributed.api.ICluster;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.shared.ClusterUtils;
+import org.apache.cassandra.distributed.test.JavaDriverUtils;
+import org.apache.cassandra.distributed.test.TestBaseImpl;
+import org.apache.cassandra.distributed.util.Auth;
+import org.apache.cassandra.distributed.util.SingleHostLoadBalancingPolicy;
+import org.apache.cassandra.security.ISslContextFactory;
+import org.apache.cassandra.transport.SimpleClientSslContextFactory;
+import org.apache.cassandra.utils.tls.CertificateBuilder;
+import org.apache.cassandra.utils.tls.CertificateBundle;
+import org.assertj.core.api.Assertions;
+import org.assertj.core.api.InstanceOfAssertFactories;
+
+import static org.apache.cassandra.auth.CassandraRoleManager.DEFAULT_SUPERUSER_NAME;
+import static org.apache.cassandra.auth.CassandraRoleManager.DEFAULT_SUPERUSER_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.CLIENT_TRUSTSTORE_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.SERVER_KEYSTORE_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.SERVER_TRUSTSTORE_PASSWORD;
+import static org.assertj.core.api.Assertions.as;
+import static org.assertj.core.api.Assertions.fail;
+
+/**
+ * Tests mTLS certificate validity period functionality
+ */
+public class MutualTlsCertificateValidityPeriodTest extends TestBaseImpl
+{
+ private static final Logger LOGGER = LoggerFactory.getLogger(MutualTlsCertificateValidityPeriodTest.class);
+ private static final String IDENTITY = "spiffe://test.cassandra.apache.org/dTest/mtls";
+ private static ICluster<IInvokableInstance> CLUSTER;
+ private static final char[] KEYSTORE_PASSWORD = "cassandra".toCharArray();
+
+ @ClassRule
+ public static TemporaryFolder tempFolder = new TemporaryFolder();
+
+ static CertificateBundle CA;
+ static Path truststorePath;
+
+ @BeforeClass
+ public static void setupClass() throws Exception
+ {
+ LOGGER.info("[test step : @BeforeClass] setupClass");
+ Cluster.Builder builder = Cluster.build(1);
+
+ CA = new CertificateBuilder().subject("CN=Apache Cassandra Root CA, OU=Certification Authority, O=Unknown, C=Unknown")
+ .alias("fakerootca")
+ .isCertificateAuthority(true)
+ .buildSelfSigned();
+
+ truststorePath = CA.toTempKeyStorePath(tempFolder.getRoot().toPath(),
+ SERVER_TRUSTSTORE_PASSWORD.toCharArray(),
+ SERVER_TRUSTSTORE_PASSWORD.toCharArray());
+
+
+ CertificateBundle keystore = new CertificateBuilder().subject("CN=Apache Cassandra, OU=ssl_test, O=Unknown, L=Unknown, ST=Unknown, C=Unknown")
+ .addSanDnsName(InetAddress.getLocalHost().getCanonicalHostName())
+ .addSanDnsName(InetAddress.getLocalHost().getHostName())
+ .buildIssuedBy(CA);
+
+ Path serverKeystorePath = keystore.toTempKeyStorePath(tempFolder.getRoot().toPath(),
+ SERVER_KEYSTORE_PASSWORD.toCharArray(),
+ SERVER_KEYSTORE_PASSWORD.toCharArray());
+
+ builder.withConfig(c -> c.set("authenticator.class_name", "org.apache.cassandra.auth.MutualTlsWithPasswordFallbackAuthenticator")
+ .set("authenticator.parameters", Collections.singletonMap("validator_class_name", "org.apache.cassandra.auth.SpiffeCertificateValidator"))
+ .set("role_manager", "CassandraRoleManager")
+ .set("authorizer", "CassandraAuthorizer")
+ .set("client_encryption_options.enabled", "true")
+ .set("client_encryption_options.require_client_auth", "optional")
+ .set("client_encryption_options.keystore", serverKeystorePath.toString())
+ .set("client_encryption_options.keystore_password", SERVER_KEYSTORE_PASSWORD)
+ .set("client_encryption_options.truststore", truststorePath.toString())
+ .set("client_encryption_options.truststore_password", SERVER_TRUSTSTORE_PASSWORD)
+ .set("client_encryption_options.require_endpoint_verification", "false")
+ .set("client_encryption_options.max_certificate_validity_period", "30d")
+ .set("client_encryption_options.certificate_validity_warn_threshold", "5d")
+ .with(Feature.NATIVE_PROTOCOL, Feature.GOSSIP));
+ CLUSTER = builder.start();
+
+ configureIdentity();
+ }
+
+ @AfterClass
+ public static void teardown() throws Exception
+ {
+ LOGGER.info("[test step : @AfterClass] teardown");
+ if (CLUSTER != null)
+ CLUSTER.close();
+ }
+
+ @Test
+ public void testExpiringCertificate() throws Exception
+ {
+ LOGGER.info("[test step : @Test] testExpiringCertificate");
+ Path clientKeystorePath = generateClientCertificate(null);
+
+ com.datastax.driver.core.Cluster driver = JavaDriverUtils.create(CLUSTER, null, b -> b.withSSL(getSSLOptions(clientKeystorePath)));
+
+ testWithDriver(driver, (Session session) -> {
+ ResultSet clientView = session.execute(new SimpleStatement("SELECT * FROM system_views.clients"));
+ Assertions.assertThat(clientView).isNotNull().isNotEmpty();
+
+ Optional<Row> thisClient = StreamSupport.stream(clientView.spliterator(), false)
+ .filter(row -> "cassandra_ssl_test".equals(row.getString("username")))
+ .findFirst();
+
+ Assertions.assertThat(thisClient).isPresent();
+ Row row = thisClient.get();
+ Map<String, String> authenticationMetadata = row.getMap("authentication_metadata", String.class, String.class);
+
+ Assertions.assertThat(authenticationMetadata).isNotNull().hasSize(1)
+ .containsKey("identity")
+ .extractingByKey("identity", as(InstanceOfAssertFactories.STRING)).isEqualTo(IDENTITY);
+ Assertions.assertThat(row.getString("authentication_mode")).isEqualTo("MutualTls");
+ });
+ }
+
+ @Test
+ public void testCertificateReachingMaxValidityPeriod() throws Exception
+ {
+ LOGGER.info("[test step : @Test] testCertificateReachingMaxValidityPeriod");
+ Path clientKeystorePath = generateClientCertificate(b -> b.notBefore(Instant.now().minus(3, ChronoUnit.DAYS))
Review Comment:
`client_encryption_options.max_certificate_validity_period` is set to 30 days, shouldn't this be a larger range?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-18951: Add option for MutualTlsAuthenticator to restrict the certificate age [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3109:
URL: https://github.com/apache/cassandra/pull/3109#discussion_r1529345185
##########
src/java/org/apache/cassandra/auth/MutualTlsAuthenticator.java:
##########
@@ -208,9 +224,29 @@ public AuthenticatedUser getAuthenticatedUser() throws AuthenticationException
nospamLogger.error(msg, identity);
throw new AuthenticationException(MessageFormatter.format(msg, identity).getMessage());
}
+
+ // Validates that the certificate validity period does not exceed the maximum certificate configured validity period
+ int minutesToCertificateExpiration = certificateValidityPeriodValidator.validate(clientCertificateChain);
+ int daysToCertificateExpiration = toDays(minutesToCertificateExpiration);
+
+ if (certificateValidityWarnThreshold != null
+ && minutesToCertificateExpiration < certificateValidityWarnThreshold.toMinutes())
+ {
+ nospamLogger.warn("Certificate with identity '{}' will expire in {} minutes",
Review Comment:
Since we are logging this, it may be nice to convert it into a duration and then log that so you get something precisely more human readable (e.g. if a certificate expires in 5 hours 4 hours and 37 minutes, this will log '7477' which is not as human readable.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-18951: Add option for MutualTlsAuthenticator to restrict the certificate age [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3109:
URL: https://github.com/apache/cassandra/pull/3109#discussion_r1491829621
##########
src/java/org/apache/cassandra/auth/SpiffeCertificateValidator.java:
##########
@@ -31,27 +32,45 @@
* This class assumes that the identity of a certificate is SPIFFE which is a URI that is present as part of the SAN
* of the client certificate. It has logic to extract identity (Spiffe) out of a certificate & knows how to validate
* the client certificates.
- * <p>
*
- * <p>
- * Example:
+ * <p>Example:
+ * <pre>
* internode_authenticator:
- * class_name : org.apache.cassandra.auth.MutualTlsAuthenticator
- * parameters :
- * validator_class_name: org.apache.cassandra.auth.SpiffeCertificateValidator
+ * class_name: org.apache.cassandra.auth.MutualTlsAuthenticator
+ * parameters:
+ * validator_class_name: org.apache.cassandra.auth.SpiffeCertificateValidator
+ * </pre>
+ *
+ * <pre>
* authenticator:
- * class_name : org.apache.cassandra.auth.MutualTlsInternodeAuthenticator
- * parameters :
- * validator_class_name: org.apache.cassandra.auth.SpiffeCertificateValidator
+ * class_name: org.apache.cassandra.auth.MutualTlsInternodeAuthenticator
+ * parameters:
+ * validator_class_name: org.apache.cassandra.auth.SpiffeCertificateValidator
+ * </pre>
*/
public class SpiffeCertificateValidator implements MutualTlsCertificateValidator
{
+ /**
+ * {@inheritDoc}
+ */
@Override
- public boolean isValidCertificate(Certificate[] clientCertificateChain)
+ public boolean isValidCertificate(Certificate[] clientCertificateChain, int maxCertificateAgeMinutes) throws AuthenticationException
{
+ X509Certificate[] castedCerts = castCertsToX509(clientCertificateChain);
+ int certificateAgeInMinutes = getCertificateAgeInMinutes(castedCerts[0]);
+ if (certificateAgeInMinutes > maxCertificateAgeMinutes)
+ {
+ String errorMessage = String.format("The age of the provided certificate exceeds the maximum allowed age of %d minutes",
Review Comment:
Looking at `DurationSpec` code, it looks like this isn't easily achievable, and I think there is precedence in C* for logging in the resolved unit rather than the given one, so probably ok to remain this way.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-18951: Add option for MutualTlsAuthenticator to restrict the certificate age [cassandra]
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #3109:
URL: https://github.com/apache/cassandra/pull/3109#discussion_r1534645331
##########
src/java/org/apache/cassandra/auth/MutualTlsAuthenticator.java:
##########
@@ -208,9 +224,29 @@ public AuthenticatedUser getAuthenticatedUser() throws AuthenticationException
nospamLogger.error(msg, identity);
throw new AuthenticationException(MessageFormatter.format(msg, identity).getMessage());
}
+
+ // Validates that the certificate validity period does not exceed the maximum certificate configured validity period
+ int minutesToCertificateExpiration = certificateValidityPeriodValidator.validate(clientCertificateChain);
+ int daysToCertificateExpiration = toDays(minutesToCertificateExpiration);
+
+ if (certificateValidityWarnThreshold != null
+ && minutesToCertificateExpiration < certificateValidityWarnThreshold.toMinutes())
+ {
+ nospamLogger.warn("Certificate with identity '{}' will expire in {} minutes",
+ identity, minutesToCertificateExpiration);
+ }
+
+ // Report metrics on client certificate expiration
+ MutualTlsMetrics.instance.clientCertificateExpirationDays.update(daysToCertificateExpiration);
+
return new AuthenticatedUser(role, MTLS, Collections.singletonMap(METADATA_IDENTITY_KEY, identity));
}
+ private int toDays(int minutes)
+ {
+ return (int) TimeUnit.MINUTES.toDays(minutes);
Review Comment:
done
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-18951: Add option for MutualTlsAuthenticator to restrict the certificate age [cassandra]
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #3109:
URL: https://github.com/apache/cassandra/pull/3109#discussion_r1491827497
##########
src/java/org/apache/cassandra/auth/SpiffeCertificateValidator.java:
##########
@@ -31,27 +32,45 @@
* This class assumes that the identity of a certificate is SPIFFE which is a URI that is present as part of the SAN
* of the client certificate. It has logic to extract identity (Spiffe) out of a certificate & knows how to validate
* the client certificates.
- * <p>
*
- * <p>
- * Example:
+ * <p>Example:
+ * <pre>
* internode_authenticator:
- * class_name : org.apache.cassandra.auth.MutualTlsAuthenticator
- * parameters :
- * validator_class_name: org.apache.cassandra.auth.SpiffeCertificateValidator
+ * class_name: org.apache.cassandra.auth.MutualTlsAuthenticator
+ * parameters:
+ * validator_class_name: org.apache.cassandra.auth.SpiffeCertificateValidator
+ * </pre>
+ *
+ * <pre>
* authenticator:
- * class_name : org.apache.cassandra.auth.MutualTlsInternodeAuthenticator
- * parameters :
- * validator_class_name: org.apache.cassandra.auth.SpiffeCertificateValidator
+ * class_name: org.apache.cassandra.auth.MutualTlsInternodeAuthenticator
+ * parameters:
+ * validator_class_name: org.apache.cassandra.auth.SpiffeCertificateValidator
+ * </pre>
*/
public class SpiffeCertificateValidator implements MutualTlsCertificateValidator
{
+ /**
+ * {@inheritDoc}
+ */
@Override
- public boolean isValidCertificate(Certificate[] clientCertificateChain)
+ public boolean isValidCertificate(Certificate[] clientCertificateChain, int maxCertificateAgeMinutes) throws AuthenticationException
{
+ X509Certificate[] castedCerts = castCertsToX509(clientCertificateChain);
+ int certificateAgeInMinutes = getCertificateAgeInMinutes(castedCerts[0]);
+ if (certificateAgeInMinutes > maxCertificateAgeMinutes)
+ {
+ String errorMessage = String.format("The age of the provided certificate exceeds the maximum allowed age of %d minutes",
Review Comment:
Yeah, makes sense, I will make the change
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-18951: Add option for MutualTlsAuthenticator to restrict the certificate age [cassandra]
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #3109:
URL: https://github.com/apache/cassandra/pull/3109#discussion_r1491827244
##########
test/unit/org/apache/cassandra/auth/MutualTlsAuthenticatorTest.java:
##########
@@ -86,7 +90,7 @@ public static void setup()
@After
public void after() throws IOException, TimeoutException
{
- MBeanWrapper.instance.unregisterMBean("org.apache.cassandra.auth:type=IdentitiesCache");
+ MBeanWrapper.instance.unregisterMBean("org.apache.cassandra.auth:type=IdentitiesCache", MBeanWrapper.OnException.IGNORE);
Review Comment:
yeah, this prevents the `after` method to fail because the bean is not registered
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-18951: Add option for MutualTlsAuthenticator to restrict the certificate age [cassandra]
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #3109:
URL: https://github.com/apache/cassandra/pull/3109#discussion_r1533012139
##########
test/distributed/org/apache/cassandra/distributed/test/auth/MutualTlsCertificateValidityPeriodTest.java:
##########
@@ -0,0 +1,329 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cassandra.distributed.test.auth;
+
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.nio.file.Path;
+import java.time.Instant;
+import java.time.temporal.ChronoUnit;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Optional;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.stream.StreamSupport;
+import javax.net.ssl.SSLException;
+
+import com.google.common.collect.ImmutableMap;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.ClassRule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.datastax.driver.core.PlainTextAuthProvider;
+import com.datastax.driver.core.RemoteEndpointAwareJdkSSLOptions;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Row;
+import com.datastax.driver.core.SSLOptions;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.core.SimpleStatement;
+import com.datastax.driver.core.policies.LoadBalancingPolicy;
+import org.apache.cassandra.config.EncryptionOptions;
+import org.apache.cassandra.distributed.Cluster;
+import org.apache.cassandra.distributed.api.Feature;
+import org.apache.cassandra.distributed.api.ICluster;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.shared.ClusterUtils;
+import org.apache.cassandra.distributed.test.JavaDriverUtils;
+import org.apache.cassandra.distributed.test.TestBaseImpl;
+import org.apache.cassandra.distributed.util.Auth;
+import org.apache.cassandra.distributed.util.SingleHostLoadBalancingPolicy;
+import org.apache.cassandra.security.ISslContextFactory;
+import org.apache.cassandra.transport.SimpleClientSslContextFactory;
+import org.apache.cassandra.utils.tls.CertificateBuilder;
+import org.apache.cassandra.utils.tls.CertificateBundle;
+import org.assertj.core.api.Assertions;
+import org.assertj.core.api.InstanceOfAssertFactories;
+
+import static org.apache.cassandra.auth.CassandraRoleManager.DEFAULT_SUPERUSER_NAME;
+import static org.apache.cassandra.auth.CassandraRoleManager.DEFAULT_SUPERUSER_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.CLIENT_TRUSTSTORE_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.SERVER_KEYSTORE_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.SERVER_TRUSTSTORE_PASSWORD;
+import static org.assertj.core.api.Assertions.as;
+import static org.assertj.core.api.Assertions.fail;
+
+/**
+ * Tests mTLS certificate validity period functionality
+ */
+public class MutualTlsCertificateValidityPeriodTest extends TestBaseImpl
+{
+ private static final Logger LOGGER = LoggerFactory.getLogger(MutualTlsCertificateValidityPeriodTest.class);
+ private static final String IDENTITY = "spiffe://test.cassandra.apache.org/dTest/mtls";
+ private static ICluster<IInvokableInstance> CLUSTER;
+ private static final char[] KEYSTORE_PASSWORD = "cassandra".toCharArray();
+
+ @ClassRule
+ public static TemporaryFolder tempFolder = new TemporaryFolder();
+
+ static CertificateBundle CA;
+ static Path truststorePath;
+
+ @BeforeClass
+ public static void setupClass() throws Exception
+ {
+ LOGGER.info("[test step : @BeforeClass] setupClass");
+ Cluster.Builder builder = Cluster.build(1);
+
+ CA = new CertificateBuilder().subject("CN=Apache Cassandra Root CA, OU=Certification Authority, O=Unknown, C=Unknown")
+ .alias("fakerootca")
+ .isCertificateAuthority(true)
+ .buildSelfSigned();
+
+ truststorePath = CA.toTempKeyStorePath(tempFolder.getRoot().toPath(),
+ SERVER_TRUSTSTORE_PASSWORD.toCharArray(),
+ SERVER_TRUSTSTORE_PASSWORD.toCharArray());
+
+
+ CertificateBundle keystore = new CertificateBuilder().subject("CN=Apache Cassandra, OU=ssl_test, O=Unknown, L=Unknown, ST=Unknown, C=Unknown")
+ .addSanDnsName(InetAddress.getLocalHost().getCanonicalHostName())
+ .addSanDnsName(InetAddress.getLocalHost().getHostName())
+ .buildIssuedBy(CA);
+
+ Path serverKeystorePath = keystore.toTempKeyStorePath(tempFolder.getRoot().toPath(),
+ SERVER_KEYSTORE_PASSWORD.toCharArray(),
+ SERVER_KEYSTORE_PASSWORD.toCharArray());
+
+ builder.withConfig(c -> c.set("authenticator.class_name", "org.apache.cassandra.auth.MutualTlsWithPasswordFallbackAuthenticator")
+ .set("authenticator.parameters", Collections.singletonMap("validator_class_name", "org.apache.cassandra.auth.SpiffeCertificateValidator"))
+ .set("role_manager", "CassandraRoleManager")
+ .set("authorizer", "CassandraAuthorizer")
+ .set("client_encryption_options.enabled", "true")
+ .set("client_encryption_options.require_client_auth", "optional")
+ .set("client_encryption_options.keystore", serverKeystorePath.toString())
+ .set("client_encryption_options.keystore_password", SERVER_KEYSTORE_PASSWORD)
+ .set("client_encryption_options.truststore", truststorePath.toString())
+ .set("client_encryption_options.truststore_password", SERVER_TRUSTSTORE_PASSWORD)
+ .set("client_encryption_options.require_endpoint_verification", "false")
+ .set("client_encryption_options.max_certificate_validity_period", "30d")
+ .set("client_encryption_options.certificate_validity_warn_threshold", "5d")
+ .with(Feature.NATIVE_PROTOCOL, Feature.GOSSIP));
+ CLUSTER = builder.start();
+
+ configureIdentity();
+ }
+
+ @AfterClass
+ public static void teardown() throws Exception
+ {
+ LOGGER.info("[test step : @AfterClass] teardown");
+ if (CLUSTER != null)
+ CLUSTER.close();
+ }
+
+ @Test
+ public void testExpiringCertificate() throws Exception
Review Comment:
yeah, good idea, I'll add the logging validation.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-18951: Add option for MutualTlsAuthenticator to restrict the certificate age [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3109:
URL: https://github.com/apache/cassandra/pull/3109#discussion_r1491820947
##########
src/java/org/apache/cassandra/auth/MutualTlsAuthenticator.java:
##########
@@ -87,6 +101,18 @@ public MutualTlsAuthenticator(Map<String, String> parameters)
}
certificateValidator = ParameterizedClass.newInstance(new ParameterizedClass(certificateValidatorClassName),
Arrays.asList("", AuthConfig.class.getPackage().getName()));
+
+ String maxCertificateAgeConfig = parameters.get(MAX_CERTIFICATE_AGE_CONFIG);
Review Comment:
One thing i'm wondering is whether the parameter should be on the authenticator or in the validator.
I noticed that the certificate age itself is evaluated in `SpiffeCertificateValidator`. Since we use `ParameterizedClass` on `validator_class_name`, technically we should be able to pass parameters to it.
If you pass the parameter to the validator, then you don't need logic in both `MutualTlsAuthenticator` and `MutualTlsInternodeAuthenticator` for parsing out the certificate age.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-18951: Add option for MutualTlsAuthenticator to restrict the certificate age [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3109:
URL: https://github.com/apache/cassandra/pull/3109#discussion_r1491821475
##########
src/java/org/apache/cassandra/auth/MutualTlsAuthenticator.java:
##########
@@ -87,6 +101,18 @@ public MutualTlsAuthenticator(Map<String, String> parameters)
}
certificateValidator = ParameterizedClass.newInstance(new ParameterizedClass(certificateValidatorClassName),
Arrays.asList("", AuthConfig.class.getPackage().getName()));
+
+ String maxCertificateAgeConfig = parameters.get(MAX_CERTIFICATE_AGE_CONFIG);
Review Comment:
On the other hand there's an argument to move the evaluation completely out of the validator, so all `MutualTlsCertificateValidator` implementations don't have to implement logic to validate the certificate age.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-18951: Add option for MutualTlsAuthenticator to restrict the certificate age [cassandra]
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #3109:
URL: https://github.com/apache/cassandra/pull/3109#discussion_r1532580249
##########
src/java/org/apache/cassandra/auth/MutualTlsCertificateValidityPeriodValidator.java:
##########
@@ -0,0 +1,90 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cassandra.auth;
+
+import java.security.cert.Certificate;
+import java.security.cert.X509Certificate;
+import java.time.temporal.ChronoUnit;
+import java.util.Date;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+
+import org.apache.cassandra.config.DurationSpec;
+import org.apache.cassandra.exceptions.AuthenticationException;
+import org.apache.cassandra.utils.FBUtilities;
+
+public class MutualTlsCertificateValidityPeriodValidator
+{
+ @Nonnull
+ private final int maxCertificateValidityPeriodMinutes;
+
+ public MutualTlsCertificateValidityPeriodValidator(@Nullable DurationSpec.IntMinutesBound maxCertificateValidityPeriod)
+ {
+ maxCertificateValidityPeriodMinutes = maxCertificateValidityPeriod != null
+ ? maxCertificateValidityPeriod.toMinutes()
+ // Sufficiently large value that exceeds any reasonable valid configuration
+ : Integer.MAX_VALUE;
+ }
+
+ /**
+ * Validates that the certificate's validity period does not exceed the {@code #maxCertificateValidityPeriod}
+ * and returns the number of minutes to certificate expiration since the verification started.
+ *
+ * @param certificates the certificate chain
+ * @return the number of minutes to certificate expiration since the verification started, or {@code -1}
+ * if no certificate chain was provided
+ * @throws AuthenticationException when the {@link X509Certificate#getNotBefore()} or
+ * {@link X509Certificate#getNotAfter()} dates are null, or when the certificate
+ * validity exceeds the maximum allowed certificate validity
+ */
+ public int validate(Certificate[] certificates) throws AuthenticationException
+ {
+ X509Certificate[] x509Certificates = MutualTlsUtil.castCertsToX509(certificates);
+ if (x509Certificates == null || x509Certificates.length == 0)
+ {
+ return -1;
+ }
+
+ Date notBefore = x509Certificates[0].getNotBefore();
+ Date notAfter = x509Certificates[0].getNotAfter();
+
+ if (notBefore == null || notAfter == null)
+ {
+ throw new AuthenticationException("The provided certificate does not have a notBefore / notAfter field");
Review Comment:
yeah, I thought about this too, just to err on the safe side I will remove this branch
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-18951: Add option for MutualTlsAuthenticator to restrict the certificate age [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3109:
URL: https://github.com/apache/cassandra/pull/3109#discussion_r1534715153
##########
test/distributed/org/apache/cassandra/distributed/test/auth/MutualTlsCertificateValidityPeriodTest.java:
##########
@@ -0,0 +1,329 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cassandra.distributed.test.auth;
+
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.nio.file.Path;
+import java.time.Instant;
+import java.time.temporal.ChronoUnit;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Optional;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.stream.StreamSupport;
+import javax.net.ssl.SSLException;
+
+import com.google.common.collect.ImmutableMap;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.ClassRule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.datastax.driver.core.PlainTextAuthProvider;
+import com.datastax.driver.core.RemoteEndpointAwareJdkSSLOptions;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Row;
+import com.datastax.driver.core.SSLOptions;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.core.SimpleStatement;
+import com.datastax.driver.core.policies.LoadBalancingPolicy;
+import org.apache.cassandra.config.EncryptionOptions;
+import org.apache.cassandra.distributed.Cluster;
+import org.apache.cassandra.distributed.api.Feature;
+import org.apache.cassandra.distributed.api.ICluster;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.shared.ClusterUtils;
+import org.apache.cassandra.distributed.test.JavaDriverUtils;
+import org.apache.cassandra.distributed.test.TestBaseImpl;
+import org.apache.cassandra.distributed.util.Auth;
+import org.apache.cassandra.distributed.util.SingleHostLoadBalancingPolicy;
+import org.apache.cassandra.security.ISslContextFactory;
+import org.apache.cassandra.transport.SimpleClientSslContextFactory;
+import org.apache.cassandra.utils.tls.CertificateBuilder;
+import org.apache.cassandra.utils.tls.CertificateBundle;
+import org.assertj.core.api.Assertions;
+import org.assertj.core.api.InstanceOfAssertFactories;
+
+import static org.apache.cassandra.auth.CassandraRoleManager.DEFAULT_SUPERUSER_NAME;
+import static org.apache.cassandra.auth.CassandraRoleManager.DEFAULT_SUPERUSER_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.CLIENT_TRUSTSTORE_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.SERVER_KEYSTORE_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.SERVER_TRUSTSTORE_PASSWORD;
+import static org.assertj.core.api.Assertions.as;
+import static org.assertj.core.api.Assertions.fail;
+
+/**
+ * Tests mTLS certificate validity period functionality
+ */
+public class MutualTlsCertificateValidityPeriodTest extends TestBaseImpl
+{
+ private static final Logger LOGGER = LoggerFactory.getLogger(MutualTlsCertificateValidityPeriodTest.class);
+ private static final String IDENTITY = "spiffe://test.cassandra.apache.org/dTest/mtls";
+ private static ICluster<IInvokableInstance> CLUSTER;
+ private static final char[] KEYSTORE_PASSWORD = "cassandra".toCharArray();
+
+ @ClassRule
+ public static TemporaryFolder tempFolder = new TemporaryFolder();
+
+ static CertificateBundle CA;
+ static Path truststorePath;
+
+ @BeforeClass
+ public static void setupClass() throws Exception
+ {
+ LOGGER.info("[test step : @BeforeClass] setupClass");
+ Cluster.Builder builder = Cluster.build(1);
+
+ CA = new CertificateBuilder().subject("CN=Apache Cassandra Root CA, OU=Certification Authority, O=Unknown, C=Unknown")
+ .alias("fakerootca")
+ .isCertificateAuthority(true)
+ .buildSelfSigned();
+
+ truststorePath = CA.toTempKeyStorePath(tempFolder.getRoot().toPath(),
+ SERVER_TRUSTSTORE_PASSWORD.toCharArray(),
+ SERVER_TRUSTSTORE_PASSWORD.toCharArray());
+
+
+ CertificateBundle keystore = new CertificateBuilder().subject("CN=Apache Cassandra, OU=ssl_test, O=Unknown, L=Unknown, ST=Unknown, C=Unknown")
+ .addSanDnsName(InetAddress.getLocalHost().getCanonicalHostName())
+ .addSanDnsName(InetAddress.getLocalHost().getHostName())
+ .buildIssuedBy(CA);
+
+ Path serverKeystorePath = keystore.toTempKeyStorePath(tempFolder.getRoot().toPath(),
+ SERVER_KEYSTORE_PASSWORD.toCharArray(),
+ SERVER_KEYSTORE_PASSWORD.toCharArray());
+
+ builder.withConfig(c -> c.set("authenticator.class_name", "org.apache.cassandra.auth.MutualTlsWithPasswordFallbackAuthenticator")
+ .set("authenticator.parameters", Collections.singletonMap("validator_class_name", "org.apache.cassandra.auth.SpiffeCertificateValidator"))
+ .set("role_manager", "CassandraRoleManager")
+ .set("authorizer", "CassandraAuthorizer")
+ .set("client_encryption_options.enabled", "true")
+ .set("client_encryption_options.require_client_auth", "optional")
+ .set("client_encryption_options.keystore", serverKeystorePath.toString())
+ .set("client_encryption_options.keystore_password", SERVER_KEYSTORE_PASSWORD)
+ .set("client_encryption_options.truststore", truststorePath.toString())
+ .set("client_encryption_options.truststore_password", SERVER_TRUSTSTORE_PASSWORD)
+ .set("client_encryption_options.require_endpoint_verification", "false")
+ .set("client_encryption_options.max_certificate_validity_period", "30d")
+ .set("client_encryption_options.certificate_validity_warn_threshold", "5d")
+ .with(Feature.NATIVE_PROTOCOL, Feature.GOSSIP));
+ CLUSTER = builder.start();
+
+ configureIdentity();
+ }
+
+ @AfterClass
+ public static void teardown() throws Exception
+ {
+ LOGGER.info("[test step : @AfterClass] teardown");
+ if (CLUSTER != null)
+ CLUSTER.close();
+ }
+
+ @Test
+ public void testExpiringCertificate() throws Exception
+ {
+ LOGGER.info("[test step : @Test] testExpiringCertificate");
+ Path clientKeystorePath = generateClientCertificate(null);
+
+ com.datastax.driver.core.Cluster driver = JavaDriverUtils.create(CLUSTER, null, b -> b.withSSL(getSSLOptions(clientKeystorePath)));
+
+ testWithDriver(driver, (Session session) -> {
+ ResultSet clientView = session.execute(new SimpleStatement("SELECT * FROM system_views.clients"));
+ Assertions.assertThat(clientView).isNotNull().isNotEmpty();
+
+ Optional<Row> thisClient = StreamSupport.stream(clientView.spliterator(), false)
+ .filter(row -> "cassandra_ssl_test".equals(row.getString("username")))
+ .findFirst();
+
+ Assertions.assertThat(thisClient).isPresent();
+ Row row = thisClient.get();
+ Map<String, String> authenticationMetadata = row.getMap("authentication_metadata", String.class, String.class);
+
+ Assertions.assertThat(authenticationMetadata).isNotNull().hasSize(1)
+ .containsKey("identity")
+ .extractingByKey("identity", as(InstanceOfAssertFactories.STRING)).isEqualTo(IDENTITY);
+ Assertions.assertThat(row.getString("authentication_mode")).isEqualTo("MutualTls");
+ });
+ }
+
+ @Test
+ public void testCertificateReachingMaxValidityPeriod() throws Exception
+ {
+ LOGGER.info("[test step : @Test] testCertificateReachingMaxValidityPeriod");
+ Path clientKeystorePath = generateClientCertificate(b -> b.notBefore(Instant.now().minus(3, ChronoUnit.DAYS))
+ .notAfter(Instant.now().plus(4, ChronoUnit.DAYS)));
+
+ com.datastax.driver.core.Cluster driver = JavaDriverUtils.create(CLUSTER, null, b -> b.withSSL(getSSLOptions(clientKeystorePath)));
+
+ testWithDriver(driver, (Session session) -> {
+ ResultSet clientView = session.execute(new SimpleStatement("SELECT * FROM system_views.clients"));
+ Assertions.assertThat(clientView).isNotNull().isNotEmpty();
+
+ Optional<Row> thisClient = StreamSupport.stream(clientView.spliterator(), false)
+ .filter(row -> "cassandra_ssl_test".equals(row.getString("username")))
+ .findFirst();
+
+ Assertions.assertThat(thisClient).isPresent();
+ Row row = thisClient.get();
+ Map<String, String> authenticationMetadata = row.getMap("authentication_metadata", String.class, String.class);
+
+ Assertions.assertThat(authenticationMetadata).isNotNull().hasSize(1)
+ .containsKey("identity")
+ .extractingByKey("identity", as(InstanceOfAssertFactories.STRING)).isEqualTo(IDENTITY);
+ Assertions.assertThat(row.getString("authentication_mode")).isEqualTo("MutualTls");
+ });
+ }
+
+ @Test
+ public void testFailsWhenCertificateExceedsMaxAllowedValidityPeriod() throws Exception
+ {
+ LOGGER.info("[test step : @Test] testFailsWhenCertificateExceedsMaxAllowedValidityPeriod");
+ Path clientKeystorePath = generateClientCertificate(b -> b.notAfter(Instant.now().plus(365, ChronoUnit.DAYS)));
+
+ com.datastax.driver.core.Cluster driver = JavaDriverUtils.create(CLUSTER, null, b -> b.withSSL(getSSLOptions(clientKeystorePath)));
+
+ try
+ {
+ testWithDriver(driver, null);
+ fail("Should not be able to connect when the certificate exceeds the maximum allowed validity period");
+ }
+ catch (com.datastax.driver.core.exceptions.NoHostAvailableException exception)
+ {
+ Assertions.assertThat(exception)
+ .hasMessageContaining("The validity period of the provided certificate (527040 minutes) exceeds the maximum allowed validity period of 43200 minutes");
+ }
+ }
+
+ @Test
+ public void testFailsWhenCertificateIsExpired() throws Exception
+ {
+ LOGGER.info("[test step : @Test] testFailsWhenCertificateIsExpired");
+ Path clientKeystorePath = generateClientCertificate(b -> b.notBefore(Instant.now().minus(30, ChronoUnit.DAYS))
Review Comment:
:+1: (talked out of band, we don't need a test for this, was just sharing an observation :+1:)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-18951: Add option for MutualTlsAuthenticator to restrict the certificate age [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3109:
URL: https://github.com/apache/cassandra/pull/3109#discussion_r1529380081
##########
test/distributed/org/apache/cassandra/distributed/test/auth/MutualTlsCertificateValidityPeriodTest.java:
##########
@@ -0,0 +1,329 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cassandra.distributed.test.auth;
+
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.nio.file.Path;
+import java.time.Instant;
+import java.time.temporal.ChronoUnit;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Optional;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.stream.StreamSupport;
+import javax.net.ssl.SSLException;
+
+import com.google.common.collect.ImmutableMap;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.ClassRule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.datastax.driver.core.PlainTextAuthProvider;
+import com.datastax.driver.core.RemoteEndpointAwareJdkSSLOptions;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Row;
+import com.datastax.driver.core.SSLOptions;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.core.SimpleStatement;
+import com.datastax.driver.core.policies.LoadBalancingPolicy;
+import org.apache.cassandra.config.EncryptionOptions;
+import org.apache.cassandra.distributed.Cluster;
+import org.apache.cassandra.distributed.api.Feature;
+import org.apache.cassandra.distributed.api.ICluster;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.shared.ClusterUtils;
+import org.apache.cassandra.distributed.test.JavaDriverUtils;
+import org.apache.cassandra.distributed.test.TestBaseImpl;
+import org.apache.cassandra.distributed.util.Auth;
+import org.apache.cassandra.distributed.util.SingleHostLoadBalancingPolicy;
+import org.apache.cassandra.security.ISslContextFactory;
+import org.apache.cassandra.transport.SimpleClientSslContextFactory;
+import org.apache.cassandra.utils.tls.CertificateBuilder;
+import org.apache.cassandra.utils.tls.CertificateBundle;
+import org.assertj.core.api.Assertions;
+import org.assertj.core.api.InstanceOfAssertFactories;
+
+import static org.apache.cassandra.auth.CassandraRoleManager.DEFAULT_SUPERUSER_NAME;
+import static org.apache.cassandra.auth.CassandraRoleManager.DEFAULT_SUPERUSER_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.CLIENT_TRUSTSTORE_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.SERVER_KEYSTORE_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.SERVER_TRUSTSTORE_PASSWORD;
+import static org.assertj.core.api.Assertions.as;
+import static org.assertj.core.api.Assertions.fail;
+
+/**
+ * Tests mTLS certificate validity period functionality
+ */
+public class MutualTlsCertificateValidityPeriodTest extends TestBaseImpl
+{
+ private static final Logger LOGGER = LoggerFactory.getLogger(MutualTlsCertificateValidityPeriodTest.class);
+ private static final String IDENTITY = "spiffe://test.cassandra.apache.org/dTest/mtls";
+ private static ICluster<IInvokableInstance> CLUSTER;
+ private static final char[] KEYSTORE_PASSWORD = "cassandra".toCharArray();
+
+ @ClassRule
+ public static TemporaryFolder tempFolder = new TemporaryFolder();
+
+ static CertificateBundle CA;
+ static Path truststorePath;
+
+ @BeforeClass
+ public static void setupClass() throws Exception
+ {
+ LOGGER.info("[test step : @BeforeClass] setupClass");
+ Cluster.Builder builder = Cluster.build(1);
+
+ CA = new CertificateBuilder().subject("CN=Apache Cassandra Root CA, OU=Certification Authority, O=Unknown, C=Unknown")
+ .alias("fakerootca")
+ .isCertificateAuthority(true)
+ .buildSelfSigned();
+
+ truststorePath = CA.toTempKeyStorePath(tempFolder.getRoot().toPath(),
+ SERVER_TRUSTSTORE_PASSWORD.toCharArray(),
+ SERVER_TRUSTSTORE_PASSWORD.toCharArray());
+
+
+ CertificateBundle keystore = new CertificateBuilder().subject("CN=Apache Cassandra, OU=ssl_test, O=Unknown, L=Unknown, ST=Unknown, C=Unknown")
+ .addSanDnsName(InetAddress.getLocalHost().getCanonicalHostName())
+ .addSanDnsName(InetAddress.getLocalHost().getHostName())
+ .buildIssuedBy(CA);
+
+ Path serverKeystorePath = keystore.toTempKeyStorePath(tempFolder.getRoot().toPath(),
+ SERVER_KEYSTORE_PASSWORD.toCharArray(),
+ SERVER_KEYSTORE_PASSWORD.toCharArray());
+
+ builder.withConfig(c -> c.set("authenticator.class_name", "org.apache.cassandra.auth.MutualTlsWithPasswordFallbackAuthenticator")
+ .set("authenticator.parameters", Collections.singletonMap("validator_class_name", "org.apache.cassandra.auth.SpiffeCertificateValidator"))
+ .set("role_manager", "CassandraRoleManager")
+ .set("authorizer", "CassandraAuthorizer")
+ .set("client_encryption_options.enabled", "true")
+ .set("client_encryption_options.require_client_auth", "optional")
+ .set("client_encryption_options.keystore", serverKeystorePath.toString())
+ .set("client_encryption_options.keystore_password", SERVER_KEYSTORE_PASSWORD)
+ .set("client_encryption_options.truststore", truststorePath.toString())
+ .set("client_encryption_options.truststore_password", SERVER_TRUSTSTORE_PASSWORD)
+ .set("client_encryption_options.require_endpoint_verification", "false")
+ .set("client_encryption_options.max_certificate_validity_period", "30d")
+ .set("client_encryption_options.certificate_validity_warn_threshold", "5d")
+ .with(Feature.NATIVE_PROTOCOL, Feature.GOSSIP));
+ CLUSTER = builder.start();
+
+ configureIdentity();
+ }
+
+ @AfterClass
+ public static void teardown() throws Exception
+ {
+ LOGGER.info("[test step : @AfterClass] teardown");
+ if (CLUSTER != null)
+ CLUSTER.close();
+ }
+
+ @Test
+ public void testExpiringCertificate() throws Exception
+ {
+ LOGGER.info("[test step : @Test] testExpiringCertificate");
+ Path clientKeystorePath = generateClientCertificate(null);
+
+ com.datastax.driver.core.Cluster driver = JavaDriverUtils.create(CLUSTER, null, b -> b.withSSL(getSSLOptions(clientKeystorePath)));
+
+ testWithDriver(driver, (Session session) -> {
+ ResultSet clientView = session.execute(new SimpleStatement("SELECT * FROM system_views.clients"));
+ Assertions.assertThat(clientView).isNotNull().isNotEmpty();
+
+ Optional<Row> thisClient = StreamSupport.stream(clientView.spliterator(), false)
+ .filter(row -> "cassandra_ssl_test".equals(row.getString("username")))
+ .findFirst();
+
+ Assertions.assertThat(thisClient).isPresent();
+ Row row = thisClient.get();
+ Map<String, String> authenticationMetadata = row.getMap("authentication_metadata", String.class, String.class);
+
+ Assertions.assertThat(authenticationMetadata).isNotNull().hasSize(1)
+ .containsKey("identity")
+ .extractingByKey("identity", as(InstanceOfAssertFactories.STRING)).isEqualTo(IDENTITY);
+ Assertions.assertThat(row.getString("authentication_mode")).isEqualTo("MutualTls");
+ });
+ }
+
+ @Test
+ public void testCertificateReachingMaxValidityPeriod() throws Exception
+ {
+ LOGGER.info("[test step : @Test] testCertificateReachingMaxValidityPeriod");
+ Path clientKeystorePath = generateClientCertificate(b -> b.notBefore(Instant.now().minus(3, ChronoUnit.DAYS))
+ .notAfter(Instant.now().plus(4, ChronoUnit.DAYS)));
+
+ com.datastax.driver.core.Cluster driver = JavaDriverUtils.create(CLUSTER, null, b -> b.withSSL(getSSLOptions(clientKeystorePath)));
+
+ testWithDriver(driver, (Session session) -> {
+ ResultSet clientView = session.execute(new SimpleStatement("SELECT * FROM system_views.clients"));
+ Assertions.assertThat(clientView).isNotNull().isNotEmpty();
+
+ Optional<Row> thisClient = StreamSupport.stream(clientView.spliterator(), false)
+ .filter(row -> "cassandra_ssl_test".equals(row.getString("username")))
+ .findFirst();
+
+ Assertions.assertThat(thisClient).isPresent();
+ Row row = thisClient.get();
+ Map<String, String> authenticationMetadata = row.getMap("authentication_metadata", String.class, String.class);
+
+ Assertions.assertThat(authenticationMetadata).isNotNull().hasSize(1)
+ .containsKey("identity")
+ .extractingByKey("identity", as(InstanceOfAssertFactories.STRING)).isEqualTo(IDENTITY);
+ Assertions.assertThat(row.getString("authentication_mode")).isEqualTo("MutualTls");
+ });
+ }
+
+ @Test
+ public void testFailsWhenCertificateExceedsMaxAllowedValidityPeriod() throws Exception
+ {
+ LOGGER.info("[test step : @Test] testFailsWhenCertificateExceedsMaxAllowedValidityPeriod");
+ Path clientKeystorePath = generateClientCertificate(b -> b.notAfter(Instant.now().plus(365, ChronoUnit.DAYS)));
+
+ com.datastax.driver.core.Cluster driver = JavaDriverUtils.create(CLUSTER, null, b -> b.withSSL(getSSLOptions(clientKeystorePath)));
+
+ try
+ {
+ testWithDriver(driver, null);
+ fail("Should not be able to connect when the certificate exceeds the maximum allowed validity period");
+ }
+ catch (com.datastax.driver.core.exceptions.NoHostAvailableException exception)
+ {
+ Assertions.assertThat(exception)
+ .hasMessageContaining("The validity period of the provided certificate (527040 minutes) exceeds the maximum allowed validity period of 43200 minutes");
+ }
+ }
+
+ @Test
+ public void testFailsWhenCertificateIsExpired() throws Exception
+ {
+ LOGGER.info("[test step : @Test] testFailsWhenCertificateIsExpired");
+ Path clientKeystorePath = generateClientCertificate(b -> b.notBefore(Instant.now().minus(30, ChronoUnit.DAYS))
Review Comment:
One thing I learned recently is that expired certificates will handshake if the certificate is self signed and directly in the trust store. I see you are making certificates signed by another CA so this is failing as expected. Just wondering if you encountered the same :)
##########
test/distributed/org/apache/cassandra/distributed/test/auth/MutualTlsCertificateValidityPeriodTest.java:
##########
@@ -0,0 +1,329 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cassandra.distributed.test.auth;
+
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.nio.file.Path;
+import java.time.Instant;
+import java.time.temporal.ChronoUnit;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Optional;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.stream.StreamSupport;
+import javax.net.ssl.SSLException;
+
+import com.google.common.collect.ImmutableMap;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.ClassRule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.datastax.driver.core.PlainTextAuthProvider;
+import com.datastax.driver.core.RemoteEndpointAwareJdkSSLOptions;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Row;
+import com.datastax.driver.core.SSLOptions;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.core.SimpleStatement;
+import com.datastax.driver.core.policies.LoadBalancingPolicy;
+import org.apache.cassandra.config.EncryptionOptions;
+import org.apache.cassandra.distributed.Cluster;
+import org.apache.cassandra.distributed.api.Feature;
+import org.apache.cassandra.distributed.api.ICluster;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.shared.ClusterUtils;
+import org.apache.cassandra.distributed.test.JavaDriverUtils;
+import org.apache.cassandra.distributed.test.TestBaseImpl;
+import org.apache.cassandra.distributed.util.Auth;
+import org.apache.cassandra.distributed.util.SingleHostLoadBalancingPolicy;
+import org.apache.cassandra.security.ISslContextFactory;
+import org.apache.cassandra.transport.SimpleClientSslContextFactory;
+import org.apache.cassandra.utils.tls.CertificateBuilder;
+import org.apache.cassandra.utils.tls.CertificateBundle;
+import org.assertj.core.api.Assertions;
+import org.assertj.core.api.InstanceOfAssertFactories;
+
+import static org.apache.cassandra.auth.CassandraRoleManager.DEFAULT_SUPERUSER_NAME;
+import static org.apache.cassandra.auth.CassandraRoleManager.DEFAULT_SUPERUSER_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.CLIENT_TRUSTSTORE_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.SERVER_KEYSTORE_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.SERVER_TRUSTSTORE_PASSWORD;
+import static org.assertj.core.api.Assertions.as;
+import static org.assertj.core.api.Assertions.fail;
+
+/**
+ * Tests mTLS certificate validity period functionality
+ */
+public class MutualTlsCertificateValidityPeriodTest extends TestBaseImpl
+{
+ private static final Logger LOGGER = LoggerFactory.getLogger(MutualTlsCertificateValidityPeriodTest.class);
+ private static final String IDENTITY = "spiffe://test.cassandra.apache.org/dTest/mtls";
+ private static ICluster<IInvokableInstance> CLUSTER;
+ private static final char[] KEYSTORE_PASSWORD = "cassandra".toCharArray();
+
+ @ClassRule
+ public static TemporaryFolder tempFolder = new TemporaryFolder();
+
+ static CertificateBundle CA;
+ static Path truststorePath;
+
+ @BeforeClass
+ public static void setupClass() throws Exception
+ {
+ LOGGER.info("[test step : @BeforeClass] setupClass");
+ Cluster.Builder builder = Cluster.build(1);
+
+ CA = new CertificateBuilder().subject("CN=Apache Cassandra Root CA, OU=Certification Authority, O=Unknown, C=Unknown")
+ .alias("fakerootca")
+ .isCertificateAuthority(true)
+ .buildSelfSigned();
+
+ truststorePath = CA.toTempKeyStorePath(tempFolder.getRoot().toPath(),
+ SERVER_TRUSTSTORE_PASSWORD.toCharArray(),
+ SERVER_TRUSTSTORE_PASSWORD.toCharArray());
+
+
+ CertificateBundle keystore = new CertificateBuilder().subject("CN=Apache Cassandra, OU=ssl_test, O=Unknown, L=Unknown, ST=Unknown, C=Unknown")
+ .addSanDnsName(InetAddress.getLocalHost().getCanonicalHostName())
+ .addSanDnsName(InetAddress.getLocalHost().getHostName())
+ .buildIssuedBy(CA);
+
+ Path serverKeystorePath = keystore.toTempKeyStorePath(tempFolder.getRoot().toPath(),
+ SERVER_KEYSTORE_PASSWORD.toCharArray(),
+ SERVER_KEYSTORE_PASSWORD.toCharArray());
+
+ builder.withConfig(c -> c.set("authenticator.class_name", "org.apache.cassandra.auth.MutualTlsWithPasswordFallbackAuthenticator")
+ .set("authenticator.parameters", Collections.singletonMap("validator_class_name", "org.apache.cassandra.auth.SpiffeCertificateValidator"))
+ .set("role_manager", "CassandraRoleManager")
+ .set("authorizer", "CassandraAuthorizer")
+ .set("client_encryption_options.enabled", "true")
+ .set("client_encryption_options.require_client_auth", "optional")
+ .set("client_encryption_options.keystore", serverKeystorePath.toString())
+ .set("client_encryption_options.keystore_password", SERVER_KEYSTORE_PASSWORD)
+ .set("client_encryption_options.truststore", truststorePath.toString())
+ .set("client_encryption_options.truststore_password", SERVER_TRUSTSTORE_PASSWORD)
+ .set("client_encryption_options.require_endpoint_verification", "false")
+ .set("client_encryption_options.max_certificate_validity_period", "30d")
+ .set("client_encryption_options.certificate_validity_warn_threshold", "5d")
+ .with(Feature.NATIVE_PROTOCOL, Feature.GOSSIP));
+ CLUSTER = builder.start();
+
+ configureIdentity();
+ }
+
+ @AfterClass
+ public static void teardown() throws Exception
+ {
+ LOGGER.info("[test step : @AfterClass] teardown");
+ if (CLUSTER != null)
+ CLUSTER.close();
+ }
+
+ @Test
+ public void testExpiringCertificate() throws Exception
+ {
+ LOGGER.info("[test step : @Test] testExpiringCertificate");
+ Path clientKeystorePath = generateClientCertificate(null);
+
+ com.datastax.driver.core.Cluster driver = JavaDriverUtils.create(CLUSTER, null, b -> b.withSSL(getSSLOptions(clientKeystorePath)));
+
+ testWithDriver(driver, (Session session) -> {
+ ResultSet clientView = session.execute(new SimpleStatement("SELECT * FROM system_views.clients"));
+ Assertions.assertThat(clientView).isNotNull().isNotEmpty();
+
+ Optional<Row> thisClient = StreamSupport.stream(clientView.spliterator(), false)
+ .filter(row -> "cassandra_ssl_test".equals(row.getString("username")))
+ .findFirst();
+
+ Assertions.assertThat(thisClient).isPresent();
+ Row row = thisClient.get();
+ Map<String, String> authenticationMetadata = row.getMap("authentication_metadata", String.class, String.class);
+
+ Assertions.assertThat(authenticationMetadata).isNotNull().hasSize(1)
+ .containsKey("identity")
+ .extractingByKey("identity", as(InstanceOfAssertFactories.STRING)).isEqualTo(IDENTITY);
+ Assertions.assertThat(row.getString("authentication_mode")).isEqualTo("MutualTls");
+ });
+ }
+
+ @Test
+ public void testCertificateReachingMaxValidityPeriod() throws Exception
+ {
+ LOGGER.info("[test step : @Test] testCertificateReachingMaxValidityPeriod");
+ Path clientKeystorePath = generateClientCertificate(b -> b.notBefore(Instant.now().minus(3, ChronoUnit.DAYS))
+ .notAfter(Instant.now().plus(4, ChronoUnit.DAYS)));
+
+ com.datastax.driver.core.Cluster driver = JavaDriverUtils.create(CLUSTER, null, b -> b.withSSL(getSSLOptions(clientKeystorePath)));
+
+ testWithDriver(driver, (Session session) -> {
+ ResultSet clientView = session.execute(new SimpleStatement("SELECT * FROM system_views.clients"));
+ Assertions.assertThat(clientView).isNotNull().isNotEmpty();
+
+ Optional<Row> thisClient = StreamSupport.stream(clientView.spliterator(), false)
+ .filter(row -> "cassandra_ssl_test".equals(row.getString("username")))
+ .findFirst();
+
+ Assertions.assertThat(thisClient).isPresent();
+ Row row = thisClient.get();
+ Map<String, String> authenticationMetadata = row.getMap("authentication_metadata", String.class, String.class);
+
+ Assertions.assertThat(authenticationMetadata).isNotNull().hasSize(1)
+ .containsKey("identity")
+ .extractingByKey("identity", as(InstanceOfAssertFactories.STRING)).isEqualTo(IDENTITY);
+ Assertions.assertThat(row.getString("authentication_mode")).isEqualTo("MutualTls");
+ });
+ }
+
+ @Test
+ public void testFailsWhenCertificateExceedsMaxAllowedValidityPeriod() throws Exception
+ {
+ LOGGER.info("[test step : @Test] testFailsWhenCertificateExceedsMaxAllowedValidityPeriod");
+ Path clientKeystorePath = generateClientCertificate(b -> b.notAfter(Instant.now().plus(365, ChronoUnit.DAYS)));
+
+ com.datastax.driver.core.Cluster driver = JavaDriverUtils.create(CLUSTER, null, b -> b.withSSL(getSSLOptions(clientKeystorePath)));
+
+ try
+ {
+ testWithDriver(driver, null);
+ fail("Should not be able to connect when the certificate exceeds the maximum allowed validity period");
+ }
+ catch (com.datastax.driver.core.exceptions.NoHostAvailableException exception)
+ {
+ Assertions.assertThat(exception)
+ .hasMessageContaining("The validity period of the provided certificate (527040 minutes) exceeds the maximum allowed validity period of 43200 minutes");
+ }
+ }
+
+ @Test
+ public void testFailsWhenCertificateIsExpired() throws Exception
+ {
+ LOGGER.info("[test step : @Test] testFailsWhenCertificateIsExpired");
+ Path clientKeystorePath = generateClientCertificate(b -> b.notBefore(Instant.now().minus(30, ChronoUnit.DAYS))
Review Comment:
One thing I learned recently is that expired certificates will succesfully handshake if the certificate is self signed and directly in the trust store. I see you are making certificates signed by another CA so this is failing as expected. Just wondering if you encountered the same :)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-18951: Add option for MutualTlsAuthenticator to restrict the certificate age [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3109:
URL: https://github.com/apache/cassandra/pull/3109#discussion_r1529374444
##########
test/distributed/org/apache/cassandra/distributed/test/auth/MutualTlsCertificateValidityPeriodTest.java:
##########
@@ -0,0 +1,329 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cassandra.distributed.test.auth;
+
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.nio.file.Path;
+import java.time.Instant;
+import java.time.temporal.ChronoUnit;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Optional;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.stream.StreamSupport;
+import javax.net.ssl.SSLException;
+
+import com.google.common.collect.ImmutableMap;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.ClassRule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.datastax.driver.core.PlainTextAuthProvider;
+import com.datastax.driver.core.RemoteEndpointAwareJdkSSLOptions;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Row;
+import com.datastax.driver.core.SSLOptions;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.core.SimpleStatement;
+import com.datastax.driver.core.policies.LoadBalancingPolicy;
+import org.apache.cassandra.config.EncryptionOptions;
+import org.apache.cassandra.distributed.Cluster;
+import org.apache.cassandra.distributed.api.Feature;
+import org.apache.cassandra.distributed.api.ICluster;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.shared.ClusterUtils;
+import org.apache.cassandra.distributed.test.JavaDriverUtils;
+import org.apache.cassandra.distributed.test.TestBaseImpl;
+import org.apache.cassandra.distributed.util.Auth;
+import org.apache.cassandra.distributed.util.SingleHostLoadBalancingPolicy;
+import org.apache.cassandra.security.ISslContextFactory;
+import org.apache.cassandra.transport.SimpleClientSslContextFactory;
+import org.apache.cassandra.utils.tls.CertificateBuilder;
+import org.apache.cassandra.utils.tls.CertificateBundle;
+import org.assertj.core.api.Assertions;
+import org.assertj.core.api.InstanceOfAssertFactories;
+
+import static org.apache.cassandra.auth.CassandraRoleManager.DEFAULT_SUPERUSER_NAME;
+import static org.apache.cassandra.auth.CassandraRoleManager.DEFAULT_SUPERUSER_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.CLIENT_TRUSTSTORE_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.SERVER_KEYSTORE_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.SERVER_TRUSTSTORE_PASSWORD;
+import static org.assertj.core.api.Assertions.as;
+import static org.assertj.core.api.Assertions.fail;
+
+/**
+ * Tests mTLS certificate validity period functionality
+ */
+public class MutualTlsCertificateValidityPeriodTest extends TestBaseImpl
+{
+ private static final Logger LOGGER = LoggerFactory.getLogger(MutualTlsCertificateValidityPeriodTest.class);
+ private static final String IDENTITY = "spiffe://test.cassandra.apache.org/dTest/mtls";
+ private static ICluster<IInvokableInstance> CLUSTER;
+ private static final char[] KEYSTORE_PASSWORD = "cassandra".toCharArray();
+
+ @ClassRule
+ public static TemporaryFolder tempFolder = new TemporaryFolder();
+
+ static CertificateBundle CA;
+ static Path truststorePath;
+
+ @BeforeClass
+ public static void setupClass() throws Exception
+ {
+ LOGGER.info("[test step : @BeforeClass] setupClass");
+ Cluster.Builder builder = Cluster.build(1);
+
+ CA = new CertificateBuilder().subject("CN=Apache Cassandra Root CA, OU=Certification Authority, O=Unknown, C=Unknown")
+ .alias("fakerootca")
+ .isCertificateAuthority(true)
+ .buildSelfSigned();
+
+ truststorePath = CA.toTempKeyStorePath(tempFolder.getRoot().toPath(),
+ SERVER_TRUSTSTORE_PASSWORD.toCharArray(),
+ SERVER_TRUSTSTORE_PASSWORD.toCharArray());
+
+
+ CertificateBundle keystore = new CertificateBuilder().subject("CN=Apache Cassandra, OU=ssl_test, O=Unknown, L=Unknown, ST=Unknown, C=Unknown")
+ .addSanDnsName(InetAddress.getLocalHost().getCanonicalHostName())
+ .addSanDnsName(InetAddress.getLocalHost().getHostName())
+ .buildIssuedBy(CA);
+
+ Path serverKeystorePath = keystore.toTempKeyStorePath(tempFolder.getRoot().toPath(),
+ SERVER_KEYSTORE_PASSWORD.toCharArray(),
+ SERVER_KEYSTORE_PASSWORD.toCharArray());
+
+ builder.withConfig(c -> c.set("authenticator.class_name", "org.apache.cassandra.auth.MutualTlsWithPasswordFallbackAuthenticator")
+ .set("authenticator.parameters", Collections.singletonMap("validator_class_name", "org.apache.cassandra.auth.SpiffeCertificateValidator"))
+ .set("role_manager", "CassandraRoleManager")
+ .set("authorizer", "CassandraAuthorizer")
+ .set("client_encryption_options.enabled", "true")
+ .set("client_encryption_options.require_client_auth", "optional")
+ .set("client_encryption_options.keystore", serverKeystorePath.toString())
+ .set("client_encryption_options.keystore_password", SERVER_KEYSTORE_PASSWORD)
+ .set("client_encryption_options.truststore", truststorePath.toString())
+ .set("client_encryption_options.truststore_password", SERVER_TRUSTSTORE_PASSWORD)
+ .set("client_encryption_options.require_endpoint_verification", "false")
+ .set("client_encryption_options.max_certificate_validity_period", "30d")
+ .set("client_encryption_options.certificate_validity_warn_threshold", "5d")
+ .with(Feature.NATIVE_PROTOCOL, Feature.GOSSIP));
+ CLUSTER = builder.start();
+
+ configureIdentity();
+ }
+
+ @AfterClass
+ public static void teardown() throws Exception
+ {
+ LOGGER.info("[test step : @AfterClass] teardown");
Review Comment:
think should remove the diagnostic logs when done :+1:
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-18951: Add option for MutualTlsAuthenticator to restrict the certificate age [cassandra]
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #3109:
URL: https://github.com/apache/cassandra/pull/3109#discussion_r1534645121
##########
test/distributed/org/apache/cassandra/distributed/test/auth/MutualTlsCertificateValidityPeriodTest.java:
##########
@@ -0,0 +1,329 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cassandra.distributed.test.auth;
+
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.nio.file.Path;
+import java.time.Instant;
+import java.time.temporal.ChronoUnit;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Optional;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.stream.StreamSupport;
+import javax.net.ssl.SSLException;
+
+import com.google.common.collect.ImmutableMap;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.ClassRule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.datastax.driver.core.PlainTextAuthProvider;
+import com.datastax.driver.core.RemoteEndpointAwareJdkSSLOptions;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Row;
+import com.datastax.driver.core.SSLOptions;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.core.SimpleStatement;
+import com.datastax.driver.core.policies.LoadBalancingPolicy;
+import org.apache.cassandra.config.EncryptionOptions;
+import org.apache.cassandra.distributed.Cluster;
+import org.apache.cassandra.distributed.api.Feature;
+import org.apache.cassandra.distributed.api.ICluster;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.shared.ClusterUtils;
+import org.apache.cassandra.distributed.test.JavaDriverUtils;
+import org.apache.cassandra.distributed.test.TestBaseImpl;
+import org.apache.cassandra.distributed.util.Auth;
+import org.apache.cassandra.distributed.util.SingleHostLoadBalancingPolicy;
+import org.apache.cassandra.security.ISslContextFactory;
+import org.apache.cassandra.transport.SimpleClientSslContextFactory;
+import org.apache.cassandra.utils.tls.CertificateBuilder;
+import org.apache.cassandra.utils.tls.CertificateBundle;
+import org.assertj.core.api.Assertions;
+import org.assertj.core.api.InstanceOfAssertFactories;
+
+import static org.apache.cassandra.auth.CassandraRoleManager.DEFAULT_SUPERUSER_NAME;
+import static org.apache.cassandra.auth.CassandraRoleManager.DEFAULT_SUPERUSER_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.CLIENT_TRUSTSTORE_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.SERVER_KEYSTORE_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.SERVER_TRUSTSTORE_PASSWORD;
+import static org.assertj.core.api.Assertions.as;
+import static org.assertj.core.api.Assertions.fail;
+
+/**
+ * Tests mTLS certificate validity period functionality
+ */
+public class MutualTlsCertificateValidityPeriodTest extends TestBaseImpl
+{
+ private static final Logger LOGGER = LoggerFactory.getLogger(MutualTlsCertificateValidityPeriodTest.class);
+ private static final String IDENTITY = "spiffe://test.cassandra.apache.org/dTest/mtls";
+ private static ICluster<IInvokableInstance> CLUSTER;
+ private static final char[] KEYSTORE_PASSWORD = "cassandra".toCharArray();
+
+ @ClassRule
+ public static TemporaryFolder tempFolder = new TemporaryFolder();
+
+ static CertificateBundle CA;
+ static Path truststorePath;
+
+ @BeforeClass
+ public static void setupClass() throws Exception
Review Comment:
done
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-18951: Add option for MutualTlsAuthenticator to restrict the certificate age [cassandra]
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh closed pull request #3109: CASSANDRA-18951: Add option for MutualTlsAuthenticator to restrict the certificate age
URL: https://github.com/apache/cassandra/pull/3109
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-18951: Add option for MutualTlsAuthenticator to restrict the certificate age [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3109:
URL: https://github.com/apache/cassandra/pull/3109#discussion_r1491854774
##########
src/java/org/apache/cassandra/auth/MutualTlsCertificateValidator.java:
##########
@@ -35,29 +35,55 @@ public interface MutualTlsCertificateValidator
* Perform any checks that are to be performed on the certificate before making authorization check to grant the
* access to the client during mTLS connection.
*
- * For example
- * - Verifying CA information
- * - Checking CN information
- * - Validating Issuer information
- * - Checking organization information etc
+ * <p>For example:
+ * <ul>
+ * <li>Verifying CA information
+ * <li>Checking CN information
+ * <li>Validating Issuer information
+ * <li>Checking organization information etc
+ * </ul>
*
* @param clientCertificateChain client certificate chain
- * @return returns if the certificate is valid or not
+ * @return returns {@code true} if the certificate is valid, {@code false} otherwise
*/
- boolean isValidCertificate(Certificate[] clientCertificateChain);
+ default boolean isValidCertificate(Certificate[] clientCertificateChain)
Review Comment:
worth marking deprecated? From what I can tell its not used anymore.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-18951: Add option for MutualTlsAuthenticator to restrict the certificate age [cassandra]
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #3109:
URL: https://github.com/apache/cassandra/pull/3109#discussion_r1534643560
##########
test/distributed/org/apache/cassandra/distributed/test/auth/MutualTlsCertificateValidityPeriodTest.java:
##########
@@ -0,0 +1,329 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cassandra.distributed.test.auth;
+
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.nio.file.Path;
+import java.time.Instant;
+import java.time.temporal.ChronoUnit;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Optional;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.stream.StreamSupport;
+import javax.net.ssl.SSLException;
+
+import com.google.common.collect.ImmutableMap;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.ClassRule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.datastax.driver.core.PlainTextAuthProvider;
+import com.datastax.driver.core.RemoteEndpointAwareJdkSSLOptions;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Row;
+import com.datastax.driver.core.SSLOptions;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.core.SimpleStatement;
+import com.datastax.driver.core.policies.LoadBalancingPolicy;
+import org.apache.cassandra.config.EncryptionOptions;
+import org.apache.cassandra.distributed.Cluster;
+import org.apache.cassandra.distributed.api.Feature;
+import org.apache.cassandra.distributed.api.ICluster;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.shared.ClusterUtils;
+import org.apache.cassandra.distributed.test.JavaDriverUtils;
+import org.apache.cassandra.distributed.test.TestBaseImpl;
+import org.apache.cassandra.distributed.util.Auth;
+import org.apache.cassandra.distributed.util.SingleHostLoadBalancingPolicy;
+import org.apache.cassandra.security.ISslContextFactory;
+import org.apache.cassandra.transport.SimpleClientSslContextFactory;
+import org.apache.cassandra.utils.tls.CertificateBuilder;
+import org.apache.cassandra.utils.tls.CertificateBundle;
+import org.assertj.core.api.Assertions;
+import org.assertj.core.api.InstanceOfAssertFactories;
+
+import static org.apache.cassandra.auth.CassandraRoleManager.DEFAULT_SUPERUSER_NAME;
+import static org.apache.cassandra.auth.CassandraRoleManager.DEFAULT_SUPERUSER_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.CLIENT_TRUSTSTORE_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.SERVER_KEYSTORE_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.SERVER_TRUSTSTORE_PASSWORD;
+import static org.assertj.core.api.Assertions.as;
+import static org.assertj.core.api.Assertions.fail;
+
+/**
+ * Tests mTLS certificate validity period functionality
+ */
+public class MutualTlsCertificateValidityPeriodTest extends TestBaseImpl
+{
+ private static final Logger LOGGER = LoggerFactory.getLogger(MutualTlsCertificateValidityPeriodTest.class);
+ private static final String IDENTITY = "spiffe://test.cassandra.apache.org/dTest/mtls";
+ private static ICluster<IInvokableInstance> CLUSTER;
+ private static final char[] KEYSTORE_PASSWORD = "cassandra".toCharArray();
+
+ @ClassRule
+ public static TemporaryFolder tempFolder = new TemporaryFolder();
+
+ static CertificateBundle CA;
+ static Path truststorePath;
+
+ @BeforeClass
+ public static void setupClass() throws Exception
+ {
+ LOGGER.info("[test step : @BeforeClass] setupClass");
+ Cluster.Builder builder = Cluster.build(1);
+
+ CA = new CertificateBuilder().subject("CN=Apache Cassandra Root CA, OU=Certification Authority, O=Unknown, C=Unknown")
+ .alias("fakerootca")
+ .isCertificateAuthority(true)
+ .buildSelfSigned();
+
+ truststorePath = CA.toTempKeyStorePath(tempFolder.getRoot().toPath(),
+ SERVER_TRUSTSTORE_PASSWORD.toCharArray(),
+ SERVER_TRUSTSTORE_PASSWORD.toCharArray());
+
+
+ CertificateBundle keystore = new CertificateBuilder().subject("CN=Apache Cassandra, OU=ssl_test, O=Unknown, L=Unknown, ST=Unknown, C=Unknown")
+ .addSanDnsName(InetAddress.getLocalHost().getCanonicalHostName())
+ .addSanDnsName(InetAddress.getLocalHost().getHostName())
+ .buildIssuedBy(CA);
+
+ Path serverKeystorePath = keystore.toTempKeyStorePath(tempFolder.getRoot().toPath(),
+ SERVER_KEYSTORE_PASSWORD.toCharArray(),
+ SERVER_KEYSTORE_PASSWORD.toCharArray());
+
+ builder.withConfig(c -> c.set("authenticator.class_name", "org.apache.cassandra.auth.MutualTlsWithPasswordFallbackAuthenticator")
+ .set("authenticator.parameters", Collections.singletonMap("validator_class_name", "org.apache.cassandra.auth.SpiffeCertificateValidator"))
+ .set("role_manager", "CassandraRoleManager")
+ .set("authorizer", "CassandraAuthorizer")
+ .set("client_encryption_options.enabled", "true")
+ .set("client_encryption_options.require_client_auth", "optional")
+ .set("client_encryption_options.keystore", serverKeystorePath.toString())
+ .set("client_encryption_options.keystore_password", SERVER_KEYSTORE_PASSWORD)
+ .set("client_encryption_options.truststore", truststorePath.toString())
+ .set("client_encryption_options.truststore_password", SERVER_TRUSTSTORE_PASSWORD)
+ .set("client_encryption_options.require_endpoint_verification", "false")
+ .set("client_encryption_options.max_certificate_validity_period", "30d")
+ .set("client_encryption_options.certificate_validity_warn_threshold", "5d")
+ .with(Feature.NATIVE_PROTOCOL, Feature.GOSSIP));
+ CLUSTER = builder.start();
+
+ configureIdentity();
+ }
+
+ @AfterClass
+ public static void teardown() throws Exception
+ {
+ LOGGER.info("[test step : @AfterClass] teardown");
+ if (CLUSTER != null)
+ CLUSTER.close();
+ }
+
+ @Test
+ public void testExpiringCertificate() throws Exception
+ {
+ LOGGER.info("[test step : @Test] testExpiringCertificate");
+ Path clientKeystorePath = generateClientCertificate(null);
+
+ com.datastax.driver.core.Cluster driver = JavaDriverUtils.create(CLUSTER, null, b -> b.withSSL(getSSLOptions(clientKeystorePath)));
+
+ testWithDriver(driver, (Session session) -> {
+ ResultSet clientView = session.execute(new SimpleStatement("SELECT * FROM system_views.clients"));
+ Assertions.assertThat(clientView).isNotNull().isNotEmpty();
+
+ Optional<Row> thisClient = StreamSupport.stream(clientView.spliterator(), false)
+ .filter(row -> "cassandra_ssl_test".equals(row.getString("username")))
+ .findFirst();
+
+ Assertions.assertThat(thisClient).isPresent();
+ Row row = thisClient.get();
+ Map<String, String> authenticationMetadata = row.getMap("authentication_metadata", String.class, String.class);
+
+ Assertions.assertThat(authenticationMetadata).isNotNull().hasSize(1)
+ .containsKey("identity")
+ .extractingByKey("identity", as(InstanceOfAssertFactories.STRING)).isEqualTo(IDENTITY);
+ Assertions.assertThat(row.getString("authentication_mode")).isEqualTo("MutualTls");
+ });
+ }
+
+ @Test
+ public void testCertificateReachingMaxValidityPeriod() throws Exception
+ {
+ LOGGER.info("[test step : @Test] testCertificateReachingMaxValidityPeriod");
+ Path clientKeystorePath = generateClientCertificate(b -> b.notBefore(Instant.now().minus(3, ChronoUnit.DAYS))
+ .notAfter(Instant.now().plus(4, ChronoUnit.DAYS)));
+
+ com.datastax.driver.core.Cluster driver = JavaDriverUtils.create(CLUSTER, null, b -> b.withSSL(getSSLOptions(clientKeystorePath)));
+
+ testWithDriver(driver, (Session session) -> {
+ ResultSet clientView = session.execute(new SimpleStatement("SELECT * FROM system_views.clients"));
+ Assertions.assertThat(clientView).isNotNull().isNotEmpty();
+
+ Optional<Row> thisClient = StreamSupport.stream(clientView.spliterator(), false)
+ .filter(row -> "cassandra_ssl_test".equals(row.getString("username")))
+ .findFirst();
+
+ Assertions.assertThat(thisClient).isPresent();
+ Row row = thisClient.get();
+ Map<String, String> authenticationMetadata = row.getMap("authentication_metadata", String.class, String.class);
+
+ Assertions.assertThat(authenticationMetadata).isNotNull().hasSize(1)
+ .containsKey("identity")
+ .extractingByKey("identity", as(InstanceOfAssertFactories.STRING)).isEqualTo(IDENTITY);
+ Assertions.assertThat(row.getString("authentication_mode")).isEqualTo("MutualTls");
+ });
+ }
+
+ @Test
+ public void testFailsWhenCertificateExceedsMaxAllowedValidityPeriod() throws Exception
+ {
+ LOGGER.info("[test step : @Test] testFailsWhenCertificateExceedsMaxAllowedValidityPeriod");
+ Path clientKeystorePath = generateClientCertificate(b -> b.notAfter(Instant.now().plus(365, ChronoUnit.DAYS)));
+
+ com.datastax.driver.core.Cluster driver = JavaDriverUtils.create(CLUSTER, null, b -> b.withSSL(getSSLOptions(clientKeystorePath)));
+
+ try
+ {
+ testWithDriver(driver, null);
+ fail("Should not be able to connect when the certificate exceeds the maximum allowed validity period");
+ }
+ catch (com.datastax.driver.core.exceptions.NoHostAvailableException exception)
+ {
+ Assertions.assertThat(exception)
+ .hasMessageContaining("The validity period of the provided certificate (527040 minutes) exceeds the maximum allowed validity period of 43200 minutes");
+ }
+ }
+
+ @Test
+ public void testFailsWhenCertificateIsExpired() throws Exception
+ {
+ LOGGER.info("[test step : @Test] testFailsWhenCertificateIsExpired");
+ Path clientKeystorePath = generateClientCertificate(b -> b.notBefore(Instant.now().minus(30, ChronoUnit.DAYS))
Review Comment:
Not really, I have not seen this in the test. But I guess it's something we could easily add a test for
##########
test/distributed/org/apache/cassandra/distributed/test/auth/MutualTlsCertificateValidityPeriodTest.java:
##########
@@ -0,0 +1,329 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cassandra.distributed.test.auth;
+
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.nio.file.Path;
+import java.time.Instant;
+import java.time.temporal.ChronoUnit;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Optional;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.stream.StreamSupport;
+import javax.net.ssl.SSLException;
+
+import com.google.common.collect.ImmutableMap;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.ClassRule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.datastax.driver.core.PlainTextAuthProvider;
+import com.datastax.driver.core.RemoteEndpointAwareJdkSSLOptions;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Row;
+import com.datastax.driver.core.SSLOptions;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.core.SimpleStatement;
+import com.datastax.driver.core.policies.LoadBalancingPolicy;
+import org.apache.cassandra.config.EncryptionOptions;
+import org.apache.cassandra.distributed.Cluster;
+import org.apache.cassandra.distributed.api.Feature;
+import org.apache.cassandra.distributed.api.ICluster;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.shared.ClusterUtils;
+import org.apache.cassandra.distributed.test.JavaDriverUtils;
+import org.apache.cassandra.distributed.test.TestBaseImpl;
+import org.apache.cassandra.distributed.util.Auth;
+import org.apache.cassandra.distributed.util.SingleHostLoadBalancingPolicy;
+import org.apache.cassandra.security.ISslContextFactory;
+import org.apache.cassandra.transport.SimpleClientSslContextFactory;
+import org.apache.cassandra.utils.tls.CertificateBuilder;
+import org.apache.cassandra.utils.tls.CertificateBundle;
+import org.assertj.core.api.Assertions;
+import org.assertj.core.api.InstanceOfAssertFactories;
+
+import static org.apache.cassandra.auth.CassandraRoleManager.DEFAULT_SUPERUSER_NAME;
+import static org.apache.cassandra.auth.CassandraRoleManager.DEFAULT_SUPERUSER_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.CLIENT_TRUSTSTORE_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.SERVER_KEYSTORE_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.SERVER_TRUSTSTORE_PASSWORD;
+import static org.assertj.core.api.Assertions.as;
+import static org.assertj.core.api.Assertions.fail;
+
+/**
+ * Tests mTLS certificate validity period functionality
+ */
+public class MutualTlsCertificateValidityPeriodTest extends TestBaseImpl
+{
+ private static final Logger LOGGER = LoggerFactory.getLogger(MutualTlsCertificateValidityPeriodTest.class);
+ private static final String IDENTITY = "spiffe://test.cassandra.apache.org/dTest/mtls";
+ private static ICluster<IInvokableInstance> CLUSTER;
+ private static final char[] KEYSTORE_PASSWORD = "cassandra".toCharArray();
+
+ @ClassRule
+ public static TemporaryFolder tempFolder = new TemporaryFolder();
+
+ static CertificateBundle CA;
+ static Path truststorePath;
+
+ @BeforeClass
+ public static void setupClass() throws Exception
+ {
+ LOGGER.info("[test step : @BeforeClass] setupClass");
+ Cluster.Builder builder = Cluster.build(1);
+
+ CA = new CertificateBuilder().subject("CN=Apache Cassandra Root CA, OU=Certification Authority, O=Unknown, C=Unknown")
+ .alias("fakerootca")
+ .isCertificateAuthority(true)
+ .buildSelfSigned();
+
+ truststorePath = CA.toTempKeyStorePath(tempFolder.getRoot().toPath(),
+ SERVER_TRUSTSTORE_PASSWORD.toCharArray(),
+ SERVER_TRUSTSTORE_PASSWORD.toCharArray());
+
+
+ CertificateBundle keystore = new CertificateBuilder().subject("CN=Apache Cassandra, OU=ssl_test, O=Unknown, L=Unknown, ST=Unknown, C=Unknown")
+ .addSanDnsName(InetAddress.getLocalHost().getCanonicalHostName())
+ .addSanDnsName(InetAddress.getLocalHost().getHostName())
+ .buildIssuedBy(CA);
+
+ Path serverKeystorePath = keystore.toTempKeyStorePath(tempFolder.getRoot().toPath(),
+ SERVER_KEYSTORE_PASSWORD.toCharArray(),
+ SERVER_KEYSTORE_PASSWORD.toCharArray());
+
+ builder.withConfig(c -> c.set("authenticator.class_name", "org.apache.cassandra.auth.MutualTlsWithPasswordFallbackAuthenticator")
+ .set("authenticator.parameters", Collections.singletonMap("validator_class_name", "org.apache.cassandra.auth.SpiffeCertificateValidator"))
+ .set("role_manager", "CassandraRoleManager")
+ .set("authorizer", "CassandraAuthorizer")
+ .set("client_encryption_options.enabled", "true")
+ .set("client_encryption_options.require_client_auth", "optional")
+ .set("client_encryption_options.keystore", serverKeystorePath.toString())
+ .set("client_encryption_options.keystore_password", SERVER_KEYSTORE_PASSWORD)
+ .set("client_encryption_options.truststore", truststorePath.toString())
+ .set("client_encryption_options.truststore_password", SERVER_TRUSTSTORE_PASSWORD)
+ .set("client_encryption_options.require_endpoint_verification", "false")
+ .set("client_encryption_options.max_certificate_validity_period", "30d")
+ .set("client_encryption_options.certificate_validity_warn_threshold", "5d")
+ .with(Feature.NATIVE_PROTOCOL, Feature.GOSSIP));
+ CLUSTER = builder.start();
+
+ configureIdentity();
+ }
+
+ @AfterClass
+ public static void teardown() throws Exception
+ {
+ LOGGER.info("[test step : @AfterClass] teardown");
Review Comment:
done!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-18951: Add option for MutualTlsAuthenticator to restrict the certificate age [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3109:
URL: https://github.com/apache/cassandra/pull/3109#discussion_r1529380081
##########
test/distributed/org/apache/cassandra/distributed/test/auth/MutualTlsCertificateValidityPeriodTest.java:
##########
@@ -0,0 +1,329 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cassandra.distributed.test.auth;
+
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.nio.file.Path;
+import java.time.Instant;
+import java.time.temporal.ChronoUnit;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Optional;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.stream.StreamSupport;
+import javax.net.ssl.SSLException;
+
+import com.google.common.collect.ImmutableMap;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.ClassRule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.datastax.driver.core.PlainTextAuthProvider;
+import com.datastax.driver.core.RemoteEndpointAwareJdkSSLOptions;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Row;
+import com.datastax.driver.core.SSLOptions;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.core.SimpleStatement;
+import com.datastax.driver.core.policies.LoadBalancingPolicy;
+import org.apache.cassandra.config.EncryptionOptions;
+import org.apache.cassandra.distributed.Cluster;
+import org.apache.cassandra.distributed.api.Feature;
+import org.apache.cassandra.distributed.api.ICluster;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.shared.ClusterUtils;
+import org.apache.cassandra.distributed.test.JavaDriverUtils;
+import org.apache.cassandra.distributed.test.TestBaseImpl;
+import org.apache.cassandra.distributed.util.Auth;
+import org.apache.cassandra.distributed.util.SingleHostLoadBalancingPolicy;
+import org.apache.cassandra.security.ISslContextFactory;
+import org.apache.cassandra.transport.SimpleClientSslContextFactory;
+import org.apache.cassandra.utils.tls.CertificateBuilder;
+import org.apache.cassandra.utils.tls.CertificateBundle;
+import org.assertj.core.api.Assertions;
+import org.assertj.core.api.InstanceOfAssertFactories;
+
+import static org.apache.cassandra.auth.CassandraRoleManager.DEFAULT_SUPERUSER_NAME;
+import static org.apache.cassandra.auth.CassandraRoleManager.DEFAULT_SUPERUSER_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.CLIENT_TRUSTSTORE_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.SERVER_KEYSTORE_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.SERVER_TRUSTSTORE_PASSWORD;
+import static org.assertj.core.api.Assertions.as;
+import static org.assertj.core.api.Assertions.fail;
+
+/**
+ * Tests mTLS certificate validity period functionality
+ */
+public class MutualTlsCertificateValidityPeriodTest extends TestBaseImpl
+{
+ private static final Logger LOGGER = LoggerFactory.getLogger(MutualTlsCertificateValidityPeriodTest.class);
+ private static final String IDENTITY = "spiffe://test.cassandra.apache.org/dTest/mtls";
+ private static ICluster<IInvokableInstance> CLUSTER;
+ private static final char[] KEYSTORE_PASSWORD = "cassandra".toCharArray();
+
+ @ClassRule
+ public static TemporaryFolder tempFolder = new TemporaryFolder();
+
+ static CertificateBundle CA;
+ static Path truststorePath;
+
+ @BeforeClass
+ public static void setupClass() throws Exception
+ {
+ LOGGER.info("[test step : @BeforeClass] setupClass");
+ Cluster.Builder builder = Cluster.build(1);
+
+ CA = new CertificateBuilder().subject("CN=Apache Cassandra Root CA, OU=Certification Authority, O=Unknown, C=Unknown")
+ .alias("fakerootca")
+ .isCertificateAuthority(true)
+ .buildSelfSigned();
+
+ truststorePath = CA.toTempKeyStorePath(tempFolder.getRoot().toPath(),
+ SERVER_TRUSTSTORE_PASSWORD.toCharArray(),
+ SERVER_TRUSTSTORE_PASSWORD.toCharArray());
+
+
+ CertificateBundle keystore = new CertificateBuilder().subject("CN=Apache Cassandra, OU=ssl_test, O=Unknown, L=Unknown, ST=Unknown, C=Unknown")
+ .addSanDnsName(InetAddress.getLocalHost().getCanonicalHostName())
+ .addSanDnsName(InetAddress.getLocalHost().getHostName())
+ .buildIssuedBy(CA);
+
+ Path serverKeystorePath = keystore.toTempKeyStorePath(tempFolder.getRoot().toPath(),
+ SERVER_KEYSTORE_PASSWORD.toCharArray(),
+ SERVER_KEYSTORE_PASSWORD.toCharArray());
+
+ builder.withConfig(c -> c.set("authenticator.class_name", "org.apache.cassandra.auth.MutualTlsWithPasswordFallbackAuthenticator")
+ .set("authenticator.parameters", Collections.singletonMap("validator_class_name", "org.apache.cassandra.auth.SpiffeCertificateValidator"))
+ .set("role_manager", "CassandraRoleManager")
+ .set("authorizer", "CassandraAuthorizer")
+ .set("client_encryption_options.enabled", "true")
+ .set("client_encryption_options.require_client_auth", "optional")
+ .set("client_encryption_options.keystore", serverKeystorePath.toString())
+ .set("client_encryption_options.keystore_password", SERVER_KEYSTORE_PASSWORD)
+ .set("client_encryption_options.truststore", truststorePath.toString())
+ .set("client_encryption_options.truststore_password", SERVER_TRUSTSTORE_PASSWORD)
+ .set("client_encryption_options.require_endpoint_verification", "false")
+ .set("client_encryption_options.max_certificate_validity_period", "30d")
+ .set("client_encryption_options.certificate_validity_warn_threshold", "5d")
+ .with(Feature.NATIVE_PROTOCOL, Feature.GOSSIP));
+ CLUSTER = builder.start();
+
+ configureIdentity();
+ }
+
+ @AfterClass
+ public static void teardown() throws Exception
+ {
+ LOGGER.info("[test step : @AfterClass] teardown");
+ if (CLUSTER != null)
+ CLUSTER.close();
+ }
+
+ @Test
+ public void testExpiringCertificate() throws Exception
+ {
+ LOGGER.info("[test step : @Test] testExpiringCertificate");
+ Path clientKeystorePath = generateClientCertificate(null);
+
+ com.datastax.driver.core.Cluster driver = JavaDriverUtils.create(CLUSTER, null, b -> b.withSSL(getSSLOptions(clientKeystorePath)));
+
+ testWithDriver(driver, (Session session) -> {
+ ResultSet clientView = session.execute(new SimpleStatement("SELECT * FROM system_views.clients"));
+ Assertions.assertThat(clientView).isNotNull().isNotEmpty();
+
+ Optional<Row> thisClient = StreamSupport.stream(clientView.spliterator(), false)
+ .filter(row -> "cassandra_ssl_test".equals(row.getString("username")))
+ .findFirst();
+
+ Assertions.assertThat(thisClient).isPresent();
+ Row row = thisClient.get();
+ Map<String, String> authenticationMetadata = row.getMap("authentication_metadata", String.class, String.class);
+
+ Assertions.assertThat(authenticationMetadata).isNotNull().hasSize(1)
+ .containsKey("identity")
+ .extractingByKey("identity", as(InstanceOfAssertFactories.STRING)).isEqualTo(IDENTITY);
+ Assertions.assertThat(row.getString("authentication_mode")).isEqualTo("MutualTls");
+ });
+ }
+
+ @Test
+ public void testCertificateReachingMaxValidityPeriod() throws Exception
+ {
+ LOGGER.info("[test step : @Test] testCertificateReachingMaxValidityPeriod");
+ Path clientKeystorePath = generateClientCertificate(b -> b.notBefore(Instant.now().minus(3, ChronoUnit.DAYS))
+ .notAfter(Instant.now().plus(4, ChronoUnit.DAYS)));
+
+ com.datastax.driver.core.Cluster driver = JavaDriverUtils.create(CLUSTER, null, b -> b.withSSL(getSSLOptions(clientKeystorePath)));
+
+ testWithDriver(driver, (Session session) -> {
+ ResultSet clientView = session.execute(new SimpleStatement("SELECT * FROM system_views.clients"));
+ Assertions.assertThat(clientView).isNotNull().isNotEmpty();
+
+ Optional<Row> thisClient = StreamSupport.stream(clientView.spliterator(), false)
+ .filter(row -> "cassandra_ssl_test".equals(row.getString("username")))
+ .findFirst();
+
+ Assertions.assertThat(thisClient).isPresent();
+ Row row = thisClient.get();
+ Map<String, String> authenticationMetadata = row.getMap("authentication_metadata", String.class, String.class);
+
+ Assertions.assertThat(authenticationMetadata).isNotNull().hasSize(1)
+ .containsKey("identity")
+ .extractingByKey("identity", as(InstanceOfAssertFactories.STRING)).isEqualTo(IDENTITY);
+ Assertions.assertThat(row.getString("authentication_mode")).isEqualTo("MutualTls");
+ });
+ }
+
+ @Test
+ public void testFailsWhenCertificateExceedsMaxAllowedValidityPeriod() throws Exception
+ {
+ LOGGER.info("[test step : @Test] testFailsWhenCertificateExceedsMaxAllowedValidityPeriod");
+ Path clientKeystorePath = generateClientCertificate(b -> b.notAfter(Instant.now().plus(365, ChronoUnit.DAYS)));
+
+ com.datastax.driver.core.Cluster driver = JavaDriverUtils.create(CLUSTER, null, b -> b.withSSL(getSSLOptions(clientKeystorePath)));
+
+ try
+ {
+ testWithDriver(driver, null);
+ fail("Should not be able to connect when the certificate exceeds the maximum allowed validity period");
+ }
+ catch (com.datastax.driver.core.exceptions.NoHostAvailableException exception)
+ {
+ Assertions.assertThat(exception)
+ .hasMessageContaining("The validity period of the provided certificate (527040 minutes) exceeds the maximum allowed validity period of 43200 minutes");
+ }
+ }
+
+ @Test
+ public void testFailsWhenCertificateIsExpired() throws Exception
+ {
+ LOGGER.info("[test step : @Test] testFailsWhenCertificateIsExpired");
+ Path clientKeystorePath = generateClientCertificate(b -> b.notBefore(Instant.now().minus(30, ChronoUnit.DAYS))
Review Comment:
One thing I learned recently is that expired certificates will successfully handshake if the certificate is self signed and directly in the trust store. I see you are making certificates signed by another CA so this is failing as expected. Just wondering if you encountered the same :)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-18951: Add option for MutualTlsAuthenticator to restrict the certificate age [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3109:
URL: https://github.com/apache/cassandra/pull/3109#discussion_r1529382596
##########
test/distributed/org/apache/cassandra/distributed/test/auth/MutualTlsCertificateValidityPeriodTest.java:
##########
@@ -0,0 +1,329 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cassandra.distributed.test.auth;
+
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.nio.file.Path;
+import java.time.Instant;
+import java.time.temporal.ChronoUnit;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Optional;
+import java.util.function.Consumer;
+import java.util.function.Function;
+import java.util.stream.StreamSupport;
+import javax.net.ssl.SSLException;
+
+import com.google.common.collect.ImmutableMap;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.ClassRule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.datastax.driver.core.PlainTextAuthProvider;
+import com.datastax.driver.core.RemoteEndpointAwareJdkSSLOptions;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Row;
+import com.datastax.driver.core.SSLOptions;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.core.SimpleStatement;
+import com.datastax.driver.core.policies.LoadBalancingPolicy;
+import org.apache.cassandra.config.EncryptionOptions;
+import org.apache.cassandra.distributed.Cluster;
+import org.apache.cassandra.distributed.api.Feature;
+import org.apache.cassandra.distributed.api.ICluster;
+import org.apache.cassandra.distributed.api.IInvokableInstance;
+import org.apache.cassandra.distributed.shared.ClusterUtils;
+import org.apache.cassandra.distributed.test.JavaDriverUtils;
+import org.apache.cassandra.distributed.test.TestBaseImpl;
+import org.apache.cassandra.distributed.util.Auth;
+import org.apache.cassandra.distributed.util.SingleHostLoadBalancingPolicy;
+import org.apache.cassandra.security.ISslContextFactory;
+import org.apache.cassandra.transport.SimpleClientSslContextFactory;
+import org.apache.cassandra.utils.tls.CertificateBuilder;
+import org.apache.cassandra.utils.tls.CertificateBundle;
+import org.assertj.core.api.Assertions;
+import org.assertj.core.api.InstanceOfAssertFactories;
+
+import static org.apache.cassandra.auth.CassandraRoleManager.DEFAULT_SUPERUSER_NAME;
+import static org.apache.cassandra.auth.CassandraRoleManager.DEFAULT_SUPERUSER_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.CLIENT_TRUSTSTORE_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.SERVER_KEYSTORE_PASSWORD;
+import static org.apache.cassandra.transport.TlsTestUtils.SERVER_TRUSTSTORE_PASSWORD;
+import static org.assertj.core.api.Assertions.as;
+import static org.assertj.core.api.Assertions.fail;
+
+/**
+ * Tests mTLS certificate validity period functionality
+ */
+public class MutualTlsCertificateValidityPeriodTest extends TestBaseImpl
+{
+ private static final Logger LOGGER = LoggerFactory.getLogger(MutualTlsCertificateValidityPeriodTest.class);
+ private static final String IDENTITY = "spiffe://test.cassandra.apache.org/dTest/mtls";
+ private static ICluster<IInvokableInstance> CLUSTER;
+ private static final char[] KEYSTORE_PASSWORD = "cassandra".toCharArray();
+
+ @ClassRule
+ public static TemporaryFolder tempFolder = new TemporaryFolder();
+
+ static CertificateBundle CA;
+ static Path truststorePath;
+
+ @BeforeClass
+ public static void setupClass() throws Exception
Review Comment:
Could also use some additional validation on the MutualTlsMetrics to ensure they are updated.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-18951: Add option for MutualTlsAuthenticator to restrict the certificate age [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3109:
URL: https://github.com/apache/cassandra/pull/3109#discussion_r1529367344
##########
test/unit/org/apache/cassandra/utils/tls/CertificateBuilder.java:
##########
@@ -0,0 +1,234 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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 org.apache.cassandra.utils.tls;
+
+import java.io.IOException;
+import java.math.BigInteger;
+import java.security.GeneralSecurityException;
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.security.SecureRandom;
+import java.security.cert.X509Certificate;
+import java.security.spec.AlgorithmParameterSpec;
+import java.security.spec.ECGenParameterSpec;
+import java.security.spec.RSAKeyGenParameterSpec;
+import java.time.Instant;
+import java.time.temporal.ChronoUnit;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.Objects;
+import javax.security.auth.x500.X500Principal;
+
+import org.bouncycastle.asn1.x500.X500Name;
+import org.bouncycastle.asn1.x509.BasicConstraints;
+import org.bouncycastle.asn1.x509.Extension;
+import org.bouncycastle.asn1.x509.GeneralName;
+import org.bouncycastle.asn1.x509.GeneralNames;
+import org.bouncycastle.cert.X509CertificateHolder;
+import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
+import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder;
+import org.bouncycastle.operator.ContentSigner;
+import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
+
+/**
+ * A utility class to generate certificates for tests
+ */
+public class CertificateBuilder
Review Comment:
Very cool ❤️ assuming this gets in would be fun to do a follow on ticket to see if we can refactor existing tests to use this instead of pre-built keystores.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-18951: Add option for MutualTlsAuthenticator to restrict the certificate age [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3109:
URL: https://github.com/apache/cassandra/pull/3109#discussion_r1491821475
##########
src/java/org/apache/cassandra/auth/MutualTlsAuthenticator.java:
##########
@@ -87,6 +101,18 @@ public MutualTlsAuthenticator(Map<String, String> parameters)
}
certificateValidator = ParameterizedClass.newInstance(new ParameterizedClass(certificateValidatorClassName),
Arrays.asList("", AuthConfig.class.getPackage().getName()));
+
+ String maxCertificateAgeConfig = parameters.get(MAX_CERTIFICATE_AGE_CONFIG);
Review Comment:
On the other hand there's an argument to move the evaluation out of the validator, so all `MutualTlsCertificateValidator` impleemntations don't have to implement logic to validate the certificate age.
##########
src/java/org/apache/cassandra/auth/MutualTlsAuthenticator.java:
##########
@@ -87,6 +101,18 @@ public MutualTlsAuthenticator(Map<String, String> parameters)
}
certificateValidator = ParameterizedClass.newInstance(new ParameterizedClass(certificateValidatorClassName),
Arrays.asList("", AuthConfig.class.getPackage().getName()));
+
+ String maxCertificateAgeConfig = parameters.get(MAX_CERTIFICATE_AGE_CONFIG);
Review Comment:
On the other hand there's an argument to move the evaluation completely out of the validator, so all `MutualTlsCertificateValidator` impleemntations don't have to implement logic to validate the certificate age.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-18951: Add option for MutualTlsAuthenticator to restrict the certificate age [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3109:
URL: https://github.com/apache/cassandra/pull/3109#discussion_r1491856502
##########
src/java/org/apache/cassandra/auth/MutualTlsCertificateValidator.java:
##########
@@ -35,29 +35,55 @@ public interface MutualTlsCertificateValidator
* Perform any checks that are to be performed on the certificate before making authorization check to grant the
* access to the client during mTLS connection.
*
- * For example
- * - Verifying CA information
- * - Checking CN information
- * - Validating Issuer information
- * - Checking organization information etc
+ * <p>For example:
+ * <ul>
+ * <li>Verifying CA information
+ * <li>Checking CN information
+ * <li>Validating Issuer information
+ * <li>Checking organization information etc
+ * </ul>
*
* @param clientCertificateChain client certificate chain
- * @return returns if the certificate is valid or not
+ * @return returns {@code true} if the certificate is valid, {@code false} otherwise
*/
- boolean isValidCertificate(Certificate[] clientCertificateChain);
+ default boolean isValidCertificate(Certificate[] clientCertificateChain)
+ {
+ return isValidCertificate(clientCertificateChain, Integer.MAX_VALUE);
+ }
+
+ /**
+ * Perform any checks that are to be performed on the certificate before making authorization check to grant the
+ * access to the client during mTLS connection.
+ *
+ * <p>For example:
+ * <ul>
+ * <li>Verifying CA information
+ * <li>Checking CN information
+ * <li>Validating Issuer information
+ * <li>Checking organization information etc
+ * </ul>
+ *
+ * @param clientCertificateChain client certificate chain
+ * @param maxCertificateAgeMinutes the maximum age allowed for the certificates in the chain
+ * @return returns {@code true} if the certificate is valid, {@code false} otherwise
+ * @throws AuthenticationException when the age of the certificate is greater than the maximum allowed age
+ * for the certificate
+ */
+ boolean isValidCertificate(Certificate[] clientCertificateChain, int maxCertificateAgeMinutes) throws AuthenticationException;
Review Comment:
maybe `isValidCertificate(Certificate[] clientCertificateChain, int maxCertificateAgeMinutes)` should be `default` and call `isValidCertificate(Certificate[] clientCertificateChain)`, instead of how it currently works. This way existing implementations don't need to make any implementation changes for this to work. (this may be moot if you end up moving out the age verification from the validator)
##########
src/java/org/apache/cassandra/auth/MutualTlsCertificateValidator.java:
##########
@@ -35,29 +35,55 @@ public interface MutualTlsCertificateValidator
* Perform any checks that are to be performed on the certificate before making authorization check to grant the
* access to the client during mTLS connection.
*
- * For example
- * - Verifying CA information
- * - Checking CN information
- * - Validating Issuer information
- * - Checking organization information etc
+ * <p>For example:
+ * <ul>
+ * <li>Verifying CA information
+ * <li>Checking CN information
+ * <li>Validating Issuer information
+ * <li>Checking organization information etc
+ * </ul>
*
* @param clientCertificateChain client certificate chain
- * @return returns if the certificate is valid or not
+ * @return returns {@code true} if the certificate is valid, {@code false} otherwise
*/
- boolean isValidCertificate(Certificate[] clientCertificateChain);
+ default boolean isValidCertificate(Certificate[] clientCertificateChain)
Review Comment:
(this may be moot if you end up moving out the age verification from the validator)
##########
src/java/org/apache/cassandra/auth/MutualTlsCertificateValidator.java:
##########
@@ -35,29 +35,55 @@ public interface MutualTlsCertificateValidator
* Perform any checks that are to be performed on the certificate before making authorization check to grant the
* access to the client during mTLS connection.
*
- * For example
- * - Verifying CA information
- * - Checking CN information
- * - Validating Issuer information
- * - Checking organization information etc
+ * <p>For example:
+ * <ul>
+ * <li>Verifying CA information
+ * <li>Checking CN information
+ * <li>Validating Issuer information
+ * <li>Checking organization information etc
+ * </ul>
*
* @param clientCertificateChain client certificate chain
- * @return returns if the certificate is valid or not
+ * @return returns {@code true} if the certificate is valid, {@code false} otherwise
*/
- boolean isValidCertificate(Certificate[] clientCertificateChain);
+ default boolean isValidCertificate(Certificate[] clientCertificateChain)
Review Comment:
(this may be moot if you end up moving out the age verification from the validator)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-18951: Add option for MutualTlsAuthenticator to restrict the certificate age [cassandra]
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #3109:
URL: https://github.com/apache/cassandra/pull/3109#discussion_r1499756263
##########
conf/cassandra.yaml:
##########
@@ -158,6 +158,7 @@ authenticator:
# class_name : org.apache.cassandra.auth.MutualTlsAuthenticator
# parameters :
# validator_class_name: org.apache.cassandra.auth.SpiffeCertificateValidator
+# max_certificate_age: 365d
Review Comment:
done, added a comment above
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-18951: Add option for MutualTlsAuthenticator to restrict the certificate age [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3109:
URL: https://github.com/apache/cassandra/pull/3109#discussion_r1491854774
##########
src/java/org/apache/cassandra/auth/MutualTlsCertificateValidator.java:
##########
@@ -35,29 +35,55 @@ public interface MutualTlsCertificateValidator
* Perform any checks that are to be performed on the certificate before making authorization check to grant the
* access to the client during mTLS connection.
*
- * For example
- * - Verifying CA information
- * - Checking CN information
- * - Validating Issuer information
- * - Checking organization information etc
+ * <p>For example:
+ * <ul>
+ * <li>Verifying CA information
+ * <li>Checking CN information
+ * <li>Validating Issuer information
+ * <li>Checking organization information etc
+ * </ul>
*
* @param clientCertificateChain client certificate chain
- * @return returns if the certificate is valid or not
+ * @return returns {@code true} if the certificate is valid, {@code false} otherwise
*/
- boolean isValidCertificate(Certificate[] clientCertificateChain);
+ default boolean isValidCertificate(Certificate[] clientCertificateChain)
Review Comment:
worth marking deprecated? From what I can tell its not used anymore. (this may be moot if you end up moving out the age verification from the validator)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-18951: Add option for MutualTlsAuthenticator to restrict the certificate age [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3109:
URL: https://github.com/apache/cassandra/pull/3109#discussion_r1491826660
##########
test/unit/org/apache/cassandra/auth/MutualTlsAuthenticatorTest.java:
##########
@@ -86,7 +90,7 @@ public static void setup()
@After
public void after() throws IOException, TimeoutException
{
- MBeanWrapper.instance.unregisterMBean("org.apache.cassandra.auth:type=IdentitiesCache");
+ MBeanWrapper.instance.unregisterMBean("org.apache.cassandra.auth:type=IdentitiesCache", MBeanWrapper.OnException.IGNORE);
Review Comment:
I was wondering why this was needed, is it because `testValidMaxCertificateAgeConfiguration` unregisters after each pair, so at the end of the test the bean is no longer registered?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-18951: Add option for MutualTlsAuthenticator to restrict the certificate age [cassandra]
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #3109:
URL: https://github.com/apache/cassandra/pull/3109#discussion_r1491828414
##########
src/java/org/apache/cassandra/auth/MutualTlsAuthenticator.java:
##########
@@ -87,6 +101,18 @@ public MutualTlsAuthenticator(Map<String, String> parameters)
}
certificateValidator = ParameterizedClass.newInstance(new ParameterizedClass(certificateValidatorClassName),
Arrays.asList("", AuthConfig.class.getPackage().getName()));
+
+ String maxCertificateAgeConfig = parameters.get(MAX_CERTIFICATE_AGE_CONFIG);
Review Comment:
yeah good point, I think there's more value in moving the validation out of the validator.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-18951: Add option for MutualTlsAuthenticator to restrict the certificate age [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3109:
URL: https://github.com/apache/cassandra/pull/3109#discussion_r1534711690
##########
src/java/org/apache/cassandra/auth/MutualTlsAuthenticator.java:
##########
@@ -208,9 +224,29 @@ public AuthenticatedUser getAuthenticatedUser() throws AuthenticationException
nospamLogger.error(msg, identity);
throw new AuthenticationException(MessageFormatter.format(msg, identity).getMessage());
}
+
+ // Validates that the certificate validity period does not exceed the maximum certificate configured validity period
+ int minutesToCertificateExpiration = certificateValidityPeriodValidator.validate(clientCertificateChain);
+ int daysToCertificateExpiration = toDays(minutesToCertificateExpiration);
+
+ if (certificateValidityWarnThreshold != null
+ && minutesToCertificateExpiration < certificateValidityWarnThreshold.toMinutes())
+ {
+ nospamLogger.warn("Certificate with identity '{}' will expire in {} minutes",
Review Comment:
your solution for this looks great, thank you!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-18951: Add option for MutualTlsAuthenticator to restrict the certificate age [cassandra]
Posted by "tolbertam (via GitHub)" <gi...@apache.org>.
tolbertam commented on code in PR #3109:
URL: https://github.com/apache/cassandra/pull/3109#discussion_r1500086508
##########
src/java/org/apache/cassandra/auth/MutualTlsAuthenticator.java:
##########
@@ -208,6 +234,16 @@ public AuthenticatedUser getAuthenticatedUser() throws AuthenticationException
nospamLogger.error(msg, identity);
throw new AuthenticationException(MessageFormatter.format(msg, identity).getMessage());
}
+
+ // Validates that the certificate age does not exceed the maximum certificate age
+ certificateValidator.certificateAgeConsumer(clientCertificateChain, certificateAgeMinutes -> {
Review Comment:
Hrmm, I'm wondering why we need both `certificateAgeInMinutes` and `certificateAgeConsumer` on `MutualTlsCertificateValidator`, especiallly if `certificateAgeConsumer` calls `certificateAgeMinutes`?
```java
int certificateAgeMinutes = certificateValidator.certificateAgeInMinutes(clientCertificateChain);
if (certificateAgeMinutes > maxCertificateAgeMinutes)
{
String errorMessage = String.format("The age of the provided certificate (%d minutes) exceeds the maximum allowed age of %d minutes", certificateAgeMinutes, maxCertificateAgeMinutes);
throw new AuthenticationException(errorMessage);
}
```
I'm guessing you are looking to avoid duplicating the logic between the Authenticator and InternodeAuthenticator implementations? Could't we just make a static utility method instead that both can use? In that case we could potentially go about things in a way where we don't need any new API on `MutualTlsCertificateValidator` (not sure we need validator-specific logic for this).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSANDRA-18951: Add option for MutualTlsAuthenticator to restrict the certificate age [cassandra]
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on PR #3109:
URL: https://github.com/apache/cassandra/pull/3109#issuecomment-2019129840
Closed via https://github.com/apache/cassandra/commit/a0af41f666c23a840d9df3f06729ed5fd2c06cd1
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org