在我的应用程序中,我想允许用户添加自己的Twig代码.但是,我不希望它执行任何后端代码(如PHP代码来访问数据库或文件).我已经测试过使用PHP代码<?php print "hello"; ?>.我可以看到PHP代码没有在Twig页面上执行.
据我所知,我可以说除非调用扩展名,否则无法在Twig文件中执行PHP代码(可以操作文件或数据库).
但是,我只想知道更多的建议.
你可以看一下树枝的沙箱延伸.您可以设置策略并明确定义每个标记,过滤器,方法,属性和功能.这是我通过安全渗透测试通过我的应用程序后得到的建议.您可以在全局或控制器内部设置它,从而呈现用户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;
}
Run Code Online (Sandbox Code Playgroud)
如果向用户输入添加了任何禁用标记,过滤器等,则会抛出Twig_Sandbox_SecurityError的异常.
| 归档时间: |
|
| 查看次数: |
310 次 |
| 最近记录: |