What is the least insecure way to store a password that is used by a script?

Solution 1:

Instead of hardcoding the password in the file, store the password in a separate file and protect the file (chmod 700 or chmod 500) so that only the authorised users can access it.

Retrieve the password with cat /dir/to/file/with/.password instead of reading the file and storing the content of it into a variable.

Solution 2:

What kind of service? Certain services have other methods to authenticate, e.g. SSH keys for SSH in conjunction with SSH agent.

I'd store the password separate from the script, and make sure that all path components have the correct permissions set. E.g., make sure that in the path /path/to/file, /, /path and /path/to are owned by a user you trust (root) and that these are not writable by someone who is not allowed to see your files. Finally, the recommended permissions for file is 600 or 400.

That file could look like this:

PASSWORD='something that you cannot remember'

In your script, use the below code to import the variable:

. /path/to/file

As for your script, make sure that it does not contain holes which may allow attackers to execute code in the script context (e.g. uncontrolled environment which may have an arbitrary $PATH variable set or invalid use of other files (e.g. sourcing a world-writable file).

As for the actual protection of your password, you can't. It must be available somehow to the other service. As an alternative, you can encrypt the file/ script containing the password using openssl or gpg so you need to enter a password before the credentials are unlocked. This is especially useful if your service's password is hard to remember.

Solution 3:

I know this is an old question but i faced this similar issue and i used Ubuntu's key ring to solve it. Here is a solution on ubuntu 18.04LTS Open the terminal Write down keyring set {{service}} {{username}} for example if you are using this for school password logging:

keyring set school mohamed

It will log you for a password enter the password. Now the password you entered is stored in Ubuntu keyring.

To get this password write in the terminal:

keyring get school mohamed

to use this in the context of an script:

password=$(keyring get school mohamed)

Now the password contatins the password you previously entered.