1
0

Encryption.php 16 KB

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