SSH

Описание

  • Соединение по SSH подразумевает обмен ключами

    • Пользователь с помощью ssh-keygen генерирует два ключа: приватный и публичный

    • Приватный ключ пользователь хранит у себя

    • Публичный ключ отдается серверу через ssh-copy-id

  • При установке SSH сессии от сервера формируется сообщение, зашифрованное публичным ключом пользователя

  • Пользователь расшифровывает это сообщение своим приватным ключом и отправляет ответное сообщение серверу, устанавливая соединение

  • Факт того, что приватным ключом дешифровано сообщение подтверждает легитимность сессии и ее участников

Настройка SSH

  • ssh-keygen создает пару приватного\публичного ключа

    • Установка пароля на приватный ключ повышает безопасность, но снижает удобство пользования

  • ssh-copy-id копирует публичный ключ на целевой сервер

  • ssh-agent /bin/bash позволяет хранить в кэше шелла пароль приватного ключа

  • ssh-add добавляет текущий пароль в кэш

[root@centos8 ~]# ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:56RRDfDqUEZCSp632rhEKnLoc6huJ6vBqPtdLBFvkmc root@centos8
The key's randomart image is:
+---[RSA 3072]----+
|    ..o o..      |
|   o o o . o     |
|    = . o o .    |
|     = + o       |
|    = E S o      |
|o. o @ o *       |
|*.+ = + o .      |
|+O = +           |
|X*B o            |
+----[SHA256]-----+
[root@centos8 ~]# ssh-copy-id 192.168.1.86
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed

/usr/bin/ssh-copy-id: ERROR: ssh: connect to host 192.168.1.86 port 22: Connection refused

Опции SSH

  • Опции сервера хранятся в /etc/ssh/sshd_config

  • Опции клиента хранятся в /etc/ssh/ssh_config

  • Можно поменять порт (обычно 22)

  • Опция PermitRootLogin - позволяет логиниться по рут правами, по-умолчанию включена

  • Опция PubkeyAuthentication - аутентификация по публичному ключу, по-умолчанию включена

  • Опция PasswordAuthentication - аутентификация по паролю

  • Опция X11Forwarding - передача графического интерфейса

[root@centos8 ~]# cat /etc/ssh/sshd_config 
#	$OpenBSD: sshd_config,v 1.103 2018/04/09 20:41:22 tj Exp $

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

# This sshd was compiled with PATH=/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/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.

# If you want to change the port on a SELinux system, you have to tell
# SELinux about this change.
# semanage port -a -t ssh_port_t -p tcp #PORTNUMBER
#
#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

<....>

#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
X11Forwarding yes
#X11DisplayOffset 10
#X11UseLocalhost yes
#PermitTTY yes
[root@centos8 ~]# cat /etc/ssh/ssh_config 
#	$OpenBSD: ssh_config,v 1.34 2019/02/04 02:39:42 dtucker Exp $

# 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
#   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
#   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
#
# To modify the system-wide ssh configuration, create a  *.conf  file under
#  /etc/ssh/ssh_config.d/  which will be automatically included below
Include /etc/ssh/ssh_config.d/*.conf
  • Настройка sshd требует перезагрузки демона

    • systemctl restart sshd

Копирование файлов

  • При помощи sshd можно передавать файлы по сети, обеспечивая безопасность этой передачи

  • Для этого используется утилита scp

    • scp file1 file2 student@remoteserver:/home/student скопирует файлы на удаленный сервер

    • scp -r root@remoteserver:/tmp/files . - копирование файлов с удаленного сервера в текущую директорию рекурсивно

  • sftp обеспечивает работу FTP клиента при помощи SSH

    • sftp 1.1.1.1 - подключение к серверу

    • put /my/file - выгрузит файл на FTP сервер

    • get /your/file - загрузит файл с FTP сервера

    • exit закрывает sftp сессию

Синхронизация файлов

  • rsync использует sshd для синхронизации файлов

  • Если искомый и конечный файлы уже созданы, то rsync будет только синхронизировать разность

  • rsync имеет множество опций, базовые из которых:

    • -r - рекурсивно синхронизировать все дерево директории

    • -l - синхронизация символьных ссылок

    • -p - сохраняет символьные ссылки

    • -n - тест перед синхронизацией

    • -a - режим архивирования, равнозначный -rlptgoD

    • -A - режим архивирования с синхронизацией ACL

    • -X - синхронизация контекста SELinux

  • rsync -ar root@serverip:/etc /tmp - синхронизация папки /etc удаленной машины в папку /tmp локальной машины

Last updated