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 8.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  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 Roeland Jago Douma <roeland@famdouma.nl>
  17. * @author Thomas Müller <thomas.mueller@tmit.eu>
  18. * @author Vincent Petry <vincent@nextcloud.com>
  19. *
  20. * @license AGPL-3.0
  21. *
  22. * This code is free software: you can redistribute it and/or modify
  23. * it under the terms of the GNU Affero General Public License, version 3,
  24. * as published by the Free Software Foundation.
  25. *
  26. * This program is distributed in the hope that it will be useful,
  27. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  28. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  29. * GNU Affero General Public License for more details.
  30. *
  31. * You should have received a copy of the GNU Affero General Public License, version 3,
  32. * along with this program. If not, see <http://www.gnu.org/licenses/>
  33. *
  34. */
  35. namespace OCA\DAV\Connector\Sabre;
  36. use Exception;
  37. use OC\Authentication\Exceptions\PasswordLoginForbiddenException;
  38. use OC\Authentication\TwoFactorAuth\Manager;
  39. use OC\Security\Bruteforce\Throttler;
  40. use OC\User\Session;
  41. use OCA\DAV\Connector\Sabre\Exception\PasswordLoginForbidden;
  42. use OCP\IRequest;
  43. use OCP\ISession;
  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. /** @var ISession */
  52. private $session;
  53. /** @var Session */
  54. private $userSession;
  55. /** @var IRequest */
  56. private $request;
  57. /** @var string */
  58. private $currentUser;
  59. /** @var Manager */
  60. private $twoFactorManager;
  61. /** @var Throttler */
  62. private $throttler;
  63. /**
  64. * @param ISession $session
  65. * @param Session $userSession
  66. * @param IRequest $request
  67. * @param Manager $twoFactorManager
  68. * @param Throttler $throttler
  69. * @param string $principalPrefix
  70. */
  71. public function __construct(ISession $session,
  72. Session $userSession,
  73. IRequest $request,
  74. Manager $twoFactorManager,
  75. Throttler $throttler,
  76. $principalPrefix = 'principals/users/') {
  77. $this->session = $session;
  78. $this->userSession = $userSession;
  79. $this->twoFactorManager = $twoFactorManager;
  80. $this->request = $request;
  81. $this->throttler = $throttler;
  82. $this->principalPrefix = $principalPrefix;
  83. // setup realm
  84. $defaults = new \OCP\Defaults();
  85. $this->realm = $defaults->getName();
  86. }
  87. /**
  88. * Whether the user has initially authenticated via DAV
  89. *
  90. * This is required for WebDAV clients that resent the cookies even when the
  91. * account was changed.
  92. *
  93. * @see https://github.com/owncloud/core/issues/13245
  94. *
  95. * @param string $username
  96. * @return bool
  97. */
  98. public function isDavAuthenticated($username) {
  99. return !is_null($this->session->get(self::DAV_AUTHENTICATED)) &&
  100. $this->session->get(self::DAV_AUTHENTICATED) === $username;
  101. }
  102. /**
  103. * Validates a username and password
  104. *
  105. * This method should return true or false depending on if login
  106. * succeeded.
  107. *
  108. * @param string $username
  109. * @param string $password
  110. * @return bool
  111. * @throws PasswordLoginForbidden
  112. */
  113. protected function validateUserPass($username, $password) {
  114. if ($this->userSession->isLoggedIn() &&
  115. $this->isDavAuthenticated($this->userSession->getUser()->getUID())
  116. ) {
  117. \OC_Util::setupFS($this->userSession->getUser()->getUID());
  118. $this->session->close();
  119. return true;
  120. } else {
  121. \OC_Util::setupFS(); //login hooks may need early access to the filesystem
  122. try {
  123. if ($this->userSession->logClientIn($username, $password, $this->request, $this->throttler)) {
  124. \OC_Util::setupFS($this->userSession->getUser()->getUID());
  125. $this->session->set(self::DAV_AUTHENTICATED, $this->userSession->getUser()->getUID());
  126. $this->session->close();
  127. return true;
  128. } else {
  129. $this->session->close();
  130. return false;
  131. }
  132. } catch (PasswordLoginForbiddenException $ex) {
  133. $this->session->close();
  134. throw new PasswordLoginForbidden();
  135. }
  136. }
  137. }
  138. /**
  139. * @param RequestInterface $request
  140. * @param ResponseInterface $response
  141. * @return array
  142. * @throws NotAuthenticated
  143. * @throws ServiceUnavailable
  144. */
  145. public function check(RequestInterface $request, ResponseInterface $response) {
  146. try {
  147. return $this->auth($request, $response);
  148. } catch (NotAuthenticated $e) {
  149. throw $e;
  150. } catch (Exception $e) {
  151. $class = get_class($e);
  152. $msg = $e->getMessage();
  153. \OC::$server->getLogger()->logException($e);
  154. throw new ServiceUnavailable("$class: $msg");
  155. }
  156. }
  157. /**
  158. * Checks whether a CSRF check is required on the request
  159. *
  160. * @return bool
  161. */
  162. private function requiresCSRFCheck() {
  163. // GET requires no check at all
  164. if ($this->request->getMethod() === 'GET') {
  165. return false;
  166. }
  167. // Official Nextcloud clients require no checks
  168. if ($this->request->isUserAgent([
  169. IRequest::USER_AGENT_CLIENT_DESKTOP,
  170. IRequest::USER_AGENT_CLIENT_ANDROID,
  171. IRequest::USER_AGENT_CLIENT_IOS,
  172. ])) {
  173. return false;
  174. }
  175. // If not logged-in no check is required
  176. if (!$this->userSession->isLoggedIn()) {
  177. return false;
  178. }
  179. // POST always requires a check
  180. if ($this->request->getMethod() === 'POST') {
  181. return true;
  182. }
  183. // If logged-in AND DAV authenticated no check is required
  184. if ($this->userSession->isLoggedIn() &&
  185. $this->isDavAuthenticated($this->userSession->getUser()->getUID())) {
  186. return false;
  187. }
  188. return true;
  189. }
  190. /**
  191. * @param RequestInterface $request
  192. * @param ResponseInterface $response
  193. * @return array
  194. * @throws NotAuthenticated
  195. */
  196. private function auth(RequestInterface $request, ResponseInterface $response) {
  197. $forcedLogout = false;
  198. if (!$this->request->passesCSRFCheck() &&
  199. $this->requiresCSRFCheck()) {
  200. // In case of a fail with POST we need to recheck the credentials
  201. if ($this->request->getMethod() === 'POST') {
  202. $forcedLogout = true;
  203. } else {
  204. $response->setStatus(401);
  205. throw new \Sabre\DAV\Exception\NotAuthenticated('CSRF check not passed.');
  206. }
  207. }
  208. if ($forcedLogout) {
  209. $this->userSession->logout();
  210. } else {
  211. if ($this->twoFactorManager->needsSecondFactor($this->userSession->getUser())) {
  212. throw new \Sabre\DAV\Exception\NotAuthenticated('2FA challenge not passed.');
  213. }
  214. if (
  215. //Fix for broken webdav clients
  216. ($this->userSession->isLoggedIn() && is_null($this->session->get(self::DAV_AUTHENTICATED))) ||
  217. //Well behaved clients that only send the cookie are allowed
  218. ($this->userSession->isLoggedIn() && $this->session->get(self::DAV_AUTHENTICATED) === $this->userSession->getUser()->getUID() && $request->getHeader('Authorization') === null) ||
  219. \OC_User::handleApacheAuth()
  220. ) {
  221. $user = $this->userSession->getUser()->getUID();
  222. \OC_Util::setupFS($user);
  223. $this->currentUser = $user;
  224. $this->session->close();
  225. return [true, $this->principalPrefix . $user];
  226. }
  227. }
  228. if (!$this->userSession->isLoggedIn() && in_array('XMLHttpRequest', explode(',', $request->getHeader('X-Requested-With')))) {
  229. // do not re-authenticate over ajax, use dummy auth name to prevent browser popup
  230. $response->addHeader('WWW-Authenticate','DummyBasic realm="' . $this->realm . '"');
  231. $response->setStatus(401);
  232. throw new \Sabre\DAV\Exception\NotAuthenticated('Cannot authenticate over ajax calls');
  233. }
  234. $data = parent::check($request, $response);
  235. if ($data[0] === true) {
  236. $startPos = strrpos($data[1], '/') + 1;
  237. $user = $this->userSession->getUser()->getUID();
  238. $data[1] = substr_replace($data[1], $user, $startPos);
  239. }
  240. return $data;
  241. }
  242. }