WebApp Sec mailing list archives

Re: SQL injection and PHP/MYSQL


From: "Sverre H. Huseby" <shh () thathost com>
Date: Tue, 9 Sep 2003 21:54:44 +0200

[Robert Buljevic]

|   And is it enough to use PHP's addslashes function? If not, why?
|   Could you provide any example of input that could cause injection
|   even if it's slashed - always referring to the particular case of
|   PHP/MYSQL?

AFAIK, MySQL doesn't support batched queries, so many of the cool
attacks will not work.

Here's an example that does not rely on batched queries.  The program
will give a user access to some data owned either by him, or by
someone who has granted him access (the latter is not implemented).

    # ID of current user.  would be read from the session or something,
    # but we make it simple and just fill it in.
    $userid = 1234;

    function hasAccessToDataOwnedBy($ownerid) {
        global $userid;

        if ($ownerid == $userid)
            return TRUE;
        # other checks removed for readability
        return FALSE;
    }

    # the following variable would be coming from the user, but we
    # make it simple again, and fill it in here.
    $listby = "1234 or 1=1";

    # note that there are no slashable characters in the input, so
    # the following line has no effect.  one should rather have
    # verified that the input was numeric.
    $listby = addslashes($listby);

    if (hasAccessToDataOwnedBy($listby)) {
        $sql = "SELECT * FROM Data WHERE OwnerId=" . $listby;
        # here we would have queried the database, but we rather print
        # the query to show what is going on.
        echo($sql . "\n");
    } else
        echo("access denied\n");

The program will print

    SELECT * FROM Data WHERE OwnerId=1234 or 1=1

which is not good, as the code tried to verify that the user had
access to the data by comparing the incoming string and the
server-side userid.  Unfortunately, PHP thinks that 1234 and "1234 or
1=1" is the same numeric value.  When passed to the database, all rows
will be retreived, not only the ones accessible by the current user.


Sverre.

-- 
shh () thathost com
http://shh.thathost.com/


Current thread: