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

The following examples show how to use org.eclipse.jetty.util.ssl.SslContextFactory#setWantClientAuth() . 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: SSLUtils.java    From kop with Apache License 2.0 6 votes vote down vote up
/**
 * Configures Authentication related settings in SslContextFactory.
 */
protected static void configureSslContextFactoryAuthentication(SslContextFactory ssl,
                                                               Map<String, Object> sslConfigValues) {
    String sslClientAuth = (String) getOrDefault(
        sslConfigValues,
        BrokerSecurityConfigs.SSL_CLIENT_AUTH_CONFIG,
        "none");
    switch (sslClientAuth) {
        case "requested":
            ssl.setWantClientAuth(true);
            break;
        case "required":
            ssl.setNeedClientAuth(true);
            break;
        default:
            ssl.setNeedClientAuth(false);
            ssl.setWantClientAuth(false);
    }
}
 
Example 2
Source File: HttpServerExtension.java    From kareldb with Apache License 2.0 6 votes vote down vote up
private static void configureClientAuth(KarelDbConfig config, SslContextFactory sslContextFactory) {
    String clientAuthentication = config.getString(KarelDbConfig.SSL_CLIENT_AUTHENTICATION_CONFIG);

    switch (clientAuthentication) {
        case KarelDbConfig.SSL_CLIENT_AUTHENTICATION_REQUIRED:
            sslContextFactory.setNeedClientAuth(true);
            break;
        case KarelDbConfig.SSL_CLIENT_AUTHENTICATION_REQUESTED:
            sslContextFactory.setWantClientAuth(true);
            break;
        case KarelDbConfig.SSL_CLIENT_AUTHENTICATION_NONE:
            break;
        default:
            throw new ConfigException(
                "Unexpected value for {} configuration: {}",
                KarelDbConfig.SSL_CLIENT_AUTHENTICATION_CONFIG,
                clientAuthentication
            );
    }
}
 
Example 3
Source File: HandleHttpRequest.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
private SslContextFactory createSslFactory(final SSLContextService sslService, final boolean needClientAuth, final boolean wantClientAuth) {
    final SslContextFactory sslFactory = new SslContextFactory();

    sslFactory.setNeedClientAuth(needClientAuth);
    sslFactory.setWantClientAuth(wantClientAuth);

    if (sslService.isKeyStoreConfigured()) {
        sslFactory.setKeyStorePath(sslService.getKeyStoreFile());
        sslFactory.setKeyStorePassword(sslService.getKeyStorePassword());
        sslFactory.setKeyStoreType(sslService.getKeyStoreType());
    }

    if (sslService.isTrustStoreConfigured()) {
        sslFactory.setTrustStorePath(sslService.getTrustStoreFile());
        sslFactory.setTrustStorePassword(sslService.getTrustStorePassword());
        sslFactory.setTrustStoreType(sslService.getTrustStoreType());
    }

    return sslFactory;
}
 
Example 4
Source File: HttpTestUtil.java    From gocd with Apache License 2.0 6 votes vote down vote up
public void httpsConnector(final int port) {
	HttpConfiguration httpsConfig = new HttpConfiguration();
	httpsConfig.setOutputBufferSize(RESPONSE_BUFFER_SIZE); // 32 MB
	httpsConfig.addCustomizer(new SecureRequestCustomizer());

	SslContextFactory sslContextFactory = new SslContextFactory();
	sslContextFactory.setKeyStorePath(serverKeyStore.getAbsolutePath());
	sslContextFactory.setKeyStorePassword(STORE_PASSWORD);
	sslContextFactory.setKeyManagerPassword(STORE_PASSWORD);
	sslContextFactory.setWantClientAuth(true);

	ServerConnector https = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, "http/1.1"), new HttpConnectionFactory(httpsConfig));
	// https.setHost(host);
	https.setPort(port);
	https.setIdleTimeout(MAX_IDLE_TIME);

	server.addConnector(https);
}
 
