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

The following examples show how to use org.eclipse.jetty.util.ssl.SslContextFactory#setNeedClientAuth() . 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: 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 2
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 3
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 4
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 5
Source File: TestServer.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
private void createSecureConnector(final Map<String, String> sslProperties) {
    SslContextFactory ssl = new SslContextFactory();

    if (sslProperties.get(StandardSSLContextService.KEYSTORE.getName()) != null) {
        ssl.setKeyStorePath(sslProperties.get(StandardSSLContextService.KEYSTORE.getName()));
        ssl.setKeyStorePassword(sslProperties.get(StandardSSLContextService.KEYSTORE_PASSWORD.getName()));
        ssl.setKeyStoreType(sslProperties.get(StandardSSLContextService.KEYSTORE_TYPE.getName()));
    }

    if (sslProperties.get(StandardSSLContextService.TRUSTSTORE.getName()) != null) {
        ssl.setTrustStorePath(sslProperties.get(StandardSSLContextService.TRUSTSTORE.getName()));
        ssl.setTrustStorePassword(sslProperties.get(StandardSSLContextService.TRUSTSTORE_PASSWORD.getName()));
        ssl.setTrustStoreType(sslProperties.get(StandardSSLContextService.TRUSTSTORE_TYPE.getName()));
    }

    final String clientAuth = sslProperties.get(NEED_CLIENT_AUTH);
    if (clientAuth == null) {
        ssl.setNeedClientAuth(true);
    } else {
        ssl.setNeedClientAuth(Boolean.parseBoolean(clientAuth));
    }

    // build the connector
    final ServerConnector https = new ServerConnector(jetty, ssl);

    // set host and port
    https.setPort(0);
    // Severely taxed environments may have significant delays when executing.
    https.setIdleTimeout(30000L);

    // add the connector
    jetty.addConnector(https);

    // mark secure as enabled
    secure = true;
}
 
Example 6
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 7
Source File: RestChangeIngestor.java    From nifi-minifi with Apache License 2.0 5 votes vote down vote up
private void createSecureConnector(Properties properties) {
    SslContextFactory ssl = new SslContextFactory();

    if (properties.getProperty(KEYSTORE_LOCATION_KEY) != null) {
        ssl.setKeyStorePath(properties.getProperty(KEYSTORE_LOCATION_KEY));
        ssl.setKeyStorePassword(properties.getProperty(KEYSTORE_PASSWORD_KEY));
        ssl.setKeyStoreType(properties.getProperty(KEYSTORE_TYPE_KEY));
    }

    if (properties.getProperty(TRUSTSTORE_LOCATION_KEY) != null) {
        ssl.setTrustStorePath(properties.getProperty(TRUSTSTORE_LOCATION_KEY));
        ssl.setTrustStorePassword(properties.getProperty(TRUSTSTORE_PASSWORD_KEY));
        ssl.setTrustStoreType(properties.getProperty(TRUSTSTORE_TYPE_KEY));
        ssl.setNeedClientAuth(Boolean.parseBoolean(properties.getProperty(NEED_CLIENT_AUTH_KEY, "true")));
    }

    // build the connector
    final ServerConnector https = new ServerConnector(jetty, ssl);

    // set host and port
    https.setPort(Integer.parseInt(properties.getProperty(PORT_KEY, "0")));
    https.setHost(properties.getProperty(HOST_KEY, "localhost"));

    // Severely taxed environments may have significant delays when executing.
    https.setIdleTimeout(30000L);

    // add the connector
    jetty.addConnector(https);

    logger.info("Added an https connector on the host '{}' and port '{}'", new Object[]{https.getHost(), https.getPort()});
}
 
Example 8
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 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: TestWebServicesFetcher.java    From datacollector with Apache License 2.0 5 votes vote down vote up
protected SslContextFactory createSslContextFactory(boolean clientAuth) {
  SslContextFactory sslContextFactory = new SslContextFactory();
  sslContextFactory.setKeyStorePath(new File(getConfDir(), "serverKS.jks").getAbsolutePath());
  sslContextFactory.setKeyStorePassword("serverKSPassword");
  sslContextFactory.setKeyManagerPassword("serverKeyPassword");
  sslContextFactory.setTrustStorePath(new File(getConfDir(), "trustKS.jks").getAbsolutePath());
  sslContextFactory.setTrustStorePassword("trustKSPassword");
  if (clientAuth) {
    sslContextFactory.setNeedClientAuth(true);
  }
  return sslContextFactory;
}
 
