Request.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. *
  6. * @author b108@volgograd "b108@volgograd"
  7. * @author Bart Visscher <bartv@thisnet.nl>
  8. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  9. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  10. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  11. * @author Georg Ehrke <oc.list@georgehrke.com>
  12. * @author J0WI <J0WI@users.noreply.github.com>
  13. * @author Joas Schilling <coding@schilljs.com>
  14. * @author Juan Pablo Villafáñez <jvillafanez@solidgear.es>
  15. * @author Julius Härtl <jus@bitgrid.net>
  16. * @author Lukas Reschke <lukas@statuscode.ch>
  17. * @author Mitar <mitar.git@tnode.com>
  18. * @author Morris Jobke <hey@morrisjobke.de>
  19. * @author Oliver Wegner <void1976@gmail.com>
  20. * @author Robin Appelman <robin@icewind.nl>
  21. * @author Robin McCorkell <robin@mccorkell.me.uk>
  22. * @author Roeland Jago Douma <roeland@famdouma.nl>
  23. * @author Thomas Müller <thomas.mueller@tmit.eu>
  24. * @author Thomas Tanghus <thomas@tanghus.net>
  25. * @author Vincent Petry <vincent@nextcloud.com>
  26. * @author Simon Leiner <simon@leiner.me>
  27. * @author Stanimir Bozhilov <stanimir@audriga.com>
  28. *
  29. * @license AGPL-3.0
  30. *
  31. * This code is free software: you can redistribute it and/or modify
  32. * it under the terms of the GNU Affero General Public License, version 3,
  33. * as published by the Free Software Foundation.
  34. *
  35. * This program is distributed in the hope that it will be useful,
  36. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  37. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  38. * GNU Affero General Public License for more details.
  39. *
  40. * You should have received a copy of the GNU Affero General Public License, version 3,
  41. * along with this program. If not, see <http://www.gnu.org/licenses/>
  42. *
  43. */
  44. namespace OC\AppFramework\Http;
  45. use OC\Security\CSRF\CsrfToken;
  46. use OC\Security\CSRF\CsrfTokenManager;
  47. use OC\Security\TrustedDomainHelper;
  48. use OCP\IConfig;
  49. use OCP\IRequest;
  50. use OCP\IRequestId;
  51. use Symfony\Component\HttpFoundation\IpUtils;
  52. /**
  53. * Class for accessing variables in the request.
  54. * This class provides an immutable object with request variables.
  55. *
  56. * @property mixed[] cookies
  57. * @property mixed[] env
  58. * @property mixed[] files
  59. * @property string method
  60. * @property mixed[] parameters
  61. * @property mixed[] server
  62. */
  63. class Request implements \ArrayAccess, \Countable, IRequest {
  64. public const USER_AGENT_IE = '/(MSIE)|(Trident)/';
  65. // Microsoft Edge User Agent from https://msdn.microsoft.com/en-us/library/hh869301(v=vs.85).aspx
  66. public const USER_AGENT_MS_EDGE = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Chrome\/[0-9.]+ (Mobile Safari|Safari)\/[0-9.]+ Edge?\/[0-9.]+$/';
  67. // Firefox User Agent from https://developer.mozilla.org/en-US/docs/Web/HTTP/Gecko_user_agent_string_reference
  68. public const USER_AGENT_FIREFOX = '/^Mozilla\/5\.0 \([^)]+\) Gecko\/[0-9.]+ Firefox\/[0-9.]+$/';
  69. // Chrome User Agent from https://developer.chrome.com/multidevice/user-agent
  70. public const USER_AGENT_CHROME = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\)( Ubuntu Chromium\/[0-9.]+|) Chrome\/[0-9.]+ (Mobile Safari|Safari)\/[0-9.]+( (Vivaldi|Brave|OPR)\/[0-9.]+|)$/';
  71. // Safari User Agent from http://www.useragentstring.com/pages/Safari/
  72. public const USER_AGENT_SAFARI = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Version\/[0-9.]+ Safari\/[0-9.A-Z]+$/';
  73. // Android Chrome user agent: https://developers.google.com/chrome/mobile/docs/user-agent
  74. public const USER_AGENT_ANDROID_MOBILE_CHROME = '#Android.*Chrome/[.0-9]*#';
  75. public const USER_AGENT_FREEBOX = '#^Mozilla/5\.0$#';
  76. public const REGEX_LOCALHOST = '/^(127\.0\.0\.1|localhost|\[::1\])$/';
  77. protected string $inputStream;
  78. protected $content;
  79. protected array $items = [];
  80. protected array $allowedKeys = [
  81. 'get',
  82. 'post',
  83. 'files',
  84. 'server',
  85. 'env',
  86. 'cookies',
  87. 'urlParams',
  88. 'parameters',
  89. 'method',
  90. 'requesttoken',
  91. ];
  92. protected IRequestId $requestId;
  93. protected IConfig $config;
  94. protected ?CsrfTokenManager $csrfTokenManager;
  95. protected bool $contentDecoded = false;
  96. /**
  97. * @param array $vars An associative array with the following optional values:
  98. * - array 'urlParams' the parameters which were matched from the URL
  99. * - array 'get' the $_GET array
  100. * - array|string 'post' the $_POST array or JSON string
  101. * - array 'files' the $_FILES array
  102. * - array 'server' the $_SERVER array
  103. * - array 'env' the $_ENV array
  104. * - array 'cookies' the $_COOKIE array
  105. * - string 'method' the request method (GET, POST etc)
  106. * - string|false 'requesttoken' the requesttoken or false when not available
  107. * @param IRequestId $requestId
  108. * @param IConfig $config
  109. * @param CsrfTokenManager|null $csrfTokenManager
  110. * @param string $stream
  111. * @see https://www.php.net/manual/en/reserved.variables.php
  112. */
  113. public function __construct(array $vars,
  114. IRequestId $requestId,
  115. IConfig $config,
  116. CsrfTokenManager $csrfTokenManager = null,
  117. string $stream = 'php://input') {
  118. $this->inputStream = $stream;
  119. $this->items['params'] = [];
  120. $this->requestId = $requestId;
  121. $this->config = $config;
  122. $this->csrfTokenManager = $csrfTokenManager;
  123. if (!array_key_exists('method', $vars)) {
  124. $vars['method'] = 'GET';
  125. }
  126. foreach ($this->allowedKeys as $name) {
  127. $this->items[$name] = $vars[$name] ?? [];
  128. }
  129. $this->items['parameters'] = array_merge(
  130. $this->items['get'],
  131. $this->items['post'],
  132. $this->items['urlParams'],
  133. $this->items['params']
  134. );
  135. }
  136. /**
  137. * @param array $parameters
  138. */
  139. public function setUrlParameters(array $parameters) {
  140. $this->items['urlParams'] = $parameters;
  141. $this->items['parameters'] = array_merge(
  142. $this->items['parameters'],
  143. $this->items['urlParams']
  144. );
  145. }
  146. /**
  147. * Countable method
  148. * @return int
  149. */
  150. public function count(): int {
  151. return \count($this->items['parameters']);
  152. }
  153. /**
  154. * ArrayAccess methods
  155. *
  156. * Gives access to the combined GET, POST and urlParams arrays
  157. *
  158. * Examples:
  159. *
  160. * $var = $request['myvar'];
  161. *
  162. * or
  163. *
  164. * if(!isset($request['myvar']) {
  165. * // Do something
  166. * }
  167. *
  168. * $request['myvar'] = 'something'; // This throws an exception.
  169. *
  170. * @param string $offset The key to lookup
  171. * @return boolean
  172. */
  173. public function offsetExists($offset): bool {
  174. return isset($this->items['parameters'][$offset]);
  175. }
  176. /**
  177. * @see offsetExists
  178. * @param string $offset
  179. * @return mixed
  180. */
  181. #[\ReturnTypeWillChange]
  182. public function offsetGet($offset) {
  183. return $this->items['parameters'][$offset] ?? null;
  184. }
  185. /**
  186. * @see offsetExists
  187. * @param string $offset
  188. * @param mixed $value
  189. */
  190. public function offsetSet($offset, $value): void {
  191. throw new \RuntimeException('You cannot change the contents of the request object');
  192. }
  193. /**
  194. * @see offsetExists
  195. * @param string $offset
  196. */
  197. public function offsetUnset($offset): void {
  198. throw new \RuntimeException('You cannot change the contents of the request object');
  199. }
  200. /**
  201. * Magic property accessors
  202. * @param string $name
  203. * @param mixed $value
  204. */
  205. public function __set($name, $value) {
  206. throw new \RuntimeException('You cannot change the contents of the request object');
  207. }
  208. /**
  209. * Access request variables by method and name.
  210. * Examples:
  211. *
  212. * $request->post['myvar']; // Only look for POST variables
  213. * $request->myvar; or $request->{'myvar'}; or $request->{$myvar}
  214. * Looks in the combined GET, POST and urlParams array.
  215. *
  216. * If you access e.g. ->post but the current HTTP request method
  217. * is GET a \LogicException will be thrown.
  218. *
  219. * @param string $name The key to look for.
  220. * @throws \LogicException
  221. * @return mixed|null
  222. */
  223. public function __get($name) {
  224. switch ($name) {
  225. case 'put':
  226. case 'patch':
  227. case 'get':
  228. case 'post':
  229. if ($this->method !== strtoupper($name)) {
  230. throw new \LogicException(sprintf('%s cannot be accessed in a %s request.', $name, $this->method));
  231. }
  232. return $this->getContent();
  233. case 'files':
  234. case 'server':
  235. case 'env':
  236. case 'cookies':
  237. case 'urlParams':
  238. case 'method':
  239. return $this->items[$name] ?? null;
  240. case 'parameters':
  241. case 'params':
  242. if ($this->isPutStreamContent()) {
  243. return $this->items['parameters'];
  244. }
  245. return $this->getContent();
  246. default:
  247. return isset($this[$name])
  248. ? $this[$name]
  249. : null;
  250. }
  251. }
  252. /**
  253. * @param string $name
  254. * @return bool
  255. */
  256. public function __isset($name) {
  257. if (\in_array($name, $this->allowedKeys, true)) {
  258. return true;
  259. }
  260. return isset($this->items['parameters'][$name]);
  261. }
  262. /**
  263. * @param string $id
  264. */
  265. public function __unset($id) {
  266. throw new \RuntimeException('You cannot change the contents of the request object');
  267. }
  268. /**
  269. * Returns the value for a specific http header.
  270. *
  271. * This method returns an empty string if the header did not exist.
  272. *
  273. * @param string $name
  274. * @return string
  275. */
  276. public function getHeader(string $name): string {
  277. $name = strtoupper(str_replace('-', '_', $name));
  278. if (isset($this->server['HTTP_' . $name])) {
  279. return $this->server['HTTP_' . $name];
  280. }
  281. // There's a few headers that seem to end up in the top-level
  282. // server array.
  283. switch ($name) {
  284. case 'CONTENT_TYPE':
  285. case 'CONTENT_LENGTH':
  286. case 'REMOTE_ADDR':
  287. if (isset($this->server[$name])) {
  288. return $this->server[$name];
  289. }
  290. break;
  291. }
  292. return '';
  293. }
  294. /**
  295. * Lets you access post and get parameters by the index
  296. * In case of json requests the encoded json body is accessed
  297. *
  298. * @param string $key the key which you want to access in the URL Parameter
  299. * placeholder, $_POST or $_GET array.
  300. * The priority how they're returned is the following:
  301. * 1. URL parameters
  302. * 2. POST parameters
  303. * 3. GET parameters
  304. * @param mixed $default If the key is not found, this value will be returned
  305. * @return mixed the content of the array
  306. */
  307. public function getParam(string $key, $default = null) {
  308. return isset($this->parameters[$key])
  309. ? $this->parameters[$key]
  310. : $default;
  311. }
  312. /**
  313. * Returns all params that were received, be it from the request
  314. * (as GET or POST) or through the URL by the route
  315. * @return array the array with all parameters
  316. */
  317. public function getParams(): array {
  318. return is_array($this->parameters) ? $this->parameters : [];
  319. }
  320. /**
  321. * Returns the method of the request
  322. * @return string the method of the request (POST, GET, etc)
  323. */
  324. public function getMethod(): string {
  325. return $this->method;
  326. }
  327. /**
  328. * Shortcut for accessing an uploaded file through the $_FILES array
  329. * @param string $key the key that will be taken from the $_FILES array
  330. * @return array the file in the $_FILES element
  331. */
  332. public function getUploadedFile(string $key) {
  333. return isset($this->files[$key]) ? $this->files[$key] : null;
  334. }
  335. /**
  336. * Shortcut for getting env variables
  337. * @param string $key the key that will be taken from the $_ENV array
  338. * @return array the value in the $_ENV element
  339. */
  340. public function getEnv(string $key) {
  341. return isset($this->env[$key]) ? $this->env[$key] : null;
  342. }
  343. /**
  344. * Shortcut for getting cookie variables
  345. * @param string $key the key that will be taken from the $_COOKIE array
  346. * @return string the value in the $_COOKIE element
  347. */
  348. public function getCookie(string $key) {
  349. return isset($this->cookies[$key]) ? $this->cookies[$key] : null;
  350. }
  351. /**
  352. * Returns the request body content.
  353. *
  354. * If the HTTP request method is PUT and the body
  355. * not application/x-www-form-urlencoded or application/json a stream
  356. * resource is returned, otherwise an array.
  357. *
  358. * @return array|string|resource The request body content or a resource to read the body stream.
  359. *
  360. * @throws \LogicException
  361. */
  362. protected function getContent() {
  363. // If the content can't be parsed into an array then return a stream resource.
  364. if ($this->isPutStreamContent()) {
  365. if ($this->content === false) {
  366. throw new \LogicException(
  367. '"put" can only be accessed once if not '
  368. . 'application/x-www-form-urlencoded or application/json.'
  369. );
  370. }
  371. $this->content = false;
  372. return fopen($this->inputStream, 'rb');
  373. } else {
  374. $this->decodeContent();
  375. return $this->items['parameters'];
  376. }
  377. }
  378. private function isPutStreamContent(): bool {
  379. return $this->method === 'PUT'
  380. && $this->getHeader('Content-Length') !== '0'
  381. && $this->getHeader('Content-Length') !== ''
  382. && !str_contains($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded')
  383. && !str_contains($this->getHeader('Content-Type'), 'application/json');
  384. }
  385. /**
  386. * Attempt to decode the content and populate parameters
  387. */
  388. protected function decodeContent() {
  389. if ($this->contentDecoded) {
  390. return;
  391. }
  392. $params = [];
  393. // 'application/json' and other JSON-related content types must be decoded manually.
  394. if (preg_match(self::JSON_CONTENT_TYPE_REGEX, $this->getHeader('Content-Type')) === 1) {
  395. $params = json_decode(file_get_contents($this->inputStream), true);
  396. if (\is_array($params) && \count($params) > 0) {
  397. $this->items['params'] = $params;
  398. if ($this->method === 'POST') {
  399. $this->items['post'] = $params;
  400. }
  401. }
  402. // Handle application/x-www-form-urlencoded for methods other than GET
  403. // or post correctly
  404. } elseif ($this->method !== 'GET'
  405. && $this->method !== 'POST'
  406. && str_contains($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded')) {
  407. parse_str(file_get_contents($this->inputStream), $params);
  408. if (\is_array($params)) {
  409. $this->items['params'] = $params;
  410. }
  411. }
  412. if (\is_array($params)) {
  413. $this->items['parameters'] = array_merge($this->items['parameters'], $params);
  414. }
  415. $this->contentDecoded = true;
  416. }
  417. /**
  418. * Checks if the CSRF check was correct
  419. * @return bool true if CSRF check passed
  420. */
  421. public function passesCSRFCheck(): bool {
  422. if ($this->csrfTokenManager === null) {
  423. return false;
  424. }
  425. if (!$this->passesStrictCookieCheck()) {
  426. return false;
  427. }
  428. if (isset($this->items['get']['requesttoken'])) {
  429. $token = $this->items['get']['requesttoken'];
  430. } elseif (isset($this->items['post']['requesttoken'])) {
  431. $token = $this->items['post']['requesttoken'];
  432. } elseif (isset($this->items['server']['HTTP_REQUESTTOKEN'])) {
  433. $token = $this->items['server']['HTTP_REQUESTTOKEN'];
  434. } else {
  435. //no token found.
  436. return false;
  437. }
  438. $token = new CsrfToken($token);
  439. return $this->csrfTokenManager->isTokenValid($token);
  440. }
  441. /**
  442. * Whether the cookie checks are required
  443. *
  444. * @return bool
  445. */
  446. private function cookieCheckRequired(): bool {
  447. if ($this->getHeader('OCS-APIREQUEST')) {
  448. return false;
  449. }
  450. if ($this->getCookie(session_name()) === null && $this->getCookie('nc_token') === null) {
  451. return false;
  452. }
  453. return true;
  454. }
  455. /**
  456. * Wrapper around session_get_cookie_params
  457. *
  458. * @return array
  459. */
  460. public function getCookieParams(): array {
  461. return session_get_cookie_params();
  462. }
  463. /**
  464. * Appends the __Host- prefix to the cookie if applicable
  465. *
  466. * @param string $name
  467. * @return string
  468. */
  469. protected function getProtectedCookieName(string $name): string {
  470. $cookieParams = $this->getCookieParams();
  471. $prefix = '';
  472. if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
  473. $prefix = '__Host-';
  474. }
  475. return $prefix.$name;
  476. }
  477. /**
  478. * Checks if the strict cookie has been sent with the request if the request
  479. * is including any cookies.
  480. *
  481. * @return bool
  482. * @since 9.1.0
  483. */
  484. public function passesStrictCookieCheck(): bool {
  485. if (!$this->cookieCheckRequired()) {
  486. return true;
  487. }
  488. $cookieName = $this->getProtectedCookieName('nc_sameSiteCookiestrict');
  489. if ($this->getCookie($cookieName) === 'true'
  490. && $this->passesLaxCookieCheck()) {
  491. return true;
  492. }
  493. return false;
  494. }
  495. /**
  496. * Checks if the lax cookie has been sent with the request if the request
  497. * is including any cookies.
  498. *
  499. * @return bool
  500. * @since 9.1.0
  501. */
  502. public function passesLaxCookieCheck(): bool {
  503. if (!$this->cookieCheckRequired()) {
  504. return true;
  505. }
  506. $cookieName = $this->getProtectedCookieName('nc_sameSiteCookielax');
  507. if ($this->getCookie($cookieName) === 'true') {
  508. return true;
  509. }
  510. return false;
  511. }
  512. /**
  513. * Returns an ID for the request, value is not guaranteed to be unique and is mostly meant for logging
  514. * If `mod_unique_id` is installed this value will be taken.
  515. * @return string
  516. */
  517. public function getId(): string {
  518. return $this->requestId->getId();
  519. }
  520. /**
  521. * Checks if given $remoteAddress matches any entry in the given array $trustedProxies.
  522. * For details regarding what "match" means, refer to `matchesTrustedProxy`.
  523. * @return boolean true if $remoteAddress matches any entry in $trustedProxies, false otherwise
  524. */
  525. protected function isTrustedProxy($trustedProxies, $remoteAddress) {
  526. try {
  527. return IpUtils::checkIp($remoteAddress, $trustedProxies);
  528. } catch (\Throwable) {
  529. // We can not log to our log here as the logger is using `getRemoteAddress` which uses the function, so we would have a cyclic dependency
  530. // Reaching this line means `trustedProxies` is in invalid format.
  531. error_log('Nextcloud trustedProxies has malformed entries');
  532. return false;
  533. }
  534. }
  535. /**
  536. * Returns the remote address, if the connection came from a trusted proxy
  537. * and `forwarded_for_headers` has been configured then the IP address
  538. * specified in this header will be returned instead.
  539. * Do always use this instead of $_SERVER['REMOTE_ADDR']
  540. * @return string IP address
  541. */
  542. public function getRemoteAddress(): string {
  543. $remoteAddress = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
  544. $trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
  545. if (\is_array($trustedProxies) && $this->isTrustedProxy($trustedProxies, $remoteAddress)) {
  546. $forwardedForHeaders = $this->config->getSystemValue('forwarded_for_headers', [
  547. 'HTTP_X_FORWARDED_FOR'
  548. // only have one default, so we cannot ship an insecure product out of the box
  549. ]);
  550. // Read the x-forwarded-for headers and values in reverse order as per
  551. // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For#selecting_an_ip_address
  552. foreach (array_reverse($forwardedForHeaders) as $header) {
  553. if (isset($this->server[$header])) {
  554. foreach (array_reverse(explode(',', $this->server[$header])) as $IP) {
  555. $IP = trim($IP);
  556. // remove brackets from IPv6 addresses
  557. if (str_starts_with($IP, '[') && str_ends_with($IP, ']')) {
  558. $IP = substr($IP, 1, -1);
  559. }
  560. if ($this->isTrustedProxy($trustedProxies, $IP)) {
  561. continue;
  562. }
  563. if (filter_var($IP, FILTER_VALIDATE_IP) !== false) {
  564. return $IP;
  565. }
  566. }
  567. }
  568. }
  569. }
  570. return $remoteAddress;
  571. }
  572. /**
  573. * Check overwrite condition
  574. * @return bool
  575. */
  576. private function isOverwriteCondition(): bool {
  577. $regex = '/' . $this->config->getSystemValueString('overwritecondaddr', '') . '/';
  578. $remoteAddr = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
  579. return $regex === '//' || preg_match($regex, $remoteAddr) === 1;
  580. }
  581. /**
  582. * Returns the server protocol. It respects one or more reverse proxies servers
  583. * and load balancers
  584. * @return string Server protocol (http or https)
  585. */
  586. public function getServerProtocol(): string {
  587. if ($this->config->getSystemValueString('overwriteprotocol') !== ''
  588. && $this->isOverwriteCondition()) {
  589. return $this->config->getSystemValueString('overwriteprotocol');
  590. }
  591. if ($this->fromTrustedProxy() && isset($this->server['HTTP_X_FORWARDED_PROTO'])) {
  592. if (str_contains($this->server['HTTP_X_FORWARDED_PROTO'], ',')) {
  593. $parts = explode(',', $this->server['HTTP_X_FORWARDED_PROTO']);
  594. $proto = strtolower(trim($parts[0]));
  595. } else {
  596. $proto = strtolower($this->server['HTTP_X_FORWARDED_PROTO']);
  597. }
  598. // Verify that the protocol is always HTTP or HTTPS
  599. // default to http if an invalid value is provided
  600. return $proto === 'https' ? 'https' : 'http';
  601. }
  602. if (isset($this->server['HTTPS'])
  603. && $this->server['HTTPS'] !== null
  604. && $this->server['HTTPS'] !== 'off'
  605. && $this->server['HTTPS'] !== '') {
  606. return 'https';
  607. }
  608. return 'http';
  609. }
  610. /**
  611. * Returns the used HTTP protocol.
  612. *
  613. * @return string HTTP protocol. HTTP/2, HTTP/1.1 or HTTP/1.0.
  614. */
  615. public function getHttpProtocol(): string {
  616. $claimedProtocol = $this->server['SERVER_PROTOCOL'];
  617. if (\is_string($claimedProtocol)) {
  618. $claimedProtocol = strtoupper($claimedProtocol);
  619. }
  620. $validProtocols = [
  621. 'HTTP/1.0',
  622. 'HTTP/1.1',
  623. 'HTTP/2',
  624. ];
  625. if (\in_array($claimedProtocol, $validProtocols, true)) {
  626. return $claimedProtocol;
  627. }
  628. return 'HTTP/1.1';
  629. }
  630. /**
  631. * Returns the request uri, even if the website uses one or more
  632. * reverse proxies
  633. * @return string
  634. */
  635. public function getRequestUri(): string {
  636. $uri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
  637. if ($this->config->getSystemValueString('overwritewebroot') !== '' && $this->isOverwriteCondition()) {
  638. $uri = $this->getScriptName() . substr($uri, \strlen($this->server['SCRIPT_NAME']));
  639. }
  640. return $uri;
  641. }
  642. /**
  643. * Get raw PathInfo from request (not urldecoded)
  644. * @throws \Exception
  645. * @return string Path info
  646. */
  647. public function getRawPathInfo(): string {
  648. $requestUri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
  649. // remove too many slashes - can be caused by reverse proxy configuration
  650. $requestUri = preg_replace('%/{2,}%', '/', $requestUri);
  651. // Remove the query string from REQUEST_URI
  652. if ($pos = strpos($requestUri, '?')) {
  653. $requestUri = substr($requestUri, 0, $pos);
  654. }
  655. $scriptName = $this->server['SCRIPT_NAME'];
  656. $pathInfo = $requestUri;
  657. // strip off the script name's dir and file name
  658. // FIXME: Sabre does not really belong here
  659. [$path, $name] = \Sabre\Uri\split($scriptName);
  660. if (!empty($path)) {
  661. if ($path === $pathInfo || str_starts_with($pathInfo, $path . '/')) {
  662. $pathInfo = substr($pathInfo, \strlen($path));
  663. } else {
  664. throw new \Exception("The requested uri($requestUri) cannot be processed by the script '$scriptName')");
  665. }
  666. }
  667. if ($name === null) {
  668. $name = '';
  669. }
  670. if (str_starts_with($pathInfo, '/' . $name)) {
  671. $pathInfo = substr($pathInfo, \strlen($name) + 1);
  672. }
  673. if ($name !== '' && str_starts_with($pathInfo, $name)) {
  674. $pathInfo = substr($pathInfo, \strlen($name));
  675. }
  676. if ($pathInfo === false || $pathInfo === '/') {
  677. return '';
  678. } else {
  679. return $pathInfo;
  680. }
  681. }
  682. /**
  683. * Get PathInfo from request
  684. * @throws \Exception
  685. * @return string|false Path info or false when not found
  686. */
  687. public function getPathInfo() {
  688. $pathInfo = $this->getRawPathInfo();
  689. return \Sabre\HTTP\decodePath($pathInfo);
  690. }
  691. /**
  692. * Returns the script name, even if the website uses one or more
  693. * reverse proxies
  694. * @return string the script name
  695. */
  696. public function getScriptName(): string {
  697. $name = $this->server['SCRIPT_NAME'];
  698. $overwriteWebRoot = $this->config->getSystemValueString('overwritewebroot');
  699. if ($overwriteWebRoot !== '' && $this->isOverwriteCondition()) {
  700. // FIXME: This code is untestable due to __DIR__, also that hardcoded path is really dangerous
  701. $serverRoot = str_replace('\\', '/', substr(__DIR__, 0, -\strlen('lib/private/appframework/http/')));
  702. $suburi = str_replace('\\', '/', substr(realpath($this->server['SCRIPT_FILENAME']), \strlen($serverRoot)));
  703. $name = '/' . ltrim($overwriteWebRoot . $suburi, '/');
  704. }
  705. return $name;
  706. }
  707. /**
  708. * Checks whether the user agent matches a given regex
  709. * @param array $agent array of agent names
  710. * @return bool true if at least one of the given agent matches, false otherwise
  711. */
  712. public function isUserAgent(array $agent): bool {
  713. if (!isset($this->server['HTTP_USER_AGENT'])) {
  714. return false;
  715. }
  716. foreach ($agent as $regex) {
  717. if (preg_match($regex, $this->server['HTTP_USER_AGENT'])) {
  718. return true;
  719. }
  720. }
  721. return false;
  722. }
  723. /**
  724. * Returns the unverified server host from the headers without checking
  725. * whether it is a trusted domain
  726. * @return string Server host
  727. */
  728. public function getInsecureServerHost(): string {
  729. if ($this->fromTrustedProxy() && $this->getOverwriteHost() !== null) {
  730. return $this->getOverwriteHost();
  731. }
  732. $host = 'localhost';
  733. if ($this->fromTrustedProxy() && isset($this->server['HTTP_X_FORWARDED_HOST'])) {
  734. if (str_contains($this->server['HTTP_X_FORWARDED_HOST'], ',')) {
  735. $parts = explode(',', $this->server['HTTP_X_FORWARDED_HOST']);
  736. $host = trim(current($parts));
  737. } else {
  738. $host = $this->server['HTTP_X_FORWARDED_HOST'];
  739. }
  740. } else {
  741. if (isset($this->server['HTTP_HOST'])) {
  742. $host = $this->server['HTTP_HOST'];
  743. } elseif (isset($this->server['SERVER_NAME'])) {
  744. $host = $this->server['SERVER_NAME'];
  745. }
  746. }
  747. return $host;
  748. }
  749. /**
  750. * Returns the server host from the headers, or the first configured
  751. * trusted domain if the host isn't in the trusted list
  752. * @return string Server host
  753. */
  754. public function getServerHost(): string {
  755. // overwritehost is always trusted
  756. $host = $this->getOverwriteHost();
  757. if ($host !== null) {
  758. return $host;
  759. }
  760. // get the host from the headers
  761. $host = $this->getInsecureServerHost();
  762. // Verify that the host is a trusted domain if the trusted domains
  763. // are defined
  764. // If no trusted domain is provided the first trusted domain is returned
  765. $trustedDomainHelper = new TrustedDomainHelper($this->config);
  766. if ($trustedDomainHelper->isTrustedDomain($host)) {
  767. return $host;
  768. }
  769. $trustedList = (array)$this->config->getSystemValue('trusted_domains', []);
  770. if (count($trustedList) > 0) {
  771. return reset($trustedList);
  772. }
  773. return '';
  774. }
  775. /**
  776. * Returns the overwritehost setting from the config if set and
  777. * if the overwrite condition is met
  778. * @return string|null overwritehost value or null if not defined or the defined condition
  779. * isn't met
  780. */
  781. private function getOverwriteHost() {
  782. if ($this->config->getSystemValueString('overwritehost') !== '' && $this->isOverwriteCondition()) {
  783. return $this->config->getSystemValueString('overwritehost');
  784. }
  785. return null;
  786. }
  787. private function fromTrustedProxy(): bool {
  788. $remoteAddress = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
  789. $trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
  790. return \is_array($trustedProxies) && $this->isTrustedProxy($trustedProxies, $remoteAddress);
  791. }
  792. }