Example usage for javax.net.ssl SSLServerSocket setNeedClientAuth

List of usage examples for javax.net.ssl SSLServerSocket setNeedClientAuth

Introduction

In this page you can find the example usage for javax.net.ssl SSLServerSocket setNeedClientAuth.

Prototype

public abstract void setNeedClientAuth(boolean need);

Source Link

Document

Controls whether accepted server-mode SSLSockets will be initially configured to require client authentication.

Usage

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    SSLServerSocket ss = (SSLServerSocket) ssf.createServerSocket(443);
    ss.setNeedClientAuth(true);
    while (true) {
        Socket s = ss.accept();//from   w  ww  . jav  a 2  s. c om

        SSLSession session = ((SSLSocket) s).getSession();
        Certificate[] cchain = session.getPeerCertificates();
        for (int j = 0; j < cchain.length; j++) {
            System.out.println(((X509Certificate) cchain[j]).getSubjectDN());
        }
        PrintStream out = new PrintStream(s.getOutputStream());
        BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
        String info = null;
        while ((info = in.readLine()) != null) {
            System.out.println("now got " + info);
            if (info.equals(""))
                break;
        }

        out.println("HTTP/1.0 200 OK\nMIME_version:1.0");
        out.println("Content_Type:text/html");
        String c = "<html> <head></head><body> <h1> Hi,</h1></Body></html>";
        out.println("Content_Length:" + c.length());
        out.println("");
        out.println(c);
        out.close();
        s.close();
        in.close();
    }
}

From source file:MainClass.java

public static void main(String[] args) throws IOException {
    SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    SSLServerSocket ss = (SSLServerSocket) ssf.createServerSocket(8080);
    ss.setNeedClientAuth(true);

    while (true) {
        try {/*from   w  ww  .  j  a  va  2 s .c  om*/
            Socket s = ss.accept();
            OutputStream out = s.getOutputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
            String line = null;
            while (((line = in.readLine()) != null) && (!("".equals(line)))) {
                System.out.println(line);
            }
            System.out.println("");

            StringBuffer buffer = new StringBuffer();
            buffer.append("<HTML>\n");
            buffer.append("<HEAD><TITLE>HTTPS Server</TITLE></HEAD>\n");
            buffer.append("<BODY>\n");
            buffer.append("<H1>Success!</H1>\n");
            buffer.append("</BODY>\n");
            buffer.append("</HTML>\n");

            String string = buffer.toString();
            byte[] data = string.getBytes();
            out.write("HTTP/1.0 200 OK\n".getBytes());
            out.write(new String("Content-Length: " + data.length + "\n").getBytes());
            out.write("Content-Type: text/html\n\n".getBytes());
            out.write(data);
            out.flush();

            out.close();
            in.close();
            s.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:com.adito.server.jetty.CustomJsseListener.java

protected ServerSocket newServerSocket(InetAddrPort p_address, int p_acceptQueueSize) throws IOException {
    SSLServerSocket serverSocket = (SSLServerSocket) super.newServerSocket(p_address, p_acceptQueueSize);
    if (serverSocket.getNeedClientAuth()) {

        serverSocket.setNeedClientAuth(require);
        setNeedClientAuth(require);// w  ww.  jav  a  2 s . c o  m
        if (!require)
            serverSocket.setWantClientAuth(true);
    }

    String[] ciphers = serverSocket.getSupportedCipherSuites();
    String[] protocols = serverSocket.getSupportedProtocols();

    if (log.isInfoEnabled()) {
        log.info("The following protocols are supported:");
        for (int i = 0; i < protocols.length; i++) {
            log.info("     " + protocols[i]);
        }
    }

    if (createAvailableCipherSuitesList) {
        File f = new File(ContextHolder.getContext().getTempDirectory(), "availableCipherSuites.txt");
        BufferedWriter writer = null;

        try {
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f)));
            if (log.isInfoEnabled())
                log.info("The following cipher suites are supported:");
            for (int i = 0; i < ciphers.length; i++) {
                if (log.isInfoEnabled())
                    log.info("     " + ciphers[i]);
                writer.write(ciphers[i]);
                writer.newLine();
            }
        } catch (Throwable e) {
            log.error("Could not create cipher list!", e);
            configureContext = false;
        } finally {
            if (writer != null)
                writer.close();
        }
        createAvailableCipherSuitesList = false;
    }

    if (configureContext) {

        PropertyList list = ContextHolder.getContext().getConfig()
                .retrievePropertyList(new ContextKey("ssl.supportedProtocols"));

        if (!list.isEmpty()) {
            serverSocket.setEnabledProtocols(list.asArray());
        }

        list = ContextHolder.getContext().getConfig()
                .retrievePropertyList(new ContextKey("ssl.supportedCiphers"));

        if (!list.isEmpty()) {
            serverSocket.setEnabledCipherSuites(list.asArray());
        }
    }

    protocols = serverSocket.getEnabledProtocols();

    if (log.isInfoEnabled()) {
        log.info("The following protocols are enabled:");
        for (int i = 0; i < protocols.length; i++) {
            log.info("     " + protocols[i]);
        }
    }

    ciphers = serverSocket.getEnabledCipherSuites();
    if (log.isInfoEnabled()) {
        log.info("The following cipher suites are enabled:");
        for (int i = 0; i < ciphers.length; i++) {
            log.info("     " + ciphers[i]);
        }
    }

    return serverSocket;
}

