Android APK加壳技术方案【1】


一、什么是加壳?

加壳是在二进制的程序中植入一段代码,在运行的时候优先取得程序的控制权,做一些额外的工作。大多数病毒就是基于此原理。PC EXE文件加壳的过程如下:



二、加壳作用

加壳的程序可以有效阻止对程序的反汇编分析,以达到它不可告人的目的。这种技术也常用来保护软件版权,防止被软件破解。


三、Android Dex文件加壳原理

PC平台现在已存在大量的标准的加壳和解壳工具,但是Android作为新兴平台还未出现APK加壳工具。Android Dex文件大量使用引用给加壳带来了一定的难度,但是从理论上讲,Android APK加壳也是可行的。

在这个过程中,牵扯到三个角色:

1、加壳程序:加密源程序为解壳数据、组装解壳程序和解壳数据

2、解壳程序:解密解壳数据,并运行时通过DexClassLoader动态加载

3、源程序:需要加壳处理的被保护代码

阅读该文章,需要您对DEX文件结构有所了解,您可以通过以下网址了解相关信息:

http://blog.csdn.net/jiazhijun/article/details/8664778


根据解壳数据在解壳程序DEX文件中的不同分布,本文将提出两种Android Dex加壳的实现方案。


(一)解壳数据位于解壳程序文件尾部


该种方式简单实用,合并后的DEX文件结构如下。




加壳程序工作流程:

1、加密源程序APK文件为解壳数据

2、把解壳数据写入解壳程序Dex文件末尾,并在文件尾部添加解壳数据的大小。

3、修改解壳程序DEX头中checksum、signature 和file_size头信息。

4、修改源程序AndroidMainfest.xml文件并覆盖解壳程序AndroidMainfest.xml文件。


解壳DEX程序工作流程:

1、读取DEX文件末尾数据获取借壳数据长度。

2、从DEX文件读取解壳数据,解密解壳数据。以文件形式保存解密数据到a.APK文件

3、通过DexClassLoader动态加载a.apk。


(二)解壳数据位于解壳程序文件头


该种方式相对比较复杂, 合并后DEX文件结构如下:





加壳程序工作流程:

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、修改源程序AndroidMainfest.xml文件并覆盖解壳程序AndroidMainfest.xml文件。


解壳DEX程序工作流程:

1、从0x70处读取解壳数据长度。

2、从DEX文件读取解壳数据,解密解壳数据。以文件形式保存解密数据到a.APK

3、通过DexClassLoader动态加载a.APK。


四、加壳及脱壳代码实现


http://blog.csdn.net/jiazhijun/article/details/8809542



一、序言


