How to connect to an HTTPS URL from a JavaFX application - java

I have a Javafx application that sends GET and POST requests to a secure web service via HTTPS. The SSL setup on the server hosting the webservices is one-way ssl, i.e. the Javafx application validates the server's identity but the server does not validate the thick client's identity.
The application server is behind an F5 that has the certificates(signed by an external authority).
For a browser this would not have been a problem as the browser itself handles validating the server's identity and displays the relevant warning to the user. But for a thick client, I am not sure how to validate the server's identity before sending the request. Please let me know how to handle this in a Javafx application.
I did ask a question relating to this earlier here and here, but those did not help. So, please pardon my limited knowledge on this topic.
Any help would be appreciated.

If your certificate don't work in Firefox/java, most likely it issuer is unknown by Firefox/java.
How to make it work:
Get full certificate chain of your server. You can do it with Firefox. View certificate -> details-> export to .pem file. In your case chain will contain at least 2 certificate (cerver cert and CA cert, CA possible self-signed or maybe not) Export CA certificate in .pem file.
Now you can force java to trust that CA, it can be done in various ways, for example, you can add CA certificate in jre cacerts or create custom SSLContext for HttpsURLConnection.
If you do DNS or etc.hosts modification, rollback it. Connection address should match with certificate CN, include wildcards.
Use that code to connect to your server:
public void test() throws Exception {
URL u = new URL(
"https://my-server.com/my-webservices/data");
HttpsURLConnection http = (HttpsURLConnection) u.openConnection();
http.setSSLSocketFactory(createSSLContext().getSocketFactory());
http.setAllowUserInteraction(true);
http.setRequestMethod("GET");
http.connect();
InputStream is = http.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
stringBuilder.append(line
+ "\n");
}
System.out.println(stringBuilder.toString());
}
private SSLContext createSSLContext() throws Exception {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
FileInputStream in = new FileInputStream("path_to_ca_file.pem");
KeyStore trustStore = KeyStore.getInstance("JKS");
trustStore.load(null);
try {
X509Certificate cacert = (X509Certificate) cf.generateCertificate(in);
trustStore.setCertificateEntry("ca", cacert);
} finally {
IOUtils.closeQuietly(in);
}
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(trustStore);
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, tmf.getTrustManagers(), new SecureRandom());
return sslContext;
}

Related

Secure Sockets in Java without CA [duplicate]

