Правильная безопасная настройка SSH

Правильная безопасная настройка SSH

Статья под влиянием много уважаемого эксперта Антона Цвет.

Эта статья предназначена для тех, кто уже понимает, что просто включить сервер и запустить на нём программу — задача несложная. Однако сделать так, чтобы программа была безопасной и устойчивой к внешним атакам в проде — это уже задача другого уровня. Здесь мы поговорим о безопасности SSH и о том, как защитить свой сервер от потенциальных угроз.

Правильная настройка SSH
Во-первых, /etc/ssh/sshd_config и /etc/ssh/ssh_config это разные файлы.
Файл /etc/ssh/sshd_config отвечает за настройку сервера ssh, чтобы можно было подключиться К данному сервер.

А уже файл /etc/ssh/ssh_config (или ~/.ssh/config) на вашем персональном компьютере отвечает за то, с какими параметрами ВЫ хотите подключаться к серверу.

  1. Можно использовать ansible для проверки правильной настройки отсюда.
  2. Использовать ED25519 ключи SSH.
  3. Запрет доступа по паролю.
  4. Ограничение количества попыток входа: Используйте параметр MaxAuthTries
  5. Запрет доступа руту.
    1. Создать группу sshusers.
    2. Создать отдельных пользователей по ключам из /root/.ssh/authorized_keys.
    3. Добавить созданных пользователей в группу sshusers.
    4. В конфиге /etc/ssh/sshd_config добавить AllowGroup sshusers.
  6. Итоговый файл конфига:
########## Binding ##########

# SSH server listening address and port
#Port 22
#ListenAddress 0.0.0.0
#ListenAddress ::

# only listen to IPv4
#AddressFamily inet

# only listen to IPv6
#AddressFamily inet6

########## Features ##########

# accept locale-related environment variables
AcceptEnv LANG LC_CTYPE LC_NUMERIC LC_TIME LC_COLLATE LC_MONETARY LC_MESSAGES
AcceptEnv LC_PAPER LC_NAME LC_ADDRESS LC_TELEPHONE LC_MEASUREMENT
AcceptEnv LC_IDENTIFICATION LC_ALL LANGUAGE
AcceptEnv XMODIFIERS

# disallow ssh-agent forwarding to prevent lateral movement
AllowAgentForwarding no

# prevent TCP ports from being forwarded over SSH tunnels
# **please be aware that disabling TCP forwarding does not prevent port forwarding**
# any user with an interactive login shell can spin up his/her own instance of sshd
AllowTcpForwarding no

# prevent StreamLocal (Unix-domain socket) forwarding
AllowStreamLocalForwarding no

# disables all forwarding features
# overrides all other forwarding switches
DisableForwarding yes

# disallow remote hosts from connecting to forwarded ports
# i.e. forwarded ports are forced to bind to 127.0.0.1 instad of 0.0.0.0
GatewayPorts no

# prevent tun device forwarding
PermitTunnel no

# suppress MOTD
PrintMotd no

# disable X11 forwarding since it is not necessary
X11Forwarding no

########## Authentication ##########

# permit only the specified users to login
# AllowUsers sshtunnel

# permit only users within the specified groups to login
AllowGroups sshusers

# uncomment the following options to permit only pubkey authentication
# be aware that this will disable password authentication
#   - AuthenticationMethods: permitted authentication methods
#   - PasswordAuthentication: set to no to disable password authentication
#   - UsePAM: set to no to disable all PAM authentication, also disables PasswordAuthentication when set to no
#AuthenticationMethods publickey
PasswordAuthentication no

# PAM authentication enabled to make password authentication available
# remove this if password authentication is not needed
UsePAM no

# challenge-response authentication backend it not configured by default
# therefore, it is set to "no" by default to avoid the use of an unconfigured backend
ChallengeResponseAuthentication no

# set maximum authenticaion retries to prevent brute force attacks
MaxAuthTries 3

# disallow connecting using empty passwords
PermitEmptyPasswords no

# prevent root from being logged in via SSH
PermitRootLogin no

# enable pubkey authentication
PubkeyAuthentication yes

########## Cryptography ##########

# explicitly define cryptography algorithms to avoid the use of weak algorithms
Ciphers [email protected],[email protected],[email protected],aes256-ctr,aes192-ctr,aes128-ctr
HostKeyAlgorithms rsa-sha2-512,rsa-sha2-256,ssh-ed25519,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
MACs [email protected],[email protected],[email protected]

# short moduli should be deactivated before enabling the use of diffie-hellman-group-exchange-sha256
# see this link for more details: https://github.com/k4yt3x/sshd_config#deactivating-short-diffie-hellman-moduli
#KexAlgorithms curve25519-sha256,[email protected],diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha256
#KexAlgorithms curve25519-sha256,[email protected],diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group14-sha256
#KexAlgorithms curve25519-sha256,[email protected],diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group-exchange-sha256,[email protected]

########## Connection Preferences ##########

# number of client alive messages sent without client responding
ClientAliveCountMax 2

# send a keepalive message to the client when the session has been idle for 300 seconds
# this prevents/detects connection timeouts
ClientAliveInterval 300

# compression before encryption might cause security issues
Compression no

# prevent SSH trust relationships from allowing lateral movements
IgnoreRhosts yes

# log verbosely for addtional information
LogLevel VERBOSE

# allow a maximum of two multiplexed sessions over a single TCP connection
MaxSessions 2

# enforce SSH server to only use SSH protocol version 2
# SSHv1 contains security issues and should be avoided at all costs
# SSHv1 is disabled by default after OpenSSH 7.0, but this option is
#   specified anyways to ensure this configuration file's compatibility
#   with older versions of OpenSSH server
Protocol 2

# override default of no subsystems
# path to the sftp-server binary depends on your distribution
#Subsystem sftp /usr/lib/openssh/sftp-server
#Subsystem sftp /usr/libexec/openssh/sftp-server
Subsystem sftp internal-sftp

# let ClientAliveInterval handle keepalive
TCPKeepAlive no

# disable reverse DNS lookups
UseDNS no

# allow scanners to login via password
Match User scanners
  PasswordAuthentication yes

/etc/ssh/sshd_config

Источники информации:

Academy
On our Academy pages, you can find a huge amount of information about SSH, PuTTY, risk and compliance for enterprise security IT professionals, academics - and for the IT community in general.
SSH | Русскоязычная документация по Ubuntu