Java Code Examples for org.eclipse.jetty.util.ssl.SslContextFactory#setTrustAll()

The following examples show how to use org.eclipse.jetty.util.ssl.SslContextFactory#setTrustAll() . 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: HttpConfig.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
@Bean
public SslContextFactory jettySslContextFactory() {
    SslContextFactory sslContextFactory = new SslContextFactory(SecurityUtils.replaceFourSlashes(keyStore));
    sslContextFactory.setProtocol(protocol);
    sslContextFactory.setKeyStorePassword(keyStorePassword);
    sslContextFactory.setKeyStoreType(keyStoreType);
    sslContextFactory.setCertAlias(keyAlias);

    if (trustStore != null) {
        sslContextFactory.setTrustStorePath(SecurityUtils.replaceFourSlashes(trustStore));
        sslContextFactory.setTrustStoreType(trustStoreType);
        sslContextFactory.setTrustStorePassword(trustStorePassword);
    }
    log.debug("jettySslContextFactory: {}", sslContextFactory.dump());

    if (!verifySslCertificatesOfServices) {
        sslContextFactory.setTrustAll(true);
    }

    return sslContextFactory;
}
 
Example 2
Source File: JettySeverTools.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
protected static void addHttpsConnector(Server server, Integer port) throws Exception {
	SslContextFactory sslContextFactory = new SslContextFactory();
	sslContextFactory.setKeyStorePath(Config.sslKeyStore().getAbsolutePath());
	sslContextFactory.setKeyStorePassword(Config.token().getSslKeyStorePassword());
	sslContextFactory.setKeyManagerPassword(Config.token().getSslKeyManagerPassword());
	sslContextFactory.setTrustAll(true);
	HttpConfiguration config = new HttpConfiguration();
	config.setSecureScheme("https");
	config.setOutputBufferSize(32768);
	config.setRequestHeaderSize(8192 * 2);
	config.setResponseHeaderSize(8192 * 2);
	config.setSendServerVersion(true);
	config.setSendDateHeader(false);
	ServerConnector sslConnector = new ServerConnector(server,
			new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
			new HttpConnectionFactory(config));
	sslConnector.setPort(port);
	server.addConnector(sslConnector);
}
 
Example 3
Source File: MockServer.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
public MockServer() throws IOException {
    server = new Server();
    connector = new ServerConnector(server);
    connector.setPort(httpPort);

    HttpConfiguration https = new HttpConfiguration();
    https.addCustomizer(new SecureRequestCustomizer());

    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setTrustAll(true);
    sslContextFactory.setValidateCerts(false);
    sslContextFactory.setNeedClientAuth(false);
    sslContextFactory.setWantClientAuth(false);
    sslContextFactory.setValidatePeerCerts(false);
    sslContextFactory.setKeyStorePassword("password");
    sslContextFactory.setKeyStorePath(MockServer.class.getResource("mock-keystore.jks").toExternalForm());

    sslConnector = new ServerConnector(server,
                                       new SslConnectionFactory(sslContextFactory,
                                                                HttpVersion.HTTP_1_1.asString()),
                                       new HttpConnectionFactory(https));
    sslConnector.setPort(httpsPort);

    server.setConnectors(new Connector[] {connector, sslConnector});

    ServletContextHandler context = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);
    context.addServlet(new ServletHolder(new AlwaysSuccessServlet()), "/*");
    server.setHandler(context);
}
 
Example 4
Source File: ProxyServlet.java    From secrets-proxy with Apache License 2.0 5 votes vote down vote up
/**
 * Async http client used to connect to <b>proxyTo</b> server. TLS config is usually done here.
 *
 * @return {@link HttpClient}
 */
@Override
protected HttpClient newHttpClient() {
  SslContextFactory sslFactory = new SslContextFactory();
  sslFactory.setTrustAll(trustAllCerts);
  return new HttpClient(sslFactory);
}
 
