javax.net.ssl.SSLException Java Examples

The following examples show how to use javax.net.ssl.SSLException. 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: ALPNOfferedClientHelloExplorer.java    From lams with GNU General Public License v2.0 7 votes vote down vote up
private static List<Integer> exploreHandshake(
        ByteBuffer input, byte recordMajorVersion,
        byte recordMinorVersion, int recordLength) throws SSLException {

    // What is the handshake type?
    byte handshakeType = input.get();
    if (handshakeType != 0x01) {   // 0x01: client_hello message
        throw UndertowMessages.MESSAGES.expectedClientHello();
    }

    // What is the handshake body length?
    int handshakeLength = getInt24(input);

    // Theoretically, a single handshake message might span multiple
    // records, but in practice this does not occur.
    if (handshakeLength > recordLength - 4) { // 4: handshake header size
        throw UndertowMessages.MESSAGES.multiRecordSSLHandshake();
    }

    input = input.duplicate();
    input.limit(handshakeLength + input.position());
    return exploreRecord(input);
}
 
Example #2
Source File: OpenDistroSecuritySSLNettyTransport.java    From deprecated-security-ssl with Apache License 2.0 7 votes vote down vote up
@Override
public final void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    if(cause instanceof DecoderException && cause != null) {
        cause = cause.getCause();
    }
    
    errorHandler.logError(cause, false);
    
    if(cause instanceof NotSslRecordException) {
        log.warn("Someone ({}) speaks transport plaintext instead of ssl, will close the channel", ctx.channel().remoteAddress());
        ctx.channel().close();
        return;
    } else if (cause instanceof SSLException) {
        log.error("SSL Problem "+cause.getMessage(),cause);
        ctx.channel().close();
        return;
    } else if (cause instanceof SSLHandshakeException) {
        log.error("Problem during handshake "+cause.getMessage());
        ctx.channel().close();
        return;
    }

    super.exceptionCaught(ctx, cause);
}
 
Example #3
Source File: OpenDistroSecuritySSLNettyTransport.java    From deprecated-security-ssl with Apache License 2.0 6 votes vote down vote up
@Override
public final void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    if(OpenDistroSecuritySSLNettyTransport.this.lifecycle.started()) {
        
        if(cause instanceof DecoderException && cause != null) {
            cause = cause.getCause();
        }
        
        errorHandler.logError(cause, false);
        
        if(cause instanceof NotSslRecordException) {
            logger.warn("Someone ({}) speaks transport plaintext instead of ssl, will close the channel", ctx.channel().remoteAddress());
            ctx.channel().close();
            return;
        } else if (cause instanceof SSLException) {
            logger.error("SSL Problem "+cause.getMessage(),cause);
            ctx.channel().close();
            return;
        } else if (cause instanceof SSLHandshakeException) {
            logger.error("Problem during handshake "+cause.getMessage());
            ctx.channel().close();
            return;
        }
    }
    
    super.exceptionCaught(ctx, cause);
}
 
Example #4
Source File: BasicOpenSSLEngineTest.java    From wildfly-openssl with Apache License 2.0 6 votes vote down vote up
@Test(expected = SSLException.class)
public void testWrongClientSideTrustManagerFailsValidation() throws IOException, NoSuchAlgorithmException, InterruptedException {
    try (ServerSocket serverSocket = SSLTestUtils.createServerSocket()) {
        final AtomicReference<byte[]> sessionID = new AtomicReference<>();
        final SSLContext sslContext = SSLTestUtils.createSSLContext("openssl.TLSv1");

        Thread acceptThread = new Thread(new EchoRunnable(serverSocket, sslContext, sessionID));
        acceptThread.start();
        final SSLSocket socket = (SSLSocket) SSLTestUtils.createSSLContext("openssl.TLSv1").getSocketFactory().createSocket();
        socket.setSSLParameters(socket.getSSLParameters());
        socket.connect(SSLTestUtils.createSocketAddress());
        socket.getOutputStream().write(MESSAGE.getBytes(StandardCharsets.US_ASCII));
        socket.getSession().invalidate();
        socket.close();
        serverSocket.close();
        acceptThread.join();
    }
}
 
