aboutsummaryrefslogtreecommitdiffstats
path: root/java/com/tigervnc/network/SSLEngineManager.java
blob: c0110995663016d9ad403c1ec6086fe7c8c4a703 (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
/* Copyright (C) 2012,2014 Brian P. Hinz
 * Copyright (C) 2012 D. R. Commander.  All Rights Reserved.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, 5th Floor, Boston, MA 02110-1301 USA
 */
 package com.tigervnc.network;

import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import javax.net.ssl.*;
import javax.net.ssl.SSLEngineResult.*;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import com.tigervnc.rdr.FdInStream;
import com.tigervnc.rdr.FdOutStream;

public class SSLEngineManager {

  private SSLEngine engine = null;

  private int appBufSize;
  private int pktBufSize;

  private ByteBuffer myAppData;
  private ByteBuffer myNetData;
  private ByteBuffer peerAppData;
  private ByteBuffer peerNetData;

  private Executor executor;
  private FdInStream in;
  private FdOutStream os;

  public SSLEngineManager(SSLEngine sslEngine, FdInStream is_,
                          FdOutStream os_) throws IOException {

    in = is_;
    os = os_;
    engine = sslEngine;

    executor = Executors.newSingleThreadExecutor();

    pktBufSize = engine.getSession().getPacketBufferSize();
    appBufSize = engine.getSession().getApplicationBufferSize();

    myAppData =
      ByteBuffer.allocate(Math.max(appBufSize, os.getBufSize()));
    myNetData = ByteBuffer.allocate(pktBufSize);
    peerAppData = ByteBuffer.allocate(appBufSize);
    peerNetData = ByteBuffer.allocate(pktBufSize);
  }

  public void doHandshake() throws Exception {

    // Begin handshake
    engine.beginHandshake();
    SSLEngineResult.HandshakeStatus hs = engine.getHandshakeStatus();

    // Process handshaking message
    while (hs != SSLEngineResult.HandshakeStatus.FINISHED &&
           hs != SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) {

      switch (hs) {
    
      case NEED_UNWRAP:
        // Receive handshaking data from peer
        peerNetData.flip();
        SSLEngineResult res = engine.unwrap(peerNetData, peerAppData);
        peerNetData.compact();
        hs = res.getHandshakeStatus();
        // Check status
        switch (res.getStatus()) {
          case BUFFER_UNDERFLOW:
            int max = Math.min(peerNetData.remaining(), in.getBufSize());
            int m = in.check(1, max, true);
            int pos = peerNetData.position();
            in.readBytes(peerNetData.array(), pos, m);
            peerNetData.position(pos+m);
            peerNetData.flip();
            peerNetData.compact();
            break;
    
          case OK:
            // Process incoming handshaking data
            break;
    
          case CLOSED:
            engine.closeInbound();
            break;
    
        }
        break;
    
      case NEED_WRAP:
        // Empty the local network packet buffer.
        myNetData.clear();
    
        // Generate handshaking data
        res = engine.wrap(myAppData, myNetData);
        hs = res.getHandshakeStatus();
    
        // Check status
        switch (res.getStatus()) {
          case OK:
            myAppData.compact();
            myNetData.flip();
            os.writeBytes(myNetData.array(), 0, myNetData.remaining());
            os.flush();
            myNetData.clear();
            break;
    
          case BUFFER_OVERFLOW:
            // FIXME: How much larger should the buffer be?
            break;
    
          case CLOSED:
            engine.closeOutbound();
            break;
    
        }
        break;

      case NEED_TASK:
        // Handle blocking tasks
        executeTasks();
        break;
      }
      hs = engine.getHandshakeStatus();
    }
  }

  private void executeTasks() {
    Runnable task;
    while ((task = engine.getDelegatedTask()) != null) {
      executor.execute(task);
    }
  }

  public int read(byte[] data, int dataPtr, int length) throws IOException {
    // Read SSL/TLS encoded data from peer
    int bytesRead = 0;
    peerNetData.flip();
    SSLEngineResult res = engine.unwrap(peerNetData, peerAppData);
    peerNetData.compact();
    switch (res.getStatus()) {
      case OK :
        bytesRead = Math.min(length, res.bytesProduced());
        peerAppData.flip();
        peerAppData.get(data, dataPtr, bytesRead);
        peerAppData.compact();
        break;

      case BUFFER_UNDERFLOW:
        // need more net data
        int pos = peerNetData.position();
        // attempt to drain the underlying buffer first
        int need = peerNetData.remaining();
        int avail = in.check(1, in.getBufSize(), false);
        if (avail < need)
          avail = in.check(1, Math.min(need, in.getBufSize()), true);
        in.readBytes(peerNetData.array(), pos, Math.min(need, avail));
        peerNetData.position(pos+Math.min(need, avail));
        break;

      case CLOSED:
        engine.closeInbound();
        break;

    }
    return bytesRead;
  }

  public int write(byte[] data, int dataPtr, int length) throws IOException {
    int n = 0;
    myAppData.put(data, dataPtr, length);
    myAppData.flip();
    while (myAppData.hasRemaining()) {
      SSLEngineResult res = engine.wrap(myAppData, myNetData);
      n += res.bytesConsumed();
      switch (res.getStatus()) {
        case OK:
          break;

        case BUFFER_OVERFLOW:
          // Make room in the buffer by flushing the outstream
          myNetData.flip();
          os.writeBytes(myNetData.array(), 0, myNetData.remaining());
          os.flush();
          myNetData.clear();
          break;

        case CLOSED:
          engine.closeOutbound();
          break;
      }
    }
    myAppData.clear();
    myNetData.flip();
    os.writeBytes(myNetData.array(), 0, myNetData.remaining());
    os.flush();
    myNetData.clear();
    return n;
  }

  public SSLSession getSession() {
    return engine.getSession();
  }

}