C# String Parameters to protect against injection?

1.1k Views Asked by At

Take this code as an example:

IAmazonSimpleDB client = new AmazonSimpleDBClient(Amazon.RegionEndpoint.USEast1);
        SelectResponse response = client.Select(new SelectRequest() { 
SelectExpression = "SELECT * FROM `foo` where FooID = '" + id + "'" });

I can rewrite it as such:

IAmazonSimpleDB client = new AmazonSimpleDBClient(Amazon.RegionEndpoint.USEast1);
        SelectResponse response = client.Select(new SelectRequest() { 
SelectExpression = "SELECT * FROM `foo` where FooID = '{0}'", id });

But from my understanding, that still leaves it vulnerable to injection right?

Is there anything else I can do here? We aren't using SQL so I can't do SQL Parameters.

1

There are 1 best solutions below

5
Christopher Vickers On BEST ANSWER

I usually do a check to see if the id is an integer. That way you will get an exception or a Boolean value if it isn't an int. It will work fine unless you are using GUID values.

var isNumeric = int.TryParse("123", out int n); //Will give a bool

Int32.Parse(yourString); //This will give an exception if it is not an possible integer

If it's anything more than that then you could use a Regex expression to look for strange values and remove characters that shouldn't be there such as spaces. Most SQL injection attacks wont work if there's no spaces... I think. Removing all the spaces is pretty easy and I would assume your ID (even if it is complex) won't include spaces.

string s = " "
string t = s.Replace(" ", ""). //It will be hard to do a sql attack if the spaces are removed.

A little off topic but with C# 6.0 you can format string differentlyl; It's a new feature called "string interpolation" (thanks Etienne de Martel).

$"SELECT * FROM `foo` where FooID = '{id}'"