SSL handshake with Apple Push Notification Server via Java - java

Hello I am trying to send a push message to my device using Java. But I'am allready getting problems when establishing the ssl connection.
Here is the code so far:
KeyStore keyStore = KeyStore.getInstance("PKCS12");
InputStream key = getClass().getResourceAsStream("apns-dev-key.p12");
char[] c = key.toString().toCharArray();
keyStore.load(getClass().getResourceAsStream("apns-dev-cert.p12"), c);
KeyManagerFactory keyMgrFactory = KeyManagerFactory.getInstance("SunX509");
keyMgrFactory.init(keyStore, c);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyMgrFactory.getKeyManagers(), null, null);
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(host, port);
String[] cipherSuites = sslSocket.getSupportedCipherSuites();
sslSocket.setEnabledCipherSuites(cipherSuites);
sslSocket.startHandshake();
The error I am getting is:
java.io.IOException: failed to decrypt safe contents entry: javax.crypto.BadPaddingException: Given final block not properly padded
I guess there is some problem with the apns-dev-key.p12 file. Any hints?
The code above is taken from: http://undermypalapa.wordpress.com/2009/08/23/apple-push-notification-service-java/

Here my working example:
private String token = "<token>";
private String host = "gateway.sandbox.push.apple.com";
private int port = 2195;
private String payload = "{\"aps\":{\"alert\":\"Message from Java o_O\"}}";
public APNSender() {
try {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(getClass().getResourceAsStream("cert.p12"), "<password>".toCharArray());
KeyManagerFactory keyMgrFactory = KeyManagerFactory.getInstance("SunX509");
keyMgrFactory.init(keyStore, "<password>".toCharArray());
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyMgrFactory.getKeyManagers(), null, null);
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(host, port);
String[] cipherSuites = sslSocket.getSupportedCipherSuites();
sslSocket.setEnabledCipherSuites(cipherSuites);
sslSocket.startHandshake();
char[] t = token.toCharArray();
byte[] b = Hex.decodeHex(t);
OutputStream outputstream = sslSocket.getOutputStream();
outputstream.write(0);
outputstream.write(0);
outputstream.write(32);
outputstream.write(b);
outputstream.write(0);
outputstream.write(payload.length());
outputstream.write(payload.getBytes());
outputstream.flush();
outputstream.close();
} catch (Exception exception) {
exception.printStackTrace();
}
}
What I'm still curious about is how to receive error codes. I tried it with
InputStream in = sslSocket.getInputStream();
[...]
but no success.
The Apple docs say that there is no answer send when no errors occured but on the other hand they list a status code for "No errors encountered".

You might want to take a look at http://code.google.com/p/javapns/. If you really need to reinvent the wheel and not use JavaPNS directly instead of writing your own code for this, at least JavaPNS' documentation should help you understand key principles you'll need to know.

Related

Netty websocket client example with a given PKCS12

