March 5, 2012

Is using a for-loop on submitted POST data in PHP safe?

Question by ACobbs

I’m always a worry-wart about security in my PHP applications, and I just (potentially) thought of a way a hacker could kill my script. Currently my application takes form data and submits it as an array to a PHP script via AJAX, then loops through this array.

foreach($_POST['form_data'] as $field => $value){
   //Do something here.
}

However, what if a hacker were to forge an AJAX request, and repeatedly submit the ‘form_data’ array with 100000000000 random elements? The loop would have to iterate through each element, possibly causing a DoS (or at least slow down service), correct?

I’m not entirely educated here, so I may have some incorrect assumptions. Thanks for any input!

Answer by NikiC

This will not be an issue: PHP limits the maximum number of POST vars using the max_input_vars directive, which defaults to 1000 variables.

This limit is actually enforced to prevent a much more serious type of DOS attack than the one you are thinking about (really, iterating a few thousand array elements is like nothing), namely hash table collision based attacks (often referred to as HashDOS). For more info on that issue see my article Supercolliding a PHP array.

Answer by Starx

Yes, ofcourse the hacker might sent all those datas, and it will definitely be unwise to iterate through them all. Could do many unexpected things.

I will suggest you trim down your application to only those, which is accepted. What you are doing now is taking all the values from the form_data.

Instead of this, you should know what values to expect. Could be something like name, address, phone and only iterate through such known values.

Thus, The problem that might occur will be reduced but not completely blocked. With additional size check, like Pekka suggested, you will trim down the risk even more.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!