16

I am running this small python script on both linux and Solaris as a not privileged user :

#!/usr/bin/python
import os
print 'uid,euid =',os.getuid(),os.geteuid()

Before running, the setuid bit is set on the script (not on python interpreter) :

chown root:myusergrp getuid.py
chmod 4750 getuid.py

On Solaris, the effective uid is set because of the setuid bit :

uid,euid = 10002 0

But not on Linux :

uid,euid = 10002 10002

Note the python version is 2.6 for both Solaris and Linux

Is it possibe to have Python Linux working as Python Solaris ?

Eric
  • 4,821
  • 6
  • 33
  • 60

4 Answers4

29

Most Unix distributions normally don't allow you to use setuid on a file that uses a #! interpreter. Solaris happens to be one that allows it due to its use of a more secure implementation than most other distributions.

See this FAQ entry for more background about why the mechanism is so dangerous: How can I get setuid shell scripts to work?

See this link for more discussion and how to compile a setuid executable that will run your script: setuid on shell scripts

The pertinent part:

int main()
{
   setuid( 0 );
   system( "/path/to/script.sh" );

   return 0;
}
David K. Hess
  • 16,632
  • 2
  • 49
  • 73
  • Solaris is based on SVR4, which as your FAQ link notes, uses more secure ways than older Unixes to handle setuid script startup. – alanc Nov 30 '11 at 03:55
  • What if your python script needs to be started as non-root user, and then suid during execution at some point? – ACK_stoverflow Mar 21 '15 at 00:54
  • You need to start as root and then temporarily drop privileges to the user before resuming root. See this question for more info: http://stackoverflow.com/questions/8499296/realuid-saved-uid-effective-uid-whats-going-on – David K. Hess Mar 21 '15 at 02:08
2

I just put two and two together today and came up with an alternative solution: cython --embed.

Follow the examples at the link above and you'll get binary executables from your Python that you'll be able to chown and chmod u+s, completing the circle without a wrapper program.

Of course, beware the risks (of this or any other setuid use)—bugs in your script can result in elevated privileges on the system.

Tanner Swett
  • 3,241
  • 1
  • 26
  • 32
Mattie
  • 20,280
  • 7
  • 36
  • 54
2

Based on David K. Hess answer, but with arguments:

#include <unistd.h>

int main(int argc, char **argv)
{
    setuid(0);
    execv("/path/to/script.sh", argv);

    return 0;
}
-2

You could potentially use sudo to achieve what you want. It runs stuff as different users:

 sudo -u otheruser command

Permissions are set by root using visudo. The setuid/setguid stuff doesn't appear to apply to scripts or the shell in linux, only compiled code.

John Rigler
  • 183
  • 1
  • 7