A module I'm adding to our large Java application has to converse with another company's SSL-secured website. The problem is that the site uses a self-signed certificate. I have a copy of the certificate to verify that I'm not encountering a man-in-the-middle attack, and I need to incorporate this certificate into our code in such a way that the connection to the server will be successful.
Here's the basic code:
void sendRequest(String dataPacket) {
String urlStr = "https://host.example.com/";
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setMethod("POST");
conn.setRequestProperty("Content-Length", data.length());
conn.setDoOutput(true);
OutputStreamWriter o = new OutputStreamWriter(conn.getOutputStream());
o.write(data);
o.flush();
}
Without any additional handling in place for the self-signed certificate, this dies at conn.getOutputStream() with the following exception:
Exception in thread "main" 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
....
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
....
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
Ideally, my code needs to teach Java to accept this one self-signed certificate, for this one spot in the application, and nowhere else.
I know that I can import the certificate into the JRE's certificate authority store, and that will allow Java to accept it. That's not an approach I want to take if I can help; it seems very invasive to do on all of our customer's machines for one module they may not use; it would affect all other Java applications using the same JRE, and I don't like that even though the odds of any other Java application ever accessing this site are nil. It's also not a trivial operation: on UNIX I have to obtain access rights to modify the JRE in this way.
I've also seen that I can create a TrustManager instance that does some custom checking. It looks like I might even be able to create a TrustManager that delegates to the real TrustManager in all instances except this one certificate. But it looks like that TrustManager gets installed globally, and I presume would affect all other connections from our application, and that doesn't smell quite right to me, either.
What is the preferred, standard, or best way to set up a Java application to accept a self-signed certificate? Can I accomplish all of the goals I have in mind above, or am I going to have to compromise? Is there an option involving files and directories and configuration settings, and little-to-no code?
Create an SSLSocket factory yourself, and set it on the HttpsURLConnection before connecting.
...
HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
conn.setSSLSocketFactory(sslFactory);
conn.setMethod("POST");
...
You'll want to create one SSLSocketFactory and keep it around. Here's a sketch of how to initialize it:
/* Load the keyStore that includes self-signed cert as a "trusted" entry. */
KeyStore keyStore = ...
TrustManagerFactory tmf =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keyStore);
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, tmf.getTrustManagers(), null);
sslFactory = ctx.getSocketFactory();
If you need help creating the key store, please comment.
Here's an example of loading the key store:
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(trustStore, trustStorePassword);
trustStore.close();
To create the key store with a PEM format certificate, you can write your own code using CertificateFactory, or just import it with keytool from the JDK (keytool won't work for a "key entry", but is just fine for a "trusted entry").
keytool -import -file selfsigned.pem -alias server -keystore server.jks
I read through LOTS of places online to solve this thing.
This is the code I wrote to make it work:
ByteArrayInputStream derInputStream = new ByteArrayInputStream(app.certificateString.getBytes());
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(derInputStream);
String alias = "alias";//cert.getSubjectX500Principal().getName();
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null);
trustStore.setCertificateEntry(alias, cert);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(trustStore, null);
KeyManager[] keyManagers = kmf.getKeyManagers();
TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
tmf.init(trustStore);
TrustManager[] trustManagers = tmf.getTrustManagers();
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers, trustManagers, null);
URL url = new URL(someURL);
conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(sslContext.getSocketFactory());
app.certificateString is a String that contains the Certificate, for example:
static public String certificateString=
"-----BEGIN CERTIFICATE-----\n" +
"MIIGQTCCBSmgAwIBAgIHBcg1dAivUzANBgkqhkiG9w0BAQsFADCBjDELMAkGA1UE" +
"BhMCSUwxFjAUBgNVBAoTDVN0YXJ0Q29tIEx0ZC4xKzApBgNVBAsTIlNlY3VyZSBE" +
... a bunch of characters...
"5126sfeEJMRV4Fl2E5W1gDHoOd6V==\n" +
"-----END CERTIFICATE-----";
I have tested that you can put any characters in the certificate string, if it is self signed, as long as you keep the exact structure above. I obtained the certificate string with my laptop's Terminal command line.
If creating a SSLSocketFactory is not an option, just import the key into the JVM
Retrieve the public key:
$openssl s_client -connect dev-server:443, then create a file dev-server.pem that looks like
-----BEGIN CERTIFICATE-----
lklkkkllklklklklllkllklkl
lklkkkllklklklklllkllklkl
lklkkkllklk....
-----END CERTIFICATE-----
Import the key: #keytool -import -alias dev-server -keystore $JAVA_HOME/jre/lib/security/cacerts -file dev-server.pem.
Password: changeit
Restart JVM
Source: How to solve javax.net.ssl.SSLHandshakeException?
We copy the JRE's truststore and add our custom certificates to that truststore, then tell the application to use the custom truststore with a system property. This way we leave the default JRE truststore alone.
The downside is that when you update the JRE you don't get its new truststore automatically merged with your custom one.
You could maybe handle this scenario by having an installer or startup routine that verifies the truststore/jdk and checks for a mismatch or automatically updates the truststore. I don't know what happens if you update the truststore while the application is running.
This solution isn't 100% elegant or foolproof but it's simple, works, and requires no code.
I've had to do something like this when using commons-httpclient to access an internal https server with a self-signed certificate. Yes, our solution was to create a custom TrustManager that simply passed everything (logging a debug message).
This comes down to having our own SSLSocketFactory that creates SSL sockets from our local SSLContext, which is set up to have only our local TrustManager associated with it. You don't need to go near a keystore/certstore at all.
So this is in our LocalSSLSocketFactory:
static {
try {
SSL_CONTEXT = SSLContext.getInstance("SSL");
SSL_CONTEXT.init(null, new TrustManager[] { new LocalSSLTrustManager() }, null);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Unable to initialise SSL context", e);
} catch (KeyManagementException e) {
throw new RuntimeException("Unable to initialise SSL context", e);
}
}
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
LOG.trace("createSocket(host => {}, port => {})", new Object[] { host, new Integer(port) });
return SSL_CONTEXT.getSocketFactory().createSocket(host, port);
}
Along with other methods implementing SecureProtocolSocketFactory. LocalSSLTrustManager is the aforementioned dummy trust manager implementation.

Java Rest Client using self-signed Certificate

