I read recently about whether you should store your database passwords in config files, environment variables, docker secrets, etc. But if somebody can steal it from those places, then s/he can already inject code into your system, so they can easily use an existing database connection for example instead of looking for the database password. So why would a hacker bother with stealing your database password?
But if somebody can steal it from those places, then s/he can already inject code into your system
This premise is wrong. Especially for a config file, there are multiple ways the password could be stolen without the attacker having the ability to modify code. Some examples:
- From old backups of the source code.
- Accidental check in of the config file into a public repo (as per Matthews comment)
- Any situation where the attacker can read but not write to files.
For environment variables and docker secrets, the risk of an attacker gaining read access is much lower. A more serious compromise would be needed, and that would increase the likelihood that the attacker could also modify the source code. This, inscidentally, is exactly why these methods of storing passwords are prefered over the simple config file!
Anyway, from a practical point of view it is much less of an headache for the attacker to connect directly to the database with the password, then having to modify an existing application to do the work for you. But you are right, once the attacker have gotten that far you are already owned any way.