This discussion is archived
4 Replies Latest reply: Jun 22, 2012 6:28 AM by EJP RSS

Interference between mutliple SSLSocket

945052 Newbie
Currently Being Moderated
Hello,

I wrote a client and a server applications using SSLSocket and Channels.
A single communication from client to server is Ok but if a second connection is made by the same client, there is interference between both connection. The first input channel became wordless and bytes sent by server are received by the second SSLSocket.

Here is the code :

Client :
public static void main(String args[]) {
new Thread(new Runnable() {
public void run() {
check("1");
}
}).start();

try {
Thread.sleep(2000);
} catch (InterruptedException e) { e.printStackTrace(); }

new Thread(new Runnable() {
public void run() {
check("2");
}
}).start();
}

public static void check(final String name) {
try {

Preferences p = Preferences.userNodeForPackage(TestMain.class);
// .... filling preferences p
KeyManager[] kms = null;
if (keyStore != null)
kms = SSLHelper.getKeyManagers(keyStore, keySecret, keyPassword);
final TrustManager[] tms = SSLHelper.getTrustManagers(trustStore, trustSecret);
tms[0] = new X509TrustManagerWrapper(localStore, localSecret, (X509TrustManager) tms[0]);
final SSLContext context = SSLHelper.getSSLContext(kms, tms);

final SSLSocketFactory ssf = context.getSocketFactory();
final int port = 7000;
final String server = "distant server";

SSLSocket socket = (SSLSocket) ssf.createSocket(server, port);

socket.startHandshake();
final WritableByteChannel outputChannel = Channels.newChannel(socket.getOutputStream());
final ReadableByteChannel inputChannel = Channels.newChannel(socket.getInputStream());

System.out.println(name + " - Connected");
new Thread(new Runnable() {
public void run() {
final ByteBuffer buff = ByteBuffer.allocate(1000);
try {
int nbRead = 0;
int i = 0;
while ((i = inputChannel.read(buff)) > 0) {
nbRead = i;
while (nbRead != 12) {
i = inputChannel.read(buff);
nbRead += i;
}
nbRead = 0;
buff.flip();
System.out.print(name + " - Reception of ");
while (buff.hasRemaining()) {
System.out.print(buff.getChar());
}
System.out.println("");
buff.clear();

buff.putChar('h');
buff.putChar('e');
buff.putChar('l');
buff.putChar('l');
buff.putChar('o');
buff.flip();
outputChannel.write(buff);
buff.clear();
}
} catch (IOException e) { e.printStackTrace(); }

}
}).start();
} catch (IOException e) { e.printStackTrace();
} catch (GeneralSecurityException e) { e.printStackTrace();}
}
Code for SSL Helper :
public final class SSLHelper {

     public final static KeyStore getKeyStore(String store, char[] secret) throws IOException, GeneralSecurityException {
          final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
          final File f = new File(store);
          if (f.exists() && f.canRead()) {
               ks.load(new FileInputStream(f), secret);
          } else {
               ks.load(null,null);
          }
          return ks;
     }
     
     
     public final static KeyManager[] getKeyManagers(KeyStore ks, char[] keyPassword)  throws IOException, GeneralSecurityException {
          final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
          kmf.init(ks, keyPassword);
          return kmf.getKeyManagers();
     }
     
     public final static KeyManager[] getKeyManagers(String keyStore, char[] keySecret, char[] keyPassword) throws IOException, GeneralSecurityException {
          return getKeyManagers(getKeyStore(keyStore, keySecret), keyPassword);
     }
     
     public final static TrustManager[] getTrustManagers(String trustStore, char[] trustSecret) throws IOException, GeneralSecurityException {
          return getTrustManagers(getKeyStore(trustStore, trustSecret));
     }
     
     public final static TrustManager[] getTrustManagers(KeyStore ks) throws IOException, GeneralSecurityException {
          final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
          tmf.init(ks);
          return tmf.getTrustManagers();
     }
     
     public final static SSLContext getSSLContext(KeyManager[] kms, TrustManager[] tms) throws IOException, GeneralSecurityException {
          final SSLContext ctx = SSLContext.getInstance("SSL");
          ctx.init(kms, tms, null);
          ctx.getServerSessionContext().setSessionTimeout(1);
          return ctx;
     }
     
