Example usage for javax.net.ssl SSLContext getServerSocketFactory

List of usage examples for javax.net.ssl SSLContext getServerSocketFactory

Introduction

In this page you can find the example usage for javax.net.ssl SSLContext getServerSocketFactory.

Prototype

public final SSLServerSocketFactory getServerSocketFactory() 

Source Link

Document

Returns a ServerSocketFactory object for this context.

Usage

From source file:org.apache.ftpserver.ssl.Ssl.java

/**
 * Create secure server socket./* w  w w  .j av a 2s. c  o m*/
 */
public ServerSocket createServerSocket(String protocol, InetAddress addr, int port) throws Exception {

    // get server socket factory
    SSLContext ctx = getSSLContext(protocol);
    SSLServerSocketFactory ssocketFactory = ctx.getServerSocketFactory();

    // create server socket
    SSLServerSocket serverSocket = null;
    if (addr == null) {
        serverSocket = (SSLServerSocket) ssocketFactory.createServerSocket(port, 100);
    } else {
        serverSocket = (SSLServerSocket) ssocketFactory.createServerSocket(port, 100, addr);
    }

    // initialize server socket
    String cipherSuites[] = serverSocket.getSupportedCipherSuites();
    serverSocket.setEnabledCipherSuites(cipherSuites);
    serverSocket.setNeedClientAuth(m_clientAuthReqd);
    return serverSocket;
}

From source file:org.apache.hadoop.security.Krb5AndCertsSslSocketConnector.java

@Override
protected SSLServerSocketFactory createFactory() throws Exception {
    if (useCerts)
        return super.createFactory();

    SSLContext context = super.getProvider() == null ? SSLContext.getInstance(super.getProtocol())
            : SSLContext.getInstance(super.getProtocol(), super.getProvider());
    context.init(null, null, null);/*from  www  .ja  v a2s.c  o m*/

    return context.getServerSocketFactory();
}

From source file:org.globus.gsi.jsse.SSLConfigurator.java

/**
 * Create an SSLServerSocketFactory based on the configured stores.
 *
 * @return A configured SSLServerSocketFactory
 * @throws GlobusSSLConfigurationException
 *             If we fail to create the server socket factory.
 *///w ww.  ja  v  a2  s .c  o  m
public SSLServerSocketFactory createServerFactory() throws GlobusSSLConfigurationException {
    SSLContext context = getSSLContext();
    return context.getServerSocketFactory();
}

From source file:org.hyperic.hq.bizapp.agent.server.SSLConnectionListener.java

public void setup(int timeout) throws AgentStartException {
    AgentConfig cfg = this.getConfig();
    AgentKeystoreConfig keystoreConfig = new AgentKeystoreConfig();
    SSLProvider provider = new DefaultSSLProviderImpl(keystoreConfig, keystoreConfig.isAcceptUnverifiedCert());
    SSLContext context = provider.getSSLContext();
    SSLServerSocketFactory sFactory = context.getServerSocketFactory();

    InetAddress addr;/*  w  ww.  ja  va2 s  .c  o m*/

    try {
        addr = cfg.getListenIpAsAddr();
    } catch (UnknownHostException exc) {
        throw new AgentStartException(
                "Failed to setup listen socket on '" + cfg.getListenIp() + "': unknown host");
    }

    int port = cfg.getListenPort();
    // Better to retry until this succeeds rather than give up and not allowing
    // the agent to start
    while (true) {
        try {
            listenSock = (SSLServerSocket) sFactory.createServerSocket(port, 50, addr);
            listenSock.setEnabledCipherSuites(
                    getSupportedAndEnabledCiphers(cfg.getEnabledCipherList(), sFactory));
            listenSock.setSoTimeout(timeout);
            break;
        } catch (IOException exc) {
            if (listenSock != null) {
                try {
                    listenSock.close();
                } catch (IOException e1) {
                    log.debug(e1, e1);
                }
            }
            log.warn("Failed to listen at " + cfg.getListenIp() + ":" + port + ": " + exc.getMessage()
                    + ".  Will retry until up.");
            log.debug(exc, exc);
            try {
                Thread.sleep(30000);
            } catch (InterruptedException e) {
                log.debug(e, e);
            }
        }
    }
}

From source file:org.jsslutils.extra.apachetomcat5.JSSLutilsJSSESocketFactory.java

