Creating raw socket in Python without root privileges

ρss picture ρss · Dec 24, 2013 · Viewed 8.6k times · Source

Is it possible to create a raw socket without root privileges? If not, can a script elevate its privileges itself?

I wrote a Python script using a raw socket:

#!/usr/bin/env python

import socket
rawSocket = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x0800))
print "Worked!"

Running it with root privileges prints Worked!. However, it gives an error when run with normal user privileges.

I want to execute my script as a normal user, and it should create a raw socket without asking for anything. Is it possible?

Answer

smeso picture smeso · Dec 24, 2013

As you noted raw sockets require higher privilege than a regular user have. You can circumvent this issue in two ways:

  1. Activating the SUID bit for the file with a command like chmod +s file and set its owner to root with chown root.root file. This will run your script as root, regardless of the effective user that executed it. Of course this could be dangerous if your script has some flaw.
  2. Setting the CAP_NET_RAW capability on the given file with a command like setcap cap_net_raw+ep file. This will give it only the privileges required to open a raw socket and nothing else.

EDIT:

As pointed out by @Netch the given solutions will not work with any interpreted language (like Python). You will need some "hack" to make it work. Try googling for "Python SUID", you should find something.