Example #5
Source File: OpenSslServerContext.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
private OpenSslServerContext(
        X509Certificate[] trustCertCollection, TrustManagerFactory trustManagerFactory,
        X509Certificate[] keyCertChain, PrivateKey key, String keyPassword, KeyManagerFactory keyManagerFactory,
        Iterable<String> ciphers, CipherSuiteFilter cipherFilter, OpenSslApplicationProtocolNegotiator apn,
        long sessionCacheSize, long sessionTimeout, ClientAuth clientAuth, String[] protocols, boolean startTls,
        boolean enableOcsp) throws SSLException {
    super(ciphers, cipherFilter, apn, sessionCacheSize, sessionTimeout, SSL.SSL_MODE_SERVER, keyCertChain,
            clientAuth, protocols, startTls, enableOcsp);
    // Create a new SSL_CTX and configure it.
    boolean success = false;
    try {
        ServerContext context = newSessionContext(this, ctx, engineMap, trustCertCollection, trustManagerFactory,
                                                  keyCertChain, key, keyPassword, keyManagerFactory);
        sessionContext = context.sessionContext;
        keyMaterialManager = context.keyMaterialManager;
        success = true;
    } finally {
        if (!success) {
            release();
        }
    }
}
 
Example #6
Source File: ConfirmingHostnameVerifier.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void verify(final String host, final X509Certificate cert) throws SSLException {
  if (!CertificateManager.getInstance().getState().CHECK_HOSTNAME) {
    return;
  }
  try {
    myVerifier.verify(host, cert);
  }
  catch (SSLException e) {
    //noinspection ConstantConditions
    if (!accepted(host, cert)) {
      throw e;
    }
    // TODO: inclusion in some kind of persistent settings
    // Read/Write lock to protect storage?
  }
}
 
Example #7
Source File: ConscryptAlpnSslEngine.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
ServerEngine(SSLEngine engine, ByteBufAllocator alloc,
             JdkApplicationProtocolNegotiator applicationNegotiator) {
    super(engine, alloc, applicationNegotiator.protocols());

    // Register for completion of the handshake.
    Conscrypt.setHandshakeListener(engine, new HandshakeListener() {
        @Override
        public void onHandshakeFinished() throws SSLException {
            selectProtocol();
        }
    });

    protocolSelector = checkNotNull(applicationNegotiator.protocolSelectorFactory()
                    .newSelector(this,
                            new LinkedHashSet<String>(applicationNegotiator.protocols())),
            "protocolSelector");
}
 
Example #8
Source File: SSLEngineTestCase.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Unwraps data with the specified engine.
 *
 * @param engine       - SSLEngine that unwraps data.
 * @param unwrapper    - Set unwrapper id, e.g. "server" of "client".
 *                       Used for logging only.
 * @param net          - Buffer with data to unwrap.
 * @param wantedStatus - Specifies expected result status of wrapping.
 * @param result       - Array which first element will be used to output
 *                       wrap result object.
 * @return - Buffer with unwrapped data.
 * @throws SSLException - thrown on engine errors.
 */
public static ByteBuffer doUnWrap(SSLEngine engine, String unwrapper,
        ByteBuffer net, SSLEngineResult.Status wantedStatus,
        SSLEngineResult[] result) throws SSLException {

    ByteBuffer app = ByteBuffer.allocate(
            engine.getSession().getApplicationBufferSize());
    int length = net.remaining();
    System.out.println(unwrapper + " unwrapping " + length + " bytes...");
    SSLEngineResult r = engine.unwrap(net, app);
    app.flip();
    System.out.println(unwrapper + " handshake status is "
            + engine.getHandshakeStatus());
    checkResult(r, wantedStatus);
    if (result != null && result.length > 0) {
        result[0] = r;
    }
    return app;
}
 
Example #9
Source File: ExtractorClient.java    From deep-spark with Apache License 2.0 6 votes vote down vote up
public ExtractorClient initialize() throws DeepExtractorInitializationException {
    try {
        // Configure SSL.
        final SslContext sslCtx;
        if (SSL) {

            sslCtx = SslContext.newClientContext(InsecureTrustManagerFactory.INSTANCE);

        } else {
            sslCtx = null;
        }

        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ExtractorClientInitializer<T>(sslCtx));

        // Make a new connection.
        this.ch = b.connect(HOST, PORT).sync().channel();

        // Get the handler instance to initiate the request.
        this.handler = ch.pipeline().get(ExtractorClientHandler.class);
    } catch (SSLException | InterruptedException e) {
        throw new DeepExtractorInitializationException(e);

    }
    return this;
}
 
Example #10
Source File: SslFilter.java    From jane with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Executed just before the filter is added into the chain, we do :
 * <ul>
 * <li>check that we don't have a SSL filter already present
 * <li>we update the next filter
 * <li>we create the SSL handler helper class
 * <li>and we store it into the session's Attributes
 * </ul>
 */