/**
 * Reads the keystore and initializes the SSL socket factory.
 *///  ww  w . jav a 2  s .c o m
void init() throws IOException {
    try {
        String clientAuthStr = (String) attributes.get("clientauth");
        if ("true".equalsIgnoreCase(clientAuthStr) || "yes".equalsIgnoreCase(clientAuthStr)) {
            requireClientAuth = true;
        } else if ("want".equalsIgnoreCase(clientAuthStr)) {
            wantClientAuth = true;
        }

        // SSL protocol variant (e.g., TLS, SSL v3, etc.)
        String protocol = (String) attributes.get("protocol");
        if (protocol == null) {
            protocol = defaultProtocol;
        }

        String keyPassAttr = (String) attributes.get("keypass");

        KeyStoreLoader ksl = KeyStoreLoader.getKeyStoreDefaultLoader();
        String keystoreFileAttr = (String) attributes.get("keystoreFile");
        if (keystoreFileAttr == null)
            keystoreFileAttr = (String) attributes.get("keystore");
        if (keystoreFileAttr != null) {
            ksl.setKeyStorePath(keystoreFileAttr.length() == 0 ? null : keystoreFileAttr);
        }
        String keystorePassAttr = (String) attributes.get("keystorePass");
        if (keystorePassAttr == null)
            keystorePassAttr = keyPassAttr;
        if (keystorePassAttr != null)
            ksl.setKeyStorePassword(keystorePassAttr);
        String keystoreTypeAttr = (String) attributes.get("keystoreType");
        ksl.setKeyStoreType(keystoreTypeAttr != null ? keystoreTypeAttr : KeyStore.getDefaultType());
        String keystoreProviderAttr = (String) attributes.get("keystoreProvider");
        if (keystoreProviderAttr != null) {
            ksl.setKeyStoreProvider(keystoreProviderAttr.length() == 0 ? null : keystoreProviderAttr);
        }

        KeyStoreLoader tsl = KeyStoreLoader.getTrustStoreDefaultLoader();
        String truststoreFileAttr = (String) attributes.get("truststoreFile");
        if (truststoreFileAttr != null) {
            tsl.setKeyStorePath(truststoreFileAttr.length() == 0 ? null : truststoreFileAttr);
        }
        String truststorePassAttr = (String) attributes.get("truststorePass");
        if (truststorePassAttr != null)
            tsl.setKeyStorePassword(truststorePassAttr);
        String truststoreTypeAttr = (String) attributes.get("truststoreType");
        tsl.setKeyStoreType(truststoreTypeAttr != null ? truststoreTypeAttr : KeyStore.getDefaultType());
        String truststoreProviderAttr = (String) attributes.get("truststoreProvider");
        if (truststoreProviderAttr != null) {
            tsl.setKeyStoreProvider(truststoreProviderAttr.length() == 0 ? null : truststoreProviderAttr);
        }

        KeyStore keyStore = ksl.loadKeyStore();
        KeyStore trustStore = tsl.loadKeyStore();

        PKIXSSLContextFactory sslContextFactory = new PKIXSSLContextFactory(keyStore, keyPassAttr, trustStore);

        String crlURLsAttr = (String) attributes.get("crlURLs");
        if (crlURLsAttr != null) {
            StringTokenizer st = new StringTokenizer(crlURLsAttr, " ");
            while (st.hasMoreTokens()) {
                String crlUrl = st.nextToken();
                sslContextFactory.addCrl(crlUrl);
            }
        }

        String acceptAnyCert = (String) attributes.get("acceptAnyCert");
        if ("true".equalsIgnoreCase(acceptAnyCert) || "yes".equalsIgnoreCase(acceptAnyCert)) {
            sslContextFactory.setTrustManagerWrapper(new TrustAllClientsWrappingTrustManager.Wrapper());
        } else {
            String acceptProxyCertsAttr = (String) attributes.get("acceptProxyCerts");
            if ((acceptProxyCertsAttr != null) && (acceptProxyCertsAttr.length() > 0)) {
                boolean allowLegacy = false;
                boolean allowPreRfc = false;
                boolean allowRfc3820 = false;
                String[] acceptProxyTypes = acceptProxyCertsAttr.split(",");
                for (int i = 0; i < acceptProxyTypes.length; i++) {
                    if ("legacy".equalsIgnoreCase(acceptProxyTypes[i].trim())) {
                        allowLegacy = true;
                    }
                    if ("prerfc".equalsIgnoreCase(acceptProxyTypes[i].trim())) {
                        allowPreRfc = true;
                    }
                    if ("rfc3820".equalsIgnoreCase(acceptProxyTypes[i].trim())) {
                        allowRfc3820 = true;
                    }
                }

                if (allowLegacy || allowPreRfc || allowRfc3820) {
                    try {
                        Class<?> wrapperClass = Class
                                .forName("org.jsslutils.extra.gsi.GsiWrappingTrustManager");
                        Constructor<?> constructor = wrapperClass.getConstructor(Boolean.TYPE, Boolean.TYPE,
                                Boolean.TYPE);
                        X509TrustManagerWrapper wrapper = (X509TrustManagerWrapper) constructor
                                .newInstance(allowLegacy, allowPreRfc, allowRfc3820);
                        sslContextFactory.setTrustManagerWrapper(wrapper);
                    } catch (ClassNotFoundException e) {
                        throw new Exception(
                                "Unable to load org.jsslutils.extra.gsi.GsiWrappingTrustManager, please put the required files on the class path.",
                                e);
                    } catch (NoSuchMethodException e) {
                        throw new Exception(
                                "Unable to load org.jsslutils.extra.gsi.GsiWrappingTrustManager, please put the required files on the class path.",
                                e);
                    } catch (SecurityException e) {
                        throw new Exception(
                                "Unable to load org.jsslutils.extra.gsi.GsiWrappingTrustManager, please put the required files on the class path.",
                                e);
                    } catch (ClassCastException e) {
                        throw new Exception(
                                "Unable to load org.jsslutils.extra.gsi.GsiWrappingTrustManager, please put the required files on the class path.",
                                e);
                    }
                }
            }
        }

        // Create and init SSLContext
        SSLContext context = sslContextFactory.buildSSLContext(protocol);

        // create proxy
        sslProxy = context.getServerSocketFactory();

        // Determine which cipher suites to enable
        String requestedCiphers = (String) attributes.get("ciphers");
        enabledCiphers = getEnabledCiphers(requestedCiphers, sslProxy.getSupportedCipherSuites());

    } catch (Exception e) {
        if (e instanceof IOException)
            throw (IOException) e;
        throw new IOException(e.getMessage());
    }
}

