SSH
SSH (Secure SHell) est un programme de terminal chiffré qui remplace telnet , l'outil classique des systèmes d'exploitation du type Unix.
En plus de l'accès par terminal distant procuré par le binaire principal ssh la suite de programmes SSH s'est développée pour inclure d'autres outils tels que scp (Secure Copy Program, pour programme de copie sécurisée) et sftp (Secure File Transfer Protocol, pour protocole de transfert de fichier sécurisé).
À l'origine, SSH n'était pas libre. Cependant, de nos jours, la mise en œuvre la plus populaire de SSH, qui constitue un standard de fait, est l'OpenSSH de OpenBSD. Cette version est pré-installée sur Gentoo.
SSH is multi-platform, and is very widely used: OpenSSH is installed by default on most Unix-like OSs, on Windows10, on MacOS, and can be installed on Android or "jailbroken" iOS (SSH clients are available). This makes SSH a great tool for working with heterogeneous systems.
Installation
Vérifier l'installation
La plupart des installations Gentoo Linux ont déjà OpenSSH d'installé. Sa présence peut être vérifiée avec la commande ssh. Dans le cas où SSH est disponible, une aide sur son invocation est affichée :
user $
ssh
usage: ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-B bind_interface] [-b bind_address] [-c cipher_spec] [-D [bind_address:]port] [-E log_file] [-e escape_char] [-F configfile] [-I pkcs11] [-i identity_file] [-J [user@]host[:port]] [-L address] [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port] [-Q query_option] [-R address] [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]] destination [command]
Dans le cas où aucune aide à l'invocation n'est affichée, SSH est soit corrompu, soit non installé. Il est aussi possible qu'un utilisateur soit en cours de recompilation d'OpenSSH afin d'inclure une nouvelle configuration USE. Quoi qu'il en soit, continuez pour voir la liste des options USE disponibles.
If this does not try to install OpenSSH, the package may have been masked, or even listed in package.provided, though this would be unusual.
Options de la variable USE
USE flags for net-misc/openssh Port of OpenBSD's free SSH release
X
|
Add support for X11 |
X509
|
Adds support for X.509 certificate authentication |
audit
|
Enable support for Linux audit subsystem using sys-process/audit |
debug
|
Enable extra debug codepaths, like asserts and extra output. If you want to get meaningful backtraces see https://wiki.gentoo.org/wiki/Project:Quality_Assurance/Backtraces |
hpn
|
Enable high performance ssh |
kerberos
|
Add kerberos support |
ldns
|
Use LDNS for DNSSEC/SSHFP validation. |
libedit
|
Use the libedit library (replacement for readline) |
livecd
|
Enable root password logins for live-cd environment. |
pam
|
Add support for PAM (Pluggable Authentication Modules)DANGEROUS to arbitrarily flip |
pie
|
Build programs as Position Independent Executables (a security hardening technique) |
sctp
|
Support for Stream Control Transmission Protocol |
security-key
|
Include builtin U2F/FIDO support |
selinux
|
!!internal use only!! Security Enhanced Linux support, this must be set by the selinux profile or breakage will occur |
ssl
|
Enable additional crypto algorithms via OpenSSL |
static
|
!!do not set this during bootstrap!! Causes binaries to be statically linked instead of dynamically |
test
|
Enable dependencies and/or preparations necessary to run tests (usually controlled by FEATURES=test but can be toggled independently) |
verify-sig
|
Verify upstream signatures on distfiles |
xmss
|
Enable XMSS post-quantum authentication algorithm |
Emerger OpenSSH
Une fois les paramètres USE changés, n'oubliez pas d'installer (ou de recompiler) OpenSSH.
root #
emerge --ask --changed-use --oneshot net-misc/openssh
After changing any global USE flags in make.conf that affect the OpenSSH package, emerge world to update to the new USE flags:
root #
emerge --ask --verbose --update --deep --newuse @world
Configuration
Créer des clés
Pour vous fournir un shell sécurisé, des clés de chiffrage sont utilisées pour le chiffrage, le déchiffrage et les fonctionnalités de hâchage offertes par SSH.
Au premier démarrage du service SSH, des clés systèmes seront générées. Les clés peuvent être (ré)générées via la commande ssh-keygen.
Pour générer les clés les clés pour la version 2 du protocole SSH (algorythmes DSA et RSA):
root #
/usr/bin/ssh-keygen -t dsa -f /etc/ssh/ssh_host_dsa_key -N "PassphraseSecrete"
root #
/usr/bin/ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key -N "PassphraseSecrete"
The article Secure Secure Shell suggests using Ed25519 and RSA public key algorithms with:
root #
/usr/bin/ssh-keygen -t ed25519 -a 100 -f /etc/ssh/ssh_host_ed25519_key -N ""
root #
/usr/bin/ssh-keygen -t rsa -b 4096 -o -a 100 -f /etc/ssh/ssh_host_rsa_key -N ""
Configuration du serveur
Le serveur SSH est ordinairement configuré dans le fichier /etc/ssh/sshd_config, bien qu'il soit aussi possible de compléter la configuration dans le fichier /etc/conf.d/sshd d'OpenRC, y compris le changement de l'emplacement du fichier de configuration. Pour une information détaillée sur la manière de configurer le serveur, reportez-vous à la page de manuel de sshd_config.
The server provides means to validate its configuration using test mode:
root #
/usr/sbin/sshd -t
Always validate the configuration changes prior restarting the service in order to keep the remote login available.
Configuration du client
Le client ssh et les programmes apparentés (scp, sftp, etc.) peuvent être configurés grâce aux fichiers suivants :
- ~/.ssh/config
- /etc/ssh/ssh_config
Pour une information plus complète reportez-vous à la page de manuel ssh_config:
user $
man ssh_config
Intrusion prevention
SSH is a commonly attacked service. Tools such as sshguard and fail2ban monitor logs and black list remote users who have repeatedly attempted, yet failed to login. Utilize them as needed to secure a frequently attacked system.
Utilisation
Services
Commands to run the SSH server will depend on active init system.
OpenRC
Add the OpenSSH daemon to the default runlevel:
root #
rc-update add sshd default
Start the sshd daemon with:
root #
rc-service sshd start
The OpenSSH server can be controlled like any other OpenRC-managed service:
root #
rc-service sshd start
root #
rc-service sshd stop
root #
rc-service sshd restart
Active SSH connections to the server remain unaffected when issuing rc-service sshd restart.
systemd
To have the OpenSSH daemon start when the system starts:
root #
systemctl enable sshd.service
Created symlink from /etc/systemd/system/multi-user.target.wants/sshd.service to /usr/lib64/systemd/system/sshd.service.
To start the OpenSSH daemon now:
root #
systemctl start sshd.service
To check if the service has started:
root #
systemctl status sshd.service
Commandes
OpenSSH provides several commands, see each command's man page for usage information:
- scp - secure file copy
- sftp - secure file transfer
- ssh-add - add private key identities to the authentication agent
- ssh-agent - authentication agent
- ssh-copy-id - use locally available keys to authorize logins on a remote machine
- ssh-keygen - authentication key utility
- ssh-keyscan - gather SSH public keys from servers
- sshd - OpenSSH daemon
Séquences d'échappement
During an active SSH session, pressing the tilde (~) key starts an escape sequence. Enter the following for a list of options:
ssh>
~?
Note that escapes are only recognized immediately after a newline. They may not always work with some shells, such as fish.
Connecting to a distant SSH server
Authentification sans mot de passe
Pratique pour la gestion du serveur git.
Client
Sur votre client, exécutez :
user $
ssh-keygen -t rsa
Generating public/private rsa key pair. Enter file in which to save the key (/home/larry/.ssh/id_rsa): Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in /home/larry/.ssh/id_rsa. Your public key has been saved in /home/larry/.ssh/id_rsa.pub. The key fingerprint is: de:ad:be:ef:15:g0:0d:13:37:15:ad:cc:dd:ee:ff:61 larry@client The key's randomart image is: +--[ RSA 2048]----+ | | | . | | . .. n . | | . (: . . | | o . . : . | | . ..: >.> . | | * ?. . | | o.. .. .. | | :. . ! . | +-----------------+
Serveur
Assurez-vous qu'un compte pour le client existe sur le serveur, et placez le contenu du fichier id_rsa.pub dans ~/.ssh/authorized_keys file.
user $
ssh-copy-id <serveur>
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/larry/.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: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys larry@<server>'s password: Number of key(s) added: 1 Now try logging into the machine, with: "ssh '<server>'" and check to make sure that only the key(s) you wanted were added.
Afterwards a passwordless login should be possible doing
user $
ssh <server>
larry@<server>
Then on the server, the file /etc/ssh/sshd_config should be set to PasswordAuthentication no
.
Test sur une machine unique
La procédure mentionnée ci-dessus peut être testée localement :
user $
ssh-keygen -t rsa
Generating public/private rsa key pair. Enter file in which to save the key (/home/larry/.ssh/id_rsa): Enter passphrase (empty for no passphrase): Enter same passphrase again: ...
user $
mv ~/.ssh/id_rsa.pub ~/.ssh/authorized_keys
user $
ssh localhost
Terminal multiplexers to preserve sessions
It is possible to use a terminal multiplexer to resume a session after a dropped connection. Tmux and screen are two popular multiplexers that can be used to be able to reconnect to a session, even if a command was running when the connection dropped out.
Mosh may be an alternative for some of SSH's functionality, for spotty connections.
Remote services over ssh
SSH may be used to access remote services through an encrypted "tunnel". Remote service access is detailed in the SSH tunneling and SSH jump host articles.
Dépannage
Il y a trois niveaux de débogage. -v fait que ssh imprime des messages de débogage sur sa progression. Ceci est utile pour déboguer une connexion, l'authentification, et les problèmes de configuration. De multiples options -v augmentent la loquacité. Le maximum est 3.
user $
ssh example.org -v
user $
ssh example.org -vv
user $
ssh example.org -vvv
Permissions are too open
An ssh connection will only work if the file permissions of the ~/.ssh directory and contents are correct.
- The ~/.ssh directory permissions should be 700 (drwx------), i.e. the owner has full access and no one else has any access.
- Under ~/.ssh:
- public key files' permissions should be 644 (-rw-r--r--), i.e. anyone may read the file, only the owner can write.
- all other files' permissions should be 600 (-rw-------), i.e. only the owner may read or write the file.
These permissions need to be correct on the client and server.
Extinction des connexions à longue durée de vie
Beaucoup de périphériques d'accès à Internet effectuent de la translation d'adresses (NAT), un processus qui autorise des matériels sur un réseau privé, tels que ceux rencontrés à la maison ou au bureau, à accéder à des réseaux externes, comme l'Internet, tout en n'ayant qu'une adresse IP unique sur ces réseaux. Malheureusement, tous les périphériques NAT ne se valent pas, et quelques uns d'entre-eux ferment inadéquatement des connexions à longue durée de vie qui utilisent occasionnellement TCP comme celles qui utilisent SSH. Ceci est généralement observable comme une soudaine incapacité à interagir avec le serveur distant, alors que le programme client ssh n'a pas été interrompu.
Pour résoudre ce problème, les clients OpenSSH et les serveurs peuvent être configurés pour envoyer un message invisible , ou 'keep alive (maintenir en vie)', qui vise à maintenir et à confirmer l'état vivant du lien.
- Pour activer keep alive pour tous les clients se connectant à votre serveur local , définissez ClientAliveInterval 30 (ou une autre valeur en secondes) dans le fichier /etc/ssh/sshd_config.
- Pour activer keep alive pour tous les serveurs auxquels se connecte votre client local, définissez ServerAliveInterval 30 (ou une autre valeur en secondes) dans le fichier /etc/ssh/ssh_config.
- To enable keep alive for all clients connecting to the local server, set
ClientAliveInterval 30
(or some other value, in seconds) within the /etc/ssh/sshd_config file. - To enable keep alive for all servers connected to by the local client, set
ServerAliveInterval 30
(or some other value, in seconds) within the /etc/ssh/ssh_config or ~/.ssh/config file. - Set
TCPKeepAlive no
to help eliminate disconnections.
For example, to modify the server's configuration:
/etc/ssh/sshd_config
Help disconnects occur less often (server)# The following ClientAlive values will keep an inactive session open for 30 minutes ClientAliveCountMax 60 ClientAliveInterval 30 # # Deactivate TCPKeepAlive TCPKeepAlive no
To modify the client's configuration:
/etc/ssh/ssh_config
Help disconnects occur less often (client)# The following ServerAlive values will keep an inactive session open for 2 hours ServerAliveInterval 60 ServerAliveCountMax 120
X11 Forwarding, Not Forwarding, ou Tunneling
Problème: Après avoir effectué les changements nécessaires aux fichiers de configuration pour autoriser le transfert X11 ( X11 Forwarding), vous vous rendrez compte que les applications X sont exécutées sur le serveur et ne sont pas transmises au client.
Solution: Ce qui se passe très vraissemblablement lors de la connexion SSH au serveur ou hôte distant, c'est que la variable DISPLAY est, soit non définie, soit définie après que la session SSH l'ait définie.
Vérifiez ce scénario après vous être connecté à distance de la manière suivante :
user $
echo $DISPLAY
localhost:10.0
Vous devriez obtenir quelque chose qui ressemble à "localhost:10.0" ou "localhost2.local:10.0" en utilisant le règlage coté serveur X11UseLocalhost no
. Si vous obtenez le ":0.0" habituel, assurez-vous que vous n'effacez pas, ou ne réinitialisez pas, la variable $DISPLAY
dans $HOME/.bash_profile. Si c'est le cas, retirez, ou mettez en commentaire, votre initialisation personnalisée de $DISPLAY
ou empêchez bash_profile d'exécuter SSH lors de la connexion :
user $
ssh -t larry@localhost2 bash --noprofile
Be sure to substitute larry
in the command above with the proper username.
Une astuce consiste à créer un alias pour cela dans bashrc.
ssh-agent
OpenSSH comes with ssh-agent, a daemon to cache and prevent from frequent ssh password entries. When run, the environment variable SSH_AUTH_SOCK is used to point to ssh-agent's communication socket. The normal way to setup ssh-agent is to run it as the top most process of the user's session. Otherwise the environment variables will not be visible inside the session.
Depending on the way the graphical user session is configured to launch, it can be tricky to find a suitable way to launch ssh-agent. As an example for the lightdm display manager, you may edit and change /etc/lightdm/Xsession from
user $
exec $commande
into
user $
exec ssh-agent $commande
To tell ssh-agent the password once per session, either run ssh-add
manually or make use of the AddKeysToAgent
option.
Recent Xfce[1] will start ssh-agent (and gpg-agent) automatically. If both are installed both will be started which makes identity management especially with SmartCards more complicated. Either stop XFCE from autostarting at least SSH's agent or disable both and use your shell, X-session or similar.
user $
xfconf-query -c xfce4-session -p /startup/ssh-agent/enabled -n -t bool -s false
user $
xfconf-query -c xfce4-session -p /startup/gpg-agent/enabled -n -t bool -s false
Voir aussi
- Autossh — a command that detects when SSH connections drop and automatically reconnects them.
- Connecting via ssh and Using screen
- dropbear — a lightweight SSH server. It runs on a variety of POSIX-based platforms.
- Keychain
- Mosh — a SSH client server that is aware of connectivity problems of the original SSH implementation.
- Securing the SSH service (Security Handbook)
- SSHFS — a secure shell client used to mount remote filesystems to local machines.
- SSH_tunneling — a method of connecting to machines on the other side of a gateway machine.
- SSH_jump_host
- Starting the SSH daemon — Gentoo Handbook — Installation
Copying files to a remote host
The SFTP command, a part of SSH, uses the SSH File Transfer Protocol to copy files to a remote host. rsync is also an alternative for this.
The OpenSSH 8.0 release notes, from 2019, state "The scp protocol is outdated, inflexible and not readily fixed. We recommend the use of more modern protocols like sftp and rsync for file transfer instead.". The OpenSSH 8.8 release notes, from 2021, state "A near-future release of OpenSSH will switch scp(1) from using the legacy scp/rcp protocol to using SFTP by default.".
- SCP — an interactive file transfer program, similar to the copy command, that copies files over an encrypted SSH transport.
- SFTP — an interactive file transfer program, similar to FTP, which performs all operations over an encrypted SSH transport.
- rsync — a powerful file sync program capable of efficient file transfers and directory synchronization.
Ressources externes
- net-misc/connect — SSH Proxy Command -- connect.c
- https://lonesysadmin.net/2011/11/08/ssh-escape-sequences-aka-kill-dead-ssh-sessions/amp/ - A blog entry on escape sequences.
- https://hackaday.com/2017/10/18/practical-public-key-cryptography/ - Practical public key cryptography (Hackaday).