How can I allow SSH password authentication from only certain IP addresses?

  • 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?

  • 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
        PasswordAuthentication yes

    Then tell the sshd service to reload its configuration:

    service ssh reload

    I tried this (with instead) and when I restarted the ssh service I got locked out. SSH refused any connections. Any idea why this could be?

    @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.

    Hmm, okay I'll experiment and come back with more detail if I continue to have issues. Thanks!

    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.

    Despite the indentation in the answer, `sshd_config` is not Python `;)`

    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 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.

    Linux is simply amazing, thank you for sharing.

  • 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.

    call I allow a group instead of a single user

    @Lamar From `man sshd_config`, it looks like `AllowGroups` works the same as `AllowUsers`, but `AllowUsers` seems to take precedence over `AllowGroups`.

License under CC-BY-SA with attribution

Content dated before 6/26/2020 9:53 AM