From source file:net.lightbody.bmp.proxy.jetty.http.JsseListener.java

/**
 * @param p_address/*  w w  w .  j  av a  2 s  .c  o m*/
 * @param p_acceptQueueSize
 * @return
 * @exception IOException
 */
protected ServerSocket newServerSocket(InetAddrPort p_address, int p_acceptQueueSize) throws IOException {
    SSLServerSocketFactory factory = null;
    SSLServerSocket socket = null;

    try {
        factory = createFactory();

        if (p_address == null) {
            socket = (SSLServerSocket) factory.createServerSocket(0, p_acceptQueueSize);
        } else {
            socket = (SSLServerSocket) factory.createServerSocket(p_address.getPort(), p_acceptQueueSize,
                    p_address.getInetAddress());
        }

        socket.setNeedClientAuth(_needClientAuth);
        log.info("JsseListener.needClientAuth=" + _needClientAuth);
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        log.warn(LogSupport.EXCEPTION, e);
        throw new IOException("Could not create JsseListener: " + e.toString());
    }
    return socket;
}

From source file:net.jradius.server.TCPListener.java

public void setConfiguration(ListenerConfigurationItem cfg, boolean noKeepAlive)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException,
        KeyManagementException, IOException {
    keepAlive = !noKeepAlive;/*  w  w w  .j av a 2  s.  c  o m*/
    config = cfg;

    Map props = config.getProperties();

    String s = (String) props.get("port");
    if (s != null)
        port = new Integer(s).intValue();

    s = (String) props.get("backlog");
    if (s != null)
        backlog = new Integer(s).intValue();

    if (keepAlive) {
        s = (String) props.get("keepAlive");
        if (s != null)
            keepAlive = new Boolean(s).booleanValue();
    }

    String useSSL = (String) props.get("useSSL");
    String trustAll = (String) props.get("trustAll");

    if (requiresSSL || "true".equalsIgnoreCase(useSSL)) {
        KeyManager[] keyManagers = null;
        TrustManager[] trustManagers = null;

        String keyManager = (String) props.get("keyManager");

        if (keyManager != null && keyManager.length() > 0) {
            try {
                KeyManager manager = (KeyManager) Configuration.getBean(keyManager);
                keyManagers = new KeyManager[] { manager };
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            String keystore = (String) props.get("keyStore");
            String keystoreType = (String) props.get("keyStoreType");
            String keystorePassword = (String) props.get("keyStorePassword");
            String keyPassword = (String) props.get("keyPassword");

            if (keystore != null) {
                if (keystoreType == null)
                    keystoreType = "pkcs12";

                KeyStore ks = KeyStore.getInstance(keystoreType);
                ks.load(new FileInputStream(keystore),
                        keystorePassword == null ? null : keystorePassword.toCharArray());

                KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
                kmf.init(ks, keyPassword == null ? null : keyPassword.toCharArray());
                keyManagers = kmf.getKeyManagers();
            }
        }

        String trustManager = (String) props.get("trustManager");

        if (trustManager != null && trustManager.length() > 0) {
            try {
                TrustManager manager = (TrustManager) Configuration.getBean(trustManager);
                trustManagers = new TrustManager[] { manager };
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if ("true".equalsIgnoreCase(trustAll)) {
            trustManagers = new TrustManager[] { new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] chain, String authType) {

                }

                public void checkServerTrusted(X509Certificate[] chain, String authType) {

                }

                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            } };
        } else {
            String keystore = (String) props.get("caStore");
            String keystoreType = (String) props.get("caStoreType");
            String keystorePassword = (String) props.get("caStorePassword");

            if (keystore != null) {
                if (keystoreType == null)
                    keystoreType = "pkcs12";

                KeyStore caKeys = KeyStore.getInstance(keystoreType);
                caKeys.load(new FileInputStream(keystore),
                        keystorePassword == null ? null : keystorePassword.toCharArray());
                TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
                tmf.init(caKeys);
                trustManagers = tmf.getTrustManagers();
            }
        }

        SSLContext sslContext = SSLContext.getInstance("SSLv3");
        sslContext.init(keyManagers, trustManagers, null);

        ServerSocketFactory socketFactory = sslContext.getServerSocketFactory();
        SSLServerSocket sslServerSocket = (SSLServerSocket) socketFactory.createServerSocket(port, backlog);
        serverSocket = sslServerSocket;

        if (sslWantClientAuth)
            sslServerSocket.setWantClientAuth(true);

        if (sslNeedClientAuth)
            sslServerSocket.setNeedClientAuth(true);

        if (sslEnabledProtocols != null)
            sslServerSocket.setEnabledProtocols(sslEnabledProtocols);

        if (sslEnabledCiphers != null)
            sslServerSocket.setEnabledCipherSuites(sslEnabledCiphers);

        usingSSL = true;
    } else {
        serverSocket = new ServerSocket(port, backlog);
    }

    serverSocket.setReuseAddress(true);
    setActive(true);
}

