LD-PRELOAD

From aldeid
Jump to: navigation, search

Description

The
LD_PRELOAD
enables to hook functions. It can be very handy in some situations (e.g. debugging, cracking).

Examples

Hook a function in a program

Supposed we have the following source (
chall.c
):
chall.c
#include <stdio.h>
#include <string.h>
 
int main(int argc, char *argv[]) {
    char secret[20] = "Very#S3Cr37_Mess4G3";
    char guess[20] = "";
    printf("What is the secret? ");
    scanf("%20s", guess);
    if(strcmp(secret, guess) == 0) {
        printf("Bazinga!\n");
    } else {
        printf("Oh no!\n");
    }
    return 0;
}

Let's compile it:

$ gcc -o chall.c chall

When provided with an incorrect secret message, the program will display "Oh no!":

$ ./chall 
What is the secret? azerty
Oh no!

And when the expected secret is given, the program outputs "Bazinga!":

$ ./chall 
What is the secret? Very#S3Cr37_Mess4G3
Bazinga!
Of course, this example is very simple and we wouldn't need to hook the
strcmp
function to solve this challenge, but let's try for learning purposes. We will now write a library (
strcmp.c
) as follows:
strcmp.c
#include <stdio.h>

int strcmp(const char *secret, const char *guess) {
    printf("secret: %s\n", secret);
    return 0;
}

Now, let's compile:

$ gcc -shared -fPIC -o strcmp.so strcmp.c
And let's run our challenge with
LD_PRELOAD
as follows:
$ LD_PRELOAD=$PWD/strcmp.so ./chall
What is the secret? anything
secret: Very#S3Cr37_Mess4G3
Bazinga!
The
strcmp
function has been hooked by our custom function to reveal the secret message.

Comments

blog comments powered by Disqus

Keywords: LD_PRELOAD ctf challenge reversing