Android安全防护篇

目录

前言

随着技术的发展,APP的破解技术也越来越成熟,因此为了防止APP被破解我们可以进行一系列安全方面的检测和加固,让破解人员的破解成本增加,这样的话就可以在一定程度上防止APP被破解

代码实现

1.模拟器检测

大部分破解人员调试APP一般都是在模拟器上进行,因此首先我们先检测模拟器,这里为了伪造检测的方法,我把设置Activity布局的逻辑也加在了检测方法中,另外为了提升安全等级,我将检测的函数在NDK层实现,同时检测后的弹窗也在NDK层创建,这样可以很大程度误导破解人员,具体如下:
首先我们创建一个工具类,用于检测,我们需要传入布局文件和Activity对象,目的是为了在NDK层设置布局加以混淆视线

public class CheckUtil {
    static {
        System.loadLibrary("native-lib");
    }

    public native static void init(int layoutId, Activity activity);
}

然后我们创建BaseActivity,其子类需要实现getLayoutId()方法返回布局文件

public abstract class BaseActivity extends AppCompatActivity {
    @LayoutRes
    protected abstract int getLayoutId();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        CheckUtil.init(getLayoutId(),this);
    }
}

然后我们的逻辑大部分都是用C语言实现,这里大体逻辑为先判断是否在模拟器上运行,如果是的话就弹窗并且在弹窗关闭的监听事件中退出APP

#include <jni.h>
#include <string>
#include "android/log.h"
#define LOGE(...) ((void)__android_log_print(ANDROID_LOG_ERROR, "安全", __VA_ARGS__))
enum DialogType{
    EMULATOR,//模拟器
    JKSERROR,//签名错误
    WIFIPROXY,//WIFI代理
};

void showDialog(JNIEnv *env,DialogType dialogType,jobject activity){
    std::string messageText = "";
    switch (dialogType) {
        case DialogType::EMULATOR:
            messageText = "请不要在模拟器上运行";
            break;
        case DialogType::JKSERROR:
            messageText = "请使用正版应用";
            break;
        case DialogType::WIFIPROXY:
            messageText = "请不要使用网络代理";
            break;
    }

    //创建AlertDialog.Builder
    jclass builderClazz = env->FindClass("android/app/AlertDialog$Builder");
    jmethodID initMethodID = env->GetMethodID(builderClazz,"<init>","(Landroid/content/Context;)V");
    jobject builder = env->NewObject(builderClazz,initMethodID,activity);
    jmethodID setPositiveButtonMethodID = env->GetMethodID(builderClazz,"setPositiveButton","(Ljava/lang/CharSequence;Landroid/content/DialogInterface$OnClickListener;)Landroid/app/AlertDialog$Builder;");

    //设置确认按钮和点击事件
    jclass onClickClazz = env->FindClass("com/itfitness/safedemo/dialog/MDialogClickListener");
    jmethodID onClickInitMethodID = env->GetMethodID(onClickClazz,"<init>", "()V");
    jobject onClickListener = env->NewObject(onClickClazz,onClickInitMethodID);
    std::string buttonText = "确定";
    env->CallObjectMethod(builder,setPositiveButtonMethodID,env->NewStringUTF(buttonText.c_str()),onClickListener);

    //设置标题
    jmethodID setTitleMethodID = env->GetMethodID(builderClazz,"setTitle","(Ljava/lang/CharSequence;)Landroid/app/AlertDialog$Builder;");
    std::string titleText = "提示";
    env->CallObjectMethod(builder,setTitleMethodID,env->NewStringUTF(titleText.c_str()));

    //设置提示内容
    jmethodID setMessageMethodID = env->GetMethodID(builderClazz,"setMessage","(Ljava/lang/CharSequence;)Landroid/app/AlertDialog$Builder;");
    env->CallObjectMethod(builder,setMessageMethodID,env->NewStringUTF(messageText.c_str()));

    //显示弹窗
    jmethodID createMethodID = env->GetMethodID(builderClazz,"create",
                                                "()Landroid/app/AlertDialog;");
    jobject alertDialog = env->CallObjectMethod(builder,createMethodID);
    jclass alertDialogClazz = env->GetObjectClass(alertDialog);

    //设置Dialog关闭的监听
    jmethodID setOnDismissListenerMethodID = env->GetMethodID(alertDialogClazz,"setOnDismissListener",
                                                              "(Landroid/content/DialogInterface$OnDismissListener;)V");
    jclass onDismissListenerClazz = env->FindClass("com/itfitness/safedemo/dialog/DialogDismissListener");
    jmethodID onDismissListenerInitMethodID = env->GetMethodID(onDismissListenerClazz,"<init>", "()V");
    jobject onDismissListener = env->NewObject(onDismissListenerClazz,onDismissListenerInitMethodID);
    env->CallVoidMethod(alertDialog,setOnDismissListenerMethodID,onDismissListener);

    //显示
    jmethodID showMethodID = env->GetMethodID(alertDialogClazz,"show", "()V");
    env->CallVoidMethod(alertDialog,showMethodID);

}

