org.glassfish.grizzly.ssl.SSLContextConfigurator Java Examples

The following examples show how to use org.glassfish.grizzly.ssl.SSLContextConfigurator. 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: RESTServer.java    From pravega with Apache License 2.0 6 votes vote down vote up
/**
 * Start REST service.
 */
@Override
protected void startUp() {
    long traceId = LoggerHelpers.traceEnterWithContext(log, this.objectId, "startUp");
    try {
        log.info("Starting REST server listening on port: {}", this.restServerConfig.getPort());
        if (restServerConfig.isTlsEnabled()) {
            SSLContextConfigurator contextConfigurator = new SSLContextConfigurator();
            contextConfigurator.setKeyStoreFile(restServerConfig.getKeyFilePath());
            contextConfigurator.setKeyStorePass(JKSHelper.loadPasswordFrom(restServerConfig.getKeyFilePasswordPath()));
            httpServer = GrizzlyHttpServerFactory.createHttpServer(baseUri, resourceConfig, true,
                    new SSLEngineConfigurator(contextConfigurator, false, false, false));
        } else {
            httpServer = GrizzlyHttpServerFactory.createHttpServer(baseUri, resourceConfig, true);
        }
    } finally {
        LoggerHelpers.traceLeave(log, this.objectId, "startUp", traceId);
    }
}
 
Example #2
Source File: DefaultWebhook.java    From TelegramBots with MIT License 6 votes vote down vote up
public void startServer() throws TelegramApiRequestException {
    ResourceConfig rc = new ResourceConfig();
    rc.register(restApi);
    rc.register(JacksonFeature.class);

    final HttpServer grizzlyServer;
    if (keystoreServerFile != null && keystoreServerPwd != null) {
        SSLContextConfigurator sslContext = new SSLContextConfigurator();

        // set up security context
        sslContext.setKeyStoreFile(keystoreServerFile); // contains server keypair
        sslContext.setKeyStorePass(keystoreServerPwd);

        grizzlyServer = GrizzlyHttpServerFactory.createHttpServer(getBaseURI(), rc, true,
                new SSLEngineConfigurator(sslContext).setClientMode(false).setNeedClientAuth(false));
    } else {
        grizzlyServer = GrizzlyHttpServerFactory.createHttpServer(getBaseURI(), rc);
    }

    try {
        grizzlyServer.start();
    } catch (IOException e) {
        throw new TelegramApiRequestException("Error starting webhook server", e);
    }
}
 
Example #3
Source File: ControllerAdminApiApplication.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
private SSLEngineConfigurator buildSSLEngineConfigurator(TlsConfiguration tlsConfiguration) {
  SSLContextConfigurator sslContextConfigurator = new SSLContextConfigurator();

  sslContextConfigurator.setKeyStoreFile(tlsConfiguration.getKeyStorePath());
  sslContextConfigurator.setKeyStorePass(tlsConfiguration.getKeyStorePassword());
  sslContextConfigurator.setTrustStoreFile(tlsConfiguration.getTrustStorePath());
  sslContextConfigurator.setTrustStorePass(tlsConfiguration.getTrustStorePassword());

  return new SSLEngineConfigurator(sslContextConfigurator).setClientMode(false)
      .setWantClientAuth(tlsConfiguration.isRequiresClientAuth()).setEnabledProtocols(new String[] { "TLSv1.2 " });
}
 
Example #4
Source File: ExoPlatformLocator.java    From exo-demo with MIT License 4 votes vote down vote up
/**
 * Initializes Grizzly-based REST interfaces as defined in the messaging config.  This method will
 * allow for REST endpoints using HTTPS by defining keystore information in exo-config.json.
 * Enabling REST will automatically expose the endpoints service and generate an ANNOUNCE_NODE message.
 * @param restConfig
 */
