android apk 防止反编译技术第一篇-加壳技术

移动开发 Android
所谓apk的加壳技术和pc exe的加壳原理一样,就是在程序的外面再包裹上另外一段代码,保护里面的代码不被非法修改或反编译,在程序运行的时候优先取得程序的控制权做一些我们自己想做的工作。(哈哈,跟病毒的原理差不多)

做android framework方面的工作将近三年的时间了,现在公司让做一下android apk安全方面的研究,于是最近就在网上找大量的资料来学习。现在将最近学习成果做一下整理总结。学习的这些成果我会做成一个系列慢慢写出来与大家分享,共同进步。这篇主要讲apk的加壳技术,废话不多说了直接进入正题。

一、加壳技术原理

所谓apk的加壳技术和pc exe的加壳原理一样,就是在程序的外面再包裹上另外一段代码,保护里面的代码不被非法修改或反编译,在程序运行的时候优先取得程序的控制权做一些我们自己想做的工作。(哈哈,跟病毒的原理差不多)

PC exe的加壳原理如下:

二、android apk加壳实现

要想实现加壳需要解决的技术点如下:

(1)怎么第一时间执行我们的加壳程序?

首先根据上面的原理我们在apk中要想优先取得程序的控制权作为android apk的开发人员都知道Application会被系统第一时间调用而我们的程序也会放在这里执行。

(2)怎么将我们的加壳程序和原有的android apk文件合并到一起?

我们知道android apk最终会打包生成dex文件,我们可以将我们的程序生成dex文件后,将我们要进行加壳的apk和我们dex文件合并成一个文件,然后修改dex文件头中的checksum、signature 和file_size的信息,并且要附加加壳的apk的长度信息在dex文件中,以便我们进行解壳保证原来apk的正常运行。加完壳后整个文件的结构如下:

(3)怎么将原来的apk正常的运行起来?

按照(2)中的合并方式在当我们的程序首先运行起来后,逆向读取dex文件获取原来的apk文件通过DexClassLoader动态加载。

具体实现如下:

(1)修改原来apk的AndroidMainfest.xml文件,假如原来apk的AndroidMainfest.xml文件内容如下:

1. <application

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

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

4. android:theme="@style/AppTheme" android:name="com.android.MyApplication" >

5. </application>

修改后的内容如下:

1. <application

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

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

4. android:theme="@style/AppTheme" android:name="com.android.shellApplication" >

5. <meta-data android:name="APPLICATION_CLASS_NAME" android:value="com.android.MyApplication"/>

6. </application>

com.android.shellApplication这个就是我们的程序的的application的名称,而

7. <meta-data android:name="APPLICATION_CLASS_NAME" android:value="com.android.MyApplication"/>

是原来的apk的application名称。

