Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions SqlInjection.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/

package detectors.sql_injection;

import javax.servlet.http.HttpServletRequest;

public class SqlInjection {

// {fact rule=sql-injection@v1.0 defects=1}
public void executeSqlStatementNoncompliant(HttpServletRequest request, java.sql.Connection connection) {
final String favoriteColor = request.getParameter("favoriteColor");
try {
String sql = "SELECT * FROM people WHERE favorite_color='" + favoriteColor + "'";
java.sql.Statement statement = connection.createStatement();
// Noncompliant: user-given input is not sanitized before use.
statement.execute(sql);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Description: Potential SQL Injection detected. Untrusted input is being directly included in an SQL query without proper parameterization. This can allow attackers to modify the query structure and execute arbitrary SQL commands. Use PreparedStatement with parameterized queries instead. Always validate and sanitize inputs before using them in queries. Learn more https://cwe.mitre.org/data/definitions/89.html

Severity: High

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Description: We detected an SQL command that might use unsanitized input. This can result in an SQL injection. To increase the security of your code, sanitize inputs before using them to form a query string.

Learn more

Severity: High

} catch (java.sql.SQLException e) {
throw new RuntimeException(e);
}
}
// {/fact}

// {fact rule=sql-injection@v1.0 defects=0}
public void executeSqlStatementCompliant(HttpServletRequest request, java.sql.Connection connection) {
final String favoriteColor = request.getParameter("favoriteColor");
// Compliant: user-given input is sanitized before use.
if (!favoriteColor.matches("[a-z]+")) {
throw new IllegalArgumentException();
}
try {
String sql = "SELECT * FROM people WHERE favorite_color='" + favoriteColor + "'";
java.sql.Statement statement = connection.createStatement();
statement.execute(sql);
} catch (java.sql.SQLException e) {
throw new RuntimeException(e);
}
}
// {/fact}

}