На серверах ECSS должны быть установлены пакеты openssh-client openssh-server или метапакет ssh, включающий в себя клиента и сервер.

Настройка конфигурации сервера и клиента ssh

Конфигурация сервера OpenSSH описана в файле /etc/ssh/sshd_config. Для более полного обеспечения безопасности необходимо изменить некоторые  настройки, принятые по умолчанию.

В репозитории Ubuntu-18.04 LTS текущая версия OpenSSH_7.6p1. Нижеприведенные рекомендации по конфигурации для версий, начиная с 7.6

В OpenSSH 7.0 и старше отключена поддержка протокола SSH 1.0 по умолчанию во время компиляции. Точно так же по умолчанию во время компиляции больше не активируется поддержка ключей diffie-hellman-group1-sha1 размером 1024 бит, хостов и пользовательских ключей ssh-dss, ssh-dss-cert-*. Вообще убрали поддержку формата сертификатов v00, а опция PermitRootLogin по умолчанию изменила значение с yes на prohibit-password.

Обмен ключами.

Для использования только заслуживающих доверия протоколов обмена ключами в /etc/ssh/sshd_config для сервера следует указать:

KexAlgorithms curve25519-sha256@libssh.org,diffie-hellman-group-exchange-sha256
Аналогичные настройки для клиента, в /etc/ssh/ssh_config: 
Host * 
    KexAlgorithms curve25519-sha256@libssh.org,diffie-hellman-group-exchange-sha25

Аутентификация.

В SSH поддерживается четыре алгоритма аутентификации по открытым ключам: DSA, ECDSA, Ed25519 и RSA.

ECDSA завязан на технологиях NIST и должен быть отключен. Так как размер ключей DSA не может превышать 1024, его тоже следует отключить, В итоге проще удалить все ключи:

cd /etc/ssh
rm ssh_host_*key*

Далее, следует позаботиться о RSA, сгенерировав ключ большего размера, а также добавить ключ ed25519:

sudo ssh-keygen -t rsa -b 4096 -f /etc/ssh/ssh_host_rsa_key
sudo ssh-keygen -o -a 100 -t ed25519 -f /etc/ssh/ssh_host_ed25519_key

Симметричные шифры.

Из 15 поддерживаемых в SSH алгоритмов симметричного шифрования, используемых для организации защиты установленного канала связи, безопасными можно считать chacha20-poly1305, aes*-ctr и aes*-gcm. Шифры 3des-cbc и arcfour потенциально уязвимы в силу использования DES и RC4, cast128-cbc применяет слишком короткий размер блока (64 бит).

В итоге, в /etc/ssh/sshd_config рекомендуется добавить:

Ciphers aes256-gcm@openssh.com,aes128-gcm@openssh.com,chacha20-poly1305@openssh.com,aes256-ctr,aes192-ctr,aes128-ctr

В /etc/ssh/ssh_config:

Host * 
    Ciphers aes256-gcm@openssh.com,aes128-gcm@openssh.com,chacha20-poly1305@openssh.com,aes256-ctr,aes192-ctr,aes128-ctr

Код аутентичности сообщения (MAC).

Для шифров в режиме CTR для гарантирования целостности передаваемых блоков доверия заслуживает только метод Encrypt-then-MAC ("*-etm", MAC добавляется к уже зашифрованному блоку). Методы MAC-then-encrypt и Encrypt-and-MAC потенциально подвержены атакам. Из 18 доступных в SSH алгоритмов MAC сразу следует отбросить основанные на хэшах MD5 и SHA1, не стойких к выявлению коллизий, а также алгоритмы использующие размеры ключей менее 128 бит и размеры тегов менее 256 бит. В итоге, наиболее безопасными MAC можно считать hmac-sha2-512-etm и hmac-sha2-256-etm.

В /etc/ssh/sshd_config:

MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com

 В /etc/ssh/ssh_config:

Host *
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com

Защита от утечки ключей.

Наиболее простым способом получения контроля за SSH-соединением является захват ключей на стороне клиента или сервера. Рекомендации сводятся к соблюдению типовых правил поддержания безопасности системы:

  • оперативная установка обновлений, установка программ только из надёжных источников
  • установка только действительно необходимых программ и сервисов
  • использование программ для которых доступны исходные тексты, включение дополнительных механизмов защиты (Grsecurity, сборка с флагом -fstack-protector)

Для защиты ключей следует выбрать надёжный пароль доступа к клиентским файлам ключей. При формировании ключа для увеличения числа итераций хэширования можно использовать опцию "ssh-keygen -o -a число", что усложнит подбор пароля. Также можно сохранить ключи только на внешнем носителе, подключая его только во время соединения по SSH.

Ограничение пользователей

Добавляем параметр AllowUsers, которого нет в конфигурационном файле по умолчанию. Этот параметр разрешает доступ к серверу по протоколу SSH только для перечисленных пользователей.

В /etc/ssh/sshd_config:

AllowUsers dmitry support 

Ограничение интерфейсов

Эти строки отвечают за настройку разграничений по сетевым интерфейсам, сетевому адресу или имени компьютера. По умолчанию сервер «слушает» (принимает подключения) на всех сетевых интерфейсах. Если нужно оставить подключение только через определенные интерфейсы, то раскомментировать строку:

ListenAddress 192.168.1.21
ListenAddress 10.16.33.5