Hello I'm trying to write a little Rest client which accesses our Cloud server (Rest Webservices). The connection is secured with a SSL Client Certificate which if I understand correctly is not signedby any Certification Authority, and am having problems.
I know that the certificate works fine as I can use this in other programming languages (e.g. C#, PHP, etc), and also because I am testing the API using Postman, however I cannot really understand how to do this in Java.
I have tried using the P12 certificate file, and I also have .key and .crt files, but still nothing changed. The .JKS file I have created using keytool.exe, and I presume it is correct (as far as I could understand).
This is the code I am using :
String keyPassphrase = certPwd;
KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(new FileInputStream("C:\\Test\\Certificate\\idscertificate.jks"), keyPassphrase.toCharArray());
SSLContext sslContext = SSLContexts.custom()
.loadKeyMaterial(keyStore, certPwd.toCharArray())
.build();
HttpClient httpClient = HttpClients.custom().setSslcontext(sslContext).build();
HttpResponse response = httpClient.execute(new HttpGet(
"https://url_that_I_am_using_to_call_my_rest_web_service"));
but every time I launch this I get an error:
"unable to find valid certification path to requested target".
As far as I could see this is because I don't have a Certification Authority to specify, am I correct?
Can anyone help me with this?
Thank you all for your help
Tommaso
/*******************
This is how I imported the P12 into the Keystore. I tried different ways, the last one i tried was:
First created the JKS:
keytool -genkey -alias myName -keystore c:\Test\Certificate\mykeystoreName.jks
then "cleaned up with:
keytool -delete -alias myName -keystore c:\Test\Certificate\myKeystoreName.jks
then imported the P12 file with:
keytool -v -importkeystore -srckeystore c:\Test\Certificate\idscertificate.p12 -srcstoretype PKCS12 -destkeystore c:\Test\Certificate\myKeystoreName.jks -deststoretype JKS
Result obtained:
Entry for alias idsclientcertificate successfully imported.
Import command completed: 1 entries successfully imported, 0 entries failed or cancelled
and if I check the content of the keystore I find my imported certificate.
Nevertheless I still get the same error.
Thank you for your help.
/****************************Update February 8th *******************
Ok I tried everything, but really everything and now slowly giving up... the situation is the following:
using the following code so far:
SSLContextBuilder sslContext = new SSLContextBuilder();
sslContext.loadKeyMaterial(readKeyStore(), userPwd.toCharArray());
//sslContext.loadTrustMaterial(readKeyStore(), new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslContext.build());
CloseableHttpClient client = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.setSSLHostnameVerifier(new NoopHostnameVerifier())
.build();
HttpGet httpGet = new HttpGet("https://myhost.com/myrest/status");
httpGet.addHeader("Accept", "application/json;charset=UTF8");
httpGet.addHeader("Cookie", "sessionids=INeedThis");
String encoded = Base64.getEncoder().encodeToString((userName+":"+userPwd).getBytes(StandardCharsets.UTF_8));
httpGet.addHeader("Authorization", "Basic "+encoded);
httpGet.addHeader("Cache-Control", "no-cache");
HttpResponse response = client.execute(httpGet);
Unfortunately still not working. I tried the following: - include my certificate in the default java cacerts, - specify the alias as my host name, - create a new jks, - load the p12 file, still nothing, same error.
Error Message I get is:
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
If I don't use a certificate, I get another error indicating that the certificate is missing therefore the certificate is loaded (also I see it in my IDE).
If I use the exact same certificate file from another platform (c# or using a browser) I get the correct response and object (therefore the certificate/password are valid)
Is there any way that I can stop the validation of the certification path?
first of all thank you all for your help. I finally got it to work following these steps:
1 - I determined my root CA Cert using command:
openssl s_client -showcerts -connect my.root.url.com:443
then I imported this certificate using Portecle.exe (https://sourceforge.net/projects/portecle/) but you can also import it using the normal keytool command, into my default Java Keystore (jre/lib/security/cacerts)
--> Make sure you assign the root URL as Alias (e.g. *.google.com if you would connect to a google API). This seems to be very important.
Then I used the following code:
First created the ServerSocketFactory:
private static SSLSocketFactory getSocketFactory()
{
try
{
SSLContext context = SSLContext.getInstance("TLS");
// Create a key manager factory for our personal PKCS12 key file
KeyManagerFactory keyMgrFactory = KeyManagerFactory.getInstance("SunX509");
KeyStore keyStore = KeyStore.getInstance("PKCS12");
char[] keyStorePassword = pk12Password.toCharArray(); // --> This is the Password for my P12 Client Certificate
keyStore.load(new FileInputStream(pk12filePath), keyStorePassword); // --> This is the path to my P12 Client Certificate
keyMgrFactory.init(keyStore, keyStorePassword);
// Create a trust manager factory for the trust store that contains certificate chains we need to trust
// our remote server (I have used the default jre/lib/security/cacerts path and password)
TrustManagerFactory trustStrFactory = TrustManagerFactory.getInstance("SunX509");
KeyStore trustStore = KeyStore.getInstance("JKS");
char[] trustStorePassword = jksTrustStorePassword.toCharArray(); // --> This is the Default password for the Java KEystore ("changeit")
trustStore.load(new FileInputStream(trustStorePath), trustStorePassword);
trustStrFactory.init(trustStore);
// Make our current SSL context use our customized factories
context.init(keyMgrFactory.getKeyManagers(),
trustStrFactory.getTrustManagers(), null);
return context.getSocketFactory();
}
catch (Exception e)
{
System.err.println("Failed to create a server socket factory...");
e.printStackTrace();
return null;
}
}
Then I created the connection using:
public static void launchApi()
{
try
{
// Uncomment this if your server cert is not signed by a trusted CA
HostnameVerifier hv = new HostnameVerifier()
{
public boolean verify(String urlHostname, SSLSession session)
{
return true;
}};
HttpsURLConnection.setDefaultHostnameVerifier(hv);
URL url = new URL("https://myRootUrl.com/to/launch/api");
HttpsURLConnection.setDefaultSSLSocketFactory(getSocketFactory());
HttpsURLConnection urlConn = (HttpsURLConnection)url.openConnection();
String encoded = Base64.getEncoder().encodeToString((userName+":"+userPwd).getBytes(StandardCharsets.UTF_8)); //Acc User Credentials if needed to log in
urlConn.setRequestProperty ("Authorization", "Basic "+encoded);
urlConn.setRequestMethod("GET"); // Specify all needed Request Properties:
urlConn.setRequestProperty("Accept", "application/json;charset=UTF8");
urlConn.setRequestProperty("Cache-Control", "no-cache");
urlConn.connect();
/* Dump what we have found */
BufferedReader in =
new BufferedReader(
new InputStreamReader(urlConn.getInputStream()));
String inputLine = null;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
This is what worked for me. Thank you all, and also thanks to:
this article that guided me on the right direction
Ciao
Instead of using loadKeyMaterial use loadTrustMaterial, the first one is for creating a SSLContext for a server, and the second one is for a client.
Example:
SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial(keyStore, new TrustSelfSignedStrategy())
.build();

Java oAuth using self-signed client certificate

I had a perfectly working oauth with a self-signed client certificate, until suddenly it stopped working. I get SocketException: Connection Reset. According to Xero, the API that I'm integrating with, everything is ok on their side now, but they did have SSL problem one week ago.
Since the last time it worked we moved to Java 8, which I rolledback for this test.
Initially I had it working with this oauth project, because it was the only one that would, kind of, support self-signed client certificates.
Today I hacked Scribe a bit, in order to add the certificate to the request. When I finally got it working, I got the same exception again.
The certificate that I have is in a KeyStore (.p12), which I exported into my java cacerts. This step should not be needed though, since it was working without it.
So, this is how I create the SSLContext that is injected in the HttpClient (in the oauth project) and in the HttpsUrlConnection (in Scribe).
Set<KeyManager> keymanagers = new HashSet<KeyManager>();
final KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
KeyManagerFactory.getDefaultAlgorithm());
kmfactory.init(entrustStore, password.toCharArray());
final KeyManager[] kms = kmfactory.getKeyManagers();
if (kms != null) {
for (final KeyManager km : kms) {
keymanagers.add(km);
}
}
// TrustManagerFactory tmf =
// TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
// tmf.init(keyStore);
SSLContext sslContext = SSLContext.getInstance(SSLSocketFactory.TLS);
sslContext.init(
keymanagers.toArray(new KeyManager[keymanagers.size()]),
null, // tmf.getTrustManagers()
null);
// in the oauth project
SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext);
Scheme scheme = new Scheme("https", 443, socketFactory);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(scheme);
BasicClientConnectionManager cm =
new BasicClientConnectionManager(schemeRegistry);
httpClient = new DefaultHttpClient(cm);
// ---------------------------------
// in Scribe
HttpsURLConnection connection =
(HttpsURLConnection) new URL(completeUrl).openConnection();
connection.setSSLSocketFactory(sslContext.getSocketFactory());
I suspect this is the code that might be causing the exception, since this is the only common part between both implementations.
The issue was related to TLS version after all. Using TLSv1.1 did the trick.

