Bypass SSL security check

The following methods can be used to bypass SSL secuirty check

1. Call XTrustProvider.install() to turn off SSL check

(For org.apache.commons.httpclient.HttpClient)

import java.security.AccessController;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.PrivilegedAction;
import java.security.Security;
import java.security.cert.X509Certificate;
 
import javax.net.ssl.ManagerFactoryParameters;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactorySpi;
import javax.net.ssl.X509TrustManager;

public final class XTrustProvider extends java.security.Provider {
       
       private final static String NAME = "XTrustJSSE";
       private final static String INFO = "XTrust JSSE Provider (implements trust factory with truststore validation disabled)";
       private final static double VERSION = 1.0D;
       
       public XTrustProvider() {
               super(NAME, VERSION, INFO);
               
               AccessController.doPrivileged(new PrivilegedAction() {
                       public Object run() {
                               put("TrustManagerFactory." + TrustManagerFactoryImpl.getAlgorithm(), TrustManagerFactoryImpl.class.getName());
                               return null;
                       }
               });
       }
       
       public static void install() {
               if(Security.getProvider(NAME) == null) {
                       Security.insertProviderAt(new XTrustProvider(), 2);
                       Security.setProperty("ssl.TrustManagerFactory.algorithm", TrustManagerFactoryImpl.getAlgorithm());
               }
       }
       
       public final static class TrustManagerFactoryImpl extends TrustManagerFactorySpi {
               public TrustManagerFactoryImpl() { }
               public static String getAlgorithm() { return "XTrust509"; }
               protected void engineInit(KeyStore keystore) throws KeyStoreException { }
               protected void engineInit(ManagerFactoryParameters mgrparams) throws InvalidAlgorithmParameterException {
                       throw new InvalidAlgorithmParameterException( XTrustProvider.NAME + " does not use ManagerFactoryParameters");
               }
               
               protected TrustManager[] engineGetTrustManagers() {
                       return new TrustManager[] {
                               new X509TrustManager() {
                                       public X509Certificate[] getAcceptedIssuers() { return null; }
                                       public void checkClientTrusted(X509Certificate[] certs, String authType) { }
                                       public void checkServerTrusted(X509Certificate[] certs, String authType) { }
                               }
                       };
               }
       }
}

 I used this method in my project, and it works well.

2. Define yourself class to bypasss the checking of security

 ((For org.apache.commons.httpclient.HttpClient))

Define yourself class which implements X509TrustManager so that nothing is checked security.

package com.fushine.example.mytest;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MySSLSocketFactory implements SecureProtocolSocketFactory {
	private static final Logger LOGGER = LoggerFactory
			.getLogger(MySSLSocketFactory.class);
    static{
        LOGGER.info("loading SSL");
    }
    private SSLContext sslcontext = null;
    
    private SSLContext createSSLContext() {
        SSLContext sslcontext=null;
        try {
            sslcontext = SSLContext.getInstance("SSL");
            sslcontext.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
        return sslcontext;
    }
    
    private SSLContext getSSLContext() {
        if (this.sslcontext == null) {
            this.sslcontext = createSSLContext();
        }
        return this.sslcontext;
    }
    
    public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
            throws IOException, UnknownHostException {
        return getSSLContext().getSocketFactory().createSocket(
                socket,
                host,
                port,
                autoClose
            );
    }

    public Socket createSocket(String host, int port) throws IOException,
            UnknownHostException {
        return getSSLContext().getSocketFactory().createSocket(
                host,
                port
            );
    }
    
    
    public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort)
            throws IOException, UnknownHostException {
        return getSSLContext().getSocketFactory().createSocket(host, port, clientHost, clientPort);
    }

    public Socket createSocket(String host, int port, InetAddress localAddress,
            int localPort, HttpConnectionParams params) throws IOException,
            UnknownHostException, ConnectTimeoutException {
        if (params == null) {
            throw new IllegalArgumentException("Parameters may not be null");
        }
        int timeout = params.getConnectionTimeout();
        SocketFactory socketfactory = getSSLContext().getSocketFactory();
        if (timeout == 0) {
            return socketfactory.createSocket(host, port, localAddress, localPort);
        } else {
            Socket socket = socketfactory.createSocket();
            SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
            SocketAddress remoteaddr = new InetSocketAddress(host, port);
            socket.bind(localaddr);
            socket.connect(remoteaddr, timeout);
            return socket;
        }
    }
    
    /**
     * define your private trust manager
     * 
     * @author pc_fxli
     *
     */
    private static class TrustAnyTrustManager implements X509TrustManager {
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[]{};
        }
    }

}

 And use it as the following example:

Protocol myhttps = new Protocol("https", new MySSLSocketFactory(), 443);
Protocol.registerProtocol("https", myhttps);

HttpClient httpclient = new HttpClient();
httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, charset);
httpclient.getHostConfiguration().setHost("127.0.0.1", 9000, myhttps);

GetMethod httpget = new GetMethod("/");
try {
      httpclient.executeMethod(httpget);
      System.out.println(httpget.getResponseBodyAsString());
} finally {
     httpget.releaseConnection();
}

 

3. One method for using org.apache.http.client.HttpClient

package com.fushine.example.mytest;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;

/*
 * This code is public domain: you are free to use, link and/or modify it in any way you want, for all purposes including commercial applications.
 */
public class WebClientDevWrapper {
        public static DefaultHttpClient wrapClient(HttpClient base) {
               

                try {
                        SSLContext ctx = SSLContext.getInstance("TLS");
                        X509TrustManager tm = new X509TrustManager() {
                                public void checkClientTrusted(X509Certificate[] xcs,
                                                String string) throws CertificateException {
                                }

                                public void checkServerTrusted(X509Certificate[] xcs,
                                                String string) throws CertificateException {
                                }

                                public X509Certificate[] getAcceptedIssuers() {
                                        return null;
                                }
                        };
                        ctx.init(null, new TrustManager[] { tm }, null);
                        SSLSocketFactory ssf = new SSLSocketFactory(ctx);
                        ssf
                                        .setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
                        ClientConnectionManager ccm = base.getConnectionManager();
                        SchemeRegistry sr = ccm.getSchemeRegistry();
                        sr.register(new Scheme("https", ssf, 443));
                        return new DefaultHttpClient(ccm, base.getParams());
                } catch (Exception ex) {
                        ex.printStackTrace();
                        return null;
                }
        }
}

 

猜你喜欢

转载自fushine-lee.iteye.com/blog/1977760