How to allow only ssh and internet access with iptables?

I want to allow only internet access (it is useful for update) and ssh on my server. I found this set of rules:

  sudo iptables -P INPUT DROP
  sudo iptables -P OUTPUT DROP
  sudo iptables -A INPUT -i lo -j ACCEPT
  sudo iptables -A INPUT -p tcp -m tcp --dport [port number] -j ACCEPT
  sudo iptables -A OUTPUT -o lo -j ACCEPT
  sudo iptables -A OUTPUT -p tcp --sport [port number] -m state --state ESTABLISHED -j ACCEPT
  sudo service iptables save
  sudo netfilter-persistent reload

This is working well but I can't update my system or access internet. Which rules should I add to allow outgoing internet connection?


Solution 1:

Let's start

Delete current rules and chains:

sudo iptables --flush
sudo iptables --delete-chain

Allow loopback:

sudo iptables -A INPUT -i lo -j ACCEPT
sudo iptables -A OUTPUT -o lo -j ACCEPT

Drop ICMP:

sudo iptables -A INPUT -p icmp --icmp-type any -j DROP
sudo iptables -A OUTPUT -p icmp -j DROP

Allow established connections:

sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

Allow SSH:

sudo iptables -A INPUT -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT

Default policies:

sudo iptables -P INPUT DROP
sudo iptables -P OUTPUT ACCEPT

Save:

sudo iptables-save

This is it. I think :)