3

I want to allow only machines with allowed ip(s) to login to my system via ssh.

For example, userA can use only ip xx.xx.xx.xx or yy.yy.yy.yy to login via ssh, and no other ip can login as the userA. And userB can use only ip zz.zz.zz.zz to login via ssh, no ip other than zz.zz.zz.zz can login as userB.

How should I set up my Linux to achieve this?

techraf
  • 5,831
  • 10
  • 33
  • 51
Marcus Thornton
  • 1,091
  • 3
  • 13
  • 16
  • 2
    Does this answer your question? [Limit SSH access to specific clients by IP address](https://unix.stackexchange.com/questions/406245/limit-ssh-access-to-specific-clients-by-ip-address) – Pablo A May 05 '23 at 03:17
  • Specifically, [tonioc's answer](/a/490120/112566) and [iBug's answer](/a/563452/112566) both address this use-case. – Toby Speight May 08 '23 at 08:44

3 Answers3

10

In /etc/ssh/sshd_config add the following:

AllowUsers [email protected] [email protected] userA
AllowUsers [email protected] userB

Then restart the SSH daemon.

You can use wildcards as described in Patterns section of the ssh_config manual.

techraf
  • 5,831
  • 10
  • 33
  • 51
  • What if I'm not sure the username of the remoteUser? I want anybody via zz.zz.zz.zz to be able to login as userB. Your method seems that require explicitly specify the username of the remoteUser. – Marcus Thornton Feb 15 '16 at 07:36
  • Use a wildcard `*@xx.xx.xx.xx` – techraf Feb 15 '16 at 07:49
  • @MarcusThornton: `*@yy.yy.yy.yy` should work, according to `man sshd_config` (see: AllowUsers) and `man ssh_config` (see: Patterns) – Ulrich Schwarz Feb 15 '16 at 07:50
1

You can do that via iptables.

All connections from address 1.2.3.4 to SSH (port 22):

iptables -A INPUT -p tcp -m state --state NEW --source 1.2.3.4 --dport 22 -j ACCEPT

Deny all other SSH connections:

iptables -A INPUT -p tcp --dport 22 -j DROP
Toby Speight
  • 8,460
  • 3
  • 26
  • 50
user6780
  • 9
  • 1
  • 2
    Iptables will not enough by it self. The best result if will add into /etc/ssh/sshd_config AllowUsers A B and no passwords, only ssh keys. – user6780 Feb 15 '16 at 07:17
  • 1
    Please familiarize yourself with the basic markup used on this site. Using headerlines like you did and not formatting code as such leads to horribly formatted, ugly, posts. (click on the "edited ..." link to see how things changed. – Anthon Feb 15 '16 at 07:25
  • @user6780 you should [edit] your answer instead of commenting. – guntbert Feb 15 '16 at 17:03
0

One approach (if you're using PAM for authentication) is to specifiy pam_rhosts as a required module in /etc/pam.d/ssh. This allows each user to specify in their own .rhosts file where they are permitted to connect from.

Note that the authentication modules in the pam.d file will not be consulted for pubkey logins (e.g. I have auth required pam_deny.so to prevent password logins on my machines). Other modules (account, session and so on) are still used.

Toby Speight
  • 8,460
  • 3
  • 26
  • 50