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 b6db952a85710a459b5edf0f3369efb54d74aa12 Author: Mark Thomas <ma...@apache.org> AuthorDate: Thu May 22 17:44:07 2025 +0100 Code clean-up - formatting. No functional change. --- .../util/net/openssl/panama/OpenSSLContext.java | 305 +++++++++++---------- .../util/net/openssl/panama/OpenSSLEngine.java | 268 +++++++++--------- .../net/openssl/panama/OpenSSLImplementation.java | 2 +- .../util/net/openssl/panama/OpenSSLLibrary.java | 81 +++--- .../net/openssl/panama/OpenSSLSessionContext.java | 18 +- .../net/openssl/panama/OpenSSLSessionStats.java | 30 +- .../util/net/openssl/panama/OpenSSLUtil.java | 4 +- .../net/openssl/panama/OpenSSLX509Certificate.java | 14 +- 8 files changed, 357 insertions(+), 365 deletions(-) diff --git a/java/org/apache/tomcat/util/net/openssl/panama/OpenSSLContext.java b/java/org/apache/tomcat/util/net/openssl/panama/OpenSSLContext.java index 6624b296e5..01e319a5c6 100644 --- a/java/org/apache/tomcat/util/net/openssl/panama/OpenSSLContext.java +++ b/java/org/apache/tomcat/util/net/openssl/panama/OpenSSLContext.java @@ -81,31 +81,29 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { private static final String defaultProtocol = "TLS"; - private static final int SSL_AIDX_RSA = 0; - private static final int SSL_AIDX_DSA = 1; - private static final int SSL_AIDX_ECC = 3; - private static final int SSL_AIDX_MAX = 4; + private static final int SSL_AIDX_RSA = 0; + private static final int SSL_AIDX_DSA = 1; + private static final int SSL_AIDX_ECC = 3; + private static final int SSL_AIDX_MAX = 4; - public static final int SSL_PROTOCOL_NONE = 0; + public static final int SSL_PROTOCOL_NONE = 0; public static final int SSL_PROTOCOL_SSLV2 = 1; - public static final int SSL_PROTOCOL_SSLV3 = (1<<1); - public static final int SSL_PROTOCOL_TLSV1 = (1<<2); - public static final int SSL_PROTOCOL_TLSV1_1 = (1<<3); - public static final int SSL_PROTOCOL_TLSV1_2 = (1<<4); - public static final int SSL_PROTOCOL_TLSV1_3 = (1<<5); - public static final int SSL_PROTOCOL_ALL = (SSL_PROTOCOL_TLSV1 | SSL_PROTOCOL_TLSV1_1 | SSL_PROTOCOL_TLSV1_2 | - SSL_PROTOCOL_TLSV1_3); + public static final int SSL_PROTOCOL_SSLV3 = (1 << 1); + public static final int SSL_PROTOCOL_TLSV1 = (1 << 2); + public static final int SSL_PROTOCOL_TLSV1_1 = (1 << 3); + public static final int SSL_PROTOCOL_TLSV1_2 = (1 << 4); + public static final int SSL_PROTOCOL_TLSV1_3 = (1 << 5); + public static final int SSL_PROTOCOL_ALL = + (SSL_PROTOCOL_TLSV1 | SSL_PROTOCOL_TLSV1_1 | SSL_PROTOCOL_TLSV1_2 | SSL_PROTOCOL_TLSV1_3); static final int OPTIONAL_NO_CA = 3; private static final String BEGIN_KEY = "-----BEGIN PRIVATE KEY-----\n"; private static final Object END_KEY = "\n-----END PRIVATE KEY-----"; - private static final byte[] HTTP_11_PROTOCOL = - new byte[] { 'h', 't', 't', 'p', '/', '1', '.', '1' }; + private static final byte[] HTTP_11_PROTOCOL = new byte[] { 'h', 't', 't', 'p', '/', '1', '.', '1' }; - private static final byte[] DEFAULT_SESSION_ID_CONTEXT = - new byte[] { 'd', 'e', 'f', 'a', 'u', 'l', 't' }; + private static final byte[] DEFAULT_SESSION_ID_CONTEXT = new byte[] { 'd', 'e', 'f', 'a', 'u', 'l', 't' }; static final CertificateFactory X509_CERT_FACTORY; static { @@ -149,8 +147,7 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { return ciphers.toArray(new String[0]); } - public OpenSSLContext(SSLHostConfigCertificate certificate, List<String> negotiableProtocols) - throws SSLException { + public OpenSSLContext(SSLHostConfigCertificate certificate, List<String> negotiableProtocols) throws SSLException { // Check that OpenSSL was initialized if (!OpenSSLStatus.isInitialized()) { @@ -181,10 +178,8 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { if (MemorySegment.NULL.equals(confCtx)) { throw new SSLException(sm.getString("openssl.errMakeConf", OpenSSLLibrary.getLastError())); } - SSL_CONF_CTX_set_flags(confCtx, SSL_CONF_FLAG_FILE() | - SSL_CONF_FLAG_SERVER() | - SSL_CONF_FLAG_CERTIFICATE() | - SSL_CONF_FLAG_SHOW_ERRORS()); + SSL_CONF_CTX_set_flags(confCtx, SSL_CONF_FLAG_FILE() | SSL_CONF_FLAG_SERVER() | + SSL_CONF_FLAG_CERTIFICATE() | SSL_CONF_FLAG_SHOW_ERRORS()); } else { log.error(sm.getString("opensslconf.unsupported")); } @@ -267,8 +262,7 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { SSL_CTX_set_timeout(sslCtx, 14400); // Set int pem_password_cb(char *buf, int size, int rwflag, void *u) callback - SSL_CTX_set_default_passwd_cb(sslCtx, - pem_password_cb.allocate(new PasswordCallback(null), contextArena)); + SSL_CTX_set_default_passwd_cb(sslCtx, pem_password_cb.allocate(new PasswordCallback(null), contextArena)); if (negotiableProtocols != null && !negotiableProtocols.isEmpty()) { alpn = true; @@ -282,21 +276,18 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { } success = true; - } catch(Exception e) { + } catch (Exception e) { throw new SSLException(sm.getString("openssl.errorSSLCtxInit"), e); } finally { this.negotiableProtocols = negotiableProtocolsBytes; state = new ContextState(sslCtx, confCtx); /* - * 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 the memory session 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 the memory session will ensure that the + * associated native resources are cleaned up. */ cleanable = cleaner.register(this, state); @@ -415,8 +406,7 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { noOcspCheck = Boolean.parseBoolean(value); rc = 1; } else { - rc = SSL_CONF_cmd(state.confCtx, localArena.allocateFrom(name), - localArena.allocateFrom(value)); + rc = SSL_CONF_cmd(state.confCtx, localArena.allocateFrom(name), localArena.allocateFrom(value)); String errorMessage = OpenSSLLibrary.getLastError(); if (rc <= 0 || errorMessage != null) { log.error(sm.getString("opensslconf.commandError", name, value, errorMessage)); @@ -428,12 +418,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(confCtx); @@ -451,11 +439,10 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { /** * Set up 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 @@ -497,15 +484,14 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { // List the ciphers that the client is permitted to negotiate if (minTlsVersion <= TLS1_2_VERSION()) { - if (SSL_CTX_set_cipher_list(state.sslCtx, - localArena.allocateFrom(sslHostConfig.getCiphers())) <= 0) { + if (SSL_CTX_set_cipher_list(state.sslCtx, localArena.allocateFrom(sslHostConfig.getCiphers())) <= 0) { log.warn(sm.getString("engine.failedCipherList", sslHostConfig.getCiphers())); } } // Check if the ciphers have been changed from the defaults - if (maxTlsVersion >= TLS1_3_VERSION() && (sslHostConfig.getCiphers() != SSLHostConfig.DEFAULT_TLS_CIPHERS)) { - if (SSL_CTX_set_ciphersuites(state.sslCtx, - localArena.allocateFrom(sslHostConfig.getCiphers())) <= 0) { + if (maxTlsVersion >= TLS1_3_VERSION() && + (sslHostConfig.getCiphers() != SSLHostConfig.DEFAULT_TLS_CIPHERS)) { + if (SSL_CTX_set_ciphersuites(state.sslCtx, localArena.allocateFrom(sslHostConfig.getCiphers())) <= 0) { log.warn(sm.getString("engine.failedCipherSuite", sslHostConfig.getCiphers())); } } @@ -533,8 +519,8 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { if (tms != null) { // Client certificate verification based on custom trust managers x509TrustManager = chooseTrustManager(tms); - SSL_CTX_set_cert_verify_callback(state.sslCtx, - SSL_CTX_set_cert_verify_callback$cb.allocate(new CertVerifyCallback(x509TrustManager), contextArena), state.sslCtx); + SSL_CTX_set_cert_verify_callback(state.sslCtx, SSL_CTX_set_cert_verify_callback$cb + .allocate(new CertVerifyCallback(x509TrustManager), contextArena), state.sslCtx); // Pass along the DER encoded certificates of the accepted client // certificate issuers, so that their subjects can be presented @@ -554,13 +540,17 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { } } else { // Client certificate verification based on trusted CA files and dirs - MemorySegment caCertificateFileNative = sslHostConfig.getCaCertificateFile() != null - ? localArena.allocateFrom(SSLHostConfig.adjustRelativePath(sslHostConfig.getCaCertificateFile())) : MemorySegment.NULL; - MemorySegment caCertificatePathNative = sslHostConfig.getCaCertificatePath() != null - ? localArena.allocateFrom(SSLHostConfig.adjustRelativePath(sslHostConfig.getCaCertificatePath())) : MemorySegment.NULL; - if ((sslHostConfig.getCaCertificateFile() != null || sslHostConfig.getCaCertificatePath() != null) - && SSL_CTX_load_verify_locations(state.sslCtx, - caCertificateFileNative, caCertificatePathNative) <= 0) { + MemorySegment caCertificateFileNative = sslHostConfig.getCaCertificateFile() != null ? + localArena + .allocateFrom(SSLHostConfig.adjustRelativePath(sslHostConfig.getCaCertificateFile())) : + MemorySegment.NULL; + MemorySegment caCertificatePathNative = sslHostConfig.getCaCertificatePath() != null ? + localArena + .allocateFrom(SSLHostConfig.adjustRelativePath(sslHostConfig.getCaCertificatePath())) : + MemorySegment.NULL; + if ((sslHostConfig.getCaCertificateFile() != null || sslHostConfig.getCaCertificatePath() != null) && + SSL_CTX_load_verify_locations(state.sslCtx, caCertificateFileNative, + caCertificatePathNative) <= 0) { logLastError("openssl.errorConfiguringLocations"); } else { var caCerts = SSL_CTX_get_client_CA_list(state.sslCtx); @@ -571,8 +561,8 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { } } else { // OpenSSL might crash here when passing null on some platforms - if (MemorySegment.NULL.equals(caCertificateFileNative) - || (SSL_add_file_cert_subjects_to_stack(caCerts, caCertificateFileNative) <= 0)) { + if (MemorySegment.NULL.equals(caCertificateFileNative) || + (SSL_add_file_cert_subjects_to_stack(caCerts, caCertificateFileNative) <= 0)) { caCerts = MemorySegment.NULL; } } @@ -583,8 +573,8 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { } if (negotiableProtocols != null && !negotiableProtocols.isEmpty()) { - SSL_CTX_set_alpn_select_cb(state.sslCtx, - SSL_CTX_set_alpn_select_cb$cb.allocate(new ALPNSelectCallback(negotiableProtocols), contextArena), state.sslCtx); + SSL_CTX_set_alpn_select_cb(state.sslCtx, SSL_CTX_set_alpn_select_cb$cb + .allocate(new ALPNSelectCallback(negotiableProtocols), contextArena), state.sslCtx); } // Log any non fatal init errors @@ -642,8 +632,7 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { if ((opts & 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(getCiphers(state.sslCtx)); } @@ -677,16 +666,12 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { var pkey = SSL_get_privatekey(ssl); int type = (MemorySegment.NULL.equals(pkey)) ? EVP_PKEY_NONE() : EVP_PKEY_base_id(pkey); /* - * OpenSSL will call us with either keylen == 512 or keylen == 1024 - * (see the definition of SSL_EXPORT_PKEYLENGTH in ssl_locl.h). - * Adjust the DH parameter length according to the size of the - * RSA/DSA private key used for the current connection, and always - * use at least 1024-bit parameters. - * Note: This may cause interoperability issues with implementations - * which limit their DH support to 1024 bit - e.g. Java 7 and earlier. - * In this case, SSLCertificateFile can be used to specify fixed - * 1024-bit DH parameters (with the effect that OpenSSL skips this - * callback). + * OpenSSL will call us with either keylen == 512 or keylen == 1024 (see the definition of + * SSL_EXPORT_PKEYLENGTH in ssl_locl.h). Adjust the DH parameter length according to the size of the RSA/DSA + * private key used for the current connection, and always use at least 1024-bit parameters. Note: This may + * cause interoperability issues with implementations which limit their DH support to 1024 bit - e.g. Java 7 + * and earlier. In this case, SSLCertificateFile can be used to specify fixed 1024-bit DH parameters (with + * the effect that OpenSSL skips this callback). */ int keylen = 0; if (type == EVP_PKEY_RSA() || type == EVP_PKEY_DSA()) { @@ -702,15 +687,17 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { } // int SSL_callback_alpn_select_proto(SSL* ssl, const unsigned char **out, unsigned char *outlen, - // const unsigned char *in, unsigned int inlen, void *arg) + // const unsigned char *in, unsigned int inlen, void *arg) private static class ALPNSelectCallback implements SSL_CTX_set_alpn_select_cb$cb.Function { private final List<byte[]> negotiableProtocols; + ALPNSelectCallback(List<byte[]> negotiableProtocols) { this.negotiableProtocols = negotiableProtocols; } + @Override - public int apply(MemorySegment ssl, MemorySegment out, - MemorySegment outlen, MemorySegment in, int inlen, MemorySegment arg) { + public int apply(MemorySegment ssl, MemorySegment out, MemorySegment outlen, MemorySegment in, int inlen, + MemorySegment arg) { try (var localArena = Arena.ofConfined()) { MemorySegment inSeg = in.reinterpret(inlen, localArena, null); byte[] advertisedBytes = inSeg.toArray(ValueLayout.JAVA_BYTE); @@ -721,9 +708,11 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { if (advertisedBytes[i + j] == negotiableProtocolBytes[j]) { if (j == negotiableProtocolBytes.length - 1) { // Match - MemorySegment outSeg = out.reinterpret(ValueLayout.ADDRESS.byteSize(), localArena, null); + MemorySegment outSeg = + out.reinterpret(ValueLayout.ADDRESS.byteSize(), localArena, null); outSeg.set(ValueLayout.ADDRESS, 0, inSeg.asSlice(i)); - MemorySegment outlenSeg = outlen.reinterpret(ValueLayout.JAVA_BYTE.byteSize(), localArena, null); + MemorySegment outlenSeg = + outlen.reinterpret(ValueLayout.JAVA_BYTE.byteSize(), localArena, null); outlenSeg.set(ValueLayout.JAVA_BYTE, 0, (byte) negotiableProtocolBytes.length); return SSL_TLSEXT_ERR_OK(); } @@ -742,11 +731,13 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { private static class CertVerifyCallback implements SSL_CTX_set_cert_verify_callback$cb.Function { private final X509TrustManager x509TrustManager; + CertVerifyCallback(X509TrustManager x509TrustManager) { this.x509TrustManager = x509TrustManager; } + @Override - public int apply(MemorySegment /*X509_STORE_CTX*/ x509_ctx, MemorySegment param) { + public int apply(MemorySegment /* X509_STORE_CTX */ x509_ctx, MemorySegment param) { if (log.isTraceEnabled()) { log.trace("Certificate verification"); } @@ -754,12 +745,12 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { return 0; } MemorySegment ssl = X509_STORE_CTX_get_ex_data(x509_ctx, SSL_get_ex_data_X509_STORE_CTX_idx()); - MemorySegment /*STACK_OF(X509)*/ sk = X509_STORE_CTX_get0_untrusted(x509_ctx); + MemorySegment /* STACK_OF(X509) */ sk = X509_STORE_CTX_get0_untrusted(x509_ctx); int len = openssl_h_Compatibility.OPENSSL_sk_num(sk); byte[][] certificateChain = new byte[len][]; try (var localArena = Arena.ofConfined()) { for (int i = 0; i < len; i++) { - MemorySegment/*(X509*)*/ x509 = openssl_h_Compatibility.OPENSSL_sk_value(sk, i); + MemorySegment/* (X509*) */ x509 = openssl_h_Compatibility.OPENSSL_sk_value(sk, i); MemorySegment bufPointer = localArena.allocateFrom(ValueLayout.ADDRESS, MemorySegment.NULL); int length = i2d_X509(x509, bufPointer); if (length < 0) { @@ -771,8 +762,8 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { OPENSSL_free(buf); } MemorySegment cipher = SSL_get_current_cipher(ssl); - String authMethod = (MemorySegment.NULL.equals(cipher)) ? "UNKNOWN" - : getCipherAuthenticationMethod(SSL_CIPHER_get_auth_nid(cipher), SSL_CIPHER_get_kx_nid(cipher)); + String authMethod = (MemorySegment.NULL.equals(cipher)) ? "UNKNOWN" : + getCipherAuthenticationMethod(SSL_CIPHER_get_auth_nid(cipher), SSL_CIPHER_get_kx_nid(cipher)); X509Certificate[] peerCerts = certificates(certificateChain); try { x509TrustManager.checkClientTrusted(peerCerts, authMethod); @@ -785,16 +776,16 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { } } - private static final int NID_kx_rsa = 1037/*NID_kx_rsa()*/; - //private static final int NID_kx_dhe = NID_kx_dhe(); - //private static final int NID_kx_ecdhe = NID_kx_ecdhe(); + private static final int NID_kx_rsa = 1037/* NID_kx_rsa() */; + // private static final int NID_kx_dhe = NID_kx_dhe(); + // private static final int NID_kx_ecdhe = NID_kx_ecdhe(); - //private static final int NID_auth_rsa = NID_auth_rsa(); - //private static final int NID_auth_dss = NID_auth_dss(); - //private static final int NID_auth_null = NID_auth_null(); - //private static final int NID_auth_ecdsa = NID_auth_ecdsa(); + // private static final int NID_auth_rsa = NID_auth_rsa(); + // private static final int NID_auth_dss = NID_auth_dss(); + // private static final int NID_auth_null = NID_auth_null(); + // private static final int NID_auth_ecdsa = NID_auth_ecdsa(); - //private static final int SSL_kRSA = 1; + // private static final int SSL_kRSA = 1; private static final int SSL_kDHr = 2; private static final int SSL_kDHd = 4; private static final int SSL_kEDH = 8; @@ -804,21 +795,21 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { private static final int SSL_kECDHe = 40; private static final int SSL_kEECDH = 80; private static final int SSL_kECDHE = SSL_kEECDH; - //private static final int SSL_kPSK = 100; - //private static final int SSL_kGOST = 200; - //private static final int SSL_kSRP = 400; + // private static final int SSL_kPSK = 100; + // private static final int SSL_kGOST = 200; + // private static final int SSL_kSRP = 400; private static final int SSL_aRSA = 1; private static final int SSL_aDSS = 2; private static final int SSL_aNULL = 4; - //private static final int SSL_aDH = 8; - //private static final int SSL_aECDH = 10; - //private static final int SSL_aKRB5 = 20; + // private static final int SSL_aDH = 8; + // private static final int SSL_aECDH = 10; + // private static final int SSL_aKRB5 = 20; private static final int SSL_aECDSA = 40; - //private static final int SSL_aPSK = 80; - //private static final int SSL_aGOST94 = 100; - //private static final int SSL_aGOST01 = 200; - //private static final int SSL_aSRP = 400; + // private static final int SSL_aPSK = 80; + // private static final int SSL_aGOST94 = 100; + // private static final int SSL_aGOST01 = 200; + // private static final int SSL_aSRP = 400; private static final String SSL_TXT_RSA = "RSA"; private static final String SSL_TXT_DH = "DH"; @@ -853,9 +844,11 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { private static class PasswordCallback implements pem_password_cb.Function { private final String callbackPassword; + PasswordCallback(String callbackPassword) { this.callbackPassword = callbackPassword; } + @Override public int apply(MemorySegment /* char **/ buf, int bufsiz, int verify, MemorySegment /* void **/ cb) { if (log.isTraceEnabled()) { @@ -894,9 +887,8 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { keyPassFile = certificate.getCertificateKeystorePasswordFile(); } if (keyPassFile != null) { - try (BufferedReader reader = - new BufferedReader(new InputStreamReader( - ConfigFileLoader.getSource().getResource(keyPassFile).getInputStream(), + try (BufferedReader reader = new BufferedReader( + new InputStreamReader(ConfigFileLoader.getSource().getResource(keyPassFile).getInputStream(), StandardCharsets.UTF_8))) { keyPassToUse = reader.readLine(); } catch (IOException e) { @@ -914,12 +906,13 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { log.error(sm.getString("openssl.errorLoadingCertificate", certificate.getCertificateFile()), e); return false; } - MemorySegment certificateFileBytesNative = localArena.allocateFrom(ValueLayout.JAVA_BYTE, certificateFileBytes); + MemorySegment certificateFileBytesNative = + localArena.allocateFrom(ValueLayout.JAVA_BYTE, certificateFileBytes); MemorySegment certificateBIO = BIO_new(BIO_s_mem()); try { if (BIO_write(certificateBIO, certificateFileBytesNative, certificateFileBytes.length) <= 0) { - log.error(sm.getString("openssl.errorLoadingCertificateWithError", - certificate.getCertificateFile(), OpenSSLLibrary.getLastError())); + log.error(sm.getString("openssl.errorLoadingCertificateWithError", certificate.getCertificateFile(), + OpenSSLLibrary.getLastError())); return false; } MemorySegment cert; @@ -957,8 +950,9 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { cert = certPointer.get(ValueLayout.ADDRESS, 0); key = keyPointer.get(ValueLayout.ADDRESS, 0); } else { - String certificateKeyFileName = (certificate.getCertificateKeyFile() == null) - ? certificate.getCertificateFile() : certificate.getCertificateKeyFile(); + String certificateKeyFileName = + (certificate.getCertificateKeyFile() == null) ? certificate.getCertificateFile() : + certificate.getCertificateKeyFile(); // Load key byte[] certificateKeyFileBytes; try (Resource resource = ConfigFileLoader.getSource().getResource(certificateKeyFileName)) { @@ -967,12 +961,13 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { log.error(sm.getString("openssl.errorLoadingCertificate", certificateKeyFileName), e); return false; } - MemorySegment certificateKeyFileBytesNative = localArena.allocateFrom(ValueLayout.JAVA_BYTE, certificateKeyFileBytes); + MemorySegment certificateKeyFileBytesNative = + localArena.allocateFrom(ValueLayout.JAVA_BYTE, certificateKeyFileBytes); MemorySegment keyBIO = BIO_new(BIO_s_mem()); try { if (BIO_write(keyBIO, certificateKeyFileBytesNative, certificateKeyFileBytes.length) <= 0) { - log.error(sm.getString("openssl.errorLoadingCertificateWithError", - certificateKeyFileName, OpenSSLLibrary.getLastError())); + log.error(sm.getString("openssl.errorLoadingCertificateWithError", certificateKeyFileName, + OpenSSLLibrary.getLastError())); return false; } key = MemorySegment.NULL; @@ -997,8 +992,8 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { } } if (MemorySegment.NULL.equals(key)) { - log.error(sm.getString("openssl.errorLoadingCertificateWithError", - certificateKeyFileName, OpenSSLLibrary.getLastError())); + log.error(sm.getString("openssl.errorLoadingCertificateWithError", certificateKeyFileName, + OpenSSLLibrary.getLastError())); return false; } // Load certificate @@ -1035,7 +1030,8 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { BIO_reset(certificateBIO); if (!openssl_h_Compatibility.BORINGSSL) { if (!openssl_h_Compatibility.OPENSSL3) { - var dh = PEM_read_bio_DHparams(certificateBIO, MemorySegment.NULL, MemorySegment.NULL, MemorySegment.NULL); + var dh = PEM_read_bio_DHparams(certificateBIO, MemorySegment.NULL, MemorySegment.NULL, + MemorySegment.NULL); if (!MemorySegment.NULL.equals(dh)) { SSL_CTX_set_tmp_dh(state.sslCtx, dh); DH_free(dh); @@ -1047,12 +1043,14 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { if (SSL_CTX_set0_tmp_dh_pkey(state.sslCtx, pkey) <= 0) { EVP_PKEY_free(pkey); } else { - log.debug(sm.getString("openssl.setCustomDHParameters", Integer.valueOf(numBits), certificate.getCertificateFile())); + log.debug(sm.getString("openssl.setCustomDHParameters", Integer.valueOf(numBits), + certificate.getCertificateFile())); } } else { String errMessage = OpenSSLLibrary.getLastError(); if (errMessage != null) { - log.debug(sm.getString("openssl.errorReadingPEMParameters", errMessage, certificate.getCertificateFile())); + log.debug(sm.getString("openssl.errorReadingPEMParameters", errMessage, + certificate.getCertificateFile())); } SSL_CTX_ctrl(state.sslCtx, SSL_CTRL_SET_DH_AUTO(), 1, MemorySegment.NULL); } @@ -1063,7 +1061,8 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { BIO_reset(certificateBIO); if (!openssl_h_Compatibility.BORINGSSL) { if (!openssl_h_Compatibility.OPENSSL3) { - var ecparams = PEM_read_bio_ECPKParameters(certificateBIO, MemorySegment.NULL, MemorySegment.NULL, MemorySegment.NULL); + var ecparams = PEM_read_bio_ECPKParameters(certificateBIO, MemorySegment.NULL, + MemorySegment.NULL, MemorySegment.NULL); if (!MemorySegment.NULL.equals(ecparams)) { int nid = EC_GROUP_get_curve_name(ecparams); var eckey = EC_KEY_new_by_curve_name(nid); @@ -1072,10 +1071,11 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { EC_GROUP_free(ecparams); } // Set callback for DH parameters - SSL_CTX_set_tmp_dh_callback(state.sslCtx, SSL_CTX_set_tmp_dh_callback$dh.allocate(new TmpDHCallback(), contextArena)); + SSL_CTX_set_tmp_dh_callback(state.sslCtx, + SSL_CTX_set_tmp_dh_callback$dh.allocate(new TmpDHCallback(), contextArena)); } else { - var ecparams = PEM_ASN1_read_bio(d2i_ECPKParameters$SYMBOL(), - PEM_STRING_ECPARAMETERS(), certificateBIO, MemorySegment.NULL, MemorySegment.NULL, MemorySegment.NULL); + var ecparams = PEM_ASN1_read_bio(d2i_ECPKParameters$SYMBOL(), PEM_STRING_ECPARAMETERS(), + certificateBIO, MemorySegment.NULL, MemorySegment.NULL, MemorySegment.NULL); if (!MemorySegment.NULL.equals(ecparams)) { int curveNid = EC_GROUP_get_curve_name(ecparams); var curveNidAddress = localArena.allocateFrom(ValueLayout.JAVA_INT, curveNid); @@ -1093,29 +1093,34 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { // Set certificate chain file if (certificate.getCertificateChainFile() != null) { byte[] certificateChainBytes; - try (Resource resource = ConfigFileLoader.getSource().getResource(certificate.getCertificateChainFile())) { + try (Resource resource = + ConfigFileLoader.getSource().getResource(certificate.getCertificateChainFile())) { certificateChainBytes = resource.getInputStream().readAllBytes(); } catch (IOException e) { - log.error(sm.getString("openssl.errorLoadingCertificate", certificate.getCertificateChainFile()), e); + log.error( + sm.getString("openssl.errorLoadingCertificate", certificate.getCertificateChainFile()), + e); return false; } - MemorySegment certificateChainBytesNative = localArena.allocateFrom(ValueLayout.JAVA_BYTE, certificateChainBytes); + MemorySegment certificateChainBytesNative = + localArena.allocateFrom(ValueLayout.JAVA_BYTE, certificateChainBytes); MemorySegment certificateChainBIO = BIO_new(BIO_s_mem()); try { - if (BIO_write(certificateChainBIO, certificateChainBytesNative, certificateChainBytes.length) <= 0) { + if (BIO_write(certificateChainBIO, certificateChainBytesNative, + certificateChainBytes.length) <= 0) { log.error(sm.getString("openssl.errorLoadingCertificateWithError", certificate.getCertificateChainFile(), OpenSSLLibrary.getLastError())); return false; } - MemorySegment certChainEntry = - PEM_read_bio_X509_AUX(certificateChainBIO, MemorySegment.NULL, MemorySegment.NULL, MemorySegment.NULL); + MemorySegment certChainEntry = PEM_read_bio_X509_AUX(certificateChainBIO, MemorySegment.NULL, + MemorySegment.NULL, MemorySegment.NULL); while (!MemorySegment.NULL.equals(certChainEntry)) { if (SSL_CTX_add0_chain_cert(state.sslCtx, certChainEntry) <= 0) { log.error(sm.getString("openssl.errorLoadingCertificateWithError", certificate.getCertificateChainFile(), OpenSSLLibrary.getLastError())); } - certChainEntry = - PEM_read_bio_X509_AUX(certificateChainBIO, MemorySegment.NULL, MemorySegment.NULL, MemorySegment.NULL); + certChainEntry = PEM_read_bio_X509_AUX(certificateChainBIO, MemorySegment.NULL, + MemorySegment.NULL, MemorySegment.NULL); } // EOF is accepted, otherwise log an error if ((ERR_peek_last_error() & ERR_REASON_MASK()) == PEM_R_NO_START_LINE()) { @@ -1132,8 +1137,8 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { MemorySegment certificateStore = SSL_CTX_get_cert_store(state.sslCtx); if (sslHostConfig.getCertificateRevocationListFile() != null) { MemorySegment x509Lookup = X509_STORE_add_lookup(certificateStore, X509_LOOKUP_file()); - var certificateRevocationListFileNative = - localArena.allocateFrom(SSLHostConfig.adjustRelativePath(sslHostConfig.getCertificateRevocationListFile())); + var certificateRevocationListFileNative = localArena.allocateFrom( + SSLHostConfig.adjustRelativePath(sslHostConfig.getCertificateRevocationListFile())); if (X509_LOOKUP_load_file(x509Lookup, certificateRevocationListFileNative, X509_FILETYPE_PEM()) <= 0) { log.error(sm.getString("openssl.errorLoadingCertificateRevocationListWithError", @@ -1142,8 +1147,8 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { } if (sslHostConfig.getCertificateRevocationListPath() != null) { MemorySegment x509Lookup = X509_STORE_add_lookup(certificateStore, X509_LOOKUP_hash_dir()); - var certificateRevocationListPathNative = - localArena.allocateFrom(SSLHostConfig.adjustRelativePath(sslHostConfig.getCertificateRevocationListPath())); + var certificateRevocationListPathNative = localArena.allocateFrom( + SSLHostConfig.adjustRelativePath(sslHostConfig.getCertificateRevocationListPath())); if (X509_LOOKUP_add_dir(x509Lookup, certificateRevocationListPathNative, X509_FILETYPE_PEM()) <= 0) { log.error(sm.getString("openssl.errorLoadingCertificateRevocationListWithError", @@ -1165,10 +1170,8 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { alias = findAlias(x509KeyManager, certificate); chain = x509KeyManager.getCertificateChain(alias); } - String encodedKey = - BEGIN_KEY + - Base64.getMimeEncoder(64, new byte[]{'\n'}).encodeToString(x509KeyManager.getPrivateKey(alias).getEncoded()) + - END_KEY; + String encodedKey = BEGIN_KEY + Base64.getMimeEncoder(64, new byte[] { '\n' }) + .encodeToString(x509KeyManager.getPrivateKey(alias).getEncoded()) + END_KEY; var rawCertificate = localArena.allocateFrom(ValueLayout.JAVA_BYTE, chain[0].getEncoded()); var rawCertificatePointer = localArena.allocateFrom(ValueLayout.ADDRESS, rawCertificate); var rawKey = localArena.allocateFrom(ValueLayout.JAVA_BYTE, encodedKey.getBytes(StandardCharsets.US_ASCII)); @@ -1180,7 +1183,8 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { MemorySegment keyBIO = BIO_new(BIO_s_mem()); try { BIO_write(keyBIO, rawKey, (int) rawKey.byteSize()); - MemorySegment privateKeyAddress = PEM_read_bio_PrivateKey(keyBIO, MemorySegment.NULL, MemorySegment.NULL, MemorySegment.NULL); + MemorySegment privateKeyAddress = + PEM_read_bio_PrivateKey(keyBIO, MemorySegment.NULL, MemorySegment.NULL, MemorySegment.NULL); if (MemorySegment.NULL.equals(privateKeyAddress)) { logLastError("openssl.errorLoadingPrivateKey"); return false; @@ -1224,7 +1228,8 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { for (int i = 1; i < chain.length; i++) { var rawCertificateChain = localArena.allocateFrom(ValueLayout.JAVA_BYTE, chain[i].getEncoded()); var rawCertificateChainPointer = localArena.allocateFrom(ValueLayout.ADDRESS, rawCertificateChain); - var x509certChain = d2i_X509(MemorySegment.NULL, rawCertificateChainPointer, rawCertificateChain.byteSize()); + var x509certChain = + d2i_X509(MemorySegment.NULL, rawCertificateChainPointer, rawCertificateChain.byteSize()); if (MemorySegment.NULL.equals(x509certChain)) { logLastError("openssl.errorLoadingCertificate"); return false; @@ -1262,8 +1267,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; @@ -1280,7 +1284,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; @@ -1319,11 +1323,9 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { @Override public SSLEngine createSSLEngine() { - return new OpenSSLEngine(cleaner, state.sslCtx, defaultProtocol, false, sessionContext, - alpn, initialized, + return new OpenSSLEngine(cleaner, state.sslCtx, defaultProtocol, false, sessionContext, alpn, initialized, sslHostConfig.getCertificateVerificationDepth(), - sslHostConfig.getCertificateVerification() == CertificateVerification.OPTIONAL_NO_CA, - noOcspCheck); + sslHostConfig.getCertificateVerification() == CertificateVerification.OPTIONAL_NO_CA, noOcspCheck); } @Override @@ -1373,11 +1375,10 @@ public class OpenSSLContext implements org.apache.tomcat.util.net.SSLContext { private ContextState(MemorySegment sslCtx, MemorySegment confCtx) { // Use another arena to avoid keeping a reference through segments // This also allows making further accesses to the main pointers safer - this.sslCtx = sslCtx.reinterpret(ValueLayout.ADDRESS.byteSize(), stateArena, - openssl_h::SSL_CTX_free); + this.sslCtx = sslCtx.reinterpret(ValueLayout.ADDRESS.byteSize(), stateArena, openssl_h::SSL_CTX_free); if (!MemorySegment.NULL.equals(confCtx)) { - this.confCtx = confCtx.reinterpret(ValueLayout.ADDRESS.byteSize(), stateArena, - openssl_h::SSL_CONF_CTX_free); + this.confCtx = + confCtx.reinterpret(ValueLayout.ADDRESS.byteSize(), stateArena, openssl_h::SSL_CONF_CTX_free); } else { this.confCtx = MemorySegment.NULL; } diff --git a/java/org/apache/tomcat/util/net/openssl/panama/OpenSSLEngine.java b/java/org/apache/tomcat/util/net/openssl/panama/OpenSSLEngine.java index 41869f7d2a..dbcca78c34 100644 --- a/java/org/apache/tomcat/util/net/openssl/panama/OpenSSLEngine.java +++ b/java/org/apache/tomcat/util/net/openssl/panama/OpenSSLEngine.java @@ -67,9 +67,8 @@ import org.apache.tomcat.util.openssl.openssl_h_Compatibility; 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 { @@ -87,8 +86,8 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn availableCipherSuites.addAll(OpenSSLLibrary.findCiphers("ALL")); AVAILABLE_CIPHER_SUITES = Collections.unmodifiableSet(availableCipherSuites); IMPLEMENTED_PROTOCOLS_SET = Set.of(Constants.SSL_PROTO_SSLv2Hello, Constants.SSL_PROTO_SSLv2, - Constants.SSL_PROTO_SSLv3, Constants.SSL_PROTO_TLSv1, Constants.SSL_PROTO_TLSv1_1, - Constants.SSL_PROTO_TLSv1_2, Constants.SSL_PROTO_TLSv1_3); + Constants.SSL_PROTO_SSLv3, Constants.SSL_PROTO_TLSv1, Constants.SSL_PROTO_TLSv1_1, + Constants.SSL_PROTO_TLSv1_2, Constants.SSL_PROTO_TLSv1_3); } private static final int MAX_PLAINTEXT_LENGTH = 16 * 1024; // 2^14 @@ -106,7 +105,8 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn private static final String INVALID_CIPHER = "SSL_NULL_WITH_NULL_NULL"; - private static final ConcurrentHashMap<Long, EngineState> states = new ConcurrentHashMap<>(); + private static final ConcurrentHashMap<Long,EngineState> states = new ConcurrentHashMap<>(); + private static EngineState getState(MemorySegment ssl) { return states.get(Long.valueOf(ssl.address())); } @@ -116,9 +116,20 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn private final Cleanable cleanable; private MemorySegment bufSegment; - private enum Accepted { NOT, IMPLICIT, EXPLICIT } + private enum Accepted { + NOT, + IMPLICIT, + EXPLICIT + } + private Accepted accepted = Accepted.NOT; - private enum PHAState { NONE, START, COMPLETE } + + private enum PHAState { + NONE, + START, + COMPLETE + } + private boolean handshakeFinished; private int currentHandshake; private boolean receivedShutdown; @@ -153,23 +164,18 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn /** * Creates a new instance * - * @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 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, MemorySegment sslCtx, String fallbackApplicationProtocol, - boolean clientMode, OpenSSLSessionContext sessionContext, boolean alpn, - boolean initialized, int certificateVerificationDepth, + OpenSSLEngine(Cleaner cleaner, MemorySegment sslCtx, String fallbackApplicationProtocol, boolean clientMode, + OpenSSLSessionContext sessionContext, boolean alpn, boolean initialized, int certificateVerificationDepth, boolean certificateVerificationOptionalNoCA, boolean noOcspCheck) { if (sslCtx == null) { throw new IllegalArgumentException(sm.getString("engine.noSSLContext")); @@ -223,8 +229,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 MemorySegment ssl, final ByteBuffer src) throws SSLException { @@ -247,6 +253,7 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn /** * Write encrypted data to the OpenSSL network BIO. + * * @throws SSLException if the OpenSSL error check fails */ private int writeEncryptedData(final MemorySegment networkBIO, final ByteBuffer src) throws SSLException { @@ -269,6 +276,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 MemorySegment ssl, final ByteBuffer dst) throws SSLException { @@ -291,9 +299,11 @@ 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 MemorySegment networkBIO, final ByteBuffer dst, final int pending) throws SSLException { + private int readEncryptedData(final MemorySegment networkBIO, final ByteBuffer dst, final int pending) + throws SSLException { clearLastError(); final int pos = dst.position(); MemorySegment dstSegment = dst.isDirect() ? MemorySegment.ofBuffer(dst) : bufSegment; @@ -311,10 +321,12 @@ 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 @@ -322,9 +334,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(); @@ -400,8 +411,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 @@ -420,10 +431,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 @@ -431,9 +444,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; @@ -549,8 +561,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 @@ -564,8 +575,7 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn int pendingReadableBytesInSSL = SSL_pending(state.ssl); // TLS 1.0 needs additional handling - 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_read(state.ssl, MemorySegment.NULL, 0); if (lastPrimingReadResult <= 0) { @@ -794,28 +804,29 @@ 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; } } private byte[] getPeerCertificate() { try (var localArena = Arena.ofConfined()) { - MemorySegment/*(X509*)*/ x509 = openssl_h_Compatibility.SSL_get_peer_certificate(state.ssl); + MemorySegment/* (X509*) */ x509 = openssl_h_Compatibility.SSL_get_peer_certificate(state.ssl); MemorySegment bufPointer = localArena.allocateFrom(ValueLayout.ADDRESS, MemorySegment.NULL); int length = i2d_X509(x509, bufPointer); if (length <= 0) { @@ -830,7 +841,7 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn } private byte[][] getPeerCertChain() { - MemorySegment/*STACK_OF(X509)*/ sk = SSL_get_peer_cert_chain(state.ssl); + MemorySegment/* STACK_OF(X509) */ sk = SSL_get_peer_cert_chain(state.ssl); int len = openssl_h_Compatibility.OPENSSL_sk_num(sk); if (len <= 0) { return null; @@ -838,7 +849,7 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn byte[][] certificateChain = new byte[len][]; try (var localArena = Arena.ofConfined()) { for (int i = 0; i < len; i++) { - MemorySegment/*(X509*)*/ x509 = openssl_h_Compatibility.OPENSSL_sk_value(sk, i); + MemorySegment/* (X509*) */ x509 = openssl_h_Compatibility.OPENSSL_sk_value(sk, i); MemorySegment bufPointer = localArena.allocateFrom(ValueLayout.ADDRESS, MemorySegment.NULL); int length = i2d_X509(x509, bufPointer); if (length < 0) { @@ -965,34 +976,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 @@ -1073,7 +1074,8 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn state.certificateVerifyMode = switch (mode) { case NONE -> SSL_VERIFY_NONE(); case REQUIRE -> SSL_VERIFY_FAIL_IF_NO_PEER_CERT(); - case OPTIONAL -> certificateVerificationOptionalNoCA ? OpenSSLContext.OPTIONAL_NO_CA : SSL_VERIFY_PEER(); + case OPTIONAL -> + certificateVerificationOptionalNoCA ? OpenSSLContext.OPTIONAL_NO_CA : SSL_VERIFY_PEER(); }; // Set int verify_callback(int preverify_ok, X509_STORE_CTX *x509_ctx) callback int value = switch (mode) { @@ -1104,7 +1106,7 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn static class VerifyCallback implements SSL_set_verify$callback.Function, SSL_CTX_set_verify$callback.Function { @Override - public int apply(int preverify_ok, MemorySegment /*X509_STORE_CTX*/ x509ctx) { + public int apply(int preverify_ok, MemorySegment /* X509_STORE_CTX */ x509ctx) { MemorySegment ssl = X509_STORE_CTX_get_ex_data(x509ctx, SSL_get_ex_data_X509_STORE_CTX_idx()); EngineState state = getState(ssl); if (state == null) { @@ -1118,34 +1120,31 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn int errnum = X509_STORE_CTX_get_error(x509ctx); int errdepth = X509_STORE_CTX_get_error_depth(x509ctx); state.phaState = PHAState.COMPLETE; - if (state.certificateVerifyMode == -1 /*SSL_CVERIFY_UNSET*/ || state.certificateVerifyMode == SSL_VERIFY_NONE()) { + if (state.certificateVerifyMode == -1 /* SSL_CVERIFY_UNSET */ || + state.certificateVerifyMode == SSL_VERIFY_NONE()) { return 1; } - /*SSL_VERIFY_ERROR_IS_OPTIONAL(errnum) -> ((errnum == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT) - || (errnum == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN) - || (errnum == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY) - || (errnum == X509_V_ERR_CERT_UNTRUSTED) - || (errnum == X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE))*/ - boolean verifyErrorIsOptional = (errnum == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT()) - || (errnum == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN()) - || (errnum == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY()) - || (errnum == X509_V_ERR_CERT_UNTRUSTED()) - || (errnum == X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE()); + /* + * SSL_VERIFY_ERROR_IS_OPTIONAL(errnum) -> ((errnum == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT) || (errnum == + * X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN) || (errnum == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY) || + * (errnum == X509_V_ERR_CERT_UNTRUSTED) || (errnum == X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE)) + */ + boolean verifyErrorIsOptional = (errnum == X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT()) || + (errnum == X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN()) || + (errnum == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY()) || + (errnum == X509_V_ERR_CERT_UNTRUSTED()) || (errnum == X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE()); if (verifyErrorIsOptional && (state.certificateVerifyMode == OpenSSLContext.OPTIONAL_NO_CA)) { ok = 1; openssl_h_Compatibility.SSL_set_verify_result(state.ssl, X509_V_OK()); } /* - * Expired certificates vs. "expired" CRLs: by default, OpenSSL - * turns X509_V_ERR_CRL_HAS_EXPIRED into a "certificate_expired(45)" - * SSL alert, but that's not really the message we should convey to the - * peer (at the very least, it's confusing, and in many cases, it's also - * inaccurate, as the certificate itself may very well not have expired - * yet). We set the X509_STORE_CTX error to something which OpenSSL's - * s3_both.c:ssl_verify_alarm_type() maps to SSL_AD_CERTIFICATE_UNKNOWN, - * i.e. the peer will receive a "certificate_unknown(46)" alert. - * We do not touch errnum, though, so that later on we will still log - * the "real" error, as returned by OpenSSL. + * Expired certificates vs. "expired" CRLs: by default, OpenSSL turns X509_V_ERR_CRL_HAS_EXPIRED into a + * "certificate_expired(45)" SSL alert, but that's not really the message we should convey to the peer (at + * the very least, it's confusing, and in many cases, it's also inaccurate, as the certificate itself may + * very well not have expired yet). We set the X509_STORE_CTX error to something which OpenSSL's + * s3_both.c:ssl_verify_alarm_type() maps to SSL_AD_CERTIFICATE_UNKNOWN, i.e. the peer will receive a + * "certificate_unknown(46)" alert. We do not touch errnum, though, so that later on we will still log the + * "real" error, as returned by OpenSSL. */ if (ok == 0 && errnum == X509_V_ERR_CRL_HAS_EXPIRED()) { X509_STORE_CTX_set_error(x509ctx, -1); @@ -1153,9 +1152,9 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn // OCSP if (!state.noOcspCheck && (ok > 0)) { - /* If there was an optional verification error, it's not - * possible to perform OCSP validation since the issuer may be - * missing/untrusted. Fail in that case. + /* + * If there was an optional verification error, it's not possible to perform OCSP validation since the + * issuer may be missing/untrusted. Fail in that case. */ if (verifyErrorIsOptional) { if (state.certificateVerifyMode != OpenSSLContext.OPTIONAL_NO_CA) { @@ -1185,7 +1184,7 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn } } - private static int processOCSP(MemorySegment /*X509_STORE_CTX*/ x509ctx) { + private static int processOCSP(MemorySegment /* X509_STORE_CTX */ x509ctx) { int ocspResponse = V_OCSP_CERTSTATUS_UNKNOWN(); MemorySegment x509 = X509_STORE_CTX_get_current_cert(x509ctx); if (!MemorySegment.NULL.equals(x509)) { @@ -1208,7 +1207,8 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn int length = ASN1_STRING_length(os); MemorySegment data = ASN1_STRING_get0_data(os); // ocsp_urls = decode_OCSP_url(os); - byte[] asn1String = data.reinterpret(length, localArenal, null).toArray(ValueLayout.JAVA_BYTE); + byte[] asn1String = + data.reinterpret(length, localArenal, null).toArray(ValueLayout.JAVA_BYTE); Asn1Parser parser = new Asn1Parser(asn1String); // Parse the byte sequence ArrayList<String> urls = new ArrayList<>(); @@ -1244,9 +1244,9 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn } private static final int ASN1_SEQUENCE = 0x30; - private static final int ASN1_OID = 0x06; - private static final int ASN1_STRING = 0x86; - private static final byte[] OCSP_OID = {0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x30, 0x01}; + private static final int ASN1_OID = 0x06; + private static final int ASN1_STRING = 0x86; + private static final byte[] OCSP_OID = { 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x30, 0x01 }; private static void parseOCSPURLs(Asn1Parser parser, ArrayList<String> urls) { while (!parser.eof()) { @@ -1273,7 +1273,7 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn } private static int processOCSPRequest(URL url, MemorySegment issuer, MemorySegment x509, - MemorySegment /*X509_STORE_CTX*/ x509ctx, Arena localArena) { + MemorySegment /* X509_STORE_CTX */ x509ctx, Arena localArena) { MemorySegment ocspRequest = MemorySegment.NULL; MemorySegment ocspResponse = MemorySegment.NULL; MemorySegment id; @@ -1336,9 +1336,10 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn return V_OCSP_CERTSTATUS_UNKNOWN(); } // Find by serial number and get the matching response - MemorySegment singleResponse = OCSP_resp_get0(basicResponse, OCSP_resp_find(basicResponse, certId, -1)); - return OCSP_single_get0_status(singleResponse, MemorySegment.NULL, - MemorySegment.NULL, MemorySegment.NULL, MemorySegment.NULL); + MemorySegment singleResponse = + OCSP_resp_get0(basicResponse, OCSP_resp_find(basicResponse, certId, -1)); + return OCSP_single_get0_status(singleResponse, MemorySegment.NULL, MemorySegment.NULL, + MemorySegment.NULL, MemorySegment.NULL); } } } catch (Exception e) { @@ -1376,7 +1377,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; @@ -1394,8 +1395,8 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn } MemorySegment sessionId = SSL_SESSION_get_id(session, lenPointer); int len = lenPointer.get(ValueLayout.JAVA_INT, 0); - id = (len == 0) ? new byte[0] - : sessionId.reinterpret(len, localArena, null).toArray(ValueLayout.JAVA_BYTE); + id = (len == 0) ? new byte[0] : + sessionId.reinterpret(len, localArena, null).toArray(ValueLayout.JAVA_BYTE); } } } @@ -1446,7 +1447,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); @@ -1474,7 +1475,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; } @@ -1484,7 +1485,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]; } @@ -1510,7 +1511,8 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn } chain = getPeerCertChain(); 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 clientCert = getPeerCertificate(); @@ -1655,17 +1657,15 @@ public final class OpenSSLEngine extends SSLEngine implements SSLUtil.ProtocolIn private int certificateVerifyMode = 0; private int handshakeCount = 0; - private EngineState(MemorySegment ssl, MemorySegment networkBIO, - int certificateVerificationDepth, boolean noOcspCheck) { + private EngineState(MemorySegment ssl, MemorySegment networkBIO, int certificateVerificationDepth, + boolean noOcspCheck) { states.put(Long.valueOf(ssl.address()), this); this.certificateVerificationDepth = certificateVerificationDepth; this.noOcspCheck = noOcspCheck; // Use another arena to avoid keeping a reference through segments // This also allows making further accesses to the main pointers safer - this.ssl = ssl.reinterpret(ValueLayout.ADDRESS.byteSize(), stateArena, - openssl_h::SSL_free); - this.networkBIO = networkBIO.reinterpret(ValueLayout.ADDRESS.byteSize(), stateArena, - openssl_h::BIO_free); + this.ssl = ssl.reinterpret(ValueLayout.ADDRESS.byteSize(), stateArena, openssl_h::SSL_free); + this.networkBIO = networkBIO.reinterpret(ValueLayout.ADDRESS.byteSize(), stateArena, openssl_h::BIO_free); } @Override diff --git a/java/org/apache/tomcat/util/net/openssl/panama/OpenSSLImplementation.java b/java/org/apache/tomcat/util/net/openssl/panama/OpenSSLImplementation.java index 260d196b93..c40acd7ed2 100644 --- a/java/org/apache/tomcat/util/net/openssl/panama/OpenSSLImplementation.java +++ b/java/org/apache/tomcat/util/net/openssl/panama/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/panama/OpenSSLLibrary.java b/java/org/apache/tomcat/util/net/openssl/panama/OpenSSLLibrary.java index 6f4f972aff..7272db9cf2 100644 --- a/java/org/apache/tomcat/util/net/openssl/panama/OpenSSLLibrary.java +++ b/java/org/apache/tomcat/util/net/openssl/panama/OpenSSLLibrary.java @@ -34,12 +34,10 @@ import org.apache.tomcat.util.openssl.openssl_h_Compatibility; import org.apache.tomcat.util.res.StringManager; - /** - * Implementation of a global initialization of OpenSSL according to specified - * configuration parameters. - * Using this from a listener is completely optional, but is needed for - * configuration and full cleanup of a few native memory allocations. + * Implementation of a global initialization of OpenSSL according to specified configuration parameters. Using this from + * a listener is completely optional, but is needed for configuration and full cleanup of a few native memory + * allocations. */ public class OpenSSLLibrary { @@ -52,20 +50,19 @@ public class OpenSSLLibrary { // ---------------------------------------------- Properties - protected static String SSLEngine = "on"; //default on + protected static String SSLEngine = "on"; // default on protected static String FIPSMode = "off"; // default off, valid only when SSLEngine="on" protected static String SSLRandomSeed = "builtin"; protected static boolean fipsModeActive = false; /** - * The "FIPS mode" level that we use as the argument to OpenSSL method - * <code>FIPS_mode_set()</code> to enable FIPS mode and that we expect as - * the return value of <code>FIPS_mode()</code> when FIPS mode is enabled. + * The "FIPS mode" level that we use as the argument to OpenSSL method <code>FIPS_mode_set()</code> to enable FIPS + * mode and that we expect as the return value of <code>FIPS_mode()</code> when FIPS mode is enabled. * <p> - * In the future the OpenSSL library might grow support for different - * non-zero "FIPS" modes that specify different allowed subsets of ciphers - * or whatever, but nowadays only "1" is the supported value. + * In the future the OpenSSL library might grow support for different non-zero "FIPS" modes that specify different + * allowed subsets of ciphers or whatever, but nowadays only "1" is the supported value. * </p> + * * @see <a href="http://wiki.openssl.org/index.php/FIPS_mode_set%28%29">OpenSSL method FIPS_mode_set()</a> * @see <a href="http://wiki.openssl.org/index.php/FIPS_mode%28%29">OpenSSL method FIPS_mode()</a> */ @@ -92,21 +89,20 @@ public class OpenSSLLibrary { } /* - { BN_get_rfc3526_prime_8192, NULL, 6145 }, - { BN_get_rfc3526_prime_6144, NULL, 4097 }, - { BN_get_rfc3526_prime_4096, NULL, 3073 }, - { BN_get_rfc3526_prime_3072, NULL, 2049 }, - { BN_get_rfc3526_prime_2048, NULL, 1025 }, - { BN_get_rfc2409_prime_1024, NULL, 0 } + * { BN_get_rfc3526_prime_8192, NULL, 6145 }, { BN_get_rfc3526_prime_6144, NULL, 4097 }, { + * BN_get_rfc3526_prime_4096, NULL, 3073 }, { BN_get_rfc3526_prime_3072, NULL, 2049 }, { BN_get_rfc3526_prime_2048, + * NULL, 1025 }, { BN_get_rfc2409_prime_1024, NULL, 0 } */ static final class DHParam { final MemorySegment dh; final int min; + private DHParam(MemorySegment dh, int min) { this.dh = dh; this.min = min; } } + static final DHParam[] dhParameters = new DHParam[6]; private static void initDHParameters() { @@ -205,8 +201,9 @@ public class OpenSSLLibrary { if (MemorySegment.NULL.equals(enginePointer)) { enginePointer = ENGINE_by_id(memorySession.allocateFrom("dynamic")); if (enginePointer != null) { - if (ENGINE_ctrl_cmd_string(enginePointer, memorySession.allocateFrom("SO_PATH"), engine, 0) == 0 - || ENGINE_ctrl_cmd_string(enginePointer, memorySession.allocateFrom("LOAD"), + if (ENGINE_ctrl_cmd_string(enginePointer, memorySession.allocateFrom("SO_PATH"), engine, + 0) == 0 || + ENGINE_ctrl_cmd_string(enginePointer, memorySession.allocateFrom("LOAD"), MemorySegment.NULL, 0) == 0) { // Engine load error ENGINE_free(enginePointer); @@ -233,7 +230,8 @@ public class OpenSSLLibrary { var randomSeed = memorySession.allocateFrom(SSLRandomSeed); seedDone = RAND_load_file(randomSeed, 128) > 0; if (!seedDone) { - log.warn(sm.getString("openssllibrary.errorSettingSSLRandomSeed", SSLRandomSeed, OpenSSLLibrary.getLastError())); + log.warn(sm.getString("openssllibrary.errorSettingSSLRandomSeed", SSLRandomSeed, + OpenSSLLibrary.getLastError())); } } if (!seedDone) { @@ -252,7 +250,8 @@ public class OpenSSLLibrary { final boolean enterFipsMode; int fipsModeState = FIPS_OFF; if (openssl_h_Compatibility.OPENSSL3) { - var md = EVP_MD_fetch(MemorySegment.NULL, memorySession.allocateFrom("SHA-512"), MemorySegment.NULL); + var md = EVP_MD_fetch(MemorySegment.NULL, memorySession.allocateFrom("SHA-512"), + MemorySegment.NULL); var provider = EVP_MD_get0_provider(md); String name = OSSL_PROVIDER_get0_name(provider).getString(0); EVP_MD_free(md); @@ -263,7 +262,7 @@ public class OpenSSLLibrary { fipsModeState = FIPS_mode(); } - if(log.isDebugEnabled()) { + if (log.isDebugEnabled()) { log.debug(sm.getString("openssllibrary.currentFIPSMode", Integer.valueOf(fipsModeState))); } @@ -281,7 +280,8 @@ public class OpenSSLLibrary { enterFipsMode = false; } else { if (openssl_h_Compatibility.OPENSSL3) { - throw new IllegalStateException(sm.getString("openssllibrary.FIPSProviderNotDefault", FIPSMode)); + throw new IllegalStateException( + sm.getString("openssllibrary.FIPSProviderNotDefault", FIPSMode)); } else { enterFipsMode = true; } @@ -292,7 +292,8 @@ public class OpenSSLLibrary { enterFipsMode = false; } else { if (openssl_h_Compatibility.OPENSSL3) { - throw new IllegalStateException(sm.getString("openssllibrary.FIPSProviderNotDefault", FIPSMode)); + throw new IllegalStateException( + sm.getString("openssllibrary.FIPSProviderNotDefault", FIPSMode)); } else { throw new IllegalStateException(sm.getString("openssllibrary.requireNotInFIPSMode")); } @@ -300,7 +301,8 @@ public class OpenSSLLibrary { } else if ("enter".equalsIgnoreCase(FIPSMode)) { if (fipsModeState == FIPS_OFF) { if (openssl_h_Compatibility.OPENSSL3) { - throw new IllegalStateException(sm.getString("openssllibrary.FIPSProviderNotDefault", FIPSMode)); + throw new IllegalStateException( + sm.getString("openssllibrary.FIPSProviderNotDefault", FIPSMode)); } else { enterFipsMode = true; } @@ -309,13 +311,12 @@ public class OpenSSLLibrary { fipsModeActive = true; enterFipsMode = false; } else { - throw new IllegalStateException(sm.getString( - "openssllibrary.enterAlreadyInFIPSMode", Integer.valueOf(fipsModeState))); + throw new IllegalStateException(sm.getString("openssllibrary.enterAlreadyInFIPSMode", + Integer.valueOf(fipsModeState))); } } } else { - throw new IllegalArgumentException(sm.getString( - "openssllibrary.wrongFIPSMode", FIPSMode)); + throw new IllegalArgumentException(sm.getString("openssllibrary.wrongFIPSMode", FIPSMode)); } if (enterFipsMode) { @@ -383,8 +384,7 @@ public class OpenSSLLibrary { if (!SSLEngine.equals(OpenSSLLibrary.SSLEngine)) { // Ensure that the SSLEngine is consistent with that used for SSL init if (OpenSSLStatus.isInitialized()) { - throw new IllegalStateException( - sm.getString("openssllibrary.tooLateForSSLEngine")); + throw new IllegalStateException(sm.getString("openssllibrary.tooLateForSSLEngine")); } OpenSSLLibrary.SSLEngine = SSLEngine; @@ -399,8 +399,7 @@ public class OpenSSLLibrary { if (!SSLRandomSeed.equals(OpenSSLLibrary.SSLRandomSeed)) { // Ensure that the random seed is consistent with that used for SSL init if (OpenSSLStatus.isInitialized()) { - throw new IllegalStateException( - sm.getString("openssllibrary.tooLateForSSLRandomSeed")); + throw new IllegalStateException(sm.getString("openssllibrary.tooLateForSSLRandomSeed")); } OpenSSLLibrary.SSLRandomSeed = SSLRandomSeed; @@ -415,8 +414,7 @@ public class OpenSSLLibrary { if (!FIPSMode.equals(OpenSSLLibrary.FIPSMode)) { // Ensure that the FIPS mode is consistent with that used for SSL init if (OpenSSLStatus.isInitialized()) { - throw new IllegalStateException( - sm.getString("openssllibrary.tooLateForFIPSMode")); + throw new IllegalStateException(sm.getString("openssllibrary.tooLateForFIPSMode")); } OpenSSLLibrary.FIPSMode = FIPSMode; @@ -475,12 +473,11 @@ public class OpenSSLLibrary { private static final int OPENSSL_ERROR_MESSAGE_BUFFER_SIZE = 256; /** - * 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 */ static String getLastError() { diff --git a/java/org/apache/tomcat/util/net/openssl/panama/OpenSSLSessionContext.java b/java/org/apache/tomcat/util/net/openssl/panama/OpenSSLSessionContext.java index 82ece562b0..5921287acd 100644 --- a/java/org/apache/tomcat/util/net/openssl/panama/OpenSSLSessionContext.java +++ b/java/org/apache/tomcat/util/net/openssl/panama/OpenSSLSessionContext.java @@ -65,8 +65,8 @@ public class OpenSSLSessionContext implements SSLSessionContext { throw new IllegalArgumentException(sm.getString("sessionContext.nullTicketKeys")); } if (keys.length != TICKET_KEYS_SIZE) { - throw new IllegalArgumentException(sm.getString("sessionContext.invalidTicketKeysLength", - Integer.valueOf(keys.length))); + throw new IllegalArgumentException( + sm.getString("sessionContext.invalidTicketKeysLength", Integer.valueOf(keys.length))); } try (var memorySession = Arena.ofConfined()) { var array = memorySession.allocateFrom(ValueLayout.JAVA_BYTE, keys); @@ -85,8 +85,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 SSL_CTX_get_session_cache_mode(context.getSSLContext()) == SSL_SESS_CACHE_SERVER(); @@ -126,12 +125,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/panama/OpenSSLSessionStats.java b/java/org/apache/tomcat/util/net/openssl/panama/OpenSSLSessionStats.java index a63e524381..31a3912bef 100644 --- a/java/org/apache/tomcat/util/net/openssl/panama/OpenSSLSessionStats.java +++ b/java/org/apache/tomcat/util/net/openssl/panama/OpenSSLSessionStats.java @@ -44,21 +44,21 @@ public final class OpenSSLSessionStats { * @return The number of started SSL/TLS handshakes in client mode. */ public long connect() { - return SSL_CTX_ctrl(ctx, SSL_CTRL_SESS_CONNECT() ,0, null); + return SSL_CTX_ctrl(ctx, SSL_CTRL_SESS_CONNECT(), 0, null); } /** * @return The number of successfully established SSL/TLS sessions in client mode. */ public long connectGood() { - return SSL_CTX_ctrl(ctx, SSL_CTRL_SESS_CONNECT_GOOD() , 0, null); + return SSL_CTX_ctrl(ctx, SSL_CTRL_SESS_CONNECT_GOOD(), 0, null); } /** * @return The number of start renegotiations in client mode. */ public long connectRenegotiate() { - return SSL_CTX_ctrl(ctx, SSL_CTRL_SESS_CONNECT_RENEGOTIATE() , 0, null); + return SSL_CTX_ctrl(ctx, SSL_CTRL_SESS_CONNECT_RENEGOTIATE(), 0, null); } /** @@ -83,44 +83,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 SSL_CTX_ctrl(ctx, SSL_CTRL_SESS_HIT(), 0, null); } /** - * @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 SSL_CTX_ctrl(ctx, SSL_CTRL_SESS_CB_HIT(), 0, null); } /** - * @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 SSL_CTX_ctrl(ctx, SSL_CTRL_SESS_MISSES(), 0, null); } /** - * @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 SSL_CTX_ctrl(ctx, SSL_CTRL_SESS_TIMEOUTS(), 0, null); } /** - * @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 SSL_CTX_ctrl(ctx, SSL_CTRL_SESS_CACHE_FULL(), 0, null); diff --git a/java/org/apache/tomcat/util/net/openssl/panama/OpenSSLUtil.java b/java/org/apache/tomcat/util/net/openssl/panama/OpenSSLUtil.java index 6080dfdfb4..458e874482 100644 --- a/java/org/apache/tomcat/util/net/openssl/panama/OpenSSLUtil.java +++ b/java/org/apache/tomcat/util/net/openssl/panama/OpenSSLUtil.java @@ -90,8 +90,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/panama/OpenSSLX509Certificate.java b/java/org/apache/tomcat/util/net/openssl/panama/OpenSSLX509Certificate.java index fc52abe8d6..0011c1be54 100644 --- a/java/org/apache/tomcat/util/net/openssl/panama/OpenSSLX509Certificate.java +++ b/java/org/apache/tomcat/util/net/openssl/panama/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