prevent_csrf.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. $check_csrf = true;
  3. if ($_SERVER['SCRIPT_FILENAME'] == '/usr/local/hestia/web/inc/mail-wrapper.php ') {
  4. $check_csrf=false;
  5. } // execute only from CLI
  6. if ($_SERVER['SCRIPT_FILENAME'] == '/usr/local/hestia/web/reset/mail/index.php ') {
  7. $check_csrf=false;
  8. } // Localhost only
  9. if ($_SERVER['SCRIPT_FILENAME'] == '/usr/local/hestia/web/api/index.php') {
  10. $check_csrf=false;
  11. } // Own check
  12. if (substr($_SERVER['SCRIPT_FILENAME'], 0, 22)=='/usr/local/hestia/bin/') {
  13. $check_csrf=false;
  14. }
  15. function checkStrictness($level)
  16. {
  17. if ($level >= $_SESSION['POLICY_CSRF_STRICTNESS']) {
  18. return true;
  19. } else {
  20. echo "<h1>Potential use CSRF detected</h1>\n".
  21. "<p>Please disable any plugins/add-ons inside your browser or contact your system administrator. If you are the system administrator you can run v-change-sys-config-value 'POLICY_CSRF_STRICTNESS' '0' as root to disable this check.<p>".
  22. "<p>If you folowed a bookmark or an static link <a href='/'>please click here</a>";
  23. die();
  24. }
  25. }
  26. function prevent_post_csrf()
  27. {
  28. if ($_SERVER['REQUEST_METHOD']==='POST') {
  29. $hostname = explode(':', $_SERVER['HTTP_HOST']);
  30. $port=$hostname[1];
  31. $hostname=$hostname[0];
  32. if (strpos($_SERVER['HTTP_ORIGIN'], gethostname()) !== false && in_array($port, array('443',$_SERVER['SERVER_PORT']))) {
  33. return checkStrictness(2);
  34. } else {
  35. if (strpos($_SERVER['HTTP_ORIGIN'], $hostname) !== false && in_array($port, array('443',$_SERVER['SERVER_PORT']))) {
  36. return checkStrictness(1);
  37. } else {
  38. return checkStrictness(0);
  39. }
  40. }
  41. }
  42. }
  43. function prevent_get_csrf()
  44. {
  45. if ($_SERVER['REQUEST_METHOD']==='GET') {
  46. $hostname = explode(':', $_SERVER['HTTP_HOST']);
  47. $port=$hostname[1];
  48. $hostname=$hostname[0];
  49. //list of possible entries route and these should never be blocked
  50. if (in_array($_SERVER['DOCUMENT_URI'], array('/list/user/index.php', '/login/index.php','/list/web/index.php','/list/dns/index.php','/list/mail/index.php','/list/db/index.php','/list/cron/index.php','/list/backup/index.php','/reset/index.php'))) {
  51. return true;
  52. }
  53. if (strpos($_SERVER['HTTP_REFERER'], gethostname()) !== false && in_array($port, array('443',$_SERVER['SERVER_PORT']))) {
  54. return checkStrictness(2);
  55. } else {
  56. if (strpos($_SERVER['HTTP_REFERER'], $hostname) !== false && in_array($port, array('443',$_SERVER['SERVER_PORT']))) {
  57. return checkStrictness(1);
  58. } else {
  59. return checkStrictness(0);
  60. }
  61. }
  62. }
  63. }
  64. if ($check_csrf == true) {
  65. prevent_post_csrf();
  66. prevent_get_csrf();
  67. }