Setting up SSH forwarding

SSH forwarding can improve your security along with reducing the need to type passwords and have multiple keys linked to your GitHub/GitLab instance. The procedure is:

Key setup

Set up a key on your local machine with a passphrase. You’ll not have to type it often, so this is worth while. Suggested way to create a new key:

ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

This creates a key with the RSA algorithm, and puts your username in as a comment. The default path is fine if you only have one key, and enter a passphrase when prompted.

SSH Agent and Keychain

Add your key to your computer keychain. ssh-add will cause it to be loaded until you log out.

Linux/Windows

eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_rsa

macOS

eval "$(ssh-agent -s)"
ssh-add -K ~/.ssh/id_rsa

If you are on a recent Mac, you might need to add the following to your ~/.ssh/config file: (also see GitHub SSH forward)

Host *
  AddKeysToAgent yes
  UseKeychain yes
  IdentityFile ~/.ssh/id_rsa

Forward agent

When you connect, use -A or add a ForwardAgent line to ~/.ssh/config. This works for proxies also. For example:

# Modern method (OpenSSH 7.3, released August 2016, also with -J)
Host myhost
  ForwardAgent yes
  Hostname example.com
  User me
  ProxyJump me@proxy.com:22 # user and port are optional

# Classic method
Host myhost
  ForwardAgent yes
  Hostname example.com
  User me
  ProxyCommand ssh -q -x me@proxy.com -W %h:22

Note that the classic method is less secure; if the machine in the middle is compromised, a malicious user on that machine could authenticate as you while you are connected. Read more about the new method with Madboa: Using ProxyJump with SSH and SCP, Gentoo: SSH jump host, or in the OpenSSH CookBook: Proxies and Jump Hosts

Quick tip: You can type ~C after a newline to add ports to forward after making an ssh connection - see ~? or this site for info.

Copy IDs

This depends on what you want to connect to.

Remote hosts

Copy your id to the remote hosts if you want to connect using your key:

ssh-copy-id myhost

If you ever need to force a password login, you can use:

ssh -o PreferredAuthentications=password -o PubkeyAuthentication=no myhost

GitHub

Add your new public key to GitHub/GitLab/etc. through your profile and/or settings.

Docker

If you use docker, you’ll want to forward your key to the container, as well. Something like this:

docker run --volume $SSH_AUTH_SOCK:/${SSH_AUTH_SOCK} --env SSH_AUTH_SOCK="${SSH_AUTH_SOCK}" ubuntu ssh-add -l

See Docker SSH forward, and note there are problems with macOS.

ssh