public static void initREST(MessagingConfig restConfig) {
	URI baseUri = UriBuilder.fromUri("http://0.0.0.0").port(restConfig.port).build();
	ResourceConfig config = new ResourceConfig()
			.packages("com.txmq.exo.messaging.rest")
			.register(new CORSFilter())
			.register(JacksonFeature.class)
			.register(MultiPartFeature.class);
	
	for (String pkg : restConfig.handlers) {
		config.packages(pkg);
	}
	
	System.out.println("Attempting to start Grizzly on " + baseUri);
	HttpServer grizzly = null;
	if (restConfig.secured == true) {
		SSLContextConfigurator sslContext = new SSLContextConfigurator();
		sslContext.setKeyStoreFile(restConfig.serverKeystore.path);
		sslContext.setKeyStorePass(restConfig.serverKeystore.password);
		sslContext.setTrustStoreFile(restConfig.serverTruststore.path);
		sslContext.setTrustStorePass(restConfig.serverTruststore.password);
		
		grizzly = GrizzlyHttpServerFactory.createHttpServer(
			baseUri, 
			config, 
			true, 
			new SSLEngineConfigurator(sslContext).setClientMode(false).setNeedClientAuth(false)
		);
	} else {
		grizzly = GrizzlyHttpServerFactory.createHttpServer(baseUri, config);
	}
	
	//Track Grizzly instances so they can be shut down later
	if (grizzly != null) {
		httpServers.add(grizzly);
	}
	
	//Publish available Exo API endpoints to the HG.
	try {
		String externalUrl = baseUri.toString();
		if (platform != null) {
			externalUrl = "http://";
			byte[] rawAddress = platform.getAddress().getAddressExternalIpv4();
			for (int ptr = 0;  ptr < rawAddress.length;  ptr++) {
				int i = rawAddress[ptr] & 0xFF;
				externalUrl += Integer.toString(i);
				if (ptr < rawAddress.length - 1) {
					externalUrl += ".";
				}
			}
			externalUrl += ":" + restConfig.port;
			
			System.out.println("Reporting available REST API at " + externalUrl);
		} else {
			
		}
		createTransaction(
			new ExoMessage(
				new ExoTransactionType(ExoTransactionType.ANNOUNCE_NODE),
				externalUrl
			)
		);
				
	} catch (IOException e1) {
		// TODO Auto-generated catch block
		e1.printStackTrace();
	}
}
 
Example #5
Source File: GrizzlyHttpService.java    From linstor-server with GNU General Public License v3.0 4 votes vote down vote up
private void initGrizzly(final String bindAddress, final String httpsBindAddress)
{
    if (keyStoreFile != null)
    {
        final URI httpsUri = URI.create(String.format("https://%s", httpsBindAddress));

        // only install a redirect handler for http
        httpServer = GrizzlyHttpServerFactory.createHttpServer(
            URI.create(String.format("http://%s", bindAddress)),
            false
        );

        addHTTPSRedirectHandler(httpServer, httpsUri.getPort());

        httpsServer = GrizzlyHttpServerFactory.createHttpServer(
            httpsUri,
            restResourceConfig,
            false
        );

        SSLContextConfigurator sslCon = new SSLContextConfigurator();
        sslCon.setSecurityProtocol("TLS");
        sslCon.setKeyStoreFile(keyStoreFile.toString());
        sslCon.setKeyStorePass(keyStorePassword);

        boolean hasClientAuth = trustStoreFile != null;
        if (hasClientAuth)
        {
            sslCon.setTrustStoreFile(trustStoreFile.toString());
            sslCon.setTrustStorePass(trustStorePassword);
        }

        for (NetworkListener netListener : httpsServer.getListeners())
        {
            netListener.setSecure(true);
            SSLEngineConfigurator ssle = new SSLEngineConfigurator(sslCon);
            ssle.setWantClientAuth(hasClientAuth);
            ssle.setClientMode(false);
            ssle.setNeedClientAuth(hasClientAuth);
            netListener.setSSLEngineConfig(ssle);
        }

        enableCompression(httpsServer);
    }
    else
    {
        httpsServer = null;
        httpServer = GrizzlyHttpServerFactory.createHttpServer(
            URI.create(String.format("http://%s", bindAddress)),
            restResourceConfig,
            false
        );
    }

    // configure access logging
    if (restAccessLogMode == null)
    {
        errorReporter.logWarning("Unknown rest_access_log_mode set, fallback to append");
        restAccessLogMode = LinstorConfig.RestAccessLogMode.APPEND;
    }

    if (restAccessLogMode != LinstorConfig.RestAccessLogMode.NO_LOG)
    {
        final Path accessLogPath = restAccessLogPath.isAbsolute() ?
            restAccessLogPath : errorReporter.getLogDirectory().resolve(restAccessLogPath);
        final AccessLogBuilder builder = new AccessLogBuilder(accessLogPath.toFile());

        switch (restAccessLogMode)
        {
            case ROTATE_HOURLY:
                errorReporter.logDebug("Rest-access log set to rotate hourly.");
                builder.rotatedHourly();
                break;
            case ROTATE_DAILY:
                errorReporter.logDebug("Rest-access log set to rotate daily.");
                builder.rotatedDaily();
                break;
            case APPEND:
            case NO_LOG:
            default:
        }

        if (httpServer != null)
        {
            builder.instrument(httpServer.getServerConfiguration());
        }
        if (httpsServer != null)
        {
            builder.instrument(httpsServer.getServerConfiguration());
        }
    }
    else
    {
        errorReporter.logDebug("Rest-access log turned off.");
    }

    if (httpServer != null)
    {
        enableCompression(httpServer);
    }
}
 
