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

后端 未结 18 2447
忘了有多久
忘了有多久 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:47

    Okay, this response will relate to the update of the question:

    "If anyone knows of any specific way to mount a SQL injection attack against this sanitization method I would love to see it."

    Now, besides the MySQL backslash escaping - and taking into account that we're actually talking about MSSQL, there are actually 3 possible ways of still SQL injecting your code

    sSanitizedInput = "'" & Replace(sInput, "'", "''") & "'"

    Take into account that these will not all be valid at all times, and are very dependant on your actual code around it:

    1. Second-order SQL Injection - if an SQL query is rebuilt based upon data retrieved from the database after escaping, the data is concatenated unescaped and may be indirectly SQL-injected. See
    2. String truncation - (a bit more complicated) - Scenario is you have two fields, say a username and password, and the SQL concatenates both of them. And both fields (or just the first) has a hard limit on length. For instance, the username is limited to 20 characters. Say you have this code:
    username = left(Replace(sInput, "'", "''"), 20)
    

    Then what you get - is the username, escaped, and then trimmed to 20 characters. The problem here - I'll stick my quote in the 20th character (e.g. after 19 a's), and your escaping quote will be trimmed (in the 21st character). Then the SQL

    sSQL = "select * from USERS where username = '" + username + "'  and password = '" + password + "'"
    

    combined with the aforementioned malformed username will result in the password already being outside the quotes, and will just contain the payload directly.
    3. Unicode Smuggling - In certain situations, it is possible to pass a high-level unicode character that looks like a quote, but isn't - until it gets to the database, where suddenly it is. Since it isn't a quote when you validate it, it will go through easy... See my previous response for more details, and link to original research.

提交回复
热议问题