Archive

Archive for the ‘Linux’ Category

PreZ: my new injector!

March 25th, 2010 Fotis 4 comments

Together with my presentation at 0×375 0×2 (check previous post), I wrote a proof of concept program, PreZ! What it does is create a new thread at a running program. I will give a small description of the way it works. The images below are taken from the presentation and refer to the linux version but the same concept is used in all versions, i.e. linux, freebsd and opensolaris.

PreZ consists of three parts, the injector, the thread creation code and the code that will be executed at the new thread (the shell code). The following steps take place each time you run PreZ.

At the beginning the injector stops the traced process, the ‘victim’. It’s state is saved (registers and some other stuff at the opensolaris version) and part of the code at the place where the EIP register points to. This code is then overwritten with the other two parts so we have the modified address space at the image above. The execution then continues and the new code we just injected runs.

What the new code does is mmap a new space with read, write and execute permissions (the orange space at the image above). Then, the shellcode at the end is copied to this new location. All this runs in a single thread (the purple thread of execution at the image). A new thread is spawned and now we have two different threads of execution, the green and the pink at the image above.

Finally, the new thread jumps to the place where we copied the new code and the original thread executes an int3 instruction. When this instruction is executed, the injector catches the trap and knows that the thread has been created successfully. The original code read at the beginning is restored, the state is restored, and finally execution continues. All these are transparent to the original process which can’t understand that the injected code has been executed.

PreZ v1.0 can be downloaded from this link. The sample code for the new thread listens for a connection to port 65226 and when it accepts one it spawns a shell. You can do much more, this is just a simple code to demonstrate the injection process.

Categories: Linux, Programming, Security Tags:

My 0×375 presentation – injecting code at a running process!

March 22nd, 2010 Fotis 2 comments

It’s been a LOT of time since I last posted to my blog. Unfortunately, I’ve been too busy to write something even if I had some ideas. So, here is my first post after more than a month of absence!

I recently made a presentation at the 0×375 (Thessaloniki Tech Talk Sessions). You can find more info about 0×375 at the grhack site. In short, it is a series of some tech talk session where anyone can present his work on a subject. Submissions are open for everyone. There are no regular dates but if you watch the site you can find info about when and where the next event will take place (always at Thessaloniki and till now at the Aristotle University).

My presentation was about injecting code at a running process and running it as a separate thread. You can download it here. Since 0×375 takes place in Greece the presentation is written in Greek, sorry if you can’t ready it! In short what the technique I presented and the accompanying program does is create a new thread at a running process. The presentation talks about Linux, however a freebsd and an opensolaris version are ready. I will put them online soon so you can check it out. Wait for the next post!

Categories: Linux, Programming, Security Tags:

Ext4 online defrag and how you can mess up everything when implementing it

December 20th, 2009 Fotis 2 comments

It’s been a long time since I last posted something at my blog. Unfortunatelly, I’m too busy so I have almost no time to write something!

This post is about the online defrag the ext4 filesystem supports. It is a very cool feature and allows you to defrag any file without even unmounting a filesystem! This is done using a special ioctl, EXT4_IOC_MOVE_EXT defined as follows:

1
#define EXT4_IOC_MOVE_EXT   _IOWR('f', 15, struct move_extent)

As you can see the ioctl’s last parameter is a special structure, struct move_extent, defined as:

1
2
3
4
5
6
7
8
struct move_extent {
    int orig_fd;
    int donor_fd;
    uint64_t orig_start;
    uint64_t donor_start;
    uint64_t len;
    uint64_t moved_len;
};

What the ioctl does is copy len extents from the file with descriptor orig_fd starting with orig_start to the one with descriptor donor_fd starting at donor_start. Finally it returns the total number of extents moved at the member moved_len. Using this syscall it is pretty easy to defrag files. You must first open a new file, which will be the donor, and allocate some space using fallocate. Hopefully the extents of the new file will be less than the ones of the original file so you just swap the extents of donor using the ones from the original file. The following code is a simple call to this ioctl which can help you understand how it works:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
int origfd, donorfd;
int origsize;
struct move_extent me;
char *origfile, *donorfile;
 
/* origfile, donorfile and origsize should be set here */
 
if((origfd = open(origfile, O_RDONLY | O_EXCL)) < 0) {
    perror("Cannot open original file");
    exit(1);
}
 
if((donorfd = open(donorfile, O_WRONLY | O_CREAT | O_EXCL)) < 0) {
    perror("Cannot create donor file");
    exit(1);
}
 
if(fallocate(donorfd, 0, 0, origsize) < 0) {
    perror("Cannot allocate space for donor");
    exit(1);
}
 
memset(&me, 0, sizeof(me));
me.orig_fd = origfd;
me.donor_fd = donorfd;
me.orig_start = 0;
me.donor_start = 0;
me.len = extentcnt;
 
if(ioctl(origfd, EXT4_IOC_MOVE_EXT, &me) < 0) {
    perror("Cannot move extents");
    exit(1);
}
 
