Herramientas de usuario

Herramientas del sitio


wiki2:ssh

SSH and similars

SSH use

Conectar con un .pem

ssh -i keyhindoor.pem ubuntu@54.217.224.44

SFTP

sftp -o IdentityFile=keyhindoor.pem ubuntu@54.217.224.44

SCP

Para hacer copia de ficheros: scp [[user@]from-host:]source-file [[user@]to-host:][destination-file]

Para hacerla con un pem: scp -i mykey.pem somefile.txt root@ec2-184-73-72-150.compute-1.amazonaws.com:/

Fichero de configuración

Configurar el host, en ~/.ssh/config:

     Host live_frontend
     HostName aws.amazon.255-255-255-255.dns.stupidlylong.domain.amazon.com
     User ubuntu
     IdentityFile ~/.ssh/aws-eu-april2012.pem

Luego: ssh live_frontend

Para montar directorio: sshfs live_frontend:/home/ubuntu /home/alfred/tmp/test/

Clave pem

Crear clave pem

Enter this command to generate 2,048 bit RSA key using verbose (questions asked during) mode, and a public .pem X.509 certificate:

$ ssh-keygen -t rsa -b 2048 -v

Generating public/private rsa key pair.
Enter file in which to save the key (/home/anonymouse/.ssh/id_rsa): hetzner
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in hetzner.
Your public key has been saved in hetzner.pub.
The key fingerprint is:
bb:c6:9c:ee:6b:c0:67:58:b2:bb:4b:44:72:d3:cc:a5 localhost@localhost
The key's randomart image is:

Duplicate the file hetzner with the name hetzner.pem. Change its permisons: chmod 600 hetzner.pem. Another (better) option is….

ssh-keygen -f hetzner -e -m pem > hetzner.pem
Otra opción (pedirá passphrase):
openssl rsa -in ./key -outform pem > key.pem

Upload and allow access to that key

$ ssh-copy-id -i ~/hetzner.pub root@12.34.56.78

Grant access to another .pem key

… In the current system:

ssh-keygen -f YOURKEY.pem -y >> ~/.ssh/authorized_keys

Revoke user keys

Just remove <user home>/.ssh/authorized_keys file.

Configure to reject password login

To disable this setting, you can do the following: $ sudo nano /etc/ssh/sshd_config

ChallengeResponseAuthentication no
PasswordAuthentication no
UsePAM no

And: $ service ssh restart

Old method to create a key

cd .ssh/

Generate the file id_dsa from which we will create the PEM file:

ssh-keygen -t dsa -b 2048

Generate the private key PEM file:

openssl dsa -in id_dsa -outform pem > pk_dsa.pem

Generate the public key PEM file for distribution to the users:

openssl dsa -in pk_dsa.pem -pubout -out pub_dsa.pem

The final pub_dsa.pem is the file you're looking for.

Usuario con home encriptado

⚠️ Si intentas acceder con un usuario que tiene el home encriptado mediante clave privada no vas a poder, ya que la clave estará guardada en el directorio home del usuario. Has de cambiar la ubicación de la clave. Para ello, crea un directorio /home/.ssh y allí pon tu clave (estará en tu directorio home, ruta .ssh/authorized_keys).

Ahora has de cambiar la config de ssh editando /etc/ssh/sshd_config. Añade la siguiente línea:

AuthorizedKeysFile /home/.ssh/%u

También será importante tener esta línea:

UsePAM yes

Añade un fichero .profile a /home/alfred no encriptado con el siguiente contenido:

/usr/bin/ecryptfs-mount-private
cd
source .profile

De esta forma te pedirá el password para desencriptar el directorio home, pero podrás acceder a él. Si no lo haces, piensa que tu clave está encriptada, se ha de tener una sesión abierta incluso para poder montarlo.

Opción alternativa

# Make your public key accessible
mkdir -m 700 /home/.ecryptfs/$USER/.ssh
echo $YOUR_PUBLIC_KEY > /home/.ecryptfs/$USER/.ssh/authorized_keys
ln -s /home/.ecryptfs/$USER/.ssh/authorized_keys ~/.ssh/authorized_keys
ecryptfs-umount-private
chmod 700 $HOME
mkdir -m 700 ~/.ssh
ln -s /home/.ecryptfs/$USER/.ssh/authorized_keys ~/.ssh/authorized_keys

# Make it auto-mount with first login.
# Note: it can cause problems with automated login.
echo /usr/bin/ecryptfs-mount-private > ~/.profile
echo cd >> ~/.profile
echo source .profile >> ~/.profile
ecryptfs-mount-private

SSH Tunel

ssh -L puerto_local:ip_enlace:puerto_servidor servidor

Es decir, si queremos conectar al servidor local en webapps desde el puerto 5432 haremos

