How to set up iptables on a Raspberry Pi

iptables is a form of firewall included in many Linux packages, it can also be used for network address translation. Here, we configure it on a Raspberry Pi to allow communication on port 80, and requests from other devices on the 192.168.0.* IP range.

Set up iptables

  • We will configure our iptables rules in a file, and then load that file into iptables. Open the rules file for editing with:

    sudo vi /etc/iptables.firewall.rules

  • …and replace the content with the following:


    *filter
    :INPUT DROP [23:2584]
    :FORWARD ACCEPT [0:0]
    :OUTPUT ACCEPT [1161:105847]
    -A INPUT -i lo -j ACCEPT
    -A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
    -A INPUT -s 192.168.0.0/24 -j ACCEPT
    -A INPUT -p icmp -m icmp --icmp-type 8 -j ACCEPT
    -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
    COMMIT

  • Where:
    *filter
    :INPUT DROP [23:2584]For all packets destined for the host computer, the default policy is to drop the packet.
    :FORWARD ACCEPT [0:0]For all packets passing through (or being routed by) the host computer, the default policy is to accept the packet.
    :OUTPUT ACCEPT [1161:105847]For all packets originating from the host computer, the default policy is to accept the packet.
    -A INPUT -i lo -j ACCEPTAccept all incoming packets that are destined for the localhost (lo, 127.0.0.1) interface.
    -A INPUT -p tcp -m tcp --dport 80 -j ACCEPTAccept all incoming packets destined for tcp port 80 (i.e. http).
    -A INPUT -s 192.168.0.0/24 -j ACCEPTAccept all incoming packets, on all network interfaces, originating from devices on our local network IP address range.
    -A INPUT -p icmp -m icmp --icmp-type 8 -j ACCEPTAccept any ping requests to the host.
    -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPTIf the state of an incoming packet is ESTABLISHED or RELATED (i.e. not a NEW connection that wasn’t initiated by the host), the packet will be accepted.
    COMMITCommit the rules above.
  • Activate the new iptables rules by loading the file with:

    sudo iptables-restore < /etc/iptables.firewall.rules

  • Check to see what rules you configured above with:

    sudo iptables -L

  • To make sure the iptables rules are loaded on a reboot we’ll create a new file. Issue the following command:


    sudo vi /etc/network/if-pre-up.d/firewall

    …and paste the content below:


    #!/bin/sh
    /sbin/iptables-restore < /etc/iptables.firewall.rules

  • Make the file executable:

    sudo chmod +x /etc/network/if-pre-up.d/firewall

Advertisements