Skip to content

Instantly share code, notes, and snippets.

@sandcastle
Last active April 30, 2018 12:55
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save sandcastle/d49b211ad56c45a032c9 to your computer and use it in GitHub Desktop.
Save sandcastle/d49b211ad56c45a032c9 to your computer and use it in GitHub Desktop.
Default firewall configuration using iptables for a fresh Ubuntu 14.04 server.
#!/bin/sh -x
# ==================================
# iptables default configuration script
#
# - this locks down our servers port access
# ==================================
# install fail2ban
sudo apt-get update
sudo apt-get install fail2ban -y
#reset the default input / output policies and flush any existing rules
sudo iptables -P INPUT ACCEPT
sudo iptables -P OUTPUT ACCEPT
sudo iptables -F
# Accept incoming packets from established or existing connections
sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
# enable SSH and web ports
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT
# enable loopback (localhost) access
sudo iptables -I INPUT 1 -i lo -j ACCEPT
# add any reuquired subnet restrictions
# sudo iptables -A INPUT -s 10.0.0.0/24 -j ACCEPT
# set the last rule to drop all traffic, this is better than
# changing the defualt policy as this can lock you out
sudo iptables -A INPUT -j DROP
# clone the config file (its updated with package updates), so we need a clone
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
# Note:
# - if running nginx, then edit the file and enable the jail for it
# - we might also want to extend the bantime to something like 1800
# sudo nano /etc/fail2ban/jail.local
# restart the service
sudo service fail2ban stop
sudo service fail2ban start
# persist the changes across restarts
sudo apt-get install iptables-persistent
# save for restarts
iptables-save > /etc/iptables/rules.v4
ip6tables-save > /etc/iptables/rules.v6
# check the policy
# sudo iptables -S
@sandcastle
Copy link
Author

To add an IP restriction, use the following:

# list with line numbers
sudo iptables -L --line-numbers

# remove last rule (drop all)
iptables -D INPUT <line>

# add ip restriction
sudo iptables -A INPUT -s xx.xx.xx.xx -j ACCEPT
sudo iptables -A INPUT -j DROP

# save changes
iptables-save > /etc/iptables/rules.v4
ip6tables-save > /etc/iptables/rules.v6

# verify changes
sudo iptables -S

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