CORSMiddleware.php 6.9 KB

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