市面上實現這種方案最先的應用應該是"黑閾",咱們在使用的時候須要開啓調試模式,而後經過adb或者注入器注入主服務,纔可使用後臺管制以及其餘高級權限的功能。因此本方案也是基於這種注入服務的方式,來實現各類須要高級權限的功能java
這種方案的關鍵點是這個擁有shell級權限的服務,Android提供了app_process指令供咱們啓動一個進程,咱們能夠經過該指令起一個Java服務,若是是經過shell執行的,該服務會從/system/bin/sh
fork出來,而且擁有shell級權限android
這裏我寫了一個service.dex服務來測試一下,並經過shell啓動它git
// 先將service.dex push至Android設備
adb push service.dex /data/local/tmp/
// 而後經過app_process啓動,並指定一個名詞
adb shell nohup app_process -Djava.class.path=/data/local/tmp/server.dex /system/bin --nice-name=club.syachiku.hackrootservice shellService.Main
複製代碼
而後再看看該服務的信息github
// 列出全部正在運行的服務
adb shell ps
// 找到服務名爲club.syachiku.hackrootservice的服務
shell 24154 1 777484 26960 ffffffff b6e7284c S club.syachiku.hackrootservice
複製代碼
能夠看到該服務pid爲24154,ppid爲1,也說明該服務是從/system/bin/sh
fork出來的shell
// 查看該服務具體信息
adb shell cat /proc/24154/status
Name: main
State: S (sleeping)
Tgid: 24154
Pid: 24154
PPid: 1
TracerPid: 0
Uid: 2000 2000 2000 2000
Gid: 2000 2000 2000 2000
FDSize: 32
Groups: 1004 1007 1011 1015 1028 3001 3002 3003 3006
VmPeak: 777484 kB
VmSize: 777484 kB
VmLck: 0 kB
VmPin: 0 kB
VmHWM: 26960 kB
VmRSS: 26960 kB
VmData: 11680 kB
VmStk: 8192 kB
VmExe: 12 kB
VmLib: 52812 kB
VmPTE: 134 kB
VmSwap: 0 kB
Threads: 13
SigQ: 0/6947
SigPnd: 0000000000000000
ShdPnd: 0000000000000000
SigBlk: 0000000000001204
SigIgn: 0000000000000001
SigCgt: 00000002000094f8
CapInh: 0000000000000000
CapPrm: 0000000000000000
CapEff: 0000000000000000
CapBnd: 00000000000000c0
Seccomp: 0
Cpus_allowed: f
Cpus_allowed_list: 0-3
voluntary_ctxt_switches: 18
nonvoluntary_ctxt_switches: 76
複製代碼
能夠看到Uid,Gid爲2000,就是shell的Uidbash
分析了app_process的可行性,咱們能夠給出一個方案,經過app_process啓動一個socket服務,而後讓咱們的App與該服務通訊,來代理App作一些見不得人須要shell級權限的事情,好比靜默卸載,安裝,全局廣播等等併發
這裏咱們新建一個名爲hack-root的工程app
而後在代碼目錄下新建一個shellService包,新建一個Main入口類,咱們先輸出一些測試代碼,來測試是否執行成功socket
public class Main {
public static void main(String[] args) {
System.out.println("*****************hack server starting****************");
}
}
複製代碼
adb shell app_process -Djava.class.path=/sdcard/classes.dex /system/bin shellService.Main
複製代碼
Abort
應該是一些基本的路徑問題,稍做仔細檢查一下,成功執行後會看到咱們的打印的日誌運行測試沒問題了就開寫socket服務吧ide
public class Main {
public static void main(String[] args) {
// 利用looper讓線程循環
Looper.prepareMainLooper();
System.out.println("*****************hack server starting****************");
// 開一個子線程啓動服務
new Thread(new Runnable() {
@Override
public void run() {
new SocketService(new SocketService.SocketListener() {
@Override
public String onMessage(String msg) {
// 接收客戶端傳過來的消息
return resolveMsg(msg);
}
});
}
}).start();
Looper.loop();
}
private static String resolveMsg(String msg) {
// 執行客戶端傳過來的消息並返回執行結果
ShellUtil.ExecResult execResult =
ShellUtil.execute("pm uninstall " + msg);
return execResult.getMessage();
}
}
複製代碼
SocketServer
public class SocketService {
private final int PORT = 10500;
private SocketListener listener;
public SocketService(SocketListener listener) {
this.listener = listener;
try {
// 利用ServerSocket類啓動服務,而後指定一個端口
ServerSocket serverSocket = new ServerSocket(PORT);
System.out.println("server running " + PORT + " port");
ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(10);
// 新建一個線程池用來併發處理客戶端的消息
ThreadPoolExecutor executor = new ThreadPoolExecutor(
5,
10,
5000,
TimeUnit.MILLISECONDS,
queue
);
while (true) {
Socket socket = serverSocket.accept();
// 接收到新消息
executor.execute(new processMsg(socket));
}
} catch (Exception e) {
System.out.println("SocketServer create Exception:" + e);
}
}
class processMsg implements Runnable {
Socket socket;
public processMsg(Socket s) {
socket = s;
}
public void run() {
try {
// 經過流讀取內容
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line = bufferedReader.readLine();
System.out.println("server receive: " + line);
PrintWriter printWriter = new PrintWriter(socket.getOutputStream());
String repeat = listener.onMessage(line);
System.out.println("server send: " + repeat);
// 服務端返回給客戶端的消息
printWriter.print(repeat);
printWriter.flush();
printWriter.close();
bufferedReader.close();
socket.close();
} catch (IOException e) {
System.out.println("socket connection error:" + e.toString());
}
}
}
public interface SocketListener{
// 通話消息回調
String onMessage(String text);
}
}
複製代碼
ShellUtil
public class ShellUtil {
private static final String COMMAND_LINE_END = "\n";
private static final String COMMAND_EXIT = "exit\n";
// 單條指令
public static ExecResult execute(String command) {
return execute(new String[] {command});
}
// 多條指令重載方法
private static ExecResult execute(String[] commands) {
if (commands == null || commands.length == 0) {
return new ExecResult(false, "empty command");
}
int result = -1;
Process process = null;
DataOutputStream dataOutputStream = null;
BufferedReader sucResult = null, errResult = null;
StringBuilder sucMsg = null, errMsg = null;
try {
// 獲取shell級別的process
process = Runtime.getRuntime().exec("sh");
dataOutputStream = new DataOutputStream(process.getOutputStream());
for (String command : commands) {
if (command == null) continue;
System.out.println("execute command: " + command);
// 執行指令
dataOutputStream.write(command.getBytes());
dataOutputStream.writeBytes(COMMAND_LINE_END);
// 刷新
dataOutputStream.flush();
}
dataOutputStream.writeBytes(COMMAND_EXIT);
dataOutputStream.flush();
result = process.waitFor();
sucMsg = new StringBuilder();
errMsg = new StringBuilder();
sucResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
errResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
String s;
while ((s = sucResult.readLine()) != null) {
sucMsg.append(s);
}
while ((s = errResult.readLine()) != null) {
errMsg.append(s);
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
} finally {
try {
// 關閉資源,防止內存泄漏
assert dataOutputStream != null;
dataOutputStream.close();
assert sucResult != null;
sucResult.close();
assert errResult != null;
errResult.close();
} catch (IOException e) {
e.printStackTrace();
}
process.destroy();
}
ExecResult execResult;
if (result == 0) {
execResult = new ExecResult(true, sucMsg.toString());
} else {
execResult = new ExecResult(false, errMsg.toString());
}
// 返回執行結果
return execResult;
}
public static class ExecResult {
private boolean success;
private String message;
public ExecResult(boolean success, String message) {
this.success = success;
this.message = message;
}
public boolean getSuccess() {
return this.success;
}
public String getMessage() {
return this.message;
}
}
}
複製代碼
一個簡易的socket服務就搭建好了,能夠用來接收客戶端傳過來的指令而且執行而後返回結果
首先編寫一個socketClient
public class SocketClient {
private final String TAG = "HackRoot SocketClient";
private final int PORT = 10500;
private SocketListener listener;
private PrintWriter printWriter;
public SocketClient(final String cmd, SocketListener listener) {
this.listener = listener;
new Thread(new Runnable() {
@Override
public void run() {
Socket socket = new Socket();
try {
// 與hackserver創建鏈接
socket.connect(new InetSocketAddress("127.0.0.1", PORT), 3000);
socket.setSoTimeout(3000);
printWriter = new PrintWriter(socket.getOutputStream(), true);
Log.d(TAG, "client send: " + cmd);
// 發送指令
printWriter.println(cmd);
printWriter.flush();
// 讀取服務端返回
readServerData(socket);
} catch (IOException e) {
Log.d(TAG, "client send fail: " + e.getMessage());
e.printStackTrace();
}
}
}).start();
}
private void readServerData(final Socket socket) {
try {
InputStreamReader ipsReader = new InputStreamReader(socket.getInputStream());
BufferedReader bfReader = new BufferedReader(ipsReader);
String line = null;
while ((line = bfReader.readLine()) != null) {
Log.d(TAG, "client receive: " + line);
listener.onMessage(line);
}
// 釋放資源
ipsReader.close();
bfReader.close();
printWriter.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
interface SocketListener {
void onMessage(String msg);
}
}
複製代碼
而後UI組件相關的事件,咱們暫時只實現一個靜默卸載App的功能
public class MainActivity extends AppCompatActivity {
private TextView textView;
private ScrollView scrollView;
private EditText uninsTxtInput;
private Button btnUnins;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnUnins = findViewById(R.id.btn_uninstall);
uninsTxtInput = findViewById(R.id.pkg_input);
textView = findViewById(R.id.tv_output);
scrollView = findViewById(R.id.text_container);
btnUnins.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendMessage(uninsTxtInput.getText().toString());
}
});
}
private void sendMessage(String msg) {
new SocketClient(msg, new SocketClient.SocketListener() {
@Override
public void onMessage(String msg) {
showOnTextView(msg);
}
});
}
private void showOnTextView(final String msg) {
runOnUiThread(new Runnable() {
@Override
public void run() {
String baseText = textView.getText().toString();
if (baseText != null) {
textView.setText(baseText + "\n" + msg);
} else {
textView.setText(msg);
}
scrollView.smoothScrollTo(0, scrollView.getHeight());
}
});
}
}
複製代碼
佈局代碼
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/pkg_input"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:hint="input package name"
app:layout_constraintEnd_toStartOf="@+id/btn_uninstall"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btn_uninstall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginTop="8dp"
android:text="uninstall"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ScrollView
android:id="@+id/text_container"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:padding="10dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/pkg_input">
<TextView
android:id="@+id/tv_output"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</ScrollView>
</android.support.constraint.ConstraintLayout>
複製代碼
代碼相關的工做基本完工,一個簡單的,實現了靜默卸載Demo就完成了
/data/local/tmp/
// 拔掉數據線會終止服務
adb shell app_process -Djava.class.path=/data/local/tmp/classes.dex /system/bin shellService.Main
複製代碼
// 會一直運行除非手動kill pid或者重啓設備
adb shell nohup app_process -Djava.class.path=/data/local/tmp/classes.dex /system/bin --nice-name=${serviceName} shellService.Main
複製代碼
github.com/zjkhiyori/h… 歡迎fork || star
感謝下列開源做者