smarty_security.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721
  1. <?php
  2. /**
  3. * Smarty plugin
  4. *
  5. * @package Smarty
  6. * @subpackage Security
  7. * @author Uwe Tews
  8. */
  9. /**
  10. * FIXME: Smarty_Security API
  11. * - getter and setter instead of public properties would allow cultivating an internal cache properly
  12. * - current implementation of isTrustedResourceDir() assumes that Smarty::$template_dir and Smarty::$config_dir
  13. * are immutable the cache is killed every time either of the variables change. That means that two distinct
  14. * Smarty objects with differing
  15. * $template_dir or $config_dir should NOT share the same Smarty_Security instance,
  16. * as this would lead to (severe) performance penalty! how should this be handled?
  17. */
  18. /**
  19. * This class does contain the security settings
  20. */
  21. class Smarty_Security
  22. {
  23. /**
  24. * This determines how Smarty handles "<?php ... ?>" tags in templates.
  25. * possible values:
  26. * <ul>
  27. * <li>Smarty::PHP_PASSTHRU -> echo PHP tags as they are</li>
  28. * <li>Smarty::PHP_QUOTE -> escape tags as entities</li>
  29. * <li>Smarty::PHP_REMOVE -> remove php tags</li>
  30. * <li>Smarty::PHP_ALLOW -> execute php tags</li>
  31. * </ul>
  32. *
  33. * @var integer
  34. */
  35. public $php_handling = Smarty::PHP_PASSTHRU;
  36. /**
  37. * This is the list of template directories that are considered secure.
  38. * $template_dir is in this list implicitly.
  39. *
  40. * @var array
  41. */
  42. public $secure_dir = array();
  43. /**
  44. * This is an array of directories where trusted php scripts reside.
  45. * {@link $security} is disabled during their inclusion/execution.
  46. *
  47. * @var array
  48. */
  49. public $trusted_dir = array();
  50. /**
  51. * List of regular expressions (PCRE) that include trusted URIs
  52. *
  53. * @var array
  54. */
  55. public $trusted_uri = array();
  56. /**
  57. * List of trusted constants names
  58. *
  59. * @var array
  60. */
  61. public $trusted_constants = array();
  62. /**
  63. * This is an array of trusted static classes.
  64. * If empty access to all static classes is allowed.
  65. * If set to 'none' none is allowed.
  66. *
  67. * @var array
  68. */
  69. public $static_classes = array();
  70. /**
  71. * This is an nested array of trusted classes and static methods.
  72. * If empty access to all static classes and methods is allowed.
  73. * Format:
  74. * array (
  75. * 'class_1' => array('method_1', 'method_2'), // allowed methods listed
  76. * 'class_2' => array(), // all methods of class allowed
  77. * )
  78. * If set to null none is allowed.
  79. *
  80. * @var array
  81. */
  82. public $trusted_static_methods = array();
  83. /**
  84. * This is an array of trusted static properties.
  85. * If empty access to all static classes and properties is allowed.
  86. * Format:
  87. * array (
  88. * 'class_1' => array('prop_1', 'prop_2'), // allowed properties listed
  89. * 'class_2' => array(), // all properties of class allowed
  90. * )
  91. * If set to null none is allowed.
  92. *
  93. * @var array
  94. */
  95. public $trusted_static_properties = array();
  96. /**
  97. * This is an array of trusted PHP functions.
  98. * If empty all functions are allowed.
  99. * To disable all PHP functions set $php_functions = null.
  100. *
  101. * @var array
  102. */
  103. public $php_functions = array('isset', 'empty', 'count', 'sizeof', 'in_array', 'is_array', 'time',);
  104. /**
  105. * This is an array of trusted PHP modifiers.
  106. * If empty all modifiers are allowed.
  107. * To disable all modifier set $php_modifiers = null.
  108. *
  109. * @var array
  110. */
  111. public $php_modifiers = array('escape', 'count', 'nl2br',);
  112. /**
  113. * This is an array of allowed tags.
  114. * If empty no restriction by allowed_tags.
  115. *
  116. * @var array
  117. */
  118. public $allowed_tags = array();
  119. /**
  120. * This is an array of disabled tags.
  121. * If empty no restriction by disabled_tags.
  122. *
  123. * @var array
  124. */
  125. public $disabled_tags = array();
  126. /**
  127. * This is an array of allowed modifier plugins.
  128. * If empty no restriction by allowed_modifiers.
  129. *
  130. * @var array
  131. */
  132. public $allowed_modifiers = array();
  133. /**
  134. * This is an array of disabled modifier plugins.
  135. * If empty no restriction by disabled_modifiers.
  136. *
  137. * @var array
  138. */
  139. public $disabled_modifiers = array();
  140. /**
  141. * This is an array of disabled special $smarty variables.
  142. *
  143. * @var array
  144. */
  145. public $disabled_special_smarty_vars = array();
  146. /**
  147. * This is an array of trusted streams.
  148. * If empty all streams are allowed.
  149. * To disable all streams set $streams = null.
  150. *
  151. * @var array
  152. */
  153. public $streams = array('file');
  154. /**
  155. * + flag if constants can be accessed from template
  156. *
  157. * @var boolean
  158. */
  159. public $allow_constants = true;
  160. /**
  161. * + flag if super globals can be accessed from template
  162. *
  163. * @var boolean
  164. */
  165. public $allow_super_globals = true;
  166. /**
  167. * max template nesting level
  168. *
  169. * @var int
  170. */
  171. public $max_template_nesting = 0;
  172. /**
  173. * current template nesting level
  174. *
  175. * @var int
  176. */
  177. private $_current_template_nesting = 0;
  178. /**
  179. * Cache for $resource_dir lookup
  180. *
  181. * @var array
  182. */
  183. protected $_resource_dir = array();
  184. /**
  185. * Cache for $template_dir lookup
  186. *
  187. * @var array
  188. */
  189. protected $_template_dir = array();
  190. /**
  191. * Cache for $config_dir lookup
  192. *
  193. * @var array
  194. */
  195. protected $_config_dir = array();
  196. /**
  197. * Cache for $secure_dir lookup
  198. *
  199. * @var array
  200. */
  201. protected $_secure_dir = array();
  202. /**
  203. * Cache for $php_resource_dir lookup
  204. *
  205. * @var array
  206. */
  207. protected $_php_resource_dir = null;
  208. /**
  209. * Cache for $trusted_dir lookup
  210. *
  211. * @var array
  212. */
  213. protected $_trusted_dir = null;
  214. /**
  215. * Cache for include path status
  216. *
  217. * @var bool
  218. */
  219. protected $_include_path_status = false;
  220. /**
  221. * Cache for $_include_array lookup
  222. *
  223. * @var array
  224. */
  225. protected $_include_dir = array();
  226. /**
  227. * @param Smarty $smarty
  228. */
  229. public function __construct($smarty)
  230. {
  231. $this->smarty = $smarty;
  232. }
  233. /**
  234. * Check if PHP function is trusted.
  235. *
  236. * @param string $function_name
  237. * @param object $compiler compiler object
  238. *
  239. * @return boolean true if function is trusted
  240. */
  241. public function isTrustedPhpFunction($function_name, $compiler)
  242. {
  243. if (isset($this->php_functions)
  244. && (empty($this->php_functions) || in_array($function_name, $this->php_functions))
  245. ) {
  246. return true;
  247. }
  248. $compiler->trigger_template_error("PHP function '{$function_name}' not allowed by security setting");
  249. return false; // should not, but who knows what happens to the compiler in the future?
  250. }
  251. /**
  252. * Check if static class is trusted.
  253. *
  254. * @param string $class_name
  255. * @param object $compiler compiler object
  256. *
  257. * @return boolean true if class is trusted
  258. */
  259. public function isTrustedStaticClass($class_name, $compiler)
  260. {
  261. if (isset($this->static_classes)
  262. && (empty($this->static_classes) || in_array($class_name, $this->static_classes))
  263. ) {
  264. return true;
  265. }
  266. $compiler->trigger_template_error("access to static class '{$class_name}' not allowed by security setting");
  267. return false; // should not, but who knows what happens to the compiler in the future?
  268. }
  269. /**
  270. * Check if static class method/property is trusted.
  271. *
  272. * @param string $class_name
  273. * @param string $params
  274. * @param object $compiler compiler object
  275. *
  276. * @return boolean true if class method is trusted
  277. */
  278. public function isTrustedStaticClassAccess($class_name, $params, $compiler)
  279. {
  280. if (!isset($params[ 2 ])) {
  281. // fall back
  282. return $this->isTrustedStaticClass($class_name, $compiler);
  283. }
  284. if ($params[ 2 ] === 'method') {
  285. $allowed = $this->trusted_static_methods;
  286. $name = substr($params[ 0 ], 0, strpos($params[ 0 ], '('));
  287. } else {
  288. $allowed = $this->trusted_static_properties;
  289. // strip '$'
  290. $name = substr($params[ 0 ], 1);
  291. }
  292. if (isset($allowed)) {
  293. if (empty($allowed)) {
  294. // fall back
  295. return $this->isTrustedStaticClass($class_name, $compiler);
  296. }
  297. if (isset($allowed[ $class_name ])
  298. && (empty($allowed[ $class_name ]) || in_array($name, $allowed[ $class_name ]))
  299. ) {
  300. return true;
  301. }
  302. }
  303. $compiler->trigger_template_error("access to static class '{$class_name}' {$params[2]} '{$name}' not allowed by security setting");
  304. return false; // should not, but who knows what happens to the compiler in the future?
  305. }
  306. /**
  307. * Check if PHP modifier is trusted.
  308. *
  309. * @param string $modifier_name
  310. * @param object $compiler compiler object
  311. *
  312. * @return boolean true if modifier is trusted
  313. */
  314. public function isTrustedPhpModifier($modifier_name, $compiler)
  315. {
  316. if (isset($this->php_modifiers)
  317. && (empty($this->php_modifiers) || in_array($modifier_name, $this->php_modifiers))
  318. ) {
  319. return true;
  320. }
  321. $compiler->trigger_template_error("modifier '{$modifier_name}' not allowed by security setting");
  322. return false; // should not, but who knows what happens to the compiler in the future?
  323. }
  324. /**
  325. * Check if tag is trusted.
  326. *
  327. * @param string $tag_name
  328. * @param object $compiler compiler object
  329. *
  330. * @return boolean true if tag is trusted
  331. */
  332. public function isTrustedTag($tag_name, $compiler)
  333. {
  334. // check for internal always required tags
  335. if (in_array(
  336. $tag_name,
  337. array(
  338. 'assign', 'call', 'private_filter', 'private_block_plugin', 'private_function_plugin',
  339. 'private_object_block_function', 'private_object_function', 'private_registered_function',
  340. 'private_registered_block', 'private_special_variable', 'private_print_expression',
  341. 'private_modifier'
  342. )
  343. )
  344. ) {
  345. return true;
  346. }
  347. // check security settings
  348. if (empty($this->allowed_tags)) {
  349. if (empty($this->disabled_tags) || !in_array($tag_name, $this->disabled_tags)) {
  350. return true;
  351. } else {
  352. $compiler->trigger_template_error("tag '{$tag_name}' disabled by security setting", null, true);
  353. }
  354. } elseif (in_array($tag_name, $this->allowed_tags) && !in_array($tag_name, $this->disabled_tags)) {
  355. return true;
  356. } else {
  357. $compiler->trigger_template_error("tag '{$tag_name}' not allowed by security setting", null, true);
  358. }
  359. return false; // should not, but who knows what happens to the compiler in the future?
  360. }
  361. /**
  362. * Check if special $smarty variable is trusted.
  363. *
  364. * @param string $var_name
  365. * @param object $compiler compiler object
  366. *
  367. * @return boolean true if tag is trusted
  368. */
  369. public function isTrustedSpecialSmartyVar($var_name, $compiler)
  370. {
  371. if (!in_array($var_name, $this->disabled_special_smarty_vars)) {
  372. return true;
  373. } else {
  374. $compiler->trigger_template_error(
  375. "special variable '\$smarty.{$var_name}' not allowed by security setting",
  376. null,
  377. true
  378. );
  379. }
  380. return false; // should not, but who knows what happens to the compiler in the future?
  381. }
  382. /**
  383. * Check if modifier plugin is trusted.
  384. *
  385. * @param string $modifier_name
  386. * @param object $compiler compiler object
  387. *
  388. * @return boolean true if tag is trusted
  389. */
  390. public function isTrustedModifier($modifier_name, $compiler)
  391. {
  392. // check for internal always allowed modifier
  393. if (in_array($modifier_name, array('default'))) {
  394. return true;
  395. }
  396. // check security settings
  397. if (empty($this->allowed_modifiers)) {
  398. if (empty($this->disabled_modifiers) || !in_array($modifier_name, $this->disabled_modifiers)) {
  399. return true;
  400. } else {
  401. $compiler->trigger_template_error(
  402. "modifier '{$modifier_name}' disabled by security setting",
  403. null,
  404. true
  405. );
  406. }
  407. } elseif (in_array($modifier_name, $this->allowed_modifiers)
  408. && !in_array($modifier_name, $this->disabled_modifiers)
  409. ) {
  410. return true;
  411. } else {
  412. $compiler->trigger_template_error(
  413. "modifier '{$modifier_name}' not allowed by security setting",
  414. null,
  415. true
  416. );
  417. }
  418. return false; // should not, but who knows what happens to the compiler in the future?
  419. }
  420. /**
  421. * Check if constants are enabled or trusted
  422. *
  423. * @param string $const constant name
  424. * @param object $compiler compiler object
  425. *
  426. * @return bool
  427. */
  428. public function isTrustedConstant($const, $compiler)
  429. {
  430. if (in_array($const, array('true', 'false', 'null'))) {
  431. return true;
  432. }
  433. if (!empty($this->trusted_constants)) {
  434. if (!in_array(strtolower($const), $this->trusted_constants)) {
  435. $compiler->trigger_template_error("Security: access to constant '{$const}' not permitted");
  436. return false;
  437. }
  438. return true;
  439. }
  440. if ($this->allow_constants) {
  441. return true;
  442. }
  443. $compiler->trigger_template_error("Security: access to constants not permitted");
  444. return false;
  445. }
  446. /**
  447. * Check if stream is trusted.
  448. *
  449. * @param string $stream_name
  450. *
  451. * @return boolean true if stream is trusted
  452. * @throws SmartyException if stream is not trusted
  453. */
  454. public function isTrustedStream($stream_name)
  455. {
  456. if (isset($this->streams) && (empty($this->streams) || in_array($stream_name, $this->streams))) {
  457. return true;
  458. }
  459. throw new SmartyException("stream '{$stream_name}' not allowed by security setting");
  460. }
  461. /**
  462. * Check if directory of file resource is trusted.
  463. *
  464. * @param string $filepath
  465. * @param null|bool $isConfig
  466. *
  467. * @return bool true if directory is trusted
  468. * @throws \SmartyException if directory is not trusted
  469. */
  470. public function isTrustedResourceDir($filepath, $isConfig = null)
  471. {
  472. if ($this->_include_path_status !== $this->smarty->use_include_path) {
  473. $_dir =
  474. $this->smarty->use_include_path ? $this->smarty->ext->_getIncludePath->getIncludePathDirs($this->smarty) : array();
  475. if ($this->_include_dir !== $_dir) {
  476. $this->_updateResourceDir($this->_include_dir, $_dir);
  477. $this->_include_dir = $_dir;
  478. }
  479. $this->_include_path_status = $this->smarty->use_include_path;
  480. }
  481. $_dir = $this->smarty->getTemplateDir();
  482. if ($this->_template_dir !== $_dir) {
  483. $this->_updateResourceDir($this->_template_dir, $_dir);
  484. $this->_template_dir = $_dir;
  485. }
  486. $_dir = $this->smarty->getConfigDir();
  487. if ($this->_config_dir !== $_dir) {
  488. $this->_updateResourceDir($this->_config_dir, $_dir);
  489. $this->_config_dir = $_dir;
  490. }
  491. if ($this->_secure_dir !== $this->secure_dir) {
  492. $this->secure_dir = (array)$this->secure_dir;
  493. foreach ($this->secure_dir as $k => $d) {
  494. $this->secure_dir[ $k ] = $this->smarty->_realpath($d . DIRECTORY_SEPARATOR, true);
  495. }
  496. $this->_updateResourceDir($this->_secure_dir, $this->secure_dir);
  497. $this->_secure_dir = $this->secure_dir;
  498. }
  499. $addPath = $this->_checkDir($filepath, $this->_resource_dir);
  500. if ($addPath !== false) {
  501. $this->_resource_dir = array_merge($this->_resource_dir, $addPath);
  502. }
  503. return true;
  504. }
  505. /**
  506. * Check if URI (e.g. {fetch} or {html_image}) is trusted
  507. * To simplify things, isTrustedUri() resolves all input to "{$PROTOCOL}://{$HOSTNAME}".
  508. * So "http://username:password@hello.world.example.org:8080/some-path?some=query-string"
  509. * is reduced to "http://hello.world.example.org" prior to applying the patters from {@link $trusted_uri}.
  510. *
  511. * @param string $uri
  512. *
  513. * @return boolean true if URI is trusted
  514. * @throws SmartyException if URI is not trusted
  515. * @uses $trusted_uri for list of patterns to match against $uri
  516. */
  517. public function isTrustedUri($uri)
  518. {
  519. $_uri = parse_url($uri);
  520. if (!empty($_uri[ 'scheme' ]) && !empty($_uri[ 'host' ])) {
  521. $_uri = $_uri[ 'scheme' ] . '://' . $_uri[ 'host' ];
  522. foreach ($this->trusted_uri as $pattern) {
  523. if (preg_match($pattern, $_uri)) {
  524. return true;
  525. }
  526. }
  527. }
  528. throw new SmartyException("URI '{$uri}' not allowed by security setting");
  529. }
  530. /**
  531. * Check if directory of file resource is trusted.
  532. *
  533. * @param string $filepath
  534. *
  535. * @return boolean true if directory is trusted
  536. * @throws SmartyException if PHP directory is not trusted
  537. */
  538. public function isTrustedPHPDir($filepath)
  539. {
  540. if (empty($this->trusted_dir)) {
  541. throw new SmartyException("directory '{$filepath}' not allowed by security setting (no trusted_dir specified)");
  542. }
  543. // check if index is outdated
  544. if (!$this->_trusted_dir || $this->_trusted_dir !== $this->trusted_dir) {
  545. $this->_php_resource_dir = array();
  546. $this->_trusted_dir = $this->trusted_dir;
  547. foreach ((array)$this->trusted_dir as $directory) {
  548. $directory = $this->smarty->_realpath($directory . '/', true);
  549. $this->_php_resource_dir[ $directory ] = true;
  550. }
  551. }
  552. $addPath = $this->_checkDir($filepath, $this->_php_resource_dir);
  553. if ($addPath !== false) {
  554. $this->_php_resource_dir = array_merge($this->_php_resource_dir, $addPath);
  555. }
  556. return true;
  557. }
  558. /**
  559. * Remove old directories and its sub folders, add new directories
  560. *
  561. * @param array $oldDir
  562. * @param array $newDir
  563. */
  564. private function _updateResourceDir($oldDir, $newDir)
  565. {
  566. foreach ($oldDir as $directory) {
  567. // $directory = $this->smarty->_realpath($directory, true);
  568. $length = strlen($directory);
  569. foreach ($this->_resource_dir as $dir) {
  570. if (substr($dir, 0, $length) === $directory) {
  571. unset($this->_resource_dir[ $dir ]);
  572. }
  573. }
  574. }
  575. foreach ($newDir as $directory) {
  576. // $directory = $this->smarty->_realpath($directory, true);
  577. $this->_resource_dir[ $directory ] = true;
  578. }
  579. }
  580. /**
  581. * Check if file is inside a valid directory
  582. *
  583. * @param string $filepath
  584. * @param array $dirs valid directories
  585. *
  586. * @return array|bool
  587. * @throws \SmartyException
  588. */
  589. private function _checkDir($filepath, $dirs)
  590. {
  591. $directory = dirname($this->smarty->_realpath($filepath, true)) . DIRECTORY_SEPARATOR;
  592. $_directory = array();
  593. if (!preg_match('#[\\\\/][.][.][\\\\/]#', $directory)) {
  594. while (true) {
  595. // test if the directory is trusted
  596. if (isset($dirs[ $directory ])) {
  597. return $_directory;
  598. }
  599. // abort if we've reached root
  600. if (!preg_match('#[\\\\/][^\\\\/]+[\\\\/]$#', $directory)) {
  601. // give up
  602. break;
  603. }
  604. // remember the directory to add it to _resource_dir in case we're successful
  605. $_directory[ $directory ] = true;
  606. // bubble up one level
  607. $directory = preg_replace('#[\\\\/][^\\\\/]+[\\\\/]$#', DIRECTORY_SEPARATOR, $directory);
  608. }
  609. }
  610. // give up
  611. throw new SmartyException(sprintf('Smarty Security: not trusted file path \'%s\' ', $filepath));
  612. }
  613. /**
  614. * Loads security class and enables security
  615. *
  616. * @param \Smarty $smarty
  617. * @param string|Smarty_Security $security_class if a string is used, it must be class-name
  618. *
  619. * @return \Smarty current Smarty instance for chaining
  620. * @throws \SmartyException when an invalid class name is provided
  621. */
  622. public static function enableSecurity(Smarty $smarty, $security_class)
  623. {
  624. if ($security_class instanceof Smarty_Security) {
  625. $smarty->security_policy = $security_class;
  626. return $smarty;
  627. } elseif (is_object($security_class)) {
  628. throw new SmartyException("Class '" . get_class($security_class) . "' must extend Smarty_Security.");
  629. }
  630. if ($security_class === null) {
  631. $security_class = $smarty->security_class;
  632. }
  633. if (!class_exists($security_class)) {
  634. throw new SmartyException("Security class '$security_class' is not defined");
  635. } elseif ($security_class !== 'Smarty_Security' && !is_subclass_of($security_class, 'Smarty_Security')) {
  636. throw new SmartyException("Class '$security_class' must extend Smarty_Security.");
  637. } else {
  638. $smarty->security_policy = new $security_class($smarty);
  639. }
  640. return $smarty;
  641. }
  642. /**
  643. * Start template processing
  644. *
  645. * @param $template
  646. *
  647. * @throws SmartyException
  648. */
  649. public function startTemplate($template)
  650. {
  651. if ($this->max_template_nesting > 0 && $this->_current_template_nesting++ >= $this->max_template_nesting) {
  652. throw new SmartyException("maximum template nesting level of '{$this->max_template_nesting}' exceeded when calling '{$template->template_resource}'");
  653. }
  654. }
  655. /**
  656. * Exit template processing
  657. */
  658. public function endTemplate()
  659. {
  660. if ($this->max_template_nesting > 0) {
  661. $this->_current_template_nesting--;
  662. }
  663. }
  664. /**
  665. * Register callback functions call at start/end of template rendering
  666. *
  667. * @param \Smarty_Internal_Template $template
  668. */
  669. public function registerCallBacks(Smarty_Internal_Template $template)
  670. {
  671. $template->startRenderCallbacks[] = array($this, 'startTemplate');
  672. $template->endRenderCallbacks[] = array($this, 'endTemplate');
  673. }
  674. }