Example 5
Source File: C2Properties.java    From nifi-minifi with Apache License 2.0 6 votes vote down vote up
public SslContextFactory getSslContextFactory() throws GeneralSecurityException, IOException {
    SslContextFactory sslContextFactory = new SslContextFactory();
    KeyStore keyStore = KeyStore.getInstance(properties.getProperty(MINIFI_C2_SERVER_KEYSTORE_TYPE));
    Path keyStorePath = Paths.get(C2_SERVER_HOME).resolve(properties.getProperty(MINIFI_C2_SERVER_KEYSTORE)).toAbsolutePath();
    logger.debug("keystore path: " + keyStorePath);
    try (InputStream inputStream = Files.newInputStream(keyStorePath)) {
        keyStore.load(inputStream, properties.getProperty(MINIFI_C2_SERVER_KEYSTORE_PASSWD).toCharArray());
    }
    sslContextFactory.setKeyStore(keyStore);
    sslContextFactory.setKeyManagerPassword(properties.getProperty(MINIFI_C2_SERVER_KEY_PASSWD));
    sslContextFactory.setWantClientAuth(true);

    String trustStorePath = Paths.get(C2_SERVER_HOME).resolve(properties.getProperty(MINIFI_C2_SERVER_TRUSTSTORE)).toAbsolutePath().toFile().getAbsolutePath();
    logger.debug("truststore path: " + trustStorePath);
    sslContextFactory.setTrustStorePath(trustStorePath);
    sslContextFactory.setTrustStoreType(properties.getProperty(MINIFI_C2_SERVER_TRUSTSTORE_TYPE));
    sslContextFactory.setTrustStorePassword(properties.getProperty(MINIFI_C2_SERVER_TRUSTSTORE_PASSWD));
    try {
        sslContextFactory.start();
    } catch (Exception e) {
        throw new IOException(e);
    }
    return sslContextFactory;
}
 
Example 6
Source File: PrometheusServer.java    From nifi with Apache License 2.0 6 votes vote down vote up
private SslContextFactory createSslFactory(final SSLContextService sslService, boolean needClientAuth, boolean wantClientAuth) {
    SslContextFactory sslFactory = new SslContextFactory();

    sslFactory.setNeedClientAuth(needClientAuth);
    sslFactory.setWantClientAuth(wantClientAuth);
    sslFactory.setProtocol(sslService.getSslAlgorithm());

    if (sslService.isKeyStoreConfigured()) {
        sslFactory.setKeyStorePath(sslService.getKeyStoreFile());
        sslFactory.setKeyStorePassword(sslService.getKeyStorePassword());
        sslFactory.setKeyStoreType(sslService.getKeyStoreType());
    }

    if (sslService.isTrustStoreConfigured()) {
        sslFactory.setTrustStorePath(sslService.getTrustStoreFile());
        sslFactory.setTrustStorePassword(sslService.getTrustStorePassword());
        sslFactory.setTrustStoreType(sslService.getTrustStoreType());
    }

    return sslFactory;
}
 
Example 7
Source File: AbstractJettyWebSocketService.java    From nifi with Apache License 2.0 6 votes vote down vote up
protected SslContextFactory createSslFactory(final SSLContextService sslService, final boolean needClientAuth, final boolean wantClientAuth, final String endpointIdentificationAlgorithm) {
    final SslContextFactory sslFactory = new SslContextFactory();

    sslFactory.setNeedClientAuth(needClientAuth);
    sslFactory.setWantClientAuth(wantClientAuth);

    // Need to set SslContextFactory's endpointIdentificationAlgorithm.
    // For clients, hostname verification should be enabled.
    // For servers, hostname verification should be disabled.
    // Previous to Jetty 9.4.15.v20190215, this defaulted to null, and now defaults to "HTTPS".
    sslFactory.setEndpointIdentificationAlgorithm(endpointIdentificationAlgorithm);

    if (sslService.isKeyStoreConfigured()) {
        sslFactory.setKeyStorePath(sslService.getKeyStoreFile());
        sslFactory.setKeyStorePassword(sslService.getKeyStorePassword());
        sslFactory.setKeyStoreType(sslService.getKeyStoreType());
    }

    if (sslService.isTrustStoreConfigured()) {
        sslFactory.setTrustStorePath(sslService.getTrustStoreFile());
        sslFactory.setTrustStorePassword(sslService.getTrustStorePassword());
        sslFactory.setTrustStoreType(sslService.getTrustStoreType());
    }

    return sslFactory;
}
 
Example 8
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 9
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 10
Source File: HandleHttpRequest.java    From nifi with Apache License 2.0 5 votes vote down vote up
private SslContextFactory createSslFactory(final SSLContextService sslService, final boolean needClientAuth, final boolean wantClientAuth) {
    final SslContextFactory sslFactory = new SslContextFactory();

    sslFactory.setNeedClientAuth(needClientAuth);
    sslFactory.setWantClientAuth(wantClientAuth);

    sslFactory.setProtocol(sslService.getSslAlgorithm());

    // Need to set SslContextFactory's endpointIdentificationAlgorithm to null; this is a server,
    // not a client.  Server does not need to perform hostname verification on the client.
    // Previous to Jetty 9.4.15.v20190215, this defaulted to null.
    sslFactory.setEndpointIdentificationAlgorithm(null);

    if (sslService.isKeyStoreConfigured()) {
        sslFactory.setKeyStorePath(sslService.getKeyStoreFile());
        sslFactory.setKeyStorePassword(sslService.getKeyStorePassword());
        sslFactory.setKeyStoreType(sslService.getKeyStoreType());
    }

    if (sslService.isTrustStoreConfigured()) {
        sslFactory.setTrustStorePath(sslService.getTrustStoreFile());
        sslFactory.setTrustStorePassword(sslService.getTrustStorePassword());
        sslFactory.setTrustStoreType(sslService.getTrustStoreType());
    }

    return sslFactory;
}
 
