├── .gitignore ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── io │ │ └── deep │ │ └── superapp │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── aidl │ │ └── io │ │ │ └── deep │ │ │ └── superapp │ │ │ ├── ITest1.aidl │ │ │ └── ITest2.aidl │ ├── java │ │ └── io │ │ │ └── deep │ │ │ └── superapp │ │ │ ├── MainActivity.java │ │ │ └── test │ │ │ ├── Main1.java │ │ │ └── Main2.java │ └── res │ │ ├── drawable-v24 │ │ └── ic_launcher_foreground.xml │ │ ├── drawable │ │ └── ic_launcher_background.xml │ │ ├── layout │ │ └── activity_main.xml │ │ ├── mipmap-anydpi-v26 │ │ ├── ic_launcher.xml │ │ └── ic_launcher_round.xml │ │ ├── mipmap-hdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-mdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── values-night │ │ └── themes.xml │ │ └── values │ │ ├── colors.xml │ │ ├── strings.xml │ │ └── themes.xml │ └── test │ └── java │ └── io │ └── deep │ └── superapp │ └── ExampleUnitTest.java ├── build.gradle ├── core ├── .gitignore ├── build.gradle ├── consumer-rules.pro ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── io │ │ └── sapp │ │ └── core │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── aidl │ │ └── io │ │ │ └── sapp │ │ │ └── core │ │ │ └── internal │ │ │ └── IRootIPC.aidl │ ├── cpp │ │ ├── CMakeLists.txt │ │ └── main.cpp │ ├── java │ │ └── io │ │ │ └── sapp │ │ │ └── core │ │ │ ├── internal │ │ │ ├── AppProcess.java │ │ │ ├── Debugger.java │ │ │ ├── IPCMain.java │ │ │ ├── IPCManager.java │ │ │ ├── IPCServer.java │ │ │ ├── Linker.java │ │ │ ├── Policies.java │ │ │ ├── Reflection.java │ │ │ ├── RootIPC.java │ │ │ ├── RootIPCReceiver.java │ │ │ └── RootServer.java │ │ │ └── utils │ │ │ ├── Debug.java │ │ │ ├── Shell.java │ │ │ ├── ShellNotClosedException.java │ │ │ ├── ShellOnMainThreadException.java │ │ │ └── StreamGobbler.java │ └── res │ │ └── values │ │ └── theme.xml │ └── test │ └── java │ └── io │ └── sapp │ └── core │ └── ExampleUnitTest.java ├── dynamic ├── .gitignore ├── README.md ├── build.gradle ├── consumer-rules.pro ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── io │ │ └── dynamic │ │ └── loader │ │ └── ExampleInstrumentedTest.java │ ├── main │ └── AndroidManifest.xml │ └── test │ └── java │ └── io │ └── dynamic │ └── loader │ └── ExampleUnitTest.java ├── gradle.properties ├── gradlew ├── gradlew.bat ├── hide ├── .gitignore ├── README.md ├── build.gradle ├── consumer-rules.pro ├── libs │ ├── ManifestEditor-1.0.2.jar │ └── bcprov-jdk15-143.jar ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── io │ │ └── app │ │ └── hide │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── io │ │ │ └── app │ │ │ └── hide │ │ │ ├── activity │ │ │ └── InstallActivity.java │ │ │ ├── apksigner │ │ │ ├── KeyHelper.java │ │ │ └── SignApk.java │ │ │ ├── proc │ │ │ ├── HideProcess.java │ │ │ └── Main.java │ │ │ └── utils │ │ │ └── RandomInfo.java │ └── res │ │ └── layout │ │ └── activity_install.xml │ └── test │ └── java │ └── io │ └── app │ └── hide │ └── ExampleUnitTest.java └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/caches 5 | /.idea/libraries 6 | /.idea/modules.xml 7 | /.idea/workspace.xml 8 | /.idea/navEditor.xml 9 | /.idea/assetWizardSettings.xml 10 | .DS_Store 11 | /build 12 | /captures 13 | .externalNativeBuild 14 | .cxx 15 | local.properties 16 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DeepApp 2 | [![](https://jitpack.io/v/xw103/DeepApp.svg)](https://jitpack.io/#xw103/DeepApp) 3 |
4 | 实现在Android上宿主进程与ROOT进程无痕交互,支持安卓5~安卓12,理论未来将更新的安卓版本都支持. 5 |
6 | 并且我后续将写一个内存扫描/修改工具的DEMO。 7 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'com.android.application' 3 | } 4 | 5 | android { 6 | compileSdkVersion 30 7 | buildToolsVersion "30.0.0" 8 | 9 | defaultConfig { 10 | applicationId "com.deep.superapp" 11 | minSdkVersion 21 12 | targetSdkVersion 28 13 | versionCode 1 14 | versionName "1.0" 15 | 16 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 17 | } 18 | 19 | buildTypes { 20 | release { 21 | minifyEnabled false 22 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 23 | } 24 | } 25 | compileOptions { 26 | sourceCompatibility JavaVersion.VERSION_1_8 27 | targetCompatibility JavaVersion.VERSION_1_8 28 | } 29 | } 30 | 31 | dependencies { 32 | 33 | implementation 'androidx.appcompat:appcompat:1.3.1' 34 | implementation 'com.google.android.material:material:1.4.0' 35 | implementation 'androidx.constraintlayout:constraintlayout:2.1.0' 36 | implementation project(path: ':core') 37 | implementation project(path: ':hide') 38 | // testImplementation 'junit:junit:4.+' 39 | androidTestImplementation 'androidx.test.ext:junit:1.1.3' 40 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' 41 | } -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile -------------------------------------------------------------------------------- /app/src/androidTest/java/io/deep/superapp/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package io.deep.superapp; 2 | 3 | import android.content.Context; 4 | 5 | import androidx.test.platform.app.InstrumentationRegistry; 6 | import androidx.test.ext.junit.runners.AndroidJUnit4; 7 | 8 | import org.junit.Test; 9 | import org.junit.runner.RunWith; 10 | 11 | import static org.junit.Assert.*; 12 | 13 | /** 14 | * Instrumented test, which will execute on an Android device. 15 | * 16 | * @see Testing documentation 17 | */ 18 | @RunWith(AndroidJUnit4.class) 19 | public class ExampleInstrumentedTest { 20 | @Test 21 | public void useAppContext() { 22 | // Context of the app under test. 23 | Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); 24 | assertEquals("com.deep.superapp", appContext.getPackageName()); 25 | } 26 | } -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | 10 | 16 | 17 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /app/src/main/aidl/io/deep/superapp/ITest1.aidl: -------------------------------------------------------------------------------- 1 | // ITest1.aidl 2 | package io.deep.superapp; 3 | 4 | // Declare any non-default types here with import statements 5 | 6 | interface ITest1 { 7 | /** 8 | * Demonstrates some basic types that you can use as parameters 9 | * and return values in AIDL. 10 | */ 11 | String getTest(); 12 | } -------------------------------------------------------------------------------- /app/src/main/aidl/io/deep/superapp/ITest2.aidl: -------------------------------------------------------------------------------- 1 | // ITest2.aidl 2 | package io.deep.superapp; 3 | 4 | // Declare any non-default types here with import statements 5 | 6 | interface ITest2 { 7 | String getTest(); 8 | } -------------------------------------------------------------------------------- /app/src/main/java/io/deep/superapp/MainActivity.java: -------------------------------------------------------------------------------- 1 | package io.deep.superapp; 2 | 3 | import androidx.appcompat.app.AppCompatActivity; 4 | 5 | import android.app.AlertDialog; 6 | import android.content.Intent; 7 | import android.os.Bundle; 8 | import android.os.Handler; 9 | import android.os.Looper; 10 | import android.os.RemoteException; 11 | import android.util.Log; 12 | import android.widget.TextView; 13 | 14 | import com.deep.superapp.R; 15 | 16 | import io.app.hide.activity.InstallActivity; 17 | import io.app.hide.proc.HideProcess; 18 | import io.deep.superapp.test.Main1; 19 | import io.deep.superapp.test.Main2; 20 | 21 | import io.sapp.core.internal.IPCServer; 22 | 23 | public class MainActivity extends AppCompatActivity { 24 | 25 | // private final RootIPCReceiver ipcReceiver1 = new RootIPCReceiver(this, 0) { 26 | // @Override 27 | // public void onConnect(ITest1 ipc) { 28 | // try { 29 | // Log.e("test", ipc.getTest()); 30 | // new Handler(Looper.getMainLooper()).post(() -> { 31 | // AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this, 6); 32 | // builder1.setTitle("提示"); 33 | // try { 34 | // builder1.setMessage(ipc.getTest()); 35 | // } catch (RemoteException e) { 36 | // e.printStackTrace(); 37 | // } 38 | // builder1.setCancelable(false); 39 | // builder1.setPositiveButton("确定", (dialog1, which1) -> { 40 | // dialog1.dismiss(); 41 | // }); 42 | // AlertDialog d = builder1.create(); 43 | // int type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY; 44 | // d.getWindow().setType(type); 45 | // d.show(); 46 | // }); 47 | // } catch (RemoteException e) { 48 | // e.printStackTrace(); 49 | // } 50 | // } 51 | // 52 | // @Override 53 | // public void onDisconnect(ITest1 ipc) { 54 | // 55 | // } 56 | // }; 57 | // 58 | // private final RootIPCReceiver ipcReceiver2 = new RootIPCReceiver(this, 1) { 59 | // @Override 60 | // public void onConnect(ITest2 ipc) { 61 | // try { 62 | // Log.e("test2", ipc.getTest()); 63 | // new Handler(Looper.getMainLooper()).post(() -> { 64 | // AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this, 6); 65 | // builder1.setTitle("提示"); 66 | // try { 67 | // builder1.setMessage(ipc.getTest()); 68 | // } catch (RemoteException e) { 69 | // e.printStackTrace(); 70 | // } 71 | // builder1.setCancelable(false); 72 | // builder1.setPositiveButton("确定", (dialog1, which1) -> { 73 | // dialog1.dismiss(); 74 | // }); 75 | // AlertDialog d = builder1.create(); 76 | // int type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY; 77 | // d.getWindow().setType(type); 78 | // d.show(); 79 | // }); 80 | // } catch (RemoteException e) { 81 | // e.printStackTrace(); 82 | // } 83 | // } 84 | // 85 | // @Override 86 | // public void onDisconnect(ITest2 ipc) { 87 | // 88 | // } 89 | // }; 90 | 91 | @Override 92 | protected void onCreate(Bundle savedInstanceState) { 93 | super.onCreate(savedInstanceState); 94 | setContentView(R.layout.activity_main); 95 | TextView tv = findViewById(R.id.text1); 96 | tv.setText(getPackageCodePath()); 97 | // new IPCServer(this) { 98 | // @Override 99 | // public void onConnect(ITest1 ipc) { 100 | // new Handler(Looper.getMainLooper()).post(() -> { 101 | // AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this, 6); 102 | // builder1.setTitle("提示"); 103 | // try { 104 | // builder1.setMessage(ipc.getTest()); 105 | // } catch (RemoteException e) { 106 | // e.printStackTrace(); 107 | // } 108 | // builder1.setCancelable(false); 109 | // builder1.setPositiveButton("确定", (dialog1, which1) -> { 110 | // dialog1.dismiss(); 111 | // }); 112 | // AlertDialog d = builder1.create(); 113 | // d.show(); 114 | // }); 115 | // } 116 | // 117 | // @Override 118 | // public void onDisconnect(ITest1 ipc) { 119 | // 120 | // } 121 | // 122 | // @Override 123 | // public void onLine(String line) { 124 | // Log.e("shell:[su]", line); 125 | // } 126 | // }.setMainClass(Main1.class) 127 | // .setParam(new String[]{"测试", "666", "888", "999"}) 128 | // .start(); 129 | // 130 | // new IPCServer(this) { 131 | // @Override 132 | // public void onConnect(ITest2 ipc) { 133 | // new Handler(Looper.getMainLooper()).post(() -> { 134 | // AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this, 6); 135 | // builder1.setTitle("提示"); 136 | // try { 137 | // builder1.setMessage(ipc.getTest()); 138 | // } catch (RemoteException e) { 139 | // e.printStackTrace(); 140 | // } 141 | // builder1.setCancelable(false); 142 | // builder1.setPositiveButton("确定", (dialog1, which1) -> { 143 | // dialog1.dismiss(); 144 | // }); 145 | // AlertDialog d = builder1.create(); 146 | // d.show(); 147 | // }); 148 | // } 149 | // 150 | // @Override 151 | // public void onDisconnect(ITest2 ipc) { 152 | // 153 | // } 154 | // 155 | // @Override 156 | // public void onLine(String line) { 157 | // Log.e("shell:[su]", line); 158 | // } 159 | // }.setMainClass(Main2.class) 160 | // .setParam(new String[]{"测试2", "666", "888", "999", "222"}) 161 | // .start(); 162 | // startActivity(new Intent(this, InstallActivity.class)); 163 | HideProcess.hideApp(this); 164 | } 165 | 166 | 167 | } -------------------------------------------------------------------------------- /app/src/main/java/io/deep/superapp/test/Main1.java: -------------------------------------------------------------------------------- 1 | package io.deep.superapp.test; 2 | 3 | import android.os.IBinder; 4 | import android.os.RemoteException; 5 | import android.util.Log; 6 | 7 | import io.deep.superapp.ITest1; 8 | 9 | import io.sapp.core.internal.IPCMain; 10 | 11 | public class Main1 extends IPCMain { 12 | 13 | @Override 14 | public void main(String sourcePath, String[] args) { 15 | Log.e("args_apkPath",sourcePath); 16 | for (int i = 0; i < args.length; i++) { 17 | Log.e(String.format("args[%d]", i), args[i]); 18 | } 19 | } 20 | 21 | @Override 22 | public IBinder onBind() { 23 | return new ITest1.Stub() { 24 | @Override 25 | public String getTest() throws RemoteException { 26 | return "第一个ROOT进程"; 27 | } 28 | }; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /app/src/main/java/io/deep/superapp/test/Main2.java: -------------------------------------------------------------------------------- 1 | package io.deep.superapp.test; 2 | 3 | import android.os.IBinder; 4 | import android.os.RemoteException; 5 | import android.util.Log; 6 | 7 | import io.deep.superapp.ITest2; 8 | 9 | import io.sapp.core.internal.IPCMain; 10 | 11 | public class Main2 extends IPCMain { 12 | 13 | @Override 14 | public void main(String sourcePath, String[] args) { 15 | Log.e("args_apkPath",sourcePath); 16 | for (int i = 0; i < args.length; i++) { 17 | Log.e(String.format("args[%d]", i), args[i]); 18 | } 19 | } 20 | 21 | @Override 22 | public IBinder onBind() { 23 | return new ITest2.Stub() { 24 | @Override 25 | public String getTest() throws RemoteException { 26 | return "第二个ROOT进程"; 27 | } 28 | }; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 8 | 9 | 15 | 18 | 21 | 22 | 23 | 24 | 30 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 18 | 19 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xw103/DeepApp/d30fab1e0a600d586bf10d83483ff2b7141b2575/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xw103/DeepApp/d30fab1e0a600d586bf10d83483ff2b7141b2575/app/src/main/res/mipmap-hdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xw103/DeepApp/d30fab1e0a600d586bf10d83483ff2b7141b2575/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xw103/DeepApp/d30fab1e0a600d586bf10d83483ff2b7141b2575/app/src/main/res/mipmap-mdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xw103/DeepApp/d30fab1e0a600d586bf10d83483ff2b7141b2575/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xw103/DeepApp/d30fab1e0a600d586bf10d83483ff2b7141b2575/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xw103/DeepApp/d30fab1e0a600d586bf10d83483ff2b7141b2575/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xw103/DeepApp/d30fab1e0a600d586bf10d83483ff2b7141b2575/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xw103/DeepApp/d30fab1e0a600d586bf10d83483ff2b7141b2575/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xw103/DeepApp/d30fab1e0a600d586bf10d83483ff2b7141b2575/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png -------------------------------------------------------------------------------- /app/src/main/res/values-night/themes.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16 | -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #FFBB86FC 4 | #FF6200EE 5 | #FF3700B3 6 | #FF03DAC5 7 | #FF018786 8 | #FF000000 9 | #FFFFFFFF 10 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | DeepApp 3 | -------------------------------------------------------------------------------- /app/src/main/res/values/themes.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16 | -------------------------------------------------------------------------------- /app/src/test/java/io/deep/superapp/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package io.deep.superapp; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * @see Testing documentation 11 | */ 12 | public class ExampleUnitTest { 13 | @Test 14 | public void addition_isCorrect() { 15 | assertEquals(4, 2 + 2); 16 | } 17 | } -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | buildscript { 3 | repositories { 4 | google() 5 | jcenter() 6 | } 7 | dependencies { 8 | classpath "com.android.tools.build:gradle:4.1.3" 9 | 10 | // NOTE: Do not place your application dependencies here; they belong 11 | // in the individual module build.gradle files 12 | } 13 | } 14 | 15 | allprojects { 16 | repositories { 17 | google() 18 | jcenter() 19 | } 20 | } 21 | 22 | task clean(type: Delete) { 23 | delete rootProject.buildDir 24 | } -------------------------------------------------------------------------------- /core/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /core/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'com.android.library' 3 | } 4 | 5 | android { 6 | compileSdkVersion 30 7 | buildToolsVersion "30.0.0" 8 | 9 | defaultConfig { 10 | minSdkVersion 21 11 | targetSdkVersion 28 12 | versionCode 1 13 | versionName "1.0" 14 | 15 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 16 | consumerProguardFiles "consumer-rules.pro" 17 | externalNativeBuild { 18 | cmake { 19 | cppFlags "" 20 | } 21 | ndk { 22 | abiFilters 'armeabi-v7a','arm64-v8a','x86', 'x86_64' 23 | } 24 | } 25 | } 26 | 27 | buildTypes { 28 | release { 29 | minifyEnabled false 30 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 31 | } 32 | } 33 | externalNativeBuild { 34 | cmake { 35 | path "src/main/cpp/CMakeLists.txt" 36 | version "3.10.2" 37 | } 38 | } 39 | compileOptions { 40 | sourceCompatibility JavaVersion.VERSION_1_8 41 | targetCompatibility JavaVersion.VERSION_1_8 42 | } 43 | } 44 | 45 | dependencies { 46 | 47 | implementation 'androidx.appcompat:appcompat:1.3.1' 48 | implementation 'com.google.android.material:material:1.4.0' 49 | // testImplementation 'junit:junit:4.+' 50 | androidTestImplementation 'androidx.test.ext:junit:1.1.3' 51 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' 52 | } -------------------------------------------------------------------------------- /core/consumer-rules.pro: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xw103/DeepApp/d30fab1e0a600d586bf10d83483ff2b7141b2575/core/consumer-rules.pro -------------------------------------------------------------------------------- /core/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile -------------------------------------------------------------------------------- /core/src/androidTest/java/io/sapp/core/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package io.sapp.core; 2 | 3 | import android.content.Context; 4 | 5 | import androidx.test.platform.app.InstrumentationRegistry; 6 | import androidx.test.ext.junit.runners.AndroidJUnit4; 7 | 8 | import org.junit.Test; 9 | import org.junit.runner.RunWith; 10 | 11 | import static org.junit.Assert.*; 12 | 13 | /** 14 | * Instrumented test, which will execute on an Android device. 15 | * 16 | * @see Testing documentation 17 | */ 18 | @RunWith(AndroidJUnit4.class) 19 | public class ExampleInstrumentedTest { 20 | @Test 21 | public void useAppContext() { 22 | // Context of the app under test. 23 | Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); 24 | assertEquals("io.sapp.core.test", appContext.getPackageName()); 25 | } 26 | } -------------------------------------------------------------------------------- /core/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 11 | 12 | 13 | -------------------------------------------------------------------------------- /core/src/main/aidl/io/sapp/core/internal/IRootIPC.aidl: -------------------------------------------------------------------------------- 1 | package io.sapp.core.internal; 2 | 3 | // This is the wrapper used internally by RootIPC(Receiver) 4 | 5 | interface IRootIPC { 6 | void addBinder(IBinder self); 7 | IBinder getIPC(); 8 | void removeBinder(IBinder self); 9 | } 10 | -------------------------------------------------------------------------------- /core/src/main/cpp/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.10.2) 2 | 3 | project("core") 4 | 5 | add_library( 6 | core 7 | 8 | SHARED 9 | 10 | main.cpp) 11 | 12 | 13 | find_library( 14 | log-lib 15 | 16 | log) 17 | 18 | target_link_libraries( 19 | core 20 | 21 | ${log-lib}) -------------------------------------------------------------------------------- /core/src/main/cpp/main.cpp: -------------------------------------------------------------------------------- 1 | // 2 | // Created by Administrator on 2021/9/15. 3 | // 4 | 5 | #include 6 | #include 7 | 8 | jint JNI_OnLoad(JavaVM *vm, void *reserved) { 9 | JNIEnv *env; 10 | if (vm->GetEnv((void **) (&env), JNI_VERSION_1_6) != JNI_OK) { 11 | return -1; 12 | } 13 | assert(env != NULL); 14 | 15 | // if (!register_native_api(env)) {//注册接口 16 | // return -1; 17 | // } 18 | return JNI_VERSION_1_6; 19 | } 20 | -------------------------------------------------------------------------------- /core/src/main/java/io/sapp/core/internal/AppProcess.java: -------------------------------------------------------------------------------- 1 | /* Copyright 2018 Jorrit 'Chainfire' Jongma 2 | * 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | 16 | package io.sapp.core.internal; 17 | 18 | import android.annotation.SuppressLint; 19 | import android.annotation.TargetApi; 20 | import android.content.Context; 21 | import android.content.pm.ApplicationInfo; 22 | import android.os.Build; 23 | 24 | import java.io.File; 25 | import java.io.FileInputStream; 26 | import java.io.FileNotFoundException; 27 | import java.io.IOException; 28 | import java.util.List; 29 | import java.util.Locale; 30 | 31 | /** 32 | * Utility methods to determine the location and bits of the app_process executable to be used.
33 | *
34 | * This is normally handled automatically by the {@link RootServer} class, but the option exists 35 | * to override the used app_process, in which case you would use these methods to find the 36 | * appropriate binary. 37 | * 38 | * @see RootServer 39 | */ 40 | @SuppressWarnings({"unused", "WeakerAccess", "BooleanMethodIsAlwaysInverted"}) 41 | public class AppProcess { 42 | /** 43 | * Toolbox or toybox? 44 | */ 45 | public static final String BOX = Build.VERSION.SDK_INT < 23 ? "toolbox" : "toybox"; 46 | 47 | /** 48 | * Used to create unique filenames in common locations 49 | */ 50 | public static final String UUID = getUUID(); 51 | 52 | /** 53 | * @return uuid that doesn't contain 32 or 64, as to not confuse bit-choosing code 54 | */ 55 | private static String getUUID() { 56 | String uuid = null; 57 | while ((uuid == null) || uuid.contains("32") || uuid.contains("64")) { 58 | uuid = java.util.UUID.randomUUID().toString(); 59 | } 60 | return uuid; 61 | } 62 | 63 | /** 64 | * Tries to read a file's ELF header to determine if it's a 64-bit binary 65 | * 66 | * @param filename Filename to check 67 | * @return True if 64-bit, false if 32-bit, null if unsure 68 | */ 69 | @SuppressWarnings("all") 70 | private static Boolean checkELFHeaderFor64Bits(final String filename) { 71 | // Check ELF header. 8-bit value at 0x04 should be 1 for 32-bit or 2 for 64-bit 72 | try { 73 | FileInputStream is = new FileInputStream(filename); 74 | try { 75 | is.skip(4); 76 | int b = is.read(); 77 | if (b == 1) return false; 78 | if (b == 2) return true; 79 | } finally { 80 | is.close(); 81 | } 82 | } catch (FileNotFoundException e) { 83 | // no action required 84 | } catch (Exception e) { 85 | e.printStackTrace(); 86 | } 87 | return null; 88 | } 89 | 90 | /** 91 | * Are we running on a 64-bit device? 92 | * 93 | * @return If 64-bit architecture 94 | */ 95 | @SuppressLint("ObsoleteSdkInt") 96 | @TargetApi(Build.VERSION_CODES.LOLLIPOP) 97 | private static boolean is64BitArch() { 98 | if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { 99 | // there is no (retail) 64-bit pre-Lollipop 100 | return false; 101 | } 102 | 103 | return Build.SUPPORTED_64_BIT_ABIS.length > 0; 104 | } 105 | 106 | /** 107 | * Are we running in 32-bit mode on a 64-bit device?
108 | *
109 | * This happens if the app includes only 32-bit native libraries and is run on a 64-bit device 110 | * 111 | * @return If running as 32-bit on a 64-bit device 112 | */ 113 | private static boolean isRunningAs32BitOn64BitArch() { 114 | if (!is64BitArch()) { 115 | return false; 116 | } 117 | 118 | File f = new File("/proc/self/exe"); 119 | try { 120 | if (f.getCanonicalPath().contains("32")) { 121 | return true; 122 | } 123 | } catch (Exception e) { 124 | e.printStackTrace(); 125 | } 126 | return false; 127 | } 128 | 129 | /** 130 | * Get the path to the app_process with unspecified bits.
131 | *
132 | * It is unlikely you will need to call this method.
133 | *
134 | * Note that app_process_original and app_process_init are checked to cope with root on 135 | * older Android versions and Xposed installations. 136 | * 137 | * @see #getAppProcess() 138 | * 139 | * @return Path to app_process binary with unspecified bits or null 140 | */ 141 | public static String getAppProcessNoBit() { 142 | for (String candidate : new String[] { 143 | "/system/bin/app_process_original", 144 | "/system/bin/app_process_init", 145 | "/system/bin/app_process" 146 | }) { 147 | if ((new File(candidate)).exists()) return candidate; 148 | } 149 | return null; 150 | } 151 | 152 | /** 153 | * Get the path to the 32-bit app_process binary.
154 | *
155 | * It is unlikely you will need to call this method. 156 | * 157 | * @see #getAppProcess() 158 | * @see #getAppProcess32Bit(boolean) 159 | * 160 | * @return Path to 32-bit app_process or app_process with unspecified bits or null 161 | */ 162 | public static String getAppProcess32Bit() { 163 | return getAppProcess32Bit(true); 164 | } 165 | 166 | /** 167 | * Get the path to the 32-bit app_process binary.
168 | *
169 | * It is unlikely you will need to call this method. 170 | * 171 | * @see #getAppProcess() 172 | * 173 | * @param orDefault Whether to return the app_process with unspecified bits if a specific 32-bit binary isn't found 174 | * @return Path to 32-bit app_process or optionally app_process with unspecified bits or null 175 | */ 176 | public static String getAppProcess32Bit(boolean orDefault) { 177 | // app_process32 or null if not 32-bit 178 | // if >32bit, app_process32 will always exist, if ==32bit, default is 32bit 179 | for (String candidate : new String[] { 180 | "/system/bin/app_process32_original", 181 | "/system/bin/app_process32_init", 182 | "/system/bin/app_process32" 183 | }) { 184 | if ((new File(candidate)).exists()) return candidate; 185 | } 186 | if (orDefault) return getAppProcessNoBit(); 187 | return null; 188 | } 189 | 190 | /** 191 | * Get the path to the 64-bit app_process binary.
192 | *
193 | * It is unlikely you will need to call this method. 194 | * 195 | * @see #getAppProcess() 196 | * 197 | * @return Path to 64-bit app_process or null 198 | */ 199 | public static String getAppProcess64Bit() { 200 | // app_process64 or null if not 64-bit 201 | for (String candidate : new String[] { 202 | "/system/bin/app_process64_original", 203 | "/system/bin/app_process64_init", 204 | "/system/bin/app_process64" 205 | }) { 206 | if ((new File(candidate)).exists()) return candidate; 207 | } 208 | return null; 209 | } 210 | 211 | /** 212 | * Get the path to the app_process binary with most bits.
213 | *
214 | * It is unlikely you will need to call this method. 215 | * 216 | * @see #getAppProcess() 217 | * 218 | * @return Path to most-bits app_process or null 219 | */ 220 | public static String getAppProcessMaxBit() { 221 | String ret = getAppProcess64Bit(); 222 | if (ret == null) ret = getAppProcess32Bit(); 223 | if (ret == null) ret = getAppProcessNoBit(); 224 | return ret; 225 | } 226 | 227 | /** 228 | * Get the path to the app_process binary that we are most likely to want to use.
229 | *
230 | * This is the most likely variant of the getAppProcessXXX calls to use, if any. 231 | * 232 | * @return Path to app_process 233 | */ 234 | public static String getAppProcess() { 235 | String app_process = null; 236 | 237 | // If we are currently running as 32-bit but the architecture is 64-bit, we probably 238 | // only have native libraries for 32-bit. In that case our root code should also run 239 | // as 32-bit, so the code running as root can load those native libraries too. 240 | if (!isRunningAs32BitOn64BitArch()) app_process = getAppProcess64Bit(); 241 | 242 | if (app_process == null) app_process = getAppProcess32Bit(true); 243 | return app_process; 244 | } 245 | 246 | /** 247 | * Attempts to determine if the app_process binary is 64-bit, most logical guess if unable.
248 | *
249 | * It is unlikely you will need to call this method 250 | * 251 | * @param app_process Path to app_process binary 252 | * @return If the app_process binary is 64-bit 253 | */ 254 | public static boolean guessIfAppProcessIs64Bits(String app_process) { 255 | if (!is64BitArch()) { 256 | return false; 257 | } 258 | 259 | String compare = app_process; 260 | int sep = compare.lastIndexOf('/'); 261 | if (sep >= 0) { 262 | compare = compare.substring(sep + 1); 263 | } 264 | if (compare.contains("32")) return false; 265 | if (compare.contains("64")) return true; 266 | 267 | try { 268 | compare = (new File(app_process)).getCanonicalFile().getName(); 269 | if (compare.contains("32")) return false; 270 | if (compare.contains("64")) return true; 271 | } catch (Exception e) { 272 | e.printStackTrace(); 273 | } 274 | 275 | // No 32 or 64 in the name? Check ELF header 276 | Boolean elf = checkELFHeaderFor64Bits(app_process); 277 | if (elf != null) { 278 | return elf; 279 | } 280 | 281 | // If we're currently running in 32-bits mode on a 64-bit architecture, chances are 282 | // we want to run root in 32-bit as well, because we're missing 64-bit libs 283 | return !isRunningAs32BitOn64BitArch(); 284 | } 285 | 286 | /** 287 | * Should app_process be relocated ?
288 | *
289 | * On older Android versions we must relocate the app_process binary to prevent it from 290 | * running in a restricted SELinux context. On Q this presents us with the linker error: 291 | * "Error finding namespace of apex: no namespace called runtime". However, at least 292 | * on the first preview release of Q, running straight from /system/bin works and does 293 | * not give us a restricted SELinux context, so we skip relocation. 294 | * 295 | * TODO: Revisit on new Q preview and production releases. Maybe spend some time figuring out what causes the namespace error and if we can fix it. 296 | * 297 | * @see #getAppProcessRelocate(Context, String, List, List, String) 298 | * 299 | * @return should app_process be relocated ? 300 | */ 301 | @TargetApi(Build.VERSION_CODES.M) 302 | public static boolean shouldAppProcessBeRelocated() { 303 | return !( 304 | (Build.VERSION.SDK_INT >= 29) || 305 | ((Build.VERSION.SDK_INT == 28) && (Build.VERSION.PREVIEW_SDK_INT != 0)) 306 | ); 307 | } 308 | 309 | /** 310 | * Create script to relocate specified app_process binary to a different location.
311 | *
312 | * On many Android versions and roots, executing app_process directly will force an 313 | * SELinux context that we do not want. Relocating it bypasses that.
314 | * 315 | * @see #getAppProcess() 316 | * @see #shouldAppProcessBeRelocated() 317 | * 318 | * @param context Application or activity context 319 | * @param appProcessBase Path to original app_process or null for default 320 | * @param preLaunch List that retrieves commands to execute to perform the relocation 321 | * @param postExecution List that retrieves commands to execute to clean-up after execution 322 | * @param path Path to relocate to - must exist prior to script execution - or null for default 323 | * @return Path to relocated app_process 324 | */ 325 | public static String getAppProcessRelocate(Context context, String appProcessBase, List preLaunch, List postExecution, String path) { 326 | if (appProcessBase == null) appProcessBase = getAppProcess(); 327 | if (path == null) { 328 | if (!shouldAppProcessBeRelocated()) { 329 | return appProcessBase; 330 | } 331 | 332 | path = "/dev"; 333 | if ((context.getApplicationInfo().flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) == 0) { 334 | File cacheDir = context.getCacheDir(); 335 | try { 336 | //noinspection ResultOfMethodCallIgnored 337 | cacheDir.mkdirs(); 338 | } catch (Exception e) { 339 | // just in case 340 | } 341 | if (cacheDir.exists()) { 342 | try { 343 | path = cacheDir.getCanonicalPath(); 344 | } catch (IOException e) { 345 | // should never happen 346 | } 347 | } 348 | } 349 | } 350 | 351 | boolean onData = path.startsWith("/data/"); 352 | 353 | String appProcessCopy; 354 | if (guessIfAppProcessIs64Bits(appProcessBase)) { 355 | appProcessCopy = path + "/.app_process64_" + UUID; 356 | } else { 357 | appProcessCopy = path + "/.app_process32_" + UUID; 358 | } 359 | preLaunch.add(String.format(Locale.ENGLISH, "%s cp %s %s >/dev/null 2>/dev/null", BOX, appProcessBase, appProcessCopy)); 360 | preLaunch.add(String.format(Locale.ENGLISH, "%s chmod %s %s >/dev/null 2>/dev/null", BOX, onData ? "0766" : "0700", appProcessCopy)); 361 | if (onData) preLaunch.add(String.format(Locale.ENGLISH, "restorecon %s >/dev/null 2>/dev/null", appProcessCopy)); 362 | postExecution.add(String.format(Locale.ENGLISH, "%s rm %s >/dev/null 2>/dev/null", BOX, appProcessCopy)); 363 | return appProcessCopy; 364 | } 365 | } 366 | -------------------------------------------------------------------------------- /core/src/main/java/io/sapp/core/internal/Debugger.java: -------------------------------------------------------------------------------- 1 | package io.sapp.core.internal; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.ByteArrayOutputStream; 5 | import java.io.File; 6 | import java.io.FileDescriptor; 7 | import java.io.FileOutputStream; 8 | import java.io.FileReader; 9 | import java.io.IOException; 10 | import java.io.PrintStream; 11 | 12 | /** 13 | * Utility methods to support debugging 14 | */ 15 | @SuppressWarnings({"unused", "WeakerAccess"}) 16 | public class Debugger { 17 | /** 18 | * Is debugging enabled ? 19 | */ 20 | static volatile boolean enabled = false; 21 | 22 | /** 23 | * Is debugging enabled ?
24 | *
25 | * If called from non-root, this will return if we are launching new processes with debugging 26 | * enabled. If called from root, this will return if the current process was launched 27 | * with debugging enabled. 28 | * 29 | * @return Debugging enabled 30 | */ 31 | public static boolean isEnabled() { 32 | if (android.os.Process.myUid() >= 10000) { 33 | return enabled; 34 | } else { 35 | return Reflection.isDebuggingEnabled(); 36 | } 37 | } 38 | 39 | /** 40 | * Launch root processes with debugging enabled ? 41 | *
42 | * To prevent issues on release builds, BuildConfig.DEBUG should be respected. So instead 43 | * of passing true you would pass BuildConfig.DEBUG, while false 44 | * remains false. 45 | * 46 | * @param enabled Enable debugging (default: false) 47 | */ 48 | public static void setEnabled(boolean enabled) { 49 | Debugger.enabled = enabled; 50 | } 51 | 52 | /** 53 | * Cache for name to present to debugger. Really only used to determine if we have manually 54 | * set a name already. 55 | */ 56 | private static volatile String name = null; 57 | 58 | /** 59 | * Set name to present to debugger
60 | *
61 | * This method should only be called from the process running as root.
62 | *
63 | * Debugging will not work if this method has not been called, but the 64 | * {@link #waitFor(boolean)} method will call it for you, if used.
65 | *
66 | * {@link RootServer#restoreOriginalLdLibraryPath()} should have been called before calling 67 | * this method.
68 | *
69 | * To prevent issues with release builds, this call should be wrapped in a BuildConfig.DEBUG 70 | * check. 71 | * 72 | * @param name Name to present to debugger, or null to use process name 73 | * 74 | * @see #waitFor(boolean) 75 | */ 76 | public static void setName(String name) { 77 | if (Debugger.name == null) { 78 | if (name == null) { 79 | final File cmdline = new File("/proc/" + android.os.Process.myPid() + "/cmdline"); 80 | try (BufferedReader reader = new BufferedReader(new FileReader(cmdline))) { 81 | name = reader.readLine(); 82 | if (name.indexOf(' ') > 0) name = name.substring(0, name.indexOf(' ')); 83 | if (name.indexOf('\0') > 0) name = name.substring(0, name.indexOf('\0')); 84 | } catch (IOException e) { 85 | name = "unknown"; 86 | } 87 | } 88 | Debugger.name = name; 89 | Reflection.setAppName(name); 90 | } 91 | } 92 | 93 | /** 94 | * Wait for debugger to connect
95 | *
96 | * This method should only be called from the process running as root.
97 | *
98 | * If {@link #setName(String)} has not been called manually, the display name for the 99 | * debugger will be set to the current process name.
100 | *
101 | * After this method has been called, you can connect AndroidStudio's debugger to the root 102 | * process via Run->Attach Debugger to Android process.
103 | *
104 | * {@link RootServer#restoreOriginalLdLibraryPath()} should have been called before calling 105 | * this method.
106 | *
107 | * Android's internal debugger code will print to STDOUT during this call using System.println, 108 | * which may be annoying if your non-root process communicates with the root process through 109 | * STDIN/STDOUT/STDERR. If the swallowOutput parameter is set to true, System.println 110 | * will be temporarily redirected, and reset back to STDOUT afterwards.
111 | *
112 | * To prevent issues with release builds, this call should be wrapped in a BuildConfig.DEBUG 113 | * check: 114 | * 115 | *
116 |      * {@code
117 |      * if (BuildConfig.DEBUG) {
118 |      *     Debugger.waitFor(true);
119 |      * }
120 |      * }
121 |      * 
122 | * 123 | * @param swallowOutput Temporarily redirect STDOUT ? 124 | */ 125 | public static void waitFor(boolean swallowOutput) { 126 | if (Reflection.isDebuggingEnabled()) { 127 | if (swallowOutput) { 128 | ByteArrayOutputStream buffer = new ByteArrayOutputStream(); 129 | System.setOut(new PrintStream(buffer)); 130 | } 131 | setName(null); 132 | android.os.Debug.waitForDebugger(); 133 | if (swallowOutput) { 134 | System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out))); 135 | } 136 | } 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /core/src/main/java/io/sapp/core/internal/IPCMain.java: -------------------------------------------------------------------------------- 1 | package io.sapp.core.internal; 2 | 3 | import android.os.IBinder; 4 | import android.os.RemoteException; 5 | import android.util.Log; 6 | 7 | import java.lang.reflect.InvocationTargetException; 8 | import java.lang.reflect.Method; 9 | import java.util.ArrayList; 10 | import java.util.List; 11 | 12 | public abstract class IPCMain { 13 | 14 | private static String nativeLibraryDir; 15 | 16 | public abstract void main(String sourcePath,String[] args); 17 | 18 | public abstract IBinder onBind(); 19 | 20 | public String getNativeLibraryDir(){ 21 | return nativeLibraryDir; 22 | } 23 | 24 | public static void main(String[] args){ 25 | String source = args[0]; 26 | String packageName = args[1]; 27 | String nativeLibraryDir = args[2]; 28 | String className = args[3]; 29 | int code = Integer.parseInt(args[4]); 30 | IPCMain.nativeLibraryDir = nativeLibraryDir; 31 | List paramList = new ArrayList(); 32 | for(int i = 5;i clz = (Class) Class.forName(className); 37 | IPCMain main = clz.newInstance(); 38 | main.main(source,paramList.toArray(new String[0])); 39 | new RootIPC(packageName,main.onBind() ,code,30*1000,true); 40 | } catch (ClassNotFoundException e) { 41 | e.printStackTrace(); 42 | } catch (IllegalAccessException e) { 43 | e.printStackTrace(); 44 | } catch (InstantiationException e) { 45 | e.printStackTrace(); 46 | } catch (RootIPC.TimeoutException e) { 47 | e.printStackTrace(); 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /core/src/main/java/io/sapp/core/internal/IPCManager.java: -------------------------------------------------------------------------------- 1 | package io.sapp.core.internal; 2 | 3 | import android.util.Log; 4 | 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | 8 | public class IPCManager { 9 | private static Map ipcs = new HashMap(); 10 | 11 | public static RootIPCReceiver getIPCReceiver(Class clz){ 12 | return ipcs.get(clz.getName()); 13 | } 14 | 15 | private static void addIPCReceiver(Class clz,RootIPCReceiver ipcReceiver){ 16 | ipcs.put(clz.getName(),ipcReceiver); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /core/src/main/java/io/sapp/core/internal/IPCServer.java: -------------------------------------------------------------------------------- 1 | package io.sapp.core.internal; 2 | 3 | import android.content.Context; 4 | import android.util.Log; 5 | 6 | import java.lang.reflect.InvocationTargetException; 7 | import java.lang.reflect.Method; 8 | import java.lang.reflect.ParameterizedType; 9 | import java.lang.reflect.Type; 10 | import java.util.ArrayList; 11 | import java.util.Collections; 12 | import java.util.List; 13 | 14 | import io.sapp.core.utils.Shell; 15 | 16 | public abstract class IPCServer extends RootIPCReceiver { 17 | 18 | private Context context; 19 | private static int code = 0; 20 | private String[] param = null; 21 | private Class mainClass = null; 22 | private String apkPath = null; 23 | private String packageName = null; 24 | private String processName = null; 25 | 26 | public abstract void onLine(String line); 27 | 28 | public IPCServer(Context context) { 29 | super(context, code); 30 | this.context = context; 31 | } 32 | 33 | public IPCServer(Context context, Class clazz) { 34 | super(context, code, clazz); 35 | this.context = context; 36 | } 37 | 38 | public IPCServer setParam(String[] param) { 39 | this.param = param; 40 | return this; 41 | } 42 | 43 | public IPCServer setMainClass(Class mainClass) { 44 | this.mainClass = mainClass; 45 | return this; 46 | } 47 | 48 | public IPCServer setApkPath(String apkPath) { 49 | this.apkPath = apkPath; 50 | return this; 51 | } 52 | 53 | public IPCServer setPackageName(String packageName) { 54 | this.packageName = packageName; 55 | return this; 56 | } 57 | 58 | public void setProcessName(String processName) { 59 | this.processName = processName; 60 | } 61 | 62 | public void createProcess(String packageCodePath, String packageName, Class clazz, String[] param, String processName) { 63 | List script = getLaunchScript(packageCodePath, packageName, clazz, param, processName); 64 | Shell.Interactive shell = (new Shell.Builder()) 65 | .useSU() 66 | .open(new Shell.OnCommandResultListener() { 67 | @Override 68 | public void onCommandResult(int commandCode, int exitCode, List output) { 69 | if (exitCode != SHELL_RUNNING) { 70 | //执行中 71 | } 72 | } 73 | }); 74 | 75 | // 异步运行Script 76 | shell.addCommand(script, code, new Shell.OnCommandLineListener() { 77 | @Override 78 | public void onCommandResult(int commandCode, int exitCode) { 79 | //执行完成 80 | } 81 | 82 | @Override 83 | public void onLine(String line) { 84 | // 接收输出 85 | IPCServer.this.onLine(line); 86 | } 87 | }); 88 | } 89 | 90 | public void createProcess(String packageCodePath, String packageName, Class clazz, String[] param) { 91 | createProcess(packageCodePath,packageName,clazz,param,"root"); 92 | } 93 | 94 | public void createProcess(Class clazz, String[] param) { 95 | createProcess(context.getPackageCodePath(), context.getPackageName(),clazz,param,"root"); 96 | } 97 | 98 | public List getLaunchScript(Class mainClass, String[] params) { 99 | return getLaunchScript(context.getPackageCodePath(), context.getPackageName(), mainClass, params, "root"); 100 | } 101 | 102 | public List getLaunchScript(Class mainClass, String[] params, String processName) { 103 | return getLaunchScript(context.getPackageCodePath(), context.getPackageName(), mainClass, params, processName); 104 | } 105 | 106 | public List getLaunchScript(String packageCodePath, String packageName, Class mainClass, String[] params, String processName) { 107 | List paramList = new ArrayList(); 108 | paramList.add(packageCodePath); 109 | paramList.add(packageName); 110 | paramList.add(context.getApplicationInfo().nativeLibraryDir); 111 | paramList.add(mainClass.getName()); 112 | paramList.add(String.valueOf(code)); 113 | if (params != null) { 114 | Collections.addAll(paramList, params); 115 | } 116 | return RootServer.getLaunchScript(context, packageCodePath, mainClass, null, null, paramList.toArray(new String[0]), packageName + ":" + processName); 117 | } 118 | 119 | public void start() { 120 | if(packageName == null){ 121 | packageName = context.getPackageName(); 122 | } 123 | if(apkPath == null){ 124 | apkPath = context.getPackageCodePath(); 125 | } 126 | if(processName == null){ 127 | processName = "root"; 128 | } 129 | createProcess(apkPath,packageName,mainClass,param,processName); 130 | try { 131 | Method m = IPCManager.class.getDeclaredMethod("addIPCReceiver",Class.class,RootIPCReceiver.class); 132 | m.setAccessible(true); 133 | Type superClass = getClass().getGenericSuperclass(); 134 | Type tType = ((ParameterizedType)superClass).getActualTypeArguments()[0]; 135 | m.invoke(null,(Class)tType,this); 136 | } catch (NoSuchMethodException e) { 137 | e.printStackTrace(); 138 | } catch (IllegalAccessException e) { 139 | e.printStackTrace(); 140 | } catch (InvocationTargetException e) { 141 | e.printStackTrace(); 142 | } 143 | code++; 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /core/src/main/java/io/sapp/core/internal/Linker.java: -------------------------------------------------------------------------------- 1 | /* Copyright 2018 Jorrit 'Chainfire' Jongma 2 | * 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | 16 | package io.sapp.core.internal; 17 | 18 | import android.annotation.TargetApi; 19 | import android.os.Build; 20 | import android.system.Os; 21 | 22 | import java.io.File; 23 | import java.io.IOException; 24 | 25 | /** 26 | * Internal utility methods that deal with LD_LIBRARY_PATH 27 | */ 28 | @SuppressWarnings({"WeakerAccess", "SameParameterValue"}) 29 | public class Linker { 30 | /** 31 | * Cross-API method to get environment variable 32 | * 33 | * @param name Name of variable 34 | * @return Value of variable 35 | */ 36 | @TargetApi(Build.VERSION_CODES.LOLLIPOP) 37 | private static String getenv(String name) { 38 | if (haveLinkerNamespaces()) { 39 | // real OS call 40 | return Os.getenv(name); 41 | } else { 42 | // cached by JVM at startup 43 | return System.getenv(name); 44 | } 45 | } 46 | 47 | /** 48 | * Set environment variable on newer API levels.
49 | *
50 | * The updated value is set at OS level, but System.getenv() calls may still return 51 | * the old values, as those are cached at JVM startup. 52 | * 53 | * @param name Name of variable 54 | * @param value Value of variable 55 | */ 56 | @TargetApi(Build.VERSION_CODES.LOLLIPOP) 57 | private static void setenv(String name, String value) { 58 | if (haveLinkerNamespaces()) { 59 | // note: restored path may not show up in methods depending on System.getenv 60 | try { 61 | if (value == null) { 62 | Os.unsetenv(name); 63 | } else { 64 | Os.setenv(name, value, true); 65 | } 66 | } catch (Exception e) { 67 | e.printStackTrace(); 68 | } 69 | } // if we don't have linker namespaces this call isn't needed 70 | } 71 | 72 | /** 73 | * Are linker namespaces used?
74 | *
75 | * Android 7.0 (API level 24) and up use linker namespaces, which prevent apps from loading 76 | * native libraries outside of that namespace.
77 | * 78 | * @see #getPatchedLdLibraryPath(boolean, String[]) 79 | * 80 | * @return If linker namespaces are used 81 | */ 82 | @TargetApi(23) 83 | private static boolean haveLinkerNamespaces() { 84 | return ( 85 | (Build.VERSION.SDK_INT >= 24) || 86 | 87 | // 7.0 preview 88 | ((Build.VERSION.SDK_INT == 23) && (Build.VERSION.PREVIEW_SDK_INT != 0)) 89 | ); 90 | } 91 | 92 | /** 93 | * Returns a value for LD_LIBRARY_PATH fit to bypass linker namespace restrictions and load 94 | * system as well as our own native libraries.
95 | *
96 | * Android 7.0 (API level 24) and up use linker namespaces, which prevent apps from loading 97 | * native libraries outside of that namespace.
98 | *
99 | * These are also employed for Java code running as root through app_process. One way to 100 | * bypass linker namespace is to explicitly set the LD_LIBRARY_PATH variable. Getting that 101 | * to work properly is trickier than it sounds with several edge-cases, do not modify this 102 | * code without testing excessively on different Android devices versions!
103 | *
104 | * We also add a marker and include the original LD_LIBRARY_PATH, so it's value may be 105 | * restored after load. Otherwise, executing other binaries may fail. 106 | * 107 | * @see #restoreOriginalLdLibraryPath() 108 | * 109 | * @param use64bit Use 64-bit paths 110 | * @param extraPaths Additional paths to include 111 | * @return Patched value for LD_LIBRARY_PATH 112 | */ 113 | static String getPatchedLdLibraryPath(boolean use64bit, String[] extraPaths) { 114 | String LD_LIBRARY_PATH = getenv("LD_LIBRARY_PATH"); 115 | if (!haveLinkerNamespaces()) { 116 | if (LD_LIBRARY_PATH != null) { 117 | // some firmwares have this, some don't, launch at boot may fail without, or with, 118 | // so just copy what is the current situation 119 | return LD_LIBRARY_PATH; 120 | } 121 | return null; 122 | } else { 123 | StringBuilder paths = new StringBuilder(); 124 | 125 | // these default paths are taken from linker code in AOSP, and are normally used 126 | // when LD_LIBRARY_PATH isn't set explicitly 127 | String[] scan; 128 | if (use64bit) { 129 | scan = new String[]{ 130 | "/system/lib64", 131 | "/data/lib64", 132 | "/vendor/lib64", 133 | "/data/vendor/lib64" 134 | }; 135 | } else { 136 | scan = new String[]{ 137 | "/system/lib", 138 | "/data/lib", 139 | "/vendor/lib", 140 | "/data/vendor/lib" 141 | }; 142 | } 143 | 144 | for (String path : scan) { 145 | File file = (new File(path)); 146 | if (file.exists()) { 147 | try { 148 | paths.append(file.getCanonicalPath()); 149 | paths.append(':'); 150 | 151 | // This part can trigger quite a few SELinux policy violations, they 152 | // are harmless for our purpose, but if you're trying to trace SELinux 153 | // related issues in your Binder calls, you may want to comment this part 154 | // out. It is rarely (but still sometimes) actually required for your code 155 | // to run. 156 | 157 | File[] files = file.listFiles(); 158 | if (files != null) { 159 | for (File dir : files) { 160 | if (dir.isDirectory()) { 161 | paths.append(dir.getCanonicalPath()); 162 | paths.append(':'); 163 | } 164 | } 165 | } 166 | } catch (IOException e) { 167 | // failed to resolve canonical path 168 | } 169 | } 170 | } 171 | 172 | if (extraPaths != null) { 173 | for (String path : extraPaths) { 174 | paths.append(path); 175 | paths.append(':'); 176 | } 177 | } 178 | 179 | paths.append("/superuser"); // for detection 180 | 181 | if (LD_LIBRARY_PATH != null) { 182 | paths.append(':'); 183 | paths.append(LD_LIBRARY_PATH); 184 | } 185 | 186 | return paths.toString(); 187 | } 188 | } 189 | 190 | /** 191 | * Retrieve the pre-patched value of LD_LIBRARY_PATH. 192 | * 193 | * @see #getPatchedLdLibraryPath(boolean, String[]) 194 | * 195 | * @return Original value of LD_LIBRARY_PATH 196 | */ 197 | private static String getOriginalLdLibraryPath() { 198 | String LD_LIBRARY_PATH = System.getenv("LD_LIBRARY_PATH"); 199 | if (LD_LIBRARY_PATH == null) 200 | return null; 201 | 202 | if (LD_LIBRARY_PATH.endsWith(":/superuser")) 203 | return null; 204 | 205 | if (LD_LIBRARY_PATH.contains(":/superuser:")) 206 | return LD_LIBRARY_PATH.substring(LD_LIBRARY_PATH.indexOf(":/superuser:") + ":/superuser:".length()); 207 | 208 | return LD_LIBRARY_PATH; 209 | } 210 | 211 | /** 212 | * Restores correct LD_LIBRARY_PATH environment variable. 213 | * 214 | * @see Linker#getPatchedLdLibraryPath(boolean, String[]) 215 | */ 216 | static void restoreOriginalLdLibraryPath() { 217 | setenv("LD_LIBRARY_PATH", getOriginalLdLibraryPath()); 218 | } 219 | } 220 | -------------------------------------------------------------------------------- /core/src/main/java/io/sapp/core/internal/Policies.java: -------------------------------------------------------------------------------- 1 | /* Copyright 2018 Jorrit 'Chainfire' Jongma 2 | * 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | 16 | package io.sapp.core.internal; 17 | 18 | import java.util.List; 19 | 20 | /** 21 | * Utility methods for handling SELinux policies 22 | */ 23 | @SuppressWarnings({"unused", "WeakerAccess"}) 24 | public class Policies { 25 | /** 26 | * SELinux policies that require patching for the Binder calls to work on newer Android 27 | * versions. Failing to do this may cause Binder transactions to fail. 28 | */ 29 | private static String[] required = new String[] { 30 | /* We skip the init context used in older SuperSU versions, as that is potentially 31 | dangerous, and Android versions that actually require this policy modification 32 | are likely to run a SuperSU version that uses it's own SELinux context or Magisk */ 33 | "allow appdomain supersu binder { call transfer }", 34 | "allow appdomain magisk binder { call transfer }" 35 | }; 36 | 37 | /** 38 | * We only want to patch the SELinux policies once, keep track 39 | */ 40 | private static Boolean patched = false; 41 | 42 | /** 43 | * Sets SELinux policies patched state.
44 | *
45 | * By default policies are only patched once. You can trigger the script to include the 46 | * policy patches again once by passing false, or every time by passing null. If you pass 47 | * true, the policies will not be patched.
48 | *
49 | * If you are not using the Binder IPC calls, you may want to set it to true to prevent 50 | * the policies from being needlessly patched. 51 | * 52 | * @param value New policy patched state 53 | */ 54 | public static void setPatched(Boolean value) { 55 | patched = value; 56 | } 57 | 58 | /** 59 | * Create script to patch SELinux policies. 60 | * 61 | * @param preLaunch List that retrieves commands to execute to perform the policy patch 62 | */ 63 | public static void getPatch(List preLaunch) { 64 | if ((patched == null) || !patched) { 65 | StringBuilder command = new StringBuilder("supolicy --live"); 66 | for (String policy : required) { 67 | command.append(" \"").append(policy).append("\""); 68 | } 69 | command.append(" >/dev/null 2>/dev/null"); 70 | preLaunch.add(command.toString()); 71 | if (patched != null) { 72 | patched = true; 73 | } 74 | } 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /core/src/main/java/io/sapp/core/internal/Reflection.java: -------------------------------------------------------------------------------- 1 | package io.sapp.core.internal; 2 | 3 | import android.annotation.SuppressLint; 4 | import android.content.Context; 5 | import android.content.Intent; 6 | import android.os.IBinder; 7 | import android.os.IInterface; 8 | import android.os.Looper; 9 | import android.util.Log; 10 | 11 | import java.lang.reflect.Constructor; 12 | import java.lang.reflect.Field; 13 | import java.lang.reflect.Method; 14 | 15 | /** 16 | * Reflection-based methods are implemented here, so we have all the methods that are most 17 | * likely to break in one spot. 18 | */ 19 | public class Reflection { 20 | private static final Object lock = new Object(); 21 | 22 | /** Cache for getSystemContext() */ 23 | @SuppressLint("StaticFieldLeak") 24 | private static Context systemContext = null; 25 | 26 | /** 27 | * Retrieve system context
28 | *
29 | * Stability: unlikely to change, this implementation works from 1.6 through 9.0
30 | * 31 | * @see RootServer#getSystemContext() 32 | * 33 | * @return system context 34 | */ 35 | @SuppressLint("PrivateApi") 36 | static Context getSystemContext() { 37 | synchronized (lock) { 38 | try { 39 | if (systemContext != null) { 40 | return systemContext; 41 | } 42 | 43 | // a prepared Looper is required for the calls below to succeed 44 | if (Looper.getMainLooper() == null) { 45 | try { 46 | Looper.prepareMainLooper(); 47 | } catch (Exception e) { 48 | e.printStackTrace(); 49 | } 50 | } 51 | 52 | Class cActivityThread = Class.forName("android.app.ActivityThread"); 53 | Method mSystemMain = cActivityThread.getMethod("systemMain"); 54 | Method mGetSystemContext = cActivityThread.getMethod("getSystemContext"); 55 | 56 | Object oActivityThread = mSystemMain.invoke(null); 57 | Object oContext = mGetSystemContext.invoke(oActivityThread); 58 | 59 | systemContext = (Context)oContext; 60 | return systemContext; 61 | } catch (Exception e) { 62 | e.printStackTrace(); 63 | throw new RuntimeException("unexpected exception in getSystemContext()"); 64 | } 65 | } 66 | } 67 | 68 | /** Cache for getActivityManager() */ 69 | private static Object oActivityManager = null; 70 | 71 | /** 72 | * Retrieve ActivityManager instance without needing a context
73 | *
74 | * Stability: has changed before, might change again, rare 75 | * 76 | * @return ActivityManager 77 | */ 78 | @SuppressLint("PrivateApi") 79 | @SuppressWarnings({"JavaReflectionMemberAccess"}) 80 | private static Object getActivityManager() { 81 | // Return object is AIDL interface IActivityManager, not an ActivityManager or 82 | // ActivityManagerService 83 | 84 | synchronized (lock) { 85 | if (oActivityManager != null) { 86 | return oActivityManager; 87 | } 88 | 89 | try { // marked deprecated in Android source 90 | Class cActivityManagerNative = Class.forName("android.app.ActivityManagerNative"); 91 | Method mGetDefault = cActivityManagerNative.getMethod("getDefault"); 92 | oActivityManager = mGetDefault.invoke(null); 93 | return oActivityManager; 94 | } catch (Exception e) { 95 | // possibly removed 96 | } 97 | 98 | try { 99 | // alternative 100 | Class cActivityManager = Class.forName("android.app.ActivityManager"); 101 | Method mGetService = cActivityManager.getMethod("getService"); 102 | oActivityManager = mGetService.invoke(null); 103 | return oActivityManager; 104 | } catch (Exception e) { 105 | e.printStackTrace(); 106 | } 107 | 108 | throw new RuntimeException("unable to retrieve ActivityManager"); 109 | } 110 | } 111 | 112 | /** Cache for getFlagReceiverFromShell() */ 113 | private static Integer FLAG_RECEIVER_FROM_SHELL = null; 114 | 115 | /** 116 | * Retrieve value of Intent.FLAG_RECEIVER_FROM_SHELL, if it exists
117 | *
118 | * Stability: stable, even if the flag goes away again this is unlikely to affect things 119 | * 120 | * @return FLAG_RECEIVER_FROM_SHELL or 0 121 | */ 122 | @SuppressWarnings({"JavaReflectionMemberAccess"}) 123 | private static int getFlagReceiverFromShell() { 124 | synchronized (lock) { 125 | if (FLAG_RECEIVER_FROM_SHELL != null) { 126 | return FLAG_RECEIVER_FROM_SHELL; 127 | } 128 | 129 | try { 130 | Field fFlagReceiverFromShell = Intent.class.getDeclaredField("FLAG_RECEIVER_FROM_SHELL"); 131 | FLAG_RECEIVER_FROM_SHELL = fFlagReceiverFromShell.getInt(null); 132 | return FLAG_RECEIVER_FROM_SHELL; 133 | } catch (NoSuchFieldException e) { 134 | // not present on all Android versions 135 | } catch (IllegalAccessException e) { 136 | e.printStackTrace(); 137 | } 138 | 139 | FLAG_RECEIVER_FROM_SHELL = 0; 140 | return FLAG_RECEIVER_FROM_SHELL; 141 | } 142 | } 143 | 144 | /** Cache for getBroadcastIntent() */ 145 | private static Method mBroadcastIntent = null; 146 | 147 | /** 148 | * Retrieve the ActivityManager.broadcastIntent() method 149 | * 150 | * @param cActivityManager ActivityManager class 151 | * @return broadcastIntent method 152 | */ 153 | private static Method getBroadcastIntent(Class cActivityManager) { 154 | synchronized (lock) { 155 | if (mBroadcastIntent != null) { 156 | return mBroadcastIntent; 157 | } 158 | 159 | for (Method m : cActivityManager.getMethods()) { 160 | if (m.getName().equals("broadcastIntent") && (m.getParameterTypes().length == 13)) { 161 | // API 24+ 162 | mBroadcastIntent = m; 163 | return mBroadcastIntent; 164 | } 165 | if (m.getName().equals("broadcastIntent") && (m.getParameterTypes().length == 12)) { 166 | // API 21+ 167 | mBroadcastIntent = m; 168 | return mBroadcastIntent; 169 | } 170 | } 171 | 172 | throw new RuntimeException("unable to retrieve broadcastIntent method"); 173 | } 174 | } 175 | 176 | /** 177 | * Broadcast intent
178 | *
179 | * Stability: the implementation for this will definitely change over time
180 | *
181 | * This implementation does not require us to have a context 182 | * 183 | * @see RootServer#sendBroadcast(Intent) 184 | * @see RootIPC#broadcastIPC() 185 | * 186 | * @param intent Intent to broadcast 187 | */ 188 | @SuppressLint("PrivateApi") 189 | public static void sendBroadcast(Intent intent) { 190 | try { 191 | // Prevent system from complaining about unprotected broadcast, if the field exists 192 | intent.setFlags(getFlagReceiverFromShell()); 193 | Object oActivityManager = getActivityManager(); 194 | Method mBroadcastIntent = getBroadcastIntent(oActivityManager.getClass()); 195 | if (mBroadcastIntent.getParameterTypes().length == 13) { 196 | // API 24+ 197 | mBroadcastIntent.invoke(oActivityManager, null, intent, null, null, 0, null, null, null, -1, null, false, false, 0); 198 | return; 199 | } 200 | if (mBroadcastIntent.getParameterTypes().length == 12) { 201 | // API 21+ 202 | mBroadcastIntent.invoke(oActivityManager, null, intent, null, null, 0, null, null, null, -1, false, false, 0); 203 | return; 204 | } 205 | } catch (Exception e) { 206 | e.printStackTrace(); 207 | return; 208 | } 209 | // broadcast wasn't sent if we arrive here 210 | throw new RuntimeException("unable to send broadcast"); 211 | } 212 | 213 | /** 214 | * Determine if debugging is enabled on the VM level
215 | *
216 | * Stability: unlikely to change, this implementation works from 1.6 through 9.0
217 | * 218 | * @see Debugger#isEnabled() 219 | * 220 | * @return Debugging enabled 221 | */ 222 | @SuppressLint("PrivateApi") 223 | static boolean isDebuggingEnabled() { 224 | try { 225 | Class cVMDebug = Class.forName("dalvik.system.VMDebug"); 226 | @SuppressLint("SoonBlockedPrivateApi") 227 | Method mIsDebuggingEnabled = cVMDebug.getDeclaredMethod("isDebuggingEnabled"); 228 | return (Boolean)mIsDebuggingEnabled.invoke(null); 229 | } catch (Exception e) { 230 | e.printStackTrace(); 231 | return false; 232 | } 233 | } 234 | 235 | /** 236 | * Set app name for debugger connection 237 | *
238 | * Stability: unlikely to change, this implementation works from 1.6 through 9.0
239 | * 240 | * @see Debugger#setName(String) 241 | */ 242 | @SuppressLint("PrivateApi") 243 | static void setAppName(String name) { 244 | try { 245 | Class cDdmHandleAppName = Class.forName("android.ddm.DdmHandleAppName"); 246 | Method m = cDdmHandleAppName.getDeclaredMethod("setAppName", String.class, int.class); 247 | m.invoke(null, name, 0); 248 | } catch (Exception e) { 249 | e.printStackTrace(); 250 | } 251 | } 252 | 253 | /** 254 | * Internal class to retrieve an interface from a Binder (Proxy) 255 | * 256 | * @param Interface 257 | */ 258 | @SuppressWarnings("unchecked") 259 | static class InterfaceRetriever { 260 | /** 261 | * Stability: stable, as changes to this pattern in AOSP would probably require all 262 | * AIDL-using apps to be recompiled. 263 | * 264 | * @param clazz Class of T 265 | * @param binder Binder proxy to retrieve interface from 266 | * @return T (proxy) instance or null 267 | */ 268 | T getInterfaceFromBinder(Class clazz, IBinder binder) { 269 | // There does not appear to be a nice way to do this without reflection, 270 | // though of course you can use T.Stub.asInterface(binder) in final code, that doesn't 271 | // help for our callbacks 272 | try { 273 | Class cStub = Class.forName(clazz.getName() + "$Stub"); 274 | Field fDescriptor = cStub.getDeclaredField("DESCRIPTOR"); 275 | fDescriptor.setAccessible(true); 276 | 277 | String descriptor = (String)fDescriptor.get(binder); 278 | IInterface intf = binder.queryLocalInterface(descriptor); 279 | if (clazz.isInstance(intf)) { 280 | // local 281 | return (T)intf; 282 | } else { 283 | // remote 284 | Class cProxy = Class.forName(clazz.getName() + "$Stub$Proxy"); 285 | Constructor ctorProxy = cProxy.getDeclaredConstructor(IBinder.class); 286 | ctorProxy.setAccessible(true); 287 | return (T)ctorProxy.newInstance(binder); 288 | } 289 | } catch (Exception e) { 290 | e.printStackTrace(); 291 | } 292 | return null; 293 | } 294 | } 295 | } 296 | -------------------------------------------------------------------------------- /core/src/main/java/io/sapp/core/internal/RootIPC.java: -------------------------------------------------------------------------------- 1 | /* Copyright 2018 Jorrit 'Chainfire' Jongma 2 | * 3 | * Licensed under the Apache License, Version 2.0 (the "License"); 4 | * you may not use this file except in compliance with the License. 5 | * You may obtain a copy of the License at 6 | * 7 | * http://www.apache.org/licenses/LICENSE-2.0 8 | * 9 | * Unless required by applicable law or agreed to in writing, software 10 | * distributed under the License is distributed on an "AS IS" BASIS, 11 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | * See the License for the specific language governing permissions and 13 | * limitations under the License. 14 | */ 15 | 16 | package io.sapp.core.internal; 17 | 18 | import android.content.Intent; 19 | import android.os.Bundle; 20 | import android.os.IBinder; 21 | import android.os.RemoteException; 22 | import android.util.Log; 23 | 24 | import java.util.ArrayList; 25 | import java.util.List; 26 | 27 | @SuppressWarnings({"unused", "WeakerAccess", "BooleanMethodIsAlwaysInverted", "FieldCanBeLocal", "Convert2Diamond"}) 28 | public class RootIPC { 29 | public static class TimeoutException extends Exception { 30 | public TimeoutException(String message) { 31 | super(message); 32 | } 33 | } 34 | 35 | private final String packageName; 36 | private final IBinder userIPC; 37 | private final int code; 38 | 39 | private final Object helloWaiter = new Object(); 40 | private final Object byeWaiter = new Object(); 41 | 42 | private class Connection { 43 | private final IBinder binder; 44 | private final IBinder.DeathRecipient deathRecipient; 45 | 46 | public Connection(IBinder binder, IBinder.DeathRecipient deathRecipient) { 47 | this.binder = binder; 48 | this.deathRecipient = deathRecipient; 49 | } 50 | 51 | public IBinder getBinder() { 52 | return binder; 53 | } 54 | 55 | public IBinder.DeathRecipient getDeathRecipient() { 56 | return deathRecipient; 57 | } 58 | } 59 | 60 | private final List connections = new ArrayList(); 61 | private volatile boolean connectionSeen = false; 62 | 63 | public RootIPC(String packageName, IBinder ipc, int code, int connection_timeout_ms, boolean blocking) throws TimeoutException { 64 | this.packageName = packageName; 65 | userIPC = ipc; 66 | this.code = code; 67 | broadcastIPC(); 68 | 69 | if (connection_timeout_ms < 0) connection_timeout_ms = 30 * 1000; 70 | if (connection_timeout_ms > 0) { 71 | synchronized (helloWaiter) { 72 | if (!haveClientsConnected()) { 73 | try { 74 | helloWaiter.wait(connection_timeout_ms); 75 | } catch (InterruptedException e) { 76 | e.printStackTrace(); 77 | } 78 | } 79 | if (!haveClientsConnected()) { 80 | throw new TimeoutException("连接超时"); 81 | } 82 | } 83 | } 84 | 85 | if (blocking) { 86 | synchronized (byeWaiter) { 87 | while (!haveAllClientsDisconnected()) { 88 | try { 89 | byeWaiter.wait(); 90 | } catch (InterruptedException e) { 91 | return; 92 | } 93 | } 94 | } 95 | } 96 | } 97 | 98 | //判断是否连接 99 | public boolean haveClientsConnected() { 100 | synchronized (connections) { 101 | return connectionSeen; 102 | } 103 | } 104 | 105 | //判断连接是否关闭 106 | public boolean haveAllClientsDisconnected() { 107 | synchronized (connections) { 108 | return connectionSeen && (getConnectionCount() == 0); 109 | } 110 | } 111 | 112 | public void broadcastIPC() { 113 | Intent intent = new Intent(); 114 | intent.setPackage(packageName); 115 | intent.setAction(RootIPCReceiver.BROADCAST_ACTION); 116 | intent.setFlags(Intent.FLAG_RECEIVER_FOREGROUND); 117 | 118 | Bundle bundle = new Bundle(); 119 | bundle.putBinder(RootIPCReceiver.BROADCAST_BINDER, binder); 120 | bundle.putInt(RootIPCReceiver.BROADCAST_CODE, code); 121 | intent.putExtra(RootIPCReceiver.BROADCAST_EXTRA, bundle); 122 | 123 | Reflection.sendBroadcast(intent); 124 | } 125 | 126 | //获取客户端连接数量 127 | public int getConnectionCount() { 128 | synchronized (connections) { 129 | pruneConnections(); 130 | return connections.size(); 131 | } 132 | } 133 | 134 | //删除无效连接 135 | private void pruneConnections() { 136 | synchronized (connections) { 137 | if (connections.size() == 0) return; 138 | 139 | for (int i = connections.size() - 1; i >= 0; i--) { 140 | Connection conn = connections.get(i); 141 | if (!conn.getBinder().isBinderAlive()) { 142 | connections.remove(i); 143 | } 144 | } 145 | 146 | if (!connectionSeen && (connections.size() > 0)) { 147 | connectionSeen = true; 148 | synchronized (helloWaiter) { 149 | helloWaiter.notifyAll(); 150 | } 151 | } 152 | 153 | if (connections.size() == 0) { 154 | synchronized (byeWaiter) { 155 | byeWaiter.notifyAll(); 156 | } 157 | } 158 | } 159 | } 160 | 161 | //获取基于IBinder的连接 162 | private Connection getConnection(IBinder binder) { 163 | synchronized (connections) { 164 | pruneConnections(); 165 | for (Connection conn : connections) { 166 | if (conn.getBinder() == binder) { 167 | return conn; 168 | } 169 | } 170 | return null; 171 | } 172 | } 173 | 174 | //获取基于DeathRecipient的连接 175 | private Connection getConnection(IBinder.DeathRecipient deathRecipient) { 176 | synchronized (connections) { 177 | pruneConnections(); 178 | for (Connection conn : connections) { 179 | if (conn.getDeathRecipient() == deathRecipient) { 180 | return conn; 181 | } 182 | } 183 | return null; 184 | } 185 | } 186 | 187 | private final IBinder binder = new IRootIPC.Stub() { 188 | @Override 189 | public void addBinder(IBinder self) {//主进程连接 190 | // 主进程死亡 191 | IBinder.DeathRecipient deathRecipient = new IBinder.DeathRecipient() { 192 | @Override 193 | public void binderDied() { 194 | Connection conn = getConnection(this); 195 | if (conn != null) { 196 | removeBinder(conn.getBinder()); 197 | } 198 | } 199 | }; 200 | try { 201 | self.linkToDeath(deathRecipient, 0); 202 | } catch (RemoteException e) { 203 | self = null; 204 | } 205 | 206 | //记录连接 207 | if (self != null) { 208 | synchronized (connections) { 209 | connections.add(new Connection(self, deathRecipient)); 210 | connectionSeen = true; 211 | } 212 | synchronized (helloWaiter) { 213 | helloWaiter.notifyAll(); 214 | } 215 | } 216 | } 217 | 218 | @Override 219 | public IBinder getIPC() { 220 | return userIPC; 221 | } 222 | 223 | @Override 224 | public void removeBinder(IBinder self) { 225 | synchronized (connections) { 226 | Connection conn = getConnection(self); 227 | if (conn != null) { 228 | try { 229 | conn.getBinder().unlinkToDeath(conn.getDeathRecipient(), 0); 230 | } catch (Exception e) { 231 | e.printStackTrace(); 232 | } 233 | connections.remove(conn); 234 | } 235 | } 236 | synchronized (byeWaiter) { 237 | byeWaiter.notifyAll(); 238 | } 239 | } 240 | }; 241 | } 242 | -------------------------------------------------------------------------------- /core/src/main/java/io/sapp/core/internal/RootIPCReceiver.java: -------------------------------------------------------------------------------- 1 | package io.sapp.core.internal; 2 | 3 | import android.content.BroadcastReceiver; 4 | import android.content.Context; 5 | import android.content.ContextWrapper; 6 | import android.content.Intent; 7 | import android.content.IntentFilter; 8 | import android.os.Binder; 9 | import android.os.Bundle; 10 | import android.os.Handler; 11 | import android.os.HandlerThread; 12 | import android.os.IBinder; 13 | import android.os.RemoteException; 14 | 15 | import java.lang.ref.WeakReference; 16 | import java.lang.reflect.ParameterizedType; 17 | import java.lang.reflect.Type; 18 | 19 | @SuppressWarnings({"unused", "WeakerAccess", "Convert2Diamond", "TryWithIdenticalCatches"}) 20 | public abstract class RootIPCReceiver { 21 | 22 | public abstract void onConnect(T ipc); 23 | 24 | public abstract void onDisconnect(T ipc); 25 | 26 | public static final String BROADCAST_ACTION = "RootIPCReceiver.BROADCAST"; 27 | public static final String BROADCAST_EXTRA = "RootIPCReceiver.BROADCAST.EXTRA"; 28 | public static final String BROADCAST_BINDER = "binder"; 29 | public static final String BROADCAST_CODE = "code"; 30 | 31 | private final HandlerThread handlerThread; 32 | private final Handler handler; 33 | 34 | private final int code; 35 | private final Class clazz; 36 | private final IBinder self = new Binder(); 37 | private final Object binderSync = new Object(); 38 | private final Object eventSync = new Object(); 39 | 40 | private volatile WeakReference context; 41 | private volatile IBinder binder = null; 42 | private volatile IRootIPC ipc = null; 43 | private volatile T userIPC = null; 44 | private volatile boolean inEvent = false; 45 | private volatile boolean disconnectAfterEvent = false; 46 | 47 | private final IntentFilter filter = new IntentFilter(BROADCAST_ACTION); 48 | 49 | private final IBinder.DeathRecipient deathRecipient = new IBinder.DeathRecipient() { 50 | @Override 51 | public void binderDied() { 52 | synchronized (binderSync) { 53 | clearBinder(); 54 | binderSync.notifyAll(); 55 | } 56 | } 57 | }; 58 | 59 | private final BroadcastReceiver receiver = new BroadcastReceiver() { 60 | @Override 61 | public void onReceive(Context context, Intent intent) { 62 | IBinder received = null; 63 | 64 | if ((intent.getAction() != null) && intent.getAction().equals(BROADCAST_ACTION)) { 65 | Bundle bundle = intent.getBundleExtra(BROADCAST_EXTRA); 66 | received = bundle.getBinder(BROADCAST_BINDER); 67 | int code = bundle.getInt(BROADCAST_CODE); 68 | if ((code == RootIPCReceiver.this.code) && (received != null)) { 69 | try { 70 | received.linkToDeath(deathRecipient, 0); 71 | } catch (RemoteException e) { 72 | received = null; 73 | } 74 | } else { 75 | received = null; 76 | } 77 | } 78 | 79 | if (received != null) { 80 | synchronized (binderSync) { 81 | binder = received; 82 | ipc = IRootIPC.Stub.asInterface(binder); 83 | try { 84 | userIPC = getInterfaceFromBinder(ipc.getIPC()); 85 | } catch (RemoteException e) { 86 | e.printStackTrace(); 87 | } 88 | try { 89 | ipc.addBinder(self); 90 | handler.post(onConnectRunnable); 91 | } catch (RemoteException e) { 92 | e.printStackTrace(); 93 | } 94 | binderSync.notifyAll(); 95 | } 96 | } 97 | } 98 | }; 99 | 100 | private final Runnable onConnectRunnable = new Runnable() { 101 | @Override 102 | public void run() { 103 | synchronized (binderSync) { 104 | doOnConnect(); 105 | } 106 | } 107 | }; 108 | 109 | public RootIPCReceiver(Context context, int code) { 110 | this(context, code, null); 111 | } 112 | 113 | @SuppressWarnings("unchecked") 114 | public RootIPCReceiver(Context context, int code, Class clazz) { 115 | if (clazz == null) { 116 | Type superClass = getClass().getGenericSuperclass(); 117 | Type tType = ((ParameterizedType)superClass).getActualTypeArguments()[0]; 118 | this.clazz = (Class)tType; 119 | } else { 120 | this.clazz = clazz; 121 | } 122 | this.code = code; 123 | handlerThread = new HandlerThread("DepthExploit:RootIPCReceiver#" + String.valueOf(code)); 124 | handlerThread.start(); 125 | handler = new Handler(handlerThread.getLooper()); 126 | setContext(context); 127 | } 128 | 129 | public void setContext(Context context) { 130 | if (this.context != null) { 131 | Context oldContext = this.context.get(); 132 | if (oldContext != null) { 133 | oldContext.unregisterReceiver(receiver); 134 | } 135 | } 136 | this.context = null; 137 | if (context != null) { 138 | if (context instanceof ContextWrapper) { 139 | if (((ContextWrapper)context).getBaseContext() == null) return; 140 | } 141 | this.context = new WeakReference(context); 142 | context.registerReceiver(receiver, filter, null, handler); 143 | } 144 | } 145 | 146 | private T getInterfaceFromBinder(IBinder binder) { 147 | return (new Reflection.InterfaceRetriever()).getInterfaceFromBinder(clazz, binder); 148 | } 149 | 150 | private void doOnConnect() { 151 | //只能在synchronized(binderSync)内调用 152 | if ((binder != null) && (userIPC != null)) { 153 | synchronized (eventSync) { 154 | disconnectAfterEvent = false; 155 | inEvent = true; 156 | } 157 | onConnect(userIPC); 158 | synchronized (eventSync) { 159 | inEvent = false; 160 | if (disconnectAfterEvent) { 161 | disconnect(); 162 | } 163 | } 164 | } 165 | } 166 | 167 | private void doOnDisconnect() { 168 | //只能在synchronized(binderSync)内调用 169 | if ((binder != null) && (userIPC != null)) { 170 | onDisconnect(userIPC); 171 | } 172 | } 173 | 174 | private void clearBinder() { 175 | doOnDisconnect(); 176 | if (binder != null) { 177 | try { 178 | binder.unlinkToDeath(deathRecipient, 0); 179 | } catch (Exception e) { 180 | e.printStackTrace(); 181 | } 182 | } 183 | binder = null; 184 | ipc = null; 185 | userIPC = null; 186 | } 187 | 188 | private boolean isInEvent() { 189 | synchronized (eventSync) { 190 | return inEvent; 191 | } 192 | } 193 | 194 | public boolean isConnected() { 195 | return (getIPC() != null); 196 | } 197 | 198 | public boolean isDisconnectScheduled() { 199 | synchronized (eventSync) { 200 | if (disconnectAfterEvent) { 201 | return true; 202 | } 203 | } 204 | return false; 205 | } 206 | 207 | public void disconnect() { 208 | synchronized (eventSync) { 209 | if (inEvent) { 210 | disconnectAfterEvent = true; 211 | return; 212 | } 213 | } 214 | 215 | synchronized (binderSync) { 216 | if (ipc != null) { 217 | try { 218 | ipc.removeBinder(self); 219 | } catch (RemoteException e) { 220 | e.printStackTrace(); 221 | } 222 | } 223 | clearBinder(); 224 | } 225 | } 226 | 227 | //释放所有资源 228 | public void release() { 229 | disconnect(); 230 | if (this.context != null) { 231 | Context context = this.context.get(); 232 | if (context != null) { 233 | context.unregisterReceiver(receiver); 234 | } 235 | } 236 | handlerThread.quitSafely(); 237 | } 238 | 239 | public T getIPC() { 240 | if (isDisconnectScheduled()) return null; 241 | if (isInEvent()) { 242 | return userIPC; 243 | } 244 | 245 | synchronized (binderSync) { 246 | if (binder != null) { 247 | if (!binder.isBinderAlive()) { 248 | clearBinder(); 249 | } 250 | } 251 | if ((binder != null) && (userIPC != null)) { 252 | return userIPC; 253 | } 254 | } 255 | return null; 256 | } 257 | 258 | 259 | public T getIPC(int timeout_ms) { 260 | if (isDisconnectScheduled()) return null; 261 | if (isInEvent()) { 262 | return userIPC; 263 | } 264 | 265 | if (timeout_ms <= 0) return getIPC(); 266 | 267 | synchronized (binderSync) { 268 | if (binder == null) { 269 | try { 270 | binderSync.wait(timeout_ms); 271 | } catch (InterruptedException e) { 272 | e.printStackTrace(); 273 | } 274 | } 275 | } 276 | 277 | return getIPC(); 278 | } 279 | } 280 | -------------------------------------------------------------------------------- /core/src/main/java/io/sapp/core/internal/RootServer.java: -------------------------------------------------------------------------------- 1 | package io.sapp.core.internal; 2 | 3 | import android.annotation.SuppressLint; 4 | import android.content.Context; 5 | import android.content.Intent; 6 | import android.content.pm.ApplicationInfo; 7 | import android.content.pm.PackageManager; 8 | import android.os.Build; 9 | import android.os.SystemClock; 10 | 11 | import java.io.File; 12 | import java.io.FilenameFilter; 13 | import java.util.ArrayList; 14 | import java.util.List; 15 | import java.util.Locale; 16 | 17 | import dalvik.system.BaseDexClassLoader; 18 | 19 | /** 20 | * Main class with utility functions to launch Java code running as root.
21 | *
22 | * We execute our code by calling app_process, so we can call into the Android framework easily. 23 | * It is possible to use dalvikvm directly to achieve the same thing, but getting all the 24 | * parameters right across different Android versions can be tricky. Neither option is ideal, 25 | * but app_process seems more stable, and takes care of a lot of work for us.
26 | *
27 | * Note: you may see complaints from dex2oat in logcat during development on 64-bit devices. This 28 | * happens because we patch LD_LIBRARY_PATH for 64-bit libraries, and dex2oat is a 32-bit 29 | * executable. When a release APK is installed however, dex2oat is called at install time and 30 | * the odex should be successfully generated, preventing this error from occurring when you 31 | * launch the Java code as root. When this error is logged, we are likely running in JIT mode, 32 | * which may be significantly slower.
33 | *
34 | * Note: occasionally during development some confusing occurs about the number of bits the 35 | * application has, and the root code will not run. Rebuild your project to fix. 36 | * 37 | * @see #getLaunchScript(Context, Class, String, String, String[], String) 38 | * @see #restoreOriginalLdLibraryPath() 39 | * @see #getSystemContext() 40 | * @see #getPackageContext(String) 41 | * @see #getLibraryPath(Context, String) 42 | // * @see Debugger#setEnabled(boolean) 43 | */ 44 | @SuppressWarnings({"unused", "WeakerAccess", "Convert2Diamond"}) 45 | public class RootServer { 46 | 47 | // ------------------------ calls for non-root ------------------------ 48 | 49 | /** 50 | * Retrieve the full path to a native library.
51 | *
52 | * If you want to load one of your own native libraries, the code running as root will have to 53 | * know it's exact location. This method helps you determine that location.
54 | * 55 | *
 56 |      * {@code
 57 |      * String libpath = RootJava.getLibraryPath(context, "mynativecode");
 58 |      * }
 59 |      * 
60 | * 61 | * NOTE: This is not compatible with using extractNativeLibs="false" in your manifest! 62 | * 63 | * @param context Application or activity context 64 | * @param libname Name of the library 65 | * @return Full path to library or null 66 | */ 67 | @SuppressLint("SdCardPath") 68 | public static String getLibraryPath(Context context, String libname) { 69 | if (Build.VERSION.SDK_INT >= 23) { 70 | if ((context.getApplicationInfo().flags & ApplicationInfo.FLAG_EXTRACT_NATIVE_LIBS) == 0) { 71 | throw new RuntimeException("incompatible with extractNativeLibs=\"false\" in your manifest"); 72 | } 73 | } 74 | 75 | if (libname.toLowerCase().startsWith("lib")) { 76 | libname = libname.substring(3); 77 | } 78 | if (libname.toLowerCase().endsWith(".so")) { 79 | libname = libname.substring(0, libname.length() - 3); 80 | } 81 | String packageName = context.getPackageName(); 82 | 83 | // try nativeLibraryDir 84 | ApplicationInfo appInfo = context.getApplicationInfo(); 85 | for (String candidate : new String[] { 86 | appInfo.nativeLibraryDir + File.separator + "lib" + libname + ".so", 87 | appInfo.nativeLibraryDir + File.separator + libname + ".so" // unlikely but not impossible 88 | }) { 89 | if (new File(candidate).exists()) { 90 | return candidate; 91 | } 92 | } 93 | 94 | // try BaseDexClassLoader 95 | if (context.getClassLoader() instanceof BaseDexClassLoader) { 96 | try { 97 | BaseDexClassLoader bdcl = (BaseDexClassLoader)context.getClassLoader(); 98 | return bdcl.findLibrary(libname); 99 | } catch (Throwable t) { 100 | // not a standard call: catch Errors and Violations too aside from Exceptions 101 | } 102 | } 103 | 104 | // try (old) default location 105 | for (String candidate : new String[] { 106 | String.format(Locale.ENGLISH, "/data/data/%s/lib/lib%s.so", packageName, libname), 107 | String.format(Locale.ENGLISH, "/data/data/%s/lib/%s.so", packageName, libname) 108 | }) { 109 | if (new File(candidate).exists()) { 110 | return candidate; 111 | } 112 | } 113 | 114 | return null; 115 | } 116 | 117 | /** 118 | * Get string to be executed (in a root shell) to launch the Java code as root. 119 | * 120 | * You would normally use {@link #getLaunchScript(Context, Class, String, String, String[], String)} 121 | * 122 | * @param context Application or activity context 123 | * @param clazz Class containing "main" method 124 | * @param app_process Specific app_process binary to use, or null for default 125 | * @param params Parameters to supply to Java code, or null 126 | * @param niceName Process name to use (ps) instead of app_process (should be unique to your app), or null 127 | * @return Script 128 | */ 129 | public static String getLaunchString(Context context, Class clazz, String app_process, String[] params, String niceName) { 130 | if (app_process == null) app_process = AppProcess.getAppProcess(); 131 | return getLaunchString(context.getPackageCodePath(), clazz.getName(), app_process, AppProcess.guessIfAppProcessIs64Bits(app_process), params, niceName); 132 | } 133 | 134 | public static String getLaunchString(String packageCodePath, Class clazz, String app_process, String[] params, String niceName) { 135 | if (app_process == null) app_process = AppProcess.getAppProcess(); 136 | return getLaunchString(packageCodePath, clazz.getName(), app_process, AppProcess.guessIfAppProcessIs64Bits(app_process), params, niceName); 137 | } 138 | 139 | /** 140 | * Get string to be executed (in a root shell) to launch the Java code as root. 141 | * 142 | * You would normally use {@link #getLaunchScript(Context, Class, String, String, String[], String)} 143 | * 144 | * @param packageCodePath Path to APK 145 | * @param clazz Class containing "main" method 146 | * @param app_process Specific app_process binary to use 147 | * @param is64Bit Is specific app_process binary 64-bit? 148 | * @param params Parameters to supply to Java code, or null 149 | * @param niceName Process name to use (ps) instead of app_process (should be unique to your app), or null 150 | * @return Script 151 | */ 152 | public static String getLaunchString(String packageCodePath, String clazz, String app_process, boolean is64Bit, String[] params, String niceName) { 153 | String ANDROID_ROOT = System.getenv("ANDROID_ROOT"); 154 | StringBuilder prefix = new StringBuilder(); 155 | if (ANDROID_ROOT != null) { 156 | prefix.append("ANDROID_ROOT="); 157 | prefix.append(ANDROID_ROOT); 158 | prefix.append(' '); 159 | } 160 | 161 | int p; 162 | String[] extraPaths = null; 163 | if ((p = app_process.lastIndexOf('/')) >= 0) { 164 | extraPaths = new String[] { app_process.substring(0, p) }; 165 | } 166 | String LD_LIBRARY_PATH = Linker.getPatchedLdLibraryPath(is64Bit, extraPaths); 167 | if (LD_LIBRARY_PATH != null) { 168 | prefix.append("LD_LIBRARY_PATH="); 169 | prefix.append(LD_LIBRARY_PATH); 170 | prefix.append(' '); 171 | } 172 | 173 | String vmParams = ""; 174 | String extraParams = ""; 175 | if (niceName != null) { 176 | extraParams += " --nice-name=" + niceName; 177 | } 178 | if (Debugger.enabled) { // we don't use isEnabled() because that has a different meaning when called as root, and though rare we might call this method from root too 179 | vmParams += " -Xcompiler-option --debuggable"; 180 | if (Build.VERSION.SDK_INT >= 28) { 181 | // Android 9.0 Pie changed things up a bit 182 | vmParams += " -XjdwpProvider:internal -XjdwpOptions:transport=dt_android_adb,suspend=n,server=y"; 183 | } else { 184 | vmParams += " -agentlib:jdwp=transport=dt_android_adb,suspend=n,server=y"; 185 | } 186 | } 187 | String ret = String.format("NO_ADDR_COMPAT_LAYOUT_FIXUP=1 %sCLASSPATH=%s %s%s /system/bin%s %s", prefix.toString(), packageCodePath, app_process, vmParams, extraParams, clazz); 188 | if (params != null) { 189 | StringBuilder full = new StringBuilder(ret); 190 | for (String param : params) { 191 | full.append(' '); 192 | full.append(param); 193 | } 194 | ret = full.toString(); 195 | } 196 | return ret; 197 | } 198 | 199 | /** 200 | * Get script to be executed (in a root shell) to launch the Java code as root.
201 | *
202 | * app_process is relocated during script execution. If a relocate_path is supplied 203 | * it must already exist. It is also made linker-namespace-safe, so optionally you 204 | * can put native libraries there (rarely necessary). By default we relocate to the app's 205 | * cache dir, falling back to /dev in case of issues or the app living on external storage.
206 | *
207 | * Note that SELinux policy patching takes place only in the script returned from 208 | * the first call, so be sure to execute that script first if you call this method 209 | * multiple times. You can change this behavior with the {@link Policies#setPatched(Boolean)} 210 | * method. The patch is only needed for the Binder-based IPC calls, if you do not use those, 211 | * you may consider passing true to {@link Policies#setPatched(Boolean)} and prevent the 212 | * patching altogether. 213 | * 214 | * @param context Application or activity context 215 | * @param clazz Class containing "main" method 216 | * @param app_process Specific app_process binary to use, or null for default 217 | * @param relocate_path Path to relocate app_process to (must exist), or null for default 218 | * @param params Parameters to supply to Java code, or null 219 | * @param niceName Process name to use (ps) instead of app_process (should be unique to your app), or null 220 | * @return Script 221 | */ 222 | public static List getLaunchScript(Context context, Class clazz, String app_process, String relocate_path, String[] params, String niceName) { 223 | ArrayList pre = new ArrayList(); 224 | ArrayList post = new ArrayList(); 225 | 226 | // relocate app_process 227 | app_process = AppProcess.getAppProcessRelocate(context, app_process, pre, post, relocate_path); 228 | 229 | // librootjavadaemon uses this 230 | pre.add(0, "#app_process=" + app_process); 231 | 232 | // patch SELinux policies 233 | Policies.getPatch(pre); 234 | 235 | // combine 236 | ArrayList script = new ArrayList(pre); 237 | script.add(getLaunchString(context, clazz, app_process, params, niceName)); 238 | script.addAll(post); 239 | return script; 240 | } 241 | 242 | public static List getLaunchScript(Context context,String packageCodePath, Class clazz, String app_process, String relocate_path, String[] params, String niceName) { 243 | ArrayList pre = new ArrayList(); 244 | ArrayList post = new ArrayList(); 245 | 246 | // relocate app_process 247 | app_process = AppProcess.getAppProcessRelocate(context, app_process, pre, post, relocate_path); 248 | 249 | // librootjavadaemon uses this 250 | pre.add(0, "#app_process=" + app_process); 251 | 252 | // patch SELinux policies 253 | Policies.getPatch(pre); 254 | 255 | // combine 256 | ArrayList script = new ArrayList(pre); 257 | script.add(getLaunchString(packageCodePath, clazz, app_process, params, niceName)); 258 | script.addAll(post); 259 | return script; 260 | } 261 | 262 | /** Prefixes of filename to remove from the app's cache directory */ 263 | public static final String[] CLEANUP_CACHE_PREFIXES = new String[] { ".app_process32_", ".app_process64_" }; 264 | 265 | /** 266 | * Clean up leftover files from our cache directory.
267 | *
268 | * In ideal circumstances no files should be left dangling, but in practise it happens sooner 269 | * or later anyway. Periodically (once per app launch or per boot) calling this method is 270 | * advised.
271 | *
272 | * This method should be called from a background thread, as it performs disk i/o.
273 | *
274 | * It is difficult to determine which of these files may actually be in use, especially in 275 | * daemon mode. We try to determine device boot time, and wipe everything from before that 276 | * time. For safety we explicitly keep files using our current UUID. 277 | * 278 | * @param context Context to retrieve cache directory from 279 | */ 280 | public static void cleanupCache(Context context) { 281 | cleanupCache(context, CLEANUP_CACHE_PREFIXES); 282 | } 283 | 284 | /** 285 | * Clean up leftover files from our cache directory.
286 | *
287 | * This version is for internal use, see {@link #cleanupCache(Context)} instead. 288 | * 289 | * @param context Context to retrieve cache directory from 290 | * @param prefixes List of prefixes to scrub 291 | */ 292 | public static void cleanupCache(Context context, final String[] prefixes) { 293 | try { 294 | File cacheDir = context.getCacheDir(); 295 | if (cacheDir.exists()) { 296 | // determine time of last boot 297 | long boot = System.currentTimeMillis() - SystemClock.elapsedRealtime(); 298 | 299 | // find our files 300 | for (File file : cacheDir.listFiles(new FilenameFilter() { 301 | @Override 302 | public boolean accept(File dir, String name) { 303 | boolean accept = false; 304 | for (String prefix : prefixes) { 305 | // just in case: don't return files that contain our current uuid 306 | if (name.startsWith(prefix) && !name.endsWith(AppProcess.UUID)) { 307 | accept = true; 308 | break; 309 | } 310 | } 311 | return accept; 312 | } 313 | })) { 314 | if (file.lastModified() < boot) { 315 | //noinspection ResultOfMethodCallIgnored 316 | file.delete(); 317 | } 318 | } 319 | } 320 | } catch (Exception e) { 321 | e.printStackTrace(); 322 | } 323 | } 324 | 325 | // ------------------------ calls for root ------------------------ 326 | 327 | /** 328 | * Restores correct LD_LIBRARY_PATH environment variable. This should be one of the first 329 | * calls in your Java code running as root, after (optionally) loading native libraries.
330 | *
331 | * Failing to call this method may cause errors when executing other binaries (such as 332 | * running shell commands). 333 | * 334 | * @see Linker#restoreOriginalLdLibraryPath() 335 | * @see Linker#getPatchedLdLibraryPath(boolean, String[]) 336 | */ 337 | public static void restoreOriginalLdLibraryPath() { 338 | Linker.restoreOriginalLdLibraryPath(); 339 | } 340 | 341 | /** 342 | * Returns a context that is useful for some calls - but this is not a proper full 343 | * context, and many calls that take a context do not actually work when running as root, or 344 | * not having the Android framework fully spun up, or not having an active ProcessRecord. 345 | * Some services can be accessed (see getPackageManager(), getSystemService(), ...).
346 | *
347 | * Due to preparing the main looper, this throws off libsuperuser if you use it for shell 348 | * commands on the main thread. If you use this call, you will probably need to call 349 | * Debug.setSanityChecksEnabled(false) to get any shell calls executed, and create a 350 | * separate HandlerThread (and Handler), and use both Shell.Builder.setAutoHandler(false) 351 | * and Shell.Builder.setHandler(^^^^) for Shell.Interactive to behave as expected. 352 | * 353 | * @return System context 354 | */ 355 | public static Context getSystemContext() { 356 | return Reflection.getSystemContext(); 357 | } 358 | 359 | /** 360 | * Returns a context with access to the resources of the passed package. This context is still 361 | * limited in many of the same ways the context returned by {@link #getSystemContext()} is, as 362 | * we still do not have an active ProcessRecord. 363 | * 364 | * @see #getSystemContext() 365 | * 366 | * @param packageName Name of the package to create Context for. Use BuildConfig.APPLICATION_ID (double check you're importing the correct BuildConfig!) to access our own package. 367 | * @return Package context 368 | * @throws PackageManager.NameNotFoundException If package could not be found 369 | */ 370 | public static Context getPackageContext(String packageName) throws PackageManager.NameNotFoundException { 371 | return getSystemContext().createPackageContext(packageName, 0); 372 | } 373 | 374 | /** 375 | * Broadcast an intent using a reflected method that doesn't require us to have a Context or 376 | * ProcessRecord. 377 | * 378 | * @param intent Intent to broadcast 379 | */ 380 | public static void sendBroadcast(Intent intent) { 381 | Reflection.sendBroadcast(intent); 382 | } 383 | 384 | } 385 | -------------------------------------------------------------------------------- /core/src/main/java/io/sapp/core/utils/Debug.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2019 Jorrit "Chainfire" Jongma 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.sapp.core.utils; 18 | 19 | import android.os.Looper; 20 | import android.os.Process; 21 | import android.util.Log; 22 | 23 | import androidx.annotation.AnyThread; 24 | import androidx.annotation.NonNull; 25 | import androidx.annotation.Nullable; 26 | 27 | import io.sapp.core.BuildConfig; 28 | 29 | 30 | /** 31 | * Utility class for logging and debug features that (by default) does nothing when not in debug mode 32 | */ 33 | @SuppressWarnings({"WeakerAccess", "UnusedReturnValue", "unused"}) 34 | @AnyThread 35 | public class Debug { 36 | 37 | // ----- DEBUGGING ----- 38 | 39 | private static boolean debug = BuildConfig.DEBUG; 40 | 41 | /** 42 | *

Enable or disable debug mode

43 | * 44 | *

By default, debug mode is enabled for development 45 | * builds and disabled for exported APKs - see 46 | * BuildConfig.DEBUG

47 | * 48 | * @param enable Enable debug mode ? 49 | */ 50 | public static void setDebug(boolean enable) { 51 | debug = enable; 52 | } 53 | 54 | /** 55 | *

Is debug mode enabled ?

56 | * 57 | * @return Debug mode enabled 58 | */ 59 | public static boolean getDebug() { 60 | return debug; 61 | } 62 | 63 | // ----- LOGGING ----- 64 | 65 | public interface OnLogListener { 66 | void onLog(int type, String typeIndicator, String message); 67 | } 68 | 69 | public static final String TAG = "DepthExploit"; 70 | 71 | public static final int LOG_GENERAL = 0x0001; 72 | public static final int LOG_COMMAND = 0x0002; 73 | public static final int LOG_OUTPUT = 0x0004; 74 | public static final int LOG_POOL = 0x0008; 75 | 76 | public static final int LOG_NONE = 0x0000; 77 | public static final int LOG_ALL = 0xFFFF; 78 | 79 | private static int logTypes = LOG_ALL; 80 | 81 | @Nullable 82 | private static OnLogListener logListener = null; 83 | 84 | /** 85 | *

Log a message (internal)

86 | * 87 | *

Current debug and enabled logtypes decide what gets logged - 88 | * even if a custom callback is registered

89 | * 90 | * @param type Type of message to log 91 | * @param typeIndicator String indicator for message type 92 | * @param message The message to log 93 | */ 94 | private static void logCommon(int type, @NonNull String typeIndicator, @NonNull String message) { 95 | if (debug && ((logTypes & type) == type)) { 96 | if (logListener != null) { 97 | logListener.onLog(type, typeIndicator, message); 98 | } else { 99 | Log.d(TAG, "[" + TAG + "][" + typeIndicator + "]" + (!message.startsWith("[") && !message.startsWith(" ") ? " " : "") + message); 100 | } 101 | } 102 | } 103 | 104 | /** 105 | *

Log a "general" message

106 | * 107 | *

These messages are infrequent and mostly occur at startup/shutdown or on error

108 | * 109 | * @param message The message to log 110 | */ 111 | public static void log(@NonNull String message) { 112 | logCommon(LOG_GENERAL, "G", message); 113 | } 114 | 115 | /** 116 | *

Log a "per-command" message

117 | * 118 | *

This could produce a lot of output if the client runs many commands in the session

119 | * 120 | * @param message The message to log 121 | */ 122 | public static void logCommand(@NonNull String message) { 123 | logCommon(LOG_COMMAND, "C", message); 124 | } 125 | 126 | /** 127 | *

Log a line of stdout/stderr output

128 | * 129 | *

This could produce a lot of output if the shell commands are noisy

130 | * 131 | * @param message The message to log 132 | */ 133 | public static void logOutput(@NonNull String message) { 134 | logCommon(LOG_OUTPUT, "O", message); 135 | } 136 | 137 | /** 138 | *

Log pool event

139 | * 140 | * @param message The message to log 141 | */ 142 | public static void logPool(@NonNull String message) { 143 | logCommon(LOG_POOL, "P", message); 144 | } 145 | 146 | /** 147 | *

Enable or disable logging specific types of message

148 | * 149 | *

You may | (or) LOG_* constants together. Note that 150 | * debug mode must also be enabled for actual logging to 151 | * occur.

152 | * 153 | * @param type LOG_* constants 154 | * @param enable Enable or disable 155 | */ 156 | public static void setLogTypeEnabled(int type, boolean enable) { 157 | if (enable) { 158 | logTypes |= type; 159 | } else { 160 | logTypes &= ~type; 161 | } 162 | } 163 | 164 | /** 165 | *

Is logging for specific types of messages enabled ?

166 | * 167 | *

You may | (or) LOG_* constants together, to learn if 168 | * all passed message types are enabled for logging. Note 169 | * that debug mode must also be enabled for actual logging 170 | * to occur.

171 | * 172 | * @param type LOG_* constants 173 | * @return enabled? 174 | */ 175 | public static boolean getLogTypeEnabled(int type) { 176 | return ((logTypes & type) == type); 177 | } 178 | 179 | /** 180 | *

Is logging for specific types of messages enabled ?

181 | * 182 | *

You may | (or) LOG_* constants together, to learn if 183 | * all message types are enabled for logging. Takes 184 | * debug mode into account for the result.

185 | * 186 | * @param type LOG_* constants 187 | * @return enabled and in debug mode? 188 | */ 189 | public static boolean getLogTypeEnabledEffective(int type) { 190 | return getDebug() && getLogTypeEnabled(type); 191 | } 192 | 193 | /** 194 | *

Register a custom log handler

195 | * 196 | *

Replaces the log method (write to logcat) with your own 197 | * handler. Whether your handler gets called is still dependent 198 | * on debug mode and message types being enabled for logging.

199 | * 200 | * @param onLogListener Custom log listener or NULL to revert to default 201 | */ 202 | public static void setOnLogListener(@Nullable OnLogListener onLogListener) { 203 | logListener = onLogListener; 204 | } 205 | 206 | /** 207 | *

Get the currently registered custom log handler

208 | * 209 | * @return Current custom log handler or NULL if none is present 210 | */ 211 | @Nullable 212 | public static OnLogListener getOnLogListener() { 213 | return logListener; 214 | } 215 | 216 | // ----- SANITY CHECKS ----- 217 | 218 | private static boolean sanityChecks = true; 219 | 220 | /** 221 | *

Enable or disable sanity checks

222 | * 223 | *

Enables or disables the library crashing when su is called 224 | * from the main thread.

225 | * 226 | * @param enable Enable or disable 227 | */ 228 | public static void setSanityChecksEnabled(boolean enable) { 229 | sanityChecks = enable; 230 | } 231 | 232 | /** 233 | *

Are sanity checks enabled ?

234 | * 235 | *

Note that debug mode must also be enabled for actual 236 | * sanity checks to occur.

237 | * 238 | * @return True if enabled 239 | */ 240 | public static boolean getSanityChecksEnabled() { 241 | return sanityChecks; 242 | } 243 | 244 | /** 245 | *

Are sanity checks enabled ?

246 | * 247 | *

Takes debug mode into account for the result.

248 | * 249 | * @return True if enabled 250 | */ 251 | public static boolean getSanityChecksEnabledEffective() { 252 | return getDebug() && getSanityChecksEnabled(); 253 | } 254 | 255 | /** 256 | *

Are we running on the main thread ?

257 | * 258 | * @return Running on main thread ? 259 | */ 260 | public static boolean onMainThread() { 261 | return ((Looper.myLooper() != null) && (Looper.myLooper() == Looper.getMainLooper()) && (Process.myUid() != 0)); 262 | } 263 | 264 | } 265 | -------------------------------------------------------------------------------- /core/src/main/java/io/sapp/core/utils/ShellNotClosedException.java: -------------------------------------------------------------------------------- 1 | package io.sapp.core.utils; 2 | 3 | /** 4 | * Exception class used to notify developer that a shell was not close()d 5 | */ 6 | @SuppressWarnings("serial") 7 | public class ShellNotClosedException extends RuntimeException { 8 | public static final String EXCEPTION_NOT_CLOSED = "Application did not close() interactive shell"; 9 | 10 | public ShellNotClosedException() { 11 | super(EXCEPTION_NOT_CLOSED); 12 | } 13 | } -------------------------------------------------------------------------------- /core/src/main/java/io/sapp/core/utils/ShellOnMainThreadException.java: -------------------------------------------------------------------------------- 1 | package io.sapp.core.utils; 2 | 3 | /** 4 | * Exception class used to crash application when shell commands are executed 5 | * from the main thread, and we are in debug mode. 6 | */ 7 | @SuppressWarnings("serial") 8 | public class ShellOnMainThreadException extends RuntimeException { 9 | public static final String EXCEPTION_COMMAND = "Application attempted to run a shell command from the main thread"; 10 | public static final String EXCEPTION_NOT_IDLE = "Application attempted to wait for a non-idle shell to close on the main thread"; 11 | public static final String EXCEPTION_WAIT_IDLE = "Application attempted to wait for a shell to become idle on the main thread"; 12 | 13 | public ShellOnMainThreadException(String message) { 14 | super(message); 15 | } 16 | } -------------------------------------------------------------------------------- /core/src/main/java/io/sapp/core/utils/StreamGobbler.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2012-2019 Jorrit "Chainfire" Jongma 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.sapp.core.utils; 18 | 19 | import java.io.BufferedReader; 20 | import java.io.IOException; 21 | import java.io.InputStream; 22 | import java.io.InputStreamReader; 23 | import java.util.List; 24 | 25 | /** 26 | * Thread utility class continuously reading from an InputStream 27 | */ 28 | public class StreamGobbler extends Thread { 29 | /** 30 | * Line callback interface 31 | */ 32 | public interface OnLineListener { 33 | /** 34 | *

Line callback

35 | * 36 | *

This callback should process the line as quickly as possible. 37 | * Delays in this callback may pause the native process or even 38 | * result in a deadlock

39 | * 40 | * @param line String that was gobbled 41 | */ 42 | public void onLine(String line); 43 | } 44 | 45 | private String shell = null; 46 | private BufferedReader reader = null; 47 | private List writer = null; 48 | private OnLineListener listener = null; 49 | 50 | /** 51 | *

StreamGobbler constructor

52 | * 53 | *

We use this class because shell STDOUT and STDERR should be read as quickly as 54 | * possible to prevent a deadlock from occurring, or Process.waitFor() never 55 | * returning (as the buffer is full, pausing the native process)

56 | * 57 | * @param shell Name of the shell 58 | * @param inputStream InputStream to read from 59 | * @param outputList List to write to, or null 60 | */ 61 | public StreamGobbler(String shell, InputStream inputStream, List outputList) { 62 | this.shell = shell; 63 | reader = new BufferedReader(new InputStreamReader(inputStream)); 64 | writer = outputList; 65 | } 66 | 67 | /** 68 | *

StreamGobbler constructor

69 | * 70 | *

We use this class because shell STDOUT and STDERR should be read as quickly as 71 | * possible to prevent a deadlock from occurring, or Process.waitFor() never 72 | * returning (as the buffer is full, pausing the native process)

73 | * 74 | * @param shell Name of the shell 75 | * @param inputStream InputStream to read from 76 | * @param onLineListener OnLineListener callback 77 | */ 78 | public StreamGobbler(String shell, InputStream inputStream, OnLineListener onLineListener) { 79 | this.shell = shell; 80 | reader = new BufferedReader(new InputStreamReader(inputStream)); 81 | listener = onLineListener; 82 | } 83 | 84 | @Override 85 | public void run() { 86 | // keep reading the InputStream until it ends (or an error occurs) 87 | try { 88 | String line = null; 89 | while ((line = reader.readLine()) != null) { 90 | Debug.logOutput(String.format("[%s] %s", shell, line)); 91 | if (writer != null) writer.add(line); 92 | if (listener != null) listener.onLine(line); 93 | } 94 | } catch (IOException e) { 95 | } 96 | 97 | // make sure our stream is closed and resources will be freed 98 | try { 99 | reader.close(); 100 | } catch (IOException e) { 101 | } 102 | } 103 | } -------------------------------------------------------------------------------- /core/src/main/res/values/theme.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | -------------------------------------------------------------------------------- /core/src/test/java/io/sapp/core/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package io.sapp.core; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * @see Testing documentation 11 | */ 12 | public class ExampleUnitTest { 13 | @Test 14 | public void addition_isCorrect() { 15 | assertEquals(4, 2 + 2); 16 | } 17 | } -------------------------------------------------------------------------------- /dynamic/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /dynamic/README.md: -------------------------------------------------------------------------------- 1 | # Dynamic 2 | 这是插件化Apk核心 -------------------------------------------------------------------------------- /dynamic/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'com.android.library' 3 | } 4 | 5 | android { 6 | compileSdkVersion 31 7 | buildToolsVersion "31.0.0" 8 | 9 | defaultConfig { 10 | minSdkVersion 21 11 | targetSdkVersion 31 12 | versionCode 1 13 | versionName "1.0" 14 | 15 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 16 | consumerProguardFiles "consumer-rules.pro" 17 | } 18 | 19 | buildTypes { 20 | release { 21 | minifyEnabled false 22 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 23 | } 24 | } 25 | compileOptions { 26 | sourceCompatibility JavaVersion.VERSION_1_8 27 | targetCompatibility JavaVersion.VERSION_1_8 28 | } 29 | } 30 | 31 | dependencies { 32 | 33 | implementation 'androidx.appcompat:appcompat:1.3.1' 34 | implementation 'com.google.android.material:material:1.4.0' 35 | testImplementation 'junit:junit:4.+' 36 | androidTestImplementation 'androidx.test.ext:junit:1.1.3' 37 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' 38 | } -------------------------------------------------------------------------------- /dynamic/consumer-rules.pro: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xw103/DeepApp/d30fab1e0a600d586bf10d83483ff2b7141b2575/dynamic/consumer-rules.pro -------------------------------------------------------------------------------- /dynamic/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile -------------------------------------------------------------------------------- /dynamic/src/androidTest/java/io/dynamic/loader/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package io.dynamic.loader; 2 | 3 | import android.content.Context; 4 | 5 | import androidx.test.platform.app.InstrumentationRegistry; 6 | import androidx.test.ext.junit.runners.AndroidJUnit4; 7 | 8 | import org.junit.Test; 9 | import org.junit.runner.RunWith; 10 | 11 | import static org.junit.Assert.*; 12 | 13 | /** 14 | * Instrumented test, which will execute on an Android device. 15 | * 16 | * @see Testing documentation 17 | */ 18 | @RunWith(AndroidJUnit4.class) 19 | public class ExampleInstrumentedTest { 20 | @Test 21 | public void useAppContext() { 22 | // Context of the app under test. 23 | Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); 24 | assertEquals("com.dynamic.loader.test", appContext.getPackageName()); 25 | } 26 | } -------------------------------------------------------------------------------- /dynamic/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | -------------------------------------------------------------------------------- /dynamic/src/test/java/io/dynamic/loader/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package io.dynamic.loader; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * @see Testing documentation 11 | */ 12 | public class ExampleUnitTest { 13 | @Test 14 | public void addition_isCorrect() { 15 | assertEquals(4, 2 + 2); 16 | } 17 | } -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | # IDE (e.g. Android Studio) users: 3 | # Gradle settings configured through the IDE *will override* 4 | # any settings specified in this file. 5 | # For more details on how to configure your build environment visit 6 | # http://www.gradle.org/docs/current/userguide/build_environment.html 7 | # Specifies the JVM arguments used for the daemon process. 8 | # The setting is particularly useful for tweaking memory settings. 9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 10 | # When configured, Gradle will run in incubating parallel mode. 11 | # This option should only be used with decoupled projects. More details, visit 12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 13 | # org.gradle.parallel=true 14 | # AndroidX package structure to make it clearer which packages are bundled with the 15 | # Android operating system, and which are packaged with your app"s APK 16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn 17 | android.useAndroidX=true 18 | # Automatically convert third-party libraries to use AndroidX 19 | android.enableJetifier=true -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 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 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /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 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 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 Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /hide/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /hide/README.md: -------------------------------------------------------------------------------- 1 | # Hide App 2 | 这是APK隐藏核心,一键隐藏应用程序防止被检测。
3 | 由于需要对base.apk进行隐藏,所以请在确保不需要访问base.apk文件后再进行隐藏。
4 | ### 随机安装 5 | - [x] 随机应用名 6 | - [x] 随机包名 7 | - [x] 随机版本号 8 | - [ ] 随机图标 9 | -------------------------------------------------------------------------------- /hide/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'com.android.library' 3 | } 4 | 5 | android { 6 | compileSdkVersion 30 7 | buildToolsVersion "31.0.0" 8 | 9 | defaultConfig { 10 | minSdkVersion 21 11 | targetSdkVersion 28 12 | versionCode 1 13 | versionName "1.0" 14 | 15 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 16 | consumerProguardFiles "consumer-rules.pro" 17 | } 18 | 19 | buildTypes { 20 | release { 21 | minifyEnabled false 22 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 23 | } 24 | } 25 | compileOptions { 26 | sourceCompatibility JavaVersion.VERSION_1_8 27 | targetCompatibility JavaVersion.VERSION_1_8 28 | } 29 | } 30 | 31 | dependencies { 32 | implementation fileTree(dir: 'libs', include: ['*.jar']) 33 | implementation 'androidx.appcompat:appcompat:1.3.1' 34 | implementation 'com.google.android.material:material:1.4.0' 35 | // testImplementation 'junit:junit:4.+' 36 | androidTestImplementation 'androidx.test.ext:junit:1.1.3' 37 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' 38 | } -------------------------------------------------------------------------------- /hide/consumer-rules.pro: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xw103/DeepApp/d30fab1e0a600d586bf10d83483ff2b7141b2575/hide/consumer-rules.pro -------------------------------------------------------------------------------- /hide/libs/ManifestEditor-1.0.2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xw103/DeepApp/d30fab1e0a600d586bf10d83483ff2b7141b2575/hide/libs/ManifestEditor-1.0.2.jar -------------------------------------------------------------------------------- /hide/libs/bcprov-jdk15-143.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xw103/DeepApp/d30fab1e0a600d586bf10d83483ff2b7141b2575/hide/libs/bcprov-jdk15-143.jar -------------------------------------------------------------------------------- /hide/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile -------------------------------------------------------------------------------- /hide/src/androidTest/java/io/app/hide/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package io.app.hide; 2 | 3 | import android.content.Context; 4 | 5 | import androidx.test.platform.app.InstrumentationRegistry; 6 | import androidx.test.ext.junit.runners.AndroidJUnit4; 7 | 8 | import org.junit.Test; 9 | import org.junit.runner.RunWith; 10 | 11 | import static org.junit.Assert.*; 12 | 13 | /** 14 | * Instrumented test, which will execute on an Android device. 15 | * 16 | * @see Testing documentation 17 | */ 18 | @RunWith(AndroidJUnit4.class) 19 | public class ExampleInstrumentedTest { 20 | @Test 21 | public void useAppContext() { 22 | // Context of the app under test. 23 | Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); 24 | assertEquals("io.app.hide.test", appContext.getPackageName()); 25 | } 26 | } -------------------------------------------------------------------------------- /hide/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /hide/src/main/java/io/app/hide/activity/InstallActivity.java: -------------------------------------------------------------------------------- 1 | package io.app.hide.activity; 2 | 3 | import android.app.Activity; 4 | import android.app.AlertDialog; 5 | import android.content.Intent; 6 | import android.content.pm.PackageInfo; 7 | import android.content.pm.PackageManager; 8 | import android.net.Uri; 9 | import android.os.Build; 10 | import android.os.Bundle; 11 | import android.os.Handler; 12 | import android.os.Looper; 13 | import android.util.Log; 14 | 15 | import androidx.annotation.Nullable; 16 | 17 | import com.wind.meditor.core.FileProcesser; 18 | import com.wind.meditor.property.AttributeItem; 19 | import com.wind.meditor.property.ModificationProperty; 20 | import com.wind.meditor.utils.NodeValue; 21 | 22 | import java.io.ByteArrayOutputStream; 23 | import java.io.File; 24 | import java.io.FileInputStream; 25 | import java.io.FileOutputStream; 26 | import java.io.IOException; 27 | import java.io.InputStream; 28 | import java.io.OutputStream; 29 | 30 | import io.app.hide.R; 31 | import io.app.hide.apksigner.KeyHelper; 32 | import io.app.hide.apksigner.SignApk; 33 | import io.app.hide.utils.RandomInfo; 34 | 35 | public class InstallActivity extends Activity implements Runnable { 36 | @Override 37 | protected void onCreate(@Nullable Bundle savedInstanceState) { 38 | super.onCreate(savedInstanceState); 39 | setContentView(R.layout.activity_install); 40 | new Thread(this).start(); 41 | } 42 | 43 | @Override 44 | public void run() { 45 | try { 46 | File baseDir = new File(getFilesDir().getAbsolutePath()); 47 | if (baseDir.exists()) { 48 | delete(baseDir); 49 | } 50 | baseDir.mkdirs(); 51 | //拷贝apk到工作目录 52 | File inFile = //new File("/storage/emulated/0/base.apk"); 53 | new File(getApplicationInfo().sourceDir); 54 | File outFile = new File(baseDir.getAbsolutePath() + "/base.apk"); 55 | outFile.createNewFile(); 56 | FileInputStream fis = new FileInputStream(inFile); 57 | FileOutputStream fos = new FileOutputStream(outFile); 58 | byte[] buf = new byte[10240]; 59 | int len = 0; 60 | while ((len = fis.read(buf)) != -1) { 61 | fos.write(buf, 0, len); 62 | } 63 | fis.close(); 64 | fos.flush(); 65 | fos.close(); 66 | ModificationProperty property = new ModificationProperty(); 67 | property.addManifestAttribute(new AttributeItem(NodeValue.Manifest.VERSION_CODE, RandomInfo.getVersionCode())) 68 | .addManifestAttribute(new AttributeItem(NodeValue.Manifest.VERSION_NAME, RandomInfo.getVersionName())) 69 | .addApplicationAttribute(new AttributeItem(NodeValue.Application.LABEL, RandomInfo.getAppName())) 70 | .addManifestAttribute(new AttributeItem(NodeValue.Manifest.PACKAGE, RandomInfo.getRandomPackageName()).setNamespace(null)); 71 | // 处理得到的未签名的apk 72 | FileProcesser.processApkFile(outFile.getAbsolutePath(), baseDir.getAbsolutePath() + "/app-unsigned.apk", property); 73 | delete(outFile); 74 | if (signApk(baseDir.getAbsolutePath() + "/app-unsigned.apk", baseDir.getAbsolutePath() + "/app-release.apk")) { 75 | installApk(); 76 | } else { 77 | throw new Exception("签名失败"); 78 | } 79 | } catch (Exception e) { 80 | e.printStackTrace(); 81 | new Handler(Looper.getMainLooper()).post(() -> { 82 | AlertDialog.Builder builder = new AlertDialog.Builder(InstallActivity.this); 83 | builder.setTitle("随机安装失败"); 84 | builder.setMessage(Log.getStackTraceString(e)); 85 | builder.setPositiveButton("确定", (dialog, which) -> { 86 | dialog.dismiss(); 87 | }); 88 | AlertDialog d = builder.create(); 89 | d.show(); 90 | }); 91 | } 92 | } 93 | 94 | public void installApk() { 95 | runShell("pm install " + getFilesDir().getAbsolutePath() + "/app-release.apk", true); 96 | PackageManager pm = getPackageManager(); 97 | PackageInfo pi = pm.getPackageArchiveInfo(getFilesDir().getAbsolutePath() + "/app-release.apk", 0); 98 | if (pi == null) { 99 | new Handler(Looper.getMainLooper()).post(() -> { 100 | AlertDialog.Builder builder = new AlertDialog.Builder(InstallActivity.this); 101 | builder.setTitle("安装失败"); 102 | builder.setMessage("apk打包失败"); 103 | builder.setPositiveButton("确定", (dialog, which) -> { 104 | dialog.dismiss(); 105 | finish(); 106 | }); 107 | AlertDialog d = builder.create(); 108 | d.show(); 109 | }); 110 | }else { 111 | new Handler(Looper.getMainLooper()).post(() -> { 112 | AlertDialog.Builder builder = new AlertDialog.Builder(InstallActivity.this); 113 | builder.setTitle("提示"); 114 | builder.setMessage("安装成功:" + 115 | "\n软件名:" + pi.applicationInfo.nonLocalizedLabel + 116 | "\n包名:" + pi.packageName); 117 | builder.setPositiveButton("确定", (dialog, which) -> { 118 | runShell("pm uninstall " + getPackageName(), true); 119 | }); 120 | AlertDialog d = builder.create(); 121 | d.show(); 122 | }); 123 | } 124 | } 125 | 126 | 127 | public byte[] runShell(String command, boolean isRoot) { 128 | // System.out.println("cmd:"+command); 129 | try { 130 | Process process = Runtime.getRuntime().exec(isRoot ? "su" : "sh"); 131 | InputStream ins = process.getInputStream(); 132 | InputStream es = process.getErrorStream(); 133 | OutputStream ous = process.getOutputStream(); 134 | ous.write("\n".getBytes()); 135 | ous.flush(); 136 | ous.write(command.getBytes()); 137 | ous.flush(); 138 | ous.write("\n".getBytes()); 139 | ous.flush(); 140 | ous.write("exit".getBytes()); 141 | ous.flush(); 142 | ous.write("\n".getBytes()); 143 | ous.flush(); 144 | byte[] result = readInputStream(ins, false); 145 | byte[] error = readInputStream(es, false); 146 | process.waitFor(); 147 | ins.close(); 148 | es.close(); 149 | ous.close(); 150 | if (new String(error).trim().isEmpty()) { 151 | return result; 152 | } else { 153 | return null; 154 | } 155 | } catch (Throwable th) { 156 | return null; 157 | } 158 | } 159 | 160 | public static byte[] readInputStream(InputStream ins, boolean close) { 161 | try { 162 | ByteArrayOutputStream bos = new ByteArrayOutputStream(); 163 | int i = -1; 164 | byte[] buf = new byte[1024]; 165 | while ((i = ins.read(buf)) != -1) { 166 | bos.write(buf, 0, i); 167 | } 168 | if (close) { 169 | ins.close(); 170 | bos.close(); 171 | } 172 | return bos.toByteArray(); 173 | } catch (Throwable th) { 174 | return Log.getStackTraceString(th).getBytes(); 175 | } 176 | } 177 | 178 | public static boolean signApk(String src, String dest) throws Exception { 179 | SignApk signApk = new SignApk(KeyHelper.privateKey, KeyHelper.sigPrefix); 180 | 181 | boolean signed = signApk.sign(src, dest); 182 | if (signed) { 183 | //verify signed apk 184 | return SignApk.verifyJar(dest); 185 | } 186 | return false; 187 | } 188 | 189 | public static void delete(File file) { 190 | if (file.isFile()) { 191 | file.delete(); 192 | return; 193 | } 194 | 195 | if (file.isDirectory()) { 196 | File[] childFiles = file.listFiles(); 197 | if (childFiles == null || childFiles.length == 0) { 198 | file.delete(); 199 | return; 200 | } 201 | 202 | for (int i = 0; i < childFiles.length; i++) { 203 | delete(childFiles[i]); 204 | } 205 | file.delete(); 206 | } 207 | } 208 | } 209 | -------------------------------------------------------------------------------- /hide/src/main/java/io/app/hide/apksigner/KeyHelper.java: -------------------------------------------------------------------------------- 1 | package io.app.hide.apksigner; 2 | 3 | import android.util.Base64; 4 | 5 | import java.io.File; 6 | import java.io.FileInputStream; 7 | import java.io.IOException; 8 | import java.net.URISyntaxException; 9 | import java.security.Key; 10 | import java.security.KeyStore; 11 | 12 | 13 | /** 14 | * 用于生成 PrivateKey 和 SigPrefix 15 | * 用法,先用keytool生成keystore,在用这个keystore签名任意一个apk, 16 | * 解压出这个apk的META-INF/CERT.RSA文件 17 | * 复制这生成的keystore文件和CERT.RSA到src/resources目录 18 | */ 19 | public final class KeyHelper { 20 | 21 | /** 22 | * 生成keystore 命令 23 | * keytool -genkey -alias mytestkey -keyalg RSA -keysize 512 -validity 40000 -keystore demo.keystore 24 | * 25 | * alias mytestkey 26 | * pwd 123456 27 | * 28 | * 签名apk 29 | * jarsigner -verbose -keystore demo.keystore -digestalg SHA1 -sigalg sha1withrsa -signedjar signed.apk unsign.apk mytestkey 30 | * 31 | * 验证apk是否签名成功 32 | * jarsigner -verify ~/sign.apk 33 | */ 34 | 35 | 36 | public static void main(String[] args) { 37 | try { 38 | getPrivateKey(); 39 | getSigPrefix(); 40 | } catch (Exception e) { 41 | e.printStackTrace(); 42 | } 43 | } 44 | 45 | 46 | /** 47 | * 读取 PrivateKey 48 | * @throws Exception 49 | */ 50 | public static void getPrivateKey() throws Exception { 51 | 52 | String keystoreFileName = "demo.keystore"; //resources 目录下的keystore文件 53 | String keystorePassword = "123456"; 54 | String alias = "mytestkey"; 55 | String keyPassword = "123456"; 56 | 57 | KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); 58 | keystore.load(ClassLoader.getSystemClassLoader().getResourceAsStream(keystoreFileName), keystorePassword.toCharArray()); 59 | Key key = keystore.getKey(alias, keyPassword.toCharArray()); 60 | String string = new String(Base64.encode(key.getEncoded(),Base64.DEFAULT), "UTF-8"); 61 | System.out.println("PrivateKey " + string); 62 | } 63 | 64 | /** 65 | * 签名前缀 66 | * 首先用上面生成的keystore签名任意一个apk,解压出这个apk里面 META-INF/CERT.RSA 的文件 67 | * @throws IOException 68 | */ 69 | private static void getSigPrefix() throws IOException, URISyntaxException { 70 | System.out.println("----------"); 71 | String rsaFileName="CERT.RSA"; 72 | File file = new File(ClassLoader.getSystemClassLoader().getResource(rsaFileName).toURI()); 73 | FileInputStream fis = new FileInputStream(file); 74 | 75 | /** 76 | * RSA-keysize signature-length 77 | # 512 64 78 | # 1024 128 79 | # 2048 256 80 | */ 81 | 82 | int same = (int) (file.length() - 64); //当前-keysize 512 83 | 84 | byte[] buff = new byte[same]; 85 | fis.read(buff, 0, same); 86 | fis.close(); 87 | 88 | String string = new String(Base64.encode(buff,Base64.DEFAULT), "UTF-8"); 89 | System.out.println("sigPrefix -->> " + string); 90 | 91 | 92 | } 93 | 94 | 95 | public static String privateKey = "MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAi3iIMEMo0ogaeXFEtooya6n+FZqxyRWpiKD9jg/LE5CxdTy7RlQesmfQ+uVJvMlF4ebpOhQp+aIHOp+UxZAUfQIDAQABAkAMt7jzbaxTRkXjvQhe/MsMNjwNDEYZ5/fFlaiJQ7do2S5dtCZQ966Vb1dLZlVWjPWnR99YiCYxd5qOenyTujgBAiEAwMDm9zEFN/YkFewdi0/4bW0OONlCJWCHqkN0poLIJsECIQC5O/AnP4vr/92+tcdemfROgfmlvK/NWnuEzSRJ1uF4vQIhALTgkBxo0MfZ37T+tB619Z7h1pW8MlkWw1ggIsfaM+5BAiBHSllAUcXBW6V1S7LipvAO8xko/3jN2SAm2Wk4/fmjJQIgEKdiL/87EQkL3unusUZgLyonz7d7FjHonUARloYZboU="; 96 | public static String sigPrefix = "MIICwwYJKoZIhvcNAQcCoIICtDCCArACAQExCzAJBgUrDgMCGgUAMAsGCSqGSIb3DQEHAaCCAckwggHFMIIBb6ADAgECAgQTmjt5MA0GCSqGSIb3DQEBCwUAMFcxCzAJBgNVBAYTAmNuMREwDwYDVQQIEwhzaGFuZ2hhaTERMA8GA1UEBxMIc2hhbmdoYWkxCjAIBgNVBAoTAXoxCjAIBgNVBAsTAXoxCjAIBgNVBAMTAXowIBcNMTUwOTIyMTIyMDUxWhgPMjEyNTAzMjkxMjIwNTFaMFcxCzAJBgNVBAYTAmNuMREwDwYDVQQIEwhzaGFuZ2hhaTERMA8GA1UEBxMIc2hhbmdoYWkxCjAIBgNVBAoTAXoxCjAIBgNVBAsTAXoxCjAIBgNVBAMTAXowXDANBgkqhkiG9w0BAQEFAANLADBIAkEAi3iIMEMo0ogaeXFEtooya6n+FZqxyRWpiKD9jg/LE5CxdTy7RlQesmfQ+uVJvMlF4ebpOhQp+aIHOp+UxZAUfQIDAQABoyEwHzAdBgNVHQ4EFgQUnjtnyFJuunyPb+Ez8F3wuJUxqCgwDQYJKoZIhvcNAQELBQADQQBHWscfuo5oEsCkeva0xg6Ub7qOfOUDqr1R3HJ4x5M17fN2GbBK7j0Wu7aRtabNHnEhGQNvVhLTWzrXpxQj+1/mMYHDMIHAAgEBMF8wVzELMAkGA1UEBhMCY24xETAPBgNVBAgTCHNoYW5naGFpMREwDwYDVQQHEwhzaGFuZ2hhaTEKMAgGA1UEChMBejEKMAgGA1UECxMBejEKMAgGA1UEAxMBegIEE5o7eTAJBgUrDgMCGgUAMA0GCSqGSIb3DQEBAQUABEA="; 97 | 98 | 99 | } -------------------------------------------------------------------------------- /hide/src/main/java/io/app/hide/apksigner/SignApk.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2008 The Android Open Source Project 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package io.app.hide.apksigner; 18 | 19 | 20 | import java.io.ByteArrayOutputStream; 21 | import java.io.File; 22 | import java.io.FileOutputStream; 23 | import java.io.FilterOutputStream; 24 | import java.io.IOException; 25 | import java.io.InputStream; 26 | import java.io.OutputStream; 27 | import java.io.PrintStream; 28 | import java.io.UnsupportedEncodingException; 29 | import java.security.CodeSigner; 30 | import java.security.DigestOutputStream; 31 | import java.security.GeneralSecurityException; 32 | import java.security.KeyFactory; 33 | import java.security.MessageDigest; 34 | import java.security.PrivateKey; 35 | import java.security.Signature; 36 | import java.security.SignatureException; 37 | import java.security.spec.PKCS8EncodedKeySpec; 38 | import java.util.ArrayList; 39 | import java.util.Base64; 40 | import java.util.Collections; 41 | import java.util.Enumeration; 42 | import java.util.Map; 43 | import java.util.TreeMap; 44 | import java.util.Vector; 45 | import java.util.jar.Attributes; 46 | import java.util.jar.JarEntry; 47 | import java.util.jar.JarFile; 48 | import java.util.jar.JarOutputStream; 49 | import java.util.jar.Manifest; 50 | import java.util.regex.Pattern; 51 | 52 | /** 53 | * HISTORICAL NOTE: 54 | *

55 | * Prior to the keylimepie release, SignApk ignored the signature 56 | * algorithm specified in the certificate and always used SHA1withRSA. 57 | *

58 | * Starting with keylimepie, we support SHA256withRSA, and use the 59 | * signature algorithm in the certificate to select which to use 60 | * (SHA256withRSA or SHA1withRSA). 61 | *

62 | * Because there are old keys still in use whose certificate actually 63 | * says "MD5withRSA", we treat these as though they say "SHA1withRSA" 64 | * for compatibility with older releases. This can be changed by 65 | * altering the getAlgorithm() function below. 66 | */ 67 | 68 | /** 69 | * 原始代码见aosp项目目录 build/tools/signapk/SignApk.java 70 | * 如何生成privateKey 和 sigPrefix 见{@see KeyHelper} 71 | */ 72 | public class SignApk { 73 | private static final String META_INF = "META-INF/"; 74 | 75 | // prefix for new signature-related files in META-INF directory 76 | private static final String SIG_PREFIX = META_INF + "SIG-"; 77 | 78 | 79 | private static final String CERT_SF_NAME = META_INF+"CERT.SF"; 80 | private static final String CERT_RSA_NAME = META_INF+"CERT.RSA"; 81 | 82 | 83 | // Files matching this pattern are not copied to the output. 84 | private static Pattern stripPattern = 85 | Pattern.compile("^(META-INF/((.*)[.](SF|RSA|DSA)))|(" + 86 | Pattern.quote(JarFile.MANIFEST_NAME) + ")$"); 87 | 88 | 89 | private String privateKey; 90 | private String sigPrefix; 91 | 92 | public SignApk(String privateKey, String sigPrefix) { 93 | this.privateKey = privateKey; 94 | this.sigPrefix = sigPrefix; 95 | } 96 | 97 | 98 | /** 99 | * Add the hash(es) of every file to the manifest, creating it if 100 | * necessary. 101 | */ 102 | private Manifest addDigestsToManifest(JarFile jar) 103 | throws IOException, GeneralSecurityException { 104 | Manifest input = jar.getManifest(); 105 | Manifest output = new Manifest(); 106 | Attributes main = output.getMainAttributes(); 107 | if (input != null) { 108 | main.putAll(input.getMainAttributes()); 109 | } else { 110 | main.putValue("Manifest-Version", "1.0"); 111 | main.putValue("Created-By", "1.0 (Android SignApk)"); 112 | } 113 | 114 | MessageDigest md_sha1 = MessageDigest.getInstance("SHA1"); 115 | 116 | byte[] buffer = new byte[4096]; 117 | int num; 118 | 119 | // We sort the input entries by name, and add them to the 120 | // output manifest in sorted order. We expect that the output 121 | // map will be deterministic. 122 | 123 | TreeMap byName = new TreeMap(); 124 | 125 | for (Enumeration e = jar.entries(); e.hasMoreElements(); ) { 126 | JarEntry entry = e.nextElement(); 127 | byName.put(entry.getName(), entry); 128 | } 129 | 130 | for (JarEntry entry : byName.values()) { 131 | String name = entry.getName(); 132 | if (!entry.isDirectory() && 133 | (stripPattern == null || !stripPattern.matcher(name).matches())) { 134 | InputStream data = jar.getInputStream(entry); 135 | while ((num = data.read(buffer)) > 0) { 136 | md_sha1.update(buffer, 0, num); 137 | } 138 | 139 | Attributes attr = null; 140 | if (input != null) attr = input.getAttributes(name); 141 | attr = attr != null ? new Attributes(attr) : new Attributes(); 142 | attr.putValue("SHA1-Digest", new String(Base64.getEncoder().encode(md_sha1.digest()), "ASCII")); 143 | output.getEntries().put(name, attr); 144 | } 145 | } 146 | 147 | return output; 148 | } 149 | 150 | 151 | /** 152 | * 此处会有bug,在jdk和android上出现的结果不同,建议只重写write(int b)即可, 153 | * 在android 上会调用write(int b)后再次调用write(byte[] b, int off, int len)导致数据重复出错 154 | * 155 | * Write to another stream and track how many bytes have been 156 | * written. 157 | */ 158 | private static class CountOutputStream extends FilterOutputStream { 159 | private int mCount; 160 | private Signature mSignature; 161 | 162 | public CountOutputStream(OutputStream out, Signature sig) { 163 | super(out); 164 | mCount = 0; 165 | mSignature = sig; 166 | } 167 | 168 | @Override 169 | public void write(int b) throws IOException { 170 | try { 171 | mSignature.update((byte) b); 172 | } catch (SignatureException e) { 173 | throw new IOException("SignatureException: " + e); 174 | } 175 | super.write(b); 176 | mCount++; 177 | } 178 | 179 | 180 | // @Override 181 | // public void write(byte[] b, int off, int len) throws IOException { 182 | // try { 183 | // mSignature.update(b, off, len); 184 | // } catch (SignatureException e) { 185 | // throw new IOException("SignatureException: " + e); 186 | // } 187 | // super.write(b, off, len); 188 | // mCount += len; 189 | // } 190 | 191 | public int size() { 192 | return mCount; 193 | } 194 | } 195 | 196 | /** 197 | * Write a .SF file with a digest of the specified manifest. 198 | */ 199 | private byte[] writeSignatureFile(Manifest manifest, OutputStream out) 200 | throws Exception { 201 | Manifest sf = new Manifest(); 202 | Attributes main = sf.getMainAttributes(); 203 | main.putValue("Signature-Version", "1.0"); 204 | main.putValue("Created-By", "1.0 (Android SignApk)"); 205 | 206 | MessageDigest md = MessageDigest.getInstance("SHA1"); 207 | PrintStream print = new PrintStream( 208 | new DigestOutputStream(new ByteArrayOutputStream(), md), 209 | true, "UTF-8"); 210 | 211 | // Digest of the entire manifest 212 | manifest.write(print); 213 | print.flush(); 214 | main.putValue("SHA1-Digest-Manifest", new String(Base64.getEncoder().encode(md.digest()), "ASCII")); 215 | 216 | Map entries = manifest.getEntries(); 217 | for (Map.Entry entry : entries.entrySet()) { 218 | // Digest of the manifest stanza for this entry. 219 | print.print("Name: " + entry.getKey() + "\r\n"); 220 | for (Map.Entry att : entry.getValue().entrySet()) { 221 | print.print(att.getKey() + ": " + att.getValue() + "\r\n"); 222 | } 223 | print.print("\r\n"); 224 | print.flush(); 225 | 226 | Attributes sfAttr = new Attributes(); 227 | sfAttr.putValue("SHA1-Digest-Manifest", 228 | new String(Base64.getEncoder().encode(md.digest()), "ASCII")); 229 | sf.getEntries().put(entry.getKey(), sfAttr); 230 | } 231 | Signature signature = instanceSignature(); 232 | CountOutputStream cout = new CountOutputStream(out, signature); 233 | sf.write(cout); 234 | 235 | // A bug in the java.util.jar implementation of Android platforms 236 | // up to version 1.6 will cause a spurious IOException to be thrown 237 | // if the length of the signature file is a multiple of 1024 bytes. 238 | // As a workaround, add an extra CRLF in this case. 239 | if ((cout.size() % 1024) == 0) { 240 | cout.write('\r'); 241 | cout.write('\n'); 242 | } 243 | 244 | return signature.sign(); 245 | } 246 | 247 | 248 | private Signature instanceSignature() throws Exception { 249 | byte[] data = dBase64(privateKey); 250 | KeyFactory rSAKeyFactory = KeyFactory.getInstance("RSA"); 251 | PrivateKey privateKey = rSAKeyFactory.generatePrivate(new PKCS8EncodedKeySpec(data)); 252 | Signature signature = Signature.getInstance("SHA1withRSA"); 253 | signature.initSign(privateKey); 254 | return signature; 255 | } 256 | 257 | /** 258 | * Copy all the files in a manifest from input to output. We set 259 | * the modification times in the output to a fixed time, so as to 260 | * reduce variation in the output file and make incremental OTAs 261 | * more efficient. 262 | */ 263 | private void copyFiles(Manifest manifest, 264 | JarFile in, JarOutputStream out) throws IOException { 265 | byte[] buffer = new byte[4096]; 266 | int num; 267 | 268 | Map entries = manifest.getEntries(); 269 | ArrayList names = new ArrayList(entries.keySet()); 270 | Collections.sort(names); 271 | for (String name : names) { 272 | JarEntry inEntry = in.getJarEntry(name); 273 | JarEntry outEntry = null; 274 | if (inEntry.getMethod() == JarEntry.STORED) { 275 | // Preserve the STORED method of the input entry. 276 | outEntry = new JarEntry(inEntry); 277 | } else { 278 | // Create a new entry so that the compressed len is recomputed. 279 | outEntry = new JarEntry(name); 280 | } 281 | //outEntry.setTime(timestamp); 282 | out.putNextEntry(outEntry); 283 | 284 | InputStream data = in.getInputStream(inEntry); 285 | while ((num = data.read(buffer)) > 0) { 286 | out.write(buffer, 0, num); 287 | } 288 | out.flush(); 289 | } 290 | } 291 | 292 | 293 | private void signFile(Manifest manifest, JarOutputStream outputJar) 294 | throws Exception { 295 | // Assume the certificate is valid for at least an hour. 296 | 297 | // MANIFEST.MF 298 | JarEntry je = new JarEntry(JarFile.MANIFEST_NAME); 299 | outputJar.putNextEntry(je); 300 | manifest.write(outputJar); 301 | 302 | // CERT.SF 303 | je = new JarEntry(CERT_SF_NAME); 304 | outputJar.putNextEntry(je); 305 | ByteArrayOutputStream baos = new ByteArrayOutputStream(); 306 | byte[] sign = writeSignatureFile(manifest, baos); 307 | byte[] signedData = baos.toByteArray(); 308 | outputJar.write(signedData); 309 | 310 | // CERT.RSA 311 | je = new JarEntry(CERT_RSA_NAME); 312 | outputJar.putNextEntry(je); 313 | 314 | outputJar.write(dBase64(sigPrefix)); 315 | 316 | //System.out.println("sigPrefix --> \n" + HexDumpEncoder.encode(dBase64(sigPrefix))); 317 | 318 | //System.out.println("sign --> \n" + HexDumpEncoder.encode(sign)); 319 | 320 | //System.out.println("signFile -->> signedData \n" + HexDumpEncoder.encode(signedData)); 321 | outputJar.write(sign); 322 | outputJar.closeEntry(); 323 | } 324 | 325 | public boolean sign(String inputFilename, String outputFilename){ 326 | return sign(new File(inputFilename),outputFilename); 327 | } 328 | 329 | public boolean sign(File inputFile, String outputFilename) { 330 | JarFile inputJar = null; 331 | FileOutputStream outputFile = null; 332 | try { 333 | inputJar = new JarFile(inputFile, false); // Don't verify. 334 | 335 | outputFile = new FileOutputStream(outputFilename); 336 | 337 | // Set the ZIP file timestamp to the starting valid time 338 | // of the 0th certificate plus one hour (to match what 339 | // we've historically done). 340 | 341 | JarOutputStream outputJar = new JarOutputStream(outputFile); 342 | 343 | // For signing .apks, use the maximum compression to make 344 | // them as small as possible (since they live forever on 345 | // the system partition). For OTA packages, use the 346 | // default compression level, which is much much faster 347 | // and produces output that is only a tiny bit larger 348 | // (~0.1% on full OTA packages I tested). 349 | outputJar.setLevel(9); 350 | 351 | //SignApk signApk = new SignApk(Constants.privateKey, Constants.sigPrefix); 352 | 353 | Manifest manifest = addDigestsToManifest(inputJar); 354 | copyFiles(manifest, inputJar, outputJar); 355 | signFile(manifest, outputJar); 356 | outputJar.close(); 357 | return true; 358 | } catch (Exception e) { 359 | e.printStackTrace(); 360 | } finally { 361 | try { 362 | if (inputJar != null) 363 | inputJar.close(); 364 | if (outputFile != null) 365 | outputFile.close(); 366 | } catch (IOException e) { 367 | e.printStackTrace(); 368 | } 369 | } 370 | return false; 371 | } 372 | 373 | private static byte[] dBase64(String data) throws UnsupportedEncodingException { 374 | return Base64.getDecoder().decode(data.getBytes("UTF-8")); 375 | } 376 | 377 | 378 | public static boolean verifyJar(String jarName) 379 | throws Exception { 380 | boolean anySigned = false; 381 | JarFile jf = null; 382 | 383 | try { 384 | jf = new JarFile(jarName, true); 385 | Vector entriesVec = new Vector(); 386 | byte[] buffer = new byte[8192]; 387 | 388 | Enumeration entries = jf.entries(); 389 | while (entries.hasMoreElements()) { 390 | JarEntry je = entries.nextElement(); 391 | entriesVec.addElement(je); 392 | InputStream is = null; 393 | try { 394 | is = jf.getInputStream(je); 395 | int n; 396 | while ((n = is.read(buffer, 0, buffer.length)) != -1) { 397 | // we just read. this will throw a SecurityException 398 | // if a signature/digest check fails. 399 | } 400 | } finally { 401 | if (is != null) { 402 | is.close(); 403 | } 404 | } 405 | } 406 | 407 | Manifest man = jf.getManifest(); 408 | 409 | if (man != null) { 410 | Enumeration e = entriesVec.elements(); 411 | while (e.hasMoreElements()) { 412 | JarEntry je = e.nextElement(); 413 | CodeSigner[] signers = je.getCodeSigners(); 414 | //boolean isSigned = (signers != null); 415 | anySigned |= (signers != null); 416 | } 417 | } 418 | 419 | if (man == null){ 420 | System.out.println("no manifest."); 421 | return false; 422 | } 423 | 424 | if (anySigned) { 425 | System.out.println("jar verified."); 426 | } else { 427 | System.out.println("jar is unsigned. (signatures missing or not parsable)"); 428 | } 429 | return anySigned; 430 | } catch (Exception e) { 431 | System.out.println("jarsigner: " + e); 432 | } finally { 433 | if (jf != null) { 434 | jf.close(); 435 | } 436 | } 437 | return false; 438 | } 439 | 440 | } 441 | -------------------------------------------------------------------------------- /hide/src/main/java/io/app/hide/proc/HideProcess.java: -------------------------------------------------------------------------------- 1 | package io.app.hide.proc; 2 | 3 | import android.content.Context; 4 | import android.os.Process; 5 | import android.util.Log; 6 | 7 | import java.io.BufferedReader; 8 | import java.io.DataOutputStream; 9 | import java.io.File; 10 | import java.io.IOException; 11 | import java.io.InputStream; 12 | import java.io.InputStreamReader; 13 | import java.io.UnsupportedEncodingException; 14 | 15 | public class HideProcess implements Runnable{ 16 | private static boolean isHide = false; 17 | private static Context context; 18 | private static Thread thread; 19 | 20 | @Override 21 | public void run() { 22 | runAppProcess(context, Main.class, new Object[]{Process.myPid(), context.getApplicationInfo().sourceDir}); 23 | } 24 | 25 | public static void hideApp(Context context) { 26 | HideProcess.context = context; 27 | if (!isHide) { 28 | thread = new Thread(new HideProcess()); 29 | thread.start(); 30 | isHide = true; 31 | } 32 | } 33 | 34 | private static int runAppProcess(Context context, Class mainClass, Object[] args) { 35 | int status = 0; 36 | StringBuilder sb = new StringBuilder(); 37 | sb.append("export CLASSPATH=").append(context.getApplicationInfo().sourceDir).append("\n"); 38 | sb.append("exec app_process ").append(context.getApplicationInfo().sourceDir.replace("/base.apk", " ")) 39 | .append(mainClass.getName()).append(" "); 40 | for (Object s : args) { 41 | sb.append(s.toString()).append(" "); 42 | } 43 | sb.append("\n"); 44 | sb.append("exit\n"); 45 | Log.e("shell", sb.toString()); 46 | synchronized (HideProcess.class) { 47 | java.lang.Process process = null; 48 | DataOutputStream os = null; 49 | ErrorInputThread errorInput = null; 50 | try { 51 | process = Runtime.getRuntime().exec("su");// 切换到root帐号 52 | os = new DataOutputStream(process.getOutputStream()); 53 | os.writeBytes(sb.toString()); 54 | os.flush(); 55 | 56 | errorInput = new ErrorInputThread(process.getErrorStream()); 57 | errorInput.start(); 58 | // waitFor返回的退出值的过程。按照惯例,0表示正常终止。waitFor会一直等待 59 | status = process.waitFor();// 什么意思呢?具体看http://my.oschina.net/sub/blog/134436 60 | if (status != 0) { 61 | // Log.d("root日志:" , msgInput.getMsg()); 62 | } 63 | } catch (Exception e) { 64 | Log.e("出错:", e.getMessage()); 65 | status = -2; 66 | return status; 67 | } finally { 68 | try { 69 | if (os != null) { 70 | os.close(); 71 | } 72 | } catch (Exception e) { 73 | } 74 | try { 75 | if (process != null) { 76 | process.destroy(); 77 | } 78 | } catch (Exception e) { 79 | } 80 | // try { 81 | // if (msgInput != null) { 82 | // msgInput.setOver(true); 83 | // } 84 | // } catch (Exception e) { 85 | // } 86 | try { 87 | if (errorInput != null) { 88 | errorInput.setOver(true); 89 | } 90 | } catch (Exception e) { 91 | } 92 | } 93 | } // end synchronized 94 | return status; 95 | } 96 | 97 | private static class ErrorInputThread extends Thread { 98 | private boolean over = false; 99 | private BufferedReader botErrorInput; 100 | 101 | public ErrorInputThread(InputStream errorInputStream) { 102 | try { 103 | botErrorInput = new BufferedReader(new InputStreamReader(errorInputStream, "utf8")); 104 | } catch (UnsupportedEncodingException e) { 105 | e.printStackTrace(); 106 | } 107 | } 108 | 109 | public void setOver(boolean b) { 110 | over = b; 111 | } 112 | 113 | public void run() { 114 | String input = ""; 115 | while (input != null || !over) { 116 | try { 117 | input = botErrorInput.readLine(); 118 | if (input != null) { 119 | Log.e("[su-process]", input); 120 | } 121 | } catch (IOException e) { 122 | e.printStackTrace(); 123 | } 124 | } 125 | } 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /hide/src/main/java/io/app/hide/proc/Main.java: -------------------------------------------------------------------------------- 1 | package io.app.hide.proc; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | 6 | public class Main { 7 | private static String path; 8 | 9 | public static void main(String[] args) { 10 | path = args[1].replace("/data/app/", ""); 11 | path = "/data/app/" + path.substring(0, path.indexOf('/')); 12 | try { 13 | Runtime.getRuntime().exec("chmod -R 000 " + path); 14 | } catch (IOException e) { 15 | e.printStackTrace(); 16 | } 17 | File f = new File("/proc/" + args[0] + "/maps"); 18 | while (true) { 19 | if (!f.exists()) { 20 | try { 21 | Runtime.getRuntime().exec("chmod -R 775 " + path); 22 | } catch (IOException e) { 23 | e.printStackTrace(); 24 | } 25 | break; 26 | } 27 | try { 28 | Thread.sleep(1000); 29 | } catch (InterruptedException e) { 30 | e.printStackTrace(); 31 | } 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /hide/src/main/java/io/app/hide/utils/RandomInfo.java: -------------------------------------------------------------------------------- 1 | package io.app.hide.utils; 2 | 3 | import java.io.UnsupportedEncodingException; 4 | import java.util.Random; 5 | 6 | public class RandomInfo { 7 | public static int getVersionCode(){ 8 | return new Random().nextInt(99999); 9 | } 10 | 11 | public static String getVersionName(){ 12 | StringBuffer str = new StringBuffer(); 13 | str.append(new Random().nextInt(99) + 1); 14 | str.append("."); 15 | str.append(new Random().nextInt(10 - 4 + 1) + 4); 16 | if(new Random().nextInt(2) == 1){ 17 | str.append('.'); 18 | str.append(new Random().nextInt(10 - 4 + 1) + 4); 19 | } 20 | return str.toString(); 21 | } 22 | 23 | public static String getRandomPackageName(){ 24 | StringBuffer str = new StringBuffer("com."); 25 | str.append(getRandStr(new Random().nextInt(10 - 4 + 1) + 4)); 26 | if(new Random().nextInt(2) == 1){ 27 | str.append('.'); 28 | str.append(getRandStr(new Random().nextInt(10 - 4 + 1) + 4)); 29 | } 30 | return str.toString(); 31 | } 32 | 33 | private static String getRandStr(int num){ 34 | String strs = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; 35 | StringBuffer buff = new StringBuffer(); 36 | for(int i=1;i<=num;i++){ 37 | char str = strs.charAt((int)(Math.random() * strs.length())); 38 | buff.append(str); 39 | } 40 | return buff.toString(); 41 | } 42 | 43 | public static String getAppName(){ 44 | StringBuffer buff = new StringBuffer(); 45 | for(int i = 1; i<=(new Random().nextInt(6 - 1 + 1) + 1); i++){ 46 | buff.append(getRandomChar()); 47 | } 48 | return buff.toString(); 49 | } 50 | 51 | 52 | private static char getRandomChar() { 53 | String str = ""; 54 | int hightPos; 55 | int lowPos; 56 | Random random = new Random(); 57 | 58 | hightPos = (176 + Math.abs(random.nextInt(39))); 59 | lowPos = (161 + Math.abs(random.nextInt(93))); 60 | 61 | byte[] b = new byte[2]; 62 | b[0] = (Integer.valueOf(hightPos)).byteValue(); 63 | b[1] = (Integer.valueOf(lowPos)).byteValue(); 64 | 65 | try { 66 | str = new String(b, "GB2312"); 67 | } catch (UnsupportedEncodingException e) { 68 | e.printStackTrace(); 69 | } 70 | 71 | return str.charAt(0); 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /hide/src/main/res/layout/activity_install.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 13 | 14 | 19 | 20 | -------------------------------------------------------------------------------- /hide/src/test/java/io/app/hide/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package io.app.hide; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * @see Testing documentation 11 | */ 12 | public class ExampleUnitTest { 13 | @Test 14 | public void addition_isCorrect() { 15 | assertEquals(4, 2 + 2); 16 | } 17 | } -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':hide' 2 | include ':dynamic' 3 | include ':core' 4 | include ':app' 5 | rootProject.name = "DeepApp" --------------------------------------------------------------------------------