I have configured my server's sshd to listen on a non-standard port 42.
However, at work I am behind a firewall/proxy, which only allow outgoing connections to ports 21, 22, 80 and 443. Consequently, I cannot ssh to my server from work, which is bad. I do not want to return sshd to port 22.
The idea is this: on my server, locally forward port 22 to port 42 if source IP is matching the external IP of my work's network. For clarity, let us assume that my server's IP is 169.1.1.1 (on eth1), and my work external IP is 169.250.250.250. For all IPs different from 169.250.250.250, my server should respond with an expected 'connection refused', as it does for a non-listening port.
I'm very new to iptables. I have briefly looked through the long iptables manual and these related / relevant questions:
- iptables question: forwarding port x to an ssh port of different machine on the network
- How can I port forward with iptables?
However, those questions deal with more complicated several-host scenarios, and it is not clear to me which tables and chains I should use for local port-forwarding, and if I should have 2 rules (for "question" and "answer" packets), or only 1 rule for "question" packets.
So far I have only enabled forwarding via sysctl. I will start testing solutions tomorrow, and will appreciate pointers or maybe case-specific examples for implementing my simple scenario.
Is the draft solution below correct?
iptables -A INPUT [-m state] [-i eth1] --source 169.250.250.250 -p tcp
--destination 169.1.1.1:42 --dport 22 --state NEW,ESTABLISHED,RELATED
-j ACCEPT
Should I use the mangle
table instead of filter
? And/or FORWARD
chain instead of INPUT
?
To forward/redirect things you must edit the NAT table.
A rule like this is probably closest to what you need.
It would be much easier and probably better to just leave SSH on the standard port and properly secure it. Using an alternate port would only slow down a motivated attacker for a couple seconds. Setup a intrusion prevention system like denyhosts/fail2ban and disable password-based authentication. Or consider rate-limit incoming ssh connections.
See:
I would use Shorewall to manage ip-tables. It sets up a decent base firewall, and doing thing like you want is simple. Add a rule to /etc/shorewall/rules like:
DNAT net:169.250.250.250 loc:169.250.250.250 tcp 42 22
Like the others I am not sure why you run sshd on anotther port. If this is an internet port you may want to look at port knocking to keep the port closed unless you hit another port first. Shorewall handles this simplely.