An implementation of APK self-protection--run-time self-tampering dalvik instruction "reprint"

Source: Internet
Author: User

People who have played Android development should know that the protection of Android apk is very poor, hard to write code, be someone else turned upside down not to say, was changed the code to change the face of the head and then take out the harm can not endure.

In addition to the SDK, Android's analysis and modification tools have many, Android static analysis tools, the most common is the use of Apktool (see http://code.google.com/p/android-apktool/) anti-compilation apk, The Dalvik bytecode generation Smali assembly, through the Smali compilation of reading analysis, the actual software runtime behavior, search positioning key information points, and then targeted to modify the assembly instructions, and then by Apktool recompile packaging signature generation apk to run, to achieve the purpose of cracking. In addition to Apktool, there are tools such as Ida Pro, Dex2jar combined Jd-gui, and Androguard, among others.

Of course, there are many ways to solve the anti-compilation apk to crack, such as adding confusion, using signature check and so on, here is a way, not the conventional way, but if the user wants to pass the regular static analysis of the code to crack the APK, not only in vain, but also easy to be brought into the ditch.

The method of this article is not original, in the actual work needs to Dalvik instruction analysis statistic, unexpectedly searched to bluebox This article: http://bluebox.com/labs/android-security-challenge/. Unfortunately, they did not provide the source code, can only follow the idea, the realization of their own. The realization of the source code in Https://github.com/freshui/dexBytecodeTamper, interested students can be compared with this article, download down to see, here first say the principle of it (only simple to choose some said, detailed please refer to the Android source document).

1.Dalvik file Format analysis

The format of the Dex file, in Android native code, is described by a dexfile structure:

[CPP]View Plaincopy
  1. struct Dexfile {
  2. Const dexheader* Pheader;
  3. Const dexstringid* Pstringids;
  4. Const dextypeid* Ptypeids;
  5. Const dexfieldid* Pfieldids;
  6. Const dexmethodid* Pmethodids;
  7. Const dexprotoid* Pprotoids;
  8. Const dexclassdef* Pclassdefs;
  9. Const dexlink* Plinkdata;
  10. };

The dexfile structure described above, is directly generated after compilation of the Dex file format, in the APK file (is a zip file, available WinRAR or other decompression tool directly open), Dex file is Classes.dex.

Dalvik format details, you can see the 2008 Google Io:dalvik VM Intenals, said very clearly. The overall structure is simpler than the ELF format, such as (a PPT copied from the Dalvik VM internals), usually composed of 7 parts, the header records some information about the Dalvik file, and marks the location of the remaining portions in the file, while the other parts of the Xxx_ IDs or xxx_defs are actually indexes, and the contents of the index exist in the data section.

