Request.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. *
  6. * @author Bart Visscher <bartv@thisnet.nl>
  7. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  8. * @author Christoph Wurst <christoph@owncloud.com>
  9. * @author coderkun <olli@coderkun.de>
  10. * @author Joas Schilling <coding@schilljs.com>
  11. * @author Juan Pablo Villafáñez <jvillafanez@solidgear.es>
  12. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  13. * @author Lukas Reschke <lukas@statuscode.ch>
  14. * @author Mitar <mitar.git@tnode.com>
  15. * @author Morris Jobke <hey@morrisjobke.de>
  16. * @author Robin Appelman <robin@icewind.nl>
  17. * @author Robin McCorkell <robin@mccorkell.me.uk>
  18. * @author Roeland Jago Douma <roeland@famdouma.nl>
  19. * @author Thomas Müller <thomas.mueller@tmit.eu>
  20. * @author Thomas Tanghus <thomas@tanghus.net>
  21. * @author Vincent Petry <pvince81@owncloud.com>
  22. *
  23. * @license AGPL-3.0
  24. *
  25. * This code is free software: you can redistribute it and/or modify
  26. * it under the terms of the GNU Affero General Public License, version 3,
  27. * as published by the Free Software Foundation.
  28. *
  29. * This program is distributed in the hope that it will be useful,
  30. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  31. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  32. * GNU Affero General Public License for more details.
  33. *
  34. * You should have received a copy of the GNU Affero General Public License, version 3,
  35. * along with this program. If not, see <http://www.gnu.org/licenses/>
  36. *
  37. */
  38. namespace OC\AppFramework\Http;
  39. use OC\Security\CSRF\CsrfToken;
  40. use OC\Security\CSRF\CsrfTokenManager;
  41. use OC\Security\TrustedDomainHelper;
  42. use OCP\IConfig;
  43. use OCP\IRequest;
  44. use OCP\Security\ICrypto;
  45. use OCP\Security\ISecureRandom;
  46. /**
  47. * Class for accessing variables in the request.
  48. * This class provides an immutable object with request variables.
  49. *
  50. * @property mixed[] cookies
  51. * @property mixed[] env
  52. * @property mixed[] files
  53. * @property string method
  54. * @property mixed[] parameters
  55. * @property mixed[] server
  56. */
  57. class Request implements \ArrayAccess, \Countable, IRequest {
  58. const USER_AGENT_IE = '/(MSIE)|(Trident)/';
  59. // Microsoft Edge User Agent from https://msdn.microsoft.com/en-us/library/hh869301(v=vs.85).aspx
  60. 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.]+$/';
  61. // Firefox User Agent from https://developer.mozilla.org/en-US/docs/Web/HTTP/Gecko_user_agent_string_reference
  62. const USER_AGENT_FIREFOX = '/^Mozilla\/5\.0 \([^)]+\) Gecko\/[0-9.]+ Firefox\/[0-9.]+$/';
  63. // Chrome User Agent from https://developer.chrome.com/multidevice/user-agent
  64. 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.]+$/';
  65. // Safari User Agent from http://www.useragentstring.com/pages/Safari/
  66. const USER_AGENT_SAFARI = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Version\/[0-9.]+ Safari\/[0-9.A-Z]+$/';
  67. // Android Chrome user agent: https://developers.google.com/chrome/mobile/docs/user-agent
  68. const USER_AGENT_ANDROID_MOBILE_CHROME = '#Android.*Chrome/[.0-9]*#';
  69. const USER_AGENT_FREEBOX = '#^Mozilla/5\.0$#';
  70. const REGEX_LOCALHOST = '/^(127\.0\.0\.1|localhost|::1)$/';
  71. /**
  72. * @deprecated use \OCP\IRequest::USER_AGENT_CLIENT_IOS instead
  73. */
  74. const USER_AGENT_OWNCLOUD_IOS = '/^Mozilla\/5\.0 \(iOS\) (ownCloud|Nextcloud)\-iOS.*$/';
  75. /**
  76. * @deprecated use \OCP\IRequest::USER_AGENT_CLIENT_ANDROID instead
  77. */
  78. const USER_AGENT_OWNCLOUD_ANDROID = '/^Mozilla\/5\.0 \(Android\) ownCloud\-android.*$/';
  79. /**
  80. * @deprecated use \OCP\IRequest::USER_AGENT_CLIENT_DESKTOP instead
  81. */
  82. const USER_AGENT_OWNCLOUD_DESKTOP = '/^Mozilla\/5\.0 \([A-Za-z ]+\) (mirall|csyncoC)\/.*$/';
  83. protected $inputStream;
  84. protected $content;
  85. protected $items = [];
  86. protected $allowedKeys = [
  87. 'get',
  88. 'post',
  89. 'files',
  90. 'server',
  91. 'env',
  92. 'cookies',
  93. 'urlParams',
  94. 'parameters',
  95. 'method',
  96. 'requesttoken',
  97. ];
  98. /** @var ISecureRandom */
  99. protected $secureRandom;
  100. /** @var IConfig */
  101. protected $config;
  102. /** @var string */
  103. protected $requestId = '';
  104. /** @var ICrypto */
  105. protected $crypto;
  106. /** @var CsrfTokenManager|null */
  107. protected $csrfTokenManager;
  108. /** @var bool */
  109. protected $contentDecoded = false;
  110. /**
  111. * @param array $vars An associative array with the following optional values:
  112. * - array 'urlParams' the parameters which were matched from the URL
  113. * - array 'get' the $_GET array
  114. * - array|string 'post' the $_POST array or JSON string
  115. * - array 'files' the $_FILES array
  116. * - array 'server' the $_SERVER array
  117. * - array 'env' the $_ENV array
  118. * - array 'cookies' the $_COOKIE array
  119. * - string 'method' the request method (GET, POST etc)
  120. * - string|false 'requesttoken' the requesttoken or false when not available
  121. * @param ISecureRandom $secureRandom
  122. * @param IConfig $config
  123. * @param CsrfTokenManager|null $csrfTokenManager
  124. * @param string $stream
  125. * @see http://www.php.net/manual/en/reserved.variables.php
  126. */
  127. public function __construct(array $vars= [],
  128. ISecureRandom $secureRandom = null,
  129. IConfig $config,
  130. CsrfTokenManager $csrfTokenManager = null,
  131. string $stream = 'php://input') {
  132. $this->inputStream = $stream;
  133. $this->items['params'] = [];
  134. $this->secureRandom = $secureRandom;
  135. $this->config = $config;
  136. $this->csrfTokenManager = $csrfTokenManager;
  137. if(!array_key_exists('method', $vars)) {
  138. $vars['method'] = 'GET';
  139. }
  140. foreach($this->allowedKeys as $name) {
  141. $this->items[$name] = isset($vars[$name])
  142. ? $vars[$name]
  143. : [];
  144. }
  145. $this->items['parameters'] = array_merge(
  146. $this->items['get'],
  147. $this->items['post'],
  148. $this->items['urlParams'],
  149. $this->items['params']
  150. );
  151. }
  152. /**
  153. * @param array $parameters
  154. */
  155. public function setUrlParameters(array $parameters) {
  156. $this->items['urlParams'] = $parameters;
  157. $this->items['parameters'] = array_merge(
  158. $this->items['parameters'],
  159. $this->items['urlParams']
  160. );
  161. }
  162. /**
  163. * Countable method
  164. * @return int
  165. */
  166. public function count(): int {
  167. return \count($this->items['parameters']);
  168. }
  169. /**
  170. * ArrayAccess methods
  171. *
  172. * Gives access to the combined GET, POST and urlParams arrays
  173. *
  174. * Examples:
  175. *
  176. * $var = $request['myvar'];
  177. *
  178. * or
  179. *
  180. * if(!isset($request['myvar']) {
  181. * // Do something
  182. * }
  183. *
  184. * $request['myvar'] = 'something'; // This throws an exception.
  185. *
  186. * @param string $offset The key to lookup
  187. * @return boolean
  188. */
  189. public function offsetExists($offset): bool {
  190. return isset($this->items['parameters'][$offset]);
  191. }
  192. /**
  193. * @see offsetExists
  194. * @param string $offset
  195. * @return mixed
  196. */
  197. public function offsetGet($offset) {
  198. return isset($this->items['parameters'][$offset])
  199. ? $this->items['parameters'][$offset]
  200. : null;
  201. }
  202. /**
  203. * @see offsetExists
  204. * @param string $offset
  205. * @param mixed $value
  206. */
  207. public function offsetSet($offset, $value) {
  208. throw new \RuntimeException('You cannot change the contents of the request object');
  209. }
  210. /**
  211. * @see offsetExists
  212. * @param string $offset
  213. */
  214. public function offsetUnset($offset) {
  215. throw new \RuntimeException('You cannot change the contents of the request object');
  216. }
  217. /**
  218. * Magic property accessors
  219. * @param string $name
  220. * @param mixed $value
  221. */
  222. public function __set($name, $value) {
  223. throw new \RuntimeException('You cannot change the contents of the request object');
  224. }
  225. /**
  226. * Access request variables by method and name.
  227. * Examples:
  228. *
  229. * $request->post['myvar']; // Only look for POST variables
  230. * $request->myvar; or $request->{'myvar'}; or $request->{$myvar}
  231. * Looks in the combined GET, POST and urlParams array.
  232. *
  233. * If you access e.g. ->post but the current HTTP request method
  234. * is GET a \LogicException will be thrown.
  235. *
  236. * @param string $name The key to look for.
  237. * @throws \LogicException
  238. * @return mixed|null
  239. */
  240. public function __get($name) {
  241. switch($name) {
  242. case 'put':
  243. case 'patch':
  244. case 'get':
  245. case 'post':
  246. if($this->method !== strtoupper($name)) {
  247. throw new \LogicException(sprintf('%s cannot be accessed in a %s request.', $name, $this->method));
  248. }
  249. return $this->getContent();
  250. case 'files':
  251. case 'server':
  252. case 'env':
  253. case 'cookies':
  254. case 'urlParams':
  255. case 'method':
  256. return isset($this->items[$name])
  257. ? $this->items[$name]
  258. : null;
  259. case 'parameters':
  260. case 'params':
  261. return $this->getContent();
  262. default;
  263. return isset($this[$name])
  264. ? $this[$name]
  265. : null;
  266. }
  267. }
  268. /**
  269. * @param string $name
  270. * @return bool
  271. */
  272. public function __isset($name) {
  273. if (\in_array($name, $this->allowedKeys, true)) {
  274. return true;
  275. }
  276. return isset($this->items['parameters'][$name]);
  277. }
  278. /**
  279. * @param string $id
  280. */
  281. public function __unset($id) {
  282. throw new \RuntimeException('You cannot change the contents of the request object');
  283. }
  284. /**
  285. * Returns the value for a specific http header.
  286. *
  287. * This method returns null if the header did not exist.
  288. *
  289. * @param string $name
  290. * @return string
  291. */
  292. public function getHeader(string $name): string {
  293. $name = strtoupper(str_replace('-', '_',$name));
  294. if (isset($this->server['HTTP_' . $name])) {
  295. return $this->server['HTTP_' . $name];
  296. }
  297. // There's a few headers that seem to end up in the top-level
  298. // server array.
  299. switch ($name) {
  300. case 'CONTENT_TYPE' :
  301. case 'CONTENT_LENGTH' :
  302. if (isset($this->server[$name])) {
  303. return $this->server[$name];
  304. }
  305. break;
  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. if (filter_var($IP, FILTER_VALIDATE_IP) !== false) {
  597. return $IP;
  598. }
  599. }
  600. }
  601. }
  602. }
  603. return $remoteAddress;
  604. }
  605. /**
  606. * Check overwrite condition
  607. * @param string $type
  608. * @return bool
  609. */
  610. private function isOverwriteCondition(string $type = ''): bool {
  611. $regex = '/' . $this->config->getSystemValue('overwritecondaddr', '') . '/';
  612. $remoteAddr = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
  613. return $regex === '//' || preg_match($regex, $remoteAddr) === 1
  614. || $type !== 'protocol';
  615. }
  616. /**
  617. * Returns the server protocol. It respects one or more reverse proxies servers
  618. * and load balancers
  619. * @return string Server protocol (http or https)
  620. */
  621. public function getServerProtocol(): string {
  622. if($this->config->getSystemValue('overwriteprotocol') !== ''
  623. && $this->isOverwriteCondition('protocol')) {
  624. return $this->config->getSystemValue('overwriteprotocol');
  625. }
  626. if ($this->fromTrustedProxy() && isset($this->server['HTTP_X_FORWARDED_PROTO'])) {
  627. if (strpos($this->server['HTTP_X_FORWARDED_PROTO'], ',') !== false) {
  628. $parts = explode(',', $this->server['HTTP_X_FORWARDED_PROTO']);
  629. $proto = strtolower(trim($parts[0]));
  630. } else {
  631. $proto = strtolower($this->server['HTTP_X_FORWARDED_PROTO']);
  632. }
  633. // Verify that the protocol is always HTTP or HTTPS
  634. // default to http if an invalid value is provided
  635. return $proto === 'https' ? 'https' : 'http';
  636. }
  637. if (isset($this->server['HTTPS'])
  638. && $this->server['HTTPS'] !== null
  639. && $this->server['HTTPS'] !== 'off'
  640. && $this->server['HTTPS'] !== '') {
  641. return 'https';
  642. }
  643. return 'http';
  644. }
  645. /**
  646. * Returns the used HTTP protocol.
  647. *
  648. * @return string HTTP protocol. HTTP/2, HTTP/1.1 or HTTP/1.0.
  649. */
  650. public function getHttpProtocol(): string {
  651. $claimedProtocol = $this->server['SERVER_PROTOCOL'];
  652. if (\is_string($claimedProtocol)) {
  653. $claimedProtocol = strtoupper($claimedProtocol);
  654. }
  655. $validProtocols = [
  656. 'HTTP/1.0',
  657. 'HTTP/1.1',
  658. 'HTTP/2',
  659. ];
  660. if(\in_array($claimedProtocol, $validProtocols, true)) {
  661. return $claimedProtocol;
  662. }
  663. return 'HTTP/1.1';
  664. }
  665. /**
  666. * Returns the request uri, even if the website uses one or more
  667. * reverse proxies
  668. * @return string
  669. */
  670. public function getRequestUri(): string {
  671. $uri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
  672. if($this->config->getSystemValue('overwritewebroot') !== '' && $this->isOverwriteCondition()) {
  673. $uri = $this->getScriptName() . substr($uri, \strlen($this->server['SCRIPT_NAME']));
  674. }
  675. return $uri;
  676. }
  677. /**
  678. * Get raw PathInfo from request (not urldecoded)
  679. * @throws \Exception
  680. * @return string Path info
  681. */
  682. public function getRawPathInfo(): string {
  683. $requestUri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
  684. // remove too many leading slashes - can be caused by reverse proxy configuration
  685. if (strpos($requestUri, '/') === 0) {
  686. $requestUri = '/' . ltrim($requestUri, '/');
  687. }
  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. $host = 'localhost';
  776. if ($this->fromTrustedProxy() && isset($this->server['HTTP_X_FORWARDED_HOST'])) {
  777. if (strpos($this->server['HTTP_X_FORWARDED_HOST'], ',') !== false) {
  778. $parts = explode(',', $this->server['HTTP_X_FORWARDED_HOST']);
  779. $host = trim(current($parts));
  780. } else {
  781. $host = $this->server['HTTP_X_FORWARDED_HOST'];
  782. }
  783. } else {
  784. if (isset($this->server['HTTP_HOST'])) {
  785. $host = $this->server['HTTP_HOST'];
  786. } else if (isset($this->server['SERVER_NAME'])) {
  787. $host = $this->server['SERVER_NAME'];
  788. }
  789. }
  790. return $host;
  791. }
  792. /**
  793. * Returns the server host from the headers, or the first configured
  794. * trusted domain if the host isn't in the trusted list
  795. * @return string Server host
  796. */
  797. public function getServerHost(): string {
  798. // overwritehost is always trusted
  799. $host = $this->getOverwriteHost();
  800. if ($host !== null) {
  801. return $host;
  802. }
  803. // get the host from the headers
  804. $host = $this->getInsecureServerHost();
  805. // Verify that the host is a trusted domain if the trusted domains
  806. // are defined
  807. // If no trusted domain is provided the first trusted domain is returned
  808. $trustedDomainHelper = new TrustedDomainHelper($this->config);
  809. if ($trustedDomainHelper->isTrustedDomain($host)) {
  810. return $host;
  811. } else {
  812. $trustedList = $this->config->getSystemValue('trusted_domains', []);
  813. if(!empty($trustedList)) {
  814. return $trustedList[0];
  815. } else {
  816. return '';
  817. }
  818. }
  819. }
  820. /**
  821. * Returns the overwritehost setting from the config if set and
  822. * if the overwrite condition is met
  823. * @return string|null overwritehost value or null if not defined or the defined condition
  824. * isn't met
  825. */
  826. private function getOverwriteHost() {
  827. if($this->config->getSystemValue('overwritehost') !== '' && $this->isOverwriteCondition()) {
  828. return $this->config->getSystemValue('overwritehost');
  829. }
  830. return null;
  831. }
  832. private function fromTrustedProxy(): bool {
  833. $remoteAddress = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
  834. $trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
  835. return \is_array($trustedProxies) && $this->isTrustedProxy($trustedProxies, $remoteAddress);
  836. }
  837. }