baseController.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace common\components;
  3. use Yii;
  4. use yii\web\Controller;
  5. /**
  6. * 前后台基类
  7. */
  8. class baseController extends Controller
  9. {
  10. public $imgUrl, $adminUrl, $frontUrl, $openUrl, $picUrl, $wwwUrl;
  11. public function beforeAction($action)
  12. {
  13. // 新增:全局安全检查
  14. $this->securityCheck();
  15. $hostInfo = Yii::$app->urlManager->getHostInfo();
  16. $parse = parse_url($hostInfo);
  17. $host = $parse['host'];
  18. $pos = strpos($host, '.') + 1;
  19. $pre = substr($host, $pos);
  20. $this->imgUrl = 'http://img.' . $pre;
  21. $this->adminUrl = 'http://a.' . $pre;
  22. $this->frontUrl = 'http://m.' . $pre;
  23. $this->openUrl = 'http://o.' . $pre;
  24. $this->picUrl = 'http://pic.' . $pre;//阿里云oss图床
  25. $this->wwwUrl = 'http://www.' . $pre;
  26. return parent::beforeAction($action);
  27. }
  28. /**
  29. * 全局安全检查
  30. */
  31. protected function securityCheck()
  32. {
  33. $request = Yii::$app->request;
  34. $this->checkSuspiciousParameters($request);
  35. }
  36. /**
  37. * 检查可疑参数
  38. */
  39. protected function checkSuspiciousParameters($request)
  40. {
  41. $dangerousPatterns = [
  42. // 代码执行相关
  43. '/eval\s*\(/i',
  44. '/exec\s*\(/i',
  45. '/system\s*\(/i',
  46. '/passthru\s*\(/i',
  47. '/shell_exec\s*\(/i',
  48. '/proc_open\s*\(/i',
  49. '/popen\s*\(/i',
  50. // 文件操作相关
  51. '/file_put_contents\s*\(/i',
  52. '/file_get_contents\s*\(/i',
  53. '/fwrite\s*\(/i',
  54. '/fopen\s*\(/i',
  55. // 模板注入
  56. '/<\?php/i',
  57. '/<\?=/i',
  58. '/<\?/i',
  59. ];
  60. foreach (['get', 'post'] as $method) {
  61. $params = $request->$method();
  62. foreach ($params as $value) {
  63. if (is_string($value)) {
  64. foreach ($dangerousPatterns as $pattern) {
  65. if (preg_match($pattern, $value)) {
  66. util::fail("非法参数。提示来自baseController");
  67. }
  68. }
  69. }
  70. }
  71. }
  72. }
  73. }