SSH

From Gentoo Wiki
Jump to:navigation Jump to:search
This page is a translated version of the page SSH and the translation is 55% complete.
Outdated translations are marked like this.

SSH (Secure SHell) ist das allgegenwärtige Tool für die sichere Anmeldung bei und die Arbeit an entfernten Rechnern. Alle sensiblen Informationen werden stark verschlüsselt, und zusätzlich zur Remote-Shell unterstützt SSH die Dateiübertragung und die Weiterleitung von Ports für beliebige Protokolle, was einen sicheren Zugang zu Remote-Diensten ermöglicht. Es ersetzt das klassische telnet, rlogin, und ähnliche unsichere Tools - aber SSH ist nicht nur eine Remote-Shell, sondern eine komplette Umgebung für die Arbeit mit entfernten Systemen.

Zusätzlich zum Haupt ssh Befehl, enthält die SSH-Programmsammlung inzwischen auch andere Werkzeuge wie scp (Secure Copy Program), sftp (Secure File Transfer Protocol), oder ssh-agent zur Unterstützung der Schlüsselverwaltung. Der Standard-SSH-Port ist Port 22.

Ursprünglich war SSH nicht frei. Heute ist die populärste und de-facto Standard-Implementation OpenBSD's OpenSSH, welche bei Gentoo vorinstalliert ist.

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

Installation überprüfen

Die meisten Bereitstellungen von Gentoo Linux haben OpenSSH bereits auf dem System installiert. Dies kann durch Ausführen des ssh-Befehls überprüft werden. Sofern es installiert ist sollte eine Gebrauchsanweisung ausgegeben werden:

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]

Wenn keine Gebrauchsanweisung ausgegeben wird ist ssh entweder beschädigt oder nicht installiert. Es ist auch möglich dass ein Nutzer OpenSSH neu baut um eine neue USE-Konfiguration zu inkludieren. Wie auch immer, zum Betrachten von möglichen USE-Konfigurationen weitermachen.

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.

USE-Flags

USE flags for net-misc/openssh Port of OpenBSD's free SSH release

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

Emerge

Nach dem Ändern der notwendigen USE-Flags das Installieren oder Neubauen von OpenSSH nicht vergessen:

root #emerge --ask --changed-use --oneshot net-misc/openssh

Nach der Änderung von globalen USE-Flags in make.conf, die das OpenSSH-Paket betreffen, muss emerge world auf die neuen USE-Flags aktualisiert werden:

root #emerge --ask --verbose --update --deep --newuse @world

Konfiguration

Schlüssel erstellen

Um eine sichere Shell bereitzustellen, werden kryptographische Schlüssel für die Ver- und Entschlüsselung sowie Hashing-Funktionen von SSH benutzt.

Beim ersten Start des SSH-Services werden die System-Schlüssel erzeugt. Diese können mittels des ssh-keygen-Befehls (neu-)erstellt werden .

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

Server-Konfiguration

Der SSH Server wird normalerweise in der Datei /etc/ssh/sshd_config konfiguriert, weitere Einstellungen, einschließlich des Ortes, an dem sich die obige Konfiguration befindet, können in /etc/conf.d/sshd getätigt werden, inklusive das Ändern des Ortes der Konfigurationsdatei. Für Details über die Konfiguration sollte die man page "sshd_config" konsultiert werden.

Der Server stellt eine Möglichkeit zur Validierung seiner Konfiguration durch den Testmodus zur Verfügung.

root #/usr/sbin/sshd -t
Wichtig
Befor der Dienst neugestartet wird, sollte die Konfiguration immer validiert werden, damit der Fernzugriff verfügbar bleibt.

Klient-Konfiguration

Der ssh-Klient und zugehörige Programme (scp, sftp, etc.) können in den folgenden Dateien konfiguriert werden:

  • ~/.ssh/config
  • /etc/ssh/ssh_config

Für weitere Information das ssh_config-Handbuch lesen:

Eindringensvermeidung

SSH ist ein oft angegriffener Dienst. Werkzeuge wie sshguard und fail2ban überwachen Logs und blacklisten entfernte Nutzer die wiederholt versuchten und scheiterten, sich anzumelden. Wie benötigt verwenden um ein häufig attackiertes System abzusichern.

Dienst

Commands to run the SSH server will depend on active init system.

OpenRC

Den OpenSSH-Daemon zum Default-Runlevel hinzufügen:

root #rc-update add sshd default