I have the client.p12 file and MyPassword, I am trying to establish the websocket connection using Netty code available over here. Currently I have the working example in OkHttpClient. But I am having a hard time to map that into netty.
My server gave me this domain to connect to "https://api.server.com"
In OkHttpClient the following code works
OkHttpClient client = getClient(info);
Request request = new Request.Builder().url("https://api.server.com" + "/messaging").build();
WebSocket webSocket = client.newWebSocket(request, listener);
Here the getClient code is following:
public static OkHttpClient getClient(ConnectionInfo info) {
KeyStore appKeyStore = KeyStore.getInstance("PKCS12");
appKeyStore.load(new FileInputStream("client.p12"), "MyPassword".toCharArray());
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
keyManagerFactory.init(appKeyStore, info.getPassword().toCharArray());
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
trustManagerFactory.init((KeyStore) null);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
throw new IllegalStateException(
"Unexpected default trust managers:" + Arrays.toString(trustManagers));
}
X509TrustManager trustManager = (X509TrustManager) trustManagers[0];
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new TrustManager[] {trustManager}, null);
context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());
OkHttpClient.Builder builder =
new OkHttpClient.Builder().sslSocketFactory(context.getSocketFactory(), trustManager);
builder.retryOnConnectionFailure(true);
return builder.build();
}
Now that code above works fine, I am trying to implement this in Netty. So looking at example code it only accepts the protocols ws and wss. While in the above example The HTTPS requests Upgraded to WebSocket using the appropriate headers. So my understanding is that If I provide the domain name as "wss:////api.server.com/messaging" Then it will first establish the https connection and then upgrade it to WebSocket.
Now I am not sure how to set the certificate and password.
// I have created a keyStore as following
KeyStore keyStore = KeyStore.getInstance("PKCS12");
FileInputStream instream = new FileInputStream(new File("client.p12"));
try {
keyStore.load(instream, "MyPassword".toCharArray());
} finally {
instream.close();
}
final boolean ssl = "wss".equalsIgnoreCase(scheme);
final SslContext sslCtx;
if (ssl) {
// How to specify the above keystore with this client?
sslCtx = SslContextBuilder.forClient()
.trustManager(InsecureTrustManagerFactory.INSTANCE).build();
} else {
sslCtx = null;
}
SSlContextBuilder has a method that takes a KeyManagerFactory:
SslContextBuilder.forClient()
.keyManager(keyManagerFactory)
.trustManager(InsecureTrustManagerFactory.INSTANCE)
.build();

Trying to pass along x509 client certificate to second server

I'm trying to give server "A" the ability to connect to server "B" using the same X509 client certificate it received from the user. Here are the basics of where I am so far:
public int makeRemoteCall() {
URL url = new URL("https://host.com/service/request");
HttpsURLConnection conn = url.openConnection();
SSLSocketFactory factory = getFactoryFromSessionCert();
conn.setSSLSocketFactory(factory);
int responseCode = conn.getResponseCode();
return responseCode;
}
public static SSLSocketFactory getFactoryFromSessionCert() throws Exception {
HttpServletRequest request = getRequest();
X509Certificate[] certs = (X509Certificate[])request.getAttribute("javax.servlet.request.X509Certificate");
KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(null, null);
keyStore.setCertificateEntry("client_cert", certs[0]);
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
keyManagerFactory.init(keyStore, null);
SSLContext context = SSLContext.getInstance("TLS");
context.init(keyManagerFactory.getKeyManagers(), null, null);
return context.getSocketFactory();
}
I am able to retrieve the client's certificate without trouble, and can verify that it does indeed end up in keyStore. But the certificate doesn't seem to make it into keyManagerFactory.
I thought the issue was that I'm not providing a password in keyManagerFactory.init(keyStore, null), so I tried providing it but without success. And should I even have to? I understand that I would need a password if I were loading certificates and keys from a protected file, but here I'm just trying to pass along an already exposed public certificate.
As further background, this basic scheme works if I replace getFactoryFromSessionCert() with this:
public static SSLSocketFactory getFactory(File pKeyFile, String pKeyPassword) throws Exception {
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
KeyStore keyStore = KeyStore.getInstance("JKS");
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();
}
So, what am I not understanding? And how should I pass along a client certificate?

Pkcs#11 with SSL in java

How to use pkcs#11 with softhsm2 in java for ssl handshake .
I am facing issues with implementing ssl context factory with keys stored in softhsm2. Please provide sample which i can make use of.
here is the solution for pkcs#11 for ssl handshake in java .
System.setProperty("javax.net.debug", "ssl");
try {
String configName = "softhsm2.cfg";
Provider p = new SunPKCS11(configName);
System.out.println(p.getName());
Security.addProvider(p);
// Load the key store
char[] pin = "5678".toCharArray();
KeyStore ks = KeyStore.getInstance("PKCS11", p);
ks.load(null, pin);
System.out.println(ks.size());
Enumeration<String> aliases = ks.aliases();
for(;aliases.hasMoreElements();)
{
System.out.println(aliases.nextElement());
}
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
//Add to keystore to key manager
keyManagerFactory.init(ks, pin);
//Create the context
SSLContext context = SSLContext.getInstance("TLS");
context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());
//Create a socket factory
SSLServerSocketFactory ssf = context.getServerSocketFactory();
//SSLSocketFactory sf = context.getSocketFactory();
//Create the socket
SSLServerSocket s = (SSLServerSocket) ssf.createServerSocket(8888);
printServerSocketInfo(s);
SSLSocket c = (SSLSocket) s.accept();

