I have an android app which is listening for socket connections and can read httpheaders (send by a browser(works all good!)). Now I wont to switch to SSL sockets but I can't get it done.
things I got working:
Keystore
ServerSocketFactory
things I not got working (and where I need help):
Client accept part
code:
public void run() {
try {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(service.getBaseContext().getResources().openRawResource(R.raw.keystore),"password".toCharArray());
ServerSocketFactory socketFactory = SSLServerSocketFactory
.getDefault();
SSLServerSocket mServerSocket = (SSLServerSocket) socketFactory
.createServerSocket(8080);
while (!mServerSocket.isClosed()) {
mServerSocket.setEnabledCipherSuites(mServerSocket.getSupportedCipherSuites());
mServerSocket.setEnabledProtocols(mServerSocket.getSupportedProtocols());
System.out.println("waiting");
SSLSocket client = (SSLSocket) mServerSocket.accept();
client.addHandshakeCompletedListener(new HandshakeCompletedListener(){
public void handshakeCompleted(HandshakeCompletedEvent arg0) {
System.out.println("handshakeCompleted");
}
});
client.startHandshake(); //MultiThreadWebServer.java:136
client.getOutputStream().flush();
client.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
Exception:
11-29 11:15:01.046: W/System.err(29941): javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0x4fec3da8: Failure in SSL library, usually a protocol error
11-29 11:15:01.046: W/System.err(29941): error:1408A0C1:SSL routines:SSL3_GET_CLIENT_HELLO:no shared cipher (external/openssl/ssl/s3_srvr.c:1365 0x41b1e7f8:0x00000000)
11-29 11:15:01.046: W/System.err(29941): at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:436)
11-29 11:15:01.046: W/System.err(29941): at at.aichinger.mario.aws.MultiThreadWebServer.run(MultiThreadWebServer.java:136)
to connect to the server I use google cheome and access "https://192.168.0.25:8080" if I do so the Exception gets throwen.
Code in line MultiThreadWebServer.java:136:
client.startHandshake();
First of all, these two lines do not make any sense. If you want to restrict supported cipher suites and protocols, define them specifically. But you have to be careful about that not all cipher suites are supported by browsers.
mServerSocket.setEnabledCipherSuites(mServerSocket.getSupportedCipherSuites());
mServerSocket.setEnabledProtocols(mServerSocket.getSupportedProtocols());
The problem in your code is that you are not using your keystore. Try this:
public void run() {
try {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(service.getBaseContext().getResources().openRawResource(R.raw.keystore),
"password".toCharArray());
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, "password".toCharArray());
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(keyManagerFactory.getKeyManagers(), null, null);
ServerSocketFactory socketFactory = sslContext.getServerSocketFactory();
SSLServerSocket mServerSocket = (SSLServerSocket) socketFactory.createServerSocket(8080);
while (!mServerSocket.isClosed()) {
System.out.println("waiting");
SSLSocket client = (SSLSocket) mServerSocket.accept();
client.addHandshakeCompletedListener(new HandshakeCompletedListener() {
public void handshakeCompleted(HandshakeCompletedEvent arg0) {
System.out.println("handshakeCompleted");
}
});
client.startHandshake(); // MultiThreadWebServer.java:136
client.getOutputStream().flush();
client.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
Instead of using keystore as default type, always define the type of keystore which you will use in your application. Otherwise There may be the chance where keystore mismatch will happen between server and client.
Related
I tried to secure the connection to my java server, after downloading a certificate(certificate.crt) and adding it to the keystore (keystore.jks) my server run normally and read the certificate.But if I want to consume a service via https://123.456.88.99:1010/myService from the navigator(firefox) I get a PR_END_OF_FILE_ERROR The page you are trying to view cannot be shown because the authenticity of the received data could not be verified.ps : http://123.456.88.99:1010/myService works and consume the service and retrieve data also by using firefox, I think its a problem of private key that the navigator don't get, I really need help, thank you
ps if I try to use a certificate that I create using keytool it works
private void startHttpsServer(RestFactory factory, int port, int minWorkers, int maxWorkers, int socketTimeoutMS,
boolean keepConnection, boolean ignoreContentLength, boolean debug, Compression compression, boolean useClassicServer, boolean requireCertificate) throws Exception {
String alias = "server-alias";
String pwd = "changeit";
char [] storepass = pwd.toCharArray();
String keystoreName = "c:\\keystore.jks";
FileInputStream in = new FileInputStream(keystoreName);
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(in, storepass);
Certificate cert = keystore.getCertificate(alias);
Log.debug("the certification is here : " + cert);
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
char [] keypass = pwd.toCharArray();
kmf.init(keystore, keypass);
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keystore);
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
SSLEngine engine = sslContext.createSSLEngine();
engine.setEnabledCipherSuites(new String[] {"TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
"TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256",
"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256"});
SSLParameters defaultSSLParameters = sslContext.getDefaultSSLParameters();
engine.setSSLParameters(defaultSSLParameters);
HttpsRestServer server = new HttpsRestServer(factory, port, minWorkers, maxWorkers, debug, compression, keystore, keypass, false);
server.addCleaner(new CleanupListener() {
#Override
public void cleanup(CleanupEvent event) {
Database.disconnectAllThreadConnections(event.thread, false);
}
});
this.servers.add(server);
log.info("Starting classic HTTPS replication server on port " + port);
server.start();
log.info("Secure XML replication server started on port " + port);
}
i found some tutorial to handle with https server and a https client. i created some keystore and it works fine. But i have some question which is not clear from the tutorial.
this is my https-server
public class HTTPSServer {
private int port = 9999;
private boolean isServerDone = false;
public static void main(String[] args) {
HTTPSServer server = new HTTPSServer();
server.run();
}
HTTPSServer() {
}
HTTPSServer(int port) {
this.port = port;
}
// Create the and initialize the SSLContext
private SSLContext createSSLContext() {
try {
//Returns keystore object in definied type, here jks
KeyStore keyStore = KeyStore.getInstance("JKS");
//loads the keystore from givin input stream, and the password to unclock jks
keyStore.load(new FileInputStream("x509-ca.jks"), "password".toCharArray());
// Create key manager
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
keyManagerFactory.init(keyStore, "password".toCharArray());
KeyManager[] km = keyManagerFactory.getKeyManagers();
// Create trust manager
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
trustManagerFactory.init(keyStore);
TrustManager[] tm = trustManagerFactory.getTrustManagers();
// opens a secure socket with definied protocol
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
//System.out.println(keyStore.getCertificate("root").getPublicKey());
//System.out.println(keyStore.isKeyEntry("root"));
sslContext.init(km, tm, null);
return sslContext;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
// Start to run the server
public void run() {
SSLContext sslContext = this.createSSLContext();
try {
// Create server socket factory
SSLServerSocketFactory sslServerSocketFactory = sslContext.getServerSocketFactory();
// Create server socket
SSLServerSocket sslServerSocket = (SSLServerSocket) sslServerSocketFactory.createServerSocket(this.port);
System.out.println("SSL server started");
while (!isServerDone) {
SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
// Start the server thread
new ServerThread(sslSocket).start();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
// Thread handling the socket from client
static class ServerThread extends Thread {
private SSLSocket sslSocket = null;
ServerThread(SSLSocket sslSocket) {
this.sslSocket = sslSocket;
}
public void run() {
sslSocket.setEnabledCipherSuites(sslSocket.getSupportedCipherSuites());
//System.out.println("HIER: " + sslSocket.getHandshakeSession());
//Klappt nicht, auch nicht, wenn der Client diese Zeile ebenfalls besitzt
//sslSocket.setEnabledCipherSuites(new String[]{"TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256"});
try {
// Start handshake
sslSocket.startHandshake();
// Get session after the connection is established
SSLSession sslSession = sslSocket.getSession();
System.out.println(sslSession.getPeerHost());
System.out.println(sslSession.getLocalCertificates());
System.out.println("\tProtocol : " + sslSession.getProtocol());
System.out.println("\tCipher suite : " + sslSession.getCipherSuite());
System.out.println("\tSession context : " + sslSession.getSessionContext());
//System.out.println("\tPeer pricipal of peer : " + sslSession.getPeerPrincipal());
// Start handling application content
InputStream inputStream = sslSocket.getInputStream();
OutputStream outputStream = sslSocket.getOutputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(outputStream));
String line = null;
String[] suites = sslSocket.getSupportedCipherSuites();
for (int i = 0; i < suites.length; i++) {
//System.out.println(suites[i]);
//System.out.println(sslSession.getCipherSuite());
}
while ((line = bufferedReader.readLine()) != null) {
System.out.println("Inut : " + line);
if (line.trim().isEmpty()) {
break;
}
}
// Write data
printWriter.print("HTTP/1.1 200\r\n");
printWriter.flush();
sslSocket.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
And this is my output:
SSL server started
127.0.0.1
null
Protocol : TLSv1.2
Cipher suite : TLS_DH_anon_WITH_AES_128_GCM_SHA256
Session context : sun.security.ssl.SSLSessionContextImpl#781df1a4
I want to know, why the line
System.out.println(sslSession.getLocalCertificates());
prints out "null"?
Thank you a lot, Mira
From the documentation:
Certificate[] getLocalCertificates()
Returns the certificate(s) that were sent to the peer during handshaking.
Note: This method is useful only when using certificate-based cipher suites.
When multiple certificates are available for use in a handshake, the implementation chooses what it considers the "best" certificate chain available, and transmits that to the other side. This method allows the caller to know which certificate chain was actually used.
Returns:
an ordered array of certificates, with the local certificate first followed by any certificate authorities. If no certificates were sent, then null is returned.
The part we care about is "Returns the certificate(s) that were sent to the peer during handshaking.", and "This method is useful only when using certificate-based cipher suites.".
Given that it is returning null, we can assume you are not sending any certificates to the client. But it's also HTTPS, so what gives? Well, it looks like you're using TLS_DH_anon_WITH_AES_128_GCM_SHA256, which is, as the name suggests, anonymous. As per the OpenSSL Wiki:
Anonymous Diffie-Hellman uses Diffie-Hellman, but without authentication. Because the keys used in the exchange are not authenticated, the protocol is susceptible to Man-in-the-Middle attacks. Note: if you use this scheme, a call to SSL_get_peer_certificate will return NULL because you have selected an anonymous protocol. This is the only time SSL_get_peer_certificate is allowed to return NULL under normal circumstances.
While this is applicable to OpenSSL, it would appear to be the same in Java - that is, you're not using a certificate-based cipher. Someone with more knowledge of TLS would need to jump in, but it looks like AES keys are generated, and they're sent to the client, but the client has no assurance those keys came from you, whereas normally you would generate the keys, and then sign / encrypt (not 100% sure) those keys with an RSA key to prove they came from you.
To fix this, I believe you would need to select a different cipher suite, e.g. TLS_RSA_WITH_AES_128_GCM_SHA256. I'm not 100% sure how you would do this, but that would appear to be the solution.
sslSocket.setEnabledCipherSuites(sslSocket.getSupportedCipherSuites());
You are enabling all the anonymous and low-grade cipher suites, so you are allowing the server not to send a certificate, so it doesn't send one, so it doesn't give you one in getLocalCertificates().
Remove this line.
For some reasons Parse users must migrate their Parse environment to a VPS (this is the case for my question) or Heroku, AWS (don't need these platforms), etc. There is a new Parse SDK for Android (1.13.0) which allows to initialize connection using the new Parse interface, as follows:
Parse.initialize(new Parse.Configuration.Builder(this)
.applicationId("myAppId")
.clientKey(null)
.addNetworkInterceptor(new ParseLogInterceptor())
.server("https://VPS_STATIC_IP_ADDRESS/parse/").build());
This kind of request is done using the port 443. The appropriate .js (nodejs) connector file has already been edited so that port 443 is locally connected to port 1337 (port-listener) and it works when accessing Parse Server in browser (remotely, of course: from outside VPS) where it's possible to apply a self-signed certificate and go further. But when an Android app (launcher) tries to connect it, it cannot because of self-signed certificate. Is there any possibility from within Parse SDK to apply a self-signed certificate?
P.S. Is it true that there's a bug concerning this issue and that this is the reason why 1.13.1 Parse version has been released? If yes, where is it possible to get the jar-library of this version?
Thank you!
I just solved this one -
Parse SDK for android does not come with out of the box support in SelfSigned certificates.
You need to modify the code yourself.
First Step - The relevant piece of code is in ParseHttpClient
public static ParseHttpClient createClient(int socketOperationTimeout,
SSLSessionCache sslSessionCache) {
String httpClientLibraryName;
ParseHttpClient httpClient;
if (hasOkHttpOnClasspath()) {
httpClientLibraryName = OKHTTP_NAME;
httpClient = new ParseOkHttpClient(socketOperationTimeout, sslSessionCache);
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
httpClientLibraryName = URLCONNECTION_NAME;
httpClient = new ParseURLConnectionHttpClient(socketOperationTimeout, sslSessionCache);
} else {
httpClientLibraryName = APACHE_HTTPCLIENT_NAME;
httpClient = new ParseApacheHttpClient(socketOperationTimeout, sslSessionCache);
}
PLog.i(TAG, "Using " + httpClientLibraryName + " library for networking communication.");
return httpClient; }
If your target support is for version more advanced then KITKAT -
Then you need to add in ParseURLConnectionHttpClient constructor:
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier(){
public boolean verify(String hostname, SSLSession session) {
if(hostname.equals("YOUR TARGET SERVER")) {
return true;
}
return false;
}});
In other cases (older versions) the code will fall to the Apache, I was not able to work with it- so I did the following: I added the okhttp library to my app (take version 2.4 - the same one parse indicates in the build , the most recent has different package name) and then the code will step into the first condition since it will find okhttp on the Path.
You should probably replace the if conditions order so it will happen only on versions less then KITKAT.
In ParseOkHttpClient add the following selfsigned certificate code:
public void initCert() {
try {
Log.i("PARSE","initCert");
CertificateFactory cf = CertificateFactory.getInstance("X.509");
String yairCert = "-----BEGIN CERTIFICATE-----\n" +
YOUR CERTIFICATE HERE
"-----END CERTIFICATE-----\n";
InputStream caInput = new ByteArrayInputStream(yairCert.getBytes());
Certificate ca = null;
try {
ca = cf.generateCertificate(caInput);
System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
} catch (CertificateException e) {
e.printStackTrace();
} finally {
try {
caInput.close();
} catch (IOException e) {
Log.e("PARSE_BUG","Failure on Cert installing",e);
e.printStackTrace();
}
}
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
Log.i("PARSE","Initiating Self Signed cert");
okHttpClient.setSslSocketFactory(context.getSocketFactory());
try {
cf = CertificateFactory.getInstance("X.509");
} catch (CertificateException e) {
Log.e("PARSE_BUG","Failure on Cert installing",e);
e.printStackTrace();
}
} catch (IOException e) {
Log.e("PARSE_BUG","Failure on Cert installing",e);
e.printStackTrace();
} catch (CertificateException e) {
Log.e("PARSE_BUG","Failure on Cert installing",e);
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
Log.e("PARSE_BUG","Failure on Cert installing",e);
e.printStackTrace();
} catch (KeyStoreException e) {
Log.e("PARSE_BUG","Failure on Cert installing",e);
e.printStackTrace();
} catch (KeyManagementException e) {
Log.e("PARSE_BUG","Failure on Cert installing",e);
e.printStackTrace();
}
And the final part is the calling this method + verifying hostname , it should happen in the Constructor too.
initCert();
okHttpClient.setHostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String s, SSLSession sslSession) {
if(s.equals("YOUR TARGET SERVER")) {
return true;
}
return false;
}
});
Thats it. Build PARSE locally and deploy to your app and it will work like a charm.
Enjoy
I set system properties for a SSL-enabled MySQL client, which worked fine:
System.setProperty("javax.net.ssl.trustStore","truststore");
System.setProperty("javax.net.ssl.trustStorePassword","12345");
String url = "jdbc:mysql://abc.com:3306/test?" +
"user=abc&password=123" +
"&useUnicode=true" +
"&characterEncoding=utf8&useSSL=true"
A couple days ago I found the client couldn't connect to another web site in which a commercially signed SSL certificate is installed. Obviously the overriding keystores didn't work with regular https connections.
Then I decided to build my version of SocketFactory based on StandardSocketFactory.java in MySQL Connector/J source.
I added a method to create Socket objects in public Socket connect(String hostname, int portNumber, Properties props) method.
private Socket createSSLSocket(InetAddress address, int port) {
Socket socket;
try {
InputStream trustStream = new FileInputStream(new File("truststore"));
KeyStore trustStore = KeyStore.getInstance("JKS");
// load the stream to your store
trustStore.load(trustStream, trustPassword);
// initialize a trust manager factory with the trusted store
TrustManagerFactory trustFactory = TrustManagerFactory.getInstance("PKIX", "SunJSSE"); trustFactory.init(trustStore);
// get the trust managers from the factory
TrustManager[] trustManagers = trustFactory.getTrustManagers();
// initialize an ssl context to use these managers and set as default
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustManagers, null);
if(address == null) {
socket = sslContext.getSocketFactory().createSocket();
} else {
socket = sslContext.getSocketFactory().createSocket(address, port);
}
} catch (Exception e) {
System.out.println(e.getLocalizedMessage());
return null;
}
return socket;
}
The url passed to jdbc driver is changed to:
String url = "jdbc:mysql://abc.com:3306/test?" +
"user=abc&password=123" +
"&useUnicode=true" +
"&characterEncoding=utf8&useSSL=true" +
"&socketFactory=" + MySocketFactory.class.getName();
The client did execute my version createSSLSocket() and return a Socket object. However, I got the following Exceptions after continuing the execution:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:
Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
javax.net.ssl.SSLException:
Unrecognized SSL message, plaintext connection?
I'm sure the MySQL was up and running, the address and port passed to createSSLSocket() were correct. Could anyone help? The client has to communicate to 2 sites at the same time: an HTTPS web server and a self-signed MySQL server.
I have created my own SSLSocketFactory as explained in this question
private SSLSocketFactory newSslSocketFactory() {
try {
// Get an instance of the Bouncy Castle KeyStore format
KeyStore trusted = KeyStore.getInstance("BKS");
// Get theraw resource, which contains the keystore with
// your trusted certificates (root and any intermediate certs)
Context context = this.activity;
Resources _resources = context.getResources();
InputStream in = _resources.openRawResource(R.raw.mystore);
try {
// Initialize the keystore with the provided trusted certificates
// Also provide the password of the keystore
trusted.load(in, "mypassword".toCharArray());
} finally {
in.close();
}
// Pass the keystore to the SSLSocketFactory. The factory is responsible
// for the verification of the server certificate.
SSLSocketFactory sf = new SSLSocketFactory(trusted);
// Hostname verification from certificate
sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
return sf;
} catch (Exception e) {
throw new AssertionError(e);
}
}
Actually i need to set this SSLSocketFactory on the HttpsURLConnection before connecting. But when i try to set it on HttpsURLConnection by calling
(HttpsURLConnection )connection.setSSLSocketFactory(trusted);
At this point am facing cast class error between 2 packages org.apache.http.conn.ssl.SSLSocketFactory and javax.net.ssl.SSLSocketFactory.
How to solve this?
Am not getting any exception with the above piece of code.
But the problem is that, when am trying to set the SSLSocketFactory on the HttpsURLConnection using:
(HttpsURLConnection )connection.setSSLSocketFactory(trusted)
It is showing "The method setSSLSocketFactory(SSLSocketFactory) in the type HttpsURLConnection is not applicable for the arguments(SSLSocketFactory)".
Because the method setSSLSocketFactory is there in both the packages.