io.netty.handler.ssl.SslContext Java Examples
The following examples show how to use
io.netty.handler.ssl.SslContext.
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: ReplicaConnectionImplTest.java From waltz with Apache License 2.0 | 6 votes |
@Before public void setup() throws Exception { final long segmentSizeThreshold = 400L; Properties properties = new Properties(); properties.setProperty(IntegrationTestHelper.Config.ZNODE_PATH, "/storage/cli/test"); properties.setProperty(IntegrationTestHelper.Config.NUM_PARTITIONS, "2"); properties.setProperty(IntegrationTestHelper.Config.ZK_SESSION_TIMEOUT, "30000"); properties.setProperty(WaltzStorageConfig.SEGMENT_SIZE_THRESHOLD, String.valueOf(segmentSizeThreshold)); helper = new IntegrationTestHelper(properties); helper.startZooKeeperServer(); helper.startWaltzStorage(true); helper.setWaltzStorageAssignment(true); UUID key = helper.getClusterKey(); SslContext sslContext = Utils.getSslContext(helper.getSslConfigPath(), WaltzServerConfig.SERVER_SSL_CONFIG_PREFIX); ConnectionConfig config = TestUtils.makeConnectionConfig(2, key, sslContext); String connectString = helper.getStorageConnectString(); connectionFactory = new ReplicaConnectionFactoryImpl(connectString, config); }
Example #2
Source File: TestWssClient.java From util4j with Apache License 2.0 | 6 votes |
public static void main(String[] args) throws Exception { SslContext sslc=SslContextBuilder.forClient().build(); NettyClientConfig nc=new NettyClientConfig(); URI uri=new URI("wss://cloud.jueb.net:1191/test"); NettyClient ns=new NettyClient(nc, "192.168.0.223", 1191,new WebSocketClientInitializer(uri,sslc) { @Override protected void webSocketHandComplete(ChannelHandlerContext ctx) { ChannelPipeline p=ctx.pipeline(); p.addLast(new WebSocketTextFrameStringAdapter());//消息解码器 p.addLast(new DefaultIdleListenerHandler<String>(new Listener()));//心跳适配器 //为新加的handler手动触发必要事件 ctx.fireChannelRegistered(); ctx.fireChannelActive(); } }); ns.start(); new Scanner(System.in).nextLine(); }
Example #3
Source File: Client.java From startup-os with Apache License 2.0 | 6 votes |
public static void main(String[] args) throws Exception { Flags.parseCurrentPackage(args); SslContext sslContext = GrpcSslContexts.forClient().trustManager(new File(certificateFile.get())).build(); ManagedChannel channel = NettyChannelBuilder.forAddress("localhost", GRPC_PORT).sslContext(sslContext).build(); GrpcAuthTestGrpc.GrpcAuthTestBlockingStub stub = GrpcAuthTestGrpc.newBlockingStub(channel) .withInterceptors(new ClientAuthInterceptor(token.get())); logger.at(Level.INFO).log("Calling server to increment %d", n.get()); Protos.Response resp = stub.getNextNumber(Protos.Request.newBuilder().setNumber(n.get()).build()); logger.at(Level.INFO).log("Got %d in response", resp.getNumber()); }
Example #4
Source File: ServerSSLContextManager.java From cute-proxy with BSD 2-Clause "Simplified" License | 6 votes |
private SslContext getNettySslContextInner(String host, boolean useH2) throws Exception { long start = System.currentTimeMillis(); PrivateKeyAndCertChain keyAndCertChain = keyStoreGenerator.generateCertChain(host, Settings.certValidityDays); logger.debug("Create certificate for {}, cost {} ms", host, System.currentTimeMillis() - start); SslContextBuilder builder = SslContextBuilder .forServer(keyAndCertChain.privateKey(), keyAndCertChain.certificateChain()); if (useH2) { // .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) builder.applicationProtocolConfig(new ApplicationProtocolConfig( ApplicationProtocolConfig.Protocol.ALPN, SelectorFailureBehavior.NO_ADVERTISE, SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1)); } return builder.build(); }
Example #5
Source File: WaltzTestBase.java From waltz with Apache License 2.0 | 6 votes |
protected WaltzServerRunner getWaltzServerRunner(int port, final SslContext serverSslCtx, final ClusterManager clusterManager, final Store store) { return new WaltzServerRunner(port, serverSslCtx, config, true) { @Override protected ZooKeeperClient getZkClient() { return null; } @Override protected Store getStore() { return store; } @Override protected ClusterManager getClusterManager() { return clusterManager; } }; }
Example #6
Source File: TLSConfigChangeFileConsumerTests.java From pravega with Apache License 2.0 | 6 votes |
@Test public void testInvocationIncrementsReloadCounter() { String pathToCertificateFile = "../../../config/" + SecurityConfigDefaults.TLS_SERVER_CERT_FILE_NAME; String pathToKeyFile = "../../../config/" + SecurityConfigDefaults.TLS_SERVER_PRIVATE_KEY_FILE_NAME; AtomicReference<SslContext> sslCtx = new AtomicReference<>(TLSHelper.newServerSslContext( new File(pathToCertificateFile), new File(pathToKeyFile))); TLSConfigChangeFileConsumer subjectUnderTest = new TLSConfigChangeFileConsumer(sslCtx, pathToCertificateFile, pathToKeyFile); subjectUnderTest.accept(null); assertEquals(1, subjectUnderTest.getNumOfConfigChangesSinceStart()); subjectUnderTest.accept(null); assertEquals(2, subjectUnderTest.getNumOfConfigChangesSinceStart()); }
Example #7
Source File: TLSConfigChangeEventConsumerTests.java From pravega with Apache License 2.0 | 6 votes |
@Test public void testInvocationIncrementsReloadCounter() { String pathToCertificateFile = "../../../config/" + SecurityConfigDefaults.TLS_SERVER_CERT_FILE_NAME; String pathToKeyFile = "../../../config/" + SecurityConfigDefaults.TLS_SERVER_PRIVATE_KEY_FILE_NAME; AtomicReference<SslContext> sslCtx = new AtomicReference<>(TLSHelper.newServerSslContext( new File(pathToCertificateFile), new File(pathToKeyFile))); TLSConfigChangeEventConsumer subjectUnderTest = new TLSConfigChangeEventConsumer(sslCtx, pathToCertificateFile, pathToKeyFile); subjectUnderTest.accept(null); assertEquals(1, subjectUnderTest.getNumOfConfigChangesSinceStart()); subjectUnderTest.accept(mock(WatchEvent.class)); assertEquals(2, subjectUnderTest.getNumOfConfigChangesSinceStart()); }
Example #8
Source File: HttpCorsServer.java From HttpProxy with MIT License | 6 votes |
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) { SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); } else { sslCtx = null; } EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new HttpCorsServerInitializer(sslCtx)); b.bind(PORT).sync().channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
Example #9
Source File: Channelizer.java From tinkerpop with Apache License 2.0 | 6 votes |
@Override protected void initChannel(final SocketChannel socketChannel) throws Exception { final ChannelPipeline pipeline = socketChannel.pipeline(); final Optional<SslContext> sslCtx; if (supportsSsl()) { try { sslCtx = Optional.of(cluster.createSSLContext()); } catch (Exception ex) { throw new RuntimeException(ex); } } else { sslCtx = Optional.empty(); } if (sslCtx.isPresent()) { pipeline.addLast(sslCtx.get().newHandler(socketChannel.alloc(), connection.getUri().getHost(), connection.getUri().getPort())); } configure(pipeline); pipeline.addLast(PIPELINE_GREMLIN_SASL_HANDLER, new Handler.GremlinSaslAuthenticationHandler(cluster.authProperties())); pipeline.addLast(PIPELINE_GREMLIN_HANDLER, new Handler.GremlinResponseHandler(pending)); }
Example #10
Source File: WaltzNetworkClient.java From waltz with Apache License 2.0 | 6 votes |
/** * Class Constructor. * * @param clientId Unique id assigned to an instance of {@link com.wepay.waltz.client.WaltzClient} on creation. * @param endpoint {@link Endpoint} Endpoint of the physical server this instance will be responsible for. * @param sslCtx {@link SslContext} SSL context required for communication * @param seqNum Sequence number of the {@link WaltzNetworkClient} responsible for the server. * @param networkClientCallbacks {@link WaltzNetworkClientCallbacks} * @param messageProcessingThreadPool {@link MessageProcessingThreadPool} */ public WaltzNetworkClient( int clientId, Endpoint endpoint, SslContext sslCtx, long seqNum, WaltzNetworkClientCallbacks networkClientCallbacks, MessageProcessingThreadPool messageProcessingThreadPool ) { super(endpoint.host, endpoint.port, sslCtx); this.clientId = clientId; this.endpoint = endpoint; this.seqNum = seqNum; this.networkClientCallbacks = networkClientCallbacks; this.messageProcessingThreadPool = messageProcessingThreadPool; this.partitions = new HashMap<>(); this.outputFuturesPerMessageType = new ConcurrentHashMap<>(); }
Example #11
Source File: NettyBootstrap.java From WeCross with Apache License 2.0 | 6 votes |
/** * init SslContext for p2p connection * * @param caCrt * @param nodeCrt * @param nodeKey * @return * @throws IOException */ public SslContext initSslContextForServer( org.springframework.core.io.Resource caCrt, org.springframework.core.io.Resource nodeCrt, org.springframework.core.io.Resource nodeKey) throws IOException { SslContext sslCtx = SslContextBuilder.forServer(nodeCrt.getInputStream(), nodeKey.getInputStream()) .trustManager(caCrt.getInputStream()) .sslProvider(SslProvider.JDK) .clientAuth(ClientAuth.REQUIRE) .build(); return sslCtx; }
Example #12
Source File: ComputeEngineChannelBuilder.java From grpc-java with Apache License 2.0 | 6 votes |
private ComputeEngineChannelBuilder(String target) { delegate = NettyChannelBuilder.forTarget(target); SslContext sslContext; try { sslContext = GrpcSslContexts.forClient().build(); } catch (SSLException e) { throw new RuntimeException(e); } InternalNettyChannelBuilder.setProtocolNegotiatorFactory( delegate(), new GoogleDefaultProtocolNegotiatorFactory( /* targetServiceAccounts= */ ImmutableList.<String>of(), SharedResourcePool.forResource(HandshakerServiceChannel.SHARED_HANDSHAKER_CHANNEL), sslContext)); CallCredentials credentials = MoreCallCredentials.from(ComputeEngineCredentials.create()); Status status = Status.OK; if (!CheckGcpEnvironment.isOnGcp()) { status = Status.INTERNAL.withDescription( "Compute Engine Credentials can only be used on Google Cloud Platform"); } delegate().intercept(new CallCredentialsInterceptor(credentials, status)); }
Example #13
Source File: OcAgentMetricsExporter.java From opencensus-java with Apache License 2.0 | 6 votes |
private static void createInternal( String endPoint, boolean useInsecure, @Nullable SslContext sslContext, String serviceName, Duration exportInterval, Duration retryInterval) { checkArgument( useInsecure == (sslContext == null), "Either use insecure or provide a valid SslContext."); synchronized (monitor) { checkState(exporter == null, "OcAgent Metrics exporter is already created."); exporter = new OcAgentMetricsExporter( endPoint, useInsecure, sslContext, serviceName, exportInterval, retryInterval, Metrics.getExportComponent().getMetricProducerManager()); exporter.workerThread.start(); } }
Example #14
Source File: SocketSslGreetingTest.java From netty4.0.27Learn with Apache License 2.0 | 6 votes |
@Parameters(name = "{index}: serverEngine = {0}, clientEngine = {1}") public static Collection<Object[]> data() throws Exception { List<SslContext> serverContexts = new ArrayList<SslContext>(); serverContexts.add(new JdkSslServerContext(CERT_FILE, KEY_FILE)); List<SslContext> clientContexts = new ArrayList<SslContext>(); clientContexts.add(new JdkSslClientContext(CERT_FILE)); boolean hasOpenSsl = OpenSsl.isAvailable(); if (hasOpenSsl) { serverContexts.add(new OpenSslServerContext(CERT_FILE, KEY_FILE)); clientContexts.add(new OpenSslClientContext(CERT_FILE)); } else { logger.warn("OpenSSL is unavailable and thus will not be tested.", OpenSsl.unavailabilityCause()); } List<Object[]> params = new ArrayList<Object[]>(); for (SslContext sc: serverContexts) { for (SslContext cc: clientContexts) { params.add(new Object[] { sc, cc }); } } return params; }
Example #15
Source File: OcspTest.java From netty-4.1.22 with Apache License 2.0 | 6 votes |
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 #16
Source File: TcpClientChannelInitializer.java From servicetalk with Apache License 2.0 | 6 votes |
/** * Creates a {@link ChannelInitializer} for the {@code config}. * * @param config to use for initialization. * @param deferSslHandler {@code true} to wrap the {@link SslHandler} in a {@link DeferSslHandler}. */ public TcpClientChannelInitializer(final ReadOnlyTcpClientConfig config, final boolean deferSslHandler) { ChannelInitializer delegate = ChannelInitializer.defaultInitializer(); if (config.idleTimeoutMs() != null) { delegate = delegate.andThen(new IdleTimeoutInitializer(config.idleTimeoutMs())); } final SslContext sslContext = config.sslContext(); if (sslContext != null) { delegate = delegate.andThen(new SslClientChannelInitializer(sslContext, config.sslHostnameVerificationAlgorithm(), config.sslHostnameVerificationHost(), config.sslHostnameVerificationPort(), deferSslHandler)); } final WireLoggingInitializer wireLoggingInitializer = config.wireLoggingInitializer(); if (wireLoggingInitializer != null) { delegate = delegate.andThen(wireLoggingInitializer); } this.delegate = delegate; }
Example #17
Source File: TransportSupportTest.java From qpid-jms with Apache License 2.0 | 6 votes |
@Test public void testLegacySslProtocolsDisabledByDefaultOpenSSL() throws Exception { assumeTrue(OpenSsl.isAvailable()); assumeTrue(OpenSsl.supportsKeyManagerFactory()); TransportOptions options = createJksSslOptions(null); SslContext context = TransportSupport.createOpenSslContext(options); assertNotNull(context); SSLEngine engine = TransportSupport.createOpenSslEngine(PooledByteBufAllocator.DEFAULT, null, context, options); assertNotNull(engine); List<String> engineProtocols = Arrays.asList(engine.getEnabledProtocols()); assertFalse("SSLv3 should not be enabled by default", engineProtocols.contains("SSLv3")); // TODO - Netty is currently unable to disable OpenSSL SSLv2Hello so we are stuck with it for now. // assertFalse("SSLv2Hello should not be enabled by default", engineProtocols.contains("SSLv2Hello")); }
Example #18
Source File: SslUtilTest.java From hivemq-community-edition with Apache License 2.0 | 5 votes |
@Test public void test_java_ssl_tls_1_context_created() throws Exception { final KeyManagerFactory kmf = createKeyManagerFactory(); final SslContext sslServerContext = sslUtil.createSslServerContext(kmf, null, null, Lists.newArrayList("TLSv1")); assertTrue(sslServerContext instanceof JdkSslContext); final List<String> protocols = getProtocolsFromContext(sslServerContext); assertEquals(1, protocols.size()); assertEquals("TLSv1", protocols.get(0)); }
Example #19
Source File: TcpSecureMetricsTests.java From reactor-netty with Apache License 2.0 | 5 votes |
@Override protected TcpServer customizeServerOptions(TcpServer tcpServer) { try { SslContext ctx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()) .sslProvider(SslProvider.JDK) .build(); return tcpServer.secure(ssl -> ssl.sslContext(ctx)).wiretap(true); } catch (SSLException e) { throw new RuntimeException(e); } }
Example #20
Source File: SocketSslEchoTest.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
public SocketSslEchoTest( SslContext serverCtx, SslContext clientCtx, Renegotiation renegotiation, boolean serverUsesDelegatedTaskExecutor, boolean clientUsesDelegatedTaskExecutor, boolean autoRead, boolean useChunkedWriteHandler, boolean useCompositeByteBuf) { this.serverCtx = serverCtx; this.clientCtx = clientCtx; this.serverUsesDelegatedTaskExecutor = serverUsesDelegatedTaskExecutor; this.clientUsesDelegatedTaskExecutor = clientUsesDelegatedTaskExecutor; this.renegotiation = renegotiation; this.autoRead = autoRead; this.useChunkedWriteHandler = useChunkedWriteHandler; this.useCompositeByteBuf = useCompositeByteBuf; }
Example #21
Source File: HttpsSendFileTests.java From reactor-netty with Apache License 2.0 | 5 votes |
@Override protected HttpServer customizeServerOptions(HttpServer server) { try { SslContext ctx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); return server.secure(ssl -> ssl.sslContext(ctx)); } catch (SSLException e) { throw new RuntimeException(e); } }
Example #22
Source File: HttpTestServer.java From arcusplatform with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) { SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).sslProvider(SslProvider.JDK).build(); } else { sslCtx = null; } EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new HttpTestServerInitializer(sslCtx)); Channel ch = b.bind(PORT).sync().channel(); System.err.println("Open your web browser and navigate to " + (SSL? "https" : "http") + "://127.0.0.1:" + PORT + '/'); ch.closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
Example #23
Source File: Http2Server.java From netty-4.1.22 with Apache License 2.0 | 5 votes |
private static SslContext configureTLS() throws CertificateException, SSLException { SelfSignedCertificate ssc = new SelfSignedCertificate(); ApplicationProtocolConfig apn = new ApplicationProtocolConfig( Protocol.ALPN, // NO_ADVERTISE is currently the only mode supported by both OpenSsl and JDK providers. SelectorFailureBehavior.NO_ADVERTISE, // ACCEPT is currently the only mode supported by both OpenSsl and JDK providers. SelectedListenerFailureBehavior.ACCEPT, ApplicationProtocolNames.HTTP_2, ApplicationProtocolNames.HTTP_1_1); return SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey(), null) .ciphers(CIPHERS, SupportedCipherSuiteFilter.INSTANCE) .applicationProtocolConfig(apn).build(); }
Example #24
Source File: ConnectionConfig.java From waltz with Apache License 2.0 | 5 votes |
/** * Class constructor. * @param sslCtx SSLContext for communication. * @param key The cluster key. * @param numPartitions The total number of partitions in the cluster. * @param initialRetryInterval The initial retry interval. * @param maxRetryInterval The maximum retry interval. * @throws GeneralSecurityException thrown if failed to create {@link javax.net.ssl.SSLContext}. * @throws IOException thrown if any issue occurs. */ public ConnectionConfig( SslContext sslCtx, UUID key, int numPartitions, final long initialRetryInterval, final long maxRetryInterval ) throws GeneralSecurityException, IOException { this.sslCtx = sslCtx != null ? sslCtx : ClientSSL.createInsecureContext(); this.key = key; this.numPartitions = numPartitions; this.initialRetryInterval = initialRetryInterval; this.maxRetryInterval = maxRetryInterval; }
Example #25
Source File: ClientJSONPoint.java From Launcher with GNU General Public License v3.0 | 5 votes |
public ClientJSONPoint(URI uri) throws SSLException { this.uri = uri; String protocol = uri.getScheme(); if (!"ws".equals(protocol) && !"wss".equals(protocol)) { throw new IllegalArgumentException("Unsupported protocol: " + protocol); } if ("wss".equals(protocol)) { ssl = true; } if (uri.getPort() == -1) { if ("ws".equals(protocol)) port = 80; else port = 443; } else port = uri.getPort(); final SslContext sslCtx; if (ssl) { sslCtx = SslContextBuilder.forClient().build(); } else sslCtx = null; bootstrap.group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) { ChannelPipeline pipeline = ch.pipeline(); if (sslCtx != null) { pipeline.addLast(sslCtx.newHandler(ch.alloc(), uri.getHost(), port)); } pipeline.addLast("http-codec", new HttpClientCodec()); pipeline.addLast("aggregator", new HttpObjectAggregator(65536)); pipeline.addLast("ws-handler", webSocketClientHandler); } }); }
Example #26
Source File: GrafanaAuth.java From timely with Apache License 2.0 | 5 votes |
protected ChannelHandler setupHttpChannel(GrafanaAuthConfiguration config, SslContext sslCtx, HttpClientPool httpClientPool) { return new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast("ssl", new NonSslRedirectHandler(config.getHttp(), sslCtx)); ch.pipeline().addLast("encoder", new HttpResponseEncoder()); ch.pipeline().addLast("decoder", new HttpRequestDecoder()); ch.pipeline().addLast("compressor", new HttpContentCompressor()); ch.pipeline().addLast("decompressor", new HttpContentDecompressor()); // high maximum contentLength so that grafana snapshots can be delivered // might not be necessary if inbound chunking (while proxying) is handled ch.pipeline().addLast("aggregator", new HttpObjectAggregator(2097152)); ch.pipeline().addLast("chunker", new ChunkedWriteHandler()); ch.pipeline().addLast("grafanaDecoder", new GrafanaRequestDecoder(config.getSecurity(), config.getHttp())); ch.pipeline().addLast("fileServer", new HttpStaticFileServerHandler()); ch.pipeline().addLast("login", new X509LoginRequestHandler(config.getSecurity(), config.getHttp())); ch.pipeline().addLast("httpRelay", new GrafanaRelayHandler(config, httpClientPool)); ch.pipeline().addLast("error", new TimelyExceptionHandler() .setIgnoreSslHandshakeErrors(config.getSecurity().getServerSsl().isUseGeneratedKeypair())); } }; }
Example #27
Source File: DefaultPooledConnectionProviderTest.java From reactor-netty with Apache License 2.0 | 5 votes |
@Test public void testSslEngineClosed() throws Exception { DisposableServer server = HttpServer.create() .port(0) .wiretap(true) .handle((req, res) -> res.sendString(Mono.just("test"))) .bindNow(); SslContext ctx = SslContextBuilder.forClient() .sslProvider(SslProvider.JDK) .build(); HttpClient client = HttpClient.create() .port(server.port()) .secure(spec -> spec.sslContext(ctx)) .wiretap(true); // Connection close happens after `Channel connected` // Re-acquiring is not possible // The SSLException will be propagated doTestSslEngineClosed(client, new AtomicInteger(0), SSLException.class, "SSLEngine is closing/closed"); // Connection close happens between `Initialized pipeline` and `Channel connected` // Re-acquiring // Connection close happens after `Channel connected` // The SSLException will be propagated, Reactor Netty re-acquire only once doTestSslEngineClosed(client, new AtomicInteger(1), SSLException.class, "SSLEngine is closing/closed"); // Connection close happens between `Initialized pipeline` and `Channel connected` // Re-acquiring // Connection close happens between `Initialized pipeline` and `Channel connected` // The IOException will be propagated, Reactor Netty re-acquire only once doTestSslEngineClosed(client, new AtomicInteger(2), IOException.class, "Error while acquiring from"); server.disposeNow(); }
Example #28
Source File: HttpSnoopServer.java From netty4.0.27Learn with Apache License 2.0 | 5 votes |
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) { SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); } else { sslCtx = null; } // Configure the server. EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new HttpSnoopServerInitializer(sslCtx)); Channel ch = b.bind(PORT).sync().channel(); System.err.println("Open your web browser and navigate to " + (SSL? "https" : "http") + "://127.0.0.1:" + PORT + '/'); ch.closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
Example #29
Source File: Server.java From LittleProxy-mitm with Apache License 2.0 | 5 votes |
protected Server start(SslContext sslCtx) throws InterruptedException { bossGroup = new NioEventLoopGroup(); workerGroup = new NioEventLoopGroup(); ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup); b.channel(NioServerSocketChannel.class); b.childHandler(new HttpStaticFileServerInitializer(sslCtx)); b.bind(getPort()); return this; }
Example #30
Source File: ImpersonatingMitmManager.java From CapturePacket with MIT License | 5 votes |
/** * Creates an SSLContext that will present an impersonated certificate for the specified hostname to the client. * This is a convenience method for {@link #createImpersonatingSslContext(CertificateInfo)} that generates the * {@link CertificateInfo} from the specified hostname using the {@link #certificateInfoGenerator}. * * @param sslSession sslSession between the proxy and the upstream server * @param hostnameToImpersonate hostname (supplied by the client's HTTP CONNECT) that will be impersonated * @return an SSLContext presenting a certificate matching the hostnameToImpersonate */ private SslContext createImpersonatingSslContext(SSLSession sslSession, String hostnameToImpersonate) { // get the upstream server's certificate so the certificateInfoGenerator can (optionally) use it to construct a forged certificate X509Certificate originalCertificate = SslUtil.getServerCertificate(sslSession); // get the CertificateInfo that will be used to populate the impersonated X509Certificate CertificateInfo certificateInfo = certificateInfoGenerator.generate(Collections.singletonList(hostnameToImpersonate), originalCertificate); SslContext sslContext = createImpersonatingSslContext(certificateInfo); return sslContext; }