Java SSL Exception,protocol_version在尝试使用HttpClient登录网站时

时间:2015-07-28 18:54:56

标签: java http ssl https httpclient

我有一个Java程序,我试图与使用与TLSv1的HTTPS连接的网站交谈。 (用FireFox检查。)

问题是我仍然遇到protocol_version异常。这是堆栈跟踪:

    javax.net.ssl.SSLException: Received fatal alert: protocol_version
2015-07-28 14:48:38 [INFO ] 
    at sun.security.ssl.Alerts.getSSLException(Alerts.java:208)
    at sun.security.ssl.Alerts.getSSLException(Alerts.java:154)
    at sun.security.ssl.SSLSocketImpl.recvAlert(SSLSocketImpl.java:2023)
    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1125)
    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1403)
    at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1387)
    at org.apache.http.conn.ssl.SSLConnectionSocketFactory.createLayeredSocket(SSLConnectionSocketFactory.java:290)
    at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:259)
    at org.apache.http.impl.conn.HttpClientConnectionOperator.connect(HttpClientConnectionOperator.java:125)
    at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:319)
    at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:363)
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:219)
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:195)
    at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:86)
    at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:108)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:106)
    at org.openhab.binding.honeywellwifithermostat.handler.honeywellWifiThermostatHandler.getHoneywellWebsiteAuthCookie(honeywellWifiThermostatHandler.java:91)
    at org.openhab.binding.honeywellwifithermostat.handler.honeywellWifiThermostatHandler.initialize(honeywellWifiThermostatHandler.java:73)
    at org.eclipse.smarthome.core.thing.binding.BaseThingHandlerFactory.registerHandler(BaseThingHandlerFactory.java:116)
    at org.eclipse.smarthome.core.thing.internal.ThingManager$6.call(ThingManager.java:480)
    at org.eclipse.smarthome.core.thing.internal.ThingManager$6.call(ThingManager.java:1)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)

以下是相关的Java源代码:

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.SSLContext;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.eclipse.smarthome.config.core.Configuration;
import org.eclipse.smarthome.core.thing.ChannelUID;
import org.eclipse.smarthome.core.thing.Thing;
import org.eclipse.smarthome.core.thing.binding.BaseThingHandler;
import org.eclipse.smarthome.core.types.Command;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The {@link honeywellWifiThermostatHandler} is responsible for handling commands, which are
 * sent to one of the channels.
 *
 * @author  - Initial contribution
 */
public class honeywellWifiThermostatHandler extends BaseThingHandler {

    private Logger logger = LoggerFactory.getLogger(honeywellWifiThermostatHandler.class);

    private String userName = null;
    private String passWord = null;

    public honeywellWifiThermostatHandler(Thing thing) {
        super(thing);
    }

    @Override
    public void handleCommand(ChannelUID channelUID, Command command) {
        if (channelUID.getId().equals(CHANNEL_1)) {
            // TODO: handle command
        }
    }

    @Override
    public void initialize() {
        // TODO Auto-generated method stub
        Configuration conf = this.getConfig();

        if (conf.get("userName") != null) {
            userName = String.valueOf(conf.get("userName"));
        }
        if (conf.get("passWord") != null) {
            passWord = String.valueOf(conf.get("passWord"));
        }

        logger.debug("Attempting to get auth cookie for Honeywell site.");
        getHoneywellWebsiteAuthCookie(userName, passWord);

        super.initialize();
    }