@Override
public void onPreAdd(IoFilterChain chain, String name, NextFilter nextFilter) throws SSLException {
	// Check that we don't have a SSL filter already present in the chain
	if (chain.getEntry(SslFilter.class) != null)
		throw new IllegalStateException("only one SSL filter is permitted in a chain");

	// Adding the supported ciphers in the SSLHandler
	if (enabledCipherSuites == null || enabledCipherSuites.length == 0)
		enabledCipherSuites = sslContext.getServerSocketFactory().getSupportedCipherSuites();

	IoSession session = chain.getSession();

	// Create a SSL handler and start handshake.
	SslHandler sslHandler = new SslHandler(this, session);
	sslHandler.init();

	session.setAttribute(SSL_HANDLER, sslHandler);
}
 
Example #11
Source File: SslContextFactory.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * Checks that all required parameters are set.
 *
 * @throws SSLException If any of required parameters is missing.
 */
private void checkParameters() throws SSLException {
    assert keyStoreType != null;
    assert proto != null;

    checkNullParameter(keyStoreFilePath, "keyStoreFilePath");
    checkNullParameter(keyStorePwd, "keyStorePwd");

    if (trustMgrs == null) {
        if (trustStoreFilePath == null)
            throw new SSLException("Failed to initialize SSL context (either trustStoreFilePath or " +
                "trustManagers must be provided)");
        else
            checkNullParameter(trustStorePwd, "trustStorePwd");
    }
}
 
Example #12
Source File: BlockingSslHandler.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * Check status and retry the negotiation process if needed.
 *
 * @param res Result.
 * @throws GridNioException If exception occurred during handshake.
 * @throws SSLException If failed to process SSL data
 */
private void renegotiateIfNeeded(SSLEngineResult res) throws IgniteCheckedException, SSLException {
    if (res.getStatus() != CLOSED && res.getStatus() != BUFFER_UNDERFLOW
        && res.getHandshakeStatus() != NOT_HANDSHAKING) {
        // Renegotiation required.
        handshakeStatus = res.getHandshakeStatus();

        if (log.isDebugEnabled())
            log.debug("Renegotiation requested [status=" + res.getStatus() + ", handshakeStatus = " +
                handshakeStatus + ']');

        handshakeFinished = false;

        handshake();
    }
}
 
Example #13
Source File: SslFactory.java    From hivemq-community-edition with Apache License 2.0 6 votes vote down vote up
@NotNull
@VisibleForTesting
SslContext getSslContext(@NotNull final Tls tls) throws SslException {

    try {
        if (sslContextStore.contains(tls)) {
            return sslContextStore.get(tls);
        }

        final SslContext sslContext = sslContextFactory.createSslContext(tls);
        sslContextStore.put(tls, sslContext);
        return sslContext;

    } catch (final SSLException e) {
        throw new SslException("Not able to create SSL server context", e);
    }
}
 
Example #14
Source File: AsyncChannelWrapperSecure.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
private void checkResult(SSLEngineResult result, boolean wrap)
        throws SSLException {

    handshakeStatus = result.getHandshakeStatus();
    resultStatus = result.getStatus();

    if (resultStatus != Status.OK &&
            (wrap || resultStatus != Status.BUFFER_UNDERFLOW)) {
        throw new SSLException("TODO");
    }
    if (wrap && result.bytesConsumed() != 0) {
        throw new SSLException("TODO");
    }
    if (!wrap && result.bytesProduced() != 0) {
        throw new SSLException("TODO");
    }
}
 
Example #15
Source File: AzureExceptionMappingService.java    From cyberduck with GNU General Public License v3.0 5 votes vote down vote up
@Override
public BackgroundException map(final StorageException failure) {
    final StringBuilder buffer = new StringBuilder();
    this.append(buffer, failure.getMessage());
    if(ExceptionUtils.getRootCause(failure) instanceof UnknownHostException) {
        return new NotfoundException(buffer.toString(), failure);
    }
    switch(failure.getHttpStatusCode()) {
        case 403:
            return new LoginFailureException(buffer.toString(), failure);
        case 404:
            return new NotfoundException(buffer.toString(), failure);
        case 304:
        case 405:
        case 400:
        case 411:
        case 412:
            return new InteroperabilityException(buffer.toString(), failure);
        case 500:
            // InternalError
            // OperationTimedOut
            return new ConnectionTimeoutException(buffer.toString(), failure);
        case 503:
            // ServerBusy
            return new RetriableAccessDeniedException(buffer.toString(), failure);
    }
    for(Throwable cause : ExceptionUtils.getThrowableList(failure)) {
        if(cause instanceof SSLException) {
            return new SSLExceptionMappingService().map(buffer.toString(), (SSLException) cause);
        }
    }
    return this.wrap(failure, buffer);
}
 
