fishhook源码学习

栏目: C · 发布时间: 7年前

内容简介:距离上个文章已经有段时间了,虽然没多少人阅读但是好在自娱自乐,前段时间出去受虐一波,所以又开始发愤图强,开始向以前比较常用的一些厉害的开源库学习学习.闲话不多说,假如你在使用一个三方的framework的时候它里面无时无刻的打印着一些无用的信息而且市面上没有很好的去替代它的产品,这时候就可以把这样就成功的在main函数调用之前就将

距离上个文章已经有段时间了,虽然没多少人阅读但是好在自娱自乐,前段时间出去受虐一波,所以又开始发愤图强,开始向以前比较常用的一些厉害的开源库学习学习.闲话不多说, fishhook 是facebook出的一款可以修改外链的C方法(非自己所写的方法,一般存在于app启动时使用dyld加载的动态库中)的一个库,整个文件只有200多行代码.

用法

假如你在使用一个三方的framework的时候它里面无时无刻的打印着一些无用的信息而且市面上没有很好的去替代它的产品,这时候就可以把 fishhook 请出来将对应的打印函数给hook掉,比如

static void (*orig_printf)(char *format, ...);
int main(int argc, const char * argv[]) {
	printf("abcd");
	return 0;
}
static void	 my_printf(const char * s, ...){
//这里可以写你想替换的代码
//比如  orig_printf("dcba");
}
__attribute((constructor)) void injected_function(){
	rebind_symbols((struct rebinding[1]){{"printf", my_printf, (void *)&orig_printf}},1);
}
复制代码

这样就成功的在main函数调用之前就将 printf 函数给替换了,可以远离烦人的打印.

int rebind_symbols(struct rebinding rebindings[], size_t rebindings_nel) 的第一个参数是个结构体数组

struct rebinding {
  const char *name; 
  void *replacement;
  void **replaced;
};
复制代码

name 是想要hook的的函数名称, replacement 是替换后的函数指针, replaced 是传入一个指向函数指针的指针(如果将函数成功的替换后,会将原函数的值给放入其中)

当然在很多情况中我们会在逆向中用到fishhook,并且fishhook只能去替换链接外部动态库中的代码,自己写的C函数不能去替换

Mach-O

在去阅读 fishhook 的时候我个人认为是必须对 Mach-O 有一些了解。 Mach-O 是iOS/MacOS下面的可执行文件,在iOS工程下使用 command+b 编译后会在 Products 目录下生成一个 .app 文件,. .app 中一个同名文件就是我们的 Mach-O 文件了,它里面包含了我们app的类,方法,以及编译期间就确定常量等内容。

fishhook源码学习

这是Mach-O的大致布局

  • Header:保存了一些Mach-O的基本信息,比如是32位/64位,LoadCommand的个数等
  • LoadCommand: 这一段跟着Header排布,加载Mach-O时会从这里面获取到对应的数据来确定内存分布
  • Data: 这里面保存了具体的数据,里面细分为多个segment,segment在分为多个section,这里面包含了具体的代码与数据等信息
    我们实际用 工具 去看下Mach-O,新建一个iOS工程,什么代码都不加,直接编译一下,然后使用 MachOView 查看
    fishhook源码学习
    因为本文关注的是 fishhook ,我们主要关注 __Data 段中的 __la_symbol_ptr 这个section(这个section表示的是懒加载的符号表,如果我们自己写的函数会在编译时确定地址写入macho,而系统的例如printf这些编译期间是不确认地址的),然后与之相关的还需要关注 Symbol TableDynamic Symbol Table__LINKEDIT

因为MachO里面的东西太多就不过多的去描述,大概有些了解知道它是什么东西就可以阅读fishhook源码,如果想要深入的了解MachO可以看这篇博客

阅读源码

下面就开始进入正题了,开始去阅读fishhook的源码。我们直接从我们的调用函数看 int rebind_symbols(struct rebinding rebindings[], size_t rebindings_nel)

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 函数,传入了三个参数,第一个参数是指向私有结构体 static struct rebindings_entry *_rebindings_head 的指针,第二个参数 struct rebinding 结构体数组,第三个值是结构体数组的长度

static int prepend_rebindings(struct rebindings_entry **rebindings_head,
                              struct rebinding rebindings[],
                              size_t nel) {
  struct rebindings_entry *new_entry = malloc(sizeof(struct rebindings_entry));
  if (!new_entry) {
    return -1;
  }
  new_entry->rebindings = malloc(sizeof(struct rebinding) * nel);
  if (!new_entry->rebindings) {
    free(new_entry);
    return -1;
  }
  memcpy(new_entry->rebindings, rebindings, sizeof(struct rebinding) * nel);
  new_entry->rebindings_nel = nel;
  new_entry->next = *rebindings_head;
  *rebindings_head = new_entry;
  return 0;
}
复制代码

这里面的代码比较简单

  • 初始化一个 struct rebindings_entry 结构体
  • 在将结构体中数组初始化
  • 将我们传入的结构体数组的值copy到刚初始化的数组中
  • 在将新初始化的结构体放在这个链表的最前面 在往下走看到以链表的next指针判断该方法是否第一次调用,如果第一次调用则调用 _dyld_register_func_for_add_image 方法,并传入 _rebind_symbols_for_image 函数指针

_dyld_register_func_for_add_image 注册自定义的回调函数,同时也会为所有已经加载的动态库或可执行文件执行回调

