Using Passwords in Scripts

Problem

You need to hardcode a password in a script.

Solution

This is obviously a bad idea and should be avoided whenever possible. Unfortunately, sometimes it isn’t possible to avoid it.

The first way to try to avoid doing this is to see if you can use sudo with the NOPASSWD option to avoid having to hardcode a password anywhere. This obviously has its own risks, but is worth checking out. See Using sudo More Securely for more details.

Another alternative may be to use SSH with public keys and ideally restricted commands. See Using SSH Without a Password.

If there is no other way around it, about the best you can do is put the user ID and password in a separate file that is readable only by the user who needs it, then source that file when necessary (Using Configuration Files in a Script). Leave that file out of revision control, of course.

Discussion

Accessing data on remote machines in a secure manner is relatively easy using SSH (see Using SSH Without a Password and Getting Input from Another Machine). It may even be possible to use that SSH method to access other data on the same host, but it’s probably much more efficient to use sudo for that. But what about accessing data in a remote database, perhaps using some SQL command? There is not much you can do in that case.

Yes, you say, but what about crypt or the other password hashes? The problem is that the secure methods for storing passwords all involve using what’s known as a one-way hash. The password checks in, but it can’t check out. In other words, given the hash, there is theoretically no way to get the plain-text password back out. And that plain-text password is the point—we need it to access our database or whatever. So secure storage is out.

That leaves insecure storage, but the problem here is that it may actually be worse than plain text because it might give you a false sense of security. If it really makes you feel better, and you promise not to get a false sense of security, go ahead and use ROT13 or something to obfuscate the password. ROT13 only handles ASCII letters, so you could also use ROT47 to handle some punctuation as well.

$ ROT13=$(echo password | tr 'A-Za-z' 'N-ZA-Mn-za-m')

$ ROT47=$(echo password | tr '!-~' 'P-~!-O')

Warning

We really can’t stress enough that ROT13 or ROT47 are nothing more than “security by obscurity” and thus are not security at all. They are better than nothing, if and only if, you (or your management) do not get a false sense that you are “secure” when you are not. Just be aware of your risks. Having said that, the reality is, sometimes the benefit outweighs the risk.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.3.167