Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

為 Android APK 加殼防反編譯:原理、流程與程式碼

編輯:關於 Android 程式設計

APK 天生容易被反編譯,想提高逆向門檻,加殼是常見的思路之一。以下把原理與實作流程完整梳理一遍。

一、什麼是加殼

加殼是在二進位程式裡植入一段程式碼,讓它在執行時優先取得控制權,先做一些額外的工作,再把流程交還給原本的程式。PC 平台上的病毒大量採用這個原理。

二、加殼的作用

殼可以有效阻擋反組譯分析,達到保護原始碼的目的;這項技術也常被用於保護軟體版權、防止破解。

三、Android Dex 加殼的原理

PC 平台早就有大量標準的加殼/脫殼工具,Android 作為新興平台則相對空白。Dex 檔案大量使用引用,這讓加殼比傳統 PE 檔案棘手一些,但理論上完全可行。

整個過程牽涉三個角色:

  • 加殼程式:把原始程式加密成「解殼數據」,再組裝解殼程式與解殼數據。
  • 解殼程式:解密解殼數據,並在執行時透過 DexClassLoader 動態載入。
  • 原始程式:需要被保護的程式碼本體。

依解殼數據在解殼程式 DEX 中的位置不同,可以分成兩種方案。

方案一:解殼數據放在解殼程式檔案尾部。簡單實用,合併後的結構如下:

加殼程式流程:

  1. 把原始 APK 加密為解殼數據。
  2. 將解殼數據寫入解殼程式 Dex 檔案末尾,並在檔尾附加解殼數據的大小。
  3. 修改解殼程式 DEX 標頭中的 checksum、signature 與 file_size。
  4. 修改原始程式的 AndroidManifest.xml,覆蓋解殼程式的版本。

解殼程式流程:

  1. 讀取 DEX 末尾取得解殼數據長度。
  2. 從 DEX 中讀出解殼數據並解密,以檔案形式存為 a.apk。
  3. 透過 DexClassLoader 動態載入 a.apk。

方案二:解殼數據放在解殼程式檔案頭部。做法相對複雜,合併後結構如下:

加殼程式流程:

  1. 把原始 APK 加密為解殼數據。
  2. 計算解殼數據長度,把長度附加到解殼 DEX 標頭末尾(插入位置為 0x70),再把解殼數據接在後面。
  3. 修改解殼程式 DEX 標頭中的 checksum、signature、file_size、header_size、string_ids_off、type_ids_off、proto_ids_off、field_ids_off、method_ids_off、class_defs_off 與 data_off 等相關欄位,並分析 map_off 資料、修正相關偏移量。
  4. 修改原始程式的 AndroidManifest.xml,覆蓋解殼程式的版本。

四、加殼程式的程式碼實作