Example #6
Source File: RestServer.java    From hugegraph with Apache License 2.0 4 votes vote down vote up
private HttpServer configHttpServer(URI uri, ResourceConfig rc) {
    final HttpServer server;
    String protocol = this.conf.get(ServerOptions.SERVER_PROTOCOL);
    String keystoreServerFile = this.conf.get(ServerOptions.SERVER_KEYSTORE_FILE);
    String keystoreServerPassword = this.conf.get(ServerOptions.SERVER_KEYSTORE_PASSWORD);
    if (protocol != null && protocol.equals("https")) {
        SSLContextConfigurator sslContext = new SSLContextConfigurator();
        // set up security context
        sslContext.setKeyStoreFile(keystoreServerFile);
        sslContext.setKeyStorePass(keystoreServerPassword);
        SSLEngineConfigurator sslEngineConfigurator = new SSLEngineConfigurator(sslContext)
                                                          .setClientMode(false)
                                                          .setWantClientAuth(true);
        server = GrizzlyHttpServerFactory.createHttpServer(uri, rc, true,
                                                           sslEngineConfigurator);
    } else {
        server = GrizzlyHttpServerFactory.createHttpServer(uri, rc, false);
    }
    Collection<NetworkListener> listeners = server.getListeners();
    E.checkState(listeners.size() > 0,
                 "Http Server should have some listeners, but now is none");
    NetworkListener listener = listeners.iterator().next();

    // Option max_worker_threads
    int maxWorkerThreads = this.conf.get(ServerOptions.MAX_WORKER_THREADS);
    listener.getTransport()
            .getWorkerThreadPoolConfig()
            .setCorePoolSize(maxWorkerThreads)
            .setMaxPoolSize(maxWorkerThreads);

    // Option keep_alive
    int idleTimeout = this.conf.get(ServerOptions.CONN_IDLE_TIMEOUT);
    int maxRequests = this.conf.get(ServerOptions.CONN_MAX_REQUESTS);
    listener.getKeepAlive().setIdleTimeoutInSeconds(idleTimeout);
    listener.getKeepAlive().setMaxRequestsCount(maxRequests);

    // Option transaction timeout
    int transactionTimeout = this.conf.get(ServerOptions.REQUEST_TIMEOUT);
    listener.setTransactionTimeout(transactionTimeout);

    return server;
}
 