How do I update the SSL cert in my android apps?

Recently I work on the project that has implemented the SSL.
The SSL cert is expire once per year. And it throw exception in android after I renew the cert on the server.
06-13 11:20:27.709: D/allenj(30076): javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
After I looking through the project code, I saw there is a bks file, so , does it mean I have to update the bks file once per year, and I have to re-upload the app to google play as well.
The problem is what is the standard way to cope with the renewal of the SSL cert? Thanks for helping.
Code extract
nnable Register_runnable = new Runnable(){
#Override
public void run() {
EditText emailText = (EditText) findViewById(R.id.editText1regist);
EditText pwText = (EditText) findViewById(R.id.editText2registpw);
String end = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
try {
KeyStore keyStore = KeyStore.getInstance("BKS");
InputStream in =
getResources().openRawResource(R.raw.ballooncardbks);
keyStore.load(in, "".toCharArray());
TrustManagerFactory tmf =
TrustManagerFactory.getInstance("X509");
tmf.init(keyStore);
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
String actionUrl = "https://app.ballooncard.com/api/client/register/format/json";
URL url = new URL(actionUrl);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
// con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestMethod("POST");
con.setSSLSocketFactory(context.getSocketFactory());
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
Looks like the app is using "certificate pinning", which means that a certificate has been hardcoded into the app, and the app has been instructed to accept only that certificate and no other.
This increases security at the expense that you need to update your app when (ideally before) the certificate expires. You can following the instructions from a post I created here:
https://stackoverflow.com/a/24007536/276949
to generate a new .bks file from your certificate. Once this is done, overwrite your old .bks file and your app should successfully connect via SSL.
Apps by default trust the pre-installed system Certificate Authorities (CA), like this example:
https://www.digitalocean.com/community/tutorials/retrofit-android-example-tutorial
Check if you really need to use certificate pinning (https://owasp.org/www-community/controls/Certificate_and_Public_Key_Pinning) in your application.
In case you want to disable Certificate Pinning, delete android:networkSecurityConfig line from AndroidManifest.xml and/or comment domain-config block from network_security_config.xml

Java Keystore reload whilst in runtime [duplicate]

A module I'm adding to our large Java application has to converse with another company's SSL-secured website. The problem is that the site uses a self-signed certificate. I have a copy of the certificate to verify that I'm not encountering a man-in-the-middle attack, and I need to incorporate this certificate into our code in such a way that the connection to the server will be successful.
Here's the basic code:
void sendRequest(String dataPacket) {
String urlStr = "https://host.example.com/";
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setMethod("POST");
conn.setRequestProperty("Content-Length", data.length());
conn.setDoOutput(true);
OutputStreamWriter o = new OutputStreamWriter(conn.getOutputStream());
o.write(data);
o.flush();
}
Without any additional handling in place for the self-signed certificate, this dies at conn.getOutputStream() with the following exception:
Exception in thread "main" 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
....
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
....
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
Ideally, my code needs to teach Java to accept this one self-signed certificate, for this one spot in the application, and nowhere else.
I know that I can import the certificate into the JRE's certificate authority store, and that will allow Java to accept it. That's not an approach I want to take if I can help; it seems very invasive to do on all of our customer's machines for one module they may not use; it would affect all other Java applications using the same JRE, and I don't like that even though the odds of any other Java application ever accessing this site are nil. It's also not a trivial operation: on UNIX I have to obtain access rights to modify the JRE in this way.
I've also seen that I can create a TrustManager instance that does some custom checking. It looks like I might even be able to create a TrustManager that delegates to the real TrustManager in all instances except this one certificate. But it looks like that TrustManager gets installed globally, and I presume would affect all other connections from our application, and that doesn't smell quite right to me, either.
What is the preferred, standard, or best way to set up a Java application to accept a self-signed certificate? Can I accomplish all of the goals I have in mind above, or am I going to have to compromise? Is there an option involving files and directories and configuration settings, and little-to-no code?
Create an SSLSocket factory yourself, and set it on the HttpsURLConnection before connecting.
...
HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
conn.setSSLSocketFactory(sslFactory);
conn.setMethod("POST");
...
You'll want to create one SSLSocketFactory and keep it around. Here's a sketch of how to initialize it:
/* Load the keyStore that includes self-signed cert as a "trusted" entry. */
KeyStore keyStore = ...
TrustManagerFactory tmf =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keyStore);
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, tmf.getTrustManagers(), null);
sslFactory = ctx.getSocketFactory();
If you need help creating the key store, please comment.
Here's an example of loading the key store:
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(trustStore, trustStorePassword);
trustStore.close();
To create the key store with a PEM format certificate, you can write your own code using CertificateFactory, or just import it with keytool from the JDK (keytool won't work for a "key entry", but is just fine for a "trusted entry").
keytool -import -file selfsigned.pem -alias server -keystore server.jks
I read through LOTS of places online to solve this thing.
This is the code I wrote to make it work:
ByteArrayInputStream derInputStream = new ByteArrayInputStream(app.certificateString.getBytes());
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(derInputStream);
String alias = "alias";//cert.getSubjectX500Principal().getName();
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null);
trustStore.setCertificateEntry(alias, cert);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(trustStore, null);
KeyManager[] keyManagers = kmf.getKeyManagers();
TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
tmf.init(trustStore);
TrustManager[] trustManagers = tmf.getTrustManagers();
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers, trustManagers, null);
URL url = new URL(someURL);
conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(sslContext.getSocketFactory());
app.certificateString is a String that contains the Certificate, for example:
static public String certificateString=
"-----BEGIN CERTIFICATE-----\n" +
"MIIGQTCCBSmgAwIBAgIHBcg1dAivUzANBgkqhkiG9w0BAQsFADCBjDELMAkGA1UE" +
"BhMCSUwxFjAUBgNVBAoTDVN0YXJ0Q29tIEx0ZC4xKzApBgNVBAsTIlNlY3VyZSBE" +
... a bunch of characters...
"5126sfeEJMRV4Fl2E5W1gDHoOd6V==\n" +
"-----END CERTIFICATE-----";
I have tested that you can put any characters in the certificate string, if it is self signed, as long as you keep the exact structure above. I obtained the certificate string with my laptop's Terminal command line.
If creating a SSLSocketFactory is not an option, just import the key into the JVM
Retrieve the public key:
$openssl s_client -connect dev-server:443, then create a file dev-server.pem that looks like
-----BEGIN CERTIFICATE-----
lklkkkllklklklklllkllklkl
lklkkkllklklklklllkllklkl
lklkkkllklk....
-----END CERTIFICATE-----
Import the key: #keytool -import -alias dev-server -keystore $JAVA_HOME/jre/lib/security/cacerts -file dev-server.pem.
Password: changeit
Restart JVM
Source: How to solve javax.net.ssl.SSLHandshakeException?
We copy the JRE's truststore and add our custom certificates to that truststore, then tell the application to use the custom truststore with a system property. This way we leave the default JRE truststore alone.
The downside is that when you update the JRE you don't get its new truststore automatically merged with your custom one.
You could maybe handle this scenario by having an installer or startup routine that verifies the truststore/jdk and checks for a mismatch or automatically updates the truststore. I don't know what happens if you update the truststore while the application is running.
This solution isn't 100% elegant or foolproof but it's simple, works, and requires no code.
I've had to do something like this when using commons-httpclient to access an internal https server with a self-signed certificate. Yes, our solution was to create a custom TrustManager that simply passed everything (logging a debug message).
This comes down to having our own SSLSocketFactory that creates SSL sockets from our local SSLContext, which is set up to have only our local TrustManager associated with it. You don't need to go near a keystore/certstore at all.
So this is in our LocalSSLSocketFactory:
static {
try {
SSL_CONTEXT = SSLContext.getInstance("SSL");
SSL_CONTEXT.init(null, new TrustManager[] { new LocalSSLTrustManager() }, null);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("Unable to initialise SSL context", e);
} catch (KeyManagementException e) {
throw new RuntimeException("Unable to initialise SSL context", e);
}
}
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
LOG.trace("createSocket(host => {}, port => {})", new Object[] { host, new Integer(port) });
return SSL_CONTEXT.getSocketFactory().createSocket(host, port);
}
Along with other methods implementing SecureProtocolSocketFactory. LocalSSLTrustManager is the aforementioned dummy trust manager implementation.

Categories

Resources