You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Auth.php 7.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Arthur Schiwon <blizzz@arthur-schiwon.de>
  6. * @author Bart Visscher <bartv@thisnet.nl>
  7. * @author Bjoern Schiessle <bjoern@schiessle.org>
  8. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  9. * @author Jakob Sack <mail@jakobsack.de>
  10. * @author Joas Schilling <coding@schilljs.com>
  11. * @author Lukas Reschke <lukas@statuscode.ch>
  12. * @author Markus Goetz <markus@woboq.com>
  13. * @author Michael Gapczynski <GapczynskiM@gmail.com>
  14. * @author Morris Jobke <hey@morrisjobke.de>
  15. * @author Robin Appelman <robin@icewind.nl>
  16. * @author Thomas Müller <thomas.mueller@tmit.eu>
  17. * @author Vincent Petry <vincent@nextcloud.com>
  18. *
  19. * @license AGPL-3.0
  20. *
  21. * This code is free software: you can redistribute it and/or modify
  22. * it under the terms of the GNU Affero General Public License, version 3,
  23. * as published by the Free Software Foundation.
  24. *
  25. * This program is distributed in the hope that it will be useful,
  26. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  27. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  28. * GNU Affero General Public License for more details.
  29. *
  30. * You should have received a copy of the GNU Affero General Public License, version 3,
  31. * along with this program. If not, see <http://www.gnu.org/licenses/>
  32. *
  33. */
  34. namespace OCA\DAV\Connector\Sabre;
  35. use Exception;
  36. use OC\Authentication\Exceptions\PasswordLoginForbiddenException;
  37. use OC\Authentication\TwoFactorAuth\Manager;
  38. use OC\User\Session;
  39. use OCA\DAV\Connector\Sabre\Exception\PasswordLoginForbidden;
  40. use OCA\DAV\Connector\Sabre\Exception\TooManyRequests;
  41. use OCP\IRequest;
  42. use OCP\ISession;
  43. use OCP\Security\Bruteforce\IThrottler;
  44. use OCP\Security\Bruteforce\MaxDelayReached;
  45. use Psr\Log\LoggerInterface;
  46. use Sabre\DAV\Auth\Backend\AbstractBasic;
  47. use Sabre\DAV\Exception\NotAuthenticated;
  48. use Sabre\DAV\Exception\ServiceUnavailable;
  49. use Sabre\HTTP\RequestInterface;
  50. use Sabre\HTTP\ResponseInterface;
  51. class Auth extends AbstractBasic {
  52. public const DAV_AUTHENTICATED = 'AUTHENTICATED_TO_DAV_BACKEND';
  53. private ISession $session;
  54. private Session $userSession;
  55. private IRequest $request;
  56. private ?string $currentUser = null;
  57. private Manager $twoFactorManager;
  58. private IThrottler $throttler;
  59. public function __construct(ISession $session,
  60. Session $userSession,
  61. IRequest $request,
  62. Manager $twoFactorManager,
  63. IThrottler $throttler,
  64. string $principalPrefix = 'principals/users/') {
  65. $this->session = $session;
  66. $this->userSession = $userSession;
  67. $this->twoFactorManager = $twoFactorManager;
  68. $this->request = $request;
  69. $this->throttler = $throttler;
  70. $this->principalPrefix = $principalPrefix;
  71. // setup realm
  72. $defaults = new \OCP\Defaults();
  73. $this->realm = $defaults->getName();
  74. }
  75. /**
  76. * Whether the user has initially authenticated via DAV
  77. *
  78. * This is required for WebDAV clients that resent the cookies even when the
  79. * account was changed.
  80. *
  81. * @see https://github.com/owncloud/core/issues/13245
  82. */
  83. public function isDavAuthenticated(string $username): bool {
  84. return !is_null($this->session->get(self::DAV_AUTHENTICATED)) &&
  85. $this->session->get(self::DAV_AUTHENTICATED) === $username;
  86. }
  87. /**
  88. * Validates a username and password
  89. *
  90. * This method should return true or false depending on if login
  91. * succeeded.
  92. *
  93. * @param string $username
  94. * @param string $password
  95. * @return bool
  96. * @throws PasswordLoginForbidden
  97. */
  98. protected function validateUserPass($username, $password) {
  99. if ($this->userSession->isLoggedIn() &&
  100. $this->isDavAuthenticated($this->userSession->getUser()->getUID())
  101. ) {
  102. $this->session->close();
  103. return true;
  104. } else {
  105. try {
  106. if ($this->userSession->logClientIn($username, $password, $this->request, $this->throttler)) {
  107. $this->session->set(self::DAV_AUTHENTICATED, $this->userSession->getUser()->getUID());
  108. $this->session->close();
  109. return true;
  110. } else {
  111. $this->session->close();
  112. return false;
  113. }
  114. } catch (PasswordLoginForbiddenException $ex) {
  115. $this->session->close();
  116. throw new PasswordLoginForbidden();
  117. } catch (MaxDelayReached $ex) {
  118. $this->session->close();
  119. throw new TooManyRequests();
  120. }
  121. }
  122. }
  123. /**
  124. * @return array{bool, string}
  125. * @throws NotAuthenticated
  126. * @throws ServiceUnavailable
  127. */
  128. public function check(RequestInterface $request, ResponseInterface $response) {
  129. try {
  130. return $this->auth($request, $response);
  131. } catch (NotAuthenticated $e) {
  132. throw $e;
  133. } catch (Exception $e) {
  134. $class = get_class($e);
  135. $msg = $e->getMessage();
  136. \OC::$server->get(LoggerInterface::class)->error($e->getMessage(), ['exception' => $e]);
  137. throw new ServiceUnavailable("$class: $msg");
  138. }
  139. }
  140. /**
  141. * Checks whether a CSRF check is required on the request
  142. */
  143. private function requiresCSRFCheck(): bool {
  144. // GET requires no check at all
  145. if ($this->request->getMethod() === 'GET') {
  146. return false;
  147. }
  148. // Official Nextcloud clients require no checks
  149. if ($this->request->isUserAgent([
  150. IRequest::USER_AGENT_CLIENT_DESKTOP,
  151. IRequest::USER_AGENT_CLIENT_ANDROID,
  152. IRequest::USER_AGENT_CLIENT_IOS,
  153. ])) {
  154. return false;
  155. }
  156. // If not logged-in no check is required
  157. if (!$this->userSession->isLoggedIn()) {
  158. return false;
  159. }
  160. // POST always requires a check
  161. if ($this->request->getMethod() === 'POST') {
  162. return true;
  163. }
  164. // If logged-in AND DAV authenticated no check is required
  165. if ($this->userSession->isLoggedIn() &&
  166. $this->isDavAuthenticated($this->userSession->getUser()->getUID())) {
  167. return false;
  168. }
  169. return true;
  170. }
  171. /**
  172. * @return array{bool, string}
  173. * @throws NotAuthenticated
  174. */
  175. private function auth(RequestInterface $request, ResponseInterface $response): array {
  176. $forcedLogout = false;
  177. if (!$this->request->passesCSRFCheck() &&
  178. $this->requiresCSRFCheck()) {
  179. // In case of a fail with POST we need to recheck the credentials
  180. if ($this->request->getMethod() === 'POST') {
  181. $forcedLogout = true;
  182. } else {
  183. $response->setStatus(401);
  184. throw new \Sabre\DAV\Exception\NotAuthenticated('CSRF check not passed.');
  185. }
  186. }
  187. if ($forcedLogout) {
  188. $this->userSession->logout();
  189. } else {
  190. if ($this->twoFactorManager->needsSecondFactor($this->userSession->getUser())) {
  191. throw new \Sabre\DAV\Exception\NotAuthenticated('2FA challenge not passed.');
  192. }
  193. if (
  194. //Fix for broken webdav clients
  195. ($this->userSession->isLoggedIn() && is_null($this->session->get(self::DAV_AUTHENTICATED))) ||
  196. //Well behaved clients that only send the cookie are allowed
  197. ($this->userSession->isLoggedIn() && $this->session->get(self::DAV_AUTHENTICATED) === $this->userSession->getUser()->getUID() && $request->getHeader('Authorization') === null) ||
  198. \OC_User::handleApacheAuth()
  199. ) {
  200. $user = $this->userSession->getUser()->getUID();
  201. $this->currentUser = $user;
  202. $this->session->close();
  203. return [true, $this->principalPrefix . $user];
  204. }
  205. }
  206. if (!$this->userSession->isLoggedIn() && in_array('XMLHttpRequest', explode(',', $request->getHeader('X-Requested-With') ?? ''))) {
  207. // do not re-authenticate over ajax, use dummy auth name to prevent browser popup
  208. $response->addHeader('WWW-Authenticate', 'DummyBasic realm="' . $this->realm . '"');
  209. $response->setStatus(401);
  210. throw new \Sabre\DAV\Exception\NotAuthenticated('Cannot authenticate over ajax calls');
  211. }
  212. $data = parent::check($request, $response);
  213. if ($data[0] === true) {
  214. $startPos = strrpos($data[1], '/') + 1;
  215. $user = $this->userSession->getUser()->getUID();
  216. $data[1] = substr_replace($data[1], $user, $startPos);
  217. }
  218. return $data;
  219. }
  220. }