note 93990 deleted from function.eval by danbrown

From: Date: Sat, 10 Oct 2009 21:00:47 +0000
Subject: note 93990 deleted from function.eval by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-161629@lists.php.net to get a copy of this message
Note Submitter: Crypton - blackcrypton at gmail dot com ---- Slightly midified version of schroeter's script below. I have adapted it to include blacklisting of vars. Useful in cases where you want to allow certain functions to be used, but want to deny access to certains vars that could be used to gain information the user should not see, such as db, sql info etc.. I have included some vars as example. <?php class SaferScript { var $source, $allowedCalls; function SaferScript($scriptText) { $this->source = $scriptText; $this->allowedCalls = array(); $this->blacklistVars = array(); } function allowHarmlessCalls() { // Whitelist overrides case switch below. $this->allowedCalls = explode(',', ' explode,implode,date,time,round,trunc,rand,ceil, floor,srand,strtolower,strtoupper,substr,stristr, strpos,print,print_r,echo' ); $this->blacklistVars = explode(',', 'db,sql,username,password,GLOBALS,_SERVER,_GET,_POST, _FILES_REQUEST,_SESSION,_ENV,_COOKIE,php_errormsg, HTTP_RAW_POST_DATA,http_response_header' ); } function parse() { $this->parseErrors = array(); $tokens = token_get_all('<?'.'php '.$this->source.' ?'.'>'); $vcall = ''; foreach ($tokens as $token) { if (is_array($token)) { $id = $token[0]; switch ($id) { case(T_VARIABLE): { $vcall .= 'v'; break; } case(T_STRING): { $vcall .= 's'; } case(T_NEW): case(T_RETURN): case(T_BREAK): case(T_EXIT): case(T_TRY): case(T_CATCH): case(T_CLONE): case(T_PRINT): case(T_ECHO): case(T_GLOBAL): case(T_INCLUDE): case(T_INCLUDE_ONCE): case(T_REQUIRE): case(T_REQUIRE_ONCE): case(T_FOR): case(T_WHILE): case(T_EVAL): case(T_FUNCTION): { if (array_search($token[1], $this->allowedCalls) === false) { $this->parseErrors[] = 'illegal call: '. $token[1]; } } } } else { $vcall .= $token; } if (stristr($vcall, 'v(') != '') { $this->parseErrors[] = array('Illegal Dynamic Function Call'); } foreach($this->blacklistVars as $blacklisted) { if (strpos($this->source, $blacklisted) !== false) { $this->parseErrors[] = 'Blacklisted Var: '. $blacklisted; } } if (sizeof($this->parseErrors) > 0) { return($this->parseErrors); } } } function execute($parameters = array()) { foreach ($parameters as $k => $v) { $k = $v; } if (sizeof($this->parseErrors) == 0) { eval($this->source); } } } Usage: $mycode = 'echo "Hello World!";'; $test = new SaferScript($mycode); $test->allowHarmlessCalls(); print_r($test->parse()); $test->execute(); ?>

« previous php.notes (#161629) next »