Allow only incoming SSH connection using IPtables

You can secure a Linux system with IPTables so that only wanted connections can be established. Here only port 22 is released for use.

To allow only SSH connections and reject all other incoming connections on a Linux system, you can use the following iptables commands:

# Flush all existing rules
iptables -F

# Set default policy to drop incoming and forwarding connections
iptables -P INPUT DROP
iptables -P FORWARD DROP

# Allow incoming SSH connections
iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT
iptables -A OUTPUT -p tcp --sport 22 -m conntrack --ctstate ESTABLISHED -j ACCEPT

# Allow already established SSH connections
iptables -A INPUT -p tcp --sport 22 -m conntrack --ctstate ESTABLISHED -j ACCEPT
iptables -A OUTPUT -p tcp --dport 22 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT

These commands perform the following actions:

The first rule (iptables -F) flushes all existing rules to ensure you start with a clean configuration.

The next two rules (iptables -P INPUT DROP and iptables -P FORWARD DROP) set the default policy to "DROP" for incoming and forwarding connections, meaning that all incoming connections are rejected unless there is a specific rule allowing them.

The next four rules allow incoming and outgoing SSH connections. Port 22 is assumed to be the SSH port. Make sure to modify this port if you are using a different port for SSH. These rules allow traffic for new connections (NEW) and established connections (ESTABLISHED).

The last two rules allow traffic for already established SSH connections. This ensures that existing connections are not disrupted when checking traffic for established connections.

After executing these iptables commands, only SSH connections should be allowed on the system, while all other incoming connections will be rejected.