本文共 2687 字,大约阅读时间需要 8 分钟。
在内核中替换函数的方法可以通过以下步骤实现:
内核提供了text_poke_smp函数来完成上述操作。以下是一个实现示例:
#include#include #include #include #include #define OPTSIZE 5char saved_op[OPTSIZE] = {0};char jump_op[OPTSIZE] = {0};static unsigned int (*ptr_orig_conntrack_in)(const struct nf_hook_ops *ops, struct sk_buff *skb, const struct net_device *in, const struct net_device *out, const struct nf_hook_state *state);static unsigned int (*ptr_ipv4_conntrack_in)(const struct nf_hook_ops *ops, struct sk_buff *skb, const struct net_device *in, const struct net_device *out, const struct nf_hook_state *state);static unsigned int stub_ipv4_conntrack_in(const struct nf_hook_ops *ops, struct sk_buff *skb, const struct net_device *in, const struct net_device *out, const struct nf_hook_state *state){ printk("hook stub conntrack\n"); return 0;}static unsigned int hook_ipv4_conntrack_in(const struct nf_hook_ops *ops, struct sk_buff *skb, const struct net_device *in, const struct net_device *out, const struct nf_hook_state *state){ printk("hook conntrack\n"); return ptr_orig_conntrack_in(ops, skb, in, out, state);}static void *(*ptr_poke_smp)(void *addr, const void *opcode, size_t len);static __init int hook_conn_init(void){ s32 hook_offset, orig_offset; ptr_poke_smp = kallsyms_lookup_name("text_poke_smp"); if (!ptr_poke_smp) { printk("err"); return -1; } ptr_ipv4_conntrack_in = kallsyms_lookup_name("ipv4_conntrack_in"); if (!ptr_ipv4_conntrack_in) { printk("err"); return -1; } jump_op[0] = 0xe9; hook_offset = (s32)((long)hook_ipv4_conntrack_in - (long)ptr_ipv4_conntrack_in - OPTSIZE); *(s32*)(&jump_op[1]) = hook_offset; saved_op[0] = 0xe9; orig_offset = (s32)((long)ptr_ipv4_conntrack_in + OPTSIZE - ((long)stub_ipv4_conntrack_in + OPTSIZE)); *(s32*)(&saved_op[1]) = orig_offset; get_online_cpus(); ptr_poke_smp(stub_ipv4_conntrack_in, saved_op, OPTSIZE); ptr_orig_conntrack_in = stub_ipv4_conntrack_in; barrier(); ptr_poke_smp(ptr_ipv4_conntrack_in, jump_op, OPTSIZE); put_online_cpus(); return 0;}static __exit void hook_conn_exit(void){ get_online_cpus(); ptr_poke_smp(ptr_ipv4_conntrack_in, saved_op, OPTSIZE); ptr_poke_smp(stub_ipv4_conntrack_in, stub_op, OPTSIZE); barrier(); put_online_cpus();}module_init(hook_conn_init);module_exit(hook_conn_exit);MODULE_DESCRIPTION("hook test");MODULE_LICENSE("GPL");MODULE_VERSION("1.1");
通过以上方法,可以在内核中实现函数指令的替换,适用于需要监控或修改内核函数的场景。
转载地址:http://zjkz.baihongyu.com/