How can I allow SSH password authentication from only certain IP addresses?
229,848
Solution 1
Use a Match
block at the end of /etc/ssh/sshd_config
:
# Global settings
…
PasswordAuthentication no
…
# Settings that override the global settings for matching IP addresses only
Match address 192.0.2.0/24
PasswordAuthentication yes
Then tell the sshd service to reload its configuration:
service ssh reload
Solution 2
you can add:
AllowUsers [email protected].*.*, [email protected].*.*
this changes default behaviour, really deny all other users from all hosts. Match block available on OpenSsh version 5.1 and above.
Related videos on Youtube
Comments
-
RusGraf over 1 year
I'd like to allow SSH password authentication from only a certain subnet. I see the option to disallow it globally in
/etc/ssh/sshd_config
:# Change to no to disable tunnelled clear text passwords #PasswordAuthentication yes
Is there a way to apply this configuration to a select range of IP addresses?
-
Michael Waterfall about 11 yearsI tried this (with 192.168.0.0/16 instead) and when I restarted the ssh service I got locked out. SSH refused any connections. Any idea why this could be?
-
h3. about 11 years@MichaelWaterfall It's impossible to tell with so little information. Make sure to keep a shell running until you've validated the new configuration. Restarting the ssh service doesn't affect active connections.
-
Michael Waterfall about 11 yearsHmm, okay I'll experiment and come back with more detail if I continue to have issues. Thanks!
-
mariojjsimoes almost 11 yearsThe likely issue is that you put the Match block someplace in the middle of your sshd_config. Match lines affect every following line until the next Match line, so they should be at the end of the file.
-
Lamour almost 8 yearscall I allow a group instead of a single user
-
Nick T about 7 yearsDespite the indentation in the answer,
sshd_config
is not Python;)
-
frepie over 6 yearsIt works when that block is added at the end of file. But somehow, it generated an error when put just below "PasswordAuthentication no". journalctl -xe follows:/etc/ssh/sshd_config line 70: Directive 'PrintMotd' is not allowed within a Match block Dec 19 09:08:31 inspiron systemd[1]: ssh.service: Main process exited, code=exited, status=255/n/a
-
h3. over 6 years@frepie The
Match
block extends until the nextMatch
directive or until the end of the file. That's why you have to put it at the end. -
W.M. about 6 yearsLinux is simply amazing, thank you for sharing.
-
conradkleinespel about 6 years@Lamar From
man sshd_config
, it looks likeAllowGroups
works the same asAllowUsers
, butAllowUsers
seems to take precedence overAllowGroups
. -
anthony about 2 yearsOr follow the Match directive with
Match All
to terminate it