List of usage examples for io.netty.handler.ssl.util SelfSignedCertificate SelfSignedCertificate
public SelfSignedCertificate(String fqdn) throws CertificateException
From source file:com.chiorichan.http.ssl.SslManager.java
License:Mozilla Public License
private void selfSignCertificate() throws SSLException { getLogger().warning(//from w w w. ja v a 2 s .c o m "No proper server-wide SSL certificate was provided, we will generate an extremely insecure temporary self signed one for now but please obtain an official one or self sign one of your own ASAP."); try { SelfSignedCertificate ssc = new SelfSignedCertificate("chiorichan.com"); updateDefaultCertificate(ssc.certificate(), ssc.privateKey(), null, false); usingSelfSignedCert = true; } catch (FileNotFoundException | CertificateException e) { // Ignore } }
From source file:com.github.unafraid.signer.server.ServerManager.java
License:Apache License
private void init() { SslContext sslCtx = null;/* w ww . j av a2 s . c om*/ if (SSL) { try { final SelfSignedCertificate ssc = new SelfSignedCertificate("localhost"); sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); } catch (Exception e) { LOGGER.warn(e.getMessage(), e); } } InetAddress listenAddress; try { listenAddress = Inet4Address.getByName(HOSTNAME); } catch (Exception e) { LOGGER.warn("Incorrect listen ip specified: {} using localhost instead!", HOSTNAME); listenAddress = Inet4Address.getLoopbackAddress(); } final EventLoopGroup bossGroup = new NioEventLoopGroup(1); final EventLoopGroup workerGroup = new NioEventLoopGroup(); try { final ServerBootstrap b = new ServerBootstrap(); b.option(ChannelOption.SO_BACKLOG, 1024); b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ServerInitializer(sslCtx)); // Start listening final Channel ch = b.bind(listenAddress, PORT).sync().channel(); LOGGER.info("Open your web browser and navigate to {}://{}{}/", (SSL ? "https" : "http"), listenAddress.getHostAddress(), (PORT != 443 && PORT != 80 ? ":" + PORT : "")); // Block til closed ch.closeFuture().sync(); } catch (Exception e) { LOGGER.warn("Failed to initialize server: ", e); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:com.linecorp.armeria.server.AbstractVirtualHostBuilder.java
License:Apache License
/** * Configures SSL or TLS of this {@link VirtualHost} with an auto-generated self-signed certificate. * <strong>Note:</strong> You should never use this in production but only for a testing purpose. * * @throws CertificateException if failed to generate a self-signed certificate */// w w w . j ava 2 s . co m public B tlsSelfSigned() throws SSLException, CertificateException { final SelfSignedCertificate ssc = new SelfSignedCertificate(defaultHostname); return tls(ssc.certificate(), ssc.privateKey()); }
From source file:com.linecorp.armeria.server.SniServerTest.java
License:Apache License
@Override protected void configureServer(ServerBuilder sb) throws Exception { dnsResolver = new InMemoryDnsResolver(); dnsResolver.add("a.com", NetUtil.LOCALHOST4); dnsResolver.add("b.com", NetUtil.LOCALHOST4); dnsResolver.add("c.com", NetUtil.LOCALHOST4); dnsResolver.add("mismatch.com", NetUtil.LOCALHOST4); dnsResolver.add("127.0.0.1", NetUtil.LOCALHOST4); sscA = new SelfSignedCertificate("a.com"); sscB = new SelfSignedCertificate("b.com"); sscC = new SelfSignedCertificate("c.com"); final VirtualHostBuilder a = new VirtualHostBuilder("a.com"); final VirtualHostBuilder b = new VirtualHostBuilder("b.com"); final VirtualHostBuilder c = new VirtualHostBuilder("c.com"); a.serviceAt("/", new AbstractHttpService() { @Override/*from www . j a v a2s. co m*/ protected void doGet(ServiceRequestContext ctx, HttpRequest req, HttpResponseWriter res) { res.respond(HttpStatus.OK, MediaType.PLAIN_TEXT_UTF_8, "a.com"); } }); b.serviceAt("/", new AbstractHttpService() { @Override protected void doGet(ServiceRequestContext ctx, HttpRequest req, HttpResponseWriter res) { res.respond(HttpStatus.OK, MediaType.PLAIN_TEXT_UTF_8, "b.com"); } }); c.serviceAt("/", new AbstractHttpService() { @Override protected void doGet(ServiceRequestContext ctx, HttpRequest req, HttpResponseWriter res) { res.respond(HttpStatus.OK, MediaType.PLAIN_TEXT_UTF_8, "c.com"); } }); a.sslContext(SessionProtocol.HTTPS, sscA.certificate(), sscA.privateKey()); b.sslContext(SessionProtocol.HTTPS, sscB.certificate(), sscB.privateKey()); c.sslContext(SessionProtocol.HTTPS, sscC.certificate(), sscC.privateKey()); sb.virtualHost(a.build()); sb.virtualHost(b.build()); sb.defaultVirtualHost(c.build()); sb.port(0, SessionProtocol.HTTPS); }
From source file:eu.matejkormuth.pexel.network.NettyServerComunicator.java
License:Open Source License
public void init(final int port) throws SSLException, CertificateException, InterruptedException { this.log.info("Initializing SSL..."); SelfSignedCertificate ssc = new SelfSignedCertificate("pexel.eu"); SslContext sslCtx = SslContext.newServerContext(ssc.certificate(), ssc.privateKey()); EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); try {//from w ww .j a va 2 s . c o m this.log.info("Starting up server..."); this.b = new ServerBootstrap(); this.b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class) .handler(new LoggingHandler(LogLevel.INFO)) .childHandler(new NettyServerComunicatorInitializer(sslCtx)); workerGroup.scheduleAtFixedRate(new Runnable() { @Override public void run() { NettyServerComunicator.this.sendQueues(); } }, 0L, 10L, TimeUnit.MILLISECONDS); this.b.bind(port).sync().channel().closeFuture().sync(); } finally { this.log.info("Stopping server..."); bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
From source file:io.fouad.jtb.webhook.WebhookServer.java
License:Open Source License
/** * Generates a self-signed SSL certificate to be used by Telegram server * to connect to your server over secure HTTPS connection. * /*www . j a va2s.co m*/ * @throws CertificateException this exception indicates one of a variety of certificate problems * @throws SSLException this exception occurs if building the certificate fails */ public void useGeneratedSelfSignedSslCertificate() throws CertificateException, SSLException { SelfSignedCertificate ssc = new SelfSignedCertificate(hostname); certificate = ssc.certificate(); sslCtx = SslContextBuilder.forServer(certificate, ssc.privateKey()).build(); }
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();/*from w ww. j a va 2 s .c o m*/ 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:org.apache.drill.exec.rpc.user.security.TestUserBitSSL.java
License:Apache License
@Ignore("This test fails in some cases where the host name may be set up inconsistently.") @Test// w ww . j a v a2 s .c o m public void testClientConfigHostnameVerification() { String password = "test_password"; String trustStoreFileName = "drillTestTrustStore"; String keyStoreFileName = "drillTestKeyStore"; KeyStore ts, ks; File tempFile1, tempFile2; String trustStorePath; String keyStorePath; try { String fqdn = InetAddress.getLocalHost().getHostName(); SelfSignedCertificate certificate = new SelfSignedCertificate(fqdn); tempFile1 = File.createTempFile(trustStoreFileName, ".ks"); tempFile1.deleteOnExit(); trustStorePath = tempFile1.getAbsolutePath(); //generate a truststore. ts = KeyStore.getInstance(KeyStore.getDefaultType()); ts.load(null, password.toCharArray()); ts.setCertificateEntry("drillTest", certificate.cert()); // Store away the truststore. try (FileOutputStream fos1 = new FileOutputStream(tempFile1);) { ts.store(fos1, password.toCharArray()); } catch (Exception e) { fail(e.getMessage()); } tempFile2 = File.createTempFile(keyStoreFileName, ".ks"); tempFile2.deleteOnExit(); keyStorePath = tempFile2.getAbsolutePath(); //generate a keystore. ts = KeyStore.getInstance(KeyStore.getDefaultType()); ts.load(null, password.toCharArray()); ts.setKeyEntry("drillTest", certificate.key(), password.toCharArray(), new java.security.cert.Certificate[] { certificate.cert() }); // Store away the keystore. try (FileOutputStream fos2 = new FileOutputStream(tempFile2);) { ts.store(fos2, password.toCharArray()); } catch (Exception e) { fail(e.getMessage()); } final Properties connectionProps = new Properties(); connectionProps.setProperty(DrillProperties.ENABLE_TLS, "true"); connectionProps.setProperty(DrillProperties.TRUSTSTORE_PATH, trustStorePath); connectionProps.setProperty(DrillProperties.TRUSTSTORE_PASSWORD, password); connectionProps.setProperty(DrillProperties.DISABLE_HOST_VERIFICATION, "false"); DrillConfig sslConfig = new DrillConfig(DrillConfig.create(cloneDefaultTestConfigProperties()) .withValue(ExecConstants.USER_SSL_ENABLED, ConfigValueFactory.fromAnyRef(true)) .withValue(ExecConstants.SSL_KEYSTORE_TYPE, ConfigValueFactory.fromAnyRef("JKS")) .withValue(ExecConstants.SSL_KEYSTORE_PATH, ConfigValueFactory.fromAnyRef(keyStorePath)) .withValue(ExecConstants.SSL_KEYSTORE_PASSWORD, ConfigValueFactory.fromAnyRef("test_password")) .withValue(ExecConstants.SSL_PROTOCOL, ConfigValueFactory.fromAnyRef("TLSv1.2"))); updateTestCluster(1, sslConfig, connectionProps); } catch (Exception e) { fail(e.getMessage()); } //reset cluster updateTestCluster(1, newConfig, initProps); }
From source file:org.graylog2.plugin.inputs.transports.AbstractTcpTransport.java
License:Open Source License
private Callable<ChannelHandler> getSslHandlerCallable(MessageInput input) { final File certFile; final File keyFile; if (tlsCertFile.exists() && tlsKeyFile.exists()) { certFile = tlsCertFile;/* w w w . ja v a 2 s . co m*/ keyFile = tlsKeyFile; } else { LOG.warn( "TLS key file or certificate file does not exist, creating a self-signed certificate for input [{}/{}].", input.getName(), input.getId()); final String tmpDir = System.getProperty("java.io.tmpdir"); checkState(tmpDir != null, "The temporary directory must not be null!"); final Path tmpPath = Paths.get(tmpDir); if (!Files.isDirectory(tmpPath) || !Files.isWritable(tmpPath)) { throw new IllegalStateException( "Couldn't write to temporary directory: " + tmpPath.toAbsolutePath()); } try { final SelfSignedCertificate ssc = new SelfSignedCertificate( configuration.getString(CK_BIND_ADDRESS) + ":" + configuration.getString(CK_PORT)); certFile = ssc.certificate(); keyFile = ssc.privateKey(); } catch (CertificateException e) { final String msg = String.format(Locale.ENGLISH, "Problem creating a self-signed certificate for input [%s/%s].", input.getName(), input.getId()); throw new IllegalStateException(msg, e); } } final ClientAuth clientAuth; switch (tlsClientAuth) { case TLS_CLIENT_AUTH_DISABLED: LOG.debug("Not using TLS client authentication"); clientAuth = ClientAuth.NONE; break; case TLS_CLIENT_AUTH_OPTIONAL: LOG.debug("Using optional TLS client authentication"); clientAuth = ClientAuth.OPTIONAL; break; case TLS_CLIENT_AUTH_REQUIRED: LOG.debug("Using mandatory TLS client authentication"); clientAuth = ClientAuth.REQUIRE; break; default: throw new IllegalArgumentException("Unknown TLS client authentication mode: " + tlsClientAuth); } return buildSslHandlerCallable(nettyTransportConfiguration.getTlsProvider(), certFile, keyFile, tlsKeyPassword, clientAuth, tlsClientAuthCertFile); }
From source file:org.neo4j.bolt.security.ssl.TestSslCertificateFactory.java
License:Open Source License
@Test public void shouldLoadPEMCertificates() throws Throwable { // Given/*from ww w . ja v a2 s . c om*/ SelfSignedCertificate cert = new SelfSignedCertificate("example.com"); Certificates certs = new Certificates(); File pemCertificate = cert.certificate(); // When Certificate[] certificates = certs.loadCertificates(pemCertificate); // Then assertThat(certificates.length, equalTo(1)); }