Java Code Examples for javax.net.ssl.SSLEngine#getUseClientMode()

The following examples show how to use javax.net.ssl.SSLEngine#getUseClientMode() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SslConduit.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
SslConduit(UndertowSslConnection connection, StreamConnection delegate, SSLEngine engine, ByteBufferPool bufferPool, Runnable handshakeCallback) {
    this.connection = connection;
    this.delegate = delegate;
    this.handshakeCallback = handshakeCallback;
    this.sink = delegate.getSinkChannel().getConduit();
    this.source = delegate.getSourceChannel().getConduit();
    this.engine = engine;
    this.bufferPool = bufferPool;
    delegate.getSourceChannel().getConduit().setReadReadyHandler(readReadyHandler = new SslReadReadyHandler(null));
    delegate.getSinkChannel().getConduit().setWriteReadyHandler(writeReadyHandler = new SslWriteReadyHandler(null));
    if(engine.getUseClientMode()) {
        state = FLAG_IN_HANDSHAKE | FLAG_READ_REQUIRES_WRITE;
    } else {
        state = FLAG_IN_HANDSHAKE | FLAG_WRITE_REQUIRES_READ;
    }
}
 
Example 2
Source File: JettyAlpnProvider.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
static SSLEngine setProtocols(final SSLEngine engine, final String[] protocols) {
    if (engine.getUseClientMode()) {
        ALPN.put(engine, new ALPNClientSelectionProvider(Arrays.asList(protocols), engine));
    } else {
        ALPN.put(engine, new ALPN.ServerProvider() {
            @Override
            public void unsupported() {
                ALPN.remove(engine);
            }

            @Override
            public String select(List<String> strings) {
                ALPN.remove(engine);
                for (String p : protocols) {
                    if (strings.contains(p)) {
                        engine.getHandshakeSession().putValue(PROTOCOL_KEY, p);
                        return p;
                    }
                }
                return null;
            }
        });
    }
    return engine;
}
 
Example 3
Source File: BufferOverflowUnderflowTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private void checkBufferOverflowOnWrap(SSLEngine engine)
        throws SSLException {
    String mode = engine.getUseClientMode() ? "client"
            : "server";
    System.out.println("================================================="
            + "===========");
    System.out.println("Testing SSLEngine buffer overflow"
            + " on wrap by " + mode);
    ByteBuffer app = ByteBuffer.wrap(MESSAGE.getBytes());
    //Making net buffer size less than required by 1 byte.
    ByteBuffer net = ByteBuffer
            .allocate(engine.getSession().getPacketBufferSize() - 1);
    SSLEngineResult r = engine.wrap(app, net);
    checkResult(r, SSLEngineResult.Status.BUFFER_OVERFLOW);
    System.out.println("Passed");
}
 
Example 4
Source File: BufferOverflowUnderflowTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private void checkBufferOverflowOnUnWrap(SSLEngine wrappingEngine,
        SSLEngine unwrappingEngine)
        throws SSLException {
    String wrapperMode = wrappingEngine.getUseClientMode() ? "client"
            : "server";
    String unwrapperMode = unwrappingEngine.getUseClientMode() ? "client"
            : "server";
    if (wrapperMode.equals(unwrapperMode)) {
        throw new Error("Test error: both engines are in the same mode!");
    }
    System.out.println("================================================="
            + "===========");
    System.out.println("Testing SSLEngine buffer overflow"
            + " on unwrap by " + unwrapperMode);
    ByteBuffer app = ByteBuffer.wrap(MESSAGE.getBytes());
    ByteBuffer net = ByteBuffer
            .allocate(wrappingEngine.getSession().getPacketBufferSize());
    SSLEngineResult r = wrappingEngine.wrap(app, net);
    checkResult(r, SSLEngineResult.Status.OK);
    //Making app buffer size less than required by 1 byte.
    app = ByteBuffer.allocate(MESSAGE.length() - 1);
    net.flip();
    r = unwrappingEngine.unwrap(net, app);
    checkResult(r, SSLEngineResult.Status.BUFFER_OVERFLOW);
    System.out.println("Passed");
}
 
