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?

10

In /etc/ssh/sshd_config add the following:

AllowUsers remoteUserA@xx.xx.xx.xx remoteUserA@yy.yy.yy.yy userA
AllowUsers remoteUserB@zz.zz.zz.zz userB

Then restart the SSH daemon.

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

  • 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 7:36
  • Use a wildcard *@xx.xx.xx.xx – techraf Feb 15 '16 at 7: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 7: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
  • 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 7: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 7: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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.