123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855 |
- <?php
- declare(strict_types=1);
- namespace OC\AppFramework\Http;
- use OC\Security\CSRF\CsrfToken;
- use OC\Security\CSRF\CsrfTokenManager;
- use OC\Security\TrustedDomainHelper;
- use OCP\IConfig;
- use OCP\IRequest;
- use OCP\IRequestId;
- use Symfony\Component\HttpFoundation\IpUtils;
- class Request implements \ArrayAccess, \Countable, IRequest {
- public const USER_AGENT_IE = '/(MSIE)|(Trident)/';
-
- 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.]+$/';
-
- public const USER_AGENT_FIREFOX = '/^Mozilla\/5\.0 \([^)]+\) Gecko\/[0-9.]+ Firefox\/[0-9.]+$/';
-
- 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.]+|)$/';
-
- public const USER_AGENT_SAFARI = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Version\/[0-9.]+ Safari\/[0-9.A-Z]+$/';
- public const USER_AGENT_SAFARI_MOBILE = '/^Mozilla\/5\.0 \([^)]+\) AppleWebKit\/[0-9.]+ \(KHTML, like Gecko\) Version\/[0-9.]+ (Mobile\/[0-9.A-Z]+) Safari\/[0-9.A-Z]+$/';
-
- public const USER_AGENT_ANDROID_MOBILE_CHROME = '#Android.*Chrome/[.0-9]*#';
- public const USER_AGENT_FREEBOX = '#^Mozilla/5\.0$#';
- public const REGEX_LOCALHOST = '/^(127\.0\.0\.1|localhost|\[::1\])$/';
- protected string $inputStream;
- protected $content;
- protected array $items = [];
- protected array $allowedKeys = [
- 'get',
- 'post',
- 'files',
- 'server',
- 'env',
- 'cookies',
- 'urlParams',
- 'parameters',
- 'method',
- 'requesttoken',
- ];
- protected IRequestId $requestId;
- protected IConfig $config;
- protected ?CsrfTokenManager $csrfTokenManager;
- protected bool $contentDecoded = false;
-
- public function __construct(array $vars,
- IRequestId $requestId,
- IConfig $config,
- ?CsrfTokenManager $csrfTokenManager = null,
- string $stream = 'php://input') {
- $this->inputStream = $stream;
- $this->items['params'] = [];
- $this->requestId = $requestId;
- $this->config = $config;
- $this->csrfTokenManager = $csrfTokenManager;
- if (!array_key_exists('method', $vars)) {
- $vars['method'] = 'GET';
- }
- foreach ($this->allowedKeys as $name) {
- $this->items[$name] = $vars[$name] ?? [];
- }
- $this->items['parameters'] = array_merge(
- $this->items['get'],
- $this->items['post'],
- $this->items['urlParams'],
- $this->items['params']
- );
- }
-
- public function setUrlParameters(array $parameters) {
- $this->items['urlParams'] = $parameters;
- $this->items['parameters'] = array_merge(
- $this->items['parameters'],
- $this->items['urlParams']
- );
- }
-
- public function count(): int {
- return \count($this->items['parameters']);
- }
-
- public function offsetExists($offset): bool {
- return isset($this->items['parameters'][$offset]);
- }
-
-
- public function offsetGet($offset) {
- return $this->items['parameters'][$offset] ?? null;
- }
-
- public function offsetSet($offset, $value): void {
- throw new \RuntimeException('You cannot change the contents of the request object');
- }
-
- public function offsetUnset($offset): void {
- throw new \RuntimeException('You cannot change the contents of the request object');
- }
-
- public function __set($name, $value) {
- throw new \RuntimeException('You cannot change the contents of the request object');
- }
-
- public function __get($name) {
- switch ($name) {
- case 'put':
- case 'patch':
- case 'get':
- case 'post':
- if ($this->method !== strtoupper($name)) {
- throw new \LogicException(sprintf('%s cannot be accessed in a %s request.', $name, $this->method));
- }
- return $this->getContent();
- case 'files':
- case 'server':
- case 'env':
- case 'cookies':
- case 'urlParams':
- case 'method':
- return $this->items[$name] ?? null;
- case 'parameters':
- case 'params':
- if ($this->isPutStreamContent()) {
- return $this->items['parameters'];
- }
- return $this->getContent();
- default:
- return isset($this[$name])
- ? $this[$name]
- : null;
- }
- }
-
- public function __isset($name) {
- if (\in_array($name, $this->allowedKeys, true)) {
- return true;
- }
- return isset($this->items['parameters'][$name]);
- }
-
- public function __unset($id) {
- throw new \RuntimeException('You cannot change the contents of the request object');
- }
-
- public function getHeader(string $name): string {
- $name = strtoupper(str_replace('-', '_', $name));
- if (isset($this->server['HTTP_' . $name])) {
- return $this->server['HTTP_' . $name];
- }
-
-
- switch ($name) {
- case 'CONTENT_TYPE':
- case 'CONTENT_LENGTH':
- case 'REMOTE_ADDR':
- if (isset($this->server[$name])) {
- return $this->server[$name];
- }
- break;
- }
- return '';
- }
-
- public function getParam(string $key, $default = null) {
- return isset($this->parameters[$key])
- ? $this->parameters[$key]
- : $default;
- }
-
- public function getParams(): array {
- return is_array($this->parameters) ? $this->parameters : [];
- }
-
- public function getMethod(): string {
- return $this->method;
- }
-
- public function getUploadedFile(string $key) {
- return isset($this->files[$key]) ? $this->files[$key] : null;
- }
-
- public function getEnv(string $key) {
- return isset($this->env[$key]) ? $this->env[$key] : null;
- }
-
- public function getCookie(string $key) {
- return isset($this->cookies[$key]) ? $this->cookies[$key] : null;
- }
-
- protected function getContent() {
-
- if ($this->isPutStreamContent()) {
- if ($this->content === false) {
- throw new \LogicException(
- '"put" can only be accessed once if not '
- . 'application/x-www-form-urlencoded or application/json.'
- );
- }
- $this->content = false;
- return fopen($this->inputStream, 'rb');
- } else {
- $this->decodeContent();
- return $this->items['parameters'];
- }
- }
- private function isPutStreamContent(): bool {
- return $this->method === 'PUT'
- && $this->getHeader('Content-Length') !== '0'
- && $this->getHeader('Content-Length') !== ''
- && !str_contains($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded')
- && !str_contains($this->getHeader('Content-Type'), 'application/json');
- }
-
- protected function decodeContent() {
- if ($this->contentDecoded) {
- return;
- }
- $params = [];
-
- if (preg_match(self::JSON_CONTENT_TYPE_REGEX, $this->getHeader('Content-Type')) === 1) {
- $params = json_decode(file_get_contents($this->inputStream), true);
- if (\is_array($params) && \count($params) > 0) {
- $this->items['params'] = $params;
- if ($this->method === 'POST') {
- $this->items['post'] = $params;
- }
- }
-
-
- } elseif ($this->method !== 'GET'
- && $this->method !== 'POST'
- && str_contains($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded')) {
- parse_str(file_get_contents($this->inputStream), $params);
- if (\is_array($params)) {
- $this->items['params'] = $params;
- }
- }
- if (\is_array($params)) {
- $this->items['parameters'] = array_merge($this->items['parameters'], $params);
- }
- $this->contentDecoded = true;
- }
-
- public function passesCSRFCheck(): bool {
- if ($this->csrfTokenManager === null) {
- return false;
- }
- if (!$this->passesStrictCookieCheck()) {
- return false;
- }
- if ($this->getHeader('OCS-APIRequest') !== '') {
- return true;
- }
- if (isset($this->items['get']['requesttoken'])) {
- $token = $this->items['get']['requesttoken'];
- } elseif (isset($this->items['post']['requesttoken'])) {
- $token = $this->items['post']['requesttoken'];
- } elseif (isset($this->items['server']['HTTP_REQUESTTOKEN'])) {
- $token = $this->items['server']['HTTP_REQUESTTOKEN'];
- } else {
-
- return false;
- }
- $token = new CsrfToken($token);
- return $this->csrfTokenManager->isTokenValid($token);
- }
-
- private function cookieCheckRequired(): bool {
- if ($this->getHeader('OCS-APIREQUEST')) {
- return false;
- }
- if ($this->getCookie(session_name()) === null && $this->getCookie('nc_token') === null) {
- return false;
- }
- return true;
- }
-
- public function getCookieParams(): array {
- return session_get_cookie_params();
- }
-
- protected function getProtectedCookieName(string $name): string {
- $cookieParams = $this->getCookieParams();
- $prefix = '';
- if ($cookieParams['secure'] === true && $cookieParams['path'] === '/') {
- $prefix = '__Host-';
- }
- return $prefix . $name;
- }
-
- public function passesStrictCookieCheck(): bool {
- if (!$this->cookieCheckRequired()) {
- return true;
- }
- $cookieName = $this->getProtectedCookieName('nc_sameSiteCookiestrict');
- if ($this->getCookie($cookieName) === 'true'
- && $this->passesLaxCookieCheck()) {
- return true;
- }
- return false;
- }
-
- public function passesLaxCookieCheck(): bool {
- if (!$this->cookieCheckRequired()) {
- return true;
- }
- $cookieName = $this->getProtectedCookieName('nc_sameSiteCookielax');
- if ($this->getCookie($cookieName) === 'true') {
- return true;
- }
- return false;
- }
-
- public function getId(): string {
- return $this->requestId->getId();
- }
-
- protected function isTrustedProxy($trustedProxies, $remoteAddress) {
- try {
- return IpUtils::checkIp($remoteAddress, $trustedProxies);
- } catch (\Throwable) {
-
-
- error_log('Nextcloud trustedProxies has malformed entries');
- return false;
- }
- }
-
- public function getRemoteAddress(): string {
- $remoteAddress = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
- $trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
- if (\is_array($trustedProxies) && $this->isTrustedProxy($trustedProxies, $remoteAddress)) {
- $forwardedForHeaders = $this->config->getSystemValue('forwarded_for_headers', [
- 'HTTP_X_FORWARDED_FOR'
-
- ]);
-
-
- foreach (array_reverse($forwardedForHeaders) as $header) {
- if (isset($this->server[$header])) {
- foreach (array_reverse(explode(',', $this->server[$header])) as $IP) {
- $IP = trim($IP);
- $colons = substr_count($IP, ':');
- if ($colons > 1) {
-
- if (preg_match('/^\[(.+?)\](?::\d+)?$/', $IP, $matches) && isset($matches[1])) {
- $IP = $matches[1];
- }
- } elseif ($colons === 1) {
-
- $IP = substr($IP, 0, strpos($IP, ':'));
- }
- if ($this->isTrustedProxy($trustedProxies, $IP)) {
- continue;
- }
- if (filter_var($IP, FILTER_VALIDATE_IP) !== false) {
- return $IP;
- }
- }
- }
- }
- }
- return $remoteAddress;
- }
-
- private function isOverwriteCondition(): bool {
- $regex = '/' . $this->config->getSystemValueString('overwritecondaddr', '') . '/';
- $remoteAddr = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
- return $regex === '//' || preg_match($regex, $remoteAddr) === 1;
- }
-
- public function getServerProtocol(): string {
- if ($this->config->getSystemValueString('overwriteprotocol') !== ''
- && $this->isOverwriteCondition()) {
- return $this->config->getSystemValueString('overwriteprotocol');
- }
- if ($this->fromTrustedProxy() && isset($this->server['HTTP_X_FORWARDED_PROTO'])) {
- if (str_contains($this->server['HTTP_X_FORWARDED_PROTO'], ',')) {
- $parts = explode(',', $this->server['HTTP_X_FORWARDED_PROTO']);
- $proto = strtolower(trim($parts[0]));
- } else {
- $proto = strtolower($this->server['HTTP_X_FORWARDED_PROTO']);
- }
-
-
- return $proto === 'https' ? 'https' : 'http';
- }
- if (isset($this->server['HTTPS'])
- && $this->server['HTTPS'] !== null
- && $this->server['HTTPS'] !== 'off'
- && $this->server['HTTPS'] !== '') {
- return 'https';
- }
- return 'http';
- }
-
- public function getHttpProtocol(): string {
- $claimedProtocol = $this->server['SERVER_PROTOCOL'];
- if (\is_string($claimedProtocol)) {
- $claimedProtocol = strtoupper($claimedProtocol);
- }
- $validProtocols = [
- 'HTTP/1.0',
- 'HTTP/1.1',
- 'HTTP/2',
- ];
- if (\in_array($claimedProtocol, $validProtocols, true)) {
- return $claimedProtocol;
- }
- return 'HTTP/1.1';
- }
-
- public function getRequestUri(): string {
- $uri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
- if ($this->config->getSystemValueString('overwritewebroot') !== '' && $this->isOverwriteCondition()) {
- $uri = $this->getScriptName() . substr($uri, \strlen($this->server['SCRIPT_NAME']));
- }
- return $uri;
- }
-
- public function getRawPathInfo(): string {
- $requestUri = isset($this->server['REQUEST_URI']) ? $this->server['REQUEST_URI'] : '';
-
- $requestUri = preg_replace('%/{2,}%', '/', $requestUri);
-
- if ($pos = strpos($requestUri, '?')) {
- $requestUri = substr($requestUri, 0, $pos);
- }
- $scriptName = $this->server['SCRIPT_NAME'];
- $pathInfo = $requestUri;
-
-
- [$path, $name] = \Sabre\Uri\split($scriptName);
- if (!empty($path)) {
- if ($path === $pathInfo || str_starts_with($pathInfo, $path . '/')) {
- $pathInfo = substr($pathInfo, \strlen($path));
- } else {
- throw new \Exception("The requested uri($requestUri) cannot be processed by the script '$scriptName')");
- }
- }
- if ($name === null) {
- $name = '';
- }
- if (str_starts_with($pathInfo, '/' . $name)) {
- $pathInfo = substr($pathInfo, \strlen($name) + 1);
- }
- if ($name !== '' && str_starts_with($pathInfo, $name)) {
- $pathInfo = substr($pathInfo, \strlen($name));
- }
- if ($pathInfo === false || $pathInfo === '/') {
- return '';
- } else {
- return $pathInfo;
- }
- }
-
- public function getPathInfo() {
- $pathInfo = $this->getRawPathInfo();
- return \Sabre\HTTP\decodePath($pathInfo);
- }
-
- public function getScriptName(): string {
- $name = $this->server['SCRIPT_NAME'];
- $overwriteWebRoot = $this->config->getSystemValueString('overwritewebroot');
- if ($overwriteWebRoot !== '' && $this->isOverwriteCondition()) {
-
- $serverRoot = str_replace('\\', '/', substr(__DIR__, 0, -\strlen('lib/private/appframework/http/')));
- $suburi = str_replace('\\', '/', substr(realpath($this->server['SCRIPT_FILENAME']), \strlen($serverRoot)));
- $name = '/' . ltrim($overwriteWebRoot . $suburi, '/');
- }
- return $name;
- }
-
- public function isUserAgent(array $agent): bool {
- if (!isset($this->server['HTTP_USER_AGENT'])) {
- return false;
- }
- foreach ($agent as $regex) {
- if (preg_match($regex, $this->server['HTTP_USER_AGENT'])) {
- return true;
- }
- }
- return false;
- }
-
- public function getInsecureServerHost(): string {
- if ($this->fromTrustedProxy() && $this->getOverwriteHost() !== null) {
- return $this->getOverwriteHost();
- }
- $host = 'localhost';
- if ($this->fromTrustedProxy() && isset($this->server['HTTP_X_FORWARDED_HOST'])) {
- if (str_contains($this->server['HTTP_X_FORWARDED_HOST'], ',')) {
- $parts = explode(',', $this->server['HTTP_X_FORWARDED_HOST']);
- $host = trim(current($parts));
- } else {
- $host = $this->server['HTTP_X_FORWARDED_HOST'];
- }
- } else {
- if (isset($this->server['HTTP_HOST'])) {
- $host = $this->server['HTTP_HOST'];
- } elseif (isset($this->server['SERVER_NAME'])) {
- $host = $this->server['SERVER_NAME'];
- }
- }
- return $host;
- }
-
- public function getServerHost(): string {
-
- $host = $this->getOverwriteHost();
- if ($host !== null) {
- return $host;
- }
-
- $host = $this->getInsecureServerHost();
-
-
-
- $trustedDomainHelper = new TrustedDomainHelper($this->config);
- if ($trustedDomainHelper->isTrustedDomain($host)) {
- return $host;
- }
- $trustedList = (array)$this->config->getSystemValue('trusted_domains', []);
- if (count($trustedList) > 0) {
- return reset($trustedList);
- }
- return '';
- }
-
- private function getOverwriteHost() {
- if ($this->config->getSystemValueString('overwritehost') !== '' && $this->isOverwriteCondition()) {
- return $this->config->getSystemValueString('overwritehost');
- }
- return null;
- }
- private function fromTrustedProxy(): bool {
- $remoteAddress = isset($this->server['REMOTE_ADDR']) ? $this->server['REMOTE_ADDR'] : '';
- $trustedProxies = $this->config->getSystemValue('trusted_proxies', []);
- return \is_array($trustedProxies) && $this->isTrustedProxy($trustedProxies, $remoteAddress);
- }
- }
|