Example usage for javax.net.ssl SSLSocket startHandshake

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

Introduction

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

Prototype

public abstract void startHandshake() throws IOException;

Source Link

Document

Starts an SSL handshake on this connection.

Usage

From source file:com.android.emailcommon.utility.SSLSocketFactory.java

@Override
public Socket connectSocket(final Socket sock, final String host, final int port,
        final InetAddress localAddress, int localPort, final HttpParams params) throws IOException {

    if (host == null) {
        throw new IllegalArgumentException("Target host may not be null.");
    }//from w  w  w. j a  v a2  s .com
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null.");
    }

    SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket());

    if ((localAddress != null) || (localPort > 0)) {

        // we need to bind explicitly
        if (localPort < 0)
            localPort = 0; // indicates "any"

        InetSocketAddress isa = new InetSocketAddress(localAddress, localPort);
        sslsock.bind(isa);
    }

    int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
    int soTimeout = HttpConnectionParams.getSoTimeout(params);

    InetSocketAddress remoteAddress;
    if (nameResolver != null) {
        remoteAddress = new InetSocketAddress(nameResolver.resolve(host), port);
    } else {
        remoteAddress = new InetSocketAddress(host, port);
    }

    sslsock.connect(remoteAddress, connTimeout);

    sslsock.setSoTimeout(soTimeout);

    // Set Server Name Indication if is available for this socket
    setSocketHostname(sslsock, host);

    // Start handshake prior to hostname verification to ensure
    // handshake exceptions do not get silenced by hostname verification.
    sslsock.startHandshake();

    try {
        hostnameVerifier.verify(host, sslsock);
        // verifyHostName() didn't blowup - good!
    } catch (IOException iox) {
        // close the socket before re-throwing the exception
        try {
            sslsock.close();
        } catch (Exception x) {
            /*ignore*/ }
        throw iox;
    }

    return sslsock;
}

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).//  w w w.  j a  v  a2s  .  c om
 */
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);
    }
}

From source file:org.apache.nutch.protocol.http.HttpResponse.java

/**
 * Default public constructor./*from  ww  w  . j  av a 2s  . c  o m*/
 *
 * @param http
 * @param url
 * @param datum
 * @throws ProtocolException
 * @throws IOException
 */
