When managing self-hosted services like Git, you may find yourself needing to forward non-standard ports—say, :10022. This could lead to a Git address that looks like ssh://git@git.sebastientaggart.com:10022/sebastientaggart/my-project.git. While this setup can function smoothly, using a non-standard port comes with its own set of challenges: public networks might block those ports, you’ll need more extensive documentation, and let’s be honest—non-standard ports can detract from the overall aesthetic of your URLs.

In this guide, we’ll focus on how to utilize ufw (Uncomplicated Firewall) to forward traffic from a standard SSH port (:22) on one server to a non-standard port on another. Think of this as setting up a traffic cop for your network, ensuring that requests get to their intended destination without unnecessary fuss.

Setting Up Port Forwarding

Start by editing the before.rules file for ufw:

sudo vi /etc/ufw/before.rules

Add the following lines to the file:

*nat
:PREROUTING ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]

# Forward traffic from this server (1.1.1.1:22) to a remote server (2.2.2.2:10022)
-A PREROUTING -i eth0 -d 1.1.1.1 -p tcp --dport 22 -j DNAT --to-destination 2.2.2.2:10022
-A POSTROUTING -o eth0 -j MASQUERADE

COMMIT

Replace 1.1.1.1 with the IP address of your server, and 2.2.2.2 with the IP of the target server.

After making these changes, reload ufw to apply the new rules:

sudo systemctl restart ufw

To ensure everything is functioning as intended, verify your settings with:

sudo iptables -t nat -L -n -v

Once you’ve completed these steps, your port :22 will successfully forward to :10022 on the remote server. Your Git addresses will now appear as follows: ssh://git@git.sebastientaggart.com/sebastientaggart/my-project.git.

Modifying Existing Rules

Now, what if you need to tweak existing rules? Flushing all iptables rules with sudo iptables -F is often too blunt an instrument; it can wreak havoc on your setup. Instead, it’s wiser to list your existing rules and delete them one by one as necessary.

To do this, list your current NAT rules with:

iptables -t nat --line-numbers -L -n -v

The --line-numbers option is crucial, as it allows you to reference specific rules when you want to delete them. For example, if you want to remove the second rule in the PREROUTING chain, you’d issue:

iptables -t nat -D PREROUTING 2

Remember, the instructions above assume you’re adding rules to /etc/ufw/before.rules for the first time. If modifications are necessary, be sure to remove the old rules using the -D option before restarting ufw with systemctl.

In Closing

By following these steps, you can seamlessly forward SSH ports using ufw and ensure that your self-hosted services run smoothly. Embracing a standard like port :22 can simplify access and improve the security posture of your applications. After all, clarity in technology often leads to enhanced usability—and who doesn’t appreciate that?