4

Im aware of how parameterised queries work, and ive used them in every non hardcoded query I've written so far, however when writing a function to create a dynamic query (for testing purposes) it made me question whether it would actually be safe to use "as is"

string sql = "SELECT * FROM Table WHERE";

string fullstring = "The quick brown fox jumped over";
string[] words = fullstring.Split(' ');

foreach (string item in words)
{
    sql = sql + " Column LIKE '%" + item + "%' AND";
}

sql = sql.Remove(sql.Length - 3);

If I were to turn this into a query, the result would be

SELECT * FROM Table WHERE Column LIKE '%the%' AND Column LIKE '%quick%' AND Column LIKE '%brown%' AND Column LIKE '%fox%' AND Column LIKE '%jumped%' AND Column LIKE '%over%' 

Now i'm still pretty sure that this is still open to injection attacks due to the lack of parameters, however i'm unsure how due to the delimiter being a space character making things like SELECT * FROM TABLE or DROP TABLE unable to be written in the string as each would be split into their own strings ie. SELECT,*,FROMand TABLE

Can anyone enlighten me further?

(Note, not planning on using this as an alternative to proper parameters, just trying to understand)

2 Answers 2

6
select"name"from"sys"."columns"

Is an example of a query I can write that SQL Server will process and that contains no spaces.

So, just say no.


Here's another example showing another way of bypassing "no spaces" and in an "injected" form:

select name from sys.columns where name like '%a'union/**/all/**/select/**/name/**/from/**/sys.objects
Sign up to request clarification or add additional context in comments.

4 Comments

Fantastic example of what i was looking for. Thank you very much.
Also, splitting a string on ' ' does not remove tabs nor does it removes line breaks, so...
And you can also just use /**/ to separate tokens also
Or add the following to the end of the sentence: %';DROP TABLE table;-- (note that the spaces are actually tabs, and they won't be filtered out by your split.
1

If the string was formated like that:

string fullstring = "DROP\tTABLE\tTableName";

you would still have a problem with injection... Just a simple example.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.