OpenSSLEngineSocketImpl.java 19.7 KB
Newer Older
nmittler's avatar
nmittler committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
 * Copyright 2016 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

17 18 19 20
package org.conscrypt;

import static javax.net.ssl.SSLEngineResult.Status.OK;

21
import java.io.EOFException;
22 23 24 25 26 27 28 29 30 31 32 33
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.security.PrivateKey;
import java.security.cert.CertificateException;
import javax.crypto.SecretKey;
import javax.net.ssl.SSLEngineResult;
34
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
35 36 37 38
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509KeyManager;
import javax.security.auth.x500.X500Principal;
39
import org.conscrypt.util.EmptyArray;
40 41 42 43 44 45

/**
 * Implements crypto handling by delegating to OpenSSLEngine. Used for socket implementations
 * that are not backed by a real OS socket.
 */
public final class OpenSSLEngineSocketImpl extends OpenSSLSocketImplWrapper {
46
    private static final ByteBuffer EMPTY_BUFFER = ByteBuffer.allocate(0);
47

48
    private final OpenSSLEngineImpl engine;
49 50 51
    private final Socket socket;
    private final OutputStreamWrapper outputStreamWrapper;
    private final InputStreamWrapper inputStreamWrapper;
52
    private boolean handshakeComplete;
53 54

    public OpenSSLEngineSocketImpl(Socket socket, String hostname, int port, boolean autoClose,
55
            SSLParametersImpl sslParameters) throws IOException {
56 57
        super(socket, hostname, port, autoClose, sslParameters);
        this.socket = socket;
58
        engine = new OpenSSLEngineImpl(hostname, port, sslParameters);
59 60
        outputStreamWrapper = new OutputStreamWrapper();
        inputStreamWrapper = new InputStreamWrapper();
61
        engine.setUseClientMode(sslParameters.getUseClientMode());
62 63 64 65 66 67
    }

    @Override
    public void startHandshake() throws IOException {
        // Trigger the handshake
        boolean beginHandshakeCalled = false;
68 69
        while (!handshakeComplete) {
            switch (engine.getHandshakeStatus()) {
70 71 72
                case NOT_HANDSHAKING: {
                    if (!beginHandshakeCalled) {
                        beginHandshakeCalled = true;
73
                        engine.beginHandshake();
74 75
                        break;
                    }
76 77 78 79 80
                    // Fall through to FINISHED processing.
                }
                case FINISHED: {
                    completeHandshake();
                    return;
81 82
                }
                case NEED_WRAP: {
83
                    outputStreamWrapper.write(EMPTY_BUFFER);
84 85 86
                    break;
                }
                case NEED_UNWRAP: {
87 88 89 90
                    if (inputStreamWrapper.read(EmptyArray.BYTE) == -1) {
                        // Can't complete the handshake due to EOF.
                        throw new EOFException();
                    }
91 92 93
                    break;
                }
                case NEED_TASK: {
94
                    throw new IllegalStateException("OpenSSLEngineImpl returned NEED_TASK");
95
                }
96
                default: { break; }
97 98 99 100 101
            }
        }
    }

    @Override
102
    public void onSSLStateChange(int type, int val) {
103 104 105 106
        throw new AssertionError("Should be handled by engine");
    }

    @Override
107
    public void verifyCertificateChain(long[] certRefs, String authMethod)
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
            throws CertificateException {
        throw new AssertionError("Should be handled by engine");
    }

    @Override
    public InputStream getInputStream() throws IOException {
        return inputStreamWrapper;
    }

    @Override
    public OutputStream getOutputStream() throws IOException {
        return outputStreamWrapper;
    }

    @Override
    public SSLSession getSession() {
124
        return engine.getSession();
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
    }

    @Override
    public boolean getEnableSessionCreation() {
        return super.getEnableSessionCreation();
    }

    @Override
    public void setEnableSessionCreation(boolean flag) {
        super.setEnableSessionCreation(flag);
    }

    @Override
    public String[] getSupportedCipherSuites() {
        return super.getSupportedCipherSuites();
    }

    @Override
    public String[] getEnabledCipherSuites() {
        return super.getEnabledCipherSuites();
    }

    @Override
    public void setEnabledCipherSuites(String[] suites) {
        super.setEnabledCipherSuites(suites);
    }

    @Override
    public String[] getSupportedProtocols() {
        return super.getSupportedProtocols();
    }

    @Override
    public String[] getEnabledProtocols() {
        return super.getEnabledProtocols();
    }

    @Override
    public void setEnabledProtocols(String[] protocols) {
        super.setEnabledProtocols(protocols);
    }

    @Override
    public void setUseSessionTickets(boolean useSessionTickets) {
        super.setUseSessionTickets(useSessionTickets);
    }

    @Override
    public void setHostname(String hostname) {
        super.setHostname(hostname);
    }

    @Override
    public void setChannelIdEnabled(boolean enabled) {
        throw new UnsupportedOperationException("Not supported");
    }

    @Override
    public byte[] getChannelId() throws SSLException {
        throw new UnsupportedOperationException("Not supported");
    }

    @Override
    public void setChannelIdPrivateKey(PrivateKey privateKey) {
        throw new UnsupportedOperationException("FIXME");
    }

    @Override
    public boolean getUseClientMode() {
        return super.getUseClientMode();
    }

    @Override
    public void setUseClientMode(boolean mode) {
199
        engine.setUseClientMode(mode);
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
    }

    @Override
    public boolean getWantClientAuth() {
        return super.getWantClientAuth();
    }

    @Override
    public boolean getNeedClientAuth() {
        return super.getNeedClientAuth();
    }

    @Override
    public void setNeedClientAuth(boolean need) {
        super.setNeedClientAuth(need);
    }

    @Override
    public void setWantClientAuth(boolean want) {
        super.setWantClientAuth(want);
    }

    @Override
    public void sendUrgentData(int data) throws IOException {
        super.sendUrgentData(data);
    }

    @Override
    public void setOOBInline(boolean on) throws SocketException {
        super.setOOBInline(on);
    }

    @Override
    public void setSoWriteTimeout(int writeTimeoutMilliseconds) throws SocketException {
        throw new UnsupportedOperationException("Not supported");
    }

    @Override
    public int getSoWriteTimeout() throws SocketException {
        return 0;
        //throw new UnsupportedOperationException("Not supported");
    }

    @Override
    public void setHandshakeTimeout(int handshakeTimeoutMilliseconds) throws SocketException {
        throw new UnsupportedOperationException("Not supported");
    }

    @Override
    public synchronized void close() throws IOException {
250 251 252
        // Closing Socket.
        engine.closeInbound();
        engine.closeOutbound();
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
        socket.close();
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
    }

    @Override
    public SocketChannel getChannel() {
        return super.getChannel();
    }

    @Override
    public FileDescriptor getFileDescriptor$() {
        throw new UnsupportedOperationException("Not supported");
    }

    @Override
    public byte[] getNpnSelectedProtocol() {
273
        return engine.getNpnSelectedProtocol();
274 275 276 277
    }

    @Override
    public byte[] getAlpnSelectedProtocol() {
278
        return engine.getAlpnSelectedProtocol();
279 280 281 282 283 284 285 286 287 288 289 290 291 292
    }

    @Override
    public void setNpnProtocols(byte[] npnProtocols) {
        super.setNpnProtocols(npnProtocols);
    }

    @Override
    public void setAlpnProtocols(byte[] alpnProtocols) {
        super.setAlpnProtocols(alpnProtocols);
    }

    @Override
    public String chooseServerAlias(X509KeyManager keyManager, String keyType) {
293
        return engine.chooseServerAlias(keyManager, keyType);
294 295 296
    }

    @Override
297 298 299
    public String chooseClientAlias(
            X509KeyManager keyManager, X500Principal[] issuers, String[] keyTypes) {
        return engine.chooseClientAlias(keyManager, issuers, keyTypes);
300 301 302 303
    }

    @Override
    public String chooseServerPSKIdentityHint(PSKKeyManager keyManager) {
304
        return engine.chooseServerPSKIdentityHint(keyManager);
305 306 307 308
    }

    @Override
    public String chooseClientPSKIdentity(PSKKeyManager keyManager, String identityHint) {
309
        return engine.chooseClientPSKIdentity(keyManager, identityHint);
310 311 312 313
    }