Example 5
Source File: JettyHttpsServer.java    From sumk with Apache License 2.0 5 votes vote down vote up
@Override
protected ConnectionFactory[] getConnectionFactorys() throws URISyntaxException {
	@SuppressWarnings("deprecation")
	SslContextFactory sslContextFactory = new SslContextFactory();
	String path = get(HttpPlugin.KEY_STORE_PATH);
	File keystoreFile = FileUtil.file(path);
	if (!keystoreFile.exists()) {
		String msg = path + " is not exist";
		Logs.http().error(msg);
		SumkException.throwException(-2345345, msg);
	}
	sslContextFactory.setKeyStorePath(keystoreFile.getAbsolutePath());
	sslContextFactory.setKeyStorePassword(get("sumk.jetty.ssl.storePassword"));
	sslContextFactory.setKeyManagerPassword(get("sumk.jetty.ssl.managerPassword"));
	sslContextFactory.setCertAlias(get("sumk.jetty.ssl.alias"));

	String v = AppInfo.get("sumk.jetty.ssl.storeType", null);
	if (v != null) {
		sslContextFactory.setKeyStoreType(v);
	}

	sslContextFactory.setTrustAll(AppInfo.getBoolean("sumk.jetty.ssl.trustAll", false));

	Logs.http().info("using https");
	return new ConnectionFactory[] { new SslConnectionFactory(sslContextFactory, "http/1.1"),
			new HttpConnectionFactory() };
}
 
Example 6
Source File: KeyStoreSSLContext.java    From pulsar with Apache License 2.0 5 votes vote down vote up
public static SslContextFactory createSslContextFactory(String sslProviderString,
                                                        String keyStoreTypeString,
                                                        String keyStore,
                                                        String keyStorePassword,
                                                        boolean allowInsecureConnection,
                                                        String trustStoreTypeString,
                                                        String trustStore,
                                                        String trustStorePassword,
                                                        boolean requireTrustedClientCertOnConnect,
                                                        long certRefreshInSec)
        throws GeneralSecurityException, SSLException, FileNotFoundException, IOException {
    SslContextFactory sslCtxFactory;

    sslCtxFactory = new SslContextFactoryWithAutoRefresh(
            sslProviderString,
            keyStoreTypeString,
            keyStore,
            keyStorePassword,
            allowInsecureConnection,
            trustStoreTypeString,
            trustStore,
            trustStorePassword,
            requireTrustedClientCertOnConnect,
            certRefreshInSec);

    if (requireTrustedClientCertOnConnect) {
        sslCtxFactory.setNeedClientAuth(true);
    } else {
        sslCtxFactory.setWantClientAuth(true);
    }
    sslCtxFactory.setTrustAll(true);

    return sslCtxFactory;
}
 
Example 7
Source File: WebSocketAbstractSampler.java    From jmeter-bzm-plugins with Apache License 2.0 4 votes vote down vote up
public WebSocketConnection getConnectionWS (String connectionId, SampleResult sampleResult) throws Exception{
  	
  	
  	
  	URI uri = getUri();
  
  	String closeConnectionPattern = getCloseConnectionPattern();
  	int connectionTimeout;
  	
  	try {
  		connectionTimeout = Integer.parseInt(getConnectionTimeout());
      } catch (NumberFormatException ex) {
          log.warn("Request timeout is not a number; using the default connection timeout of " + DEFAULT_CONNECTION_TIMEOUT + "ms");
          connectionTimeout = DEFAULT_CONNECTION_TIMEOUT;
      }

  	SslContextFactory sslContexFactory = new SslContextFactory();
      sslContexFactory.setTrustAll(true);
      WebSocketClient webSocketClient = new WebSocketClient(sslContexFactory);
      WebSocketConnection webSocketConnection = factory.getWebSocketHandler(webSocketClient, closeConnectionPattern, getContentEncoding());
      
webSocketClient.start();
      
      ClientUpgradeRequest request = new ClientUpgradeRequest();
      setConnectionHeaders(request, getHeaderManager(), null);
      setConnectionCookie(webSocketClient, uri, getCookieManager());
      webSocketClient.connect(webSocketConnection, uri, request);
      
      for (Map.Entry<String, List<String>> entry : request.getHeaders().entrySet()){
      	sampleResult.setRequestHeaders(sampleResult.getRequestHeaders() + entry.getKey() + ": ");
      	for (String s : entry.getValue()){
      		sampleResult.setRequestHeaders(sampleResult.getRequestHeaders() + entry.getValue() + " ");
      	}
      	sampleResult.setRequestHeaders(sampleResult.getRequestHeaders() + "\n");
      }
      
      sampleResult.setRequestHeaders(sampleResult.getRequestHeaders() + "\n\nCookies: \n\n");
      
      for (HttpCookie h : webSocketClient.getCookieStore().getCookies()){
      	sampleResult.setRequestHeaders(sampleResult.getRequestHeaders() + h);
      }

webSocketConnection.awaitOpen(connectionTimeout, TimeUnit.MILLISECONDS);

      
      if (!webSocketConnection.isConnected()){
  		return null;
      }
      
      connectionList.put(connectionId, webSocketConnection);
      
      return webSocketConnection;
  }
 
