Configure SSH Agent Forwarding in Ubuntu

This guide explains how to configure your Ubuntu Linux SSH client to automatically forward your local SSH agent to remote servers. By enabling SSH agent forwarding, you can securely use your local SSH keys on remote hosts to authenticate further connections (such as accessing private Git repositories or hopping to other servers) without copying your private keys to the remote machines.


Step 1: Ensure Your SSH Agent is Running and Keys are Added

Before configuring forwarding, your local SSH agent must be active and holding your SSH keys.

  1. Open your terminal on Ubuntu.

  2. Verify the SSH agent is running and load your SSH keys by running:

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

    (Replace ~/.ssh/id_rsa with the path to your specific private key if it differs).

Step 2: Configure SSH Agent Forwarding

You can configure agent forwarding temporarily for a single session, or permanently for specific hosts or all hosts.

To automatically forward the agent without typing extra commands every time, edit your local SSH configuration file.

  1. Open or create your user-specific SSH configuration file using a text editor:

    nano ~/.ssh/config
  2. To enable forwarding for all remote hosts, add the following block:

    Host *
        ForwardAgent yes
  3. To enable forwarding only for a specific remote host (more secure), add its details like this:

    Host target-server-alias
        HostName server.example.com
        User ubuntu
        ForwardAgent yes
  4. Save the file and exit the editor (in nano, press Ctrl+O, Enter, then Ctrl+X).

  5. Secure the configuration file permissions:

    chmod 600 ~/.ssh/config

Option B: Temporary Forwarding via Command Line

If you only want to forward your agent for a single session, use the -A flag when connecting:

ssh -A user@remote-host

Step 3: Verify the Configuration

To confirm that the SSH agent has been successfully forwarded to the remote host:

  1. Connect to your remote server:

    ssh user@remote-host
  2. Once logged into the remote machine, check if the SSH authentication socket environment variable is present:

    echo $SSH_AUTH_SOCK

    If configured correctly, this command will output a path to a socket file (e.g., /tmp/ssh-XXXXXX/agent.XXXX).

  3. Test if your forwarded keys are accessible by running:

    ssh-add -l

    This should list the fingerprints of the keys loaded on your local machine.