    @Override
    public SecretKey getPSKKey(PSKKeyManager keyManager, String identityHint, String identity) {
314 315 316 317 318 319 320 321
        return engine.getPSKKey(keyManager, identityHint, identity);
    }

    private void completeHandshake() {
        if (!handshakeComplete) {
            handshakeComplete = true;
            super.notifyHandshakeCompletedListeners();
        }
322 323 324 325 326
    }

    /**
     * Wrap bytes written to the underlying socket.
     */
327 328 329 330 331
    private final class OutputStreamWrapper extends OutputStream {
        private final Object stateLock = new Object();
        private ByteBuffer target;
        private OutputStream socketOutputStream;
        private SocketChannel socketChannel;
332

333
        OutputStreamWrapper() {}
334

335 336 337
        @Override
        public void write(int b) throws IOException {
            write(new byte[] {(byte) b});
338 339 340 341
        }

        @Override
        public void write(byte[] b) throws IOException {
342
            write(ByteBuffer.wrap(b));
343 344 345
        }

        @Override
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
        public void write(byte[] b, int off, int len) throws IOException {
            write(ByteBuffer.wrap(b, off, len));
        }

        private void write(ByteBuffer buffer) throws IOException {
            synchronized (stateLock) {
                try {
                    init();

                    // Need to loop through at least once to enable handshaking where no application
                    // bytes are
                    // processed.
                    int len = buffer.remaining();
                    SSLEngineResult engineResult;
                    do {
                        target.clear();
                        engineResult = engine.wrap(buffer, target);
                        if (engineResult.getStatus() != OK) {
                            throw new SSLException(
                                    "Unexpected engine result " + engineResult.getStatus());
                        }
                        if (target.position() != engineResult.bytesProduced()) {
                            throw new SSLException("Engine bytesProduced "
                                    + engineResult.bytesProduced()
                                    + " does not match bytes written " + target.position());
                        }
                        len -= engineResult.bytesConsumed();
                        if (len != buffer.remaining()) {
                            throw new SSLException(
                                    "Engine did not read the correct number of bytes");
                        }

                        target.flip();

                        // Write the data to the socket.
                        if (socketChannel != null) {
                            // Loop until all of the data is written to the channel. Typically,
                            // SocketChannel writes will return only after all bytes are written,
                            // so we won't really loop here.
                            while (target.hasRemaining()) {
                                socketChannel.write(target);
                            }
                        } else {
                            // Target is a heap buffer.
                            socketOutputStream.write(target.array(), 0, target.position());
                        }
                        if (engineResult.getHandshakeStatus() == HandshakeStatus.FINISHED) {
                            completeHandshake();
                        }
                    } while (len > 0);
                } catch (IOException e) {
                    e.printStackTrace();
                    throw e;
                } catch (RuntimeException e) {
                    e.printStackTrace();
                    throw e;
402
                }
403
            }
404 405 406 407
        }

        @Override
        public void flush() throws IOException {
408 409 410 411
            synchronized (stateLock) {
                init();
                socketOutputStream.flush();
            }
412 413 414 415 416 417 418
        }

        @Override
        public void close() throws IOException {
            socket.close();
        }

419 420 421 422 423 424 425 426 427 428 429 430
        private void init() throws IOException {
            if (socketOutputStream == null) {
                socketOutputStream = socket.getOutputStream();
                socketChannel = socket.getChannel();
                if (socketChannel != null) {
                    // Optimization. Using direct buffers wherever possible to avoid passing
                    // arrays to JNI.
                    target = ByteBuffer.allocateDirect(engine.getSession().getPacketBufferSize());
                } else {
                    target = ByteBuffer.allocate(engine.getSession().getPacketBufferSize());
                }
            }
431 432 433 434 435 436
        }
    }