Example 11
Source File: JettyHTTPServerEngine.java    From cxf with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("deprecation")
protected void setClientAuthentication(SslContextFactory con,
                                       ClientAuthentication clientAuth) {
    con.setWantClientAuth(true);
    if (clientAuth != null) {
        if (clientAuth.isSetWant()) {
            con.setWantClientAuth(clientAuth.isWant());
        }
        if (clientAuth.isSetRequired()) {
            con.setNeedClientAuth(clientAuth.isRequired());
        }
    }
}
 
Example 12
Source File: CipherAndProtocolSelectionTest.java    From apiman with Apache License 2.0 4 votes vote down vote up
@Before
public void setupJetty() throws Exception {
    server = new Server();
    server.setStopAtShutdown(true);

    http_config = new HttpConfiguration();
    http_config.setSecureScheme("https");

    jettySslContextFactory = new SslContextFactory();
    jettySslContextFactory.setTrustStorePath(getResourcePath("2waytest/mutual_trust_via_ca/common_ts.jks"));
    jettySslContextFactory.setTrustStorePassword("password");
    jettySslContextFactory.setKeyStorePath(getResourcePath("2waytest/mutual_trust_via_ca/service_ks.jks"));
    jettySslContextFactory.setKeyStorePassword("password");
    jettySslContextFactory.setKeyManagerPassword("password");
    // Use default trust store
    // No client auth
    jettySslContextFactory.setNeedClientAuth(false);
    jettySslContextFactory.setWantClientAuth(false);

    HttpConfiguration https_config = new HttpConfiguration(http_config);
    https_config.addCustomizer(new SecureRequestCustomizer());

    ServerConnector sslConnector = new ServerConnector(server,
        new SslConnectionFactory(jettySslContextFactory,"http/1.1"),
        new HttpConnectionFactory(https_config));
    sslConnector.setPort(8008);

    server.addConnector(sslConnector);
    // Thanks to Jetty getting started guide.
    server.setHandler(new AbstractHandler() {

        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException, ServletException {

            jettyRequestAttributes = new HashMap<>();
            Enumeration<String> requestAttrNames = request.getAttributeNames();

            while (requestAttrNames.hasMoreElements()) {
                String elem = requestAttrNames.nextElement();
                jettyRequestAttributes.put(elem, request.getAttribute(elem).toString());
                System.out.println(elem + " - " + request.getAttribute(elem).toString());
            }

            response.setStatus(HttpServletResponse.SC_OK);
            baseRequest.setHandled(true);
            response.getWriter().println("apiman");
        }
    });
}
 
