One 、 Preface

Today we continue to look at cracking apk Knowledge about , In the previous one :Eclipse Dynamic debugging smali Source code cracking apk  Today we're going to focus on how to use IDA To debug Android Medium native Source code , Because now some app, For the sake of safety or efficiency , Will put some important functions into native layer , So in this way , What we talked about earlier Eclipse debugging smali The source code is very weak , Because the core is native layer ,Android In general native The layer uses so The library files , So this article will introduce how to debug so The content of the document , So that we can achieve a higher success rate of cracking .

Two 、 Knowledge preparation

We're talking about debugging so When you file , Let's take a look at the preparation knowledge first :

First of all 、IDA Tool use

A previous article :Android Through static analysis technology to crack apk  Use in IDA Tool static analysis so file , Through analysis arm Instructions , To get cracking information , Like printed log Information , To crack apk Of , At that time, we have already introduced how to use IDA Tools :

There are multiple windows , There are also multiple views , The most used one is :

1、Function Window Corresponding so Function area : Here we can use ctrl+f Search for functions

2、IDA View Corresponding so In the code instruction view : Here we can look at the corresponding functions arm Instruction code

3、Hex View Corresponding so The hexadecimal data view of : We can see arm Data corresponding to instructions, etc


Of course. IDA We also need to know some common shortcut keys :

1、 Powerful F5 The shortcut key can change arm Instructions are converted into readable C Language , Help analyze

First of all, choose to translate C Functions of language , Then press F5:

I saw it , I feel much fresher immediately , The code should look better .

Now we need to do one more step , Namely Restore JNI Function method name
commonly JNI The function method name starts with a pointer and a number , such as v3+676. Then use this address as a method pointer to make a method call , And the first parameter is the pointer itself , such as (v3+676)(v3…). This is actually where we are JNI It's often used in JNIEnv Method . because Ida It doesn't automatically identify these methods , So when we're dealing with so When debugging a file, you often see it, but you can't figure out what this function is doing , Because this function is too abstract . The solution is very simple , Only need to JNIEnv Pointer to do a type conversion can . For example, as mentioned above a1 and v4 The pointer :

We can choose a1 Variable , And then click y key :

Then declare the type as :JNIEnv*.

Let's see after confirmation :

After the modification , Is it a lot clearer in an instant ? Someone else ( It seems to be from the snow forum ) It also sums up all the JNIEnv The number corresponding to the method , Address and method statement :

2、Shirt+F12 Shortcut key , Speed on so All the string contents in the window

occasionally , String is a very important information , Especially when it comes to cracking , It could be the code , Or password library information .

3、Ctrl+S Shortcut key , There are two uses , On normal opening so Of documents IDA View When viewing , You can see so Corresponding Segement Information

You can get it quickly , The beginning and end of a segment , But this position is relative , No so Mapped to the location after memory , About so Section information in , Students who don't know can refer to this article :Android in so File format details   This article is very clear , I'm not going to introduce it here .

When debugging a page ,ctrl+s We can quickly locate what we want to debug so The address of the file mapped to memory :

Because usually a program , There are bound to be multiple so Of documents , For example, systematic so There are a lot of , It's usually in /system/lib below , Of course, we have our own so, Here we see that the starting and ending positions here are this so Files are mapped into memory :

Here we can use cat Command to view the memory mapping information of a process :cat /proc/[pid]/maps

We see how much of the mapping information so file , In fact, this is not many so file , It is so The corresponding difference in the file Segement Information is mapped to... In memory , It's usually code snippets , Data segments, etc , Because we need to debug the code , So we only care about code segments , One of the characteristics of a code segment is that it has execution permission x, So we just need to find out if there is x That's all .

4、G Shortcut key : stay IDA When debugging a page , We can use S Key to quickly jump to the specified memory location

The jump address here , It can be calculated , For example, I want to jump to A function , And then the next breakpoint , So we can use the above ctrl+s Find the so The base address of the beginning of the file's memory , And then use IDA View View in A The relative address of the function , The sum is the absolute address , Then jump to , Like here :

Java_cn_wjdiankong_encryptdemo_MainActivity_isEquals Functional IDA View The relative address in ( That is to say so File address ):E9C

See above so The file is mapped to the base address of memory :74FE4000

So the jump address is :74FE4000+E9C=74FE4E9C

Be careful :

Generally, the base address here is as long as the program does not exit , In operation , Then his value won't change , Because the data of the program has been loaded into the memory , The base address doesn't change , Unless the program exits , Run again and load the data into the memory , And the relative address will never change , It's only in the modification so When you file , The size of the file has changed , Maybe the relative address will change , In other cases it won't change , The relative address is the data in the whole so Location in file .

Here we can see that the function is mapped to the absolute address in memory .

Be careful :

Sometimes we find that after jumping to the designated position , All you see is DCB data , At this point, we choose the function address , Click on P You can see arm Instruction source code :

5、 Debug shortcuts :F8 Step by step debugging ,F7 Step into debugging

After finding the function address above , We can go down the breakpoint , The next breakpoint is simple , Click on the green circle of the signature , Turn it into a red entry , Then we can click F9 Shortcut key , Or click the run button , Ready to run program :

There are also pause and end buttons . After we run it , And then click so Of native function , Trigger breakpoint logic :

Now , We see entering the debug interface , Click on F8 It can be debugged in one step , See a PC Indicator , Actually in arm in PC It's a special register , Used to store the address of the current instruction , This will be introduced to .

All right, come here , Let's talk about IDA In the debug so When you file , Shortcut keys needed :

