SSH: diferència entre les revisions

De WikiMar
Salta a la navegació Salta a la cerca
Línia 261: Línia 261:
*ClientAliveInternal: number of seconds that the server will wait before sending a null packet to the client (to keep the connection alive).
*ClientAliveInternal: number of seconds that the server will wait before sending a null packet to the client (to keep the connection alive).
Setting a value of 0 (the default) will disable these features so your connection could drop if it is idle for too long.
Setting a value of 0 (the default) will disable these features so your connection could drop if it is idle for too long.
==Cron per mantenir un local/remote tunnel v3 usant autossh==
login-hook
<pre>
#!/bin/bash
COMMAND="/home/<user>/tunnel-start.sh"
LOGFILE="/home/<user>/tunnel-start.log"
DATE=$(date +'%Y-%m-%d %H:%M:%S')
if [ "$(ps ax | grep tunnel-start.sh | grep -vc grep)" -lt 1 ]; then
    echo "$DATE - Starting tunnel-start.sh" >> $LOGFILE
    $COMMAND &
    exit
fi
</pre>
tunnel-start.sh
<pre>
#!/bin/bash
LOGFILE="/home/<user>/tunnel-start.log"
DATE=$(date +'%Y-%m-%d %H:%M:%S')
while [ 1 ]; do
echo "$DATE - Starting autossh" >> $LOGFILE
autossh -M 0 -q -f -N -o "ServerAliveInterval 60" -o "ServerAliveCountMax 3" -R 8081:localhost:80 my.linuxbox.at.home
sleep 5
done
</pre>
More info: http://en.gentoo-wiki.com/wiki/Autossh
Without them, the -f option complains that it needs a command to fork and will just quit. -N says no command and -q says be quiet. Also if you would like to have a special key with no passphrase you can generate one and then use it via the -i option for ssh.
The above command will make ssh send a keep-alive request if no other data has been sent for 60 seconds, if it doesn't receive a reply after 3 attempts it will close the connection. autossh will then detect its been closed and attempt re-establish it.
The "-M 0" option disables autossh's own monitoring which uses separate ports and is less reliable.


==Cron per mantenir un doble reverse tunnel (usant gateway)==
==Cron per mantenir un doble reverse tunnel (usant gateway)==

Revisió del 15:43, 3 des 2012

Engega el ssh:

/etc/init.d/sshd restart

Tornar a demanar IP:

/net.eth0 restart

Sessió:

 /xdm restart


Connexió rebent les finestres a la màquina local:

ssh -X usuari@maquina

En cas que no hi sigui cal tenir fer

emerge xauth

En cas de problemes

ssh -v -X usuari@maquina

Usar compressió:

... -C

