To start this off, I am well aware that parameterized queries are the best option, but I am asking what makes the strategy I present below vulnerable. People insist the below solution doesn't work, so I am look for an example of why it wouldn't.
If dynamic SQL is built in code using the following escaping before being sent to a SQL Server, what kind of injection can defeat this?
string userInput= "N'" + userInput.Replace("'", "''") + "'"
A similar question was answered here, but I don't believe any of the answers are applicable here.
Escaping the single quote with a "\" isn't possible in SQL Server.
I believe SQL Smuggling with Unicode (outlined here) would be thwarted by the fact that the string being produced is marked as Unicode by the N preceding the single quote. As far as I know, there are no other character sets that SQL Server would automatically translate to a single quote. Without an unescaped single quote, I don't believe injection is possible.
I don't believe String Truncation is a viable vector either. SQL Server certainly won't be doing the truncating since the max size for an nvarchar
is 2GB according to microsoft. A 2 GB string is unfeasible in most situations, and impossible in mine.
Second Order Injection could be possible, but is it possible if:
- All data going into the database is sanitized using the above method
- Values from the database are never appended into dynamic SQL (why would you ever do that anyways, when you can just reference the table value in the static part of any dynamic SQL string?).
I'm not suggesting that this is better than or an alternative to using parameterized queries, but I want to know how what I outlined is vulnerable. Any ideas?
"SELECT * FROM MyTable WHERE Field = " + userInput
whenuserInput
is0; DROP TABLE OhNo;
. – Yuck