以下以方案一為例:加密原始 APK、附加到 DEX 末尾、寫入長度、修正標頭。

 package com.android.dexshell;

 import java.io.ByteArrayOutputStream;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.security.MessageDigest;
 import java.security.NoSuchAlgorithmException;
 import java.util.zip.Adler32;

 public class DexShellTool {
 public static void main(String[] args) {
 try {
 File payloadSrcFile = new File("g:/payload.apk");
 File unShellDexFile = new File("g:/unshell.dex");

 byte[] payloadArray = encrpt(readFileBytes(payloadSrcFile));
 byte[] unShellDexArray = readFileBytes(unShellDexFile);

 int payloadLen = payloadArray.length;
 int unShellDexLen = unShellDexArray.length;
 int totalLen = payloadLen + unShellDexLen + 4;
 byte[] newdex = new byte[totalLen];

 //添加解殼代碼
 System.arraycopy(unShellDexArray, 0, newdex, 0, unShellDexLen);
 //添加加密後的解殼數據
 System.arraycopy(payloadArray, 0, newdex, unShellDexLen, payloadLen);
 //添加解殼數據長度
 System.arraycopy(intToByte(payloadLen), 0, newdex, totalLen - 4, 4);

 //修改 DEX file size 標頭
 fixFileSizeHeader(newdex);
 //修改 DEX SHA1 標頭
 fixSHA1Header(newdex);
 //修改 DEX CheckSum 標頭
 fixCheckSumHeader(newdex);

 String str = "g:/classes.dex";
 File file = new File(str);
 if (!file.exists()) {
 file.createNewFile();
 }
 FileOutputStream localFileOutputStream = new FileOutputStream(str);
 localFileOutputStream.write(newdex);
 localFileOutputStream.flush();
 localFileOutputStream.close();
 } catch (Exception e) {
 e.printStackTrace();
 }
 }

 //直接返回數據,讀者可以替換成自己的加密方法
 private static byte[] encrpt(byte[] srcdata) {
 return srcdata;
 }

 private static void fixCheckSumHeader(byte[] dexBytes) {
 Adler32 adler = new Adler32();
 adler.update(dexBytes, 12, dexBytes.length - 12);
 long value = adler.getValue();
 int va = (int) value;
 byte[] newcs = intToByte(va);
 byte[] recs = new byte[4];
 for (int i = 0; i < 4; i++) {
 recs[i] = newcs[newcs.length - 1 - i];
 System.out.println(Integer.toHexString(newcs[i]));
 }
 System.arraycopy(recs, 0, dexBytes, 8, 4);
 System.out.println(Long.toHexString(value));
 System.out.println();
 }

 public static byte[] intToByte(int number) {
 byte[] b = new byte[4];
 for (int i = 3; i >= 0; i--) {
 b[i] = (byte) (number % 256);
 number >>= 8;
 }
 return b;
 }

 private static void fixSHA1Header(byte[] dexBytes) throws NoSuchAlgorithmException {
 MessageDigest md = MessageDigest.getInstance("SHA-1");
 md.update(dexBytes, 32, dexBytes.length - 32);
 byte[] newdt = md.digest();
 System.arraycopy(newdt, 0, dexBytes, 12, 20);
 String hexstr = "";
 for (int i = 0; i < newdt.length; i++) {
 hexstr += Integer.toString((newdt[i] & 0xff) + 0x100, 16).substring(1);
 }
 System.out.println(hexstr);
 }

 private static void fixFileSizeHeader(byte[] dexBytes) {
 byte[] newfs = intToByte(dexBytes.length);
 System.out.println(Integer.toHexString(dexBytes.length));
 byte[] refs = new byte[4];
 for (int i = 0; i < 4; i++) {
 refs[i] = newfs[newfs.length - 1 - i];
 System.out.println(Integer.toHexString(newfs[i]));
 }
 System.arraycopy(refs, 0, dexBytes, 32, 4);
 }

 private static byte[] readFileBytes(File file) throws IOException {
 byte[] arrayOfByte = new byte[1024];
 ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
 FileInputStream fis = new FileInputStream(file);
 while (true) {
 int i = fis.read(arrayOfByte);
 if (i != -1) {
 localByteArrayOutputStream.write(arrayOfByte, 0, i);
 } else {
 return localByteArrayOutputStream.toByteArray();
 }
 }
 }
 } 

注意三個標頭修正的順序:先改 file_size,再算 SHA-1 簽章,最後才是 checksum。因為 checksum 是對第 12 位元組之後的全部內容做 Adler32,必須放在最後。

五、解殼程式的關鍵難題

解殼端才是真正棘手的地方,有四個問題必須解決。

1. 讓解殼程式碼搶在最前面執行

Android 由不同元件構成,系統在需要時才啟動元件。所以解殼必須在元件啟動之前完成,否則會出現找不到類別的例外。Application 作為整個應用的上下文會被系統最先呼叫,是開發者程式的第一執行點,因此把 Application 指向解殼類別即可。

 <application android:icon="@drawable/ic_launcher"
 android:label="@string/app_name"
 android:theme="@style/AppTheme"
 android:name="com.android.dexunshell.ProxyApplication"
 android:meta-data android:name="APPLICATION_CLASS_NAME"
 android:value="com.android.dexunshell.RealApplication">
 </application> 

