CORSMiddleware.php 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\AppFramework\Middleware\Security;
  8. use OC\AppFramework\Middleware\Security\Exceptions\SecurityException;
  9. use OC\AppFramework\Utility\ControllerMethodReflector;
  10. use OC\Authentication\Exceptions\PasswordLoginForbiddenException;
  11. use OC\User\Session;
  12. use OCP\AppFramework\Controller;
  13. use OCP\AppFramework\Http;
  14. use OCP\AppFramework\Http\Attribute\CORS;
  15. use OCP\AppFramework\Http\Attribute\PublicPage;
  16. use OCP\AppFramework\Http\JSONResponse;
  17. use OCP\AppFramework\Http\Response;
  18. use OCP\AppFramework\Middleware;
  19. use OCP\IRequest;
  20. use OCP\ISession;
  21. use OCP\Security\Bruteforce\IThrottler;
  22. use Psr\Log\LoggerInterface;
  23. use ReflectionMethod;
  24. /**
  25. * This middleware sets the correct CORS headers on a response if the
  26. * controller has the @CORS annotation. This is needed for webapps that want
  27. * to access an API and don't run on the same domain, see
  28. * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
  29. */
  30. class CORSMiddleware extends Middleware {
  31. /** @var IRequest */
  32. private $request;
  33. /** @var ControllerMethodReflector */
  34. private $reflector;
  35. /** @var Session */
  36. private $session;
  37. /** @var IThrottler */
  38. private $throttler;
  39. public function __construct(
  40. IRequest $request,
  41. ControllerMethodReflector $reflector,
  42. Session $session,
  43. IThrottler $throttler,
  44. private readonly LoggerInterface $logger,
  45. ) {
  46. $this->request = $request;
  47. $this->reflector = $reflector;
  48. $this->session = $session;
  49. $this->throttler = $throttler;
  50. }
  51. /**
  52. * This is being run in normal order before the controller is being
  53. * called which allows several modifications and checks
  54. *
  55. * @param Controller $controller the controller that is being called
  56. * @param string $methodName the name of the method that will be called on
  57. * the controller
  58. * @throws SecurityException
  59. * @since 6.0.0
  60. */
  61. public function beforeController($controller, $methodName) {
  62. $reflectionMethod = new ReflectionMethod($controller, $methodName);
  63. // ensure that @CORS annotated API routes are not used in conjunction
  64. // with session authentication since this enables CSRF attack vectors
  65. if ($this->hasAnnotationOrAttribute($reflectionMethod, 'CORS', CORS::class) &&
  66. (!$this->hasAnnotationOrAttribute($reflectionMethod, 'PublicPage', PublicPage::class) || $this->session->isLoggedIn())) {
  67. $user = array_key_exists('PHP_AUTH_USER', $this->request->server) ? $this->request->server['PHP_AUTH_USER'] : null;
  68. $pass = array_key_exists('PHP_AUTH_PW', $this->request->server) ? $this->request->server['PHP_AUTH_PW'] : null;
  69. // Allow to use the current session if a CSRF token is provided
  70. if ($this->request->passesCSRFCheck()) {
  71. return;
  72. }
  73. // Skip CORS check for requests with AppAPI auth.
  74. if ($this->session->getSession() instanceof ISession && $this->session->getSession()->get('app_api') === true) {
  75. return;
  76. }
  77. $this->session->logout();
  78. try {
  79. if ($user === null || $pass === null || !$this->session->logClientIn($user, $pass, $this->request, $this->throttler)) {
  80. throw new SecurityException('CORS requires basic auth', Http::STATUS_UNAUTHORIZED);
  81. }
  82. } catch (PasswordLoginForbiddenException $ex) {
  83. throw new SecurityException('Password login forbidden, use token instead', Http::STATUS_UNAUTHORIZED);
  84. }
  85. }
  86. }
  87. /**
  88. * @template T
  89. *
  90. * @param ReflectionMethod $reflectionMethod
  91. * @param string $annotationName
  92. * @param class-string<T> $attributeClass
  93. * @return boolean
  94. */
  95. protected function hasAnnotationOrAttribute(ReflectionMethod $reflectionMethod, string $annotationName, string $attributeClass): bool {
  96. if ($this->reflector->hasAnnotation($annotationName)) {
  97. $this->logger->debug($reflectionMethod->getDeclaringClass()->getName() . '::' . $reflectionMethod->getName() . ' uses the @' . $annotationName . ' annotation and should use the #[' . $attributeClass . '] attribute instead');
  98. return true;
  99. }
  100. if (!empty($reflectionMethod->getAttributes($attributeClass))) {
  101. return true;
  102. }
  103. return false;
  104. }
  105. /**
  106. * This is being run after a successful controller method call and allows
  107. * the manipulation of a Response object. The middleware is run in reverse order
  108. *
  109. * @param Controller $controller the controller that is being called
  110. * @param string $methodName the name of the method that will be called on
  111. * the controller
  112. * @param Response $response the generated response from the controller
  113. * @return Response a Response object
  114. * @throws SecurityException
  115. */
  116. public function afterController($controller, $methodName, Response $response) {
  117. // only react if it's a CORS request and if the request sends origin and
  118. if (isset($this->request->server['HTTP_ORIGIN'])) {
  119. $reflectionMethod = new ReflectionMethod($controller, $methodName);
  120. if ($this->hasAnnotationOrAttribute($reflectionMethod, 'CORS', CORS::class)) {
  121. // allow credentials headers must not be true or CSRF is possible
  122. // otherwise
  123. foreach ($response->getHeaders() as $header => $value) {
  124. if (strtolower($header) === 'access-control-allow-credentials' &&
  125. strtolower(trim($value)) === 'true') {
  126. $msg = 'Access-Control-Allow-Credentials must not be ' .
  127. 'set to true in order to prevent CSRF';
  128. throw new SecurityException($msg);
  129. }
  130. }
  131. $origin = $this->request->server['HTTP_ORIGIN'];
  132. $response->addHeader('Access-Control-Allow-Origin', $origin);
  133. }
  134. }
  135. return $response;
  136. }
  137. /**
  138. * If an SecurityException is being caught return a JSON error response
  139. *
  140. * @param Controller $controller the controller that is being called
  141. * @param string $methodName the name of the method that will be called on
  142. * the controller
  143. * @param \Exception $exception the thrown exception
  144. * @throws \Exception the passed in exception if it can't handle it
  145. * @return Response a Response object or null in case that the exception could not be handled
  146. */
  147. public function afterException($controller, $methodName, \Exception $exception) {
  148. if ($exception instanceof SecurityException) {
  149. $response = new JSONResponse(['message' => $exception->getMessage()]);
  150. if ($exception->getCode() !== 0) {
  151. $response->setStatus($exception->getCode());
  152. } else {
  153. $response->setStatus(Http::STATUS_INTERNAL_SERVER_ERROR);
  154. }
  155. return $response;
  156. }
  157. throw $exception;
  158. }
  159. }