Here's a safe and secure method of storing passwords, encrypted, for use in shell scripts. This is in bash,
but can easily be ported to other shells as the bulk of the work is handled by the openssl
and sshpass
apps.
- Install
openssl
andsshpass
:
sudo apt update && sudo apt install openssl sshpass -y
- Encrypt password:
echo 'password!here!' | openssl enc -aes-256-cbc -md sha512 -a -pbkdf2 -iter 100000 -salt -pass pass:'pick.your.password'
NOTE: The --pass pass:'pick.your.password'
is the password we will use to decrypt.
The result will be something like U2FsdGVkX19H1ZUfQvWYl4x4kPNPp8u0WPgNwZKYIS0=
. This is the AES-256 encrypted password.
- Decrypt password:
echo U2FsdGVkX19H1ZUfQvWYl4x4kPNPp8u0WPgNwZKYIS0= | openssl enc -aes-256-cbc -md sha512 -a -d -pbkdf2 -iter 100000 -salt -pass pass:'pick.your.password'
- Store encrypted password in a dotfile:
echo 'password!here!' | openssl enc -aes-256-cbc -md sha512 -a -pbkdf2 -iter 100000 -salt -pass pass:'pick.your.password' > .credentials
- Decrypt stored password:
cat .credentials | openssl enc -aes-256-cbc -md sha512 -a -d -pbkdf2 -iter 100000 -salt -pass pass:'pick.your.password'
- Control permissions so no one else can view or edit the contents of
.credentials
:
chmod 600 .credentials
NOTE: This will make it so the current user is the only one who can view the hash inside the .credentials file.
- Using this method from a script:
#!/bin/bash
REMOTE_USER=youruser
REMOTE_PASSWD=$(cat .credentials | openssl enc -aes-256-cbc -md sha512 -a -d -pbkdf2 -iter 100000 -salt -pass pass:'pick.your.password')
REMOTE_LINUX=yourdomain.com
# connect to the remote computer and put a timestamp in a file called sshscript.log
sshpass -p $REMOTE_PASSWD ssh -T $REMOTE_USER@$REMOTE_LINUX << _remote_commands
echo $USER "-" $(date) >> /home/$REMOTE_USER/script.log
_remote_commands