2. 把 Application 換回原始程式的版本

一旦 manifest 的 Application 被指向解殼類別,原始程式的 Application 就被頂掉了。為了不影響原本的邏輯,解殼完成後必須把它換回來。做法是在 manifest 的 meta-data 中保留原 Application 的類別名稱,解殼程式執行完畢後建立該物件,並用反射改寫回去。

3. 讓 DexClassLoader 載入的類別具備元件生命週期

DexClassLoader 載入的類別沒有元件生命週期,也就是說即使動態載入成功,系統啟動該元件時仍會抛出找不到類別的例外。原因在於元件類別是由另一個 ClassLoader 負責載入的,它和 DexClassLoader 之間沒有關聯。解法是把系統元件 ClassLoader 的 parent 改成我們的 DexClassLoader。

4. 讓解殼後 APK 的資源能被引用

程式預設引用的資源在最外層的解殼程式裡,因此需要增加系統的資源載入路徑,才能讀到被包起來那個 APK 的資源。

六、解殼程式的程式碼

 package com.android.dexunshell;

 import java.io.BufferedInputStream;
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
 import java.io.DataInputStream;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.lang.ref.WeakReference;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.zip.ZipEntry;
 import java.util.zip.ZipInputStream;

 import android.app.Application;
 import android.content.pm.ApplicationInfo;
 import android.content.pm.PackageManager;
 import android.content.pm.PackageManager.NameNotFoundException;
 import android.os.Bundle;
 import dalvik.system.DexClassLoader;

 public class ProxyApplication extends Application {
 private static final String appkey = "APPLICATION_CLASS_NAME";
 private String apkFileName;
 private String odexPath;
 private String libPath;

 @Override
 public void onCreate() {
 super.onCreate();
 try {
 File odex = this.getDir("payload_odex", MODE_PRIVATE);
 File libs = this.getDir("payload_lib", MODE_PRIVATE);
 odexPath = odex.getAbsolutePath();
 libPath = libs.getAbsolutePath();
 apkFileName = odex.getAbsolutePath() + "/payload.apk";

 File dexFile = new File(apkFileName);
 if (!dexFile.exists()) dexFile.createNewFile();

 //讀取程式 classes.dex
 byte[] dexdata = this.readDexFileFromApk();
 //分離出解殼後的 apk,用於動態載入
 this.splitPayLoadFromDex(dexdata);
 //配置動態載入環境
 this.configApplicationEnv();
 } catch (Exception e) {
 e.printStackTrace();
 }
 }

 private void configApplicationEnv() throws NameNotFoundException,
 IllegalAccessException, InstantiationException,
 ClassNotFoundException, IOException {
 Object currentActivityThread = RefInvoke.invokeStaticMethod(
 "android.app.ActivityThread", "currentActivityThread",
 new Class[]{}, new Object[]{});
 HashMap mPackages = (HashMap) RefInvoke.getFieldOjbect(
 "android.app.ActivityThread", currentActivityThread, "mPackages");

 //替換元件類載入器為 DexClassLoader,使動態載入的程式碼具備元件生命週期
 WeakReference wr = (WeakReference) mPackages.get(this.getPackageName());
 DexClassLoader dLoader = new DexClassLoader(apkFileName, odexPath, libPath,
 (ClassLoader) RefInvoke.getFieldOjbect(
 "android.app.LoadedApk", wr.get(), "mClassLoader"));
 RefInvoke.setFieldOjbect("android.app.LoadedApk", "mClassLoader", wr.get(), dLoader);

 //若原始應用配置了 Application,則替換回來,避免影響原程式邏輯
 ApplicationInfo appInfo = this.getPackageManager()
 .getApplicationInfo(this.getPackageName(), PackageManager.GET_META_DATA);
 Bundle bundle = appInfo.metaData;
 if (bundle != null && bundle.containsKey(appkey)) {
 String appClassName = bundle.getString(appkey);
 Application app = (Application) dLoader.loadClass(appClassName).newInstance();

 RefInvoke.setFieldOjbect("android.app.ContextImpl", "mOuterContext",
 this.getBaseContext(), app);
 RefInvoke.setFieldOjbect("android.content.ContextWrapper", "mBase",
 app, this.getBaseContext());

 Object mBoundApplication = RefInvoke.getFieldOjbect(
 "android.app.ActivityThread", currentActivityThread, "mBoundApplication");
 Object info = RefInvoke.getFieldOjbect(
 "android.app.ActivityThread$AppBindData", mBoundApplication, "info");
 RefInvoke.setFieldOjbect("android.app.LoadedApk", "mApplication", info, app);

 Object oldApplication = RefInvoke.getFieldOjbect(
 "android.app.ActivityThread", currentActivityThread, "mInitialApplication");
 RefInvoke.setFieldOjbect("android.app.ActivityThread", "mInitialApplication",
 currentActivityThread, app);

 ArrayList<Application> mAllApplications = (ArrayList<Application>)
 RefInvoke.getFieldOjbect("android.app.ActivityThread",
 currentActivityThread, "mAllApplications");
 mAllApplications.remove(oldApplication);
 mAllApplications.add(app);

 HashMap mProviderMap = (HashMap) RefInvoke.getFieldOjbect(
 "android.app.ActivityThread", currentActivityThread, "mProviderMap");
 Iterator it = mProviderMap.values().iterator();
 while (it.hasNext()) {
 Object providerClientRecord = it.next();
 Object localProvider = RefInvoke.getFieldOjbect(
 "android.app.ProviderClientRecord", providerClientRecord, "mLocalProvider");
 RefInvoke.setFieldOjbect("android.content.ContentProvider", "mContext",
 localProvider, app);
 }

 RefInvoke.invokeMethod(appClassName, "onCreate", app,
 new Class[]{}, new Object[]{});
 }
 }

 private void splitPayLoadFromDex(byte[] data) throws IOException {
 byte[] apkdata = decrypt(data);
 int ablen = apkdata.length;
 byte[] dexlen = new byte[4];
 System.arraycopy(apkdata, ablen - 4, dexlen, 0, 4);

 ByteArrayInputStream bais = new ByteArrayInputStream(dexlen);
 DataInputStream in = new DataInputStream(bais);
 int readInt = in.readInt();
 System.out.println(Integer.toHexString(readInt));

 byte[] newdex = new byte[readInt];
 System.arraycopy(apkdata, ablen - 4 - readInt, newdex, 0, readInt);

 File file = new File(apkFileName);
 try {
 FileOutputStream localFileOutputStream = new FileOutputStream(file);
 localFileOutputStream.write(newdex);
 localFileOutputStream.close();
 } catch (IOException localIOException) {
 throw new RuntimeException(localIOException);
 }

 //把 apk 中的 so 解出來,供動態載入時使用
 ZipInputStream localZipInputStream = new ZipInputStream(
 new BufferedInputStream(new FileInputStream(file)));
 while (true) {
 ZipEntry localZipEntry = localZipInputStream.getNextEntry();
 if (localZipEntry == null) {
 localZipInputStream.close();
 break;
 }
 String name = localZipEntry.getName();
 if (name.startsWith("lib/") && name.endsWith(".so")) {
 File storeFile = new File(libPath + "/" + name.substring(name.lastIndexOf('/')));
 storeFile.createNewFile();
 FileOutputStream fos = new FileOutputStream(storeFile);
 byte[] arrayOfByte = new byte[1024];
 while (true) {
 int i = localZipInputStream.read(arrayOfByte);
 if (i == -1) break;
 fos.write(arrayOfByte, 0, i);
 }
 fos.flush();
 fos.close();
 }
 localZipInputStream.closeEntry();
 }
 localZipInputStream.close();
 }

 private byte[] readDexFileFromApk() throws IOException {
 ByteArrayOutputStream dexByteArrayOutputStream = new ByteArrayOutputStream();
 ZipInputStream localZipInputStream = new ZipInputStream(
 new BufferedInputStream(
 new FileInputStream(this.getApplicationInfo().sourceDir)));
 while (true) {
 ZipEntry localZipEntry = localZipInputStream.getNextEntry();
 if (localZipEntry == null) {
 localZipInputStream.close();
 break;
 }
 if (localZipEntry.getName().equals("classes.dex")) {
 byte[] arrayOfByte = new byte[1024];
 while (true) {
 int i = localZipInputStream.read(arrayOfByte);
 if (i == -1) break;
 dexByteArrayOutputStream.write(arrayOfByte, 0, i);
 }
 }
 localZipInputStream.closeEntry();
 }
 localZipInputStream.close();
 return dexByteArrayOutputStream.toByteArray();
 }

 //直接返回數據,讀者可以替換成自己的解密方法
 private byte[] decrypt(byte[] data) {
 return data;
 }
 } 

