Blog | G5 Cyber Security

Git & RSA Keys: Security Risks

TL;DR

No, you should never commit an encrypted RSA key (or any private key) directly to a Git repository. Even if it’s encrypted, the history of the repository contains previous versions of the file, and encryption keys can be compromised. Use secure methods like SSH agents or dedicated secret management tools instead.

Why Committing Encrypted Keys is Dangerous

Git tracks changes to files over time. This means that even if you encrypt your RSA key now, older, potentially unencrypted versions might still exist in the repository’s history. Anyone with access to the Git history could recover those earlier versions.

Step-by-Step Guide: Secure Alternatives

  1. Don’t Store Keys Directly: The fundamental rule is to avoid storing private keys within your Git repository at all.
  2. Use SSH Agents: This is the most common and recommended approach for authenticating with remote repositories.
    • Generate an SSH key pair (if you don’t have one already):
      ssh-keygen -t rsa -b 4096 -C "your_email@example.com"
    • Add your private key to the SSH agent:
      ssh-add ~/.ssh/id_rsa
    • Configure Git to use the SSH protocol for authentication (usually automatic if you’ve set up SSH keys correctly). Check your remote URL in .git/config; it should start with git@... rather than https://....
  3. Use a Dedicated Secret Management Tool: For more complex scenarios, consider tools designed to manage secrets securely.
    • HashiCorp Vault: A popular option for storing and controlling access to sensitive data. Requires setup and configuration.
    • AWS Secrets Manager/Azure Key Vault/Google Cloud Secret Manager: If you’re using a cloud provider, these services offer integrated secret management solutions.
  4. If You Accidentally Committed a Key (Recovery Steps): This is a serious situation.
    • Rewrite Git History: Use git filter-branch or similar tools to remove the key from all commits and branches. Warning: Rewriting history can be complex and disruptive, especially if others are collaborating on the repository.
    git filter-branch --force --index-filter 'git rm --cached --ignore-unmatch path/to/your/keyfile' --prune-empty --tag-name-filter cat -- --all
  5. Force Push: After rewriting history, you’ll need to force push the changes to the remote repository.
    git push origin --force --all

    Warning: This will overwrite the remote repository’s history. Coordinate with your team before doing this!

  6. Rotate Keys: Immediately generate a new RSA key pair and revoke the compromised one.

Key Takeaways

Exit mobile version