Android Open Source - myglob Trust All Socket Factory






From Project

Back to project page myglob.

License

The source code is released under:

GNU General Public License

If you think the Android project myglob listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

/*
 * MyGlob Android Application/*w w  w.jav  a 2 s.  co  m*/
 * 
 * Copyright (C) 2010 Petar Petrov
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
package net.vexelon.myglob.utils;

import java.io.IOException;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

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

import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.scheme.LayeredSocketFactory;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

/**
 * <p>
 * Use this socket factory to blindly verify server certificates.
 * <p> 
 * Also includes reverse DNS fix for Android < 4.0
 * Source: http://code.google.com/p/android/issues/detail?id=13117#c14
 * 
 * @author petarov
 *
 */
public final class TrustAllSocketFactory implements LayeredSocketFactory {
  
//  private static TrustAllSocketFactory INSTANCE = new TrustAllSocketFactory();
  private SSLContext sslContext = null;
  private SSLSocketFactory socketFactory = null;
  
//  public TrustAllSocketFactory getSocketFactory() {
//    return INSTANCE;
//  }
  
  public TrustAllSocketFactory() throws InvalidAlgorithmParameterException {
    super();
    
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override
        public X509Certificate[] getAcceptedIssuers() {
          return new X509Certificate[] {};
        }
        
        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType)
            throws CertificateException {
          
        }
        
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType)
            throws CertificateException {
          
        }
      }
    };
    
    SecureRandom secureRND = new SecureRandom();
    
    try {
      sslContext = SSLContext.getInstance(org.apache.http.conn.ssl.SSLSocketFactory.TLS);
      sslContext.init(null, trustAllCerts, secureRND);
    } catch (NoSuchAlgorithmException e) {
      throw new InvalidAlgorithmParameterException("Failed to initlize TLS context!", e);
    } catch (KeyManagementException e) {
      throw new InvalidAlgorithmParameterException("Failed to init SSL context!", e);
    }
    
    socketFactory = sslContext.getSocketFactory();
  }
  
  /**
   * Prevents the reverse DNS lookup from being made. Fixed in Android 4.0, but still needs
   * workaround for earlier versions. 
   * Source: http://code.google.com/p/android/issues/detail?id=13117#c14
   * @param socket
   * @param host
   */
    private void injectHostname(Socket socket, String host) {
        try {
            Field field = InetAddress.class.getDeclaredField("hostName");
            field.setAccessible(true);
            field.set(socket.getInetAddress(), host);
        } catch (Exception ignored) {
          // uhm
        }
    }  

  @Override
  public Socket connectSocket(Socket sock, String host, int port,
      InetAddress localAddress, int localPort, HttpParams params)
      throws IOException, UnknownHostException, ConnectTimeoutException {
    
    if (host == null) {
      throw new IllegalArgumentException("Target host may not be null.");
    }
    if (params == null) {
      throw new IllegalArgumentException("Parameters may not be null.");
    }

    SSLSocket sslSocket = (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);
      sslSocket.bind(isa);
    }

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

    InetSocketAddress remoteAddress;
    remoteAddress = new InetSocketAddress(host, port);

    sslSocket.connect(remoteAddress, connTimeout);
    sslSocket.setSoTimeout(soTimeout);

    return sslSocket;
  }

  @Override
  public Socket createSocket() throws IOException {
    return (SSLSocket)socketFactory.createSocket();
  }

  @Override
  public boolean isSecure(Socket sock) throws IllegalArgumentException {
    return true;
  }

  @Override
  public Socket createSocket(Socket socket, String host, int port,
      boolean autoClose) throws IOException, UnknownHostException {
    injectHostname(socket, host); // reverse DNS fix
    SSLSocket sslSocket = (SSLSocket) socketFactory.createSocket(socket, host, port, autoClose);
    return sslSocket;
  }
  
}




Java Source Code List

net.vexelon.mobileops.GLBClient.java
net.vexelon.mobileops.GLBInvoiceXMLParser.java
net.vexelon.mobileops.GLBRequestType.java
net.vexelon.mobileops.HttpClientException.java
net.vexelon.mobileops.IClient.java
net.vexelon.mobileops.InvalidCredentialsException.java
net.vexelon.mobileops.InvoiceException.java
net.vexelon.mobileops.MTLClient.java
net.vexelon.mobileops.SecureCodeRequiredException.java
net.vexelon.myglob.AccountsArrayAdapter.java
net.vexelon.myglob.MainActivity.java
net.vexelon.myglob.OperationsArrayAdapter.java
net.vexelon.myglob.Operations.java
net.vexelon.myglob.UpdateWidgetService.java
net.vexelon.myglob.WidgetProvider4x2.java
net.vexelon.myglob.WidgetProvider.java
net.vexelon.myglob.actions.AccountStatusAction.java
net.vexelon.myglob.actions.ActionExecuteException.java
net.vexelon.myglob.actions.ActionResult.java
net.vexelon.myglob.actions.Action.java
net.vexelon.myglob.actions.BaseAction.java
net.vexelon.myglob.actions.InvoiceLoadCachedAction.java
net.vexelon.myglob.actions.InvoiceUpdateAction.java
net.vexelon.myglob.configuration.AccountPreferencesActivity.java
net.vexelon.myglob.configuration.Defs.java
net.vexelon.myglob.configuration.GlobalSettings.java
net.vexelon.myglob.configuration.LegacySettings.java
net.vexelon.myglob.crypto.CryptoAES.java
net.vexelon.myglob.crypto.Crypto.java
net.vexelon.myglob.crypto.PasswordEngineImpl1.java
net.vexelon.myglob.crypto.PasswordEngineImpl2.java
net.vexelon.myglob.crypto.PasswordEngine.java
net.vexelon.myglob.fragments.AboutFragment.java
net.vexelon.myglob.fragments.BaseFragment.java
net.vexelon.myglob.fragments.HomeFragment.java
net.vexelon.myglob.fragments.IFragmentEvents.java
net.vexelon.myglob.fragments.InvoiceFragment.java
net.vexelon.myglob.users.AccountType.java
net.vexelon.myglob.users.User.java
net.vexelon.myglob.users.UsersManager.java
net.vexelon.myglob.utils.Base64.java
net.vexelon.myglob.utils.DateUtils.java
net.vexelon.myglob.utils.TrustAllSocketFactory.java
net.vexelon.myglob.utils.UserAgentHelper.java
net.vexelon.myglob.utils.Utils.java