Example 8
Source File: HttpService.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public HttpService start() throws Exception {
    TestResourceUnavailableException.throwIfResourceUnavailable(getClass(), ROOT_WAR_PATH);

    try {
        if (httpsEnabled) {
            //by default the server is configured with a http connector, this needs to be removed since we are going
            //to provide https
            for (Connector c: server.getConnectors()) {
                server.removeConnector(c);
            }

            InputStream keyStoreStream = ResourceUtils.create(this).getResourceFromUrl(SERVER_KEYSTORE);
            KeyStore keyStore;
            try {
                keyStore = SecureKeys.newKeyStore(keyStoreStream, "password");
            } finally {
                keyStoreStream.close();
            }

            // manually create like seen in XMLs at http://www.eclipse.org/jetty/documentation/current/configuring-ssl.html
            SslContextFactory sslContextFactory = new SslContextFactory();
            sslContextFactory.setKeyStore(keyStore);
            sslContextFactory.setTrustAll(true);
            sslContextFactory.setKeyStorePassword("password");

            HttpConfiguration sslHttpConfig = new HttpConfiguration();
            sslHttpConfig.setSecureScheme("https");
            sslHttpConfig.setSecurePort(actualPort);

            ServerConnector httpsConnector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(sslHttpConfig));
            httpsConnector.setPort(actualPort);

            server.addConnector(httpsConnector);
        }

        addShutdownHook();

        File tmpWarFile = Os.writeToTempFile(
                ResourceUtils.create(this).getResourceFromUrl(ROOT_WAR_URL), 
                "TestHttpService", 
                ".war");
        
        WebAppContext context = new WebAppContext();
        context.setWar(tmpWarFile.getAbsolutePath());
        context.setContextPath("/");
        context.setParentLoaderPriority(true);

        if (securityHandler.isPresent()) {
            context.setSecurityHandler(securityHandler.get());
        }

        server.setHandler(context);
        server.start();

        log.info("Started test HttpService at "+getUrl());
        
    } catch (Exception e) {
        try {
            shutdown();
        } catch (Exception e2) {
            log.warn("Error shutting down HttpService while recovering from earlier error (re-throwing earlier error)", e2);
            throw e;
        }
    }

    return this;
}
 
Example 9
Source File: HttpdForTests.java    From buck with Apache License 2.0 4 votes vote down vote up
/**
 * Creates an HTTPS server that requires client authentication (though doesn't validate the chain)
 *
 * @param caPath The path to a CA certificate to put in the keystore.
 * @param certificatePath The path to a pem encoded x509 certificate
 * @param keyPath The path to a pem encoded PKCS#8 certificate
 * @throws IOException Any of the keys could not be read
 * @throws KeyStoreException There's a problem writing the key into the keystore
 * @throws CertificateException The certificate was not valid
 * @throws NoSuchAlgorithmException The algorithm used by the certificate/key are invalid
 */
public HttpdForTests(Path caPath, Path certificatePath, Path keyPath)
    throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException {

  // Configure the logging for jetty. Which uses a singleton. Ho hum.
  Log.setLog(new JavaUtilLog());
  server = new Server();

  String password = "super_sekret";

  ImmutableList<X509Certificate> caCerts =
      ClientCertificateHandler.parseCertificates(Optional.of(caPath), true);
  ClientCertificateHandler.CertificateInfo certInfo =
      ClientCertificateHandler.parseCertificateChain(Optional.of(certificatePath), true).get();
  PrivateKey privateKey =
      ClientCertificateHandler.parsePrivateKey(
              Optional.of(keyPath), certInfo.getPrimaryCert(), true)
          .get();

  KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  ks.load(null, password.toCharArray());
  for (int i = 0; i < caCerts.size(); i++) {
    ks.setCertificateEntry(String.format("ca%d", i), caCerts.get(i));
  }
  ks.setKeyEntry(
      "private",
      privateKey,
      password.toCharArray(),
      new Certificate[] {certInfo.getPrimaryCert()});

  SslContextFactory sslFactory = new SslContextFactory();
  sslFactory.setKeyStore(ks);
  sslFactory.setKeyStorePassword(password);
  sslFactory.setCertAlias("private");
  sslFactory.setTrustStore(ks);
  sslFactory.setTrustStorePassword(password);
  // *Require* a client cert, but don't validate it (getting TLS auth working properly was a
  // bit of a pain). We'll store peers' certs in the handler, and validate the certs manually
  // in our tests.
  sslFactory.setNeedClientAuth(true);
  sslFactory.setTrustAll(true);

  HttpConfiguration https_config = new HttpConfiguration();
  https_config.setSecurePort(0);
  https_config.setSecureScheme("https");
  https_config.addCustomizer(new SecureRequestCustomizer());

  ServerConnector sslConnector =
      new ServerConnector(
          server,
          new SslConnectionFactory(sslFactory, HttpVersion.HTTP_1_1.toString()),
          new HttpConnectionFactory(https_config));
  server.addConnector(sslConnector);

  handlerList = new HandlerList();
  localhost = getLocalhostAddress(false).getHostAddress();
}
 
