Run python as root using cap_sys_admin capability linux - python

I have the following capability of python2.7 (using getcap):
/usr/bin/python2.7 = cap_sys_admin+ep
I know that CAP_SYS_ADMIN is "CAP_SYS_ADMIN is a highly privileged access level and should generally be avoided as it is equivalent to root access level." (https://docs.bridgecrew.io/docs/bc_k8s_36)
It's mean that I can run as root using /usr/bin/python2.7?
So how actually I can get example root bash using /usr/bin/python2.7?

Setting cap_sys_admin on /usr/bin/python means that python will be able to make any 'root' system call. This means that any one who runs python has the power to do things that normally only root can do. If someone (maliciously or accidentally) tries to do something dangwerous, they won't be stopped. Something as simple as the following could be catastrophic:
import shutil
shutil.rmtree('/')
In most cases if you need a script to run with elevated privileges it is better to use a user account that has these permissions, using su or sudo, rather than making a command always run without limits. That way you can focus on 'who' is allowed to do thingsm rather than 'what'.

Related

how to run chmod in python?

I was working with a sensor called Rplidar. To connect the Rplidar with my operating system(Ubuntu) sometimes i have to use this command in the terminal:
sudo chmod 666 /dev/ttyUSB0
After running this instruction, ubuntu can detect the Rplidar. Later on, i will run a python script to work with the Rplidar. Now I want to include this command inside my python script so that i do not need to run it in the terminal before working with the Rplidar. Is there any way that i could do it in python script?
The simple answer is that chmod is provided in the os module in Python:
https://docs.python.org/3/library/os.html#os.chmod
so all you need to do is run:
import os
filename = 'example.dat'
os.chmod(filename,
stat.S_IRUSR |
stat.S_IWUSR |
stat.S_IRGRP |
stat.S_IWGRP |
stat.S_IROTH)
so there's no need to shell out to perform this operation normally. Also have a look at the os.path and shutil modules for much more support in this area.
Things get a little complicated if you need to perform this operation with elevated privileges, but that's actually not the solution here.
Also, it is not a good idea to give 666 permissions to system devices. This can open up security problems when any user on the system has read/write access to system devices. As a matter of principle, use the least permissions required for correct operation.
As #KlausD. comments, you shouldn't be forcing permission changes on these device nodes anyway. The correct approach is to perform a one-time operation of adding the relevant user to the dialout group on your system. Then by being in the correct group, the user running your application will have access to the device. This is already answered here:
https://askubuntu.com/questions/112568/how-do-i-allow-a-non-default-user-to-use-serial-device-ttyusb0
Just run this once:
sudo adduser kazi dialout
then log out and back in for it to take effect. Your Rplidar app will run fine.
You can use the subprocess library to run shell command in Python
import subprocess
subprocess.Popen(["sudo", "chmod", "666", "/dev/ttyUSB0"], stdout=subprocess.PIPE, shell=True)

Privileged subprocess starts in the wrong working directory

Im trying to start a few python scripts from another, unprivileged one, using subprocess.Popen. Works good for the most part, but the ones that need root permissions dont work, i have narrowed the problem to pkexec, that is not staying at the working directory nor accepting it as parameter, thats because
This:
subprocess.Popen(['kdesudo','pwd'],cwd=sys.path[0])
#also works with sudo
effectively prints the cwd, whereas:
subprocess.Popen(['pkexec','pwd'],cwd=sys.path[0])
always stays at /root. (also tried passing env=os.environ to no avail)
i need to prompt the user with a gui, and the portability that pkexec offers over kdesudo/gksu. Any ideas?
Edit: Since its not possible to change pkexec's working directory, the following can be used to prompt the user for the root password across gtk and kde environments:
try:
check_call('which gksu',shell=True)
sudo = 'gksu'
except:
print "gksu frontend not found, using kdesudo instead"
sudo = 'kdesudo'
prompt = Popen([sudo, '<privileged command/script to run>'])
There's no way to get pkexec to keep the old directory when invoking it's command because it always changes to the target user's home directory.
It changes to pw->pw_dir, which is the home directory of the target user and there's no override for this.
I can't see a documented reason for this, but it could be simply a matter of attempting to ensure that the user executing the program can access their current working directory. It's been there since the creation of pkexec and I don't see any bugs relating to this behavior.
I run pcmanfm file-manager as privileged user from current dir using pkexec like this :
pkexec env DISPLAY=$DISPLAY XAUTHORITY=$XAUTHORITY pcmanfm $PWD
User must belong to sudo group.
just use --keep-cwd in newest version of pkexec

Python - running a script as a service with a name other than 'python'

I have a set of python scripts which I run as a daemon services. These all work great, but when all the scripts are running and I use top -u <USER>, I see all my scripts running as python.
I would really like to know which script is running under which process id. So is there any way to execute a python script as a different process name?
I'm stuck here, and I'm not ever sure what terms to Google. :-)
Note: I'm using Ubuntu Linux. Not sure if the OS matters or not.
Try using setproctitle. It should work fine on Linux.
Don't have a linux system here to test this on appropriately, but if the above doesn't work, you should be able to use the same trick they use for things like gzip etc.
The script has to tell what to run it at the top like this:
#!/usr/local/bin/python
Use a softlink like this:
ln -s /usr/local/bin/python ~/bin/myutil
Then just change your script to
#!~/bin/myutil
and it should show up that way instead. You may need to use a hard link instead of a soft link.
Launching a python script using the python script itself (and file associations and/or shell magic) is not very portable, but you can use similar methods on nearly any OS.
The easiest way to get this is using she bang. The first line of your python script should be:
#!/usr/bin/python
or
#!/usr/bin/python3
depending upon whether you use python or python3
and then assign executable permissions to the script as follows:
chmod +x <scriptname>
and then run the script as
./scriptname
this will show up as scriptname in top.