extern "C"
JNIEXPORT void JNICALL
Java_com_itfitness_safedemo_utils_CheckUtil_init(JNIEnv *env, jclass clazz, jint layout_id,
                                                 jobject activity) {
    //设置布局文件
    jclass activityClazz = env->GetObjectClass(activity);
    //获取Java层方法的id
    char* methodName = "setContentView";
    char* methodSig = "(I)V";
    jmethodID setContentViewMethodId = env->GetMethodID(activityClazz,methodName,methodSig);
    //调用方法
    env->CallVoidMethod(activity, setContentViewMethodId,layout_id);


    //检测是否是模拟器
    jclass deviceUtilsClazz = env->FindClass("com/blankj/utilcode/util/DeviceUtils");
    jmethodID isEmulatorMethodId = env->GetStaticMethodID(deviceUtilsClazz,"isEmulator", "()Z");
    jboolean isEmulator = env->CallStaticBooleanMethod(deviceUtilsClazz,isEmulatorMethodId);
    if(isEmulator){
        showDialog(env,DialogType::EMULATOR,activity);
        return;
    }
}

按钮点击和弹窗关闭的监听事件如下

public class DialogDismissListener implements DialogInterface.OnDismissListener{
    @Override
    public void onDismiss(DialogInterface dialog) {
        AppUtils.exitApp();
    }
}
public class MDialogClickListener implements DialogInterface.OnClickListener {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        dialog.dismiss();
    }
}

然后我们创建MainActivity

public class MainActivity extends BaseActivity {

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }
}

运行APP效果如下(分别为模拟器和真机)


模拟器

真机
2.签名校验

假如某些破解人员发现模拟器不能运行,由于APP破解价值较高,他可能会继续使用真机进行调试,那么他在反编译代码并重新打包的过程中必定会对APK进行重新签名,因此接下来我们就对APK的签名进行校验,我们的校验逻辑同样在NDK层,我们在模拟器检测的逻辑下面加入签名校验,在这之前我们先通过命令获取我们APK签名的SHA-1值,如下

keytool -list -v -keystore safedemo.jks

然后我们加入检测逻辑

