CORSMiddleware.php 6.9 KB

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