下面列出了io.netty.channel.ChannelInitializer#io.netty.handler.ssl.SslContext 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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());
}
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();
}
}
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();
}
}
@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;
}
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);
}
}
/**
* 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;
}
@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());
}
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();
}
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();
}
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;
}
};
}
@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);
}
@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));
}
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));
}
@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"));
}
/**
* 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;
}
/**
* 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<>();
}
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());
}
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;
}
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 WebSocketServerInitializer(sslCtx));
Channel ch = b.bind(PORT).sync().channel();
System.out.println("Open your web browser and navigate to " +
(SSL? "https" : "http") + "://127.0.0.1:" + PORT + '/');
ch.closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public SslContext SslContext() throws SSLException {
if( CommonConfig.getBoolean( "jees.jsts.websocket.ssl.enable", false ) ) {
File file = new File( CommonConfig.getString( "jees.jsts.websocket.ssl.file" ) );
File key = new File( CommonConfig.getString( "jees.jsts.websocket.ssl.keyfile" ) );
return SslContextBuilder.forServer(file, key).build();
}
return null;
}
public static void createAndAttachSSLClient(ServiceHost h) throws Throwable {
// we create a random userAgent string to validate host to host communication when
// the client appears to be from an external, non-Xenon source.
ServiceClient client = NettyHttpServiceClient.create(UUID.randomUUID().toString(),
null,
h.getScheduledExecutor(), h);
if (NettyChannelContext.isALPNEnabled()) {
SslContext http2ClientContext = SslContextBuilder.forClient()
.trustManager(InsecureTrustManagerFactory.INSTANCE)
.ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
.applicationProtocolConfig(new ApplicationProtocolConfig(
ApplicationProtocolConfig.Protocol.ALPN,
ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE,
ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT,
ApplicationProtocolNames.HTTP_2))
.build();
((NettyHttpServiceClient) client).setHttp2SslContext(http2ClientContext);
}
SSLContext clientContext = SSLContext.getInstance(ServiceClient.TLS_PROTOCOL_NAME);
clientContext.init(null, InsecureTrustManagerFactory.INSTANCE.getTrustManagers(), null);
client.setSSLContext(clientContext);
h.setClient(client);
SelfSignedCertificate ssc = new SelfSignedCertificate();
h.setCertificateFileReference(ssc.certificate().toURI());
h.setPrivateKeyFileReference(ssc.privateKey().toURI());
}
private Channel connect(boolean management) {
Logger logger = LoggerFactory.getLogger(ModelServerTest.class);
final Connector connector = configManager.getListener(management);
try {
Bootstrap b = new Bootstrap();
final SslContext sslCtx =
SslContextBuilder.forClient()
.trustManager(InsecureTrustManagerFactory.INSTANCE)
.build();
b.group(Connector.newEventLoopGroup(1))
.channel(connector.getClientChannel())
.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000)
.handler(
new ChannelInitializer<Channel>() {
@Override
public void initChannel(Channel ch) {
ChannelPipeline p = ch.pipeline();
if (connector.isSsl()) {
p.addLast(sslCtx.newHandler(ch.alloc()));
}
p.addLast(new ReadTimeoutHandler(30));
p.addLast(new HttpClientCodec());
p.addLast(new HttpContentDecompressor());
p.addLast(new ChunkedWriteHandler());
p.addLast(new HttpObjectAggregator(6553600));
p.addLast(new TestHandler());
}
});
return b.connect(connector.getSocketAddress()).sync().channel();
} catch (Throwable t) {
logger.warn("Connect error.", t);
}
return null;
}
/**
* Create a server TLS handler for HTTP/2 capable of using ALPN/NPN.
*/
public static ProtocolNegotiator serverTls(final SslContext sslContext) {
Preconditions.checkNotNull(sslContext, "sslContext");
return new ProtocolNegotiator() {
@Override
public Handler newHandler(GrpcHttp2ConnectionHandler handler) {
return new ServerTlsHandler(sslContext, handler);
}
@Override
public void close() {}
};
}
public static SslContext ctxForServer(NitmProxyConfig config, String serverHost) throws SSLException {
Certificate certificate = CertUtil.newCert(config.getCertFile(), config.getKeyFile(), serverHost);
return SslContextBuilder
.forServer(certificate.getKeyPair().getPrivate(), certificate.getChain())
.ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE)
.applicationProtocolConfig(applicationProtocolConfig(config, config.isClientHttp2()))
.build();
}
private SslContext getSslContext(ImapClientConfiguration clientConfiguration) {
if (!clientConfiguration.trustManagerFactory().isPresent()) {
return sslContext;
}
try {
return SslContextBuilder.forClient()
.trustManager(clientConfiguration.trustManagerFactory().get())
.build();
} catch (SSLException e) {
throw new RuntimeException(e);
}
}
@Test
public void failIfSslContextIsNotClient() {
SslContext sslContext = mock(SslContext.class);
NettyChannelBuilder builder = new NettyChannelBuilder(new SocketAddress(){});
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Server SSL context can not be used for client channel");
builder.sslContext(sslContext);
}
public NonSslRedirectHandler(Configuration conf, SslContext sslContext) {
super(sslContext);
String timelyHost = conf.getHttp().getHost();
int timelyPort = conf.getHttp().getPort();
String path = conf.getHttp().getRedirectPath();
redirectAddress = "https://" + timelyHost + ":" + timelyPort + path;
}
@Before
public void setup() throws Exception {
s = new Server(conf);
s.run();
Connector con = mac.getConnector("root", "secret");
con.securityOperations().changeUserAuthorizations("root", new Authorizations("A", "B", "C", "D", "E", "F"));
this.sessionId = UUID.randomUUID().toString();
AuthCache.getCache().put(sessionId, token);
group = new NioEventLoopGroup();
SslContext ssl = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
String cookieVal = ClientCookieEncoder.STRICT.encode(Constants.COOKIE_NAME, sessionId);
HttpHeaders headers = new DefaultHttpHeaders();
headers.add(HttpHeaderNames.COOKIE, cookieVal);
WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(LOCATION,
WebSocketVersion.V13, (String) null, false, headers);
handler = new ClientHandler(handshaker);
Bootstrap boot = new Bootstrap();
boot.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast("ssl", ssl.newHandler(ch.alloc(), "127.0.0.1", WS_PORT));
ch.pipeline().addLast(new HttpClientCodec());
ch.pipeline().addLast(new HttpObjectAggregator(8192));
ch.pipeline().addLast(handler);
}
});
ch = boot.connect("127.0.0.1", WS_PORT).sync().channel();
// Wait until handshake is complete
while (!handshaker.isHandshakeComplete()) {
sleepUninterruptibly(500, TimeUnit.MILLISECONDS);
LOG.debug("Waiting for Handshake to complete");
}
}
SeleniumHttpInitializer(
SslContext sslCtx,
HttpHandler seleniumHandler,
BiFunction<String, Consumer<Message>, Optional<Consumer<Message>>> webSocketHandler) {
this.sslCtx = sslCtx;
this.seleniumHandler = Require.nonNull("HTTP handler", seleniumHandler);
this.webSocketHandler = Require.nonNull("WebSocket handler", webSocketHandler);
}
@Test
public void failIfSslContextIsNotServer() {
SslContext sslContext = mock(SslContext.class);
when(sslContext.isClient()).thenReturn(true);
thrown.expect(IllegalArgumentException.class);
thrown.expectMessage("Client SSL context can not be used for server");
builder.sslContext(sslContext);
}