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

The following examples show how to use javax.net.ssl.SSLEngine#getSession() . 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: SSLSocketChannel.java    From mts with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Construct a new channel.
 * 
 * @param channel the unsecure socket channel.
 * @param engine the SSL engine.
 */
public SSLSocketChannel(SocketChannel channel, SSLEngine engine)
{
    super(channel.provider());
    socketChannel = channel;
    sslEngine = engine;
    sslSession = engine.getSession();
    minCacheSize = sslSession.getApplicationBufferSize();
    inputCache = new ByteBuffer[]{ ByteBuffer.allocate(minCacheSize) };
    minBufferSize = sslSession.getPacketBufferSize();
    inputBuffer = new ByteBuffer[]{ ByteBuffer.allocate(minBufferSize) };
    outputBuffer = new ByteBuffer[]{ ByteBuffer.allocate(minBufferSize) };
    emptyBuffer = ByteBuffer.allocate(0);

    // Set initial values.
    inputCache[0].limit(0);
    outputBuffer[0].limit(0);
}
 
Example 2
Source File: PublicAccessLogHandlerTest.java    From ambry with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an {@link EmbeddedChannel} that incorporates an instance of {@link PublicAccessLogHandler}
 * and {@link EchoMethodHandler}.
 * @param useSSL {@code true} to add an {@link SslHandler} to the pipeline.
 * @return an {@link EmbeddedChannel} that incorporates an instance of {@link PublicAccessLogHandler}
 *         and {@link EchoMethodHandler}, and an {@link SslHandler} if needed.
 */
private EmbeddedChannel createChannel(boolean useSSL) {
  EmbeddedChannel channel = new EmbeddedChannel();
  if (useSSL) {
    SSLEngine sslEngine = SSL_CONTEXT.newEngine(channel.alloc());
    // HttpRequests pass through the SslHandler without a handshake (it only operates on ByteBuffers) so we have
    // to mock certain methods of SSLEngine and SSLSession to ensure that we can test certificate logging.
    SSLEngine mockSSLEngine =
        new MockSSLEngine(sslEngine, new MockSSLSession(sslEngine.getSession(), new Certificate[]{PEER_CERT}));
    channel.pipeline().addLast(new SslHandler(mockSSLEngine));
  }
  channel.pipeline()
      .addLast(new PublicAccessLogHandler(publicAccessLogger, new NettyMetrics(new MetricRegistry())))
      .addLast(new EchoMethodHandler());
  return channel;
}
 
Example 3
Source File: AcceptLargeFragments.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public static void main (String[] args) throws Exception {
    SSLContext context = SSLContext.getDefault();

    // set the property before initialization SSLEngine.
    System.setProperty("jsse.SSLEngine.acceptLargeFragments", "true");

    SSLEngine cliEngine = context.createSSLEngine();
    cliEngine.setUseClientMode(true);

    SSLEngine srvEngine = context.createSSLEngine();
    srvEngine.setUseClientMode(false);

    SSLSession cliSession = cliEngine.getSession();
    SSLSession srvSession = srvEngine.getSession();

    // check packet buffer sizes.
    if (cliSession.getPacketBufferSize() < 33049 ||
        srvSession.getPacketBufferSize() < 33049) {
            throw new Exception("Don't accept large SSL/TLS fragments");
    }

    // check application data buffer sizes.
    if (cliSession.getApplicationBufferSize() < 32768 ||
        srvSession.getApplicationBufferSize() < 32768) {
            throw new Exception(
                    "Don't accept large SSL/TLS application data ");
    }
}
 
Example 4
Source File: TlsCryptoSocket.java    From vespa with Apache License 2.0 5 votes vote down vote up
public TlsCryptoSocket(SocketChannel channel, SSLEngine sslEngine) {
    this.channel = channel;
    this.sslEngine = sslEngine;
    SSLSession nullSession = sslEngine.getSession();
    this.wrapBuffer = new Buffer(Math.max(0x10000, nullSession.getPacketBufferSize() * 2));
    this.unwrapBuffer = new Buffer(Math.max(0x10000, nullSession.getPacketBufferSize() * 2));
    // Note: Dummy buffer as unwrap requires a full size application buffer even though no application data is unwrapped
    this.handshakeDummyBuffer = ByteBuffer.allocate(nullSession.getApplicationBufferSize());
    this.handshakeState = HandshakeState.NOT_STARTED;
    log.fine(() -> "Initialized with " + sslEngine.toString());
}
 