public HttpResponse(HttpBase http, URL url, CrawlDatum datum) throws ProtocolException, IOException {

    this.http = http;
    this.url = url;
    this.orig = url.toString();
    this.base = url.toString();

    Scheme scheme = null;

    if ("http".equals(url.getProtocol())) {
        scheme = Scheme.HTTP;
    } else if ("https".equals(url.getProtocol())) {
        scheme = Scheme.HTTPS;
    } else {
        throw new HttpException("Unknown scheme (not http/https) for url:" + url);
    }

    if (Http.LOG.isTraceEnabled()) {
        Http.LOG.trace("fetching " + url);
    }

    String path = "".equals(url.getFile()) ? "/" : url.getFile();

    // some servers will redirect a request with a host line like
    // "Host: <hostname>:80" to "http://<hpstname>/<orig_path>"- they
    // don't want the :80...

    LOG.info("Fetching " + url.toString());

    String host = url.getHost();
    int port;
    String portString;
    if (url.getPort() == -1) {
        if (scheme == Scheme.HTTP) {
            port = 80;
        } else {
            port = 443;
        }
        portString = "";
    } else {
        port = url.getPort();
        portString = ":" + port;
    }
    Socket socket = null;

    try {
        socket = new Socket(); // create the socket
        socket.setSoTimeout(http.getTimeout());

        // connect
        String sockHost = http.useProxy(url) ? http.getProxyHost() : host;
        int sockPort = http.useProxy(url) ? http.getProxyPort() : port;
        InetSocketAddress sockAddr = new InetSocketAddress(sockHost, sockPort);
        socket.connect(sockAddr, http.getTimeout());

        if (scheme == Scheme.HTTPS) {
            SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
            SSLSocket sslsocket = (SSLSocket) factory.createSocket(socket, sockHost, sockPort, true);
            sslsocket.setUseClientMode(true);

            // Get the protocols and ciphers supported by this JVM
            Set<String> protocols = new HashSet<String>(Arrays.asList(sslsocket.getSupportedProtocols()));
            Set<String> ciphers = new HashSet<String>(Arrays.asList(sslsocket.getSupportedCipherSuites()));

            // Intersect with preferred protocols and ciphers
            protocols.retainAll(http.getTlsPreferredProtocols());
            ciphers.retainAll(http.getTlsPreferredCipherSuites());

            sslsocket.setEnabledProtocols(protocols.toArray(new String[protocols.size()]));
            sslsocket.setEnabledCipherSuites(ciphers.toArray(new String[ciphers.size()]));

            sslsocket.startHandshake();
            socket = sslsocket;
        }

        this.conf = http.getConf();
        if (sockAddr != null && conf.getBoolean("store.ip.address", false) == true) {
            headers.add("_ip_", sockAddr.getAddress().getHostAddress());
        }

        // make request
        OutputStream req = socket.getOutputStream();

        StringBuffer reqStr = new StringBuffer("GET ");
        if (http.useProxy(url)) {
            reqStr.append(url.getProtocol() + "://" + host + portString + path);
        } else {
            reqStr.append(path);
        }

        reqStr.append(" HTTP/1.0\r\n");

        reqStr.append("Host: ");
        reqStr.append(host);
        reqStr.append(portString);
        reqStr.append("\r\n");

        reqStr.append("Accept-Encoding: x-gzip, gzip, deflate\r\n");

        String userAgent = http.getUserAgent();
        if ((userAgent == null) || (userAgent.length() == 0)) {
            if (Http.LOG.isErrorEnabled()) {
                Http.LOG.error("User-agent is not set!");
            }
        } else {
            reqStr.append("User-Agent: ");
            reqStr.append(userAgent);
            reqStr.append("\r\n");
        }

        reqStr.append("Accept-Language: ");
        reqStr.append(this.http.getAcceptLanguage());
        reqStr.append("\r\n");

        reqStr.append("Accept: ");
        reqStr.append(this.http.getAccept());
        reqStr.append("\r\n");

        if (http.isIfModifiedSinceEnabled() && datum.getModifiedTime() > 0) {
            reqStr.append("If-Modified-Since: " + HttpDateFormat.toString(datum.getModifiedTime()));
            reqStr.append("\r\n");
        }
        reqStr.append("\r\n");

        // store the request in the metadata?
        if (conf.getBoolean("store.http.request", false) == true) {
            headers.add("_request_", reqStr.toString());
        }

        byte[] reqBytes = reqStr.toString().getBytes();

        req.write(reqBytes);
        req.flush();

        LOG.info("Processing response..");

        PushbackInputStream in = // process response
                new PushbackInputStream(new BufferedInputStream(socket.getInputStream(), Http.BUFFER_SIZE),
                        Http.BUFFER_SIZE);

        StringBuffer line = new StringBuffer();

        // store the http headers verbatim
        if (conf.getBoolean("store.http.headers", false) == true) {
            httpHeaders = new StringBuffer();
        }

        headers.add("nutch.fetch.time", Long.toString(System.currentTimeMillis()));

        boolean haveSeenNonContinueStatus = false;
        while (!haveSeenNonContinueStatus) {
            // parse status code line
            this.code = parseStatusLine(in, line);
            if (httpHeaders != null)
                httpHeaders.append(line).append("\n");
            // parse headers
            parseHeaders(in, line, httpHeaders);
            haveSeenNonContinueStatus = code != 100; // 100 is "Continue"
        }

        if (httpHeaders != null) {
            headers.add("_response.headers_", httpHeaders.toString());
        }

        String transferEncoding = getHeader(Response.TRANSFER_ENCODING);
        LOG.info("Transfer Encoding for " + url + ":" + transferEncoding);
        if (transferEncoding != null && "chunked".equalsIgnoreCase(transferEncoding.trim())) {
            readChunkedContent(in, line);
        } else {
            readPlainContent(in);
        }

        String contentEncoding = getHeader(Response.CONTENT_ENCODING);
        if ("gzip".equals(contentEncoding) || "x-gzip".equals(contentEncoding)) {
            content = http.processGzipEncoded(content, url);
        } else if ("deflate".equals(contentEncoding)) {
            content = http.processDeflateEncoded(content, url);
        } else {
            if (Http.LOG.isTraceEnabled()) {
                Http.LOG.trace("fetched " + content.length + " bytes from " + url);
            }
        }

        LOG.info("Checking URL:" + url.toString());
        //check if url contains google drive string
        if (url.toString().toLowerCase().contains("https://drive.google.com/")) {
            //split into two string separated by '=' to get the article id
            LOG.info("Google Drive URL Detected!");
            String[] parts = url.toString().split("=");
            url = new URL("http://drive.google.com/uc?export=download&id=" + parts[1]);

            LOG.info("New URL:" + url.toString());
            this.http = http;
            this.url = url;
            this.orig = url.toString();
            this.base = url.toString();

            HttpClient client = new HttpClient();
            GetMethod method = new GetMethod(url.toString());
            int statusCode = client.executeMethod(method);
            content = method.getResponseBody();
            LOG.info("File Size on Drive: " + content.length);
            //   return;

        }

        LOG.info("Fetch Bytes: " + content.length + " bytes from " + url);

    } finally {
        if (socket != null)
            socket.close();
    }

}

