Solemnly declare:
- 1. Relevant cracking technology is limited to technical research and shall not be used for illegal purposes, otherwise the consequences shall be borne by the user.
- 2. Out of curiosity for the technology, the author does not damage the APP maliciously and respects the labor achievements of the original developer. It is not used for commercial purposes.
0x1 Invisible blade, the most deadly => Read
The last article “Because of a design draft, I stripped the rival APP to the bottom of my pants (1)” is a relatively simple article:
- JSW => Technician text, pooh,
- JSW => Description, pooh pooh,
- JSW => technical text, bah bah bah, this what rubbish input method!
Technical post, but there seems to be something wrong with the ethos of the comment section.
I’ve never been to such a place or experienced such “service”. It’s just hearsay, maybe:
I described the “vivid”, and you see the officer “imagination”, will feel “serious”.
Em… Uh, can you help me up? Uh… Kneel down for a long time… A little numb in the leg…
By the way congratulations: FPX 3-0 G2, Xti S9 champion, FPX awesome!! Broken tone!!
Yasso’s happiness you don’t understand
Haha, back to this article:
- Find => many children are very interested in APP reverse;
- However, online articles about APP reverse are scattered;
- Do not know => how to start, after all, the reverse water can be deep;
- I am just a small white player, interested to play;
- Share => Some “Android APP Basic Reverse poses” currently available;
- Also hope => you really, reverse big guy light spray;
- If there is a better tool or method amway, please point it out in the comments section, thanks ~
By the way, I would like to share a few reverse forums that THE author often visits:
- Watch the snow on bbs.pediy.com/
- My love cracked: www.52pojie.cn/
- Ant security network: bbs.mayidui.net/
- Jiang Wei: www.520monkey.com/
Intimate reminder:
The content of this article is more, may be a little boring, suggest the first click like collection, after lunch and then slowly taste ~
0x2 Captain Timo, On standby => Hardware ready
Before starting to reverse engineer your Android APP, you need to:
1, a “full Root” Android phone, note “full Root” permissions!!
For example, “Meizu mobile phone” can open Root permission under Settings -> Security ->Root permission, but it is “castrated Root permission”, install SuperSu and restart after the balloon has been stuck.
2, how Root? According to their own mobile phone model Baidu and go to all kinds of machine forum (don’t ask me! General common processes:
Remove the BL lock (BootLoader) -> brush third-party Recovery(such as TWRP) -> Card brush Maglisk or SuperSU(Android before 8.0)
3, do not easily try to use which “one key Root” software (mostly cancer, such as KingRoot), of course not can not be used, can burn Bridges, such as my magic blue E2 Root process:
- Install KingRoot(V5.0) grant Root permission, fix Root permission exception, then have full Root permission;
- Then delete KingRoot with “Remove KingRoot”.
- Install SuperSu(v2.8.2), update binaries the normal way, restart, Root is done.
4, recommend some can Root mobile phone?
Google Pixel’s son (true original, fragrant, but not cost-effective), Xiaomi, One Plus, etc.
5. If you have no money to buy an Android phone or you already have a phone that can’t Root, you can try the “Android Emulator”.
AS built-in AVD simulator Root can see “make machine: AS built-in simulator AVD Root and Xposed installation” can also use other third party Android simulator, such AS “night android simulator, BlueStacks blue stack” and so on.
0x3, a little cold awn first, then gun out like a dragon => concept and noun
Before we start messing around with APP reverse, let’s get to know some concepts and nouns
① What is in the APK file?
Channels to obtain APK: Kuan, App Treasure, Wandoujia and other app market download, some also provide “app history version” download. APK is essentially a “compressed package”, change the “.apk suffix “to”.zip suffix “and unzip it, you can see the following directory structure (and possibly other files) :
A brief introduction:
② Compiling APK and decompiling APK
The so-called “compilation” is to package “source code, resource files, etc.” into APK “according to certain” rules “. The official website provides a detailed compilation and construction process diagram:
Outline the process:
Step 1: Resource file processing “AAPT”
- Assets are packaged intact in APK;
- Each resource in res is assigned a resource ID, defined as a constant in R.Java, which generates a resource. Arsc file (resource index table).
Step 2: File “AIDL”
- Convert files with the AIDL suffix to C/ S-side Java code that can be used for process communication.
Source Code “Java Compiler”
- Compile and generate. Class files.
Step 4: Code confusion “ProGuard” (optional)
- Increase decompile difficulty, shorten names to 1-2 letter names, compress (remove invalid classes, attributes, methods, etc.), optimize Bytecode to remove useless structures.
Step 5: Convert the dex to dx.bat.
- Convert all claas files to classes.dex files, class -> Dalvik bytecode, generate constant pool, eliminate redundant data, etc. (Multiple dex files will be generated if the number of methods exceeds 65535)
Package “ApkBuilder”
- Arsc, classes.dex, and other resources are packaged together to generate an unsigned APK.
Step 7: Sign Jarsigner
- Debug or release signing of an unsigned APK.
Align and optimize “zipalign”.
- Offsets all resource files in APK to integer multiples of 4 bytes from the start of the file, resulting in faster access to APK files through memory mapping.
If you want to know more about the build process, you can go to: 10 Minutes to learn about the Android Project build process and “decompile” is the reverse, through some decompile tools, extract the source code, the conversion process is as follows:
“APK = = = = > Dex = = = = > Jar (class files)/Smali = = > Java source”.
③ Reinforcement and peeling
APK is the brainchild of every Android developer, encapsulating what he or she thinks is “awesome and weird technology.” But there are always malicious people who want to exploit your APP, get your source code through some “decompiler” and do whatever they want:
- Add ads: Your app is free, give you some ads, or change it to paid, and get more downloads than you, not mad?
- Crack pay: you application charge, Hook off your detection method, send a crack package, but also spread everywhere, not gas?
- Malicious attacks: reverse request interface rule, batch SMS verification registration, consumption of your SMS pool, etc., not angry?
The “vile” behavior was “outrageous” and resembled something from a classic “action movie” :
- Man aspirant, hard work, sister virtuous, housework;
- Sister every day to do food, such as men come back, eat together, full of vision, talk about the two people in the world;
- Wine after full meal, think XX, can not be described, but was “malicious” neighbor to target;
- As usual, the man went to work, the girl did housework at home, hanging clothes;
- Neighbors on the line, with “lies” to lure sister to open the door, and squeeze the door into;
- Use “violence and intimidation”, や Meumyour sister’s support and resistance, against your will;
- Violently removed the clothes one by one, leaving only the “evil Mosaic”;
- Guarding the last “absolute realm”;
- After a few indescribable moments, he takes the girl for himself and plays with her like a plaything.
Looking at sister “because of emotional overreaction and body convulsions”, crying “pear flowers with rain”, can not help but let a person “heart pity”, like me this emotional blue child:
Always could not help but take out a few pieces of paper, “quietly wipe tears”, wipe, feel dull, a blank, and then began to reflect:
Why wasn’t that neighbor me? Bah…
In addition to “sympathize with the heroine” and “scold the bad guy”, how should avoid this kind of thing happen?
- 1, spend some money, please a “bodyguard” door, bad people want to come in to the bodyguard this pass;
- Give sister “add a lock”, so that the bad guys can not be described, can only hope and sigh.
“Sister” in the example can be regarded as “APK” prepared by us, while “bodyguard” and “locking operation” can be regarded as “APK reinforcement”, and reinforcement is also called “shell”. The definition of shell is as follows:
A “program that protects software from illegal modification or decompilation,” usually runs ahead of the program, takes control, and completes its task of protecting the software.
There are “shell”, naturally also “shell”, that is, to remove the shell, get the source code, also known as “shell”.
About the development of reinforcement technology, see the article: “a table to understand: the most common Android installation package (APK) five generations of reinforcement technology development history and advantages and disadvantages comparison”, but the figure is not very clear, the author relayout, interested readers can have a look:
(4) confusion and counter-confusion
“Confusion” can be likened to the above “evil Mosaic”, a stumbling block to human progress. In the same way that obfuscation makes decompilation more difficult, “de-obfuscation” corresponds to “removing the Mosaic” and trying to restore it to its original form.
0x4, Engine started, ready to go => get APP source code
While the hardening can “prevent decompilation and repackaging” to a certain extent, the hardening of the APP may cause some problems:
Large size, slow startup, compatibility issues, etc
Online “free reinforcement” scheme there are a lot of, peeling tutorial is rotten street, and some disgusting third-party reinforcement will give you add material (360 reinforcement lock screen advertising), and the use of “enterprise reinforcement”, the need to pay a lot of fees, so many apps directly choose “streptomania”. First to explain how to get the unhardened source ~
① Not hardened (author’s tool: ApkTool + JADX)
- Using apkTool: Get “Material resources, Androidmanifest.xml and smali code”
- Using JADx: Convert “classes.dex” to “.java “code
Considerations for using Jadx:
Using JadX-GUI, you can directly open apK to view the source code, but if APK is large (there are several classes. Dex), it will be directly blocked (such as wechat). What I do is to decompile each dex file on the command line, and finally integrate the decompilated folder into the same directory.
This operation is tedious and repetitive, which is most suitable for batch processing, so I wrote a decompiled batch script (as needed) :
"" "
Automatic decompression of APK, batch use of JADX decompilation, the resulting code summary
"" "
import os
import shutil
import zipfile
from datetime import datetime
apk_file_dict = {} # APK path dictionary
Construct APK path dictionary (construct file path list, filter APK, splice)
def init_apk_dict(file_dir):
apk_path_list = list(filter(lambda fp: fp.endswith(".apk"),
list(map(lambda x: os.path.join(file_dir, x), os.listdir(file_dir)))))
index_list = [str(x) for x in range(1, len(apk_path_list) + 1)]
return dict(zip(index_list, apk_path_list))
# Move folders
def move_dir(origin_dir, finally_dir):
shutil.move(origin_dir, finally_dir)
# If folder exists delete rebuild
def deal_dir_existed(path):
if os.path.exists(path):
print("Folder [%s] has been detected, delete..." % path)
shutil.rmtree(path)
os.makedirs(path)
Create a directory if it does not exist
def is_dir_existed(path, mkdir=True):
if mkdir:
if not os.path.exists(path):
os.makedirs(path)
else:
return os.path.exists(path)
Get the path of all files in the directory
def fetch_all_file(file_dir):
return list(map(lambda x: os.path.join(file_dir, x), os.listdir(file_dir)))
Unzip the file to a specific path
def unzip_file(file_name, output_dir):
print("Start unpacking files...")
f = zipfile.ZipFile(file_name, 'r')
for file in f.namelist():
f.extract(file, os.path.join(os.getcwd(), output_dir))
print("File unzipped...")
if __name__ == '__main__':
print("Traverse all APK in the current directory...")
apk_file_dict = init_apk_dict(os.getcwd())
print("Traversed... \n\n============ All APK in the current directory ============\n")
for (k, v) in apk_file_dict.items():
print("%s.%s" % (k, v.split(os.sep)[- 1]))
print("\n%s" % ("=" * 45))
choice_pos = input("%s" % "Please enter the number to decompile APK:")
print("=" * 45.)
choice_apk = apk_file_dict.get(choice_pos)
apk_name = choice_apk.split(os.sep)[- 1] [:4 -] # APK name
Create related folders
crack_dir = os.path.join(os.getcwd(), apk_name) Project root directory
deal_dir_existed(crack_dir)
crack_apktool_dir = os.path.join(crack_dir, "apktool" + os.sep) # APKTool decompile directory
deal_dir_existed(crack_apktool_dir)
crack_jadx_dir = os.path.join(crack_dir, "jadx" + os.sep) # JADX decompile directory
deal_dir_existed(crack_jadx_dir)
crack_temp_dir = os.path.join(crack_dir, "temp" + os.sep) # temporary storage path for decompressed files
deal_dir_existed(crack_temp_dir)
Use APKTool to extract resource files
begin = datetime.now() # timing
print("APKTool extracts resource files...")
os.system("./apktool d %s -f -o %s" % (choice_apk, crack_apktool_dir))
Copy a copy of androidmanifest.xml, res, assets file to the outside
shutil.copy(os.path.join(crack_apktool_dir, "AndroidManifest.xml"), os.path.join(crack_dir, "AndroidManifest.xml"))
shutil.copytree(os.path.join(crack_apktool_dir, "res" + os.sep), os.path.join(crack_dir, "res" + os.sep))
shutil.copytree(os.path.join(crack_apktool_dir, "assets" + os.sep), os.path.join(crack_dir, "assets" + os.sep))
print("Resource file extraction completed")
# Decompile source code using JADX
print("JADX decompile extract source code...")
choice_apk_zip = shutil.copy(choice_apk, choice_apk.replace(".apk".".zip"))
unzip_file(choice_apk_zip, crack_temp_dir)
print("Start decompiling dex files in batches")
for dex in list(filter(lambda fp: fp.endswith(".dex"), fetch_all_file(crack_temp_dir))):
os.system(
"./jadx -d {0} {1}".format(os.path.join(crack_jadx_dir, dex.split(os.sep)[- 1] [:4 -]), dex))
print("Decompiled all dex files.")
Move the resource file in
shutil.move(os.path.join(crack_dir, "AndroidManifest.xml"), os.path.join(crack_jadx_dir, "AndroidManifest.xml"))
shutil.move(os.path.join(crack_dir, "res" + os.sep), os.path.join(crack_jadx_dir, "res" + os.sep))
shutil.move(os.path.join(crack_dir, "assets" + os.sep), os.path.join(crack_jadx_dir, "assets" + os.sep))
Delete temporary folders and compress files
shutil.rmtree(crack_temp_dir)
os.unlink(choice_apk_zip)
end = datetime.now()
print("Close operation ~~~\n Decompilation completed, total time: %s" % (end - begin).seconds)
Copy the code
To do this, you need to drop the apktool stuff into the jadx/build/jadx/bin directory, as shown in the following figure:
Then the terminal type: python3 auto_extract_apk.py, enter the corresponding number, press Enter to compile:
After a moment’s rest:
Tips: I don’t merge multiple classes folders together because some apps have merge conflicts.
Open the decompiled directory, there are the following two folders:
Just use Android Studio to open one of them for your own needs:
- Apktool directory: Decomcompiled content of apktool, used for dynamic debugging of SMALI.
- Jadx directory: Decompiled into Java.
② Anti-confusion (Simplefy, Deguard)
The code is obtained, but open the code, “a bunch of ABCD”, with the dizziness, you can try the “anti-obconfusion”, there are two kinds of solutions, one is through the “code inverse” name, the other is through the “statistical inverse” name.
There are many tools for the first scheme (Jeb2, Simplify, etc.). The former requires payment to crack, the Java version is limited, and the Mac configuration is a bit difficult, so I used the latter: “Simplefy”, Github repository: github.com/CalebFenton… , the use method is also very simple:
Open the terminal and type:
# pull repository code
git clone --recursive https://github.com/CalebFenton/simplify.git
# go to the directory
cd simplify
# compiler
./gradlew fatjar
Copy the code
After compiling, execute the following command to de-obfuscate APK:
# de-obfuscate APK (de-obfuscate APK required, de-obfuscate APK name)
./gradlew build && cp xxx.apk yyy.apk
Copy the code
Wait until the de-obfuscating is complete, then decompile the batch script to go through a wave, open MapFragment comparison:
There are a few more variable names than before the obfuscations, not all of them, but the readability is slightly improved. For example, I don’t have to exclude adCD from adCD to adCD when searching, but the compilation is time-consuming and my computer fan is buzzing.
The second is through the statistical method, using statistics to infer the name: DEGUARD:apk-deguard.com/, open the official website:
Select the APK to be de-obfuscated, Upload it, and wait for the processing to complete!! Don’t close the page!!
After processing, click output.apk and download the apK to the local directory. Also execute the batch script to decomcompile a wave.
Much the same. In addition, de-obfuscation is not 100% true, and there may be some minor errors, such as the following code:
Although decompilation has improved readability, it is recommended to look at it with mixed source code.
③ Unshell (FDex2, Reflecting assistant, dumpDex)
Finally came to a lot of students looking forward to the unshell link, first of all, the author is only “tool party” level, not Native layer, so file debugging! If this section of the tool, you can not take off, or take off the problem, I can not help. See snow there are a lot of people peeling big guy, you can send a post above for help ~
1. Determine what kind of reinforcement
Libjiagu_x86. so, you can use the “MT file manager 2.0” to directly view the files.
2, FDex2 peeling (only applicable to Android 7 or the following version, can take off most free reinforcement on the market, high success rate, recommended)
- ROOT: Install XposedInstaller and FDex2
- ROOT: Install “VirtualXposed” “FDex2”
For example, here is a “free 360 hardened APK”, which is directly decompiled with JADx and imported into AS, but decompiled into classes:
Root: XposedInstall Enable the FDex2 plugin after restarting, follow these steps to remove it:
- Step 1: FDex2 Select the application to be shelled:
- Step 2: Open the application to be unhulled, and then go to the dex output directory in the figure above:
- Step 3: Pull the entire directory onto your computer using the ADB command:
adb root
adb pull /data/user/0/Package name computer folder
Copy the code
- Step 4: “Remove the dex related to reinforcement”, open it in jadX-GUI, and delete the dex when you see the following one
- Step 5: Decompile dex using jadx command and rename the dex in descending order by file size, as shown in the following example:
Sort by file from largest to smallest!!
jadx aaa.dex -d classes
jadx bbb.dex -d classes1
jadx ccc.dex -d classes2
Copy the code
- Delete the classes from the decompiled project and copy them into it:
Ok, debunking successfully, here can also restore APK (two packaging), etc. ~ not root player, install open VirtualXposed, add application: Fdex2 and to be debunked application
If processed, the path of dex is just a little different.
3, reflected master (similar to FDex, download address: www.lanzous.com/b04xxlujg)
Note, also only support Android 7.0 and below, adb installation, Xposed enable plug-in, restart the phone, then open reflection master:
Step 1: Select the APP to be shelled, and open the dialog box
Step 2: Click the six star in the middle to pop up the following dialog box, and long press “Write DEX”.
Step 3: After the data is written, you can find the dex from /storage/emulated/0:
Step 4: Pull on your computer and open it with jadX-GUI.
Ok, that’s the dex we want, the other one is classes2. Dex is related ~ :
4. DumpDex Unshell (Github: github.com/WrBug/dumpD…)
The readme.md of the official repository reads:
If possible, it is recommended to compile by yourself. The process is also very simple:
# 1. Pull the project code locally
git clone https://github.com/WrBug/dumpDex.git
# 2, Open project in AS, wait for compilation to complete
# 3: Delete the signature code in build.gradle
# 4, Click Build -> Build APK on the top menu bar, or go directly to the terminal
The ADB command installs the compiled APK directly on the phone
Adb push the corresponding so to the directory:
adb push lib/armeabi-v7a/libnativeDump.so /data/local/tmp
adb push lib/arm64-v8a/libnativeDump.so /data/local/tmp/libnativeDump64.so
# change permission
adb shell
su
chmod 777 /data/local/tmp/libnativeDump.so
chmod 777 /data/local/tmp/libnativeDump64.so
# temporarily shut down SELinux(will not work after restart, can call getenforce query)
setenfore 0
# 7. Open XposedInstaller to see if DumpDex is enabled. If so, restart the phone
# 8, After boot, open the application that you want to unshell, no need to blink back, then open data/data/ package name to check whether there is a Dump directory
# 9. If multiple dex as shown in the following figure appears, it indicates that the hulling is successful; otherwise, the hulling may fail
# (see if there is an error message), or not supported (e.g. 360 hardened free version only supports the new version, not the old version)
Copy the code
In addition, the dex may not be available, such as an application that uses “Tencent Royal Security” :
Open the dex here with jadX-GUI and a bunch of errors like this:
The reason for this is “instruction set extraction”, open the smali file and you will see:
The method instructions have been replaced by noP (zero), and the tool-handler can be abandoned at this point to debug the so file.
0x? , To be continue
A Python crawler primer written by myself will be available in the comments section, and will be available next Friday
Tips: there are official download links for all the things used in this section!! You can also go to the public number “pat boy” input 000, reply to the corresponding serial number download, thank you ~
References:
- Android Packaging Process
Congratulations “Weare family” between the winning ~ lucky draw on screen in: www.bilibili.com/video/av771…