This is an automated email from the ASF dual-hosted git repository. markt pushed a commit to branch main in repository https://gitbox.apache.org/repos/asf/tomcat.git
commit 0f72e51cadadd0c1f150e57870e27777b890f248 Author: Mark Thomas <ma...@apache.org> AuthorDate: Thu May 22 17:45:12 2025 +0100 Code clean-up - formatting. No functional change. --- .../tomcat/util/net/openssl/OpenSSLContext.java | 91 ++++------ .../tomcat/util/net/openssl/OpenSSLEngine.java | 188 ++++++++++----------- .../util/net/openssl/OpenSSLImplementation.java | 2 +- .../util/net/openssl/OpenSSLSessionContext.java | 14 +- .../util/net/openssl/OpenSSLSessionStats.java | 24 ++- .../tomcat/util/net/openssl/OpenSSLStatus.java | 6 +- .../tomcat/util/net/openssl/OpenSSLUtil.java | 4 +- .../util/net/openssl/OpenSSLX509Certificate.java | 14 +- 8 files changed, 156 insertions(+), 187 deletions(-) diff --git a/java/org/apache/tomcat/util/net/openssl/OpenSSLContext.java b/java/org/apache/tomcat/util/net/openssl/OpenSSLContext.java index 978d41bad7..2e4bb9a085 100644 --- a/java/org/apache/tomcat/util/net/openssl/OpenSSLContext.java +++ b/java/org/apache/tomcat/util/net/openssl/OpenSSLContext.java @@ -91,8 +91,7 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { private final OpenSSLState state; private final Cleanable cleanable; - public OpenSSLContext(SSLHostConfigCertificate certificate, List<String> negotiableProtocols) - throws SSLException { + public OpenSSLContext(SSLHostConfigCertificate certificate, List<String> negotiableProtocols) throws SSLException { this.sslHostConfig = certificate.getSSLHostConfig(); this.certificate = certificate; long aprPool = Pool.create(0); @@ -107,11 +106,8 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { if (log.isTraceEnabled()) { log.trace(sm.getString("openssl.makeConf")); } - cctx = SSLConf.make(aprPool, - SSL.SSL_CONF_FLAG_FILE | - SSL.SSL_CONF_FLAG_SERVER | - SSL.SSL_CONF_FLAG_CERTIFICATE | - SSL.SSL_CONF_FLAG_SHOW_ERRORS); + cctx = SSLConf.make(aprPool, SSL.SSL_CONF_FLAG_FILE | SSL.SSL_CONF_FLAG_SERVER | + SSL.SSL_CONF_FLAG_CERTIFICATE | SSL.SSL_CONF_FLAG_SHOW_ERRORS); } catch (Exception e) { throw new SSLException(sm.getString("openssl.errMakeConf"), e); } @@ -157,20 +153,17 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { this.negotiableProtocols = negotiableProtocols; success = true; - } catch(Exception e) { + } catch (Exception e) { throw new SSLException(sm.getString("openssl.errorSSLCtxInit"), e); } finally { state = new OpenSSLState(aprPool, cctx, ctx); /* - * When an SSLHostConfig is replaced at runtime, it is not possible to - * call destroy() on the associated OpenSSLContext since it is likely - * that there will be in-progress connections using the OpenSSLContext. - * A reference chain has been deliberately established (see - * OpenSSLSessionContext) to ensure that the OpenSSLContext remains - * ineligible for GC while those connections are alive. Once those - * connections complete, the OpenSSLContext will become eligible for GC - * and this method will ensure that the associated native resources are - * cleaned up. + * When an SSLHostConfig is replaced at runtime, it is not possible to call destroy() on the associated + * OpenSSLContext since it is likely that there will be in-progress connections using the OpenSSLContext. A + * reference chain has been deliberately established (see OpenSSLSessionContext) to ensure that the + * OpenSSLContext remains ineligible for GC while those connections are alive. Once those connections + * complete, the OpenSSLContext will become eligible for GC and this method will ensure that the associated + * native resources are cleaned up. */ cleanable = cleaner.register(this, state); @@ -222,12 +215,10 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { return false; } if (rc <= 0) { - log.error(sm.getString("opensslconf.failedCommand", name, value, - Integer.toString(rc))); + log.error(sm.getString("opensslconf.failedCommand", name, value, Integer.toString(rc))); result = false; } else if (log.isTraceEnabled()) { - log.trace(sm.getString("opensslconf.resultCommand", name, value, - Integer.toString(rc))); + log.trace(sm.getString("opensslconf.resultCommand", name, value, Integer.toString(rc))); } } if (!result) { @@ -262,12 +253,10 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { return false; } if (rc <= 0) { - log.error(sm.getString("opensslconf.failedCommand", name, value, - Integer.toString(rc))); + log.error(sm.getString("opensslconf.failedCommand", name, value, Integer.toString(rc))); result = false; } else if (log.isTraceEnabled()) { - log.trace(sm.getString("opensslconf.resultCommand", name, value, - Integer.toString(rc))); + log.trace(sm.getString("opensslconf.resultCommand", name, value, Integer.toString(rc))); } } rc = SSLConf.finish(cctx); @@ -284,16 +273,14 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { /** * Setup the SSL_CTX. * - * @param kms Must contain a KeyManager of the type - * {@code OpenSSLKeyManager} - * @param tms Must contain a TrustManager of the type - * {@code X509TrustManager} - * @param sr Is not used for this implementation. + * @param kms Must contain a KeyManager of the type {@code OpenSSLKeyManager} + * @param tms Must contain a TrustManager of the type {@code X509TrustManager} + * @param sr Is not used for this implementation. + * * @throws KeyManagementException if an error occurs */ @Override - public void init(KeyManager[] kms, TrustManager[] tms, SecureRandom sr) - throws KeyManagementException { + public void init(KeyManager[] kms, TrustManager[] tms, SecureRandom sr) throws KeyManagementException { if (initialized) { log.warn(sm.getString("openssl.doubleInit")); return; @@ -430,8 +417,7 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { if ((opts & SSL.SSL_OP_NO_SSLv3) == 0) { enabled.add(Constants.SSL_PROTO_SSLv3); } - sslHostConfig.setEnabledProtocols( - enabled.toArray(new String[0])); + sslHostConfig.setEnabledProtocols(enabled.toArray(new String[0])); // Reconfigure the enabled ciphers sslHostConfig.setEnabledCiphers(SSLContext.getCiphers(state.ctx)); } @@ -456,29 +442,25 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { // Set certificate String passwordToUse; if (certificate.getCertificateKeyPasswordFile() != null) { - try (BufferedReader reader = - new BufferedReader(new InputStreamReader( - new FileInputStream( + try (BufferedReader reader = new BufferedReader(new InputStreamReader( + new FileInputStream( SSLHostConfig.adjustRelativePath(certificate.getCertificateKeyPasswordFile())), - StandardCharsets.UTF_8))) { + StandardCharsets.UTF_8))) { passwordToUse = reader.readLine(); } } else { passwordToUse = certificate.getCertificateKeyPassword(); } - SSLContext.setCertificate(state.ctx, - SSLHostConfig.adjustRelativePath(certificate.getCertificateFile()), - SSLHostConfig.adjustRelativePath(certificate.getCertificateKeyFile()), - passwordToUse, getCertificateIndex(certificate)); + SSLContext.setCertificate(state.ctx, SSLHostConfig.adjustRelativePath(certificate.getCertificateFile()), + SSLHostConfig.adjustRelativePath(certificate.getCertificateKeyFile()), passwordToUse, + getCertificateIndex(certificate)); // Set certificate chain file SSLContext.setCertificateChainFile(state.ctx, SSLHostConfig.adjustRelativePath(certificate.getCertificateChainFile()), false); // Set revocation SSLContext.setCARevocation(state.ctx, - SSLHostConfig.adjustRelativePath( - sslHostConfig.getCertificateRevocationListFile()), - SSLHostConfig.adjustRelativePath( - sslHostConfig.getCertificateRevocationListPath())); + SSLHostConfig.adjustRelativePath(sslHostConfig.getCertificateRevocationListFile()), + SSLHostConfig.adjustRelativePath(sslHostConfig.getCertificateRevocationListPath())); } else { String alias = certificate.getCertificateKeyAlias(); X509KeyManager x509KeyManager = certificate.getCertificateKeyManager(); @@ -491,12 +473,10 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { chain = x509KeyManager.getCertificateChain(alias); } PrivateKey key = x509KeyManager.getPrivateKey(alias); - String encodedKey = - BEGIN_KEY + - Base64.getMimeEncoder(64, new byte[]{'\n'}).encodeToString(key.getEncoded()) + - END_KEY; + String encodedKey = BEGIN_KEY + + Base64.getMimeEncoder(64, new byte[] { '\n' }).encodeToString(key.getEncoded()) + END_KEY; SSLContext.setCertificateRaw(state.ctx, chain[0].getEncoded(), - encodedKey.getBytes(StandardCharsets.US_ASCII), getCertificateIndex(certificate)); + encodedKey.getBytes(StandardCharsets.US_ASCII), getCertificateIndex(certificate)); for (int i = 1; i < chain.length; i++) { SSLContext.addChainCertificateRaw(state.ctx, chain[i].getEncoded()); } @@ -524,8 +504,7 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { /* * Find a valid alias when none was specified in the config. */ - private static String findAlias(X509KeyManager keyManager, - SSLHostConfigCertificate certificate) { + private static String findAlias(X509KeyManager keyManager, SSLHostConfigCertificate certificate) { Type type = certificate.getType(); String result = null; @@ -542,7 +521,7 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { Iterator<Type> iter = candidateTypes.iterator(); while (result == null && iter.hasNext()) { - result = keyManager.chooseServerAlias(iter.next().toString(), null, null); + result = keyManager.chooseServerAlias(iter.next().toString(), null, null); } return result; @@ -624,8 +603,8 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { /** * @param aprPool the APR pool - * @param cctx OpenSSLConfCmd context - * @param ctx SSL context + * @param cctx OpenSSLConfCmd context + * @param ctx SSL context */ private record OpenSSLState(long aprPool, long cctx, long ctx) implements Runnable { @Override diff --git a/java/org/apache/tomcat/util/net/openssl/OpenSSLEngine.java b/java/org/apache/tomcat/util/net/openssl/OpenSSLEngine.java index d751b616cf..dc5b0f4b6c 100644 --- a/java/org/apache/tomcat/util/net/openssl/OpenSSLEngine.java +++ b/java/org/apache/tomcat/util/net/openssl/OpenSSLEngine.java @@ -53,9 +53,8 @@ import org.apache.tomcat.util.net.openssl.ciphers.OpenSSLCipherConfigurationPars import org.apache.tomcat.util.res.StringManager; /** - * Implements a {@link SSLEngine} using - * <a href="https://www.openssl.org/docs/crypto/BIO_s_bio.html#EXAMPLE">OpenSSL - * BIO abstractions</a>. + * Implements a {@link SSLEngine} using <a href="https://www.openssl.org/docs/crypto/BIO_s_bio.html#EXAMPLE">OpenSSL BIO + * abstractions</a>. */ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolInfo { @@ -78,7 +77,7 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn SSLContext.setCipherSuite(sslCtx, "ALL"); final long ssl = SSL.newSSL(sslCtx, true); try { - for (String c: SSL.getCiphers(ssl)) { + for (String c : SSL.getCiphers(ssl)) { // Filter out bad input. if (c == null || c.isEmpty() || availableCipherSuites.contains(c)) { continue; @@ -138,7 +137,12 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn private final Cleanable cleanable; private final ByteBuffer buf = ByteBuffer.allocateDirect(MAX_ENCRYPTED_PACKET_LENGTH); - private enum Accepted { NOT, IMPLICIT, EXPLICIT } + private enum Accepted { + NOT, + IMPLICIT, + EXPLICIT + } + private Accepted accepted = Accepted.NOT; private boolean handshakeFinished; private int currentHandshake; @@ -175,25 +179,20 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn /** * Creates a new instance * - * @param cleaner Used to clean up references to instances before they are - * garbage collected - * @param sslCtx an OpenSSL {@code SSL_CTX} object - * @param fallbackApplicationProtocol the fallback application protocol - * @param clientMode {@code true} if this is used for clients, {@code false} - * otherwise - * @param sessionContext the {@link OpenSSLSessionContext} this - * {@link SSLEngine} belongs to. - * @param alpn {@code true} if alpn should be used, {@code false} - * otherwise - * @param initialized {@code true} if this instance gets its protocol, - * cipher and client verification from the {@code SSL_CTX} {@code sslCtx} - * @param certificateVerificationDepth Certificate verification depth - * @param certificateVerificationOptionalNoCA Skip CA verification in - * optional mode + * @param cleaner Used to clean up references to instances before they are garbage + * collected + * @param sslCtx an OpenSSL {@code SSL_CTX} object + * @param fallbackApplicationProtocol the fallback application protocol + * @param clientMode {@code true} if this is used for clients, {@code false} otherwise + * @param sessionContext the {@link OpenSSLSessionContext} this {@link SSLEngine} belongs to. + * @param alpn {@code true} if alpn should be used, {@code false} otherwise + * @param initialized {@code true} if this instance gets its protocol, cipher and client + * verification from the {@code SSL_CTX} {@code sslCtx} + * @param certificateVerificationDepth Certificate verification depth + * @param certificateVerificationOptionalNoCA Skip CA verification in optional mode */ - OpenSSLEngine(Cleaner cleaner, long sslCtx, String fallbackApplicationProtocol, - boolean clientMode, OpenSSLSessionContext sessionContext, boolean alpn, - boolean initialized, int certificateVerificationDepth, + OpenSSLEngine(Cleaner cleaner, long sslCtx, String fallbackApplicationProtocol, boolean clientMode, + OpenSSLSessionContext sessionContext, boolean alpn, boolean initialized, int certificateVerificationDepth, boolean certificateVerificationOptionalNoCA) { if (sslCtx == 0) { throw new IllegalArgumentException(sm.getString("engine.noSSLContext")); @@ -231,8 +230,8 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn } /** - * Write plain text data to the OpenSSL internal BIO - * Calling this function with src.remaining == 0 is undefined. + * Write plain text data to the OpenSSL internal BIO Calling this function with src.remaining == 0 is undefined. + * * @throws SSLException if the OpenSSL error check fails */ private int writePlaintextData(final long ssl, final ByteBuffer src) throws SSLException { @@ -276,12 +275,12 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn } } - throw new IllegalStateException( - sm.getString("engine.writeToSSLFailed", Integer.toString(sslWrote))); + throw new IllegalStateException(sm.getString("engine.writeToSSLFailed", Integer.toString(sslWrote))); } /** * Write encrypted data to the OpenSSL network BIO. + * * @throws SSLException if the OpenSSL error check fails */ private int writeEncryptedData(final long networkBIO, final ByteBuffer src) throws SSLException { @@ -324,6 +323,7 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn /** * Read plain text data from the OpenSSL internal BIO + * * @throws SSLException if the OpenSSL error check fails */ private int readPlaintextData(final long ssl, final ByteBuffer dst) throws SSLException { @@ -366,6 +366,7 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn /** * Read encrypted data from the OpenSSL network BIO + * * @throws SSLException if the OpenSSL error check fails */ private int readEncryptedData(final long networkBIO, final ByteBuffer dst, final int pending) throws SSLException { @@ -404,11 +405,13 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn } @Override - public synchronized SSLEngineResult wrap(final ByteBuffer[] srcs, final int offset, final int length, final ByteBuffer dst) throws SSLException { + public synchronized SSLEngineResult wrap(final ByteBuffer[] srcs, final int offset, final int length, + final ByteBuffer dst) throws SSLException { // Check to make sure the engine has not been closed if (destroyed) { - return new SSLEngineResult(SSLEngineResult.Status.CLOSED, SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING, 0, 0); + return new SSLEngineResult(SSLEngineResult.Status.CLOSED, SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING, + 0, 0); } // Throw required runtime exceptions @@ -416,9 +419,8 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn throw new IllegalArgumentException(sm.getString("engine.nullBuffer")); } if (offset >= srcs.length || offset + length > srcs.length) { - throw new IndexOutOfBoundsException(sm.getString("engine.invalidBufferArray", - Integer.toString(offset), Integer.toString(length), - Integer.toString(srcs.length))); + throw new IndexOutOfBoundsException(sm.getString("engine.invalidBufferArray", Integer.toString(offset), + Integer.toString(length), Integer.toString(srcs.length))); } if (dst.isReadOnly()) { throw new ReadOnlyBufferException(); @@ -489,8 +491,8 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn // Do we have enough room in dst to write encrypted data? int capacity = dst.remaining(); if (capacity < pendingNet) { - return new SSLEngineResult( - SSLEngineResult.Status.BUFFER_OVERFLOW, getHandshakeStatus(), bytesConsumed, bytesProduced); + return new SSLEngineResult(SSLEngineResult.Status.BUFFER_OVERFLOW, getHandshakeStatus(), + bytesConsumed, bytesProduced); } // Write the pending data from the network BIO into the dst buffer @@ -508,10 +510,12 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn } @Override - public synchronized SSLEngineResult unwrap(final ByteBuffer src, final ByteBuffer[] dsts, final int offset, final int length) throws SSLException { + public synchronized SSLEngineResult unwrap(final ByteBuffer src, final ByteBuffer[] dsts, final int offset, + final int length) throws SSLException { // Check to make sure the engine has not been closed if (destroyed) { - return new SSLEngineResult(SSLEngineResult.Status.CLOSED, SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING, 0, 0); + return new SSLEngineResult(SSLEngineResult.Status.CLOSED, SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING, + 0, 0); } // Throw required runtime exceptions @@ -519,9 +523,8 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn throw new IllegalArgumentException(sm.getString("engine.nullBuffer")); } if (offset >= dsts.length || offset + length > dsts.length) { - throw new IndexOutOfBoundsException(sm.getString("engine.invalidBufferArray", - Integer.toString(offset), Integer.toString(length), - Integer.toString(dsts.length))); + throw new IndexOutOfBoundsException(sm.getString("engine.invalidBufferArray", Integer.toString(offset), + Integer.toString(length), Integer.toString(dsts.length))); } int capacity = 0; final int endOffset = offset + length; @@ -625,7 +628,8 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn } // Check to see if we received a close_notify message from the peer - if (!receivedShutdown && (SSL.getShutdown(state.ssl) & SSL.SSL_RECEIVED_SHUTDOWN) == SSL.SSL_RECEIVED_SHUTDOWN) { + if (!receivedShutdown && + (SSL.getShutdown(state.ssl) & SSL.SSL_RECEIVED_SHUTDOWN) == SSL.SSL_RECEIVED_SHUTDOWN) { receivedShutdown = true; closeInbound(); } @@ -636,8 +640,7 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn } } - private int pendingReadableBytesInSSL() - throws SSLException { + private int pendingReadableBytesInSSL() throws SSLException { // NOTE: Calling a fake read is necessary before calling pendingReadableBytesInSSL because // SSL_pending will return 0 if OpenSSL has not started the current TLS record // See https://www.openssl.org/docs/manmaster/man3/SSL_pending.html @@ -653,8 +656,7 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn // TLS 1.0 needs additional handling // TODO Figure out why this is necessary and if a simpler / better // solution is available - if (Constants.SSL_PROTO_TLSv1.equals(version) && lastPrimingReadResult == 0 && - pendingReadableBytesInSSL == 0) { + if (Constants.SSL_PROTO_TLSv1.equals(version) && lastPrimingReadResult == 0 && pendingReadableBytesInSSL == 0) { // Perform another priming read lastPrimingReadResult = SSL.readFromSSL(state.ssl, EMPTY_ADDR, 0); if (lastPrimingReadResult <= 0) { @@ -878,22 +880,23 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn throw new SSLException(sm.getString("engine.engineClosed")); } switch (accepted) { - case NOT: - handshake(); - accepted = Accepted.EXPLICIT; - break; - case IMPLICIT: - // A user did not start handshake by calling this method by themselves, - // but handshake has been started already by wrap() or unwrap() implicitly. - // Because it's the user's first time to call this method, it is unfair to - // raise an exception. From the user's standpoint, they never asked for - // renegotiation. - - accepted = Accepted.EXPLICIT; // Next time this method is invoked by the user, we should raise an exception. - break; - case EXPLICIT: - renegotiate(); - break; + case NOT: + handshake(); + accepted = Accepted.EXPLICIT; + break; + case IMPLICIT: + // A user did not start handshake by calling this method by themselves, + // but handshake has been started already by wrap() or unwrap() implicitly. + // Because it's the user's first time to call this method, it is unfair to + // raise an exception. From the user's standpoint, they never asked for + // renegotiation. + + accepted = Accepted.EXPLICIT; // Next time this method is invoked by the user, we should raise an + // exception. + break; + case EXPLICIT: + renegotiate(); + break; } } @@ -960,12 +963,11 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn } /** - * Many calls to SSL methods do not check the last error. Those that do - * check the last error need to ensure that any previously ignored error is - * cleared prior to the method call else errors may be falsely reported. - * Ideally, before any SSL_read, SSL_write, clearLastError should always - * be called, and getLastError should be called after on any negative or - * zero result. + * Many calls to SSL methods do not check the last error. Those that do check the last error need to ensure that any + * previously ignored error is cleared prior to the method call else errors may be falsely reported. Ideally, before + * any SSL_read, SSL_write, clearLastError should always be called, and getLastError should be called after on any + * negative or zero result. + * * @return the first error in the stack */ private static String getLastError() { @@ -1008,34 +1010,24 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn } /* - * Tomcat Native stores a count of the completed handshakes in the - * SSL instance and increments it every time a handshake is - * completed. Comparing the handshake count when the handshake - * started to the current handshake count enables this code to - * detect when the handshake has completed. + * Tomcat Native stores a count of the completed handshakes in the SSL instance and increments it every time + * a handshake is completed. Comparing the handshake count when the handshake started to the current + * handshake count enables this code to detect when the handshake has completed. * - * Obtaining client certificates after the connection has been - * established requires additional checks. We need to trigger - * additional reads until the certificates have been read, but we - * don't know how many reads we will need as it depends on both - * client and network behaviour. + * Obtaining client certificates after the connection has been established requires additional checks. We + * need to trigger additional reads until the certificates have been read, but we don't know how many reads + * we will need as it depends on both client and network behaviour. * - * The additional reads are triggered by returning NEED_UNWRAP - * rather than FINISHED. This allows the standard I/O code to be - * used. + * The additional reads are triggered by returning NEED_UNWRAP rather than FINISHED. This allows the + * standard I/O code to be used. * - * For TLSv1.2 and below, the handshake completes before the - * renegotiation. We therefore use SSL.renegotiatePending() to - * check on the current status of the renegotiation and return - * NEED_UNWRAP until it completes which means the client - * certificates will have been read from the client. + * For TLSv1.2 and below, the handshake completes before the renegotiation. We therefore use + * SSL.renegotiatePending() to check on the current status of the renegotiation and return NEED_UNWRAP until + * it completes which means the client certificates will have been read from the client. * - * For TLSv1.3, Tomcat Native sets a flag when post handshake - * authentication is started and updates it once the client - * certificate has been received. We therefore use - * SSL.getPostHandshakeAuthInProgress() to check the current status - * and return NEED_UNWRAP until that methods indicates that PHA is - * no longer in progress. + * For TLSv1.3, Tomcat Native sets a flag when post handshake authentication is started and updates it once + * the client certificate has been received. We therefore use SSL.getPostHandshakeAuthInProgress() to check + * the current status and return NEED_UNWRAP until that methods indicates that PHA is no longer in progress. */ // No pending data to be sent to the peer @@ -1123,9 +1115,8 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn SSL.setVerify(state.ssl, SSL.SSL_CVERIFY_REQUIRE, certificateVerificationDepth); break; case OPTIONAL: - SSL.setVerify(state.ssl, - certificateVerificationOptionalNoCA ? SSL.SSL_CVERIFY_OPTIONAL_NO_CA : SSL.SSL_CVERIFY_OPTIONAL, - certificateVerificationDepth); + SSL.setVerify(state.ssl, certificateVerificationOptionalNoCA ? SSL.SSL_CVERIFY_OPTIONAL_NO_CA : + SSL.SSL_CVERIFY_OPTIONAL, certificateVerificationDepth); break; } clientAuth = mode; @@ -1149,7 +1140,7 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn private class OpenSSLSession implements SSLSession { // lazy init for memory reasons - private Map<String, Object> values; + private Map<String,Object> values; // Last accessed time private long lastAccessedTime = -1; @@ -1206,7 +1197,7 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn if (value == null) { throw new IllegalArgumentException(sm.getString("engine.nullValue")); } - Map<String, Object> values = this.values; + Map<String,Object> values = this.values; if (values == null) { // Use size of 2 to keep the memory overhead small values = this.values = new HashMap<>(2); @@ -1234,7 +1225,7 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn if (name == null) { throw new IllegalArgumentException(sm.getString("engine.nullName")); } - Map<String, Object> values = this.values; + Map<String,Object> values = this.values; if (values == null) { return; } @@ -1244,7 +1235,7 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn @Override public String[] getValueNames() { - Map<String, Object> values = this.values; + Map<String,Object> values = this.values; if (values == null || values.isEmpty()) { return new String[0]; } @@ -1270,7 +1261,8 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn } chain = SSL.getPeerCertChain(state.ssl); if (!clientMode) { - // if used on the server side SSL_get_peer_cert_chain(...) will not include the remote peer certificate. + // if used on the server side SSL_get_peer_cert_chain(...) will not include the remote peer + // certificate. // We use SSL_get_peer_certificate to get it in this case and add it to our array later. // // See https://www.openssl.org/docs/ssl/SSL_get_peer_cert_chain.html diff --git a/java/org/apache/tomcat/util/net/openssl/OpenSSLImplementation.java b/java/org/apache/tomcat/util/net/openssl/OpenSSLImplementation.java index d496e7dab0..0067295edc 100644 --- a/java/org/apache/tomcat/util/net/openssl/OpenSSLImplementation.java +++ b/java/org/apache/tomcat/util/net/openssl/OpenSSLImplementation.java @@ -30,7 +30,7 @@ import org.apache.tomcat.util.net.jsse.JSSESupport; public class OpenSSLImplementation extends SSLImplementation { @Override - public SSLSupport getSSLSupport(SSLSession session, Map<String, List<String>> additionalAttributes) { + public SSLSupport getSSLSupport(SSLSession session, Map<String,List<String>> additionalAttributes) { return new JSSESupport(session, additionalAttributes); } diff --git a/java/org/apache/tomcat/util/net/openssl/OpenSSLSessionContext.java b/java/org/apache/tomcat/util/net/openssl/OpenSSLSessionContext.java index d28fafb956..492545befc 100644 --- a/java/org/apache/tomcat/util/net/openssl/OpenSSLSessionContext.java +++ b/java/org/apache/tomcat/util/net/openssl/OpenSSLSessionContext.java @@ -81,8 +81,7 @@ public class OpenSSLSessionContext implements SSLSessionContext { } /** - * @return {@code true} if caching of SSL sessions is enabled, {@code false} - * otherwise. + * @return {@code true} if caching of SSL sessions is enabled, {@code false} otherwise. */ public boolean isSessionCacheEnabled() { return SSLContext.getSessionCacheMode(contextID) == SSL.SSL_SESS_CACHE_SERVER; @@ -122,12 +121,13 @@ public class OpenSSLSessionContext implements SSLSessionContext { } /** - * Set the context within which session be reused (server side only) - * See <a href="http://www.openssl.org/docs/ssl/SSL_CTX_set_session_id_context.html"> - * man SSL_CTX_set_session_id_context</a> + * Set the context within which session be reused (server side only) See + * <a href="http://www.openssl.org/docs/ssl/SSL_CTX_set_session_id_context.html"> man + * SSL_CTX_set_session_id_context</a> + * + * @param sidCtx can be any kind of binary data, it is therefore possible to use e.g. the name of the application + * and/or the hostname and/or service name * - * @param sidCtx can be any kind of binary data, it is therefore possible to use e.g. the name - * of the application and/or the hostname and/or service name * @return {@code true} if success, {@code false} otherwise. */ public boolean setSessionIdContext(byte[] sidCtx) { diff --git a/java/org/apache/tomcat/util/net/openssl/OpenSSLSessionStats.java b/java/org/apache/tomcat/util/net/openssl/OpenSSLSessionStats.java index 12c44f76a5..6133fff11e 100644 --- a/java/org/apache/tomcat/util/net/openssl/OpenSSLSessionStats.java +++ b/java/org/apache/tomcat/util/net/openssl/OpenSSLSessionStats.java @@ -81,44 +81,40 @@ public final class OpenSSLSessionStats { } /** - * @return The number of successfully reused sessions. In client mode, a - * session set with {@code SSL_set_session} successfully reused is - * counted as a hit. In server mode, a session successfully - * retrieved from internal or external cache is counted as a hit. + * @return The number of successfully reused sessions. In client mode, a session set with {@code SSL_set_session} + * successfully reused is counted as a hit. In server mode, a session successfully retrieved from + * internal or external cache is counted as a hit. */ public long hits() { return SSLContext.sessionHits(context); } /** - * @return The number of successfully retrieved sessions from the external - * session cache in server mode. + * @return The number of successfully retrieved sessions from the external session cache in server mode. */ public long cbHits() { return SSLContext.sessionCbHits(context); } /** - * @return The number of sessions proposed by clients that were not found in - * the internal session cache in server mode. + * @return The number of sessions proposed by clients that were not found in the internal session cache in server + * mode. */ public long misses() { return SSLContext.sessionMisses(context); } /** - * @return The number of sessions proposed by clients and either found in - * the internal or external session cache in server mode, but that - * were invalid due to timeout. These sessions are not included in - * the {@link #hits()} count. + * @return The number of sessions proposed by clients and either found in the internal or external session cache in + * server mode, but that were invalid due to timeout. These sessions are not included in the + * {@link #hits()} count. */ public long timeouts() { return SSLContext.sessionTimeouts(context); } /** - * @return The number of sessions that were removed because the maximum - * session cache size was exceeded. + * @return The number of sessions that were removed because the maximum session cache size was exceeded. */ public long cacheFull() { return SSLContext.sessionCacheFull(context); diff --git a/java/org/apache/tomcat/util/net/openssl/OpenSSLStatus.java b/java/org/apache/tomcat/util/net/openssl/OpenSSLStatus.java index daf346d5b8..1ad7d3dc84 100644 --- a/java/org/apache/tomcat/util/net/openssl/OpenSSLStatus.java +++ b/java/org/apache/tomcat/util/net/openssl/OpenSSLStatus.java @@ -25,7 +25,11 @@ public class OpenSSLStatus { * OpenSSL library variant that has been identified */ public enum Name { - OPENSSL, OPENSSL3, LIBRESSL, BORINGSSL, UNKNOWN + OPENSSL, + OPENSSL3, + LIBRESSL, + BORINGSSL, + UNKNOWN } private static volatile boolean libraryInitialized = false; diff --git a/java/org/apache/tomcat/util/net/openssl/OpenSSLUtil.java b/java/org/apache/tomcat/util/net/openssl/OpenSSLUtil.java index 7a9ccf0feb..263442e3b0 100644 --- a/java/org/apache/tomcat/util/net/openssl/OpenSSLUtil.java +++ b/java/org/apache/tomcat/util/net/openssl/OpenSSLUtil.java @@ -115,8 +115,8 @@ public class OpenSSLUtil extends SSLUtilBase { // KeyStoreException or IOException if it doesn't understand the // provided file. if (certificate.getCertificateFile() != null) { - String msg = sm.getString("openssl.nonJsseCertificate", - certificate.getCertificateFile(), certificate.getCertificateKeyFile()); + String msg = sm.getString("openssl.nonJsseCertificate", certificate.getCertificateFile(), + certificate.getCertificateKeyFile()); if (log.isDebugEnabled()) { log.info(msg, e); } else { diff --git a/java/org/apache/tomcat/util/net/openssl/OpenSSLX509Certificate.java b/java/org/apache/tomcat/util/net/openssl/OpenSSLX509Certificate.java index fb15ab7346..81d1aa3f88 100644 --- a/java/org/apache/tomcat/util/net/openssl/OpenSSLX509Certificate.java +++ b/java/org/apache/tomcat/util/net/openssl/OpenSSLX509Certificate.java @@ -134,16 +134,14 @@ final class OpenSSLX509Certificate extends X509Certificate { } @Override - public void verify(PublicKey key) - throws CertificateException, NoSuchAlgorithmException, - InvalidKeyException, NoSuchProviderException, SignatureException { + public void verify(PublicKey key) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, + NoSuchProviderException, SignatureException { unwrap().verify(key); } @Override - public void verify(PublicKey key, String sigProvider) - throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, - NoSuchProviderException, SignatureException { + public void verify(PublicKey key, String sigProvider) throws CertificateException, NoSuchAlgorithmException, + InvalidKeyException, NoSuchProviderException, SignatureException { unwrap().verify(key, sigProvider); } @@ -181,8 +179,8 @@ final class OpenSSLX509Certificate extends X509Certificate { X509Certificate wrapped = this.wrapped; if (wrapped == null) { try { - wrapped = this.wrapped = (X509Certificate) OpenSSLContext.X509_CERT_FACTORY.generateCertificate( - new ByteArrayInputStream(bytes)); + wrapped = this.wrapped = (X509Certificate) OpenSSLContext.X509_CERT_FACTORY + .generateCertificate(new ByteArrayInputStream(bytes)); } catch (CertificateException e) { throw new IllegalStateException(e); } --------------------------------------------------------------------- To unsubscribe, e-mail: dev-unsubscr...@tomcat.apache.org For additional commands, e-mail: dev-h...@tomcat.apache.org