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

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.


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.