
一、什么是加壳?
加壳是在二进制的程序中植入一段代码,在运行的时候优先取得程序的控制权,做一些额外的工作。大多数病毒就是基于此原理。
二、加壳作用
加壳的程序可以有效阻止对程序的反汇编分析,以达到它不可告人的目的。这种技术也常用来保护软件版权,防止被软件破解。
三、AndroID Dex文件加壳原理
PC平台现在已存在大量的标准的加壳和解壳工具,但是AndroID作为新兴平台还未出现APK加壳工具。AndroID Dex文件大量使用引用给加壳带来了一定的难度,但是从理论上讲,AndroID APK加壳也是可行的。
在这个过程中,牵扯到三个角色:
1、加壳程序:加密源程序为解壳数据、组装解壳程序和解壳数据
2、解壳程序:解密解壳数据,并运行时通过DexClassLoader动态加载
3、源程序:需要加壳处理的被保护代码
根据解壳数据在解壳程序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文件。
七、加壳程序流程及代码实现
1、加密源程序APK为解壳数据
2、把解壳数据写入解壳程序DEX文件末尾,并在文件尾部添加解壳数据的大小。
3、修改解壳程序DEX头中checksum、signature 和file_size头信息。
代码实现如下:
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 { /** * @param args */ public static voID main(String[] args) { // Todo auto-generated method stub 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,newdex,unShellDexLen); //添加加密后的解壳数据 System.arraycopy(payloadArray,unShellDexLen,payloadLen); //添加解壳数据长度 System.arraycopy(intToByte(payloadLen),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) { // Todo auto-generated catch block 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,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,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,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,i); } else { return localByteArrayOutputStream.toByteArray(); } } } }
八、解壳程序流程及代码实现
在解壳程序的开发过程中需要解决如下几个关键的技术问题:
1.解壳代码如何能够第一时间执行?
AndroID程序由不同的组件构成,系统在有需要的时候启动程序组件。因此解壳程序必须在AndroID系统启动组件之前运行,完成对解壳数据的解壳及APK文件的动态加载,否则会使程序出现加载类失败的异常。
AndroID开发者都知道Applicaiton做为整个应用的上下文,会被系统第一时间调用,这也是应用开发者程序代码的第一执行点。因此通过对AndroIDMainfest.xml的application的配置可以实现解壳代码第一时间运行。
<application androID:icon="@drawable/ic_launcher" androID:label="@string/app_name" androID:theme="@style/Apptheme" androID:name=" </application>
2.如何替换回源程序原有的Application?
当在AndroIDMainfest.xml文件配置为解壳代码的Application时。源程序原有的Applicaiton将被替换,为了不影响源程序代码逻辑,我们需要 在解壳代码运行完成后,替换回源程序原有的Application对象。我们通过在AndroIDMainfest.xml文件中配置原有Applicaiton类信息来达到我们 的目的。解壳程序要在运行完毕后通过创建配置的Application对象,并通过反射修改回原Application。
<application androID:icon="@drawable/ic_launcher" androID:label="@string/app_name" androID:theme="@style/Apptheme" androID:name=" </application>
3.如何通过DexClassLoader实现对apk代码的动态加载。
我们知道DexClassLoader加载的类是没有组件生命周期的,也就是说即使DexClassLoader通过对APK的动态加载完成了对组件类的加载,当系统启动该组件时,还会出现加载类失败的异常。为什么组件类被动态加载入虚拟机,但系统却出现加载类失败呢?
通过查看AndroID源代码我们知道组件类的加载是由另一个ClassLoader来完成的,DexClassLoader和系统组件ClassLoader并不存在关系,系统组件ClassLoader当然找不到由DexClassLoader加载的类,如果把系统组件ClassLoader的parent修改成DexClassLoader,我们就可以实现对apk代码的动态加载。
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 dalvik.system.DexClassLoader; import androID.app.Application; import androID.content.pm.ApplicationInfo; import androID.content.pm.PackageManager; import androID.content.pm.PackageManager.nameNotFoundException; import androID.os.Bundle; 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() { // Todo auto-generated method stub 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) { // Todo auto-generated catch block 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",dLoader); //如果源应用配置有Appliction对象,则替换为源应用Applicaiton,以便不影响源程序逻辑。 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","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","mInitialApplication"); RefInvoke.setFIEldOjbect("androID.app.ActivityThread","mInitialApplication",app); ArrayList<Application> mAllApplications = (ArrayList<Application>)RefInvoke.getFIEldOjbect("androID.app.ActivityThread","mAllApplications"); mAllApplications.remove(oldApplication); mAllApplications.add(app); HashMap mProvIDerMap = (HashMap) RefInvoke.getFIEldOjbect("androID.app.ActivityThread","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",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,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,readInt); file file = new file(apkfilename); try { fileOutputStream localfileOutputStream = new fileOutputStream(file); localfileOutputStream.write(newdex); localfileOutputStream.close(); } catch (IOException localiOException) { throw new RuntimeException(localiOException); } 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,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,i); } } localZipinputStream.closeEntry(); } localZipinputStream.close(); return dexByteArrayOutputStream.toByteArray(); } ////直接返回数据,读者可以添加自己解密方法 private byte[] decrypt(byte[] data){ return data; } } RefInvoke为反射调用工具类:
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 (SecurityException e) { // Todo auto-generated catch block e.printstacktrace(); } catch (IllegalArgumentException e) { // Todo auto-generated catch block e.printstacktrace(); } catch (illegalaccessexception e) { // Todo auto-generated catch block e.printstacktrace(); } catch (NoSuchMethodException e) { // Todo auto-generated catch block e.printstacktrace(); } catch (InvocationTargetException e) { // Todo auto-generated catch block e.printstacktrace(); } catch (ClassNotFoundException e) { // Todo auto-generated catch block e.printstacktrace(); } return null; } public static Object invokeMethod(String class_name,Object obj,pareTyple); return method.invoke(obj,pareVaules); } catch (SecurityException e) { // Todo auto-generated catch block e.printstacktrace(); } catch (IllegalArgumentException e) { // Todo auto-generated catch block e.printstacktrace(); } catch (illegalaccessexception e) { // Todo auto-generated catch block e.printstacktrace(); } catch (NoSuchMethodException e) { // Todo auto-generated catch block e.printstacktrace(); } catch (InvocationTargetException e) { // Todo auto-generated catch block e.printstacktrace(); } catch (ClassNotFoundException e) { // Todo auto-generated catch block e.printstacktrace(); } return null; } public static Object getFIEldOjbect(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(obj); } catch (SecurityException e) { // Todo auto-generated catch block e.printstacktrace(); } catch (NoSuchFIEldException e) { // Todo auto-generated catch block e.printstacktrace(); } catch (IllegalArgumentException e) { // Todo auto-generated catch block e.printstacktrace(); } catch (illegalaccessexception e) { // Todo auto-generated catch block e.printstacktrace(); } catch (ClassNotFoundException e) { // Todo auto-generated catch block 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 (SecurityException e) { // Todo auto-generated catch block e.printstacktrace(); } catch (NoSuchFIEldException e) { // Todo auto-generated catch block e.printstacktrace(); } catch (IllegalArgumentException e) { // Todo auto-generated catch block e.printstacktrace(); } catch (illegalaccessexception e) { // Todo auto-generated catch block e.printstacktrace(); } catch (ClassNotFoundException e) { // Todo auto-generated catch block e.printstacktrace(); } return null; } public static voID setFIEldOjbect(String classname,String filedname,Object filedVaule){ try { Class obj_class = Class.forname(classname); FIEld fIEld = obj_class.getDeclaredFIEld(filedname); fIEld.setAccessible(true); fIEld.set(obj,filedVaule); } catch (SecurityException e) { // Todo auto-generated catch block e.printstacktrace(); } catch (NoSuchFIEldException e) { // Todo auto-generated catch block e.printstacktrace(); } catch (IllegalArgumentException e) { // Todo auto-generated catch block e.printstacktrace(); } catch (illegalaccessexception e) { // Todo auto-generated catch block e.printstacktrace(); } catch (ClassNotFoundException e) { // Todo auto-generated catch block e.printstacktrace(); } } public static voID setStaticOjbect(String class_name,Object filedVaule){ try { Class obj_class = Class.forname(class_name); FIEld fIEld = obj_class.getDeclaredFIEld(filedname); fIEld.setAccessible(true); fIEld.set(null,filedVaule); } catch (SecurityException e) { // Todo auto-generated catch block e.printstacktrace(); } catch (NoSuchFIEldException e) { // Todo auto-generated catch block e.printstacktrace(); } catch (IllegalArgumentException e) { // Todo auto-generated catch block e.printstacktrace(); } catch (illegalaccessexception e) { // Todo auto-generated catch block e.printstacktrace(); } catch (ClassNotFoundException e) { // Todo auto-generated catch block e.printstacktrace(); } } }
九、总结
本文代码基本实现了APK文件的加壳及脱壳原理,该代码作为实验代码还有诸多地方需要改进。比如:
1、加壳数据的加密算法的添加。
2、脱壳代码由java语言实现,可通过C代码的实现对脱壳逻辑进行保护,以达到更好的反逆向分析效果。
以上是内存溢出为你收集整理的为Android的apk应用程序文件加壳以防止反编译的教程全部内容,希望文章能够帮你解决为Android的apk应用程序文件加壳以防止反编译的教程所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)