How can I avoid putting the database password in a perl script?

The standard way is to put the credentials into a config file, and attempt to protect the config file from being more readable than the perl file. This offers a moderate increase in security; for example, the code may be in source control and accessible to developers, the config file wouldn't be. The code needs to be in the web server's cgi root, and possibly downloadable under certain misconfigurations, and the config file needn't be.

The ambitious way is to reversibly encrypt the credentials and put them into a config file. Of course, anything reversibly encrypted can be decrypted. The BladeLogic application did this, and it was trivial (<1 day) for me to de-compile their Java enough to find out the function to decrypt credentials and use it to decrypt them to my satisfaction. Not a mark against them; that's just the name of the reversibly encrypted game.

Another option is to use OS-based authorization in concert with strictly limited database restrictions. For example, limit the database client user's access to a set of stored procedures to limit the potential for abuse, and allow that user to access the database without a password. This doesn't work if you're doing client-server over the network, which limits how often it's useful. Also, people tend to look more askance at "passwordless" OS-user access than they do at writing the password down willy-nilly. It is not completely logical, but there are standards that say all database users must have passwords, so that's that.


I often pass the password to the script in an environment variable that way the script need not have access to the secure location that contains the password.

PASSWORD=`cat passwd_file`  perl_script.pl

then the script reads the password

my $password = $ENV{'PASSWORD'}

bonus points if the perl script drops privileges


As others have already said, put the credentials in a separate file which the script will load. Risks of having the password in the script include its being exposed to shoulder surfing, its being committed in revision control systems or configuration management systems and distributed far beyond what it should be, accidentally copying to another location when reusing part of the code, etc.

The credentials file should have the minimum permissions necessary. It should possibly not be included or treated differently by configuration management systems.

If available, look into using an operating system feature that limits the access to the credential file further than permissions. For example, AppArmor or SELinux under Linux can restrict the access to the credential file to the one script that needs it. This only protects against an attacker who cannot take control of the legitimate script, so make sure the legitimate script is not owned by the user who runs it (this is a general recommendation: don't have executable programs owned by the user that runs them).