Example 13
Source File: JettyServerWrapper.java    From cougar with Apache License 2.0 4 votes vote down vote up
public void initialiseConnectors() throws Exception {
    threadPool = new QueuedThreadPool();
    threadPool.setMaxThreads(maxThreads);
    threadPool.setMinThreads(minThreads);
    threadPool.setName("JettyThread");
    jettyServer = new Server(threadPool);

    jettyServer.setStopAtShutdown(true);

    MBeanContainer container = new MBeanContainer(mbeanServer);
    jettyServer.addBean(container);

    LowResourceMonitor lowResourcesMonitor = new LowResourceMonitor(jettyServer);
    lowResourcesMonitor.setPeriod(lowResourcesPeriod);
    lowResourcesMonitor.setLowResourcesIdleTimeout(lowResourcesIdleTime);
    lowResourcesMonitor.setMonitorThreads(lowResourcesMonitorThreads);
    lowResourcesMonitor.setMaxConnections(lowResourcesMaxConnections);
    lowResourcesMonitor.setMaxMemory(lowResourcesMaxMemory);
    lowResourcesMonitor.setMaxLowResourcesTime(lowResourcesMaxTime);
    jettyServer.addBean(lowResourcesMonitor);

    // US24803 - Needed for preventing Hashtable key collision DoS CVE-2012-2739
    jettyServer.setAttribute("org.eclipse.jetty.server.Request.maxFormContentSize", maxFormContentSize);

    List<Connector> connectors = new ArrayList<Connector>();

    if (httpPort != -1) {
        httpConfiguration = createHttpConfiguration();
        setBufferSizes(httpConfiguration);
        if (httpForwarded) {
            httpConfiguration.addCustomizer(new ForwardedRequestCustomizer());
        }
        httpConnector = createHttpConnector(jettyServer, httpConfiguration, httpAcceptors, httpSelectors);
        httpConnector.setPort(httpPort);
        httpConnector.setReuseAddress(httpReuseAddress);
        httpConnector.setIdleTimeout(httpMaxIdle);
        httpConnector.setAcceptQueueSize(httpAcceptQueueSize);
        httpConnector.addBean(new ConnectorStatistics());

        connectors.add(httpConnector);
    }

    if (httpsPort != -1) {
        SslContextFactory sslContextFactory = new SslContextFactory();
        sslContextFactory.setKeyStorePath(httpsKeystore.getFile().getCanonicalPath());
        sslContextFactory.setKeyStoreType(httpsKeystoreType);
        sslContextFactory.setKeyStorePassword(httpsKeyPassword);
        if (StringUtils.isNotBlank(httpsCertAlias)) {
            sslContextFactory.setCertAlias(httpsCertAlias);
        }
        sslContextFactory.setKeyManagerPassword(httpsKeyPassword);
        // if you need it then you defo want it
        sslContextFactory.setWantClientAuth(httpsNeedClientAuth || httpsWantClientAuth);
        sslContextFactory.setNeedClientAuth(httpsNeedClientAuth);
        sslContextFactory.setRenegotiationAllowed(httpsAllowRenegotiate);

        httpsConfiguration = createHttpConfiguration();
        setBufferSizes(httpsConfiguration);
        if (httpsForwarded) {
            httpsConfiguration.addCustomizer(new ForwardedRequestCustomizer());
        }

        httpsConnector = createHttpsConnector(jettyServer, httpsConfiguration, httpsAcceptors, httpsSelectors, sslContextFactory);
        httpsConnector.setPort(httpsPort);
        httpsConnector.setReuseAddress(httpsReuseAddress);
        httpsConnector.setIdleTimeout(httpsMaxIdle);
        httpsConnector.setAcceptQueueSize(httpsAcceptQueueSize);
        httpsConnector.addBean(new ConnectorStatistics());

        mbeanServer.registerMBean(getKeystoreCertificateChains(), new ObjectName("CoUGAR.https:name=keyStore"));
        // truststore is not required if we don't want client auth
        if (httpsWantClientAuth) {
            sslContextFactory.setTrustStorePath(httpsTruststore.getFile().getCanonicalPath());
            sslContextFactory.setTrustStoreType(httpsTruststoreType);
            sslContextFactory.setTrustStorePassword(httpsTrustPassword);
            mbeanServer.registerMBean(getTruststoreCertificateChains(), new ObjectName("CoUGAR.https:name=trustStore"));
        }
        connectors.add(httpsConnector);
    }

    if (connectors.size() == 0) {
        throw new IllegalStateException("HTTP transport requires at least one port enabled to function correctly.");
    }

    jettyServer.setConnectors(connectors.toArray(new Connector[connectors.size()]));
}
 
