2

I am trying to build an api using django which should alter iptables using POST parameters. I am using django 1.4, djangorestframework, python-iptables. The problem I am facing is that python-iptables need root access to change iptables rules. I can change the iptables rules by doing $ sudo python and from the python shell I can change those rules. Also I can change those rules by using iptdump module which takes in iptables parameters and create those rules which I can later save in a file (iptables.rules.txt) and use fabric's local('sudo iptables-restore < iptables.rules.txt'). But this will always prompt the user for a root password. Is there a way I can give django app root privileges so that I can bypass sudo password prompt.

Saad
  • 1,856
  • 1
  • 22
  • 28

1 Answers1

4

If you really need a part of the application to run as root, you could rewrite it as a daemon, and communicate with it from the main Django application as suggested in this answer. I would only recommend it if the alternative below does not suit your requirements.

The alternative sudo iptables-restore < iptables.rules.txt is much simpler, just tell sudo not to ask for the password for just this command by adding this to your /etc/sudoers file:

djangouser ALL=(ALL) NOPASSWD: /sbin/iptables-restore

Where djangouser is the user the Django process is running as.

EDIT: You can avoid writing an intermediate file by sending the new iptables directly to the iptables-restore process:

import iptdump
import subprocess

ipt = iptdump.Iptables()
proc = subprocess.Popen(['sudo', '/sbin/iptables-restore'],
                        stdin=subprocess.PIPE)
proc.communicate(ipt.dump())
Community
  • 1
  • 1
Nicolas Cortot
  • 6,591
  • 34
  • 44
  • hey thanks this works but is there a way that I can bypass sudo password prompt. – Saad Apr 21 '13 at 16:28
  • 1
    @Saad the line in **/etc/sudoers** should prevent the password prompt, are you sure the code is running as the user specified in sudoers? – Nicolas Cortot Apr 21 '13 at 17:37