From source file:com.serphacker.serposcope.scraper.http.extensions.ScrapClientSSLConnectionFactory.java

@Override
public Socket createLayeredSocket(final Socket socket, final String target, final int port,
        final HttpContext context) throws IOException {

    SSLSocketFactory sslSocketFactory = insecure ? insecoreSSLSocketfactory : defaultSSLSocketFactory;

    final SSLSocket sslsock = (SSLSocket) sslSocketFactory.createSocket(socket, target, port, true);

    if (supportedProtocols != null) {
        sslsock.setEnabledProtocols(supportedProtocols);
    } else {/*w w  w . j  a  v  a 2  s.com*/
        // If supported protocols are not explicitly set, remove all SSL protocol versions
        final String[] allProtocols = sslsock.getEnabledProtocols();
        final List<String> enabledProtocols = new ArrayList<String>(allProtocols.length);
        for (String protocol : allProtocols) {
            if (!protocol.startsWith("SSL")) {
                enabledProtocols.add(protocol);
            }
        }
        if (!enabledProtocols.isEmpty()) {
            sslsock.setEnabledProtocols(enabledProtocols.toArray(new String[enabledProtocols.size()]));
        }
    }
    if (supportedCipherSuites != null) {
        sslsock.setEnabledCipherSuites(supportedCipherSuites);
    }

    if (this.log.isDebugEnabled()) {
        this.log.debug("Enabled protocols: " + Arrays.asList(sslsock.getEnabledProtocols()));
        this.log.debug("Enabled cipher suites:" + Arrays.asList(sslsock.getEnabledCipherSuites()));
    }

    prepareSocket(sslsock);
    this.log.debug("Starting handshake");
    sslsock.startHandshake();
    verifyHostname(sslsock, target);
    return sslsock;
}

From source file:org.apache.nutch.protocol.s2jh.HttpResponse.java