Example 14
Source File: JettyServer.java    From nifi with Apache License 2.0 4 votes vote down vote up
protected static void configureSslContextFactory(SslContextFactory contextFactory, NiFiProperties props) {
    // Need to set SslContextFactory's endpointIdentificationAlgorithm to null; this is a server,
    // not a client.  Server does not need to perform hostname verification on the client.
    // Previous to Jetty 9.4.15.v20190215, this defaulted to null, and now defaults to "HTTPS".
    contextFactory.setEndpointIdentificationAlgorithm(null);

    // Explicitly exclude legacy TLS protocol versions
    // contextFactory.setProtocol(CertificateUtils.getHighestCurrentSupportedTlsProtocolVersion());
    contextFactory.setIncludeProtocols(CertificateUtils.getCurrentSupportedTlsProtocolVersions());
    contextFactory.setExcludeProtocols("TLS", "TLSv1", "TLSv1.1", "SSL", "SSLv2", "SSLv2Hello", "SSLv3");

    // require client auth when not supporting login, Kerberos service, or anonymous access
    if (props.isClientAuthRequiredForRestApi()) {
        contextFactory.setNeedClientAuth(true);
    } else {
        contextFactory.setWantClientAuth(true);
    }

    /* below code sets JSSE system properties when values are provided */
    // keystore properties
    if (StringUtils.isNotBlank(props.getProperty(NiFiProperties.SECURITY_KEYSTORE))) {
        contextFactory.setKeyStorePath(props.getProperty(NiFiProperties.SECURITY_KEYSTORE));
    }
    String keyStoreType = props.getProperty(NiFiProperties.SECURITY_KEYSTORE_TYPE);
    if (StringUtils.isNotBlank(keyStoreType)) {
        contextFactory.setKeyStoreType(keyStoreType);
        String keyStoreProvider = KeyStoreUtils.getKeyStoreProvider(keyStoreType);
        if (StringUtils.isNoneEmpty(keyStoreProvider)) {
            contextFactory.setKeyStoreProvider(keyStoreProvider);
        }
    }
    final String keystorePassword = props.getProperty(NiFiProperties.SECURITY_KEYSTORE_PASSWD);
    final String keyPassword = props.getProperty(NiFiProperties.SECURITY_KEY_PASSWD);
    if (StringUtils.isNotBlank(keystorePassword)) {
        // if no key password was provided, then assume the keystore password is the same as the key password.
        final String defaultKeyPassword = (StringUtils.isBlank(keyPassword)) ? keystorePassword : keyPassword;
        contextFactory.setKeyStorePassword(keystorePassword);
        contextFactory.setKeyManagerPassword(defaultKeyPassword);
    } else if (StringUtils.isNotBlank(keyPassword)) {
        // since no keystore password was provided, there will be no keystore integrity check
        contextFactory.setKeyManagerPassword(keyPassword);
    }

    // truststore properties
    if (StringUtils.isNotBlank(props.getProperty(NiFiProperties.SECURITY_TRUSTSTORE))) {
        contextFactory.setTrustStorePath(props.getProperty(NiFiProperties.SECURITY_TRUSTSTORE));
    }
    String trustStoreType = props.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_TYPE);
    if (StringUtils.isNotBlank(trustStoreType)) {
        contextFactory.setTrustStoreType(trustStoreType);
        String trustStoreProvider = KeyStoreUtils.getKeyStoreProvider(trustStoreType);
        if (StringUtils.isNoneEmpty(trustStoreProvider)) {
            contextFactory.setTrustStoreProvider(trustStoreProvider);
        }
    }
    if (StringUtils.isNotBlank(props.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_PASSWD))) {
        contextFactory.setTrustStorePassword(props.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_PASSWD));
    }
}
 
Example 15
Source File: StandardTLSTest.java    From apiman with Apache License 2.0 4 votes vote down vote up
@Before
public void setupJetty() throws Exception {
    server = new Server();
    server.setStopAtShutdown(true);

    http_config = new HttpConfiguration();
    http_config.setSecureScheme("https");

    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setTrustStorePath(getResourcePath("2waytest/mutual_trust_via_ca/common_ts.jks"));
    sslContextFactory.setTrustStorePassword("password");
    sslContextFactory.setKeyStorePath(getResourcePath("2waytest/mutual_trust_via_ca/service_ks.jks"));
    sslContextFactory.setKeyStorePassword("password");
    sslContextFactory.setKeyManagerPassword("password");
    // Use default trust store
    // No client auth
    sslContextFactory.setNeedClientAuth(false);
    sslContextFactory.setWantClientAuth(false);

    HttpConfiguration https_config = new HttpConfiguration(http_config);
    https_config.addCustomizer(new SecureRequestCustomizer());

    ServerConnector sslConnector = new ServerConnector(server,
        new SslConnectionFactory(sslContextFactory,"http/1.1"),
        new HttpConnectionFactory(https_config));
    sslConnector.setPort(8008);

    server.addConnector(sslConnector);
    // Thanks to Jetty getting started guide.
    server.setHandler(new AbstractHandler() {

        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request,
                HttpServletResponse response) throws IOException, ServletException {

            Enumeration<String> z = request.getAttributeNames();

            while (z.hasMoreElements()) {
                String elem = z.nextElement();
                System.out.println(elem + " - " + request.getAttribute(elem));
            }

            response.setStatus(HttpServletResponse.SC_OK);
            baseRequest.setHandled(true);
            response.getWriter().println("apiman");
        }
    });
    server.start();
}
 
