How can prepared statements protect from SQL injection attacks?

前端 未结 9 2034
予麋鹿
予麋鹿 2020-11-21 05:40

How do prepared statements help us prevent SQL injection attacks?

Wikipedia says:

Prepared statements are resilient against SQL injection, because

相关标签:
9条回答
  • 2020-11-21 06:07

    When you create and send a prepared statement to the DBMS, it's stored as the SQL query for execution.

    You later bind your data to the query such that the DBMS uses that data as the query parameters for execution (parameterization). The DBMS doesn't use the data you bind as a supplemental to the already compiled SQL query; it's simply the data.

    This means it's fundamentally impossible to perform SQL injection using prepared statements. The very nature of prepared statements and their relationship with the DBMS prevents this.

    0 讨论(0)
  • 2020-11-21 06:08

    In SQL Server, using a prepared statement is definitely injection-proof because the input parameters don't form the query. It means that the executed query is not a dynamic query. Example of an SQL injection vulnerable statement.

    string sqlquery = "select * from table where username='" + inputusername +"' and password='" + pass + "'";
    

    Now if the value in the inoutusername variable is something like a' or 1=1 --, this query now becomes:

    select * from table where username='a' or 1=1 -- and password=asda
    

    And the rest is commented after --, so it never gets executed and bypassed as using the prepared statement example as below.

    Sqlcommand command = new sqlcommand("select * from table where username = @userinput and password=@pass");
    command.Parameters.Add(new SqlParameter("@userinput", 100));
    command.Parameters.Add(new SqlParameter("@pass", 100));
    command.prepare();
    

    So in effect you cannot send another parameter in, thus avoiding SQL injection...

    0 讨论(0)
  • 2020-11-21 06:20

    Basically, with prepared statements the data coming in from a potential hacker is treated as data - and there's no way it can be intermixed with your application SQL and/or be interpreted as SQL (which can happen when data passed in is placed directly into your application SQL).

    This is because prepared statements "prepare" the SQL query first to find an efficient query plan, and send the actual values that presumably come in from a form later - at that time the query is actually executed.

    More great info here:

    Prepared statements and SQL Injection

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