Thursday 24 November 2011

T-SQL Dynamic SQL Variable replacement

Overview of technique
A nice way of doing SQL Injection is to:
  1. Copy the code you want dynamic into the script
  2. Put quotes on each end
  3. Replace the parameters with <parametername>
  4. Using the sql REPLACE function, switch out with the value of the parameter
  5. Query your little heart out
This T-SQL script shows an example



/*
 Declare variables
*/
DECLARE @wcSQL AS NVARCHAR(max)
DECLARE @columnWeWantToReturn VARCHAR(50)
SET @columnWeWantToReturn = 'name'

/*
 Prepare SQL Statement
*/
SET @wcSQL = 'SELECT <name> 
 FROM sys.sysobjects'
/*
 Replace parameters
*/      
SET @wcSQL = REPLACE(@wcSQL, '<name>', @columnWeWantToReturn)

/*
 Execute the dynamic sql
*/
EXEC sp_executeSQL @statement = @wcSQL


No comments:

Post a Comment