Example 16
Source File: SecureEmbeddedServer.java    From incubator-atlas with Apache License 2.0 4 votes vote down vote up
protected Connector getConnector(int port) throws IOException {
    org.apache.commons.configuration.Configuration config = getConfiguration();

    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath(config.getString(KEYSTORE_FILE_KEY,
            System.getProperty(KEYSTORE_FILE_KEY, DEFAULT_KEYSTORE_FILE_LOCATION)));
    sslContextFactory.setKeyStorePassword(getPassword(config, KEYSTORE_PASSWORD_KEY));
    sslContextFactory.setKeyManagerPassword(getPassword(config, SERVER_CERT_PASSWORD_KEY));
    sslContextFactory.setTrustStorePath(config.getString(TRUSTSTORE_FILE_KEY,
            System.getProperty(TRUSTSTORE_FILE_KEY, DEFATULT_TRUSTORE_FILE_LOCATION)));
    sslContextFactory.setTrustStorePassword(getPassword(config, TRUSTSTORE_PASSWORD_KEY));
    sslContextFactory.setWantClientAuth(config.getBoolean(CLIENT_AUTH_KEY, Boolean.getBoolean(CLIENT_AUTH_KEY)));

    List<Object> cipherList = config.getList(ATLAS_SSL_EXCLUDE_CIPHER_SUITES, DEFAULT_CIPHER_SUITES);
    sslContextFactory.setExcludeCipherSuites(cipherList.toArray(new String[cipherList.size()]));
    sslContextFactory.setRenegotiationAllowed(false);

    String[] excludedProtocols = config.containsKey(ATLAS_SSL_EXCLUDE_PROTOCOLS) ?
            config.getStringArray(ATLAS_SSL_EXCLUDE_PROTOCOLS) : DEFAULT_EXCLUDE_PROTOCOLS;
    if (excludedProtocols != null && excludedProtocols.length > 0) {
        sslContextFactory.addExcludeProtocols(excludedProtocols);
    }

    // SSL HTTP Configuration
    // HTTP Configuration
    HttpConfiguration http_config = new HttpConfiguration();
    http_config.setSecureScheme("https");
    final int bufferSize = AtlasConfiguration.WEBSERVER_REQUEST_BUFFER_SIZE.getInt();
    http_config.setSecurePort(port);
    http_config.setRequestHeaderSize(bufferSize);
    http_config.setResponseHeaderSize(bufferSize);
    http_config.setSendServerVersion(true);
    http_config.setSendDateHeader(false);

    HttpConfiguration https_config = new HttpConfiguration(http_config);
    https_config.addCustomizer(new SecureRequestCustomizer());

    // SSL Connector
    ServerConnector sslConnector = new ServerConnector(server,
        new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
        new HttpConnectionFactory(https_config));
    sslConnector.setPort(port);
    server.addConnector(sslConnector);

    return sslConnector;
}
 
Example 17
Source File: ZTSUtils.java    From athenz with Apache License 2.0 4 votes vote down vote up
public static SslContextFactory createSSLContextObject(final String[] clientProtocols,
        final PrivateKeyStore privateKeyStore) {
    
    String keyStorePath = System.getProperty(ZTSConsts.ZTS_PROP_KEYSTORE_PATH);
    String keyStorePasswordAppName = System.getProperty(ZTSConsts.ZTS_PROP_KEYSTORE_PASSWORD_APPNAME);
    String keyStorePassword = System.getProperty(ZTSConsts.ZTS_PROP_KEYSTORE_PASSWORD);
    String keyStoreType = System.getProperty(ZTSConsts.ZTS_PROP_KEYSTORE_TYPE, "PKCS12");
    String keyManagerPassword = System.getProperty(ZTSConsts.ZTS_PROP_KEYMANAGER_PASSWORD);
    String keyManagerPasswordAppName = System.getProperty(ZTSConsts.ZTS_PROP_KEYMANAGER_PASSWORD_APPNAME);

    String trustStorePath = System.getProperty(ZTSConsts.ZTS_PROP_TRUSTSTORE_PATH);
    String trustStorePassword = System.getProperty(ZTSConsts.ZTS_PROP_TRUSTSTORE_PASSWORD);
    String trustStorePasswordAppName = System.getProperty(ZTSConsts.ZTS_PROP_TRUSTSTORE_PASSWORD_APPNAME);

    String trustStoreType = System.getProperty(ZTSConsts.ZTS_PROP_TRUSTSTORE_TYPE, "PKCS12");
    String excludedCipherSuites = System.getProperty(ZTSConsts.ZTS_PROP_EXCLUDED_CIPHER_SUITES,
            ZTS_DEFAULT_EXCLUDED_CIPHER_SUITES);
    String excludedProtocols = System.getProperty(ZTSConsts.ZTS_PROP_EXCLUDED_PROTOCOLS,
            ZTS_DEFAULT_EXCLUDED_PROTOCOLS);
    boolean wantClientAuth = Boolean.parseBoolean(System.getProperty(ZTSConsts.ZTS_PROP_WANT_CLIENT_CERT, "false"));
    
    SslContextFactory sslContextFactory = new SslContextFactory();
    if (keyStorePath != null) {
        LOGGER.info("createSSLContextObject: using SSL KeyStore path: " + keyStorePath);
        sslContextFactory.setKeyStorePath(keyStorePath);
    }
    
    if (keyStorePassword != null) {
        keyStorePassword = getApplicationSecret(privateKeyStore, keyStorePasswordAppName, keyStorePassword);
        sslContextFactory.setKeyStorePassword(keyStorePassword);
    }
    sslContextFactory.setKeyStoreType(keyStoreType);

    if (keyManagerPassword != null) {
        keyManagerPassword = getApplicationSecret(privateKeyStore, keyManagerPasswordAppName, keyManagerPassword);
        sslContextFactory.setKeyManagerPassword(keyManagerPassword);
    }
    
    if (trustStorePath != null) {
        LOGGER.info("createSSLContextObject: using SSL TrustStore path: " + trustStorePath);
        sslContextFactory.setTrustStorePath(trustStorePath);
    }
    if (trustStorePassword != null) {
        trustStorePassword = getApplicationSecret(privateKeyStore, trustStorePasswordAppName, trustStorePassword);
        sslContextFactory.setTrustStorePassword(trustStorePassword);
    }
    sslContextFactory.setTrustStoreType(trustStoreType);

    sslContextFactory.setExcludeCipherSuites(excludedCipherSuites.split(","));
    sslContextFactory.setExcludeProtocols(excludedProtocols.split(","));

    sslContextFactory.setWantClientAuth(wantClientAuth);
    if (clientProtocols != null) {
        sslContextFactory.setIncludeProtocols(clientProtocols);
    }

    return sslContextFactory;
}
 
