直接进入内容

安全性

当有不可信方编辑模板并且要降低通过模板语言影响系统安全风险的时候,安全性对于这种情况是好的。

安全策略的设置通过覆写 \Smarty\Security 类的实例中的公有属性来定义。以下是可能的设置

  • $secure_dir是一个被认为安全的模板目录的数组。使用$smarty->setTemplateDir()配置的目录被暗含为安全目录。默认情况是一个空数组。
  • $trusted_uri是一个被认为可信的 URI 的正则表达式匹配数组。此安全指令由 {fetch}{html_image} 使用。传递给这些函数的 URI 会被简化为 {$PROTOCOL}://{$HOSTNAME} 以允许简单的正则表达式(而不必处理认证令牌等边缘情况)。

表达式 '#https?://.*smarty.net$#i' 将允许访问以下 URI

-   `http://smarty.net/foo`
-   `http://smarty.net/foo`
-   `https://smarty.php.net/foo`
-   `http://smarty.net/foo`
-   `https://foo.bar.www.smarty.net/foo/bla?blubb=1`

但拒绝访问这些 URI

-   `http://smarty.com/foo` (not matching top-level domain \"com\")
-   `ftp://smarty.php.net/foo` (not matching protocol \"ftp\")
-   `https://smarty.php.ac.cn.otherdomain.com/foo` (not matching end of
    domain \"smarty.net\")
  • $static_classes是被认为可信的类的数组。默认情况下是一个空数组,它允许访问所有静态类。要禁用对所有静态类的访问,请将 $static_classes = null。

  • $streams 是一系列被视为受信任,且可在模板内使用的流。要禁用对所有流的访问,请将 $streams 设置为 null。一个空数组 ( $streams = [] ) 将允许所有流。默认值为数组('file')。

  • $allowed_modifiers 是应能让模板访问的一系列(已注册 / 已自动加载)的修饰符。如果此数组是非空的,则只能使用在此列出的修饰符。这是一个白名单。

  • $disabled_modifiers 是不能让模板访问的一系列(已注册 / 已自动加载)的修饰符。

  • $allowed_tags 是一个布尔值标志,它控制函数、块和过滤器插件(应能让模板访问)是否可用。如果此数组是非空的,则只能使用在此列出的修饰符。这是一个白名单。

  • $disabled_tags 是不能让模板访问的一系列(已注册 / 已自动加载)的函数、块和过滤器插件。

  • $allow_constants 是一个布尔值标志,它控制模板是否可访问常量。默认值为“true”。

  • $allow_super_globals 是一个布尔值标志,它控制模板是否可访问 PHP 超级全局变量。默认值为“true”。

如果启用了安全,则模板不能访问静态类或已分配对象的私有方法、函数或属性(以‘_’开头)。

要自定义安全策略设置,你可以扩展 \Smarty\Security 类或创建一个它的实例。

<?php

use Smarty\Smarty;

class My_Security_Policy extends \Smarty\Security {
  public $allow_constants = false;
}

$smarty = new Smarty();

$smarty->enableSecurity('My_Security_Policy');
<?php

use Smarty\Smarty;

$smarty = new Smarty();

$my_security_policy = new \Smarty\Security($smarty);
$my_security_policy->allow_constants = false;

$smarty->enableSecurity($my_security_policy);
<?php

use Smarty\Smarty;

$smarty = new Smarty();

// enable default security
$smarty->enableSecurity();

注意

大多数安全策略设置仅在模板被编译时才会被检查。因此,当你更改安全设置时,你应当删除所有缓存的和已编译的模板文件。