SSH

Aus wiki.archlinux.de

Secure Shell oder SSH ist ein Netzwerk Protokoll welches den sicheren Datenaustausch zwischen zwei Computern über ein Netzwerk gestattet. SSH bietet dank Verschlüsselung Diskretion und Integrität der versendeten Daten. Als Verschlüsselungsverfahren wird ein asymmetrisches Kryptosystem (Verschlüsselung durch public und privat Keys) eingesetzt, um den zugreifenden Computer und - falls benötigt - auch den zugreifenden Benutzer zu verifizieren.

SSH wird normalerweise benutzt, um sich in einem entfernten System einzuloggen und Kommandos auszuführen. Zusätzlich wird Tunneling, das Transmission Control Protocol (TCP) und X11 Verbindungen unterstützt. Datentransfer kann durch die Protokolle SFTP und SCP erreicht werden.

Standardmäßig lauscht der SSH-Server auf den Standard TCP Port 22. Ein SSH-Client Programm wird normalerweise benutzt um eine Verbindung zu einem sshd (Secure Shell Daemon) herzustellen. Beide Programme sind für die meisten modernen Betriebssysteme vorhanden. U. a. für Mac OS X, GNU/Linux, Solaris und OpenVMS. Proprietäre, freie und Open Source Versionen in unterschiedlicher Komplexität und Vollständigkeit existieren.

(Source: Secure Shell])


OpenSSH

OpenSSH (OpenBSD Secure Shell) ist eine Sammlung von Programmen die eine verschlüsselte Verbindung über ein Computernetzwerk mit dem SSH Protokoll erlauben. Sie wurde als eine Open Source Alternative zu der proprietären Secure Shell software suite des Unternehmens SSH Communications Security erstellt. OpenSSH wird als Teil des OpenBSD Projektes entwickelt und von Theo de Raadt geleitet.

OpenSSH wird gelegentlich mit dem ähnlich benannten OpenSSL verwechselt. Beide Projekte haben allerdings verschiedene Zwecke und werden von verschiedenen Teams entwickelt. Der ähnliche Name kommt allein von ähnlichen Zielen.


OpenSSH installieren

# pacman -S openssh

SSH Konfigurieren

Client

Die SSH Client Konfigurationsdatei wird unter /etc/ssh/ssh_config automatisch angelegt.


Hier eine Beispiel Konfiguration:

#       $OpenBSD: ssh_config,v 1.25 2009/02/17 01:28:32 djm 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
#   RhostsRSAAuthentication no
#   RSAAuthentication yes
#   PasswordAuthentication yes
#   HostbasedAuthentication no
#   GSSAPIAuthentication no
#   GSSAPIDelegateCredentials no
#   BatchMode no
#   CheckHostIP yes
#   AddressFamily any
#   ConnectTimeout 0
#   StrictHostKeyChecking ask
#   IdentityFile ~/.ssh/identity
#   IdentityFile ~/.ssh/id_rsa
#   IdentityFile ~/.ssh/id_dsa
#   Port 22
#   Protocol 2,1
#   Cipher 3des
#   Ciphers aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc
#   MACs hmac-md5,hmac-sha1,umac-64@openssh.com,hmac-ripemd160
#   EscapeChar ~
#   Tunnel no
#   TunnelDevice any:any
#   PermitLocalCommand no
#   VisualHostKey no
HashKnownHosts yes
StrictHostKeyChecking ask

Es wird empfohlen die Protokoll Zeile in Folgendes zu ändern:

Protocol 2

Dies bedeutet, dass nur Protokoll 2 benutzt wird, da Protokoll 1 als unsicher gilt.


Daemon

Die SSH Daemon Konfigurationsdatei wird unter /etc/ssh/ssh automatisch angelegt.

Hier eine Beispiel Konfiguration:

#	$OpenBSD: sshd_config,v 1.75 2007/03/19 01:01:29 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 change a
# default value.

#Port 22
#Protocol 2,1
ListenAddress 0.0.0.0
#ListenAddress ::

# HostKey for protocol version 1
#HostKey /etc/ssh/sshhostkey
# HostKeys for protocol version 2
#HostKey /etc/ssh/sshhostrsa_key
#HostKey /etc/ssh/sshhostdsa_key

# Lifetime and size of ephemeral version 1 server key
#KeyRegenerationInterval 1h
#ServerKeyBits 768 

# Logging
#obsoletes ~QuietMode and ~FascistLogging
#SyslogFacility AUTH
#LogLevel INFO 

# Authentication:
#LoginGraceTime 2m
#PermitRootLogin yes
#StrictModes yes
#MaxAuthTries 6

#RSAAuthentication yes
#PubkeyAuthentication yes
#AuthorizedKeysFile     .ssh/authorized_keys

# For this to work you will also need host keys in /etc/ssh/sshknownhosts
#RhostsRSAAuthentication no
# similar for protocol version 2
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# RhostsRSAAuthentication and 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 no to disable s/key passwords
#ChallengeResponseAuthentication yes 

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

# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes 

# 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 mechanism.
# Depending on your PAM configuration, this may bypass the setting of
# PasswordAuthentication, ~PermitEmptyPasswords, and
# "PermitRootLogin without-password". If you just want the PAM account and
# session checks to run without PAM authentication, then enable this but set
# ChallengeResponseAuthentication=no
#UsePAM no

#AllowTcpForwarding yes
#GatewayPorts no
#X11Forwarding no
#X11DisplayOffset 10
#X11UseLocalhost yes
#PrintMotd yes
#PrintLastLog yes
#TCPKeepAlive yes
#UseLogin no
#UsePrivilegeSeparation yes
#PermitUserEnvironment no
#Compression yes
#ClientAliveInterval 0
#ClientAliveCountMax 3
#UseDNS yes
#PidFile /var/run/sshd.pid
#MaxStartups 10 

# no default banner path
#Banner /some/path 

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

Um den Zugriff nur für bestimmte User zu erlauben füge folgende Zeile hinzu:

AllowUsers    user1 user2

Evtl. möchtest Du auch einige Zeilen ändern, so dass sie wie folgt aussehen:


Protocol 2

.

.

.

LoginGraceTime 120

.

.

.

PermitRootLogin no # (put yes here if you want root login)

Außerdem kannst Du die BANNER Option einkommentieren und deine /etc/issue für eine nette Willkommens Botschaft bearbeiten.

Wahrscheinlich willst Du den Standard Port von 22 auf irgendeinen höheren Port ändern (siehe dazu: security through obscurity).

Obwohl der Port, auf welchen SSH lauscht, von einem Port Scanner wie nmap gefunden werden kann, wird die Änderung des Ports die Anzahl der automatischen Login Versuche merklich eindämmen.

Das Ausschalten von Passwort basierten Logins erhöht ebenfalls die Sicherheit, da jeder User der sich auf dem Server anmelden will einen SSH Key erstellen muss (siehe dazu Using SSH Keys).

Dazu ist in der /etc/ssh/ssh einzutragen:

PasswordAuthentication no

ChallengeResponseAuthentication no

Erlaube Fremdzugriffe

Du musst diese Datei anpassen um per SSH auf deinen Server zugreifen zu können, da diese per default leer ist.

Um andere Menschen per SSH auf deinen Server zugreifen zu lassen musst Du die /etc/hosts.allow anpassen und folgendes hinzufügen:


# let everyone connect to you

sshd: ALL



# OR you can restrict it to a certain ip

sshd: 192.168.0.1



# OR restrict for an IP range

sshd: 10.0.0.0/255.255.255.0



# OR restrict for an IP match

sshd: 192.168.1.

Nun solltest Du deine /etc/hosts.deny ansehen und sicherstellen, dass sie wie folgt aussieht:

ALL: ALL: DENY

That's it. You can SSH out and others should be able to SSH in :). Das war es. Du solltest nun einen funktionierenden SSH-Clienten & Daemon haben.

Um die neue Konfiguration zu benutzen starte den Daemon (als root) neu:

# /etc/rc.d/sshd restart


Kontrolle des SSH Daemon

Füge den sshd zu der "DAEMONS" Zeile deiner /etc/rc.conf hinzu:

DAEMONS=(... ... sshd ... ...)

Um den Daemon zu starten/stoppen/neu starten, benutze folgendes:

# /etc/rc.d/sshd {start|stop|restart}

Mit dem Server verbinden

Um sich mit einem Server zu verbinden führe folgendes aus:

$ ssh -p port user@server-address


Tips und Tricks

Verschlüsselter Socks Tunnel

Dies ist sehr nützlich für Laptop Benutzer die zu unterschiedlichen, unsicheren Funknetzwerken verbunden werden. Das einzige was du dafür brauchst ist ein laufender SSH-Server mit einem sicheren Anschluss, wie dein Home-PC oder dein Arbeitsplatz Rechner. Es ist nützlich einen dynamischen DNS Service wie DynDNS zu benutzen, damit du deine IP-Adresse nicht behalten musst.


Schritt 1: Starte die Verbindung

Du musst nur ein einziges Programm in deinem Terminal ausführen um die Verbindung zu starten:

$ ssh -ND 4711 user@host

Dabei ist user dein Benutzername auf dem SSH Server der als host läuft. SSH wird dich nach deinem Passwort fragen und dich dann verbinden. Das N-Flag schaltet die interaktive Eingabeaufforderung ab und das D-Flag stellt den lokalen Port ein, auf dem gelauscht werden soll. Du kannst eine beliebige Port Nummer wählen, wenn du willst.

Ein Weg dies zu vereinfachen ist, einen Alias wie den folgenden in deine ~/.bashrc (oder je nach der eingesetzten Shell) hinzuzufügen:

