HiveBrain v1.2.0
Get Started
← Back to all entries
patternbashMinor

Iptables Lockdown

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
lockdowniptablesstackoverflow

Problem

I have nginx serving files with uwsgi and I wanted to lock my server down just to allow SSH and Nginx to run.

#!/bin/bash
i=/sbin/iptables

# Flush all rules
$i -F
$i -X

# Setup default filter policy
$i -P INPUT DROP
$i -P OUTPUT DROP
$i -P FORWARD DROP

# Allow unlimited traffic on loopback
$i -A INPUT -i lo -j ACCEPT
$i -A OUTPUT -o lo -j ACCEPT

# Open up ports for nginx
$i -A INPUT -p tcp --dport 443 -j ACCEPT
$i -A INPUT -p tcp --dport 80 -j ACCEPT
$i -A INPUT -p tcp --dport 22 -j ACCEPT

# Make sure nothing comes or goes out of this box
$i -A INPUT -j DROP
$i -A OUTPUT -j DROP


It's quite a minimal example but it looks like it would do the job. Are there any improvements to be had?

Solution

There is a miniscule chance of a failure between /sbin/iptable -P INPUT DROP and /sbin/iptables -A INPUT -p tcp --dport 22 -j ACCEPT. It really isn't likely, as there's not much that could go wrong, but it's theoretically possible. If you are remotely administering this server over SSH, then you might get locked out of your own machine. Therefore, I suggest deferring the following sequence of commands:

  • /sbin/iptables -P INPUT ACCEPT



/sbin/iptables -P OUTPUT ACCEPT

  • /sbin/iptables -F; /sbin/iptables -X



  • Set up the rules



  • /sbin/iptables -P INPUT DROP



/sbin/iptables -P FORWARD DROP

In contrast to @eckes, who worries about leaving the server vulnerable for a moment, I worry about possibly losing SSH access to it. If you are raising the firewall for the first time, my sequence introduces no new window of vulnerability. If you are reinitializing the firewall, the window of vulnerability between steps 1 and 3 would only be a split second, not enough for a meaningful attack.

Context

StackExchange Code Review Q#45098, answer score: 8

Revisions (0)

No revisions yet.