ShareController.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OCA\Files_Sharing\Controller;
  8. use OC\Security\CSP\ContentSecurityPolicy;
  9. use OC_Files;
  10. use OC_Util;
  11. use OCA\DAV\Connector\Sabre\PublicAuth;
  12. use OCA\FederatedFileSharing\FederatedShareProvider;
  13. use OCA\Files_Sharing\Activity\Providers\Downloads;
  14. use OCA\Files_Sharing\Event\BeforeTemplateRenderedEvent;
  15. use OCA\Files_Sharing\Event\ShareLinkAccessedEvent;
  16. use OCP\Accounts\IAccountManager;
  17. use OCP\AppFramework\AuthPublicShareController;
  18. use OCP\AppFramework\Http\Attribute\NoCSRFRequired;
  19. use OCP\AppFramework\Http\Attribute\OpenAPI;
  20. use OCP\AppFramework\Http\Attribute\PublicPage;
  21. use OCP\AppFramework\Http\NotFoundResponse;
  22. use OCP\AppFramework\Http\TemplateResponse;
  23. use OCP\Defaults;
  24. use OCP\EventDispatcher\IEventDispatcher;
  25. use OCP\Files\Folder;
  26. use OCP\Files\IRootFolder;
  27. use OCP\Files\NotFoundException;
  28. use OCP\IConfig;
  29. use OCP\IL10N;
  30. use OCP\IPreview;
  31. use OCP\IRequest;
  32. use OCP\ISession;
  33. use OCP\IURLGenerator;
  34. use OCP\IUserManager;
  35. use OCP\Security\ISecureRandom;
  36. use OCP\Share;
  37. use OCP\Share\Exceptions\ShareNotFound;
  38. use OCP\Share\IManager as ShareManager;
  39. use OCP\Share\IPublicShareTemplateFactory;
  40. use OCP\Share\IShare;
  41. use OCP\Template;
  42. /**
  43. * @package OCA\Files_Sharing\Controllers
  44. */
  45. #[OpenAPI(scope: OpenAPI::SCOPE_IGNORE)]
  46. class ShareController extends AuthPublicShareController {
  47. protected ?Share\IShare $share = null;
  48. public const SHARE_ACCESS = 'access';
  49. public const SHARE_AUTH = 'auth';
  50. public const SHARE_DOWNLOAD = 'download';
  51. public function __construct(
  52. string $appName,
  53. IRequest $request,
  54. protected IConfig $config,
  55. IURLGenerator $urlGenerator,
  56. protected IUserManager $userManager,
  57. protected \OCP\Activity\IManager $activityManager,
  58. protected ShareManager $shareManager,
  59. ISession $session,
  60. protected IPreview $previewManager,
  61. protected IRootFolder $rootFolder,
  62. protected FederatedShareProvider $federatedShareProvider,
  63. protected IAccountManager $accountManager,
  64. protected IEventDispatcher $eventDispatcher,
  65. protected IL10N $l10n,
  66. protected ISecureRandom $secureRandom,
  67. protected Defaults $defaults,
  68. private IPublicShareTemplateFactory $publicShareTemplateFactory,
  69. ) {
  70. parent::__construct($appName, $request, $session, $urlGenerator);
  71. }
  72. /**
  73. * Show the authentication page
  74. * The form has to submit to the authenticate method route
  75. */
  76. #[PublicPage]
  77. #[NoCSRFRequired]
  78. public function showAuthenticate(): TemplateResponse {
  79. $templateParameters = ['share' => $this->share];
  80. $this->eventDispatcher->dispatchTyped(new BeforeTemplateRenderedEvent($this->share, BeforeTemplateRenderedEvent::SCOPE_PUBLIC_SHARE_AUTH));
  81. $response = new TemplateResponse('core', 'publicshareauth', $templateParameters, 'guest');
  82. if ($this->share->getSendPasswordByTalk()) {
  83. $csp = new ContentSecurityPolicy();
  84. $csp->addAllowedConnectDomain('*');
  85. $csp->addAllowedMediaDomain('blob:');
  86. $response->setContentSecurityPolicy($csp);
  87. }
  88. return $response;
  89. }
  90. /**
  91. * The template to show when authentication failed
  92. */
  93. protected function showAuthFailed(): TemplateResponse {
  94. $templateParameters = ['share' => $this->share, 'wrongpw' => true];
  95. $this->eventDispatcher->dispatchTyped(new BeforeTemplateRenderedEvent($this->share, BeforeTemplateRenderedEvent::SCOPE_PUBLIC_SHARE_AUTH));
  96. $response = new TemplateResponse('core', 'publicshareauth', $templateParameters, 'guest');
  97. if ($this->share->getSendPasswordByTalk()) {
  98. $csp = new ContentSecurityPolicy();
  99. $csp->addAllowedConnectDomain('*');
  100. $csp->addAllowedMediaDomain('blob:');
  101. $response->setContentSecurityPolicy($csp);
  102. }
  103. return $response;
  104. }
  105. /**
  106. * The template to show after user identification
  107. */
  108. protected function showIdentificationResult(bool $success = false): TemplateResponse {
  109. $templateParameters = ['share' => $this->share, 'identityOk' => $success];
  110. $this->eventDispatcher->dispatchTyped(new BeforeTemplateRenderedEvent($this->share, BeforeTemplateRenderedEvent::SCOPE_PUBLIC_SHARE_AUTH));
  111. $response = new TemplateResponse('core', 'publicshareauth', $templateParameters, 'guest');
  112. if ($this->share->getSendPasswordByTalk()) {
  113. $csp = new ContentSecurityPolicy();
  114. $csp->addAllowedConnectDomain('*');
  115. $csp->addAllowedMediaDomain('blob:');
  116. $response->setContentSecurityPolicy($csp);
  117. }
  118. return $response;
  119. }
  120. /**
  121. * Validate the identity token of a public share
  122. *
  123. * @param ?string $identityToken
  124. * @return bool
  125. */
  126. protected function validateIdentity(?string $identityToken = null): bool {
  127. if ($this->share->getShareType() !== IShare::TYPE_EMAIL) {
  128. return false;
  129. }
  130. if ($identityToken === null || $this->share->getSharedWith() === null) {
  131. return false;
  132. }
  133. return $identityToken === $this->share->getSharedWith();
  134. }
  135. /**
  136. * Generates a password for the share, respecting any password policy defined
  137. */
  138. protected function generatePassword(): void {
  139. $event = new \OCP\Security\Events\GenerateSecurePasswordEvent();
  140. $this->eventDispatcher->dispatchTyped($event);
  141. $password = $event->getPassword() ?? $this->secureRandom->generate(20);
  142. $this->share->setPassword($password);
  143. $this->shareManager->updateShare($this->share);
  144. }
  145. protected function verifyPassword(string $password): bool {
  146. return $this->shareManager->checkPassword($this->share, $password);
  147. }
  148. protected function getPasswordHash(): ?string {
  149. return $this->share->getPassword();
  150. }
  151. public function isValidToken(): bool {
  152. try {
  153. $this->share = $this->shareManager->getShareByToken($this->getToken());
  154. } catch (ShareNotFound $e) {
  155. return false;
  156. }
  157. return true;
  158. }
  159. protected function isPasswordProtected(): bool {
  160. return $this->share->getPassword() !== null;
  161. }
  162. protected function authSucceeded() {
  163. if ($this->share === null) {
  164. throw new NotFoundException();
  165. }
  166. // For share this was always set so it is still used in other apps
  167. $this->session->set(PublicAuth::DAV_AUTHENTICATED, $this->share->getId());
  168. }
  169. protected function authFailed() {
  170. $this->emitAccessShareHook($this->share, 403, 'Wrong password');
  171. $this->emitShareAccessEvent($this->share, self::SHARE_AUTH, 403, 'Wrong password');
  172. }
  173. /**
  174. * throws hooks when a share is attempted to be accessed
  175. *
  176. * @param \OCP\Share\IShare|string $share the Share instance if available,
  177. * otherwise token
  178. * @param int $errorCode
  179. * @param string $errorMessage
  180. *
  181. * @throws \OCP\HintException
  182. * @throws \OC\ServerNotAvailableException
  183. *
  184. * @deprecated use OCP\Files_Sharing\Event\ShareLinkAccessedEvent
  185. */
  186. protected function emitAccessShareHook($share, int $errorCode = 200, string $errorMessage = '') {
  187. $itemType = $itemSource = $uidOwner = '';
  188. $token = $share;
  189. $exception = null;
  190. if ($share instanceof \OCP\Share\IShare) {
  191. try {
  192. $token = $share->getToken();
  193. $uidOwner = $share->getSharedBy();
  194. $itemType = $share->getNodeType();
  195. $itemSource = $share->getNodeId();
  196. } catch (\Exception $e) {
  197. // we log what we know and pass on the exception afterwards
  198. $exception = $e;
  199. }
  200. }
  201. \OC_Hook::emit(Share::class, 'share_link_access', [
  202. 'itemType' => $itemType,
  203. 'itemSource' => $itemSource,
  204. 'uidOwner' => $uidOwner,
  205. 'token' => $token,
  206. 'errorCode' => $errorCode,
  207. 'errorMessage' => $errorMessage
  208. ]);
  209. if (!is_null($exception)) {
  210. throw $exception;
  211. }
  212. }
  213. /**
  214. * Emit a ShareLinkAccessedEvent event when a share is accessed, downloaded, auth...
  215. */
  216. protected function emitShareAccessEvent(IShare $share, string $step = '', int $errorCode = 200, string $errorMessage = ''): void {
  217. if ($step !== self::SHARE_ACCESS &&
  218. $step !== self::SHARE_AUTH &&
  219. $step !== self::SHARE_DOWNLOAD) {
  220. return;
  221. }
  222. $this->eventDispatcher->dispatchTyped(new ShareLinkAccessedEvent($share, $step, $errorCode, $errorMessage));
  223. }
  224. /**
  225. * Validate the permissions of the share
  226. *
  227. * @param Share\IShare $share
  228. * @return bool
  229. */
  230. private function validateShare(\OCP\Share\IShare $share) {
  231. // If the owner is disabled no access to the link is granted
  232. $owner = $this->userManager->get($share->getShareOwner());
  233. if ($owner === null || !$owner->isEnabled()) {
  234. return false;
  235. }
  236. // If the initiator of the share is disabled no access is granted
  237. $initiator = $this->userManager->get($share->getSharedBy());
  238. if ($initiator === null || !$initiator->isEnabled()) {
  239. return false;
  240. }
  241. return $share->getNode()->isReadable() && $share->getNode()->isShareable();
  242. }
  243. /**
  244. * @param string $path
  245. * @return TemplateResponse
  246. * @throws NotFoundException
  247. * @throws \Exception
  248. */
  249. #[PublicPage]
  250. #[NoCSRFRequired]
  251. public function showShare($path = ''): TemplateResponse {
  252. \OC_User::setIncognitoMode(true);
  253. // Check whether share exists
  254. try {
  255. $share = $this->shareManager->getShareByToken($this->getToken());
  256. } catch (ShareNotFound $e) {
  257. // The share does not exists, we do not emit an ShareLinkAccessedEvent
  258. $this->emitAccessShareHook($this->getToken(), 404, 'Share not found');
  259. throw new NotFoundException($this->l10n->t('This share does not exist or is no longer available'));
  260. }
  261. if (!$this->validateShare($share)) {
  262. throw new NotFoundException($this->l10n->t('This share does not exist or is no longer available'));
  263. }
  264. $shareNode = $share->getNode();
  265. try {
  266. $templateProvider = $this->publicShareTemplateFactory->getProvider($share);
  267. $response = $templateProvider->renderPage($share, $this->getToken(), $path);
  268. } catch (NotFoundException $e) {
  269. $this->emitAccessShareHook($share, 404, 'Share not found');
  270. $this->emitShareAccessEvent($share, ShareController::SHARE_ACCESS, 404, 'Share not found');
  271. throw new NotFoundException($this->l10n->t('This share does not exist or is no longer available'));
  272. }
  273. // We can't get the path of a file share
  274. try {
  275. if ($shareNode instanceof \OCP\Files\File && $path !== '') {
  276. $this->emitAccessShareHook($share, 404, 'Share not found');
  277. $this->emitShareAccessEvent($share, self::SHARE_ACCESS, 404, 'Share not found');
  278. throw new NotFoundException($this->l10n->t('This share does not exist or is no longer available'));
  279. }
  280. } catch (\Exception $e) {
  281. $this->emitAccessShareHook($share, 404, 'Share not found');
  282. $this->emitShareAccessEvent($share, self::SHARE_ACCESS, 404, 'Share not found');
  283. throw $e;
  284. }
  285. $this->emitAccessShareHook($share);
  286. $this->emitShareAccessEvent($share, self::SHARE_ACCESS);
  287. return $response;
  288. }
  289. /**
  290. * @NoSameSiteCookieRequired
  291. *
  292. * @param string $token
  293. * @param string $files
  294. * @param string $path
  295. * @param string $downloadStartSecret
  296. * @return void|\OCP\AppFramework\Http\Response
  297. * @throws NotFoundException
  298. */
  299. #[PublicPage]
  300. #[NoCSRFRequired]
  301. public function downloadShare($token, $files = null, $path = '', $downloadStartSecret = '') {
  302. \OC_User::setIncognitoMode(true);
  303. $share = $this->shareManager->getShareByToken($token);
  304. if (!($share->getPermissions() & \OCP\Constants::PERMISSION_READ)) {
  305. return new \OCP\AppFramework\Http\DataResponse('Share has no read permission');
  306. }
  307. $files_list = null;
  308. if (!is_null($files)) { // download selected files
  309. $files_list = json_decode($files);
  310. // in case we get only a single file
  311. if ($files_list === null) {
  312. $files_list = [$files];
  313. }
  314. // Just in case $files is a single int like '1234'
  315. if (!is_array($files_list)) {
  316. $files_list = [$files_list];
  317. }
  318. }
  319. if (!$this->validateShare($share)) {
  320. throw new NotFoundException();
  321. }
  322. $userFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
  323. $originalSharePath = $userFolder->getRelativePath($share->getNode()->getPath());
  324. // Single file share
  325. if ($share->getNode() instanceof \OCP\Files\File) {
  326. // Single file download
  327. $this->singleFileDownloaded($share, $share->getNode());
  328. }
  329. // Directory share
  330. else {
  331. /** @var \OCP\Files\Folder $node */
  332. $node = $share->getNode();
  333. // Try to get the path
  334. if ($path !== '') {
  335. try {
  336. $node = $node->get($path);
  337. } catch (NotFoundException $e) {
  338. $this->emitAccessShareHook($share, 404, 'Share not found');
  339. $this->emitShareAccessEvent($share, self::SHARE_DOWNLOAD, 404, 'Share not found');
  340. return new NotFoundResponse();
  341. }
  342. }
  343. $originalSharePath = $userFolder->getRelativePath($node->getPath());
  344. if ($node instanceof \OCP\Files\File) {
  345. // Single file download
  346. $this->singleFileDownloaded($share, $share->getNode());
  347. } else {
  348. try {
  349. if (!empty($files_list)) {
  350. $this->fileListDownloaded($share, $files_list, $node);
  351. } else {
  352. // The folder is downloaded
  353. $this->singleFileDownloaded($share, $share->getNode());
  354. }
  355. } catch (NotFoundException $e) {
  356. return new NotFoundResponse();
  357. }
  358. }
  359. }
  360. /* FIXME: We should do this all nicely in OCP */
  361. OC_Util::tearDownFS();
  362. OC_Util::setupFS($share->getShareOwner());
  363. /**
  364. * this sets a cookie to be able to recognize the start of the download
  365. * the content must not be longer than 32 characters and must only contain
  366. * alphanumeric characters
  367. */
  368. if (!empty($downloadStartSecret)
  369. && !isset($downloadStartSecret[32])
  370. && preg_match('!^[a-zA-Z0-9]+$!', $downloadStartSecret) === 1) {
  371. // FIXME: set on the response once we use an actual app framework response
  372. setcookie('ocDownloadStarted', $downloadStartSecret, time() + 20, '/');
  373. }
  374. $this->emitAccessShareHook($share);
  375. $this->emitShareAccessEvent($share, self::SHARE_DOWNLOAD);
  376. $server_params = [ 'head' => $this->request->getMethod() === 'HEAD' ];
  377. /**
  378. * Http range requests support
  379. */
  380. if (isset($_SERVER['HTTP_RANGE'])) {
  381. $server_params['range'] = $this->request->getHeader('Range');
  382. }
  383. // download selected files
  384. if (!is_null($files) && $files !== '') {
  385. // FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
  386. // after dispatching the request which results in a "Cannot modify header information" notice.
  387. OC_Files::get($originalSharePath, $files_list, $server_params);
  388. exit();
  389. } else {
  390. // FIXME: The exit is required here because otherwise the AppFramework is trying to add headers as well
  391. // after dispatching the request which results in a "Cannot modify header information" notice.
  392. OC_Files::get(dirname($originalSharePath), basename($originalSharePath), $server_params);
  393. exit();
  394. }
  395. }
  396. /**
  397. * create activity for every downloaded file
  398. *
  399. * @param Share\IShare $share
  400. * @param array $files_list
  401. * @param \OCP\Files\Folder $node
  402. * @throws NotFoundException when trying to download a folder or multiple files of a "hide download" share
  403. */
  404. protected function fileListDownloaded(Share\IShare $share, array $files_list, \OCP\Files\Folder $node) {
  405. if ($share->getHideDownload() && count($files_list) > 1) {
  406. throw new NotFoundException('Downloading more than 1 file');
  407. }
  408. foreach ($files_list as $file) {
  409. $subNode = $node->get($file);
  410. $this->singleFileDownloaded($share, $subNode);
  411. }
  412. }
  413. /**
  414. * create activity if a single file was downloaded from a link share
  415. *
  416. * @param Share\IShare $share
  417. * @throws NotFoundException when trying to download a folder of a "hide download" share
  418. */
  419. protected function singleFileDownloaded(Share\IShare $share, \OCP\Files\Node $node) {
  420. if ($share->getHideDownload() && $node instanceof Folder) {
  421. throw new NotFoundException('Downloading a folder');
  422. }
  423. $fileId = $node->getId();
  424. $userFolder = $this->rootFolder->getUserFolder($share->getSharedBy());
  425. $userNode = $userFolder->getFirstNodeById($fileId);
  426. $ownerFolder = $this->rootFolder->getUserFolder($share->getShareOwner());
  427. $userPath = $userFolder->getRelativePath($userNode->getPath());
  428. $ownerPath = $ownerFolder->getRelativePath($node->getPath());
  429. $remoteAddress = $this->request->getRemoteAddress();
  430. $dateTime = new \DateTime();
  431. $dateTime = $dateTime->format('Y-m-d H');
  432. $remoteAddressHash = md5($dateTime . '-' . $remoteAddress);
  433. $parameters = [$userPath];
  434. if ($share->getShareType() === IShare::TYPE_EMAIL) {
  435. if ($node instanceof \OCP\Files\File) {
  436. $subject = Downloads::SUBJECT_SHARED_FILE_BY_EMAIL_DOWNLOADED;
  437. } else {
  438. $subject = Downloads::SUBJECT_SHARED_FOLDER_BY_EMAIL_DOWNLOADED;
  439. }
  440. $parameters[] = $share->getSharedWith();
  441. } else {
  442. if ($node instanceof \OCP\Files\File) {
  443. $subject = Downloads::SUBJECT_PUBLIC_SHARED_FILE_DOWNLOADED;
  444. $parameters[] = $remoteAddressHash;
  445. } else {
  446. $subject = Downloads::SUBJECT_PUBLIC_SHARED_FOLDER_DOWNLOADED;
  447. $parameters[] = $remoteAddressHash;
  448. }
  449. }
  450. $this->publishActivity($subject, $parameters, $share->getSharedBy(), $fileId, $userPath);
  451. if ($share->getShareOwner() !== $share->getSharedBy()) {
  452. $parameters[0] = $ownerPath;
  453. $this->publishActivity($subject, $parameters, $share->getShareOwner(), $fileId, $ownerPath);
  454. }
  455. }
  456. /**
  457. * publish activity
  458. *
  459. * @param string $subject
  460. * @param array $parameters
  461. * @param string $affectedUser
  462. * @param int $fileId
  463. * @param string $filePath
  464. */
  465. protected function publishActivity($subject,
  466. array $parameters,
  467. $affectedUser,
  468. $fileId,
  469. $filePath) {
  470. $event = $this->activityManager->generateEvent();
  471. $event->setApp('files_sharing')
  472. ->setType('public_links')
  473. ->setSubject($subject, $parameters)
  474. ->setAffectedUser($affectedUser)
  475. ->setObject('files', $fileId, $filePath);
  476. $this->activityManager->publish($event);
  477. }
  478. }