preface
This paper is a summary of what I have learned in the field of iOS reverse engineering, and the examples used in this paper are only used for study and research.
1. What is reverse engineering?
From the function or behavior of iOS applications, through a series of technical means such as unshell, runtime analysis, static analysis, dynamic debugging, Hook, injection, derive the structure, process, algorithm, code of the object file, known as “iOS application reverse engineering.
IOS reverse engineering includes but is not limited to the following:
2. Why learn reverse engineering?
Usually, we reverse an APP to understand the structure of the APP or the code implementation of a key function of the APP without source code, such as interface layout or functional logic analysis for a third-party APP.
This article will introduce some common attack and defense technologies in the field of iOS reverse, and use these technologies to analyze some security problems existing in third-party apps and give defense solutions.
3. How do I start working backwards?
First we need a jailbreak phone. The iOS platform has a sandbox mechanism. The principle of sandbox is to redirect the files generated and modified by the application to its own folder. Under the sandbox mechanism, the folders of each application are not accessible to each other. So a non-jailbroken phone has no way of understanding its internals, runtime mechanics, etc.
Recommended plugins to install after jailbreak (an application called Cydia is automatically installed after jailbreak, and plugins are installed through Cydia) :
Cydia Substrate: Reverse Substrate essential basic framework that encapsulates many functions and incorporates secure crash protection mechanisms to make plug-in development easy and efficient.
AFC2: Used to activate assistant tools to access all paths on iOS devices.
Adv-cmds: displays the ps command to view the PID of the current running process and the path of the application.
AppSync Unified: Enables you to install and run stripped IPAs as you like, bypassing system signature verification for applications.
Filza File Manager: Free access to the iOS File system on the iPhone.
NewTerm 2: terminal tool that can run on a mobile phone.
4. The shell
IOS apps are protected by FairPlayDRM encryption (called “shell”) from the apple store before they go live.
4.1. What is hulling?
The use of special algorithms to change the executable code (such as compression, encryption) to achieve the purpose of protecting the program code.
To analyze an application, you must first decrypt it (called “unshell”) to get the original unencrypted binary.
4.2. How to remove the shell?
There are a number of useful unshell tools available in iOS, such as Clutch, Dumpdecrypted, AppCrackr, and Crackulous.
Using Dumpdecrypted as an example, the process is as follows:
A. First we need to generate the dynamic library dumpDecrypted.dylib for “cracking”;
B. to escape on his mobile phone to find “smashing shells” app path (through SSH connection device, the terminal use ps – e | grep wordios command to get the equipment name in all the currently running application information including wordios application, we can find wordios run path;
C. Use Cycript to inject the Wordios process, and then enter the following command to get the Document directory
D. Then use the Aes assistant to access the directory and copy dumpdecrypted. Dylib to the directory.
E. Go to the directory and run the following command:
DYLD_INSERT_LIBRARIES=dumpdecrypted.dylib /var/containers/Bundle/Application/48C8B703-726F-4304-89E8-7D6F725792F4/wordios.app/wordios
F. After the command is executed, the decrypted executable file is generated. Decrypted.
G. Use MachOView to analyze the Crypt ID in LC_ENCRYPTION_INFO_64. If the Crypt ID is 0, the encryption is successful.
Attack 5.
5.1. Attack 1: Runtime analysis
Runtime analysis is a common attack method. Specific solutions or tools include Cycript/Reveal/LookinLoader/Flex/class-dump.
5.1.1. Cycript
Cycript is a scripting language that combines OC and JS syntax interpreters to detect and modify running applications. It is mainly used to inject target programs for runtime debugging, and all changes become invalid when the program is restarted.
Use Cycript to inject code into the target App to obtain the current interface layout and controller from the surface, so as to locate suspicious methods or functions, and then conduct various call tests, and finally locate the entry of the reversed function.
Installation method: Jailbreak device directly install in Cydia
Usage: a. Inject target programs, such as wordios in operation;
B. Run time analysis using Cycript syntax.
Example 1:
View the Wordios BundleId/APP run path/DocumentPath/CachePath/current KeyWindow/Current controller/View hierarchy, etc
Jjcript is an interface file encapsulated in advance. Part of the interface is as follows:
Example 2: Get the button click event
Cycript can also retrieve the click event of a button, the method name, which is very useful for analyzing code logic. For example, if you use a paid feature in a social APP, if you are not a member, a member launcher will pop up. See if you can bypass the paid code logic and use the paid feature directly.
5.1.2. Reveal / LookinLoader
Reveal/LookinLoader is a powerful UI debugging tool for any iOS application. It can view the interface hierarchy of the App at runtime, and modify the program interface in real time. The effect of the modification can be seen without re-running the program, eliminating the need to restart the process after each modification of the code. Reverse engineering often uses Reveal/LookinLoader to quickly locate controls of interest, find controllers, and perform event analysis using Cycript.
(pass Reveal)
(LookinLoader)
5.1.3. Flex
Flex is an internal debugging tool for iOS applications. When it loads, it adds a floating toolbar to the top of the target program that lets you view and modify the view hierarchy, dynamically modify class properties, dynamically invoke instances and methods, dynamically view classes and frameworks, and dynamically modify the UI.
5.1.4 ensuring.class-dump
Class-dump is a command-line tool that uses the runtime features of object-C to export information about classes, methods, and properties in binary files as header files.
Download method: from stevenygard.com/projects/cl…
Take Wordios as an example to explain how to use it:
class-dump -S -s -H wordios.decrypted -o ./Headers
5.2. Attack 2: Listening and intercepting function calls
Frida is a cross-platform lightweight Hook framework that supports all major operating systems and helps reverse researchers analyze specific processes. It mainly provides a compact Python interface and a rich JS interface. In addition to using its own console interaction, it can also use Python to inject JS script libraries into the target process. You can use Frida to get process details, intercept and call specified functions, inject code, modify functions, dump classes and class method information from iOS applications, and more.
Frida can do a lot of things. Here are some of the most common ones:
5.2.1. Gets the list of available devices
Low frida – ls – devices
The picture shows a usb connected device named iPhone.
5.2.2. Obtain the device process list
● Frida-ps -u // -u stands for connecting to a USB device
The figure shows that the device is running a process with document table editing and its ID is 2432.
5.2.3 requires.End a process on the device
Frida -kill -u 2432//2432 is the id of the document table editor obtained above
The document table editing process is killed immediately after the terminal runs.
5.2.4. Tracking function / The method call
Trace function: for example, trace the compress function in the process whose id is 9218:
frida-trace -U -i compress 9218
This method is output at the terminal when triggered.
Trace OC methods: For example, trace the viewWillAppear method in the CourseVC controller for document table editing
Frida -trace -u -m “-[wordios.coursevc viewWillAppear*]” frida-trace -u -m “-[wordios.coursevc viewWillAppear*]”
The viewWillAppear method is triggered every time it enters the CourseVC interface, which is printed twice in the terminal.
5.2.5. Intercepts all methods of a class
For example, in the following scenario, the document table editing tutorial interface, after clicking Word document, if you are a non-member, the unlock function interface will pop up; So if I want to know what functions are called from clicking on a Word document to jumping to the unlock function screen, WE can use Frida to track that.
First use the LookinLoader to find the controller where the Word document button resides.
As shown in the figure above, the controller is CourseVC.
Write a JS script to intercept all the methods of the CourseVC class
Then load the JS script with Frida
Frida -u -l wordios.js Document table editing
After you run the script, it looks like the image above.
For more information about Frida, see frida.re/docs/home/
5.3. Attack method 3: Static analysis
Static analysis is reverse analysis when the program is not yet running. Disassembly, pseudocode, flow chart, code modification and other methods are mainly used. Static analysis tools such as Hopper and IDA Pro are commonly used.
Hopper/IDA Pro can decompile machine-language code from Mach-O files into assembly code, OC pseudocode, or SWIFT pseudocode.
Hopper/IDA Pro addresses are VM addresses that do not use ASLR.
In the case of Wordios, Hopper allows us to view all methods in the Wordios executable. If we are interested in a method, we can search it and see it, but only assembly code or OC pseudo-code implementation; We can see that the app has many function names such as sub_10004f850, indicating that the app uses code obfuscation protection for a large number of method names.
5.4. Attack 4: Dynamic analysis
Dynamic analysis, simply put, is that we can directly use LLDB to debug other people’s programs. In static analysis, we must analyze and guess with the context, while in dynamic analysis, we only need to print out the relevant register or stack content to be clear at a glance, and we can even directly modify the return value to verify the accuracy of the results.
LLDB runs only on macOS. To debug iOS applications, you need to run a tool called DebugServer on the device.
The DebugServer plays the role of the server, transfers LLDB instructions executed on the macOS terminal to the device, and feeds back the results of the device to the macOS terminal. This debugging mode is called remote debugging.
5.4.1. How do I configure the DebugServer?
If the current iOS device has been debugged, the debugServer is automatically installed in the Develop/usr/bin directory and can be exported to macOS using ace Assistant
Because the debugServer lacks task_for_PID permission, it can only debug its own applications. If you want to debug third-party applications, you need to process the DebugServer. Running in iOS11, you need to add platform-application permission.
Specific steps:
A. Create a file named ent. XML in the same directory as the exported debugServer and enter the following content
b. Sign at the terminal using CODesign
codesign -f -s – –entitlements ent.xml ./debugserver
C. Copy the signed debugServer to the /usr/bin/directory of the device and add the execution permission
chmod +x /usr/bin/debugserver
The advantage of copying the debugserber to the “/usr/bin/” directory is that you can run the DebugServer directly in any directory.
- The connection is established with the LLDB
Open debugserer
// *: port number
// * means to accept connections from any IP and start the debugServer service using a port on the iPhone (as long as the port number is not reserved)
/ / – a process
// Enter the APP process information (process ID or process name)
$debugServer *: port number -a process
A. 10011 Port Mapping
b. Allows the device’s debugServer to attach to wordios process
C. Open a terminal to connect the LLDB to the debugserer
For example, to debug [wordios.courseVC showMore:], we can set a breakpoint on a method as long as we know the starting address of the method, which we can find in Hopper.
However, due to the ASLR mechanism, the address space is simply randomized each time a process is started, which is equivalent to adding a random address value before the Mach-O start address, so the method address in Hopper is not a real address
Real address = ASLR offset + Hopper method address
Use the following command to view the ASLR offset of the application
image list -f -o
In the following figure, the offset is 0x0000000000398000
Find the static address 0x000000010006b9ec for showMore: in Hopper
Breakpoint set –address ASLR offset address + method static address
breakpoint set –address 0x0000000000398000+0x000000010006b9ec
5.5. Means of attack V:Theos
Theos is a cross-platform jailbreak development kit that comes with code templates and basic Makefile scripts ready for developers to develop plug-ins.
Theos is equivalent to the encapsulation of CydiaSubstrate, so it can Hook objective-C runtime as well as C language functions.
Simply put, Theos can be hacked by modifying the implementation of a method in the binary.
The above is a common attack method in reverse engineering, there is a point to note that when we successfully modify the executable file, directly replace the original file installed on the phone is not running, this time needs to use re-signature.
5.5.1. Heavy signature
Once changed the application binaries, or add, and modify the application resources, the signature of the application itself will be destroyed, due to the force deployed many iOS kernel code signing mechanism, running the modified application can flash back and installation is not successful, so you can avoid the attacker spread on the user’s device and running untrusted code.
If you want to install the broken installation package on a non-jailbroken mobile phone, you need to re-sign the installation package.
There are two caveats:
A. The executable files in the installation package must be shelled for re-signature to be valid.
All dynamic libraries (.framework,.dylib), AppExtension (PlugIns folder, extension name appex) and WatchApp (Watch folder) inside the.. app package need to be re-signed
Re-signature steps:
A. Prepare an Embedded. Mobileprovision file (generated by the payment certificate, and the appID and device must match) and add it to the. App package. It can be automatically generated by Xcode and found in the compiled APP package, or it can be generated and downloaded from the developer certificate website.
B. Extract Entitlements. Plist file from embedded. Mobileprovision file.
Tap the following command on the terminal to extract:
security cms -D -i embedded.mobileprovision > temp.plist
/usr/libexec/PlistBuddy -x -c ‘Print :Entitlements’ temp.plist > entitlements.plist
View available certificates:
security find-identity -v -p codesigning
Sign the dynamic library inside app, AppExtension, etc. :
Codesign-fs certificate ID xxx.dylib
To sign the.app package:
Codesign-fs Certificate ID — Entitlements.plist XXX. App
You can also use some re-signing tools with a UI. Such as:
IOS App Signer (github.com/DanTheMan82…
IOS App Signer can re-sign. App into ipA, and the corresponding Embedded. Mobileprovision file must be provided in the. App package.
IReSign (github.com/maciekish/i…
IReSign can re-sign ipA, and needs to provide entitlements. Plist, embedded. Mobileprovision file path.
Problems and points to note during the re-signature process:
A. Only shelled executable files can be re-signed.
B. The tool can only re-sign IPA. The dynamic library and AppExtension in app need to be re-signed manually before using the tool to re-sign IPA.
C. Re-signature packaged as IPA and installed on mobile phone if DeviceNotSupportB… Error: UISupportedDevices field in info.plist file, need to remove this field and repackage.
Summary of re-signature steps (taking document table editing as an example)
A. Copy the document form editing APP package to the computer through ace Assistant and other tools
B. Place the shelled executable file in the APP to replace the original unshelled executable file
C. Put the new descriptive file and the dynamic library to be injected into the app package (same path as the executable file)
D. Re-sign all the dynamic libraries, extension, framework and PlugIns in the APP package.
Codesign-fs Certificate ID Dynamic library name
E. Change the search path of all dynamic libraries, for example, to @executable_path/wordiosfree.dylib. If the dynamic library wordiosfree depends on other dynamic libraries, In general, by the library of CydiaSubstrate, So you also need to replace the search path that CydiaSubstrate @ loader_path/CydiaSubstrate dylib (@ loader_path/libsubstrate dylib, it is important to note that in general is to use this, Because derived from the cell phone terminal to CydiaSubstrate renamed libsubstrate automatically, if use @ loader_path/CydiaSubstrate dylib can cause path error flash back)
Otool -l wordiosfree.dylib // find the libraries that dynamic libraries depend on and their paths
install_name_tool -change /Library/Frameworks/CydiaSubstrate.framework/CydiaSubstrate @loader_path/CydiaSubstrate // Modify the execution path of CydiaSubstrate
F. Inject the wordiosfree dynamic library into the executable
insert_dylib @executable_path/wordiosfree.dylib wordios wordios –all-yes –weak
G. Delete the UISupportedDevices field in info.plist
Use tools to re-sign app packages and generate IPA files, and then install them on mobile phones through Ace Assistant
6. prevent
As mentioned above, there are also many corresponding defense means, such as data encryption (string, network data, sensitive data, etc.), application shell (binary encryption, iOS upload appstore will automatically shell, But has long been cracked), code confusion (class name, method name, code logic, etc.), anti-debugging, anti-injection, Hook detection, jailbreak detection, integrity detection, etc.
After reviewing a large number of apps on the market, I found that most of them did not take too many protective measures, but a few well-known apps like Douyin and wechat did take a lot of protective measures. In short, there is no defence of APP like expose the source code in front of others, porous, there are a lot of potential safety problems, so I think the APP is necessary to do some protection, learn some reverse knowledge, can also improve our safety consciousness, in the development process of the usual code will always notice what kind of writing is flawed, What kind of writing is safe.
I’m going to talk about several common defenses in the reverse domain, also known as application hardening.
6.1. Defense 1: Code confusion
IOS applications can use class-dump, hopper, IDA, etc., to get class names, method names, and analysis logic. If it is easy for others to see what the class name or method name is for, it is easy for others to crack it. So code obfuscation makes it harder for others to analyze.
In iOS, code obfuscation is mostly about source code obfuscation, such as class names, method names, protocol names, and attribute names. Use macros to define obliquation, such as confusing the name of the Person class with abcd:
#define Person abcd
If you change the class name or method name to abcd or something, it can be confusing, but it is also very troublesome to maintain.
Note:
● Do not confuse system methods with macro definitions
● Do not confuse methods that start with init
● If the xiB or storyboard needs to be changed, for example, if the controller name is confused, then the xiB or storyboard name needs to be changed manually, because the system will not help you to change it (some tools can be used automatically).
● Don’t mess with everything, because too much code will be rejected. Only key code
● Consider adding a prefix to code that needs to be obfuscated, so that it can be distinguished from normal code
6.2. Defense 2: Reverse debugging -ptrace
Ptrace is a means to track and control a running process. Through ptrace, a Ptrace can dynamically read and write another process’s memory and registers, including instruction space, data space, stack and all registers. Ptrace also provides a very useful PT_DENY_ATTACH parameter that tells the system to prevent the debugger from attaching, so the most common way to de-debug is to call ptrace.
Parameter 1: Things to do
Parameter 2: ID of the process to be controlled
Parameter 3: address
Parameter 4: Data
Parameters 3 and 4 both depend on parameter 1 to determine the address and data to be passed.
The list of arguments 1
Call method:
Effect:
When we attempt to use dynamic debugging, a segmentation fault:11 error is reported directly.
6.3. Defense 3: reverse injection
When a dylib you write fails to load into a target application, it indicates that the application is protected from reverse injection. We can do this by building Settings -> Signing -> Enable Hardened Runtime to YES, or Capabilities. In this case, the runtime checks whether the signature of the injection library is consistent with that of the IPA. If the signature is inconsistent, the injection cannot be performed.
The following link is the official solution:
Developer.apple.com/documentati…
6.4. Defense means 4: Hook detection
There are two main Hook methods on iOS, Method Swizzing and Inline Hook.
The principle of Method Swizzing is to replace IMP, so you can use dladdr to get the INFORMATION of the IMP address module to judge, as shown in the following example:
An Inline Hook is an Inline Hook that changes the first N bytes of memory of a function to jump to a function written by the program itself.
6.5. Defense 5: Jailbreak detection
Many apps need to detect jailbroken environments to ensure security, and if the machine is jailbroken, some sensitive functions will not be enabled (such as wechat’s fingerprint payment function, which is automatically turned off during jailbreak).
Specific plan:
6.5.1. Detect jailbroken stores and their affiliated files
Jailbreak environments are almost always installed with Cydia, Sileo and their associated files, which can be detected with the following code:
Tactical fix packs for 6.5.2.Try to read the system application list
If the device has been jailbroken, it can read the contents of the system application list as a basis for detection. You can use the following code to detect:
6.5.3. Check URLSchemes for availability
URLSchemes is a mechanism provided by Apple to jump to system apps and to jump to other apps.
This mechanism provides an idea for detecting jailbreaks:
If Cydia or other unofficial apps can be opened, it means jailbroken. Use “- (BOOL)canOpenUrl:(NSURL *)url” to test whether URLSchemes of the corresponding apps are available.
6.6. Defense 6: Integrity check
Integrity checks can confirm whether the object file is shelled, statically injected, modified, re-signed, and so on. Common ways are:
6.6.1. Load command detection
To enable unjailbroken devices to use plug-ins smoothly, LC_LOAD_DYLIB or LC_LOAD_WEAK_DYLIB is added to LoadCommand (LoadCommand) to point to its own dynamic library path, so as to achieve the injection function, which is also known as “static injection”.
Record command detection is to detect LC_LOAD_DYLIB or LC_LOAD_WEAK_DYLIB in LoadCommand of Mach-O file, the code is as follows:
6.6.2. Snippet detection
The code section detection technique is used to check whether the “_TEXT, _TEXT” section has been modified, as shown in the following example:
Where &_MH_execute_header points to the starting location of Mach-O in memory, and the getSectionData function returns the memory address and size of the specified Section.
In actual applications, the correct Hash value can be saved to the server or encrypted to the local PC for comparison when the process is started. If the Hash value does not match, logical processing can be performed.
6.6.3. Signature Information Detection
Re-signing the modified application is a necessary step in order for it to be used on a non-jailbroken machine.
Signature information detection is to check whether the signature information in LC_CODE_SIGNATURE (such as TeamID) matches the user’s own.
7. Actual combat case: some instant communication software – Guessing and throwing dice code implementation analysis
7.1. The target App introduce
Practical goal of this article is a famous instant messaging App, packets can be sent via mobile phone network expression, such as mora and throw the dice, the two is the expression website packages, sent out after the first one is kept beating animation, finally will stay in a random/scissors/stone cloth or points, all these seem to be random, But by working backwards we can automate and deliver the results we want.
7.2. Looking for an entry point
Reverse an App first need to find the breakthrough point, in this case, to analysis and the realization of the throw the dice mora, the first thing we have to start from the UI level, find out the current controller, and then click expression after the package method calls, find the key method of analyzing code implementation of this method, and find bugs, once you find can hook code logic, Then we can implement the code logic we want.
7.3. The analysis process
We can know the current controller is BaseMsgContentViewController use Lookin, then further analysis of the interface:
As you can see, this is a UICollectionViewCell, and it’s natural to think that clicking on it will trigger
The following proxy methods:
- (void)collectionView: (UICollectionView *)collectionView didSelectItemAtIndexPath: (NSIndexPath *)indexPath; We can through the breakpoint BaseMsgContentViewController kind didSelectItem... Methods to analyze the code logic, but there is another more convenient method is to directly monitor BaseMsgContentViewController all method calls, Here is Frida + js script that I use to track the dice when the class all method calls - [BaseMsgContentViewController useTransparentNavibar] -[BaseMsgContentViewController useTransparentNavibar] -[BaseMsgContentViewController shouldInteractivePop] -[BaseMsgContentViewController toolView] -[BaseMsgContentViewController SendEmoticonMesssageToolView:] -[BaseMsgContentViewController findNodeDataByLocalId:] -[BaseMsgContentViewController addMessageNode:layout:addMoreMsg:] -[BaseMsgContentViewController findNodeDataByLocalId:] -[BaseMsgContentViewController getCurContentSizeHeight]Copy the code
Observe carefully we can find that [BaseMsgContentViewController sendEmoticonMessageToolView:] this method has a great chance is the key method, we are looking for literally means sending expression information. Then continue writing the script
Using frida to load the script, you can print out the stack information for the method (removing unnecessary address information) :
-[BaseMsgContentViewController SendEmoticonMesssageToolView:] Backtrace: -[MMInputToolView didSelectorSelfDefinedEmotcion:] -[EmoticonBoardView onTapEmoticonWrap:atIndex:maxCountPerLine:fromSection:] -[EmoticonBoardCrossCollectionController onEmoticonPageCellTapEmoticonWrap:atIndex:pid:maxCountPerLine:] -[EmoticonBoardCrossCollectionEmoticonPageCell collectionView:didSelectItemAtIndexPath:] -[UICollectionView _selectItemAtIndexPath:animated:scrollPosition:notifyDelegate:deselectPrevious:] -[UICollectionView touchesEnded:withEvent:] UIKitCore! forwardTouchMethod UIKitCore! -[UIResponder touchesEnded:withEvent:] UIKitCore! forwardTouchMethod UIKitCore! -[UIResponder touchesEnded:withEvent:] UIKitCore! forwardTouchMethod UIKitCore! -[UIResponder touchesEnded:withEvent:] UIKitCore! _UIGestureEnvironmentUpdate UIKitCore! -[UIGestureEnvironment _deliverEvent:toGestureRecognizers:usingBlock:] UIKitCore! -[UIGestureEnvironment _updateForEvent:window:] UIKitCore! -[UIWindow sendEvent:]Copy the code
After dynamic analysis, we successfully found the stack call information when clicking the dice. Then we used static analysis to analyze the source code implementation of these methods, and used Hopper to load the shucked binaries.
We first analysis – [EmoticonBoardCrossCollectionController onEmoticonPageCellTapEmoticonWrap: atIndex: pid: maxCountPerLine:]
This method, because it’s called after did select index path.
By analyzing the method of pseudo code, we can know this method didn’t do the practical work, just a forwarding agent, then to see – [EmoticonBoardView onTapEmoticonWrap: atIndex: maxCountPerLine: fromSection:]
The pseudo-code implementation of this method, because the code logic of this method is quite large, so briefly describe what this method does, this method determines whether the selected emoticons are custom emoticons, if so, it will be uploaded asynchronously. Final call – [MMInputToolView didSelectorSelfDefinedEmotcion:] method,
We know that the parameter passed in is r27. We don’t know exactly what type r27 is, but from the context of the pseudocode, we can see that r27 calls the following methods:
[r27 m_emojiInfo]
[r27 m_isAsyncUpload]
[r27 attachObject:r20 forKey:@"emoticonpageid"]
Copy the code
Then use Hopper to find the corresponding classes of these methods
Is CEmoticonWrap class, thus the incoming parameters and dice results should be kept in this class, and then continue to analysis – [MMInputToolView didSelectorSelfDefinedEmotcion:] method of pseudo code:
The realization of this method is simple, just for a forward agent operation, then analysis – [BaseMsgContentViewController SendEmoticonMesssageToolView:]
This method is still in the forward agent, continue to analyze – [BaseMsgContentLogicController SendEmoticonMessage]
M_uiGameType is an attribute of arg2. Arg2 is a CEmoticonWrap class. Then find the CEmoticonWrap class header:
Let’s print arg2 and write a script that prints all the attribute values for this parameter:
<CEmoticonWrap: self.m_uiType=1, self.m_bCanDelete=1, self.m_uiGameType=2, self.m_nsAppID=(null), self.m_extFlag=0, self.m_nsThumbImgPath=(null), self.m_lastUsedTime=0, self.m_isAsyncUpload=0, self.m_isRemoteRecommed=0, self.m_isLastSended=0, self.m_query=(null), self.m_emojiInfo=<EmojiInfoObj: 0x281bbd950> {
activityId = <nil>;
aesKey = <nil>;
attachedText = <nil>;
attachedTextColor = <nil>;
authkey = <nil>;
designerId = <nil>;
disableExtern = 0;
encryptUrl = <nil>;
externMd5 = <nil>;
externUrl = <nil>;
lensId = <nil>;
linkId = <nil>;
md5 = "dice_emoticon_md5";
productId = "custom_emoticon_pid";
thumbUrl = <nil>;
tpUrlString = <nil>;
url = <nil>
}
Copy the code
M_uiGameType is equal to 2, and most of the other attributes of the class, including the image URL, have not been assigned a value, so far the dice result has not come out.
If m_uiGameType is not equal to 0, call the -[GameController sendGameMessage:toUsr:] method
And then I call -[GameController SetGameContentForMsgWrap]
Analysis to here, finally found a breakthrough!
M_uiGameType is not equal to 0, if m_uiGameType is equal to 1, if else, m_uiGameType is equal to 2, so we can take a bold guess, M_uiGameType is actually the type of guessing and dice roll, where guessing is 1 and dice roll is 2. After verification, when clicking on guessing, m_uiGameType is indeed 1, so we can conclude that this code is the formula for calculating the results of these two games.
If m_uiGameType = 1 (guess fist) :
r20 = 1 + random() – random() / 3 * 3 = 1 + random() % 3
If m_uiGameType = 2 (roll dice) :
r20 = 4 + random() – random() / 6 * 6 = 4 + random() % 6
According to the formula, the number of guesses ranges from 1 to 3, while the number of dice rolls ranges from 4 to 9, which corresponds to rock paper scissors and 6 rolls.
At this point, we have completed the logic analysis of the code for hand guessing and dice rolling. If you want to further modify the result, you can hook the value of random(), which is the only variable. Because random() is a C language function, it does not use the API provided by the runtime mechanism to directly replace the method implementation. The Method Swizzling function does not work on a jailbroken phone. The Method Swizzling function does not work on a jailbroken phone. The Method Swizzling function does not work on a jailbroken phone, so the Method Swizzling function does not work on a jailbroken phone. Fishhook is recommended if you want it to work on non-jailbroken phones.
7.4. Case process sorting
Case chose a instant messaging app, to determine the need to reverse function – mora and throw the dice, then from the UI level laid hands on him to find the breakthrough point, to find the current controller and the corresponding control types, and then the method of using frida to monitor the current controller calls, to find key method after the method invocation, print the method call stack, Using Hopper static analysis stack call involved in the implementation of each method code, combined with dynamic analysis of the print method parameter value, find the key code, and finally restore the function of the implementation code.
Above is a complete process of reverse looks be like simple, practical process will encounter a lot of the pit, and the reverse field is small, encounter problems can be difficult to find the answer on the Internet, so the process is very time consuming, but reverse after success will reap many, reverse engineering, in contrast to the positive development, it makes you from another perspective on software development, Peep into the essence of code.
8. conclusion
This paper shares most of the knowledge and technology of iOS reverse engineering. Due to the limited space, some knowledge points in the mind map in the beginning are not discussed in detail, mainly explaining the attack and defense means in reverse engineering.
The attack methods include application unmasking, runtime analysis, static analysis, dynamic debugging, modifying executable files, injecting dynamic libraries, etc.
Defense means include code obfuscation, anti-debugging, anti-injection, Hook detection, jailbreak detection, integrity detection, etc.
In short, the basic process of iOS reverse engineering attack is: first try every means to find a breakthrough point (breakthrough), and then through the combination of static analysis and dynamic debugging, tracking and analysis of the core code of the target program, understand its design ideas, so as to restore the similar code.
Almost all of the defense is arrangement according to the means of attack, it is important to note that even for the defense, also do not represent must not be cracked, there is no perfect APP in the world, as long as the hacking strong enough, can always find some holes, we can do is do as much as possible defences, forced the attacker to abandon the idea of crack.
At the end of the article, an interesting function in the reverse third-party App is used to put all the introduced reverse technology into actual combat.
9. The resources
A. Book: iOS App Reverse and Security
B. Video: Basic Principles of iOS
C. Reference link: iosre.com/