public HttpResponse(HttpBase http, URL url, WebPage page) throws ProtocolException, IOException {
    conf = http.getConf();// w  ww  . j  av  a2  s . c  om
    this.http = http;
    this.url = url;
    Scheme scheme = null;

    if ("http".equals(url.getProtocol())) {
        scheme = Scheme.HTTP;
    } else if ("https".equals(url.getProtocol())) {
        scheme = Scheme.HTTPS;
    } else {
        throw new HttpException("Unknown scheme (not http/https) for url:" + url);
    }

    if (Http.LOG.isTraceEnabled()) {
        Http.LOG.trace("fetching " + url);
    }

    String path = "".equals(url.getFile()) ? "/" : url.getFile();

    // some servers will redirect a request with a host line like
    // "Host: <hostname>:80" to "http://<hpstname>/<orig_path>"- they
    // don't want the :80...

    String host = url.getHost();
    int port;
    String portString;
    if (url.getPort() == -1) {
        if (scheme == Scheme.HTTP) {
            port = 80;
        } else {
            port = 443;
        }
        portString = "";
    } else {
        port = url.getPort();
        portString = ":" + port;
    }
    Socket socket = null;

    try {
        socket = new Socket(); // create the socket
        socket.setSoTimeout(http.getTimeout());

        // connect
        String sockHost = http.useProxy() ? http.getProxyHost() : host;
        int sockPort = http.useProxy() ? http.getProxyPort() : port;
        InetSocketAddress sockAddr = new InetSocketAddress(sockHost, sockPort);
        socket.connect(sockAddr, http.getTimeout());

        if (scheme == Scheme.HTTPS) {
            SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
            SSLSocket sslsocket = (SSLSocket) factory.createSocket(socket, sockHost, sockPort, true);
            sslsocket.setUseClientMode(true);

            // Get the protocols and ciphers supported by this JVM
            Set<String> protocols = new HashSet<String>(Arrays.asList(sslsocket.getSupportedProtocols()));
            Set<String> ciphers = new HashSet<String>(Arrays.asList(sslsocket.getSupportedCipherSuites()));

            // Intersect with preferred protocols and ciphers
            protocols.retainAll(http.getTlsPreferredProtocols());
            ciphers.retainAll(http.getTlsPreferredCipherSuites());

            sslsocket.setEnabledProtocols(protocols.toArray(new String[protocols.size()]));
            sslsocket.setEnabledCipherSuites(ciphers.toArray(new String[ciphers.size()]));

            sslsocket.startHandshake();
            socket = sslsocket;
        }

        if (sockAddr != null && conf.getBoolean("store.ip.address", false) == true) {
            String ipString = sockAddr.getAddress().getHostAddress(); // get the ip
                                                                      // address
            page.getMetadata().put(new Utf8("_ip_"), ByteBuffer.wrap(ipString.getBytes()));
        }

        Http.LOG.debug("HTTP fetching: " + url);
        // make request
        OutputStream req = socket.getOutputStream();

        StringBuffer reqStr = new StringBuffer("GET ");
        if (http.useProxy()) {
            reqStr.append(url.getProtocol() + "://" + host + portString + path);
        } else {
            reqStr.append(path);
        }

        reqStr.append(" HTTP/1.0\r\n");

        reqStr.append("Host: ");
        reqStr.append(host);
        reqStr.append(portString);
        reqStr.append("\r\n");

        reqStr.append("Accept-Encoding: x-gzip, gzip\r\n");

        reqStr.append("Accept: ");
        reqStr.append(this.http.getAccept());
        reqStr.append("\r\n");

        String userAgent = http.getUserAgent();
        if ((userAgent == null) || (userAgent.length() == 0)) {
            if (Http.LOG.isErrorEnabled()) {
                Http.LOG.error("User-agent is not set!");
            }
        } else {
            reqStr.append("User-Agent: ");
            reqStr.append(userAgent);
            reqStr.append("\r\n");
        }

        // if (page.isReadable(WebPage.Field.MODIFIED_TIME.getIndex())) {
        reqStr.append("If-Modified-Since: " + HttpDateFormat.toString(page.getModifiedTime()));
        reqStr.append("\r\n");
        // }
        reqStr.append("\r\n");

        byte[] reqBytes = reqStr.toString().getBytes();

        req.write(reqBytes);
        req.flush();

        PushbackInputStream in = // process response
                new PushbackInputStream(new BufferedInputStream(socket.getInputStream(), Http.BUFFER_SIZE),
                        Http.BUFFER_SIZE);

        StringBuffer line = new StringBuffer();

        boolean haveSeenNonContinueStatus = false;
        while (!haveSeenNonContinueStatus) {
            // parse status code line
            this.code = parseStatusLine(in, line);
            // parse headers
            parseHeaders(in, line);
            haveSeenNonContinueStatus = code != 100; // 100 is "Continue"
        }

        if (!url.toString().endsWith("robots.txt")) {
            if (readPlainContent(url.toString(), in)) {
            } else if (readPlainContentByHtmlunit(url)) {
            } else {
                readPlainContentByWebDriver(url);
            }
        }

        if (content != null && content.length > 0) {
            String html = charset == null ? new String(content) : new String(content, charset);
            //System.out.println("URL: " + url + ", CharsetName: " + charset + " , Page HTML=\n" + html);
            Http.LOG_HTML.trace("URL: " + url + ", CharsetName: " + charset + " , Page HTML=\n" + html);
        }

        // add headers in metadata to row
        if (page.getHeaders() != null) {
            page.getHeaders().clear();
        }
        for (String key : headers.names()) {
            page.getHeaders().put(new Utf8(key), new Utf8(headers.get(key)));
        }

    } catch (Exception e) {
        Http.LOG.error(e.getMessage(), e);
    } finally {
        if (socket != null)
            socket.close();
    }

}

