programing tip

Linux 커널 : 시스템 호출 후킹 예제

itbloger 2020. 11. 15. 11:00
반응형

Linux 커널 : 시스템 호출 후킹 예제


시스템 호출 테이블을 연결하는 데모로 간단한 테스트 코드를 작성하려고합니다.

"sys_call_table"은 더 이상 2.6에서 내보내지지 않으므로 System.map 파일에서 주소를 가져 왔고 올바른지 확인할 수 있습니다 (찾은 주소의 메모리를 살펴보면 해당 주소에 대한 포인터를 볼 수 있습니다. 시스템 호출).

그러나이 테이블을 수정하려고하면 커널에서 "가상 주소 c061e4f4에서 커널 페이징 요청을 처리 할 수 ​​없음"과 함께 "죄송합니다."라는 메시지가 표시되고 시스템이 재부팅됩니다.

2.6.18-164.10.1.el5를 실행하는 CentOS 5.4입니다. 어떤 종류의 보호가 있습니까? 아니면 버그가 있습니까? SELinux와 함께 제공된다는 것을 알고 있으며 허용 모드로 설정해 보았지만 차이가 없습니다.

내 코드는 다음과 같습니다.

#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/unistd.h>

void **sys_call_table;

asmlinkage int (*original_call) (const char*, int, int);

asmlinkage int our_sys_open(const char* file, int flags, int mode)
{
   printk("A file was opened\n");
   return original_call(file, flags, mode);
}

int init_module()
{
    // sys_call_table address in System.map
    sys_call_table = (void*)0xc061e4e0;
    original_call = sys_call_table[__NR_open];

    // Hook: Crashes here
    sys_call_table[__NR_open] = our_sys_open;
}

void cleanup_module()
{
   // Restore the original call
   sys_call_table[__NR_open] = original_call;
}

마침내 답을 찾았습니다.

http://www.linuxforums.org/forum/linux-kernel/133982-cannot-modify-sys_call_table.html

커널은 시스템 호출 테이블이 읽기 전용이되도록 변경되었습니다.

cypherpunk :

늦었지만 솔루션이 다른 사람들에게도 흥미로울 수 있습니다 : entry.S 파일에서 찾을 수 있습니다 : 코드 :

.section .rodata,"a"
#include "syscall_table_32.S"

sys_call_table-> ReadOnly sys_call_table로 "해킹"하려면 커널을 새로 컴파일해야합니다 ...

링크에는 쓰기 가능하도록 메모리를 변경하는 예도 있습니다.

나세 코모에 :

여러분 안녕하세요. 답장 해 주셔서 감사합니다. 오래 전에 메모리 페이지에 대한 액세스를 수정하여 문제를 해결했습니다. 내 상위 수준 코드에 대해 수행하는 두 가지 기능을 구현했습니다.

#include <asm/cacheflush.h>
#ifdef KERN_2_6_24
#include <asm/semaphore.h>
int set_page_rw(long unsigned int _addr)
{
    struct page *pg;
    pgprot_t prot;
    pg = virt_to_page(_addr);
    prot.pgprot = VM_READ | VM_WRITE;
    return change_page_attr(pg, 1, prot);
}

int set_page_ro(long unsigned int _addr)
{
    struct page *pg;
    pgprot_t prot;
    pg = virt_to_page(_addr);
    prot.pgprot = VM_READ;
    return change_page_attr(pg, 1, prot);
}

#else
#include <linux/semaphore.h>
int set_page_rw(long unsigned int _addr)
{
    return set_memory_rw(_addr, 1);
}

int set_page_ro(long unsigned int _addr)
{
    return set_memory_ro(_addr, 1);
}

#endif // KERN_2_6_24

나를 위해 작동하는 원래 코드의 수정 된 버전이 있습니다.

#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/unistd.h>
#include <asm/semaphore.h>
#include <asm/cacheflush.h>

void **sys_call_table;

asmlinkage int (*original_call) (const char*, int, int);

asmlinkage int our_sys_open(const char* file, int flags, int mode)
{
   printk("A file was opened\n");
   return original_call(file, flags, mode);
}

