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.6KB

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