Search code examples
phpajaxsql-injection

Is it possible to manipulate the post data in an jquery Ajax post?


I was wondering if code I have written is open to attack.

    $.ajax({
        url: site_url+"/customer/update",
        type: 'POST',
        dataType: "json",
        async: true,
        data: {
            'id':$('#id').val(),
            'cuFirstname':$('#firstname').val(),
            'cuLastname':$('#lastname').val(),
            'cuPersonalnr':$('#personalnr').val(),
        },
    });

On the server it looks like this:

    $this->db->where('cuID = '.$customerid);
    $this->db->update('customers',$_POST);

So I'm thinking that maybe if someone could change the variables (cuFirstname, cuLastname, cuPersonalnr) in the data part of the ajax post, that they would be able to write sql-code there.

"update customers set cuFirstname = 'charlie', cuLastname = 'brown', cuPersonalnr = '7012230303' where cuID = 1000"

So if they changed cuLastname to something else it could look like this:

update customers set cuFirstname = 'charlie', [cuShouldnotbechanged] = 'brown', cuPersonalnr = '7012230303' where cuID = 1000

So my question is: Is it possible for an attacker to change those variable names, and if so, how?


Solution

  • The client can change any aspect of the AJAX call, simply by making their own HTTP request to your URL with their own parameters. So, yes, they could conceivably change any part of the request.

    In your code, the question really boils down to "how does my database library handle the update?". You're doing the following:

    $this->db->where('cuID = '.$customerid);
    $this->db->update('customers',$_POST);
    

    which is, presumably, building a query like:

    UPDATE customers SET column1='some value', column2='some other value', ... WHERE cuID='whatever';
    

    based on the keys and values of the $_POST array. To address your specific question about what happens if a client changes the keys n the $_POST array, it seems to me there are two possibilities:

    1. if they enter a column name that does not exist, the database library is either going to ignore it (and update the stuff it is able to) or throw an error (because an UPDATE statement with a non-existent column name is an SQL error).

    2. if they enter a column name that exists but that you did not intend to update, then that new column name will probably be used and updated (unless your database library has protection in place for that - some require you to explicitly state which columns can be updated in this way).