SSLHandshakeException while connecting to HTTPS site - java

I'm creating in Java HttpsURLConnection. I downloaded certificates from website and created file truststore.jks with this certs. My application is getting certs from truststore.jks and connecting to website. And it works... on my PC. But after deploy application on server I got this ugly exception:
Cause: javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
Stack trace:
[sun.security.ssl.Alerts.getSSLException(Unknown Source)
sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
sun.security.ssl.Handshaker.fatalSE(Unknown Source)
sun.security.ssl.Handshaker.fatalSE(Unknown Source)
sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source)
sun.security.ssl.ClientHandshaker.processMessage(Unknown Source)
sun.security.ssl.Handshaker.processLoop(Unknown Source)
sun.security.ssl.Handshaker.process_record(Unknown Source)
sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
I'm creating HttpsURLConnection in ConnectionFactory class, and running connection.getInputStream() method.
ConnectionFactory.java:
public final class ConnectionFactory {
public HttpsURLConnection getHttpsURLConnection(URL url, String trustStorePath, String trustStorePassword)
throws FileTransferWorkerException {
KeyStore keyStore = loadKeyStore(trustStorePath, trustStorePassword);
TrustManagerFactory trustManagerFactory = initTrustManagerFactory(keyStore);
SSLSocketFactory sslSocketFactory = buildSSLSocketFactory(trustManagerFactory);
return buildConnection(url, sslSocketFactory);
}
private KeyStore loadKeyStore(String path, String password) throws FileTransferWorkerException {
KeyStore keystore;
try {
keystore = KeyStore.getInstance("JKS");
} catch (KeyStoreException e) {
throw new FileTransferWorkerException(e);
}
try (FileInputStream fileInputStream = new FileInputStream(path)) {
keystore.load(fileInputStream, password.toCharArray());
} catch (IOException | CertificateException | NoSuchAlgorithmException e) {
throw new FileTransferWorkerException("Can not load keyStore from " + path, e);
}
return keystore;
}
private TrustManagerFactory initTrustManagerFactory(KeyStore keyStore) throws FileTransferWorkerException {
TrustManagerFactory trustManagerFactory;
try {
trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
} catch (NoSuchAlgorithmException e) {
throw new FileTransferWorkerException(e);
}
try {
trustManagerFactory.init(keyStore);
} catch (KeyStoreException e) {
throw new FileTransferWorkerException(e);
}
return trustManagerFactory;
}
private SSLSocketFactory buildSSLSocketFactory(TrustManagerFactory trustManagerFactory) throws FileTransferWorkerException {
SSLContext sslContext;
try {
sslContext = SSLContext.getInstance("TLS");
} catch (NoSuchAlgorithmException e) {
throw new FileTransferWorkerException(e);
}
try {
sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
} catch (KeyManagementException e) {
throw new FileTransferWorkerException(e);
}
return sslContext.getSocketFactory();
}
private HttpsURLConnection buildConnection(URL url, SSLSocketFactory sslSocketFactory) throws FileTransferWorkerException {
HttpsURLConnection connection;
try {
connection = (HttpsURLConnection) url.openConnection();
} catch (IOException e) {
throw new FileTransferWorkerException("Can not connect to " + url.getPath(), e);
}
connection.setSSLSocketFactory(sslSocketFactory);
return connection;
}
}
and invoke method:
private void download(URL url, String trustStorePath, String trustStorePassword, File file)
throws IOException, FileTransferWorkerException {
HttpsURLConnection connection = new ConnectionFactory().getHttpsURLConnection(url, trustStorePath, trustStorePassword);
try (ReadableByteChannel reader = Channels.newChannel(connection.getInputStream()){
...
} finally {
connection.disconnect();
}
}
I need to use my truststor.jks file, not cacerts. Do you have any ideas where I made a mistake? Help.

I figured it. Locally I'm connected to my company's network and I have their certificates (because of proxy). But server isn't using proxy and should have real certificates from endpoint server.

Related

Consume REST API using java - SSLHandshakeException

I am trying to consume a REST API using Java. however, when I run the code it shows me this exception.
I didn't understand what does it mean, I try to search for the solution but I can't get it :(
this is the connection code:
import javax.ws.rs.core.MediaType;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
public class connectToAPI {
public static void main(String[] args) {
try{
URL url = new URL("https://ip:port/rest/path");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
String userpassword = "user:pass";
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization","Basic "+
userpassword);
conn.setRequestProperty("Content-Type","application/json");
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.flush();
int status = 0;
if( null != conn ){
status = conn.getResponseCode();
}
if( status != 0){
System.out.println("status!=0");
if( status == 200 ){
System.out.println("status==200");
//SUCCESS message
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
}else if(status == 401){
System.out.println("status==401");
}else if(status == 501){
System.out.println("status==501");
}else if( status == 503){
System.out.println("status==503");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
when I run the code it shows me this exception:
javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No subject alternative names matching IP address ip found
at sun.security.ssl.Alerts.getSSLException(Unknown Source)
at sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
at sun.security.ssl.Handshaker.fatalSE(Unknown Source)
at sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source)
at sun.security.ssl.ClientHandshaker.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.startHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(Unknown Source)
at alert.connectToBAM.main(connectToBAM.java:77)
Caused by: java.security.cert.CertificateException: No subject
alternative names matching IP address ip found
at sun.security.util.HostnameChecker.matchIP(Unknown Source)
at sun.security.util.HostnameChecker.match(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.checkIdentity(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.checkIdentity(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.checkTrusted(Unknown Source)
at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
... 14 more
I also tried jersey clinet:
javax.ws.rs.client.Client client = ClientBuilder.newClient();
WebTarget target = client.target("https://ip:port/rest/path");
System.out.println(
target.request(MediaType.APPLICATION_JSON).get(String.class));
it shows this error:
Exception in thread "main" javax.ws.rs.ProcessingException:
javax.net.ssl.SSLHandshakeException:
java.security.cert.CertificateException: No subject alternative names
matching IP address ip found
at org.glassfish.jersey.client.internal.HttpUrlConnector.apply(HttpUrlConnector.java:284)
at org.glassfish.jersey.client.ClientRuntime.invoke(ClientRuntime.java:278)
at org.glassfish.jersey.client.JerseyInvocation.lambda$invoke$1(JerseyInvocation.java:767)
at org.glassfish.jersey.internal.Errors.process(Errors.java:316)
at org.glassfish.jersey.internal.Errors.process(Errors.java:298)
at org.glassfish.jersey.internal.Errors.process(Errors.java:229)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:414)
at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:765)
at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:428)
at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:324)
at alert.connectToBAM.main(connectToBAM.java:47)
Any idea? pleaseeee, it is my graduation project :(
javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException
Generally these type of exceptions are occurs due to certificate verification issue of the certificate, follow the below steps :
1. Download the certificate from the browser and add it to cacerts file in the jre folder
2. we need to add some java code to verify the certificate using TrustManager.
Code is given below :
public static void trustManager()
{
try
{
TrustManager[] trustAllCerts = new TrustManager[]
{
new X509TrustManager()
{
#Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// TODO Auto-generated method stub
}
#Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
// TODO Auto-generated method stub
}
#Override
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
}
}
};
//Create an Instance for SSLContext class
SSLContext sc = SSLContext.getInstance("SSL");
//overload init method
sc.init(null, trustAllCerts, new java.security.SecureRandom());
//Use static method setDefaultSSLSocketFactory
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
//Create Instance for Hostname verifier and override verify() method
HostnameVerifier allHostsValid = new HostnameVerifier() {
#Override
public boolean verify(String arg0, SSLSession arg1)
{
return true;
}
};
//Verify hostname using static method setDefaultHostnameVerifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
}
catch(Exception e)
{
e.printStackTrace();
}
}
Whenever you are trying to execute just call this method at first in main method. Hope this will help you :)

javax.net.ssl.SSLHandshakeException: null cert chain java error

Am trying to establish an ssl connection.I have a Server and I have a client. I have both of them running on the same machine. am trying to establish an SSL connection between the client and the server. i have generated certificates for both the server and the client with the following keytool command.
For Client
keytool -keystore clientstore -genkey -alias client -validity 3650
Then i export the root certificate of the client to a cer file callled client.cer
For Server
keytool -keystore serverstore -genkey -alias server -validity 3650 Then i export the root certificate of the server to a cer file callled server.cer
I now import the client certificate "client.cer" into the serverstore keystore with the following command
keytool -import -keystore serverstore -file client.cer -alias client
And also import the servers certificate "server.cer" into the clientstore keystore with the following command
keytool -import -keystore clientstore -file server.cer -alias server
After doing this, i imported both the server.cer and client.cer into the cacerts Keystore. But when i try to establish an ssl connection, i get this error on the server javax.net.ssl.SSLHandshakeException: null cert chain and this error on the client javax.net.ssl.SSLHandshakeException: Received fatal alert: bad_certificate.
My Servers Code.
package serverapplicationssl;
import java.io.*;
import java.security.KeyStore;
import java.security.Security;
import java.security.PrivilegedActionException;
import javax.net.ssl.*;
import com.sun.net.ssl.internal.ssl.Provider;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import java.security.Security;
import java.io.*;
public class ServerApplicationSSL {
public static void main(String[] args) {
boolean debug = true;
System.out.println("Waiting For Connection");
int intSSLport = 4447;
{
Security.addProvider(new Provider());
}
if (debug) {
System.setProperty("javax.net.debug", "all");
}
FileWriter file = null;
try {
file = new FileWriter("C:\\SSLCERT\\Javalog.txt");
} catch (Exception ee) {
//message = ee.getMessage();
}
try {
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(new FileInputStream("C:\\SSLCERT\\OntechServerKS"), "server".toCharArray());
file.write("Incoming Connection\r\n");
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory
.getDefaultAlgorithm());
kmf.init(keystore, "server".toCharArray());
SSLContext context = SSLContext.getInstance("TLS");
context.init(kmf.getKeyManagers(), null, null);
SSLServerSocketFactory sslServerSocketfactory = (SSLServerSocketFactory) context.getServerSocketFactory();
SSLServerSocket sslServerSocket = (SSLServerSocket) sslServerSocketfactory.createServerSocket(intSSLport);
sslServerSocket.setEnabledCipherSuites(sslServerSocket.getSupportedCipherSuites());
sslServerSocket.setNeedClientAuth(true);
SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
//SSLServerSocket server_socket = (SSLServerSocket) sslServerSocket;
sslSocket.startHandshake();
// Start the session
System.out.println("Connection Accepted");
file.write("Connection Accepted\r\n");
while (true) {
PrintWriter out = new PrintWriter(sslSocket.getOutputStream(), true);
String inputLine;
//while ((inputLine = in.readLine()) != null) {
out.println("Hello Client....Welcome");
System.out.println("Hello Client....Welcome");
//}
out.close();
//in.close();
sslSocket.close();
sslServerSocket.close();
file.flush();
file.close();
}
} catch (Exception exp) {
try {
System.out.println(exp.getMessage() + "\r\n");
exp.printStackTrace();
file.write(exp.getMessage() + "\r\n");
file.flush();
file.close();
} catch (Exception eee) {
//message = eee.getMessage();
}
}
}
}
Here's My Clients Code
import java.io.*;
import java.net.*;
import java.security.*;
import java.util.Enumeration;
import javax.net.ssl.*;
public class SSLConnect {
public String MakeSSlCall(String meternum) {
String message = "";
FileWriter file = null;
try {
file = new FileWriter("C:\\SSLCERT\\ClientJavalog.txt");
} catch (Exception ee) {
message = ee.getMessage();
}
//writer = new BufferedWriter(file );
try {
file.write("KeyStore Generated\r\n");
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(new FileInputStream("C:\\SSLCERT\\SkyeClientKS"), "client".toCharArray());
file.write("KeyStore Generated\r\n");
Enumeration enumeration = keystore.aliases();
while (enumeration.hasMoreElements()) {
String alias = (String) enumeration.nextElement();
file.write("alias name: " + alias + "\r\n");
keystore.getCertificate(alias);
file.write(keystore.getCertificate(alias).toString() + "\r\n");
}
TrustManagerFactory tmf =TrustManagerFactory.getInstance("SunX509");
tmf.init(keystore);
file.write("KeyStore Stored\r\n");
SSLContext context = SSLContext.getInstance("SSL");
TrustManager[] trustManagers = tmf.getTrustManagers();
context.init(null, trustManagers, null);
SSLSocketFactory f = context.getSocketFactory();
file.write("About to Connect to Ontech\r\n");
SSLSocket c = (SSLSocket) f.createSocket("192.168.1.16", 4447);
file.write("Connection Established to 196.14.30.33 Port: 8462\r\n");
file.write("About to Start Handshake\r\n");
c.startHandshake();
file.write("Handshake Established\r\n");
file.flush();
file.close();
return "Connection Established";
} catch (Exception e) {
try {
file.write("An Error Occured\r\n");
file.write(e.getMessage() + "\r\n");
StackTraceElement[] arrmessage = e.getStackTrace();
for (int i = 0; i < arrmessage.length; i++) {
file.write(arrmessage[i] + "\r\n");
}
file.flush();
file.close();
} catch (Exception eee) {
message = eee.getMessage();
}
return "Connection Failed";
}
}
}
Stack Trace Execption on my Server
javax.net.ssl.SSLHandshakeException: null cert chain
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1937)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:292)
at sun.security.ssl.ServerHandshaker.clientCertificate(ServerHandshaker.java:1804)
at sun.security.ssl.ServerHandshaker.processMessage(ServerHandshaker.java:222)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:957)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:892)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1050)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1363)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1391)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1375)
at serverapplicationssl.ServerApplicationSSL.main(ServerApplicationSSL.java:69)
Stack Trace Execption on my client
Received fatal alert: bad_certificate
sun.security.ssl.Alerts.getSSLException(Unknown Source)
sun.security.ssl.Alerts.getSSLException(Unknown Source)
sun.security.ssl.SSLSocketImpl.recvAlert(Unknown Source)
sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
SSLConnect.MakeSSlCall(SSLConnect.java:96)
BankCollectSSLCon.main(BankCollectSSLCon.java:13)
What could be causing this error?, could it be because i am running both the server and the client on the same machine?...Been on this for quite a while now. i need help
Please try to include this code snippet so that all the certificates will be trusted.
public static void trustSelfSignedSSL() {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] xcs, String string)
throws CertificateException {}
public void checkServerTrusted(X509Certificate[] xcs, String string)
throws CertificateException {}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLContext.setDefault(ctx);
} catch (Exception ex) {
// LOGGER.error("Exception : ", ex.getStackTrace());
System.out.println(ex.getStackTrace());
}