printf("Moved extents: %i\n", me.moved_len);
 
close(origfd);
close(donorfd);

You should note that there is no restriction on the doner file, it can be any file on the disk.

And here it is! CVE-2009-4131! Until commit 910123ba363623f15ffb5d05dd87bdf06d08c609 the only check was if the user could read the donor file, not write it! Furthermore, there were no checks on the file’s mode. You can simply open your program which executes /bin/sh as the original file, /bin/ping as the donor and kaboom! /bin/ping is an suid root executable and the code that will be executed will be your code!

I have written a small program that you can use to demonstrate this vulnerability. It simply moves extents. You can download it here. Just use a program that spawns a shell as the original file, a suid root file as a donor, zero as the offset and ceil(filesize/1024) as len. However, it is not very usable yet since for some strange reason you need to unmount the fs and then remount it in order for the changes to take effect. If you find a solution just leave a comment!

UPDATE: Try reading a LOT of data from the partition after running the program! Damn cache! I shouldn’t have been working with a filesystem that’s 10mbs and store only the executable there!

Categories: Linux, Programming Tags:

Concurrent programming the fast and dirty way!

November 20th, 2009 Fotis No comments

Creating threads, mutexes, setting attributes and joining can be very easy using the pthreads library. However, there are times when you don’t want to link your program with another library or you need something fast. As an example you can see the pipe exploit where I need only two threads to trigger the race condition.

Here’s a simple way to create these threads. First, we need to allocate the stack for the thread using malloc(3) and then we can start it using clone(2).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
int koko(void *arg)
{
    /* do something concurrently with main */
}
 
int start_thread(int (*func)(void *), void *arg)
{
    int thread_id;
    char *stack;
 
    if((stack = malloc(0x4000)) == NULL) {
        perror("malloc");
        return -1;
    }
 
    if((thread_id = clone(func, stack + 0x4000 - sizeof(unsigned long), CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_VM | CLONE_THREAD, arg)) < 0) {
        perror("clone");
        return -1;
    }
 
    return thread_id;
}
 
int main()
{
    int thread_id;
    if((thread_id = startthread(koko, NULL)) == -1) {
        printf("Couldn't start thread.\n");
        exit(1);
    }
 
    /* This runs together with koko */
}

Using this code we create a new thread running in the same thread group. This means that calling getpid(2) will return the same pid. In order to distinguish threads in the same thread group you must use gettid(2) to get the thread id.

When creating a thread in the same thread group you cannot get the return value from the function you called. In order to get this value when it finishes you must create a thread in a new thread group which will be assigned a new pid and then call wait(2). To create such a thread you have to remove the CLONE_THREAD flag and replace it with SIGCHLD which will be the signal that will be send to the parent when the function returns. If we choose to send another signal, then wait(2) should be called with the __WALL or __WCLONE options.

These were the basics of creating threads. However, creating threads is only a part of concurrent programming. We will now create spinlocks using some internal functions of gcc. So, here are lock and unlock functions.

1
2
3
4
5
6
7
8
9
10
void lock(int spinlock)
{
    while(__sync_lock_test_and_set(&spinlock, 1))
        ;
}
 
void unlock(int spinlock)
{
    __sync_lock_release(&amp;spinlock);
}

It’s pretty simple using the functions gcc provides us. You can find more at the gcc documentation about atomic builtins.

Categories: Linux, Programming Tags:

Loading symbols when debugging the kernel and kernel modules

October 29th, 2009 Fotis No comments

Recently I received some comments from a friend about a previous article on linux kernel debugging using kgdb. What he asked me was how could he load symbols from a kernel or a kernel module. So I wrote a quick guide to help you start with kernel debugging. After each step I will show you the gdb output.

First of all you should start gdb!

$ gdb
GNU gdb (GDB) 6.8.50.20090628-cvs-debian
Copyright (C) 2009 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "i486-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
(gdb)

Then you should load all kernel symbols from the vmlinux file. This can be found at the directory where you compiled the kernel, most probably /usr/src/linux. Remember to compile the kernel using debug information by setting the appropriate option, it will help you a lot!

(gdb) file vmlinux
Reading symbols from /home/fotisl/programs/kgdb/vmlinux...done.
(gdb)

You’re ready to start debugging! Set the target and use the Alt-SysRq-G sequence as it was described at the previous post. You can now set breakpoints, watch anything you want in memory, step or continue running the kernel!

(gdb) target remote /dev/pts/12
Remote debugging using /dev/pts/12
kgdb_breakpoint (key=103, tty=0x0) at kernel/kgdb.c:1721
1721            wmb(); /* Sync point after breakpoint */
(gdb)

Now let’s see how we can debug kernel modules. I will test the l2cap bluetooth kernel module.

You first need to find the object file which contains the module. For l2cap this is net/bluetooth/l2cap.o in the kernel source tree. Transfer this to the host (or the machine running gdb if you’re not using a virtual machine). Then load the module in the virtual machine. This creates a new directory in /sys/module named after the module name, i.e. l2cap. Inside this directory, there is another one named sections which contains the addresses where all sections are loaded. We are interested in the .text section so we read the file /sys/module/l2cap/sections/.text.

