Skip to content

Add time gated SSH key script #32

Description

@ulises-c

SSH Agent Passphrase Cooldown

Setup so the SSH key passphrase is asked once per login, then cached
until logout/reconnect or 4 hours pass, whichever comes first.

Machine: Ubuntu, accessed via tty/SSH login. Login shell: bash (reads ~/.profile).

Key

  • ~/.ssh/<key> — ED25519, passphrase-protected (public half: <key>.pub)

What was changed

1. ~/.ssh/config

Auto-load the key on first git/ssh use and cap its in-agent lifetime at 4h:

Example

Host github.com
  AddKeysToAgent 4h
  IdentityFile /home/ulises/.ssh/github

(Changed from AddKeysToAgent yes. ssh -G github.com confirms addkeystoagent 14400.)

2. ~/.profile

Start a per-login ssh-agent with a 4h default key lifetime, and kill it on logout:

# ssh-agent scoped to this login session; keys expire after 4h.
# First git/ssh use prompts for the passphrase, then it is cached until
# the agent dies (logout/reconnect) or 4 hours pass, whichever comes first.
if [ -z "$SSH_AUTH_SOCK" ]; then
    eval "$(ssh-agent -s -t 4h)" >/dev/null
    trap 'ssh-agent -k >/dev/null 2>&1' EXIT
fi

Resulting behavior

  • New SSH/console login → fresh agent, no key loaded.
  • First git pull/push to → prompted for passphrase once; key loads into agent.
  • Next 4 hours, same session → no prompts.
  • After 4h, or on logout/reconnect → key dropped, prompted again. Whichever comes first wins.

Why two layers

  • Per-login agent (dies on logout) handles the reconnect condition.
  • -t 4h on the agent + AddKeysToAgent 4h in config handle the time condition.

Activate in the current session without re-login

eval "$(ssh-agent -s -t 4h)"

The next git command then prompts and caches for 4h. New logins do this automatically.

Useful commands

ssh-add -l        # list keys currently held by the agent
ssh-add -D        # forget all keys now (force re-prompt)
ssh-agent -k      # kill the current agent

Notes

  • One agent per login connection. Several simultaneous SSH sessions each get their
    own agent (each prompts once). To share one cache across them, use tmux (panes
    inherit the first session's agent) or switch to a fixed-socket agent setup.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions