Introduction

SQL Injection is one of the most dangerous web vulnerabilities. So much so that it's the #1 item in the OWASP Top 10.

It represents a serious threat because SQL Injection allows evil attacker code to change the structure of a web application's SQL statement in a way that can steal data, modify data, or potentially facilitate command injection to the underlying OS.

This cheat sheet is a derivative work of the SQL Injection Prevention Cheat Sheet.

Parameterized Query Examples

SQL Injection is best prevented through the use of parameterized queries. The following chart demonstrates, with real-world code samples, how to build parameterized queries in most of the common web languages. The purpose of these code samples is to demonstrate to the web developer how to avoid SQL Injection when building database queries within a web application.

Prepared Statement Examples

Using Java built-in feature

  1. String custname = request.getParameter("customerName");
  2. String query = "SELECT account_balance FROM user_data WHERE user_name = ? ";
  3. PreparedStatement pstmt = connection.prepareStatement( query );
  4. pstmt.setString( 1, custname);
  5. ResultSet results = pstmt.executeQuery( );

Using Java with Hibernate

  1. //HQL
  2. @Entity // declare as entity;
  3. @NamedQuery(
  4. name="findByDescription",
  5. query="FROM Inventory i WHERE i.productDescription = :productDescription"
  6. )
  7. public class Inventory implements Serializable {
  8. @Id
  9. private long id;
  10. private String productDescription;
  11. }
  12. // use case
  13. // This should REALLY be validated too
  14. String userSuppliedParameter = request.getParameter("Product-Description");
  15. // perform input validation to detect attacks
  16. List<Inventory> list =
  17. session.getNamedQuery("findByDescription")
  18. .setParameter("productDescription", userSuppliedParameter).list();
  19. //Criteria API
  20. // This should REALLY be validated too
  21. String userSuppliedParameter = request.getParameter("Product-Description");
  22. // perform input validation to detect attacks
  23. Inventory inv = (Inventory) session.createCriteria(Inventory.class).add
  24. (Restrictions.eq("productDescription", userSuppliedParameter)).uniqueResult();

Using .NET built-in feature

  1. String query = "SELECT account_balance FROM user_data WHERE user_name = ?";
  2. try {
  3. OleDbCommand command = new OleDbCommand(query, connection);
  4. command.Parameters.Add(new OleDbParameter("customerName", CustomerName Name.Text));
  5. OleDbDataReader reader = command.ExecuteReader();
  6. // …
  7. } catch (OleDbException se) {
  8. // error handling
  9. }

Using ASP .NET built-in feature

  1. string sql = "SELECT * FROM Customers WHERE CustomerId = @CustomerId";
  2. SqlCommand command = new SqlCommand(sql);
  3. command.Parameters.Add(new SqlParameter("@CustomerId", System.Data.SqlDbType.Int));
  4. command.Parameters["@CustomerId"].Value = 1;

Using Ruby with ActiveRecord

  1. # Create
  2. Project.create!(:name => 'owasp')
  3. # Read
  4. Project.all(:conditions => "name = ?", name)
  5. Project.all(:conditions => { :name => name })
  6. Project.where("name = :name", :name => name)
  7. # Update
  8. project.update_attributes(:name => 'owasp')
  9. # Delete
  10. Project.delete(:name => 'name')

Using Ruby built-in feature

  1. insert_new_user = db.prepare "INSERT INTO users (name, age, gender) VALUES (?, ? ,?)"
  2. insert_new_user.execute 'aizatto', '20', 'male'

Using PHP with PHP Data Objects

  1. $stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
  2. $stmt->bindParam(':name', $name);
  3. $stmt->bindParam(':value', $value);

Using Cold Fusion built-in feature

  1. <cfquery name = "getFirst" dataSource = "cfsnippets">
  2. SELECT * FROM #strDatabasePrefix#_courses WHERE intCourseID =
  3. <cfqueryparam value = #intCourseID# CFSQLType = "CF_SQL_INTEGER">
  4. </cfquery>

Using PERL with Database Independent Interface

  1. my $sql = "INSERT INTO foo (bar, baz) VALUES ( ?, ? )";
  2. my $sth = $dbh->prepare( $sql );
  3. $sth->execute( $bar, $baz );

Stored Procedure Examples

The SQL you write in your web application isn't the only place that SQL injection vulnerabilities can be introduced. If you are using Stored Procedures, and you are dynamically constructing SQL inside them, you can also introduce SQL injection vulnerabilities.

To ensure this dynamic SQL is secure, you can parameterize this dynamic SQL too using bind variables.

Here are some examples of using bind variables in stored procedures in different databases.

Oracle using PL/SQL

Normal Stored Procedure

No dynamic SQL being created. Parameters passed in to stored procedures are naturally bound to their location within the query without anything special being required:

  1. PROCEDURE SafeGetBalanceQuery(UserID varchar, Dept varchar) AS BEGIN
  2. SELECT balance FROM accounts_table WHERE user_ID = UserID AND department = Dept;
  3. END;

Stored Procedure Using Bind Variables in SQL Run with EXECUTE

Bind variables are used to tell the database that the inputs to this dynamic SQL are 'data' and not possibly code:

  1. PROCEDURE AnotherSafeGetBalanceQuery(UserID varchar, Dept varchar)
  2. AS stmt VARCHAR(400); result NUMBER;
  3. BEGIN
  4. stmt := 'SELECT balance FROM accounts_table WHERE user_ID = :1
  5. AND department = :2';
  6. EXECUTE IMMEDIATE stmt INTO result USING UserID, Dept;
  7. RETURN result;
  8. END;

SQL Server using Transact-SQL

Normal Stored Procedure

No dynamic SQL being created. Parameters passed in to stored procedures are naturally bound to their location within the query without anything special being required:

  1. PROCEDURE SafeGetBalanceQuery(@UserID varchar(20), @Dept varchar(10)) AS BEGIN
  2. SELECT balance FROM accounts_table WHERE user_ID = @UserID AND department = @Dept
  3. END

Stored Procedure Using Bind Variables in SQL Run with EXEC

Bind variables are used to tell the database that the inputs to this dynamic SQL are 'data' and not possibly code:

  1. PROCEDURE SafeGetBalanceQuery(@UserID varchar(20), @Dept varchar(10)) AS BEGIN
  2. DECLARE @sql VARCHAR(200)
  3. SELECT @sql = 'SELECT balance FROM accounts_table WHERE '
  4. + 'user_ID = @UID AND department = @DPT'
  5. EXEC sp_executesql @sql,
  6. '@UID VARCHAR(20), @DPT VARCHAR(10)',
  7. @UID=@UserID, @DPT=@Dept
  8. END

References