Auth.php 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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 OCA\DAV\Connector\Sabre;
  8. use Exception;
  9. use OC\Authentication\Exceptions\PasswordLoginForbiddenException;
  10. use OC\Authentication\TwoFactorAuth\Manager;
  11. use OC\User\Session;
  12. use OCA\DAV\Connector\Sabre\Exception\PasswordLoginForbidden;
  13. use OCA\DAV\Connector\Sabre\Exception\TooManyRequests;
  14. use OCP\Defaults;
  15. use OCP\IRequest;
  16. use OCP\ISession;
  17. use OCP\Security\Bruteforce\IThrottler;
  18. use OCP\Security\Bruteforce\MaxDelayReached;
  19. use Psr\Log\LoggerInterface;
  20. use Sabre\DAV\Auth\Backend\AbstractBasic;
  21. use Sabre\DAV\Exception\NotAuthenticated;
  22. use Sabre\DAV\Exception\ServiceUnavailable;
  23. use Sabre\HTTP\RequestInterface;
  24. use Sabre\HTTP\ResponseInterface;
  25. class Auth extends AbstractBasic {
  26. public const DAV_AUTHENTICATED = 'AUTHENTICATED_TO_DAV_BACKEND';
  27. private Session $userSession;
  28. private ?string $currentUser = null;
  29. private Manager $twoFactorManager;
  30. public function __construct(
  31. private ISession $session,
  32. Session $userSession,
  33. private IRequest $request,
  34. Manager $twoFactorManager,
  35. private IThrottler $throttler,
  36. string $principalPrefix = 'principals/users/',
  37. ) {
  38. $this->userSession = $userSession;
  39. $this->twoFactorManager = $twoFactorManager;
  40. $this->principalPrefix = $principalPrefix;
  41. // setup realm
  42. $defaults = new Defaults();
  43. $this->realm = $defaults->getName() ?: 'Nextcloud';
  44. }
  45. /**
  46. * Whether the user has initially authenticated via DAV
  47. *
  48. * This is required for WebDAV clients that resent the cookies even when the
  49. * account was changed.
  50. *
  51. * @see https://github.com/owncloud/core/issues/13245
  52. */
  53. public function isDavAuthenticated(string $username): bool {
  54. return !is_null($this->session->get(self::DAV_AUTHENTICATED)) &&
  55. $this->session->get(self::DAV_AUTHENTICATED) === $username;
  56. }
  57. /**
  58. * Validates a username and password
  59. *
  60. * This method should return true or false depending on if login
  61. * succeeded.
  62. *
  63. * @param string $username
  64. * @param string $password
  65. * @return bool
  66. * @throws PasswordLoginForbidden
  67. */
  68. protected function validateUserPass($username, $password) {
  69. if ($this->userSession->isLoggedIn() &&
  70. $this->isDavAuthenticated($this->userSession->getUser()->getUID())
  71. ) {
  72. $this->session->close();
  73. return true;
  74. } else {
  75. try {
  76. if ($this->userSession->logClientIn($username, $password, $this->request, $this->throttler)) {
  77. $this->session->set(self::DAV_AUTHENTICATED, $this->userSession->getUser()->getUID());
  78. $this->session->close();
  79. return true;
  80. } else {
  81. $this->session->close();
  82. return false;
  83. }
  84. } catch (PasswordLoginForbiddenException $ex) {
  85. $this->session->close();
  86. throw new PasswordLoginForbidden();
  87. } catch (MaxDelayReached $ex) {
  88. $this->session->close();
  89. throw new TooManyRequests();
  90. }
  91. }
  92. }
  93. /**
  94. * @return array{bool, string}
  95. * @throws NotAuthenticated
  96. * @throws ServiceUnavailable
  97. */
  98. public function check(RequestInterface $request, ResponseInterface $response) {
  99. try {
  100. return $this->auth($request, $response);
  101. } catch (NotAuthenticated $e) {
  102. throw $e;
  103. } catch (Exception $e) {
  104. $class = get_class($e);
  105. $msg = $e->getMessage();
  106. \OC::$server->get(LoggerInterface::class)->error($e->getMessage(), ['exception' => $e]);
  107. throw new ServiceUnavailable("$class: $msg");
  108. }
  109. }
  110. /**
  111. * Checks whether a CSRF check is required on the request
  112. */
  113. private function requiresCSRFCheck(): bool {
  114. // GET requires no check at all
  115. if ($this->request->getMethod() === 'GET') {
  116. return false;
  117. }
  118. // Official Nextcloud clients require no checks
  119. if ($this->request->isUserAgent([
  120. IRequest::USER_AGENT_CLIENT_DESKTOP,
  121. IRequest::USER_AGENT_CLIENT_ANDROID,
  122. IRequest::USER_AGENT_CLIENT_IOS,
  123. ])) {
  124. return false;
  125. }
  126. // If not logged-in no check is required
  127. if (!$this->userSession->isLoggedIn()) {
  128. return false;
  129. }
  130. // POST always requires a check
  131. if ($this->request->getMethod() === 'POST') {
  132. return true;
  133. }
  134. // If logged-in AND DAV authenticated no check is required
  135. if ($this->userSession->isLoggedIn() &&
  136. $this->isDavAuthenticated($this->userSession->getUser()->getUID())) {
  137. return false;
  138. }
  139. return true;
  140. }
  141. /**
  142. * @return array{bool, string}
  143. * @throws NotAuthenticated
  144. */
  145. private function auth(RequestInterface $request, ResponseInterface $response): array {
  146. $forcedLogout = false;
  147. if (!$this->request->passesCSRFCheck() &&
  148. $this->requiresCSRFCheck()) {
  149. // In case of a fail with POST we need to recheck the credentials
  150. if ($this->request->getMethod() === 'POST') {
  151. $forcedLogout = true;
  152. } else {
  153. $response->setStatus(401);
  154. throw new \Sabre\DAV\Exception\NotAuthenticated('CSRF check not passed.');
  155. }
  156. }
  157. if ($forcedLogout) {
  158. $this->userSession->logout();
  159. } else {
  160. if ($this->twoFactorManager->needsSecondFactor($this->userSession->getUser())) {
  161. throw new \Sabre\DAV\Exception\NotAuthenticated('2FA challenge not passed.');
  162. }
  163. if (
  164. //Fix for broken webdav clients
  165. ($this->userSession->isLoggedIn() && is_null($this->session->get(self::DAV_AUTHENTICATED))) ||
  166. //Well behaved clients that only send the cookie are allowed
  167. ($this->userSession->isLoggedIn() && $this->session->get(self::DAV_AUTHENTICATED) === $this->userSession->getUser()->getUID() && empty($request->getHeader('Authorization'))) ||
  168. \OC_User::handleApacheAuth()
  169. ) {
  170. $user = $this->userSession->getUser()->getUID();
  171. $this->currentUser = $user;
  172. $this->session->close();
  173. return [true, $this->principalPrefix . $user];
  174. }
  175. }
  176. $data = parent::check($request, $response);
  177. if ($data[0] === true) {
  178. $startPos = strrpos($data[1], '/') + 1;
  179. $user = $this->userSession->getUser()->getUID();
  180. $data[1] = substr_replace($data[1], $user, $startPos);
  181. } elseif (in_array('XMLHttpRequest', explode(',', $request->getHeader('X-Requested-With') ?? ''))) {
  182. // For ajax requests use dummy auth name to prevent browser popup in case of invalid creditials
  183. $response->addHeader('WWW-Authenticate', 'DummyBasic realm="' . $this->realm . '"');
  184. $response->setStatus(401);
  185. throw new \Sabre\DAV\Exception\NotAuthenticated('Cannot authenticate over ajax calls');
  186. }
  187. return $data;
  188. }
  189. }