I have an .NET application which is running the following statement using SqlCommand:
DECLARE @SQL VARCHAR(100)
SELECT @SQL = 'CREATE DATABASE ' + @DB
EXEC(@SQL)
The @DB parameter comes from user input, so obviously the application is vulnerable to something like ‘X DROP DATABASE Y’. I’m sure there must be an obvious way I’m missing…
Edit: using a parametrized statement cannot work because you cannot use a parameter in CREATE DATABASE (CREATE DATABASE @DB returns a syntax error).
First, you should never, ever do this from a web app. Ever. Really. I’m serious. With the exception of deployment packages, the only time I’ve needed to execute a
CREATE DATABASEis from the query analyzer in SSMS. Additionally, I’m suspicious of any code that would let a user enter a database name, and then go and create it.Most importantly, what you’ve posted is not a “parameterized query.” It’s concatenated SQL, which is the source of SQL injection vulnerabilities.. If it were a parameterized query (or a stored proc, but I don’t think you can do a
CREATE DATABASEfrom a sproc), SQL injection would be a non-issue.You can either use a real parametrized query (here is a good tutorial on parametrized queries.), or sanitize your inputs, but ADO.NET or whatever other db library will reliably handle this for you IF you properly build the command and parameter objects.