Java-Gaming.org    
Featured games (81)
games approved by the League of Dukes
Games in Showcase (487)
Games in Android Showcase (110)
games submitted by our members
Games in WIP (553)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
   Home   Help   Search   Login   Register   
  Show Posts
Pages: [1]
1  Game Development / Shared Code / NIO SSL Server and HTML5 Secure WebSockets on: 2013-07-24 09:01:21
Hi everyone,

this post relates to the "very old" topic http://www.java-gaming.org/topics/nio-ssl-server/21984/view started by Riven.

I'm trying to implement HTML 5 "Secure WebSocket" (TLS/SSL) connections with my existing Java Server using NIO channels. Up to now I have successfully implemented unsecure "WebSocket" connections.

Javascript example code for unsecure WebSocket connections
1  
var connection = new WebSocket('ws://192.168.166.150:9005');


Javascript example code for secure WebSocket connections
1  
var connection = new WebSocket('wss://192.168.166.150:9005');


Javascript Code is executed in Google Chrome or Firefox.

Here's my server side JAVA code called on incoming data
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
private void read(SelectionKey key) throws IOException
   {
      SocketChannel socketChannel = (SocketChannel) key.channel();

      // Clear out our read buffer so it's ready for new data
     this.readBuffer.clear();

      // Attempt to read off the channel
     int numRead;
      try
      {
         numRead = socketChannel.read(this.readBuffer);
      }
      catch(IOException e)
      {
         // The remote forcibly closed the connection, cancel
        // the selection key and close the channel.
        this.checkRemoveClient(key);
         return;
      }

      if(numRead == -1)
      {
         // Remote entity shut the socket down cleanly. Do the
        // same from our end and cancel the channel.
        this.checkRemoveClient(key);
         return;
      }
      else
      {
         // Hand the data off to our clientRequestHandler thread
        Client client = (Client)this.clientList.get(socketChannel.hashCode());
         
         byte[] rawData;
         if(this.isSSLEnabled())
         {
            this.writeLogMessage("PLAIN DATA read ["+(new String(this.readBuffer.array()))+"]");

             this.readBuffer.flip();

             ByteBuffer copy = ByteBuffer.allocateDirect(numRead);
             copy.put(this.readBuffer);
             copy.flip();

             ClientRequestHandlerSSL crhSSL = new ClientRequestHandlerSSL(this, client, sslContext.createSSLEngine(), this.readBuffer.capacity());
             crhSSL.receive(copy);
         }
         else
         {
            rawData = this.readBuffer.array();
            ClientRequestHandler crh = new ClientRequestHandler(this, client, rawData, numRead);
            crh.run();
         }
         //
        //this.clientRequestHandler.processData(this, client, this.readBuffer.array(), numRead);
     }
   }


I used the JAVA code example from Riven and adapted it to my existing code architecture for handling SSL data coming over my socket channel:
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
18  
19  
20  
21  
22  
23  
24  
25  
26  
27  
28  
29  
30  
31  
32  
33  
34  
35  
36  
37  
38  
39  
40  
41  
42  
43  
44  
45  
46  
47  
48  
49  
50  
51  
52  
53  
54  
55  
56  
57  
58  
59  
60  
61  
62  
63  
64  
65  
66  
67  
68  
69  
70  
71  
72  
73  
74  
75  
76  
77  
78  
79  
80  
81  
82  
83  
84  
85  
86  
87  
88  
89  
90  
91  
92  
93  
94  
95  
96  
97  
98  
99  
100  
101  
102  
103  
104  
105  
106  
107  
108  
109  
110  
111  
112  
113  
114  
115  
116  
117  
118  
119  
120  
121  
122  
123  
124  
125  
126  
127  
128  
129  
130  
131  
132  
133  
134  
135  
136  
137  
138  
139  
140  
141  
142  
143  
144  
145  
146  
147  
148  
149  
150  
151  
152  
153  
154  
155  
156  
157  
158  
159  
160  
161  
162  
163  
164  
165  
166  
167  
168  
169  
170  
171  
172  
173  
174  
175  
176  
177  
178  
179  
180  
181  
182  
183  
184  
185  
186  
187  
188  
189  
190  
191  
192  
193  
194  
195  
196  
197  
198  
199  
200  
201  
202  
203  
204  
205  
206  
207  
208  
209  
210  
211  
212  
213  
214  
215  
216  
217  
218  
219  
220  
221  
222  
223  
224  
225  
226  
227  
228  
229  
230  
231  
232  
233  
234  
235  
236  
237  
238  
239  
240  
241  
242  
243  
244  
245  
246  
247  
248  
249  
250  
251  
252  
253  
254  
255  
256  
257  
258  
259  
260  
261  
262  
263  
264  
265  
266  
267  
268  
269  
270  
271  
272  
273  
274  
275  
276  
277  
278  
279  
280  
281  
282  
283  
284  
285  
286  
287  
288  
289  
290  
291  
292  
293  
294  
295  
296  
297  
298  
299  
300  
301  
302  
303  
304  
305  
306  
307  
308  
309  
310  
311  
312  
313  
314  
315  
316  
317  
318  
319  
320  
321  
322  
323  
324  
325  
326  
327  
328  
329  
330  
331  
332  
333  
334  
335  
336  
337  
338  
339  
340  
341  
342  
343  
344  
345  
346  
347  
348  
349  
350  
351  
352  
353  
354  
355  
356  
357  
358  
359  
360  
361  
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;

