Auth.php 7.6 KB

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