Jetty server端如何在创建mTLS链接时获得clien

2020-09-17  本文已影响0人  金圣迪

Requirement

Client端在发送请求时,没有做user的authentication,显然这样不符合安全要求。结合客户端的特点-是设备自动发送,所以提出要用mTLS去验证客户端的身份信息来达到对客户的验证。

目前Server端里边起了一个embedded jetty server, 并且在client端在连接时会要求验证client的证书,并且要求把验证的结果以log形式存起来,包括证书的DN信息。

Analysis

证书方面,服务器端jetty要加载keystore.jks,里边包括server端的private key,还要加载truststore.jks,里边包括认证client证书的CA证书,如果是由intermediate CA认证的话,那么所有CA chain 都要包括在truststore里,还有client的证书。客户端在请求的时候要带上自己的私钥公钥,这取决于client端访问的形式。

jetty方面,在生成Connector的时候要加载keystore, truststore,还要setNeedClientAuth为true才能去触发对client证书的验证。还有就是要获取client证书验证的结果,有一个listener的接口,在验证结束后会把结果notify的这类的是实现上。

下面是jetty server的代码例子,在connector上加了一个SSLHandshakeListener的实现。

Server server = new Server();

// === Configure SSL KeyStore, TrustStore, and Ciphers ===
SslContextFactory sslContextFactory = new SslContextFactory.Server();
sslContextFactory.setKeyStorePath("/path/to/keystore");
sslContextFactory.setKeyStorePassword("xxxxxx");
sslContextFactory.setTrustStorePath("/path/to/truststore");
sslContextFactory.setTrustStorePassword("xxxxxx");
// OPTIONAL - for client certificate auth (both are not needed)
sslContextFactory.getWantClientAuth(true)
sslContextFactory.setNeedClientAuth(true)

// === SSL HTTP Configuration ===
HttpConfiguration https_config = new HttpConfiguration(http_config);
https_config.addCustomizer(new SecureRequestCustomizer()); 

// == Add SSL Connector ===
ServerConnector sslConnector = new ServerConnector(server,
    new SslConnectionFactory(sslContextFactory,"http/1.1"),
    new HttpConnectionFactory(https_config));
sslConnector.setPort(8778);
SslHandshakeListener sslHandshakeListener = new MySslHandshakeListener ();
sslConnector.addBean(sslHandshakeListener);
server.addConnector(sslConnector);

server.start()
public class MySslHandshakeListener implements SslHandshakeListener {

    @Override
    public void handshakeSucceeded(Event event) throws SSLException {
       Arrays.stream(event.getSSLEngine().getSession().getPeerCertificateChain()).forEach(x509Certificate -> {
            System.out.printf("Certificates [{}] is authenticated successfully", x509Certificate.getSubjectDN().toString());

    }
    @Override
    public void handshakeFailed(Event event, Throwable failure) {
        Arrays.stream(event.getSSLEngine().getSession().getPeerCertificateChain()).forEach(x509Certificate -> {
            System.out.printf("Certificates [{}] is authenticated failed", x509Certificate.getSubjectDN().toString());
    }
}

一起似乎很美好,但是这个getPeerCertificateChain()说 if the peer identity has not been verified, throw SSLPeerUnverifiedException,所以这个方法没办法在authentication失败的时候拿到client端的证书信息。所以还要在依照其他的办法。
最后的办法是自己创建一个SSLContext, init with KeyManagers和TrustManagers, 然后把TrustManager里的X509TrustManager包一层,把checkClientTrusted(X509Certificate[] x509Certificates, String authType)重写,这样肯定能拿到peer client的证书信息,不管到底成功还是失败

public class MyTrustManagerWrapper implements X509TrustManager {
        private X509TrustManager x509TrustManager;

        TrustManagerWrapper(X509TrustManager trustManager) {
            x509TrustManager= trustManager;
        }

        @Override
        public void checkClientTrusted(X509Certificate[] x509Certificates, String xx) throws CertificateException {
            try {
                x509TrustManager.checkClientTrusted(x509Certificates, xx);
               // 认证成功,读取证书信息
            } catch (CertificateException e) {
                //认证失败,也可以读取证书信息
                throw e;
            }
        }

        ...
    }

生成SSLContext的代码

public static SSLContext getSSLContextInstance()
            throws Exception {
        try {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(getKeyManagers(), getTrustManagers(), new java.security.SecureRandom());
            return sslContext;
        } catch (Exception e) {
            throw e;
        }
    }
private KeyManager[] getKeyManagers() throws Exception {
        try (InputStream stream = new FileInputStream(keyStoreFile)) {
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(stream, keyStorePassword);
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(keyStore, keyStorePassword);
            return kmf.getKeyManagers();
        } catch (Exception e) {
            throw e;
        }
    }
private TrustManager[] getTrustManagers() throws Exception {
        try (InputStream stream = new FileInputStream(trustStoreFile)) {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(stream, trustStorePassword);
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            tmf.init(trustStore);
            TrustManager[] trustManagers = tmf.getTrustManagers();
            return Arrays.stream(trustManagers).map(t -> t instanceof X509TrustManager ? new MyTrustManagerWrapper((X509TrustManager) t): t).toArray(TrustManager[]::new);
        } catch (Exception e) {
            throw e;
        }
    }

Conclusion

目前测试看下来没有什么问题,我用的是curl发的request,
curl -X POST https://127.0.0.1:8778/my/request --cert ./client.crt --key ./client.key -T ../request_body.json -v -k --tlsv1.2
研发过程中也发过一个帖子,得到一个jetty专家解答,才有的第一个方法,虽然不能满足需求,但还是得到了很多启发,很是感谢 链接

自己敲字,原创经验分享,有问题请指正,谢谢

上一篇下一篇

猜你喜欢

热点阅读