From source file:org.dcache.srm.client.FlexibleCredentialSSLConnectionSocketFactory.java

@Override
public Socket createLayeredSocket(final Socket socket, final String target, final int port,
        final HttpContext context) throws IOException {

    final X509Credential credential = (X509Credential) context
            .getAttribute(HttpClientTransport.TRANSPORT_HTTP_CREDENTIALS);
    if (credential == null) {
        throw new IOException("Client credentials are missing from context.");
    }//  ww w . ja v a2s.  co  m
    final SSLContext sslContext;
    try {
        sslContext = contextProvider.getContext(credential);
    } catch (GeneralSecurityException e) {
        throw new IOException("Failed to create SSLContext: " + e.getMessage(), e);
    }
    final SSLSocket sslsock = (SSLSocket) sslContext.getSocketFactory().createSocket(socket, target, port,
            true);
    if (supportedProtocols != null) {
        sslsock.setEnabledProtocols(supportedProtocols);
    } else {
        // If supported protocols are not explicitly set, remove all SSL protocol versions
        final String[] allProtocols = sslsock.getEnabledProtocols();
        final List<String> enabledProtocols = new ArrayList<String>(allProtocols.length);
        for (String protocol : allProtocols) {
            if (!protocol.startsWith("SSL")) {
                enabledProtocols.add(protocol);
            }
        }
        if (!enabledProtocols.isEmpty()) {
            sslsock.setEnabledProtocols(enabledProtocols.toArray(new String[enabledProtocols.size()]));
        }
    }
    if (supportedCipherSuites != null) {
        sslsock.setEnabledCipherSuites(supportedCipherSuites);
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Enabled protocols: {}", Arrays.asList(sslsock.getEnabledProtocols()));
        LOGGER.debug("Enabled cipher suites: {}", Arrays.asList(sslsock.getEnabledCipherSuites()));
    }

    prepareSocket(sslsock);
    LOGGER.debug("Starting handshake");
    sslsock.startHandshake();
    verifyHostname(sslsock, target);
    return sslsock;
}

From source file:org.globus.myproxy.MyProxy.java

/**
 * Bootstraps trustroot information from the MyProxy server.
 *
 * @exception MyProxyException/*w ww .j  a va2  s  . c o  m*/
 *         If an error occurred during the operation.
 */
public void bootstrapTrust() throws MyProxyException {
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        MyTrustManager myTrustManager = new MyTrustManager();
        TrustManager[] trustAllCerts = new TrustManager[] { myTrustManager };
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        SSLSocketFactory sf = sc.getSocketFactory();
        SSLSocket socket = (SSLSocket) sf.createSocket(this.host, this.port);
        socket.setEnabledProtocols(new String[] { "SSLv3" });
        socket.startHandshake();
        socket.close();

        X509Certificate[] acceptedIssuers = myTrustManager.getAcceptedIssuers();
        if (acceptedIssuers == null) {
            throw new MyProxyException("Failed to determine MyProxy server trust roots in bootstrapTrust.");
        }
        for (int idx = 0; idx < acceptedIssuers.length; idx++) {
            File x509Dir = new File(org.globus.myproxy.MyProxy.getTrustRootPath());
            if (!x509Dir.exists()) {
                StringBuffer newSubject = new StringBuffer();
                String[] subjArr = acceptedIssuers[idx].getSubjectDN().getName().split(", ");
                for (int i = (subjArr.length - 1); i > -1; i--) {
                    newSubject.append("/");
                    newSubject.append(subjArr[i]);
                }
                String subject = newSubject.toString();

                File tmpDir = new File(getTrustRootPath() + "-" + System.currentTimeMillis());
                if (tmpDir.mkdir() == true) {
                    String hash = opensslHash(acceptedIssuers[idx]);
                    String filename = tmpDir.getPath() + tmpDir.separator + hash + ".0";

                    FileOutputStream os = new FileOutputStream(new File(filename));
                    CertificateIOUtil.writeCertificate(os, acceptedIssuers[idx]);

                    os.close();
                    if (logger.isDebugEnabled()) {
                        logger.debug("wrote trusted certificate to " + filename);
                    }

                    filename = tmpDir.getPath() + tmpDir.separator + hash + ".signing_policy";

                    os = new FileOutputStream(new File(filename));
                    Writer wr = new OutputStreamWriter(os, Charset.forName("UTF-8"));
                    wr.write("access_id_CA X509 '");
                    wr.write(subject);
                    wr.write("'\npos_rights globus CA:sign\ncond_subjects globus \"*\"\n");
                    wr.flush();
                    wr.close();
                    os.close();

                    if (logger.isDebugEnabled()) {
                        logger.debug("wrote trusted certificate policy to " + filename);
                    }

                    // success.  commit the bootstrapped directory.
                    if (tmpDir.renameTo(x509Dir) == true) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("renamed " + tmpDir.getPath() + " to " + x509Dir.getPath());
                        }
                    } else {
                        throw new MyProxyException(
                                "Unable to rename " + tmpDir.getPath() + " to " + x509Dir.getPath());
                    }
                } else {
                    throw new MyProxyException("Cannot create temporary directory: " + tmpDir.getName());
                }
            }
        }
    } catch (Exception e) {
        throw new MyProxyException("MyProxy bootstrapTrust failed.", e);
    }
}