From source file:org.lockss.protocol.BlockingStreamComm.java

/** One-time startup configuration  */
private void configure(Configuration config, Configuration prevConfig, Configuration.Differences changedKeys) {
    enabled = config.getBoolean(PARAM_ENABLED, DEFAULT_ENABLED);
    if (!enabled) {
        return;/*from www .j  a v a2s .c o  m*/
    }
    paramMinPoolSize = config.getInt(PARAM_CHANNEL_THREAD_POOL_MIN, DEFAULT_CHANNEL_THREAD_POOL_MIN);
    paramMaxPoolSize = config.getInt(PARAM_CHANNEL_THREAD_POOL_MAX, DEFAULT_CHANNEL_THREAD_POOL_MAX);
    paramPoolKeepaliveTime = config.getTimeInterval(PARAM_CHANNEL_THREAD_POOL_KEEPALIVE,
            DEFAULT_CHANNEL_THREAD_POOL_KEEPALIVE);

    if (config.getBoolean(PARAM_BIND_TO_LOCAL_IP_ONLY, DEFAULT_BIND_TO_LOCAL_IP_ONLY)) {
        bindAddr = config.get(IdentityManager.PARAM_LOCAL_IP);
    }
    sendFromBindAddr = config.getBoolean(PARAM_SEND_FROM_BIND_ADDR, DEFAULT_SEND_FROM_BIND_ADDR);

    if (changedKeys.contains(PARAM_USE_V3_OVER_SSL)) {
        paramUseV3OverSsl = config.getBoolean(PARAM_USE_V3_OVER_SSL, DEFAULT_USE_V3_OVER_SSL);
        sockFact = null;
        // XXX shut down old listen socket, do exponential backoff
        // XXX on bind() to bring up new listen socket
        // XXX then move this to the "change on the fly" above
    }
    if (!paramUseV3OverSsl)
        return;
    log.info("Using SSL");
    // We're trying to use SSL
    if (changedKeys.contains(PARAM_USE_SSL_CLIENT_AUTH)) {
        paramSslClientAuth = config.getBoolean(PARAM_USE_SSL_CLIENT_AUTH, DEFAULT_USE_SSL_CLIENT_AUTH);
        sockFact = null;
    }
    if (sslServerSocketFactory != null && sslSocketFactory != null) {
        // already initialized
        return;
    }

    if (changedKeys.contains(PARAM_SSL_KEYSTORE_NAME) || changedKeys.contains(PARAM_SSL_PRIVATE_KEYSTORE_NAME)
            || changedKeys.contains(PARAM_SSL_PUBLIC_KEYSTORE_NAME)) {
        String name = getOrNull(config, PARAM_SSL_KEYSTORE_NAME);
        String priv = getOrNull(config, PARAM_SSL_PRIVATE_KEYSTORE_NAME);
        String pub = getOrNull(config, PARAM_SSL_PUBLIC_KEYSTORE_NAME);
        if (!StringUtil.isNullString(name)) {
            paramSslPrivateKeyStoreName = name;
            paramSslPublicKeyStoreName = name;
        }
        if (priv != null) {
            if (name != null && !priv.equals(name)) {
                log.warning("Overriding " + PARAM_SSL_KEYSTORE_NAME + ": " + name + " with "
                        + PARAM_SSL_PRIVATE_KEYSTORE_NAME + ": " + priv);
            }
            paramSslPrivateKeyStoreName = priv;
        }
        if (pub != null) {
            if (name != null && !pub.equals(name)) {
                log.warning("Overriding " + PARAM_SSL_KEYSTORE_NAME + ": " + name + " with "
                        + PARAM_SSL_PUBLIC_KEYSTORE_NAME + ": " + pub);
            }
            paramSslPublicKeyStoreName = pub;
        }
        if (StringUtil.equalStrings(paramSslPublicKeyStoreName, paramSslPrivateKeyStoreName)) {
            // so can use == later
            paramSslPrivateKeyStoreName = paramSslPublicKeyStoreName;
            log.debug("Using keystore " + paramSslPrivateKeyStoreName);
        } else {
            log.debug("Using private keystore " + paramSslPrivateKeyStoreName + ", public keystore "
                    + paramSslPublicKeyStoreName);
        }
        sockFact = null;
    }
    if (changedKeys.contains(PARAM_SSL_PROTOCOL)) {
        paramSslProtocol = config.get(PARAM_SSL_PROTOCOL, DEFAULT_SSL_PROTOCOL);
        sockFact = null;
    }
    KeyManagerFactory kmf = keystoreMgr.getKeyManagerFactory(paramSslPrivateKeyStoreName, "LCAP");
    if (kmf == null) {
        throw new IllegalArgumentException("Keystore not found: " + paramSslPrivateKeyStoreName);
    }
    KeyManager[] kma = kmf.getKeyManagers();

    TrustManagerFactory tmf = keystoreMgr.getTrustManagerFactory(paramSslPublicKeyStoreName, "LCAP");
    if (tmf == null) {
        throw new IllegalArgumentException("Keystore not found: " + paramSslPublicKeyStoreName);
    }
    TrustManager[] tma = tmf.getTrustManagers();

    // Now create an SSLContext from the KeyManager
    SSLContext sslContext = null;
    try {
        RandomManager rmgr = getDaemon().getRandomManager();
        SecureRandom rng = rmgr.getSecureRandom();

        sslContext = SSLContext.getInstance(paramSslProtocol);
        sslContext.init(kma, tma, rng);
        // Now create the SSL socket factories from the context
        sslServerSocketFactory = sslContext.getServerSocketFactory();
        sslSocketFactory = sslContext.getSocketFactory();
        log.info("SSL init successful");
    } catch (NoSuchAlgorithmException ex) {
        log.error("Creating SSL context threw " + ex);
        sslContext = null;
    } catch (NoSuchProviderException ex) {
        log.error("Creating SSL context threw " + ex);
        sslContext = null;
    } catch (KeyManagementException ex) {
        log.error("Creating SSL context threw " + ex);
        sslContext = null;
    }
}

