Skip to content

Commit f35fac5

Browse files
authored
Select a JSSE certificate valid for TLS server authentication
When configuring a JSSE Certificate from a key store that exposes several certificates sharing a Subject, ignore those that are not valid for TLS server authentication (by extended key usage) so a usable certificate is selected rather than relying on the key store alias alone.
1 parent aa920fd commit f35fac5

8 files changed

Lines changed: 482 additions & 15 deletions

File tree

‎java/org/apache/tomcat/util/net/Constants.java‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,13 @@ public class Constants {
6868
*/
6969
public static final String SSL_PROTO_SSLv2Hello = "SSLv2Hello";
7070

71+
/**
72+
* EKU OIDs.
73+
*/
74+
public static final String SERVER_AUTH_EXTENDED_KEY_USAGE_OID = "1.3.6.1.5.5.7.3.1";
75+
public static final String CLIENT_AUTH_EXTENDED_KEY_USAGE_OID = "1.3.6.1.5.5.7.3.2";
76+
public static final String ANY_EXTENDED_KEY_USAGE_OID = "2.5.29.37.0";
77+
7178
/**
7279
* Private constructor to prevent instantiation.
7380
*/

‎java/org/apache/tomcat/util/net/LocalStrings.properties‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,12 +175,16 @@ sslUtilBase.alias_no_key_entry=Alias name [{0}] does not identify a key entry
175175
sslUtilBase.fipsPemNotSupported=FIPS enabled so PEM format certificate files are not supported. Configure the certificate using a key store rather than the certificateFile attribute
176176
sslUtilBase.invalidTrustManagerClassName=The trustManagerClassName provided [{0}] does not implement javax.net.ssl.TrustManager
177177
sslUtilBase.keystore_load_failed=Failed to load keystore type [{0}] with path [{1}] due to [{2}]
178+
sslUtilBase.multipleServerAuthCerts=Starting from alias [{0}], multiple certificates valid for TLS server authentication were found: [{1}]. The first one will be used.
178179
sslUtilBase.noCertFile=SSLHostConfig attribute certificateFile must be defined when using an SSL connector
179180
sslUtilBase.noCrlSupport=The truststoreProvider [{0}] does not support the certificateRevocationFile configuration option
180181
sslUtilBase.noKeys=No aliases for private keys found in key store
182+
sslUtilBase.noServerAuthCert=No certificate valid for TLS server authentication was found for alias [{0}]. The configured alias will be used unchanged.
181183
sslUtilBase.noVerificationDepth=The truststoreProvider [{0}] does not support the certificateVerificationDepth configuration option
182184
sslUtilBase.noneSupported=None of the [{0}] specified are supported by the SSL engine : [{1}]
185+
sslUtilBase.selectedServerAuthCert=Selected the certificate with alias [{0}] for TLS server authentication in preference to the configured alias [{1}]
183186
sslUtilBase.skipped=Tomcat interprets the [{0}] attribute in a manner consistent with the latest OpenSSL development branch. Some of the specified [{0}] are not supported by the configured SSL engine for this connector (which may use JSSE or an older OpenSSL version) and have been skipped: [{1}]
187+
sslUtilBase.skippedKeyUsage=Skipping certificate with alias [{0}] as it is not valid for TLS server authentication
184188
sslUtilBase.ssl3=SSLv3 has been explicitly enabled. This protocol is known to be insecure.
185189
sslUtilBase.tls13.auth=The JSSE TLS 1.3 implementation does not support post handshake authentication (PHA) and is therefore incompatible with optional certificate authentication
186190
sslUtilBase.trustedCertNotChecked=The validity dates of the trusted certificate with alias [{0}] were not checked as the certificate was of an unknown type

‎java/org/apache/tomcat/util/net/SSLUtilBase.java‎

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
import java.security.DomainLoadStoreParameter;
2626
import java.security.Key;
2727
import java.security.KeyStore;
28+
import java.security.KeyStoreException;
2829
import java.security.cert.CRL;
2930
import java.security.cert.CRLException;
3031
import java.security.cert.CertPathParameters;
@@ -36,6 +37,7 @@
3637
import java.security.cert.CertificateExpiredException;
3738
import java.security.cert.CertificateFactory;
3839
import java.security.cert.CertificateNotYetValidException;
40+
import java.security.cert.CertificateParsingException;
3941
import java.security.cert.CollectionCertStoreParameters;
4042
import java.security.cert.PKIXBuilderParameters;
4143
import java.security.cert.PKIXRevocationChecker;
@@ -59,6 +61,7 @@
5961
import javax.net.ssl.TrustManager;
6062
import javax.net.ssl.TrustManagerFactory;
6163
import javax.net.ssl.X509KeyManager;
64+
import javax.security.auth.x500.X500Principal;
6265

6366
import org.apache.juli.logging.Log;
6467
import org.apache.juli.logging.LogFactory;
@@ -411,6 +414,8 @@ public KeyManager[] getKeyManagers() throws Exception {
411414
}
412415
}
413416