From source file:android.net.http.CertificateChainValidator.java

/**
 * Performs the handshake and server certificates validation
 * @param sslSocket The secure connection socket
 * @param domain The website domain/*  w  w  w.  java2 s. c  o  m*/
 * @return An SSL error object if there is an error and null otherwise
 */
public SslError doHandshakeAndValidateServerCertificates(HttpsConnection connection, SSLSocket sslSocket,
        String domain) throws SSLHandshakeException, IOException {

    ++sTotal;

    SSLContext sslContext = HttpsConnection.getContext();
    if (sslContext == null) {
        closeSocketThrowException(sslSocket, "SSL context is null");
    }

    X509Certificate[] serverCertificates = null;

    long sessionBeforeHandshakeLastAccessedTime = 0;
    byte[] sessionBeforeHandshakeId = null;

    SSLSession sessionAfterHandshake = null;

    synchronized (sslContext) {
        // get SSL session before the handshake
        SSLSession sessionBeforeHandshake = getSSLSession(sslContext, connection.getHost());
        if (sessionBeforeHandshake != null) {
            sessionBeforeHandshakeLastAccessedTime = sessionBeforeHandshake.getLastAccessedTime();

            sessionBeforeHandshakeId = sessionBeforeHandshake.getId();
        }

        // start handshake, close the socket if we fail
        try {
            sslSocket.setUseClientMode(true);
            sslSocket.startHandshake();
        } catch (IOException e) {
            closeSocketThrowException(sslSocket, e.getMessage(), "failed to perform SSL handshake");
        }

        // retrieve the chain of the server peer certificates
        Certificate[] peerCertificates = sslSocket.getSession().getPeerCertificates();

        if (peerCertificates == null || peerCertificates.length <= 0) {
            closeSocketThrowException(sslSocket, "failed to retrieve peer certificates");
        } else {
            serverCertificates = new X509Certificate[peerCertificates.length];
            for (int i = 0; i < peerCertificates.length; ++i) {
                serverCertificates[i] = (X509Certificate) (peerCertificates[i]);
            }

            // update the SSL certificate associated with the connection
            if (connection != null) {
                if (serverCertificates[0] != null) {
                    connection.setCertificate(new SslCertificate(serverCertificates[0]));
                }
            }
        }

        // get SSL session after the handshake
        sessionAfterHandshake = getSSLSession(sslContext, connection.getHost());
    }

    if (sessionBeforeHandshakeLastAccessedTime != 0 && sessionAfterHandshake != null
            && Arrays.equals(sessionBeforeHandshakeId, sessionAfterHandshake.getId())
            && sessionBeforeHandshakeLastAccessedTime < sessionAfterHandshake.getLastAccessedTime()) {

        if (HttpLog.LOGV) {
            HttpLog.v("SSL session was reused: total reused: " + sTotalReused + " out of total of: " + sTotal);

            ++sTotalReused;
        }

        // no errors!!!
        return null;
    }

    // check if the first certificate in the chain is for this site
    X509Certificate currCertificate = serverCertificates[0];
    if (currCertificate == null) {
        closeSocketThrowException(sslSocket, "certificate for this site is null");
    } else {
        if (!DomainNameChecker.match(currCertificate, domain)) {
            String errorMessage = "certificate not for this host: " + domain;

            if (HttpLog.LOGV) {
                HttpLog.v(errorMessage);
            }

            sslSocket.getSession().invalidate();
            return new SslError(SslError.SSL_IDMISMATCH, currCertificate);
        }
    }

    //
    // first, we validate the chain using the standard validation
    // solution; if we do not find any errors, we are done; if we
    // fail the standard validation, we re-validate again below,
    // this time trying to retrieve any individual errors we can
    // report back to the user.
    //
    try {
        synchronized (mDefaultTrustManager) {
            mDefaultTrustManager.checkServerTrusted(serverCertificates, "RSA");

            // no errors!!!
            return null;
        }
    } catch (CertificateException e) {
        if (HttpLog.LOGV) {
            HttpLog.v("failed to pre-validate the certificate chain, error: " + e.getMessage());
        }
    }

    sslSocket.getSession().invalidate();

    SslError error = null;

    // we check the root certificate separately from the rest of the
    // chain; this is because we need to know what certificate in
    // the chain resulted in an error if any
    currCertificate = serverCertificates[serverCertificates.length - 1];
    if (currCertificate == null) {
        closeSocketThrowException(sslSocket, "root certificate is null");
    }

    // check if the last certificate in the chain (root) is trusted
    X509Certificate[] rootCertificateChain = { currCertificate };
    try {
        synchronized (mDefaultTrustManager) {
            mDefaultTrustManager.checkServerTrusted(rootCertificateChain, "RSA");
        }
    } catch (CertificateExpiredException e) {
        String errorMessage = e.getMessage();
        if (errorMessage == null) {
            errorMessage = "root certificate has expired";
        }

        if (HttpLog.LOGV) {
            HttpLog.v(errorMessage);
        }

        error = new SslError(SslError.SSL_EXPIRED, currCertificate);
    } catch (CertificateNotYetValidException e) {
        String errorMessage = e.getMessage();
        if (errorMessage == null) {
            errorMessage = "root certificate not valid yet";
        }

        if (HttpLog.LOGV) {
            HttpLog.v(errorMessage);
        }

        error = new SslError(SslError.SSL_NOTYETVALID, currCertificate);
    } catch (CertificateException e) {
        String errorMessage = e.getMessage();
        if (errorMessage == null) {
            errorMessage = "root certificate not trusted";
        }

        if (HttpLog.LOGV) {
            HttpLog.v(errorMessage);
        }

        return new SslError(SslError.SSL_UNTRUSTED, currCertificate);
    }

    // Then go through the certificate chain checking that each
    // certificate trusts the next and that each certificate is
    // within its valid date range. Walk the chain in the order
    // from the CA to the end-user
    X509Certificate prevCertificate = serverCertificates[serverCertificates.length - 1];

    for (int i = serverCertificates.length - 2; i >= 0; --i) {
        currCertificate = serverCertificates[i];

        // if a certificate is null, we cannot verify the chain
        if (currCertificate == null) {
            closeSocketThrowException(sslSocket, "null certificate in the chain");
        }

        // verify if trusted by chain
        if (!prevCertificate.getSubjectDN().equals(currCertificate.getIssuerDN())) {
            String errorMessage = "not trusted by chain";

            if (HttpLog.LOGV) {
                HttpLog.v(errorMessage);
            }

            return new SslError(SslError.SSL_UNTRUSTED, currCertificate);
        }

        try {
            currCertificate.verify(prevCertificate.getPublicKey());
        } catch (GeneralSecurityException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "not trusted by chain";
            }

            if (HttpLog.LOGV) {
                HttpLog.v(errorMessage);
            }

            return new SslError(SslError.SSL_UNTRUSTED, currCertificate);
        }

        // verify if the dates are valid
        try {
            currCertificate.checkValidity();
        } catch (CertificateExpiredException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "certificate expired";
            }

            if (HttpLog.LOGV) {
                HttpLog.v(errorMessage);
            }

            if (error == null || error.getPrimaryError() < SslError.SSL_EXPIRED) {
                error = new SslError(SslError.SSL_EXPIRED, currCertificate);
            }
        } catch (CertificateNotYetValidException e) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "certificate not valid yet";
            }

            if (HttpLog.LOGV) {
                HttpLog.v(errorMessage);
            }

            if (error == null || error.getPrimaryError() < SslError.SSL_NOTYETVALID) {
                error = new SslError(SslError.SSL_NOTYETVALID, currCertificate);
            }
        }

        prevCertificate = currCertificate;
    }

    // if we do not have an error to report back to the user, throw
    // an exception (a generic error will be reported instead)
    if (error == null) {
        closeSocketThrowException(sslSocket,
                "failed to pre-validate the certificate chain due to a non-standard error");
    }

    return error;
}

