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

移动开发
所谓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文件头中的checksumsignaturefile_size的信息,并且要附加加壳的apk的长度信息在dex文件中,以便我们进行解壳保证原来apk的正常运行。加完壳后整个文件的结构如下:

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

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

具体实现如下:

1)修改原来apkAndroidMainfest.xml文件,假如原来apkAndroidMainfest.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"/>

是原来的apkapplication名称。

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.                   
  37.                 FileOutputStream localFileOutputStream = new FileOutputStream(str); 
  38.                 localFileOutputStream.write(newdex); 
  39.                 localFileOutputStream.flush(); 
  40.                 localFileOutputStream.close(); 
  41.    
  42.    
  43.          } catch (Exception e) { 
  44.                 // TODO Auto-generated catch block 
  45.                 e.printStackTrace(); 
  46.          } 
  47.   } 
  48.     
  49.   //直接返回数据,读者可以添加自己加密方法 
  50.   private static byte[] encrpt(byte[] srcdata){ 
  51.          return srcdata; 
  52.   } 
  53.    
  54.    
  55.   private static void fixCheckSumHeader(byte[] dexBytes) { 
  56.          Adler32 adler = new Adler32(); 
  57.          adler.update(dexBytes, 12, dexBytes.length - 12); 
  58.          long value = adler.getValue(); 
  59.          int va = (int) value; 
  60.          byte[] newcs = intToByte(va); 
  61.          byte[] recs = new byte[4]; 
  62.          for (int i = 0; i < 4; i++) { 
  63.                 recs[i] = newcs[newcs.length - 1 - i]; 
  64.                 System.out.println(Integer.toHexString(newcs[i])); 
  65.          } 
  66.          System.arraycopy(recs, 0, dexBytes, 84); 
  67.          System.out.println(Long.toHexString(value)); 
  68.          System.out.println(); 
  69.   } 
  70.    
  71.    
  72.   public static byte[] intToByte(int number) { 
  73.          byte[] b = new byte[4]; 
  74.          for (int i = 3; i >= 0; i--) { 
  75.                 b[i] = (byte) (number % 256); 
  76.                 number >>= 8
  77.          } 
  78.          return b; 
  79.   } 
  80.    
  81.    
  82.   private static void fixSHA1Header(byte[] dexBytes) 
  83.                 throws NoSuchAlgorithmException { 
  84.          MessageDigest md = MessageDigest.getInstance("SHA-1"); 
  85.          md.update(dexBytes, 32, dexBytes.length - 32); 
  86.          byte[] newdt = md.digest(); 
  87.          System.arraycopy(newdt, 0, dexBytes, 1220); 
  88.          String hexstr = ""
  89.          for (int i = 0; i < newdt.length; i++) { 
  90.                 hexstr += Integer.toString((newdt[i] & 0xff) + 0x10016
  91.                               .substring(1); 
  92.          } 
  93.          System.out.println(hexstr); 
  94.   } 
  95.    
  96.    
  97.   private static void fixFileSizeHeader(byte[] dexBytes) { 
  98.    
  99.    
  100.          byte[] newfs = intToByte(dexBytes.length); 
  101.          System.out.println(Integer.toHexString(dexBytes.length)); 
  102.          byte[] refs = new byte[4]; 
  103.          for (int i = 0; i < 4; i++) { 
  104.                 refs[i] = newfs[newfs.length - 1 - i]; 
  105.                 System.out.println(Integer.toHexString(newfs[i])); 
  106.          } 
  107.          System.arraycopy(refs, 0, dexBytes, 324); 
  108.   } 
  109.    
  110.    
  111.   private static byte[] readFileBytes(File file) throws IOException { 
  112.          byte[] arrayOfByte = new byte[1024]; 
  113.          ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream(); 
  114.          FileInputStream fis = new FileInputStream(file); 
  115.          while (true) { 
  116.                 int i = fis.read(arrayOfByte); 
  117.                 if (i != -1) { 
  118.                        localByteArrayOutputStream.write(arrayOfByte, 0, i); 
  119.                 } else { 
  120.                        return localByteArrayOutputStream.toByteArray(); 
  121.                 } 
  122.          } 
  123.   } 
  124.    
  125.    

?

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.    
  47.    
  48.   public void onCreate() { 
  49.          { 
  50.    
  51.    
  52.                 // 如果源应用配置有Appliction对象,则替换为源应用Applicaiton,以便不影响源程序逻辑。 
  53.                 String appClassName = null
  54.                 try { 
  55.                        ApplicationInfo ai = this.getPackageManager() 
  56.                                      .getApplicationInfo(this.getPackageName(), 
  57.                                                    PackageManager.GET_META_DATA); 
  58.                        Bundle bundle = ai.metaData; 
  59.                        if (bundle != null 
  60.                                      && bundle.containsKey("APPLICATION_CLASS_NAME")) { 
  61.                               appClassName = bundle.getString("APPLICATION_CLASS_NAME"); 
  62.                        } else { 
  63.                               return
  64.                        } 
  65.                 } catch (NameNotFoundException e) { 
  66.                        // TODO Auto-generated catch block 
  67.                        e.printStackTrace(); 
  68.                 } 
  69.    
  70.    
  71.                 Object currentActivityThread = RefInvoke.invokeStaticMethod( 
  72.                               "android.app.ActivityThread""currentActivityThread"
  73.                               new Class[] {}, new Object[] {}); 
  74.                 Object mBoundApplication = RefInvoke.getFieldOjbect( 
  75.                               "android.app.ActivityThread", currentActivityThread, 
  76.                               "mBoundApplication"); 
  77.                 Object loadedApkInfo = RefInvoke.getFieldOjbect( 
  78.                               "android.app.ActivityThread$AppBindData"
  79.                               mBoundApplication, "info"); 
  80.                 RefInvoke.setFieldOjbect("android.app.LoadedApk""mApplication"
  81.                               loadedApkInfo, null); 
  82.                 Object oldApplication = RefInvoke.getFieldOjbect( 
  83.                               "android.app.ActivityThread", currentActivityThread, 
  84.                               "mInitialApplication"); 
  85.                 ArrayList<Application> mAllApplications = (ArrayList<Application>) RefInvoke 
  86.                               .getFieldOjbect("android.app.ActivityThread"
  87.                                             currentActivityThread, "mAllApplications"); 
  88.                 mAllApplications.remove(oldApplication); 
  89.                 ApplicationInfo appinfo_In_LoadedApk = (ApplicationInfo) RefInvoke 
  90.                               .getFieldOjbect("android.app.LoadedApk", loadedApkInfo, 
  91.                                             "mApplicationInfo"); 
  92.                 ApplicationInfo appinfo_In_AppBindData = (ApplicationInfo) RefInvoke 
  93.                               .getFieldOjbect("android.app.ActivityThread$AppBindData"
  94.                                             mBoundApplication, "appInfo"); 
  95.                 appinfo_In_LoadedApk.className = appClassName; 
  96.                 appinfo_In_AppBindData.className = appClassName; 
  97.                 Application app = (Application) RefInvoke.invokeMethod( 
  98.                               "android.app.LoadedApk""makeApplication", loadedApkInfo, 
  99.                               new Class[] { boolean.class, Instrumentation.class }, 
  100.                               new Object[] { falsenull }); 
  101.                 RefInvoke.setFieldOjbect("android.app.ActivityThread"
  102.                               "mInitialApplication", currentActivityThread, app); 
  103.    
  104.    
  105.                 HashMap mProviderMap = (HashMap) RefInvoke.getFieldOjbect( 
  106.                               "android.app.ActivityThread", currentActivityThread, 
  107.                               "mProviderMap"); 
  108.                 Iterator it = mProviderMap.values().iterator(); 
  109.                 while (it.hasNext()) { 
  110.                        Object providerClientRecord = it.next(); 
  111.                        Object localProvider = RefInvoke.getFieldOjbect( 
  112.                                      "android.app.ActivityThread$ProviderClientRecord"
  113.                                      providerClientRecord, "mLocalProvider"); 
  114.                        RefInvoke.setFieldOjbect("android.content.ContentProvider"
  115.                                      "mContext", localProvider, app); 
  116.                 } 
  117.                 app.onCreate(); 
  118.          } 
  119.   } 
  120.    
  121.    
  122.   private void splitPayLoadFromDex(byte[] data) throws IOException { 
  123.          byte[] apkdata = decrypt(data); 
  124.          int ablen = apkdata.length; 
  125.          byte[] dexlen = new byte[4]; 
  126.          System.arraycopy(apkdata, ablen - 4, dexlen, 04); 
  127.          ByteArrayInputStream bais = new ByteArrayInputStream(dexlen); 
  128.          DataInputStream in = new DataInputStream(bais); 
  129.          int readInt = in.readInt(); 
  130.          System.out.println(Integer.toHexString(readInt)); 
  131.          byte[] newdex = new byte[readInt]; 
  132.          System.arraycopy(apkdata, ablen - 4 - readInt, newdex, 0, readInt); 
  133.          File file = new File(apkFileName); 
  134.          try { 
  135.                 FileOutputStream localFileOutputStream = new FileOutputStream(file); 
  136.                 localFileOutputStream.write(newdex); 
  137.                 localFileOutputStream.close(); 
  138.    
  139.    
  140.          } catch (IOException localIOException) { 
  141.                 throw new RuntimeException(localIOException); 
  142.          } 
  143.    
  144.    
  145.          ZipInputStream localZipInputStream = new ZipInputStream( 
  146.                        new BufferedInputStream(new FileInputStream(file))); 
  147.          while (true) { 
  148.                 ZipEntry localZipEntry = localZipInputStream.getNextEntry(); 
  149.                 if (localZipEntry == null) { 
  150.                        localZipInputStream.close(); 
  151.                        break
  152.                 } 
  153.                 String name = localZipEntry.getName(); 
  154.                 if (name.startsWith("lib/") && name.endsWith(".so")) { 
  155.                        File storeFile = new File(libPath + "/" 
  156.                                      + name.substring(name.lastIndexOf('/'))); 
  157.                        storeFile.createNewFile(); 
  158.                        FileOutputStream fos = new FileOutputStream(storeFile); 
  159.                        byte[] arrayOfByte = new byte[1024]; 
  160.                        while (true) { 
  161.                               int i = localZipInputStream.read(arrayOfByte); 
  162.                               if (i == -1
  163.                                      break
  164.                               fos.write(arrayOfByte, 0, i); 
  165.                        } 
  166.                        fos.flush(); 
  167.                        fos.close(); 
  168.                 } 
  169.                 localZipInputStream.closeEntry(); 
  170.          } 
  171.          localZipInputStream.close(); 
  172.    
  173.    
  174.   } 
  175.    
  176.    
  177.   private byte[] readDexFileFromApk() throws IOException { 
  178.          ByteArrayOutputStream dexByteArrayOutputStream = new ByteArrayOutputStream(); 
  179.          ZipInputStream localZipInputStream = new ZipInputStream( 
  180.                        new BufferedInputStream(new FileInputStream( 
  181.                                      this.getApplicationInfo().sourceDir))); 
  182.          while (true) { 
  183.                 ZipEntry localZipEntry = localZipInputStream.getNextEntry(); 
  184.                 if (localZipEntry == null) { 
  185.                        localZipInputStream.close(); 
  186.                        break
  187.                 } 
  188.                 if (localZipEntry.getName().equals("classes.dex")) { 
  189.                        byte[] arrayOfByte = new byte[1024]; 
  190.                        while (true) { 
  191.                               int i = localZipInputStream.read(arrayOfByte); 
  192.                               if (i == -1
  193.                                      break
  194.                               dexByteArrayOutputStream.write(arrayOfByte, 0, i); 
  195.                        } 
  196.                 } 
  197.                 localZipInputStream.closeEntry(); 
  198.          } 
  199.          localZipInputStream.close(); 
  200.          return dexByteArrayOutputStream.toByteArray(); 
  201.   } 
  202.    
  203.    
  204.   // //直接返回数据,读者可以添加自己解密方法 
  205.   private byte[] decrypt(byte[] data) { 
  206.          return data; 
  207.   } 
责任编辑:倪明
相关推荐

2015-08-20 10:13:34

2011-03-14 15:52:50

Windows Azu

2014-07-30 14:25:41

SwiftiBeacon

2011-06-21 09:14:01

Oracle查询

2015-05-27 09:32:29

iOS应用架构

2017-04-10 13:43:34

AndroidGradleAS

2022-08-01 08:18:58

网络网络协议

2014-03-28 13:14:33

2021-11-30 19:58:51

Java问题排查

2013-04-15 10:00:14

Hyper-V虚拟化网络

2023-06-26 00:26:40

I/OJava字节流

2018-10-22 12:50:20

CDN网络内容发布网络

2022-03-29 08:18:32

位图算法索引技术

2015-01-15 11:01:43

2021-09-07 09:20:44

Hadoop数据容错

2018-03-20 14:14:48

NB-IoT物联网终端

2017-11-20 15:09:21

2013-12-10 09:50:03

技术技术博客

2022-05-30 21:47:21

技术目标PRD

2021-12-17 14:27:52

jar反编译Java
点赞
收藏

51CTO技术栈公众号