ssh -L 5432:127.0.0.1:5432 webapps

O enlazar el puerto 5433 localmente al puerto 5432 del servidor 182.198.5.5 que tiene un usuario denominado exploit:

ssh -L 5433:127.0.0.1:5432 exploit@182.198.5.5

Several ports:

ssh -L 5433:127.0.0.1:5432 -L 5432:127.0.0.1:5432 exploit@182.198.5.5

He visto cosas como ssh -L *:127.0.0.1:* host. No sé si funcionaría.

Tunel reverso

ssh -R interface_remota:puerto_remoto:interface_local:puerto_local user@host

ssh -R "0.0.0.0:81:0.0.0.0:8000" webapps

Este ejemplo sirve el puerto 81 de la interface 0.0.0.0 en webapps, redirigido a la interface local 0.0.0.0:8000. Es decir, cualquier petición que llegue por la 81 a webapps será mapeada al puerto local 8000 donde una app puede estar escuchando. Se puede escribir así también: ssh -R 81:0.0.0.0:8000 webapps (tengo dudas de si el 0.0.0.0 es necesario).

📌 Para que pueda funcionar directamente necesitarás cambiar la configuración por defecto de /etc/sshd_config, concretamente el valor:

    GatewayPorts no

Ha de cambiarse por:

    GatewayPorts yes

Si esto no estuvise configurado en el servidor remoto entonces no podrás acceder desde fuera a ese puerto, solo desde local. Si quieres realizar el puente entonces necesitarás un programa que sirva por un puerto externo y lo redirija al local. socat por ejemplo, en el siguiente comando se redirije todo lo del puerto 80 al 5000:

 socat TCP-LISTEN:80,fork TCP:127.0.0.1:5000

Proxy

For example, let’s say the database server at your office is located at 192.168.1.111 on the office network. You have access to the office’s SSH server at ssh.youroffice.com , and your user account on the SSH server is bob . In that case, your command would look like this:

ssh -L 8888:192.168.1.111:1234 bob@ssh.youroffice.com

After running that command, you’d be able to access the database server at port 8888 at localhost (127.0.0.1).

Another example is a postgres docker container running on 5432 of the 172.18.0.2 (thanks to docker inspect postgres, property IPAddress). You access to the ssh server webapps with this that also allows you to connect to that container on localhost:

ssh -L 5432:172.18.0.2:5432 webapps
You can do this using ssh
$ ssh -L 80:remotehost:80 user@myserver
You will have a tunnel from your local port 80 to the remotehost port 80 then. This does not have to be 
the same as myserver. To make that transparent you should add an entry to the hosts file. If you don't 
do that vhosts will not work. If you want a SOCKS-proxy connection you could also use

$ ssh -D 5000 user@myserver
This will create a SOCKS-proxy on localhost port 5000 which routes all requests through myserver.

ssh -D 4000 user@example.com
The SSH client creates a SOCKS proxy at port 4000 on your local computer. Any traffic sent to this port is sent to its destination through the SSH server.

Old

For example, if you ssh'ed into the remote machine using

ssh hal@remote.machine.com -i ~/.ssh/hal.key

Then you could set up the port forwarding like this:

ssh -L 54321:127.0.0.1:3306 hal@remote.machine.com -i ~/.ssh/hal.key -f -N -M -S ~/.ssh/tunnel_54321_remote_machine_mysql

Then you can connect to the database as if you were connecting to the database locally (using the commanline mysql client as example):

mysql -h 127.0.0.1 -P 54321 -u my_user -p my_database

This should then prompt for your password.

To close the tunnel:

ssh -S ~/.ssh/tunnel_54321_remote_machine_mysql hal@remote.machine.com -i ~/.ssh/hal.key

Tunnels, port mapping table

Command Meaning
ssh -L 8000:127.0.0.1:8000 dev You are mapping the port 8000 from the dev host to localhost, port 8000. Now you can connect to localhost:8000 and dev:8000 will respond.
ssh -L 8000:127.0.0.1:8000 -L 5432:127.0.0.1:5432 dev You are mapping the port 8000 and 5432 from the dev host to localhost, both on the same portport 8000. As previous but two.
ssh -R 8000:127.0.0.1:8000 shappsrv You are mapping the port 8000 from localhost to the shappsrv host. When a request arrives to shappsrv:8000 it will be redirected to localhost:8000.
ssh -D 1337 -q -C -N webapps You are creating a SOCKS5 proxy in local host to webapps, port 1337. It will make any connection done to this port to outside as it was from webapps.

Parameters:

  • -q Quiet mode. No errors or warnings will be shown.
  • -C Compress communication.
  • -N Do not execute a command.

How To...

Generar un par de keys:

ssh-keygen -t rsa -b 4096 -C "alfred@electronicstars.com"

Listar identidades registradas:

ssh-add -l
ssh-add -L

Añadir una identidad (key generada que no es .pub) a tu sistema:

ssh-add cringer2

Eliminar una identidad (desde la key generada no .pub):

$ ssh-add -d cringer.key

Forwarding X11

To forward the X11 session from a server you need to connect to it using the -X parameter. To ensure it went well use -v -X so you can check it. Once connected to the server you will see the GUI of thoso executables you launched in the server which provide one.

A /etc/ssh/sshd_config server file configured for that is:

# Package generated configuration file
# See the sshd_config(5) manpage for details

# What ports, IPs and protocols we listen for
Port 22
# Use these options to restrict which interfaces/protocols sshd will bind to
#ListenAddress ::
#ListenAddress 0.0.0.0
Protocol 2
# HostKeys for protocol version 2
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key
#Privilege Separation is turned on for security
UsePrivilegeSeparation yes

# Lifetime and size of ephemeral version 1 server key
KeyRegenerationInterval 3600
ServerKeyBits 1024

# Logging
SyslogFacility AUTH
LogLevel INFO

# Authentication:
LoginGraceTime 120
PermitRootLogin yes
StrictModes yes

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

# Don't read the user's ~/.rhosts and ~/.shosts files
IgnoreRhosts yes
# For this to work you will also need host keys in /etc/ssh_known_hosts
RhostsRSAAuthentication no
# similar for protocol version 2
HostbasedAuthentication no
# Uncomment if you don't trust ~/.ssh/known_hosts for RhostsRSAAuthentication
#IgnoreUserKnownHosts yes

# To enable empty passwords, change to yes (NOT RECOMMENDED)
PermitEmptyPasswords no

# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
ChallengeResponseAuthentication no

# Change to no to disable tunnelled clear text passwords
#PasswordAuthentication yes

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

# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes

X11Forwarding yes
X11DisplayOffset 10
X11UseLocalhost no

PrintMotd no
PrintLastLog yes
TCPKeepAlive yes
#UseLogin no

#MaxStartups 10:30:60
#Banner /etc/issue.net

# Allow client to pass locale environment variables
AcceptEnv LANG LC_*

Subsystem sftp /usr/lib/openssh/sftp-server

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

Theoretically you only need to have:

X11Forwarding yes
X11UseLocalhost no

So you can do something similar to: ssh -X root@127.0.0.1 and launch firefox.

The xauth program must be installed on the server side. If there are any X11 programs there, it's very likely that xauth will be there.

A package with utils for the X11 server is: x11-xserver-utils

Activar login de root

You need to edit /etc/ssh/sshd_config, and commend out the following line: PermitRootLogin without-password. Just below it, add the following line: PermitRootLogin yes. Then restart SSH: service ssh restart

Jump between serveral hosts

Use the -J parameter.

In the next example it makes a jump between two hosts (wiki.sir.gtd and 10.1.80.101) to arrive to 10.1.80.111, also makes two port bridges between this 10.1.80.111 and the local machine: 6379 and 27017.

ssh -J gtdsir@wiki.sir.gtd,root@10.1.80.101 -L 6379:127.0.0.1:6379 -L 27017:127.0.0.1:27017 root@10.1.80.111

Create port mapping from config

  Host <hostname>
     HostName <Hostname IP>
     User <User>
     IdentityFile <Identity File Path>
     LocalForward 127.0.0.1:8000 127.0.0.1:8000
     LocalForward 127.0.0.1:7000 127.0.0.1:7000

The LocalForwards are key in setting up any tunnels I need working locally - you can tunnel as many ports as you need.

Problems

  • You can detect them running tail -f /var/log/auth.log

Unable to negotiate a key

If there was something like this: Jun 10 03:23:52 wikis sshd[4773]: fatal: Unable to negotiate a key exchange method [preauth] I recommend to add to /etc/ssh/sshd_config:

Ciphers aes128-ctr,aes192-ctr,aes256-ctr,aes128-gcm@openssh.com,aes256-gcm@openssh.com,chacha20-poly1305@openssh.com,blowfish-cbc,aes128-cbc,3des-cbc,cast128-cbc,arcfour,aes192-cbc,aes256-cbc

KexAlgorithms=curve25519-sha256@libssh.org,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1

The client loses connection after a while

In the server, in the /etc/ssh/sshd_config file, add:

ClientAliveInterval 30
ClientAliveCountMax 5

You will need to restart the service: service ssh restart.

Error Could not open a connection to your authentication agent

eval "$(ssh-agent -s)"
eval `ssh-agent -s`
wiki2/ssh.txt · Última modificación: 2022/05/25 07:38 (editor externo)