javax.net.ssl.SSLHandshakeException: Received fatal alert: unknown_ca

I have to connect to a server via SSL dual authentication. I have added my own private key plus certificate to a keystore.jks and the self signed certificate of the server to a truststore.jks, both files are copied to /usr/share/tomcat7. The socket factory used by my code is delivered by the following provider:
#Singleton
public static class SecureSSLSocketFactoryProvider implements Provider<SSLSocketFactory> {
private SSLSocketFactory sslSocketFactory;
public SecureSSLSocketFactoryProvider() throws RuntimeException {
try {
final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
final InputStream trustStoreFile = new FileInputStream("/usr/share/tomcat7/truststore.jks");
trustStore.load(trustStoreFile, "changeit".toCharArray());
final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(trustStore);
final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
final InputStream keyStoreFile = new FileInputStream("/usr/share/tomcat7/keystore.jks");
keyStore.load(keyStoreFile, "changeit".toCharArray());
final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, "changeit".toCharArray());
final SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
this.sslSocketFactory = sslContext.getSocketFactory();
} catch (final KeyStoreException e) {
Log.error("Key store exception: {}", e.getMessage(), e);
} catch (final CertificateException e) {
Log.error("Certificate exception: {}", e.getMessage(), e);
} catch (final UnrecoverableKeyException e) {
Log.error("Unrecoverable key exception: {}", e.getMessage(), e);
} catch (final NoSuchAlgorithmException e) {
Log.error("No such algorithm exception: {}", e.getMessage(), e);
} catch (final KeyManagementException e) {
Log.error("Key management exception: {}", e.getMessage(), e);
} catch (final IOException e) {
Log.error("IO exception: {}", e.getMessage(), e);
}
}
#Override
public SSLSocketFactory get() {
return sslSocketFactory;
}
}
When I try to connect to an endpoint on the server I get the following exception though:
javax.net.ssl.SSLHandshakeException: Received fatal alert: unknown_ca
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192) ~[na:1.7.0_45]
at sun.security.ssl.Alerts.getSSLException(Alerts.java:154) ~[na:1.7.0_45]
at sun.security.ssl.SSLSocketImpl.recvAlert(SSLSocketImpl.java:1959) ~[na:1.7.0_45]
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1077) ~[na:1.7.0_45]
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1312) ~[na:1.7.0_45]
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339) ~[na:1.7.0_45]
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1323) ~[na:1.7.0_45]
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:563) ~[na:1.7.0_45]
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185) ~[na:1.7.0_45]
at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:153) ~[na:1.7.0_45]
Any idea what I have missed here?
If you get an alert unknown_ca back from the server, then the server did not like the certificate you've send as the client certificate, because it is not signed by a CA which is trusted by the server for client certificates.

