Skip to content

Files

Latest commit

 

History

History
53 lines (36 loc) · 1.76 KB

B608.md

File metadata and controls

53 lines (36 loc) · 1.76 KB

Pattern: Possible SQL injection via string-based query construction

Issue: -

Description

An SQL injection attack consists of insertion or "injection" of a SQL query via the input data given to an application. It is a very common attack vector. This rule looks for strings that resemble SQL statements that are involved in some form of string building operation. For example:

  • "SELECT %s FROM derp;" % var
  • "SELECT thing FROM " \+ tab
  • "SELECT " \+ val + " FROM " \+ tab + ...
  • "SELECT {} FROM derp;".format(var)

Unless care is taken to sanitize and control the input data when building such SQL statement strings, an injection attack becomes possible.

Example of insecure code:

import MySQLdb

query = "select username from users where username = '%s'" % name
con = MySQLdb.connect('localhost', 'testuser', 'test623', 'testdb');

with con:
    cur = con.cursor()
    cur.execute(query)

Example of secure code:

import MySQLdb

query = "select username from users where username = '%s'" % name
con = MySQLdb.connect('localhost', 'testuser', 'test623', 'testdb');

with con:
    cur = con.cursor()
    cur.execute(MySQLdb.escape_string(query))

In this example the query is created using pythons standard, unsafe % operator. MySQL’s escape_string() method is used to perform escaping on the query string immediately before executing it.

Further Reading