(2)合并文件代码实现如下:
?

  1. public class ShellTool { 
  2. /** 
  3. * @param args 
  4. */ 
  5. public static void main(String[] args) { 
  6. // TODO Auto-generated method stub 
  7. try { 
  8. File payloadSrcFile = new File("payload.apk");//我们要加壳的apk文件 
  9. File unShellDexFile = new File("classes.dex");//我们的程序生成的dex文件 
  10. byte[] payloadArray = encrpt(readFileBytes(payloadSrcFile)); 
  11. byte[] unShellDexArray = readFileBytes(unShellDexFile); 
  12. int payloadLen = payloadArray.length; 
  13. int unShellDexLen = unShellDexArray.length; 
  14. int totalLen = payloadLen + unShellDexLen +4
  15. byte[] newdex = new byte[totalLen]; 
  16. //添加我们程序的dex 
  17. System.arraycopy(unShellDexArray, 0, newdex, 0, unShellDexLen); 
  18. //添加要加壳的apk文件 
  19. System.arraycopy(payloadArray, 0, newdex, unShellDexLen, 
  20. payloadLen); 
  21. //添加apk文件长度 
  22. System.arraycopy(intToByte(payloadLen), 0, newdex, totalLen-44); 
  23. //修改DEX file size文件头 
  24. fixFileSizeHeader(newdex); 
  25. //修改DEX SHA1 文件头 
  26. fixSHA1Header(newdex); 
  27. //修改DEX CheckSum文件头 
  28. fixCheckSumHeader(newdex); 
  29.  
  30.  
  31. String str = "outdir/classes.dex"
  32. File file = new File(str); 
  33. if (!file.exists()) { 
  34. file.createNewFile(); 
  35.  
  36. FileOutputStream localFileOutputStream = new FileOutputStream(str); 
  37. localFileOutputStream.write(newdex); 
  38. localFileOutputStream.flush(); 
  39. localFileOutputStream.close(); 
  40.  
  41.  
  42. catch (Exception e) { 
  43. // TODO Auto-generated catch block 
  44. e.printStackTrace(); 
  45.  
  46. //直接返回数据,读者可以添加自己加密方法 
  47. private static byte[] encrpt(byte[] srcdata){ 
  48. return srcdata; 
  49.  
  50.  
  51. private static void fixCheckSumHeader(byte[] dexBytes) { 
  52. Adler32 adler = new Adler32(); 
  53. adler.update(dexBytes, 12, dexBytes.length - 12); 
  54. long value = adler.getValue(); 
  55. int va = (int) value; 
  56. byte[] newcs = intToByte(va); 
  57. byte[] recs = new byte[4]; 
  58. for (int i = 0; i < 4; i++) { 
  59. recs[i] = newcs[newcs.length - 1 - i]; 
  60. System.out.println(Integer.toHexString(newcs[i])); 
  61. System.arraycopy(recs, 0, dexBytes, 84); 
  62. System.out.println(Long.toHexString(value)); 
  63. System.out.println(); 
  64.  
  65.  
  66. public static byte[] intToByte(int number) { 
  67. byte[] b = new byte[4]; 
  68. for (int i = 3; i >= 0; i--) { 
  69. b[i] = (byte) (number % 256); 
  70. number >>= 8
  71. return b; 
  72.  
  73.  
  74. private static void fixSHA1Header(byte[] dexBytes) 
  75. throws NoSuchAlgorithmException { 
  76. MessageDigest md = MessageDigest.getInstance("SHA-1"); 
  77. md.update(dexBytes, 32, dexBytes.length - 32); 
  78. byte[] newdt = md.digest(); 
  79. System.arraycopy(newdt, 0, dexBytes, 1220); 
  80. String hexstr = ""
  81. for (int i = 0; i < newdt.length; i++) { 
  82. hexstr += Integer.toString((newdt[i] & 0xff) + 0x10016
  83. .substring(1); 
  84. System.out.println(hexstr); 
  85.  
  86.  
  87. private static void fixFileSizeHeader(byte[] dexBytes) { 
  88.  
  89.  
  90. byte[] newfs = intToByte(dexBytes.length); 
  91. System.out.println(Integer.toHexString(dexBytes.length)); 
  92. byte[] refs = new byte[4]; 
  93. for (int i = 0; i < 4; i++) { 
  94. refs[i] = newfs[newfs.length - 1 - i]; 
  95. System.out.println(Integer.toHexString(newfs[i])); 
  96. System.arraycopy(refs, 0, dexBytes, 324); 
  97.  
  98.  
  99. private static byte[] readFileBytes(File file) throws IOException { 
  100. byte[] arrayOfByte = new byte[1024]; 
  101. ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream(); 
  102. FileInputStream fis = new FileInputStream(file); 
  103. while (true) { 
  104. int i = fis.read(arrayOfByte); 
  105. if (i != -1) { 
  106. localByteArrayOutputStream.write(arrayOfByte, 0, i); 
  107. else { 
  108. return localByteArrayOutputStream.toByteArray(); 
  109.  
  110.  

(3)在我们的程序中加载运行原来的apk文件,代码如下:

  1. public class shellApplication extends Application { 
  2.  
  3.  
  4. private static final String appkey = "APPLICATION_CLASS_NAME"
  5. private String apkFileName; 
  6. private String odexPath; 
  7. private String libPath; 
  8.  
  9.  
  10. protected void attachBaseContext(Context base) { 
  11. super.attachBaseContext(base); 
  12. try { 
  13. File odex = this.getDir("payload_odex", MODE_PRIVATE); 
  14. File libs = this.getDir("payload_lib", MODE_PRIVATE); 
  15. odexPath = odex.getAbsolutePath(); 
  16. libPath = libs.getAbsolutePath(); 
  17. apkFileName = odex.getAbsolutePath() + "/payload.apk"
  18. File dexFile = new File(apkFileName); 
  19. if (!dexFile.exists()) 
  20. dexFile.createNewFile(); 
  21. // 读取程序classes.dex文件 
  22. byte[] dexdata = this.readDexFileFromApk(); 
  23. // 分离出解壳后的apk文件已用于动态加载 
  24. this.splitPayLoadFromDex(dexdata); 
  25. // 配置动态加载环境 
  26. Object currentActivityThread = RefInvoke.invokeStaticMethod( 
  27. "android.app.ActivityThread""currentActivityThread"
  28. new Class[] {}, new Object[] {}); 
  29. String packageName = this.getPackageName(); 
  30. HashMap mPackages = (HashMap) RefInvoke.getFieldOjbect( 
  31. "android.app.ActivityThread", currentActivityThread, 
  32. "mPackages"); 
  33. WeakReference wr = (WeakReference) mPackages.get(packageName); 
  34. DexClassLoader dLoader = new DexClassLoader(apkFileName, odexPath, 
  35. libPath, (ClassLoader) RefInvoke.getFieldOjbect( 
  36. "android.app.LoadedApk", wr.get(), "mClassLoader")); 
  37. RefInvoke.setFieldOjbect("android.app.LoadedApk""mClassLoader"
  38. wr.get(), dLoader); 
  39.  
  40.  
  41. catch (Exception e) { 
  42. // TODO Auto-generated catch block 
  43. e.printStackTrace(); 
  44.  
  45.  
  46. public void onCreate() { 
  47.  
  48.  
  49. // 如果源应用配置有Appliction对象,则替换为源应用Applicaiton,以便不影响源程序逻辑。 
  50. String appClassName = null
  51. try { 
  52. ApplicationInfo ai = this.getPackageManager() 
  53. .getApplicationInfo(this.getPackageName(), 
  54. PackageManager.GET_META_DATA); 
  55. Bundle bundle = ai.metaData; 
  56. if (bundle != null 
  57. && bundle.containsKey("APPLICATION_CLASS_NAME")) { 
  58. appClassName = bundle.getString("APPLICATION_CLASS_NAME"); 
  59. else { 
  60. return
  61. catch (NameNotFoundException e) { 
  62. // TODO Auto-generated catch block 
  63. e.printStackTrace(); 
  64.  
  65.  
  66. Object currentActivityThread = RefInvoke.invokeStaticMethod( 
  67. "android.app.ActivityThread""currentActivityThread"
  68. new Class[] {}, new Object[] {}); 
  69. Object mBoundApplication = RefInvoke.getFieldOjbect( 
  70. "android.app.ActivityThread", currentActivityThread, 
  71. "mBoundApplication"); 
  72. Object loadedApkInfo = RefInvoke.getFieldOjbect( 
  73. "android.app.ActivityThread$AppBindData"
  74. mBoundApplication, "info"); 
  75. RefInvoke.setFieldOjbect("android.app.LoadedApk""mApplication"
  76. loadedApkInfo, null); 
  77. Object oldApplication = RefInvoke.getFieldOjbect( 
  78. "android.app.ActivityThread", currentActivityThread, 
  79. "mInitialApplication"); 
  80. ArrayList<Application> mAllApplications = (ArrayList<Application>) RefInvoke 
  81. .getFieldOjbect("android.app.ActivityThread"
  82. currentActivityThread, "mAllApplications"); 
  83. mAllApplications.remove(oldApplication); 
  84. ApplicationInfo appinfo_In_LoadedApk = (ApplicationInfo) RefInvoke 
  85. .getFieldOjbect("android.app.LoadedApk", loadedApkInfo, 
  86. "mApplicationInfo"); 
  87. ApplicationInfo appinfo_In_AppBindData = (ApplicationInfo) RefInvoke 
  88. .getFieldOjbect("android.app.ActivityThread$AppBindData"
  89. mBoundApplication, "appInfo"); 
  90. appinfo_In_LoadedApk.className = appClassName; 
  91. appinfo_In_AppBindData.className = appClassName; 
  92. Application app = (Application) RefInvoke.invokeMethod( 
  93. "android.app.LoadedApk""makeApplication", loadedApkInfo, 
  94. new Class[] { boolean.class, Instrumentation.class }, 
  95. new Object[] { falsenull }); 
  96. RefInvoke.setFieldOjbect("android.app.ActivityThread"
  97. "mInitialApplication", currentActivityThread, app); 
  98.  
  99.  
  100. HashMap mProviderMap = (HashMap) RefInvoke.getFieldOjbect( 
  101. "android.app.ActivityThread", currentActivityThread, 
  102. "mProviderMap"); 
  103. Iterator it = mProviderMap.values().iterator(); 
  104. while (it.hasNext()) { 
  105. Object providerClientRecord = it.next(); 
  106. Object localProvider = RefInvoke.getFieldOjbect( 
  107. "android.app.ActivityThread$ProviderClientRecord"
  108. providerClientRecord, "mLocalProvider"); 
  109. RefInvoke.setFieldOjbect("android.content.ContentProvider"
  110. "mContext", localProvider, app); 
  111. app.onCreate(); 
  112.  
  113.  
  114. private void splitPayLoadFromDex(byte[] data) throws IOException { 
  115. byte[] apkdata = decrypt(data); 
  116. int ablen = apkdata.length; 
  117. byte[] dexlen = new byte[4]; 
  118. System.arraycopy(apkdata, ablen - 4, dexlen, 04); 
  119. ByteArrayInputStream bais = new ByteArrayInputStream(dexlen); 
  120. DataInputStream in = new DataInputStream(bais); 
  121. int readInt = in.readInt(); 
  122. System.out.println(Integer.toHexString(readInt)); 
  123. byte[] newdex = new byte[readInt]; 
  124. System.arraycopy(apkdata, ablen - 4 - readInt, newdex, 0, readInt); 
  125. File file = new File(apkFileName); 
  126. try { 
  127. FileOutputStream localFileOutputStream = new FileOutputStream(file); 
  128. localFileOutputStream.write(newdex); 
  129. localFileOutputStream.close(); 
  130.  
  131.  
  132. catch (IOException localIOException) { 
  133. throw new RuntimeException(localIOException); 
  134.  
  135.  
  136. ZipInputStream localZipInputStream = new ZipInputStream( 
  137. new BufferedInputStream(new FileInputStream(file))); 
  138. while (true) { 
  139. ZipEntry localZipEntry = localZipInputStream.getNextEntry(); 
  140. if (localZipEntry == null) { 
  141. localZipInputStream.close(); 
  142. break
  143. String name = localZipEntry.getName(); 
  144. if (name.startsWith("lib/") && name.endsWith(".so")) { 
  145. File storeFile = new File(libPath + "/" 
  146. + name.substring(name.lastIndexOf('/'))); 
  147. storeFile.createNewFile(); 
  148. FileOutputStream fos = new FileOutputStream(storeFile); 
  149. byte[] arrayOfByte = new byte[1024]; 
  150. while (true) { 
  151. int i = localZipInputStream.read(arrayOfByte); 
  152. if (i == -1
  153. break
  154. fos.write(arrayOfByte, 0, i); 
  155. fos.flush(); 
  156. fos.close(); 
  157. localZipInputStream.closeEntry(); 
  158. localZipInputStream.close(); 
  159.  
  160.  
  161.  
  162.  
  163. private byte[] readDexFileFromApk() throws IOException { 
  164. ByteArrayOutputStream dexByteArrayOutputStream = new ByteArrayOutputStream(); 
  165. ZipInputStream localZipInputStream = new ZipInputStream( 
  166. new BufferedInputStream(new FileInputStream( 
  167. this.getApplicationInfo().sourceDir))); 
  168. while (true) { 
  169. ZipEntry localZipEntry = localZipInputStream.getNextEntry(); 
  170. if (localZipEntry == null) { 
  171. localZipInputStream.close(); 
  172. break
  173. if (localZipEntry.getName().equals("classes.dex")) { 
  174. byte[] arrayOfByte = new byte[1024]; 
  175. while (true) { 
  176. int i = localZipInputStream.read(arrayOfByte); 
  177. if (i == -1
  178. break
  179. dexByteArrayOutputStream.write(arrayOfByte, 0, i); 
  180. localZipInputStream.closeEntry(); 
  181. localZipInputStream.close(); 
  182. return dexByteArrayOutputStream.toByteArray(); 
  183.  
  184.  
  185. // //直接返回数据,读者可以添加自己解密方法 
  186. private byte[] decrypt(byte[] data) { 
  187. return data; 

 

责任编辑:chenqingxiang 来源: 51CTO
相关推荐

2015-07-20 16:37:11

2017-04-10 13:43:34

AndroidGradleAS

2011-03-14 15:52:50

Windows Azu

2014-03-28 13:14:33

2014-07-30 14:25:41

SwiftiBeacon

2015-07-13 15:52:18

反编译Android APK

2011-06-21 09:14:01

Oracle查询

2015-05-27 09:32:29

iOS应用架构

2022-08-01 08:18:58

网络网络协议

2021-11-30 19:58:51

Java问题排查

2017-07-13 13:13:49

AndroidAPK反编译

2013-04-15 10:00:14

Hyper-V虚拟化网络

2015-01-15 11:01:43

2023-06-26 00:26:40

I/OJava字节流

2018-10-22 12:50:20

CDN网络内容发布网络

2022-03-29 08:18:32

位图算法索引技术

2011-05-31 14:52:13

Android 反编译 方法

2021-09-07 09:20:44

Hadoop数据容错

2018-03-20 14:14:48

NB-IoT物联网终端

2017-11-20 15:09:21

点赞
收藏

51CTO技术栈公众号