1、Shift+F12 Take a quick look at so The string information contained in the file

2、F5 The shortcut key can change arm Instructions are converted into readable C Code , You can also use Y key , modify JNIEnv Function method name of

3、Ctrl+S There are two uses , stay IDA View You can see so All segments of the file , On the debug page, you can view all the programs so The file is mapped to the base address of memory

4、G Key can be used in the debug interface , Quickly jump to the specified absolute address , Debug the next breakpoint , Here, if you jump to the destination address , Found to be DCB Data words , Can be used in P key , Just transform , About DCB data , The following will introduce .

5、F7 Key to step into debugging ,F8 Key can be debugged in one step

second 、 frequently-used ARM Instruction set knowledge

We see it above IDA open so after , What you see is pure assembly instruction code , So this requires us to understand the assembly code , It's like we're debugging Java It's the same with layer code , Must be able to smali grammar , Fortunately, , Neither grammar is very complicated , So we just need to know some general syntax and instructions , Let's take a look at arm Addressing mode in instruction , register , Commonly used instructions , After reading these three knowledge points , We will be right arm There is a general understanding of instructions , For watching arm Instruction code also has a general cognition .

1、arm Addressing mode in instruction

1>. Immediate addressing
It's also called immediate addressing , It's a special way of addressing , The operands themselves are contained in the instructions , As long as the fetch instruction fetches the operands . This is called an immediate number , The corresponding addressing method is called immediate addressing . for example :
MOV R0,#64   ;R0  ← 64
2>. Register addressing
Register addressing is to use the value in the register as the operands , Also known as register direct addressing .
for example :ADD R0,R1, R2   ;R0  ← R1 + R2
3>. Register indirection
Register indirect addressing is to use the value in the register as the address , And then get the operands through this address , The operands themselves are stored in memory .
for example :
LDR R0,[R1] ;R0 ←[R1]
4>. Register offset addressing
This is a ARM Instruction set specific addressing , It is in register addressing to get operands and then shift operation , Get the final operands .
for example :
MOV R0,R2,LSL  #3   ;R0 ← R2 * 8 ,R2 The value of is shifted to the left 3 position , The result is given to R0.
5>. Register base address, index address
Register base addressing is also called base addressing , It is based on register indirect addressing . It will register ( This register is generally called the base register ) Add the value in to the address offset given in the instruction , To get an address , Get the operands from this address .
for example :
LDR R0,[R1,#4] ;R0 ←[R1 + 4], take R1 Add... To the content of 4 The address that forms the operands , The obtained operands are stored in the register R0 in .
6>. Multi register addressing
This addressing method can transfer multiple register values at one time . for example :
LDMIA  R0,{R1,R2,R3,R4} ;R1←[R0],R2←[R0+4],R3←[R0+8],R4←[R0+12]
7>. Stack addressing
Stack is a kind of data structure , Press in and out (First In Last Out,FILO) How to work , Use the stack pointer (Stack Pointer, SP) Indicates the current operating position , The stack pointer always points to the top of the stack .
An example of stack addressing is as follows :
STMFD  SP!,{R1-R7, LR} ; take R1-R7, LR Push into the stack . Full decrement stack .
LDMED  SP!,{R1-R7, LR} ; Take the data from the stack back to R1-R7, LR register . Empty decrement stack .

2、ARM Register in

R0-R3: Used to pass function parameters and return values
R4-R6, R8, R10-R11: There are no special rules , It's a general purpose register
R7: Stack frame pointer (Frame Pointer). Point to the previous saved stack frame (stack frame) And link registers (link register, lr) Address on the stack .
R9: operating system Retain
R12: Also called IP(intra-procedure scratch )
R13: Also called SP(stack pointer), It's the top of the stack pointer
R14: Also called LR(link register), Store the return address of the function .
R15: Also called PC(program counter), Points to the current instruction address .

3、ARM The meaning of common instructions in

ADD Give orders
SUB  Minus instruction
STR Put the register contents on the stack
LDR Load the stack into a register
.W Is an optional instruction width specifier . It doesn't affect the behavior of this command , It just ensures that 32 Bit instruction Details of
BL Perform function calls , And make lr Point to the caller (caller) Next instruction for , The return address of the function
BLX ditto , But in ARM and thumb Switching between instruction sets .
CMP Instruction to compare the size of two operands

4、ARM Instruction simple code segment analysis

C Code :

#include <stdio.h>
int func(int a, int b, int c, int d, int e, int f)
    int g = a + b + c + d + e + f;
    return g;

Corresponding ARM Instructions :

add r0, r1   The parameter a And parameters b Add and assign the result to r0
ldr.w r12, [sp]   Take the most important parameter f Load from stack to r12 register
add r0, r2   Put parameters c Add up to r0 On
ldr.w r9, [sp, #4]   Put parameters e Load from stack to r9 register
add r0, r3   Add up d Add up to r0
add r0, r12   Add up parameters f To r0
add r0, r9   Add up parameters e To r0

3、 ... and 、 structure so Case study

Okay , About ARM Knowledge of instruction , That's all , But when we debug the analysis , Certainly can't do the whole understanding , Because itself ARM Instruction syntax is more complex , But fortunately, the university learned assembly language , So I can read it a little bit , If you don't know how to compile, you may need a tutorial , Because we're using IDA analysis so When you file , If you don't know how to assemble , That's not going to work , So we have to understand assembly code , If you meet students who don't understand special instructions , You can search it online .

We have finished our preparation above , One is IDA When it comes to tools , One is ARM Understanding of instructions , Now let's start to operate the knife , For the convenience of starting , Let's write a simple Android native Layer code , Then proceed IDA Can be analyzed .

Here you can use AndroidStudio To build a new simple project , Then create JNI that will do :

Here, by the way AndroidStudio How to proceed in NDK Development of :

First step : Build a new one in the project jni Catalog

The second step : Use javah Generate native The header file

Be careful :

javah Directory of execution , Must be the top layer of the class package name path , And then execute :

javah Class full name

Note that there is no suffix java Oh

The third step : Configure project NDK Catalog

Select the setting of the module and select the line :Open Module Settings

Set up NDK directory


Step four :copy Header file to jni Under the table of contents , Then configure gradle Medium ndk Options

Here you just need to set the compiled module name , Namely so The name of the document , We need to generate the so file , There is also the need to use lib library , Here we see that we use Android Print in log Library file .


Step five : Compile operation , stay build Generate the specified so file ,copy To Engineering libs Under the directory

Okay , So here we are, very quickly AndroidStudio A new Native project , Here's about native The project code doesn't want to explain too much , Namely Java layer

Pass the user's password , then native Did the verification process , Return the verification result to Java Layer can be :


The specific verification process will not be explained here . After we run the project , obtain apk file , Now we're on our crack journey

Four 、 Start cracking so file

Start cracking our compiled apk file

First of all 、 First, we can use the simplest compression software , open apk file , And unzip his so file

We get After the document , Use IDA To open it :

We know that in general so The names of functions and methods in are :Java_ Class name _ Method name

So here we search directly :Java Key words can be used , Or use jd-gui The tool finds the specified native Method

double-click , On the right IDA View See... On the page Java_cn_wjdiankong_encryptdemo_MainActivity_isEquals The instruction code of the function :

We can simply analyze this instruction code :

1>、PUSH {r3-r7,lr} Is save r3,r4,r5,r6,r7,lr To the memory stack , So finally, after performing an operation , You want to go back to lr Point to the place to execute , Of course, to pc 了 , because pc Keep the next one CPU Instructions to be executed , Only give pc, The next instruction will not be executed until lr Where to point

pc: Program register , Keep the next one CPU Instructions to be executed
lr: Connection return register , After the reservation function returns , The next instruction to be executed

This and the last part of the function POP {r3-r7,pc} It's a correspondence .

2>、 And then it calls strlen,malloc,strcpy And so on , Every time you use BLX and BL When instructions call these functions , We all found a rule : Before calling them, they are usually called by MOV Instructions , Used to pass parameter values , Like here R5 What's in it is strlen The parameters of the function ,R0 Namely is_number The parameters of the function , So after we analyze it this way , In the later dynamic debugging process, you can get the entry parameter value of the function , So you can get some important information

3>、 The command after each call to a function with a return value , It's usually a comparison command , such as CMP,CBZ, Or is it strcmp etc. , This is the breakthrough point of our solution , Because the general encryption is no matter how powerful , The last parameter to compare must be the correct password ( Or the correct encrypted password ) And the password we entered ( Or the encrypted input password ), We can get the correct password here , Or the encrypted password :

Come here , We're done with the analysis native Layer cipher comparison function :Java_cn_wjdiankong_encryptdemo_MainActivity_isEquals

If you think it's ARM It's hard to see the instructions , have access to F5 key , Check out his C The language code :

We see here that there are actually two functions at the core :

1>is_number function , We should guess the name of this function to judge whether it is a number , We can use F5 key , Check his correspondence C The language code :

Here's a quick look , Mainly to see return Statement and if Judgment statement , See there's a cycle here , And get _BYTE* Here is the value of the address , And add one more , Then save it to v2 in , If v3 by '\0' Words , Just close the loop , And then make a judgment , Namely v2-48 Is it greater than 9, So here we know 48 The corresponding is ASCII Number in 0, So what's certain here is that : Traverse... With a loop _BYTE* Is the string stored here a number string .

2>get_encrypt_str function , We can guess the name of this function , It gets the encrypted value of the password we entered , Again using F5 Shortcut key to view :

Here we see , The first is a if sentence , Used to determine whether the parameter passed is NULL, If so , Go straight back to , No. , Use strlen Function to get the length of the string and save it to v2 in , And then use malloc Apply for a piece of heap memory , The first pointer is saved to result, Size is v2+1 That is, the length of the string passed in +1, And then it starts to go into the loop , Head pointer result, Assign a value to i The pointer , Start the cycle ,v3 It's through v1-1 Acquired , Is the address of the string passed in by the function , that v6 Is to get the character value of the string passed in , Then subtract 48, Assign a value to v7, Here we can guess , I want to do character conversion here , hold char Turn it into int type , Keep looking down , If v6==48 Words ,v7=1, That is to say, if characters are encountered here '0', Just assign 1, Looking down , See what we got above v7 value , It's used to get key_src The values in the array , So here we double-click key_src Variable , Just jump to his value , Sure enough , Here is an array of characters , See his length is exactly 18, So here we should understand , Here, through the string passed in , Loop through the string , Character acquisition , And then turn it into numbers , Get... In reverse order key_src The characters in , Save to result in . Then return .

Okay , So far, we have analyzed the functions of these two important functions , One is to determine whether the input content is a numeric string , One is to get the password content through the input content , And then with the correct encryption password :ssBCqpBssP The comparison .

second 、 Start using IDA Make debugging settings

Now let's use dynamic debugging to track the incoming string value , And encrypted values , Here we see no printing log Function of , So it's hard to know the specific parameters and register values , So here we need to start debugging , Know the value of the register after each function is executed , We were using the IDA debug so When , The following preparation steps are required :

1、 stay IDA Get under installation directory android_server Command file

stay IDA The installation directory \dbgsrv\android_server, What is this document for ? How does he work ? Let's talk about it :

Do we remember the previous article :Android in run-as The security issues of command   In this article we introduce Android The principle of debugging in , It's actually using gdb and gdbserver To do that ,gdb and gdbserver When debugging , Must be injected into the debugged program process , But not root Equipment , Injection into other processes can only be done with the help of run-as This is the order , So we know , If you want to debug an application process , It has to be injected into him , that IDA debugging so It's the same principle , He needs to inject (Attach additional ) process , To debug , however IDA I didn't make one myself, which is similar to gdbserver Such a tool , That's it android_server 了 , So he needs to run in the device , Guarantee and PC Terminal IDA communicate , For example, get the process information of the device , Specific process of so Memory address , Debugging information, etc .

So we put android_server Saved to the device's /data Under the table of contents , Modify his permissions , And then it has to be in root Operation in environment , Because he has to do the injection process operation , It has to be root.


Be careful :

He's in here /data Under the table of contents , then ./android_server function , Here's a hint IDA Android 32-bit, So we're opening it later IDA It must be 32 Bit IDA, No 64 Bit , Or save it ,IDA After installation, there are two executable programs , One is 32 position , One is 64 Bit , If you don't open it correctly, you will report such an error :

There is also a kind of problem :error: only position independent executables (PIE) are supported

This is mainly Android5.0 The above compilation options are on by default pie, stay 5.0 The following compiled native applications cannot run , There are two solutions , One is to use Android5.0 The following mobile phone operation , Another way is to use IDA6.6+ Version can .

Then we'll see , It's starting to monitor the device's 23946 port , So if you want to make IDA And this android_server communicate , Then we have to let PC Terminal IDA Also connect to this port , Then we need to use adb It's an order of mine :

adb forward tcp: Remote device port number ( Debug the program side ) tcp: Local device port ( Debugged program side )

So here , We can android_server Port forwarding :

And then this time , All we have to do is PC End use IDA Connected to the 23946 This port is OK , Some people are curious about it , Why is the remote port number the same 23946, Because we're using IDA When connecting , Find out IDA He set the port dead , Namely 23946, So we can't customize this port .

We can use netstat Command view port 23946 Usage situation , See is ida Using this port

2、 It's ready up there android_server, The successful running , Let's use it IDA Try to connect , pick up information , Process additional injection

We need to open a IDA, Before opening a IDA It's used to analyze so Of documents , Generally used for static analysis , We need to debug so Words , You need to open a IDA To carry out , So we usually need to open two IDA, It's also called double opening IDA operation . Dynamic static combination strategy .

Remember to choose here Go This option , It just doesn't need to open so The file , Entry is a blank page :

We choose Debugger Options , choice Attach, See there's a lot debugger, So IDA The tools are really powerful , Do a lot debugger Compatibility , You can debug many programs on different platforms . Here we choose Android debugger:

See here , The port is dead :23946, It can't be modified , So the top adb forward Port forwarding must be 23946. here PC The local machine is the debugging side , therefore host It's native ip Address :, Click ok :

Here you can see all the process information listed in the device , All of them are android_server What to do , Get device process information and pass it to IDA To display .

Be careful :

If we didn't use it root Identity to run android_server:

Here it will be IDA It will not enumerate the process information of the device :

There's one more thing to pay attention to , Namely IDA and android_server Be consistent .

We can ctrl+F Search for processes we need to debug , Of course, here we have to run the process we need to debug , Otherwise, the process will not be found

Double click on the process , You can enter the debug page :

Why does it break here What about China? ?

android In the system libc yes c The most basic function library in layer ,libc Encapsulated io、 file 、socket And so on . All upper level calls need to go through libc Package layer . therefore Is the most basic , So it's going to break here , And we also need to know some common systems so, such as linker:

We know , This linker Is used to load so Module of file , So we're going to analyze how to .init_array Bottom breakpoint

The other one is file , He contains DVM All the underlying loads in dex Some of the ways :

We need to do dynamic debugging later dump After encryption dex file , You need to debug this so The file .

3、 Find the function address , Lower breakpoint , Start debugging

We use Ctrl+S Find out what needs to be debugged so The base address :74FE4000

And then through another IDA open so file , Look at the relative address of the function :E9C

So the absolute address of the function is :74FE4E9C, Use G Key to quickly jump to this absolute address :

Jump to the specified address , Start the next breakpoint , Click the green dot on the far left to go down the breakpoint :

Then click the green button in the upper left corner , function , You can also use F9 Key run program :

We click the button in the program :

Trigger native Function operation :

I saw it , It's in the debugging phase , Now , We can use F8 Single step debugging ,F7 Step into debugging :

We click F8 Single step debugging , achieve is_number Function calls out , notice R0 Is the value of the parameter in and out , We can see R0 The contents of the register , And then I saw it was 123456, This is Java Layer pass in password string , Then go down :

Here is the is_number The return value of the function is saved to R0 In storage , And then call CBZ Instructions , Judge whether it is 0, If 0 Jump to locret_74FE4EEC It's about , see R0 The value of the register is not 0, Keep going down :

I saw it get_encrypt_str Function call , The return value of the function is stored in R1 In the register , View content :zytyrTRA*B 了 , So see , From the top :123456=》zytyrTRA*B 了 , We analyzed it statically get_encrypt_str The logic of a function , Keep looking down :

I saw it , Here, we combine the above string with ssBCqpBssP The comparison , So here ssBCqpBssP It's the correct encryption password , So our current resources are :

Correct encryption password :ssBCqpBssP, Encryption keystore :zytyrTRA*BniqCPpVs, Encryption logic get_encrypt_str

So we can write a reverse encryption method , To parse the correct encryption password to get the value , Here to give you a chance to crack , The correct answer will not be published here , This apk I'll upload it later , Students with itchy hands can try to crack it .

encryption apk Download address :

Third 、 summary IDA The process of debugging

Come here , We analyzed how to crack apk The process of , Let's summarize :

1、 We do it by decompressing apk file , Get the corresponding so file , And then use IDA Tool open so, Find the designated native Layer function

2、 adopt IDA Some of the shortcuts in :F5,Ctrl+S,Y Static analysis of functions by equal bond arm Instructions , General understanding of the function execution process

3、 Open one again IDA To debug it so

1> take IDA In the directory android_server Copy to the specified directory of the device , modify android_server Operation authority of , use Root Identity running android_server

2> Use adb forward Port forwarding , Let remote debugging end IDA You can connect to the debugged end

3> Use IDA Connect to the forwarding port , View all processes on the device , Find the process we need to debug .

4> By opening the so file , Find the relative address of the function to be debugged , Then use... On the debug page Ctrl+S find so The base address of the file , Add it up to get the absolute address , Use G key , Jump to the address of the function , Make a good breakpoint . Click Run or F9 key .

5> Trigger native Functions of layers , Use F8 and F7 Single step debugging , Look at the values in the key registers , For example, the parameters of a function , And the return value of the function

The conclusion is : In the debug so When , It needs double opening IDA, Dynamic static analysis .

5、 ... and 、 Use IDA To solve the anti debugging problem

So here we end our crack journey ? The answer is No , Because we see that the above example is actually my own first one apk, The purpose is to show you , How to use IDA For dynamic debugging so, Now we have a case of hand-in-hand operation , Namely 2014 year , The second question of Ali security challenge :AliCrackme_2:

Ali can really create atmosphere , Remember the first problem we solved , I saw the second question this time , ok , Let's take a look at the cracking process :

use first aapt Order to see his AndroidManifest.xml file , Get access to Activity class :

And then use dex2jar and jd-gui Check out his source code class :com.yaotong.crackme.MainActivity:

notice , His judgment , yes securityCheck Method , It's a native Layer of , So at this time, we go to decompress apk file , Get him so file , Use IDA Open view native The relative address of the function :11A8

there ARM The instruction code is no longer being analyzed , You can check it by yourself , Let's go straight to debugging :

Opening a IDA Do associated debugging :

Select the corresponding debugging process , Then determine :

Use Ctrl+S Key to find the corresponding so The base address of the file :74EA9000

Add the relative address above to get the absolute address :74EA9000+11A8=74EAA1A8   Use G Key to jump directly to this address :

Next breakpoint , And then click F9 Run the program :

wipe ,IDA Exit the debug page , Let's go back to the debug page , function , Still exit the debug page , Okay , This egg hurts , No way to debug .

In fact, Ali did anti debugging investigation , If you find that your program has been debugged , Just exit the program , So there's a problem , Why do you know it's anti debugging ? This mainly depends on our own cracking experience , There's no technology , Another is how Ali implements the anti debugging strategy , This is limited to space , Just a brief introduction to the principle :

It was said that ,IDA It's using android_server stay root Environment into the process being debugged , So one of the techniques used here is Linux Medium ptrace, I won't explain it here , You can search by yourself ptrace Knowledge about , that Android If one process is replaced by another process ptrace After that , In his status There is a field in the file :TracerPid It can identify which process is being used trace 了 , We can use commands to view our debugged progress information :

status The file in :/proc/[pid]/status

I saw it , The process here is 9187 process trace 了 , We were using the ps Order to see 9187 Which process :

Sure enough , It is our android_server process , Okay , We know how it works , I also roughly guessed that Ali did a loop detection at the bottom. If this field is not 0, So representing your own progress is being trace, Then stop and exit the program , This anti detection technology is used in many security areas , It's also an important knowledge point .

Now let's take a look at how to deal with this anti debugging ?

We just saw , Just run the program , You exit the debug interface , explain , This loop detection program is executed very early , So the two earliest times we know now are : One is .init_array, One is JNI_OnLoad

.init_array It's a so First loaded segment information , The earliest time , Now it's normal so Decryption operations are all done here

JNI_OnLoad yes so By System.loadLibrary When called , What's his timing before native Method execution , But no .init_array The time is early

So with these two opportunities , Now let's see if we are JNI_OnLoad The strategy in the function , So we need to debug dynamically first JNI_OnLoad function

Now that we know JNI_OnLoad The timing of the function , If Ali puts the detection function here , We can't debug in the same way as before , Because it's too late to do that before , As long as it's running, it's already executed JNI_OnLoad function , So you exit the debug page , Fortunately here IDA Provided in so file load The timing of , All we need to do is Debug Option Just set it up in :

On the debug page Debugger choice Debugger Option Options :

Then check it out. Suspend on library load/unload that will do

After setting this way , Not yet. , Because our program is already running , It's just static Load... In the code block so The file ,static It's very early , So at this point , We need to stop the program loading so Just before the file .

So what I think of is adding code waitForDebugger Code. , The way is to wait debug, We remember debugging before smali Code time , This is the way to stop the program and start it , And wait for us to use jdb Conduct attach operation .

So this time we can System.loadLibrary Method waitForDebugger The code can be , But we don't do that here , There's a simpler way to do that is to use am command , In itself am Command can start a program , Yes, of course debug Mode start :

adb shell am start -D -n com.yaotong.crackme/.MainActivity

An important parameter here is -D, use debug Mode start

After running , The device is out of a wait Debugger The state of :

Now , We use... Again IDA Carry out process attachment , Then go to the debug page , At the same time, set up Debugger Option Options , And then locate JNI_OnLoad The absolute address of the function .

But we found that , Nothing here RX The powers of the so file , explain so The file is not loaded into memory , If you think about it, it's still true , I think our current program is wait Debugger, That is, it hasn't gone yet System.loadLibrary Method ,so The file is not loaded into memory, of course , So we need to make our program run , At this time, we can use jdb Order to go attach Waiting procedures , The order is as follows :

jdb -connect com.sun.jdi.SocketAttach:hostname=,port=8700

In fact, the function of this command is similar to , We talked about using in the previous article Eclipse debugging smali Source code time , stay Eclipse Setting up remote debugging project is the same as , choice Attach The way , Debug the machine ip Address and port , Remember 8700 Port is the default port , But after we run this command , An error occurred :

wipe , Unable to connect to target's VM, So most of these problems occur when the debugged program is not debuggable , We can see apk Of android:debuggable attribute :

Sure enough , Nothing here debug attribute , So this apk It can't be debugged , So we need to add this property , Then compile it back :

Recompile :java -jar apktool.jar b -d out -o debug.apk

Signature apk:java -jar .\sign\signapk.jar .\sign\testkey.x509.pem .\sign\testkey.pk8 debug.apk debug.sig.apk

And then in the next installation , Use am Command to start :

First step : function :adb shell am start -D -n com.yaotong.crackme/.MainActivity

appear Debugger Waiting state

The second step : start-up IDA Carry out the target process Attach operation

The third step : function :jdb -connect com.sun.jdi.SocketAttach:hostname=,port=8700

The third step : Set up Debugger Option Options

Step four : Click on IDA Run button , perhaps F9 Shortcut key , function

I saw it , This time, jdb The success of attach Live in the ,debug disappear , Up and running ,

But a selection prompt pops up at the same time :

Now , Don't worry about it. , Select the cancel all button , And then it runs to linker Module :

Now , explain so It's loaded in , We're going to get JNI_OnLoad The absolute address of the function

Ctrl+S Found the base address :7515A000

In a static way IDA open so Look at the relative address :1B9C

Add to get the absolute address :7515A000+1B9C=7515BB9C, And then click S key , Jump :

Jump to the specified function position :

Then click run again , Into the JNI_OnLoad The breakpoint at :

Next, we will start single step debugging , But every time we arrive BLX R7 After this instruction is executed , Just JNI_OnLoad Dropped out :

After several attempts, the result is the same , So we found something wrong with this place , Maybe it's the anti debugging place

Let's go into debugging again , See BLX Where to jump R7 In the register is pthread_create function , This is Linux To create a new thread in

So Ali's anti debugging starts a thread here for rotation operation , Read out /proc/[pid]/status In the document TrackerPid field value , If you don't find out 0, It means someone is debugging this application , stay JNI_OnLoad You can exit directly from . In fact, here you can go into details to see the specific code implementation , But it's limited to space , Don't explain in detail , In the following article, we can realize this kind of anti debugging mechanism by ourselves . The focus of this paper is to be able to debug dynamically .


So the problem is found , How do we operate now ?

It's very simple , All we have to do is put BLX R7 Just kill this command , If it is smali code , We can just delete this line of code , however so Different files , It's assembly instruction , If you delete this command directly , The files can go wrong , Because itself so Files have a fixed format , Like many Segement The content of , Every Segement The offset value of is also saved , If you delete it in this way, it will affect these offset values , Will destroy so File format , Lead to so Error loading , So we can't delete this command manually here , We have another way , That is to change this instruction into an empty instruction , In assembly language ,nop An instruction is an empty instruction , He doesn't do anything , So here we can change the instruction directly ,arm Corresponding nop Instruction is :00 00 00 00

So we see BLX R7 The corresponding command position is :1C58

Check out his Hex The content is :37 FF 2F E1

We can use some binary software to modify the content , Use here 010Editor Tools to modify :

It's directly changed to 00 00 00 00:

Now , Save the modified so file , We use... Again IDA Open to view :

ha-ha , The instruction was changed to :ANDEQ R0,R0,R0 了

So after the modification , We're replacing the original so file , Compile again , Signature installation , Again, break the main encryption function according to the previous logic , There's no need to give JNI_OnLoad The function is down , Because we have modified the anti debugging function , So here we just need to follow these simple steps :

First step : Start the program

The second step : Use IDA In progress attach

The third step : find Java_com_yaotong_crackme_MainActivity_securityCheck The absolute address of the function

Step four : Set a breakpoint , Click on the run , Single step debugging

See? , Here we can single step debug. Come in, cheera , It shows that we have successfully modified the anti debug instruction .

Let's move on F8 Step by step debugging :

Debug here , Find a problem , Namely CMP After the instruction ,BNE The command starts to jump to loc_74FAF2D0 It's too late , So we can guess ,CMP The command should compare the password we entered with the correct password , Let's debug it again , have a look R3 and R1 Register value

See here R3 The value of a register is in register addressing mode , Of the assignment string , here R2 A register is the address where the string is stored , What we see is aiyou... But it's certainly not all strings here , Because we don't see the end of the string :'\0', We click R2 register , Go to see the full content :

Here's the whole story :aiyou,bucuoo

Let's continue to look at R1 The contents of the register :

Register addressing is also used here ,R0 The register stores R1 The address of the string in , What we see here is the string content :jiangwei

This is what I typed in , So here you can suddenly see , The password is on it :aiyou,bucuoo

Let's enter the code again :

Ha ha ha , Crack success cheerleading ~~


Students with itchy hands can download items to play ~~

Project Download :

6、 ... and 、 Technical summary

So far, we have explained how to use IDA To debug so Code , To crack apk The knowledge of the , Because here IDA The tools are complex , So this article is a bit long , So students can watch it several times , It's almost there . Now let's sort out the knowledge points involved in this article :

First of all 、IDA Common shortcut keys in

1、Shift+F12 You can quickly view so Constant string content in , occasionally , String content is a big breakthrough

2、 Use powerful F5 key , You can see arm Assembly instructions correspond to C The language code , At the same time, you can use Y key , Conduct JNIEnv* Method reduction

3、 Use Ctrl+S key , Can be in IDA View Page view so All segments of the information , On the debug page, you can find the corresponding so The file is mapped to the base address of memory , Here we can also use G key , Jump to the address

4、 Use F8 Single step debugging ,F7 Step into debugging , At the same time, you can use F9 Run the program

second 、ARM Knowledge of assembly instructions

1、 Understand several addressing methods , It's good for us to simply understand arm Assembly instruction code

2、 I understand arm The function of several registers in , especially PC register

3、 I understand arm Instructions commonly used in , such as :MOV,ADD,SUB,LDR,STR,CMP,CBZ,BL,BLX

Third 、 Use IDA debug so Steps for , There are two scenarios

1、IDA Debugging has no reverse debugging so Code steps :

1》 hold IDA In the installation directory android_server Copy to the specified directory of the device , modify android_server Authority , And use root The way it works , monitor 23946 port

2》 Use adb forward Command to forward the port , Forward the port of the debugged end of the device to the remote debugging end

3》 stripped of Party membership and expelled from public office IDA Tools , One is to open so file , Do file analysis , For example, simple analysis arm Instruction code , I know the general logic , There is also information such as finding the relative position of specific functions , One more IDA It's for debugging so Of documents , We are Debugger Options Debugger Option, Then attach the process that needs to be debugged

4》 After entering the debug page , adopt Ctrl+S and G Shortcut key , Navigate to the key functions that need to be debugged , Go to the next breakpoint

5》 Click the run or shortcut key F9, The key function of the trigger program , And then go to the breakpoint , Use F8 Step by step debugging ,F7 Step into debugging , In the process of debugging, the main observation is BL,BLX Instructions , as well as CMP and CBZ And so on , Then look at the specific register values .

2、IDA Debugging has anti debugging so Code steps :

1》 see apk Whether it is adjustable or not , have access to aapt Order to see his AndroidManifest.xml In the document android:debuggeable Whether the property is true, If not debug state , Then you need to add this attribute manually , And then compile back , In the signature package, re install

2》 Use adb shell am start -D -n com.yaotong.crackme/.MainActivity Command to start the program , Out of wait Debug state

3》 open IDA, Process attach , Go to the debug page

4》 Use  jdb -connect com.sun.jdi.SocketAttach:hostname=,port=8700   command attach Previous debug state , Let the program run

5》 Set up Debug Option Options , Set up Suspend on library start/exit/Suspend on library load/unload/Suspend on process entry point Options

6》 Click the run button or F9 key , The program stops running at linker Module , It means that so The file is loaded in , We go through Ctrl+S and G Key to jump to JNI_OnLoad Function out of , Go to the next breakpoint

7》 Then keep running , Get into JNI_OnLoad Breakpoint , Use F8 Single step debugging ,F7 Step into debugging , Find the debug code

8》 Then use binary software to modify the debugged code to nop Instructions , namely 00 value

9》 After the modification , Replacing the original so file , Do a back compile , From the new signature package can be installed

10》 According to the above no anti debugging so Code step is enough

Fourth 、 Learn how to do anti debug detection

Now many applications prevent other processes from debugging or injecting , It's usually a self-test device , The principle is loop detection /proc/[mypid]/status file , Check out his TracerPid Is the field 0, If not for 0, Denotes that it is used by other processes trace 了 , Then exit the program directly at this time . Because of the present IDA Debugging requires process injection , Process injection now uses Linux Medium ptrace Mechanism , So here TracePid You can record trace Of pid, We can see that our program is injected by that process , Or he's debugging it . And then take some measures .

The fifth 、IDA The whole principle of debugging

We know what's up there IDA Debugging steps , In fact, we can think about it carefully , His debugging principle is basically like this :

First, he has to put a program on the debugged side , be used for IDA The terminal communicates with the debugging device , The program is android_server, Because to attach processes , So this program has to use root Identity running , When this program comes up , Will open a port 23946, We are using adb forward Port forwarding to remote debugging end , Now IDA It can be used with the debugging side android_server We're communicating . Get the process list of the device later , Additional processes , Passing debugging information , You can use this communication mechanism to complete .IDA Can get the memory data of the debugged process , Usually in /proc/[pid]maps In file , So we're using Ctrl+S You can see all of so The base address of the file , Traversable maps Files can do it .


Breaking the law : Always pay attention to the key BL/BLX Wait for the jump command , After they do it , There are bound to be some CMP/CBZ And so on , At this time, you can view the contents of important registers to obtain important information .

7、 ... and 、 summary

That's it at last IDA debugging so I learned this knowledge point , We also know a new way to crack native Layer code , Now some programs still put the key code in Java layer , So here we can use Eclipse debugging samli You can crack , If the program is for security , And maybe put the key code in native layer , So at this point , We can use IDA To debug so Code to crack , Of course, cracking and encryption are always mutually reinforcing , Now the program has a reinforcement strategy for security , So this is what we need to introduce in our next article , How to crack those reinforced apk.

Android Dynamic mode cracking apk Advanced (IDA debugging so Source code ) More articles about

  1. Android A journey in reverse --- Dynamic mode cracking apk Advanced (IDA debugging so Source code )

    Android A journey in reverse --- Dynamic mode cracking apk Advanced (IDA debugging so Source code ) source ...

  2. Dynamic mode cracking apk Advanced (IDA debugging so Source code )

    Dynamic mode cracking apk Advanced (IDA debugging so Source code ) source Let's talk about IDA in And ...

  3. Android Dynamic mode cracking apk Prelude (Eclipse Dynamic debugging smail Source code )

    One . Preface Today we start apk Another way to crack : Dynamic code debugging and cracking , In fact, I have talked about how to crack it in an article before apk 了 : Android Using static mode to crack Apk   It's mainly static , The steps are also very simple , use first ...

  4. Android Dynamic mode cracking apk The ultimate ( strengthening apk How to crack it )

    One . Preface Today finally ushered in the last article of the crack series , The two previous articles are : Chapter one : How to use Eclipse Dynamic debugging smali Source code Second articles : How to use IDA Dynamic debugging SO file Now it's the last one , How to respond to ...

  5. Android Check for defects and make up for omissions ( Thread chapter )-- IntentService Source analysis of

    The author of this article :CodingBlock The article links : stay Android There are two concepts that are easy to confuse ,Servic ...

  6. Android Advanced : 5、 ... and 、RxJava2 The source code parsing 2

    Last article Android Advanced : Four .RxJava2 The source code parsing 1 We talk about Rxjava2 The principle of the process from creating an event to being observed , In this article we talk about Rxjava2 The principle of chain call in . This article does not talk about usage , Still need readers to be familiar with ...

  7. 【 turn 】Android The event distribution mechanism fully parses , Take you to understand the source code thoroughly ( Next )

    Reprint please indicate the source : Remember in the previous article , I'll take you to analyze it from the perspective of source code Android in Vi ...

  8. Android5.1.1 - APK Signature verification analysis and modify the source code to bypass signature verification

    Android5.1.1 - APK Signature verification analysis and modify the source code to bypass signature verification author : Seeking Yu @ Ali gather security APK Signature verification analysis find PackageParser class , This class is in the file “frameworks/base/cor ...

  9. Third articles : vernacular tornado Here comes the request for source code

    Last one < vernacular tornado Source pending request phase > This paper introduces the in tornado The framework's preparation before the client requests ( The figure below 1.2 part ), It's essentially creating a socket Server side , And carried on IP Binding with port , But not ...

Random recommendation

  1. Apache The reverse proxy is implemented as http add to https The appearance of

    Apache Reverse proxy Jintian : Keep writing , It's not easy , In other words, it's not easy to insist . If there is a shortcut to learning , It's practice , Keep accumulating . Write notes , Actually, it's for myself , It's a way of accumulating , To stick to . ...

  2. Python Determine the type of upload file

    When developing the upload service , It is often necessary to filter the uploaded files . This article provides python The method of judging file type by file header , Very practical . The code is as follows 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ...

  3. Struts 2 Zero configuration

    from struts2.1 Start ,struts2 No longer recommended Codebehind As a zero configuration plug-in , Instead, use Convention Plug in to support zero configuration , and Codebehind comparison ,Convention Plug ins are more thorough , The ...

  4. modify node To add custom tool commands

    How to use node Create custom cmd command One . The realization of command function 1. Put the folder of your own custom tools in the currently used node Under the installation directory of node_modules Under the folder : 2. go back to node Copy from the installation directory ...

  5. [ Reprint ] Hive structure

    Reprinted from Hive Architecture Hive The structure of is as shown in the figure It is mainly divided into the following parts : The user interface , Include CLI,Clie ...

  6. be based on python Script , Realization Unity Platform wide automatic packaging

    Reprint please indicate the source : 0. summary This paper focuses on the research of automatic packaging process in the project , To achieve python Script to play win/android/ios Three platforms ...

  7. Shell command - File and directory operation ls、cd

    File and directory operations - List the contents of the directory and its content attribute information ls Function description of the command ls The command is used to list the contents of a directory and its content attribute information . ls The syntax of the command ls [OPTION]... [FILE ...

  8. Spark Introduction to common operators in learning

    1. reduceByKey reduceByKey It works on things like (key, value) Formal rdd, and reduce There is a decrease in . Compression means ,reduceByKey It's the same thing key Data processing , In the end, every ...

  9. The road of Architecture :nginx And IIS Servers build clusters to achieve load balancing ( 3、 ... and )

    Refer to the website : [ Preface ] stay < The road of Architecture :nginx And IIS The server ...

  10. GetDocument missing storage-class or type specifiers Solutions for

    error C2143: syntax error : missing ';' before '*'error C2501: 'CTest1Doc' : missing storage-class o ...