How can I allow ssh connection from an IP subnet on port 10022 using iptables?
Use the -s
option of iptables
. It accepts an IP of the form nnn.nnn.nnn.nnn
or with a mask (nnn.nnn.nnn.nnn/nnn.nnn.nnn.nnn
or nnn.nnn.nnn.nnn/nn
). So to allow for example connections from nnn.nnn.nnn.* you can write
iptables -A INPUT -s nnn.nnn.nnn.0/255.255.255.0 -i em1 -p tcp --dport XXXXX -m state --state NEW,ESTABLISHED -j ACCEPT
or
iptables -A INPUT -s nnn.nnn.nnn.0/24 -i em1 -p tcp --dport XXXXX -m state --state NEW,ESTABLISHED -j ACCEPT
(see for example here for netmask calculation)
If you cannot create a netmask, then I'm afraid you will have to duplicate the rule for each of the IP addresses you want to allow to connect to your server.
In general, though, I never found working with iptables directly very nice, one can quickly loose the overview. I'd probably go for something like shorewall.
Related videos on Youtube
Mike
Updated on September 18, 2022Comments
-
Mike over 1 year
I need to set up a server with public IP for bandwidth testing, and I already have a script to drop all incoming traffic except for the ports I need. I have changed the ssh port from default (22) to another one (let's call it XXXXX; sorry for the paranoia but we just got hacked last week).
So my question is how can I allow a range of IP's to ssh into the server through that specific port?
The script I mentioned earlier:
iptables -F iptables -P INPUT DROP iptables -P FORWARD DROP iptables -P OUTPUT DROP iptables -A INPUT -i em1 -p tcp --dport XXXXX -m state --state NEW,ESTABLISHED -j ACCEPT iptables -A OUTPUT -o em1 -p tcp --sport XXXXX -m state --state ESTABLISHED -j ACCEPT iptables -A OUTPUT -o em1 -p tcp --dport XXXXX -m state --state NEW,ESTABLISHED -j ACCEPT iptables -A INPUT -i em1 -p tcp --sport XXXXX -m state --state ESTABLISHED -j ACCEPT
So I just need to add the ip range so that I can ssh remotely.
-
0xC0000022L almost 10 yearsIf you lose the overview it means likely you're doing it wrong.
ipset
is, for example, an awesome way of staying on top of the complexity, while giving symbolic names to whole sets of IPs, networks or ports or interfaces or combinations of the former and speeding up processing compared to adding individual rules instead of referencing an IP set.