$ cat /sys/module/l2cap/sections/.text
0xe0c77000

We know where the .text section is loaded so we can now load the symbols from l2cap.o using the add-symbol-file gdb command.

(gdb) add-symbol-file l2cap.o 0xe0c77000
add symbol table from file "l2cap.o" at
        .text_addr = 0xe0c77000
(y or n) y
Reading symbols from /home/fotisl/programs/kgdb/l2cap.o...done.
(gdb)

If you need to load other sections too, in case they are not contiguous with the text in memory, you need to read their addresses. For example we’ll load both the .text and the .data sections (you should do .bss too but it’s omitted since I wanted to write a quick and dirty guide and it’s already very big!)

Find where both .text and .data are loaded.

$ cat /sys/module/l2cap/sections/.text
0xe0c77000
$ cat /sys/module/l2cap/sections/.data
0xe0c7b438

Then you load apart from the .text section the .data too.

(gdb) add-symbol-file l2cap.o 0xe0c77000 -s .data 0xe0c7b438
add symbol table from file "l2cap.o" at
        .text_addr = 0xe0c77000
        .data_addr = 0xe0c7b438
(y or n) y
Reading symbols from /home/fotisl/programs/kgdb/l2cap.o...done.
(gdb)

You’re now ready to start debugging your kernel module!

Categories: Linux, Linux Kernel, Programming Tags:

Debugging the linux kernel using kgdb and VirtualBox

September 6th, 2009 Fotis 5 comments

Kgdb is a source level debugger for the linux kernel. It requires two machines, one running a kernel compiled with kgdb enabled and the second one running gdb. It can be found at sourceforge and a light version has been merged into the 2.6.26 kernel. There is an article at kerneltrap which contains all the appropriate information about this light version and it’s differences from the full one. I am going to describe how you can debug a linux kernel running under VirtualBox using the kgdb-light debugger.

First of all you must define a serial port. Go to the settings of your virtual machine, then at the “Serial Ports” and enable “Port 1″. Use port number COM1, port mode ‘Host Pipe’, check ‘Create Pipe’ and enter a path, e.g. /home/fotisl/virtualbox/myvm/serial1. You can use another port number, e.g. COM2, but then you’ll have to change the device below to ttyS1, ttyS2 for COM3 etc. Furthermore, you can create the pipe yourself and not automatically using:

$ mkfifo /home/fotisl/virtualbox/myvm/serial1

At your virtual machine you must have a kernel compiled with the option CONFIG_KGDB. You can find this under the “Kernel debugging” menu. I also advise you to enable the CONFIG_DEBUG_INFO to insert debug symbols.

At the host machine you only need to install socat and of course gdb. Socat is a multipurpose relay which can be found here. You should also transfer the uncompressed image of the kernel running at the vm. It can be found at the directory where you compiled the kernel and it’s name will be vmlinux.

You are now ready to start. At the host machine run:

$ socat -d -d /home/fotisl/virtualbox/myvm/serial1 pty:
2009/01/01 00:00:00 socat[12345] N opening connection to AF=1 "/home/fotisl/virtualbox/myvm/serial1"
2009/01/01 00:00:00 socat[12345] N successfully connected from local address AF=1 "\x04\b\xAB"
2009/01/01 00:00:00 socat[12345] N successfully connected via \xD0\xA7\x10
2009/01/01 00:00:00 socat[12345] N PTY is /dev/pts/4
2009/01/01 00:00:00 socat[12345] N starting data transfer loop with FDs [3,3] and [4,4]

You must note the PTY, in this case /dev/pts/4. Now fire gdb and load vmlinux. Then set the remote baud to 115200 and attach to the serial port.

$ gdb ~/vmlinux
GNU gdb (GDB) 6.8.50.20090628-cvs-debian
Copyright (C) 2009 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "i486-linux-gnu".
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>...
(gdb) set remotebaud 115200
(gdb) target remote /dev/pts/4
Remote debugging using /dev/pts/4

Now switch to the virtual machine. You must first set the serial port that kgdb will use.

# echo ttyS0,115200 > /sys/module/kgdboc/parameters/kgdboc

You’re ready to start debugging! When you want to break use the Alt-SysRq-G key combination or use

# echo g > /proc/sysrq-trigger

If you want to start the debugging when the kernel starts loading, append

kgdboc=ttyS0,115200 kgdbwait

to the command line parameters of the kernel. You must use this order! First you must register the I/O driver and then kgdb will be able to wait.

You can now explore the linux kernel! Warning, messing with various structures and executing code that you shouldn’t can cause kernel panics and mess up your virtual machine! But you already know that, that’s why you use virtualbox!

Categories: Linux, Linux Kernel, Programming Tags:
SEO Powered by Platinum SEO from Techblissonline