Problems with connecting to LDAPS - java

While Im connecting to LDAPS I get the following Exception:
Exception in thread "main" java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:189)
at java.net.SocketInputStream.read(SocketInputStream.java:121)
at sun.security.ssl.InputRecord.readFully(InputRecord.java:312)
at sun.security.ssl.InputRecord.read(InputRecord.java:350)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:927)
at sun.security.ssl.SSLSocketImpl.waitForClose(SSLSocketImpl.java:1723)
at sun.security.ssl.HandshakeOutStream.flush(HandshakeOutStream.java:122)
at sun.security.ssl.Handshaker.kickstart(Handshaker.java:909)
at sun.security.ssl.SSLSocketImpl.kickstartHandshake(SSLSocketImpl.java:1439)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1304)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1355)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339)
at InstallCert.main(InstallCert.java:72)
I'm connecting using the following code:
InputStream in = new FileInputStream(file);
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(in, passphrase);
in.close();
SSLContext context = SSLContext.getInstance("TSL");
TrustManagerFactory tmf =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
X509TrustManager defaultTrustManager = (X509TrustManager)tmf.getTrustManagers()[0];
SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
context.init(null, new TrustManager[] {tm}, null);
SSLSocketFactory factory = context.getSocketFactory();
System.out.println("Opening connection to " + host + ":" + port + "...");
SSLSocket socket = (SSLSocket)factory.createSocket(host, port);
socket.setSoTimeout(10000);
try {
System.out.println("Starting SSL handshake...");
socket.startHandshake();
socket.close();
System.out.println();
System.out.println("No errors, certificate is already trusted");
} catch (SSLException e) {
System.out.println();
e.printStackTrace(System.out);
}
Port is : 636. Domain Controller is on Windows 2012. When I connect to domain controller on Windows 2008 there is no problem, it works correctly.
Does it mean that LDAP doesn't use SSL?

Related

"SSLHandshakeException: no cipher suites in common"

Im trying to connect a client to a server via SSL secure connection, but I seem to be thrown the "SSLHandshakeExceptin: no cipher suites in common" everytime. I could really use some help with this one.
Here is the server code:
public ChatServer() {
usedNames.add("arnold");
SSLServerSocket ss = null;
try {
SecureRandom sr = new SecureRandom();
String passphrase = "serverpwd";
//read a file with client certificates
KeyStore clientKeyStore = KeyStore.getInstance("JKS");
clientKeyStore.load(new FileInputStream("client.public"), "public".toCharArray());
//reads a file with servers certificate and secret key
KeyStore serverKeyStore = KeyStore.getInstance("JKS");
serverKeyStore.load(new FileInputStream("server.private"), passphrase.toCharArray());
// tmf,kmf and sslContext
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(clientKeyStore);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(serverKeyStore, passphrase.toCharArray());
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), sr);
// Create socket
SSLServerSocketFactory factory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
ss = (SSLServerSocket) factory.createServerSocket(serverPort);
ss.setNeedClientAuth(true); // client needs to have auth.
ss.setEnabledCipherSuites(new String[]{"TLS_RSA_WITH_AES_128_CBC_SHA"});
} catch (Exception e) {
System.err.println("[system] could not create socket on port " + this.serverPort);
e.printStackTrace(System.err);
System.exit(1);
}
// start listening for new connections
System.out.println("[system] listening ...");
try {
while (true) {
Socket socket = ss.accept(); // connection established
((SSLSocket)socket).startHandshake(); //explicitly trigger SSL handshake
String username = ((SSLSocket) socket).getSession().getPeerPrincipal().getName();
And here is the client code:
SecureRandom sr = new SecureRandom();
KeyStore serverKeyStore = KeyStore.getInstance("JKS");
serverKeyStore.load(new FileInputStream("server.public"), "public".toCharArray());
KeyStore clientKeyStore = KeyStore.getInstance("JKS");
clientKeyStore.load(new FileInputStream(sslPrivate), passphrase.toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(serverKeyStore);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(clientKeyStore, passphrase.toCharArray());
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), sr);
// create socket
SSLSocketFactory sf = sslContext.getSocketFactory();
socket = (SSLSocket)sf.createSocket("localhost", serverPort);
socket.setEnabledCipherSuites(new String[] { "TLS_RSA_WITH_AES_128_CBC_SHA" }); //(CipherSuite)
socket.startHandshake(); // //explicitly trigger SSL handshake
This is what prints out on the console where i run the "server":
And this is on the console where i run the "client":

SSL handshakeCompleted never called

I am trying to send data from my client to my server. Therefore I am using TSL.
I created the certificates and these are loaded without any troubles.
The connection is established, but the handshake between the client and the server is never called, and the handshakeCompleted is never called.
Client:
char[] password = "Password".toCharArray();
KeyStore trustStore = KeyStore.getInstance("BKS");
trustStore.load(activity.getResources().openRawResource(R.raw.truststore), password);
Log.i("Update", "Loaded trust certificate");
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(trustStore);
Log.i("Update", "Loaded trustManagerFactory");
KeyStore keyStore = KeyStore.getInstance("BKS");
keyStore.load(activity.getResources().openRawResource(R.raw.keystore), password);
Log.i("Update", "Loaded key certificate");
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, password);
Log.i("Update", "Loaded keyManagerFactory");
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
Log.i("Update", "Loaded SSLContext");
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
final SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket(InetAddress.getByName(host), port);
Log.i("Update", "Loaded SSL
socket.addHandshakeCompletedListener(new HandshakeCompletedListener(){
#Override
public void handshakeCompleted(HandshakeCompletedEvent handshakeCompletedEvent){
try{
Log.i("Update", "Did handshake");
writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
Log.i("Update", "Writer");
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Log.i("Update", "Reader");
while(isRunning){
try{
writer.println("Test");
writer.flush();
Log.i("DATA", "DATA SENT");
}catch(Exception e){
e.printStackTrace();
}
}
writer.close();
reader.close();
socket.close();
}catch(Exception e){
e.printStackTrace();
}
}
});
socket.startHandshake();
Server:
char[] password = "Password".toCharArray();
KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(getClass().getResourceAsStream("/security/keystore.jks"), password);
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, password);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagerFactory.getKeyManagers(), null, null);
SSLServerSocketFactory sslServerSocketFactory = sslContext.getServerSocketFactory();
SSLServerSocket serverSocket = (SSLServerSocket) sslServerSocketFactory.createServerSocket(7826);
System.out.println("Accepting connections now...");
while(true){
SSLSocket socket = (SSLSocket) serverSocket.accept();
socket.setUseClientMode(false);
socket.addHandshakeCompletedListener(handshakeCompletedEvent -> {
try{
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
while(running){
if(!socket.isConnected() || socket.isClosed()){
disconnect();
return;
}
for(Iterator<String> pendingIterator = pendingMessages.iterator(); pendingIterator.hasNext();){
String message = pendingIterator.next();
pendingIterator.remove();
writer.println(message); writer.flush();
}
//Auto decrypt when message arrives, but no thread blocking
if(reader.ready()){
String line = reader.readLine();
System.out.println(line);
}
}
}catch(Exception e){
e.printStackTrace();
}
});
socket.startHandshake();
}
As you can see I am waiting on both sides for the handshakeComplete, using it only on the client or only on the server side doesn't work either