public class ClientRequestHandlerSSL implements Runnable
{
   private ByteBuffer wrapSrc, unwrapSrc;
   private ByteBuffer wrapDst, unwrapDst;

   private SSLEngine  engine;
   private Executor   ioWorker, taskWorkers;
   
   private MyServer serverHandle;
   private SocketChannel socketChannel;
   private Client client;

   /**
    * RECEIVE
    * @param serverHandle
    * @param client
    * @param engine
    * @param bufferSize
    * @param ioWorker
    * @param taskWorkers
    */

   public ClientRequestHandlerSSL(MyServer serverHandle, Client client, SSLEngine engine, int bufferSize)
   {
      System.out.println("construct read");
      this.serverHandle = serverHandle;
      this.socketChannel = null;
      this.client = client;
   System.out.println("Allocate RCV Buffer size: ["+bufferSize+"]");
      this.wrapSrc = ByteBuffer.allocateDirect(bufferSize);
      this.wrapDst = ByteBuffer.allocateDirect(bufferSize);

      this.unwrapSrc = ByteBuffer.allocateDirect(bufferSize);
      this.unwrapDst = ByteBuffer.allocateDirect(bufferSize);

      this.unwrapSrc.limit(0);

      this.engine = engine;
      this.engine.setUseClientMode(false);
      this.engine.setNeedClientAuth(false);
      this.engine.setWantClientAuth(false);
      try
      {
         this.engine.beginHandshake();
      }
      catch(SSLException e) {
         this.serverHandle.writeLogMessage("Can not begin handshake ["+e.getMessage()+"]");
      }
     
      this.ioWorker = Executors.newSingleThreadExecutor();
      this.taskWorkers = Executors.newFixedThreadPool(4);

      this.ioWorker.execute(this);
   }
   
   /**
    * SEND
    *
    * @param serverHandle
    * @param socketChannel
    * @param engine
    * @param bufferSize
    * @param ioWorker
    * @param taskWorkers
    */

   public ClientRequestHandlerSSL(MyServer serverHandle, SocketChannel socketChannel, SSLEngine engine, int bufferSize)
   {
      System.out.println("construct send");
      this.serverHandle = serverHandle;
      this.socketChannel = socketChannel;
      this.client = null;
System.out.println("Allocate SND Buffer size: ["+bufferSize+"]");
      this.wrapSrc = ByteBuffer.allocateDirect(bufferSize);
      this.wrapDst = ByteBuffer.allocateDirect(bufferSize);

      this.unwrapSrc = ByteBuffer.allocateDirect(bufferSize);
      this.unwrapDst = ByteBuffer.allocateDirect(bufferSize);

      this.unwrapSrc.limit(0);

      this.engine = engine;
      this.engine.setUseClientMode(false);
      this.engine.setNeedClientAuth(false);
      this.engine.setWantClientAuth(false);
     
      try
      {
         this.engine.beginHandshake();
      }
      catch(SSLException e) {
         this.serverHandle.writeLogMessage("Can not begin handshake ["+e.getMessage()+"]");
      }
     
      this.ioWorker = Executors.newSingleThreadExecutor();
      this.taskWorkers = Executors.newFixedThreadPool(4);

      this.ioWorker.execute(this);
   }