每个动态库都会回调 _rebind_symbols_for_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;
  segment_command_t *linkedit_segment = NULL;
  struct symtab_command* symtab_cmd = NULL;
  struct dysymtab_command* dysymtab_cmd = NULL;

  uintptr_t cur = (uintptr_t)header + sizeof(mach_header_t);
  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_LINKEDIT) == 0) {
        linkedit_segment = cur_seg_cmd;
      }
    } else if (cur_seg_cmd->cmd == LC_SYMTAB) {
      symtab_cmd = (struct symtab_command*)cur_seg_cmd;
    } else if (cur_seg_cmd->cmd == LC_DYSYMTAB) {
      dysymtab_cmd = (struct dysymtab_command*)cur_seg_cmd;
    }
  }
  ...
}
复制代码

这段代码主要是为了获取对应的 Symbol TableDynamic Symbol Table__LINKEDIT 段对应的结构体

uintptr_t cur = (uintptr_t)header + sizeof(mach_header_t);

在往下看

static void rebind_symbols_for_image(struct rebindings_entry *rebindings,
                                     const struct mach_header *header,
                                     intptr_t slide) {
    ...
  // Find base symbol/string table addresses
  uintptr_t linkedit_base = (uintptr_t)slide + linkedit_segment->vmaddr - linkedit_segment->fileoff;
  nlist_t *symtab = (nlist_t *)(linkedit_base + symtab_cmd->symoff);
  char *strtab = (char *)(linkedit_base + symtab_cmd->stroff);

  // Get indirect symbol table (array of uint32_t indices into symbol table)
  uint32_t *indirect_symtab = (uint32_t *)(linkedit_base + dysymtab_cmd->indirectsymoff);

  cur = (uintptr_t)header + sizeof(mach_header_t);
  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) {
        continue;
      }
      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) {
          perform_rebinding_with_section(rebindings, sect, slide, symtab, strtab, indirect_symtab);
        }
        if ((sect->flags & SECTION_TYPE) == S_NON_LAZY_SYMBOL_POINTERS) {
          perform_rebinding_with_section(rebindings, sect, slide, symtab, strtab, indirect_symtab);
        }
      }
    }
  }
}
复制代码

首先是可以根据上面代码得到个结论, 程序的基地址 = sild + __LINKEDIT->vmaddr - __LINKEDIT->fileoff ,这里面的 __LINKEDIT->vmaddr__LINKEDIT 在内存中的地址, fileoff__LINKEDIT 在mach-o文件中的偏移量,那么 silde 是什么?其实 silde 就是 ASLR ,那 ASLR 又是什么? ASLR:Address space layout randomization ,通俗的说就是在app每次启动的时候会随机给一个地址偏移量,然后我们真正的内存地址就是 Mach-O 中的地址加上这个偏移量。得到程序的基地址后在根据符号表中的偏移值得到符号表中的数据,之后在遍历一遍LoadCommand,寻找 __DATA__DATA_CONST 的section,并对对 __nl_symbol_ptr 以及 __la_symbol_ptr 进行重新绑定。

接下来调用了 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) {
  uint32_t *indirect_symbol_indices = indirect_symtab + section->reserved1;
  void **indirect_symbol_bindings = (void **)((uintptr_t)slide + section->addr);
  for (uint i = 0; i < section->size / sizeof(void *); i++) {
    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;
    }
    uint32_t strtab_offset = symtab[symtab_index].n_un.n_strx;
    char *symbol_name = strtab + strtab_offset;
    bool symbol_name_longer_than_1 = symbol_name[0] && symbol_name[1];
    struct rebindings_entry *cur = rebindings;
    while (cur) {
      for (uint j = 0; j < cur->rebindings_nel; j++) {
        if (symbol_name_longer_than_1 &&
            strcmp(&symbol_name[1], cur->rebindings[j].name) == 0) {
          if (cur->rebindings[j].replaced != NULL &&
              indirect_symbol_bindings[i] != cur->rebindings[j].replacement) {
            *(cur->rebindings[j].replaced) = indirect_symbol_bindings[i];
          }
          indirect_symbol_bindings[i] = cur->rebindings[j].replacement;
          goto symbol_loop;
        }
      }
      cur = cur->next;
    }
  symbol_loop:;
  }
}
复制代码

这段函数看起来稍微有点长,但是逻辑是很好去理解的,首先先根据动态符号表中地址 + 在符号表中的index 获得在该段在动态符号表中的位置( reserved1 的值表示偏移量),进行一个for循环在每次循环中获取到对应方法的方法名,然后在遍历私有结构体链表 struct rebindings_entry * ,把链表中的每个结构体中的数组中的方法名与当前的表中的方法名比较,如果相同就将符号表中的指针信息保存给外面调用时传入的指向函数指针的指针中,在表中的指针替换成我们传入的函数指针,就这样就完成了一次偷天换日的过程。 最后借官方的图

fishhook源码学习

以上所述就是小编给大家介绍的《fishhook源码学习》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Linux Command Line

The Linux Command Line

William E. Shotts Jr. / No Starch Press, Incorporated / 2012-1-17 / USD 39.95

You've experienced the shiny, point-and-click surface of your Linux computer-now dive below and explore its depths with the power of the command line. The Linux Command Line takes you from your very ......一起来看看 《The Linux Command Line》 这本书的介绍吧!

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具