SSLHandshakeException SSLProtocolException with Android 6 (marshmallow)

I've an app that communicates with a server through an SSLSocket.
From Android 6 I receive a SSLHandshakeException
javax.net.ssl.SSLHandshakeException: Handshake failed
at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:396)
at com.android.org.conscrypt.OpenSSLSocketImpl.waitForHandshake(OpenSSLSocketImpl.java:629)
at com.android.org.conscrypt.OpenSSLSocketImpl.getInputStream(OpenSSLSocketImpl.java:591)
at com.pandaproject.service.ClientSocket.sendPatient(ClientSocket.java:1355)
at com.pandaproject.service.ClientSocket.uploadPatient(ClientSocket.java:826)
at com.pandaproject.service.ClientSocket.<init>(ClientSocket.java:241)
at com.pandaproject.service.UploadObject.getFromServer(UploadObject.java:201)
at com.pandaproject.service.UploadObject.access$000(UploadObject.java:20)
at com.pandaproject.service.UploadObject$1.run(UploadObject.java:97)
at java.lang.Thread.run(Thread.java:818)
Caused by javax.net.ssl.SSLProtocolException: SSL handshake terminated: ssl=0x9dea4280: Failure in SSL library, usually a protocol error
error:100c5410:SSL routines:ssl3_read_bytes:SSLV3_ALERT_HANDSHAKE_FAILURE (external/boringssl/src/ssl/s3_pkt.c:972 0xaee563c0:0x00000001)
error:100c009f:SSL routines:ssl3_get_server_hello:HANDSHAKE_FAILURE_ON_CLIENT_HELLO (external/boringssl/src/ssl/s3_clnt.c:750 0xab2a450f:0x00000000)
at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(NativeCrypto.java)
at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:324)
at com.android.org.conscrypt.OpenSSLSocketImpl.waitForHandshake(OpenSSLSocketImpl.java:629)
at com.android.org.conscrypt.OpenSSLSocketImpl.getInputStream(OpenSSLSocketImpl.java:591)
at com.pandaproject.service.ClientSocket.sendPatient(ClientSocket.java:1355)
at com.pandaproject.service.ClientSocket.uploadPatient(ClientSocket.java:826)
at com.pandaproject.service.ClientSocket.<init>(ClientSocket.java:241)
at com.pandaproject.service.UploadObject.getFromServer(UploadObject.java:201)
at com.pandaproject.service.UploadObject.access$000(UploadObject.java:20)
at com.pandaproject.service.UploadObject$1.run(UploadObject.java:97)
at java.lang.Thread.run(Thread.java:818)
And in the server side:
javax.net.ssl.SSLHandshakeException: no cipher suites in common
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1949)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:292)
at sun.security.ssl.ServerHandshaker.chooseCipherSuite(ServerHandshaker.java:1036)
at sun.security.ssl.ServerHandshaker.clientHello(ServerHandshaker.java:739)
at sun.security.ssl.ServerHandshaker.processMessage(ServerHandshaker.java:221)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:979)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:914)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1062)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375)
at sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:747)
at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:123)
at java.io.ObjectOutputStream$BlockDataOutputStream.drain(ObjectOutputStream.java:1877)
at java.io.ObjectOutputStream$BlockDataOutputStream.setBlockDataMode(ObjectOutputStream.java:1786)
at java.io.ObjectOutputStream.<init>(ObjectOutputStream.java:247)
This happens only with Android 6, it seems there is something different in the chiper suites
I'm pasting the Server and client code for better troubleshooting
Server code:
ServerSocket server = null;
Socket socket=null;
SSLContext ctx;
KeyManagerFactory kmf;
KeyStore ks;
try{
char[] passphrase = "password".toCharArray();
String keyfile = "keyName";
ctx = SSLContext.getInstance("TLS");
kmf = KeyManagerFactory.getInstance("SunX509");
ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream(keyfile), passphrase);
kmf.init(ks, passphrase);
ctx.init(kmf.getKeyManagers(), null, null);
ServerSocketFactory ssf = ctx.getServerSocketFactory();
server = ssf.createServerSocket(port);
}catch (IOException e){
e.printStackTrace();
}
while (true) {
socket = server.accept();
new Thread(new WorkerThread(socket));
}
Android code:
Socket clientSocket = null;
KeyStore store = KeyStore.getInstance("BKS");
InputStream in2 = ctx.getResources().openRawResource(
R.raw.server);
store.load(in2, "password".toCharArray());
TrustManagerFactory tmf = TrustManagerFactory
.getInstance(KeyManagerFactory.getDefaultAlgorithm());
tmf.init(store);
SSLContext sslcontext = SSLContext.getInstance("SSL");
sslcontext.init(null, tmf.getTrustManagers(),
new SecureRandom());
SSLSocketFactory sslsocketfactory = sslcontext
.getSocketFactory();
clientSocket = (SSLSocket) sslsocketfactory.createSocket(
Constants.SERVER_HOST, port);
ObjectInputStream obi = new ObjectInputStream(
clientSocket.getInputStream());
ObjectOutputStream obs = new ObjectOutputStream(
clientSocket.getOutputStream());
obs.writeObject("text");
obs.flush();
Any hint?
According to this:
https://github.com/iiordanov/remote-desktop-clients/issues/57
What seems to have happened is that annonimous DH cipher were dropped.
So, you cannot use a certificates that are not in Android keystore anymore.

