Search code examples
sqlsql-injection

SQL Injection Query


I am writing a report on SQL injection attacks. I've found an example on Owasp as shown bellow.

Since this is an example and to me, it seems as a simple query getting a row with the specific ID, does it do anything else or my assumption is correct?

String query = "SELECT * FROM accounts WHERE custID='" + 
request.getParameter("id") + "'";  
// Since this is an online example i don't know what getParameter("id") method does.

Solution

  • to me it seems as a simple query getting a row with specific ID

    Thats the magic of injection. The query should only get a row that fits a certain criteria that comes from a request (like a GET or POST from html for example).

    So request.getParameter("id") provides a parameter submitted by the user (or a very bad guy).

    Usually whoever wrote that peace of code expected something like this:

    id = 12

    which would result in

    SELECT * FROM accounts WHERE custID='12'
    

    Now image what happens if the user (a bad one in this case) sends this instead:

    id = 0'; DROP TABLE accounts; --
    

    This would execute as

    SELECT * FROM accounts WHERE custID='0'; DROP TABLE accounts; --'
    

    Step-by-step:

    1. Make sure the intended query executes without error (0)
    2. End the query before the intended point (';)
    3. Inject your malicous code (DROP TABLE accounts;)
    4. Make sure everything that is left of the original query is treated as a comment (--)

    The problem in the OWASP example isn't the query itself, but the fact that parameters that come from 'outside' (request.getParameter("id")) are used to generate a query, without escaping any potential control characters.

    This style of writing code basically allows any user to execute code on your SQL-Server.