SSL Connection fail through Proxy server(mod_proxy) using java(Axis2)

I am using Java(Axis2) to connect .net web service.
I created stub class from WSDL2Java Converter.
Proxy Server : Apache mod_proxy
below all cases are working with the C# code but getting error with the Java(Axis2)
(SSL = true, Proxy = false : Success)
(SSl = false, Proxy = true : Success)
(SSL = true, Proxy = true : Fail (class javax.net.ssl.SSLException))
ServiceStub objStub = new ServiceStub(sWebServiceURL);
      objStub._getServiceClient().getOptions().setProperty(org.apache.axis2.transport.http.HTTPConstants.CHUNKED, Boolean.FALSE);
objStub._getServiceClient().getOptions().setProperty("customCookieID",DEF_COOKIEID);
objStub._getServiceClient().getOptions().setManageSession(true);
objConfigSetting = new DCAServiceConfigSetting();
nSocketTimeout = 30000;
objStub._getServiceClient().getOptions().setProperty(org.apache.axis2.transport.http.HTTPConstants.SO_TIMEOUT, new Integer(nSocketTimeout));
//Setting the authentication for web service
setServiceAuthentication(objStub, objConnSetting.getAuthenticationInfo());
//Setting Proxy properties
if(objConnSetting.getProxySettingStatus() == true)
{
setProxyProperties(objStub, objConnSetting.getProxySettingInfo());
}
if(objConnSetting.getWebServiceURL().contains("https://"))
{
if(objConnSetting.getWithoutSSLSerCertificateStatus() == true)
{
Protocol objProtocol = new Protocol("https", new MySocketFactory(), 443);
objStub._getServiceClient().getOptions().setProperty(org.apache.axis2.transport.http.HTTPConstants.CUSTOM_PROTOCOL_HANDLER, objProtocol);
}
// command to set proxy setting
objStub._getServiceClient().getOptions().setProperty(org.apache.axis2.transport.http.HTTPConstants.PROXY, objProxyProperties);
// Inside MySocketFactory class ----------------------------------------------
public Socket createSocket(final String host,
final int port,
final InetAddress localAddress,
final int localPort,
final HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException
{
if (params == null){
throw new IllegalArgumentException("Parameters may not be null");
}
int timeout = params.getConnectionTimeout();
SocketFactory socketfactory = getSSLContext().getSocketFactory();
if (timeout == 0)
{
return socketfactory.createSocket(host, port, localAddress, localPort);
}
else
{
Socket socket = socketfactory.createSocket();
SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
SocketAddress remoteaddr = new InetSocketAddress(host, port);
socket.bind(localaddr);
socket.connect(remoteaddr, timeout);
return socket;
}
}
// Also
private static SSLContext createEasySSLContext()
{
try
{
SSLContext context = SSLContext.getInstance("SSL");
context.init(null, new TrustManager[] {new NaiveTrustManager()}, null);
return context;
}
catch (Exception e)
{
LOG.error(e.getMessage(), e);
throw new HttpClientError(e.toString());
}
}
Detail Error log
Exception Message: Unrecognized SSL message, plaintext connection?
Stack Trace: org.apache.axis2.AxisFault: Unrecognized SSL message, plaintext connection?
at org.apache.axis2.AxisFault.makeFault(AxisFault.java:430)
at org.apache.axis2.transport.http.AxisRequestEntity.writeRequest(AxisRequestEntity.java:98)
at org.apache.commons.httpclient.methods.EntityEnclosingMethod.writeRequestBody(EntityEnclosingMethod.java:499)
at org.apache.commons.httpclient.HttpMethodBase.writeRequest(HttpMethodBase.java:2114)
at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1096)
at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:398)
at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)
at org.apache.axis2.transport.http.AbstractHTTPSender.executeMethod(AbstractHTTPSender.java:621)
at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:193)
at org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:75)
at org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:404)
at org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:231)
at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:443)
at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:406)
at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:229)
at org.apache.axis2.client.OperationClient.execute(OperationClient.java:165)
at WebService.ServiceStub.calWebFunction(ServiceStub.java:1892)
Caused by:
javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
at sun.security.ssl.InputRecord.handleUnknownRecord(Unknown Source)
at sun.security.ssl.InputRecord.read(Unknown Source)
at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.writeRecord(Unknown Source)
at sun.security.ssl.AppOutputStream.write(Unknown Source)
at java.io.BufferedOutputStream.flushBuffer(Unknown Source)
at java.io.BufferedOutputStream.flush(Unknown Source)
at java.io.FilterOutputStream.flush(Unknown Source)
at org.apache.axis2.transport.http.AxisRequestEntity.writeRequest(AxisRequestEntity.java:94) ... 20 more
Apache access.log
10.128.43.60 - - [24/Sep/2013:13:49:02 +0900] "\x16\x03\x01" 501 215
Please reply ASAP

