Restricting SSH Port Forwarding with IPTables

Introduction

SSH port forwarding (also known as tunneling) allows users to securely access remote services. However, unrestricted SSH port forwarding can be a security risk, as attackers or malicious users can bypass firewall rules. By using IPTables, you can restrict SSH port forwarding to prevent unauthorized use while still allowing necessary connections.

This guide will show you how to configure IPTables to block or control SSH port forwarding.


Step 1: Understanding SSH Port Forwarding

SSH supports three types of port forwarding:

  • Local Port Forwarding: Forwards a local port to a remote server.

  • Remote Port Forwarding: Allows remote servers to forward traffic to a local machine.

  • Dynamic Port Forwarding: Creates a SOCKS proxy for flexible forwarding.

To secure your server, you should restrict unauthorized users from creating SSH tunnels.


Step 2: Blocking SSH Port Forwarding with IPTables

  1. Block All SSH Forwarding To completely disable SSH tunneling, use the following IPTables rule:

    iptables -A OUTPUT -p tcp --dport 22 -m owner . --uid-owner root -j REJECT

This rule blocks non-root users from establishing SSH connections.

  1. Block Dynamic (SOCKS) Tunneling If you only want to disable SOCKS proxying while allowing standard SSH connections:

    iptables -A OUTPUT -p tcp --dport 1080 -j REJECT

  2. Allow SSH but Restrict Port Forwarding You can allow SSH connections while preventing port forwarding by modifying SSHD settings. Edit the SSH configuration file:

    sudo nano /etc/ssh/sshd_config

    Find and set:

    AllowTcpForwarding no

    X11Forwarding no

    Save and restart SSH:

    sudo systemctl restart ssh


Step 3: Verifying IPTables Rules

To check if your rules are active:

  • List all IPTables rules:

    sudo iptables -L -v -n

  • Test SSH connections to ensure forwarding is blocked.


Conclusion

By restricting SSH port forwarding using IPTables, you enhance your server’s security and prevent unauthorized tunneling. Consider combining these steps with SSH key authentication and firewall rules for even stronger protection.