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\OpenAPI;
  19. use OCP\AppFramework\Http\NotFoundResponse;
  20. use OCP\AppFramework\Http\TemplateResponse;
  21. use OCP\Defaults;
  22. use OCP\EventDispatcher\IEventDispatcher;
  23. use OCP\Files\Folder;
  24. use OCP\Files\IRootFolder;
  25. use OCP\Files\NotFoundException;
  26. use OCP\IConfig;
  27. use OCP\IL10N;
  28. use OCP\IPreview;
  29. use OCP\IRequest;
  30. use OCP\ISession;
  31. use OCP\IURLGenerator;
  32. use OCP\IUserManager;
  33. use OCP\Security\ISecureRandom;
  34. use OCP\Share;
  35. use OCP\Share\Exceptions\ShareNotFound;
  36. use OCP\Share\IManager as ShareManager;
  37. use OCP\Share\IPublicShareTemplateFactory;
  38. use OCP\Share\IShare;
  39. use OCP\Template;
  40. /**
  41. * @package OCA\Files_Sharing\Controllers
  42. */
  43. #[OpenAPI(scope: OpenAPI::SCOPE_IGNORE)]
  44. class ShareController extends AuthPublicShareController {
  45. protected ?Share\IShare $share = null;
  46. public const SHARE_ACCESS = 'access';
  47. public const SHARE_AUTH = 'auth';
  48. public const SHARE_DOWNLOAD = 'download';
  49. public function __construct(
  50. string $appName,
  51. IRequest $request,
  52. protected IConfig $config,
  53. IURLGenerator $urlGenerator,
  54. protected IUserManager $userManager,
  55. protected \OCP\Activity\IManager $activityManager,
  56. protected ShareManager $shareManager,
  57. ISession $session,
  58. protected IPreview $previewManager,
  59. protected IRootFolder $rootFolder,
  60. protected FederatedShareProvider $federatedShareProvider,
  61. protected IAccountManager $accountManager,
  62. protected IEventDispatcher $eventDispatcher,
  63. protected IL10N $l10n,
  64. protected ISecureRandom $secureRandom,
  65. protected Defaults $defaults,
  66. private IPublicShareTemplateFactory $publicShareTemplateFactory,
  67. ) {
  68. parent::__construct($appName, $request, $session, $urlGenerator);
  69. }
  70. /**
  71. * @PublicPage
  72. * @NoCSRFRequired
  73. *
  74. * Show the authentication page
  75. * The form has to submit to the authenticate method route
  76. */
  77. public function showAuthenticate(): TemplateResponse {
  78. $templateParameters = ['share' => $this->share];
  79. $this->eventDispatcher->dispatchTyped(new BeforeTemplateRenderedEvent($this->share, BeforeTemplateRenderedEvent::SCOPE_PUBLIC_SHARE_AUTH));
  80. $response = new TemplateResponse('core', 'publicshareauth', $templateParameters, 'guest');
  81. if ($this->share->getSendPasswordByTalk()) {
  82. $csp = new ContentSecurityPolicy();
  83. $csp->addAllowedConnectDomain('*');
  84. $csp->addAllowedMediaDomain('blob:');
  85. $response->setContentSecurityPolicy($csp);
  86. }
  87. return $response;
  88. }
  89. /**
  90. * The template to show when authentication failed
  91. */
  92. protected function showAuthFailed(): TemplateResponse {
  93. $templateParameters = ['share' => $this->share, 'wrongpw' => true];
  94. $this->eventDispatcher->dispatchTyped(new BeforeTemplateRenderedEvent($this->share, BeforeTemplateRenderedEvent::SCOPE_PUBLIC_SHARE_AUTH));
  95. $response = new TemplateResponse('core', 'publicshareauth', $templateParameters, 'guest');
  96. if ($this->share->getSendPasswordByTalk()) {
  97. $csp = new ContentSecurityPolicy();
  98. $csp->addAllowedConnectDomain('*');
  99. $csp->addAllowedMediaDomain('blob:');
  100. $response->setContentSecurityPolicy($csp);
  101. }
  102. return $response;
  103. }
  104. /**
  105. * The template to show after user identification
  106. */
  107. protected function showIdentificationResult(bool $success = false): TemplateResponse {
  108. $templateParameters = ['share' => $this->share, 'identityOk' => $success];
  109. $this->eventDispatcher->dispatchTyped(new BeforeTemplateRenderedEvent($this->share, BeforeTemplateRenderedEvent::SCOPE_PUBLIC_SHARE_AUTH));
  110. $response = new TemplateResponse('core', 'publicshareauth', $templateParameters, 'guest');
  111. if ($this->share->getSendPasswordByTalk()) {
  112. $csp = new ContentSecurityPolicy();
  113. $csp->addAllowedConnectDomain('*');
  114. $csp->addAllowedMediaDomain('blob:');
  115. $response->setContentSecurityPolicy($csp);
  116. }
  117. return $response;
  118. }
  119. /**
  120. * Validate the identity token of a public share
  121. *
  122. * @param ?string $identityToken
  123. * @return bool
  124. */
  125. protected function validateIdentity(?string $identityToken = null): bool {
  126. if ($this->share->getShareType() !== IShare::TYPE_EMAIL) {
  127. return false;
  128. }
  129. if ($identityToken === null || $this->share->getSharedWith() === null) {
  130. return false;
  131. }
  132. return $identityToken === $this->share->getSharedWith();
  133. }
  134. /**
  135. * Generates a password for the share, respecting any password policy defined
  136. */
  137. protected function generatePassword(): void {
  138. $event = new \OCP\Security\Events\GenerateSecurePasswordEvent();
  139. $this->eventDispatcher->dispatchTyped($event);
  140. $password = $event->getPassword() ?? $this->secureRandom->generate(20);
  141. $this->share->setPassword($password);
  142. $this->shareManager->updateShare($this->share);
  143. }
  144. protected function verifyPassword(string $password): bool {
  145. return $this->shareManager->checkPassword($this->share, $password);
  146. }
  147. protected function getPasswordHash(): ?string {
  148. return $this->share->getPassword();
  149. }
  150. public function isValidToken(): bool {
  151. try {
  152. $this->share = $this->shareManager->getShareByToken($this->getToken());
  153. } catch (ShareNotFound $e) {
  154. return false;
  155. }
  156. return true;
  157. }
  158. protected function isPasswordProtected(): bool {
  159. return $this->share->getPassword() !== null;
  160. }
  161. protected function authSucceeded() {
  162. if ($this->share === null) {
  163. throw new NotFoundException();
  164. }
  165. // For share this was always set so it is still used in other apps
  166. $this->session->set(PublicAuth::DAV_AUTHENTICATED, $this->share->getId());
  167. }
  168. protected function authFailed() {
  169. $this->emitAccessShareHook($this->share, 403, 'Wrong password');
  170. $this->emitShareAccessEvent($this->share, self::SHARE_AUTH, 403, 'Wrong password');
  171. }
  172. /**
  173. * throws hooks when a share is attempted to be accessed
  174. *
  175. * @param \OCP\Share\IShare|string $share the Share instance if available,
  176. * otherwise token
  177. * @param int $errorCode
  178. * @param string $errorMessage
  179. *
  180. * @throws \OCP\HintException
  181. * @throws \OC\ServerNotAvailableException
  182. *
  183. * @deprecated use OCP\Files_Sharing\Event\ShareLinkAccessedEvent
  184. */
  185. protected function emitAccessShareHook($share, int $errorCode = 200, string $errorMessage = '') {
  186. $itemType = $itemSource = $uidOwner = '';
  187. $token = $share;
  188. $exception = null;
  189. if ($share instanceof \OCP\Share\IShare) {
  190. try {
  191. $token = $share->getToken();
  192. $uidOwner = $share->getSharedBy();
  193. $itemType = $share->getNodeType();
  194. $itemSource = $share->getNodeId();
  195. } catch (\Exception $e) {
  196. // we log what we know and pass on the exception afterwards
  197. $exception = $e;
  198. }
  199. }
  200. \OC_Hook::emit(Share::class, 'share_link_access', [
  201. 'itemType' => $itemType,
  202. 'itemSource' => $itemSource,
  203. 'uidOwner' => $uidOwner,
  204. 'token' => $token,
  205. 'errorCode' => $errorCode,
  206. 'errorMessage' => $errorMessage
  207. ]);
  208. if (!is_null($exception)) {
  209. throw $exception;
  210. }
  211. }
  212. /**
  213. * Emit a ShareLinkAccessedEvent event when a share is accessed, downloaded, auth...
  214. */
  215. protected function emitShareAccessEvent(IShare $share, string $step = '', int $errorCode = 200, string $errorMessage = ''): void {
  216. if ($step !== self::SHARE_ACCESS &&
  217. $step !== self::SHARE_AUTH &&
  218. $step !== self::SHARE_DOWNLOAD) {
  219. return;
  220. }
  221. $this->eventDispatcher->dispatchTyped(new ShareLinkAccessedEvent($share, $step, $errorCode, $errorMessage));
  222. }
  223. /**
  224. * Validate the permissions of the share
  225. *
  226. * @param Share\IShare $share
  227. * @return bool
  228. */
  229. private function validateShare(\OCP\Share\IShare $share) {
  230. // If the owner is disabled no access to the link is granted
  231. $owner = $this->userManager->get($share->getShareOwner());
  232. if ($owner === null || !$owner->isEnabled()) {
  233. return false;
  234. }
  235. // If the initiator of the share is disabled no access is granted
  236. $initiator = $this->userManager->get($share->getSharedBy());
  237. if ($initiator === null || !$initiator->isEnabled()) {
  238. return false;
  239. }
  240. return $share->getNode()->isReadable() && $share->getNode()->isShareable();
  241. }
  242. /**
  243. * @PublicPage
  244. * @NoCSRFRequired
  245. *
  246. *
  247. * @param string $path
  248. * @return TemplateResponse
  249. * @throws NotFoundException
  250. * @throws \Exception
  251. */
  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();
  261. }
  262. if (!$this->validateShare($share)) {
  263. throw new NotFoundException();
  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();
  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();
  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. * @PublicPage
  292. * @NoCSRFRequired
  293. * @NoSameSiteCookieRequired
  294. *
  295. * @param string $token
  296. * @param string $files
  297. * @param string $path
  298. * @param string $downloadStartSecret
  299. * @return void|\OCP\AppFramework\Http\Response
  300. * @throws NotFoundException
  301. */
  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. }