Example #7
Source File: CommonUtil.java    From batfish with Apache License 2.0 4 votes vote down vote up
public static HttpServer startSslServer(
    ResourceConfig resourceConfig,
    URI mgrUri,
    Path keystorePath,
    String keystorePassword,
    boolean trustAllCerts,
    Path truststorePath,
    String truststorePassword,
    Class<?> configurationLocatorClass,
    Class<?> callerClass) {
  if (keystorePath == null) {
    throw new BatfishException(
        "Cannot start SSL server without keystore. If you have none, you must disable SSL.");
  }
  // first find the file as specified.
  // if that does not work, find it relative to the binary
  Path keystoreAbsolutePath = keystorePath.toAbsolutePath();
  if (!Files.exists(keystoreAbsolutePath)) {
    String callingClass = callerClass.getCanonicalName();
    System.err.printf(
        "%s: keystore file not found at %s or %s%n",
        callingClass, keystorePath, keystoreAbsolutePath);
    System.exit(1);
  }
  SSLContextConfigurator sslCon = new SSLContextConfigurator();
  sslCon.setKeyStoreFile(keystoreAbsolutePath.toString());
  sslCon.setKeyStorePass(keystorePassword);
  if (truststorePath != null) {
    if (truststorePassword == null) {
      throw new BatfishException("Truststore file supplied but truststore password missing");
    }
    sslCon.setTrustStoreFile(truststorePath.toString());
    sslCon.setTrustStorePass(truststorePassword);
  }
  boolean verifyClient = !trustAllCerts;
  return GrizzlyHttpServerFactory.createHttpServer(
      mgrUri,
      resourceConfig,
      true,
      new SSLEngineConfigurator(sslCon, false, verifyClient, false));
}
 
Example #8
Source File: SSLConfigurationBuilder.java    From micro-server with Apache License 2.0 3 votes vote down vote up
public SSLEngineConfigurator build(SSLProperties sslProperties) {
	
	SSLContextConfigurator sslContext = new SSLContextConfigurator();

       sslContext.setKeyStoreFile(sslProperties.getKeyStoreFile()); // contains server keypair
       sslContext.setKeyStorePass(sslProperties.getKeyStorePass());
       
       /**
        * trustStore stores public key or certificates from CA (Certificate Authorities) 
        * which is used to trust remote party or SSL connection. So should be optional
        */
       sslProperties.getTrustStoreFile().ifPresent(file->sslContext.setTrustStoreFile(file)); // contains client certificate
       sslProperties.getTrustStorePass().ifPresent(pass->sslContext.setTrustStorePass(pass));
       
       
       
       sslProperties.getKeyStoreType().ifPresent(type->sslContext.setKeyStoreType(type));
       sslProperties.getKeyStoreProvider().ifPresent(provider->sslContext.setKeyStoreProvider(provider));
	
       
       sslProperties.getTrustStoreType().ifPresent(type->sslContext.setTrustStoreType(type));
       sslProperties.getTrustStoreProvider().ifPresent(provider->sslContext.setTrustStoreProvider(provider));
	
	
	
	
	
       SSLEngineConfigurator sslConf = new SSLEngineConfigurator(sslContext).setClientMode(false);
       sslProperties.getClientAuth().filter(auth-> auth.toLowerCase().equals("want"))
								.ifPresent(auth->sslConf.setWantClientAuth(true));
       sslProperties.getClientAuth().filter(auth-> auth.toLowerCase().equals("need"))
						.ifPresent(auth->sslConf.setNeedClientAuth(true));
       Maybe.fromOptional(sslProperties.getCiphers()).peek(ciphers->sslConf.setEnabledCipherSuites(ciphers.split(",")))
       			.forEach(c-> sslConf.setCipherConfigured(true));
       Maybe.fromOptional(sslProperties.getProtocol()).peek(pr->sslConf.setEnabledProtocols(pr.split(",")))
       						.forEach(p->sslConf.setProtocolConfigured(true));
       
       
       return sslConf;
}