iOS逆向之旅(進階篇) — HOOK(Method Swizzling)
在Objective-C中呼叫一個方法,其實是向一個物件傳送訊息,即查詢訊息的唯一依據是selector的名字。每一個SEL都對應著其方法實現真實的執行地址(IMP)。 如下圖:

Method Swizzling 可以使得兩個SEL所對應的IMP相互交換達到HOOK的目的如下圖

接下來,我們通過一個小小的案例,從逆向的角度來了解HOOK的強大
首先我們看看微信的主頁

第一步【移植】
把 ofollow,noindex">iOS逆向之旅(進階篇) — 程式碼注入 中dylib的程式碼直接拿過來,在上面進行開發
第二步【分析】
利用Debug View 從介面上先分析登入介面程式碼

從圖可以直接看到登入Button的Target與Action,接下來通過LLDB分析檢視Target/Action裡面到底是啥子東西
(lldb) po 0x1c3a7f800 { className = WCAccountLoginControlLogic memoryAddress = 0x1c0322300; } (lldb) po 0x1c3a7fa80 { className = "__NSCFString"; memoryAddress = 0x1c0e289c0; } (lldb) po 0x1c0e289c0 onFirstViewLogin 複製程式碼
我們以前是不是通過以下方法,為Button新增點選事件的? - (void)addTarget:(nullable id)target action:(SEL)action forControlEvents:(UIControlEvents)controlEvents;
有了這些我們就能很肯定,當點選 登入按鈕 的時候觸發的是這個WCAccountLoginControlLogic控制器 下的 onFirstViewLogin方法
第三方【寫程式碼】
直接在我們的dylib中進行開發,我就直接上程式碼了
#import "PFLibrary.h" #include <objc/runtime.h> #import <UIKit/UIKit.h> @implementation PFLibrary - (void) loginBtnPressed { UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"你想登入??" message:nil preferredStyle:UIAlertControllerStyleAlert]; [alertVC addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleCancel handler:nil]]; [[[UIApplication sharedApplication] keyWindow].rootViewController presentViewController:alertVC animated:true completion:nil]; } + (void)load { NSLog(@"Dylib注入成功..."); // 原微信的點選觸發的方法 Method old = class_getInstanceMethod(objc_getClass("WCAccountLoginControlLogic"),@selector(onFirstViewLogin)); // 本地自己的方法 Method new = class_getInstanceMethod(self, @selector(loginBtnPressed)); //交換兩個方法的IMP method_exchangeImplementations(old, new); NSLog(@":cat::cat::cat::cat::cat::cat::cat::cat:Hook成功:cat::cat::cat::cat::cat::cat::cat::cat:"); } @end 複製程式碼
這段程式碼就是利用Method Swizzling進行了HOOK。由於比較簡單,我就不不細緻分析了,我相信大夥通過我的註釋都看得懂。
來~看看結果!