Example 5
Source File: RespondToRetransmit.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Override
boolean produceHandshakePackets(SSLEngine engine, SocketAddress socketAddr,
        String side, List<DatagramPacket> packets) throws Exception {

    boolean finished = super.produceHandshakePackets(
            engine, socketAddr, side, packets);

    if (needPacketDuplicate && (!(isClient ^ engine.getUseClientMode()))) {
        DatagramPacket packet = getPacket(packets, handshakeType);
        if (packet != null) {
            needPacketDuplicate = false;

            System.out.println("Duplicate the flight.");
            List<DatagramPacket> duplicates = new ArrayList<>();
            finished = super.produceHandshakePackets(
                    engine, socketAddr, side, duplicates);
            packets.addAll(duplicates);
        }
    }

    return finished;
}
 
Example 6
Source File: PacketLossRetransmission.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Override
boolean produceHandshakePackets(SSLEngine engine, SocketAddress socketAddr,
        String side, List<DatagramPacket> packets) throws Exception {

    boolean finished = super.produceHandshakePackets(
            engine, socketAddr, side, packets);

    if (needPacketLoss && (!(isClient ^ engine.getUseClientMode()))) {
        DatagramPacket packet = getPacket(packets, handshakeType);
        if (packet != null) {
            needPacketLoss = false;

            System.out.println("Loss a packet of handshake messahe");
            packets.remove(packet);
        }
    }

    return finished;
}
 
Example 7
Source File: DTLSIncorrectAppDataTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private void checkIncorrectAppDataUnwrap(SSLEngine sendEngine,
        SSLEngine recvEngine) throws SSLException {
    String direction = sendEngine.getUseClientMode() ? "client"
            : "server";
    System.out.println("================================================="
            + "===========");
    System.out.println("Testing DTLS incorrect app data packages unwrapping"
            + " by sending data from " + direction);
    ByteBuffer app = ByteBuffer.wrap(MESSAGE.getBytes());
    ByteBuffer net = doWrap(sendEngine, direction, 0, app);
    final Random RNG = RandomFactory.getRandom();
    int randomPlace = RNG.nextInt(net.remaining());
    net.array()[randomPlace] += 1;
    app = ByteBuffer.allocate(recvEngine.getSession()
            .getApplicationBufferSize());
    recvEngine.unwrap(net, app);
    app.flip();
    int length = app.remaining();
    System.out.println("Unwrapped " + length + " bytes.");
}
 
Example 8
Source File: ClientTlsChannel.java    From pgadba with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private ClientTlsChannel(
    ByteChannel underlying,
    SSLEngine engine,
    Consumer<SSLSession> sessionInitCallback,
    boolean runTasks,
    BufferAllocator plainBufAllocator,
    BufferAllocator encryptedBufAllocator,
    boolean releaseBuffers,
    boolean waitForCloseNotifyOnClose) {
  if (!engine.getUseClientMode()) {
    throw new IllegalArgumentException("SSLEngine must be in client mode");
  }
  this.underlying = underlying;
  TrackingAllocator trackingPlainBufAllocator = new TrackingAllocator(plainBufAllocator);
  TrackingAllocator trackingEncryptedAllocator = new TrackingAllocator(encryptedBufAllocator);
  impl = new TlsChannelImpl(underlying, underlying, engine, Optional.empty(), sessionInitCallback, runTasks,
      trackingPlainBufAllocator, trackingEncryptedAllocator, releaseBuffers, waitForCloseNotifyOnClose);
}
 