В этой же строке можно явно указать порт, предварительно закомментировав (поставив символ # в начале строки) первую строку – Port 22:

ListenAddress 10.16.33.5:22025

Смена порта

Если есть вероятность попыток подбора пароля(например сервер в публичной сети) можно изменить порт на другой.

Port 22025

По умолчанию используется 22 порт. Изменим его на нестандартный порт 22025 – это избавит наш сервер от сетевых роботов, которые автоматически сканируют интернет в поиске открытых портов и пытаются через них подключиться. В основном, боты настроены на поиск стандартных портов. Это не избавит от сканирования человеком, но для защиты от человека существует фаервол, хитрые способы открытия порта и пр.

Примерный листинг получившихся файлов конфигурации:

 /etc/ssh/sshd_config:
#    $OpenBSD: sshd_config,v 1.101 2017/03/14 07:19:07 djm Exp $

# This is the sshd server system-wide configuration file.  See
# sshd_config(5) for more information.

# This sshd was compiled with PATH=/usr/bin:/bin:/usr/sbin:/sbin

# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented.  Uncommented options override the
# default value.

#Port 22
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::

#HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_ecdsa_key
#HostKey /etc/ssh/ssh_host_ed25519_key

# Ciphers and keying
#RekeyLimit default none

# Logging
#SyslogFacility AUTH
#LogLevel INFO

# Authentication:

#LoginGraceTime 2m
#PermitRootLogin prohibit-password
#StrictModes yes
#MaxAuthTries 6
#MaxSessions 10

#PubkeyAuthentication yes

# Expect .ssh/authorized_keys2 to be disregarded by default in future.
#AuthorizedKeysFile    .ssh/authorized_keys .ssh/authorized_keys2

#AuthorizedPrincipalsFile none

#AuthorizedKeysCommand none
#AuthorizedKeysCommandUser nobody

# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes

# To disable tunneled clear text passwords, change to no here!
#PasswordAuthentication yes
#PermitEmptyPasswords no

# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
ChallengeResponseAuthentication no

# Kerberos options
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no

# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes
#GSSAPIStrictAcceptorCheck yes
#GSSAPIKeyExchange no

# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
UsePAM yes

#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
X11Forwarding yes
#X11DisplayOffset 10
#X11UseLocalhost yes
#PermitTTY yes
PrintMotd no
#PrintLastLog yes
#TCPKeepAlive yes
#UseLogin no
#PermitUserEnvironment no
#Compression delayed
#ClientAliveInterval 0
#ClientAliveCountMax 3
#UseDNS no
#PidFile /var/run/sshd.pid
#MaxStartups 10:30:100
#PermitTunnel no
#ChrootDirectory none
#VersionAddendum none

# no default banner path
#Banner none

# Allow client to pass locale environment variables
AcceptEnv LANG LC_*

# override default of no subsystems
Subsystem    sftp    /usr/lib/openssh/sftp-server

# Example of overriding settings on a per-user basis
#Match User anoncvs
#    X11Forwarding no
#    AllowTcpForwarding no
#    PermitTTY no
#    ForceCommand cvs server

# @override for ECSS

KexAlgorithms curve25519-sha256@libssh.org,diffie-hellman-group-exchange-sha256
Ciphers aes256-gcm@openssh.com,aes128-gcm@openssh.com,chacha20-poly1305@openssh.com,aes256-ctr,aes192-ctr,aes128-ctr
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com

HostKey /etc/ssh/ssh_host_ed25519_key
HostKey /etc/ssh/ssh_host_rsa_key
PY
 /etc/ssh/ssh_config:
# This is the ssh client system-wide configuration file. See
# ssh_config(5) for more information. This file provides defaults for
# users, and the values can be changed in per-user configuration files
# or on the command line.

# Configuration data is parsed as follows:
# 1. command line options
# 2. user-specific file
# 3. system-wide file
# Any configuration value is only changed the first time it is set.
# Thus, host-specific definitions should be at the beginning of the
# configuration file, and defaults at the end.

# Site-wide defaults for some commonly used options. For a comprehensive
# list of available options, their meanings and defaults, please see the
# ssh_config(5) man page.

Host *
# ForwardAgent no
# ForwardX11 no
# ForwardX11Trusted yes
# PasswordAuthentication yes
# HostbasedAuthentication no
# GSSAPIAuthentication no
# GSSAPIDelegateCredentials no
# GSSAPIKeyExchange no
# GSSAPITrustDNS no
# BatchMode no
# CheckHostIP yes
# AddressFamily any
# ConnectTimeout 0
# StrictHostKeyChecking ask
# IdentityFile ~/.ssh/id_rsa
# IdentityFile ~/.ssh/id_dsa
# IdentityFile ~/.ssh/id_ecdsa
# IdentityFile ~/.ssh/id_ed25519
# Port 22
# Protocol 2
# Ciphers aes128-ctr,aes192-ctr,aes256-ctr,aes128-cbc,3des-cbc
# MACs hmac-md5,hmac-sha1,umac-64@openssh.com
# EscapeChar ~
# Tunnel no
# TunnelDevice any:any
# PermitLocalCommand no
# VisualHostKey no
# ProxyCommand ssh -q -W %h:%p gateway.example.com
# RekeyLimit 1G 1h
 SendEnv LANG LC_*
 HashKnownHosts yes
 GSSAPIAuthentication yes
# @override for ECSS
 Ciphers aes256-gcm@openssh.com,aes128-gcm@openssh.com,chacha20-poly1305@openssh.com,aes256-ctr,aes192-ctr,aes128-ctr
 KexAlgorithms curve25519-sha256@libssh.org,diffie-hellman-group-exchange-sha256 
 MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com
PY

Проверить синтаксис файла конфигурации можно командой:

sshd -t

Посмотреть текущие настройки сервера :

sshd -T