由于公司应用需要过安全测试,测试那边说有so注入漏洞;
废话不多说。直接上代码
package com.pactera.dongfeng.util; import android.content.Context; import android.content.pm.ApplicationInfo; import android.os.Debug; import com.hjq.toast.ToastUtils; import com.pactera.dongfeng.BuildConfig; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.Locale; /** * @Description: 防止被动态调试 * 防止恶意注入so文件 * @Author: 大魔王老杨 * @Date: 2020-10-27 10:20 */ public class DebuggerUtils { /** * 判断当前应用是否是debug状态 */ public static boolean isDebuggable(Context context) { try { ApplicationInfo info = context.getApplicationInfo(); return (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0; } catch (Exception e) { return false; } } /** * 检测是否在非Debug编译模式下,进行了调试操作,以防动态调试 * * @param context * @return */ public static void checkDebuggableInNotDebugModel(Context context) { //非Debug 编译,反调试检测 if (!BuildConfig.DEBUG) { if (isDebuggable(context)) { ToastUtils.show("已被动态调试"); AppUtil.INSTANCE.appExit(); } Thread t = new Thread(new Runnable() { @Override public void run() { while (true) { try { //每隔300ms检测一次 Thread.sleep(300); //判断是否有调试器连接,是就退出 if (Debug.isDebuggerConnected()) { ToastUtils.show("已被动态调试"); AppUtil.INSTANCE.appExit(); } //判断是否被其他进程跟踪,是就退出 if (isUnderTraced()) { ToastUtils.show("已被其他恶意进程跟踪"); AppUtil.INSTANCE.appExit(); } } catch (InterruptedException e) { e.printStackTrace(); } } } }, "SafeGuardThread"); t.start(); } if (isUnderTraced()) { ToastUtils.show("已被其他恶意进程跟踪"); AppUtil.INSTANCE.appExit(); } } /** * 当我们使用Ptrace方式跟踪一个进程时,目标进程会记录自己被谁跟踪,可以查看/proc/pid/status看到这个信息,而没有被调试的时候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; } }
在application的onCreate中调用即可;
DebuggerUtils.checkDebuggableInNotDebugModel(MyApp.getContext());
这个工具类解决了截图中 3、4的安全漏洞;