APP安全(一)-防二次打包(C、C++签名校验)
前言
由于Android系统的开放性,开发出来的APP很容易被逆向,修改代码逻、加入广告、病毒等二次打包后发布,对开发者和用户造成一定的损失。因此我们的APP运行过程中需要进行签名校验,以及使用加解密算法对数据进行处理,从而保证访问服务端的请求是我们信任的APK。签名校验如果放在Java语言层面,很容易被逆向,因此需要在C/C++层进行校验,从而增加**的难度。
校验逻辑
- APP启动时候初始化我们所写的动态库,一般在Application的onCrate()方法中初始化
- 获取APP的签名SHA1值
- 匹配获取到的值是否与C/C++中写入的值相同
- APP在加载so文件是,会自动调用JNI_OnLoad方法,因此在该方法中进行判断,如果签名不匹配,返回-1,让App Crash
实现步骤
第一步:NDK环境搭建
NDK环境的搭建可参考谷歌官方文档,已经翻译为中文;
第二步:编写Java层代码
1,工具类
public class SecurityTool {
static {
System.loadLibrary("hts-security");
}
public static void init(){}
}
2,在Application中初始化
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
SecurityTool.init();
}
}
SecurityTool的init(){}方法只写了一个空方法,根据虚拟机类的初始化机制,当遇到new,getstatic,putstatic、invokestatic这4条字节码指令时,会执行类的初始化。类的初始化过程中,先执行静态代码块,因此会自动执行我们动态库的OnLoad,完成校验。
第二步:C++代码完成校验
定义校验文件:app-validate.cpp
//
// Created by qj on 2020/1/8.
//
const char HEX_CODE[] = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
const char *APP_SIGNATURE = "6C97D7FC026DB630523D6ECA15941129F62B0083";
char *appSha1 = NULL;
/**
*
* get sha1 by reflect
*
*/
char* getAppSha1(JNIEnv *env, jobject context_object){
if(appSha1 == NULL){
jclass context_class = env->GetObjectClass(context_object);
jmethodID methodId = env->GetMethodID(context_class, "getPackageManager", "()Landroid/content/pm/PackageManager;");
jobject package_manager = env->CallObjectMethod(context_object, methodId);
methodId = env->GetMethodID(context_class, "getPackageName", "()Ljava/lang/String;");
jstring package_name = (jstring)env->CallObjectMethod(context_object, methodId);
env->DeleteLocalRef(context_class);
jclass pack_manager_class = env->GetObjectClass(package_manager);
methodId = env->GetMethodID(pack_manager_class, "getPackageInfo", "(Ljava/lang/String;I)Landroid/content/pm/PackageInfo;");
env->DeleteLocalRef(pack_manager_class);
jobject package_info = env->CallObjectMethod(package_manager, methodId, package_name, 0x40);
env->DeleteLocalRef(package_manager);
jclass package_info_class = env->GetObjectClass(package_info);
jfieldID fieldId = env->GetFieldID(package_info_class, "signatures", "[Landroid/content/pm/Signature;");
env->DeleteLocalRef(package_info_class);
jobjectArray signature_object_array = (jobjectArray)env->GetObjectField(package_info, fieldId);
jobject signature_object = env->GetObjectArrayElement(signature_object_array, 0);
env->DeleteLocalRef(package_info);
jclass signature_class = env->GetObjectClass(signature_object);
methodId = env->GetMethodID(signature_class, "toByteArray", "()[B");
env->DeleteLocalRef(signature_class);
jbyteArray signature_byte = (jbyteArray) env->CallObjectMethod(signature_object, methodId);
jclass byte_array_input_class=env->FindClass("java/io/ByteArrayInputStream");
methodId=env->GetMethodID(byte_array_input_class,"<init>","([B)V");
jobject byte_array_input=env->NewObject(byte_array_input_class,methodId,signature_byte);
jclass certificate_factory_class=env->FindClass("java/security/cert/CertificateFactory");
methodId=env->GetStaticMethodID(certificate_factory_class,"getInstance","(Ljava/lang/String;)Ljava/security/cert/CertificateFactory;");
jstring x_509_jstring=env->NewStringUTF("X.509");
jobject cert_factory=env->CallStaticObjectMethod(certificate_factory_class,methodId,x_509_jstring);
methodId=env->GetMethodID(certificate_factory_class,"generateCertificate",("(Ljava/io/InputStream;)Ljava/security/cert/Certificate;"));
jobject x509_cert=env->CallObjectMethod(cert_factory,methodId,byte_array_input);
env->DeleteLocalRef(certificate_factory_class);
jclass x509_cert_class=env->GetObjectClass(x509_cert);
methodId=env->GetMethodID(x509_cert_class,"getEncoded","()[B");
jbyteArray cert_byte=(jbyteArray)env->CallObjectMethod(x509_cert,methodId);
env->DeleteLocalRef(x509_cert_class);
jclass message_digest_class=env->FindClass("java/security/MessageDigest");
methodId=env->GetStaticMethodID(message_digest_class,"getInstance","(Ljava/lang/String;)Ljava/security/MessageDigest;");
jstring sha1_jstring=env->NewStringUTF("SHA1");
jobject sha1_digest=env->CallStaticObjectMethod(message_digest_class,methodId,sha1_jstring);
methodId=env->GetMethodID(message_digest_class,"digest","([B)[B");
jbyteArray sha1_byte=(jbyteArray)env->CallObjectMethod(sha1_digest,methodId,cert_byte);
env->DeleteLocalRef(message_digest_class);
jsize array_size=env->GetArrayLength(sha1_byte);
jbyte* sha1 =env->GetByteArrayElements(sha1_byte,NULL);
char *hex_sha=new char[array_size*2+1];
for (int i = 0; i <array_size ; ++i) {
hex_sha[2*i]=HEX_CODE[((unsigned char)sha1[i])/16];
hex_sha[2*i+1]=HEX_CODE[((unsigned char)sha1[i])%16];
}
hex_sha[array_size*2]='\0';
appSha1 = hex_sha;
}
return appSha1;
}
jboolean checkSignature(JNIEnv *env, jobject context){
const char *appSignatureSha1 = getAppSha1(env,context);
jstring releaseSignature = env->NewStringUTF(APP_SIGNATURE);
jstring appSignature = env->NewStringUTF(appSignatureSha1);
const char *charAppSignature = env->GetStringUTFChars(appSignature, NULL);
const char *charReleaseSignature = env->GetStringUTFChars(releaseSignature, NULL);
jboolean result = JNI_FALSE;
if (charAppSignature != NULL && charReleaseSignature != NULL) {
if (strcmp(charAppSignature, charReleaseSignature) == 0) {
result = JNI_TRUE;
}
}
env->ReleaseStringUTFChars(appSignature, charAppSignature);
env->ReleaseStringUTFChars(releaseSignature, charReleaseSignature);
return result;
}
/**
*
*get Application Context
*
*/
jobject getApplication(JNIEnv *env){
jobject application = NULL;
jclass activity_thread_clz = env->FindClass("android/app/ActivityThread");
if (activity_thread_clz != NULL) {
jmethodID currentApplication = env->GetStaticMethodID(
activity_thread_clz, "currentApplication", "()Landroid/app/Application;");
if (currentApplication != NULL) {
application = env->CallStaticObjectMethod(activity_thread_clz, currentApplication);
}
env->DeleteLocalRef(activity_thread_clz);
}
return application;
}
/**
*
*validate signature
*
*/
jboolean checkSignature(JNIEnv *env){
jobject appContext = getApplication(env);
if(appContext != NULL){
return checkSignature(env,appContext);
}
return JNI_FALSE;
}
hts-security.cpp调用校验方法
#include <jni.h>
#include <string>
#include "app-validate.cpp"
extern "C" {
JNIEXPORT jint JNICALL
JNI_OnLoad(JavaVM *vm, void *reserved) {
JNIEnv *env;
if (vm->GetEnv((void **) (&env), JNI_VERSION_1_6) != JNI_OK) {
return -1;
}
if (checkSignature(env) != JNI_TRUE) {
return -1;
}
return JNI_VERSION_1_6;
}
}
注意事项:
const char *APP_SIGNATURE = "6C97D7FC026DB630523D6ECA15941129F62B0083";
该值为apk签名证书SHA1值,Windows环境下debug.keystore一般存储在C:\Users\xx用户xx\.android目录下,进该目录输入:
keytool -list -v -keystore debug.keystore
秘钥库口令一般为:android
完成后可获得证书信息:
**库类型: jks
**库提供方: SUN
您的**库包含 1 个条目
别名: androiddebugkey
创建日期: 2019-1-4
条目类型: PrivateKeyEntry
证书链长度: 1
证书[1]:
所有者: C=US, O=Android, CN=Android Debug
发布者: C=US, O=Android, CN=Android Debug
***: 1
有效期为 Fri Jan 04 10:14:36 CST 2019 至 Sun Dec 27 10:14:36 CST 2048
证书指纹:
MD5: A5:1A:C1:16:03:AA:54:BB:DF:A8:D8:E8:FC:20:93:EB
SHA1: 6C:97:D7:FC:02:6D:B6:30:52:3D:6E:CA:15:94:11:29:F6:2B:00:83
SHA256: 21:E5:21:EA:13:9D:06:ED:1B:D7:D5:F8:B7:F3:B1:41:5B:34:B9:73:B5:5D:6E:F1:B8:6B:7F:80:8B:0C:EF:10
签名算法名称: SHA1withRSA
主体公共**算法: 1024 位 RSA **
版本: 1
*******************************************
*******************************************
其中SHA1: 6C:97:D7:FC:02:6D:B6:30:52:3D:6E:CA:15:94:11:29:F6:2B:00:83,去掉":"为C++中对比值。
其他证书的SHA1值可参考上述方法。
需要改进的点:
通过反射获取证书能被 hook掉与PMS交互的IPackageManager即可完美**,没有这块的逆向经验,所以没有试验过。针对这块网上有文章使用 APK安装时的备份,解压APK获取CERT.RSA,然后提取公钥,在进行校验。具体可参考:Android安全机制之NDK实现防钩子签名校验
总结
使用上述方法在C++层面实现了APK签名的校验,但如果仅仅只有这层校验,远远是不够的;因为逆向后删除SecurityTool.init();这行代码,我们所写的动态库就形同虚设,完全没有作用。因此我们我们还在需要在所写的动态库中加入加密算法,和服务交互的数据需要经过我们所写的动态库进行加密,服务端拿到数据后进行解密验证,这样才能保证我们所写的动态库的价值。签名校验完成了第一步,防止二次打包,后续将结合OpenSSL进行加解密,这样保证我们整个APP的安全。
上一篇: Android开发命名规范
下一篇: Android开发代码规范