List of usage examples for javax.net.ssl SSLSocket setNeedClientAuth
public abstract void setNeedClientAuth(boolean need);
From source file:net.lightbody.bmp.proxy.jetty.http.ClientCertAuthenticator.java
/** * @return UserPrinciple if authenticated or null if not. If * Authentication fails, then the authenticator may have committed * the response as an auth challenge or redirect. * @exception IOException //from w w w . j a va 2 s. com */ public Principal authenticate(UserRealm realm, String pathInContext, HttpRequest request, HttpResponse response) throws IOException { java.security.cert.X509Certificate[] certs = (java.security.cert.X509Certificate[]) request .getAttribute("javax.servlet.request.X509Certificate"); if (response != null && (certs == null || certs.length == 0 || certs[0] == null)) { // No certs available so lets try and force the issue // Get the SSLSocket Object s = HttpConnection.getHttpConnection().getConnection(); if (!(s instanceof SSLSocket)) return null; SSLSocket socket = (SSLSocket) s; if (!socket.getNeedClientAuth()) { // Need to re-handshake socket.setNeedClientAuth(true); socket.startHandshake(); // Need to wait here - but not forever. The Handshake // Listener API does not look like a good option to // avoid waiting forever. So we will take a slightly // busy timelimited approach. For now: for (int i = (_maxHandShakeSeconds * 4); i-- > 0;) { certs = (java.security.cert.X509Certificate[]) request .getAttribute("javax.servlet.request.X509Certificate"); if (certs != null && certs.length > 0 && certs[0] != null) break; try { Thread.sleep(250); } catch (Exception e) { break; } } } } if (certs == null || certs.length == 0 || certs[0] == null) return null; Principal principal = certs[0].getSubjectDN(); if (principal == null) principal = certs[0].getIssuerDN(); String username = principal == null ? "clientcert" : principal.getName(); Principal user = realm.authenticate(username, certs, request); request.setAuthType(SecurityConstraint.__CERT_AUTH); if (user != null) request.setAuthUser(user.getName()); request.setUserPrincipal(user); return user; }
From source file:com.mendhak.gpslogger.common.network.CertificateValidationWorkflow.java
private void connectToSSLSocket(Socket plainSocket) throws IOException { SSLSocketFactory factory = Networks.getSocketFactory(context); SSLSocket socket = (SSLSocket) factory.createSocket(host, port); if (plainSocket != null) { socket = (SSLSocket) factory.createSocket(plainSocket, host, port, true); }/* w ww . jav a2 s.c o m*/ if (serverType == ServerType.SMTP) { socket.setUseClientMode(true); socket.setNeedClientAuth(true); } socket.setSoTimeout(5000); LOG.debug("Starting handshake..."); socket.startHandshake(); SSLSession session = socket.getSession(); Certificate[] servercerts = session.getPeerCertificates(); }
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!"); }// www . ja va 2 s .com 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; }
From source file:org.apache.ftpserver.ssl.Ssl.java
/** * Returns a socket layered over an existing socket. *//*from w w w . j av a 2s .c o m*/ public Socket createSocket(String protocol, Socket soc, boolean clientMode) throws Exception { // already wrapped - no need to do anything if (soc instanceof SSLSocket) { return soc; } // get socket factory SSLContext ctx = getSSLContext(protocol); SSLSocketFactory socFactory = ctx.getSocketFactory(); // create socket String host = soc.getInetAddress().getHostAddress(); int port = soc.getLocalPort(); SSLSocket ssoc = (SSLSocket) socFactory.createSocket(soc, host, port, true); ssoc.setUseClientMode(clientMode); // initialize socket String cipherSuites[] = ssoc.getSupportedCipherSuites(); ssoc.setEnabledCipherSuites(cipherSuites); ssoc.setNeedClientAuth(m_clientAuthReqd); return ssoc; }
From source file:org.apache.tomcat.util.net.jsse.JSSESocketFactory.java
public Socket acceptSocket(ServerSocket socket) throws IOException { SSLSocket asock = null; try {//from w ww .j a v a 2 s . c o m asock = (SSLSocket) socket.accept(); asock.setNeedClientAuth(clientAuth); } catch (SSLException e) { throw new SocketException("SSL handshake error" + e.toString()); } return asock; }
From source file:org.beepcore.beep.profile.tls.jsse.TLSProfileJSSE.java
public void receiveMSG(MessageMSG msg) { Channel channel = msg.getChannel(); InputDataStreamAdapter is = msg.getDataStream().getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String data;//from w w w . j a va 2 s.co m try { try { data = reader.readLine(); } catch (IOException e) { msg.sendERR(BEEPError.CODE_PARAMETER_ERROR, "Error reading data"); return; } if (data.equals(READY1) == false && data.equals(READY2) == false) { msg.sendERR(BEEPError.CODE_PARAMETER_INVALID, "Expected READY element"); } this.begin(channel); msg.sendRPY(new StringOutputDataStream(PROCEED2)); } catch (BEEPException e1) { channel.getSession().terminate("unable to send ERR"); return; } try { Socket oldSocket = ((TCPSession) channel.getSession()).getSocket(); /** @TODO add support for serverName */ SSLSocket newSocket = (SSLSocket) socketFactory.createSocket(oldSocket, oldSocket.getInetAddress().getHostName(), oldSocket.getPort(), true); BeepListenerHCL l = new BeepListenerHCL(channel); newSocket.addHandshakeCompletedListener(l); newSocket.setUseClientMode(false); newSocket.setNeedClientAuth(needClientAuth); newSocket.setEnabledCipherSuites(newSocket.getSupportedCipherSuites()); if (sslProtocols != null) { newSocket.setEnabledProtocols(sslProtocols); } newSocket.startHandshake(); } catch (IOException e) { channel.getSession().terminate("TLS error: " + e.getMessage()); return; } }
From source file:org.beepcore.beep.profile.tls.jsse.TLSProfileJSSE.java
/** * start a channel for the TLS profile. Besides issuing the * channel start request, it also performs the initiator side * chores necessary to begin encrypted communication using TLS * over a session. Parameters regarding the type of encryption * and whether or not authentication is required are specified * using the profile configuration passed to the <code>init</code> * method Upon returning, all traffic over the session will be * entrusted as per these parameters.<p> * * @see #init init - profile configuration * @param session The session to encrypt communcation for * * @return new <code>Session</code> with TLS negotiated. * @throws BEEPException an error occurs during the channel start * request or the TLS handshake (such as trying to negotiate an * anonymous connection with a peer that doesn't support an * anonymous cipher suite).//from w w w . ja v a 2 s .c o m */ public TCPSession startTLS(TCPSession session) throws BEEPException { Channel ch = startChannel(session, uri, false, READY2, null); // See if we got start data back String data = ch.getStartData(); if (log.isDebugEnabled()) { log.debug("Got start data of " + data); } // Consider the data (see if it's proceed) if ((data == null) || (!data.equals(PROCEED1) && !data.equals(PROCEED2))) { log.error("Invalid reply: " + data); throw new BEEPException(ERR_EXPECTED_PROCEED); } // Freeze IO and get the socket and reset it to TLS Socket oldSocket = session.getSocket(); SSLSocket newSocket = null; TLSHandshake l = new TLSHandshake(); // create the SSL Socket try { newSocket = (SSLSocket) socketFactory.createSocket(oldSocket, oldSocket.getInetAddress().getHostName(), oldSocket.getPort(), true); newSocket.addHandshakeCompletedListener(l); newSocket.setUseClientMode(true); newSocket.setNeedClientAuth(needClientAuth); newSocket.setEnabledCipherSuites(newSocket.getSupportedCipherSuites()); if (this.sslProtocols != null) { newSocket.setEnabledProtocols(sslProtocols); } // set up so the handshake listeners will be called l.session = session; log.debug("Handshake starting"); newSocket.startHandshake(); log.debug("Handshake returned"); synchronized (l) { if (!l.notifiedHandshake) { l.waitingForHandshake = true; l.wait(); l.waitingForHandshake = false; } } log.debug("Handshake done waiting"); } catch (javax.net.ssl.SSLException e) { log.error(e); throw new BEEPException(e); } catch (java.io.IOException e) { log.error(e); throw new BEEPException(ERR_TLS_SOCKET); } catch (InterruptedException e) { log.error(e); throw new BEEPException(ERR_TLS_HANDSHAKE_WAIT); } // swap it out for the new one with TLS enabled. if (abortSession) { session.close(); throw new BEEPException(ERR_TLS_NO_AUTHENTICATION); } else { Hashtable hash = new Hashtable(); hash.put(SessionTuningProperties.ENCRYPTION, "true"); SessionTuningProperties tuning = new SessionTuningProperties(hash); return (TCPSession) reset(session, generateCredential(), l.cred, tuning, session.getProfileRegistry(), newSocket); } }