CORSMiddleware.php 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  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(IRequest $request,
  40. ControllerMethodReflector $reflector,
  41. Session $session,
  42. IThrottler $throttler,
  43. private readonly LoggerInterface $logger,
  44. ) {
  45. $this->request = $request;
  46. $this->reflector = $reflector;
  47. $this->session = $session;
  48. $this->throttler = $throttler;
  49. }
  50. /**
  51. * This is being run in normal order before the controller is being
  52. * called which allows several modifications and checks
  53. *
  54. * @param Controller $controller the controller that is being called
  55. * @param string $methodName the name of the method that will be called on
  56. * the controller
  57. * @throws SecurityException
  58. * @since 6.0.0
  59. */
  60. public function beforeController($controller, $methodName) {
  61. $reflectionMethod = new ReflectionMethod($controller, $methodName);
  62. // ensure that @CORS annotated API routes are not used in conjunction
  63. // with session authentication since this enables CSRF attack vectors
  64. if ($this->hasAnnotationOrAttribute($reflectionMethod, 'CORS', CORS::class) &&
  65. (!$this->hasAnnotationOrAttribute($reflectionMethod, 'PublicPage', PublicPage::class) || $this->session->isLoggedIn())) {
  66. $user = array_key_exists('PHP_AUTH_USER', $this->request->server) ? $this->request->server['PHP_AUTH_USER'] : null;
  67. $pass = array_key_exists('PHP_AUTH_PW', $this->request->server) ? $this->request->server['PHP_AUTH_PW'] : null;
  68. // Allow to use the current session if a CSRF token is provided
  69. if ($this->request->passesCSRFCheck()) {
  70. return;
  71. }
  72. // Skip CORS check for requests with AppAPI auth.
  73. if ($this->session->getSession() instanceof ISession && $this->session->getSession()->get('app_api') === true) {
  74. return;
  75. }
  76. $this->session->logout();
  77. try {
  78. if ($user === null || $pass === null || !$this->session->logClientIn($user, $pass, $this->request, $this->throttler)) {
  79. throw new SecurityException('CORS requires basic auth', Http::STATUS_UNAUTHORIZED);
  80. }
  81. } catch (PasswordLoginForbiddenException $ex) {
  82. throw new SecurityException('Password login forbidden, use token instead', Http::STATUS_UNAUTHORIZED);
  83. }
  84. }
  85. }
  86. /**
  87. * @template T
  88. *
  89. * @param ReflectionMethod $reflectionMethod
  90. * @param string $annotationName
  91. * @param class-string<T> $attributeClass
  92. * @return boolean
  93. */
  94. protected function hasAnnotationOrAttribute(ReflectionMethod $reflectionMethod, string $annotationName, string $attributeClass): bool {
  95. if ($this->reflector->hasAnnotation($annotationName)) {
  96. return true;
  97. }
  98. if (!empty($reflectionMethod->getAttributes($attributeClass))) {
  99. $this->logger->debug($reflectionMethod->getDeclaringClass()->getName() . '::' . $reflectionMethod->getName() . ' uses the @' . $annotationName . ' annotation and should use the #[' . $attributeClass . '] attribute instead');
  100. return true;
  101. }
  102. return false;
  103. }
  104. /**
  105. * This is being run after a successful controller method call and allows
  106. * the manipulation of a Response object. The middleware is run in reverse order
  107. *
  108. * @param Controller $controller the controller that is being called
  109. * @param string $methodName the name of the method that will be called on
  110. * the controller
  111. * @param Response $response the generated response from the controller
  112. * @return Response a Response object
  113. * @throws SecurityException
  114. */
  115. public function afterController($controller, $methodName, Response $response) {
  116. // only react if it's a CORS request and if the request sends origin and
  117. if (isset($this->request->server['HTTP_ORIGIN'])) {
  118. $reflectionMethod = new ReflectionMethod($controller, $methodName);
  119. if ($this->hasAnnotationOrAttribute($reflectionMethod, 'CORS', CORS::class)) {
  120. // allow credentials headers must not be true or CSRF is possible
  121. // otherwise
  122. foreach ($response->getHeaders() as $header => $value) {
  123. if (strtolower($header) === 'access-control-allow-credentials' &&
  124. strtolower(trim($value)) === 'true') {
  125. $msg = 'Access-Control-Allow-Credentials must not be '.
  126. 'set to true in order to prevent CSRF';
  127. throw new SecurityException($msg);
  128. }
  129. }
  130. $origin = $this->request->server['HTTP_ORIGIN'];
  131. $response->addHeader('Access-Control-Allow-Origin', $origin);
  132. }
  133. }
  134. return $response;
  135. }
  136. /**
  137. * If an SecurityException is being caught return a JSON error response
  138. *
  139. * @param Controller $controller the controller that is being called
  140. * @param string $methodName the name of the method that will be called on
  141. * the controller
  142. * @param \Exception $exception the thrown exception
  143. * @throws \Exception the passed in exception if it can't handle it
  144. * @return Response a Response object or null in case that the exception could not be handled
  145. */
  146. public function afterException($controller, $methodName, \Exception $exception) {
  147. if ($exception instanceof SecurityException) {
  148. $response = new JSONResponse(['message' => $exception->getMessage()]);
  149. if ($exception->getCode() !== 0) {
  150. $response->setStatus($exception->getCode());
  151. } else {
  152. $response->setStatus(Http::STATUS_INTERNAL_SERVER_ERROR);
  153. }
  154. return $response;
  155. }
  156. throw $exception;
  157. }
  158. }