CORSMiddleware.php 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bernhard Posselt <dev@bernhard-posselt.com>
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author korelstar <korelstar@users.noreply.github.com>
  8. * @author Lukas Reschke <lukas@statuscode.ch>
  9. * @author Morris Jobke <hey@morrisjobke.de>
  10. * @author Stefan Weil <sw@weilnetz.de>
  11. *
  12. * @license AGPL-3.0
  13. *
  14. * This code is free software: you can redistribute it and/or modify
  15. * it under the terms of the GNU Affero General Public License, version 3,
  16. * as published by the Free Software Foundation.
  17. *
  18. * This program is distributed in the hope that it will be useful,
  19. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. * GNU Affero General Public License for more details.
  22. *
  23. * You should have received a copy of the GNU Affero General Public License, version 3,
  24. * along with this program. If not, see <http://www.gnu.org/licenses/>
  25. *
  26. */
  27. namespace OC\AppFramework\Middleware\Security;
  28. use OC\AppFramework\Middleware\Security\Exceptions\SecurityException;
  29. use OC\AppFramework\Utility\ControllerMethodReflector;
  30. use OC\Authentication\Exceptions\PasswordLoginForbiddenException;
  31. use OC\User\Session;
  32. use OCP\AppFramework\Controller;
  33. use OCP\AppFramework\Http;
  34. use OCP\AppFramework\Http\Attribute\CORS;
  35. use OCP\AppFramework\Http\Attribute\PublicPage;
  36. use OCP\AppFramework\Http\JSONResponse;
  37. use OCP\AppFramework\Http\Response;
  38. use OCP\AppFramework\Middleware;
  39. use OCP\IRequest;
  40. use OCP\Security\Bruteforce\IThrottler;
  41. use ReflectionMethod;
  42. /**
  43. * This middleware sets the correct CORS headers on a response if the
  44. * controller has the @CORS annotation. This is needed for webapps that want
  45. * to access an API and don't run on the same domain, see
  46. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  47. */
  48. class CORSMiddleware extends Middleware {
  49. /** @var IRequest */
  50. private $request;
  51. /** @var ControllerMethodReflector */
  52. private $reflector;
  53. /** @var Session */
  54. private $session;
  55. /** @var IThrottler */
  56. private $throttler;
  57. public function __construct(IRequest $request,
  58. ControllerMethodReflector $reflector,
  59. Session $session,
  60. IThrottler $throttler) {
  61. $this->request = $request;
  62. $this->reflector = $reflector;
  63. $this->session = $session;
  64. $this->throttler = $throttler;
  65. }
  66. /**
  67. * This is being run in normal order before the controller is being
  68. * called which allows several modifications and checks
  69. *
  70. * @param Controller $controller the controller that is being called
  71. * @param string $methodName the name of the method that will be called on
  72. * the controller
  73. * @throws SecurityException
  74. * @since 6.0.0
  75. */
  76. public function beforeController($controller, $methodName) {
  77. $reflectionMethod = new ReflectionMethod($controller, $methodName);
  78. // ensure that @CORS annotated API routes are not used in conjunction
  79. // with session authentication since this enables CSRF attack vectors
  80. if ($this->hasAnnotationOrAttribute($reflectionMethod, 'CORS', CORS::class) &&
  81. (!$this->hasAnnotationOrAttribute($reflectionMethod, 'PublicPage', PublicPage::class) || $this->session->isLoggedIn())) {
  82. $user = array_key_exists('PHP_AUTH_USER', $this->request->server) ? $this->request->server['PHP_AUTH_USER'] : null;
  83. $pass = array_key_exists('PHP_AUTH_PW', $this->request->server) ? $this->request->server['PHP_AUTH_PW'] : null;
  84. // Allow to use the current session if a CSRF token is provided
  85. if ($this->request->passesCSRFCheck()) {
  86. return;
  87. }
  88. $this->session->logout();
  89. try {
  90. if ($user === null || $pass === null || !$this->session->logClientIn($user, $pass, $this->request, $this->throttler)) {
  91. throw new SecurityException('CORS requires basic auth', Http::STATUS_UNAUTHORIZED);
  92. }
  93. } catch (PasswordLoginForbiddenException $ex) {
  94. throw new SecurityException('Password login forbidden, use token instead', Http::STATUS_UNAUTHORIZED);
  95. }
  96. }
  97. }
  98. /**
  99. * @template T
  100. *
  101. * @param ReflectionMethod $reflectionMethod
  102. * @param string $annotationName
  103. * @param class-string<T> $attributeClass
  104. * @return boolean
  105. */
  106. protected function hasAnnotationOrAttribute(ReflectionMethod $reflectionMethod, string $annotationName, string $attributeClass): bool {
  107. if ($this->reflector->hasAnnotation($annotationName)) {
  108. return true;
  109. }
  110. if (!empty($reflectionMethod->getAttributes($attributeClass))) {
  111. return true;
  112. }
  113. return false;
  114. }
  115. /**
  116. * This is being run after a successful controller method call and allows
  117. * the manipulation of a Response object. The middleware is run in reverse order
  118. *
  119. * @param Controller $controller the controller that is being called
  120. * @param string $methodName the name of the method that will be called on
  121. * the controller
  122. * @param Response $response the generated response from the controller
  123. * @return Response a Response object
  124. * @throws SecurityException
  125. */
  126. public function afterController($controller, $methodName, Response $response) {
  127. // only react if it's a CORS request and if the request sends origin and
  128. if (isset($this->request->server['HTTP_ORIGIN'])) {
  129. $reflectionMethod = new ReflectionMethod($controller, $methodName);
  130. if ($this->hasAnnotationOrAttribute($reflectionMethod, 'CORS', CORS::class)) {
  131. // allow credentials headers must not be true or CSRF is possible
  132. // otherwise
  133. foreach ($response->getHeaders() as $header => $value) {
  134. if (strtolower($header) === 'access-control-allow-credentials' &&
  135. strtolower(trim($value)) === 'true') {
  136. $msg = 'Access-Control-Allow-Credentials must not be '.
  137. 'set to true in order to prevent CSRF';
  138. throw new SecurityException($msg);
  139. }
  140. }
  141. $origin = $this->request->server['HTTP_ORIGIN'];
  142. $response->addHeader('Access-Control-Allow-Origin', $origin);
  143. }
  144. }
  145. return $response;
  146. }
  147. /**
  148. * If an SecurityException is being caught return a JSON error response
  149. *
  150. * @param Controller $controller the controller that is being called
  151. * @param string $methodName the name of the method that will be called on
  152. * the controller
  153. * @param \Exception $exception the thrown exception
  154. * @throws \Exception the passed in exception if it can't handle it
  155. * @return Response a Response object or null in case that the exception could not be handled
  156. */
  157. public function afterException($controller, $methodName, \Exception $exception) {
  158. if ($exception instanceof SecurityException) {
  159. $response = new JSONResponse(['message' => $exception->getMessage()]);
  160. if ($exception->getCode() !== 0) {
  161. $response->setStatus($exception->getCode());
  162. } else {
  163. $response->setStatus(Http::STATUS_INTERNAL_SERVER_ERROR);
  164. }
  165. return $response;
  166. }
  167. throw $exception;
  168. }
  169. }