2

I am trying to exploit the following sql (in SQL Server 2014):

declare @maliciousSQL nvarchar(max);
set @maliciousSQL = '???'
exec ('SELECT SUM(quantity) from mytable where id in ' + @maliciousSQL );

How can parameter @maliciousSQL be crafted to run any arbitrary sql? Assume the task is to execute command 'truncate table othertable' - is it doable?

Thanks to anyone for help

lekso
  • 1,731
  • 3
  • 24
  • 46
  • As far as i know, IN has to refer to a dataset with 1 column, so don't think that can be done. Though there might be workarounds – Kevin Sijbers May 17 '17 at 11:55
  • @Kevin Sijbers I am exactly after a 'workaround' solution. Can some block of SQL be executed after the "IN" condition and then, say, execute SELECT 1,2,3 to behave like normal? The latter is not important really. Most important is to execute some evil code – lekso May 17 '17 at 12:14

3 Answers3

5

SQL Injection looks like this:

declare @maliciousSQL nvarchar(max);
set @maliciousSQL = '(1); DELETE test1;'
exec ('SELECT SUM(quantity) from mytable where id in ' + @maliciousSQL );

Terminate the statement with a semicolon then write what you like

Nick.Mc
  • 18,304
  • 6
  • 61
  • 91
2

You can use this:

set @maliciousSQL = '(1);  truncate table XXX;'

The entire point is to do not concatenate SQL statements and preferring to use parameterized queries.

Actually, the question title is misleading: you can't run DDL inside a DML statement, but a malicious caller can run multiple separate commands if you allows unsafe concatenation.

Community
  • 1
  • 1
Rubens Farias
  • 57,174
  • 8
  • 131
  • 162
1

You need to set up the SQL before executing. I also recommend sp_executesql. So:

declare @maliciousSQL nvarchar(max);
declare @sql nvarchar(max);

set @maliciousSQL = '???'
set @sql = 'SELECT SUM(quantity) from mytable where id in ' + @maliciousSQL;

exec sp_executesql @sql;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • Sorry, I might have been wrong describing my task. My question was: How should @maliciousSQL parameter look like in order to execute a 'truncate table ..." command? – lekso May 17 '17 at 12:11