From source file:net.lightbody.bmp.proxy.jetty.http.SslListener.java

/**
 * @param p_address/*ww w.jav a  2s.  co m*/
 * @param p_acceptQueueSize
 * @return @exception IOException
 */
protected ServerSocket newServerSocket(InetAddrPort p_address, int p_acceptQueueSize) throws IOException {
    SSLServerSocketFactory factory = null;
    SSLServerSocket socket = null;

    try {
        factory = createFactory();

        if (p_address == null) {
            socket = (SSLServerSocket) factory.createServerSocket(0, p_acceptQueueSize);
        } else {
            socket = (SSLServerSocket) factory.createServerSocket(p_address.getPort(), p_acceptQueueSize,
                    p_address.getInetAddress());
        }

        if (_needClientAuth)
            socket.setNeedClientAuth(true);
        else if (_wantClientAuth)
            socket.setWantClientAuth(true);

        if (cipherSuites != null && cipherSuites.length > 0) {
            socket.setEnabledCipherSuites(cipherSuites);
            for (int i = 0; i < cipherSuites.length; i++) {
                log.debug("SslListener enabled ciphersuite: " + cipherSuites[i]);
            }
        }
    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        log.warn(LogSupport.EXCEPTION, e);
        throw new IOException("Could not create JsseListener: " + e.toString());
    }
    return socket;
}

