I want to open a raw socket in Linux (with Python) without giving Python the cap_net_raw capability. I want the user to have this capability, not the program. I am using Ubuntu 12.4.
-
Welcome to stackoverflow.com. Please take some time to read [the help pages](http://stackoverflow.com/help), especially the sections named ["What topics can I ask about here?"](http://stackoverflow.com/help/on-topic) and ["What types of questions should I avoid asking?"](http://stackoverflow.com/help/dont-ask). And more importantly, please read [the Stack Overflow question checklist](http://meta.stackoverflow.com/questions/156810/stack-overflow-question-checklist). You might also want to learn how to create a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). – Some programmer dude Jul 01 '14 at 20:54
2 Answers
Capabilities are related to processes (threads to be precise), not to the users.
As pointed out by @wheredidthatnamecomefrom, you could leverage ambient capabilities to execute a python script with just the cap_net_raw
, without setting any file capabilities for python
binary.
You can have a look at the following question for a generic idea on how to do that.

- 1,336
- 2
- 18
- 29
I've been struggling with this as well. There does not seem to be any good workarounds, at least for an interpretive language like python. Either run in root or don't capture raw packets :). The only thing I can think of doing is executing the script as a daemon.
sudo service start snifferd
where snifferd is something like:
PATH=/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/home/<user>/projects/sniffer.py
DAEMON_NAME=snifferd
case "$1" in
start)
log_daemon_msg "Starting $DAEMON_NAME"
setcap cap_net_raw=+ep /usr/bin/python2.7
start-stop-daemon --start --background --pidfile $PIDFILE --make-pid --user $DAEMON_USER --chuid $DAEMON_USER --startas $DAEMON
setcap cap_net_raw=-ep /usr/bin/python2.7
log_end_msg $?
;;
...
I've tried executing setcap in my code right before initializing the socket and removing the cap right after but it seems that python needs the permission before the instance is started.
There is also http://www.subspacefield.org/security/privilege/code/privilege/ for privelege dropping but I haven't really looked at it.
EDIT 1 Just tried it. It works but if the deamon removes the capability before the program needs it, it will fail. Guess, it needs some kind of pause in there etc

- 634
- 9
- 21
-
On Linux 4.3 and up add the Ambient capabilities can be set. These will always be added to the permitted and effective set for non-root processes. This way python's file set doesn't have to change. – wheredidthatnamecomefrom Sep 10 '16 at 15:21