Search code examples
c#asp.netsql-serversql-injection

SQL Injection Technique For Query String


I've been trying to ensure my code isn't susceptible to the infamous SQL Injection Attack. The question involves the Query String, the legacy code I'm managing has instances of inline SQL which applies:

string query = @"SELECT * FROM [Order] 
   WHERE ([Id]=" + Request.QueryString[@"oid"] + ");";

Obviously that is bad, it will take the attack. My question is this enough?

command.Parameters.AddWithValue("@OrderId", Request.QueryString[@"oid"]);

So now the query has a parameter, which is being passed a value. I know it has some form of encoding. However, will that be enough as any malicious attacker could exploit that query string? So should I do Encode on the query string? That way it will encode it safely to avoid being exploited any further?

Some clarification on the matter would be helpful.


Solution

  • is this enough?

    No - you also need to change your query to

    string query = @"SELECT * FROM [Order] 
       WHERE ([Id]=@OrderId);";
    

    I know it has some form of encoding

    No, it uses the actual value, but it does not inject it into the SQL statement. It treats it as a literal string, so there's no way to include punctuation or malicious code that will get interpreted as SQL.

    EDIT

    I may have misunderstood - you may need to URL-decode the value if it included URL-encoded characters (%20, &, etc. ), but no encoding (or decoding) is necessary to prevent SQL injection.