Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Injection Prevention in .NET

Tags:

c#

.net

sql

ado.net

I typically write my SQL as so in .NET

sql.Append("SELECT id, code, email FROM mytable WHERE variable = @variable ");

Then do something like this:

using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings[ConfigurationManager.AppSettings["defaultConnection"]].ConnectionString))
{
    using (SqlCommand myCommand = new SqlCommand(sql.ToString(), conn))
    {
        myCommand.Parameters.AddWithValue("@variable", myVariableName");
        ...

But should I also do this addParameter when the data I got comes directly from the database like so?

likesql.Append(string.Format("SELECT group_id, like_text FROM likeTerms ORDER BY group_id ASC "));

DataTable dtLike = SqlHelper.GetDataTable(likesql.ToString());

foreach (DataRow dr in dtLike)
{
    buildsql.Append(".... varId = " + dr["group_id"].ToString() + "...");

    ...

Is this acceptable? What is best practice?

like image 373
cdub Avatar asked Nov 20 '12 23:11

cdub


People also ask

Does ASP NET prevent SQL injection?

In fact, you don't even need to be using ASP.NET to be susceptible to SQL injection attacks. Any application that queries a database using user-entered data, including Windows Forms applications is a potential target of an injection attack. Protecting yourself against SQL injection attacks is not very difficult.

How can SQL injection be prevented?

The only sure way to prevent SQL Injection attacks is input validation and parametrized queries including prepared statements. The application code should never use the input directly. The developer must sanitize all input, not only web form inputs such as login forms.

What is SQL injection in C#?

SQL injection is a code injection technique that might destroy your database. SQL injection is one of the most common web hacking techniques. SQL injection is the placement of malicious code in SQL statements, via web page input.

What is SQL injection how we can prevent SQL injection in Ado net?

SQL injection attacks can be performed in Entity SQL by supplying malicious input to values that are used in a query predicate and in parameter names. To avoid the risk of SQL injection, you should never combine user input with Entity SQL command text.


1 Answers

You should always use parameters:

  • Where are the values in your database coming from?
  • Can you trust, in your example, that 'group_id' wasn't modified to be something you're not expecting?

Trust noone

Can someone with limited database access inject directly into a field used elsewhere?

Performance

Also, it helps performance. Cached execution plans will disregard the value of the parameter, meaning you're saving the server from recompiling the query every time the parameters change.

like image 67
Tass Avatar answered Oct 06 '22 03:10

Tass