Page 1 of 1

How to safely allow user to input php code?

Posted: Thu Oct 02, 2008 12:34 pm
by betatester
Hi all,

I have a special requirement, where the web application must allow the user to enter certain snippets of source code - java, php, sql - almost all programming languages on the planet.

User enters the code into a text area, it's stored in a mysql database, later retrieved and displayed in an html <pre></pre> element.

Now how should I proceed with properly sanitizing, filtering, displaying etc? My PHP knowledge is very limited (Im not a PHP coder but understands the syntax etc etc...).

I tried with sanitizing the input data using strip_tags but later realized that it is not what I actually wanted. strip_tags just removed certain portions of the user input text, which is not my aim. For my application to work, all user input data should be stored and displayed as it was entered.

Guys, could you please guide me in the approach I should take?

Re: How to safely allow user to input php code?

Posted: Fri Oct 03, 2008 1:09 am
by The_Anomaly
The others might know better than me, but you just need to escape it really well. If it's fully escaped, it doesn't matter what the user inputs, it's all treated as input and therefore can't be used maliciously.

I've always used PDO (PHP Data Objects) for all of my Database work, and with bound parameters for all of my queries. You get full SQL Injections protection for free, and some other nice features (i.e. database abstraction.).

To quote OWASP:
Open Web Application Security Program wrote: Do not use simple escaping functions, such as PHP's addslashes() or character replacement functions like str_replace("'", ""). These are weak and have been successfully exploited by attackers. . For PHP, use mysql_real_escape_string() if using MySQL, or preferably use PDO which does not require escaping
EDIT: By the way, if you're allowing a user to input text (your code) and then displaying it to other users, you're at a high risk for XSS attacks. Check this out if you need to know more about that.

Re: How to safely allow user to input php code?

Posted: Sat Oct 11, 2008 3:43 am
by betatester
Hi all,

I finally settled for:

Code: Select all

$string = mysql_real_escape_string(addslashes(htmlspecialchars(trim($source))));
and it seems to work fine. Do you experts have any suggestion on this. Can this code be exploited somehow. If yes, kindly tell me how it can be made better.

Re: How to safely allow user to input php code?

Posted: Sat Oct 11, 2008 7:03 am
by Mordred
Try it with a single \

Re: How to safely allow user to input php code?

Posted: Sat Oct 11, 2008 12:41 pm
by betatester
It appears perfectly. 8)

Re: How to safely allow user to input php code?

Posted: Sat Oct 11, 2008 12:54 pm
by Mordred
With the double escaping? So you do stripslashes() on stuff coming from the database?