Tell me the best way to allow for certain private ips to enter into linux by ssh loginrsa key pair?

Best Answer


You can limit which hosts can connect by configuring TCP wrappers  or filtering network traffic (firewalling) using iptables . If you want to use different authentication methods depending on the client ip address, configure ssh daemon instead (option 3).

Option 1: Filtering with IPTABLES

Iptables rules are evaluated in order, until first match.

For example, to allow traffic from 192.168.0.0/24 network and otherwise drop the traffic (to port 22). The DROP rule is not required if your iptables default policy is configured to DROP .

iptables -A INPUT -p tcp --dport 22 --source 192.168.0.0/24 -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -j DROP

You can add rules before dropping the rule to match more networkshosts If you have a lot of networks or host addresses, you should use ipset module. There is also iprange module which allows using any arbitrary range of IP addresses.

Iptables are not persistent throughout a reboot You need to configure some mechanism to restore iptables on boot

iptables apply only to IPv4 traffic. Systems which have ssh listening to IPv6 address the necessary configuration can be done with ip6tables .

Option 2: Using TCP wrappers

Note: this might not be an option on modern distributions, as support for tcpwrappers was removed from OpenSSH 6.7

You can also specify which hosts can connect using tcp wrappers In addition to ip addresses you can use hostnames in tcp wrappers

By default we will deny all hosts

/etc/hosts.deny .

sshd : ALL

Then list allowed hosts in hosts.allow. For example to allow network 192.168.0.0/24 and localhost .

/etc/hosts.allow .

sshd : 192.168.0.0/24
sshd : 127.0.0.1
sshd : [::1]

Option 3: SSH daemon configuration

You can configure the ssh daemon in the sshdconfig to use different authentication methods depending on the client address or hostname If you want to block other hosts from connecting you should use iptables or tcp wrappers instead

Remove the default authentication methods first

PasswordAuthentication no
PubkeyAuthentication no

Then add desired authentication methods after a Match Address in the end of the file. Placing Match in the end of the file is important, since all the configuration lines after it are placed inside the conditional block until the next Match line. For example.

Match Address 127.0.0.*
    PubkeyAuthentication yes

Other clients can still connect but logins will fail because there are no available authentication methods

Match arguments and allowed conditional configuration options are documented in sshd_config man page . Match patterns are documented in ssh_config man page .