Because it is easy to extract strings from an application source code or binary, passwords should not be hard-coded. This is particularly true for applications that are distributed or that are open-source.


In the past, it has led to the following vulnerabilities:

* http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2019-13466[CVE-2019-13466]
* http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2018-15389[CVE-2018-15389]

Passwords should be stored outside of the code in a configuration file, a database, or a password management service.


This rule flags instances of hard-coded passwords used in database and LDAP connections. It looks for hard-coded passwords in connection strings, and for variable names that match any of the patterns from the provided list.


== Ask Yourself Whether

* The password allows access to a sensitive component like a database, a file storage, an API, or a service.
* The password is used in production environments.
* Application re-distribution is required before updating the password.

There would be a risk if you answered yes to any of those questions.


include::../recommended.adoc[]

== Sensitive Code Example

[source,java]
----
String username = "steve";
String password = "blue";
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test?" +
                  "user=" + username + "&password=" + password); // Sensitive
----

== Compliant Solution

[source,java]
----
String username = getEncryptedUser();
String password = getEncryptedPassword();
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test?" +
                  "user=" + username + "&password=" + password);
----

== See

* OWASP - https://owasp.org/Top10/A07_2021-Identification_and_Authentication_Failures/[Top 10 2021 Category A7 - Identification and Authentication Failures]
* OWASP - https://owasp.org/www-project-top-ten/2017/A2_2017-Broken_Authentication[Top 10 2017 Category A2 - Broken Authentication]
* CWE - https://cwe.mitre.org/data/definitions/798[CWE-798 - Use of Hard-coded Credentials]
* CWE - https://cwe.mitre.org/data/definitions/259[CWE-259 - Use of Hard-coded Password]
* https://wiki.sei.cmu.edu/confluence/x/OjdGBQ[CERT, MSC03-J.] - Never hard code sensitive information
* Derived from FindSecBugs rule https://h3xstream.github.io/find-sec-bugs/bugs.htm#HARD_CODE_PASSWORD[Hard Coded Password]

ifdef::env-github,rspecator-view[]

'''
== Implementation Specification
(visible only on this page)

include::../message.adoc[]

include::../parameters.adoc[]

'''
== Comments And Links
(visible only on this page)

=== on 2 Jan 2019, 15:47:08 Alexandre Gigleux wrote:
I updated the "Default value" to be in sync with what is implemented here: \https://github.com/SonarSource/sonar-java/blob/dfdf526f4b3446e181e6a869be9410400ce0499e/java-checks/src/main/java/org/sonar/java/checks/HardCodedCredentialsCheck.java#L51

include::../comments-and-links.adoc[]

endif::env-github,rspecator-view[]
