javax.net.ssl.SSLPeerUnverifiedException: Hostname not verified:

CROSP picture CROSP · Jun 10, 2015 · Viewed 29.6k times · Source

I am trying to use HTTPS connection with self-signed certificate.
I have followed steps of creating self-signed certificate as mentioned here - Creating Self-signed certificate.
Everything works fine even in browser, it only shows me a message that my certificate is signed by unknown CA.
But I have problem with my FQDN(server name doesn't match) name in certificate because I have set incorrect name while generating certificate.
I have regenerated it and now no such error.

I need to use my server sertificate from mobile Android Client, I have found great article about this problem - Use Retrofit with a self-signed or unknown SSL certificate in Android. I have followed all steps, but unfortunately get an error (exception).

javax.net.ssl.SSLPeerUnverifiedException: Hostname 195.xx.xx.xx not verified:
    certificate: sha1/qvH7lFeijE/ZXxNHI0B/M+AU/aA=
    DN: 1.2.840.113549.1.9.1=#160e63726f73704078616b65702e7275,CN=195.xx.xx.xx,OU=Departament of Development,O=CROSP Solutions,L=Chernihiv,ST=Chernihiv,C=UA
    subjectAltNames: []
            at com.squareup.okhttp.internal.http.SocketConnector.connectTls(SocketConnector.java:124)

As you can see hostname are the same, but error is still present.
Please help to deal with this problem, I will be grateful for any help.
Thank you.

PSEUDO-SOLUTION

Of course I searched before and found HostName Verifier Solution.
I have tried it, it works. But is it OK to use this workaround, I added certificate into my app in order to read it dynamicly as in the prior example, is it still being used in this case.

Solution with OkHttp is one line. (If you followed all steps in tutorial).

 okHttpClient.setHostnameVerifier(new NullHostNameVerifier());

But I still feel that it is not the best solution, please any thoughts ?

Answer

ZhongYu picture ZhongYu · Jun 10, 2015

Interestingly, if the request host is an IP, "CN" is not used to match it; instead,

http://tools.ietf.org/html/rfc2818#section-3.1

the iPAddress subjectAltName must be present in the certificate and must exactly match the IP in the URI"

If you use java's keytool, it can be done by

keytool -genkeypair  -ext SAN=IP:195.xx.xx.xx    ........

NullHostNameVerifier is also ok for you use case. You client is trusting only one certificate; as long as the connection uses that certificate, you are secure; host name doesn't matter here.