Example usage for io.netty.handler.ssl ClientAuth NONE

List of usage examples for io.netty.handler.ssl ClientAuth NONE

Introduction

In this page you can find the example usage for io.netty.handler.ssl ClientAuth NONE.

Prototype

ClientAuth NONE

To view the source code for io.netty.handler.ssl ClientAuth NONE.

Click Source Link

Document

Indicates that the javax.net.ssl.SSLEngine will not request client authentication.

Usage

From source file:com.github.ambry.rest.NettySslFactory.java

License:Open Source License

/**
 * @param config the {@link SSLConfig}./*from w w w  .  j a v a 2 s. c o  m*/
 * @return the {@link ClientAuth} setting.
 */
private static ClientAuth getClientAuth(SSLConfig config) {
    switch (config.sslClientAuthentication) {
    case "required":
        return ClientAuth.REQUIRE;
    case "requested":
        return ClientAuth.OPTIONAL;
    default:
        return ClientAuth.NONE;
    }
}

From source file:io.druid.server.emitter.HttpEmitterModule.java

License:Apache License

static AsyncHttpClient createAsyncHttpClient(String nameFormat, String timerThreadNameFormat,
        @Nullable SSLContext sslContext) {
    final DefaultAsyncHttpClientConfig.Builder builder = new DefaultAsyncHttpClientConfig.Builder()
            .setThreadFactory(Execs.makeThreadFactory(nameFormat))
            .setNettyTimer(new HashedWheelTimer(Execs.makeThreadFactory(timerThreadNameFormat)));
    if (sslContext != null) {
        builder.setSslContext(new JdkSslContext(sslContext, true, ClientAuth.NONE));
    }/*ww  w.  j a va 2 s .co  m*/
    return new DefaultAsyncHttpClient(builder.build());
}

From source file:io.druid.server.emitter.ParametrizedUriEmitterModule.java

License:Apache License

@Provides
@ManageLifecycle/*from   w w  w. ja  va2 s. co m*/
@Named("parametrized")
public Emitter getEmitter(Supplier<ParametrizedUriEmitterConfig> config, @Nullable SSLContext sslContext,
        Lifecycle lifecycle, ObjectMapper jsonMapper) {
    final DefaultAsyncHttpClientConfig.Builder builder = new DefaultAsyncHttpClientConfig.Builder();
    if (sslContext != null) {
        builder.setSslContext(new JdkSslContext(sslContext, true, ClientAuth.NONE));
    }
    final AsyncHttpClient client = new DefaultAsyncHttpClient(builder.build());
    lifecycle.addCloseableInstance(client);

    return new ParametrizedUriEmitter(config.get(), client, jsonMapper);
}

From source file:org.apache.nifi.processors.grpc.ListenGRPC.java

License:Apache License

@OnScheduled
public void startServer(final ProcessContext context) throws NoSuchAlgorithmException, IOException,
        KeyStoreException, CertificateException, UnrecoverableKeyException {
    final ComponentLog logger = getLogger();
    // gather configured properties
    final Integer port = context.getProperty(PROP_SERVICE_PORT).asInteger();
    final Boolean useSecure = context.getProperty(PROP_USE_SECURE).asBoolean();
    final Integer flowControlWindow = context.getProperty(PROP_FLOW_CONTROL_WINDOW).asDataSize(DataUnit.B)
            .intValue();/*from  www  .ja v  a  2 s  .  com*/
    final Integer maxMessageSize = context.getProperty(PROP_MAX_MESSAGE_SIZE).asDataSize(DataUnit.B).intValue();
    final SSLContextService sslContextService = context.getProperty(PROP_SSL_CONTEXT_SERVICE)
            .asControllerService(SSLContextService.class);
    final SSLContext sslContext = sslContextService == null ? null
            : sslContextService.createSSLContext(SSLContextService.ClientAuth.NONE);
    final Pattern authorizedDnPattern = Pattern
            .compile(context.getProperty(PROP_AUTHORIZED_DN_PATTERN).getValue());
    final FlowFileIngestServiceInterceptor callInterceptor = new FlowFileIngestServiceInterceptor(getLogger());
    callInterceptor.enforceDNPattern(authorizedDnPattern);

    final FlowFileIngestService flowFileIngestService = new FlowFileIngestService(getLogger(),
            sessionFactoryReference, context);
    NettyServerBuilder serverBuilder = NettyServerBuilder.forPort(port)
            .addService(ServerInterceptors.intercept(flowFileIngestService, callInterceptor))
            // default (de)compressor registries handle both plaintext and gzip compressed messages
            .compressorRegistry(CompressorRegistry.getDefaultInstance())
            .decompressorRegistry(DecompressorRegistry.getDefaultInstance())
            .flowControlWindow(flowControlWindow).maxMessageSize(maxMessageSize);

    if (useSecure && sslContext != null) {
        // construct key manager
        if (StringUtils.isBlank(sslContextService.getKeyStoreFile())) {
            throw new IllegalStateException(
                    "SSL is enabled, but no keystore has been configured. You must configure a keystore.");
        }

        final KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm(), sslContext.getProvider());
        final KeyStore keyStore = KeyStore.getInstance(sslContextService.getKeyStoreType());
        try (final InputStream is = new FileInputStream(sslContextService.getKeyStoreFile())) {
            keyStore.load(is, sslContextService.getKeyStorePassword().toCharArray());
        }
        keyManagerFactory.init(keyStore, sslContextService.getKeyStorePassword().toCharArray());

        SslContextBuilder sslContextBuilder = SslContextBuilder.forServer(keyManagerFactory);

        // if the trust store is configured, then client auth is required.
        if (StringUtils.isNotBlank(sslContextService.getTrustStoreFile())) {
            final TrustManagerFactory trustManagerFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm(), sslContext.getProvider());
            final KeyStore trustStore = KeyStore.getInstance(sslContextService.getTrustStoreType());
            try (final InputStream is = new FileInputStream(sslContextService.getTrustStoreFile())) {
                trustStore.load(is, sslContextService.getTrustStorePassword().toCharArray());
            }
            trustManagerFactory.init(trustStore);
            sslContextBuilder = sslContextBuilder.trustManager(trustManagerFactory);
            sslContextBuilder = sslContextBuilder.clientAuth(ClientAuth.REQUIRE);
        } else {
            sslContextBuilder = sslContextBuilder.clientAuth(ClientAuth.NONE);
        }
        sslContextBuilder = GrpcSslContexts.configure(sslContextBuilder);
        serverBuilder = serverBuilder.sslContext(sslContextBuilder.build());
    }
    logger.info("Starting gRPC server on port: {}", new Object[] { port.toString() });
    this.server = serverBuilder.build().start();
}

From source file:org.apache.nifi.processors.grpc.TestInvokeGRPC.java

License:Apache License

@Test
public void testSecureOneWaySsl() throws Exception {
    final Map<String, String> sslProperties = getKeystoreProperties();
    sslProperties.put(TestGRPCServer.NEED_CLIENT_AUTH, ClientAuth.NONE.name());
    final TestGRPCServer<DummyFlowFileService> server = new TestGRPCServer<>(DummyFlowFileService.class,
            sslProperties);/*from  w  w  w.  ja  va2s  .  com*/

    try {
        final TestRunner runner = TestRunners.newTestRunner(InvokeGRPC.class);
        runner.setProperty(InvokeGRPC.PROP_SERVICE_HOST, TestGRPCServer.HOST);
        useSSLContextService(runner, getTruststoreProperties());
        final int port = server.start(0);
        runner.setProperty(InvokeGRPC.PROP_SERVICE_PORT, String.valueOf(port));
        runner.setProperty(InvokeGRPC.PROP_USE_SECURE, "true");

        final MockFlowFile mockFlowFile = new MockFlowFile(SUCCESS);
        runner.enqueue(mockFlowFile);
        runner.run();
        runner.assertTransferCount(InvokeGRPC.REL_RESPONSE, 1);
        runner.assertTransferCount(InvokeGRPC.REL_SUCCESS_REQ, 1);
        runner.assertTransferCount(InvokeGRPC.REL_RETRY, 0);
        runner.assertTransferCount(InvokeGRPC.REL_NO_RETRY, 0);
        runner.assertTransferCount(InvokeGRPC.REL_FAILURE, 0);

        final List<MockFlowFile> responseFiles = runner.getFlowFilesForRelationship(InvokeGRPC.REL_RESPONSE);
        assertThat(responseFiles.size(), equalTo(1));
        final MockFlowFile response = responseFiles.get(0);
        response.assertAttributeEquals(InvokeGRPC.RESPONSE_CODE,
                String.valueOf(FlowFileReply.ResponseCode.SUCCESS));
        response.assertAttributeEquals(InvokeGRPC.RESPONSE_BODY, "success");
        response.assertAttributeEquals(InvokeGRPC.SERVICE_HOST, TestGRPCServer.HOST);
        response.assertAttributeEquals(InvokeGRPC.SERVICE_PORT, String.valueOf(port));

        final List<MockFlowFile> successFiles = runner.getFlowFilesForRelationship(InvokeGRPC.REL_SUCCESS_REQ);
        assertThat(successFiles.size(), equalTo(1));
        final MockFlowFile successFile = successFiles.get(0);
        successFile.assertAttributeEquals(InvokeGRPC.RESPONSE_CODE,
                String.valueOf(FlowFileReply.ResponseCode.SUCCESS));
        successFile.assertAttributeEquals(InvokeGRPC.RESPONSE_BODY, "success");
        successFile.assertAttributeEquals(InvokeGRPC.SERVICE_HOST, TestGRPCServer.HOST);
        successFile.assertAttributeEquals(InvokeGRPC.SERVICE_PORT, String.valueOf(port));
    } finally {
        server.stop();
    }
}

From source file:org.apache.rocketmq.remoting.netty.TlsHelper.java

License:Apache License

private static ClientAuth parseClientAuthMode(String authMode) {
    if (null == authMode || authMode.trim().isEmpty()) {
        return ClientAuth.NONE;
    }/* w  ww. ja v  a2  s  . c  om*/

    for (ClientAuth clientAuth : ClientAuth.values()) {
        if (clientAuth.name().equals(authMode.toUpperCase())) {
            return clientAuth;
        }
    }

    return ClientAuth.NONE;
}

From source file:org.eclipse.milo.opcua.stack.server.transport.http.OpcServerHttpChannelInitializer.java

License:Open Source License

public OpcServerHttpChannelInitializer(UaStackServer stackServer) {
    this.stackServer = stackServer;

    KeyPair keyPair = stackServer.getConfig().getHttpsKeyPair().orElse(null);
    X509Certificate httpsCertificate = stackServer.getConfig().getHttpsCertificate().orElse(null);

    if (keyPair != null && httpsCertificate != null) {
        try {//www .  j a  v a2 s  .  co  m
            PrivateKey privateKey = keyPair.getPrivate();

            sslContext = SslContextBuilder.forServer(privateKey, httpsCertificate).clientAuth(ClientAuth.NONE)
                    .trustManager(InsecureTrustManagerFactory.INSTANCE).build();
        } catch (Exception e) {
            LoggerFactory.getLogger(OpcServerHttpChannelInitializer.class)
                    .error("Error configuration SslContext: {}", e.getMessage(), e);
        }
    } else {
        LoggerFactory.getLogger(OpcServerHttpChannelInitializer.class)
                .warn("HTTPS KeyPair and/or Certificate not configured; falling back to plaintext...");
    }
}

From source file:org.glassfish.jersey.netty.connector.NettyConnector.java

License:Open Source License

@Override
public Future<?> apply(final ClientRequest jerseyRequest, final AsyncConnectorCallback jerseyCallback) {

    final CompletableFuture<Object> settableFuture = new CompletableFuture<>();

    final URI requestUri = jerseyRequest.getUri();
    String host = requestUri.getHost();
    int port = requestUri.getPort() != -1 ? requestUri.getPort()
            : "https".equals(requestUri.getScheme()) ? 443 : 80;

    try {/*from   w  ww.j  a v  a2 s  .c  o  m*/
        Bootstrap b = new Bootstrap();
        b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline p = ch.pipeline();

                // Enable HTTPS if necessary.
                if ("https".equals(requestUri.getScheme())) {
                    // making client authentication optional for now; it could be extracted to configurable property
                    JdkSslContext jdkSslContext = new JdkSslContext(client.getSslContext(), true,
                            ClientAuth.NONE);
                    p.addLast(jdkSslContext.newHandler(ch.alloc()));
                }

                // http proxy
                Configuration config = jerseyRequest.getConfiguration();
                final Object proxyUri = config.getProperties().get(ClientProperties.PROXY_URI);
                if (proxyUri != null) {
                    final URI u = getProxyUri(proxyUri);

                    final String userName = ClientProperties.getValue(config.getProperties(),
                            ClientProperties.PROXY_USERNAME, String.class);
                    final String password = ClientProperties.getValue(config.getProperties(),
                            ClientProperties.PROXY_PASSWORD, String.class);

                    p.addLast(new HttpProxyHandler(
                            new InetSocketAddress(u.getHost(), u.getPort() == -1 ? 8080 : u.getPort()),
                            userName, password));
                }

                p.addLast(new HttpClientCodec());
                p.addLast(new ChunkedWriteHandler());
                p.addLast(new HttpContentDecompressor());
                p.addLast(new JerseyClientHandler(NettyConnector.this, jerseyRequest, jerseyCallback,
                        settableFuture));
            }
        });

        // connect timeout
        Integer connectTimeout = ClientProperties.getValue(jerseyRequest.getConfiguration().getProperties(),
                ClientProperties.CONNECT_TIMEOUT, 0);
        if (connectTimeout > 0) {
            b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout);
        }

        // Make the connection attempt.
        final Channel ch = b.connect(host, port).sync().channel();

        // guard against prematurely closed channel
        final GenericFutureListener<io.netty.util.concurrent.Future<? super Void>> closeListener = new GenericFutureListener<io.netty.util.concurrent.Future<? super Void>>() {
            @Override
            public void operationComplete(io.netty.util.concurrent.Future<? super Void> future)
                    throws Exception {
                if (!settableFuture.isDone()) {
                    settableFuture.completeExceptionally(new IOException("Channel closed."));
                }
            }
        };

        ch.closeFuture().addListener(closeListener);

        HttpRequest nettyRequest;

        if (jerseyRequest.hasEntity()) {
            nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1,
                    HttpMethod.valueOf(jerseyRequest.getMethod()), requestUri.getRawPath());
        } else {
            nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
                    HttpMethod.valueOf(jerseyRequest.getMethod()), requestUri.getRawPath());
        }

        // headers
        for (final Map.Entry<String, List<String>> e : jerseyRequest.getStringHeaders().entrySet()) {
            nettyRequest.headers().add(e.getKey(), e.getValue());
        }

        // host header - http 1.1
        nettyRequest.headers().add(HttpHeaderNames.HOST, jerseyRequest.getUri().getHost());

        if (jerseyRequest.hasEntity()) {
            if (jerseyRequest.getLengthLong() == -1) {
                HttpUtil.setTransferEncodingChunked(nettyRequest, true);
            } else {
                nettyRequest.headers().add(HttpHeaderNames.CONTENT_LENGTH, jerseyRequest.getLengthLong());
            }
        }

        if (jerseyRequest.hasEntity()) {
            // Send the HTTP request.
            ch.writeAndFlush(nettyRequest);

            final JerseyChunkedInput jerseyChunkedInput = new JerseyChunkedInput(ch);
            jerseyRequest.setStreamProvider(new OutboundMessageContext.StreamProvider() {
                @Override
                public OutputStream getOutputStream(int contentLength) throws IOException {
                    return jerseyChunkedInput;
                }
            });

            if (HttpUtil.isTransferEncodingChunked(nettyRequest)) {
                ch.write(new HttpChunkedInput(jerseyChunkedInput));
            } else {
                ch.write(jerseyChunkedInput);
            }

            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    // close listener is not needed any more.
                    ch.closeFuture().removeListener(closeListener);

                    try {
                        jerseyRequest.writeEntity();
                    } catch (IOException e) {
                        jerseyCallback.failure(e);
                        settableFuture.completeExceptionally(e);
                    }
                }
            });

            ch.flush();
        } else {
            // close listener is not needed any more.
            ch.closeFuture().removeListener(closeListener);

            // Send the HTTP request.
            ch.writeAndFlush(nettyRequest);
        }

    } catch (InterruptedException e) {
        settableFuture.completeExceptionally(e);
        return settableFuture;
    }

    return settableFuture;
}

From source file:org.graylog2.plugin.inputs.transports.AbstractTcpTransport.java

License:Open Source License

private Callable<ChannelHandler> getSslHandlerCallable(MessageInput input) {
    final File certFile;
    final File keyFile;
    if (tlsCertFile.exists() && tlsKeyFile.exists()) {
        certFile = tlsCertFile;// w  ww.j a  v  a 2s  .  c  o  m
        keyFile = tlsKeyFile;
    } else {
        LOG.warn(
                "TLS key file or certificate file does not exist, creating a self-signed certificate for input [{}/{}].",
                input.getName(), input.getId());

        final String tmpDir = System.getProperty("java.io.tmpdir");
        checkState(tmpDir != null, "The temporary directory must not be null!");
        final Path tmpPath = Paths.get(tmpDir);
        if (!Files.isDirectory(tmpPath) || !Files.isWritable(tmpPath)) {
            throw new IllegalStateException(
                    "Couldn't write to temporary directory: " + tmpPath.toAbsolutePath());
        }

        try {
            final SelfSignedCertificate ssc = new SelfSignedCertificate(
                    configuration.getString(CK_BIND_ADDRESS) + ":" + configuration.getString(CK_PORT));
            certFile = ssc.certificate();
            keyFile = ssc.privateKey();
        } catch (CertificateException e) {
            final String msg = String.format(Locale.ENGLISH,
                    "Problem creating a self-signed certificate for input [%s/%s].", input.getName(),
                    input.getId());
            throw new IllegalStateException(msg, e);
        }
    }

    final ClientAuth clientAuth;
    switch (tlsClientAuth) {
    case TLS_CLIENT_AUTH_DISABLED:
        LOG.debug("Not using TLS client authentication");
        clientAuth = ClientAuth.NONE;
        break;
    case TLS_CLIENT_AUTH_OPTIONAL:
        LOG.debug("Using optional TLS client authentication");
        clientAuth = ClientAuth.OPTIONAL;
        break;
    case TLS_CLIENT_AUTH_REQUIRED:
        LOG.debug("Using mandatory TLS client authentication");
        clientAuth = ClientAuth.REQUIRE;
        break;
    default:
        throw new IllegalArgumentException("Unknown TLS client authentication mode: " + tlsClientAuth);
    }

    return buildSslHandlerCallable(nettyTransportConfiguration.getTlsProvider(), certFile, keyFile,
            tlsKeyPassword, clientAuth, tlsClientAuthCertFile);
}

From source file:org.wso2.carbon.transport.http.netty.common.ssl.SSLHandlerFactory.java

License:Open Source License

/**
 * This method will provide netty ssl context which supports HTTP2 over TLS using
 * Application Layer Protocol Negotiation (ALPN)
 *
 * @return instance of {@link SslContext}
 * @throws SSLException if any error occurred during building SSL context.
 *//*from  w w w  . ja  v a  2  s  .c o  m*/
public SslContext createHttp2TLSContext() throws SSLException {

    // If listener configuration does not include cipher suites , default ciphers required by the HTTP/2
    // specification will be added.
    List<String> ciphers = sslConfig.getCipherSuites() != null && sslConfig.getCipherSuites().length > 0
            ? Arrays.asList(sslConfig.getCipherSuites())
            : Http2SecurityUtil.CIPHERS;
    SslProvider provider = OpenSsl.isAlpnSupported() ? SslProvider.OPENSSL : SslProvider.JDK;
    return SslContextBuilder.forServer(this.getKeyManagerFactory()).trustManager(this.getTrustStoreFactory())
            .sslProvider(provider).ciphers(ciphers, SupportedCipherSuiteFilter.INSTANCE)
            .clientAuth(needClientAuth ? ClientAuth.REQUIRE : ClientAuth.NONE)
            .applicationProtocolConfig(new ApplicationProtocolConfig(ApplicationProtocolConfig.Protocol.ALPN,
                    // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers.
                    ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
                    // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers.
                    ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
                    ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1))
            .build();
}