How can I avoid SQL injection attacks in my ASP.NET application?

前端 未结 16 1932
死守一世寂寞
死守一世寂寞 2020-11-27 20:16

I need to avoid being vulnerable to SQL injection in my ASP.NET application. How might I accomplish this?

相关标签:
16条回答
  • 2020-11-27 20:46

    Use parameters! It really is that simple :-)

    Create your queries like this (for MS Sql server with C#):

    SqlCommand getPersons = new SqlCommand("SELECT * FROM Table WHERE Name = @Name", conn); 
    

    Here @Name is the parameter where you want to avoid sql injection and conn is an SqlConnection object. Then to add the parameter value you do the following:

    getPersons.Parameters.AddWithValue("@Name", theName);
    

    Here theName is a variable that contains the name you are searching for.

    Now it should be impossible to do any sql injections on that query.

    Since it is this simple there is no reason not to use parameters.

    0 讨论(0)
  • 2020-11-27 20:47

    Use parametrized queries and/or stored procedures and parse your parameters via SQL parameters. Never generate SQL code by concatenating strings. Also do some reading about SQL injection and about writing secure code, because preventing SQL injection is only a small part of security. There is many more (like XSS - Cross Site Scripting). If a hacker wants to compromise your site/application he will look for more then only SQL injection.

    0 讨论(0)
  • 2020-11-27 20:47

    Always use only parameterized queries.

    0 讨论(0)
  • 2020-11-27 20:49

    Try to use Stored Procedures, and validate the input on your data. Do not use any direct SQL like INSERT INTO ...

    0 讨论(0)
  • 2020-11-27 20:50

    Scott Guthrie posted a decent little article about this a while back. In it, he offers 5 suggestions for protecting yourself:

    1. Don't construct dynamic SQL Statements without using a type-safe parameter encoding mechanism. [...]

    2. Always conduct a security review of your application before ever put it in production, and establish a formal security process to review all code anytime you make updates. [...]

    3. Never store sensitive data in clear-text within a database. [...]

    4. Ensure you write automation unit tests that specifically verify your data access layer and application against SQL Injection attacks. [...]

    5. Lock down your database to only grant the web application accessing it the minimal set of permissions that it needs to function. [...]

    He does a decent job of explaining why these are important, and links to several other resources as well...

    0 讨论(0)
  • 2020-11-27 20:53

    The book, "Building Secure ASP.NET Applications" guideline has a section on this topic.

    0 讨论(0)
提交回复
热议问题