Example #16
Source File: DeploymentTest.java    From msf4j with Apache License 2.0 5 votes vote down vote up
@Test(description = "Testing broadcasting messages for text, binary and pong using two clients.")
public void testBroadcast() throws InterruptedException, SSLException, URISyntaxException {
    //Initializing local variables
    String textReceived;
    String client1Name = "abc";
    String client2Name = "xyz";

    WebSocketClient chatClient1 = new WebSocketClient(chatUrl + client1Name);
    Assert.assertTrue(chatClient1.handhshake());
    Thread.sleep(sleepTime);

    WebSocketClient chatClient2 = new WebSocketClient(chatUrl + client2Name);
    Assert.assertTrue(chatClient2.handhshake());
    Thread.sleep(sleepTime);

    textReceived = chatClient1.getTextReceived();
    Assert.assertEquals(textReceived, client2Name + " connected to chat");

    //Check the broadcast text
    String textSent = "test";
    chatClient1.sendText(textSent);
    Thread.sleep(sleepTime);
    Assert.assertEquals(chatClient1.getTextReceived(), client1Name + ":" + textSent);
    Assert.assertEquals(chatClient2.getTextReceived(), client1Name + ":" + textSent);

    //Check close connection
    chatClient2.shutDown();
    Thread.sleep(sleepTime);
    Assert.assertEquals(chatClient1.getTextReceived(), client2Name + " left the chat");
    chatClient1.shutDown();
}
 
Example #17
Source File: DTLSInputRecord.java    From openjsse with GNU General Public License v2.0 5 votes vote down vote up
private int bytesInCompletePacket(ByteBuffer packet) throws SSLException {

        // DTLS length field is in bytes 11/12
        if (packet.remaining() < headerSize) {
            return -1;
        }

        // Last sanity check that it's not a wild record
        int pos = packet.position();

        // Check the content type of the record.
        byte contentType = packet.get(pos);
        if (ContentType.valueOf(contentType) == null) {
            throw new SSLException(
                    "Unrecognized SSL message, plaintext connection?");
        }

        // Check the protocol version of the record.
        byte majorVersion = packet.get(pos + 1);
        byte minorVersion = packet.get(pos + 2);
        if (!ProtocolVersion.isNegotiable(
                majorVersion, minorVersion, true, false)) {
            throw new SSLException("Unrecognized record version " +
                    ProtocolVersion.nameOf(majorVersion, minorVersion) +
                    " , plaintext connection?");
        }

        // Get the fragment length of the record.
        int fragLen = ((packet.get(pos + 11) & 0xFF) << 8) +
                       (packet.get(pos + 12) & 0xFF) + headerSize;
        if (fragLen > Record.maxFragmentSize) {
            throw new SSLException(
                    "Record overflow, fragment length (" + fragLen +
                    ") MUST not exceed " + Record.maxFragmentSize);
        }

        return fragLen;
    }
 
Example #18
Source File: TlsCryptoSocket.java    From vespa with Apache License 2.0 5 votes vote down vote up
private int applicationDataWrap(ByteBuffer src) throws IOException {
    SSLEngineResult result = sslEngineWrap(src);
    if (result.getHandshakeStatus() != HandshakeStatus.NOT_HANDSHAKING) throw new SSLException("Renegotiation detected");
    switch (result.getStatus()) {
        case OK:
            return result.bytesConsumed();
        case BUFFER_OVERFLOW:
            return 0;
        default:
            throw unexpectedStatusException(result.getStatus());
    }
}
 
Example #19
Source File: SslHandler.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Decrypt the incoming buffer and move the decrypted data to an
 * application buffer.
 */
