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

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