   public void handleSendData(ByteBuffer decrypted)
   {
      try
      {
         this.serverHandle.writeLogMessage("SSL data send ["+(new String(decrypted.array()))+"]");
         this.socketChannel.write(decrypted);
      }
      catch (IOException e)
      {
         e.printStackTrace();
      }
   }

   public void handleReceivedData(ByteBuffer encrypted)
   {
      byte[] dst = new byte[encrypted.remaining()];
      encrypted.get(dst);
       

      this.serverHandle.writeLogMessage("SSL data received ["+(new String(dst))+"]");
      this.serverHandle.writeLogMessage("=======================================================================================");
       this.serverHandle.writeLogMessage("SSL data received decoded ["+(MessageDeEncoder.decodeWebSocketFrame(dst))+"]");
   }

   public void onHandshakeFailure(Exception cause)
   {
      System.out.println("handshake failure");

       cause.printStackTrace();
   }

   public void onHandshakeSuccess()
   {
      System.out.println("handshake success");

       SSLSession session = engine.getSession();

       try
       {
          System.out.println("- local principal: " + session.getLocalPrincipal());
          System.out.println("- remote principal: " + session.getPeerPrincipal());
          System.out.println("- using cipher: " + session.getCipherSuite());
       }
       catch (Exception exc)
       {
          exc.printStackTrace();
       }
   }

   public void onClosed()
   {
     
   }

   public void send(final ByteBuffer data)
   {
      //wrapSrc.clear();
     System.out.println("send");
      this.ioWorker.execute(new Runnable()
      {
         @Override
         public void run()
         {
            wrapSrc.put(data);

            ClientRequestHandlerSSL.this.run();
         }
      });
   }

   public void receive(final ByteBuffer data)
   {
     unwrapSrc.clear();
     //unwrapDst.clear();
     System.out.println("receive");
      this.ioWorker.execute(new Runnable()
      {
         @Override
         public void run()
         {
            unwrapSrc.put(data);

            ClientRequestHandlerSSL.this.run();
         }
      });
   }

   public void run()
   {
      // executes non-blocking tasks on the IO-Worker
System.out.println("RUN");
      while (this.step())
      {
         continue;
      }
      System.out.println("Thread end");
      // apparently we hit a blocking-task...
  }

   private boolean step()
   {
      switch (engine.getHandshakeStatus())
      {
         case NOT_HANDSHAKING:
            System.out.println("not handshaking");
            boolean anything = false;
            {
               if (wrapSrc.position() > 0)
                  anything |= this.wrap();
               if (unwrapSrc.position() > 0)
                  anything |= this.unwrap();
            }
            return anything;

         case NEED_WRAP:
            System.out.println("need wrap");
            if (!this.wrap())
               return false;
            break;

         case NEED_UNWRAP:
            System.out.println("need unwrap");
            if (!this.unwrap())
               return false;
            break;

         case NEED_TASK:
            System.out.println("need task");
            final Runnable sslTask = engine.getDelegatedTask();
            Runnable wrappedTask = new Runnable()
            {
               @Override
               public void run()
               {
                  System.out.println("async SSL task: " + sslTask);
                  long t0 = System.nanoTime();
                  sslTask.run();
                  long t1 = System.nanoTime();
                  System.out.println("async SSL task took: " + (t1 - t0) / 1000000 + "ms");

                  // continue handling I/O
                 ioWorker.execute(ClientRequestHandlerSSL.this);
               }
            };
            taskWorkers.execute(wrappedTask);
            return false;

         case FINISHED:
            System.out.println("finished");
            throw new IllegalStateException("FINISHED");
      }
      System.out.println("true");
      return true;
   }