From source file:org.apache.http.HC4.conn.ssl.AbstractVerifier.java

@Override
public final void verify(final String host, final SSLSocket ssl) throws IOException {
    Args.notNull(host, "Host");
    SSLSession session = ssl.getSession();
    if (session == null) {
        // In our experience this only happens under IBM 1.4.x when
        // spurious (unrelated) certificates show up in the server'
        // chain.  Hopefully this will unearth the real problem:
        final InputStream in = ssl.getInputStream();
        in.available();//from  ww w .j  ava2  s  .  c  om
        /*
          If you're looking at the 2 lines of code above because
          you're running into a problem, you probably have two
          options:
                
        #1.  Clean up the certificate chain that your server
             is presenting (e.g. edit "/etc/apache2/server.crt"
             or wherever it is your server's certificate chain
             is defined).
                
                                   OR
                
        #2.   Upgrade to an IBM 1.5.x or greater JVM, or switch
              to a non-IBM JVM.
        */

        // If ssl.getInputStream().available() didn't cause an
        // exception, maybe at least now the session is available?
        session = ssl.getSession();
        if (session == null) {
            // If it's still null, probably a startHandshake() will
            // unearth the real problem.
            ssl.startHandshake();

            // Okay, if we still haven't managed to cause an exception,
            // might as well go for the NPE.  Or maybe we're okay now?
            session = ssl.getSession();
        }
    }

    final Certificate[] certs = session.getPeerCertificates();
    final X509Certificate x509 = (X509Certificate) certs[0];
    verify(host, x509);
}

