M
M
Maxim Anarchistov2016-03-11 13:39:46
PHP
Maxim Anarchistov, 2016-03-11 13:39:46

How to safely execute PHP source code from a string?

The bottom line is: I write a pseudo-code parser in PHP code (which should call some methods I defined and standard if, for, else, etc), and after that this code will run a fairly large number of times in a row (which, with heavy code, can create a serious load on server).
At the moment, the scheme is implemented:
The user writes a pseudocode that is written to a string -> The pseudocode is converted into PHP code -> at the right time, I run this pseudocode with the eval() function.
But this option is dangerous because during the work of the parser, situations may arise when the user can run malicious code. Therefore, there are several options:
1. Dig towards callable
2. Use one of the options from the article https://habrahabr.ru/post/215139/.Not very good, because it slows down the execution of the code, and it does not become more secure.
3. Use eval, but strengthen the check at the conversion stage.
4. Look for other options.
What option would you suggest?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
M
Mikhail Osher, 2016-03-11
@ozonar

Generate code, parse with this library .
Filter certain features.

Y
Yuri, 2016-03-11
@riky

did a similar thing myself recently, compiler from pseudocode to php.
I had thousands of functions at the input that editors could edit, all formulas were compiled into one php class in the form of methods. this file was then included.
it is better to filter malicious functions at the stage of analyzing pseudocode and compiling php, and not nikic parser. although, of course, if your conversion is done by regular expressions, then of course there is no way without it.

G
Grigory Esin, 2016-03-11
@xotey83

Keywords: eval, runkit

S
Sergey, 2016-03-11
Protko @Fesor

1) isolate the code in the sandbox, pass as arguments only what can be used ( php.net/manual/en/function.create-function.php)
2) use, for example, nick/php-parser and make sure that things are not used type global

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question