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

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