generating SSL certificates and hooking an ssl client into them in java

So I have some of the ssl server and client side code. I'm not sure what to put in some of the methods though.
public void client() throws UnknownHostException, IOException{
KeyStore keyStore = KeyStore.getInstance("PKCS12");
FileInputStream stream = new FileInputStream(new File("")); // need correct file
keyStore.load(stream, "Some Password".toCharArray());
// load in the appropriate keystore and truststore for the client
// get the X509KeyManager and X509TrustManager instances
TrustManagerFactory trustManagerFactory =
TrustManagerFactory.getInstance("PKIX", "SunJSSE");
trustManagerFactory.init("NOT SURE WHAT TO PUT HERE");
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(new KeyManager[]{"NOT SURE WHAT TO PUT HERE"},
new TrustManager[]{"NOT SURE WHAT TO PUT HERE"}, null);
SSLSocketFactory socketFactory = sslContext.getSocketFactory();
SSLSocket socket =
(SSLSocket) socketFactory.createSocket("localhost", 25500);
socket.setEnabledProtocols(new String[]{"TLSv1"});
// read from the socket, etc
}
public void server() throws IOException{
// load in the appropriate keystore and truststore for the server
// get the X509KeyManager and X509TrustManager instances
SSLContext sslContext = SSLContext.getInstance("TLS");
// the final null means use the default secure random source
sslContext.init(new KeyManager[]{"NOT SURE WHAT TO PUT HERE"},
new TrustManager[]{"NOT SURE WHAT TO PUT HERE"}, null);
SSLServerSocketFactory serverSocketFactory =
sslContext.getServerSocketFactory();
SSLServerSocket serverSocket =
(SSLServerSocket) serverSocketFactory.createServerSocket(25500);
serverSocket.setNeedClientAuth(true);
// prevent older protocols from being used, especially SSL2 which is insecure
serverSocket.setEnabledProtocols(new String[]{"TLSv1"});
// you can now call accept() on the server socket, etc
}
Also, how do I generate certificates in java "like the code" and print it out to a file and have it use the same certificate over and over again.
Thx for any help.

Categories