1
0

Encryption.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  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\Encryption\Crypto;
  8. use OC\Encryption\Exceptions\DecryptionFailedException;
  9. use OC\Files\Cache\Scanner;
  10. use OC\Files\View;
  11. use OCA\Encryption\Exceptions\PublicKeyMissingException;
  12. use OCA\Encryption\KeyManager;
  13. use OCA\Encryption\Session;
  14. use OCA\Encryption\Util;
  15. use OCP\Encryption\IEncryptionModule;
  16. use OCP\IL10N;
  17. use Psr\Log\LoggerInterface;
  18. use Symfony\Component\Console\Input\InputInterface;
  19. use Symfony\Component\Console\Output\OutputInterface;
  20. class Encryption implements IEncryptionModule {
  21. public const ID = 'OC_DEFAULT_MODULE';
  22. public const DISPLAY_NAME = 'Default encryption module';
  23. /** @var string */
  24. private $cipher;
  25. /** @var string */
  26. private $path;
  27. /** @var string */
  28. private $user;
  29. private array $owner;
  30. /** @var string */
  31. private $fileKey;
  32. /** @var string */
  33. private $writeCache;
  34. /** @var array */
  35. private $accessList;
  36. /** @var boolean */
  37. private $isWriteOperation;
  38. private bool $useMasterPassword;
  39. private bool $useLegacyBase64Encoding = false;
  40. /** @var int Current version of the file */
  41. private int $version = 0;
  42. /** @var array remember encryption signature version */
  43. private static $rememberVersion = [];
  44. public function __construct(
  45. private Crypt $crypt,
  46. private KeyManager $keyManager,
  47. private Util $util,
  48. private Session $session,
  49. private EncryptAll $encryptAll,
  50. private DecryptAll $decryptAll,
  51. private LoggerInterface $logger,
  52. private IL10N $l,
  53. ) {
  54. $this->owner = [];
  55. $this->useMasterPassword = $this->util->isMasterKeyEnabled();
  56. }
  57. /**
  58. * @return string defining the technical unique id
  59. */
  60. public function getId() {
  61. return self::ID;
  62. }
  63. /**
  64. * In comparison to getKey() this function returns a human readable (maybe translated) name
  65. *
  66. * @return string
  67. */
  68. public function getDisplayName() {
  69. return self::DISPLAY_NAME;
  70. }
  71. /**
  72. * start receiving chunks from a file. This is the place where you can
  73. * perform some initial step before starting encrypting/decrypting the
  74. * chunks
  75. *
  76. * @param string $path to the file
  77. * @param string $user who read/write the file
  78. * @param string $mode php stream open mode
  79. * @param array $header contains the header data read from the file
  80. * @param array $accessList who has access to the file contains the key 'users' and 'public'
  81. *
  82. * @return array $header contain data as key-value pairs which should be
  83. * written to the header, in case of a write operation
  84. * or if no additional data is needed return a empty array
  85. */
  86. public function begin($path, $user, $mode, array $header, array $accessList) {
  87. $this->path = $this->getPathToRealFile($path);
  88. $this->accessList = $accessList;
  89. $this->user = $user;
  90. $this->isWriteOperation = false;
  91. $this->writeCache = '';
  92. $this->useLegacyBase64Encoding = true;
  93. if (isset($header['encoding'])) {
  94. $this->useLegacyBase64Encoding = $header['encoding'] !== Crypt::BINARY_ENCODING_FORMAT;
  95. }
  96. if ($this->session->isReady() === false) {
  97. // if the master key is enabled we can initialize encryption
  98. // with a empty password and user name
  99. if ($this->util->isMasterKeyEnabled()) {
  100. $this->keyManager->init('', '');
  101. }
  102. }
  103. /* If useLegacyFileKey is not specified in header, auto-detect, to be safe */
  104. $useLegacyFileKey = (($header['useLegacyFileKey'] ?? '') == 'false' ? false : null);
  105. $this->fileKey = $this->keyManager->getFileKey($this->path, $this->user, $useLegacyFileKey, $this->session->decryptAllModeActivated());
  106. // always use the version from the original file, also part files
  107. // need to have a correct version number if they get moved over to the
  108. // final location
  109. $this->version = (int)$this->keyManager->getVersion($this->stripPartFileExtension($path), new View());
  110. if (
  111. $mode === 'w'
  112. || $mode === 'w+'
  113. || $mode === 'wb'
  114. || $mode === 'wb+'
  115. ) {
  116. $this->isWriteOperation = true;
  117. if (empty($this->fileKey)) {
  118. $this->fileKey = $this->crypt->generateFileKey();
  119. }
  120. } else {
  121. // if we read a part file we need to increase the version by 1
  122. // because the version number was also increased by writing
  123. // the part file
  124. if (Scanner::isPartialFile($path)) {
  125. $this->version = $this->version + 1;
  126. }
  127. }
  128. if ($this->isWriteOperation) {
  129. $this->cipher = $this->crypt->getCipher();
  130. $this->useLegacyBase64Encoding = $this->crypt->useLegacyBase64Encoding();
  131. } elseif (isset($header['cipher'])) {
  132. $this->cipher = $header['cipher'];
  133. } else {
  134. // if we read a file without a header we fall-back to the legacy cipher
  135. // which was used in <=oC6
  136. $this->cipher = $this->crypt->getLegacyCipher();
  137. }
  138. $result = [
  139. 'cipher' => $this->cipher,
  140. 'signed' => 'true',
  141. 'useLegacyFileKey' => 'false',
  142. ];
  143. if ($this->useLegacyBase64Encoding !== true) {
  144. $result['encoding'] = Crypt::BINARY_ENCODING_FORMAT;
  145. }
  146. return $result;
  147. }
  148. /**
  149. * last chunk received. This is the place where you can perform some final
  150. * operation and return some remaining data if something is left in your
  151. * buffer.
  152. *
  153. * @param string $path to the file
  154. * @param string $position
  155. * @return string remained data which should be written to the file in case
  156. * of a write operation
  157. * @throws PublicKeyMissingException
  158. * @throws \Exception
  159. * @throws \OCA\Encryption\Exceptions\MultiKeyEncryptException
  160. */
  161. public function end($path, $position = '0') {
  162. $result = '';
  163. if ($this->isWriteOperation) {
  164. // in case of a part file we remember the new signature versions
  165. // the version will be set later on update.
  166. // This way we make sure that other apps listening to the pre-hooks
  167. // still get the old version which should be the correct value for them
  168. if (Scanner::isPartialFile($path)) {
  169. self::$rememberVersion[$this->stripPartFileExtension($path)] = $this->version + 1;
  170. }
  171. if (!empty($this->writeCache)) {
  172. $result = $this->crypt->symmetricEncryptFileContent($this->writeCache, $this->fileKey, $this->version + 1, $position);
  173. $this->writeCache = '';
  174. }
  175. $publicKeys = [];
  176. if ($this->useMasterPassword === true) {
  177. $publicKeys[$this->keyManager->getMasterKeyId()] = $this->keyManager->getPublicMasterKey();
  178. } else {
  179. foreach ($this->accessList['users'] as $uid) {
  180. try {
  181. $publicKeys[$uid] = $this->keyManager->getPublicKey($uid);
  182. } catch (PublicKeyMissingException $e) {
  183. $this->logger->warning(
  184. 'no public key found for user "{uid}", user will not be able to read the file',
  185. ['app' => 'encryption', 'uid' => $uid]
  186. );
  187. // if the public key of the owner is missing we should fail
  188. if ($uid === $this->user) {
  189. throw $e;
  190. }
  191. }
  192. }
  193. }
  194. $publicKeys = $this->keyManager->addSystemKeys($this->accessList, $publicKeys, $this->getOwner($path));
  195. $shareKeys = $this->crypt->multiKeyEncrypt($this->fileKey, $publicKeys);
  196. if (!$this->keyManager->deleteLegacyFileKey($this->path)) {
  197. $this->logger->warning(
  198. 'Failed to delete legacy filekey for {path}',
  199. ['app' => 'encryption', 'path' => $path]
  200. );
  201. }
  202. foreach ($shareKeys as $uid => $keyFile) {
  203. $this->keyManager->setShareKey($this->path, $uid, $keyFile);
  204. }
  205. }
  206. return $result ?: '';
  207. }
  208. /**
  209. * encrypt data
  210. *
  211. * @param string $data you want to encrypt
  212. * @param int $position
  213. * @return string encrypted data
  214. */
  215. public function encrypt($data, $position = 0) {
  216. // If extra data is left over from the last round, make sure it
  217. // is integrated into the next block
  218. if ($this->writeCache) {
  219. // Concat writeCache to start of $data
  220. $data = $this->writeCache . $data;
  221. // Clear the write cache, ready for reuse - it has been
  222. // flushed and its old contents processed
  223. $this->writeCache = '';
  224. }
  225. $encrypted = '';
  226. // While there still remains some data to be processed & written
  227. while (strlen($data) > 0) {
  228. // Remaining length for this iteration, not of the
  229. // entire file (may be greater than 8192 bytes)
  230. $remainingLength = strlen($data);
  231. // If data remaining to be written is less than the
  232. // size of 1 unencrypted block
  233. if ($remainingLength < $this->getUnencryptedBlockSize(true)) {
  234. // Set writeCache to contents of $data
  235. // The writeCache will be carried over to the
  236. // next write round, and added to the start of
  237. // $data to ensure that written blocks are
  238. // always the correct length. If there is still
  239. // data in writeCache after the writing round
  240. // has finished, then the data will be written
  241. // to disk by $this->flush().
  242. $this->writeCache = $data;
  243. // Clear $data ready for next round
  244. $data = '';
  245. } else {
  246. // Read the chunk from the start of $data
  247. $chunk = substr($data, 0, $this->getUnencryptedBlockSize(true));
  248. $encrypted .= $this->crypt->symmetricEncryptFileContent($chunk, $this->fileKey, $this->version + 1, (string)$position);
  249. // Remove the chunk we just processed from
  250. // $data, leaving only unprocessed data in $data
  251. // var, for handling on the next round
  252. $data = substr($data, $this->getUnencryptedBlockSize(true));
  253. }
  254. }
  255. return $encrypted;
  256. }
  257. /**
  258. * decrypt data
  259. *
  260. * @param string $data you want to decrypt
  261. * @param int|string $position
  262. * @return string decrypted data
  263. * @throws DecryptionFailedException
  264. */
  265. public function decrypt($data, $position = 0) {
  266. if (empty($this->fileKey)) {
  267. $msg = 'Cannot decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.';
  268. $hint = $this->l->t('Cannot decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.');
  269. $this->logger->error($msg);
  270. throw new DecryptionFailedException($msg, $hint);
  271. }
  272. return $this->crypt->symmetricDecryptFileContent($data, $this->fileKey, $this->cipher, $this->version, $position, !$this->useLegacyBase64Encoding);
  273. }
  274. /**
  275. * update encrypted file, e.g. give additional users access to the file
  276. *
  277. * @param string $path path to the file which should be updated
  278. * @param string $uid of the user who performs the operation
  279. * @param array $accessList who has access to the file contains the key 'users' and 'public'
  280. * @return bool
  281. */
  282. public function update($path, $uid, array $accessList) {
  283. if (empty($accessList)) {
  284. if (isset(self::$rememberVersion[$path])) {
  285. $this->keyManager->setVersion($path, self::$rememberVersion[$path], new View());
  286. unset(self::$rememberVersion[$path]);
  287. }
  288. return false;
  289. }
  290. $fileKey = $this->keyManager->getFileKey($path, $uid, null);
  291. if (!empty($fileKey)) {
  292. $publicKeys = [];
  293. if ($this->useMasterPassword === true) {
  294. $publicKeys[$this->keyManager->getMasterKeyId()] = $this->keyManager->getPublicMasterKey();
  295. } else {
  296. foreach ($accessList['users'] as $user) {
  297. try {
  298. $publicKeys[$user] = $this->keyManager->getPublicKey($user);
  299. } catch (PublicKeyMissingException $e) {
  300. $this->logger->warning('Could not encrypt file for ' . $user . ': ' . $e->getMessage());
  301. }
  302. }
  303. }
  304. $publicKeys = $this->keyManager->addSystemKeys($accessList, $publicKeys, $this->getOwner($path));
  305. $shareKeys = $this->crypt->multiKeyEncrypt($fileKey, $publicKeys);
  306. $this->keyManager->deleteAllFileKeys($path);
  307. foreach ($shareKeys as $uid => $keyFile) {
  308. $this->keyManager->setShareKey($path, $uid, $keyFile);
  309. }
  310. } else {
  311. $this->logger->debug('no file key found, we assume that the file "{file}" is not encrypted',
  312. ['file' => $path, 'app' => 'encryption']);
  313. return false;
  314. }
  315. return true;
  316. }
  317. /**
  318. * should the file be encrypted or not
  319. *
  320. * @param string $path
  321. * @return boolean
  322. */
  323. public function shouldEncrypt($path) {
  324. if ($this->util->shouldEncryptHomeStorage() === false) {
  325. $storage = $this->util->getStorage($path);
  326. if ($storage && $storage->instanceOfStorage('\OCP\Files\IHomeStorage')) {
  327. return false;
  328. }
  329. }
  330. $parts = explode('/', $path);
  331. if (count($parts) < 4) {
  332. return false;
  333. }
  334. if ($parts[2] === 'files') {
  335. return true;
  336. }
  337. if ($parts[2] === 'files_versions') {
  338. return true;
  339. }
  340. if ($parts[2] === 'files_trashbin') {
  341. return true;
  342. }
  343. return false;
  344. }
  345. /**
  346. * get size of the unencrypted payload per block.
  347. * Nextcloud read/write files with a block size of 8192 byte
  348. *
  349. * Encrypted blocks have a 22-byte IV and 2 bytes of padding, encrypted and
  350. * signed blocks have also a 71-byte signature and 1 more byte of padding,
  351. * resulting respectively in:
  352. *
  353. * 8192 - 22 - 2 = 8168 bytes in each unsigned unencrypted block
  354. * 8192 - 22 - 2 - 71 - 1 = 8096 bytes in each signed unencrypted block
  355. *
  356. * Legacy base64 encoding then reduces the available size by a 3/4 factor:
  357. *
  358. * 8168 * (3/4) = 6126 bytes in each base64-encoded unsigned unencrypted block
  359. * 8096 * (3/4) = 6072 bytes in each base64-encoded signed unencrypted block
  360. *
  361. * @param bool $signed
  362. * @return int
  363. */
  364. public function getUnencryptedBlockSize($signed = false) {
  365. if ($this->useLegacyBase64Encoding) {
  366. return $signed ? 6072 : 6126;
  367. } else {
  368. return $signed ? 8096 : 8168;
  369. }
  370. }
  371. /**
  372. * check if the encryption module is able to read the file,
  373. * e.g. if all encryption keys exists
  374. *
  375. * @param string $path
  376. * @param string $uid user for whom we want to check if he can read the file
  377. * @return bool
  378. * @throws DecryptionFailedException
  379. */
  380. public function isReadable($path, $uid) {
  381. $fileKey = $this->keyManager->getFileKey($path, $uid, null);
  382. if (empty($fileKey)) {
  383. $owner = $this->util->getOwner($path);
  384. if ($owner !== $uid) {
  385. // if it is a shared file we throw a exception with a useful
  386. // error message because in this case it means that the file was
  387. // shared with the user at a point where the user didn't had a
  388. // valid private/public key
  389. $msg = 'Encryption module "' . $this->getDisplayName() .
  390. '" is not able to read ' . $path;
  391. $hint = $this->l->t('Cannot read this file, probably this is a shared file. Please ask the file owner to reshare the file with you.');
  392. $this->logger->warning($msg);
  393. throw new DecryptionFailedException($msg, $hint);
  394. }
  395. return false;
  396. }
  397. return true;
  398. }
  399. /**
  400. * Initial encryption of all files
  401. *
  402. * @param InputInterface $input
  403. * @param OutputInterface $output write some status information to the terminal during encryption
  404. */
  405. public function encryptAll(InputInterface $input, OutputInterface $output) {
  406. $this->encryptAll->encryptAll($input, $output);
  407. }
  408. /**
  409. * prepare module to perform decrypt all operation
  410. *
  411. * @param InputInterface $input
  412. * @param OutputInterface $output
  413. * @param string $user
  414. * @return bool
  415. */
  416. public function prepareDecryptAll(InputInterface $input, OutputInterface $output, $user = '') {
  417. return $this->decryptAll->prepare($input, $output, $user);
  418. }
  419. /**
  420. * @param string $path
  421. * @return string
  422. */
  423. protected function getPathToRealFile($path) {
  424. $realPath = $path;
  425. $parts = explode('/', $path);
  426. if ($parts[2] === 'files_versions') {
  427. $realPath = '/' . $parts[1] . '/files/' . implode('/', array_slice($parts, 3));
  428. $length = strrpos($realPath, '.');
  429. $realPath = substr($realPath, 0, $length);
  430. }
  431. return $realPath;
  432. }
  433. /**
  434. * remove .part file extension and the ocTransferId from the file to get the
  435. * original file name
  436. *
  437. * @param string $path
  438. * @return string
  439. */
  440. protected function stripPartFileExtension($path) {
  441. if (pathinfo($path, PATHINFO_EXTENSION) === 'part') {
  442. $pos = strrpos($path, '.', -6);
  443. $path = substr($path, 0, $pos);
  444. }
  445. return $path;
  446. }
  447. /**
  448. * get owner of a file
  449. *
  450. * @param string $path
  451. * @return string
  452. */
  453. protected function getOwner($path) {
  454. if (!isset($this->owner[$path])) {
  455. $this->owner[$path] = $this->util->getOwner($path);
  456. }
  457. return $this->owner[$path];
  458. }
  459. /**
  460. * Check if the module is ready to be used by that specific user.
  461. * In case a module is not ready - because e.g. key pairs have not been generated
  462. * upon login this method can return false before any operation starts and might
  463. * cause issues during operations.
  464. *
  465. * @param string $user
  466. * @return boolean
  467. * @since 9.1.0
  468. */
  469. public function isReadyForUser($user) {
  470. if ($this->util->isMasterKeyEnabled()) {
  471. return true;
  472. }
  473. return $this->keyManager->userHasKeys($user);
  474. }
  475. /**
  476. * We only need a detailed access list if the master key is not enabled
  477. *
  478. * @return bool
  479. */
  480. public function needDetailedAccessList() {
  481. return !$this->util->isMasterKeyEnabled();
  482. }
  483. }