Example 5
Source File: AcceptLargeFragments.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void main (String[] args) throws Exception {
    SSLContext context = SSLContext.getDefault();

    // set the property before initialization SSLEngine.
    System.setProperty("jsse.SSLEngine.acceptLargeFragments", "true");

    SSLEngine cliEngine = context.createSSLEngine();
    cliEngine.setUseClientMode(true);

    SSLEngine srvEngine = context.createSSLEngine();
    srvEngine.setUseClientMode(false);

    SSLSession cliSession = cliEngine.getSession();
    SSLSession srvSession = srvEngine.getSession();

    // check packet buffer sizes.
    if (cliSession.getPacketBufferSize() < 33049 ||
        srvSession.getPacketBufferSize() < 33049) {
            throw new Exception("Don't accept large SSL/TLS fragments");
    }

    // check application data buffer sizes.
    if (cliSession.getApplicationBufferSize() < 32768 ||
        srvSession.getApplicationBufferSize() < 32768) {
            throw new Exception(
                    "Don't accept large SSL/TLS application data ");
    }
}
 
Example 6
Source File: SslService.java    From smart-socket with Apache License 2.0 5 votes vote down vote up
HandshakeModel createSSLEngine(AsynchronousSocketChannel socketChannel, BufferPage bufferPage) {
    try {
        HandshakeModel handshakeModel = new HandshakeModel();
        SSLEngine sslEngine = sslContext.createSSLEngine();
        SSLSession session = sslEngine.getSession();
        sslEngine.setUseClientMode(isClient);
        if (clientAuth != null) {
            switch (clientAuth) {
                case OPTIONAL:
                    sslEngine.setWantClientAuth(true);
                    break;
                case REQUIRE:
                    sslEngine.setNeedClientAuth(true);
                    break;
                case NONE:
                    break;
                default:
                    throw new Error("Unknown auth " + clientAuth);
            }
        }
        handshakeModel.setSslEngine(sslEngine);
        handshakeModel.setAppWriteBuffer(bufferPage.allocate(session.getApplicationBufferSize()));
        handshakeModel.setNetWriteBuffer(bufferPage.allocate(session.getPacketBufferSize()));
        handshakeModel.getNetWriteBuffer().buffer().flip();
        handshakeModel.setAppReadBuffer(bufferPage.allocate(session.getApplicationBufferSize()));
        handshakeModel.setNetReadBuffer(bufferPage.allocate(session.getPacketBufferSize()));
        sslEngine.beginHandshake();

        handshakeModel.setSocketChannel(socketChannel);
        return handshakeModel;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}
 
Example 7
Source File: TlsOrPlainConnectionFactory.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
@Override
protected void doStart() throws Exception
{
    super.doStart();

    final SSLEngine engine = _sslContextFactory.newSSLEngine();
    engine.setUseClientMode(false);
    final SSLSession session = engine.getSession();
    if (session.getPacketBufferSize() > this.getInputBufferSize())
    {
        this.setInputBufferSize(session.getPacketBufferSize());
    }
    engine.closeInbound();
    engine.closeOutbound();
}
 
Example 8
Source File: AcceptLargeFragments.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main (String[] args) throws Exception {
    SSLContext context = SSLContext.getDefault();

    // set the property before initialization SSLEngine.
    System.setProperty("jsse.SSLEngine.acceptLargeFragments", "true");

    SSLEngine cliEngine = context.createSSLEngine();
    cliEngine.setUseClientMode(true);

    SSLEngine srvEngine = context.createSSLEngine();
    srvEngine.setUseClientMode(false);

    SSLSession cliSession = cliEngine.getSession();
    SSLSession srvSession = srvEngine.getSession();

    // check packet buffer sizes.
    if (cliSession.getPacketBufferSize() < 33049 ||
        srvSession.getPacketBufferSize() < 33049) {
            throw new Exception("Don't accept large SSL/TLS fragments");
    }

    // check application data buffer sizes.
    if (cliSession.getApplicationBufferSize() < 32768 ||
        srvSession.getApplicationBufferSize() < 32768) {
            throw new Exception(
                    "Don't accept large SSL/TLS application data ");
    }
}
 
Example 9
Source File: Nio2Endpoint.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 * @param clientCertProvider Ignored for this implementation
 */
@Override
public SSLSupport getSslSupport(String clientCertProvider) {
    if (getSocket() instanceof SecureNio2Channel) {
        SecureNio2Channel ch = (SecureNio2Channel) getSocket();
        SSLEngine sslEngine = ch.getSslEngine();
        if (sslEngine != null) {
            SSLSession session = sslEngine.getSession();
            return ((Nio2Endpoint) getEndpoint()).getSslImplementation().getSSLSupport(session);
        }
    }
    return null;
}
 
Example 10
Source File: FlowContext.java    From g4proxy with Apache License 2.0 5 votes vote down vote up
public FlowContext(ClientToProxyConnection clientConnection) {
    super();
    this.clientAddress = clientConnection.getClientAddress();
    SSLEngine sslEngine = clientConnection.getSslEngine();
    this.clientSslSession = sslEngine != null ? sslEngine.getSession()
            : null;
}
 
Example 11
Source File: SSLFacade.java    From getty with Apache License 2.0 5 votes vote down vote up
public SSLFacade(SSLContext context, boolean client,
                 boolean clientAuthRequired, ITaskHandler taskHandler) {
    //Currently there is no support for SSL session reuse,
    // so no need to take a peerHost or port from the host application
    final String who = client ? "client" : "server";
    SSLEngine engine = makeSSLEngine(context, client, clientAuthRequired);
    engine.setEnabledProtocols(new String[]{context.getProtocol()});
    //engine.setEnabledProtocols(new String[]{"TLSv1", "TLSv1.1", "TLSv1.2"});
    Buffers buffers = new Buffers(engine.getSession());
    _worker = new Worker(who, engine, buffers);
    _handshaker = new Handshaker(client, _worker, taskHandler);
    _clientMode = client;
}
 
Example 12
Source File: AcceptLargeFragments.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public static void main (String[] args) throws Exception {
    SSLContext context = SSLContext.getDefault();

    // set the property before initialization SSLEngine.
    System.setProperty("jsse.SSLEngine.acceptLargeFragments", "true");

    SSLEngine cliEngine = context.createSSLEngine();
    cliEngine.setUseClientMode(true);

    SSLEngine srvEngine = context.createSSLEngine();
    srvEngine.setUseClientMode(false);

    SSLSession cliSession = cliEngine.getSession();
    SSLSession srvSession = srvEngine.getSession();

    // check packet buffer sizes.
    if (cliSession.getPacketBufferSize() < 33049 ||
        srvSession.getPacketBufferSize() < 33049) {
            throw new Exception("Don't accept large SSL/TLS fragments");
    }

    // check application data buffer sizes.
    if (cliSession.getApplicationBufferSize() < 32768 ||
        srvSession.getApplicationBufferSize() < 32768) {
            throw new Exception(
                    "Don't accept large SSL/TLS application data ");
    }
}
 
Example 13
Source File: AcceptLargeFragments.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main (String[] args) throws Exception {
    SSLContext context = SSLContext.getDefault();

    // set the property before initialization SSLEngine.
    System.setProperty("jsse.SSLEngine.acceptLargeFragments", "true");

    SSLEngine cliEngine = context.createSSLEngine();
    cliEngine.setUseClientMode(true);

    SSLEngine srvEngine = context.createSSLEngine();
    srvEngine.setUseClientMode(false);

    SSLSession cliSession = cliEngine.getSession();
    SSLSession srvSession = srvEngine.getSession();

    // check packet buffer sizes.
    if (cliSession.getPacketBufferSize() < 33049 ||
        srvSession.getPacketBufferSize() < 33049) {
            throw new Exception("Don't accept large SSL/TLS fragments");
    }

    // check application data buffer sizes.
    if (cliSession.getApplicationBufferSize() < 32768 ||
        srvSession.getApplicationBufferSize() < 32768) {
            throw new Exception(
                    "Don't accept large SSL/TLS application data ");
    }
}
 
Example 14
Source File: AcceptLargeFragments.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main (String[] args) throws Exception {
    SSLContext context = SSLContext.getDefault();

    // set the property before initialization SSLEngine.
    System.setProperty("jsse.SSLEngine.acceptLargeFragments", "true");

    SSLEngine cliEngine = context.createSSLEngine();
    cliEngine.setUseClientMode(true);

    SSLEngine srvEngine = context.createSSLEngine();
    srvEngine.setUseClientMode(false);

    SSLSession cliSession = cliEngine.getSession();
    SSLSession srvSession = srvEngine.getSession();

    // check packet buffer sizes.
    if (cliSession.getPacketBufferSize() < 33049 ||
        srvSession.getPacketBufferSize() < 33049) {
            throw new Exception("Don't accept large SSL/TLS fragments");
    }

    // check application data buffer sizes.
    if (cliSession.getApplicationBufferSize() < 32768 ||
        srvSession.getApplicationBufferSize() < 32768) {
            throw new Exception(
                    "Don't accept large SSL/TLS application data ");
    }
}
 
Example 15
Source File: NioEndpoint.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 * @param clientCertProvider Ignored for this implementation
 */
@Override
public SSLSupport getSslSupport(String clientCertProvider) {
    if (getSocket() instanceof SecureNioChannel) {
        SecureNioChannel ch = (SecureNioChannel) getSocket();
        SSLEngine sslEngine = ch.getSslEngine();
        if (sslEngine != null) {
            SSLSession session = sslEngine.getSession();
            return ((NioEndpoint) getEndpoint()).getSslImplementation().getSSLSupport(session);
        }
    }
    return null;
}
 
Example 16
Source File: TestTLS12.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
public static void run() throws Exception {
    SSLEngine[][] enginesToTest = getSSLEnginesToTest();

    for (SSLEngine[] engineToTest : enginesToTest) {

        SSLEngine clientSSLEngine = engineToTest[0];
        SSLEngine serverSSLEngine = engineToTest[1];

        // SSLEngine code based on RedhandshakeFinished.java

        boolean dataDone = false;

        ByteBuffer clientOut = null;
        ByteBuffer clientIn = null;
        ByteBuffer serverOut = null;
        ByteBuffer serverIn = null;
        ByteBuffer cTOs;
        ByteBuffer sTOc;

        SSLSession session = clientSSLEngine.getSession();
        int appBufferMax = session.getApplicationBufferSize();
        int netBufferMax = session.getPacketBufferSize();

        clientIn = ByteBuffer.allocate(appBufferMax + 50);
        serverIn = ByteBuffer.allocate(appBufferMax + 50);

        cTOs = ByteBuffer.allocateDirect(netBufferMax);
        sTOc = ByteBuffer.allocateDirect(netBufferMax);

        clientOut = ByteBuffer.wrap(
                "Hi Server, I'm Client".getBytes());
        serverOut = ByteBuffer.wrap(
                "Hello Client, I'm Server".getBytes());

        SSLEngineResult clientResult;
        SSLEngineResult serverResult;

        while (!dataDone) {
            clientResult = clientSSLEngine.wrap(clientOut, cTOs);
            runDelegatedTasks(clientResult, clientSSLEngine);
            serverResult = serverSSLEngine.wrap(serverOut, sTOc);
            runDelegatedTasks(serverResult, serverSSLEngine);
            cTOs.flip();
            sTOc.flip();

            if (enableDebug) {
                System.out.println("Client -> Network");
                printTlsNetworkPacket("", cTOs);
                System.out.println("");
                System.out.println("Server -> Network");
                printTlsNetworkPacket("", sTOc);
                System.out.println("");
            }

            clientResult = clientSSLEngine.unwrap(sTOc, clientIn);
            runDelegatedTasks(clientResult, clientSSLEngine);
            serverResult = serverSSLEngine.unwrap(cTOs, serverIn);
            runDelegatedTasks(serverResult, serverSSLEngine);

            cTOs.compact();
            sTOc.compact();

            if (!dataDone &&
                    (clientOut.limit() == serverIn.position()) &&
                    (serverOut.limit() == clientIn.position())) {
                checkTransfer(serverOut, clientIn);
                checkTransfer(clientOut, serverIn);
                dataDone = true;
            }
        }
    }
}
 
Example 17
Source File: XmppTcpTransportModule.java    From Smack with Apache License 2.0 4 votes vote down vote up
private TlsEstablishedResult(SSLEngine sslEngine) {
    super("TLS established: " + sslEngine.getSession());
}
 
Example 18
Source File: ExchangeImpl.java    From freehealth-connector with GNU Affero General Public License v3.0 4 votes vote down vote up
public SSLSession getSSLSession() {
   SSLEngine e = this.connection.getSSLEngine();
   return e == null ? null : e.getSession();
}
 
Example 19
Source File: SSLRequestHelper.java    From deprecated-security-ssl with Apache License 2.0 4 votes vote down vote up
public static SSLInfo getSSLInfo(final Settings settings, final Path configPath, final RestRequest request, PrincipalExtractor principalExtractor) throws SSLPeerUnverifiedException {

        if(request == null || !(request instanceof Netty4HttpRequest)) {
            return null;
        }
        
        final Netty4HttpRequest nettyHttpRequest = (Netty4HttpRequest) request;
        final SslHandler sslhandler = (SslHandler) nettyHttpRequest.getChannel().pipeline().get("ssl_http");
        
        if(sslhandler == null) {
            return null;
        }
        
        final SSLEngine engine = sslhandler.engine();
        final SSLSession session = engine.getSession();

        X509Certificate[] x509Certs = null;
        final String protocol = session.getProtocol();
        final String cipher = session.getCipherSuite();
        String principal = null;
        boolean validationFailure = false;

        if (engine.getNeedClientAuth() || engine.getWantClientAuth()) {

            try {
                final Certificate[] certs = session.getPeerCertificates();

                if (certs != null && certs.length > 0 && certs[0] instanceof X509Certificate) {
                    x509Certs = Arrays.copyOf(certs, certs.length, X509Certificate[].class);
                    final X509Certificate[] x509CertsF = x509Certs;
                    
                    final SecurityManager sm = System.getSecurityManager();

                    if (sm != null) {
                        sm.checkPermission(new SpecialPermission());
                    }

                    validationFailure = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
                        @Override
                        public Boolean run() {                        
                            return !validate(x509CertsF, settings, configPath);
                        }
                    });

                    if(validationFailure) {
                        throw new SSLPeerUnverifiedException("Unable to validate certificate (CRL)");
                    }
                    principal = principalExtractor == null?null: principalExtractor.extractPrincipal(x509Certs[0], Type.HTTP);
                } else if (engine.getNeedClientAuth()) {
                    final ElasticsearchException ex = new ElasticsearchException("No client certificates found but such are needed (Security 9).");
                    throw ex;
                }

            } catch (final SSLPeerUnverifiedException e) {
                if (engine.getNeedClientAuth() || validationFailure) {
                    throw e;
                }
            }
        }

        Certificate[] localCerts = session.getLocalCertificates();
        return new SSLInfo(x509Certs, principal, protocol, cipher, localCerts==null?null:Arrays.copyOf(localCerts, localCerts.length, X509Certificate[].class));
    }
 
