Java SSL双向握手错误

时间:2015-05-30 00:16:19

标签: java sockets ssl

我正在使用Java开发一个简单的SSL服务器/客户端。请忽略未使用的trustStore。当服务器设置serverSock.setNeedClientAuth(false)时,它工作正常。但是,如果设置了serverSock.setNeedClientAuth(true),则会出现错误提示

*** ServerHello, TLSv1
....
***


   *** ECDH ServerKeyExchange
    Server key: Sun EC public key, 256 bits
      public x coord: 61670393751189389356366022463080915345182339021857366784148461923453434926203
      public y coord: 11927389709535675731950695034443898307097761611191306989959806723983291216258
      parameters: secp256r1 [NIST P-256, X9.62 prime256v1] (1.2.840.10045.3.1.7)
    **main, handling exception: java.lang.NullPointerException
    %% Invalidated:  [Session-1, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA]**
    main, SEND TLSv1 ALERT:  fatal, description = internal_error
    main, WRITE: TLSv1 Alert, length = 2
    main, called closeSocket()
Exception in thread "main" javax.net.ssl.SSLException: java.lang.NullPointerException
    at sun.security.ssl.Alerts.getSSLException(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.handleException(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.handleException(Unknown Source)
    at sun.security.ssl.AppInputStream.read(Unknown Source)
    at java.io.InputStream.read(Unknown Source)
    at cn.secure.CAServer.start(SecureServer.java:100)
    at cn.secure.SecureServer.main(SecureServer.java:33)
Caused by: java.lang.NullPointerException
    at sun.security.ssl.HandshakeMessage$CertificateRequest.<init>(Unknown Source)
    at sun.security.ssl.ServerHandshaker.clientHello(Unknown Source)
    at sun.security.ssl.ServerHandshaker.processMessage(Unknown Source)
    at sun.security.ssl.Handshaker.processLoop(Unknown Source)
    at sun.security.ssl.Handshaker.process_record(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
    at sun.security.ssl.SSLSocketImpl.readDataRecord(Unknown Source)
    ... 4 more

看来ServerHello还没有完成。

以下是我的代码。请让我知道如何解决它。

// Server code
class CAServer
{
    private SSLContext ctx;
    private KeyManagerFactory kmf;
    private TrustManagerFactory tmf;
    private SSLServerSocket serverSock;

    public void init() throws NoSuchAlgorithmException, KeyStoreException, CertificateException, FileNotFoundException, IOException, UnrecoverableKeyException, KeyManagementException
    {
        ctx=SSLContext.getInstance("TLS");
        kmf=KeyManagerFactory.getInstance("SunX509");
        tmf=TrustManagerFactory.getInstance("SunX509");
        char[] pwd="111".toCharArray();

        KeyStore ks=KeyStore.getInstance("JKS");
        KeyStore ts=KeyStore.getInstance("JKS");

        ks.load(new FileInputStream("C:/Users/Jim/ca.keystore"), pwd);        
        ts.load(new FileInputStream("C:/Users/Jim/ca.keystore"), pwd); // unused    

        kmf.init(ks,pwd);
        tmf.init(ts);

        TrustManager[] trustClientCerts = new TrustManager[] { new X509TrustManager() {

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkClientTrusted(X509Certificate[] certs,String authType) {

            }

            @Override
            public void checkServerTrusted(X509Certificate[] certs,String authType) {
            }
        } 
        };


        ctx.init(kmf.getKeyManagers(),trustClientCerts, null);

        //init server
        serverSock=(SSLServerSocket)ctx.getServerSocketFactory().createServerSocket(13000);

        serverSock.setNeedClientAuth(true);
    }

    public void start() throws IOException
    {
        System.out.println("My Secure server start");
        while(true)
        {
            Socket s=serverSock.accept();

            InputStream input=s.getInputStream();   

            byte[] c=new byte[256];
            input.read(c);           **// error(NullPointer) occurs here** 
            System.out.println(new String(c));
        }
    }

}


// Client code
class MyClient
{
    private SSLContext ctx;
    KeyManagerFactory kmf;
    TrustManagerFactory tmf;
    private SSLSocket clientSock;

    public void init() throws NoSuchAlgorithmException, KeyStoreException, CertificateException, FileNotFoundException, IOException, KeyManagementException, UnrecoverableKeyException
    {
        ctx=SSLContext.getInstance("TLS");
        kmf=KeyManagerFactory.getInstance("SunX509");
        tmf=TrustManagerFactory.getInstance("SunX509");

        char[] pwd="111".toCharArray();

        KeyStore ks=KeyStore.getInstance("JKS");
        KeyStore ts=KeyStore.getInstance("JKS");

        ks.load(new FileInputStream("C:/Users/jim/alice.keystore"), pwd);         
        ts.load(new FileInputStream("C:/Users/jim/alice.keystore"), pwd);    //unused  

        TrustManager[] trustServerCerts = new TrustManager[]{new X509TrustManager() 
        {

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) 
            {

                for(X509Certificate c :certs){
                   System.out.println(c.getSubjectDN().getName());
                }

             }
            }
        };

        kmf.init(ks, pwd);
        tmf.init(ts);

        ctx.init(kmf.getKeyManagers(), trustServerCerts, null);

        clientSock=(SSLSocket)ctx.getSocketFactory().createSocket("127.0.0.1", 13000);
        clientSock.setUseClientMode(true);

    }

    public void run() throws IOException
    {
        InputStream input = null;  
        OutputStream output = null;  

        output = clientSock.getOutputStream(); 
        BufferedOutputStream bufferedOutput = new BufferedOutputStream(output);
        bufferedOutput.write("Alice: is running".getBytes());  
        bufferedOutput.flush();

    }

}

顺便说一下,Windows根据日志只支持TLSv1,这是令人惊讶的。

2 个答案:

答案 0 :(得分:2)

来自X509TrustManager.getAcceptedIssuers()文档:

  

返回:可接受的CA颁发者证书的非null (可能为空)数组。

如果在那里返回一个空值(就像你那样)会在随后的某处导致NullPointerException,那就不足为奇了。

确实,constructor of sun.security.ssl.HandshakeMessage$CertificateRequest makes use of this array of CA certificates assuming it's not null

此外,如果您想要更加真实地尝试双向身份验证,则可以创建自己的测试CA并拥有适当的信任库。您正在使用的行为(空列表)有效,但它仅在TLS 1.1规范中指定为可接受。 (无论如何,绕过所有信任检查都不是一个好主意。)

您的一条评论:

  

我不知道使用getAcceptedIssuers。你能解释一下吗?

getAcceptedIssuers()仅用于构建Certificate Request TLS消息中发送的可接受CA证书列表。虽然它是一组证书,但实际上只使用了这些证书的主题DN。

这与SSLCADNRequestFile and SSLCADNRequestPath directives in Apache Httpd非常相似。将它与信任库中的列表区别开来是非常有用的。

验证的实际用途是checkServerTrusted()

  

Truststore包含可信方的证书,在程序启动时加载。如果我们要在运行时在Truststore中添加/删除条目,有没有办法做到这一点?

如果需要,您可以以编程方式加载信任库,而不是使用默认或系统属性,如this answer中所述。然后,从您使用它初始化的SSLContext创建服务器套接字。

如果您每次需要更改信任库时都可以关闭并重新打开服务器套接字在实现自己的TrustManager时,您可能会有一些更复杂的事情,它将其调用委托给另一个初始化的信任管理器。 KeyStore(您的信任库)和TrustManagerFactory。每当您的信任库发生更改时,您都会更改委派的TrustManager(您可能需要考虑可能的并发问题)。

答案 1 :(得分:0)

getAcceptedIssuers()方法可能不会返回null。见Javadoc。

但是请不要使用这种不安全的信任管理器代码,尤其是当您拥有自己的信任库时。

呃,不,不。您的密钥库应该与您的信任库不同。它们具有完全不同的功能。