30

I want to run the iptables command in a Ubuntu 16.04 Docker container. I have created a user, given that user root permissions, added them to the sudo group, but I am still being told that I am not running iptables as root.

$ groups
stack root sudo

$ sudo whoami
root

$ sudo iptables --list
iptables v1.6.0: can't initialize iptables table `filter': Permission 
denied (you must be root)
Perhaps iptables or your kernel needs to be upgraded.

In my /etc/sudoers file I have the line: %sudo ALL=(ALL:ALL) ALL, which I believe should allow any user in the sudo group (which I am) to run any command, but I still get the permission denied error.

How would I successfully run the iptables command as this user?

Please note I am doing this in a Docker container with image: ubuntu:16.04

1 Answers1

36

Capabilities

If you want have iptables access within your containers, you need to enable specific capabilities via the --cap-add=NET_ADMIN switch when running the container initially.

Example

$ docker run --cap-add=NET_ADMIN -it ubuntu:16.04

Then in the container set up iptables & sudo:

# apt update -y
# apt-get install iptables sudo -y

Then inside the container, set up a user, user1, and added it to the sudo group:

# adduser user1
# adduser user1 sudo

Then set user to user1:

# su - user1

Check user1's sudo permissions:

$ sudo -l
[sudo] password for user1:
Matching Defaults entries for user1 on 1356bf8bd61a:
    env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin

User user1 may run the following commands on 1356bf8bd61a:
    (ALL : ALL) ALL

Check if they can access iptables via sudo:

$ sudo iptables -L -n
Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

References

Paulo Tomé
  • 3,782
slm
  • 369,824
  • 2
    That worked! Thanks for the detailed answer! Alternatively, I also found that using the --privileged flag works as well – northsideknight Jul 30 '18 at 01:10
  • 1
    @northsideknight - that gives all capabilities to the container whereas what I show just gives the networking, so is a little more secure. It's discussed here - https://stackoverflow.com/questions/36425230/privileged-containers-and-capabilities. – slm Jul 30 '18 at 01:12
  • ah yes, good point – northsideknight Jul 30 '18 at 01:12
  • 2
    How would you do it in Compose 3 ? The doc says the cap_add: option is ignored https://docs.docker.com/compose/compose-file/ – Stephane Sep 22 '19 at 12:55
  • The cap_add and cap_drop options are ignored when deploying a stack in swarm mode – Adan Rehtla Mar 24 '20 at 23:30