417+
keyAlias = selectServerAuthAlias(ks, keyAlias, certificate.getCertificateKeyAlias() != null);
418+
414419
Key k = ks.getKey(keyAlias, keyPassArray);
415420
if (k != null && !"DKS".equalsIgnoreCase(certificate.getCertificateKeystoreType()) &&
416421
"PKCS#8".equalsIgnoreCase(k.getFormat())) {
@@ -450,6 +455,108 @@ public KeyManager[] getKeyManagers() throws Exception {
450455
}
451456

452457

458+
/*
459+
* Prefer a key entry whose certificate is usable for TLS server authentication. This handles key stores that can
460+
* expose several certificates sharing a Subject (and therefore colliding on similar aliases).
461+
* The certificate currently identified by the alias provides the Subject to match.
462+
* When no alias was configured every key entry is a candidate.
463+
* When no usable certificate is found, the configured alias is returned unchanged.
464+
*/
465+
private String selectServerAuthAlias(KeyStore ks, String currentAlias, boolean aliasConfigured)
466+
throws KeyStoreException, CertificateParsingException {
467+
468+
Certificate current = ks.getCertificate(currentAlias);
469+
X509Certificate currentX509 = current instanceof X509Certificate x509 ? x509 : null;
470+
471+
// If the current selection is already usable there is nothing to do.
472+
if (currentX509 != null && isServerAuthCapable(currentX509)) {
473+
return currentAlias;
474+
}
475+
476+
X500Principal subject = currentX509 == null ? null : currentX509.getSubjectX500Principal();
477+
478+
List<String> matches = new ArrayList<>();
479+
// Defense-in-depth so no misbehaving provider can ever hang a TLS-config path.
480+
int remaining = ks.size();
481+
Enumeration<String> aliases = ks.aliases();
482+
while (aliases.hasMoreElements() && remaining-- > 0) {
483+
String alias = aliases.nextElement();
484+
if (!ks.isKeyEntry(alias)) {
485+
continue;
486+
}
487+
Certificate candidate = ks.getCertificate(alias);
488+
if (!(candidate instanceof X509Certificate x509Candidate)) {
489+
continue;
490+
}
491+
// When the user named an alias, only consider certificates that share its Subject.
492+
if (aliasConfigured && subject != null && !subject.equals(x509Candidate.getSubjectX500Principal())) {
493+
continue;
494+
}
495+
if (isServerAuthCapable(x509Candidate)) {
496+
matches.add(alias);
497+
} else if (log.isDebugEnabled()) {
498+
log.debug(sm.getString("sslUtilBase.skippedKeyUsage", alias));
499+
}
500+
}
501+
502+
if (matches.isEmpty()) {
503+
if (log.isDebugEnabled()) {
504+
log.debug(sm.getString("sslUtilBase.noServerAuthCert", currentAlias));
505+
}
506+
return currentAlias;
507+
}
508+
if (matches.size() > 1 && log.isDebugEnabled()) {
509+
log.debug(sm.getString("sslUtilBase.multipleServerAuthCerts", currentAlias, matches));
510+
}
511+
String selected = matches.get(0);
512+
if (!selected.equals(currentAlias) && log.isDebugEnabled()) {
513+
log.debug(sm.getString("sslUtilBase.selectedServerAuthCert", selected, currentAlias));
514+
}
515+
return selected;
516+
}
517+
518+
519+
/**
520+
* Determines whether the given certificate may be used for TLS server authentication, based on its Extended Key
521+
* Usage (EKU) extension. Called by {@link #selectServerAuthAlias} to choose between certificates that share a
522+
* Subject.
523+
* <p>
524+
* The policy is deliberately lenient about absent usage and strict about declared usage:
525+
* <ul>
526+
* <li>A certificate with <strong>no EKU extension</strong> ({@link X509Certificate#getExtendedKeyUsage()} returns
527+
* {@code null}) is treated as usable. An absent EKU places no restriction on the certificate's purpose - the
528+
* way TLS implementations generally interpret such certificates - so rejecting them would needlessly exclude
529+
* the many server certificates issued without an EKU.</li>
530+
* <li>A certificate that <strong>does</strong> carry an EKU extension is usable only if that extension explicitly
531+
* lists the {@code id-kp-serverAuth} OID ({@value Constants#SERVER_AUTH_EXTENDED_KEY_USAGE_OID}) or the
532+
* {@code anyExtendedKeyUsage} OID ({@value Constants#ANY_EXTENDED_KEY_USAGE_OID}). Any other declared usage
533+
* - for example a certificate limited to client authentication, such as a Remote Desktop authentication
534+
* certificate - is rejected, which is what lets this feature skip the wrong certificate.</li>
535+
* </ul>
536+
*
537+
* @param cert the certificate to test
538+
*
539+
* @return {@code true} if the certificate may be used for TLS server authentication
540+
*
541+
* @throws CertificateParsingException if the Extended Key Usage extension cannot be decoded
542+
*/
543+
private static boolean isServerAuthCapable(X509Certificate cert) throws CertificateParsingException {
544+
List<String> objectIdentifiers = cert.getExtendedKeyUsage();
545+
546+
if (objectIdentifiers == null) {
547+
return true;
548+
}
549+
550+
for (String objectIdentifier : objectIdentifiers) {
551+
if (objectIdentifier.equals(Constants.SERVER_AUTH_EXTENDED_KEY_USAGE_OID) ||
552+
objectIdentifier.equals(Constants.ANY_EXTENDED_KEY_USAGE_OID)) {
553+
return true;
554+
}
555+
}
556+
557+
return false;
558+
}
559+
453560
@Override
454561
public String[] getEnabledProtocols() {
455562
return enabledProtocols;
Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
/*
2+
* Licensed to the Apache Software Foundation (ASF) under one or more
3+
* contributor license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright ownership.
5+
* The ASF licenses this file to You under the Apache License, Version 2.0
6+
* (the "License"); you may not use this file except in compliance with
7+
* the License. You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS,
13+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
* See the License for the specific language governing permissions and
15+
* limitations under the License.
16+
*/
17+
18+
package org.apache.tomcat.util.net;
19+
20+
import java.io.File;
21+
import java.security.cert.X509Certificate;
22+
import java.util.List;
23+
24+
import javax.net.ssl.X509KeyManager;
25+
26+
import org.junit.Assert;
27+
import org.junit.Test;
28+
29+
import org.apache.tomcat.util.net.SSLHostConfigCertificate.Type;
30+
import org.apache.tomcat.util.net.TesterKeystoreGenerator.CertificateExtensionsCustomizer;
31+
import org.apache.tomcat.util.net.TesterKeystoreGenerator.KeystoreEntry;
32+
import org.apache.tomcat.util.net.jsse.JSSEUtil;
33+
import org.bouncycastle.asn1.x509.ExtendedKeyUsage;
34+
import org.bouncycastle.asn1.x509.Extension;
35+
import org.bouncycastle.asn1.x509.KeyPurposeId;
36+
37+
/**
38+
* Tests selection of a TLS server authentication certificate when a key store holds several certificates that share a
39+
* Subject.
40+
*/
41+
public class TestSSLUtilBaseKeyUsageSelection {
42+
43+
private static final String HOST = "localhost";
44+
45+
@SuppressWarnings("unused")
46+
private static final CertificateExtensionsCustomizer SERVER_AUTH = (keyPair, builder) -> builder
47+
.addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));
48+
@SuppressWarnings("unused")
49+
private static final CertificateExtensionsCustomizer CLIENT_AUTH = (keyPair, builder) -> builder
50+
.addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth));
51+
@SuppressWarnings("unused")
52+
private static final CertificateExtensionsCustomizer ANY_AUTH = (keyPair, builder) -> builder
53+
.addExtension(Extension.extendedKeyUsage, true, new ExtendedKeyUsage(KeyPurposeId.anyExtendedKeyUsage));
54+
55+
56+
private static KeystoreEntry key(String alias, CertificateExtensionsCustomizer eku) {
57+
return KeystoreEntry.key(alias, HOST, eku);
58+
}
59+
60+
61+
/*
62+
* Builds a key store from the given entries, configures a JSSE certificate pointed at alias (null for none), and
63+
* returns the leaf certificate the key manager actually presents.
64+
*/
65+
private static X509Certificate present(String alias, KeystoreEntry... entries) throws Exception {
66+
File keystore = TesterKeystoreGenerator.generateKeystore(List.of(entries));
67+
68+
SSLHostConfig hostConfig = new SSLHostConfig();
69+
SSLHostConfigCertificate certificate = new SSLHostConfigCertificate(hostConfig, Type.UNDEFINED);
70+
certificate.setCertificateKeystoreFile(keystore.getAbsolutePath());
71+
certificate.setCertificateKeystorePassword(TesterSupport.JKS_PASS);
72+
if (alias != null) {
73+
certificate.setCertificateKeyAlias(alias);
74+
}
75+
76+
X509KeyManager keyManager = (X509KeyManager) new JSSEUtil(certificate).getKeyManagers()[0];
77+
X509Certificate[] chain = keyManager.getCertificateChain(keyManager.chooseServerAlias("RSA", null, null));
78+
Assert.assertNotNull("Key manager returned no certificate chain", chain);
79+
return chain[0];
80+
}
81+
82+
83+
private static void assertEku(X509Certificate certificate, String oid) throws Exception {
84+
List<String> extendedKeyUsage = certificate.getExtendedKeyUsage();
85+
Assert.assertNotNull("Presented certificate has no Extended Key Usage", extendedKeyUsage);
86+
Assert.assertTrue("Presented certificate must be valid for Extended Key Usage " + oid,
87+
extendedKeyUsage.contains(oid));
88+
}
89+
90+
91+
@Test
92+
public void testSelectsServerAuthCertificateOverConfiguredClientAuthAlias() throws Exception {
93+
X509Certificate presented = present(HOST,
94+
key(HOST, CLIENT_AUTH),
95+
key("localhost-server", SERVER_AUTH));
96+
assertEku(presented, Constants.SERVER_AUTH_EXTENDED_KEY_USAGE_OID);
97+
}
98+
99+
100+
@Test
101+
public void testKeepsConfiguredAliasWhenItIsAlreadyServerAuth() throws Exception {
102+
X509Certificate presented = present(HOST,
103+
key(HOST, SERVER_AUTH),
104+
key("localhost-client", CLIENT_AUTH));
105+
assertEku(presented, Constants.SERVER_AUTH_EXTENDED_KEY_USAGE_OID);
106+
}
107+
108+
109+
@Test
110+
public void testSelectsCertificateWithAnyExtendedKeyUsage() throws Exception {
111+
X509Certificate presented = present(HOST,
112+
key(HOST, CLIENT_AUTH),
113+
key("localhost-any", ANY_AUTH));
114+
assertEku(presented, Constants.ANY_EXTENDED_KEY_USAGE_OID);
115+
}
116+
117+
118+
@Test
119+
public void testSelectsCertificateWithoutExtendedKeyUsage() throws Exception {
120+
X509Certificate presented = present(HOST,
121+
key(HOST, CLIENT_AUTH),
122+
key("localhost-none", null));
123+
Assert.assertNull("A certificate with no Extended Key Usage is unrestricted and must be selectable",
124+
presented.getExtendedKeyUsage());
125+
}
126+
127+
128+
@Test
129+
public void testSelectsServerAuthCertificateWhenNoAliasConfigured() throws Exception {
130+
X509Certificate presented = present(null,
131+
key("first", CLIENT_AUTH),
132+
key("second", SERVER_AUTH));
133+
assertEku(presented, Constants.SERVER_AUTH_EXTENDED_KEY_USAGE_OID);
134+
}
135+
136+
137+
@Test
138+
public void testSelectsServerAuthCertificateWhenMultipleMatch() throws Exception {
139+
// Two server-auth certificates share the Subject. Which one wins depends on key-store enumeration order,
140+
// which JKS does not guarantee, so this only asserts that the ambiguity resolves to a server-auth
141+
// certificate rather than the client-auth one - not which of the two is chosen.
142+
X509Certificate presented = present(HOST,
143+
key(HOST, CLIENT_AUTH),
144+
key("localhost-s1", SERVER_AUTH),
145+
key("localhost-s2", SERVER_AUTH));
146+
assertEku(presented, Constants.SERVER_AUTH_EXTENDED_KEY_USAGE_OID);
147+
}
148+
149+
150+
@Test
151+
public void testFallsBackToConfiguredAliasWhenNoServerAuthCertificate() throws Exception {
152+
X509Certificate presented = present(HOST,
153+
key(HOST, CLIENT_AUTH),
154+
key("localhost-2", CLIENT_AUTH));
155+
assertEku(presented, Constants.CLIENT_AUTH_EXTENDED_KEY_USAGE_OID);
156+
}
157+
158+
159+
@Test
160+
public void testIgnoresServerAuthCertificateWithDifferentSubject() throws Exception {
161+
X509Certificate presented = present(HOST,
162+
key(HOST, CLIENT_AUTH),
163+
KeystoreEntry.key("other-server", "other.example", SERVER_AUTH));
164+
assertEku(presented, Constants.CLIENT_AUTH_EXTENDED_KEY_USAGE_OID);
165+
}
166+
167+
168+
@Test
169+
public void testIgnoresTrustedCertificateEntries() throws Exception {
170+
// The only server-auth-capable certificate is a trusted (keyless) entry, so it cannot be used as a server key.
171+
// Selection must skip it and fall back to the configured key entry. If trusted entries were NOT skipped, the
172+
// keyless "ca" would be chosen and the resulting key manager would have no chain for it.
173+
X509Certificate presented = present(HOST,
174+
KeystoreEntry.trusted("ca", HOST, SERVER_AUTH),
175+
key(HOST, CLIENT_AUTH));
176+
assertEku(presented, Constants.CLIENT_AUTH_EXTENDED_KEY_USAGE_OID);
177+
}
178+
}

0 commit comments

Comments
 (0)