CodyKochmann
2/10/2016 - 3:04 PM

ssh cheat sheet

ssh cheat sheet

Pipe a remote machine's localhost:5432 for postgres to your localhost:6432

    ssh -nNT -L 9000:localhost:5432 user@database-ip-address

You can then use psql -h localhost -p 6432 to connect to the database locally.


Pipe your local web server currently on localhost:7777 to a remote server's port 8001.

    ssh -nNT -R 8001:localhost:7777 user@server-ip-address

If you haven't already, add GatewayPorts yes to /etc/ssh/sshd_config and run sudo service ssh restart to allow remote hosts to access forwarded ports.


Use ssh to get around a firewall that doesn't allow access to facebook by piping to facebook.com:80 from your remote server to your localhost:9000

    ssh -nNT -L 9000:facebook.com:80  user@remote-server-ip

Then simply open http://localhost:9000 to get full, encrypted access to facebook.


Permissions

  • Home directory on the server should not be writable by others:
    • chmod go-w "/home/$USER"
  • SSH folder on the server needs 700 permissions:
    • chmod 700 "/home/$USER/.ssh"
  • Authorized_keys file needs 644 permissions:
    • chmod 644 "/home/$USER/.ssh/authorized_keys"
  • Make sure that user owns the ssh files and folders and not root:
    • chown $USER:$USER "/home/$USER/.ssh/authorized_keys" && chown $USER:$USER "/home/$USER/.ssh"
  • Put the generated public key (from ssh-keygen) in the user's authorized_keys file on the server
  • Make sure that user's home directory is set to what you expect it to be and that it contains the correct .ssh folder that you've been modifying. If not, use usermod -d "/home/$USER" user to fix the issue
  • Finally, restart ssh: service ssh restart
  • Then make sure client has the public key and private key files in the local user's .ssh folder and login: ssh user@host.com

If you would like to just use it in a single snippet, use fix-permissions.sh below:

#!/bin/bash
# corrects and secures the permissions for ssh
# by: Cody Kochmann

if [[ "$USER" == "root" ]]
then
  echo "This script is for non-root users."
else
  # ensuring everything exists
  mkdir -p "/home/$USER/.ssh"
  touch "/home/$USER/.ssh/authorized_keys"
  # make sure the user's home directory is actually owned by the user
  usermod -d "/home/$USER"
  # Home directory on the server should not be writable by others
  chmod go-w "/home/$USER"
  # .ssh folder on the server needs 700 permissions
  chmod 700 "/home/$USER/.ssh"
  # authorized_keys file needs 644 permissions
  chmod 644 "/home/$USER/.ssh/authorized_keys"
  # make sure that user owns the ssh files and folders and not root
  chown "$USER":"$USER" "/home/$USER/.ssh/authorized_keys"
  chown "$USER:$USER" "/home/$USER/.ssh"
  # restart ssh
  service ssh restart
fi