How to handle erroneous data?

How do you deal with user input (unicode) that you need to constrain to a certain set of values ​​and you want to minimize the risk to the applications you are passing data to in order to move forward. For example, if I have to store data in SQL, I would like to remove any chance of SQL injection. If I were to send it over the cable over HTTP, I would like to make sure that it does not mangle the request, etc.

I'm guessing what I'm asking is is there any general method for sanitizing data?

+1


a source to share


3 answers


Each interface has its own challenges when it comes to ways to compromise a system. If you want to play it safely, you will need to tweak checks to account for issues and / or threats that are relevant to the current context.

If you need to use a specific text box in the user interface for numeric input, make sure that the user cannot enter (or paste) anything non-numeric into it. If you are using a specific control to collect a date from a user, make sure that the given value is indeed a valid date (it may even need to fall within a specific range).



Make sure url encodes whatever is passed as query string value in the HTTP request. Use stored procedures and pass values ​​to them as parameters.

Etc. Unfortunately there is no free lunch.

+1


a source


In the case of saving to a database, it is very easy. Just use parameters (DbParameter objects) - they will protect you from SQL injection and will also add escape characters if necessary.

The code could be like this:



OleDbConnection cn = new OleDbConnection(strConn);
cn.Open();
strSQL = "INSERT INTO customers (Name) VALUES (@Name)";
OleDbCommand cmd = new OleDbCommand(strSQL, cn);
cmd.Parameters.Add("@Name", "John O'Brian");
cmd.ExecuteNonQuery();
      

0


a source


Like night coder, parameters are a way to avoid SQL injection. If you are using SQL, consider using the SqlClient namespace as it is more efficient than its OleDb counterpart and was built specifically for SQL Server 7 and up.

Using night coder above example:

SqlConnection cn = new SqlConnection(strConn);
cn.Open();
strSQL = "INSERT INTO customers (Name) VALUES (@Name)";
SqlCommand cmd = new SqlCommand(strSQL, cn);
cmd.Parameters.Add(new SqlParameter("@Name", SqlDbType.Varchar)).Value = "John O'Brian";
cmd.ExecuteNonQuery();

      

Something to keep in mind in the SqlClient namespace is that if you are writing older systems (Win98) then there may be compatibility issues, making OldDBxxx a better choice.

Hooray!

0


a source







All Articles