How to setup simple firewall on Ubuntu?

Could somebody give some simple steps with configuration example how to setup simple firewall on Ubuntu (using console only)? Only ssh, http and https access should be allowed.


sudo ufw default deny

sudo ufw allow http

sudo ufw allow https

sudo ufw allow ssh

sudo ufw enable


Use this script.

Just decide if you want to allow incoming ICMP (ping) or not.

# Clear any existing firewall stuff before we start
iptables --flush
iptables -t nat --flush
iptables -t mangle --flush

# As the default policies, drop all incoming traffic but allow all
# outgoing traffic.  This will allow us to make outgoing connections
# from any port, but will only allow incoming connections on the ports
# specified below.
iptables --policy INPUT DROP
iptables --policy OUTPUT ACCEPT

# Allow all incoming traffic if it is coming from the local loopback device
iptables -A INPUT -i lo -j ACCEPT

# Accept all incoming traffic associated with an established
# connection, or a "related" connection
iptables -A INPUT -i eth0 -m state --state ESTABLISHED,RELATED -j ACCEPT

# Allow incoming connections
# SSH
iptables -A INPUT -p tcp -i eth0 --dport 22 -m state --state NEW -j ACCEPT
# HTTP
iptables -A INPUT -p tcp -i eth0 --dport 80 -m state --state NEW -j ACCEPT
# HTTPS
iptables -A INPUT -p tcp -i eth0 --dport 443 -m state --state NEW -j ACCEPT

# Allow icmp input so that people can ping us
iptables -A INPUT -p icmp -j ACCEPT

# Reject all other incoming packets
iptables -A INPUT -j REJECT

As noted in comments to another answer, you don't want to lose your connection before you allow the ssh port. From the man page:

"REMOTE MANAGEMENT

When running ufw enable or starting ufw via its initscript, ufw will flush its chains. This is required so ufw can maintain a consistent state, but it may drop existing connections (eg ssh). ufw does support adding rules before enabling the firewall, so administrators can do:

ufw allow proto tcp from any to any port 22

before running ’ufw enable’. The rules will still be flushed, but the ssh port will be open after enabling the firewall. Please note that once ufw is ’enabled’, ufw will not flush the chains when adding or removing rules (but will when modifying a rule or changing the default policy)."

So here is an approach that uses a script to set it. You will get logged out when you run this script, but having run it you can then log in again over ssh.

Put the following in a script and call it start-firewall.sh

#!/bin/sh
ufw allow ssh
ufw enable
ufw default deny
ufw allow http
ufw allow https

And then make it executable and run it by doing

$ chmod + x start-firewall.sh
$ sudo ./start-firewall.sh

To learn more, read the man page.