SV.DATA.DB

This error detects the insertion of unvalidated user data into SQL database queries. This data is stored in the database directly from user input and could contain malicious content. If the data is later used in other SQL statements, then an SQL injection vulnerability also exists. If the data is later used as output to the web interface, a cross-site scripting vulnerability also exists.

As of release 2023.2, this checker supports Jakarta EE.

Vulnerability and risk

A data injection vulnerability opens up an application to the storage of malicious content. The vulnerability exists when user input is stored directly, unchecked, into the application's database. This data could contain malicious HTML content, SQL statements, manipulated paths, etc., that could later be used in the application. For example, a data injection can lead to a cross-site scripting vulnerability if this data is reflected back to the web interface.

Klocwork security vulnerability (SV) checkers identify calls that create potentially dangerous data; these calls are considered unsafe sources. An unsafe source can be any data provided by the user, since the user could be an attacker or has the potential for introducing human error.

Mitigation and prevention

The prevention of data injection flaws can be achieved by validating any and all input from outside the application (user input, file input, system parameters, etc.). Validation should include length and content. All data stored in the database should include a lexical check for a particular type, such as user name. Typically only alphanumeric characters are needed (i.e., A-Za-z, 0-9). Any other accepted characters should be escaped. This validation should be done at each source of data, such as when each parameter is read from the HTTP request. Additionally, it may be advisable to check all strings used in SQL statements before their use.

Example 1

Copy
     public void setUserLastName(ServletRequest req, Connection con) throws SQLException {
         // Source of data from HTTP request in servlet
         String lastName = req.getParameter("lastName");
         int userId = Integer.parseInt(req.getParameter("userId"));
 
         String query = "UPDATE userData INTO lastName=? WHERE userid = ?";
         PreparedStatement statement = con.prepareStatement(query);
         statement.setString(1, lastName);
         statement.setInt(2, userId);
         statement.executeUpdate();
     }

SV.DATA.DB is reported for line 21: 'lastName' contains a value coming from an HTTP request and thus can be tainted (line 14). On line 19 tainted 'lastName' is used to create an SQL statement 'statement', which is executed on line 21.

Extension

This checker can be extended through the Klocwork knowledge base. See Tuning Java analysis for more information.