Tuesday, October 11, 2016

How To Run A Script As The Owner Of The Script


For the explanation below, just keep in mind that these assumption is true:-
- owner of file == yltan(uid=742)
- user that executes the script == icetools(uid=48102)

How to run a python script as the owner of the script.

1. Create any simple python script, eg a.py:-
#!/usr/bin/env python
import os

print "Before swap::" + str(os.getresuid())
os.system("whoami")

os.setreuid(os.geteuid(),os.getuid())

print "After Swap:" + str(os.getresuid())
os.system("whoami")
2. This is the magic wrapper script, setuid_swap.c. :-
/* This binary is intended to be a setuid script wrapper for dbRsync.pl.
  
   Example compilation on an hp machine:  gcc dbRsync.c -o dbRsync
   This compilation creates an executable called dbRsync. After compiling,
   chmod +s dbRsync (or whatever the executable is) to set the sticky bit or
   it won't work.
*/

int main(int ac, char **av) {
    execv( "/path/to/your/a.py", av );
}
3. Compile the setuid_wrap.c to wrapper_a :-
gcc setuid_swap.c -o wrapper_a
4. Change the setuid bit:-
chmod 4755 wrapper_a
5. Run wrapper_a as someone else other than the owner of the file:-
sudo su - icetools

./wrapper_a
6. ... and this is the output that you get (Running as icetools):-
Before swap::(48102, 742, 742)
icetools
After Swap:(742, 48102, 48102)
yltan






For a detail explanation of how setuid work,

https://drive.google.com/open?id=0B_HHt58thGk_MTVwQkhleWNmZE0



Alternatively, you could swap the users in the compiled code itself by doing this:-
/* This binary is intended to be a setuid script wrapper for dbRsync.pl.
  
   Example compilation on an hp machine:  gcc dbRsync.c -o dbRsync
   This compilation creates an executable called dbRsync. After compiling,
   chmod +s dbRsync (or whatever the executable is) to set the sticky bit or
   it won't work.
*/

int main(int ac, char **av) {
    int uid;
    uid = geteuid();
    setreuid(uid, uid);
    execv( "/path/to/your/a.py", av );
}

No comments:

Post a Comment

How To Bypass Kerberos(kinit) Authentication

Whenever you try to setuid and impersonate as someone else to run something, it is very likely that you will run into kerberos/kinit issues....