130

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?

ændrük
  • 75,636
  • 74
  • 233
  • 365

2 Answers2

194

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
Gilles 'SO- stop being evil'
  • 59,745
  • 16
  • 131
  • 158
  • 1
    I 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? – Michael Waterfall Feb 26 '13 at 11:24
  • 3
    @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. – Gilles 'SO- stop being evil' Feb 26 '13 at 12:23
  • Hmm, okay I'll experiment and come back with more detail if I continue to have issues. Thanks! – Michael Waterfall Feb 27 '13 at 11:58
  • 33
    The 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. – Ken Simon May 16 '13 at 03:11
  • 6
    Despite the indentation in the answer, `sshd_config` is not Python `;)` – Nick T Feb 07 '17 at 17:25
  • It 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 – frepie Dec 19 '17 at 14:19
  • 1
    @frepie The `Match` block extends until the next `Match` directive or until the end of the file. That's why you have to put it at the end. – Gilles 'SO- stop being evil' Dec 19 '17 at 15:27
  • Linux is simply amazing, thank you for sharing. – W.M. Feb 09 '18 at 13:56
  • Or follow the Match directive with `Match All` to terminate it – anthony Feb 14 '22 at 02:54
9

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.

Verhagen
  • 131
  • 6
glooch
  • 99
  • 1
  • 2