One advantage of Dalvik compared to the traditional class file is that all of the constant string sets are managed uniformly, so that you can reduce redundancy (actually I feel, also can't squeeze much, now is a few g of memory, not much meaning), the final Dex file size can also be smaller. In a few parts, the String_ids and Elf string table are somewhat similar, with the position of the offset of each string, and the other parts to reference the string, then use the subscript of the string_ids directly, in the same way as the ELF format index. The index relationship is visible:

Detailed Dex file Introduction will not say, interested can directly look at the Android source code, although the surface looks pretty scary, but its structure and complexity of less than elf, analytic than Elf is simpler.

Odex file format

When the APK is installed, the optimized Dalvik bytecode Odex file is validated and produced by Dexopt. The process is to unzip the Classes.dex in the APK, use dexopt processing, and save to/data/dalvik-cache/[email protected]@<package-name>[ Email protected]. The Odex file resolves dependencies, attaches the list of dependent libraries required for loading to the file, and modifies some instructions to speed up parsing and processing.

The Odex file can be viewed as a superset of the Dex file, with the following structure:

The Dex file as part of the optimized Odex, in this analysis, only need to find the dexfile part from the Odex.

2. dex File parsing

Our goal is to self-modify bytecode. To implement a self-modifying bytecode, you need to first locate the location where you want to modify the code, which requires parsing the Dex file first. Dex files We put in the native code parsing processing, naitive code Analysis of cracking, more complex than Dalvik. Here to the Dex file parsing implementation, you can refer to Dalvik source code, where functions can be used directly, the details can refer to its Dexdump module, code details do not want to say, you can see Dalvik source code or example.

2.1 Locating and modifying files

To modify the Dalvik directive, we need to find the map address of the Odex file to be modified, and then add the writable property to modify it through the mprotect call. The code is as follows:

First, find the location of the Odex file in the process map, and note how Android names the Odex file name in the Dalvik-cache directory:

[CPP]View Plaincopy
  1. void *base = NULL;
  2. int module_size = 0;
  3. Char filename[512];
  4. Simple test Code here!
  5. for (int i=0; i<2; i++) {
  6. sprintf (filename, "/data/dalvik-cache/[email protected]@%s-%[email protected]", "Com.freshui.dextamper", i+  1);
  7. Base = Get_module_base ( -1, filename);
  8. if (base! = NULL) {
  9. Break ;
  10. }
  11. }
  12. if (base = = NULL) {
  13. Aloge ("Can not found module:%s", filename);
  14. return;
  15. }

After you locate the Odex file, you also need to know the size of the Odex file in which to Mprotect modify the properties:

[CPP]View Plaincopy
    1. Module_size = get_module_size ( -1, filename);


Once the Odex file is found, we need to determine the offset of the Dex file in order to parse the Dex file format and find the Dex file offset location:

[CPP]View Plaincopy
    1. Search Dex from Odex
    2. void *dexbase = Searchdexstart (base);
    3. if (checkdexmagic (dexbase) = = false) {
    4. Aloge ("error!  Invalid DEX format at:%p ", dexbase);
    5. return;
    6. }


If you find the offset where Dex is located, you can parse the Dex file header and locate the area of the Dex file for the next resolution:

[CPP]View Plaincopy
  1. Dexheader *dexheader = (Dexheader *) dexbase;
  2. Gdexfile.baseaddr = (u1*) dexbase;
  3. Gdexfile.pheader = Dexheader;
  4. Gdexfile.pstringids = (dexstringid*) ((U4) dexbase+dexheader->stringidsoff);
  5. Gdexfile.ptypeids = (dextypeid*) ((U4) dexbase+dexheader->typeidsoff);
  6. Gdexfile.pmethodids = (dexmethodid*) ((U4) dexbase+dexheader->methodidsoff);
  7. Gdexfile.pfieldids = (dexfieldid*) ((U4) dexbase+dexheader->fieldidsoff);
  8. Gdexfile.pclassdefs = (dexclassdef*) ((U4) dexbase+dexheader->classdefsoff);
  9. Gdexfile.pprotoids = (dexprotoid*) ((U4) dexbase+dexheader->protoidsoff);
  10. Dumpdexheader (Dexheader);
  11. Dumpdexstrings (&gdexfile);
  12. Dumpdextypeids (&gdexfile);
  13. Dumpdexprotos (&gdexfile);
  14. Dumpfieldids (&gdexfile);
  15. Dumpclassdefines (&gdexfile);

Above, have basically determined the information of Dex file, next to modify Dalvik bytecode.

Before you modify the bytecode, you also need to locate the location of the byte code that needs to be modified. The modifications that can be made at the moment are only for the Dalvik instruction section, and the modifications to the other parts are not attempted. The data structure of the Dalvik directive is:

[CPP]View Plaincopy
  1. struct Dexcode {
  2. U2 registerssize;
  3. U2 inssize;
  4. U2 outssize;
  5. U2 triessize;
  6. U4 Debuginfooff; / * file offset to debug Info stream * /
  7. U4 Insnssize; / * Size of the Insns array, in U2 units * /
  8. U2 insns[1];
  9. / * followed by optional U2 padding * /
  10. / * followed by try_item[triessize] * /
  11. / * followed by uleb128 handlerssize * /
  12. / * followed by catch_handler_item[handlerssize] * /
  13. };


The Insns array here holds the Dalvik bytecode. As long as we locate the Dexcode data segment of the related class method, we can tamper with the instruction by modifying the Insns array.

Before you locate the bytecode, you need to navigate to the location of the Dexmethod (because only method has instructions), in the Dexmehod structure, there are members that point to the offsets of the DEXCODE data structure:

[CPP]View Plaincopy
    1. /* Expanded form of Encoded_method */
    2. struct Dexmethod {
    3. U4 Methodidx; / * Index to a method_id_item * /
    4. U4 AccessFlags;
    5. U4 Codeoff; / * file offset to a code_item * /
    6. };

Here, Codeoff is the offset position of the dexcode you are looking for.

To find Dexmethod, we need to find certain information about this method: the class to which it belongs, the function name, the parameter and the return value information, and so on. Once you know this information, you can find the Dexmethod structure through the class_defs and Method_ids tables in the Dex file structure, and eventually return to Dexcode.

The associated code is encapsulated in a function that implements:

[CPP]View Plaincopy
  1. Static const Dexcode *dexfindclassmethod (dexfile *dexfile, const Char *clazz, const char *method)
  2. {
  3. ALOGD ("Found:%s->%s", Clazz, method);
  4. dexclassdata* classdata = Dexfindclassdata (Dexfile, clazz);
  5. if (classdata = = null) return null;
  6. Const DEXCODE* Code = DEXFINDMETHODINSNS (Dexfile, Classdata, method);
  7. if (Code! = NULL) {
  8. Dumpdexcode (code);
  9. }
  10. //dumpdexclassdatamethod (&gdexfile, classdata);
  11. return code;
  12. }

Once you have found Dexcode, you can modify the instructions:

[CPP]View Plaincopy
  1. Const Dexcode *code =
  2. Dexfindclassmethod (&gdexfile, "Lcom/freshui/dextemper/gamecontrol;", "Setscorehidden");
  3. Const Dexcode *code2 = Dexfindclassmethod (&gdexfile, "Lcom/freshui/dextemper/gamecontrol;", "SetScore");
  4. REMAP!!!!
  5. if (Mprotect (base, module_size, Prot_read | Prot_write | prot_exec) = = 0) {
  6. ALOGD ("Found the Odex module at:%p [%x]", base, module_size);
  7. Dexcode *pcode = (Dexcode *) Code2;
  8. //modify!
  9. Pcode->registerssize = code->registerssize;
  10. For (U4 k=0; k<code->insnssize; k++) {
  11. Pcode->insns[k] = code->insns[k];
  12. }
  13. //Cleanup write PROT
  14. Mprotect (base, module_size, Prot_read | PROT_EXEC);
  15. }


How to modify instructions:

1. As described above, you need to find the offset position of the Dexcode first

2. The memory location of the Odex file map needs to be set, and the memory access permission is mprotect to allow modification.

3. Modify the Dalvik byte code pointed to by Insns in Dexcode

4. Change the access to the memory location of the Odex map back to, of course, does not matter.

Details are not detailed and are interesting to look at the sample code.

One thing to note here: The Dalvik directive is also not modifiable, and it is important to note that size, register, and index cannot have exceptions, and they can only be re-edited for each Dex file. Another important point is the index problem, which does not unfold.

Transferred from: http://blog.csdn.net/freshui/article/details/13620647#comments

An implementation of APK self-protection--run-time self-tampering dalvik instruction "reprint"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.