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:org.caffinitas.prometheusmetrics.PrometheusMetricsExporter.java
License:Apache License
private void setupNetty() throws CertificateException, SSLException { final SslContext sslCtx; if (config.ssl) { SelfSignedCertificate ssc = new SelfSignedCertificate(); LOGGER.info("Setting up SSL context for certificate subject DN {} valid until {}", ssc.cert().getSubjectDN(), ssc.cert().getNotAfter()); sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); } else {/* w ww . j a v a 2 s. c o m*/ sslCtx = null; } EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); this.nettyChannel = new ServerBootstrap().option(ChannelOption.SO_BACKLOG, 1024) .group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ServerInitializer(sslCtx)).bind(config.bindAddress, config.httpPort) .syncUninterruptibly().channel(); nettyChannel.closeFuture().addListener(f -> { LOGGER.info("Shutting down listener"); bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); }); }
From source file:org.conscrypt.OpenJdkEngineFactoryConfig.java
License:Apache License
private static SslContext newNettyServerContext(io.netty.handler.ssl.SslProvider sslProvider, boolean useAlpn) { try {/*from w ww.ja v a 2s. c om*/ PrivateKeyEntry server = TestKeyStore.getServer().getPrivateKey("RSA", "RSA"); SslContextBuilder ctx = SslContextBuilder .forServer(server.getPrivateKey(), (X509Certificate[]) server.getCertificateChain()) .sslProvider(sslProvider); if (useAlpn) { ctx.applicationProtocolConfig(OpenJdkEngineFactoryConfig.NETTY_ALPN_CONFIG); } return ctx.build(); } catch (SSLException e) { throw new RuntimeException(e); } }
From source file:org.conscrypt.testing.TestUtil.java
License:Apache License
public static SslContext newNettyServerContext(String cipher) { try {//from w w w .ja v a 2 s. c om PrivateKeyEntry server = TestKeyStore.getServer().getPrivateKey("RSA", "RSA"); SslContextBuilder ctx = SslContextBuilder .forServer(server.getPrivateKey(), (X509Certificate[]) server.getCertificateChain()) .sslProvider(io.netty.handler.ssl.SslProvider.OPENSSL); if (cipher != null) { ctx.ciphers(Collections.singletonList(cipher)); } return ctx.build(); } catch (SSLException e) { throw new RuntimeException(e); } }
From source file:org.curioswitch.common.server.framework.ServerModule.java
License:Open Source License
private static SslContextBuilder serverSslContext(InputStream keyCertChainFile, InputStream keyFile) { SslContextBuilder builder = SslContextKeyConverter.execute(keyCertChainFile, keyFile, (cert, key) -> SslContextBuilder.forServer(cert, key, null)); return builder.sslProvider(Flags.useOpenSsl() ? SslProvider.OPENSSL : SslProvider.JDK) .ciphers(Http2SecurityUtil.CIPHERS, SupportedCipherSuiteFilter.INSTANCE) .applicationProtocolConfig(HTTPS_ALPN_CFG); }
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 {//from w w w . ja 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.elasticsearch.plugin.readonlyrest.SSLEngineProvider.java
License:Open Source License
@Inject public SSLEngineProvider(Settings settings) throws Exception { this.conf = ConfigurationHelper.getInstance(settings, null); if (conf.sslEnabled) { if (!Strings.isNullOrEmpty(conf.sslCertChainPem) && !Strings.isNullOrEmpty(conf.sslPrivKeyPem)) { AccessController.doPrivileged(new PrivilegedAction<Void>() { @Override// w ww . j a v a 2 s. c o m public Void run() { try { logger.info("Loading SSL context with certChain=" + conf.sslCertChainPem + ", privKey=" + conf.sslPrivKeyPem); // #TODO expose configuration of sslPrivKeyPem password? Letsencrypt never sets one.. context = SslContextBuilder .forServer(new File(conf.sslCertChainPem), new File(conf.sslPrivKeyPem), null) .build(); } catch (SSLException e) { logger.error("Failed to load SSL CertChain & private key!"); e.printStackTrace(); } return null; } }); // Everything is configured logger.info("SSL configured through cert_chain and privkey"); return; } logger.info("SSL cert_chain and privkey not configured, attempting with JKS keystore.."); try { char[] keyStorePassBa = null; if (!Strings.isNullOrEmpty(conf.sslKeyStorePassword)) { keyStorePassBa = conf.sslKeyStorePassword.toCharArray(); } // Load the JKS keystore java.security.KeyStore ks = java.security.KeyStore.getInstance("JKS"); ks.load(new java.io.FileInputStream(conf.sslKeyStoreFile), keyStorePassBa); char[] keyPassBa = null; if (!Strings.isNullOrEmpty(conf.sslKeyPassword)) { keyPassBa = conf.sslKeyPassword.toCharArray(); } // Get PrivKey from keystore if (Strings.isNullOrEmpty(conf.sslKeyAlias)) { if (ks.aliases().hasMoreElements()) { String inferredAlias = ks.aliases().nextElement(); logger.info( "SSL ssl.key_alias not configured, took first alias in keystore: " + inferredAlias); conf.sslKeyAlias = inferredAlias; } else { throw new ElasticsearchException("No alias found, therefore key found in keystore!"); } } Key key = ks.getKey(conf.sslKeyAlias, keyPassBa); if (key == null) { throw new ElasticsearchException( "Private key not found in keystore for alias: " + conf.sslKeyAlias); } // Create a PEM of the private key StringBuilder sb = new StringBuilder(); sb.append("---BEGIN PRIVATE KEY---\n"); sb.append(Base64.getEncoder().encodeToString(key.getEncoded())); sb.append("\n"); sb.append("---END PRIVATE KEY---"); String privateKey = sb.toString(); logger.info("Discovered key from JKS"); // Get CertChain from keystore Certificate[] cchain = ks.getCertificateChain(conf.sslKeyAlias); // Create a PEM of the certificate chain sb = new StringBuilder(); for (Certificate c : cchain) { sb.append("-----BEGIN CERTIFICATE-----\n"); sb.append(Base64.getEncoder().encodeToString(c.getEncoded())); sb.append("\n"); sb.append("-----END CERTIFICATE-----\n"); } String certChain = sb.toString(); logger.info("Discovered cert chain from JKS"); AccessController.doPrivileged(new PrivilegedAction<Void>() { @Override public Void run() { try { // #TODO expose configuration of sslPrivKeyPem password? Letsencrypt never sets one.. context = SslContextBuilder .forServer(new ByteArrayInputStream(certChain.getBytes(StandardCharsets.UTF_8)), new ByteArrayInputStream(privateKey.getBytes(StandardCharsets.UTF_8)), null) .build(); } catch (Exception e) { logger.error("Failed to load SSL CertChain & private key from Keystore!"); e.printStackTrace(); } return null; } }); } catch (Throwable t) { logger.error("Failed to load SSL certs and keys from JKS Keystore!"); t.printStackTrace(); } } }
From source file:org.ftccommunity.services.DevConsole.java
License:Apache License
/** * Start the service./* w ww . ja v a 2s. c o m*/ */ @Override protected void startUp() throws Exception { // Configure SSL. final SslContext sslCtx; if (SSL) { SelfSignedCertificate ssc = new SelfSignedCertificate(); sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build(); } else { sslCtx = null; } serverBootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new TelnetServerInitializer(sslCtx)); mainThread = Thread.currentThread(); }
From source file:org.glowroot.ui.AdminJsonService.java
License:Apache License
@POST(path = "/backend/admin/web", permission = "admin:edit:web") Object updateWebConfig(@BindRequest WebConfigDto configDto) throws Exception { WebConfig config = configDto.convert(); if (httpServer == null) { // running central inside servlet container try {/* ww w . java 2s . c om*/ configRepository.updateWebConfig(config, configDto.version()); } catch (OptimisticLockException e) { throw new JsonServiceException(PRECONDITION_FAILED, e); } return getWebConfig(false); } if (config.https() && !httpServer.getHttps()) { // validate certificate and private key exist and are valid File certificateFile = new File(certificateDir, "certificate.pem"); if (!certificateFile.exists()) { return "{\"httpsRequiredFilesDoNotExist\":true}"; } File privateKeyFile = new File(certificateDir, "private.pem"); if (!privateKeyFile.exists()) { return "{\"httpsRequiredFilesDoNotExist\":true}"; } try { SslContextBuilder.forServer(certificateFile, privateKeyFile); } catch (Exception e) { logger.debug(e.getMessage(), e); StringWriter sw = new StringWriter(); JsonGenerator jg = mapper.getFactory().createGenerator(sw); jg.writeStartObject(); jg.writeStringField("httpsValidationError", e.getMessage()); jg.writeEndObject(); jg.close(); return sw.toString(); } } try { configRepository.updateWebConfig(config, configDto.version()); } catch (OptimisticLockException e) { throw new JsonServiceException(PRECONDITION_FAILED, e); } return onSuccessfulWebUpdate(config); }
From source file:org.glowroot.ui.HttpServer.java
License:Apache License
HttpServer(String bindAddress, int port, int numWorkerThreads, ConfigRepository configRepository, CommonHandler commonHandler, File certificateDir) throws Exception { InternalLoggerFactory.setDefaultFactory(Slf4JLoggerFactory.INSTANCE); ThreadFactory bossThreadFactory = new ThreadFactoryBuilder().setDaemon(true) .setNameFormat("Glowroot-Http-Boss").build(); ThreadFactory workerThreadFactory = new ThreadFactoryBuilder().setDaemon(true) .setNameFormat("Glowroot-Http-Worker-%d").build(); bossGroup = new NioEventLoopGroup(1, bossThreadFactory); workerGroup = new NioEventLoopGroup(numWorkerThreads, workerThreadFactory); final HttpServerHandler handler = new HttpServerHandler(configRepository, commonHandler); if (configRepository.getWebConfig().https()) { sslContext = SslContextBuilder .forServer(new File(certificateDir, "certificate.pem"), new File(certificateDir, "private.pem")) .build();/*from ww w . j a v a2 s. c o m*/ } this.certificateDir = certificateDir; bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); SslContext sslContextLocal = sslContext; if (sslContextLocal != null) { p.addLast(sslContextLocal.newHandler(ch.alloc())); } // bumping maxInitialLineLength (first arg below) from default 4096 to 32768 // in order to handle long urls on /jvm/gauges view // bumping maxHeaderSize (second arg below) from default 8192 to 32768 for // same reason due to "Referer" header once url becomes huge // leaving maxChunkSize (third arg below) at default 8192 p.addLast(new HttpServerCodec(32768, 32768, 8192)); p.addLast(new HttpObjectAggregator(1048576)); p.addLast(new ConditionalHttpContentCompressor()); p.addLast(new ChunkedWriteHandler()); p.addLast(handler); } }); this.handler = handler; logger.debug("<init>(): binding http server to port {}", port); this.bindAddress = bindAddress; Channel serverChannel; try { serverChannel = bootstrap.bind(new InetSocketAddress(bindAddress, port)).sync().channel(); } catch (Exception e) { // FailedChannelFuture.sync() is using UNSAFE to re-throw checked exceptions bossGroup.shutdownGracefully(0, 0, SECONDS); workerGroup.shutdownGracefully(0, 0, SECONDS); throw new SocketBindException(e); } this.serverChannel = serverChannel; this.port = ((InetSocketAddress) serverChannel.localAddress()).getPort(); logger.debug("<init>(): http server bound"); }
From source file:org.glowroot.ui.HttpServer.java
License:Apache License
void changeProtocol(boolean ssl) throws Exception { if (ssl) {//from w w w . j a va2 s .co m sslContext = SslContextBuilder .forServer(new File(certificateDir, "certificate.pem"), new File(certificateDir, "private.pem")) .build(); } else { sslContext = null; } handler.closeAllButCurrent(); }