Example 10
Source File: PHttpServer.java    From jphp with Apache License 2.0 4 votes vote down vote up
@Signature
public void listen(Memory value, ArrayMemory sslSettings) {
    ServerConnector connector;

    if (sslSettings != null) {
        SslContextFactory contextFactory = new SslContextFactory();

        // key store
        if (sslSettings.containsKey("keyStorePath"))
            contextFactory.setKeyStorePath(sslSettings.valueOfIndex("keyStorePath").toString());

        if (sslSettings.containsKey("keyStorePassword"))
            contextFactory.setKeyStoreType(sslSettings.valueOfIndex("keyStorePassword").toString());

        if (sslSettings.containsKey("keyStoreType"))
            contextFactory.setKeyStoreType(sslSettings.valueOfIndex("keyStoreType").toString());

        if (sslSettings.containsKey("keyStoreProvider"))
            contextFactory.setKeyStoreProvider(sslSettings.valueOfIndex("keyStoreProvider").toString());

        // trust store
        if (sslSettings.containsKey("trustStorePath"))
            contextFactory.setTrustStorePath(sslSettings.valueOfIndex("trustStorePath").toString());

        if (sslSettings.containsKey("trustStorePassword"))
            contextFactory.setTrustStoreType(sslSettings.valueOfIndex("trustStorePassword").toString());

        if (sslSettings.containsKey("trustStoreType"))
            contextFactory.setTrustStoreType(sslSettings.valueOfIndex("trustStoreType").toString());

        if (sslSettings.containsKey("trustStoreProvider"))
            contextFactory.setTrustStoreProvider(sslSettings.valueOfIndex("trustStoreProvider").toString());

        if (sslSettings.containsKey("trustAll"))
            contextFactory.setTrustAll(sslSettings.valueOfIndex("trustAll").toBoolean());

        if (sslSettings.containsKey("trustManagerFactoryAlgorithm"))
            contextFactory.setTrustManagerFactoryAlgorithm(sslSettings.valueOfIndex("trustManagerFactoryAlgorithm").toString());

        // key manager
        if (sslSettings.containsKey("keyManagerFactoryAlgorithm"))
            contextFactory.setKeyManagerFactoryAlgorithm(sslSettings.valueOfIndex("keyManagerFactoryAlgorithm").toString());

        if (sslSettings.containsKey("keyManagerPassword"))
            contextFactory.setKeyManagerPassword(sslSettings.valueOfIndex("keyManagerPassword").toString());

        // other
        if (sslSettings.containsKey("certAlias"))
            contextFactory.setCertAlias(sslSettings.valueOfIndex("certAlias").toString());

        if (sslSettings.containsKey("protocol"))
            contextFactory.setProtocol(sslSettings.valueOfIndex("protocol").toString());

        if (sslSettings.containsKey("provider"))
            contextFactory.setProvider(sslSettings.valueOfIndex("provider").toString());

        if (sslSettings.containsKey("validateCerts"))
            contextFactory.setValidateCerts(sslSettings.valueOfIndex("validateCerts").toBoolean());

        connector = new ServerConnector(server, contextFactory);
    } else {
        connector = new ServerConnector(server);
    }

    if (value.isNumber()) {
        connector.setName("0.0.0.0:" + value.toInteger());
        connector.setPort(value.toInteger());
    } else {
        String[] strings = value.toString().split("\\:");

        if (strings.length < 2) {
            throw new IllegalArgumentException("Invalid listen value: " + value);
        }

        connector.setHost(strings[0]);
        connector.setPort(Integer.parseInt(strings[1]));
        connector.setName(strings[0] + ":" + strings[1]);
    }

    server.addConnector(connector);
}