Can I protect against SQL injection by escaping single-quote and surrounding user input with single-quotes?

后端 未结 18 2268
忘了有多久
忘了有多久 2020-11-22 14:03

I realize that parameterized SQL queries is the optimal way to sanitize user input when building queries that contain user input, but I\'m wondering what is wrong with takin

相关标签:
18条回答
  • 2020-11-22 14:39

    Rather than changing a single quote to (what looks like) two single quotes, why not just change it to an apostrophe, a quote, or remove it entirely?

    Either way, it's a bit of a kludge... especially when you legitimately have things (like names) which may use single quotes...

    NOTE: Your method also assumes everyone working on your app always remembers to sanitize input before it hits the database, which probably isn't realistic most of the time.

    0 讨论(0)
  • 2020-11-22 14:40

    What ugly code all that sanitisation of user input would be! Then the clunky StringBuilder for the SQL statement. The prepared statement method results in much cleaner code, and the SQL Injection benefits are a really nice addition.

    Also why reinvent the wheel?

    0 讨论(0)
  • 2020-11-22 14:43

    Your defence would fail if:

    • the query is expecting a number rather than a string
    • there were any other way to represent a single quotation mark, including:
      • an escape sequence such as \039
      • a unicode character

    (in the latter case, it would have to be something which were expanded only after you've done your replace)

    0 讨论(0)
  • 2020-11-22 14:44

    In a nutshell: Never do query escaping yourself. You're bound to get something wrong. Instead, use parameterized queries, or if you can't do that for some reason, use an existing library that does this for you. There's no reason to be doing it yourself.

    0 讨论(0)
  • 2020-11-22 14:44

    Patrick, are you adding single quotes around ALL input, even numeric input? If you have numeric input, but are not putting the single quotes around it, then you have an exposure.

    0 讨论(0)
  • 2020-11-22 14:46

    Simple answer: It will work sometimes, but not all the time. You want to use white-list validation on everything you do, but I realize that's not always possible, so you're forced to go with the best guess blacklist. Likewise, you want to use parametrized stored procs in everything, but once again, that's not always possible, so you're forced to use sp_execute with parameters.

    There are ways around any usable blacklist you can come up with (and some whitelists too).

    A decent writeup is here: http://www.owasp.org/index.php/Top_10_2007-A2

    If you need to do this as a quick fix to give you time to get a real one in place, do it. But don't think you're safe.

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