From source file:org.opennms.netmgt.provision.server.SSLServer.java

/**
 * <p>init</p>/*from   w w w.  j  a va 2  s .  c  o  m*/
 *
 * @throws java.lang.Exception if any.
 */
@Override
public void init() throws Exception {
    super.init();
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(getKeyManagerAlgorithm(), getKeyManagerProvider());
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    char[] password = getPassword().toCharArray();

    java.io.FileInputStream fis = null;
    try {
        fis = new java.io.FileInputStream(getPathToKeyStore());
        ks.load(fis, password);
    } finally {
        if (fis != null) {
            fis.close();
        }
    }

    kmf.init(ks, password);
    KeyManager[] km = kmf.getKeyManagers();

    SSLContext sslContext = SSLContext.getInstance(getSslContextProtocol());
    sslContext.init(km, null, new SecureRandom());
    SSLServerSocketFactory serverFactory = sslContext.getServerSocketFactory();
    setServerSocket(serverFactory.createServerSocket(getPort()));
    onInit();
}

From source file:org.pepstock.jem.node.security.keystore.KeyStoreUtil.java

/**
 * Returns a SSL socket factory creating asymmetric keys at runtime.
 * /* w w  w  .ja  va  2 s .  co m*/
 * @return a SSL socket factory for HTTPS listener 
 * @throws KeyStoreException if any errors occurs to get keys
 */