    public void getHoneywellWebsiteAuthCookie(String userName, String passWord) {

        CloseableHttpClient httpclient;
        try {
            SSLContext ctx = SSLContexts.custom().useProtocol("TLSv1").build();
            httpclient = HttpClientBuilder.create().setSslcontext(ctx).build();

            HttpPost httpPost = new HttpPost("https://www.mytotalconnectcomfort.com/portal/");
            List<NameValuePair> fields = new ArrayList<NameValuePair>();
            fields.add(new BasicNameValuePair("UserName", userName));
            fields.add(new BasicNameValuePair("Password", passWord));

            httpPost.setEntity(new UrlEncodedFormEntity(fields));
            CloseableHttpResponse resp = httpclient.execute(httpPost);

            logger.debug("Status line: {}", resp.getStatusLine());
        } catch (IOException | NoSuchAlgorithmException | KeyManagementException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

有什么想法吗?甚至想知道如何追溯这一点?

更新

我从Java VM获得了调试信息。它给出了一些关于不受支持的密码套件的错误,然后可能会尝试回退到SSLv3?我对加密的东西不太强烈。再次,非常感谢任何帮助。

-------------------------  NET DEBUG CRAP ---------------------------
trustStore is: /usr/lib/jvm/java-8-openjdk/jre/lib/security/cacerts
trustStore type is : jks
trustStore provider is : 
init truststore

== REMOVED ADDING TRUSTED ROOT CERT MESSAGES ==

trigger seeding of SecureRandom
done seeding SecureRandom
Ignoring unsupported cipher suite: TLS_DHE_DSS_WITH_AES_256_GCM_SHA384
Ignoring unsupported cipher suite: TLS_DHE_DSS_WITH_AES_128_CBC_SHA256
Ignoring unsupported cipher suite: TLS_DHE_RSA_WITH_AES_128_CBC_SHA256
Ignoring unsupported cipher suite: TLS_DHE_DSS_WITH_AES_128_GCM_SHA256
Ignoring unsupported cipher suite: TLS_DHE_RSA_WITH_AES_256_GCM_SHA384
Ignoring unsupported cipher suite: TLS_DHE_RSA_WITH_AES_128_GCM_SHA256
Ignoring unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
Ignoring unsupported cipher suite: TLS_RSA_WITH_AES_256_CBC_SHA256
Ignoring unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
Ignoring unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256
Ignoring unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384
Ignoring unsupported cipher suite: TLS_RSA_WITH_AES_128_CBC_SHA256
Ignoring unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384
Ignoring unsupported cipher suite: TLS_RSA_WITH_AES_128_GCM_SHA256
Ignoring unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256
Ignoring unsupported cipher suite: TLS_RSA_WITH_AES_256_GCM_SHA384
Ignoring unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384
Ignoring unsupported cipher suite: TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256
Ignoring unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384
Ignoring unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
Ignoring unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384
Ignoring unsupported cipher suite: TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256
Ignoring unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384
Ignoring unsupported cipher suite: TLS_DHE_RSA_WITH_AES_256_CBC_SHA256
Ignoring unsupported cipher suite: TLS_DHE_DSS_WITH_AES_256_CBC_SHA256
Ignoring unsupported cipher suite: TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
Ignoring unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
Ignoring unsupported cipher suite: TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
Allow unsafe renegotiation: false
Allow legacy hello messages: true
Is initial handshake: true
Is secure renegotiation: false
%% No cached client session
*** ClientHello, TLSv1.2
RandomCookie:  GMT: 1421269547 bytes = { 179, 68, 198, 137, 7, 197, 13, 106, 3, 187, 99, 160, 117, 164, 48, 226, 113, 136, 166, 199, 101, 82, 195, 192, 46, 52, 140, 181 }
Session ID:  {}
Cipher Suites: [TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_RSA_WITH_AES_256_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDH_RSA_WITH_AES_256_CBC_SHA, TLS_DHE_RSA_WITH_AES_256_CBC_SHA, TLS_DHE_DSS_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA, TLS_ECDH_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_DSS_WITH_AES_128_CBC_SHA, TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA, TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, TLS_EMPTY_RENEGOTIATION_INFO_SCSV]
Compression Methods:  { 0 }
Extension elliptic_curves, curve names: {secp256r1, sect163k1, sect163r2, secp192r1, secp224r1, sect233k1, sect233r1, sect283k1, sect283r1, secp384r1, sect409k1, sect409r1, secp521r1, sect571k1, sect571r1, secp160k1, secp160r1, secp160r2, sect163r1, secp192k1, sect193r1, sect193r2, secp224k1, sect239k1, secp256k1}
Extension ec_point_formats, formats: [uncompressed]
Extension signature_algorithms, signature_algorithms: SHA512withECDSA, SHA512withRSA, SHA384withECDSA, SHA384withRSA, SHA256withECDSA, SHA256withRSA, SHA224withECDSA, SHA224withRSA, SHA1withECDSA, SHA1withRSA, SHA1withDSA, MD5withRSA
Extension server_name, server_name: [type=host_name (0), value=www.mytotalconnectcomfort.com]
***
[write] MD5 and SHA1 hashes:  len = 219
0000: 01 00 00 D7 03 03 55 B7   DA 2B B3 44 C6 89 07 C5  ......U..+.D....
0010: 0D 6A 03 BB 63 A0 75 A4   30 E2 71 88 A6 C7 65 52  .j..c.u.0.q...eR
0020: C3 C0 2E 34 8C B5 00 00   2C C0 0A C0 14 00 35 C0  ...4....,.....5.
0030: 05 C0 0F 00 39 00 38 C0   09 C0 13 00 2F C0 04 C0  ....9.8...../...
0040: 0E 00 33 00 32 C0 08 C0   12 00 0A C0 03 C0 0D 00  ..3.2...........
0050: 16 00 13 00 FF 01 00 00   82 00 0A 00 34 00 32 00  ............4.2.
0060: 17 00 01 00 03 00 13 00   15 00 06 00 07 00 09 00  ................
0070: 0A 00 18 00 0B 00 0C 00   19 00 0D 00 0E 00 0F 00  ................
0080: 10 00 11 00 02 00 12 00   04 00 05 00 14 00 08 00  ................
0090: 16 00 0B 00 02 01 00 00   0D 00 1A 00 18 06 03 06  ................
00A0: 01 05 03 05 01 04 03 04   01 03 03 03 01 02 03 02  ................
00B0: 01 02 02 01 01 00 00 00   22 00 20 00 00 1D 77 77  ........". ...ww
00C0: 77 2E 6D 79 74 6F 74 61   6C 63 6F 6E 6E 65 63 74  w.mytotalconnect
00D0: 63 6F 6D 66 6F 72 74 2E   63 6F 6D                 comfort.com
ESH-safeCall-2, WRITE: TLSv1.2 Handshake, length = 219
[Raw write]: length = 224
0000: 16 03 03 00 DB 01 00 00   D7 03 03 55 B7 DA 2B B3  ...........U..+.
0010: 44 C6 89 07 C5 0D 6A 03   BB 63 A0 75 A4 30 E2 71  D.....j..c.u.0.q
0020: 88 A6 C7 65 52 C3 C0 2E   34 8C B5 00 00 2C C0 0A  ...eR...4....,..
0030: C0 14 00 35 C0 05 C0 0F   00 39 00 38 C0 09 C0 13  ...5.....9.8....
0040: 00 2F C0 04 C0 0E 00 33   00 32 C0 08 C0 12 00 0A  ./.....3.2......
0050: C0 03 C0 0D 00 16 00 13   00 FF 01 00 00 82 00 0A  ................
0060: 00 34 00 32 00 17 00 01   00 03 00 13 00 15 00 06  .4.2............
0070: 00 07 00 09 00 0A 00 18   00 0B 00 0C 00 19 00 0D  ................
0080: 00 0E 00 0F 00 10 00 11   00 02 00 12 00 04 00 05  ................
0090: 00 14 00 08 00 16 00 0B   00 02 01 00 00 0D 00 1A  ................
00A0: 00 18 06 03 06 01 05 03   05 01 04 03 04 01 03 03  ................
00B0: 03 01 02 03 02 01 02 02   01 01 00 00 00 22 00 20  .............". 
00C0: 00 00 1D 77 77 77 2E 6D   79 74 6F 74 61 6C 63 6F  ...www.mytotalco
00D0: 6E 6E 65 63 74 63 6F 6D   66 6F 72 74 2E 63 6F 6D  nnectcomfort.com
[Raw read]: length = 5
0000: 15 03 00 00 02                                     .....
[Raw read]: length = 2
0000: 02 46                                              .F
ESH-safeCall-2, READ: SSLv3 Alert, length = 2
ESH-safeCall-2, RECV TLSv1.2 ALERT:  fatal, protocol_version
ESH-safeCall-2, called closeSocket()
ESH-safeCall-2, handling exception: javax.net.ssl.SSLException: Received fatal alert: protocol_version

4 个答案:

答案 0 :(得分:3)

  

*** ClientHello,TLSv1.2

您正在使用TLS 1.2。但遗憾的是服务器完全不了解TLS 1.2并且会导致握手失败。我的analyze-ssl.pl节目测试显示:

 * supported SSL versions with handshake used and preferred cipher(s):
  * handshake protocols ciphers
  * SSLv23    TLSv1     RC4-MD5
  * TLSv1_2   FAILED: SSL connect attempt failed error:1408F10B:SSL routines:SSL3_GET_RECORD:wrong version number
  * TLSv1_1   FAILED: SSL connect attempt failed error:1408F10B:SSL routines:SSL3_GET_RECORD:wrong version number
  * TLSv1     TLSv1     RC4-MD5
  * SSLv3     FAILED: SSL connect attempt failed because of handshake problems error:1409442E:SSL routines:SSL3_READ_BYTES:tlsv1 alert protocol version

因此,服务器只是在TLSv1_2握手时失败。

您正尝试在代码中设置TLS 1.0:

        SSLContext ctx = SSLContexts.custom().useProtocol("TLSv1").build();

不幸的是the documentation声明“TLSv1”不仅是TLS 1.0而是

TLSv1   Supports RFC 2246: TLS version 1.0 ; may support other versions

因此它尝试使用最好的版本(TLS1.2)并因为服务器坏了而失败。 BTW,Chrome和Firefox只能成功,因为他们会针对此类错误重试较低的协议版本。我自己不做Java,但根据我在网上找到的各种文档,你可能需要做类似的事情:

   sslSocket.setEnabledProtocols(new String[] {"SSLv2Hello", "TLSv1" })

应删除对TLS1.1和TLS1.2的支持。

答案 1 :(得分:3)

Steffen,

That answer got me on the right track. For anyone else that has a future problem, here is some code that works to force an Apache HttpClient to use TLSv1:

CloseableHttpClient httpclient;
        try {

            SSLContext ctx = SSLContexts.createSystemDefault();

            SSLConnectionSocketFactory fac = new SSLConnectionSocketFactory(ctx, new String[] { "TLSv1" }, null,
                    SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

            httpclient = HttpClientBuilder.create().setSSLSocketFactory(fac).build();

            HttpPost httpPost = new HttpPost("https://mytotalconnectcomfort.com/portal/");
            List<NameValuePair> fields = new ArrayList<NameValuePair>();
            fields.add(new BasicNameValuePair("UserName", userName));
            fields.add(new BasicNameValuePair("Password", passWord));

            httpPost.setEntity(new UrlEncodedFormEntity(fields));
            CloseableHttpResponse resp = httpclient.execute(httpPost);

            logger.debug("Status line: {}", resp.getStatusLine());
            // } catch (IOException | NoSuchAlgorithmException | KeyManagementException e) {
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

答案 2 :(得分:1)

快速解决方案(Java 8):-Djdk.tls.client.protocols=TLSv1

详细信息:我遇到了与我的应用程序相同的问题。这是使用-Djavax.net.debug=ssl:handshake

的客户端视图
myScheduler-1, WRITE: TLSv1.2 Handshake, length = 189 
myScheduler-1, READ: TLSv1 Alert, length = 2 
myScheduler-1, RECV TLSv1.2 ALERT: fatal, protocol_version 
myScheduler-1, called closeSocket()
myScheduler-1, handling exception: javax.net.ssl.SSLException: Received fatal alert: protocol_version

我的WebLogic服务器(10.3.6)仅支持TLSv1。将客户端升级到Java 8后,它将不再使用SSL进行身份验证(如上所示)。项目Web客户端是Apache http客户端的旧版本(4.1.3)。 Java 8添加了新的系统属性jdk.tls.client.protocols,允许用户设置可用的JSSE协议。有关详细信息,请参阅http://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html#InstallationAndCustomization 在Java 8升级之后,客户端将不再接受服务器响应的TLSv1握手,并且将失败,如图所示。我将-Djdk.tls.client.protocols=TLSv1添加到客户端启动,重新启动客户端,问题立即得到解决。请注意,我确实按https://blogs.oracle.com/java-platform-group/entry/diagnosing_tls_ssl_and_https尝试了https.protocols系统属性,但它对我不起作用。我假设它失败了,因为我正在使用Apache,并且正如页面说明的那样,它与

有关
  

通过使用HttpsURLConnection类或通过https连接   URL.openStream()操作

但我没有广泛地测试它。

答案 3 :(得分:0)

我正在将apache-tomcat- 7.0.70 jdk1.7.0_45 结合使用,而这里和其他关于stackoverflow的解决方案都没有对我有用。只是共享此解决方案,因为它有望对某人有所帮助,因为这在Google搜索中非常重要

这两个步骤都有效:

  1. 通过将tomcat添加到tomcat / bin / setenv.sh(在Windows上语法稍有不同),以“ export JAVA_OPTS =“ $ JAVA_OPTS -Dhttps.protocols = TLSv1.2”开始我的tomcat。

  2. 使用TLS1.2协议手动构建/强制HttpClient或您需要执行的其他任何操作:

    Context ctx = SSLContexts.custom().useProtocol("TLSv1.2").build();
    HttpClient httpClient = HttpClientBuilder.create().setSslcontext(ctx).build();
    HttpPost httppost = new HttpPost(scsTokenVerificationUrl);
    
    List<NameValuePair> paramsAccessToken = new ArrayList<NameValuePair>(2);
    paramsAccessToken.add(new BasicNameValuePair("token", token));
    paramsAccessToken.add(new BasicNameValuePair("client_id", scsClientId));
    paramsAccessToken.add(new BasicNameValuePair("secret", scsClientSecret));
    httppost.setEntity(new UrlEncodedFormEntity(paramsAccessToken, "utf-8"));
    
    //Execute and get the response.
    HttpResponse httpResponseAccessToken = httpClientAccessToken.execute(httppost);
    
    String responseJsonAccessToken = EntityUtils.toString(httpResponseAccessToken.getEntity());
    
相关问题