Den sshd-Daemon starten mit:

root #rc-service sshd start

Der OpenSSH-Server kann wie jeder andere OpenRC-Dienst gesteuert werden:

root #rc-service sshd start
root #rc-service sshd stop
root #rc-service sshd restart
Hinweis
Aktive Verbindungen zum Server bleiben beim Ausführen von rc-service sshd restart intakt.

systemd

Um den OpenSSH-Daemon mit dem System zu starten:

root #systemctl enable sshd.service
Hat einen symbolischen Verweis von /etc/systemd/system/multi-user.target.wants/sshd.service auf /usr/lib64/systemd/system/sshd.service angelegt.

Um den OpenSSH-Daemon jetzt zu starten:

root #systemctl start sshd.service

Um zu überprüfen ob der Dienst gestartet wurde:

root #systemctl status sshd.service

Bedienung

Befehle

OpenSSH provides several commands, see each command's man page for usage information:

  • scp - Secure File Copy
  • sftp - Secure File Transfer
  • ssh-add - Private-Key Identitäten zum Authentifizierungsagenten hinzufügen
  • ssh-agent - Authentifizierungsagenten
  • ssh-copy-id - Verwendung lokal verfügbarer Schlüssel zur Autorisierung von Anmeldungen auf einem entfernten Rechner
  • ssh-keygen - Authentifizierungsschlüssel-Dienstprogramm
  • ssh-keyscan - öffentliche SSH-Schlüssel von Servern sammeln
  • sshd - OpenSSH Daemon

Ausbruchsequenzen

Während einer aktiven SSH-Sitzung wird durch das Drücken der Tile-Taste (~) eine Ausbruchsequenz begonnen:

ssh>~?

Note that escapes are only recognized immediately after a newline. They may not always work with some shells, such as fish.

Verbindung zu einem entfernten SSH-Server aufbauen

Praktisch für das Verwalten von git-Servern. Siehe auch das Sicherheitshandbuch.

Siehe auch
For more details see the Security Handbook.
Warnung
Leaving the passphrase empty implies the private key file will not be encrypted. An attacker having access to the local filesystem will be able to read the private key.

Client

Falls noch nicht vorhanden, muss auf dem Klienten ein Schlüsselpaar angelegt werden. Dies erfolgt durch die Eingabe des folgenden Befehls (natürlich ohne eine Passphrase einzugeben):

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.. .. ..       |
| :. .  ! .       |
+-----------------+

The default file names of the keys must not be changed, or the server may persist in asking for a password even after running ssh-copy-id as explained below. The file name will be one of:

  • id_rsa
  • id_ecdsa
  • id_ed25519

depending on the key algorithm used.

Server

Nun muss sichergestellt werden, dass für den Anwender ein Benutzerkonto auf dem Server existiert. Dann kann der Inhalt der id_rsa.pub-Datei des Klienten in der Datei ~/.ssh/authorized_keys im Homeverzeichnis des Anwenders auf dem Server platziert werden. Dies erfolgt durch das Ausführen des folgenden Befehls auf dem Klienten (ess wird die Passphrase des Anwenders auf dem Server benötigt):

user $ssh-copy-id <server>
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/larry/.ssh/id_ed25519.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.

Anschließend sollte eine Anmeldung ohne Eingabe der Passphrase wie folgt möglich sein:

user $ssh <server>
larry@<server>

Auf dem Server sollte dann in der Datei /etc/ssh/sshd_config PasswordAuthentication no eingetragen werden.

Einzel-Maschinen-Test

Die oben beschriebene Prozedur kann lokal getestet werden:

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

Remote services over ssh

SSH may be used to access remote services, such as HTTP, HTTPS, fileshares, etc., through an encrypted "tunnel". Remote service access is detailed in the SSH tunneling and SSH jump host articles.

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.

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

ssh-agent

OpenSSH enthält ssh-agent, einen Dienst, der für SSH verwandte Passphrasen zwischenspeichert, sodass keine erneute Eingabe erforderlich ist. Wenn er ausgeführt wird, zeigt die Variable SSH_AUTH_SOCK auf sein Kommunikations-Socket. Der übliche Weg zur Einrichtung von ssh-agent ist es, ihn als Wurzelprozess in der Sitzung des Benutzers auszuführen. Andernfalls sind Umgebungsvariablen in der Sitzung nicht abrufbar.

