Auth.php 6.4 KB

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