Search code examples
phpmysqlpdosql-injection

SQL injection: mechanism


Many answers on SO talk about the SQL injection and remedies against it, which is clear to me. What most of them don't touch (or perhaps I don't get it) is how actually a malicious SQL gets injected into the query.

Here is my confusion.

Suppose an example: php + pdo (or mysqli) + Mysql. The code:

$sql = "select SomeName from SomeTable where SomeNameId = $neededId"; $pdoInstance->query($sql);

If I understand right, to append some malicious code to the $neededId variable, an attacker needs to know about the existence of the $neededId variable. But to find out the variable name, an attacker has to surpass the php interpreter which I don't think is easy.

Could someone clarify?


Solution

  • You are right, an attacker must maybe guess the name of a table. for example:

    $neededId = "0; DELETE FROM tblUser;"
    
    select SomeName from SomeTable where SomeNameId = $neededId
    

    If that doesn't work, try the next tablename: tblCustomer, tblcontact, etc, etc.

    You just don't want that to be possible.

    Edit: In case you are building some famous open sourced framework, people don't even have to guess the tablenames, they can look them up.

    OP asked: "how an attacker can inject delete blah-blah from tblUser into the $neededId variable?"

    That is very easy. Your data comes in from a form. A HTML form. You can put ANYTHING inside the post. It cannot be trusted.

    You can do it by building your own HTML form, or use it on the webpage itself, eg via: https://addons.mozilla.org/en-US/firefox/addon/tamper-data/

    Does that answer your inquiry?