Example 9
Source File: BufferOverflowUnderflowTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private void checkBufferUnderflowOnUnWrap(SSLEngine wrappingEngine,
        SSLEngine unwrappingEngine)
        throws SSLException {
    String wrapperMode = wrappingEngine.getUseClientMode() ? "client"
            : "server";
    String unwrapperMode = unwrappingEngine.getUseClientMode() ? "client"
            : "server";
    if (wrapperMode.equals(unwrapperMode)) {
        throw new Error("Test error: both engines are in the same mode!");
    }
    System.out.println("================================================="
            + "===========");
    System.out.println("Testing SSLEngine buffer underflow"
            + " on unwrap by " + unwrapperMode);
    ByteBuffer app = ByteBuffer.wrap(MESSAGE.getBytes());
    ByteBuffer net = ByteBuffer
            .allocate(wrappingEngine.getSession().getPacketBufferSize());
    SSLEngineResult r = wrappingEngine.wrap(app, net);
    checkResult(r, SSLEngineResult.Status.OK);
    app = ByteBuffer.allocate(unwrappingEngine.getSession()
            .getApplicationBufferSize());
    net.flip();
    //Making net buffer size less than size of dtls message.
    net.limit(net.limit() - 1);
    r = unwrappingEngine.unwrap(net, app);
    checkResult(r, SSLEngineResult.Status.BUFFER_UNDERFLOW);
    System.out.println("Passed");
}
 
Example 10
Source File: Reordered.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
boolean produceHandshakePackets(SSLEngine engine, SocketAddress socketAddr,
        String side, List<DatagramPacket> packets) throws Exception {

    boolean finished = super.produceHandshakePackets(
            engine, socketAddr, side, packets);

    if (needPacketReorder && (!engine.getUseClientMode())) {
        needPacketReorder = false;
        Collections.reverse(packets);
    }

    return finished;
}
 
Example 11
Source File: Retransmission.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
boolean produceHandshakePackets(SSLEngine engine, SocketAddress socketAddr,
        String side, List<DatagramPacket> packets) throws Exception {

    boolean finished = super.produceHandshakePackets(
            engine, socketAddr, side, packets);

    if (!needPacketLoss || (!engine.getUseClientMode())) {
        return finished;
    }

    List<DatagramPacket> parts = new ArrayList<>();
    int lostSeq = 2;
    for (DatagramPacket packet : packets) {
        lostSeq--;
        if (lostSeq == 0) {
            needPacketLoss = false;
            // loss this packet
            System.out.println("Loss a packet");
            continue;
        }

        parts.add(packet);
    }

    packets.clear();
    packets.addAll(parts);

    return finished;
}
 
Example 12
Source File: ClientTlsChannel.java    From tls-channel with MIT License 5 votes vote down vote up
private ClientTlsChannel(
    ByteChannel underlying,
    SSLEngine engine,
    Consumer<SSLSession> sessionInitCallback,
    boolean runTasks,
    BufferAllocator plainBufAllocator,
    BufferAllocator encryptedBufAllocator,
    boolean releaseBuffers,
    boolean waitForCloseNotifyOnClose) {
  if (!engine.getUseClientMode())
    throw new IllegalArgumentException("SSLEngine must be in client mode");
  this.underlying = underlying;
  TrackingAllocator trackingPlainBufAllocator = new TrackingAllocator(plainBufAllocator);
  TrackingAllocator trackingEncryptedAllocator = new TrackingAllocator(encryptedBufAllocator);
  impl =
      new TlsChannelImpl(
          underlying,
          underlying,
          engine,
          Optional.empty(),
          sessionInitCallback,
          runTasks,
          trackingPlainBufAllocator,
          trackingEncryptedAllocator,
          releaseBuffers,
          waitForCloseNotifyOnClose);
}
 
Example 13
Source File: SSLEngineTestCase.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Routine to send application data from one SSLEngine to another.
 *
 * @param fromEngine - Sending engine.
 * @param toEngine   - Receiving engine.
 * @return - Result of unwrap method of the receiving engine.
 * @throws SSLException - thrown on engine errors.
 */
