summaryrefslogtreecommitdiffstats
path: root/simple/simple-http/src/test/java/org/simpleframework/http/RenegotiationExample.java
blob: 0ee0e7d44f4649e09d9970c5d9ab4ec1fd6eb517 (plain)
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
package org.simpleframework.http;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.channels.SelectableChannel;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;

import javax.net.SocketFactory;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.X509TrustManager;

import org.simpleframework.http.core.Client.AnonymousTrustManager;
import org.simpleframework.transport.ByteCursor;
import org.simpleframework.transport.TransportProcessor;
import org.simpleframework.transport.TransportSocketProcessor;
import org.simpleframework.transport.SocketProcessor;
import org.simpleframework.transport.Socket;
import org.simpleframework.transport.Transport;
import org.simpleframework.transport.TransportCursor;
import org.simpleframework.transport.TransportWriter;
import org.simpleframework.transport.connect.Connection;
import org.simpleframework.transport.connect.SocketConnection;
import org.simpleframework.transport.trace.TraceAnalyzer;
import org.simpleframework.transport.trace.Trace;

public class RenegotiationExample {

   public static void main(String[] list) throws Exception {
      Connection serverCon = createServer(false, 443);      
      /*SSLSocket socketCon = createClient();
      OutputStream out = socketCon.getOutputStream();
      
      for(int i = 0; i < 1000; i++) {
         out.write("TEST".getBytes());   
         out.flush();
         Thread.sleep(5000);
      }*/
      Thread.sleep(1000000);
      serverCon.close();
   }
   
   public static Connection createServer(boolean certificateRequired, int listenPort) throws Exception {
      System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true");
      System.setProperty("sun.security.ssl.allowLegacyHelloMessages", "true");
      File file = new File("C:\\work\\development\\async_http\\yieldbroker-proxy-trading\\etc\\uat.yieldbroker.com.pfx");
      KeyStoreReader reader = new KeyStoreReader(KeyStoreType.PKCS12, file, "p", "p");
      SecureSocketContext context = new SecureSocketContext(reader, SecureProtocol.TLS);
      SSLContext sslContext = context.getContext();
      TraceAnalyzer agent = new MockAgent();
      TransportProcessor processor = new MockTransportProcessor();
      TransportSocketProcessor server = new TransportSocketProcessor(processor);
      ConfigurableCertificateServer certServer = new ConfigurableCertificateServer(server);
      SocketConnection con = new SocketConnection(certServer, agent);
      SocketAddress serverAddress = new InetSocketAddress(listenPort);
      
      certServer.setCertRequired(certificateRequired);
      con.connect(serverAddress, sslContext);
      
      return con;
   }
   
   
   public static SSLSocket createClient() throws Exception {
      System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true");
      System.setProperty("sun.security.ssl.allowLegacyHelloMessages", "true");
      File file = new File("C:\\work\\development\\async_http\\yieldbroker-proxy-benchmark\\etc\\niall.pfx");
      KeyStoreReader reader = new KeyStoreReader(KeyStoreType.PKCS12, file, "1234", "1234");
      SecureSocketContext context = new SecureSocketContext(reader, SecureProtocol.TLS);   
      SocketFactory factory = context.getSocketFactory();
      SSLSocket socket = (SSLSocket)factory.createSocket("localhost", 9333);
      socket.setEnabledProtocols(new String[] {"SSLv3", "TLSv1"});
      
      return socket;
   }
   
   public static class ConfigurableCertificateServer implements SocketProcessor {
      
      private SocketProcessor server;
      private boolean certRequired;
      
      public ConfigurableCertificateServer(SocketProcessor server) {
         this.server = server;
      }
      
      public void setCertRequired(boolean certRequired) {
         this.certRequired = certRequired;
      }

      public void process(Socket socket) throws IOException {
         if(certRequired) {
            socket.getEngine().setNeedClientAuth(true);
         }
         server.process(socket);
      }

      public void stop() throws IOException {
         System.err.println("stop");
      }      
   }
   
   public static class TransportPoller extends Thread {
      
      private final ByteCursor cursor;
      private final Transport transport;
      
      
      public TransportPoller(Transport transport) {
         this.cursor = new TransportCursor(transport);
         this.transport = transport;
      }
      