Je nachdem, wie die graphische Benutzersitzung gestartet wird, kann es schwierig sein, einen adäquaten Weg zu finden, ssh-agent zu starten. Als Beispiel für den Displaymanager lightdm kann der Inhalt der Datei /etc/lightdm/Xsession:

user $exec $command

durch Folgendes ersetzt werden:

user $exec ssh-agent $command

Um ssh-agent die Passphrase einmal pro Sitzung mitzuteilen, kann entweder ssh-add manuell ausgeführt, oder die Option AddKeysToAgent verwendet werden.

Neuere Versionen von Xfce starten ssh-agent (und gpg-agent) automatisch. Sind beide Programme installiert, werden sie auch beide gestartet, was das Identitätsmanagement insbesondere mit SmartCards erschwert. Um das zu beheben, kann der Autostart des SSH-Agents deaktiviert werden. Alternativ kann auch der Autostart beider Programme deaktiviert werden, um stattdessen die Shell, X-Session oder Ähnliches zu benutzen.

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

Tipps

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.

SSH over intermittent connections

When on unstable Internet connections, or when roaming between networks (such as when moving wifi networks), mosh can help avoid dropping SSH sessions.

Open new tabs for session with Kitty terminal

By using the SSH kitten for the Kitty terminal emulator, it is possible to open new "tabs", or windows, on the current SSH session without having log in again.

Kitty also provides other practical SSH functionality.

Benchmark the optimal rounds for an ed25519 key

Tipp
It is highly advisable to conduct benchmarking for the ed25519 key generation process, particularly considering the default value of 16 rounds and the potential performance improvements achievable with higher round values.
DATEI ssh-benchmark.shBenchmark SSH Ciphers
#!/bin/sh

rounds="16 32 64 100 150"
num_runs=20

for r in $rounds; do
    printf "Benchmarking 'ssh-keygen -t ed25519 -a %s' on average:\n" "$r"
    total_time=0
    i=1
    while [ $i -le $num_runs ]; do
        start_time=$(date +%s.%N)
        ssh-keygen -t ed25519 -a "$r" -f test -N test >/dev/null 2>&1
        end_time=$(date +%s.%N)
        runtime=$(echo "$end_time - $start_time" | bc)
        total_time=$(echo "$total_time + $runtime" | bc)
        rm test{,.pub} >/dev/null 2>&1
        printf "Run %s: %s seconds\n" "$i" "$runtime"
        i=$((i + 1))
    done
    average_time=$(echo "scale=3; $total_time / $num_runs"| bc)
    printf "Average execution time: %s seconds\n\n" "$average_time"
done
Hinweis
It is highly recommended to perform benchmarking for ed25519 key generation, considering both security and performance aspects. While the highest recommended round may offer superior security, it's essential to find the optimal balance based on individual requirements and time constraints. By conducting benchmark tests, one can evaluate the trade-off between security and performance, ensuring the selection of an appropriate round value for ed25519 keys.

Benchmarking is a crucial process to measure the performance and efficiency of a system or a specific component, such as cryptographic algorithms. In the context of SSH (Secure Shell) ciphers, it is important to determine the optimal number of rounds for generating ed25519 keys.

The provided script, ssh-benchmark.sh, conducts benchmarking on the ssh-keygen command with different round values for ed25519 keys. The script executes the ssh-keygen command multiple times with varying round values and measures the execution time for each run. It then calculates the average execution time for each round value.

By benchmarking different round values, system administrators and security professionals can identify the optimal round value that strikes a balance between security and performance. Higher round values generally provide stronger security but can result in increased computational overhead. Finding the right balance ensures that ed25519 keys are generated efficiently without compromising security.

Benchmarking helps identify potential bottlenecks, vulnerabilities, or areas that require improvement in security systems. It assists in selecting the most suitable algorithms and configurations for a particular use case, ensuring that security measures are robust and effective.

Fehlersuche

Es gibt drei verschiedene Level von Debug-Modi, die bei der Problemlösung helfen können. Mit der -v-Option gibt SSH Debugging-Nachrichten über seinen Fortschritt aus. Dies ist hilfreich bei dem Debugging von Verbindungs-, Authentifikations- und Konfigurationsproblemen. Mehrfache -v-Optionen erhöhen die Verbosität. Das Maximum ist drei.

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.

Abbruch langlebiger Verbindungen

