本文是 iOS 安全攻防系列的一則教學記錄,目的是讓開發者理解「單靠用戶端做密碼校驗」為什麼不可靠,並據此設計更穩健的防護。所有操作都應在你自己持有或獲授權的裝置與 App 上進行。
在先前的文章中,我們用 gdb 對一個 App 做靜態與動態分析,確認了幾件事:手勢密碼以字串形式保存,九個點依序對應 1 到 9;負責處理手勢輸入的是一個名為 GestureUnlockViewController 的類別,其中的 gestureInputView:didFinishWithPassword: 方法接收使用者畫出的結果;正確密碼則由 GestureUtil 類別的 getPassword 方法讀出。
也就是說,整條校驗鏈路完全落在用戶端:取密碼、比對、放行,全部在同一支 App 裡完成。這正是問題所在。
技術手段是 Method Swizzling,也就是交換兩個方法的 IMP。這裡有個關鍵前提:交換必須在目標類別已經載入之後才能進行,太早執行會拿到 nil。因此改用 NSNotificationCenter,等 UIApplicationDidBecomeActiveNotification 觸發時再動手。
#import <objc/runtime.h>
#import <UIKit/UIKit.h>
IMP ori_getPasswd_IMP = NULL;
IMP ori_gesture_IMP = NULL;
@interface NSObject (HackPortal)
@end
@implementation NSObject (HackPortal)
+ (id)getPassword {
NSString *passwd = ori_getPasswd_IMP(self, @selector(getPassword));
return passwd;
}
- (void)gestureInputView:(id)view didFinishWithPassword:(id)password {
password = ori_getPasswd_IMP(self, @selector(getPassword));
ori_gesture_IMP(self, @selector(gestureInputView:didFinishWithPassword:), view, password);
}
@end
@implementation PortalListener
- (id)init {
self = [super init];
if (self) {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(appLaunched:)
name:UIApplicationDidBecomeActiveNotification
object:nil];
}
return self;
}
- (void)appLaunched:(NSNotification *)notification {
Class class_GestureUtil = NSClassFromString(@"GestureUtil");
Class class_PortalListener = NSClassFromString(@"PortalListener");
Method ori_Method = class_getClassMethod(class_GestureUtil, @selector(getPassword));
ori_getPasswd_IMP = method_getImplementation(ori_Method);
Method my_Method = class_getClassMethod(class_PortalListener, @selector(getPassword));
method_exchangeImplementations(ori_Method, my_Method);
Class class_Gesture = NSClassFromString(@"GestureUnlockViewController");
Method ori_Method1 = class_getInstanceMethod(class_Gesture,
@selector(gestureInputView:didFinishWithPassword:));
ori_gesture_IMP = method_getImplementation(ori_Method1);
Method my_Method1 = class_getInstanceMethod(class_PortalListener,
@selector(gestureInputView:didFinishWithPassword:));
method_exchangeImplementations(ori_Method1, my_Method1);
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
static void __attribute__((constructor)) initialize(void) {
static PortalListener *entrance;
entrance = [[PortalListener alloc] init];
}
編譯成動態庫並在越獄裝置上載入後,無論畫出什麼圖形,都會被替換成真正的密碼再送去驗證,於是必然通過。
結論很清楚:任何存放或比對於用戶端的秘密,都可以被還原。 這不是某個 App 的實作缺陷,而是架構層面的必然。因此設計敏感操作時應該遵循幾個原則:
把「用戶端不可信」當成基本假設,是行動應用安全設計最實際的起點。