CORSMiddleware.php 6.0 KB

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