前言
fishhook是fackbook開源的一個用來hook c函數的庫。在iOS開發中我們一般都是對OC方法進行hook,這是因爲OC的動態特性才能實現的,OC的方法調用是在運行時動態查找的。而c函數是靜態,爲什麼同樣能夠hook呢?接來下就看看這其中用到了什麼黑魔法!
一、Mach-O文件
首先,我們將iOS源代碼打包後會生成一個.ipa文件,裏面包含了一些資源文件以及可執行文件,這個可執行文件就是Mach-O文件。Mach-O文件格式如下(源自官方文檔):
Header: Specifies the target architecture of the file, such as PPC, PPC64, IA-32, or x86-64.
Load commands: Specify the logical structure of the file and the layout of the file in virtual memory.
Raw segment data: Contains raw data for the segments defined in the load commands.
Mach-O格式官方圖片
Mach-O文件包含三個部分:
1、Header:頭部信息,描述該文件的一些基本信息,例如cpu類型,文件架構類型是arm64還是x86等等。
2、Load commands:主要是描述了文件在內存中的佈局,一個segment command對應一個segment data,描述了它在文件中的偏移地址,內存大小等信息。
3、Segment Data:segment的具體數據,__TEXT段表示這部分數據是代碼,也即是這部分數據是執行指令的,__DATA段表示存放的是數據,如全局變量、靜態變量等數據。
二、準備知識
APP啓動的時候是會去鏈接很多動態庫,如UIKit,UIFoundation等。函數的調用是通過跳轉指令跳到函數對應的內存地址,而動態庫是在程序啓動時纔去鏈接的,因此動態庫中函數的地址在一開始是不知道的,所以這些函數的地址存放在__DATA,__la_symbol_prt
表中,也就是所謂的PIC(位置無關代碼)。在函數第一次調用的時候例如NSLog()函數,這個表中的地址不是直接指向NSLog的正確地址,而是指向了dyld_stub_binder
函數地址,它的作用就是去計算出NSLog的真正地址,然後將__DATA,__la_symbol_prt
中NSLog對應的地址改爲它的實際地址,這樣第二次調用的時候就是直接調用到NSLog。另外除了__la_symbol_prt
表之外,還有與之對應的indirect Symbols
、Symbol Table
以及String Table
。它們之間的關係是,首先通過符號在__la_symbol_prt
的index,加上在Load Command中對__la_symbol_prt
的描述信息reversed1,找到indirect Symbols
中 index+reversed1 位置的數據index2,然後在找到Symbol Table
中index2位置的數據拿到偏移地址offset,最後在String Table
中找offset處的數據,該數據就是函數名"_NSLog"。下面通過圖示演示一下該過程:
以__la_symbol_prt
中的第一個函數NSLog舉例,index = 0;
__la_symbol_prt
Load Commands中找到__la_symbol_prt
的描述信息得到reversed1 = 12;
Load Commands
在indirect Symbols
找到index+reverse1處的數據,得到index2 =12;
indirect Symbols
在Symbol Table
找到index2處的數據,得到offset = 18;
Symbol Table
在String Table
中首地址是0xC4C8,加上offset得到0xC4D0,也就是箭頭所指的位置,結果爲_NSLog。
String Table
三、fishhook源碼分析
先來看下fishhook的用法。
fishhook用法
首先構造了一個sturct rebinding結構體的數組rebindArr,調用rebind_symbols函數將數組和數組長度傳遞進去。
sturct rebinding結構入下:
struct rebinding {
const char *name;//函數名
void *replacement;//hook之後用於替換的函數
void **replaced;//原來的函數
};
rebind_symbols函數
int rebind_symbols(struct rebinding rebindings[], size_t rebindings_nel) {
int retval = prepend_rebindings(&_rebindings_head, rebindings, rebindings_nel);
if (retval < 0) {
return retval;
}
// If this was the first call, register callback for image additions (which is also invoked for
// existing images, otherwise, just run on existing images
if (!_rebindings_head->next) {
_dyld_register_func_for_add_image(_rebind_symbols_for_image);
} else {
uint32_t c = _dyld_image_count();
for (uint32_t i = 0; i < c; i++) {
_rebind_symbols_for_image(_dyld_get_image_header(i), _dyld_get_image_vmaddr_slide(i));
}
}
return retval;
}
首先調用prepend_rebindings函數進行預綁定操作,內部主要是將傳遞進來的參數rebindings數組生成一個鏈表節點,然後將這個節點添加到鏈表的頭部,鏈表結構如下:
struct rebindings_entry {
struct rebinding *rebindings;
size_t rebindings_nel;
struct rebindings_entry *next;
};
prepend_rebindings函數之後,判斷這個_rebindings_head鏈表是否只有一個節點,如果只有一個節點表明是第一次調用fishhook,就去註冊dyld加載image的回調函數_rebind_symbols_for_image;否則,遍歷所有的image,手動調用_rebind_symbols_for_image函數。
rebind_symbols_for_image函數
static void rebind_symbols_for_image(struct rebindings_entry *rebindings,
const struct mach_header *header,
intptr_t slide) {
Dl_info info;
if (dladdr(header, &info) == 0) {
return;
}
segment_command_t *cur_seg_cmd;//當前的LoadCommand
segment_command_t *linkedit_segment = NULL;//__LINKEDIT段的LoadCommand {LC_SEGMENT_64(__LINKEDIT)}
struct symtab_command* symtab_cmd = NULL;//LC_SYMTAB,可以找到Symbol Table的地址
struct dysymtab_command* dysymtab_cmd = NULL;//LC_DYSYMTAB,可以找到indirect Symbols的地址
uintptr_t cur = (uintptr_t)header + sizeof(mach_header_t);//當前內存地址指向LoadCommand起始地址
//第一次遍歷所有的LoadCommand
for (uint i = 0; i < header->ncmds; i++, cur += cur_seg_cmd->cmdsize) {
cur_seg_cmd = (segment_command_t *)cur; //保存當前的LoadCommand
if (cur_seg_cmd->cmd == LC_SEGMENT_ARCH_DEPENDENT) {
if (strcmp(cur_seg_cmd->segname, SEG_LINKEDIT) == 0) {
//判斷segment的名稱是否爲__LINKEDIT
linkedit_segment = cur_seg_cmd;
}
} else if (cur_seg_cmd->cmd == LC_SYMTAB) {
//判斷是否是LC_SYMTAB,symtab_cmd->symoff 找到Symbol Table的偏移地址
symtab_cmd = (struct symtab_command*)cur_seg_cmd;
} else if (cur_seg_cmd->cmd == LC_DYSYMTAB) {
//判斷是否是LC_DYSYMTAB,dysymtab_cmd->indirectsymoff 找到indirect Symbols的偏移地址
dysymtab_cmd = (struct dysymtab_command*)cur_seg_cmd;
}
}
if (!symtab_cmd || !dysymtab_cmd || !linkedit_segment ||
!dysymtab_cmd->nindirectsyms) {
return;
}
// Find base symbol/string table addresses
//slide是ASLR的隨機偏移,linkedit_segment->vmaddr - linkedit_segment->fileoff是mach-o在文件中的基地址,兩者相加就是ASLR後的mach-o加載進內存的基地址
uintptr_t linkedit_base = (uintptr_t)slide + linkedit_segment->vmaddr - linkedit_segment->fileoff;
//Symbol Table表的內存地址
nlist_t *symtab = (nlist_t *)(linkedit_base + symtab_cmd->symoff);
//String Table表的內存地址
char *strtab = (char *)(linkedit_base + symtab_cmd->stroff);
// Get indirect symbol table (array of uint32_t indices into symbol table)
//indirect symbols表的內存地址
uint32_t *indirect_symtab = (uint32_t *)(linkedit_base + dysymtab_cmd->indirectsymoff);
cur = (uintptr_t)header + sizeof(mach_header_t);//指針指向LoadCommand起始地址
//第二次遍歷所有的LoadCommand
for (uint i = 0; i < header->ncmds; i++, cur += cur_seg_cmd->cmdsize) {
cur_seg_cmd = (segment_command_t *)cur;
if (cur_seg_cmd->cmd == LC_SEGMENT_ARCH_DEPENDENT) {
if (strcmp(cur_seg_cmd->segname, SEG_DATA) != 0 &&
strcmp(cur_seg_cmd->segname, SEG_DATA_CONST) != 0) {
//如果不是__DATA段就跳過
continue;
}
//如果是__DATA段,則遍歷該Segment下的Sections
for (uint j = 0; j < cur_seg_cmd->nsects; j++) {
section_t *sect =
(section_t *)(cur + sizeof(segment_command_t)) + j;
if ((sect->flags & SECTION_TYPE) == S_LAZY_SYMBOL_POINTERS) {
//找到__la_symbol_ptr
//重綁定
perform_rebinding_with_section(rebindings, sect, slide, symtab, strtab, indirect_symtab);
}
if ((sect->flags & SECTION_TYPE) == S_NON_LAZY_SYMBOL_POINTERS) {
//找到_nla_symbol_ptr
//重綁定
perform_rebinding_with_section(rebindings, sect, slide, symtab, strtab, indirect_symtab);
}
}
}
}
}
代碼中有詳細的註釋不多做解釋了,做一些其他補充。Mach-O加載進內存的地址是經過ASLR(Address Space Layout Randomization),地址空間佈局隨機化。就是說每次Mach-O的內存地址不是從固定的地址開始,而是每次加上了一個隨機數。所以要找到每張表的地址除了從Load Commands中獲取offset偏移,還要計算ASLR後的基地址。找到幾張符號表的地址之後,調用perform_rebinding_with_section進行重新綁定。
perform_rebinding_with_section函數
static void perform_rebinding_with_section(struct rebindings_entry *rebindings,
section_t *section,
intptr_t slide,
nlist_t *symtab,
char *strtab,
uint32_t *indirect_symtab) {
//indirect Symbols中包含了各個section中符號在Symbol Table的index,這裏是直接定位到對應__DATA,__la_symbol_ptr所在的index數組
uint32_t *indirect_symbol_indices = indirect_symtab + section->reserved1;
//__la_symbol_ptr表,符號地址的數組
void **indirect_symbol_bindings = (void **)((uintptr_t)slide + section->addr);
for (uint i = 0; i < section->size / sizeof(void *); i++) {
//找到符號在Symbol Table(數組)中的下標
uint32_t symtab_index = indirect_symbol_indices[i];
if (symtab_index == INDIRECT_SYMBOL_ABS || symtab_index == INDIRECT_SYMBOL_LOCAL ||
symtab_index == (INDIRECT_SYMBOL_LOCAL | INDIRECT_SYMBOL_ABS)) {
continue;
}
//從Symbol Table中找到符號在String Table中的偏移量
uint32_t strtab_offset = symtab[symtab_index].n_un.n_strx;
//String Table的起始地址 + 偏移量,得到符號的名稱
char *symbol_name = strtab + strtab_offset;
if (strnlen(symbol_name, 2) < 2) {
continue;
}
struct rebindings_entry *cur = rebindings;
while (cur) {
for (uint j = 0; j < cur->rebindings_nel; j++) {
if (strcmp(&symbol_name[1], cur->rebindings[j].name) == 0) {
//編譯的時候會將符號轉成帶下劃線的,比如printf會轉成_printf,所以從下劃線後面的字符開始比較
if (cur->rebindings[j].replaced != NULL &&
indirect_symbol_bindings[i] != cur->rebindings[j].replacement) {
//保存原來的符號地址
*(cur->rebindings[j].replaced) = indirect_symbol_bindings[i];
}
//替換__DATA,__la_symbol_ptr表中的符號地址
indirect_symbol_bindings[i] = cur->rebindings[j].replacement;
//退出鏈表的遍歷,即針對同一符號多次調用fishhook重綁定,只有會對最後一次調用的生效
goto symbol_loop;
}
}
cur = cur->next;
}
symbol_loop:;
}
}
遍歷__la_symbol_ptr
表,通過indirect Symbols
、Symbol Table
和String Table
獲取符號名稱,如果是和我們要重綁定的函數名稱一致,則更改__la_symbol_ptr
表中的數據爲要替換的函數地址。最後放一張官方的圖片直觀的查看整個過程:
fishhook官方圖片
四、是否能hook在項目或者靜態庫中的定義的C函數
答案是不能!!!因爲無論在項目中還是靜態庫中的函數,在編譯的時候它們的地址就已經確定(Mach-O基地址+偏移),它們不會存在於__la_symbol_ptr
表中,自然也就無法更改。