     public final static SSLContext getSSLContext(String keyStore, char[] keySecret, char[] KeyPassword, String trustStore, char[] trustSecret) throws IOException, GeneralSecurityException {
          KeyManager[] kms = null;
          if (keyStore != null) {
               kms = getKeyManagers(keyStore, keySecret, KeyPassword);
          }
          TrustManager[] tms = null;
          if (trustSecret != null) {
               tms = getTrustManagers(trustStore, trustSecret);
          }
          return getSSLContext(kms, tms);
     }
     
     public static SSLContext getSSLContext(String keyStore, char[] keySecret, char[] keyPassword) throws IOException, GeneralSecurityException {
          KeyManager[] kms = null;
          if (keyStore != null) {
               kms = getKeyManagers(keyStore, keySecret, keyPassword);
          }
          return getSSLContext(kms, null);
     }
     
     public static SSLContext getSSLContext(String trustStore, char[] trustSecret) throws IOException, GeneralSecurityException {
          TrustManager[] tms = null;
          if (trustStore != null) {
               tms = getTrustManagers(trustStore, trustSecret);
          }
          return getSSLContext(null, tms);
     }
}

Code for Server :

public static void main(String args[]) {
          Preferences p = Preferences.userNodeForPackage(ServerMainTest.class);
          p.put("port", "7000");
          // .... filling preferences p

          String keyStore = p.get("keyStore", "");
          char[] keySecret = p.get("keySecret", "keySecret").toCharArray();
          char[] keyPassword = p.get("keyPassword", "keyPassword").toCharArray();
          try {
               BoundConcurrent server = new BoundConcurrent(p);
               SSLContext ctx;
               SSLServerSocket ss;

               ctx = SSLHelper.getSSLContext(keyStore, keySecret, keyPassword);
               ss = (SSLServerSocket) ctx.getServerSocketFactory().createServerSocket();
               server.setServerSocket(ss);
               server.setService(new TestServer());
               String nbThread = "10";
               server.setThreadNumber(Integer.valueOf(nbThread));
               server.launch();
               
          } catch (GeneralSecurityException e) {      e.printStackTrace();
          } catch (IOException e) { e.printStackTrace(); }
     }

public class TestServer implements Service {
     
     private final static int BUFF_SIZE = 10000;
     private final ByteBuffer readByteBuffer = ByteBuffer.allocateDirect(BUFF_SIZE);
     private final ByteBuffer writeByteBuffer = ByteBuffer.allocateDirect(BUFF_SIZE);
     
     private WritableByteChannel outputChannel;

     public void serve(Socket socketService) {
          try {
               final ReadableByteChannel inputChannel = Channels.newChannel(socketService.getInputStream());
               outputChannel = Channels.newChannel(socketService.getOutputStream());
               System.out.println(Thread.currentThread().getName() + " - Reception of new connection");
               SSLSocket s = (SSLSocket) socketService;
               s.getSession().invalidate();
               
               byte[] b = s.getSession().getId();
               final StringBuilder sb = new StringBuilder();
               
               for(int i = 0; i < b.length; i++) {
                    sb.append(b);
               }
               System.out.println(sb.toString());
               
               new Thread(new Runnable() {
                    
                    public void run() {
                         final ByteBuffer buff = ByteBuffer.allocate(1000);
                         try {
                              int nbRead = 0;
                              int i = 0;
                              while ((i = inputChannel.read(buff)) > 0) {
                                   nbRead = i;
                                   while (nbRead != 10) {
                                        i = inputChannel.read(buff);
                                        nbRead += i;
                                   }
                                   nbRead = 0;
                                   buff.flip();
                                   System.out.print(Thread.currentThread().getName() + " - Reception of ");
                                   while (buff.hasRemaining()) {
                                        System.out.print(buff.getChar());
                                   }
                                   System.out.println("");
                                   buff.clear();
                              }
                         } catch (IOException e) { e.printStackTrace(); }
                         
                    }
               }).start();
               while (true) {
                    writeByteBuffer.clear();
                    writeByteBuffer.putChar('c');
                    writeByteBuffer.putChar('o');
                    writeByteBuffer.putChar('u');
                    writeByteBuffer.putChar('c');
                    writeByteBuffer.putChar('o');
                    writeByteBuffer.putChar('u');
                    writeByteBuffer.flip();
                    outputChannel.write(writeByteBuffer);
                    try {
                         Thread.sleep(3000);
                    } catch (InterruptedException e) { e.printStackTrace(); }
               }
          } catch (IOException e) { e.printStackTrace(); }
          
     }


public class BoundConcurrent extends Server {

