Sql-server – SQL Injection penn testing from the queries only

Securitysql serversql-injection

Is there an established method or tool available to perform pen testing on an application by only testing queries it sends to the database?

For example, if I have a bunch of SQL Servers hosting various websites and a query came through that wasn't parameterised, is there a way I can detect these?

Example query that probably isn't secure:

SELECT x,y,z FROM logins WHERE username = 'xx' and password = 'yyy'

…instead I would expect a secure application to be probably be using sp_executesql.

Best Answer

Parameters are passed as an RPC (remote procedure call) to SQL Server over the TDS protocol. Consequently, a parameterized query will show as RPC starting/completed events in a trace (SQL Trace or Extended Events). Depending on the API and application methods used, parameterized queries might call API system procedures (e.g. sp_prepare) instead of sp_executesql or may call user stored procedures directly.

Ad-hoc queries are passed as a batch one or more SQL statements. These will show as a batch starting/completed events in a trace. Ad-hoc queries can be a SQL injection risk when:

  1. the query is not static or
  2. it built in the application code with string concatenation from untrusted sources.

Static queries might contain literals too so one would need to guess at the context and examine the app code to determine if the query is a vulnerability.

Be aware that even parameterized queries can pose an injection risk if built dynamically with a mix of parameters and literals, or by concatenation from untrusted sources. I can't think of a way to identify such practices without examining the app code or finding the vulnerability in penn testing.