Execute Python Script as Root (seteuid vs c-wrapper)

I have a quick one off task in a python script that I'd like to call from Django (www user), that's going to need to root privileges.
At first I thought I would could use Python's os.seteuid() and set the setuid bit on the script, but then I realized that I would have to set the setuid bit on Python itself, which I assume is big no no. From what I can tell, this would also be the case if using sudo, which I really would like to avoid.
At this point, I'm considering just writing a C wrapper the uses seteuid and calls my python script as root, passing the necessary arguments to it.
Is this the correct thing to do or should I be looking at something else?
sudo does not require setuid bit on Python. You can enable sudo for one command only, no arguments:
www ALL=(ALL) NOPASSWD: /root/bin/reload-stuff.py ""
This would be secure if your script does not take any arguments, cannot be overridden by www user, and sudo does "env_reset" (the default in most distros).
You can accept arguments, but be very careful with them -- do not take output filenames, make sure you verify all inputs. In this case, remove "" from the end of sudo line.
The correct thing is called privilege separation: clearly identify minimal set of tasks which have to be done on elevated privileges. Write a separate daemon and an as much limited as possible way of communicating the task to do. Run this daemon as another user with elevated privileges. A bit more work, but also more secure.
EDIT: using a setuid-able wrapper will also satisfy the concept of privilege separation, although I recommend having the web server chrooted and mounting the chrooted file system nosuid (which would defeat that).
sudo allows you to limit arguments passed to the program. From man sudoers:
john ALPHA = /usr/bin/su [!-]*, !/usr/bin/su *root*
On the ALPHA machines, user john may su to anyone except root but
he is not allowed to specify any options to the su(1) command.
So use sudo. Of course you need to be extra careful with root access – make sure only root can modify the script itself and any parent directories, and that the script is safe and only does the absolute minimum that needs to be run as root.

when we need use sudo python xxx.py or just python xxx.py or xxx.py

I have write a website,what confused me is when i run the website,first i need start the the app,
so there are 3 ways:
sudo python xxx.py
python xxx.py
xxx.py
I didn't clear with how to use each of them,the NO.3 method currently in my computer dosen't work well
sudo will run the application with superuser permissions. Considering that you're referring to a website, this is certainly not what you want to do. (For a webapp, if it requires superuser permissions, it's broken. That's far, far too big of a security risk to consider actually using.)
Under other circumstances you might have a python program that does some sort of system maintaince and requires being run as root. In this case, you'd use sudo, but you would never want to do this for something that's publicly accessible and could potentially be exploited. In fact, for anything other than testing, you should probably run the webapp as a separate user with very limited access (e.g. with their shell set to /dev/null, no read or write access to anything that they don't need, etc...).
The other two are effectively identical (in therms of what they do), but the last option (executing the script directly) will require:
the executable bit to be set (on
unix-y systems) (e.g. chmod +x whatever.py)
a shebang on the first line(e.g. #!
/usr/bin/python) pointing to the
python execuctable that you want to
run things with (again, this only applies to unix-y systems)
Calling python to run the code (python whatever.py) and following the steps above (resulting in a script that you can call directly with whatever.py)
do exactly the same thing (assuming that the shebang in the python file points to the same python executable as "python" does, anyway...)

Categories