Secure Password storage for bash scripts on MacOS
Many times the reason to create a bash script is to automate and document a work flow. Most of my work flows need some kind of password or complex secret files.
I am sure it happed to you too — you checked in your code in a public git and just to find out that you made your secrets public to every one 🙈.
Some tools like docker provide their own secure registry but what about storing everything in a place you can simple search an access?
Simple Passwords
If the secure key is only a short text string, the only thing you need is:
security add-generic-password -a $USER -s name-of-the-note \
-w "PASSWORD"
when ever you need the password in your script you can access the passwort with:
mysql --user=user_name \
--password \
$(security find-generic-password -a $USER -s name-of-a-note -w)
and a modal dialog will ask to allow access:
Complex multiline password files
Sometimes you might have a file (e.g. htpasswd) with multiple passwords on multiple lines.
user1:a609316768619f154ef58db4d847b75e
user2:f522d1d715970073a6413474ca0e0f63
There is no problem to store this files but when you try to access it, you will get this output:
$ security find-generic-password -a $USER -C note \
-s name-of-the-note -w
75736572313a61363039333136373638363139663135346566353864623464383437623735650a75736572323a6635323264316437313539373030373361363431333437346361306530663633
It looks like garbage but it is only the hexadecimal representation of the original content. The easiest way to solve this is to use the tool `xxd`:
$ security find-generic-password -a $USER -C note \
-s name-of-the-note -w | xxd -r -p -
user1:a609316768619f154ef58db4d847b75e
user2:f522d1d715970073a6413474ca0e0f63
If you try to add the same key “name-of-the-note” a second time you will receive an error:
security: SecKeychainItemCreateFromContent (<default>): The specified item already exists in the keychain.
use the option to delete the key to solve this problem:
security delete-generic-password -a $USER \
-s name-of-the-note -w
if you need to add a file “passwords.txt” use this:
security add-generic-password -a $USER -s name-of-the-note -C note \
-w "$(cat passwords.txt)"
Never try to add the content of a file by manual creating a note and using copy & paste. The result is a RTF content with font info and other garbage.
Conclusion
The MacOS keychain is an easy solution with a graphical user interface to handle any kind of secret and allows to get a usability similar to normal applocations.
If you look for the manual or other solutions have a look at this links:
- man security
- pass — unix password manager
- 1Password CLI
- Lastpass CLI