Redirecting port 443 to 8443 using iptables

Privileged ports are ports below 1024. These usually require root privileges to bind (unless setting capabilities). Web servers run on port 80 and 443 and you have just made this neat little thing and want to bind it directly to these ports, but you don’t want to run it as root - what to do?

Having misplaced my notes on how to redirect port 80 and 443 to unprivileged port (above 1024) so that normal users can bind them was the precursor to going live with this site/blog.

In the process of provisioning a new VM, I landed with the following solution. The VM was an Amazon Linux 2023, an RPM-based system. iptables was not installed, but it had the systemd service package which should start and restore the rules on boot…

sudo yum install iptables-services
sudo systemctl enable iptables
sudo systemctl start iptables

The setup is as follows…

# flush all chains
sudo iptables -F

# open port 22, 8443 and 8080 - block the rest
sudo iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
sudo iptables -A INPUT -p icmp -j ACCEPT
sudo iptables -A INPUT -i lo -j ACCEPT
sudo iptables -A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
sudo iptables -A INPUT -p tcp -m state --state NEW -m tcp --dport 8080 -j ACCEPT
sudo iptables -A INPUT -p tcp -m state --state NEW -m tcp --dport 8443 -j ACCEPT
sudo iptables -A INPUT -j REJECT --reject-with icmp-host-prohibited
sudo iptables -A FORWARD -j REJECT --reject-with icmp-host-prohibited

# redirect incoming port 80 to 8080 and 443 to 8443.
sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080
sudo iptables -t nat -A OUTPUT -o lo -p tcp --dport 80 -j REDIRECT --to-port 8080
sudo iptables -t nat -A PREROUTING -p tcp --dport 443 -j REDIRECT --to-port 8443
sudo iptables -t nat -A OUTPUT -o lo -p tcp --dport 443 -j REDIRECT --to-port 8443

# save chains to /etc/sysconfig/iptables
sudo service iptables save

# you can also use something like the following...
sudo sh -c 'iptables-save > /etc/sysconfig/iptables'

Now you can start your program or container as an unprivileged user binding it to e.g :8443. Traffic from outside should now reach the app.

prokoptôn

A person making progress. Even though one has not obtained the wisdom of a sage; when appropriate actions are increasingly chosen, fewer and fewer mistakes will be made, and one will be prokoptôn (προκόπτων), making progress.


How to redirect port 443 to 8443 and 80 to 8080 using iptables.

By Mike, 2024-02-26