Example 11
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 12
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 13
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 14
Source File: TestServer.java    From nifi with Apache License 2.0 4 votes vote down vote up
private void createSecureConnector(final Map<String, String> sslProperties) {
    SslContextFactory ssl = new SslContextFactory();

    if (sslProperties.get(StandardSSLContextService.KEYSTORE.getName()) != null) {
        ssl.setKeyStorePath(sslProperties.get(StandardSSLContextService.KEYSTORE.getName()));
        ssl.setKeyStorePassword(sslProperties.get(StandardSSLContextService.KEYSTORE_PASSWORD.getName()));
        ssl.setKeyStoreType(sslProperties.get(StandardSSLContextService.KEYSTORE_TYPE.getName()));
    }

    if (sslProperties.get(StandardSSLContextService.TRUSTSTORE.getName()) != null) {
        ssl.setTrustStorePath(sslProperties.get(StandardSSLContextService.TRUSTSTORE.getName()));
        ssl.setTrustStorePassword(sslProperties.get(StandardSSLContextService.TRUSTSTORE_PASSWORD.getName()));
        ssl.setTrustStoreType(sslProperties.get(StandardSSLContextService.TRUSTSTORE_TYPE.getName()));
    }

    final String clientAuth = sslProperties.get(NEED_CLIENT_AUTH);
    if (clientAuth == null) {
        ssl.setNeedClientAuth(true);
    } else {
        ssl.setNeedClientAuth(Boolean.parseBoolean(clientAuth));
    }

    // 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".
    ssl.setEndpointIdentificationAlgorithm(null);

    // build the connector
    final ServerConnector https = new ServerConnector(jetty, ssl);

    // set host and port
    https.setPort(0);
    // Severely taxed environments may have significant delays when executing.
    https.setIdleTimeout(30000L);

    // add the connector
    jetty.addConnector(https);

    // mark secure as enabled
    secure = true;
}
 
Example 15
Source File: SSLUtilsTest.java    From athenz with Apache License 2.0 4 votes vote down vote up
private static JettyServer createHttpsJettyServer(boolean clientAuth) throws IOException {
    Server server = new Server();
    HttpConfiguration https_config = new HttpConfiguration();
    https_config.setSecureScheme("https");
    int port;
    try (ServerSocket socket = new ServerSocket(0)) {
        port = socket.getLocalPort();
    }
    https_config.setSecurePort(port);
    https_config.setOutputBufferSize(32768);

    SslContextFactory sslContextFactory = new SslContextFactory();
    File keystoreFile = new File(DEFAULT_SERVER_KEY_STORE);
    if (!keystoreFile.exists()) {
        throw new FileNotFoundException();
    }

    String trustStorePath = DEFAULT_CA_TRUST_STORE;
    File trustStoreFile = new File(trustStorePath);
    if (!trustStoreFile.exists()) {
        throw new FileNotFoundException();
    }

    sslContextFactory.setEndpointIdentificationAlgorithm(null);

    sslContextFactory.setTrustStorePath(trustStorePath);
    sslContextFactory.setTrustStoreType(DEFAULT_SSL_STORE_TYPE);
    sslContextFactory.setTrustStorePassword(DEFAULT_CERT_PWD);

    sslContextFactory.setKeyStorePath(keystoreFile.getAbsolutePath());
    sslContextFactory.setKeyStoreType(DEFAULT_SSL_STORE_TYPE);
    sslContextFactory.setKeyStorePassword(DEFAULT_CERT_PWD);

    sslContextFactory.setProtocol(DEFAULT_SSL_PROTOCOL);
    sslContextFactory.setNeedClientAuth(clientAuth);

    ServerConnector https = new ServerConnector(server,
            new SslConnectionFactory(sslContextFactory,HttpVersion.HTTP_1_1.asString()),
            new HttpConnectionFactory(https_config));
    https.setPort(port);
    https.setIdleTimeout(500000);
    server.setConnectors(new Connector[] { https });
    HandlerList handlers = new HandlerList();
    ResourceHandler resourceHandler = new ResourceHandler();
    resourceHandler.setBaseResource(Resource.newResource("."));
    handlers.setHandlers(new Handler[]
            { resourceHandler, new DefaultHandler() });
    server.setHandler(handlers);
    return new JettyServer(server, port);
}
 
Example 16
Source File: BasicMutualAuthTest.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 {
    server = new Server();
    server.setStopAtShutdown(true);

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

    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath(getResourcePath("2waytest/basic_mutual_auth/service_ks.jks"));

    sslContextFactory.setKeyStorePassword("password");
    sslContextFactory.setKeyManagerPassword("password");
    sslContextFactory.setTrustStorePath(getResourcePath("2waytest/basic_mutual_auth/service_ts.jks"));
    sslContextFactory.setTrustStorePassword("password");
    sslContextFactory.setNeedClientAuth(true);

    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));
            }

            if (request.getAttribute("javax.servlet.request.X509Certificate") != null) {
                clientSerial = ((java.security.cert.X509Certificate[]) request
                        .getAttribute("javax.servlet.request.X509Certificate"))[0].getSerialNumber();
            }

            response.setStatus(HttpServletResponse.SC_OK);
            baseRequest.setHandled(true);
            response.getWriter().println("apiman");
        }
    });
    server.start();
}
 
Example 17
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 18
Source File: CAMutualAuthTest.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.setKeyStorePath(getResourcePath("2waytest/mutual_trust_via_ca/service_ks.jks"));
    sslContextFactory.setKeyStorePassword("password");
    sslContextFactory.setKeyManagerPassword("password");
    sslContextFactory.setTrustStorePath(getResourcePath("2waytest/mutual_trust_via_ca/common_ts.jks"));
    sslContextFactory.setTrustStorePassword("password");
    sslContextFactory.setNeedClientAuth(true);

    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 19
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");
}
 
Example 20
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();
}