baseController.php 2.2 KB

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