Request.php 26 KB

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