Adarsh Dinesh
Adarsh Dinesh

Reputation: 106

Failed to get root shell while loading execl() function

#include <stdio.h>
#include <unistd.h>
#include <string.h>

int good(int addr) {
    printf("Address of hmm: %p\n", addr);
}

int hmm() {
    printf("Win.\n");
    execl("/bin/sh", "sh", NULL);
}

extern char **environ;

int main(int argc, char **argv) {

    int i, limit;

    for(i = 0; environ[i] != NULL; i++) 
        memset(environ[i], 0x00, strlen(environ[i]));

    int (*fptr)(int) = good;
    char buf[32];

    if(strlen(argv[1]) <= 40) limit = strlen(argv[1]);

    for(i = 0; i <= limit; i++) {
        buf[i] = argv[1][i];
        if(i < 36) buf[i] = 0x41;
    }

    int (*hmmptr)(int) = hmm;

    (*fptr)((int)hmmptr);

    return 0;

}

I compiled the above C program as root without any type of stack protection (gcc -fno-stack-protector -o out test.c) and exploited as normal user. I failed to get the root shell.

This is the same code which I had exploited from 'smashthestack'.

Upvotes: 1

Views: 1310

Answers (2)

Mischa Arefiev
Mischa Arefiev

Reputation: 5417

Did you make the binary suid?

Working as root:

# cd /your/working/directory/
# chmod +s ./out

If all stack smashing protections are off and your code is correct, you will get a root shell. Otherwise (if protection is off and code is correct) you will only get a user shell.

Upvotes: 1

Sangeeth Saravanaraj
Sangeeth Saravanaraj

Reputation: 16597

All you need is only the following to get to the shell using a c program.

#include <stdio.h>
#include <unistd.h>

int main(int argc, char *argv[]) 
{
    execl("/bin/sh", "sh", NULL);
    return 0;
}

Execute the above mentioned code in the root shell.

You can still have the following piece of code to clear the environment variables in the new shell..

for(i = 0; environ[i] != NULL; i++) 
    memset(environ[i], 0x00, strlen(environ[i]));

But in order to execute your code, you must change

printf("Address of hmm: %p\n", addr);

to

printf("Address of hmm: %p\n", &addr);

I don't understand why you want to print the address of variable in that function.. OTOH, the function itself is lacking an objective.

Upvotes: 0

Related Questions