From 8799fe807e12b546465015940013f4a5acdaaecb Mon Sep 17 00:00:00 2001 From: Justin Bertram Date: Tue, 3 Aug 2021 22:29:37 -0500 Subject: [PATCH] ARTEMIS-3302 fix regression with OpenSSL When using the OpenSSL provider on the broker the getPeerCertificates() method does *not* return a X509Certificate[] so we need to convert the Certificate[] that is returned. This code is inspired by Tomcat's org.apache.tomcat.util.net.jsse.JSSESupport class. --- .../artemis/utils/CertificateUtil.java | 33 +++++++++++++++++-- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/CertificateUtil.java b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/CertificateUtil.java index 56a7ae91ed..bd23a74c25 100644 --- a/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/CertificateUtil.java +++ b/artemis-commons/src/main/java/org/apache/activemq/artemis/utils/CertificateUtil.java @@ -18,26 +18,53 @@ package org.apache.activemq.artemis.utils; import javax.net.ssl.SSLPeerUnverifiedException; +import java.io.ByteArrayInputStream; +import java.security.cert.Certificate; +import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import io.netty.channel.Channel; import io.netty.channel.ChannelHandler; import io.netty.handler.ssl.SslHandler; +import org.jboss.logging.Logger; public class CertificateUtil { + private static final Logger logger = Logger.getLogger(CertificateUtil.class); public static X509Certificate[] getCertsFromChannel(Channel channel) { - X509Certificate[] certificates = null; + Certificate[] plainCerts = null; ChannelHandler channelHandler = channel.pipeline().get("ssl"); if (channelHandler != null && channelHandler instanceof SslHandler) { SslHandler sslHandler = (SslHandler) channelHandler; try { - certificates = (X509Certificate[]) sslHandler.engine().getSession().getPeerCertificates(); + plainCerts = sslHandler.engine().getSession().getPeerCertificates(); } catch (SSLPeerUnverifiedException e) { // ignore } } - return certificates; + X509Certificate[] x509Certs = null; + if (plainCerts != null && plainCerts.length > 0) { + x509Certs = new X509Certificate[plainCerts.length]; + for (int i = 0; i < plainCerts.length; i++) { + if (plainCerts[i] instanceof X509Certificate) { + x509Certs[i] = (X509Certificate) plainCerts[i]; + } else { + try { + x509Certs[i] = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(new ByteArrayInputStream(plainCerts[i].getEncoded())); + } catch (Exception ex) { + if (logger.isTraceEnabled()) { + logger.trace("Failed to convert SSL cert", ex); + } + return null; + } + } + if (logger.isTraceEnabled()) { + logger.trace("Cert #" + i + " = " + x509Certs[i]); + } + } + } + + return x509Certs; } }