【问题标题】:SSLHandshakeFailed on mongodb server while trying to connect through java driver尝试通过 java 驱动程序连接时,mongodb 服务器上的 SSLHandshakeFailed
【发布时间】:2020-04-16 13:01:59
【问题描述】:

我一直在尝试通过 java 驱动程序将 mongodb 服务器与 TLS 1.2 连接,但是我无法理解为什么握手失败。这是我的设置

  • MongoDB 服务器 4.2.1
  • mongod.conf:
net:
   bindIp: 127.0.0.1
   port: 27017

   tls:
    mode: requireTLS
    CAFile: <location-to-ca.crt>
    certificateKeyFile: <location-to-server.pem>
    disabledProtocols: TLS1_0,TLS1_1
  • JDK:1.8.0_202
  • mongo-java-driver: 3.12.3
private static void Tls1_2Test() throws Exception {
    SSLContext sslContext = createSSLContext();
    MongoClientSettings settings = MongoClientSettings.builder()
            .applyToSslSettings(builder -> {
                builder.enabled(true);
                builder.context(sslContext);
                builder.invalidHostNameAllowed(true);
            })
            .build();
    try (MongoClient client = MongoClients.create(settings)) {
        for (String s : client.listDatabaseNames()) {
            System.out.println(s);
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

public static SSLContext createSSLContext() throws Exception {

    // root CA
    TrustManagerFactory tmf;
    try (InputStream is = new FileInputStream("<location-to-ca.crt>")) {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509Certificate caCert = (X509Certificate) cf.generateCertificate(is);
        tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(null); // You don't need the KeyStore instance to come from a file.
        ks.setCertificateEntry("caCert", caCert);
        tmf.init(ks);
    }

    // client key
    KeyManagerFactory keyFac;
    try (InputStream is = Test.class.getResourceAsStream("<location-to-client.pem>")) {
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        keystore.load(is, null);
        keyFac = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyFac.init(keystore, null);
    }

    SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
    sslContext.init(keyFac.getKeyManagers(), tmf.getTrustManagers(), null);

    return sslContext;
}

如果我不使用 CAFile 或在配置中使用allowConnectionsWithoutCertificates: true,我可以连接,因为服务器不负责握手的可信授权。但是,我找不到 java 代码有什么问题,因此服务器没有获得 CA 证书以用于握手。

注意 mongod config 中的 net.tls.CAFile 和 java 代码中的 root CA 指向同一个文件。我也尝试在 net.tls.CAFile 中使用 .pem 文件,但得到了相同的结果。

这是我尝试连接时的 java 控制台:

14:39:55.501 [main] INFO org.mongodb.driver.cluster - Cluster created with settings {hosts=[127.0.0.1:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
14:39:55.524 [main] DEBUG org.mongodb.driver.cluster - Updating cluster description to  {type=UNKNOWN, servers=[{address=127.0.0.1:27017, type=UNKNOWN, state=CONNECTING}]
14:39:55.536 [main] INFO org.mongodb.driver.cluster - Cluster description not yet available. Waiting for 30000 ms before timing out
14:39:55.641 [cluster-ClusterId{value='5e98521b6091fb316cd91fbe', description='null'}-127.0.0.1:27017] DEBUG org.mongodb.driver.connection - Closing connection connectionId{localValue:1}
14:39:55.643 [cluster-ClusterId{value='5e98521b6091fb316cd91fbe', description='null'}-127.0.0.1:27017] INFO org.mongodb.driver.cluster - Exception in monitor thread while connecting to server 127.0.0.1:27017
com.mongodb.MongoSocketReadException: Exception receiving message
    at com.mongodb.internal.connection.InternalStreamConnection.translateReadException(InternalStreamConnection.java:569)
    at com.mongodb.internal.connection.InternalStreamConnection.receiveMessage(InternalStreamConnection.java:448)
    at com.mongodb.internal.connection.InternalStreamConnection.receiveCommandMessageResponse(InternalStreamConnection.java:299)
    at com.mongodb.internal.connection.InternalStreamConnection.sendAndReceive(InternalStreamConnection.java:259)
    at com.mongodb.internal.connection.CommandHelper.sendAndReceive(CommandHelper.java:83)
    at com.mongodb.internal.connection.CommandHelper.executeCommand(CommandHelper.java:33)
    at com.mongodb.internal.connection.InternalStreamConnectionInitializer.initializeConnectionDescription(InternalStreamConnectionInitializer.java:105)
    at com.mongodb.internal.connection.InternalStreamConnectionInitializer.initialize(InternalStreamConnectionInitializer.java:62)
    at com.mongodb.internal.connection.InternalStreamConnection.open(InternalStreamConnection.java:129)
    at com.mongodb.internal.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:117)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(SocketInputStream.java:210)
    at java.net.SocketInputStream.read(SocketInputStream.java:141)
    at sun.security.ssl.InputRecord.readFully(InputRecord.java:465)
    at sun.security.ssl.InputRecord.read(InputRecord.java:503)
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:975)
    at sun.security.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:933)
    at sun.security.ssl.AppInputStream.read(AppInputStream.java:105)
    at com.mongodb.internal.connection.SocketStream.read(SocketStream.java:109)
    at com.mongodb.internal.connection.InternalStreamConnection.receiveResponseBuffers(InternalStreamConnection.java:580)
    at com.mongodb.internal.connection.InternalStreamConnection.receiveMessage(InternalStreamConnection.java:445)
    ... 9 common frames omitted
14:39:55.644 [cluster-ClusterId{value='5e98521b6091fb316cd91fbe', description='null'}-127.0.0.1:27017] DEBUG org.mongodb.driver.cluster - Updating cluster description to  {type=UNKNOWN, servers=[{address=127.0.0.1:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketReadException: Exception receiving message}, caused by {java.net.SocketException: Connection reset}}]
14:39:56.174 [cluster-ClusterId{value='5e98521b6091fb316cd91fbe', description='null'}-127.0.0.1:27017] DEBUG org.mongodb.driver.connection - Closing connection connectionId{localValue:2}
14:39:56.174 [cluster-ClusterId{value='5e98521b6091fb316cd91fbe', description='null'}-127.0.0.1:27017] DEBUG org.mongodb.driver.cluster - Updating cluster description to  {type=UNKNOWN, servers=[{address=127.0.0.1:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketReadException: Exception receiving message}, caused by {java.net.SocketException: Connection reset}}]
14:39:56.699 [cluster-ClusterId{value='5e98521b6091fb316cd91fbe', description='null'}-127.0.0.1:27017] DEBUG org.mongodb.driver.connection - Closing connection connectionId{localValue:3}
14:39:56.700 [cluster-ClusterId{value='5e98521b6091fb316cd91fbe', description='null'}-127.0.0.1:27017] DEBUG org.mongodb.driver.cluster - Updating cluster description to  {type=UNKNOWN, servers=[{address=127.0.0.1:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketReadException: Exception receiving message}, caused by {java.net.SocketException: Connection reset}}]
14:39:57.228 [cluster-ClusterId{value='5e98521b6091fb316cd91fbe', description='null'}-127.0.0.1:27017] DEBUG org.mongodb.driver.connection - Closing connection connectionId{localValue:4}
14:39:57.228 [cluster-ClusterId{value='5e98521b6091fb316cd91fbe', description='null'}-127.0.0.1:27017] DEBUG org.mongodb.driver.cluster - Updating cluster description to  {type=UNKNOWN, servers=[{address=127.0.0.1:27017, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketReadException: Exception receiving message}, caused by {java.net.SocketException: Connection reset}}]

Process finished with exit code 130 (interrupted by signal 2: SIGINT)

这是我尝试连接时的服务器日志:

2020-04-16T14:39:57.227+0200 I  NETWORK  [conn4] Error receiving request from client: SSLHandshakeFailed: SSL peer certificate validation failed: no SSL certificate provided by peer: No error.; connection rejected. Ending connection from 127.0.0.1:52955 (connection id: 4)

提前致谢

【问题讨论】:

    标签: java mongodb ssl-certificate tls1.2


    【解决方案1】:

    经过一番挖掘,我发现不是仅仅使用Keystore(因为我没有设置任何Keystore来使用)我使用bouncy castle读取客户端文件。使用 bouncycastle 1.65 版本。这是我实现它的方法:

    我将客户端文件读取更新为以下内容

    // client key
    KeyManagerFactory keyFac;
    try (FileReader fr = new FileReader("<location-to-client.pem>")) {
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        keystore.load(null); // needs to be initialised, otherwise throws exception
        PEMParser pemParser = new PEMParser(fr);
        PrivateKeyInfo privateKeyInfo = (PrivateKeyInfo) pemParser.readObject();
        JcaPEMKeyConverter converter = new JcaPEMKeyConverter();
        PrivateKey privateKey = converter.getPrivateKey(privateKeyInfo);
        JcaX509CertificateConverter certConverter = new JcaX509CertificateConverter();
        X509CertificateHolder certificateHolder = (X509CertificateHolder) pemParser.readObject();
        X509Certificate certificate = certConverter.getCertificate(certificateHolder);
        keystore.setKeyEntry("alias", privateKey, "".toCharArray(), new Certificate[]{certificate});
        keyFac = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyFac.init(keystore, "".toCharArray());
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-13
      相关资源
      最近更新 更多