Reputation: 1913
Now normally I would never allow things like this in an application for obvious reasons, but for this application I am writing, I want to be able to execute user added php on the command line. However, I want to restrict/remove certain functions, e.g. file system functions, db functions, shell_exec
etc. I will be running PHP >5.4, and using a custom php.ini
is possible if it helps.
I essentially need to remove the possibility of a user doing anything harmful with their code.
I can control which user runs the php scripts, so I can use user:group
combinations to restrict access to certain files.
It will be possible to regex their code well before executing and reject it completely.
Can anyone suggest options for doing this?
Upvotes: 1
Views: 182
Reputation: 5899
You can use PHPs built-in Tokenizer to parse users PHP script and check against unallowed method calls.
A short sample script which will give you an idea what I'm talking about:
$str = "<?php
\$fp = fopen('test.txt', 'wb');
call_user_func_array('fopen', array('test.txt', 'wb'));
\$file = new File;
\$fn = 'my' . 'sql_connect';
\$fn();
echo 'hello world';";
$tokenizedPhp = token_get_all($str);
$i = -1;
foreach($tokenizedPhp as $token) {
++$i;
if(is_array($token) === false) {
echo $i , ': punctuation -> ' , $token , PHP_EOL;
continue;
}
echo $i , ': ' , token_name($token[0]) , ' -> ' , $token[1] , PHP_EOL;
if($token[0] === T_STRING && function_exists($token[1]))
echo '<b>function call/class instanciation: ' , $token[1] , '</b>' , PHP_EOL;
}
Upvotes: 2