How to call the https get method on a self signed server and client certificate

I have set up the Apache tomcat 5 to support ssl. Created self signed certificates and imported the client certificate into the trusstore of the server and imported the p12 file into the browser and accessing the page on the https is possible. How to achieve the same using java ?
Following is the code that i am attempting with but without any success...
//reference : http://vafer.org/blog/20061010073725/ http://www.mkyong.com/java/java-//https-client-httpsurlconnection-example/
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLPeerUnverifiedException;
import java.security.cert.Certificate;
public class HttpClientTutorial {
#SuppressWarnings("unused")
private static javax.net.ssl.SSLSocketFactory getFactory( File pKeyFile, String pKeyPassword ) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException, UnrecoverableKeyException, KeyManagementException
{
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
KeyStore keyStore = KeyStore.getInstance("PKCS12");
InputStream keyInput = new FileInputStream(pKeyFile);
keyStore.load(keyInput, pKeyPassword.toCharArray());
keyInput.close();
keyManagerFactory.init(keyStore, pKeyPassword.toCharArray());
SSLContext context = SSLContext.getInstance("TLS");
context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());
return context.getSocketFactory();
}
private static void print_https_cert(HttpsURLConnection con){
if(con!=null){
try {
System.out.println("Response Code : " + con.getResponseCode());
System.out.println("Cipher Suite : " + con.getCipherSuite());
System.out.println("\n");
Certificate[] certs = con.getServerCertificates();
for(Certificate cert : certs){
System.out.println("Cert Type : " + cert.getType());
System.out.println("Cert Hash Code : " + cert.hashCode());
System.out.println("Cert Public Key Algorithm : " + cert.getPublicKey().getAlgorithm());
System.out.println("Cert Public Key Format : " + cert.getPublicKey().getFormat());
System.out.println("\n");
}
} catch (SSLPeerUnverifiedException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
}
}
private static void print_content(HttpsURLConnection con){
if(con!=null){
try {
System.out.println("****** Content of the URL ********");
BufferedReader br =
new BufferedReader(
new InputStreamReader(con.getInputStream()));
String input;
while ((input = br.readLine()) != null){
System.out.println(input);
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException, UnrecoverableKeyException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException {
URL url = new URL("https://localhost:8443/SpringSec2");
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setSSLSocketFactory(getFactory(new File("src/Client.p12"), "client"));
//dumpl all cert info
print_https_cert(con);
//dump all the content
print_content(con);
}
}
***************************************************************************************
Exception:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Unknown Source)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(Unknown Source)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at java.net.HttpURLConnection.getResponseCode(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(Unknown Source)
Since you are doing self signed certificate, you need to provide your own TrustManager. The line in your code
SSLContext context = SSLContext.getInstance("TLS");
context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());
The second parameter in context.init is the TrustManager to manage which server you can trust. You basically need to create your own extension X509TrustManager. An example of that code can be found at http://www.howardism.org/Technical/Java/SelfSignedCerts.html. Search for NaiveTrustManager, you'll see that checkServerTrusted() is not implemented which implies it trusts everything. Try that first and see if that works. After it does, you might want to consider implementing stronger check.

Categories

Resources