Example 18
Source File: SecureEmbeddedServer.java    From atlas with Apache License 2.0 4 votes vote down vote up
@Override
protected Connector getConnector(String host, int port) throws IOException {
    org.apache.commons.configuration.Configuration config = getConfiguration();

    SSLContext sslContext = getSSLContext();
    if (sslContext != null) {
        SSLContext.setDefault(sslContext);
    }

    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath(config.getString(KEYSTORE_FILE_KEY,
            System.getProperty(KEYSTORE_FILE_KEY, DEFAULT_KEYSTORE_FILE_LOCATION)));
    sslContextFactory.setKeyStorePassword(getPassword(config, KEYSTORE_PASSWORD_KEY));
    sslContextFactory.setKeyManagerPassword(getPassword(config, SERVER_CERT_PASSWORD_KEY));
    sslContextFactory.setTrustStorePath(config.getString(TRUSTSTORE_FILE_KEY,
            System.getProperty(TRUSTSTORE_FILE_KEY, DEFATULT_TRUSTORE_FILE_LOCATION)));
    sslContextFactory.setTrustStorePassword(getPassword(config, TRUSTSTORE_PASSWORD_KEY));
    sslContextFactory.setWantClientAuth(config.getBoolean(CLIENT_AUTH_KEY, Boolean.getBoolean(CLIENT_AUTH_KEY)));

    List<Object> cipherList = config.getList(ATLAS_SSL_EXCLUDE_CIPHER_SUITES, DEFAULT_CIPHER_SUITES);
    sslContextFactory.setExcludeCipherSuites(cipherList.toArray(new String[cipherList.size()]));
    sslContextFactory.setRenegotiationAllowed(false);

    String[] excludedProtocols = config.containsKey(ATLAS_SSL_EXCLUDE_PROTOCOLS) ?
            config.getStringArray(ATLAS_SSL_EXCLUDE_PROTOCOLS) : DEFAULT_EXCLUDE_PROTOCOLS;
    if (excludedProtocols != null && excludedProtocols.length > 0) {
        sslContextFactory.addExcludeProtocols(excludedProtocols);
    }

    // SSL HTTP Configuration
    // HTTP Configuration
    HttpConfiguration http_config = new HttpConfiguration();
    http_config.setSecureScheme("https");
    final int bufferSize = AtlasConfiguration.WEBSERVER_REQUEST_BUFFER_SIZE.getInt();
    http_config.setSecurePort(port);
    http_config.setRequestHeaderSize(bufferSize);
    http_config.setResponseHeaderSize(bufferSize);
    http_config.setSendServerVersion(true);
    http_config.setSendDateHeader(false);

    HttpConfiguration https_config = new HttpConfiguration(http_config);
    https_config.addCustomizer(new SecureRequestCustomizer());

    // SSL Connector
    ServerConnector sslConnector = new ServerConnector(server,
        new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()),
        new HttpConnectionFactory(https_config));
    sslConnector.setPort(port);
    server.addConnector(sslConnector);

    return sslConnector;
}
 