   private boolean wrap()
   {
      SSLEngineResult wrapResult;

      try
      {
         wrapSrc.flip();
         wrapResult = engine.wrap(wrapSrc, wrapDst);
         wrapSrc.compact();
      }
      catch (SSLException exc)
      {
         this.onHandshakeFailure(exc);
         return false;
      }

      switch (wrapResult.getStatus())
      {
         case OK:
            System.out.println("Wrap: OK");
            if (wrapDst.position() > 0)
            {
               wrapDst.flip();
               System.out.println("calling handleReceiveData");
               this.handleReceivedData(wrapDst);
               wrapDst.compact();
            }
            break;

         case BUFFER_UNDERFLOW:
            System.out.println("Wrap: Buffer underflow");
            // try again later
           break;

         case BUFFER_OVERFLOW:
            System.out.println("Wrap: Buffer overflow");
            throw new IllegalStateException("failed to wrap");

         case CLOSED:
            this.onClosed();
            return false;
      }

      return true;
   }

   private boolean unwrap()
   {
      SSLEngineResult unwrapResult;

      try
      {
         unwrapSrc.flip();
         unwrapResult = engine.unwrap(unwrapSrc, unwrapDst);
         unwrapSrc.compact();
      }
      catch (SSLException exc)
      {
         this.onHandshakeFailure(exc);
         return false;
      }

      switch (unwrapResult.getStatus())
      {
         case OK:
            System.out.println("Unwrap: OK");
            if (unwrapDst.position() > 0)
            {
               unwrapDst.flip();
               System.out.println("calling handleSendData");
               this.handleSendData(unwrapDst);
               unwrapDst.compact();
            }
            break;

         case CLOSED:
            this.onClosed();
            return false;

         case BUFFER_OVERFLOW:
            throw new IllegalStateException("failed to unwrap");

         case BUFFER_UNDERFLOW:
            System.out.println("Unwrap: Buffer underflow");
            return false;
      }

      switch (unwrapResult.getHandshakeStatus())
      {
         case FINISHED:
            this.onHandshakeSuccess();
            return false;
      }

      return true;
   }
}


My SSLContext implementation
1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
14  
15  
16  
17  
KeyStore ks = KeyStore.getInstance("JKS");
            KeyStore ts = KeyStore.getInstance("JKS");
            FileInputStream fin = new FileInputStream(keyStoreFilePath);
            ks.load(fin, keyStoreFilePassword.toCharArray());
     
            // Set up key manager factory to use our key store
           // Assume key password is the same as the key store file
           // password
           KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
            kmf.init(ks, keyStoreFilePassword.toCharArray());
           
            TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
            tmf.init(ts);
           
            // Initialize the SSLContext to work with our key managers.
           sslContext = SSLContext.getInstance("TLS");
            sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);


This is the result printed by ClientRequestHandlerSSL class to eclipse console when I open the secure websocket in Chrome:
construct read
Allocate RCV Buffer size: [65536]
receive
RUN
need unwrap
Unwrap: Buffer underflow
Thread end
RUN
need unwrap
Unwrap: OK
true
need task
Thread end
async SSL task: sun.security.ssl.Handshaker$DelegatedTask@1d0fe80
async SSL task took: 44ms
RUN
need wrap
Wrap: OK
calling handleReceiveData
true
need unwrap
Unwrap: Buffer underflow
Thread end

The code seems to work as but the result data written to my server logfile by "handleReceivedData" seems to be messed up. I can partially see data of my SSL certificate along with unreadable data. Obviously I do something terribly wrong.
I hope someone can please point me in the right direction?  Smiley
Pages: [1]
 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

CopyableCougar4 (24 views)
2014-08-22 19:31:30

atombrot (34 views)
2014-08-19 09:29:53

Tekkerue (30 views)
2014-08-16 06:45:27

Tekkerue (28 views)
2014-08-16 06:22:17

Tekkerue (18 views)
2014-08-16 06:20:21

Tekkerue (27 views)
2014-08-16 06:12:11

Rayexar (65 views)
2014-08-11 02:49:23

BurntPizza (41 views)
2014-08-09 21:09:32

BurntPizza (33 views)
2014-08-08 02:01:56

Norakomi (42 views)
2014-08-06 19:49:38
List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50

List of Learning Resources
by SilverTiger
2014-07-31 16:26:06

List of Learning Resources
by SilverTiger
2014-07-31 11:54:12

HotSpot Options
by dleskov
2014-07-08 01:59:08
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!