In my application, I want to allow the user to add his own Twig code. But, I don't want it to execute any back-end code (like PHP code to get access to database or files). I have tested using php code <?php print "hello"; ?>
. I can see the PHP code does not execute on the Twig page.
To my knowledge, I can say there is no way to execute PHP code (that can manipulate files or database) in a Twig file unless calling an extension.
But, I just want to know more advises.
You could take a look at the sandbox extension of twig. You can set up a policy and explicitly define each single tag, filter, method, property and function. This was an advice I got after passing my application through a security-penetration-test. You can set it up globally or inside your controller which renders the user twig-input.
https://twig.symfony.com/doc/2.x/tags/sandbox.html
https://twig.symfony.com/doc/2.x/api.html#sandbox-extension
/**
* Adds sandbox limitations to twig-environment to prevent template-injections
*
* @return \Twig_Environment
*/
private function getSandboxedTwigEnvironment()
{
$tags = array('if', 'include', 'import', 'block', 'set', 'for');
$filters = array('date', 'escape', 'trans', 'split', 'length', 'slice', 'lower', 'raw');
$methods = array();
$properties = array();
$functions = array('include', 'path', 'absolute_url', 'asset', 'is_granted');
$policy = new Twig_Sandbox_SecurityPolicy($tags, $filters, $methods, $properties, $functions);
$sandbox = new Twig_Extension_Sandbox($policy);
$twigEnvironment = $this->getCentralService()->getTwigEnvironment();
$twigEnvironment->addExtension($sandbox);
return $twigEnvironment;
}
An exception of Twig_Sandbox_SecurityError will be thrown if any forbidden tags, filter etc were added to the user-input.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With