Understanding the Problem

Many teams configure their CI/CD pipelines to forward the local SSH agent when a job needs to access a remote Git server or a provisioned VM. The practice appears convenient: the runner inherits the developer’s private key, and the same key can be used across environments without copying secrets. However, the convenience masks a serious security flaw. Agent forwarding effectively hands the remote host the ability to use the forwarded key for any SSH connection, which means a compromised runner or a malicious job step can impersonate the developer on any system where the developer has access.

The threat model is simple:

  • A malicious contributor pushes a pull request that adds a step to the workflow.
  • The step runs on a shared runner that has ssh-agent -A enabled.
  • The attacker extracts the forwarded agent socket and uses it to authenticate to production servers.
  • Because the original private key never leaves the developer’s machine, the breach is hard to detect.

In addition, many CI platforms expose the agent socket as a file in the container’s filesystem, making it trivially accessible to any process with read permissions. Once an attacker has the socket, they can perform ssh-add -l to list keys and ssh -i to open new sessions.

Why Not to Use Agent Forwarding in CI/CD

The core reasons to avoid this pattern are:

  1. Privilege escalation: The forwarded key often has broad permissions, including access to production, staging, and internal Git repos.
  2. Lack of auditability: Actions performed with the forwarded key are attributed to the original user, obscuring the true origin of the operation.
  3. Persistence risk: If the runner is compromised, the attacker can retain the socket for the duration of the job, extending the attack window.
  4. Compliance conflict: Regulations that require key rotation and limited lifetimes are violated when a long‑lived developer key is reused across automated jobs.

The recommended approach is to replace agent forwarding with short‑lived, purpose‑built deploy keys that are generated per‑workflow, stored in a secret manager, and revoked automatically after the job finishes.

Generating a One‑Time Deploy Key

The following Bash function creates an RSA key pair, adds the public key to a remote Git server via its API, and returns the private key as a base64‑encoded string suitable for injection into a CI secret.

generate_deploy_key() {
  # Create a temporary key pair
  ssh-keygen -t rsa -b 4096 -N "" -f /tmp/deploy_key -q

  # Extract the public key
  PUB_KEY=$(cat /tmp/deploy_key.pub)

  # Call the Git server API to add the key (example uses GitHub)
  # Replace $REPO and $TOKEN with appropriate values
  curl -X POST -H "Authorization: token $TOKEN" \
    -d "{\"title\":\"CI Deploy Key $(date +%s)\",\"key\":\"$PUB_KEY\",\"read_only\":false}" \
    https://api.github.com/repos/$REPO/keys

  # Output the private key base64‑encoded
  base64 -w 0 /tmp/deploy_key
  # Clean up
  shred -u /tmp/deploy_key /tmp/deploy_key.pub
}

Store the resulting base64 string in a secret manager (e.g., GitHub Secrets, AWS Secrets Manager, or HashiCorp Vault). The secret will be consumed by the workflow and written to a temporary file that the runner uses for the SSH connection.

GitHub Actions Workflow Without Agent Forwarding

Below is a complete .github/workflows/deploy.yml that demonstrates the safe pattern. Notice the absence of ssh-agent -A. Instead, we decode the stored key, set appropriate file permissions, and use it directly with ssh and git.

name: Secure Deploy

on:
  push:
    branches: [ main ]

jobs:
  deploy:
    runs-on: ubuntu-latest
    env:
      DEPLOY_KEY_B64: ${{ secrets.DEPLOY_KEY_B64 }}
      REMOTE_HOST: ${{ secrets.REMOTE_HOST }}
      REMOTE_USER: ${{ secrets.REMOTE_USER }}

    steps:
      - name: Checkout repository
        uses: actions/checkout@v3

      - name: Install SSH client
        run: sudo apt-get update && sudo apt-get install -y openssh-client

      - name: Prepare temporary deploy key
        id: prep_key
        run: |
          echo "${DEPLOY_KEY_B64}" | base64 -d > /tmp/deploy_key
          chmod 600 /tmp/deploy_key

      - name: Add remote host to known_hosts
        run: |
          ssh-keyscan -H $REMOTE_HOST >> ~/.ssh/known_hosts

      - name: Test SSH connectivity
        run: |
          ssh -i /tmp/deploy_key $REMOTE_USER@$REMOTE_HOST "echo Connected"

      - name: Push built artifacts
        run: |
          # Example: copy a built binary to the remote host
          scp -i /tmp/deploy_key ./build/myapp $REMOTE_USER@$REMOTE_HOST:/opt/myapp/
          ssh -i /tmp/deploy_key $REMOTE_USER@$REMOTE_HOST "systemctl restart myapp"

      - name: Clean up temporary key
        if: always()
        run: shred -u /tmp/deploy_key

The workflow follows best‑practice steps:

  • Decode the secret only in a controlled step.
  • Set strict permissions (600) on the key file.
  • Add the remote host’s fingerprint to known_hosts to avoid man‑in‑the‑middle attacks.
  • Explicitly use the -i flag with each SSH command, preventing any accidental fallback to a forwarded agent.
  • Remove the private key immediately after use.

Automating Key Revocation

To keep the attack surface minimal, revoke the deploy key as soon as the job finishes. The following script can be called in a post‑job step:

revoke_deploy_key() {
  KEY_ID=$1   # The ID returned when the key was created
  curl -X DELETE -H "Authorization: token $TOKEN" \
    https://api.github.com/repos/$REPO/keys/$KEY_ID
}
# Example usage after deployment
revoke_deploy_key $NEW_KEY_ID

Capture NEW_KEY_ID from the API response when the key is created (modify generate_deploy_key to parse the JSON). By ensuring the key exists only for the duration of the pipeline, you eliminate persistence risk entirely.

Security and Best Practices

Never store raw private keys in the repository. Always keep them encrypted in a secret manager that supports audit logging.

Use RSA‑4096 or Ed25519 keys. Ed25519 offers smaller signatures and stronger security for the same key length.

Limit key permissions. When creating the deploy key, set it to read‑only if the workflow only needs to pull artifacts. For write operations, use a dedicated service account with the minimum required scopes.

Rotate keys regularly. A scheduled job (e.g., nightly) can generate a fresh key pair and replace the existing secret, ensuring that any leaked key becomes useless after a short window.

“Treat every automated SSH connection as if it were a privileged user session; if you would not grant a human that access, do not grant a script that access.”

Conclusion

SSH agent forwarding provides a tempting shortcut for CI/CD pipelines, but the hidden threat it introduces far outweighs the convenience. By generating short‑lived deploy keys, storing them securely, and revoking them immediately after use, you retain the operational benefits of SSH while eliminating the privilege‑escalation vector that