Skip to content

Instantly share code, notes, and snippets.

@bradwestfall
Last active February 20, 2023 17:03
Show Gist options
  • Save bradwestfall/d8a00045221e179e3ae9 to your computer and use it in GitHub Desktop.
Save bradwestfall/d8a00045221e179e3ae9 to your computer and use it in GitHub Desktop.

Ubuntu IP Tables (Firewall)

When setting up an Ubuntu server, you'll want to establish basic security including a firewall to only allow certain types of requests, and to allow only certain types of responses. This code will:

  • Flush your current firewall
  • Because it's our server and we're not hosting other people's stuff (like a shared server), we'll allow all output
  • Allow input requests for SSH, Port 80 and 443 (Web and TLS (SSL))
  • Log bad requests with the prefix "iptables denied:"
  • Then save these rules to a file called /etc/iptables.up.rules

Note: Run the following as the sudo user

iptables -F
iptables -A OUTPUT -j ACCEPT
iptables -A INPUT -p icmp -m icmp --icmp-type 8 -j ACCEPT
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -p tcp --dport ssh -j ACCEPT
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT
iptables -A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables denied: " --log-level 7
iptables -A INPUT -j DROP
iptables -A FORWARD -j DROP
iptables-save > /etc/iptables.up.rules
iptables-restore < /etc/iptables.up.rules

When you server restarts, the default is to use Ubuntu's Defalut IP Tables. To use our custom ones, we'll need to edit this file to re-establish our rules:

nano /etc/network/if-pre-up.d/iptables

Edit the file to look like this:

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

Make the file executable

chmod +x /etc/network/if-pre-up.d/iptables
Copy link

ghost commented Apr 7, 2016

Thanks Brad! I'm really getting a lot out of your web server workflow series on youtube.com!

@ismarkunc
Copy link

Hmm..why not work on debian? With these settings, my web site is unavailable..

@JacquesvanWyk
Copy link

This series of workflow is exactly what i needed.Thank you so much for doing this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment