Git: Encrypt Credentials Within a Repository
This article explores the concept of encrypting credentials within a Git repository. It demonstrates a method using git smudge/clean filters but ultimately advises against it, advocating for the use of config servers instead.
Especially in the microservices era, you should use a config server and never store your credentials in a repository!
You should not use git smudge/clean filters for encryption. Why? Here’s an example!
Let’s create an example repository
% TMP=$(mktemp -d)
% cd $TMP
% git init
% echo 'Hello world!' > credentials
Add .gitattributes
/credentials filter=crypto
Add .git/config
[filter "crypto"]
smudge = openssl enc -aes-256-cbc -salt
clean = openssl enc -aes-256-cbc -salt
require
Note: require indicates that these commands need to exit with code 0, otherwise it could happen that these files are added without any encryption. You can test this by using smudge = gpg -d -q –batch –no-tty -r <SIGNATURE> and clean = gpg -ea -q –batch -no-tty -r <SIGNATURE> filters.
Add file to stage and commit
% git add .gitattributes credentials
% git add credentials
enter aes-256-cbc encryption password:
Verifying - enter aes-256-cbc encryption password:
% git status
Changes to be committed:
new file: .gitattributes
new file: credentials
% git commit -m "Inital commit" [master (Basis-Commit) 860cedc] Initial commit
2 files changed, 2 insertions(+)
create mode 100644 .gitattributes
create mode 100644 credentials
Note: The .git/config for filters will not be added to the commit!
Clone the example repository
% TMP2=$(mktemp -d)
% git clone $TMP .
% cat credentials
Salted__:.1٩H8[25%%
We now have an encrypted file in our repository. To decode it, we need the clean command. On the other hand, anyone can still commit this file and break the configuration.
Thoughts
- Yes, you can automate credential encoding or decoding with filters.
- But you could also encode or decode manually and check-in or -out. This does not make much of a difference!
- GitLab provides file locks. This probably makes sense as long as you use GitLab premium. Otherwise, you might use git commit hooks.
- If you want to use git repos to store credentials and have them fully encrypted you may have a look at Git Annex GCrypt. However, this is not based on git but its own project written in Haskell! It just uses the git format!
- You’re doomed if you store your production credentials in clear text so every developer can read them.
- Credentials should never be stored in repositories!
- Use config servers and tools like
consulfor creating configs or directly pull the configs from the servers!
So, why all these circumstances?! This can easily get messed up. This is just a badly designed “solution”. Therefore I would call it only a “workaround” and not a real solution!