aboutsummaryrefslogtreecommitdiffstats
path: root/apps/encryption/lib/Crypto
diff options
context:
space:
mode:
Diffstat (limited to 'apps/encryption/lib/Crypto')
-rw-r--r--apps/encryption/lib/Crypto/Crypt.php815
-rw-r--r--apps/encryption/lib/Crypto/DecryptAll.php124
-rw-r--r--apps/encryption/lib/Crypto/EncryptAll.php429
-rw-r--r--apps/encryption/lib/Crypto/Encryption.php554
4 files changed, 1922 insertions, 0 deletions
diff --git a/apps/encryption/lib/Crypto/Crypt.php b/apps/encryption/lib/Crypto/Crypt.php
new file mode 100644
index 00000000000..463ca4e22bb
--- /dev/null
+++ b/apps/encryption/lib/Crypto/Crypt.php
@@ -0,0 +1,815 @@
+<?php
+
+/**
+ * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
+ */
+namespace OCA\Encryption\Crypto;
+
+use OC\Encryption\Exceptions\DecryptionFailedException;
+use OC\Encryption\Exceptions\EncryptionFailedException;
+use OC\ServerNotAvailableException;
+use OCA\Encryption\Exceptions\MultiKeyDecryptException;
+use OCA\Encryption\Exceptions\MultiKeyEncryptException;
+use OCP\Encryption\Exceptions\GenericEncryptionException;
+use OCP\IConfig;
+use OCP\IL10N;
+use OCP\IUserSession;
+use phpseclib\Crypt\RC4;
+use Psr\Log\LoggerInterface;
+
+/**
+ * Class Crypt provides the encryption implementation of the default Nextcloud
+ * encryption module. As default AES-256-CTR is used, it does however offer support
+ * for the following modes:
+ *
+ * - AES-256-CTR
+ * - AES-128-CTR
+ * - AES-256-CFB
+ * - AES-128-CFB
+ *
+ * For integrity protection Encrypt-Then-MAC using HMAC-SHA256 is used.
+ *
+ * @package OCA\Encryption\Crypto
+ */
+class Crypt {
+ public const SUPPORTED_CIPHERS_AND_KEY_SIZE = [
+ 'AES-256-CTR' => 32,
+ 'AES-128-CTR' => 16,
+ 'AES-256-CFB' => 32,
+ 'AES-128-CFB' => 16,
+ ];
+ // one out of SUPPORTED_CIPHERS_AND_KEY_SIZE
+ public const DEFAULT_CIPHER = 'AES-256-CTR';
+ // default cipher from old Nextcloud versions
+ public const LEGACY_CIPHER = 'AES-128-CFB';
+
+ public const SUPPORTED_KEY_FORMATS = ['hash2', 'hash', 'password'];
+ // one out of SUPPORTED_KEY_FORMATS
+ public const DEFAULT_KEY_FORMAT = 'hash2';
+ // default key format, old Nextcloud version encrypted the private key directly
+ // with the user password
+ public const LEGACY_KEY_FORMAT = 'password';
+
+ public const HEADER_START = 'HBEGIN';
+ public const HEADER_END = 'HEND';
+
+ // default encoding format, old Nextcloud versions used base64
+ public const BINARY_ENCODING_FORMAT = 'binary';
+
+ private string $user;
+
+ private ?string $currentCipher = null;
+
+ private bool $supportLegacy;
+
+ /**
+ * Use the legacy base64 encoding instead of the more space-efficient binary encoding.
+ */
+ private bool $useLegacyBase64Encoding;
+
+ public function __construct(
+ private LoggerInterface $logger,
+ IUserSession $userSession,
+ private IConfig $config,
+ private IL10N $l,
+ ) {
+ $this->user = $userSession->isLoggedIn() ? $userSession->getUser()->getUID() : '"no user given"';
+ $this->supportLegacy = $this->config->getSystemValueBool('encryption.legacy_format_support', false);
+ $this->useLegacyBase64Encoding = $this->config->getSystemValueBool('encryption.use_legacy_base64_encoding', false);
+ }
+
+ /**
+ * create new private/public key-pair for user
+ *
+ * @return array{publicKey: string, privateKey: string}|false
+ */
+ public function createKeyPair() {
+ $res = $this->getOpenSSLPKey();
+
+ if (!$res) {
+ $this->logger->error("Encryption Library couldn't generate users key-pair for {$this->user}",
+ ['app' => 'encryption']);
+
+ if (openssl_error_string()) {
+ $this->logger->error('Encryption library openssl_pkey_new() fails: ' . openssl_error_string(),
+ ['app' => 'encryption']);
+ }
+ } elseif (openssl_pkey_export($res,
+ $privateKey,
+ null,
+ $this->getOpenSSLConfig())) {
+ $keyDetails = openssl_pkey_get_details($res);
+ $publicKey = $keyDetails['key'];
+
+ return [
+ 'publicKey' => $publicKey,
+ 'privateKey' => $privateKey
+ ];
+ }
+ $this->logger->error('Encryption library couldn\'t export users private key, please check your servers OpenSSL configuration.' . $this->user,
+ ['app' => 'encryption']);
+ if (openssl_error_string()) {
+ $this->logger->error('Encryption Library:' . openssl_error_string(),
+ ['app' => 'encryption']);
+ }
+
+ return false;
+ }
+
+ /**
+ * Generates a new private key
+ *
+ * @return \OpenSSLAsymmetricKey|false
+ */
+ public function getOpenSSLPKey() {
+ $config = $this->getOpenSSLConfig();
+ return openssl_pkey_new($config);
+ }
+
+ private function getOpenSSLConfig(): array {
+ $config = ['private_key_bits' => 4096];
+ $config = array_merge(
+ $config,
+ $this->config->getSystemValue('openssl', [])
+ );
+ return $config;
+ }
+
+ /**
+ * @throws EncryptionFailedException
+ */
+ public function symmetricEncryptFileContent(string $plainContent, string $passPhrase, int $version, string $position): string|false {
+ if (!$plainContent) {
+ $this->logger->error('Encryption Library, symmetrical encryption failed no content given',
+ ['app' => 'encryption']);
+ return false;
+ }
+
+ $iv = $this->generateIv();
+
+ $encryptedContent = $this->encrypt($plainContent,
+ $iv,
+ $passPhrase,
+ $this->getCipher());
+
+ // Create a signature based on the key as well as the current version
+ $sig = $this->createSignature($encryptedContent, $passPhrase . '_' . $version . '_' . $position);
+
+ // combine content to encrypt the IV identifier and actual IV
+ $catFile = $this->concatIV($encryptedContent, $iv);
+ $catFile = $this->concatSig($catFile, $sig);
+ return $this->addPadding($catFile);
+ }
+
+ /**
+ * generate header for encrypted file
+ *
+ * @param string $keyFormat see SUPPORTED_KEY_FORMATS
+ * @return string
+ * @throws \InvalidArgumentException
+ */
+ public function generateHeader($keyFormat = self::DEFAULT_KEY_FORMAT) {
+ if (in_array($keyFormat, self::SUPPORTED_KEY_FORMATS, true) === false) {
+ throw new \InvalidArgumentException('key format "' . $keyFormat . '" is not supported');
+ }
+
+ $header = self::HEADER_START
+ . ':cipher:' . $this->getCipher()
+ . ':keyFormat:' . $keyFormat;
+
+ if ($this->useLegacyBase64Encoding !== true) {
+ $header .= ':encoding:' . self::BINARY_ENCODING_FORMAT;
+ }
+
+ $header .= ':' . self::HEADER_END;
+
+ return $header;
+ }
+
+ /**
+ * @throws EncryptionFailedException
+ */
+ private function encrypt(string $plainContent, string $iv, string $passPhrase = '', string $cipher = self::DEFAULT_CIPHER): string {
+ $options = $this->useLegacyBase64Encoding ? 0 : OPENSSL_RAW_DATA;
+ $encryptedContent = openssl_encrypt($plainContent,
+ $cipher,
+ $passPhrase,
+ $options,
+ $iv);
+
+ if (!$encryptedContent) {
+ $error = 'Encryption (symmetric) of content failed';
+ $this->logger->error($error . openssl_error_string(),
+ ['app' => 'encryption']);
+ throw new EncryptionFailedException($error);
+ }
+
+ return $encryptedContent;
+ }
+
+ /**
+ * return cipher either from config.php or the default cipher defined in
+ * this class
+ */
+ private function getCachedCipher(): string {
+ if (isset($this->currentCipher)) {
+ return $this->currentCipher;
+ }
+
+ // Get cipher either from config.php or the default cipher defined in this class
+ $cipher = $this->config->getSystemValueString('cipher', self::DEFAULT_CIPHER);
+ if (!isset(self::SUPPORTED_CIPHERS_AND_KEY_SIZE[$cipher])) {
+ $this->logger->warning(
+ sprintf(
+ 'Unsupported cipher (%s) defined in config.php supported. Falling back to %s',
+ $cipher,
+ self::DEFAULT_CIPHER
+ ),
+ ['app' => 'encryption']
+ );
+ $cipher = self::DEFAULT_CIPHER;
+ }
+
+ // Remember current cipher to avoid frequent lookups
+ $this->currentCipher = $cipher;
+ return $this->currentCipher;
+ }
+
+ /**
+ * return current encryption cipher
+ *
+ * @return string
+ */
+ public function getCipher() {
+ return $this->getCachedCipher();
+ }
+
+ /**
+ * get key size depending on the cipher
+ *
+ * @param string $cipher
+ * @return int
+ * @throws \InvalidArgumentException
+ */
+ protected function getKeySize($cipher) {
+ if (isset(self::SUPPORTED_CIPHERS_AND_KEY_SIZE[$cipher])) {
+ return self::SUPPORTED_CIPHERS_AND_KEY_SIZE[$cipher];
+ }
+
+ throw new \InvalidArgumentException(
+ sprintf(
+ 'Unsupported cipher (%s) defined.',
+ $cipher
+ )
+ );
+ }
+
+ /**
+ * get legacy cipher
+ *
+ * @return string
+ */
+ public function getLegacyCipher() {
+ if (!$this->supportLegacy) {
+ throw new ServerNotAvailableException('Legacy cipher is no longer supported!');
+ }
+
+ return self::LEGACY_CIPHER;
+ }
+
+ private function concatIV(string $encryptedContent, string $iv): string {
+ return $encryptedContent . '00iv00' . $iv;
+ }
+
+ private function concatSig(string $encryptedContent, string $signature): string {
+ return $encryptedContent . '00sig00' . $signature;
+ }
+
+ /**
+ * Note: This is _NOT_ a padding used for encryption purposes. It is solely
+ * used to achieve the PHP stream size. It has _NOTHING_ to do with the
+ * encrypted content and is not used in any crypto primitive.
+ */
+ private function addPadding(string $data): string {
+ return $data . 'xxx';
+ }
+
+ /**
+ * generate password hash used to encrypt the users private key
+ *
+ * @param string $uid only used for user keys
+ */
+ protected function generatePasswordHash(string $password, string $cipher, string $uid = '', int $iterations = 600000): string {
+ $instanceId = $this->config->getSystemValue('instanceid');
+ $instanceSecret = $this->config->getSystemValue('secret');
+ $salt = hash('sha256', $uid . $instanceId . $instanceSecret, true);
+ $keySize = $this->getKeySize($cipher);
+
+ return hash_pbkdf2(
+ 'sha256',
+ $password,
+ $salt,
+ $iterations,
+ $keySize,
+ true
+ );
+ }
+
+ /**
+ * encrypt private key
+ *
+ * @param string $privateKey
+ * @param string $password
+ * @param string $uid for regular users, empty for system keys
+ * @return false|string
+ */
+ public function encryptPrivateKey($privateKey, $password, $uid = '') {
+ $cipher = $this->getCipher();
+ $hash = $this->generatePasswordHash($password, $cipher, $uid);
+ $encryptedKey = $this->symmetricEncryptFileContent(
+ $privateKey,
+ $hash,
+ 0,
+ '0'
+ );
+
+ return $encryptedKey;
+ }
+
+ /**
+ * @param string $privateKey
+ * @param string $password
+ * @param string $uid for regular users, empty for system keys
+ * @return false|string
+ */
+ public function decryptPrivateKey($privateKey, $password = '', $uid = '') {
+ $header = $this->parseHeader($privateKey);
+
+ if (isset($header['cipher'])) {
+ $cipher = $header['cipher'];
+ } else {
+ $cipher = $this->getLegacyCipher();
+ }
+
+ if (isset($header['keyFormat'])) {
+ $keyFormat = $header['keyFormat'];
+ } else {
+ $keyFormat = self::LEGACY_KEY_FORMAT;
+ }
+
+ if ($keyFormat === 'hash') {
+ $password = $this->generatePasswordHash($password, $cipher, $uid, 100000);
+ } elseif ($keyFormat === 'hash2') {
+ $password = $this->generatePasswordHash($password, $cipher, $uid, 600000);
+ }
+
+ $binaryEncoding = isset($header['encoding']) && $header['encoding'] === self::BINARY_ENCODING_FORMAT;
+
+ // If we found a header we need to remove it from the key we want to decrypt
+ if (!empty($header)) {
+ $privateKey = substr($privateKey,
+ strpos($privateKey,
+ self::HEADER_END) + strlen(self::HEADER_END));
+ }
+
+ $plainKey = $this->symmetricDecryptFileContent(
+ $privateKey,
+ $password,
+ $cipher,
+ 0,
+ 0,
+ $binaryEncoding
+ );
+
+ if ($this->isValidPrivateKey($plainKey) === false) {
+ return false;
+ }
+
+ return $plainKey;
+ }
+
+ /**
+ * check if it is a valid private key
+ *
+ * @param string $plainKey
+ * @return bool
+ */
+ protected function isValidPrivateKey($plainKey) {
+ $res = openssl_get_privatekey($plainKey);
+ if (is_object($res) && get_class($res) === 'OpenSSLAsymmetricKey') {
+ $sslInfo = openssl_pkey_get_details($res);
+ if (isset($sslInfo['key'])) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ /**
+ * @param string $keyFileContents
+ * @param string $passPhrase
+ * @param string $cipher
+ * @param int $version
+ * @param int|string $position
+ * @param boolean $binaryEncoding
+ * @return string
+ * @throws DecryptionFailedException
+ */
+ public function symmetricDecryptFileContent($keyFileContents, $passPhrase, $cipher = self::DEFAULT_CIPHER, $version = 0, $position = 0, bool $binaryEncoding = false) {
+ if ($keyFileContents == '') {
+ return '';
+ }
+
+ $catFile = $this->splitMetaData($keyFileContents, $cipher);
+
+ if ($catFile['signature'] !== false) {
+ try {
+ // First try the new format
+ $this->checkSignature($catFile['encrypted'], $passPhrase . '_' . $version . '_' . $position, $catFile['signature']);
+ } catch (GenericEncryptionException $e) {
+ // For compatibility with old files check the version without _
+ $this->checkSignature($catFile['encrypted'], $passPhrase . $version . $position, $catFile['signature']);
+ }
+ }
+
+ return $this->decrypt($catFile['encrypted'],
+ $catFile['iv'],
+ $passPhrase,
+ $cipher,
+ $binaryEncoding);
+ }
+
+ /**
+ * check for valid signature
+ *
+ * @throws GenericEncryptionException
+ */
+ private function checkSignature(string $data, string $passPhrase, string $expectedSignature): void {
+ $enforceSignature = !$this->config->getSystemValueBool('encryption_skip_signature_check', false);
+
+ $signature = $this->createSignature($data, $passPhrase);
+ $isCorrectHash = hash_equals($expectedSignature, $signature);
+
+ if (!$isCorrectHash) {
+ if ($enforceSignature) {
+ throw new GenericEncryptionException('Bad Signature', $this->l->t('Bad Signature'));
+ } else {
+ $this->logger->info('Signature check skipped', ['app' => 'encryption']);
+ }
+ }
+ }
+
+ /**
+ * create signature
+ */
+ private function createSignature(string $data, string $passPhrase): string {
+ $passPhrase = hash('sha512', $passPhrase . 'a', true);
+ return hash_hmac('sha256', $data, $passPhrase);
+ }
+
+
+ /**
+ * @param bool $hasSignature did the block contain a signature, in this case we use a different padding
+ */
+ private function removePadding(string $padded, bool $hasSignature = false): string|false {
+ if ($hasSignature === false && substr($padded, -2) === 'xx') {
+ return substr($padded, 0, -2);
+ } elseif ($hasSignature === true && substr($padded, -3) === 'xxx') {
+ return substr($padded, 0, -3);
+ }
+ return false;
+ }
+
+ /**
+ * split meta data from encrypted file
+ * Note: for now, we assume that the meta data always start with the iv
+ * followed by the signature, if available
+ */
+ private function splitMetaData(string $catFile, string $cipher): array {
+ if ($this->hasSignature($catFile, $cipher)) {
+ $catFile = $this->removePadding($catFile, true);
+ $meta = substr($catFile, -93);
+ $iv = substr($meta, strlen('00iv00'), 16);
+ $sig = substr($meta, 22 + strlen('00sig00'));
+ $encrypted = substr($catFile, 0, -93);
+ } else {
+ $catFile = $this->removePadding($catFile);
+ $meta = substr($catFile, -22);
+ $iv = substr($meta, -16);
+ $sig = false;
+ $encrypted = substr($catFile, 0, -22);
+ }
+
+ return [
+ 'encrypted' => $encrypted,
+ 'iv' => $iv,
+ 'signature' => $sig
+ ];
+ }
+
+ /**
+ * check if encrypted block is signed
+ *
+ * @throws GenericEncryptionException
+ */
+ private function hasSignature(string $catFile, string $cipher): bool {
+ $skipSignatureCheck = $this->config->getSystemValueBool('encryption_skip_signature_check', false);
+
+ $meta = substr($catFile, -93);
+ $signaturePosition = strpos($meta, '00sig00');
+
+ // If we no longer support the legacy format then everything needs a signature
+ if (!$skipSignatureCheck && !$this->supportLegacy && $signaturePosition === false) {
+ throw new GenericEncryptionException('Missing Signature', $this->l->t('Missing Signature'));
+ }
+
+ // Enforce signature for the new 'CTR' ciphers
+ if (!$skipSignatureCheck && $signaturePosition === false && stripos($cipher, 'ctr') !== false) {
+ throw new GenericEncryptionException('Missing Signature', $this->l->t('Missing Signature'));
+ }
+
+ return ($signaturePosition !== false);
+ }
+
+
+ /**
+ * @throws DecryptionFailedException
+ */
+ private function decrypt(string $encryptedContent, string $iv, string $passPhrase = '', string $cipher = self::DEFAULT_CIPHER, bool $binaryEncoding = false): string {
+ $options = $binaryEncoding === true ? OPENSSL_RAW_DATA : 0;
+ $plainContent = openssl_decrypt($encryptedContent,
+ $cipher,
+ $passPhrase,
+ $options,
+ $iv);
+
+ if ($plainContent) {
+ return $plainContent;
+ } else {
+ throw new DecryptionFailedException('Encryption library: Decryption (symmetric) of content failed: ' . openssl_error_string());
+ }
+ }
+
+ /**
+ * @param string $data
+ * @return array
+ */
+ protected function parseHeader($data) {
+ $result = [];
+
+ if (substr($data, 0, strlen(self::HEADER_START)) === self::HEADER_START) {
+ $endAt = strpos($data, self::HEADER_END);
+ $header = substr($data, 0, $endAt + strlen(self::HEADER_END));
+
+ // +1 not to start with an ':' which would result in empty element at the beginning
+ $exploded = explode(':',
+ substr($header, strlen(self::HEADER_START) + 1));
+
+ $element = array_shift($exploded);
+
+ while ($element !== self::HEADER_END) {
+ $result[$element] = array_shift($exploded);
+ $element = array_shift($exploded);
+ }
+ }
+
+ return $result;
+ }
+
+ /**
+ * generate initialization vector
+ *
+ * @throws GenericEncryptionException
+ */
+ private function generateIv(): string {
+ return random_bytes(16);
+ }
+
+ /**
+ * Generate a cryptographically secure pseudo-random 256-bit ASCII key, used
+ * as file key
+ *
+ * @return string
+ * @throws \Exception
+ */
+ public function generateFileKey() {
+ return random_bytes(32);
+ }
+
+ /**
+ * @param \OpenSSLAsymmetricKey|\OpenSSLCertificate|array|string $privateKey
+ * @throws MultiKeyDecryptException
+ */
+ public function multiKeyDecrypt(string $shareKey, $privateKey): string {
+ $plainContent = '';
+
+ // decrypt the intermediate key with RSA
+ if (openssl_private_decrypt($shareKey, $intermediate, $privateKey, OPENSSL_PKCS1_OAEP_PADDING)) {
+ return $intermediate;
+ } else {
+ throw new MultiKeyDecryptException('multikeydecrypt with share key failed:' . openssl_error_string());
+ }
+ }
+
+ /**
+ * @param \OpenSSLAsymmetricKey|\OpenSSLCertificate|array|string $privateKey
+ * @throws MultiKeyDecryptException
+ */
+ public function multiKeyDecryptLegacy(string $encKeyFile, string $shareKey, $privateKey): string {
+ if (!$encKeyFile) {
+ throw new MultiKeyDecryptException('Cannot multikey decrypt empty plain content');
+ }
+
+ $plainContent = '';
+ if ($this->opensslOpen($encKeyFile, $plainContent, $shareKey, $privateKey, 'RC4')) {
+ return $plainContent;
+ } else {
+ throw new MultiKeyDecryptException('multikeydecrypt with share key failed:' . openssl_error_string());
+ }
+ }
+
+ /**
+ * @param array<string,\OpenSSLAsymmetricKey|\OpenSSLCertificate|array|string> $keyFiles
+ * @throws MultiKeyEncryptException
+ */
+ public function multiKeyEncrypt(string $plainContent, array $keyFiles): array {
+ if (empty($plainContent)) {
+ throw new MultiKeyEncryptException('Cannot multikeyencrypt empty plain content');
+ }
+
+ // Set empty vars to be set by openssl by reference
+ $shareKeys = [];
+ $mappedShareKeys = [];
+
+ // make sure that there is at least one public key to use
+ if (count($keyFiles) >= 1) {
+ // prepare the encrypted keys
+ $shareKeys = [];
+
+ // iterate over the public keys and encrypt the intermediate
+ // for each of them with RSA
+ foreach ($keyFiles as $tmp_key) {
+ if (openssl_public_encrypt($plainContent, $tmp_output, $tmp_key, OPENSSL_PKCS1_OAEP_PADDING)) {
+ $shareKeys[] = $tmp_output;
+ }
+ }
+
+ // set the result if everything worked fine
+ if (count($keyFiles) === count($shareKeys)) {
+ $i = 0;
+
+ // Ensure each shareKey is labelled with its corresponding key id
+ foreach ($keyFiles as $userId => $publicKey) {
+ $mappedShareKeys[$userId] = $shareKeys[$i];
+ $i++;
+ }
+
+ return $mappedShareKeys;
+ }
+ }
+ throw new MultiKeyEncryptException('multikeyencryption failed ' . openssl_error_string());
+ }
+
+ /**
+ * @param string $plainContent
+ * @param array $keyFiles
+ * @return array
+ * @throws MultiKeyEncryptException
+ * @deprecated 27.0.0 use multiKeyEncrypt
+ */
+ public function multiKeyEncryptLegacy($plainContent, array $keyFiles) {
+ // openssl_seal returns false without errors if plaincontent is empty
+ // so trigger our own error
+ if (empty($plainContent)) {
+ throw new MultiKeyEncryptException('Cannot multikeyencrypt empty plain content');
+ }
+
+ // Set empty vars to be set by openssl by reference
+ $sealed = '';
+ $shareKeys = [];
+ $mappedShareKeys = [];
+
+ if ($this->opensslSeal($plainContent, $sealed, $shareKeys, $keyFiles, 'RC4')) {
+ $i = 0;
+
+ // Ensure each shareKey is labelled with its corresponding key id
+ foreach ($keyFiles as $userId => $publicKey) {
+ $mappedShareKeys[$userId] = $shareKeys[$i];
+ $i++;
+ }
+
+ return [
+ 'keys' => $mappedShareKeys,
+ 'data' => $sealed
+ ];
+ } else {
+ throw new MultiKeyEncryptException('multikeyencryption failed ' . openssl_error_string());
+ }
+ }
+
+ /**
+ * returns the value of $useLegacyBase64Encoding
+ *
+ * @return bool
+ */
+ public function useLegacyBase64Encoding(): bool {
+ return $this->useLegacyBase64Encoding;
+ }
+
+ /**
+ * Uses phpseclib RC4 implementation
+ */
+ private function rc4Decrypt(string $data, string $secret): string {
+ $rc4 = new RC4();
+ /** @psalm-suppress InternalMethod */
+ $rc4->setKey($secret);
+
+ return $rc4->decrypt($data);
+ }
+
+ /**
+ * Uses phpseclib RC4 implementation
+ */
+ private function rc4Encrypt(string $data, string $secret): string {
+ $rc4 = new RC4();
+ /** @psalm-suppress InternalMethod */
+ $rc4->setKey($secret);
+
+ return $rc4->encrypt($data);
+ }
+
+ /**
+ * Custom implementation of openssl_open()
+ *
+ * @param \OpenSSLAsymmetricKey|\OpenSSLCertificate|array|string $private_key
+ * @throws DecryptionFailedException
+ */
+ private function opensslOpen(string $data, string &$output, string $encrypted_key, $private_key, string $cipher_algo): bool {
+ $result = false;
+
+ // check if RC4 is used
+ if (strcasecmp($cipher_algo, 'rc4') === 0) {
+ // decrypt the intermediate key with RSA
+ if (openssl_private_decrypt($encrypted_key, $intermediate, $private_key, OPENSSL_PKCS1_PADDING)) {
+ // decrypt the file key with the intermediate key
+ // using our own RC4 implementation
+ $output = $this->rc4Decrypt($data, $intermediate);
+ $result = (strlen($output) === strlen($data));
+ }
+ } else {
+ throw new DecryptionFailedException('Unsupported cipher ' . $cipher_algo);
+ }
+
+ return $result;
+ }
+
+ /**
+ * Custom implementation of openssl_seal()
+ *
+ * @deprecated 27.0.0 use multiKeyEncrypt
+ * @throws EncryptionFailedException
+ */
+ private function opensslSeal(string $data, string &$sealed_data, array &$encrypted_keys, array $public_key, string $cipher_algo): int|false {
+ $result = false;
+
+ // check if RC4 is used
+ if (strcasecmp($cipher_algo, 'rc4') === 0) {
+ // make sure that there is at least one public key to use
+ if (count($public_key) >= 1) {
+ // generate the intermediate key
+ $intermediate = openssl_random_pseudo_bytes(16, $strong_result);
+
+ // check if we got strong random data
+ if ($strong_result) {
+ // encrypt the file key with the intermediate key
+ // using our own RC4 implementation
+ $sealed_data = $this->rc4Encrypt($data, $intermediate);
+ if (strlen($sealed_data) === strlen($data)) {
+ // prepare the encrypted keys
+ $encrypted_keys = [];
+
+ // iterate over the public keys and encrypt the intermediate
+ // for each of them with RSA
+ foreach ($public_key as $tmp_key) {
+ if (openssl_public_encrypt($intermediate, $tmp_output, $tmp_key, OPENSSL_PKCS1_PADDING)) {
+ $encrypted_keys[] = $tmp_output;
+ }
+ }
+
+ // set the result if everything worked fine
+ if (count($public_key) === count($encrypted_keys)) {
+ $result = strlen($sealed_data);
+ }
+ }
+ }
+ }
+ } else {
+ throw new EncryptionFailedException('Unsupported cipher ' . $cipher_algo);
+ }
+
+ return $result;
+ }
+}
diff --git a/apps/encryption/lib/Crypto/DecryptAll.php b/apps/encryption/lib/Crypto/DecryptAll.php
new file mode 100644
index 00000000000..362f43b8672
--- /dev/null
+++ b/apps/encryption/lib/Crypto/DecryptAll.php
@@ -0,0 +1,124 @@
+<?php
+
+/**
+ * SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
+ */
+namespace OCA\Encryption\Crypto;
+
+use OCA\Encryption\Exceptions\PrivateKeyMissingException;
+use OCA\Encryption\KeyManager;
+use OCA\Encryption\Session;
+use OCA\Encryption\Util;
+use Symfony\Component\Console\Helper\QuestionHelper;
+use Symfony\Component\Console\Input\InputInterface;
+use Symfony\Component\Console\Output\OutputInterface;
+use Symfony\Component\Console\Question\ConfirmationQuestion;
+use Symfony\Component\Console\Question\Question;
+
+class DecryptAll {
+
+ /**
+ * @param Util $util
+ * @param KeyManager $keyManager
+ * @param Crypt $crypt
+ * @param Session $session
+ * @param QuestionHelper $questionHelper
+ */
+ public function __construct(
+ protected Util $util,
+ protected KeyManager $keyManager,
+ protected Crypt $crypt,
+ protected Session $session,
+ protected QuestionHelper $questionHelper,
+ ) {
+ }
+
+ /**
+ * prepare encryption module to decrypt all files
+ *
+ * @param InputInterface $input
+ * @param OutputInterface $output
+ * @param $user
+ * @return bool
+ */
+ public function prepare(InputInterface $input, OutputInterface $output, $user) {
+ $question = new Question('Please enter the recovery key password: ');
+
+ if ($this->util->isMasterKeyEnabled()) {
+ $output->writeln('Use master key to decrypt all files');
+ $user = $this->keyManager->getMasterKeyId();
+ $password = $this->keyManager->getMasterKeyPassword();
+ } else {
+ $recoveryKeyId = $this->keyManager->getRecoveryKeyId();
+ if (!empty($user)) {
+ $output->writeln('You can only decrypt the users files if you know');
+ $output->writeln('the users password or if they activated the recovery key.');
+ $output->writeln('');
+ $questionUseLoginPassword = new ConfirmationQuestion(
+ 'Do you want to use the users login password to decrypt all files? (y/n) ',
+ false
+ );
+ $useLoginPassword = $this->questionHelper->ask($input, $output, $questionUseLoginPassword);
+ if ($useLoginPassword) {
+ $question = new Question('Please enter the user\'s login password: ');
+ } elseif ($this->util->isRecoveryEnabledForUser($user) === false) {
+ $output->writeln('No recovery key available for user ' . $user);
+ return false;
+ } else {
+ $user = $recoveryKeyId;
+ }
+ } else {
+ $output->writeln('You can only decrypt the files of all users if the');
+ $output->writeln('recovery key is enabled by the admin and activated by the users.');
+ $output->writeln('');
+ $user = $recoveryKeyId;
+ }
+
+ $question->setHidden(true);
+ $question->setHiddenFallback(false);
+ $password = $this->questionHelper->ask($input, $output, $question);
+ }
+
+ $privateKey = $this->getPrivateKey($user, $password);
+ if ($privateKey !== false) {
+ $this->updateSession($user, $privateKey);
+ return true;
+ } else {
+ $output->writeln('Could not decrypt private key, maybe you entered the wrong password?');
+ }
+
+
+ return false;
+ }
+
+ /**
+ * get the private key which will be used to decrypt all files
+ *
+ * @param string $user
+ * @param string $password
+ * @return bool|string
+ * @throws PrivateKeyMissingException
+ */
+ protected function getPrivateKey($user, $password) {
+ $recoveryKeyId = $this->keyManager->getRecoveryKeyId();
+ $masterKeyId = $this->keyManager->getMasterKeyId();
+ if ($user === $recoveryKeyId) {
+ $recoveryKey = $this->keyManager->getSystemPrivateKey($recoveryKeyId);
+ $privateKey = $this->crypt->decryptPrivateKey($recoveryKey, $password);
+ } elseif ($user === $masterKeyId) {
+ $masterKey = $this->keyManager->getSystemPrivateKey($masterKeyId);
+ $privateKey = $this->crypt->decryptPrivateKey($masterKey, $password, $masterKeyId);
+ } else {
+ $userKey = $this->keyManager->getPrivateKey($user);
+ $privateKey = $this->crypt->decryptPrivateKey($userKey, $password, $user);
+ }
+
+ return $privateKey;
+ }
+
+ protected function updateSession($user, $privateKey) {
+ $this->session->prepareDecryptAll($user, $privateKey);
+ }
+}
diff --git a/apps/encryption/lib/Crypto/EncryptAll.php b/apps/encryption/lib/Crypto/EncryptAll.php
new file mode 100644
index 00000000000..4ed75b85a93
--- /dev/null
+++ b/apps/encryption/lib/Crypto/EncryptAll.php
@@ -0,0 +1,429 @@
+<?php
+
+/**
+ * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
+ */
+namespace OCA\Encryption\Crypto;
+
+use OC\Encryption\Exceptions\DecryptionFailedException;
+use OC\Files\View;
+use OCA\Encryption\KeyManager;
+use OCA\Encryption\Users\Setup;
+use OCA\Encryption\Util;
+use OCP\Files\FileInfo;
+use OCP\IConfig;
+use OCP\IL10N;
+use OCP\IUser;
+use OCP\IUserManager;
+use OCP\L10N\IFactory;
+use OCP\Mail\Headers\AutoSubmitted;
+use OCP\Mail\IMailer;
+use OCP\Security\ISecureRandom;
+use Psr\Log\LoggerInterface;
+use Symfony\Component\Console\Helper\ProgressBar;
+use Symfony\Component\Console\Helper\QuestionHelper;
+use Symfony\Component\Console\Helper\Table;
+use Symfony\Component\Console\Input\InputInterface;
+use Symfony\Component\Console\Output\OutputInterface;
+use Symfony\Component\Console\Question\ConfirmationQuestion;
+
+class EncryptAll {
+
+ /** @var array */
+ protected $userPasswords;
+
+ /** @var OutputInterface */
+ protected $output;
+
+ /** @var InputInterface */
+ protected $input;
+
+ public function __construct(
+ protected Setup $userSetup,
+ protected IUserManager $userManager,
+ protected View $rootView,
+ protected KeyManager $keyManager,
+ protected Util $util,
+ protected IConfig $config,
+ protected IMailer $mailer,
+ protected IL10N $l,
+ protected IFactory $l10nFactory,
+ protected QuestionHelper $questionHelper,
+ protected ISecureRandom $secureRandom,
+ protected LoggerInterface $logger,
+ ) {
+ // store one time passwords for the users
+ $this->userPasswords = [];
+ }
+
+ /**
+ * start to encrypt all files
+ *
+ * @param InputInterface $input
+ * @param OutputInterface $output
+ */
+ public function encryptAll(InputInterface $input, OutputInterface $output) {
+ $this->input = $input;
+ $this->output = $output;
+
+ $headline = 'Encrypt all files with the ' . Encryption::DISPLAY_NAME;
+ $this->output->writeln("\n");
+ $this->output->writeln($headline);
+ $this->output->writeln(str_pad('', strlen($headline), '='));
+ $this->output->writeln("\n");
+
+ if ($this->util->isMasterKeyEnabled()) {
+ $this->output->writeln('Use master key to encrypt all files.');
+ $this->keyManager->validateMasterKey();
+ } else {
+ //create private/public keys for each user and store the private key password
+ $this->output->writeln('Create key-pair for every user');
+ $this->output->writeln('------------------------------');
+ $this->output->writeln('');
+ $this->output->writeln('This module will encrypt all files in the users files folder initially.');
+ $this->output->writeln('Already existing versions and files in the trash bin will not be encrypted.');
+ $this->output->writeln('');
+ $this->createKeyPairs();
+ }
+
+
+ // output generated encryption key passwords
+ if ($this->util->isMasterKeyEnabled() === false) {
+ //send-out or display password list and write it to a file
+ $this->output->writeln("\n");
+ $this->output->writeln('Generated encryption key passwords');
+ $this->output->writeln('----------------------------------');
+ $this->output->writeln('');
+ $this->outputPasswords();
+ }
+
+ //setup users file system and encrypt all files one by one (take should encrypt setting of storage into account)
+ $this->output->writeln("\n");
+ $this->output->writeln('Start to encrypt users files');
+ $this->output->writeln('----------------------------');
+ $this->output->writeln('');
+ $this->encryptAllUsersFiles();
+ $this->output->writeln("\n");
+ }
+
+ /**
+ * create key-pair for every user
+ */
+ protected function createKeyPairs() {
+ $this->output->writeln("\n");
+ $progress = new ProgressBar($this->output);
+ $progress->setFormat(" %message% \n [%bar%]");
+ $progress->start();
+
+ foreach ($this->userManager->getBackends() as $backend) {
+ $limit = 500;
+ $offset = 0;
+ do {
+ $users = $backend->getUsers('', $limit, $offset);
+ foreach ($users as $user) {
+ if ($this->keyManager->userHasKeys($user) === false) {
+ $progress->setMessage('Create key-pair for ' . $user);
+ $progress->advance();
+ $this->setupUserFS($user);
+ $password = $this->generateOneTimePassword($user);
+ $this->userSetup->setupUser($user, $password);
+ } else {
+ // users which already have a key-pair will be stored with a
+ // empty password and filtered out later
+ $this->userPasswords[$user] = '';
+ }
+ }
+ $offset += $limit;
+ } while (count($users) >= $limit);
+ }
+
+ $progress->setMessage('Key-pair created for all users');
+ $progress->finish();
+ }
+
+ /**
+ * iterate over all user and encrypt their files
+ */
+ protected function encryptAllUsersFiles() {
+ $this->output->writeln("\n");
+ $progress = new ProgressBar($this->output);
+ $progress->setFormat(" %message% \n [%bar%]");
+ $progress->start();
+ $numberOfUsers = count($this->userPasswords);
+ $userNo = 1;
+ if ($this->util->isMasterKeyEnabled()) {
+ $this->encryptAllUserFilesWithMasterKey($progress);
+ } else {
+ foreach ($this->userPasswords as $uid => $password) {
+ $userCount = "$uid ($userNo of $numberOfUsers)";
+ $this->encryptUsersFiles($uid, $progress, $userCount);
+ $userNo++;
+ }
+ }
+ $progress->setMessage('all files encrypted');
+ $progress->finish();
+ }
+
+ /**
+ * encrypt all user files with the master key
+ *
+ * @param ProgressBar $progress
+ */
+ protected function encryptAllUserFilesWithMasterKey(ProgressBar $progress) {
+ $userNo = 1;
+ foreach ($this->userManager->getBackends() as $backend) {
+ $limit = 500;
+ $offset = 0;
+ do {
+ $users = $backend->getUsers('', $limit, $offset);
+ foreach ($users as $user) {
+ $userCount = "$user ($userNo)";
+ $this->encryptUsersFiles($user, $progress, $userCount);
+ $userNo++;
+ }
+ $offset += $limit;
+ } while (count($users) >= $limit);
+ }
+ }
+
+ /**
+ * encrypt files from the given user
+ *
+ * @param string $uid
+ * @param ProgressBar $progress
+ * @param string $userCount
+ */
+ protected function encryptUsersFiles($uid, ProgressBar $progress, $userCount) {
+ $this->setupUserFS($uid);
+ $directories = [];
+ $directories[] = '/' . $uid . '/files';
+
+ while ($root = array_pop($directories)) {
+ $content = $this->rootView->getDirectoryContent($root);
+ foreach ($content as $file) {
+ $path = $root . '/' . $file->getName();
+ if ($file->isShared()) {
+ $progress->setMessage("Skip shared file/folder $path");
+ $progress->advance();
+ continue;
+ } elseif ($file->getType() === FileInfo::TYPE_FOLDER) {
+ $directories[] = $path;
+ continue;
+ } else {
+ $progress->setMessage("encrypt files for user $userCount: $path");
+ $progress->advance();
+ try {
+ if ($this->encryptFile($file, $path) === false) {
+ $progress->setMessage("encrypt files for user $userCount: $path (already encrypted)");
+ $progress->advance();
+ }
+ } catch (\Exception $e) {
+ $progress->setMessage("Failed to encrypt path $path: " . $e->getMessage());
+ $progress->advance();
+ $this->logger->error(
+ 'Failed to encrypt path {path}',
+ [
+ 'user' => $uid,
+ 'path' => $path,
+ 'exception' => $e,
+ ]
+ );
+ }
+ }
+ }
+ }
+ }
+
+ protected function encryptFile(FileInfo $fileInfo, string $path): bool {
+ // skip already encrypted files
+ if ($fileInfo->isEncrypted()) {
+ return true;
+ }
+
+ $source = $path;
+ $target = $path . '.encrypted.' . time();
+
+ try {
+ $copySuccess = $this->rootView->copy($source, $target);
+ if ($copySuccess === false) {
+ /* Copy failed, abort */
+ if ($this->rootView->file_exists($target)) {
+ $this->rootView->unlink($target);
+ }
+ throw new \Exception('Copy failed for ' . $source);
+ }
+ $this->rootView->rename($target, $source);
+ } catch (DecryptionFailedException $e) {
+ if ($this->rootView->file_exists($target)) {
+ $this->rootView->unlink($target);
+ }
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * output one-time encryption passwords
+ */
+ protected function outputPasswords() {
+ $table = new Table($this->output);
+ $table->setHeaders(['Username', 'Private key password']);
+
+ //create rows
+ $newPasswords = [];
+ $unchangedPasswords = [];
+ foreach ($this->userPasswords as $uid => $password) {
+ if (empty($password)) {
+ $unchangedPasswords[] = $uid;
+ } else {
+ $newPasswords[] = [$uid, $password];
+ }
+ }
+
+ if (empty($newPasswords)) {
+ $this->output->writeln("\nAll users already had a key-pair, no further action needed.\n");
+ return;
+ }
+
+ $table->setRows($newPasswords);
+ $table->render();
+
+ if (!empty($unchangedPasswords)) {
+ $this->output->writeln("\nThe following users already had a key-pair which was reused without setting a new password:\n");
+ foreach ($unchangedPasswords as $uid) {
+ $this->output->writeln(" $uid");
+ }
+ }
+
+ $this->writePasswordsToFile($newPasswords);
+
+ $this->output->writeln('');
+ $question = new ConfirmationQuestion('Do you want to send the passwords directly to the users by mail? (y/n) ', false);
+ if ($this->questionHelper->ask($this->input, $this->output, $question)) {
+ $this->sendPasswordsByMail();
+ }
+ }
+
+ /**
+ * write one-time encryption passwords to a csv file
+ *
+ * @param array $passwords
+ */
+ protected function writePasswordsToFile(array $passwords) {
+ $fp = $this->rootView->fopen('oneTimeEncryptionPasswords.csv', 'w');
+ foreach ($passwords as $pwd) {
+ fputcsv($fp, $pwd);
+ }
+ fclose($fp);
+ $this->output->writeln("\n");
+ $this->output->writeln('A list of all newly created passwords was written to data/oneTimeEncryptionPasswords.csv');
+ $this->output->writeln('');
+ $this->output->writeln('Each of these users need to login to the web interface, go to the');
+ $this->output->writeln('personal settings section "basic encryption module" and');
+ $this->output->writeln('update the private key password to match the login password again by');
+ $this->output->writeln('entering the one-time password into the "old log-in password" field');
+ $this->output->writeln('and their current login password');
+ }
+
+ /**
+ * setup user file system
+ *
+ * @param string $uid
+ */
+ protected function setupUserFS($uid) {
+ \OC_Util::tearDownFS();
+ \OC_Util::setupFS($uid);
+ }
+
+ /**
+ * generate one time password for the user and store it in a array
+ *
+ * @param string $uid
+ * @return string password
+ */
+ protected function generateOneTimePassword($uid) {
+ $password = $this->secureRandom->generate(16, ISecureRandom::CHAR_HUMAN_READABLE);
+ $this->userPasswords[$uid] = $password;
+ return $password;
+ }
+
+ /**
+ * send encryption key passwords to the users by mail
+ */
+ protected function sendPasswordsByMail() {
+ $noMail = [];
+
+ $this->output->writeln('');
+ $progress = new ProgressBar($this->output, count($this->userPasswords));
+ $progress->start();
+
+ foreach ($this->userPasswords as $uid => $password) {
+ $progress->advance();
+ if (!empty($password)) {
+ $recipient = $this->userManager->get($uid);
+ if (!$recipient instanceof IUser) {
+ continue;
+ }
+
+ $recipientDisplayName = $recipient->getDisplayName();
+ $to = $recipient->getEMailAddress();
+
+ if ($to === '' || $to === null) {
+ $noMail[] = $uid;
+ continue;
+ }
+
+ $l = $this->l10nFactory->get('encryption', $this->l10nFactory->getUserLanguage($recipient));
+
+ $template = $this->mailer->createEMailTemplate('encryption.encryptAllPassword', [
+ 'user' => $recipient->getUID(),
+ 'password' => $password,
+ ]);
+
+ $template->setSubject($l->t('one-time password for server-side-encryption'));
+ // 'Hey there,<br><br>The administration enabled server-side-encryption. Your files were encrypted using the password <strong>%s</strong>.<br><br>
+ // Please login to the web interface, go to the section "Basic encryption module" of your personal settings and update your encryption password by entering this password into the "Old log-in password" field and your current login-password.<br><br>'
+ $template->addHeader();
+ $template->addHeading($l->t('Encryption password'));
+ $template->addBodyText(
+ $l->t('The administration enabled server-side-encryption. Your files were encrypted using the password <strong>%s</strong>.', [htmlspecialchars($password)]),
+ $l->t('The administration enabled server-side-encryption. Your files were encrypted using the password "%s".', $password)
+ );
+ $template->addBodyText(
+ $l->t('Please login to the web interface, go to the "Security" section of your personal settings and update your encryption password by entering this password into the "Old login password" field and your current login password.')
+ );
+ $template->addFooter();
+
+ // send it out now
+ try {
+ $message = $this->mailer->createMessage();
+ $message->setTo([$to => $recipientDisplayName]);
+ $message->useTemplate($template);
+ $message->setAutoSubmitted(AutoSubmitted::VALUE_AUTO_GENERATED);
+ $this->mailer->send($message);
+ } catch (\Exception $e) {
+ $noMail[] = $uid;
+ }
+ }
+ }
+
+ $progress->finish();
+
+ if (empty($noMail)) {
+ $this->output->writeln("\n\nPassword successfully send to all users");
+ } else {
+ $table = new Table($this->output);
+ $table->setHeaders(['Username', 'Private key password']);
+ $this->output->writeln("\n\nCould not send password to following users:\n");
+ $rows = [];
+ foreach ($noMail as $uid) {
+ $rows[] = [$uid, $this->userPasswords[$uid]];
+ }
+ $table->setRows($rows);
+ $table->render();
+ }
+ }
+}
diff --git a/apps/encryption/lib/Crypto/Encryption.php b/apps/encryption/lib/Crypto/Encryption.php
new file mode 100644
index 00000000000..6d388624e48
--- /dev/null
+++ b/apps/encryption/lib/Crypto/Encryption.php
@@ -0,0 +1,554 @@
+<?php
+
+/**
+ * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
+ * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
+ * SPDX-License-Identifier: AGPL-3.0-only
+ */
+namespace OCA\Encryption\Crypto;
+
+use OC\Encryption\Exceptions\DecryptionFailedException;
+use OC\Files\Cache\Scanner;
+use OC\Files\View;
+use OCA\Encryption\Exceptions\MultiKeyEncryptException;
+use OCA\Encryption\Exceptions\PublicKeyMissingException;
+use OCA\Encryption\KeyManager;
+use OCA\Encryption\Session;
+use OCA\Encryption\Util;
+use OCP\Encryption\IEncryptionModule;
+use OCP\IL10N;
+use Psr\Log\LoggerInterface;
+use Symfony\Component\Console\Input\InputInterface;
+use Symfony\Component\Console\Output\OutputInterface;
+
+class Encryption implements IEncryptionModule {
+ public const ID = 'OC_DEFAULT_MODULE';
+ public const DISPLAY_NAME = 'Default encryption module';
+
+ /** @var string */
+ private $cipher;
+
+ /** @var string */
+ private $path;
+
+ /** @var string */
+ private $user;
+
+ private array $owner;
+
+ /** @var string */
+ private $fileKey;
+
+ /** @var string */
+ private $writeCache;
+
+ /** @var array */
+ private $accessList;
+
+ /** @var boolean */
+ private $isWriteOperation;
+
+ private bool $useMasterPassword;
+
+ private bool $useLegacyBase64Encoding = false;
+
+ /** @var int Current version of the file */
+ private int $version = 0;
+
+ /** @var array remember encryption signature version */
+ private static $rememberVersion = [];
+
+ public function __construct(
+ private Crypt $crypt,
+ private KeyManager $keyManager,
+ private Util $util,
+ private Session $session,
+ private EncryptAll $encryptAll,
+ private DecryptAll $decryptAll,
+ private LoggerInterface $logger,
+ private IL10N $l,
+ ) {
+ $this->owner = [];
+ $this->useMasterPassword = $this->util->isMasterKeyEnabled();
+ }
+
+ /**
+ * @return string defining the technical unique id
+ */
+ public function getId() {
+ return self::ID;
+ }
+
+ /**
+ * In comparison to getKey() this function returns a human readable (maybe translated) name
+ *
+ * @return string
+ */
+ public function getDisplayName() {
+ return self::DISPLAY_NAME;
+ }
+
+ /**
+ * start receiving chunks from a file. This is the place where you can
+ * perform some initial step before starting encrypting/decrypting the
+ * chunks
+ *
+ * @param string $path to the file
+ * @param string $user who read/write the file
+ * @param string $mode php stream open mode
+ * @param array $header contains the header data read from the file
+ * @param array $accessList who has access to the file contains the key 'users' and 'public'
+ *
+ * @return array $header contain data as key-value pairs which should be
+ * written to the header, in case of a write operation
+ * or if no additional data is needed return a empty array
+ */
+ public function begin($path, $user, $mode, array $header, array $accessList) {
+ $this->path = $this->getPathToRealFile($path);
+ $this->accessList = $accessList;
+ $this->user = $user;
+ $this->isWriteOperation = false;
+ $this->writeCache = '';
+ $this->useLegacyBase64Encoding = true;
+
+
+ if (isset($header['encoding'])) {
+ $this->useLegacyBase64Encoding = $header['encoding'] !== Crypt::BINARY_ENCODING_FORMAT;
+ }
+
+ if ($this->session->isReady() === false) {
+ // if the master key is enabled we can initialize encryption
+ // with a empty password and user name
+ if ($this->util->isMasterKeyEnabled()) {
+ $this->keyManager->init('', '');
+ }
+ }
+
+ /* If useLegacyFileKey is not specified in header, auto-detect, to be safe */
+ $useLegacyFileKey = (($header['useLegacyFileKey'] ?? '') == 'false' ? false : null);
+
+ $this->fileKey = $this->keyManager->getFileKey($this->path, $this->user, $useLegacyFileKey, $this->session->decryptAllModeActivated());
+
+ // always use the version from the original file, also part files
+ // need to have a correct version number if they get moved over to the
+ // final location
+ $this->version = (int)$this->keyManager->getVersion($this->stripPartFileExtension($path), new View());
+
+ if (
+ $mode === 'w'
+ || $mode === 'w+'
+ || $mode === 'wb'
+ || $mode === 'wb+'
+ ) {
+ $this->isWriteOperation = true;
+ if (empty($this->fileKey)) {
+ $this->fileKey = $this->crypt->generateFileKey();
+ }
+ } else {
+ // if we read a part file we need to increase the version by 1
+ // because the version number was also increased by writing
+ // the part file
+ if (Scanner::isPartialFile($path)) {
+ $this->version = $this->version + 1;
+ }
+ }
+
+ if ($this->isWriteOperation) {
+ $this->cipher = $this->crypt->getCipher();
+ $this->useLegacyBase64Encoding = $this->crypt->useLegacyBase64Encoding();
+ } elseif (isset($header['cipher'])) {
+ $this->cipher = $header['cipher'];
+ } else {
+ // if we read a file without a header we fall-back to the legacy cipher
+ // which was used in <=oC6
+ $this->cipher = $this->crypt->getLegacyCipher();
+ }
+
+ $result = [
+ 'cipher' => $this->cipher,
+ 'signed' => 'true',
+ 'useLegacyFileKey' => 'false',
+ ];
+
+ if ($this->useLegacyBase64Encoding !== true) {
+ $result['encoding'] = Crypt::BINARY_ENCODING_FORMAT;
+ }
+
+ return $result;
+ }
+
+ /**
+ * last chunk received. This is the place where you can perform some final
+ * operation and return some remaining data if something is left in your
+ * buffer.
+ *
+ * @param string $path to the file
+ * @param string $position
+ * @return string remained data which should be written to the file in case
+ * of a write operation
+ * @throws PublicKeyMissingException
+ * @throws \Exception
+ * @throws MultiKeyEncryptException
+ */
+ public function end($path, $position = '0') {
+ $result = '';
+ if ($this->isWriteOperation) {
+ // in case of a part file we remember the new signature versions
+ // the version will be set later on update.
+ // This way we make sure that other apps listening to the pre-hooks
+ // still get the old version which should be the correct value for them
+ if (Scanner::isPartialFile($path)) {
+ self::$rememberVersion[$this->stripPartFileExtension($path)] = $this->version + 1;
+ }
+ if (!empty($this->writeCache)) {
+ $result = $this->crypt->symmetricEncryptFileContent($this->writeCache, $this->fileKey, $this->version + 1, $position);
+ $this->writeCache = '';
+ }
+ $publicKeys = [];
+ if ($this->useMasterPassword === true) {
+ $publicKeys[$this->keyManager->getMasterKeyId()] = $this->keyManager->getPublicMasterKey();
+ } else {
+ foreach ($this->accessList['users'] as $uid) {
+ try {
+ $publicKeys[$uid] = $this->keyManager->getPublicKey($uid);
+ } catch (PublicKeyMissingException $e) {
+ $this->logger->warning(
+ 'no public key found for user "{uid}", user will not be able to read the file',
+ ['app' => 'encryption', 'uid' => $uid]
+ );
+ // if the public key of the owner is missing we should fail
+ if ($uid === $this->user) {
+ throw $e;
+ }
+ }
+ }
+ }
+
+ $publicKeys = $this->keyManager->addSystemKeys($this->accessList, $publicKeys, $this->getOwner($path));
+ $shareKeys = $this->crypt->multiKeyEncrypt($this->fileKey, $publicKeys);
+ if (!$this->keyManager->deleteLegacyFileKey($this->path)) {
+ $this->logger->warning(
+ 'Failed to delete legacy filekey for {path}',
+ ['app' => 'encryption', 'path' => $path]
+ );
+ }
+ foreach ($shareKeys as $uid => $keyFile) {
+ $this->keyManager->setShareKey($this->path, $uid, $keyFile);
+ }
+ }
+ return $result ?: '';
+ }
+
+
+
+ /**
+ * encrypt data
+ *
+ * @param string $data you want to encrypt
+ * @param int $position
+ * @return string encrypted data
+ */
+ public function encrypt($data, $position = 0) {
+ // If extra data is left over from the last round, make sure it
+ // is integrated into the next block
+ if ($this->writeCache) {
+ // Concat writeCache to start of $data
+ $data = $this->writeCache . $data;
+
+ // Clear the write cache, ready for reuse - it has been
+ // flushed and its old contents processed
+ $this->writeCache = '';
+ }
+
+ $encrypted = '';
+ // While there still remains some data to be processed & written
+ while (strlen($data) > 0) {
+ // Remaining length for this iteration, not of the
+ // entire file (may be greater than 8192 bytes)
+ $remainingLength = strlen($data);
+
+ // If data remaining to be written is less than the
+ // size of 1 unencrypted block
+ if ($remainingLength < $this->getUnencryptedBlockSize(true)) {
+ // Set writeCache to contents of $data
+ // The writeCache will be carried over to the
+ // next write round, and added to the start of
+ // $data to ensure that written blocks are
+ // always the correct length. If there is still
+ // data in writeCache after the writing round
+ // has finished, then the data will be written
+ // to disk by $this->flush().
+ $this->writeCache = $data;
+
+ // Clear $data ready for next round
+ $data = '';
+ } else {
+ // Read the chunk from the start of $data
+ $chunk = substr($data, 0, $this->getUnencryptedBlockSize(true));
+
+ $encrypted .= $this->crypt->symmetricEncryptFileContent($chunk, $this->fileKey, $this->version + 1, (string)$position);
+
+ // Remove the chunk we just processed from
+ // $data, leaving only unprocessed data in $data
+ // var, for handling on the next round
+ $data = substr($data, $this->getUnencryptedBlockSize(true));
+ }
+ }
+
+ return $encrypted;
+ }
+
+ /**
+ * decrypt data
+ *
+ * @param string $data you want to decrypt
+ * @param int|string $position
+ * @return string decrypted data
+ * @throws DecryptionFailedException
+ */
+ public function decrypt($data, $position = 0) {
+ if (empty($this->fileKey)) {
+ $msg = 'Cannot decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you.';
+ $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.');
+ $this->logger->error($msg);
+
+ throw new DecryptionFailedException($msg, $hint);
+ }
+
+ return $this->crypt->symmetricDecryptFileContent($data, $this->fileKey, $this->cipher, $this->version, $position, !$this->useLegacyBase64Encoding);
+ }
+
+ /**
+ * update encrypted file, e.g. give additional users access to the file
+ *
+ * @param string $path path to the file which should be updated
+ * @param string $uid of the user who performs the operation
+ * @param array $accessList who has access to the file contains the key 'users' and 'public'
+ * @return bool
+ */
+ public function update($path, $uid, array $accessList) {
+ if (empty($accessList)) {
+ if (isset(self::$rememberVersion[$path])) {
+ $this->keyManager->setVersion($path, self::$rememberVersion[$path], new View());
+ unset(self::$rememberVersion[$path]);
+ }
+ return false;
+ }
+
+ $fileKey = $this->keyManager->getFileKey($path, $uid, null);
+
+ if (!empty($fileKey)) {
+ $publicKeys = [];
+ if ($this->useMasterPassword === true) {
+ $publicKeys[$this->keyManager->getMasterKeyId()] = $this->keyManager->getPublicMasterKey();
+ } else {
+ foreach ($accessList['users'] as $user) {
+ try {
+ $publicKeys[$user] = $this->keyManager->getPublicKey($user);
+ } catch (PublicKeyMissingException $e) {
+ $this->logger->warning('Could not encrypt file for ' . $user . ': ' . $e->getMessage());
+ }
+ }
+ }
+
+ $publicKeys = $this->keyManager->addSystemKeys($accessList, $publicKeys, $this->getOwner($path));
+
+ $shareKeys = $this->crypt->multiKeyEncrypt($fileKey, $publicKeys);
+
+ $this->keyManager->deleteAllFileKeys($path);
+
+ foreach ($shareKeys as $uid => $keyFile) {
+ $this->keyManager->setShareKey($path, $uid, $keyFile);
+ }
+ } else {
+ $this->logger->debug('no file key found, we assume that the file "{file}" is not encrypted',
+ ['file' => $path, 'app' => 'encryption']);
+
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * should the file be encrypted or not
+ *
+ * @param string $path
+ * @return boolean
+ */
+ public function shouldEncrypt($path) {
+ if ($this->util->shouldEncryptHomeStorage() === false) {
+ $storage = $this->util->getStorage($path);
+ if ($storage && $storage->instanceOfStorage('\OCP\Files\IHomeStorage')) {
+ return false;
+ }
+ }
+ $parts = explode('/', $path);
+ if (count($parts) < 4) {
+ return false;
+ }
+
+ if ($parts[2] === 'files') {
+ return true;
+ }
+ if ($parts[2] === 'files_versions') {
+ return true;
+ }
+ if ($parts[2] === 'files_trashbin') {
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * get size of the unencrypted payload per block.
+ * Nextcloud read/write files with a block size of 8192 byte
+ *
+ * Encrypted blocks have a 22-byte IV and 2 bytes of padding, encrypted and
+ * signed blocks have also a 71-byte signature and 1 more byte of padding,
+ * resulting respectively in:
+ *
+ * 8192 - 22 - 2 = 8168 bytes in each unsigned unencrypted block
+ * 8192 - 22 - 2 - 71 - 1 = 8096 bytes in each signed unencrypted block
+ *
+ * Legacy base64 encoding then reduces the available size by a 3/4 factor:
+ *
+ * 8168 * (3/4) = 6126 bytes in each base64-encoded unsigned unencrypted block
+ * 8096 * (3/4) = 6072 bytes in each base64-encoded signed unencrypted block
+ *
+ * @param bool $signed
+ * @return int
+ */
+ public function getUnencryptedBlockSize($signed = false) {
+ if ($this->useLegacyBase64Encoding) {
+ return $signed ? 6072 : 6126;
+ } else {
+ return $signed ? 8096 : 8168;
+ }
+ }
+
+ /**
+ * check if the encryption module is able to read the file,
+ * e.g. if all encryption keys exists
+ *
+ * @param string $path
+ * @param string $uid user for whom we want to check if they can read the file
+ * @return bool
+ * @throws DecryptionFailedException
+ */
+ public function isReadable($path, $uid) {
+ $fileKey = $this->keyManager->getFileKey($path, $uid, null);
+ if (empty($fileKey)) {
+ $owner = $this->util->getOwner($path);
+ if ($owner !== $uid) {
+ // if it is a shared file we throw a exception with a useful
+ // error message because in this case it means that the file was
+ // shared with the user at a point where the user didn't had a
+ // valid private/public key
+ $msg = 'Encryption module "' . $this->getDisplayName()
+ . '" is not able to read ' . $path;
+ $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.');
+ $this->logger->warning($msg);
+ throw new DecryptionFailedException($msg, $hint);
+ }
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Initial encryption of all files
+ *
+ * @param InputInterface $input
+ * @param OutputInterface $output write some status information to the terminal during encryption
+ */
+ public function encryptAll(InputInterface $input, OutputInterface $output) {
+ $this->encryptAll->encryptAll($input, $output);
+ }
+
+ /**
+ * prepare module to perform decrypt all operation
+ *
+ * @param InputInterface $input
+ * @param OutputInterface $output
+ * @param string $user
+ * @return bool
+ */
+ public function prepareDecryptAll(InputInterface $input, OutputInterface $output, $user = '') {
+ return $this->decryptAll->prepare($input, $output, $user);
+ }
+
+
+ /**
+ * @param string $path
+ * @return string
+ */
+ protected function getPathToRealFile($path) {
+ $realPath = $path;
+ $parts = explode('/', $path);
+ if ($parts[2] === 'files_versions') {
+ $realPath = '/' . $parts[1] . '/files/' . implode('/', array_slice($parts, 3));
+ $length = strrpos($realPath, '.');
+ $realPath = substr($realPath, 0, $length);
+ }
+
+ return $realPath;
+ }
+
+ /**
+ * remove .part file extension and the ocTransferId from the file to get the
+ * original file name
+ *
+ * @param string $path
+ * @return string
+ */
+ protected function stripPartFileExtension($path) {
+ if (pathinfo($path, PATHINFO_EXTENSION) === 'part') {
+ $pos = strrpos($path, '.', -6);
+ $path = substr($path, 0, $pos);
+ }
+
+ return $path;
+ }
+
+ /**
+ * get owner of a file
+ *
+ * @param string $path
+ * @return string
+ */
+ protected function getOwner($path) {
+ if (!isset($this->owner[$path])) {
+ $this->owner[$path] = $this->util->getOwner($path);
+ }
+ return $this->owner[$path];
+ }
+
+ /**
+ * Check if the module is ready to be used by that specific user.
+ * In case a module is not ready - because e.g. key pairs have not been generated
+ * upon login this method can return false before any operation starts and might
+ * cause issues during operations.
+ *
+ * @param string $user
+ * @return boolean
+ * @since 9.1.0
+ */
+ public function isReadyForUser($user) {
+ if ($this->util->isMasterKeyEnabled()) {
+ return true;
+ }
+ return $this->keyManager->userHasKeys($user);
+ }
+
+ /**
+ * We only need a detailed access list if the master key is not enabled
+ *
+ * @return bool
+ */
+ public function needDetailedAccessList() {
+ return !$this->util->isMasterKeyEnabled();
+ }
+}