/**
* @Description: 防止被動態(tài)調(diào)試
* 防止惡意注入so文件
*/
public class DebuggerUtils {
/**
* 判斷當(dāng)前應(yīng)用是否是debug狀態(tài)
*/
public static boolean isDebuggable(Context context) {
try {
ApplicationInfo info = context.getApplicationInfo();
return (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
} catch (Exception e) {
return false;
}
}
/**
* 檢測是否在非Debug編譯模式下,進(jìn)行了調(diào)試操作,以防動態(tài)調(diào)試
*
* @param context
* @return
*/
public static void checkDebuggableInNotDebugModel(Context context) {
//非Debug 編譯,反調(diào)試檢測
// if (!BuildConfig.DEBUG) {
if (!BuildConfig.DEBUG) {
if (isDebuggable(context)) {
// ToastUtils.show("已被動態(tài)調(diào)試");
//進(jìn)程自殺
int myPid = android.os.Process.myPid();
Process.killProcess(myPid);
//異常退出虛擬機(jī)
System.exit(1);
}
Thread t = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
//每隔300ms檢測一次
Thread.sleep(300);
//判斷是否有調(diào)試器連接,是就退出
if (Debug.isDebuggerConnected()) {
//進(jìn)程自殺
int myPid = android.os.Process.myPid();
Process.killProcess(myPid);
//異常退出虛擬機(jī)
System.exit(1);
}
//判斷是否被其他進(jìn)程跟蹤,是就退出
if (isUnderTraced()) {
//進(jìn)程自殺
int myPid = android.os.Process.myPid();
Process.killProcess(myPid);
//異常退出虛擬機(jī)
System.exit(1);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}, "SafeGuardThread");
t.start();
}
if (isUnderTraced()) {
//進(jìn)程自殺
int myPid = android.os.Process.myPid();
Process.killProcess(myPid);
//異常退出虛擬機(jī)
System.exit(1);
}
}
/**
* 當(dāng)我們使用Ptrace方式跟蹤一個進(jìn)程時,目標(biāo)進(jìn)程會記錄自己被誰跟蹤,可以查看/proc/pid/status看到這個信息,而沒有被調(diào)試的時候TracerPid為0
*
* @return
*/
private static boolean isUnderTraced() {
String processStatusFilePath = String.format(Locale.US, "/proc/%d/status", android.os.Process.myPid());
File procInfoFile = new File(processStatusFilePath);
try {
BufferedReader b = new BufferedReader(new FileReader(procInfoFile));
String readLine;
while ((readLine = b.readLine()) != null) {
if (readLine.contains("TracerPid")) {
String[] arrays = readLine.split(":");
if (arrays.length == 2) {
int tracerPid = Integer.parseInt(arrays[1].trim());
if (tracerPid != 0) {
return true;
}
}
}
}
b.close();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
調(diào)用:
在application的onCreate方法中調(diào)用即可
@Override
public void onCreate() {
super.onCreate();
DebuggerUtils.checkDebuggableInNotDebugModel(getApplicationContext());
}