From source file:com.newrelic.agent.deps.org.apache.http.conn.ssl.SSLConnectionSocketFactory.java

@Override
public Socket createLayeredSocket(final Socket socket, final String target, final int port,
        final HttpContext context) throws IOException {
    final SSLSocket sslsock = (SSLSocket) this.socketfactory.createSocket(socket, target, port, true);
    if (supportedProtocols != null) {
        sslsock.setEnabledProtocols(supportedProtocols);
    } else {//w w  w.ja v  a 2s  .co m
        // If supported protocols are not explicitly set, remove all SSL protocol versions
        final String[] allProtocols = sslsock.getEnabledProtocols();
        final List<String> enabledProtocols = new ArrayList<String>(allProtocols.length);
        for (String protocol : allProtocols) {
            if (!protocol.startsWith("SSL")) {
                enabledProtocols.add(protocol);
            }
        }
        if (!enabledProtocols.isEmpty()) {
            sslsock.setEnabledProtocols(enabledProtocols.toArray(new String[enabledProtocols.size()]));
        }
    }
    if (supportedCipherSuites != null) {
        sslsock.setEnabledCipherSuites(supportedCipherSuites);
    }

    if (this.log.isDebugEnabled()) {
        this.log.debug("Enabled protocols: " + Arrays.asList(sslsock.getEnabledProtocols()));
        this.log.debug("Enabled cipher suites:" + Arrays.asList(sslsock.getEnabledCipherSuites()));
    }

    prepareSocket(sslsock);
    this.log.debug("Starting handshake");
    sslsock.startHandshake();
    verifyHostname(sslsock, target);
    return sslsock;
}