iOS 知识点

非越狱设备Hook 纯Swift工程Swift函数

2018-07-19  本文已影响461人  史贵岭

我们在做App逆向时,会遇到各种类型App,虽然大部分是OC工程,越来越多App采用了混合(OC和Swift)开发,甚至纯Swift开发。我们更多希望我们逆向后的App能在非越狱设备上使用,对于如何在非越狱环境去Hook Swift函数,目前没找到有效方案,希望知道的能一起探讨下。

我们常用的fishhook或者MobileHooker经过验证是无法实现如上Hook需求的。理由如下:

fishhook能够工作的原理还是PIC(Position Independ Code),从dyld的角度来说,就是mach-o外部符号(像printf引用其他动态库)绑定的过程。对于内部符号,fishhook是无法进行hook的。内部函数,编译后,函数的实现会在mach-o的__TEXT(代码段)里,而不会出现在lazy或non lazy的symbols里。

1、Hook SWift函数要点分析

(1)通过image命令查找Swift函数在match-o文件中的符号
(2)通过__attribute__((constructor))并结合dlopen提前加载当前match-o文件
(3)通过dlsym来加载步骤(1)中符号对应的函数调用地址
(4)通过substitute库来Hook找到的函数
其实归纳起来就是三大步骤:
1、找到swift编译后真实的函数名(swift会在编译后,为函数按照一定规则增加前后缀),通过函数名字找到函数实际内存地址;
2、通过__attribute__((constructor))告诉编译器,其范围内函数需要在main函数前加载,所以可以把Hook代码放在此作用域范围内;
3、调用第三方 inline hook库(substitute)实现内部自定义函数Hook

2、示例解析

创建了一个名叫SwiftDemo的纯Swift工程,并定义了一个纯Swift函数CustomMethod

 @IBAction func onClick(_ sender: UIButton) {
        let result = self.CustomMethod(number: 10)
        print("origin: \(result)")
    }
    
    func CustomMethod(number: Int) -> Int{
        return number + 10
    }

Swift和OC一样,会隐藏函数部分参数,OC隐藏其第一个(即self)和第二个参数(_cmd即selector),而swift默认会隐藏self参数,并且这个参数是作为函数最后一个传递的。
所以定义了CustomMethod(Int number)函数,实际产生调用函数为CustomMethod(Int number, id _self)

2.1查找CustomMethod在match-o符号

创建一个名叫HookSwiftFinal的MonkeyDev工程,将SwiftDemo的ipa复制到HookSwiftFinal的TargetApp目录下,并运行MonkeyDev工程

2.1.1激活LLDB,运行image命令

MonkeyDev在真机运行起来后,按照下图激活LLDB


激活LLDB.png

激活LLDB后,可以运行image命令查找CustomMethod在Match-O符号

image lookup -rn SwiftDemo.*CustomMethod //得到一个地址
image dump symtab -m SwiftDemo //根据上面地址搜索得出符号

2.2 Hook Swift函数实现

个人比较喜欢logos语法,所以在MonkeyDev的HookSwiftFinalDylib.xm加入Hook代码

__attribute__((constructor))
int main(void){
    NSLog(@"Load!!!abc");
    
    void* Handle=dlopen(NULL,RTLD_NOW|RTLD_LAZY);
    //image lookup -rn SwiftDemo.*CustomMethod //得到一个地址
    //image dump symtab -m SwiftDemo //根据上面地址搜索得出符号
    //通过dlsym加载方法会少一个下划线
    void*findCMFunction= dlsym(Handle,"_T09SwiftDemo14ViewControllerC12CustomMethodS2i6number_tF");
    int (*customMethodFunction)(int,id) = (int(*)(int,id))findCMFunction;
    
    static const struct substitute_function_hook hooks[] = {
        {(void *)customMethodFunction, (void *)new_custom_method,(void *) &origin_custom_method},
    };
    
    int ret = substitute_hook_functions(&hooks[0], sizeof(hooks)/sizeof(*hooks),
                                        NULL, 0);
    
    return 0;
}

Hook函数补充和申明

static int (*origin_custom_method)(int,id) = NULL;

int new_custom_method(int number, id _self)
{
    NSLog(@"Hooked!!!");
    number = 20;
    return origin_custom_method(number, _self);
}

2.3 关于MonkeyDev *.xm调试

其实在MonkeyDev中*.xm是可以下断点调试的,需要更改下*.xm的文件类型,默认是普通的text类型,选中*.xm打开xcode右侧编辑面板,更改type为objective c++类型,重启xcode,即可下断点调试


更改xm文件类型.png

写在最后,Demo完整下载地址:
https://github.com/shiflymoon/-Demo/tree/master/%E9%9D%9E%E8%B6%8A%E7%8B%B1%E5%B9%B3%E5%8F%B0Hook%20%E7%BA%AFSwift%E5%B7%A5%E7%A8%8BSwift%E5%87%BD%E6%95%B0

上一篇 下一篇

猜你喜欢

热点阅读