git,

How to remove already committed secrets from Git repositories

Mar 11, 2022 · 1 min read · Post a comment

One of the most common secure practices in Git is to never commit any secrets in Git repos. But, what happen if you did, or someone else made that rookie mistake?! Let’s see how to remove them if they are already committed in Git.

Prerequisites

  • Git

Solution

We are going to use BFG, an alternative to git-filter-branch tool written in Scala for removing any bad data out of your Git repository.

Step 1. Install BFG. If you are using macOS, run:

brew install bfg

If you are using Windows, simply download the JAR file from the official site: https://rtyley.github.io/bfg-repo-cleaner/

Step 2. Navigate to your repo directory.

cd <your_repo_dir>/

Step 3. Save all of your plaintext passwords from the Git repo in a file. Let’s call it passwords.txt.

Step 4. Clean up the passwords committed.

bfg --replace-text passwords.txt

If you are using the JAR file, run:

java -jar bfg.jar --replace-text passwords.txt

or even better, if you decide to delete the file(s) with the sensitive data, run:

bfg --delete-files <file_with_sensitive_data>

Step 5. Last but not least:

git reflog expire --expire=now --all && git gc --prune=now --aggressive
git push

Conclusion

I’m pretty sure there a lot of alternative scanning Git repos for leaks tools out there, which usually are implemented as a CI pipeline step as part of the DevSecOps best practices. To find more neat Git commands and hacks, browse the Git category. On a side note, follow our official channel on Telegram.