You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Request.php 27KB

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