Tunel Normal (obrir port d'escolta a màquina local)

ssh -L 3002:localhost:119 vecino@brutal


Tunnel Invers (Obrir port d'escolta a la màquina remota)

ssh -p4022 -g -R 10022 usuari@maquina

o bé:

ssh -p4022 -g -R 10022:localhost:80 usuari@maquina

(per la -g, cal GatewayPorts yes en la configuració del servidor.)

Un altre exemple util a Cafe:

ssh -p23 -g -R 20022:localhost:22 usuari@cube

o be

~/papes-emergencia-tunel-20022.sh

Tunnel invers per permetre connexions inverses de VNC:

ssh -p4022 -g -R 5500:10.0.2.2:5500 [email protected]


Tunnel Dinamic / crear proxy SOCKS5

Amb l'opció -D creem un port LOCAL que és un port proxy SOCKS5 a on tot surt per la màquina REMOTA.

ex.

ssh -C2qTnN -D 8080 username@remote_machine.com
-C Compression
-2 SSH2 only
-q Quite
-T Force pseudo-tty allocation
-n Redirect stdin from /dev/null
-N and Place the ssh client into "master" mode for connection sharing.

Més info:

https://calomel.org/firefox_ssh_proxy.html
http://embraceubuntu.com/2006/12/08/ssh-tunnel-socks-proxy-forwarding-secure-browsing/

Copiar fitxers entre màquines:

scp -P 4022 usuari@maquina:/home/usuari/...


RSync

-a Archive. Mainly propogate file permissions, ownership, timestamp, etc.
-v Verbose -vv More verbose. -vvv Even more verbose.
-e ssh: Specify the remote shell as ssh
--numeric-ids: Tells rsync to not map user and group id numbers local user and group names
--delete: Makes server copy an exact copy of the source by removing any files that have been removed on the remote machine 
-n Don't do any copying, but display what rsync *would* copy. For testing.
-u Update. Don't copy file if file on destination is newer.
-z Comprimeix
rsync -avz -e "ssh -p23" /media/a/_PORTABLE/prog  cube.aluzina.org:/var/www/carpeta.espai.de/htdocs/portable/_PORTABLE_UTIL/prog
rsync --delete -avz -e 'ssh -p 222' /usr/portage [email protected]:/usr/portage

Per copiar un sistema sencer:

rsync -axHv --delete-after / [email protected]:/home/test
   -x, --one-file-system       don't cross filesystem boundaries
   -H, --hard-links            preserve hard links

Per copiar un fitxer gran (ensenyar % i si es para continuar):

rsync -avr --partial --progress ...

equivalent a:

rsync -avrP ...


Script

Més info a http://www.scrounge.org/linux/rsync.html

# Only run rsync if $DEST responds.
VAR=`ping -s 1 -c 1 $DEST > /dev/null; echo $?`
if [ $VAR -eq 0 ]; then
   rsync $OPTS $BACKDIR $USER@$DEST:$DESTDIR
else
   echo "Cannot connect to $DEST."
fi



Cron per mantenir un reverse tunnel v1

#!/bin/bash

REMOTE_HOST="[email protected]"
REMOTE_PORT="1122"
SSHKEY="/home/marti/.ssh/id_dsa"
COMMAND="ssh -f -N -p23 -i $SSHKEY -CD 8080 -g -R $REMOTE_PORT:localhost:22 $REMOTE_HOST"
# important: -f fa que quedi en background i el script continui
# -n fa que no obri ternimal nomes port forwarding

LOGFILE="/home/marti/routes-load.log"
DATE=$(date +'%Y-%m-%d %H:%M:%S')   

#disable next line?:
echo "$DATE - Started" >> $LOGFILE

# Is the tunnel up? Perform two tests:

# 1. Check for relevant process ($COMMAND)
pgrep -f -x "$COMMAND" || ($COMMAND && echo "$DATE - Not in ps" >> $LOGFILE)

# 2. Test tunnel by looking at 'netstat' output on $REMOTE_HOST
ssh -p23 -i $SSHKEY $REMOTE_HOST netstat -an | egrep "tcp.*:$REMOTE_PORT.*LISTEN" > /dev/null 2>&1

if [ $? -ne 0 ] ; then
   echo "$DATE - Not in netstat" >> $LOGFILE
   pkill -f -x '$COMMAND'
   $COMMAND
fi

Edit /etc/ssh/sshd_config and add/modify the following lines :

# TCPKeepAlive yes
# ClientAliveInterval 30
# ClientAliveCountMax 99999
# GatewayPorts yes
millor:
# GatewayPorts clientspecified

More information on keeping SSH connections stable: http://drupal.star.bnl.gov/STAR/comp/sofi/facility-access/ssh-stable-con

Cron per mantenir un reverse tunnel v1.2 en cas de no tenir pgrep - millor

#!/bin/bash

# REMOTE_HOST="[email protected]"
REMOTE_PORT="9922"
#SSHKEY="/home/marti/.ssh/id_dsa"
#COMMAND="ssh -p23 -i $SSHKEY -CD 8080 -f -N -g -R $REMOTE_PORT:localhost:22 $REMOTE_HOST"
COMMAND="/usr/bin/ssh -f -N -R $REMOTE_PORT:127.0.0.1:22 -L 6622:127.0.0.1:6622 unixsmod@earth ssh -R 0.0.0.0:$REMOTE_PORT:127.0.0.1:9922 -L 6622:127.0.0.1:443 -p 443 [email protected]"


LOGFILE="/home/marti/routes-load.log"
DATE=$(date +'%Y-%m-%d %H:%M:%S')   

#disable next line?:
echo "$DATE - Started" >> $LOGFILE

# Is the tunnel up? Perform two tests:

# 1. Check for relevant process ($COMMAND)
if ! ps ax | grep -v grep | grep "$COMMAND" > /dev/null 2>&1
then
    echo "$DATE - Not in ps" >> $LOGFILE
    $COMMAND
    #Potser: exit 
fi

# 2. Test tunnel by looking at 'netstat' output on $REMOTE_HOST
ssh -p23 -i $SSHKEY $REMOTE_HOST netstat -an | egrep "tcp.*:$REMOTE_PORT.*LISTEN" > /dev/null 2>&1
if [ $? -ne 0 ] ; then
   echo "$DATE - Not in netstat" >> $LOGFILE
   pkill -f -x '$COMMAND'
   $COMMAND
fi

Si es per obrir "SSH", i a la maquina remota hi ha "nmap" es pot fer:

# 2.
ssh -p23 -i $SSHKEY $REMOTE_HOST nmap -sV -p $REMOTE_PORT 127.0.0.1 | grep -i "OpenSSH" > /dev/null 2>&1
if [ $? -ne 0 ] ; then
   echo "$DATE - Not detected as OpenSSH" >> $LOGFILE
   pkill -f -x '$COMMAND'
   $COMMAND
fi

Alternativa 1:

if [ $(ps ax | grep "$COMMAND" | grep -vc grep) -lt 1 ]

Alternativa 2:

#ps ax | grep -v grep | grep "$COMMAND" > /dev/null 2>&1
#if [ $? -ne 0 ]

$? es el exit code de la ultima comanda. Si es 0=success. En cas de grep vol dir que ha trobat.

Cron per mantenir un local tunnel v2

login-hook

#!/bin/bash
COMMAND="/Users/<user>/devel/tunnel-start.sh"
LOGFILE="/home/marti/routes-load.log"
DATE=$(date +'%Y-%m-%d %H:%M:%S') 


if [ "$(ps ax | grep tunnel-start.sh | grep -vc grep)" -lt 1 ]; then
    echo "$DATE - Not in ps" >> $LOGFILE
    $COMMAND &
    #sudo -u <user> /Users/<user>/devel/tunnel-start.sh &
    exit
fi


#Opcional: Potser es pot mirar tambe el nestat local si el port esta obert:
netstat -an | egrep "tcp.*:$REMOTE_PORT.*LISTEN" > /dev/null 2>&1
if [ $? -ne 0 ] ; then
   echo "$DATE - Not in netstat" >> $LOGFILE
   pkill -f -x '$COMMAND'
   $COMMAND &
fi


tunnel-start.sh

#!/bin/bash
 
while [ 1 ]; do
 ssh -N -L 6667:127.0.0.1:6667 -o ServerAliveInterval=3 user@server
 sleep 5
done

More info: http://crz.lt/2007/09/26/setting-up-a-permanent-ssh-tunnel-on-mac-os-x/

-o ServerAliveInterval=15 or even 60 should be fine and with less stress:

  • ServerAliveInterval: number of seconds that the client will wait before sending a null packet to the server (to keep the connection alive).
  • ClientAliveInternal: number of seconds that the server will wait before sending a null packet to the client (to keep the connection alive).

Setting a value of 0 (the default) will disable these features so your connection could drop if it is idle for too long.



Cron per mantenir un local/remote tunnel v3 usant autossh

login-hook

#!/bin/bash
COMMAND="/home/<user>/tunnel-start.sh"
LOGFILE="/home/<user>/tunnel-start.log"
DATE=$(date +'%Y-%m-%d %H:%M:%S') 

if [ "$(ps ax | grep tunnel-start.sh | grep -vc grep)" -lt 1 ]; then
    echo "$DATE - Starting tunnel-start.sh" >> $LOGFILE
    $COMMAND &
    exit
fi


tunnel-start.sh

#!/bin/bash

LOGFILE="/home/<user>/tunnel-start.log"
DATE=$(date +'%Y-%m-%d %H:%M:%S') 
 
while [ 1 ]; do
 echo "$DATE - Starting autossh" >> $LOGFILE
 autossh -M 0 -q -f -N -o "ServerAliveInterval 60" -o "ServerAliveCountMax 3" -R 8081:localhost:80 my.linuxbox.at.home
 sleep 5
done

More info: http://en.gentoo-wiki.com/wiki/Autossh

Without them, the -f option complains that it needs a command to fork and will just quit. -N says no command and -q says be quiet. Also if you would like to have a special key with no passphrase you can generate one and then use it via the -i option for ssh.

The above command will make ssh send a keep-alive request if no other data has been sent for 60 seconds, if it doesn't receive a reply after 3 attempts it will close the connection. autossh will then detect its been closed and attempt re-establish it.

The "-M 0" option disables autossh's own monitoring which uses separate ports and is less reliable.

Cron per mantenir un doble reverse tunnel (usant gateway)

#!/bin/bash

REMOTE_PORT="9922"
LOCAL_PORT="6722"
#COMMAND="/usr/bin/ssh -f -N -R $REMOTE_PORT:127.0.0.1:22 -L 6622:127.0.0.1:6622 unixsmod@earth ssh -R 0.0.0.0:$REMOTE_PORT:127.0.0.1:9922 -L 6622:127.0.0.1:443 -p 443 [email protected]"
#COMMAND="/usr/bin/ssh -R 9922:127.0.0.1:22 -L 6622:127.0.0.1:6622 unixsmod@earth ssh -N -R 0.0.0.0:9922:127.0.0.1:9922 -L 6622:127.0.0.1:443 -p 443 [email protected]"

COMMAND1="/usr/bin/ssh -f -N -L $LOCAL_PORT:xx.espai.de:23 unixsmod@earth"
COMMAND2="/usr/bin/ssh -f -N -R 0.0.0.0:$REMOTE_PORT:127.0.0.1:22 -p $LOCAL_PORT esrin@localhost"

LOGFILE="/home/logica/checksshbackup.log"
DATE=$(date +'%Y-%m-%d %H:%M:%S')


#disable next line?:
#echo "$DATE - Started" >> $LOGFILE


# 2 tests to check if the tunnel is working:

# 1st Check the 2 processes are running
#if [ $(ps ax | grep "$COMMAND" | grep -vc grep) -lt 1 ]

if ! ps ax | grep -v grep | grep "$COMMAND1" > /dev/null 2>&1
then
    echo "$DATE - Command1 not in ps" >> $LOGFILE
    $COMMAND1
fi

if ! ps ax | grep -v grep | grep "$COMMAND2" > /dev/null 2>&1
then
    echo "$DATE - Command2 not in ps" >> $LOGFILE
    $COMMAND2
fi


# 2nd Test tunnel

ssh -p $LOCAL_PORT esrin@localhost netstat -an | egrep "tcp.*:$REMOTE_PORT.*LISTEN" > /dev/null 2>&1
if [ $? -ne 0 ] ; then
   echo "$DATE - Not in netstat" >> $LOGFILE
   pkill -f -x '$COMMAND1'
   pkill -f -x '$COMMAND2'

   $COMMAND1
   $COMMAND2
#else
#   echo "Ok"
fi

exit



Més info

Aqui hi ha una copia d'una part de la pàgina:

Funcions

Todos los servicios funcionan a través del puerto 22/tcp del sistema:

  • Shell: Tal y como dice el nombre Secure Shell remoto, vamos a probarlo: ssh vecino.
    • Ojo porque si esto lo ejecutamos desde una sesión telnet no sirve de nada la criptografía que lleva.
    • La primera vez que nos conectamos al host, se produce una autentifiación a nivel de host.
    • Podemos acceder al menú del ssh escribiendo: <intro>~?
  • X-Forward. ssh -X vecino@brutal (también necesitamos la opción X11Forwarding yes en el servidor).
  • Copia: scp vecino@brutal:/etc .
  • FTP Seguro: sftp brutal.xxx
  • Ejecución. ssh vecino@brutal ps axf
  • Tuneling. Hay de dos tipos:
    • local. ssh -L 3002:localhost:119 vecino@brutal
    • remoto. ssh -g -R 8000:localhost:80 vecino@brutal (ojo con la -g, que necesitamos GatewayPorts yes en la configuración del servidor.
  • VPN. En combinación con el demonio pppd, puede funcionar como VPN.

Autentificació

Host

  • El host se autentifica de la siguiente forma:
  1. Cliente -> Servidor. Inicia conexión TCP por el puerto 22.
  2. Servidor -> Cliente. El servidor le envía al cliente su clave pública RSA de host (almacenada en /etc/ssh/ssh_host_rsa_key.pub). Para que el cliente acepte esta clave, la primera vez te pregunta si te fias de la clave que te envía el servidor imprimiendo el fingerprint. Es recomendable llamar al administrador del servidor para que ejecute ssh-keygen -l -f /etc/ssh/ssh_host_rsa_key.pub y comparar a viva voz el fingerprint de la clave.
  3. Cliente -> Servidor. El cliente pide al servidor que demuestre que él posee la clave privada asociada a la pública que está enviando. Esto se llama desafío o challenge en inglés. En este caso, le envía un TEXTO aleatorio que pide que firme.
  4. Servidor -> Cliente. Le envía el TEXTO firmado con su clave privada y el cliente verifica la firma con la clave pública del servidor. A continuación se cede el paso y se encripta la comunicación.
  5. La comunicación a partir de este punto está cifrada con una clave simétrica de sesión aleatoria (ya que la criptografía simétrica es mucho más rápida). Ésta se envía de forma asimétrica con las claves negociadas.

Usuaris

A continuación viene la autentificación de usuario (ya con la comunicación encriptada). Se puede hacer con password via PAM. Y este es la forma estándar. Pero hay una manera más segura, mediante criptografía de clave pública.

  • Las contraseñas pueden tener varios problemas: largas y difíciles de recordar, se pueden interceptar en el servidor o en el cliente si tienen un troyano y hay problemas con cuentas compartidas... Para solucionar esto se utiliza criptografía:
  1. Cliente -> Servidor. El cliente le envía el nombre de usuario.
  2. Servidor -> Cliente. El servidor no se lo cree y le envía un desafío con un TEXTO aleatorio para que lo firme con su clave privada de usuario.
  3. Cliente -> Servidor. El cliente le envía el TEXTO firmado y el servidor lo comprueba con su clave pública. A continuación le deja pasar.

Esto tiene diversas ventajas con respecto a las contraseñas:

  • Dos componentes secretos. La clave privada del usuario y la contraseña que cifra simétricamente esta clave privada.
  • No se están transmitiendo la contraseña ni la clave.
  • Las claves no se pueden adivinar tan facilmente como las contraseñas...

La instalación son dos pasos:

  1. Como usuario, ejecutamos ssh-keygen -t dsa
  2. Copiamos la clave pública ~/.ssh/id_dsa.pub al fichero del servidor ~/.ssh/authorized_keys2. Podemos poner varias públicas (una por línea). El fichero no puede ser escribible por nadie excepto el propietario.

Agents SSH

  • Es un programa en ejecución que guarda la clave privada desencriptada en su espacio de memoria RAM. Sirve para que no se tenga que escribir un password cada vez se usa la clave privada:
  1. ssh-agent /bin/bash
  2. ssh-add

A continuación funcionan las conexiones a otras máquinas sin que pida password, la clave sin encriptar no se almacena en ningún lugar.