From source file:org.nectarframework.base.service.nanohttp.NanoHttpService.java

/**
 * Creates an SSLSocketFactory for HTTPS. Pass a KeyStore resource with your
 * certificate and passphrase//from   www .j  a  v  a  2s .c  o m
 */
public ServerSocket makeSSLServerSocket(String keyAndTrustStoreClasspathPath, char[] passphrase)
        throws IOException {
    try {
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        InputStream keystoreStream = new FileInputStream(new File(keyAndTrustStoreClasspathPath));

        keystore.load(keystoreStream, passphrase);
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keystore, passphrase);

        SSLServerSocketFactory res = null;
        try {
            TrustManagerFactory trustManagerFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerFactory.init(keystore);
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
            res = ctx.getServerSocketFactory();

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

        SSLServerSocket ss = null;
        ss = (SSLServerSocket) res.createServerSocket();
        ss.setEnabledProtocols(ss.getSupportedProtocols());
        ss.setUseClientMode(false);
        ss.setWantClientAuth(false);
        ss.setNeedClientAuth(false);

        return ss;

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

From source file:com.predic8.membrane.core.transport.ssl.SSLContext.java

public ServerSocket createServerSocket(int port, int backlog, InetAddress bindAddress) throws IOException {
    SSLServerSocketFactory sslssf = sslc.getServerSocketFactory();
    SSLServerSocket sslss = (SSLServerSocket) sslssf.createServerSocket(port, backlog, bindAddress);
    applyCiphers(sslss);/*from  ww  w  .  j  a v  a  2 s .c o m*/
    if (protocols != null) {
        sslss.setEnabledProtocols(protocols);
    } else {
        String[] protocols = sslss.getEnabledProtocols();
        Set<String> set = new HashSet<String>();
        for (String protocol : protocols) {
            if (protocol.equals("SSLv3") || protocol.equals("SSLv2Hello")) {
                continue;
            }
            set.add(protocol);
        }
        sslss.setEnabledProtocols(set.toArray(new String[0]));
    }
    sslss.setWantClientAuth(wantClientAuth);
    sslss.setNeedClientAuth(needClientAuth);
    return sslss;
}

From source file:net.timewalker.ffmq4.listeners.tcp.io.TcpListener.java

private ServerSocket createServerSocket(int port, int tcpBackLog, InetAddress localAddr, boolean useSSL)
        throws JMSException {
    try {/* w ww  . j a va  2 s . com*/
        if (useSSL) {
            SSLServerSocket socket = (SSLServerSocket) createSSLContext().getServerSocketFactory()
                    .createServerSocket(port, tcpBackLog, localAddr);
            socket.setNeedClientAuth(false);
            return socket;
        } else
            return new ServerSocket(port, tcpBackLog, localAddr);
    } catch (Exception e) {
        throw new FFMQException("Cannot create server socket", "NETWORK_ERROR", e);
    }
}

From source file:org.apache.cassandra.security.SSLFactory.java

public static SSLServerSocket getServerSocket(EncryptionOptions options, InetAddress address, int port)
        throws IOException {
    SSLContext ctx = createSSLContext(options, true);
    SSLServerSocket serverSocket = (SSLServerSocket) ctx.getServerSocketFactory().createServerSocket();
    serverSocket.setReuseAddress(true);// w  ww .j a  va  2 s . c o  m
    String[] suits = filterCipherSuites(serverSocket.getSupportedCipherSuites(), options.cipher_suites);
    serverSocket.setEnabledCipherSuites(suits);
    serverSocket.setNeedClientAuth(options.require_client_auth);
    serverSocket.setEnabledProtocols(ACCEPTED_PROTOCOLS);
    serverSocket.bind(new InetSocketAddress(address, port), 500);
    return serverSocket;
}