Example 20
Source File: TestTLS12.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public static void run() throws Exception {
    SSLEngine[][] enginesToTest = getSSLEnginesToTest();

    for (SSLEngine[] engineToTest : enginesToTest) {

        SSLEngine clientSSLEngine = engineToTest[0];
        SSLEngine serverSSLEngine = engineToTest[1];

        // SSLEngine code based on RedhandshakeFinished.java

        boolean dataDone = false;

        ByteBuffer clientOut = null;
        ByteBuffer clientIn = null;
        ByteBuffer serverOut = null;
        ByteBuffer serverIn = null;
        ByteBuffer cTOs;
        ByteBuffer sTOc;

        SSLSession session = clientSSLEngine.getSession();
        int appBufferMax = session.getApplicationBufferSize();
        int netBufferMax = session.getPacketBufferSize();

        clientIn = ByteBuffer.allocate(appBufferMax + 50);
        serverIn = ByteBuffer.allocate(appBufferMax + 50);

        cTOs = ByteBuffer.allocateDirect(netBufferMax);
        sTOc = ByteBuffer.allocateDirect(netBufferMax);

        clientOut = ByteBuffer.wrap(
                "Hi Server, I'm Client".getBytes());
        serverOut = ByteBuffer.wrap(
                "Hello Client, I'm Server".getBytes());

        SSLEngineResult clientResult;
        SSLEngineResult serverResult;

        while (!dataDone) {
            clientResult = clientSSLEngine.wrap(clientOut, cTOs);
            runDelegatedTasks(clientResult, clientSSLEngine);
            serverResult = serverSSLEngine.wrap(serverOut, sTOc);
            runDelegatedTasks(serverResult, serverSSLEngine);
            cTOs.flip();
            sTOc.flip();

            if (enableDebug) {
                System.out.println("Client -> Network");
                printTlsNetworkPacket("", cTOs);
                System.out.println("");
                System.out.println("Server -> Network");
                printTlsNetworkPacket("", sTOc);
                System.out.println("");
            }

            clientResult = clientSSLEngine.unwrap(sTOc, clientIn);
            runDelegatedTasks(clientResult, clientSSLEngine);
            serverResult = serverSSLEngine.unwrap(cTOs, serverIn);
            runDelegatedTasks(serverResult, serverSSLEngine);

            cTOs.compact();
            sTOc.compact();

            if (!dataDone &&
                    (clientOut.limit() == serverIn.position()) &&
                    (serverOut.limit() == clientIn.position())) {
                checkTransfer(serverOut, clientIn);
                checkTransfer(clientOut, serverIn);
                dataDone = true;
            }
        }
    }
}