int set_page_rw(long unsigned int _addr)
{
   struct page *pg;
   pgprot_t prot;
   pg = virt_to_page(_addr);
   prot.pgprot = VM_READ | VM_WRITE;
   return change_page_attr(pg, 1, prot);
}

int init_module()
{
    // sys_call_table address in System.map
    sys_call_table = (void*)0xc061e4e0;
    original_call = sys_call_table[__NR_open];

    set_page_rw(sys_call_table);
    sys_call_table[__NR_open] = our_sys_open;
}

void cleanup_module()
{
   // Restore the original call
   sys_call_table[__NR_open] = original_call;
}

Thanks Stephen, your research here was helpful to me. I had a few problems, though, as I was trying this on a 2.6.32 kernel, and getting WARNING: at arch/x86/mm/pageattr.c:877 change_page_attr_set_clr+0x343/0x530() (Not tainted) followed by a kernel OOPS about not being able to write to the memory address.

The comment above the mentioned line states:

// People should not be passing in unaligned addresses

The following modified code works:

int set_page_rw(long unsigned int _addr)
{
    return set_memory_rw(PAGE_ALIGN(_addr) - PAGE_SIZE, 1);
}

int set_page_ro(long unsigned int _addr)
{
    return set_memory_ro(PAGE_ALIGN(_addr) - PAGE_SIZE, 1);
}

Note that this still doesn't actually set the page as read/write in some situations. The static_protections() function, which is called inside of set_memory_rw(), removes the _PAGE_RW flag if:

  • It's in the BIOS area
  • The address is inside .rodata
  • CONFIG_DEBUG_RODATA is set and the kernel is set to read-only

I found this out after debugging why I still got "unable to handle kernel paging request" when trying to modify the address of kernel functions. I was eventually able to solve that problem by finding the page table entry for the address myself and manually setting it to writable. Thankfully, the lookup_address() function is exported in version 2.6.26+. Here is the code I wrote to do that:

void set_addr_rw(unsigned long addr) {

    unsigned int level;
    pte_t *pte = lookup_address(addr, &level);

    if (pte->pte &~ _PAGE_RW) pte->pte |= _PAGE_RW;

}

void set_addr_ro(unsigned long addr) {

    unsigned int level;
    pte_t *pte = lookup_address(addr, &level);

    pte->pte = pte->pte &~_PAGE_RW;

}

Finally, while Mark's answer is technically correct, it'll case problem when ran inside Xen. If you want to disable write-protect, use the read/write cr0 functions. I macro them like this:

#define GPF_DISABLE write_cr0(read_cr0() & (~ 0x10000))
#define GPF_ENABLE write_cr0(read_cr0() | 0x10000)

Hope this helps anyone else who stumbles upon this question.


Note that the following will also work instead of using change_page_attr and cannot be depreciated:

static void disable_page_protection(void) {

    unsigned long value;
    asm volatile("mov %%cr0,%0" : "=r" (value));
    if (value & 0x00010000) {
            value &= ~0x00010000;
            asm volatile("mov %0,%%cr0": : "r" (value));
    }
}

static void enable_page_protection(void) {

    unsigned long value;
    asm volatile("mov %%cr0,%0" : "=r" (value));
    if (!(value & 0x00010000)) {
            value |= 0x00010000;
            asm volatile("mov %0,%%cr0": : "r" (value));
    }
}

If you are dealing with kernel 3.4 and later (it can also work with earlier kernels, I didn't test it) I would recommend a smarter way to acquire the system callы table location.

For example

#include <linux/module.h>
#include <linux/kallsyms.h>

static unsigned long **p_sys_call_table;
/* Aquire system calls table address */
p_sys_call_table = (void *) kallsyms_lookup_name("sys_call_table");

That's it. No addresses, it works fine with every kernel I've tested.

The same way you can use a not exported Kernel function from your module:

static int (*ref_access_remote_vm)(struct mm_struct *mm, unsigned long addr,
                void *buf, int len, int write);
ref_access_remote_vm = (void *)kallsyms_lookup_name("access_remote_vm");

Enjoy!

참고URL : https://stackoverflow.com/questions/2103315/linux-kernel-system-call-hooking-example

반응형