    /**
     * Unwrap bytes read from the underlying socket.
     */
437 438
    private final class InputStreamWrapper extends InputStream {
        private final Object stateLock = new Object();
439 440
        private final byte[] singleByte = new byte[1];
        private final ByteBuffer fromEngine;
441
        private ByteBuffer fromSocket;
442
        private InputStream socketInputStream;
443
        private SocketChannel socketChannel;
444

445 446 447
        InputStreamWrapper() {
            fromEngine = ByteBuffer.allocateDirect(engine.getSession().getApplicationBufferSize());
            // Initially fromEngine.remaining() == 0.
448 449 450
            fromEngine.flip();
        }

451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
        @Override
        public int read() throws IOException {
            synchronized (stateLock) {
                // Handle returning of -1 if EOF is reached.
                int count = read(singleByte, 0, 1);
                if (count == -1) {
                    // Handle EOF.
                    return -1;
                }
                if (count != 1) {
                    throw new SSLException("read incorrect number of bytes " + count);
                }
                return (int) singleByte[0];
            }
        }

467 468 469 470 471 472
        @Override
        public int read(byte[] b) throws IOException {
            return read(b, 0, b.length);
        }

        @Override
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545
        public int read(byte[] b, int off, int len) throws IOException {
            synchronized (stateLock) {
                try {
                    // Make sure the input stream has been created.
                    init();

                    for (;;) {
                        // Serve any remaining data from the engine first.
                        if (fromEngine.remaining() > 0) {
                            int readFromEngine = Math.min(fromEngine.remaining(), len);
                            fromEngine.get(b, off, readFromEngine);
                            return readFromEngine;
                        }

                        // Try to unwrap any data already in the socket buffer.
                        boolean needMoreData = true;
                        if (fromSocket.position() > 0) {
                            // Unwrap the unencrypted bytes into the engine buffer.
                            fromSocket.flip();
                            fromEngine.clear();
                            SSLEngineResult engineResult = engine.unwrap(fromSocket, fromEngine);

                            // Shift any remaining data to the beginning of the buffer so that
                            // we can accommodate the next full packet. After this is called,
                            // limit will be restored to capacity and position will point just
                            // past the end of the data.
                            fromSocket.compact();
                            fromEngine.flip();

                            switch (engineResult.getStatus()) {
                                case BUFFER_UNDERFLOW: {
                                    if (engineResult.bytesProduced() == 0) {
                                        // Need to read more data from the socket.
                                        break;
                                    }
                                    // Fall-through and serve the data that was produced.
                                }
                                case OK: {
                                    // We processed the entire packet successfully.
                                    needMoreData = false;
                                    break;
                                }
                                default: {
                                    // Anything else is an error.
                                    throw new SSLException(
                                            "Unexpected engine result " + engineResult.getStatus());
                                }
                            }

                            if (engineResult.getHandshakeStatus() == HandshakeStatus.FINISHED) {
                                completeHandshake();
                            }
                            if (engineResult.bytesProduced() == 0) {
                                // Read successfully, but produced no data. Possibly part of a
                                // handshake.
                                return 0;
                            }
                        }

                        // Read more data from the socket.
                        if (needMoreData && readFromSocket() == -1) {
                            // Failed to read the next encrypted packet before reaching EOF.
                            return -1;
                        }

                        // Continue the loop and return the data from the engine buffer.
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    throw e;
                } catch (RuntimeException e) {
                    e.printStackTrace();
                    throw e;
546
                }
547 548
            }
        }
549

550 551 552 553 554 555 556
        private void init() throws IOException {
            if (socketInputStream == null) {
                socketInputStream = socket.getInputStream();
                socketChannel = socket.getChannel();
                if (socketChannel != null) {
                    fromSocket =
                            ByteBuffer.allocateDirect(engine.getSession().getPacketBufferSize());
557
                } else {
558
                    fromSocket = ByteBuffer.allocate(engine.getSession().getPacketBufferSize());
559 560 561 562
                }
            }
        }

563 564 565 566 567 568 569 570 571 572 573 574
        private int readFromSocket() throws IOException {
            if (socketChannel != null) {
                return socketChannel.read(fromSocket);
            }
            // Read directly to the underlying array and increment the buffer position if
            // appropriate.
            int read = socketInputStream.read(
                    fromSocket.array(), fromSocket.position(), fromSocket.remaining());
            if (read > 0) {
                fromSocket.position(fromSocket.position() + read);
            }
            return read;
575 576 577
        }
    }
}