trusteddomainhelper.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. /**
  3. * @author Lukas Reschke <lukas@owncloud.com>
  4. * @author Morris Jobke <hey@morrisjobke.de>
  5. *
  6. * @copyright Copyright (c) 2015, ownCloud, Inc.
  7. * @license AGPL-3.0
  8. *
  9. * This code is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU Affero General Public License, version 3,
  11. * as published by the Free Software Foundation.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU Affero General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Affero General Public License, version 3,
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>
  20. *
  21. */
  22. namespace OC\Security;
  23. use OC\AppFramework\Http\Request;
  24. use OCP\IConfig;
  25. /**
  26. * Class TrustedDomain
  27. *
  28. * @package OC\Security
  29. */
  30. class TrustedDomainHelper {
  31. /** @var IConfig */
  32. private $config;
  33. /**
  34. * @param IConfig $config
  35. */
  36. function __construct(IConfig $config) {
  37. $this->config = $config;
  38. }
  39. /**
  40. * Strips a potential port from a domain (in format domain:port)
  41. * @param string $host
  42. * @return string $host without appended port
  43. */
  44. private function getDomainWithoutPort($host) {
  45. $pos = strrpos($host, ':');
  46. if ($pos !== false) {
  47. $port = substr($host, $pos + 1);
  48. if (is_numeric($port)) {
  49. $host = substr($host, 0, $pos);
  50. }
  51. }
  52. return $host;
  53. }
  54. /**
  55. * Checks whether a domain is considered as trusted from the list
  56. * of trusted domains. If no trusted domains have been configured, returns
  57. * true.
  58. * This is used to prevent Host Header Poisoning.
  59. * @param string $domainWithPort
  60. * @return bool true if the given domain is trusted or if no trusted domains
  61. * have been configured
  62. */
  63. public function isTrustedDomain($domainWithPort) {
  64. $domain = $this->getDomainWithoutPort($domainWithPort);
  65. // Read trusted domains from config
  66. $trustedList = $this->config->getSystemValue('trusted_domains', []);
  67. if(!is_array($trustedList)) {
  68. return false;
  69. }
  70. // TODO: Workaround for older instances still with port applied. Remove for ownCloud 9.
  71. if(in_array($domainWithPort, $trustedList)) {
  72. return true;
  73. }
  74. // Always allow access from localhost
  75. if (preg_match(Request::REGEX_LOCALHOST, $domain) === 1) {
  76. return true;
  77. }
  78. return in_array($domain, $trustedList);
  79. }
  80. }