Monday, May 28, 2012

Preloading a segfault


Linux (through its dynamic linker) offers a mechanism for loading a predefined shared library prior to loading any other library. This feature can be utilized to override certain functions in other shared libraries (for instance, toprovide a different malloc implementation), or more generally: it can be used to get your own code to execute in the context of a different process. There are, of course, some security restrictions in place for preventing pre-loading your own code with setuid programs and the likes. In this post we shall present an exploitation of this feature which produces quite a frustrating prank.

Apparently, the GNU C library (glibc) comes with a library called libSegFaultwhose purpose is to assist with debugging. Let us consider a different kind of a segfault library; One which has some chance to cause a segmentation fault when it is being loaded.
1// libsegfault: g++ segfault.c -shared -o libsegfault.so
2 
3#include <stdlib.h>
4#include <time.h>
5 
6void segfault () __attribute__ ((constructor));
7 
8void segfault () {
9    srand(time(NULL));
10    if (rand() % 10 < 1)
11        *static_cast<char*>(NULL) = 0;
12}
Statistically, one in every ten invocations of the segfault() function will cause a segmentation fault (by dereferencing the NULL pointer). In our case, we have utilized the constructor attribute from GCC to make sure our function is executed when the library is loaded.
To wrap things up, setting the LD_PRELOAD environmental variable to contain this library will create a very strange system: any command executed by the user (be it even basic shell commands, such as ‘ls’, ‘cat’, etc) has a 10% chance to result in a segmentation fault.
This prank has been pulled on a colleague of mine, and I can’t say he liked it too much. However, the dynamic-loader features presented in this article may be of use in actual work as well — and this is what I hope most of you will take from the post.

No comments:

Post a Comment