Advertisement
Guest User

Untitled

a guest
Jun 27th, 2019
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 14.11 KB | None | 0 0
  1. Details: General SSLEngine problem
  2. Trace detail #0: com.sun.net.ssl.internal.ssl.Handshaker.checkThrown(Handshaker.java:994)
  3. Trace detail #1: com.sun.net.ssl.internal.ssl.SSLEngineImpl.checkTaskThrown(SSLEngineImpl.java:459)
  4. Trace detail #2: com.sun.net.ssl.internal.ssl.SSLEngineImpl.writeAppRecord(SSLEngineImpl.java:1058)
  5. Trace detail #3: com.sun.net.ssl.internal.ssl.SSLEngineImpl.wrap(SSLEngineImpl.java:1030)
  6. Trace detail #4: javax.net.ssl.SSLEngine.wrap(SSLEngine.java:411)
  7. Trace detail #5: epic.clarity.extract.CRSslSocketHandler.doHandshake(CRSslSocketHandler.java:333)
  8. Trace detail #6: epic.clarity.extract.CRSslSocketHandler.readAndUnwrap(CRSslSocketHandler.java:282)
  9. Trace detail #7: epic.clarity.extract.CRSslSocketHandler.doHandshake(CRSslSocketHandler.java:322)
  10. Trace detail #8: epic.clarity.extract.CRSslSocketHandler.readAndUnwrap(CRSslSocketHandler.java:282)
  11. Trace detail #9: epic.clarity.extract.CRSslSocketHandler.doHandshake(CRSslSocketHandler.java:322)
  12. Trace detail #10: epic.clarity.extract.CRSslSocketHandler.ReadExtFile(CRSslSocketHandler.java:159)
  13.  
  14. public class CRSslSocketHandler extends CRSocketHandler{
  15.  
  16. private SSLEngine _engine;
  17. private SSLEngineResult.HandshakeStatus hsStatus;
  18.  
  19. /**
  20. * Stores the result from the last operation performed by the SSLEngine
  21. */
  22. private SSLEngineResult.Status status = null;
  23.  
  24. /** Application data decrypted from the data received from the peer.
  25. * This buffer must have enough space for a full unwrap operation,
  26. * so we can't use the buffer provided by the application, since we
  27. * have no control over its size.
  28. */
  29. private final ByteBuffer peerAppData;
  30. /** Network data received from the peer. Encrypted. */
  31. private final ByteBuffer peerNetData;
  32. /** Network data to be sent to the peer. Encrypted. */
  33. private final ByteBuffer netData;
  34.  
  35. /** Used during handshake, for the operations that don't consume any data */
  36. private ByteBuffer dummy;
  37.  
  38.  
  39. private boolean initialHandshake = false;
  40.  
  41. private final String[] AvailProtocol = {"TLSv1"};
  42.  
  43. private boolean FirstTime = true;
  44.  
  45. //Debug
  46. private BufferedWriter debugFile;
  47. private BufferedWriter test;
  48.  
  49.  
  50. /** Creates a new instance of CRSslSocketHandler */
  51. public CRSslSocketHandler(SocketChannel channel, DualKeyHashtable queryCollection, DualKeyHashtable routineCollection, long sn, String hostName, int portNum) throws Exception {
  52. super(channel, queryCollection, routineCollection, sn);
  53.  
  54.  
  55. // Debug purposes
  56. debugFile = new BufferedWriter(new FileWriter("SslDebug.txt",true));
  57. test = new BufferedWriter(new FileWriter("ssltest.txt",true));
  58. try{
  59. System.out.println("Create Ssl Context");
  60. test.write("Create Ssl Context");
  61.  
  62. SSLContext sslContext = SSLContext.getInstance("TLSv1");
  63. System.out.println("Init Ssl Context");
  64. test.write("Init Ssl Context");
  65.  
  66. /String Pass = "password";
  67. char[] passphrase = Pass.toCharArray();
  68.  
  69. System.out.println("Get keys");
  70. test.write("Get keys");
  71. KeyStore ks = KeyStore.getInstance("JKS");
  72. ks.load(new FileInputStream("keystore.ks"), passphrase);
  73. System.out.println("Get trust");
  74. test.write("Get trust");
  75. TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
  76. System.out.println("Init trust");
  77. test.write("Init trust");
  78. tmf.init(ks);
  79.  
  80. System.out.println("Init context");
  81. test.write("Init context");
  82. sslContext.init(null, tmf.getTrustManagers(), null);
  83. System.out.println("Create engine host name: " + hostName + " port number: " + portNum);
  84. test.write("Create engine host name: " + hostName + " port number: " + portNum);
  85. _engine = sslContext.createSSLEngine(hostName, portNum);
  86. // _engine = sslContext.createSSLEngine();
  87. System.out.println("Set client mode");
  88. test.write("Set client mode");
  89. _engine.setUseClientMode(true);
  90. _engine.setEnabledProtocols(AvailProtocol);
  91.  
  92.  
  93.  
  94. test.write("Begin Hanshaking");
  95. System.out.println("Begin Hanshaking");
  96. _engine.beginHandshake();
  97. hsStatus = _engine.getHandshakeStatus();
  98. }
  99. catch (IOException e){
  100.  
  101. }
  102. catch (Exception e) {
  103. System.out.println("Exception: " + e.getMessage());
  104. test.write("Exception: " + e.getMessage());
  105. test.close();
  106. }
  107. System.out.println("Alocate buffers");
  108. test.write("Alocate buffers");
  109. SSLSession session = _engine.getSession();
  110. peerNetData = ByteBuffer.allocate(session.getPacketBufferSize());
  111. peerAppData = ByteBuffer.allocate(session.getApplicationBufferSize());
  112. netData = ByteBuffer.allocate(session.getPacketBufferSize());
  113. // Change the position of the buffers so that a
  114. // call to hasRemaining() returns false. A buffer is considered
  115. // empty when the position is set to its limit, that is when
  116. // hasRemaining() returns false.
  117. peerAppData.position(peerAppData.limit());
  118. netData.position(netData.limit());
  119. char c = (char)(28);
  120. String msg = "OK" + c;
  121. dummy = ByteBuffer.wrap(msg.getBytes());
  122. // dummy = ByteBuffer.allocate(0);
  123. initialHandshake = true;
  124. test.close();
  125. }
  126.  
  127. protected int ReadExtFile(ByteBuffer buffer) throws IOException{
  128. if (initialHandshake) {
  129. doHandshake();
  130. }
  131. // Check if the stream is closed.
  132. if (_engine.isInboundDone()) {
  133. // We reached EOF.
  134. return EOF;
  135. }
  136. // First check if there is decrypted data waiting in the buffers
  137. if (!peerAppData.hasRemaining()) {
  138. int appBytesProduced = readAndUnwrap();
  139. if (appBytesProduced == EOF){
  140. debugFile.write("Failed to read");
  141. debugFile.close();
  142. return appBytesProduced;
  143. }
  144. if (appBytesProduced == 0) {
  145. return appBytesProduced;
  146. }
  147. }
  148.  
  149. // It's not certain that we will have some data decrypted ready to
  150. // be sent to the application. Anyway, copy as much data as possible
  151. int limit = Math.min(peerAppData.remaining(), buffer.remaining());
  152. for (int i = 0; i < limit; i++) {
  153. buffer.put(peerAppData.get());
  154. }
  155. return limit;
  156. }
  157. private int readAndUnwrap() throws IOException {
  158. // No decrypted data left on the buffers.
  159. // Try to read from the socket. There may be some data
  160. // on the peerNetData buffer, but it might not be sufficient.
  161. int bytesRead = _client.read(peerNetData);
  162. // decoder.decode(peerNetData, charBuffer, false);
  163. // charBuffer.flip();
  164. System.out.println("Read bytes " + bytesRead);
  165.  
  166.  
  167. if (bytesRead == EOF) {
  168. // We will not receive any more data. Closing the engine
  169. // is a signal that the end of stream was reached.
  170. _engine.closeInbound();
  171. // EOF. But do we still have some useful data available?
  172. if (peerNetData.position() == 0 ||
  173. status == SSLEngineResult.Status.BUFFER_UNDERFLOW) {
  174. // Yup. Either the buffer is empty or it's in underflow,
  175. // meaning that there is not enough data to reassemble a
  176. // TLS packet. So we can return EOF.
  177. return EOF;
  178. }
  179. // Although we reach EOF, we still have some data left to
  180. // be decrypted. We must process it
  181. }
  182.  
  183. // Prepare the application buffer to receive decrypted data
  184. peerAppData.clear();
  185.  
  186. // Prepare the net data for reading.
  187. peerNetData.flip();
  188. SSLEngineResult res;
  189. System.out.println("Do unwrap " + bytesRead);
  190. try{
  191. do {
  192. res = _engine.unwrap(peerNetData, peerAppData);
  193. System.out.println("Read status" + res.getHandshakeStatus().toString());
  194. // During an handshake renegotiation we might need to perform
  195. // several unwraps to consume e handshake data.
  196. } while (res.getStatus() == SSLEngineResult.Status.OK &&
  197. res.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.NEED_UNWRAP &&
  198. res.bytesProduced() == 0);
  199.  
  200. System.out.println("Read status" + res.getHandshakeStatus().toString());
  201. // If the initial handshake finish after an unwrap, we must activate
  202. // the application interestes, if any were set during the handshake
  203. if (res.getHandshakeStatus() == SSLEngineResult.HandshakeStatus.FINISHED) {
  204. initialHandshake = false;
  205. }
  206. // If no data was produced, and the status is still ok, try to read once more
  207. if (peerAppData.position() == 0 &&
  208. res.getStatus() == SSLEngineResult.Status.OK &&
  209. peerNetData.hasRemaining()) {
  210. res = _engine.unwrap(peerNetData, peerAppData);
  211. }
  212. /*
  213. * The status may be:
  214. * OK - Normal operation
  215. * OVERFLOW - Should never happen since the application buffer is
  216. * sized to hold the maximum packet size.
  217. * UNDERFLOW - Need to read more data from the socket. It's normal.
  218. * CLOSED - The other peer closed the socket. Also normal.
  219. */
  220. status = res.getStatus();
  221. hsStatus = res.getHandshakeStatus();
  222. // Should never happen, the peerAppData must always have enough space
  223. // for an unwrap operation
  224. assert status != SSLEngineResult.Status.BUFFER_OVERFLOW :
  225. "Buffer should not overflow: " + res.toString();
  226. }
  227. catch (Exception e){
  228. System.out.println("Error: " + e.getMessage());
  229. }
  230.  
  231.  
  232.  
  233.  
  234. // The handshake status here can be different than NOT_HANDSHAKING
  235. // if the other peer closed the connection. So only check for it
  236. // after testing for closure.
  237. if (status == SSLEngineResult.Status.CLOSED) {
  238. debugFile.write("Connection is being closed by peer.");
  239. return EOF;
  240. }
  241.  
  242. // Prepare the buffer to be written again.
  243. peerNetData.compact();
  244. // And the app buffer to be read.
  245. peerAppData.flip();
  246.  
  247. if (hsStatus == SSLEngineResult.HandshakeStatus.NEED_TASK ||
  248. hsStatus == SSLEngineResult.HandshakeStatus.NEED_WRAP ||
  249. hsStatus == SSLEngineResult.HandshakeStatus.FINISHED)
  250. {
  251. debugFile.write("Rehandshaking...");
  252. doHandshake();
  253. }
  254.  
  255. return peerAppData.remaining();
  256. }
  257.  
  258. public void closeSocket(boolean timeout){
  259.  
  260. super.closeSocket(timeout);
  261. try{
  262. debugFile.write("Close");
  263. debugFile.close();
  264. }catch(IOException e){}
  265. }
  266.  
  267. /**
  268. * Execute delegated tasks in the main thread. These are compute
  269. * intensive tasks, so there's no point in scheduling them in a different
  270. * thread.
  271. */
  272. private void doTasks() {
  273. Runnable task;
  274. while ((task = _engine.getDelegatedTask()) != null) {
  275. task.run();
  276. }
  277. hsStatus = _engine.getHandshakeStatus();
  278. }
  279. private void doHandshake() throws IOException {
  280. while (true) {
  281. SSLEngineResult res;
  282. System.out.println("Handshake status: " + hsStatus.toString());
  283. switch (hsStatus) {
  284. case FINISHED:
  285. initialHandshake = false;
  286. return;
  287. case NEED_TASK:
  288. doTasks();
  289. // The hs status was updated, so go back to the switch
  290. break;
  291. case NEED_UNWRAP:
  292. readAndUnwrap();
  293. return;
  294. case NEED_WRAP:
  295.  
  296. if (netData.hasRemaining()) {
  297. return;
  298. }
  299. // Prepare to write
  300. netData.clear();
  301.  
  302. try{
  303. res = _engine.wrap(dummy, netData);
  304.  
  305. if (res.bytesProduced() == 0){
  306. System.out.println("No net data produced during handshake wrap.");
  307. }
  308. else{
  309. System.out.println("Result status: " + res.getStatus() + "Bytes porduced: " + res.bytesProduced());
  310. }
  311. if (res.bytesConsumed() != 0){
  312. System.out.println("App data consumed during handshake wrap.");
  313. }
  314. hsStatus = res.getHandshakeStatus();
  315. }catch(SSLException se){
  316.  
  317. System.out.println("Error: " + se.getMessage());
  318. System.out.println("Details: " + se.getLocalizedMessage());
  319. throw se;
  320. }
  321.  
  322. System.out.println(hsStatus.toString());
  323. netData.flip();
  324. try{
  325. int writebytes = _client.write(netData);
  326. System.out.println("Number of bytes sent: " + writebytes);
  327. if (netData.hasRemaining()) {
  328. System.out.println("netdata has remaining");
  329. }
  330. }
  331. catch(Exception e){
  332. System.out.println(e.getMessage());
  333. }
  334. break;
  335. case NOT_HANDSHAKING:
  336. assert false : "doHandshake() should never reach the NOT_HANDSHAKING state";
  337. return;
  338. }
  339. }
  340. }
  341.  
  342.  
  343. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement