Java Code Examples for io.netty.handler.ssl.SslContext#newHandler()

The following examples show how to use io.netty.handler.ssl.SslContext#newHandler() . 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: OcspTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
private static void testClientOcspNotEnabled(SslProvider sslProvider) throws Exception {
    SslContext context = SslContextBuilder.forClient()
            .sslProvider(sslProvider)
            .build();
    try {
        SslHandler sslHandler = context.newHandler(ByteBufAllocator.DEFAULT);
        ReferenceCountedOpenSslEngine engine = (ReferenceCountedOpenSslEngine) sslHandler.engine();
        try {
            engine.getOcspResponse();
        } finally {
            engine.release();
        }
    } finally {
        ReferenceCountUtil.release(context);
    }
}
 
Example 2
Source File: OcspTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
private static void testServerOcspNotEnabled(SslProvider sslProvider) throws Exception {
    SelfSignedCertificate ssc = new SelfSignedCertificate();
    try {
        SslContext context = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey())
                .sslProvider(sslProvider)
                .build();
        try {
            SslHandler sslHandler = context.newHandler(ByteBufAllocator.DEFAULT);
            ReferenceCountedOpenSslEngine engine = (ReferenceCountedOpenSslEngine) sslHandler.engine();
            try {
                engine.setOcspResponse(new byte[] { 1, 2, 3 });
            } finally {
                engine.release();
            }
        } finally {
            ReferenceCountUtil.release(context);
        }
    } finally {
        ssc.delete();
    }
}
 
Example 3
Source File: OcspTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
private static ChannelHandler newServerHandler(final SslContext context,
        final byte[] response, final ChannelHandler handler) {
    return new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            SslHandler sslHandler = context.newHandler(ch.alloc());

            if (response != null) {
                ReferenceCountedOpenSslEngine engine = (ReferenceCountedOpenSslEngine) sslHandler.engine();
                engine.setOcspResponse(response);
            }

            pipeline.addLast(sslHandler);

            if (handler != null) {
                pipeline.addLast(handler);
            }
        }
    };
}
 
Example 4
Source File: OcspTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
private static ChannelHandler newClientHandler(final SslContext context,
        final OcspClientCallback callback, final ChannelHandler handler) {
    return new ChannelInitializer<Channel>() {
        @Override
        protected void initChannel(Channel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();

            SslHandler sslHandler = context.newHandler(ch.alloc());
            ReferenceCountedOpenSslEngine engine = (ReferenceCountedOpenSslEngine) sslHandler.engine();

            pipeline.addLast(sslHandler);
            pipeline.addLast(new OcspClientCallbackHandler(engine, callback));

            if (handler != null) {
                pipeline.addLast(handler);
            }
        }
    };
}
 
Example 5
Source File: SslSimpleBuilder.java    From jlogstash-input-plugin with Apache License 2.0 6 votes vote down vote up
public SslHandler build(ByteBufAllocator bufferAllocator) throws SSLException {
    SslContextBuilder builder = SslContextBuilder.forServer(sslCertificateFile, sslKeyFile, passPhrase);

    builder.ciphers(Arrays.asList(ciphers));

    if(requireClientAuth()) {
        logger.debug("Certificate Authorities: " + certificateAuthorities);
        builder.trustManager(new File(certificateAuthorities));
    }

    SslContext context = builder.build();
    SslHandler sslHandler = context.newHandler(bufferAllocator);

    SSLEngine engine = sslHandler.engine();
    engine.setEnabledProtocols(protocols);


    if(requireClientAuth()) {
        engine.setUseClientMode(false);
        engine.setNeedClientAuth(true);
    }

    return sslHandler;
}
 
Example 6
Source File: SslUtils.java    From servicetalk with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link SslHandler} which will supports SNI if the {@link InetSocketAddress} was created from
 * a hostname.
 *
 * @param context the {@link SslContext} which will be used to create the {@link SslHandler}
 * @param allocator the {@link ByteBufAllocator} which will be used to allocate direct memory if required for
 * {@link SSLEngine}
 * @param hostnameVerificationAlgorithm see {@link SSLParameters#setEndpointIdentificationAlgorithm(String)}.
 * If this is {@code null} or empty then you will be vulnerable to a MITM attack.
 * @param hostnameVerificationHost the non-authoritative name of the host.
 * @param hostnameVerificationPort the non-authoritative port.
 * @return a {@link SslHandler}
 */
static SslHandler newHandler(SslContext context, ByteBufAllocator allocator,
                             @Nullable String hostnameVerificationAlgorithm,
                             @Nullable String hostnameVerificationHost,
                             int hostnameVerificationPort) {
    if (hostnameVerificationHost == null) {
        return newHandler(context, allocator);
    }

    SslHandler handler = context.newHandler(allocator, hostnameVerificationHost, hostnameVerificationPort);
    SSLEngine engine = handler.engine();
    try {
        SSLParameters parameters = engine.getSSLParameters();
        parameters.setEndpointIdentificationAlgorithm(hostnameVerificationAlgorithm);
        if (!NetUtil.isValidIpV4Address(hostnameVerificationHost) &&
                !NetUtil.isValidIpV6Address(hostnameVerificationHost)) {
            // SNI doesn't permit IP addresses!
            // https://tools.ietf.org/html/rfc6066#section-3
            // Literal IPv4 and IPv6 addresses are not permitted in "HostName".
            parameters.setServerNames(Collections.singletonList(new SNIHostName(hostnameVerificationHost)));
        }
        engine.setSSLParameters(parameters);
    } catch (Throwable cause) {
        ReferenceCountUtil.release(engine);
        throw cause;
    }
    return handler;
}
 
Example 7
Source File: NettyConnection.java    From styx with Apache License 2.0 5 votes vote down vote up
private static void addChannelHandlers(Channel channel, HttpConfig httpConfig, SslContext sslContext, boolean sendSni, String targetHost) {
    ChannelPipeline pipeline = channel.pipeline();

    if (sslContext != null) {
        SslHandler sslHandler = sendSni
                ? sslContext.newHandler(channel.alloc(), targetHost, IGNORED_PORT_NUMBER)
                : sslContext.newHandler(channel.alloc());
        pipeline.addLast("ssl", sslHandler);
    }

    pipeline.addLast("http-codec", new HttpClientCodec(httpConfig.maxInitialLength(), httpConfig.maxHeadersSize(), httpConfig.maxChunkSize()));
    if (httpConfig.compress()) {
        pipeline.addLast("decompressor", new HttpContentDecompressor());
    }
}
 
Example 8
Source File: ConnectionPoolImpl.java    From pravega with Apache License 2.0 5 votes vote down vote up
/**
 * Create a Channel Initializer which is to to setup {@link ChannelPipeline}.
 */
@VisibleForTesting
ChannelInitializer<SocketChannel> getChannelInitializer(final PravegaNodeUri location,
                                                                final FlowHandler handler) {
    final SslContext sslCtx = getSslContext();

    return new ChannelInitializer<SocketChannel>() {
        @Override
        public void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline p = ch.pipeline();
            if (sslCtx != null) {
                SslHandler sslHandler = sslCtx.newHandler(ch.alloc(), location.getEndpoint(), location.getPort());

                if (clientConfig.isValidateHostName()) {
                    SSLEngine sslEngine = sslHandler.engine();
                    SSLParameters sslParameters = sslEngine.getSSLParameters();
                    sslParameters.setEndpointIdentificationAlgorithm("HTTPS");
                    sslEngine.setSSLParameters(sslParameters);
                }
                p.addLast(sslHandler);
            }
            p.addLast(
                    new ExceptionLoggingHandler(location.getEndpoint()),
                    new CommandEncoder(handler::getAppendBatchSizeTracker, metricNotifier),
                    new LengthFieldBasedFrameDecoder(WireCommands.MAX_WIRECOMMAND_SIZE, 4, 4),
                    new CommandDecoder(),
                    handler);
        }
    };
}
 
Example 9
Source File: PipelineRegistry.java    From crate with Apache License 2.0 5 votes vote down vote up
public void registerItems(ChannelPipeline pipeline, Netty4CorsConfig corsConfig) {
    for (PipelineRegistry.ChannelPipelineItem item : addBeforeList) {
        pipeline.addBefore(item.base, item.name, item.handlerFactory.apply(corsConfig));
    }

    if (sslContextProvider != null) {
        SslContext sslContext = sslContextProvider.getSslContext();
        if (sslContext != null) {
            SslHandler sslHandler = sslContext.newHandler(pipeline.channel().alloc());
            pipeline.addFirst(sslHandler);
        }
    }
}
 
Example 10
Source File: SslReqHandler.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Process receives incoming data from the Netty pipeline. It
 * may request more data by returning the WAITING_FOR_INPUT
 * state. The process method should return DONE when it has
 * finished processing. It may add additional elements to the
 * pipeline. The handler is responsible for to position the
 * buffer read marker correctly such that successive readers
 * see the correct data. The handler is expected to position the
 * marker after the SSLRequest payload.
 * @param buffer The buffer with incoming data
 * @param pipeline The Netty pipeline which may be modified
 * @return The state of the handler
 */
public State process(ByteBuf buffer, ChannelPipeline pipeline) {
    if (buffer.readableBytes() < SSL_REQUEST_BYTE_LENGTH) {
        return State.WAITING_FOR_INPUT;
    }
    // mark the buffer so we can jump back if we don't handle this startup
    buffer.markReaderIndex();
    // reads the total message length (int) and the SSL request code (int)
    if (buffer.readInt() == SSL_REQUEST_BYTE_LENGTH && buffer.readInt() == SSL_REQUEST_CODE) {
        final SslContext sslContext;
        if (sslContextProvider != null) {
            sslContext = sslContextProvider.getSslContext();
        } else {
            sslContext = null;
        }
        // received optional SSL negotiation pkg
        if (sslContext != null) {
            writeByteAndFlushMessage(pipeline.channel(), 'S');
            SslHandler sslHandler = sslContext.newHandler(pipeline.channel().alloc());
            pipeline.addFirst(sslHandler);
        } else {
            writeByteAndFlushMessage(pipeline.channel(), 'N');
        }
        buffer.markReaderIndex();
    } else {
        buffer.resetReaderIndex();
    }
    return State.DONE;
}
 
Example 11
Source File: DFSocketManager.java    From dfactor with MIT License 4 votes vote down vote up
@Override
		protected void initChannel(SocketChannel ch) throws Exception {
			final ChannelPipeline pipe = ch.pipeline();
			if(_sslCfg != null){ //ssl
				SslContext sslCtx = null;
				if(_isServer){
					sslCtx = SslContextBuilder.forServer(new File(_sslCfg.getCertPath()), 
							new File(_sslCfg.getPemPath())).build();
				}else{
					sslCtx = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
				}
				SslHandler sslHandler = sslCtx.newHandler(ch.alloc());
				pipe.addLast(sslHandler);
			}
			//
			if(_decodeType == DFActorDefine.TCP_DECODE_WEBSOCKET){
				if(_isServer){
					pipe.addLast(new HttpServerCodec());
					pipe.addLast(new HttpObjectAggregator(_maxLen));
					pipe.addLast(new DFWSRequestHandler("/"+_wsSfx));
					pipe.addLast(new WebSocketServerProtocolHandler("/"+_wsSfx, null, true));
					if(_customHandler == null){
						pipe.addLast(new TcpWsHandler(_actorId, _requestId, _decodeType, (DFActorTcpDispatcher) _dispatcher, _decoder, _encoder));
					}else{
						pipe.addLast(_customHandler);
					}
				}else{
					pipe.addLast(new HttpClientCodec());
					pipe.addLast(new HttpObjectAggregator(_maxLen));
					if(_customHandler == null){
						DFWsClientHandler handler =  
			                    new DFWsClientHandler(  
			                            WebSocketClientHandshakerFactory.newHandshaker(  
			                            		new URI(_wsSfx), WebSocketVersion.V13, null, false, new DefaultHttpHeaders()),
			                            _actorId, _requestId, _decodeType, (DFActorTcpDispatcher) _dispatcher, _decoder, _encoder); 
						pipe.addLast(handler);
					}else{
						pipe.addLast(_customHandler);
					}
				}
			}
			else if(_decodeType == DFActorDefine.TCP_DECODE_HTTP){
				if(_isServer){
//					pipe.addLast(new HttpServerCodec());
					
					pipe.addLast(new HttpRequestDecoder());
					pipe.addLast(new HttpObjectAggregator(_maxLen));
					pipe.addLast(new HttpResponseEncoder());
					pipe.addLast(new ChunkedWriteHandler());
					
					if(_customHandler == null){
						pipe.addLast(new DFHttpSvrHandler(_actorId, _requestId, _decoder, (DFHttpDispatcher) _dispatcher, (CbHttpServer) _userHandler));
					}else{
						pipe.addLast(_customHandler);
					}
				}else{ //client
					pipe.addLast(new HttpClientCodec());
					pipe.addLast(new HttpObjectAggregator(_maxLen));
					if(_customHandler == null){
						pipe.addLast(new DFHttpCliHandler(_actorId, _requestId, _decoder, (DFHttpDispatcher) _dispatcher, 
								(CbHttpClient) _userHandler, (DFHttpCliReqWrap) _reqData));
					}else{
						pipe.addLast(_customHandler);
					}
				}
			}
			else{
				if(_decodeType == DFActorDefine.TCP_DECODE_LENGTH){ //length base field
					pipe.addLast(new LengthFieldBasedFrameDecoder(_maxLen, 0, 2, 0, 2));
				}
				if(_customHandler == null){
					pipe.addLast(new TcpHandler(_actorId, _requestId, _decodeType, (DFActorTcpDispatcher) _dispatcher, _decoder, _encoder));
				}else{
					pipe.addLast(_customHandler);
				}
			}
			
		}
 
Example 12
Source File: WebServerConnectorFactory.java    From styx with Apache License 2.0 4 votes vote down vote up
private SslHandler sslHandler(Channel channel) {
    SslContext sslContext = newSSLContext((HttpsConnectorConfig) config);

    return sslContext.newHandler(channel.alloc());
}
 
Example 13
Source File: SslUtils.java    From servicetalk with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new {@link SslHandler}.
 *
 * @param context the {@link SslContext} which will be used to create the {@link SslHandler}
 * @param allocator the {@link ByteBufAllocator} which will be used
 * @return a {@link SslHandler}
 */
static SslHandler newHandler(SslContext context, ByteBufAllocator allocator) {
    return context.newHandler(allocator);
}