Does using parameterized SqlCommand make my program immune to SQL injection?

后端 未结 5 1713
故里飘歌
故里飘歌 2020-11-27 19:12

I\'m aware that SQL injection is rather dangerous. Now in my C# code I compose parameterized queries with SqlCommand class:

SqlCommand command = ...;
command         


        
相关标签:
5条回答
  • 2020-11-27 19:20

    Using SqlCommand a very good practice and as long as you don't concatenate SQL strings anywhere (including inside any stored procedures you call -- i.e. avoid dynamic SQL), you will be immune from SQL injection attacks.

    0 讨论(0)
  • 2020-11-27 19:25

    SQL Injection is mostly dependent on execution of dynamic SQL. In other words, SQL statements constructed by the concatenation of SQL with user-entered values.

    To avoid SQL Injection completely,

    Protecting yourself against SQL injection attacks is not very difficult. Applications that are immune to SQL injection attacks validate and sanitize all user input, never use dynamic SQL, execute using an account with few privileges, hash or encrypt their secrets, and present error messages that reveal little if no useful information to the hacker. By following a multi-layered approach to prevention you can be assured that if one defense is circumvented, you will still be protected.

    From MSDN

    0 讨论(0)
  • 2020-11-27 19:28

    You are not immune to SQL injection if you use dynamic sql, even if you are passing it through parameters. Too bad SQL Server doesn't have a built in function to sanitize parameters

    0 讨论(0)
  • 2020-11-27 19:31

    According to the Note on this MSDN Article, "Special input characters pose a threat only with dynamic SQL and not when using parameterized SQL."

    So I believe you are safe against SQL Injection. There might be some logical risks when using Identifiers like Idendity Values in your URLs but this is another story.

    0 讨论(0)
  • 2020-11-27 19:39

    I'd say for your particular, and probably canonical, example for parametrized queries, yes it is sufficient.

    However, people sometimes write code like this

    cmd.CommandText = string.Format("SELECT * FROM {0} WHERE col = @col;", tableName);
    cmd.Parameters.Add("@col", ...);
    

    because there is simply no way to pass the tablename itself as a parameter and the desire to do exists sometimes - misguided or not. It seems it is then often overlooked, that tableName (unless maybe only read from a set of static/constant values that do not derive from any input) indeed allows for SQL injection.

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