BruteForceMiddleware.php 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2023 Joas Schilling <coding@schilljs.com>
  5. * @copyright Copyright (c) 2017 Lukas Reschke <lukas@statuscode.ch>
  6. *
  7. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  8. * @author Joas Schilling <coding@schilljs.com>
  9. * @author Lukas Reschke <lukas@statuscode.ch>
  10. *
  11. * @license GNU AGPL version 3 or any later version
  12. *
  13. * This program is free software: you can redistribute it and/or modify
  14. * it under the terms of the GNU Affero General Public License as
  15. * published by the Free Software Foundation, either version 3 of the
  16. * License, or (at your option) any later version.
  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
  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\Utility\ControllerMethodReflector;
  29. use OCP\AppFramework\Controller;
  30. use OCP\AppFramework\Http;
  31. use OCP\AppFramework\Http\Attribute\BruteForceProtection;
  32. use OCP\AppFramework\Http\Response;
  33. use OCP\AppFramework\Http\TooManyRequestsResponse;
  34. use OCP\AppFramework\Middleware;
  35. use OCP\AppFramework\OCS\OCSException;
  36. use OCP\AppFramework\OCSController;
  37. use OCP\IRequest;
  38. use OCP\Security\Bruteforce\IThrottler;
  39. use OCP\Security\Bruteforce\MaxDelayReached;
  40. use Psr\Log\LoggerInterface;
  41. use ReflectionMethod;
  42. /**
  43. * Class BruteForceMiddleware performs the bruteforce protection for controllers
  44. * that are annotated with @BruteForceProtection(action=$action) whereas $action
  45. * is the action that should be logged within the database.
  46. *
  47. * @package OC\AppFramework\Middleware\Security
  48. */
  49. class BruteForceMiddleware extends Middleware {
  50. private int $delaySlept = 0;
  51. public function __construct(
  52. protected ControllerMethodReflector $reflector,
  53. protected IThrottler $throttler,
  54. protected IRequest $request,
  55. protected LoggerInterface $logger,
  56. ) {
  57. }
  58. /**
  59. * {@inheritDoc}
  60. */
  61. public function beforeController($controller, $methodName) {
  62. parent::beforeController($controller, $methodName);
  63. if ($this->reflector->hasAnnotation('BruteForceProtection')) {
  64. $action = $this->reflector->getAnnotationParameter('BruteForceProtection', 'action');
  65. $this->delaySlept += $this->throttler->sleepDelayOrThrowOnMax($this->request->getRemoteAddress(), $action);
  66. } else {
  67. $reflectionMethod = new ReflectionMethod($controller, $methodName);
  68. $attributes = $reflectionMethod->getAttributes(BruteForceProtection::class);
  69. if (!empty($attributes)) {
  70. $remoteAddress = $this->request->getRemoteAddress();
  71. foreach ($attributes as $attribute) {
  72. /** @var BruteForceProtection $protection */
  73. $protection = $attribute->newInstance();
  74. $action = $protection->getAction();
  75. $this->delaySlept += $this->throttler->sleepDelayOrThrowOnMax($remoteAddress, $action);
  76. }
  77. }
  78. }
  79. }
  80. /**
  81. * {@inheritDoc}
  82. */
  83. public function afterController($controller, $methodName, Response $response) {
  84. if ($response->isThrottled()) {
  85. try {
  86. if ($this->reflector->hasAnnotation('BruteForceProtection')) {
  87. $action = $this->reflector->getAnnotationParameter('BruteForceProtection', 'action');
  88. $ip = $this->request->getRemoteAddress();
  89. $this->throttler->registerAttempt($action, $ip, $response->getThrottleMetadata());
  90. $this->delaySlept += $this->throttler->sleepDelayOrThrowOnMax($ip, $action);
  91. } else {
  92. $reflectionMethod = new ReflectionMethod($controller, $methodName);
  93. $attributes = $reflectionMethod->getAttributes(BruteForceProtection::class);
  94. if (!empty($attributes)) {
  95. $ip = $this->request->getRemoteAddress();
  96. $metaData = $response->getThrottleMetadata();
  97. foreach ($attributes as $attribute) {
  98. /** @var BruteForceProtection $protection */
  99. $protection = $attribute->newInstance();
  100. $action = $protection->getAction();
  101. if (!isset($metaData['action']) || $metaData['action'] === $action) {
  102. $this->throttler->registerAttempt($action, $ip, $metaData);
  103. $this->delaySlept += $this->throttler->sleepDelayOrThrowOnMax($ip, $action);
  104. }
  105. }
  106. } else {
  107. $this->logger->debug('Response for ' . get_class($controller) . '::' . $methodName . ' got bruteforce throttled but has no annotation nor attribute defined.');
  108. }
  109. }
  110. } catch (MaxDelayReached $e) {
  111. if ($controller instanceof OCSController) {
  112. throw new OCSException($e->getMessage(), Http::STATUS_TOO_MANY_REQUESTS);
  113. }
  114. return new TooManyRequestsResponse();
  115. }
  116. }
  117. if ($this->delaySlept) {
  118. $response->addHeader('X-Nextcloud-Bruteforce-Throttled', $this->delaySlept . 'ms');
  119. }
  120. return parent::afterController($controller, $methodName, $response);
  121. }
  122. /**
  123. * @param Controller $controller
  124. * @param string $methodName
  125. * @param \Exception $exception
  126. * @throws \Exception
  127. * @return Response
  128. */
  129. public function afterException($controller, $methodName, \Exception $exception): Response {
  130. if ($exception instanceof MaxDelayReached) {
  131. if ($controller instanceof OCSController) {
  132. throw new OCSException($exception->getMessage(), Http::STATUS_TOO_MANY_REQUESTS);
  133. }
  134. return new TooManyRequestsResponse();
  135. }
  136. throw $exception;
  137. }
  138. }