Example usage for javax.net.ssl SSLSocket setWantClientAuth

List of usage examples for javax.net.ssl SSLSocket setWantClientAuth

Introduction

In this page you can find the example usage for javax.net.ssl SSLSocket setWantClientAuth.

Prototype

public abstract void setWantClientAuth(boolean want);

Source Link

Document

Configures the socket to request client authentication.

Usage

From source file:net.jmhertlein.mcanalytics.console.gui.LoginPane.java

@FXML
public void onLoginButtonPressed(ActionEvent event) {
    HostEntry selected = hostList.getSelectionModel().getSelectedItem();
    if (selected == null)
        return;//from  w ww  . ja va 2s.  c  om

    try {
        SSLContext ctx = SSLUtil.buildClientContext(trust);
        SSLSocket raw = (SSLSocket) ctx.getSocketFactory().createSocket(selected.getUrl(), selected.getPort());
        raw.setWantClientAuth(true);
        try {
            System.out.println("Starting handshake...");
            raw.startHandshake();
        } catch (SSLException ssle) {
            if (ssle.getCause() instanceof UntrustedCertificateException) {
                System.out.println("Got the correct exception");
                UntrustedCertificateException uce = (UntrustedCertificateException) ssle.getCause();
                CertTrustPromptDialog dlg = new CertTrustPromptDialog(trust,
                        (X509Certificate) uce.getChain()[0]);
                dlg.showAndWait();
                System.out.println("DIALOG RETURNED");
            }
            return;
        }

        PrintWriter out = new PrintWriter(raw.getOutputStream());
        BufferedReader in = new BufferedReader(new InputStreamReader(raw.getInputStream()));
        APISocket sock = new APISocket(out, in);
        app.setAPISocket(sock);
        sock.startListener();

        //handle authentication
        boolean hasCert = false;
        FutureRequest<AuthenticationResult> login;
        if (trust.isCertificateEntry(selected.getUrl())) {
            try {
                ((X509Certificate) trust.getCertificate(selected.getUrl())).checkValidity();
                hasCert = true;
            } catch (CertificateExpiredException | CertificateNotYetValidException ex) {
                Logger.getLogger(LoginPane.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        System.out.println("Has cert: " + hasCert);
        KeyPair newPair = null;
        String username;

        if (hasCert) {
            username = SSLUtil.getCNs((X509Certificate) trust.getCertificate(selected.getUrl())).iterator()
                    .next();
            login = sock.submit(new AuthenticationRequest(username));
            System.out.println("Logging in w/ cert. CN: " + username + ", URL: " + selected.getUrl());
        } else if (rememberLoginBox.isSelected()) {
            newPair = SSLUtil.newECDSAKeyPair();
            username = usernameField.getText();
            PKCS10CertificationRequest csr = SSLUtil.newCertificateRequest(
                    SSLUtil.newX500Name(username, selected.getUrl(), "mcanalytics"), newPair);
            login = sock
                    .submit(new AuthenticationRequest(usernameField.getText(), passwordField.getText(), csr));
            System.out.println("Logging in with: " + usernameField.getText() + " + " + passwordField.getText()
                    + " and requesting a cert.");
        } else {
            username = usernameField.getText();
            login = sock.submit(new AuthenticationRequest(username, passwordField.getText()));
            System.out.println("Logging in with: " + username + " + " + passwordField.getText());
        }

        try {
            boolean success = login.get().getSuccess();
            if (success) {
                System.out.println("Login successful");
                if (login.get().hasCertificate()) {
                    trust.setCertificateEntry(selected.getUrl(), login.get().getCert());
                    trust.setKeyEntry(selected.getUrl() + "-private", newPair.getPrivate(), new char[0],
                            new Certificate[] { login.get().getCert(), login.get().getCA() });
                    System.out.println("Stored a trusted cert from server.");
                }
            } else {
                System.out.println("Login failed.");
                Dialog dlg = new Dialog();
                dlg.setTitle("Login Failed");
                dlg.setContentText("Could not login- invalid login credentials.");
                dlg.showAndWait();
                return;
            }
        } catch (InterruptedException | ExecutionException | KeyStoreException ex) {
            Logger.getLogger(LoginPane.class.getName()).log(Level.SEVERE, null, ex);
            Dialogs.showMessage("Connection Error", "Connection Error", ex.getMessage(), ex.toString());
            System.out.println("Login error.");
            return;
        }
        //auth done

        Stage window = (Stage) loginButton.getScene().getWindow();
        window.setScene(new Scene(new ChartPane(username, sock)));
        window.show();
    } catch (IOException | KeyStoreException ex) {
        Logger.getLogger(LoginPane.class.getName()).log(Level.SEVERE, null, ex);
        Dialog dlg = new Dialog();
        dlg.setTitle("Connection Error");
        dlg.setContentText(ex.getMessage());
        dlg.showAndWait();
        System.out.println("Login error.");
        return;
    }
}

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

@Override
public Socket wrapAcceptedSocket(Socket socket) throws IOException {
    InputStream ins = socket.getInputStream();

    byte[] buffer = new byte[0xFF];
    int position = 0;
    SSLCapabilities capabilities = null;

    // Read the header of TLS record
    while (position < SSLExplorer.RECORD_HEADER_SIZE) {
        int count = SSLExplorer.RECORD_HEADER_SIZE - position;
        int n = ins.read(buffer, position, count);
        if (n < 0) {
            throw new IOException("unexpected end of stream!");
        }//  w  ww .ja  v  a 2  s. co  m
        position += n;
    }

    // Get the required size to explore the SSL capabilities
    int recordLength = SSLExplorer.getRequiredSize(buffer, 0, position);
    if (buffer.length < recordLength) {
        buffer = Arrays.copyOf(buffer, recordLength);
    }

    while (position < recordLength) {
        int count = recordLength - position;
        int n = ins.read(buffer, position, count);
        if (n < 0) {
            throw new IOException("unexpected end of stream!");
        }
        position += n;
    }

    capabilities = SSLExplorer.explore(buffer, 0, recordLength);

    SSLContext sslContext = null;

    if (capabilities != null) {
        List<SNIServerName> serverNames = capabilities.getServerNames();
        if (serverNames != null && serverNames.size() > 0) {
            OUTER: for (SNIServerName snisn : serverNames) {
                String hostname = new String(snisn.getEncoded(), "UTF-8");
                for (int i = 0; i < dnsNames.size(); i++)
                    if (dnsNames.get(i).matcher(hostname).matches()) {
                        sslContext = sslContexts.get(i);
                        break OUTER;
                    }
            }
            if (sslContext == null) {
                // no hostname matched: send 'unrecognized_name' alert and close socket

                byte[] alert_unrecognized_name = { 21 /* alert */, 3, 1 /* TLS 1.0 */, 0,
                        2 /* length: 2 bytes */, 2 /* fatal */, 112 /* unrecognized_name */ };

                try {
                    socket.getOutputStream().write(alert_unrecognized_name);
                } finally {
                    socket.close();
                }

                StringBuilder hostname = null;
                for (SNIServerName snisn : serverNames) {
                    if (hostname == null)
                        hostname = new StringBuilder();
                    else
                        hostname.append(", ");
                    hostname.append(new String(snisn.getEncoded(), "UTF-8"));
                }

                throw new RuntimeException(
                        "no certificate configured (sending unrecognized_name alert) for hostname \"" + hostname
                                + "\"");
            }
        }
    }

    // no Server Name Indication used by the client: fall back to first sslContext
    if (sslContext == null)
        sslContext = sslContexts.get(0);

    SSLSocketFactory serviceSocketFac = sslContext.getSocketFactory();

    ByteArrayInputStream bais = new ByteArrayInputStream(buffer, 0, position);

    SSLSocket serviceSocket;
    // "serviceSocket = (SSLSocket)serviceSocketFac.createSocket(socket, bais, true);" only compileable with Java 1.8
    try {
        serviceSocket = (SSLSocket) createSocketMethod.invoke(serviceSocketFac,
                new Object[] { socket, bais, true });
    } catch (IllegalArgumentException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(e);
    }

    sslContext.applyCiphers(serviceSocket);
    if (sslContext.getProtocols() != null) {
        serviceSocket.setEnabledProtocols(sslContext.getProtocols());
    } else {
        String[] protocols = serviceSocket.getEnabledProtocols();
        Set<String> set = new HashSet<String>();
        for (String protocol : protocols) {
            if (protocol.equals("SSLv3") || protocol.equals("SSLv2Hello")) {
                continue;
            }
            set.add(protocol);
        }
        serviceSocket.setEnabledProtocols(set.toArray(new String[0]));
    }
    serviceSocket.setWantClientAuth(sslContext.isWantClientAuth());
    serviceSocket.setNeedClientAuth(sslContext.isNeedClientAuth());

    return serviceSocket;
}