public static SSLEngineResult sendApplicationData(SSLEngine fromEngine,
                                                  SSLEngine toEngine)
        throws SSLException {
    String sender = null;
    String reciever = null;
    String excMsgSent = EXCHANGE_MSG_SENT;
    if (fromEngine.getUseClientMode() && !toEngine.getUseClientMode()) {
        sender = "Client";
        reciever = "Server";
        excMsgSent += " Client.";
    } else if (toEngine.getUseClientMode() &&
            !fromEngine.getUseClientMode()) {
        sender = "Server";
        reciever = "Client";
        excMsgSent += " Server.";
    } else {
        throw new Error("Test issue: both engines are in the same mode");
    }
    System.out.println("=============================================");
    System.out.println("Trying to send application data from " + sender
            + " to " + reciever);
    ByteBuffer clientAppSent
            = ByteBuffer.wrap(excMsgSent.getBytes());
    net = doWrap(fromEngine, sender, 0, clientAppSent);
    SSLEngineResult[] r = new SSLEngineResult[1];
    ByteBuffer serverAppRecv = doUnWrap(toEngine, reciever, net, r);
    byte[] serverAppRecvTrunc = Arrays.copyOf(serverAppRecv.array(),
            serverAppRecv.limit());
    String msgRecv = new String(serverAppRecvTrunc);
    if (!msgRecv.equals(excMsgSent)) {
        throw new AssertionError(sender + " to " + reciever
                + ": application data"
                + " has been altered while sending."
                + " Message sent: " + "\"" + excMsgSent + "\"."
                + " Message recieved: " + "\"" + msgRecv + "\".");
    }
    System.out.println("Successful sending application data from " + sender
            + " to " + reciever);
    return r[0];
}
 
Example 14
Source File: SSLEngineTestCase.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Close engines by sending "close outbound" message from one SSLEngine to
 * another.
 *
 * @param fromEngine - Sending engine.
 * @param toEngine   - Receiving engine.
 * @throws SSLException - thrown on engine errors.
 */
public static void closeEngines(SSLEngine fromEngine,
                                SSLEngine toEngine) throws SSLException {
    String from = null;
    String to = null;
    ByteBuffer app;
    if (fromEngine.getUseClientMode() && !toEngine.getUseClientMode()) {
        from = "Client";
        to = "Server";
    } else if (toEngine.getUseClientMode() &&
            !fromEngine.getUseClientMode()) {
        from = "Server";
        to = "Client";
    } else {
        throw new Error("Both engines are in the same mode");
    }
    System.out.println("=============================================");
    System.out.println(
            "Trying to close engines from " + from + " to " + to);
    // Sending close outbound request to peer
    fromEngine.closeOutbound();
    app = ByteBuffer.allocate(
            fromEngine.getSession().getApplicationBufferSize());
    net = doWrap(fromEngine, from, 0, app, SSLEngineResult.Status.CLOSED);
    doUnWrap(toEngine, to, net, SSLEngineResult.Status.CLOSED);
    app = ByteBuffer.allocate(
            fromEngine.getSession().getApplicationBufferSize());
    net = doWrap(toEngine, to, 0, app, SSLEngineResult.Status.CLOSED);
    doUnWrap(fromEngine, from, net, SSLEngineResult.Status.CLOSED);
    if (!toEngine.isInboundDone()) {
        throw new AssertionError(from + " sent close request to " + to
                + ", but " + to + "did not close inbound.");
    }
    // Executing close inbound
    fromEngine.closeInbound();
    app = ByteBuffer.allocate(
            fromEngine.getSession().getApplicationBufferSize());
    net = doWrap(fromEngine, from, 0, app, SSLEngineResult.Status.CLOSED);
    doUnWrap(toEngine, to, net, SSLEngineResult.Status.CLOSED);
    if (!toEngine.isOutboundDone()) {
        throw new AssertionError(from + "sent close request to " + to
                + ", but " + to + "did not close outbound.");
    }
    System.out.println("Successful closing from " + from + " to " + to);
}