private SSLEngineResult unwrap() throws SSLException {
    // We first have to create the application buffer if it does not exist
    if (appBuffer == null) {
        appBuffer = IoBuffer.allocate(inNetBuffer.remaining());
    } else {
        // We already have one, just add the new data into it
        appBuffer.expand(inNetBuffer.remaining());
    }

    SSLEngineResult res;

    Status status = null;
    HandshakeStatus handshakeStatus = null;

    do {
        // Decode the incoming data
        res = sslEngine.unwrap(inNetBuffer.buf(), appBuffer.buf());
        status = res.getStatus();

        // We can be processing the Handshake
        handshakeStatus = res.getHandshakeStatus();

        if (status == SSLEngineResult.Status.BUFFER_OVERFLOW) {
            // We have to grow the target buffer, it's too small.
            // Then we can call the unwrap method again
            appBuffer.capacity(appBuffer.capacity() << 1);
            appBuffer.limit(appBuffer.capacity());
            continue;
        }
    } while (((status == SSLEngineResult.Status.OK) || (status == SSLEngineResult.Status.BUFFER_OVERFLOW))
            && ((handshakeStatus == SSLEngineResult.HandshakeStatus.NOT_HANDSHAKING) || (handshakeStatus == SSLEngineResult.HandshakeStatus.NEED_UNWRAP)));

    return res;
}
 
Example #20
Source File: SSLServerSocketImpl.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Initializes the server socket.
 */
private void initServer(SSLContextImpl context) throws SSLException {
    if (context == null) {
        throw new SSLException("No Authentication context given");
    }
    sslContext = context;
    enabledCipherSuites = sslContext.getDefaultCipherSuiteList(true);
    enabledProtocols = sslContext.getDefaultProtocolList(true);
}
 
Example #21
Source File: HttpClientTest.java    From braintree_android with MIT License 5 votes vote down vote up
@Test(timeout = 1000)
public void postsErrorForHttpsRequestsWhenSSLSocketFactoryIsNull() throws IOException, InterruptedException {
    HttpClient httpClient = new HttpClient()
            .setBaseUrl("https://example.com")
            .setSSLSocketFactory(null);

    assertExceptionIsPosted(httpClient, SSLException.class, "SSLSocketFactory was not set or failed to initialize");
}
 
Example #22
Source File: SSLEngineImpl.java    From openjsse with GNU General Public License v2.0 5 votes vote down vote up
private static SSLException getTaskThrown(Exception taskThrown) {
    String msg = taskThrown.getMessage();

    if (msg == null) {
        msg = "Delegated task threw Exception or Error";
    }

    if (taskThrown instanceof RuntimeException) {
        throw new RuntimeException(msg, taskThrown);
    } else if (taskThrown instanceof SSLHandshakeException) {
        return (SSLHandshakeException)
            new SSLHandshakeException(msg).initCause(taskThrown);
    } else if (taskThrown instanceof SSLKeyException) {
        return (SSLKeyException)
            new SSLKeyException(msg).initCause(taskThrown);
    } else if (taskThrown instanceof SSLPeerUnverifiedException) {
        return (SSLPeerUnverifiedException)
            new SSLPeerUnverifiedException(msg).initCause(taskThrown);
    } else if (taskThrown instanceof SSLProtocolException) {
        return (SSLProtocolException)
            new SSLProtocolException(msg).initCause(taskThrown);
    } else if (taskThrown instanceof SSLException) {
        return (SSLException)taskThrown;
    } else {
        return new SSLException(msg, taskThrown);
    }
}
 
Example #23
Source File: ClientConfigShould.java    From mutual-tls-ssl with Apache License 2.0 5 votes vote down vote up
@Test
public void createNettyHttpClientWithOneWayAuthentication() throws SSLException {
    SSLFactory sslFactory = createSSLFactory(true, false);

    reactor.netty.http.client.HttpClient httpClient = victim.nettyHttpClient(sslFactory);

    assertThat(httpClient).isNotNull();
    verify(sslFactory, times(2)).getSslContext();
    verify(sslFactory, times(1)).getTrustManager();
}
 
Example #24
Source File: SslConduit.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void closed() {
    if(anyAreSet(state, FLAG_CLOSED)) {
        return;
    }
    state |= FLAG_CLOSED | FLAG_DELEGATE_SINK_SHUTDOWN | FLAG_DELEGATE_SOURCE_SHUTDOWN | FLAG_WRITE_SHUTDOWN | FLAG_READ_SHUTDOWN;
    notifyReadClosed();
    notifyWriteClosed();
    if(dataToUnwrap != null) {
        dataToUnwrap.close();
        dataToUnwrap = null;
    }
    if(unwrappedData != null) {
        unwrappedData.close();
        unwrappedData = null;
    }
    if(wrappedData != null) {
        wrappedData.close();
        wrappedData = null;
    }
    if(allAreClear(state, FLAG_ENGINE_OUTBOUND_SHUTDOWN)) {
        engine.closeOutbound();
    }
    if(allAreClear(state, FLAG_ENGINE_INBOUND_SHUTDOWN)) {
        try {
            engine.closeInbound();
        } catch (SSLException e) {
            UndertowLogger.REQUEST_LOGGER.ioException(e);
        } catch (Throwable t) {
            UndertowLogger.REQUEST_LOGGER.handleUnexpectedFailure(t);
        }
    }
    IoUtils.safeClose(delegate);
}
 
Example #25
Source File: DTLSHandshakeWithReplicatedPacketsTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected void testOneCipher(String cipher) throws SSLException {
    SSLContext context = getContext();
    int maxPacketSize = getMaxPacketSize();
    boolean useSNI = !TEST_MODE.equals("norm");
    SSLEngine clientEngine = getClientSSLEngine(context, useSNI);
    SSLEngine serverEngine = getServerSSLEngine(context, useSNI);
    clientEngine.setEnabledCipherSuites(new String[]{cipher});
    serverEngine.setEnabledCipherSuites(new String[]{cipher});
    serverEngine.setNeedClientAuth(!cipher.contains("anon"));
    doHandshake(clientEngine, serverEngine, maxPacketSize,
            HandshakeMode.INITIAL_HANDSHAKE, true);
}
 
Example #26
Source File: AsyncTcpSocketSsl.java    From datakernel with Apache License 2.0 5 votes vote down vote up
private void tryCloseOutbound() {
	if (!engine.isOutboundDone()) {
		engine.closeOutbound();
		try {
			while (!engine.isOutboundDone()) {
				SSLEngineResult result = tryToWrap();
				if (result.getStatus() == CLOSED) {
					break;
				}
			}
		} catch (SSLException ignored) {
		}
	}
}
 
Example #27
Source File: GrpcConfig.java    From benchmarks with Apache License 2.0 5 votes vote down vote up
public static ManagedChannel getServerChannel()
{
    final NettyChannelBuilder channelBuilder =
        NettyChannelBuilder.forAddress(getServerHost(), getServerPort());
    if (getBoolean(TLS))
    {
        final Path certificatesDir = Configuration.certificatesDirectory();
        final SslContextBuilder sslClientContextBuilder = GrpcSslContexts.forClient()
            .trustManager(certificatesDir.resolve("ca.pem").toFile())
            .keyManager(
            certificatesDir.resolve("client.pem").toFile(), certificatesDir.resolve("client.key").toFile());

        try
        {
            channelBuilder.sslContext(sslClientContextBuilder.build());
        }
        catch (final SSLException ex)
        {
            LangUtil.rethrowUnchecked(ex);
        }
    }
    else
    {
        channelBuilder.usePlaintext();
    }
    return channelBuilder.build();
}
 
Example #28
Source File: SSLServerSocketImpl.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Initializes the server socket.
 */
private void initServer(SSLContextImpl context) throws SSLException {
    if (context == null) {
        throw new SSLException("No Authentication context given");
    }
    sslContext = context;
    enabledCipherSuites = sslContext.getDefaultCipherSuiteList(true);
    enabledProtocols = sslContext.getDefaultProtocolList(true);
}
 
Example #29
Source File: OpenSSLEngine.java    From wildfly-openssl with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized void beginHandshake() throws SSLException {
    if (engineClosed || destroyed != 0) {
        throw ENGINE_CLOSED;
    }
    if (clientMode) {
        switch (accepted) {
            case 0:
                handshake();
                accepted = 2;
                break;
            case 1:
                // A user did not start handshake by calling this method by him/herself,
                // but handshake has been started already by wrap() or unwrap() implicitly.
                // Because it's the user's first time to call this method, it is unfair to
                // raise an exception.  From the user's standpoint, he or she never asked
                // for renegotiation.

                accepted = 2; // Next time this method is invoked by the user, we should raise an exception.
                break;
            case 2:
                throw RENEGOTIATION_UNSUPPORTED;
            default:
                throw new Error();
        }
    } else {
        if (accepted > 0) {
            renegotiate();
        }
        accepted = 2;
    }
}
 
Example #30
Source File: InstrumentedSSLEngine.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Override
public SSLEngineResult wrap(
      ByteBuffer[] srcs, int offset, int length, ByteBuffer dst)
      throws SSLException {
   long startTimeNs = metrics.startTime();
   try {
      return engine.wrap(srcs, offset, length, dst);
   }
   finally {
      metrics.onEncodeComplete(startTimeNs);
   }
}