ShareController.php 17 KB

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