Search code examples
cbuffer-overflowstack-smash

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'.


Solution

  • 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.