What is SSH Agent?

  • SSH agent is a daemon for SSH that keeps track of identity keys and their passphrases in memory (not on disk). Which improves security and convenience.
  • When an SSH key with a passphrase is used, the agent prompts for the passphrase only once per login session, and then handles authentication for future connections automatically.
  • The agent only allows the stored keys to sign authentication messages, never allowing the private key material to be extracted.

Main Uses

  • Single Sign-On (SSO): Enter the password once per login session, then use SSH seamlessly across multiple terminals and program without needing to authenticate.
  • Agent Forwarding: Allows remote SSH sessions to use your local agent, making it possible to authenticate to further hosts without needing to copying the private keys around.
  • Key Management: Easily add, remove, and list keys managed by the agent, improving operational security and ease of use. Example: ssh-add

Usage (Manual)

To use ssh-agent in Linux, start the agent, add your private key, and optionally configure it for automatic use and forwarding.

  1. Start ssh-agent:
    eval "$(ssh-agent -s)"
    
  2. Add SSH key to agent:
    ssh-add ~/.ssh/id_rsa
    
    #example output from my device
    Enter passphrase for <sensitive-info>.ssh/id_rsa: 
    Identity added: <sensitive-info>.ssh/id_rsa (email@email.com)
    
  3. Verify added keys:
    ssh-add -l
    
    #example output from my device
    4096 SHA256:<asdasdasdasdasdasdasdasdasdasdasdasdasdasdas> email@email.com (RSA)
    

Automatic Start Using Systemd Units

  1. Create ssh-agent.service:
  • Location: .config/systemd/user/ssh-agent.service

  • Ownership: sudo chmod $USER:$USER .config/systemd/user/ssh-agent.service

  • Permission: sudo chmod 644 .config/systemd/user/ssh-agent.service

    [Unit]
    Description=SSH Key Agent For All Users
    After=network.target
    
    [Service]
    Type=simple
    Environment=SSH_AUTH_SOCK=%t/ssh-agent.socket
    ExecStart=/usr/bin/ssh-agent -D -a $SSH_AUTH_SOCK
    ExecStop=/usr/bin/pkill -u $USER ssh-agent
    
    [Install]
    WantedBy=default.target
    
  1. Add Environment Variable $SSH_AUTH_SOCK in .bashrc:
    #ssh-agent environment variable for user systemd
    export SSH_AUTH_SOCK="$XDG_RUNTIME_DIR/ssh-agent.socket"
    
  2. Start the service:
    sudo systemctl daemon-reload
    
    sudo systemctl --user enable --now ssh-agent
    sudo systemctl --user start ssh-agent
    sudo systemctl --user status ssh-agent