前文手工處理了int3中斷,實現了監控Linux系統鍵盤輸入的效果:
https://blog.csdn.net/dog250/article/details/106481123
但是還是太複雜了。在這篇文章中,我深深地知道, int3替換了原來的單字節指令push %rbp,所以int3的處理中要想辦法恢復原始指令執行。
於是,我在int3的處理中改變了RIP,將執行流拉入了一個stub函數,執行完push %rbp之後,再return回原始路徑。
這無可厚非,但是不雅。
不就是一條push %rbp指令嘛,int3中斷處理中直接模擬這條指令的效果不就好了嘛:
- RSP遞減一個long型長度:RSP -= 8
- RBP的值塞入RSP指向的位置:*RSP = RBP
這還不簡單:
#include <linux/module.h>
#include <linux/kdebug.h>
#include <linux/kallsyms.h>
#include <linux/tty.h>
#define DIE_INT3 2
unsigned long orig;
int int3_notify(struct notifier_block *self,
unsigned long val,void* data)
{
struct die_args *args = data;
struct pt_regs *regs = args->regs;
int ret = NOTIFY_DONE;
switch(val){
case DIE_INT3:
{
unsigned long *rsp;
struct tty_struct *tty;
char c;
// 三言兩語完成push %rbp操作
rsp = (unsigned long *)regs->sp;
rsp --;
regs->sp = (unsigned long)rsp;
*rsp = regs->bp;
tty = (struct tty_struct *)regs->di;
c = regs->si;
printk("raw %c %s\n", c, tty->name);
ret = NOTIFY_STOP;
break;
}
default:
break;
}
return ret;
}
static struct notifier_block int3_nb = {
.notifier_call = int3_notify,
.priority =0x7fffffff,
};
unsigned char *p, old;
unsigned long cr0;
static int __init int3hook_init(void)
{
int ret;
ret = register_die_notifier(&int3_nb);
if (ret) {
printk("register_die_notifier failed %d\n", ret);
return ret;
}
orig = (unsigned long)kallsyms_lookup_name("n_tty_receive_char");
p = (unsigned char *)orig;
old = *p;
cr0 = read_cr0();
clear_bit(16, &cr0);
memset(p, 0xcc, 1);
set_bit(16, &cr0);
write_cr0(cr0);
return 0;
}
// exit函數也可以不提供
static void __exit int3hook_exit(void)
{
cr0 = read_cr0();
clear_bit(16, &cr0);
memset(p, old, 1);
set_bit(16, &cr0);
write_cr0(cr0);
unregister_die_notifier(&int3_nb);
}
module_init(int3hook_init)
module_exit(int3hook_exit)
MODULE_LICENSE("GPL");
你看,沒有了stub函數,是不是清爽了很多呢?
看看效果:
[root@localhost probe]# insmod ./2int3hook.ko
[root@localhost probe]# dmesg
[ 528.960858] raw d pts0
[ 529.080784] raw m pts0
[ 529.217513] raw e pts0
[ 529.392473] raw s pts0
[ 529.593502] raw pts0
pts0.104994] raw
dmesg和回車被記錄了下來。
浙江溫州皮鞋溼,下雨進水不會胖。