      public void run() {
         try {
            System.err.println("Poller started");
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] chunk = new byte[1024];
            int count = 0;
            
            while(cursor.isOpen()) {
               while(cursor.isReady()) {
                  count = cursor.read(chunk);
                  if(count != 0) {
                     out.write(chunk, 0, count);                     
                  }                  
               }
               String message = out.toString();
               out.reset();
               if(message != null && !message.isEmpty()) {
                  SSLEngine engine = transport.getEngine();
                  String certificateInfo = null;
                  
                  if(engine != null) {
                     try {
                        Certificate[] list = engine.getSession().getPeerCertificates();
                        StringBuilder builder = new StringBuilder();
                        for(Certificate cert : list) {
                           X509Certificate x509 = (X509Certificate)cert;
                           builder.append(x509);
                        }
                        certificateInfo = builder.toString();
                     } catch(Exception e) {
                        
                        // Here we would have to ask the transport to renegotiate.....!!!                      
                        transport.getEngine().setWantClientAuth(true);
                        transport.getEngine().beginHandshake();
                        transport.getEngine().setWantClientAuth(true);
                        for(int i = 0; i < 100; i++) {
                           Runnable task = transport.getEngine().getDelegatedTask();
                           if(task != null){
                              task.run();
                           }
                        }
                        certificateInfo = e.getMessage();
                     }
                  }
                  TransportWriter sender = new TransportWriter(transport);
                  sender.write(
                        ("HTTP/1.1 200 OK\r\n" + 
                        "Connection: keep-alive\r\n"+
                        "Content-Length: 5\r\n"+
                        "Content-Type: text/plain\r\n"+
                        "\r\n"+ 
                        "hello").getBytes());                 
                  
                  
                  sender.flush();
                  
                  
                  
                  
                  System.err.println("["+message+"]: " + certificateInfo);                  
               }
               Thread.sleep(5000);
            }
         } catch(Exception e) {
            e.printStackTrace();
         }
      }
   }
   
   
   
   public static class MockTransportProcessor implements TransportProcessor {

      public void process(Transport transport) throws IOException {
         System.err.println("New transport");        
         TransportPoller poller = new TransportPoller(transport);
         poller.start(); 
      }

      public void stop() throws IOException {
         System.err.println("Transport stopped");         
      }      
   }
   
   private static class MockAgent implements TraceAnalyzer {

      public Trace attach(SelectableChannel channel) {
         return new Trace() {
            public void trace(Object event) {
               trace(event, "");
            }
            public void trace(Object event, Object value) {
               if(value != null && !String.valueOf(value).isEmpty()) {
                  System.err.printf("%s: %s%n", event, value);
               } else {
                  System.err.println(event);
               }               
            }            
         };
      }

      public void stop() {
         System.err.println("Stop agent");
      }
      
   }

   public enum KeyStoreType {
      JKS("JKS", "SunX509"),
      PKCS12("PKCS12", "SunX509");
      
      private final String algorithm;
      private final String type;
      
      private KeyStoreType(String type, String algorithm) {
         this.algorithm = algorithm;
         this.type = type;
      }
      
      public String getType() {
         return type;
      }
      
      public KeyStore getKeyStore() throws KeyStoreException {
         return KeyStore.getInstance(type); 
      }
      
      public KeyManagerFactory getKeyManagerFactory() throws NoSuchAlgorithmException {
         return KeyManagerFactory.getInstance(algorithm);   
      }
   }
   
   private static class KeyStoreManager {

      private final KeyStoreType keyStoreType;

      public KeyStoreManager(KeyStoreType keyStoreType) {
         this.keyStoreType = keyStoreType;
      }
      
      public KeyManager[] getKeyManagers(InputStream keyStoreSource, String keyStorePassword, String keyManagerPassword) throws Exception {
         KeyStore keyStore = keyStoreType.getKeyStore();
         KeyManagerFactory keyManagerFactory = keyStoreType.getKeyManagerFactory();
         
         keyStore.load(keyStoreSource, keyManagerPassword.toCharArray());
          keyManagerFactory.init(keyStore, keyManagerPassword.toCharArray());
         
         return keyManagerFactory.getKeyManagers();
      }

   }
   
   private static class KeyStoreReader {

      private final KeyStoreManager keyStoreManager;
      private final String keyManagerPassword;
      private final String keyStorePassword;
      private final File keyStore;
      
      public KeyStoreReader(KeyStoreType keyStoreType, File keyStore, String keyStorePassword, String keyManagerPassword) {
         this.keyStoreManager = new KeyStoreManager(keyStoreType);
         this.keyManagerPassword = keyManagerPassword;
         this.keyStorePassword = keyStorePassword;
         this.keyStore = keyStore;
      }
      
      public KeyManager[] getKeyManagers() throws Exception {
         InputStream storeSource = new FileInputStream(keyStore);
         
         try {
            return keyStoreManager.getKeyManagers(storeSource, keyStorePassword, keyManagerPassword);
         } finally {
            storeSource.close();
         }
      }
   }

   public enum SecureProtocol {
      DEFAULT("Default"),
      SSL("SSL"),
      TLS("TLS");
      
      private final String protocol;
      
      private SecureProtocol(String protocol) {
         this.protocol = protocol;
      }
      
      public SSLContext getContext() throws NoSuchAlgorithmException {
         return SSLContext.getInstance(protocol);
      }
   }
   
   private static class SecureSocketContext {

      private final X509TrustManager trustManager;
      private final X509TrustManager[] trustManagers;
      private final KeyStoreReader keyStoreReader;
      private final SecureProtocol secureProtocol;

      public SecureSocketContext(KeyStoreReader keyStoreReader, SecureProtocol secureProtocol) {
         this.trustManager = new AnonymousTrustManager();
         this.trustManagers = new X509TrustManager[]{trustManager};
         this.keyStoreReader = keyStoreReader;
         this.secureProtocol = secureProtocol;
      }
      
      public SSLContext getContext() throws Exception {
         KeyManager[] keyManagers = keyStoreReader.getKeyManagers();
         SSLContext secureContext = secureProtocol.getContext();
         
         secureContext.init(keyManagers, trustManagers, null);     
         
         return secureContext;
      }

      public SocketFactory getSocketFactory() throws Exception {
         KeyManager[] keyManagers = keyStoreReader.getKeyManagers();
         SSLContext secureContext = secureProtocol.getContext();
         
         secureContext.init(keyManagers, trustManagers, null);      
          
         return secureContext.getSocketFactory();
      }
   }

}