Viele Geräte, die Zugriff zum Internet anbieten, benutzen dafür Network Address Translation (NAT), ein Prozess der Geräten in einem privaten Netzwerk (typischerweise in Heim- oder Berufsumgebungen) Zugriff auf fremde Netzwerke wie dem Internet ermöglicht, obwohl sie nur eine einzige IP-Adresse in diesem fremden Netzwerk besitzt. Leider funktionieren diese NAT-Geräte nicht alle gleich und manche von ihnen schließen langlebige, nur gelegentlich genutzte TCP Verbindungen wie die von SSH. Man erkennt das daran, dass man auf einmal nicht mehr mit dem entfernten Computer interagieren kann, obwohl das ssh-Klienten-Programm nicht beendet wurde.

Um dieses Problem zu lösen, können OpenSSH-Klienten und -Server so konfiguriert werden, dass sie eine unsichtbare "keep alive" Nachricht senden, deren Ziel das Aufrechterhalten der Verbindung ist:

  • Um Keep-Alive für alle Klienten, die sich mit dem lokalen Server verbinden, zu aktivieren, ClientAliveInterval 30 (oder einen anderen Wert, in Sekunden) in der /etc/ssh/sshd_config-Datei setzen.
  • Um Keep-Alive für alle Server, mit denen sich der lokale Klient verbindet, zu aktivieren, ClientAliveInterval 30 (oder einen anderen Wert, in Sekunden) in der /etc/ssh/ssh_config- oder ~/.ssh/config-Datei setzen.
  • Setzen Sie TCPKeepAlive no, um Verbindungsabbrüche zu vermeiden.

For example, to modify the server's configuration, add following file:

DATEI /etc/ssh/sshd_config/01_ClientAlive.confHelp 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, add following file:

DATEI /etc/ssh/ssh_config/01_ServerAlive.confHelp disconnects occur less often (client)
# The following ServerAlive values will keep an inactive session open for 2 hours
ServerAliveInterval 60
ServerAliveCountMax 120

New key does not get used

This scenario covers the case when a key to access a remote system has been created, the public key installed on the remote system, but the remote system is (for some reason) not accessible via ssh. This can happen if the name of the keyfile is not known to ssh.

Confirm which key files ssh is trying by running it with one of the verbose options, as described at the start of the Troubleshooting section. The verbose output will include the names of the keyfiles it is trying, and the one (if any) that actually gets used.

The default key files for the system are listed in the /etc/ssh/ssh_config, see the commented-out lines containing IdentityFile directives.

There are several ways to use a key with a non-default name.

The key name can be specified on the command line every time:

user $ssh -i ~/.ssh/my_keyfile user@remotesys

Alternatively, add following ssh configuration file to add a special case for ssh to the remote system:

DATEI /etc/ssh/ssh_config/02_remotesys.confDefine keyfiles to use for host remotesys
Host remotesys
    IdentityFile ~/.ssh/id_rsa
    IdentityFile ~/.ssh/my_keyfile

If any are specified, it appears to be necessary to specify all the desired keys on a remote host. Read up on the ssh IdentityFile.

X11-Weiterleitung, keine Portweiterleitung oder Tunnelung

Problem: Nachdem die nötigen Veränderungen an den Konfigurationsdateien gemacht sind, wird bemerkt dass X-Applikationen auf dem Server ausgeführt und nicht an den Klienten weitergeleitet werden.

Lösung: Was vermutlich während der SSH-Anmeldung auf dem Server passiert, die DISPLAY-Variable ist entweder nicht gesetzt oder wird gesetzt nachdem die SSH-Sitzung sie setzt.

Wenn das Szenario zutrifft, kann es wie folgend nach dem Anmelden auf dem Server getestet werden:

user $echo $DISPLAY
localhost:10.0

Die Ausgabe sollte in etwa ähnlich zu localhost:10.0 oder localhost2.local:10.0 mit der serverseitigen Einstellung X11UseLocalhost no sein. Wenn das übliche :0.0 nicht ausgegeben wird, sicherstellen dass die DISPLAY-Variable in ~/.bash_profile nicht ungesetzt oder reinitialisiert ist. Wenn sie es ist, jegliche Initialisierung der DISPLAY-Variable entfernen oder auskommentieren um die Ausführung des Codes in ~/.bash_profile bei einer SSH-Anmeldung zu verhindern:

user $ssh -t larry@localhost2 bash --noprofile

larry im Kommando oberhalb mit dem passenden Benutzernamen ersetzen.

Ein Trick der funktioniert wäre ein alias innerhalb der ~/.bashrc-Datei zu definieren.

Siehe auch

Externe Ressourcen