Example 19
Source File: JettyServer.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
protected static void configureSslContextFactory(SslContextFactory contextFactory, NiFiProperties props) {
    // require client auth when not supporting login, Kerberos service, or anonymous access
    if (props.isClientAuthRequiredForRestApi()) {
        contextFactory.setNeedClientAuth(true);
    } else {
        contextFactory.setWantClientAuth(true);
    }

    /* below code sets JSSE system properties when values are provided */
    // keystore properties
    if (StringUtils.isNotBlank(props.getProperty(NiFiProperties.SECURITY_KEYSTORE))) {
        contextFactory.setKeyStorePath(props.getProperty(NiFiProperties.SECURITY_KEYSTORE));
    }
    String keyStoreType = props.getProperty(NiFiProperties.SECURITY_KEYSTORE_TYPE);
    if (StringUtils.isNotBlank(keyStoreType)) {
        contextFactory.setKeyStoreType(keyStoreType);
        String keyStoreProvider = KeyStoreUtils.getKeyStoreProvider(keyStoreType);
        if (StringUtils.isNoneEmpty(keyStoreProvider)) {
            contextFactory.setKeyStoreProvider(keyStoreProvider);
        }
    }
    final String keystorePassword = props.getProperty(NiFiProperties.SECURITY_KEYSTORE_PASSWD);
    final String keyPassword = props.getProperty(NiFiProperties.SECURITY_KEY_PASSWD);
    if (StringUtils.isNotBlank(keystorePassword)) {
        // if no key password was provided, then assume the keystore password is the same as the key password.
        final String defaultKeyPassword = (StringUtils.isBlank(keyPassword)) ? keystorePassword : keyPassword;
        contextFactory.setKeyStorePassword(keystorePassword);
        contextFactory.setKeyManagerPassword(defaultKeyPassword);
    } else if (StringUtils.isNotBlank(keyPassword)) {
        // since no keystore password was provided, there will be no keystore integrity check
        contextFactory.setKeyManagerPassword(keyPassword);
    }

    // truststore properties
    if (StringUtils.isNotBlank(props.getProperty(NiFiProperties.SECURITY_TRUSTSTORE))) {
        contextFactory.setTrustStorePath(props.getProperty(NiFiProperties.SECURITY_TRUSTSTORE));
    }
    String trustStoreType = props.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_TYPE);
    if (StringUtils.isNotBlank(trustStoreType)) {
        contextFactory.setTrustStoreType(trustStoreType);
        String trustStoreProvider = KeyStoreUtils.getKeyStoreProvider(trustStoreType);
        if (StringUtils.isNoneEmpty(trustStoreProvider)) {
            contextFactory.setTrustStoreProvider(trustStoreProvider);
        }
    }
    if (StringUtils.isNotBlank(props.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_PASSWD))) {
        contextFactory.setTrustStorePassword(props.getProperty(NiFiProperties.SECURITY_TRUSTSTORE_PASSWD));
    }
}
 
Example 20
Source File: BasicAuthTest.java    From apiman with Apache License 2.0 4 votes vote down vote up
/**
 * With thanks to assistance of http://stackoverflow.com/b/20056601/2766538
 * @throws Exception any exception
 */
@Before
public void setupJetty() throws Exception {
    ContextHandlerCollection handlers = new ContextHandlerCollection();

    ServletContextHandler sch = new ServletContextHandler(ServletContextHandler.SESSIONS);
    sch.setSecurityHandler(createSecurityHandler());
    sch.setContextPath("/echo");
    ServletHolder mockEchoServlet = new ServletHolder(new EchoServlet());
    sch.addServlet(mockEchoServlet, "/*");
    sch.addFilter(AuthenticationFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));

    handlers.addHandler(sch);

    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setTrustStorePath(getResourcePath("common_ts.jks"));
    sslContextFactory.setTrustStorePassword("password");
    sslContextFactory.setKeyStorePath(getResourcePath("service_ks.jks"));
    sslContextFactory.setKeyStorePassword("password");
    sslContextFactory.setKeyManagerPassword("password");
    sslContextFactory.setNeedClientAuth(false);
    sslContextFactory.setWantClientAuth(false);

    // Create the server.
    int serverPort = 8008;
    server = new Server(serverPort);
    server.setStopAtShutdown(true);

    HttpConfiguration http_config = new HttpConfiguration();
    http_config.setSecureScheme("https");
    HttpConfiguration https_config = new HttpConfiguration(http_config);
    https_config.addCustomizer(new SecureRequestCustomizer());
    ServerConnector sslConnector = new ServerConnector(server,
            new SslConnectionFactory(sslContextFactory, "http/1.1"),
            new HttpConnectionFactory(https_config));
    sslConnector.setPort(8009);
    server.addConnector(sslConnector);

    server.setHandler(handlers);
    server.start();

    globalConfig.put(TLSOptions.TLS_DEVMODE, "true");
}