搭配的反射工具類 RefInvoke,把 invokeStaticMethod、invokeMethod、getFieldOjbect、setFieldOjbect 這幾個常用操作包成靜態方法,讓上面的邏輯讀起來清爽一些:

 package com.android.dexunshell;

 import java.lang.reflect.Field;
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;

 public class RefInvoke {
 public static Object invokeStaticMethod(String class_name, String method_name,
 Class[] pareTyple, Object[] pareVaules) {
 try {
 Class obj_class = Class.forName(class_name);
 Method method = obj_class.getMethod(method_name, pareTyple);
 return method.invoke(null, pareVaules);
 } catch (Exception e) {
 e.printStackTrace();
 }
 return null;
 }

 public static Object invokeMethod(String class_name, String method_name, Object obj,
 Class[] pareTyple, Object[] pareVaules) {
 try {
 Class obj_class = Class.forName(class_name);
 Method method = obj_class.getMethod(method_name, pareTyple);
 return method.invoke(obj, pareVaules);
 } catch (Exception e) {
 e.printStackTrace();
 }
 return null;
 }

 public static Object getFieldOjbect(String class_name, Object obj, String filedName) {
 try {
 Class obj_class = Class.forName(class_name);
 Field field = obj_class.getDeclaredField(filedName);
 field.setAccessible(true);
 return field.get(obj);
 } catch (Exception e) {
 e.printStackTrace();
 }
 return null;
 }

 public static Object getStaticFieldOjbect(String class_name, String filedName) {
 try {
 Class obj_class = Class.forName(class_name);
 Field field = obj_class.getDeclaredField(filedName);
 field.setAccessible(true);
 return field.get(null);
 } catch (Exception e) {
 e.printStackTrace();
 }
 return null;
 }

 public static void setFieldOjbect(String classname, String filedName,
 Object obj, Object filedVaule) {
 try {
 Class obj_class = Class.forName(classname);
 Field field = obj_class.getDeclaredField(filedName);
 field.setAccessible(true);
 field.set(obj, filedVaule);
 } catch (Exception e) {
 e.printStackTrace();
 }
 }

 public static void setStaticOjbect(String class_name, String filedName, Object filedVaule) {
 try {
 Class obj_class = Class.forName(class_name);
 Field field = obj_class.getDeclaredField(filedName);
 field.setAccessible(true);
 field.set(null, filedVaule);
 } catch (Exception e) {
 e.printStackTrace();
 }
 }
 } 

七、總結

以上程式碼把加殼與脫殼的原理跑通了,但作為實驗性實作還有明顯改進空間:

  1. 加殼資料目前只是原樣附加,實際上線需要替換成真正的加密演算法。
  2. 脫殼邏輯用 Java 撰寫,容易被靜態分析;改以 C/native 層實作,能顯著提高逆向成本。

另外要提醒的是,這套方案高度依賴反射去改 ActivityThread、LoadedApk 這些內部欄位,欄位名稱與結構在不同 Android 版本之間變動頻繁,加上系統對動態載入的限制逐步收緊,實際使用前務必針對目標版本逐一驗證。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved