PublicAuth.php 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * @copyright Copyright (c) 2016, ownCloud, Inc.
  5. *
  6. * @author Björn Schießle <bjoern@schiessle.org>
  7. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  8. * @author Joas Schilling <coding@schilljs.com>
  9. * @author Lukas Reschke <lukas@statuscode.ch>
  10. * @author Maxence Lange <maxence@artificial-owl.com>
  11. * @author Robin Appelman <robin@icewind.nl>
  12. * @author Roeland Jago Douma <roeland@famdouma.nl>
  13. * @author Thomas Müller <thomas.mueller@tmit.eu>
  14. * @author Vincent Petry <vincent@nextcloud.com>
  15. *
  16. * @license AGPL-3.0
  17. *
  18. * This code is free software: you can redistribute it and/or modify
  19. * it under the terms of the GNU Affero General Public License, version 3,
  20. * as published by the Free Software Foundation.
  21. *
  22. * This program is distributed in the hope that it will be useful,
  23. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  24. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  25. * GNU Affero General Public License for more details.
  26. *
  27. * You should have received a copy of the GNU Affero General Public License, version 3,
  28. * along with this program. If not, see <http://www.gnu.org/licenses/>
  29. *
  30. */
  31. namespace OCA\DAV\Connector\Sabre;
  32. use OCP\IRequest;
  33. use OCP\ISession;
  34. use OCP\Security\Bruteforce\IThrottler;
  35. use OCP\Share\Exceptions\ShareNotFound;
  36. use OCP\Share\IManager;
  37. use OCP\Share\IShare;
  38. use Psr\Log\LoggerInterface;
  39. use Sabre\DAV\Auth\Backend\AbstractBasic;
  40. use Sabre\DAV\Exception\NotAuthenticated;
  41. use Sabre\DAV\Exception\NotFound;
  42. use Sabre\DAV\Exception\ServiceUnavailable;
  43. use Sabre\HTTP;
  44. use Sabre\HTTP\RequestInterface;
  45. use Sabre\HTTP\ResponseInterface;
  46. /**
  47. * Class PublicAuth
  48. *
  49. * @package OCA\DAV\Connector
  50. */
  51. class PublicAuth extends AbstractBasic {
  52. private const BRUTEFORCE_ACTION = 'public_dav_auth';
  53. public const DAV_AUTHENTICATED = 'public_link_authenticated';
  54. private ?IShare $share = null;
  55. private IManager $shareManager;
  56. private ISession $session;
  57. private IRequest $request;
  58. private IThrottler $throttler;
  59. private LoggerInterface $logger;
  60. public function __construct(IRequest $request,
  61. IManager $shareManager,
  62. ISession $session,
  63. IThrottler $throttler,
  64. LoggerInterface $logger) {
  65. $this->request = $request;
  66. $this->shareManager = $shareManager;
  67. $this->session = $session;
  68. $this->throttler = $throttler;
  69. $this->logger = $logger;
  70. // setup realm
  71. $defaults = new \OCP\Defaults();
  72. $this->realm = $defaults->getName();
  73. }
  74. /**
  75. * @param RequestInterface $request
  76. * @param ResponseInterface $response
  77. *
  78. * @return array
  79. * @throws NotAuthenticated
  80. * @throws ServiceUnavailable
  81. */
  82. public function check(RequestInterface $request, ResponseInterface $response): array {
  83. try {
  84. $this->throttler->sleepDelayOrThrowOnMax($this->request->getRemoteAddress(), self::BRUTEFORCE_ACTION);
  85. $auth = new HTTP\Auth\Basic(
  86. $this->realm,
  87. $request,
  88. $response
  89. );
  90. $userpass = $auth->getCredentials();
  91. // If authentication provided, checking its validity
  92. if ($userpass && !$this->validateUserPass($userpass[0], $userpass[1])) {
  93. return [false, 'Username or password was incorrect'];
  94. }
  95. return $this->checkToken();
  96. } catch (NotAuthenticated $e) {
  97. throw $e;
  98. } catch (\Exception $e) {
  99. $class = get_class($e);
  100. $msg = $e->getMessage();
  101. $this->logger->error($e->getMessage(), ['exception' => $e]);
  102. throw new ServiceUnavailable("$class: $msg");
  103. }
  104. }
  105. /**
  106. * Extract token from request url
  107. * @return string
  108. * @throws NotFound
  109. */
  110. private function getToken(): string {
  111. $path = $this->request->getPathInfo() ?: '';
  112. // ['', 'dav', 'files', 'token']
  113. $splittedPath = explode('/', $path);
  114. if (count($splittedPath) < 4 || $splittedPath[3] === '') {
  115. throw new NotFound();
  116. }
  117. return $splittedPath[3];
  118. }
  119. /**
  120. * Check token validity
  121. * @return array
  122. * @throws NotFound
  123. * @throws NotAuthenticated
  124. */
  125. private function checkToken(): array {
  126. $token = $this->getToken();
  127. try {
  128. /** @var IShare $share */
  129. $share = $this->shareManager->getShareByToken($token);
  130. } catch (ShareNotFound $e) {
  131. $this->throttler->registerAttempt(self::BRUTEFORCE_ACTION, $this->request->getRemoteAddress());
  132. throw new NotFound();
  133. }
  134. $this->share = $share;
  135. \OC_User::setIncognitoMode(true);
  136. // If already authenticated
  137. if ($this->session->exists(self::DAV_AUTHENTICATED)
  138. && $this->session->get(self::DAV_AUTHENTICATED) === $share->getId()) {
  139. return [true, $this->principalPrefix . $token];
  140. }
  141. // If the share is protected but user is not authenticated
  142. if ($share->getPassword() !== null) {
  143. $this->throttler->registerAttempt(self::BRUTEFORCE_ACTION, $this->request->getRemoteAddress());
  144. throw new NotAuthenticated();
  145. }
  146. return [true, $this->principalPrefix . $token];
  147. }
  148. /**
  149. * Validates a username and password
  150. *
  151. * This method should return true or false depending on if login
  152. * succeeded.
  153. *
  154. * @param string $username
  155. * @param string $password
  156. *
  157. * @return bool
  158. * @throws NotAuthenticated
  159. */
  160. protected function validateUserPass($username, $password) {
  161. $this->throttler->sleepDelayOrThrowOnMax($this->request->getRemoteAddress(), self::BRUTEFORCE_ACTION);
  162. $token = $this->getToken();
  163. try {
  164. $share = $this->shareManager->getShareByToken($token);
  165. } catch (ShareNotFound $e) {
  166. $this->throttler->registerAttempt(self::BRUTEFORCE_ACTION, $this->request->getRemoteAddress());
  167. return false;
  168. }
  169. $this->share = $share;
  170. \OC_User::setIncognitoMode(true);
  171. // check if the share is password protected
  172. if ($share->getPassword() !== null) {
  173. if ($share->getShareType() === IShare::TYPE_LINK
  174. || $share->getShareType() === IShare::TYPE_EMAIL
  175. || $share->getShareType() === IShare::TYPE_CIRCLE) {
  176. if ($this->shareManager->checkPassword($share, $password)) {
  177. // If not set, set authenticated session cookie
  178. if (!$this->session->exists(self::DAV_AUTHENTICATED)
  179. || $this->session->get(self::DAV_AUTHENTICATED) !== $share->getId()) {
  180. $this->session->set(self::DAV_AUTHENTICATED, $share->getId());
  181. }
  182. return true;
  183. }
  184. if ($this->session->exists(PublicAuth::DAV_AUTHENTICATED)
  185. && $this->session->get(PublicAuth::DAV_AUTHENTICATED) === $share->getId()) {
  186. return true;
  187. }
  188. if (in_array('XMLHttpRequest', explode(',', $this->request->getHeader('X-Requested-With')))) {
  189. // do not re-authenticate over ajax, use dummy auth name to prevent browser popup
  190. http_response_code(401);
  191. header('WWW-Authenticate: DummyBasic realm="' . $this->realm . '"');
  192. throw new NotAuthenticated('Cannot authenticate over ajax calls');
  193. }
  194. $this->throttler->registerAttempt(self::BRUTEFORCE_ACTION, $this->request->getRemoteAddress());
  195. return false;
  196. } elseif ($share->getShareType() === IShare::TYPE_REMOTE) {
  197. return true;
  198. }
  199. $this->throttler->registerAttempt(self::BRUTEFORCE_ACTION, $this->request->getRemoteAddress());
  200. return false;
  201. }
  202. return true;
  203. }
  204. public function getShare(): IShare {
  205. assert($this->share !== null);
  206. return $this->share;
  207. }
  208. }