在上篇“Android APK加壳技术方案”(http://blog.csdn.net/jiazhijun/article/details/8678399)博文中,根据加壳数据在解壳程序Dex文件所处的位置,我提出了两种Android Dex加壳技术实现方案,本片博文将对方案1代码实现进行讲解。博友可以根据方案1的代码实现原理对方案2自行实现。

在方案1的代码实现过程中,各种不同的问题接踵出现,最初的方案也在不同问题的出现、解决过程中不断的得到调整、优化。

本文的代码实现了对整个APK包的加壳处理。加壳程序不会对源程序有任何的影响。


二、代码实现


本程序基于Android2.3代码实现,因为牵扯到系统代码的反射修改,本程序不保证在其它android版本正常工作,博友可以根据实现原理,自行实现对其它Android版本的兼容性开发。


1、 加壳程序流程及代码实现


1、加密源程序APK为解壳数据

2、把解壳数据写入解壳程序DEX文件末尾,并在文件尾部添加解壳数据的大小。

3、修改解壳程序DEX头中checksum、signature 和file_size头信息。


代码实现如下:


[java] view plaincopy

  1. package com.android.dexshell;

  2. import java.io.ByteArrayOutputStream;

  3. import java.io.File;

  4. import java.io.FileInputStream;

  5. import java.io.FileOutputStream;

  6. import java.io.IOException;

  7. import java.security.MessageDigest;

  8. import java.security.NoSuchAlgorithmException;

  9. import java.util.zip.Adler32;


  10. public class DexShellTool {

  11. /**

  12. * @param args

  13. */

  14. public static void main(String[] args) {

  15. // TODO Auto-generated method stub

  16. try {

  17. File payloadSrcFile = new File("g:/payload.apk");

  18. File unShellDexFile = new File("g:/unshell.dex");

  19. byte[] payloadArray = encrpt(readFileBytes(payloadSrcFile));

  20. byte[] unShellDexArray = readFileBytes(unShellDexFile);

  21. int payloadLen = payloadArray.length;

  22. int unShellDexLen = unShellDexArray.length;

  23. int totalLen = payloadLen + unShellDexLen +4;

  24. byte[] newdex = new byte[totalLen];

  25. //添加解壳代码

  26. System.arraycopy(unShellDexArray, 0, newdex, 0, unShellDexLen);

  27. //添加加密后的解壳数据

  28. System.arraycopy(payloadArray, 0, newdex, unShellDexLen,

  29. payloadLen);

  30. //添加解壳数据长度

  31. System.arraycopy(intToByte(payloadLen), 0, newdex, totalLen-4, 4);

  32. //修改DEX file size文件头

  33. fixFileSizeHeader(newdex);

  34. //修改DEX SHA1 文件头

  35. fixSHA1Header(newdex);

  36. //修改DEX CheckSum文件头

  37. fixCheckSumHeader(newdex);



  38. String str = "g:/classes.dex";

  39. File file = new File(str);

  40. if (!file.exists()) {

  41. file.createNewFile();

  42. }


  43. FileOutputStream localFileOutputStream = new FileOutputStream(str);

  44. localFileOutputStream.write(newdex);

  45. localFileOutputStream.flush();

  46. localFileOutputStream.close();



  47. } catch (Exception e) {

  48. // TODO Auto-generated catch block

  49. e.printStackTrace();

  50. }

  51. }


  52. //直接返回数据,读者可以添加自己加密方法

  53. private static byte[] encrpt(byte[] srcdata){

  54. return srcdata;

  55. }



  56. private static void fixCheckSumHeader(byte[] dexBytes) {

  57. Adler32 adler = new Adler32();

  58. adler.update(dexBytes, 12, dexBytes.length - 12);

  59. long value = adler.getValue();

  60. int va = (int) value;

  61. byte[] newcs = intToByte(va);

  62. byte[] recs = new byte[4];

  63. for (int i = 0; i < 4; i++) {

  64. recs[i] = newcs[newcs.length - 1 - i];

  65. System.out.println(Integer.toHexString(newcs[i]));

  66. }

  67. System.arraycopy(recs, 0, dexBytes, 8, 4);

  68. System.out.println(Long.toHexString(value));

  69. System.out.println();

  70. }



  71. public static byte[] intToByte(int number) {

  72. byte[] b = new byte[4];

  73. for (int i = 3; i >= 0; i--) {

  74. b[i] = (byte) (number % 256);

  75. number >>= 8;

  76. }

  77. return b;

  78. }



  79. private static void fixSHA1Header(byte[] dexBytes)

  80. throws NoSuchAlgorithmException {

  81. MessageDigest md = MessageDigest.getInstance("SHA-1");

  82. md.update(dexBytes, 32, dexBytes.length - 32);

  83. byte[] newdt = md.digest();

  84. System.arraycopy(newdt, 0, dexBytes, 12, 20);

  85. String hexstr = "";

  86. for (int i = 0; i < newdt.length; i++) {

  87. hexstr += Integer.toString((newdt[i] & 0xff) + 0x100, 16)

  88. .substring(1);

  89. }

  90. System.out.println(hexstr);

  91. }



  92. private static void fixFileSizeHeader(byte[] dexBytes) {



  93. byte[] newfs = intToByte(dexBytes.length);

  94. System.out.println(Integer.toHexString(dexBytes.length));

  95. byte[] refs = new byte[4];

  96. for (int i = 0; i < 4; i++) {

  97. refs[i] = newfs[newfs.length - 1 - i];

  98. System.out.println(Integer.toHexString(newfs[i]));

  99. }

  100. System.arraycopy(refs, 0, dexBytes, 32, 4);

  101. }



  102. private static byte[] readFileBytes(File file) throws IOException {

  103. byte[] arrayOfByte = new byte[1024];

  104. ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();

  105. FileInputStream fis = new FileInputStream(file);

  106. while (true) {

  107. int i = fis.read(arrayOfByte);

  108. if (i != -1) {

  109. localByteArrayOutputStream.write(arrayOfByte, 0, i);

  110. } else {

  111. return localByteArrayOutputStream.toByteArray();

  112. }

  113. }

  114. }



  115. }



2、 解壳程序流程及代码实现

在解壳程序的开发过程中需要解决如下几个关键的技术问题:

(1)解壳代码如何能够第一时间执行?

Android程序由不同的组件构成,系统在有需要的时候启动程序组件。因此解壳程序必须在Android系统启动组件之前运行,完成对解壳数 据的解壳及APK文件的动态加载,否则会使程序出现加载类失败的异常。

Android开发者都知道Applicaiton做为整个应用的上下文,会被系统第一时间调用,这也是应用开发者程序代码的第一执行点。因此通过对 AndroidMainfest.xml的application的配置可以实现解壳代码第一时间运行。


[html] view plaincopy

  1. <application

  2. android:icon="@drawable/ic_launcher"

  3. android:label="@string/app_name"

  4. android:theme="@style/AppTheme" android:name="<span style="color: rgb(255, 0, 0);"><em><strong>com.android.dexunshell.ProxyApplication</strong></em></span>" >

  5. </application>



(2)如何替换回源程序原有的Application?

当在AndroidMainfest.xml文件配置为解壳代码的Application时。源程序原有的Applicaiton将被替换,为了不影响源程序代码逻辑,我们需要 在解壳代码运行完成后,替换回源程序原有的Application对象。我们通过在AndroidMainfest.xml文件中配置原有Applicaiton类信息来达到我们 的目的。解壳程序要在运行完毕后通过创建配置的Application对象,并通过反射修改回原Application。


[html] view plaincopy

  1. <application

  2. android:icon="@drawable/ic_launcher"

  3. android:label="@string/app_name"

  4. android:theme="@style/AppTheme" android:name="<em><strong><span style="color: rgb(255, 0, 0);">com.android.dexunshell.ProxyApplication</span></strong></em>" >

  5. <span style="color: rgb(255, 0, 0);"><em><strong><meta-data android:name="APPLICATION_CLASS_NAME" android:value="com.***.Application"/></strong></em></span>

  6. </application>



(3)如何通过DexClassLoader实现对apk代码的动态加载。


我们知道DexClassLoader加载的类是没有组件生命周期的,也就是说即使DexClassLoader通过对APK的动态加载完成了对组件类的加载, 当系统启动该组件时,还会出现加载类失败的异常。为什么组件类被动态加载入虚拟机,但系统却出现加载类失败呢?

通过查看Android源代码我们知道组件类的加载是由另一个ClassLoader来完成的,DexClassLoader和系统组件ClassLoader并不存在关 系,系统组件ClassLoader当然找不到由DexClassLoader加载的类,如果把系统组件ClassLoader的parent修改成DexClassLoader,我们就可 以实现对apk代码的动态加载。


(4)如何使解壳后的APK资源文件被代码动态引用。

代码默认引用的资源文件在最外层的解壳程序中,因此我们要增加系统的资源加载路径来实现对借壳后APK文件资源的加载。


解壳实现代码:


[java] view plaincopy

  1. package com.android.dexunshell;


  2. import java.io.BufferedInputStream;

  3. import java.io.ByteArrayInputStream;

  4. import java.io.ByteArrayOutputStream;

  5. import java.io.DataInputStream;

  6. import java.io.File;

  7. import java.io.FileInputStream;

  8. import java.io.FileOutputStream;

  9. import java.io.IOException;

  10. import java.lang.ref.WeakReference;

  11. import java.util.ArrayList;

  12. import java.util.HashMap;

  13. import java.util.Iterator;

  14. import java.util.zip.ZipEntry;

  15. import java.util.zip.ZipInputStream;


  16. import dalvik.system.DexClassLoader;

  17. import android.app.Application;

  18. import android.content.pm.ApplicationInfo;

  19. import android.content.pm.PackageManager;

  20. import android.content.pm.PackageManager.NameNotFoundException;

  21. import android.os.Bundle;

  22. public class ProxyApplication extends Application {



  23. private static final String appkey = "APPLICATION_CLASS_NAME";

  24. private String apkFileName;

  25. private String odexPath;

  26. private String libPath;



  27. protected void attachBaseContext(Context base) {

  28. super.attachBaseContext(base);

  29. try {

  30. File odex = this.getDir("payload_odex", MODE_PRIVATE);

  31. File libs = this.getDir("payload_lib", MODE_PRIVATE);

  32. odexPath = odex.getAbsolutePath();

  33. libPath = libs.getAbsolutePath();

  34. apkFileName = odex.getAbsolutePath() + "/payload.apk";

  35. File dexFile = new File(apkFileName);

  36. if (!dexFile.exists())

  37. dexFile.createNewFile();

  38. // 读取程序classes.dex文件

  39. byte[] dexdata = this.readDexFileFromApk();

  40. // 分离出解壳后的apk文件已用于动态加载

  41. this.splitPayLoadFromDex(dexdata);

  42. // 配置动态加载环境

  43. Object currentActivityThread = RefInvoke.invokeStaticMethod(

  44. "android.app.ActivityThread", "currentActivityThread",

  45. new Class[] {}, new Object[] {});

  46. String packageName = this.getPackageName();

  47. HashMap mPackages = (HashMap) RefInvoke.getFieldOjbect(

  48. "android.app.ActivityThread", currentActivityThread,

  49. "mPackages");

  50. WeakReference wr = (WeakReference) mPackages.get(packageName);

  51. DexClassLoader dLoader = new DexClassLoader(apkFileName, odexPath,

  52. libPath, (ClassLoader) RefInvoke.getFieldOjbect(

  53. "android.app.LoadedApk", wr.get(), "mClassLoader"));

  54. RefInvoke.setFieldOjbect("android.app.LoadedApk", "mClassLoader",

  55. wr.get(), dLoader);



  56. } catch (Exception e) {

  57. // TODO Auto-generated catch block

  58. e.printStackTrace();

  59. }

  60. }



  61. public void onCreate() {

  62. {



  63. // 如果源应用配置有Appliction对象,则替换为源应用Applicaiton,以便不影响源程序逻辑。

  64. String appClassName = null;

  65. try {

  66. ApplicationInfo ai = this.getPackageManager()

  67. .getApplicationInfo(this.getPackageName(),

  68. PackageManager.GET_META_DATA);

  69. Bundle bundle = ai.metaData;

  70. if (bundle != null

  71. && bundle.containsKey("APPLICATION_CLASS_NAME")) {

  72. appClassName = bundle.getString("APPLICATION_CLASS_NAME");

  73. } else {

  74. return;

  75. }

  76. } catch (NameNotFoundException e) {

  77. // TODO Auto-generated catch block

  78. e.printStackTrace();

  79. }



  80. Object currentActivityThread = RefInvoke.invokeStaticMethod(

  81. "android.app.ActivityThread", "currentActivityThread",

  82. new Class[] {}, new Object[] {});

  83. Object mBoundApplication = RefInvoke.getFieldOjbect(

  84. "android.app.ActivityThread", currentActivityThread,

  85. "mBoundApplication");

  86. Object loadedApkInfo = RefInvoke.getFieldOjbect(

  87. "android.app.ActivityThread$AppBindData",

  88. mBoundApplication, "info");

  89. RefInvoke.setFieldOjbect("android.app.LoadedApk", "mApplication",

  90. loadedApkInfo, null);

  91. Object oldApplication = RefInvoke.getFieldOjbect(

  92. "android.app.ActivityThread", currentActivityThread,

  93. "mInitialApplication");

  94. ArrayList<Application> mAllApplications = (ArrayList<Application>) RefInvoke

  95. .getFieldOjbect("android.app.ActivityThread",

  96. currentActivityThread, "mAllApplications");

  97. mAllApplications.remove(oldApplication);

  98. ApplicationInfo appinfo_In_LoadedApk = (ApplicationInfo) RefInvoke

  99. .getFieldOjbect("android.app.LoadedApk", loadedApkInfo,

  100. "mApplicationInfo");

  101. ApplicationInfo appinfo_In_AppBindData = (ApplicationInfo) RefInvoke

  102. .getFieldOjbect("android.app.ActivityThread$AppBindData",

  103. mBoundApplication, "appInfo");

  104. appinfo_In_LoadedApk.className = appClassName;

  105. appinfo_In_AppBindData.className = appClassName;

  106. Application app = (Application) RefInvoke.invokeMethod(

  107. "android.app.LoadedApk", "makeApplication", loadedApkInfo,

  108. new Class[] { boolean.class, Instrumentation.class },

  109. new Object[] { false, null });

  110. RefInvoke.setFieldOjbect("android.app.ActivityThread",

  111. "mInitialApplication", currentActivityThread, app);



  112. HashMap mProviderMap = (HashMap) RefInvoke.getFieldOjbect(

  113. "android.app.ActivityThread", currentActivityThread,

  114. "mProviderMap");

  115. Iterator it = mProviderMap.values().iterator();

  116. while (it.hasNext()) {

  117. Object providerClientRecord = it.next();

  118. Object localProvider = RefInvoke.getFieldOjbect(

  119. "android.app.ActivityThread$ProviderClientRecord",

  120. providerClientRecord, "mLocalProvider");

  121. RefInvoke.setFieldOjbect("android.content.ContentProvider",

  122. "mContext", localProvider, app);

  123. }

  124. app.onCreate();

  125. }

  126. }



  127. private void splitPayLoadFromDex(byte[] data) throws IOException {

  128. byte[] apkdata = decrypt(data);

  129. int ablen = apkdata.length;

  130. byte[] dexlen = new byte[4];

  131. System.arraycopy(apkdata, ablen - 4, dexlen, 0, 4);

  132. ByteArrayInputStream bais = new ByteArrayInputStream(dexlen);

  133. DataInputStream in = new DataInputStream(bais);

  134. int readInt = in.readInt();

  135. System.out.println(Integer.toHexString(readInt));

  136. byte[] newdex = new byte[readInt];

  137. System.arraycopy(apkdata, ablen - 4 - readInt, newdex, 0, readInt);

  138. File file = new File(apkFileName);

  139. try {

  140. FileOutputStream localFileOutputStream = new FileOutputStream(file);

  141. localFileOutputStream.write(newdex);

  142. localFileOutputStream.close();



  143. } catch (IOException localIOException) {

  144. throw new RuntimeException(localIOException);

  145. }



  146. ZipInputStream localZipInputStream = new ZipInputStream(

  147. new BufferedInputStream(new FileInputStream(file)));

  148. while (true) {

  149. ZipEntry localZipEntry = localZipInputStream.getNextEntry();

  150. if (localZipEntry == null) {

  151. localZipInputStream.close();

  152. break;

  153. }

  154. String name = localZipEntry.getName();

  155. if (name.startsWith("lib/") && name.endsWith(".so")) {

  156. File storeFile = new File(libPath + "/"

  157. + name.substring(name.lastIndexOf('/')));

  158. storeFile.createNewFile();

  159. FileOutputStream fos = new FileOutputStream(storeFile);

  160. byte[] arrayOfByte = new byte[1024];

  161. while (true) {

  162. int i = localZipInputStream.read(arrayOfByte);

  163. if (i == -1)

  164. break;

  165. fos.write(arrayOfByte, 0, i);

  166. }

  167. fos.flush();

  168. fos.close();

  169. }

  170. localZipInputStream.closeEntry();

  171. }

  172. localZipInputStream.close();



  173. }



  174. private byte[] readDexFileFromApk() throws IOException {

  175. ByteArrayOutputStream dexByteArrayOutputStream = new ByteArrayOutputStream();

  176. ZipInputStream localZipInputStream = new ZipInputStream(

  177. new BufferedInputStream(new FileInputStream(

  178. this.getApplicationInfo().sourceDir)));

  179. while (true) {

  180. ZipEntry localZipEntry = localZipInputStream.getNextEntry();

  181. if (localZipEntry == null) {

  182. localZipInputStream.close();

  183. break;

  184. }

  185. if (localZipEntry.getName().equals("classes.dex")) {

  186. byte[] arrayOfByte = new byte[1024];

  187. while (true) {

  188. int i = localZipInputStream.read(arrayOfByte);

  189. if (i == -1)

  190. break;

  191. dexByteArrayOutputStream.write(arrayOfByte, 0, i);

  192. }

  193. }

  194. localZipInputStream.closeEntry();

  195. }

  196. localZipInputStream.close();

  197. return dexByteArrayOutputStream.toByteArray();

  198. }



  199. // //直接返回数据,读者可以添加自己解密方法

  200. private byte[] decrypt(byte[] data) {

  201. return data;

  202. }



RefInvoke为反射调用工具类:




三、总结


本文代码基本实现了APK文件的加壳及脱壳原理,该代码作为实验代码还有诸多地方需要改进。比如:

1、加壳数据的加密算法的添加。

2、脱壳代码由java语言实现,可通过C代码的实现对脱壳逻辑进行保护,以达到更好的反逆向分析效果。


原文链接:http://blog.csdn.net/jiazhijun/article/details/8678399


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值