├── .gitignore ├── res ├── drawable-hdpi │ └── icon.png ├── drawable-ldpi │ └── icon.png ├── drawable-mdpi │ └── icon.png ├── layout │ ├── read_logs.xml │ ├── tunnel_list.xml │ ├── tunnel_list_item.xml │ └── tunnel_details.xml ├── menu │ └── main.xml └── values │ └── strings.xml ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── README ├── .settings └── org.eclipse.jdt.core.prefs ├── .classpath ├── assets ├── tunnels_example.xml └── ssldroid_logo.svg ├── .project ├── proguard.cfg ├── src └── hu │ └── blint │ └── ssldroid │ ├── BootStartupReceiver.java │ ├── TcpProxy.java │ ├── db │ ├── SSLDroidDbHelper.java │ └── SSLDroidDbAdapter.java │ ├── NetworkChangeReceiver.java │ ├── Relay.java │ ├── SSLDroidReadLogs.java │ ├── SSLDroid.java │ ├── SSLDroidGui.java │ ├── TcpProxyServerThread.java │ └── SSLDroidTunnelDetails.java ├── AndroidManifest.xml ├── gradlew.bat ├── gradlew └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle/ 2 | build/ 3 | **.orig 4 | **.rej 5 | **.patch -------------------------------------------------------------------------------- /res/drawable-hdpi/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/blint/SSLDroid/HEAD/res/drawable-hdpi/icon.png -------------------------------------------------------------------------------- /res/drawable-ldpi/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/blint/SSLDroid/HEAD/res/drawable-ldpi/icon.png -------------------------------------------------------------------------------- /res/drawable-mdpi/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/blint/SSLDroid/HEAD/res/drawable-mdpi/icon.png -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/blint/SSLDroid/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /README: -------------------------------------------------------------------------------- 1 | SSLDroid is a Java-based plain-to-SSL proxy for Android devices 2 | 3 | The main goal of SSLDroid is to provide client-side certificate based 4 | authentication capabilities to software on Android, most notably email 5 | and calendar sync 6 | 7 | -------------------------------------------------------------------------------- /.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | #Sat Mar 19 16:20:10 CET 2011 2 | eclipse.preferences.version=1 3 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 4 | org.eclipse.jdt.core.compiler.compliance=1.5 5 | org.eclipse.jdt.core.compiler.source=1.5 6 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Sat Jul 25 01:04:55 EDT 2015 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.5-bin.zip 7 | -------------------------------------------------------------------------------- /.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /res/layout/read_logs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /res/layout/tunnel_list.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 7 | 9 | 10 | -------------------------------------------------------------------------------- /assets/tunnels_example.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 9443 5 | host1.example.com 6 | 443 7 | /sdcard/vpn/user.p12 8 | 9 | /sdcard/vpn/cacert.crt 10 | 11 | 12 | 9993 13 | host2.example.com 14 | 993 15 | /sdcard/vpn/user.p12 16 | 17 | /sdcard/vpn/cacert.crt 18 | 19 | 20 | -------------------------------------------------------------------------------- /res/layout/tunnel_list_item.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 10 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | SSLDroid 4 | 5 | 6 | 7 | 8 | 9 | com.android.ide.eclipse.adt.ResourceManagerBuilder 10 | 11 | 12 | 13 | 14 | com.android.ide.eclipse.adt.PreCompilerBuilder 15 | 16 | 17 | 18 | 19 | org.eclipse.jdt.core.javabuilder 20 | 21 | 22 | 23 | 24 | com.android.ide.eclipse.adt.ApkBuilder 25 | 26 | 27 | 28 | 29 | 30 | com.android.ide.eclipse.adt.AndroidNature 31 | org.eclipse.jdt.core.javanature 32 | 33 | 34 | -------------------------------------------------------------------------------- /res/menu/main.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /proguard.cfg: -------------------------------------------------------------------------------- 1 | -optimizationpasses 5 2 | -dontusemixedcaseclassnames 3 | -dontskipnonpubliclibraryclasses 4 | -dontpreverify 5 | -verbose 6 | -optimizations !code/simplification/arithmetic,!field/*,!class/merging/* 7 | 8 | -keep public class * extends android.app.Activity 9 | -keep public class * extends android.app.Application 10 | -keep public class * extends android.app.Service 11 | -keep public class * extends android.content.BroadcastReceiver 12 | -keep public class * extends android.content.ContentProvider 13 | -keep public class * extends android.app.backup.BackupAgentHelper 14 | -keep public class * extends android.preference.Preference 15 | -keep public class com.android.vending.licensing.ILicensingService 16 | 17 | -keepclasseswithmembers class * { 18 | native ; 19 | } 20 | 21 | -keepclasseswithmembers class * { 22 | public (android.content.Context, android.util.AttributeSet); 23 | } 24 | 25 | -keepclasseswithmembers class * { 26 | public (android.content.Context, android.util.AttributeSet, int); 27 | } 28 | 29 | -keepclassmembers enum * { 30 | public static **[] values(); 31 | public static ** valueOf(java.lang.String); 32 | } 33 | 34 | -keep class * implements android.os.Parcelable { 35 | public static final android.os.Parcelable$Creator *; 36 | } 37 | -------------------------------------------------------------------------------- /src/hu/blint/ssldroid/BootStartupReceiver.java: -------------------------------------------------------------------------------- 1 | package hu.blint.ssldroid; 2 | 3 | import hu.blint.ssldroid.db.SSLDroidDbAdapter; 4 | import android.content.BroadcastReceiver; 5 | import android.content.Context; 6 | import android.content.Intent; 7 | import android.database.Cursor; 8 | import android.util.Log; 9 | 10 | public class BootStartupReceiver extends BroadcastReceiver { 11 | 12 | private boolean isStopped(Context context){ 13 | Boolean stopped = false; 14 | SSLDroidDbAdapter dbHelper; 15 | dbHelper = new SSLDroidDbAdapter(context); 16 | dbHelper.open(); 17 | Cursor cursor = dbHelper.getStopStatus(); 18 | 19 | int tunnelcount = cursor.getCount(); 20 | Log.d("SSLDroid", "Tunnelcount: "+tunnelcount); 21 | 22 | //don't start if the stop status field is available 23 | if (tunnelcount != 0){ 24 | stopped = true; 25 | } 26 | 27 | cursor.close(); 28 | dbHelper.close(); 29 | 30 | return stopped; 31 | } 32 | 33 | @Override 34 | public void onReceive(Context context, Intent intent) { 35 | if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) { 36 | Intent i = new Intent(); 37 | i.setAction("hu.blint.ssldroid.SSLDroid"); 38 | if (!isStopped(context)) 39 | context.startService(i); 40 | else 41 | Log.w("SSLDroid", "Not starting service as directed by explicit stop"); 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | SSLDroid 4 | Local port 5 | Remote host 6 | Remote port 7 | PKCS12 file 8 | CA cert file 9 | 10 | Apply 11 | PKCS12 pass 12 | Tunnel name 13 | Add tunnel 14 | Stop service 15 | Stop until explicit start 16 | Start service 17 | No tunnels configured yet 18 | Delete tunnel 19 | Pick a PKCS12 file from SD card 20 | No SD card present, please insert one to continue 21 | Read logs 22 | Reading log messages… 23 | Provisioning 24 | Please enter the URL for remote XML configuration 25 | Back 26 | Refresh 27 | Share logs 28 | Clone tunnel 29 | 30 | -------------------------------------------------------------------------------- /src/hu/blint/ssldroid/TcpProxy.java: -------------------------------------------------------------------------------- 1 | package hu.blint.ssldroid; 2 | 3 | import java.io.IOException; 4 | import android.util.Log; 5 | 6 | /** 7 | * This is a modified version of the TcpTunnelGui utility borrowed from the 8 | * xml.apache.org project. 9 | */ 10 | public class TcpProxy { 11 | String tunnelName; 12 | int listenPort; 13 | String tunnelHost; 14 | int tunnelPort; 15 | String keyFile, keyPass, caCertFile; 16 | TcpProxyServerThread server = null; 17 | 18 | public TcpProxy(String tunnelName, int listenPort, String targetHost, int targetPort, String keyFile, String keyPass, String caCertFile) { 19 | this.tunnelName = tunnelName; 20 | this.listenPort = listenPort; 21 | this.tunnelHost = targetHost; 22 | this.tunnelPort = targetPort; 23 | this.keyFile = keyFile; 24 | this.keyPass = keyPass; 25 | this.caCertFile = caCertFile; 26 | } 27 | 28 | public void serve() throws IOException { 29 | server = new TcpProxyServerThread(this.tunnelName, this.listenPort, this.tunnelHost, 30 | this.tunnelPort, this.keyFile, this.keyPass, this.caCertFile); 31 | server.start(); 32 | } 33 | 34 | public void stop() { 35 | if (server != null) { 36 | try { 37 | //close the server socket and interrupt the server thread 38 | server.ss.close(); 39 | server.interrupt(); 40 | } catch (Exception e) { 41 | Log.d("SSLDroid", "Interrupt failure: " + e.toString()); 42 | } 43 | } 44 | Log.d("SSLDroid", "Stopping tunnel "+this.listenPort+":"+this.tunnelHost+":"+this.tunnelPort); 45 | } 46 | 47 | //if the listening socket is still active, we're alive 48 | public boolean isAlive() { 49 | return server.ss.isBound(); 50 | } 51 | 52 | } 53 | -------------------------------------------------------------------------------- /src/hu/blint/ssldroid/db/SSLDroidDbHelper.java: -------------------------------------------------------------------------------- 1 | package hu.blint.ssldroid.db; 2 | 3 | import android.content.Context; 4 | import android.database.sqlite.SQLiteDatabase; 5 | import android.database.sqlite.SQLiteOpenHelper; 6 | import android.util.Log; 7 | 8 | public class SSLDroidDbHelper extends SQLiteOpenHelper { 9 | private static final String DATABASE_NAME = "applicationdata"; 10 | private static final int DATABASE_VERSION = 3; 11 | 12 | // Database creation sql statement 13 | private static final String DATABASE_CREATE = "CREATE TABLE IF NOT EXISTS tunnels (_id integer primary key autoincrement, " 14 | + "name text not null, localport integer not null, remotehost text not null, " 15 | + "remoteport integer not null, pkcsfile text not null, pkcspass text, cacertfile text );"; 16 | private static final String STATUS_CREATE = "CREATE TABLE IF NOT EXISTS status (name text, value text);"; 17 | 18 | public SSLDroidDbHelper(Context context) { 19 | super(context, DATABASE_NAME, null, DATABASE_VERSION); 20 | } 21 | 22 | // Method is called during creation of the database 23 | @Override 24 | public void onCreate(SQLiteDatabase database) { 25 | database.execSQL(DATABASE_CREATE); 26 | database.execSQL(STATUS_CREATE); 27 | } 28 | 29 | // Method is called during an update of the database, e.g. if you increase 30 | // the database version 31 | @Override 32 | public void onUpgrade(SQLiteDatabase database, int oldVersion, 33 | int newVersion) { 34 | Log.w(SSLDroidDbHelper.class.getName(), 35 | "Upgrading database from version " + oldVersion + " to " 36 | + newVersion + ", which will add a status table"); 37 | database.execSQL("CREATE TABLE IF NOT EXISTS status (name text, value text);"); 38 | if (oldVersion < 3) 39 | database.execSQL("ALTER TABLE tunnels ADD cacertfile text;"); 40 | onCreate(database); 41 | } 42 | } 43 | 44 | -------------------------------------------------------------------------------- /src/hu/blint/ssldroid/NetworkChangeReceiver.java: -------------------------------------------------------------------------------- 1 | package hu.blint.ssldroid; 2 | 3 | import hu.blint.ssldroid.db.SSLDroidDbAdapter; 4 | import android.content.BroadcastReceiver; 5 | import android.content.Context; 6 | import android.content.Intent; 7 | import android.database.Cursor; 8 | import android.net.ConnectivityManager; 9 | import android.net.NetworkInfo; 10 | import android.util.Log; 11 | 12 | public class NetworkChangeReceiver extends BroadcastReceiver { 13 | 14 | private boolean isStopped(Context context){ 15 | Boolean stopped = false; 16 | SSLDroidDbAdapter dbHelper; 17 | dbHelper = new SSLDroidDbAdapter(context); 18 | dbHelper.open(); 19 | Cursor cursor = dbHelper.getStopStatus(); 20 | 21 | int tunnelcount = cursor.getCount(); 22 | Log.d("SSLDroid", "Tunnelcount: "+tunnelcount); 23 | 24 | //don't start if the stop status field is available 25 | if (tunnelcount != 0){ 26 | stopped = true; 27 | } 28 | 29 | cursor.close(); 30 | dbHelper.close(); 31 | 32 | return stopped; 33 | } 34 | 35 | @Override 36 | public void onReceive(Context context, Intent intent) { 37 | ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService( Context.CONNECTIVITY_SERVICE ); 38 | NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo(); 39 | if ( activeNetInfo == null ) { 40 | Intent i = new Intent(); 41 | i.setAction("hu.blint.ssldroid.SSLDroid"); 42 | context.stopService(i); 43 | return; 44 | } 45 | Log.d("SSLDroid", activeNetInfo.toString()); 46 | if (activeNetInfo.isAvailable()) { 47 | Intent i = new Intent(); 48 | i.setAction("hu.blint.ssldroid.SSLDroid"); 49 | context.stopService(i); 50 | if (!isStopped(context)) 51 | context.startService(i); 52 | else 53 | Log.w("SSLDroid", "Not starting service as directed by explicit stop"); 54 | } 55 | } 56 | } 57 | 58 | -------------------------------------------------------------------------------- /AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /src/hu/blint/ssldroid/Relay.java: -------------------------------------------------------------------------------- 1 | package hu.blint.ssldroid; 2 | 3 | import java.io.IOException; 4 | import java.io.InputStream; 5 | import java.io.OutputStream; 6 | import java.net.SocketException; 7 | 8 | import android.util.Log; 9 | 10 | public class Relay extends Thread { 11 | /** 12 | * 13 | */ 14 | private final TcpProxyServerThread tcpProxyServerThread; 15 | private InputStream in; 16 | private OutputStream out; 17 | private String side; 18 | private int sessionid; 19 | private final static int BUFSIZ = 4096; 20 | private byte buf[] = new byte[BUFSIZ]; 21 | 22 | public Relay(TcpProxyServerThread tcpProxyServerThread, InputStream in, OutputStream out, String side, int sessionid) { 23 | this.tcpProxyServerThread = tcpProxyServerThread; 24 | this.in = in; 25 | this.out = out; 26 | this.side = side; 27 | this.sessionid = sessionid; 28 | } 29 | 30 | public void run() { 31 | int n = 0; 32 | 33 | try { 34 | while ((n = in.read(buf)) > 0) { 35 | if (Thread.interrupted()) { 36 | // We've been interrupted: no more relaying 37 | Log.d("SSLDroid", this.tcpProxyServerThread.tunnelName+"/"+sessionid+": Interrupted "+side+" thread"); 38 | try { 39 | in.close(); 40 | out.close(); 41 | } catch (IOException e) { 42 | Log.d("SSLDroid", this.tcpProxyServerThread.tunnelName+"/"+sessionid+": "+e.toString()); 43 | } 44 | return; 45 | } 46 | out.write(buf, 0, n); 47 | out.flush(); 48 | 49 | for (int i = 0; i < n; i++) { 50 | if (buf[i] == 7) 51 | buf[i] = '#'; 52 | } 53 | } 54 | } catch (SocketException e) { 55 | Log.d("SSLDroid", this.tcpProxyServerThread.tunnelName+"/"+sessionid+": "+e.toString()); 56 | } catch (IOException e) { 57 | Log.d("SSLDroid", this.tcpProxyServerThread.tunnelName+"/"+sessionid+": "+e.toString()); 58 | } finally { 59 | try { 60 | in.close(); 61 | out.close(); 62 | } catch (IOException e) { 63 | Log.d("SSLDroid", this.tcpProxyServerThread.tunnelName+"/"+sessionid+": "+e.toString()); 64 | } 65 | } 66 | Log.d("SSLDroid", this.tcpProxyServerThread.tunnelName+"/"+sessionid+": Quitting "+side+"-side stream proxy..."); 67 | } 68 | } -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /src/hu/blint/ssldroid/SSLDroidReadLogs.java: -------------------------------------------------------------------------------- 1 | package hu.blint.ssldroid; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.IOException; 5 | import java.io.InputStreamReader; 6 | 7 | import android.app.Activity; 8 | import android.content.Intent; 9 | import android.os.Bundle; 10 | import android.util.Log; 11 | import android.view.Menu; 12 | import android.view.MenuItem; 13 | import android.widget.TextView; 14 | 15 | public class SSLDroidReadLogs extends Activity { 16 | 17 | @Override 18 | public boolean onCreateOptionsMenu(Menu menu) { 19 | MenuItem refresh = menu.add(R.string.refresh); 20 | refresh.setIcon(android.R.drawable.ic_menu_rotate); 21 | MenuItem share = menu.add(R.string.share); 22 | share.setIcon(android.R.drawable.ic_menu_share); 23 | return true; 24 | } 25 | 26 | @Override 27 | public boolean onOptionsItemSelected(MenuItem item) { 28 | if (item.getTitle() == getResources().getString(R.string.refresh)) 29 | refreshLogs(); 30 | else if ((item.getTitle() == getResources().getString(R.string.share))) 31 | shareLogs(); 32 | else 33 | return false; 34 | return true; 35 | } 36 | 37 | @Override 38 | public void onCreate(Bundle savedInstanceState) { 39 | super.onCreate(savedInstanceState); 40 | setContentView(R.layout.read_logs); 41 | refreshLogs(); 42 | } 43 | 44 | public void refreshLogs() { 45 | TextView logcontainer = (TextView) findViewById(R.id.logTextView); 46 | logcontainer.setText(""); 47 | Process mLogcatProc = null; 48 | BufferedReader reader = null; 49 | try { 50 | mLogcatProc = Runtime.getRuntime().exec(new String[] 51 | {"logcat", "-d", "-v", "time", "-b", "main", "SSLDroid:D SSLDroidGui:D AndroidRuntime *:S" }); 52 | 53 | reader = new BufferedReader(new InputStreamReader(mLogcatProc.getInputStream())); 54 | 55 | String line; 56 | String separator = System.getProperty("line.separator"); 57 | 58 | while ((line = reader.readLine()) != null) { 59 | logcontainer.append(line+separator); 60 | } 61 | } catch (IOException e) { 62 | Log.d("SSLDroid", "Logcat problem: "+e.toString()); 63 | } 64 | finally { 65 | if (reader != null) 66 | try { 67 | reader.close(); 68 | } catch (IOException e) { 69 | Log.d("SSLDroid", "Logcat problem: "+e.toString()); 70 | } 71 | } 72 | } 73 | 74 | public void shareLogs() { 75 | Intent sendIntent = new Intent(); 76 | TextView logcontainer = (TextView) findViewById(R.id.logTextView); 77 | CharSequence logdata = logcontainer.getText(); 78 | 79 | sendIntent.setAction(Intent.ACTION_SEND); 80 | sendIntent.putExtra(Intent.EXTRA_TEXT, logdata); 81 | sendIntent.setType("text/plain"); 82 | startActivity(sendIntent); 83 | } 84 | 85 | } 86 | -------------------------------------------------------------------------------- /res/layout/tunnel_details.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 12 | 13 | 16 | 17 | 18 | 21 | 22 | 25 | 26 | 27 | 30 | 31 | 34 | 35 | 36 | 39 | 40 | 43 | 44 | 45 | 48 | 49 | 52 | 53 | 54 | 55 | 56 | 59 | 60 | 63 | 64 | 65 | 68 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # For Cygwin, ensure paths are in UNIX format before anything is touched. 46 | if $cygwin ; then 47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"` 48 | fi 49 | 50 | # Attempt to set APP_HOME 51 | # Resolve links: $0 may be a link 52 | PRG="$0" 53 | # Need this for relative symlinks. 54 | while [ -h "$PRG" ] ; do 55 | ls=`ls -ld "$PRG"` 56 | link=`expr "$ls" : '.*-> \(.*\)$'` 57 | if expr "$link" : '/.*' > /dev/null; then 58 | PRG="$link" 59 | else 60 | PRG=`dirname "$PRG"`"/$link" 61 | fi 62 | done 63 | SAVED="`pwd`" 64 | cd "`dirname \"$PRG\"`/" >&- 65 | APP_HOME="`pwd -P`" 66 | cd "$SAVED" >&- 67 | 68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 69 | 70 | # Determine the Java command to use to start the JVM. 71 | if [ -n "$JAVA_HOME" ] ; then 72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 73 | # IBM's JDK on AIX uses strange locations for the executables 74 | JAVACMD="$JAVA_HOME/jre/sh/java" 75 | else 76 | JAVACMD="$JAVA_HOME/bin/java" 77 | fi 78 | if [ ! -x "$JAVACMD" ] ; then 79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 80 | 81 | Please set the JAVA_HOME variable in your environment to match the 82 | location of your Java installation." 83 | fi 84 | else 85 | JAVACMD="java" 86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 87 | 88 | Please set the JAVA_HOME variable in your environment to match the 89 | location of your Java installation." 90 | fi 91 | 92 | # Increase the maximum file descriptors if we can. 93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 94 | MAX_FD_LIMIT=`ulimit -H -n` 95 | if [ $? -eq 0 ] ; then 96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 97 | MAX_FD="$MAX_FD_LIMIT" 98 | fi 99 | ulimit -n $MAX_FD 100 | if [ $? -ne 0 ] ; then 101 | warn "Could not set maximum file descriptor limit: $MAX_FD" 102 | fi 103 | else 104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 105 | fi 106 | fi 107 | 108 | # For Darwin, add options to specify how the application appears in the dock 109 | if $darwin; then 110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 111 | fi 112 | 113 | # For Cygwin, switch paths to Windows format before running java 114 | if $cygwin ; then 115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 158 | function splitJvmOpts() { 159 | JVM_OPTS=("$@") 160 | } 161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 163 | 164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 165 | -------------------------------------------------------------------------------- /src/hu/blint/ssldroid/SSLDroid.java: -------------------------------------------------------------------------------- 1 | package hu.blint.ssldroid; 2 | 3 | import hu.blint.ssldroid.TcpProxy; 4 | import android.app.*; 5 | import android.content.Intent; 6 | import android.content.pm.PackageInfo; 7 | import android.content.pm.PackageManager; 8 | import android.content.pm.PackageManager.NameNotFoundException; 9 | import android.database.Cursor; 10 | import android.os.IBinder; 11 | import android.util.Log; 12 | import hu.blint.ssldroid.db.SSLDroidDbAdapter; 13 | 14 | public class SSLDroid extends Service { 15 | 16 | final String TAG = "SSLDroid"; 17 | TcpProxy tp[]; 18 | private SSLDroidDbAdapter dbHelper; 19 | 20 | @Override 21 | public void onCreate() { 22 | 23 | dbHelper = new SSLDroidDbAdapter(this); 24 | dbHelper.open(); 25 | Cursor cursor = dbHelper.fetchAllTunnels(); 26 | 27 | int tunnelcount = cursor.getCount(); 28 | 29 | //skip start if the db is empty yet 30 | if (tunnelcount == 0) 31 | return; 32 | 33 | tp = new TcpProxy[tunnelcount]; 34 | 35 | int i; 36 | for (i=0; i 0; 72 | } 73 | 74 | /** 75 | * Return a Cursor over the list of all tunnels in the database 76 | * 77 | * @return Cursor over all notes 78 | */ 79 | public Cursor fetchAllTunnels() { 80 | return database.query(DATABASE_TABLE, new String[] { KEY_ROWID, 81 | KEY_NAME, KEY_LOCALPORT, KEY_REMOTEHOST, KEY_REMOTEPORT, KEY_PKCSFILE, 82 | KEY_PKCSPASS, KEY_CACERTFILE 83 | }, null, null, null, null, null); 84 | } 85 | 86 | /** 87 | * Return a Cursor over the list of all tunnels in the database 88 | * 89 | * @return Cursor over all notes 90 | */ 91 | public Cursor fetchAllLocalPorts() { 92 | return database.query(DATABASE_TABLE, new String[] { KEY_NAME, 93 | KEY_LOCALPORT 94 | }, null, null, null, null, null); 95 | } 96 | 97 | /** 98 | * Return a Cursor positioned at the defined tunnel 99 | */ 100 | public Cursor fetchStatus(String valuename) throws SQLException { 101 | return database.query(STATUS_TABLE, new String[] { 102 | KEY_STATUS_NAME, KEY_STATUS_VALUE 103 | }, 104 | KEY_STATUS_NAME + "='" + valuename + "'", null, null, null, null); 105 | } 106 | 107 | public Cursor getStopStatus() { 108 | return fetchStatus("stopped"); 109 | } 110 | 111 | public boolean setStopStatus() { 112 | ContentValues stopStatus = new ContentValues(); 113 | stopStatus.put(KEY_STATUS_NAME, "stopped"); 114 | stopStatus.put(KEY_STATUS_VALUE, "yes"); 115 | if (getStopStatus().getCount() == 0) 116 | database.insert(STATUS_TABLE, null, stopStatus); 117 | return true; 118 | } 119 | 120 | public boolean delStopStatus() { 121 | return database.delete(STATUS_TABLE, KEY_STATUS_NAME+"= 'stopped'", null) > 0; 122 | } 123 | 124 | public Cursor fetchTunnel(long rowId) throws SQLException { 125 | Cursor mCursor = database.query(true, DATABASE_TABLE, new String[] { 126 | KEY_ROWID, KEY_NAME, KEY_LOCALPORT, KEY_REMOTEHOST, KEY_REMOTEPORT, 127 | KEY_PKCSFILE, KEY_PKCSPASS, KEY_CACERTFILE 128 | }, 129 | KEY_ROWID + "=" + rowId, null, null, null, null, null); 130 | if (mCursor != null) { 131 | mCursor.moveToFirst(); 132 | } 133 | return mCursor; 134 | } 135 | 136 | private ContentValues createContentValues(String name, int localport, String remotehost, int remoteport, 137 | String pkcsfile, String pkcspass, String cacertfile) { 138 | ContentValues values = new ContentValues(); 139 | values.put(KEY_NAME, name); 140 | values.put(KEY_LOCALPORT, localport); 141 | values.put(KEY_REMOTEHOST, remotehost); 142 | values.put(KEY_REMOTEPORT, remoteport); 143 | values.put(KEY_REMOTEPORT, remoteport); 144 | values.put(KEY_PKCSFILE, pkcsfile); 145 | values.put(KEY_PKCSPASS, pkcspass); 146 | values.put(KEY_CACERTFILE, cacertfile); 147 | return values; 148 | } 149 | } 150 | 151 | 152 | -------------------------------------------------------------------------------- /src/hu/blint/ssldroid/SSLDroidGui.java: -------------------------------------------------------------------------------- 1 | package hu.blint.ssldroid; 2 | 3 | import android.app.ListActivity; 4 | import android.content.Intent; 5 | import android.database.Cursor; 6 | import android.os.Bundle; 7 | import android.util.Log; 8 | import android.view.ContextMenu; 9 | import android.view.ContextMenu.ContextMenuInfo; 10 | import android.view.Menu; 11 | import android.view.MenuInflater; 12 | import android.view.MenuItem; 13 | import android.view.View; 14 | import android.widget.AdapterView.AdapterContextMenuInfo; 15 | import android.widget.ListView; 16 | import android.widget.SimpleCursorAdapter; 17 | import hu.blint.ssldroid.db.SSLDroidDbAdapter; 18 | 19 | public class SSLDroidGui extends ListActivity { 20 | private SSLDroidDbAdapter dbHelper; 21 | private static final int ACTIVITY_CREATE = 0; 22 | private static final int ACTIVITY_EDIT = 1; 23 | private static final int DELETE_ID = Menu.FIRST + 1; 24 | private static final int CLONE_ID = Menu.FIRST + 2; 25 | private Cursor cursor; 26 | 27 | /** Called when the activity is first created. */ 28 | @Override 29 | public void onCreate(Bundle savedInstanceState) { 30 | super.onCreate(savedInstanceState); 31 | setContentView(R.layout.tunnel_list); 32 | this.getListView().setDividerHeight(2); 33 | dbHelper = new SSLDroidDbAdapter(this); 34 | dbHelper.open(); 35 | fillData(); 36 | registerForContextMenu(getListView()); 37 | } 38 | 39 | // Create the menu based on the XML defintion 40 | @Override 41 | public boolean onCreateOptionsMenu(Menu menu) { 42 | MenuInflater inflater = getMenuInflater(); 43 | inflater.inflate(R.menu.main, menu); 44 | return true; 45 | } 46 | 47 | // Reaction to the menu selection 48 | @Override 49 | public boolean onMenuItemSelected(int featureId, MenuItem item) { 50 | switch (item.getItemId()) { 51 | case R.id.addtunnel: 52 | createTunnel(); 53 | return true; 54 | case R.id.stopservice: 55 | Log.d("SSLDroid", "Stopping service"); 56 | stopService(new Intent(this, SSLDroid.class)); 57 | return true; 58 | case R.id.stopserviceforgood: 59 | Log.d("SSLDroid", "Stopping service until explicitly started"); 60 | dbHelper.setStopStatus(); 61 | stopService(new Intent(this, SSLDroid.class)); 62 | return true; 63 | case R.id.startservice: 64 | Log.d("SSLDroid", "Starting service"); 65 | dbHelper.delStopStatus(); 66 | startService(new Intent(this, SSLDroid.class)); 67 | return true; 68 | case R.id.readlogs: 69 | readLogs(); 70 | return true; 71 | } 72 | return super.onMenuItemSelected(featureId, item); 73 | } 74 | 75 | @Override 76 | public boolean onOptionsItemSelected(MenuItem item) { 77 | switch (item.getItemId()) { 78 | case R.id.addtunnel: 79 | createTunnel(); 80 | return true; 81 | case R.id.stopservice: 82 | Log.d("SSLDroid", "Stopping service"); 83 | stopService(new Intent(this, SSLDroid.class)); 84 | return true; 85 | case R.id.stopserviceforgood: 86 | Log.d("SSLDroid", "Stopping service until explicitly started"); 87 | dbHelper.setStopStatus(); 88 | stopService(new Intent(this, SSLDroid.class)); 89 | return true; 90 | case R.id.startservice: 91 | Log.d("SSLDroid", "Starting service"); 92 | dbHelper.delStopStatus(); 93 | startService(new Intent(this, SSLDroid.class)); 94 | return true; 95 | case R.id.readlogs: 96 | readLogs(); 97 | return true; 98 | //case R.id.provision: 99 | // getProvisioning(); 100 | // return true; 101 | } 102 | return super.onOptionsItemSelected(item); 103 | } 104 | 105 | @Override 106 | public boolean onContextItemSelected(MenuItem item) { 107 | AdapterContextMenuInfo info = (AdapterContextMenuInfo) item 108 | .getMenuInfo(); 109 | switch (item.getItemId()) { 110 | case DELETE_ID: 111 | dbHelper.deleteTunnel(info.id); 112 | fillData(); 113 | return true; 114 | case CLONE_ID: 115 | cloneTunnel(info.id); 116 | fillData(); 117 | return true; 118 | } 119 | return super.onContextItemSelected(item); 120 | } 121 | 122 | private void createTunnel() { 123 | Intent i = new Intent(this, SSLDroidTunnelDetails.class); 124 | startActivityForResult(i, ACTIVITY_CREATE); 125 | } 126 | 127 | public void cloneTunnel(long id) { 128 | Intent i = new Intent(this, SSLDroidTunnelDetails.class); 129 | i.putExtra(SSLDroidDbAdapter.KEY_ROWID, id); 130 | i.putExtra("doClone", true); 131 | startActivityForResult(i, ACTIVITY_EDIT); 132 | } 133 | 134 | private void readLogs() { 135 | Intent i = new Intent(this, SSLDroidReadLogs.class); 136 | startActivity(i); 137 | } 138 | 139 | @SuppressWarnings("unused") 140 | private void getProvisioning() { 141 | //Intent i = new Intent(this, SSLDroidProvisioning.class); 142 | //startActivity(i); 143 | } 144 | 145 | // ListView and view (row) on which was clicked, position and 146 | @Override 147 | protected void onListItemClick(ListView l, View v, int position, long id) { 148 | super.onListItemClick(l, v, position, id); 149 | Intent i = new Intent(this, SSLDroidTunnelDetails.class); 150 | i.putExtra(SSLDroidDbAdapter.KEY_ROWID, id); 151 | // Activity returns an result if called with startActivityForResult 152 | startActivityForResult(i, ACTIVITY_EDIT); 153 | } 154 | 155 | // Called with the result of the other activity 156 | // requestCode was the origin request code send to the activity 157 | // resultCode is the return code, 0 is everything is ok 158 | // intend can be use to get some data from the caller 159 | @Override 160 | protected void onActivityResult(int requestCode, int resultCode, 161 | Intent intent) { 162 | super.onActivityResult(requestCode, resultCode, intent); 163 | fillData(); 164 | 165 | } 166 | 167 | private void fillData() { 168 | cursor = dbHelper.fetchAllTunnels(); 169 | startManagingCursor(cursor); 170 | 171 | String[] from = new String[] { SSLDroidDbAdapter.KEY_NAME }; 172 | int[] to = new int[] { R.id.text1 }; 173 | 174 | // Now create an array adapter and set it to display using our row 175 | SimpleCursorAdapter tunnels = new SimpleCursorAdapter(this, 176 | R.layout.tunnel_list_item, cursor, from, to); 177 | setListAdapter(tunnels); 178 | } 179 | 180 | @Override 181 | public void onCreateContextMenu(ContextMenu menu, View v, 182 | ContextMenuInfo menuInfo) { 183 | super.onCreateContextMenu(menu, v, menuInfo); 184 | menu.add(0, DELETE_ID, 0, R.string.menu_delete); 185 | menu.add(0, CLONE_ID, 0, R.string.menu_clone); 186 | } 187 | 188 | @Override 189 | public void onDestroy (){ 190 | cursor.close(); 191 | dbHelper.close(); 192 | super.onDestroy(); 193 | } 194 | 195 | } 196 | -------------------------------------------------------------------------------- /src/hu/blint/ssldroid/TcpProxyServerThread.java: -------------------------------------------------------------------------------- 1 | package hu.blint.ssldroid; 2 | 3 | import java.io.FileInputStream; 4 | import java.io.FileNotFoundException; 5 | import java.io.IOException; 6 | import java.io.InputStream; 7 | import java.net.Inet4Address; 8 | import java.net.InetAddress; 9 | import java.net.ServerSocket; 10 | import java.net.Socket; 11 | import java.net.SocketException; 12 | import java.security.KeyManagementException; 13 | import java.security.KeyStore; 14 | import java.security.KeyStoreException; 15 | import java.security.NoSuchAlgorithmException; 16 | import java.security.SecureRandom; 17 | import java.security.UnrecoverableKeyException; 18 | import java.security.cert.CertificateException; 19 | import java.security.cert.CertificateFactory; 20 | import java.security.cert.X509Certificate; 21 | 22 | import javax.net.ssl.KeyManagerFactory; 23 | import javax.net.ssl.SSLContext; 24 | import javax.net.ssl.SSLSocket; 25 | import javax.net.ssl.SSLSocketFactory; 26 | import javax.net.ssl.TrustManager; 27 | import javax.net.ssl.X509TrustManager; 28 | 29 | import android.util.Log; 30 | 31 | public class TcpProxyServerThread extends Thread { 32 | 33 | String tunnelName; 34 | int listenPort; 35 | String tunnelHost; 36 | int tunnelPort; 37 | String keyFile, keyPass, caFile; 38 | Relay inRelay, outRelay; 39 | ServerSocket ss = null; 40 | int sessionid = 0; 41 | private SSLSocketFactory sslSocketFactory; 42 | private X509Certificate caCert; 43 | 44 | public TcpProxyServerThread(String tunnelName, int listenPort, String tunnelHost, int tunnelPort, String keyFile, String keyPass, String caFile) { 45 | this.tunnelName = tunnelName; 46 | this.listenPort = listenPort; 47 | this.tunnelHost = tunnelHost; 48 | this.tunnelPort = tunnelPort; 49 | this.keyFile = keyFile; 50 | this.keyPass = keyPass; 51 | this.caFile = caFile; 52 | 53 | // Loading the CA cert 54 | if (caFile != null && !caFile.isEmpty()) { 55 | InputStream inStream = null; 56 | try { 57 | inStream = new FileInputStream(this.caFile); 58 | CertificateFactory cf = CertificateFactory.getInstance("X.509"); 59 | caCert = (X509Certificate) cf.generateCertificate(inStream); 60 | } catch (Exception ex) { 61 | //FIXME 62 | } finally { 63 | try { 64 | if (inStream != null) 65 | inStream.close(); 66 | } catch (IOException ex) { } 67 | } 68 | } 69 | } 70 | 71 | // Create a trust manager that does not validate certificate chains 72 | // TODO: handle this somehow properly (popup if cert is untrusted?) 73 | // TODO: cacert + crl should be configurable 74 | /*TrustManager[] trustAllCerts = new TrustManager[] { 75 | new X509TrustManager() { 76 | public java.security.cert.X509Certificate[] getAcceptedIssuers() { 77 | return null; 78 | } 79 | public void checkClientTrusted( 80 | java.security.cert.X509Certificate[] certs, String authType) { 81 | } 82 | public void checkServerTrusted( 83 | java.security.cert.X509Certificate[] certs, String authType) { 84 | } 85 | } 86 | };*/ 87 | 88 | // FIXME: https://stackoverflow.com/questions/6629473/validate-x-509-certificate-agains-concrete-ca-java 89 | TrustManager[] trustCaCert = new TrustManager[] { 90 | new X509TrustManager() { 91 | public java.security.cert.X509Certificate[] getAcceptedIssuers() { 92 | return null; 93 | } 94 | public void checkClientTrusted( 95 | java.security.cert.X509Certificate[] certs, String authType) { 96 | } 97 | public void checkServerTrusted( 98 | java.security.cert.X509Certificate[] certs, String authType) throws CertificateException { 99 | 100 | if (caFile == null || caFile.isEmpty()) //No CA file - trust all 101 | return; 102 | 103 | if (certs == null || certs.length == 0) { 104 | throw new IllegalArgumentException("null or zero-length certificate chain"); 105 | } 106 | 107 | if (authType == null || authType.length() == 0) { 108 | throw new IllegalArgumentException("null or zero-length authentication type"); 109 | } 110 | 111 | if (caCert == null) { //CA file specified, but no CA cert loaded 112 | throw new CertificateException("Invalid CA cert"); 113 | } 114 | 115 | //Check if top-most cert is our CA's 116 | if(!certs[0].equals(caCert)){ 117 | try 118 | { //Not our CA's. Check if it has been signed by our CA 119 | certs[0].verify(caCert.getPublicKey()); 120 | } 121 | catch(Exception e){ 122 | throw new CertificateException("Certificate not trusted",e); 123 | } 124 | } 125 | 126 | //If we end here certificate is trusted. Check if any cert in the chain has expired. 127 | try{ 128 | for (X509Certificate cert : certs) { 129 | cert.checkValidity(); 130 | } 131 | } 132 | catch(Exception e){ 133 | throw new CertificateException("Certificate not trusted. It has expired",e); 134 | } 135 | } 136 | } 137 | }; 138 | 139 | 140 | 141 | public final SSLSocketFactory getSocketFactory(String pkcsFile, 142 | String pwd, int sessionid) { 143 | if (sslSocketFactory == null) { 144 | try { 145 | KeyManagerFactory keyManagerFactory; 146 | if (pkcsFile != null && !pkcsFile.isEmpty()) { 147 | keyManagerFactory = KeyManagerFactory.getInstance("X509"); 148 | KeyStore keyStore = KeyStore.getInstance("PKCS12"); 149 | keyStore.load(new FileInputStream(pkcsFile), pwd.toCharArray()); 150 | keyManagerFactory.init(keyStore, pwd.toCharArray()); 151 | } else { 152 | keyManagerFactory = null; 153 | } 154 | SSLContext context = SSLContext.getInstance("TLS"); 155 | context.init(keyManagerFactory == null ? null : keyManagerFactory.getKeyManagers(), trustCaCert, 156 | new SecureRandom()); 157 | sslSocketFactory = context.getSocketFactory(); 158 | } catch (FileNotFoundException e) { 159 | Log.d("SSLDroid", tunnelName+"/"+sessionid+": Error loading the client certificate file:" 160 | + e.toString()); 161 | } catch (KeyManagementException e) { 162 | Log.d("SSLDroid", tunnelName+"/"+sessionid+": No SSL algorithm support: " + e.toString()); 163 | } catch (NoSuchAlgorithmException e) { 164 | Log.d("SSLDroid", tunnelName+"/"+sessionid+": No common SSL algorithm found: " + e.toString()); 165 | } catch (KeyStoreException e) { 166 | Log.d("SSLDroid", tunnelName+"/"+sessionid+": Error setting up keystore:" + e.toString()); 167 | } catch (java.security.cert.CertificateException e) { 168 | Log.d("SSLDroid", tunnelName+"/"+sessionid+": Error loading the client certificate:" + e.toString()); 169 | } catch (IOException e) { 170 | Log.d("SSLDroid", tunnelName+"/"+sessionid+": Error loading the client certificate file:" + e.toString()); 171 | } catch (UnrecoverableKeyException e) { 172 | Log.d("SSLDroid", tunnelName+"/"+sessionid+": Error loading the client certificate:" + e.toString()); 173 | } 174 | } 175 | return sslSocketFactory; 176 | } 177 | 178 | public void run() { 179 | try { 180 | InetAddress bindAddr = Inet4Address.getByAddress(new byte[] { 127, 0, 0, 1 }); 181 | ss = new ServerSocket(listenPort, 50, bindAddr); 182 | Log.d("SSLDroid", "Listening for connections on "+bindAddr.getHostAddress()+":"+ 183 | + this.listenPort + " ..."); 184 | } catch (Exception e) { 185 | Log.d("SSLDroid", "Error setting up listening socket: " + e.toString()); 186 | return; 187 | } 188 | while (true) { 189 | try { 190 | Thread fromBrowserToServer = null; 191 | Thread fromServerToBrowser = null; 192 | 193 | if (isInterrupted()) { 194 | Log.d("SSLDroid", tunnelName+"/"+sessionid+": Interrupted server thread, closing sockets..."); 195 | ss.close(); 196 | return; 197 | } 198 | // accept the connection from my client 199 | Socket sc = null; 200 | try { 201 | sc = ss.accept(); 202 | sessionid++; 203 | } catch (SocketException e) { 204 | Log.d("SSLDroid", "Accept failure: " + e.toString()); 205 | } 206 | 207 | Socket st = null; 208 | try { 209 | final SSLSocketFactory sf = getSocketFactory(this.keyFile, this.keyPass, this.sessionid); 210 | st = (SSLSocket) sf.createSocket(this.tunnelHost, this.tunnelPort); 211 | setSNIHost(sf, (SSLSocket) st, this.tunnelHost); 212 | ((SSLSocket) st).startHandshake(); 213 | } catch (IOException e) { 214 | Log.d("SSLDroid", tunnelName+"/"+sessionid+": SSL failure: " + e.toString()); 215 | return; 216 | } 217 | catch (Exception e) { 218 | Log.d("SSLDroid", tunnelName+"/"+sessionid+": SSL failure: " + e.toString()); 219 | if (sc != null) 220 | { 221 | sc.close(); 222 | } 223 | return; 224 | } 225 | 226 | if (sc == null || st == null) { 227 | Log.d("SSLDroid", tunnelName+"/"+sessionid+": Trying socket operation on a null socket, returning"); 228 | return; 229 | } 230 | Log.d("SSLDroid", tunnelName+"/"+sessionid+": Tunnelling port " 231 | + listenPort + " to port " 232 | + tunnelPort + " on host " 233 | + tunnelHost + " ..."); 234 | 235 | // relay the stuff through 236 | fromBrowserToServer = new Relay( 237 | this, sc.getInputStream(), st.getOutputStream(), "client", sessionid); 238 | fromServerToBrowser = new Relay( 239 | this, st.getInputStream(), sc.getOutputStream(), "server", sessionid); 240 | 241 | fromBrowserToServer.start(); 242 | fromServerToBrowser.start(); 243 | 244 | } catch (IOException ee) { 245 | Log.d("SSLDroid", tunnelName+"/"+sessionid+": Ouch: " + ee.toString()); 246 | } 247 | } 248 | } 249 | 250 | private void setSNIHost(final SSLSocketFactory factory, final SSLSocket socket, final String hostname) { 251 | if (factory instanceof android.net.SSLCertificateSocketFactory && android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) { 252 | ((android.net.SSLCertificateSocketFactory)factory).setHostname(socket, hostname); 253 | } else { 254 | try { 255 | socket.getClass().getMethod("setHostname", String.class).invoke(socket, hostname); 256 | } catch (Throwable e) { 257 | // ignore any error, we just can't set the hostname... 258 | } 259 | } 260 | } 261 | }; 262 | 263 | -------------------------------------------------------------------------------- /assets/ssldroid_logo.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 21 | 23 | 24 | 26 | image/svg+xml 27 | 29 | 30 | 31 | 32 | 33 | 35 | 42 | 43 | 63 | 66 | 70 | 74 | 78 | 82 | 86 | 90 | 91 | 92 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /src/hu/blint/ssldroid/SSLDroidTunnelDetails.java: -------------------------------------------------------------------------------- 1 | package hu.blint.ssldroid; 2 | 3 | import java.io.File; 4 | import java.io.FileInputStream; 5 | import java.io.IOException; 6 | import java.net.InetAddress; 7 | import java.net.UnknownHostException; 8 | import java.security.KeyStore; 9 | import java.security.KeyStoreException; 10 | import java.security.NoSuchAlgorithmException; 11 | import java.security.UnrecoverableKeyException; 12 | import java.security.cert.CertificateException; 13 | 14 | import java.security.cert.Certificate; 15 | import javax.security.cert.CertificateExpiredException; 16 | import javax.security.cert.X509Certificate; 17 | import java.util.Collections; 18 | import java.util.Enumeration; 19 | import java.util.LinkedList; 20 | import java.util.List; 21 | import java.util.ListIterator; 22 | 23 | import android.app.Activity; 24 | import android.app.AlertDialog; 25 | import android.content.Context; 26 | import android.content.DialogInterface; 27 | import android.content.Intent; 28 | import android.content.DialogInterface.OnClickListener; 29 | import android.database.Cursor; 30 | import android.net.ConnectivityManager; 31 | import android.os.AsyncTask; 32 | import android.os.Bundle; 33 | import android.os.Environment; 34 | import android.util.Log; 35 | import android.view.View; 36 | import android.widget.Button; 37 | import android.widget.EditText; 38 | import android.widget.Toast; 39 | import hu.blint.ssldroid.db.SSLDroidDbAdapter; 40 | 41 | //TODO: cacert + crl should be configurable for the tunnel 42 | //TODO: test connection button 43 | 44 | public class SSLDroidTunnelDetails extends Activity { 45 | 46 | private final class SSLDroidTunnelHostnameChecker extends AsyncTask { 47 | 48 | @Override 49 | protected Boolean doInBackground(String... params) { 50 | ConnectivityManager conMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); 51 | String hostname = params[0]; 52 | 53 | if ( conMgr.getActiveNetworkInfo() != null || conMgr.getActiveNetworkInfo().isAvailable()) { 54 | try { 55 | InetAddress.getByName(hostname); 56 | } catch (UnknownHostException e) { 57 | return false; 58 | } 59 | } 60 | return true; 61 | } 62 | protected void onPostExecute(Boolean result) { 63 | if (result == false) { 64 | Toast.makeText(getBaseContext(), "Remote host not found, please recheck...", Toast.LENGTH_LONG).show(); 65 | } 66 | } 67 | } 68 | 69 | private final class SSLDroidTunnelValidator implements View.OnClickListener { 70 | public void onClick(View view) { 71 | if (name.getText().length() == 0) { 72 | Toast.makeText(getBaseContext(), "Required tunnel name parameter not set up, skipping save", Toast.LENGTH_LONG).show(); 73 | return; 74 | } 75 | //local port validation 76 | if (localport.getText().length() == 0) { 77 | Toast.makeText(getBaseContext(), "Required local port parameter not set up, skipping save", Toast.LENGTH_LONG).show(); 78 | return; 79 | } 80 | else { 81 | //local port should be between 1025-65535 82 | int cPort = 0; 83 | try { 84 | cPort = Integer.parseInt(localport.getText().toString()); 85 | } catch (NumberFormatException e) { 86 | Toast.makeText(getBaseContext(), "Local port parameter has invalid number format", Toast.LENGTH_LONG).show(); 87 | return; 88 | } 89 | if (cPort < 1025 || cPort > 65535) { 90 | Toast.makeText(getBaseContext(), "Local port parameter not in valid range (1025-65535)", Toast.LENGTH_LONG).show(); 91 | return; 92 | } 93 | //check if the requested port is colliding with a port already configured for another tunnel 94 | SSLDroidDbAdapter dbHelper = new SSLDroidDbAdapter(getBaseContext()); 95 | dbHelper.open(); 96 | Cursor cursor = dbHelper.fetchAllLocalPorts(); 97 | startManagingCursor(cursor); 98 | while (cursor.moveToNext()) { 99 | String cDbName = cursor.getString(cursor.getColumnIndexOrThrow(SSLDroidDbAdapter.KEY_NAME)); 100 | int cDbPort = cursor.getInt(cursor.getColumnIndexOrThrow(SSLDroidDbAdapter.KEY_LOCALPORT)); 101 | if (cPort == cDbPort && !cDbName.contentEquals(name.getText().toString())) { 102 | Toast.makeText(getBaseContext(), "Local port already configured in tunnel '"+cDbName+"', please change...", Toast.LENGTH_LONG).show(); 103 | return; 104 | } 105 | } 106 | } 107 | //remote host validation 108 | if (remotehost.getText().length() == 0) { 109 | Toast.makeText(getBaseContext(), "Required remote host parameter not set up, skipping save", Toast.LENGTH_LONG).show(); 110 | return; 111 | } 112 | else { 113 | //if we have interwebs access, the remote host should exist 114 | String hostname = remotehost.getText().toString(); 115 | new SSLDroidTunnelHostnameChecker().execute(hostname); 116 | } 117 | 118 | //remote port validation 119 | if (remoteport.getText().length() == 0) { 120 | Toast.makeText(getBaseContext(), "Required remote port parameter not set up, skipping save", Toast.LENGTH_LONG).show(); 121 | return; 122 | } 123 | else { 124 | //remote port should be between 1025-65535 125 | int cPort = 0; 126 | try { 127 | cPort = Integer.parseInt(remoteport.getText().toString()); 128 | } catch (NumberFormatException e) { 129 | Toast.makeText(getBaseContext(), "Remote port parameter has invalid number format", Toast.LENGTH_LONG).show(); 130 | return; 131 | } 132 | if (cPort < 1 || cPort > 65535) { 133 | Toast.makeText(getBaseContext(), "Remote port parameter not in valid range (1-65535)", Toast.LENGTH_LONG).show(); 134 | return; 135 | } 136 | } 137 | if (pkcsfile.getText().length() != 0) { 138 | // try to open pkcs12 file with password 139 | String cPkcsFile = pkcsfile.getText().toString(); 140 | String cPkcsPass = pkcspass.getText().toString(); 141 | try { 142 | if (checkKeys(cPkcsFile, cPkcsPass) == false) { 143 | return; 144 | } 145 | } catch (Exception e) { 146 | Toast.makeText(getBaseContext(), "PKCS12 problem: "+e.getMessage(), Toast.LENGTH_LONG).show(); 147 | return; 148 | } 149 | } 150 | saveState(); 151 | setResult(RESULT_OK); 152 | finish(); 153 | } 154 | } 155 | 156 | private EditText name; 157 | private EditText localport; 158 | private EditText remotehost; 159 | private EditText remoteport; 160 | private EditText pkcsfile; 161 | private EditText pkcspass; 162 | private EditText cacertfile; 163 | private Long rowId; 164 | private Boolean doClone = false; 165 | private SSLDroidDbAdapter dbHelper; 166 | 167 | @Override 168 | protected void onCreate(Bundle bundle) { 169 | super.onCreate(bundle); 170 | dbHelper = new SSLDroidDbAdapter(this); 171 | dbHelper.open(); 172 | setContentView(R.layout.tunnel_details); 173 | 174 | Button confirmButton = (Button) findViewById(R.id.tunnel_apply_button); 175 | name = (EditText) findViewById(R.id.name); 176 | localport = (EditText) findViewById(R.id.localport); 177 | remotehost = (EditText) findViewById(R.id.remotehost); 178 | remoteport = (EditText) findViewById(R.id.remoteport); 179 | pkcsfile = (EditText) findViewById(R.id.pkcsfile); 180 | pkcspass = (EditText) findViewById(R.id.pkcspass); 181 | cacertfile = (EditText) findViewById(R.id.cacertfile); 182 | Button pickFile = (Button) findViewById(R.id.pickFile); 183 | Button pickCaFile = (Button) findViewById(R.id.pickCaFile); 184 | 185 | pickFile.setOnClickListener(new View.OnClickListener() { 186 | public void onClick(View view) { 187 | pickFileSimple(pkcsfile, pkcspass); 188 | } 189 | }); 190 | pickCaFile.setOnClickListener(new View.OnClickListener() { 191 | public void onClick(View view) { 192 | pickFileSimple(cacertfile, null); 193 | } 194 | }); 195 | 196 | rowId = null; 197 | Bundle extras = getIntent().getExtras(); 198 | rowId = (bundle == null) ? null : (Long) bundle 199 | .getSerializable(SSLDroidDbAdapter.KEY_ROWID); 200 | if (extras != null) { 201 | rowId = extras.getLong(SSLDroidDbAdapter.KEY_ROWID); 202 | doClone = extras.getBoolean("doClone", false); 203 | } 204 | populateFields(); 205 | confirmButton.setOnClickListener(new SSLDroidTunnelValidator()); 206 | } 207 | 208 | final List getFileNames(File url, File baseurl) 209 | { 210 | final List names = new LinkedList(); 211 | File[] files = url.listFiles(); 212 | if (files != null && files.length > 0) { 213 | for (File file : url.listFiles()) { 214 | if (file.getName().startsWith(".")) 215 | continue; 216 | names.add(file); 217 | } 218 | } 219 | return names; 220 | } 221 | 222 | private void showFiles(final List names, final File baseurl, final EditText editBox, final View nextView) { 223 | final String[] namesList = new String[names.size()]; // = names.toArray(new String[] {}); 224 | ListIterator filelist = names.listIterator(); 225 | int i = 0; 226 | while (filelist.hasNext()) { 227 | File file = filelist.next(); 228 | if (file.isDirectory()) 229 | namesList[i] = file.getAbsolutePath().replaceFirst(baseurl+"/", "")+" (...)"; 230 | else 231 | namesList[i] = file.getAbsolutePath().replaceFirst(baseurl+"/", ""); 232 | i++; 233 | } 234 | //Log.d("SSLDroid", "Gathered file names: "+namesList.toString()); 235 | 236 | // prompt user to select any file from the sdcard root 237 | new AlertDialog.Builder(SSLDroidTunnelDetails.this) 238 | .setTitle(R.string.file_pick) 239 | .setItems(namesList, new OnClickListener() { 240 | public void onClick(DialogInterface arg0, int arg1) { 241 | File name = names.get(arg1); 242 | if (name.isDirectory()) { 243 | List names_ = getFileNames(name, baseurl); 244 | Collections.sort(names_); 245 | if (names_.size() > 0) { 246 | showFiles(names_, baseurl, editBox, nextView); 247 | } 248 | else 249 | Toast.makeText(getBaseContext(), "Empty directory", Toast.LENGTH_LONG).show(); 250 | } 251 | if (name.isFile()) { 252 | editBox.setText(name.getAbsolutePath()); 253 | if (nextView != null) 254 | nextView.requestFocus(); 255 | } 256 | } 257 | }) 258 | //create a Back button (shouldn't go above base URL) 259 | .setNeutralButton(R.string.back, new OnClickListener() { 260 | public void onClick(DialogInterface arg0, int arg1) { 261 | if (names.size() == 0) 262 | return; 263 | File name = names.get(0); 264 | if (!name.getParentFile().equals(baseurl)) { 265 | List names_ = getFileNames(name.getParentFile().getParentFile(), baseurl); 266 | Collections.sort(names_); 267 | if (names_.size() > 0) { 268 | showFiles(names_, baseurl, editBox, nextView); 269 | } 270 | else 271 | return; 272 | } 273 | } 274 | }) 275 | .setNegativeButton(android.R.string.cancel, null).create().show(); 276 | } 277 | 278 | //pick a file from /sdcard, courtesy of ConnectBot 279 | private void pickFileSimple(final EditText editBox, final View nextView) { 280 | // build list of all files in sdcard root 281 | final File sdcard = Environment.getExternalStorageDirectory(); 282 | Log.d("SSLDroid", "SD Card location: "+sdcard.toString()); 283 | 284 | // Don't show a dialog if the SD card is completely absent. 285 | final String state = Environment.getExternalStorageState(); 286 | if (!Environment.MEDIA_MOUNTED_READ_ONLY.equals(state) 287 | && !Environment.MEDIA_MOUNTED.equals(state)) { 288 | new AlertDialog.Builder(SSLDroidTunnelDetails.this) 289 | .setMessage(R.string.alert_sdcard_absent) 290 | .setNegativeButton(android.R.string.cancel, null).create().show(); 291 | return; 292 | } 293 | 294 | List names = new LinkedList(); 295 | names = getFileNames(sdcard, sdcard); 296 | Collections.sort(names); 297 | showFiles(names, sdcard, editBox, nextView); 298 | } 299 | 300 | private void populateFields() { 301 | if (rowId != null) { 302 | Cursor Tunnel = dbHelper.fetchTunnel(rowId); 303 | startManagingCursor(Tunnel); 304 | 305 | if(!doClone){ 306 | name.setText(Tunnel.getString(Tunnel 307 | .getColumnIndexOrThrow(SSLDroidDbAdapter.KEY_NAME))); 308 | localport.setText(Tunnel.getString(Tunnel 309 | .getColumnIndexOrThrow(SSLDroidDbAdapter.KEY_LOCALPORT))); 310 | } 311 | remotehost.setText(Tunnel.getString(Tunnel 312 | .getColumnIndexOrThrow(SSLDroidDbAdapter.KEY_REMOTEHOST))); 313 | remoteport.setText(Tunnel.getString(Tunnel 314 | .getColumnIndexOrThrow(SSLDroidDbAdapter.KEY_REMOTEPORT))); 315 | pkcsfile.setText(Tunnel.getString(Tunnel 316 | .getColumnIndexOrThrow(SSLDroidDbAdapter.KEY_PKCSFILE))); 317 | pkcspass.setText(Tunnel.getString(Tunnel 318 | .getColumnIndexOrThrow(SSLDroidDbAdapter.KEY_PKCSPASS))); 319 | cacertfile.setText(Tunnel.getString(Tunnel 320 | .getColumnIndexOrThrow(SSLDroidDbAdapter.KEY_CACERTFILE))); 321 | } 322 | } 323 | 324 | public boolean checkKeys(String inCertPath, String passw) throws Exception { 325 | try { 326 | FileInputStream in_cert = new FileInputStream(inCertPath); 327 | KeyStore myStore = KeyStore.getInstance("PKCS12"); 328 | myStore.load(in_cert, passw.toCharArray()); 329 | Enumeration eAliases = myStore.aliases(); 330 | while (eAliases.hasMoreElements()) { 331 | String strAlias = (String) eAliases.nextElement(); 332 | if (myStore.isKeyEntry(strAlias)) { 333 | // try to retrieve the private key part from PKCS12 certificate 334 | myStore.getKey(strAlias, passw.toCharArray()); 335 | Certificate mycrt = myStore.getCertificate(strAlias); 336 | X509Certificate mycert = X509Certificate.getInstance(mycrt.getEncoded()); 337 | try { 338 | mycert.checkValidity(); 339 | } catch (CertificateExpiredException e) { 340 | Toast.makeText(getBaseContext(), "PKCS12 problem: "+e.getMessage(), Toast.LENGTH_LONG).show(); 341 | return false; 342 | } 343 | } 344 | } 345 | 346 | } catch (KeyStoreException e) { 347 | Toast.makeText(getBaseContext(), "PKCS12 problem: "+e.getMessage(), Toast.LENGTH_LONG).show(); 348 | return false; 349 | } catch (NoSuchAlgorithmException e) { 350 | Toast.makeText(getBaseContext(), "PKCS12 problem: "+e.getMessage(), Toast.LENGTH_LONG).show(); 351 | return false; 352 | } catch (CertificateException e) { 353 | Toast.makeText(getBaseContext(), "PKCS12 problem: "+e.getMessage(), Toast.LENGTH_LONG).show(); 354 | return false; 355 | } catch (IOException e) { 356 | Toast.makeText(getBaseContext(), "PKCS12 problem: "+e.getMessage(), Toast.LENGTH_LONG).show(); 357 | return false; 358 | } catch (UnrecoverableKeyException e) { 359 | Toast.makeText(getBaseContext(), "PKCS12 problem: "+e.getMessage(), Toast.LENGTH_LONG).show(); 360 | return false; 361 | } 362 | return true; 363 | } 364 | 365 | 366 | protected void onSaveInstanceState(Bundle outState) { 367 | super.onSaveInstanceState(outState); 368 | saveState(); 369 | outState.putSerializable(SSLDroidDbAdapter.KEY_ROWID, rowId); 370 | } 371 | 372 | @Override 373 | protected void onPause() { 374 | super.onPause(); 375 | //saveState(); 376 | } 377 | 378 | @Override 379 | protected void onResume() { 380 | super.onResume(); 381 | populateFields(); 382 | } 383 | 384 | private void saveState() { 385 | String sName = name.getText().toString(); 386 | int sLocalport = 0; 387 | try { 388 | sLocalport = Integer.parseInt(localport.getText().toString()); 389 | } catch (NumberFormatException e) { 390 | } 391 | String sRemotehost = remotehost.getText().toString(); 392 | int sRemoteport = 0; 393 | try { 394 | sRemoteport = Integer.parseInt(remoteport.getText().toString()); 395 | } catch (NumberFormatException e) { 396 | } 397 | String sPkcsfile = pkcsfile.getText().toString(); 398 | String sPkcspass = pkcspass.getText().toString(); 399 | String sCacertfile = cacertfile.getText().toString(); 400 | 401 | //make sure that we have all of our values correctly set 402 | if (sName.length() == 0) { 403 | return; 404 | } 405 | if (sLocalport == 0) { 406 | return; 407 | } 408 | if (sRemotehost.length() == 0) { 409 | return; 410 | } 411 | if (sRemoteport == 0) { 412 | return; 413 | } 414 | 415 | if (rowId == null || doClone) { 416 | long id = dbHelper.createTunnel(sName, sLocalport, sRemotehost, 417 | sRemoteport, sPkcsfile, sPkcspass, sCacertfile); 418 | if (id > 0) { 419 | rowId = id; 420 | } 421 | } else { 422 | dbHelper.updateTunnel(rowId, sName, sLocalport, sRemotehost, sRemoteport, 423 | sPkcsfile, sPkcspass, sCacertfile); 424 | } 425 | Log.d("SSLDroid", "Saving settings..."); 426 | 427 | //restart the service 428 | stopService(new Intent(this, SSLDroid.class)); 429 | startService(new Intent(this, SSLDroid.class)); 430 | Log.d("SSLDroid", "Restarting service after settings save..."); 431 | 432 | } 433 | } 434 | 435 | --------------------------------------------------------------------------------