alias sshtunnel="ssh -ND 4711 -v user@host"

Es ist praktisch, das v-Flag (für verbose - gesprächig) hinzuzufügen, da du dank diesem in dem SSH Output ablesen kannst, ob du verbunden bist. Nun musst du nur noch das sshtunnel-Kommando ausführen :)


Schritt 2: Konfiguriere deinen Browser (oder andere Programme)

Der vorherige Schritt ist vollkommen nutzlos, wenn du deinen Web Browser (oder andere Programme) nicht so konfigurierst, dass sie den neuen Socks Tunnel benutzen.

  • Für Firefox: Edit → Preferences → Advanced → Network → Connection → Setting:
Markiere die "Manual proxy configuration" Option und schreibe "localhost" in das "SOCKS host" Textfeld. Dann gib deine Port-Nummer im nächsten Feld an.
Stelle sicher, dass du SOCKS4 als das zu benutzende Protokoll angibst, da diese Einstellungen nicht für SOCKS5 funktionieren.

Viel Spaß mit deinem sicheren Tunnel!

X11 Forwarding

To run graphical programs through a SSH connection you can enable X11 forwarding. An option needs to be set in the configuration files on the server and client (here "client" means your (desktop) machine your X11 Server runs on, and you will run X applications on the "server").


Install xorg-xauth on the server:

# pacman -S xorg-xauth





To use the forwarding, log on to your server through ssh:

# ssh -X -p port user@server-address

If you receive errors trying to run graphical applications try trusted forwarding instead:

# ssh -Y -p port user@server-address

You can now start any X program on the remote server, the output will be forwarded to your local session:

# xclock


Speed up SSH

Changing the ciphers used by SSH to less cpu-demanding ones can improve speed. In this aspect, the best choices are arcfour and blowfish-cbc. To use them, run SSH with the Vorlage:Codeline flag, like this:

# ssh -c arcfour,blowfish-cbc user@server-address

To use them permanently, add this line under the proper host in Vorlage:Filename:

Ciphers arcfour,blowfish-cbc

Another option to improve speed is to enable compression with the Vorlage:Codeline flag. A permanent solution is to add this line under the proper host in Vorlage:Filename:

Compression yes

Login time can be shorten by using the Vorlage:Codeline flag, which bypasses IPv6 lookup. This can be made permanent by adding this line under the proper host in Vorlage:Filename:

AddressFamily inet

Another way of making these changes permanent is to create an alias in Vorlage:Filename:

alias ssh='ssh -C4c arcfour,blowfish-cbc'

Finally, you can make all sessions to the same host use a single connection, which will greatly speed up subsequent logins, by adding those line under the proper host in Vorlage:Filename:

ControlMaster auto
ControlPath ~/.ssh/socket-%r@%h:%p


Trouble Shooting

make sure your DISPLAY string is resolveable on the remote end:


ssh -X user@server-address
server$ echo $DISPLAY
localhost:10.0
server$ telnet localhost 6010
localhost/6010: lookup failure: Temporary failure in name resolution   


can be fixed by adding localhost to Vorlage:Filename.


Mounting a Remote Filesystem with SSHFS

Install sshfs

# pacman -S sshfs


Load the Fuse module

# modprobe fuse

Add fuse to the modules array in Vorlage:Filename to load it on each system boot.


Mount the remote folder using sshfs

# mkdir ~/remote_folder
# sshfs USER@remote_server:/tmp ~/remote_folder


The command above will cause the folder /tmp on the remote server to be mounted as ~/remote_folder on the local machine. Copying any file to this folder will result in transparent copying over the network using SFTP. Same concerns direct file editing, creating or removing.


When we’re done working with the remote filesystem, we can unmount the remote folder by issuing:

# fusermount -u ~/remote_folder


If we work on this folder on a daily basis, it is wise to add it to the Vorlage:Filename table. This way is can be automatically mounted upon system boot or mounted manually (if Vorlage:Codeline option is chosen) without the need to specify the remote location each time. Here is a sample entry in the table:

sshfs#USER@remote_server:/tmp /full/path/to/directory fuse    defaults,auto,allow_other    0 0


Keep Alive

Your ssh session will automatically log out if it is idle. To keep the connection active (alive) add this to Vorlage:Filename or to Vorlage:Filename on the client.


ServerAliveInterval 120


This will send a "keep alive" signal to the server every 120 seconds.


Conversely, to keep incoming connections alive, you can set


ClientAliveInterval 120


(or some other number greater than 0) in Vorlage:Filename on the server.


Save connection data in .ssh/config

Whenever you want to connect to a server, you usually have to type at least its address and your username. To save that typing work for servers you regularly connect to, you can use the Vorlage:Filename file as shown in the following example:


Vorlage:File


Now you can simply connect to the server by using the name you specified:


$ ssh myserver


To see a complete list of the possible options, check out ssh_config's manpage on your system or the ssh_config documentation on the official website.


See Also


Links & References