List of usage examples for io.netty.handler.ssl SslContextBuilder forServer
boolean forServer
To view the source code for io.netty.handler.ssl SslContextBuilder forServer.
Click Source Link
From source file:io.grpc.netty.GrpcSslContexts.java
License:Apache License
/** * Creates an SslContextBuilder with ciphers and APN appropriate for gRPC. * * @see SslContextBuilder#forServer(InputStream, InputStream) * @see #configure(SslContextBuilder)/*from w w w .jav a 2 s. c om*/ */ public static SslContextBuilder forServer(InputStream keyCertChain, InputStream key) { return configure(SslContextBuilder.forServer(keyCertChain, key)); }
From source file:io.grpc.netty.GrpcSslContexts.java
License:Apache License
/** * Creates an SslContextBuilder with ciphers and APN appropriate for gRPC. * * @see SslContextBuilder#forServer(InputStream, InputStream, String) * @see #configure(SslContextBuilder)// www . ja v a2s . c o m */ public static SslContextBuilder forServer(InputStream keyCertChain, InputStream key, String keyPassword) { return configure(SslContextBuilder.forServer(keyCertChain, key, keyPassword)); }
From source file:io.grpc.netty.ProtocolNegotiatorsTest.java
License:Apache License
@Test public void clientTlsHandler_firesNegotiation() throws Exception { SelfSignedCertificate cert = new SelfSignedCertificate("authority"); SslContext clientSslContext = GrpcSslContexts .configure(SslContextBuilder.forClient().trustManager(cert.cert())).build(); SslContext serverSslContext = GrpcSslContexts .configure(SslContextBuilder.forServer(cert.key(), cert.cert())).build(); FakeGrpcHttp2ConnectionHandler gh = FakeGrpcHttp2ConnectionHandler.newHandler(); ClientTlsProtocolNegotiator pn = new ClientTlsProtocolNegotiator(clientSslContext); WriteBufferingAndExceptionHandler clientWbaeh = new WriteBufferingAndExceptionHandler(pn.newHandler(gh)); SocketAddress addr = new LocalAddress("addr"); ChannelHandler sh = ProtocolNegotiators.serverTls(serverSslContext) .newHandler(FakeGrpcHttp2ConnectionHandler.noopHandler()); WriteBufferingAndExceptionHandler serverWbaeh = new WriteBufferingAndExceptionHandler(sh); Channel s = new ServerBootstrap().childHandler(serverWbaeh).group(group).channel(LocalServerChannel.class) .bind(addr).sync().channel(); Channel c = new Bootstrap().handler(clientWbaeh).channel(LocalChannel.class).group(group).register().sync() .channel();//w w w.j ava 2s .com ChannelFuture write = c.writeAndFlush(NettyClientHandler.NOOP_MESSAGE); c.connect(addr).sync(); write.sync(); boolean completed = gh.negotiated.await(TIMEOUT_SECONDS, TimeUnit.SECONDS); if (!completed) { assertTrue("failed to negotiated", write.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)); // sync should fail if we are in this block. write.sync(); throw new AssertionError("neither wrote nor negotiated"); } c.close(); s.close(); assertThat(gh.securityInfo).isNotNull(); assertThat(gh.securityInfo.tls).isNotNull(); assertThat(gh.attrs.get(GrpcAttributes.ATTR_SECURITY_LEVEL)).isEqualTo(SecurityLevel.PRIVACY_AND_INTEGRITY); assertThat(gh.attrs.get(Grpc.TRANSPORT_ATTR_SSL_SESSION)).isInstanceOf(SSLSession.class); // This is not part of the ClientTls negotiation, but shows that the negotiation event happens // in the right order. assertThat(gh.attrs.get(Grpc.TRANSPORT_ATTR_REMOTE_ADDR)).isEqualTo(addr); }
From source file:io.grpc.netty.TlsTest.java
License:Apache License
private ServerBuilder<?> serverBuilder(int port, File serverCertChainFile, File serverPrivateKeyFile, X509Certificate[] serverTrustedCaCerts) throws IOException { SslContextBuilder sslContextBuilder = SslContextBuilder.forServer(serverCertChainFile, serverPrivateKeyFile);//ww w. j a v a2 s. c om if (sslProvider == SslProvider.JDK) { GrpcSslContexts.configure(sslContextBuilder, jdkProvider); } else { GrpcSslContexts.configure(sslContextBuilder, sslProvider); } sslContextBuilder.trustManager(serverTrustedCaCerts).clientAuth(ClientAuth.REQUIRE); return NettyServerBuilder.forPort(port).sslContext(sslContextBuilder.build()); }
From source file:io.hekate.network.internal.NettySslUtils.java
License:Apache License
/** * Builds a new server SSL context.//from w ww .java2 s. c om * * @param cfg SSL configuration. * @param res Resource service for loading {@link KeyStore}. * * @return SSL context. */ public static SslContext serverContext(NetworkSslConfig cfg, ResourceService res) { ConfigCheck check = checkConfig(cfg); try { return SslContextBuilder.forServer(keyManager(cfg, res)).sslProvider(provider(cfg)) .trustManager(trustManager(cfg, res)).sessionCacheSize(cfg.getSslSessionCacheSize()) .sessionTimeout(cfg.getSslSessionCacheTimeout()).build(); } catch (ResourceLoadingException | GeneralSecurityException | IOException e) { throw check.fail(e); } }
From source file:io.netty.example.echo.EchoServer.java
License:Apache License
public static void main(String[] args) throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) {/* w w w .j a va 2 s. c o m*/ SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); } else { sslCtx = null; } // Configure the server. EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); final EchoServerHandler serverHandler = new EchoServerHandler(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); if (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc())); } //p.addLast(new LoggingHandler(LogLevel.INFO)); p.addLast(serverHandler); } }); // Start the server. ChannelFuture f = b.bind(PORT).sync(); // Wait until the server socket is closed. f.channel().closeFuture().sync(); } finally { // Shut down all event loops to terminate all threads. bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:io.netty.example.ocsp.OcspServerExample.java
License:Apache License
public static void main(String[] args) throws Exception { // We assume there's a private key. PrivateKey privateKey = null; // Step 1: Load the certificate chain for netty.io. We'll need the certificate // and the issuer's certificate and we don't need any of the intermediate certs. // The array is assumed to be a certain order to keep things simple. X509Certificate[] keyCertChain = parseCertificates(OcspServerExample.class, "netty_io_chain.pem"); X509Certificate certificate = keyCertChain[0]; X509Certificate issuer = keyCertChain[keyCertChain.length - 1]; // Step 2: We need the URL of the CA's OCSP responder server. It's somewhere encoded // into the certificate! Notice that it's an HTTP URL. URI uri = OcspUtils.ocspUri(certificate); System.out.println("OCSP Responder URI: " + uri); if (uri == null) { throw new IllegalStateException("The CA/certificate doesn't have an OCSP responder"); }/*from www.ja v a2 s . co m*/ // Step 3: Construct the OCSP request OCSPReq request = new OcspRequestBuilder().certificate(certificate).issuer(issuer).build(); // Step 4: Do the request to the CA's OCSP responder OCSPResp response = OcspUtils.request(uri, request, 5L, TimeUnit.SECONDS); if (response.getStatus() != OCSPResponseStatus.SUCCESSFUL) { throw new IllegalStateException("response-status=" + response.getStatus()); } // Step 5: Is my certificate any good or has the CA revoked it? BasicOCSPResp basicResponse = (BasicOCSPResp) response.getResponseObject(); SingleResp first = basicResponse.getResponses()[0]; CertificateStatus status = first.getCertStatus(); System.out.println("Status: " + (status == CertificateStatus.GOOD ? "Good" : status)); System.out.println("This Update: " + first.getThisUpdate()); System.out.println("Next Update: " + first.getNextUpdate()); if (status != null) { throw new IllegalStateException("certificate-status=" + status); } BigInteger certSerial = certificate.getSerialNumber(); BigInteger ocspSerial = first.getCertID().getSerialNumber(); if (!certSerial.equals(ocspSerial)) { throw new IllegalStateException("Bad Serials=" + certSerial + " vs. " + ocspSerial); } // Step 6: Cache the OCSP response and use it as long as it's not // expired. The exact semantics are beyond the scope of this example. if (!OpenSsl.isAvailable()) { throw new IllegalStateException("OpenSSL is not available!"); } if (!OpenSsl.isOcspSupported()) { throw new IllegalStateException("OCSP is not supported!"); } if (privateKey == null) { throw new IllegalStateException( "Because we don't have a PrivateKey we can't continue past this point."); } ReferenceCountedOpenSslContext context = (ReferenceCountedOpenSslContext) SslContextBuilder .forServer(privateKey, keyCertChain).sslProvider(SslProvider.OPENSSL).enableOcsp(true).build(); try { ServerBootstrap bootstrap = new ServerBootstrap().childHandler(newServerHandler(context, response)); // so on and so forth... } finally { context.release(); } }
From source file:io.opendevice.sonoff.SonOffServerConnection.java
License:Open Source License
private SslContext generateSSLContext() { // File certFile = config.getFile("sonoff.ssl.certificateFile"); // if(cert == null) throw new IllegalArgumentException("Certificate not found (check sonoff.ssl.certificateFile) !"); // File key = config.getFile("sonoff.ssl.certificateKey"); // if(key == null) throw new IllegalArgumentException("Certificate key must be provided (check sonoff.ssl.certificateKey) !"); OpenDeviceConfig config = ODev.getConfig(); InputStream cert = null;//from w w w. j ava2s .c o m InputStream key = null; try { File certFile = config.getFile("sonoff.ssl.certificateFile"); if (certFile != null) { cert = new FileInputStream(certFile); } else { log.info("Using self-signed embedded certificate ..."); cert = getClass().getClassLoader().getResourceAsStream("ssl/cert.pem"); } File keyFile = config.getFile("sonoff.ssl.certificateKey"); if (keyFile != null) { key = new FileInputStream(keyFile); } else { key = getClass().getClassLoader().getResourceAsStream("ssl/key.pem"); } } catch (FileNotFoundException e) { e.printStackTrace(); } try { SslContextBuilder sslContextBuilder = SslContextBuilder.forServer(cert, key); sslContextBuilder.sslProvider(SslProvider.JDK); SslContext sslContext = sslContextBuilder.build(); return sslContext; } catch (SSLException e) { e.printStackTrace(); } return null; }
From source file:io.pravega.segmentstore.server.host.handler.PravegaConnectionListener.java
License:Open Source License
public void startListening() { // Configure SSL. final SslContext sslCtx; if (ssl) {/*from ww w . j a v a 2 s .c o m*/ try { SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); } catch (CertificateException | SSLException e) { throw new RuntimeException(e); } } else { sslCtx = null; } boolean nio = false; try { bossGroup = new EpollEventLoopGroup(1); workerGroup = new EpollEventLoopGroup(); } catch (ExceptionInInitializerError | NoClassDefFoundError e) { nio = true; bossGroup = new NioEventLoopGroup(1); workerGroup = new NioEventLoopGroup(); } ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup).channel(nio ? NioServerSocketChannel.class : EpollServerSocketChannel.class) .option(ChannelOption.SO_BACKLOG, 100).handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); if (sslCtx != null) { p.addLast(sslCtx.newHandler(ch.alloc())); } ServerConnectionInboundHandler lsh = new ServerConnectionInboundHandler(); // p.addLast(new LoggingHandler(LogLevel.INFO)); p.addLast(new ExceptionLoggingHandler(ch.remoteAddress().toString()), new CommandEncoder(null), new LengthFieldBasedFrameDecoder(MAX_WIRECOMMAND_SIZE, 4, 4), new CommandDecoder(), new AppendDecoder(), lsh); lsh.setRequestProcessor(new AppendProcessor(store, lsh, new PravegaRequestProcessor(store, lsh, statsRecorder), statsRecorder)); } }); // Start the server. serverChannel = b.bind(host, port).awaitUninterruptibly().channel(); }
From source file:io.vertx.core.net.impl.SSLHelper.java
License:Open Source License
private SslContext createContext(VertxInternal vertx) { try {/*from ww w.j av a2 s.c o m*/ KeyManagerFactory keyMgrFactory = getKeyMgrFactory(vertx); TrustManagerFactory trustMgrFactory = getTrustMgrFactory(vertx); SslContextBuilder builder; if (client) { builder = SslContextBuilder.forClient(); if (keyMgrFactory != null) { builder.keyManager(keyMgrFactory); } } else { if (keyMgrFactory == null) { throw new VertxException("Key/certificate is mandatory for SSL"); } builder = SslContextBuilder.forServer(keyMgrFactory); } Collection<String> cipherSuites = enabledCipherSuites; if (openSsl) { builder.sslProvider(SslProvider.OPENSSL); if (cipherSuites == null || cipherSuites.isEmpty()) { cipherSuites = OpenSsl.availableOpenSslCipherSuites(); } } else { builder.sslProvider(SslProvider.JDK); if (cipherSuites == null || cipherSuites.isEmpty()) { cipherSuites = DEFAULT_JDK_CIPHER_SUITE; } } if (trustMgrFactory != null) { builder.trustManager(trustMgrFactory); } if (cipherSuites != null && cipherSuites.size() > 0) { builder.ciphers(cipherSuites); } if (useAlpn && applicationProtocols != null && applicationProtocols.size() > 0) { builder.applicationProtocolConfig(new ApplicationProtocolConfig( ApplicationProtocolConfig.Protocol.ALPN, ApplicationProtocolConfig.SelectorFailureBehavior.NO_ADVERTISE, ApplicationProtocolConfig.SelectedListenerFailureBehavior.ACCEPT, applicationProtocols .stream().map(PROTOCOL_NAME_MAPPING::get).collect(Collectors.toList()))); } return builder.build(); } catch (Exception e) { throw new VertxException(e); } }