public static SSLServerSocketFactory getSSLServerSocketFactory() throws KeyStoreException {
    try {
        // gets a key stores created at runtime
        ByteArrayInputStream baos = SelfSignedCertificate.getCertificate();
        KeyStore keystore = KeyStore.getInstance("jks");
        // loads the keystore
        keystore.load(baos, SelfSignedCertificate.CERTIFICATE_PASSWORD.toCharArray());
        KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());

        // initialiazes the key manager
        kmfactory.init(keystore, SelfSignedCertificate.CERTIFICATE_PASSWORD.toCharArray());
        KeyManager[] keymanagers = kmfactory.getKeyManagers();
        // creates SSL socket factory
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(keymanagers, null, null);
        return sslcontext.getServerSocketFactory();
    } catch (UnrecoverableKeyException e) {
        throw new KeyStoreException(e.getMessage(), e);
    } catch (KeyManagementException e) {
        throw new KeyStoreException(e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        throw new KeyStoreException(e.getMessage(), e);
    } catch (CertificateException e) {
        throw new KeyStoreException(e.getMessage(), e);
    } catch (SecurityException e) {
        throw new KeyStoreException(e.getMessage(), e);
    } catch (IOException e) {
        throw new KeyStoreException(e.getMessage(), e);
    } catch (OperatorCreationException e) {
        throw new KeyStoreException(e.getMessage(), e);
    }
}

From source file:test.integ.be.fedict.commons.eid.client.SSLTest.java

@Test
public void testMutualSSL() throws Exception {

    Security.addProvider(new BeIDProvider());

    final KeyPair serverKeyPair = generateKeyPair();
    final PrivateKey serverPrivateKey = serverKeyPair.getPrivate();
    final DateTime notBefore = new DateTime();
    final DateTime notAfter = notBefore.plusDays(1);
    final X509Certificate serverCertificate = generateCACertificate(serverKeyPair, "CN=Test", notBefore,
            notAfter);//from   w w w .  j  a  v a2s.c o  m

    final KeyManager keyManager = new ServerTestX509KeyManager(serverPrivateKey, serverCertificate);
    final TrustManager trustManager = new ServerTestX509TrustManager();
    final SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(new KeyManager[] { keyManager }, new TrustManager[] { trustManager }, new SecureRandom());

    final SSLServerSocketFactory sslServerSocketFactory = sslContext.getServerSocketFactory();

    final int serverPort = 8443;
    final SSLServerSocket sslServerSocket = (SSLServerSocket) sslServerSocketFactory
            .createServerSocket(serverPort);

    sslServerSocket.setNeedClientAuth(true);

    final TestRunnable testRunnable = new TestRunnable(serverPort);
    final Thread thread = new Thread(testRunnable);
    thread.start();

    SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
    LOG.debug("server accepted");
    InputStream inputStream = sslSocket.getInputStream();
    int result = inputStream.read();
    LOG.debug("result: " + result);
    assertEquals(12, result);
    SSLSession sslSession = sslSocket.getSession();
    sslSession.invalidate();
    sslSocket = (SSLSocket) sslServerSocket.accept();
    inputStream = sslSocket.getInputStream();
    result = inputStream.read();
    LOG.debug("result: " + result);
    assertEquals(34, result);
}