const char * SHA1 = "B5:AA:30:95:6A:AA:67:F3:74:FB:CB:91:A6:1C:A2:E2:A8:61:87:8B";
extern "C"
JNIEXPORT void JNICALL
Java_com_itfitness_safedemo_utils_CheckUtil_init(JNIEnv *env, jclass clazz, jint layout_id,
                                                 jobject activity) {
   ...省略部分代码

    //检测签名是否正确
    jclass appUtilsClazz = env->FindClass("com/blankj/utilcode/util/AppUtils");
    jmethodID getAppSignaturesSHA1MethodId = env->GetStaticMethodID(appUtilsClazz,"getAppSignaturesSHA1", "()Ljava/util/List;");
    jobject sha1ArrayList = env->CallStaticObjectMethod(appUtilsClazz,getAppSignaturesSHA1MethodId);
    jclass listClazz = env->FindClass("java/util/List");
    jmethodID getMethodId = env->GetMethodID(listClazz,"get", "(I)Ljava/lang/Object;");
    jstring javaSha1 = (jstring)env->CallObjectMethod(sha1ArrayList,getMethodId,0);
    char * cSha1 = (char*)env->GetStringUTFChars(javaSha1,0);
    LOGE("%s",cSha1);
    //将获取到的SHA-1值与正确签名的SHA-1值比较
    if(strcmp(cSha1,SHA1) != 0){
        showDialog(env,DialogType::JKSERROR,activity);
        return;
    }
}

运行APP效果如下(分别为正版签名和盗版签名)


正版签名

盗版签名
3.WiFi代理校验

有时破解人员也会通过设置WiFi代理来截取手机的数据,因此这里我们也检测下是否有WIFI代理,如下所示,我们创建了一个检测代理的工具类,当然最好也是通过C语言实现,不过这里我暂时就用Java代码实现

public class WifiUtil {
    /*
     * 判断设备 是否使用代理上网
     * */
    public static boolean isWifiProxy(Context context) {
        // 是否大于等于4.0
        final boolean IS_ICS_OR_LATER = Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
        String proxyAddress;
        int proxyPort;
        if (IS_ICS_OR_LATER) {
            proxyAddress = System.getProperty("http.proxyHost");
            String portStr = System.getProperty("http.proxyPort");
            proxyPort = Integer.parseInt((portStr != null ? portStr : "-1"));
        } else {
            proxyAddress = android.net.Proxy.getHost(context);
            proxyPort = android.net.Proxy.getPort(context);
        }
        return (!TextUtils.isEmpty(proxyAddress)) && (proxyPort != -1);
    }
}

然后我们在JNI函数中加入逻辑

extern "C"
JNIEXPORT void JNICALL
Java_com_itfitness_safedemo_utils_CheckUtil_init(JNIEnv *env, jclass clazz, jint layout_id,
                                                 jobject activity) {
    ...省略部分代码


    //检测是否使用了WIFI代理
    jclass wifiUtilsClazz = env->FindClass("com/itfitness/safedemo/utils/WifiUtil");
    jmethodID isWifiProxyMethodId = env->GetStaticMethodID(wifiUtilsClazz,"isWifiProxy",
                                                           "(Landroid/content/Context;)Z");
    jboolean isWifiProxy = env->CallStaticBooleanMethod(wifiUtilsClazz,isWifiProxyMethodId,activity);
    if(isWifiProxy){
        showDialog(env,DialogType::WIFIPROXY,activity);
        return;
    }
}

运行APP效果如下(分别为有代理和无代理)


有代理

无代理

具体的代理设置方法可以参考这篇文章:charles连接手机抓包

4.代码混淆

接下来我们为了让代码更不易阅读可以进行代码混淆

buildTypes {
        release {
            signingConfig signingConfigs.release
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
        debug {
            signingConfig signingConfigs.release
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

不过在混淆代码的时候要注意将JNI函数用到的类取消混淆

-keep class com.itfitness.safedemo.utils.** { *; }
-keep class com.itfitness.safedemo.dialog.** { *; }
-keep class com.blankj.utilcode.util.** { *; }
5.安全加固

最后我们为了更加保险,同时也是为了给破解人员再增加破解难度,这时我们可以进行安全加固,这里我知道的免费加固有:爱加密360加固,如果认为免费的不保险可以使用付费的,完成以上步骤后,一般情况下如果没有特别深的仇恨或是APP价值与破解成本相比还是很高的话一般是没人再去破解了

结语

我现在还在学习中,假如有哪些地方写的不好还请大家帮我指正,谢谢大家

案例源码

https://gitee.com/itfitness/safe-demo

推荐阅读更多精彩内容