     protected int threadNb = -1;     
     public BoundConcurrent(Preferences pref) {
          super(pref);
     }
     
     public void setThreadNumber(int nb) {
          threadNb = nb;
     }
     
     @Override
     public void launch() {
          try {
               bind();
          } catch (IOException e) { return;     }
          
          if (threadNb==-1)
               threadNb = getPreferences().getInt("threadNB", 10);
          final ThreadGroup group = new ThreadGroup("Service");
          for (int i=0; i<threadNb; i++) {
               final String name = "server"+i;
               try {
                    new Thread(group, new RunnableService(), name).start();
               } catch (NullPointerException e) { break; }
          }
     }
     
     public class RunnableService implements Runnable {
          
          public void run() {
               Socket serviceSocket;
               while (true) {
                    synchronized (serverSocket) {
                         try {
                              serviceSocket = serverSocket.accept();
                              final SSLSocket sslSocket = (SSLSocket)serviceSocket;
                              sslSocket.setEnableSessionCreation(true);
                              sslSocket.getSession().invalidate();
                         } catch (IOException e) { break;     }
                    }
                    try {
                         service.serve(serviceSocket);
                         serviceSocket.close();
                    } catch (IOException e) { e.printStackTrace(); }
               }     
          }
     }
}
Thanks.

Edited by: duncan55 on 21 juin 2012 03:08                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            
  • 1. Re: Interference between mutliple SSLSocket
    EJP Guru
    Currently Being Moderated
    Well this is a right royal mess, far too over-complicated to comment on in detail, but the crux of the problem is that you have one instance of Service, which has one pair of buffers, and you are using it to service all clients. So the clients are sharing buffers, so the data is getting mixed up.

    The entire architecture is wrong. You need to take a really good look at the Custom Networking trail of the Java Tutorial.
  • 2. Re: Interference between mutliple SSLSocket
    945052 Newbie
    Currently Being Moderated
    It's not a mess, you don't understand that there is one instance of service (one thread) by client.
  • 3. Re: Interference between mutliple SSLSocket
    gimbal2 Guru
    Currently Being Moderated
    you don't understand that there is one instance of service (one thread) by client.
    A single communication from client to server is Ok but if a second connection is made by the same client, there is interference between both connection.
    Its not hard to be confused by all that.
  • 4. Re: Interference between mutliple SSLSocket
    EJP Guru
    Currently Being Moderated
    It's not a mess, you don't understand that there is one instance of service (one thread) by client.
    Me case rests, m'lud. It's such a mess that you don't even understand your own code. You have:
    public class TestServer implements Service
    It has an instance member:
    private final ByteBuffer writeByteBuffer = ByteBuffer.allocateDirect(BUFF_SIZE);
    You instantiate it here:
    ss = (SSLServerSocket) ctx.getServerSocketFactory().createServerSocket();
    server.setServerSocket(ss);
    server.setService(new TestServer());
    and nowhere else. There is therefore only one instance of TestServer. It has a serve(Socket socketService) method, that is called with different values of 'socketService' where you reuse the 'writeByteBuffer' member for all sockets:
    writeByteBuffer.clear();
    writeByteBuffer.putChar('c');
    writeByteBuffer.putChar('o');
    writeByteBuffer.putChar('u');
    writeByteBuffer.putChar('c');
    writeByteBuffer.putChar('o');
    writeByteBuffer.putChar('u');
    writeByteBuffer.flip();
    outputChannel.write(writeByteBuffer);
    QED. Try the tutorial I mentioned and see how it's done.

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points