Error by SSLServerSocket

I tried to make an Android Server with an SSLServerSocket. I made a keystore and started to make the server. I initialize the server as follows:
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
InputStream inputStream = context.getResources().openRawResource(R.raw.server);
keyStore.load(inputStream, "passwd".toCharArray());
String keyalg = KeyManagerFactory.getDefaultAlgorithm();
kmf.init(keyStore, "passwd".toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(keyalg);
SSLContext context = SSLContext.getInstance("TLS");
context.init(kmf.getKeyManagers(), null, null);
SSLServerSocket ss = (SSLServerSocket) context.getServerSocketFactory().createServerSocket();
inputStream.close();
//Here comes the error
ss.accept();
So if I try to accept clients (without that the client side tried to connect), I get an error.
java.net.SocketException: accept failed: EINVAL (Invalid argument)
at java.net.PlainSocketImpl.accept(PlainSocketImpl.java:110)
at java.net.ServerSocket.implAccept(ServerSocket.java:203)
at com.android.org.conscrypt.OpenSSLServerSocketImpl.accept(OpenSSLServerSocketImpl.java:184)
at de.turtc.util.ServerUtil.run(ServerUtil.java:88)
Caused by: libcore.io.ErrnoException: accept failed: EINVAL (Invalid argument)
at libcore.io.Posix.accept(Native Method)
at libcore.io.BlockGuardOs.accept(BlockGuardOs.java:55)
at java.net.PlainSocketImpl.accept(PlainSocketImpl.java:98)
Without a SSLServerSocket it works! I dont get any information of this error!
Problem was: I didn't give a port to the server.
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
InputStream inputStream = context.getResources().openRawResource(R.raw.server);
keyStore.load(inputStream, "passwd".toCharArray());
String keyalg = KeyManagerFactory.getDefaultAlgorithm();
kmf.init(keyStore, "passwd".toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(keyalg);
SSLContext context = SSLContext.getInstance("TLS");
context.init(kmf.getKeyManagers(), null, null);
SSLServerSocket ss = (SSLServerSocket) context.getServerSocketFactory().createServerSocket(4444);
inputStream.close();
ss.accept();
So I changed:
SSLServerSocket ss = (SSLServerSocket) context.getServerSocketFactory().createServerSocket();
to
SSLServerSocket ss = (SSLServerSocket)context.getServerSocketFactory().createServerSocket(4444);
That solved my problem!

Create app with SSLSocket Java

I want to create an app use SSLSocket: client send a String to server and server will uppercase that String and send back to client for display.
SSLServer
public class SSLServer {
public static void main(String args[]) throws Exception
{
try{
//Creaet a SSLServersocket
SSLServerSocketFactory factory=(SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
SSLServerSocket sslserversocket=(SSLServerSocket) factory.createServerSocket(1234);
//Tạo 1 đối tượng Socket từ serversocket để lắng nghe và chấp nhận kết nối từ client
SSLSocket sslsocket=(SSLSocket) sslserversocket.accept();
//Tao cac luong de nhan va gui du lieu cua client
DataInputStream is=new DataInputStream(sslsocket.getInputStream());
PrintStream os=new PrintStream(sslsocket.getOutputStream());
while(true) //khi dang ket noi voi client
{
//Doc du lieu den
String input=is.readUTF();
String ketqua=input.toUpperCase();
//Du lieu tra ve
os.println(ketqua);
}
}
catch(IOException e)
{
System.out.print(e);
}
}
}
SSLClient
public class SSLClient {
public static void main(String args[])
{
try
{
//Mo 1 client socket den server voi so cong va dia chi xac dinh
SSLSocketFactory factory=(SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket sslsocket=(SSLSocket) factory.createSocket("127.0.0.1",1234);
//Tao luong nhan va gui du lieu len server
DataOutputStream os=new DataOutputStream(sslsocket.getOutputStream());
DataInputStream is=new DataInputStream(sslsocket.getInputStream());
//Gui du lieu len server
String str="helloworld";
os.writeBytes(str);
//Nhan du lieu da qua xu li tu server ve
String responseStr;
if((responseStr=is.readUTF())!=null)
{
System.out.println(responseStr);
}
os.close();
is.close();
sslsocket.close();
}
catch(UnknownHostException e)
{
System.out.println(e.getMessage());
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
}
When run SSLServer. It displays this error:
javax.net.ssl.SSLException: No available certificate or key corresponds
to the SSL cipher suites which are enabled
I have search and do some ways but.. Can you help me.
This will generate certificate:
keytool -genkey -keystore yourKEYSTORE -keyalg RSA
Enter yourPASSWORD and than start your server with ssl debug information(put yourKEYSTORE into directory with SSLServer.class):
java -Djavax.net.ssl.keyStore=yourKEYSTORE -Djavax.net.ssl.keyStorePassword=yourPASSWORD -Djava.protocol.handler.pkgs=com.sun.net.ssl.internal.www.protocol -Djavax.net.debug=ssl SSLServer
Than start your client(put yourKEYSTORE into directory with SSLClient.class):
java -Djavax.net.ssl.trustStore=yourKEYSTORE -Djavax.net.ssl.trustStorePassword=yourPASSWORD SSLClient
#corVaroxid's answer is right. But if you want to set configurations programmatically to avoid global settings (like me), you can go like below (Kotlin):
val password = "yourPassword".toCharArray()
val keyStore = KeyStore.getInstance(File("yourKeystorePath.jks"), password)
val trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
trustManagerFactory.init(keyStore)
val keyManagerFactory = KeyManagerFactory.getInstance("NewSunX509")
keyManagerFactory.init(keyStore, password)
val context = SSLContext.getInstance("TLS") //"SSL" "TLS"
context.init(keyManagerFactory.keyManagers, trustManagerFactory.trustManagers, null)
val factory = context.serverSocketFactory
(factory.createServerSocket(LISTENING_PORT) as SSLServerSocket).use { serverSocket ->
logger.trace("Listening on port: $LISTENING_PORT")
// ...
}
Or in Java:
final char[] password = "yourPassword".toCharArray();
final KeyStore keyStore = KeyStore.getInstance(new File("yourKeystorePath.jks"), password);
final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("NewSunX509");
keyManagerFactory.init(keyStore, password);
final SSLContext context = SSLContext.getInstance("TLS");//"SSL" "TLS"
context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
final SSLServerSocketFactory factory = context.getServerSocketFactory();
try (SSLServerSocket serverSocket = ((SSLServerSocket) factory.createServerSocket(LISTENING_PORT))) {
logger.trace("Listening on port: " + LISTENING_PORT);
// ...
}
Check the certificates that you have installed. Make sure they are supporting the cipher suites that you are negotiating.

APN push notification from java server?

I am using the p12 file to connect to APN server using java code but am getting error:javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
Code:
private String token="c585ca35 21468c52 e7285b15 5441fcd3 77b50594 c05000c1 165aa025a87a1660";
private String host = "gateway.sandbox.push.apple.com";
private int port = 2195;
private String payload = "{\"aps\":{\"alert\":\"Message from Java o_O\"}}";
try {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(getClass().getResourceAsStream("E://workspace//Product//javatest//lib//Certificates_key.p12"), "ducont".toCharArray());
// keyStore.load(getClass().getResourceAsStream("Certificates_key.p12"), "ducont".toCharArray());
KeyManagerFactory keyMgrFactory = KeyManagerFactory.getInstance("SunX509");
keyMgrFactory.init(keyStore, "ducont".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();
}

Categories

Resources