SamatsWiki

Mozilla has an excellent list of security guidelines for OpenSSH.

Copy an SSH public key to a remote machine

This:

   1 cat ~/.ssh/id_rsa.pub | ssh remoteuser@remotehost 'mkdir .ssh ; shat >> .ssh/authorized_keys'

will copy a public key to a remote machine, but most likely you want to use ssh-copy-id included with recent versions of OpenSSH.

Protect sshd from kernel OOM events

The kernel out-of-memory killer kills processes when a system runs out of RAM. Killing SSH typically does not help fix anything, and makes remotely-accessible systems inaccessible.

   1 for pid in $(pidof sshd) ; do
   2         echo "disabling oom on pid $pid"
   3   echo -17 | sudo tee /proc/$pid/oom_adj > /dev/null
   4 done

This is done by a few distributions, but when working on an arbitrary remote machine may be useful to run just in case.

Generate new SSH host key

Make sure /etc/ssh/sshd_config contains a path to the host key, e.g.:

HostKey /etc/ssh/ssh_host_ed25519_key

Once it's there, create a new host key with:

sudo ssh-keygen -t ed25519 -f /etc/ssh/ssh_host_ed25519_key

Backups and transferring stuff over SSH

Using tar to transfer over SSH:

tar czhf - $SRC_DIR | \
  ssh $SSH_USER@$SSH_HOST \
    "tar xzhf - -C $DST_DIR"

or doing so in two commands:

# Backup
ssh root@$SSH_HOST "tar cpf - / --exclude=/sys --exclude=/proc --exclude=/dev" | pv | gzip | cat > backup.tar.gz

# Restore
cat backup.tar.gz | ssh root@$SSH_HOST "pv | tar zxvf - -C /"

Cloning a disk with dd over SSH:

ssh -C $USER@$REMOTE_HOST "dd if=/dev/sda" | dd of=/dev/sda

SSH tunnels

   1 # $LOCAL_IP: 'localhost' or machine from local network
   2 # $LOCAL_PORT: open port on local machine
   3 # $REMOTE_IP: remote localhost or IP from remote network
   4 # $REMOTE_PORT: open port on remote site
   5 
   6 # Forward Tunnel: map port from remote machine/network on local machine
   7 ssh -L $LOCAL_PORT:$REMOTE_IP:$REMOTE_PORT $USER@$SERVER
   8 
   9 # Reverse Tunnel: make local port accesible to remote machine
  10 ssh -R $REMOTE_PORT:$LOCAL_IP:$LOCAL_PORT $USER@$SERVER

Interesting reading


CategoryCheatSheet

SamatsWiki: CheatSheet/SSH (last edited 2018-07-22 11:54:14 by SamatJain)