This commit is contained in:
Clebert Suconic 2021-08-04 09:19:41 -04:00
commit 9b49e63ef3
1 changed files with 30 additions and 3 deletions

View File

@ -18,26 +18,53 @@
package org.apache.activemq.artemis.utils; package org.apache.activemq.artemis.utils;
import javax.net.ssl.SSLPeerUnverifiedException; 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 java.security.cert.X509Certificate;
import io.netty.channel.Channel; import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandler;
import io.netty.handler.ssl.SslHandler; import io.netty.handler.ssl.SslHandler;
import org.jboss.logging.Logger;
public class CertificateUtil { public class CertificateUtil {
private static final Logger logger = Logger.getLogger(CertificateUtil.class);
public static X509Certificate[] getCertsFromChannel(Channel channel) { public static X509Certificate[] getCertsFromChannel(Channel channel) {
X509Certificate[] certificates = null; Certificate[] plainCerts = null;
ChannelHandler channelHandler = channel.pipeline().get("ssl"); ChannelHandler channelHandler = channel.pipeline().get("ssl");
if (channelHandler != null && channelHandler instanceof SslHandler) { if (channelHandler != null && channelHandler instanceof SslHandler) {
SslHandler sslHandler = (SslHandler) channelHandler; SslHandler sslHandler = (SslHandler) channelHandler;
try { try {
certificates = (X509Certificate[]) sslHandler.engine().getSession().getPeerCertificates(); plainCerts = sslHandler.engine().getSession().getPeerCertificates();
} catch (SSLPeerUnverifiedException e) { } catch (SSLPeerUnverifiedException e) {
// ignore // 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;
} }
} }