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.php422
-rw-r--r--apps/encryption/lib/Crypto/DecryptAll.php58
-rw-r--r--apps/encryption/lib/Crypto/EncryptAll.php214
-rw-r--r--apps/encryption/lib/Crypto/Encryption.php229
4 files changed, 439 insertions, 484 deletions
diff --git a/apps/encryption/lib/Crypto/Crypt.php b/apps/encryption/lib/Crypto/Crypt.php
index 93120068c6a..463ca4e22bb 100644
--- a/apps/encryption/lib/Crypto/Crypt.php
+++ b/apps/encryption/lib/Crypto/Crypt.php
@@ -1,32 +1,9 @@
<?php
+
/**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Bjoern Schiessle <bjoern@schiessle.org>
- * @author Björn Schießle <bjoern@schiessle.org>
- * @author Christoph Wurst <christoph@winzerhof-wurst.at>
- * @author Clark Tomlinson <fallen013@gmail.com>
- * @author Joas Schilling <coding@schilljs.com>
- * @author Lukas Reschke <lukas@statuscode.ch>
- * @author Morris Jobke <hey@morrisjobke.de>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- * @author Stefan Weiberg <sweiberg@suse.com>
- * @author Thomas Müller <thomas.mueller@tmit.eu>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
+ * 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;
@@ -38,8 +15,9 @@ use OCA\Encryption\Exceptions\MultiKeyEncryptException;
use OCP\Encryption\Exceptions\GenericEncryptionException;
use OCP\IConfig;
use OCP\IL10N;
-use OCP\ILogger;
use OCP\IUserSession;
+use phpseclib\Crypt\RC4;
+use Psr\Log\LoggerInterface;
/**
* Class Crypt provides the encryption implementation of the default Nextcloud
@@ -67,9 +45,9 @@ class Crypt {
// default cipher from old Nextcloud versions
public const LEGACY_CIPHER = 'AES-128-CFB';
- public const SUPPORTED_KEY_FORMATS = ['hash', 'password'];
+ public const SUPPORTED_KEY_FORMATS = ['hash2', 'hash', 'password'];
// one out of SUPPORTED_KEY_FORMATS
- public const DEFAULT_KEY_FORMAT = 'hash';
+ 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';
@@ -77,53 +55,45 @@ class Crypt {
public const HEADER_START = 'HBEGIN';
public const HEADER_END = 'HEND';
- /** @var ILogger */
- private $logger;
-
- /** @var string */
- private $user;
-
- /** @var IConfig */
- private $config;
+ // default encoding format, old Nextcloud versions used base64
+ public const BINARY_ENCODING_FORMAT = 'binary';
- /** @var IL10N */
- private $l;
+ private string $user;
- /** @var string|null */
- private $currentCipher;
+ private ?string $currentCipher = null;
- /** @var bool */
- private $supportLegacy;
+ private bool $supportLegacy;
/**
- * @param ILogger $logger
- * @param IUserSession $userSession
- * @param IConfig $config
- * @param IL10N $l
+ * Use the legacy base64 encoding instead of the more space-efficient binary encoding.
*/
- public function __construct(ILogger $logger, IUserSession $userSession, IConfig $config, IL10N $l) {
- $this->logger = $logger;
- $this->user = $userSession && $userSession->isLoggedIn() ? $userSession->getUser()->getUID() : '"no user given"';
- $this->config = $config;
- $this->l = $l;
+ 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|bool
+ * @return array{publicKey: string, privateKey: string}|false
*/
public function createKeyPair() {
- $log = $this->logger;
$res = $this->getOpenSSLPKey();
if (!$res) {
- $log->error("Encryption Library couldn't generate users key-pair for {$this->user}",
+ $this->logger->error("Encryption Library couldn't generate users key-pair for {$this->user}",
['app' => 'encryption']);
if (openssl_error_string()) {
- $log->error('Encryption library openssl_pkey_new() fails: ' . openssl_error_string(),
+ $this->logger->error('Encryption library openssl_pkey_new() fails: ' . openssl_error_string(),
['app' => 'encryption']);
}
} elseif (openssl_pkey_export($res,
@@ -138,10 +108,10 @@ class Crypt {
'privateKey' => $privateKey
];
}
- $log->error('Encryption library couldn\'t export users private key, please check your servers OpenSSL configuration.' . $this->user,
+ $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()) {
- $log->error('Encryption Library:' . openssl_error_string(),
+ $this->logger->error('Encryption Library:' . openssl_error_string(),
['app' => 'encryption']);
}
@@ -151,19 +121,14 @@ class Crypt {
/**
* Generates a new private key
*
- * @return resource
+ * @return \OpenSSLAsymmetricKey|false
*/
public function getOpenSSLPKey() {
$config = $this->getOpenSSLConfig();
return openssl_pkey_new($config);
}
- /**
- * get openSSL Config
- *
- * @return array
- */
- private function getOpenSSLConfig() {
+ private function getOpenSSLConfig(): array {
$config = ['private_key_bits' => 4096];
$config = array_merge(
$config,
@@ -173,14 +138,9 @@ class Crypt {
}
/**
- * @param string $plainContent
- * @param string $passPhrase
- * @param int $version
- * @param int $position
- * @return false|string
* @throws EncryptionFailedException
*/
- public function symmetricEncryptFileContent($plainContent, $passPhrase, $version, $position) {
+ 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']);
@@ -195,7 +155,7 @@ class Crypt {
$this->getCipher());
// Create a signature based on the key as well as the current version
- $sig = $this->createSignature($encryptedContent, $passPhrase.'_'.$version.'_'.$position);
+ $sig = $this->createSignature($encryptedContent, $passPhrase . '_' . $version . '_' . $position);
// combine content to encrypt the IV identifier and actual IV
$catFile = $this->concatIV($encryptedContent, $iv);
@@ -215,29 +175,28 @@ class Crypt {
throw new \InvalidArgumentException('key format "' . $keyFormat . '" is not supported');
}
- $cipher = $this->getCipher();
-
$header = self::HEADER_START
- . ':cipher:' . $cipher
- . ':keyFormat:' . $keyFormat
- . ':' . self::HEADER_END;
+ . ':cipher:' . $this->getCipher()
+ . ':keyFormat:' . $keyFormat;
+
+ if ($this->useLegacyBase64Encoding !== true) {
+ $header .= ':encoding:' . self::BINARY_ENCODING_FORMAT;
+ }
+
+ $header .= ':' . self::HEADER_END;
return $header;
}
/**
- * @param string $plainContent
- * @param string $iv
- * @param string $passPhrase
- * @param string $cipher
- * @return string
* @throws EncryptionFailedException
*/
- private function encrypt($plainContent, $iv, $passPhrase = '', $cipher = self::DEFAULT_CIPHER) {
+ 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,
- 0,
+ $options,
$iv);
if (!$encryptedContent) {
@@ -253,16 +212,14 @@ class Crypt {
/**
* return cipher either from config.php or the default cipher defined in
* this class
- *
- * @return string
*/
- private function getCachedCipher() {
+ 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->getSystemValue('cipher', self::DEFAULT_CIPHER);
+ $cipher = $this->config->getSystemValueString('cipher', self::DEFAULT_CIPHER);
if (!isset(self::SUPPORTED_CIPHERS_AND_KEY_SIZE[$cipher])) {
$this->logger->warning(
sprintf(
@@ -303,8 +260,8 @@ class Crypt {
throw new \InvalidArgumentException(
sprintf(
- 'Unsupported cipher (%s) defined.',
- $cipher
+ 'Unsupported cipher (%s) defined.',
+ $cipher
)
);
}
@@ -322,21 +279,11 @@ class Crypt {
return self::LEGACY_CIPHER;
}
- /**
- * @param string $encryptedContent
- * @param string $iv
- * @return string
- */
- private function concatIV($encryptedContent, $iv) {
+ private function concatIV(string $encryptedContent, string $iv): string {
return $encryptedContent . '00iv00' . $iv;
}
- /**
- * @param string $encryptedContent
- * @param string $signature
- * @return string
- */
- private function concatSig($encryptedContent, $signature) {
+ private function concatSig(string $encryptedContent, string $signature): string {
return $encryptedContent . '00sig00' . $signature;
}
@@ -344,38 +291,30 @@ class Crypt {
* 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.
- *
- * @param string $data
- * @return string
*/
- private function addPadding($data) {
+ private function addPadding(string $data): string {
return $data . 'xxx';
}
/**
* generate password hash used to encrypt the users private key
*
- * @param string $password
- * @param string $cipher
* @param string $uid only used for user keys
- * @return string
*/
- protected function generatePasswordHash($password, $cipher, $uid = '') {
+ 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);
- $hash = hash_pbkdf2(
+ return hash_pbkdf2(
'sha256',
$password,
$salt,
- 100000,
+ $iterations,
$keySize,
true
);
-
- return $hash;
}
/**
@@ -393,7 +332,7 @@ class Crypt {
$privateKey,
$hash,
0,
- 0
+ '0'
);
return $encryptedKey;
@@ -420,10 +359,14 @@ class Crypt {
$keyFormat = self::LEGACY_KEY_FORMAT;
}
- if ($keyFormat === self::DEFAULT_KEY_FORMAT) {
- $password = $this->generatePasswordHash($password, $cipher, $uid);
+ 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,
@@ -435,7 +378,9 @@ class Crypt {
$privateKey,
$password,
$cipher,
- 0
+ 0,
+ 0,
+ $binaryEncoding
);
if ($this->isValidPrivateKey($plainKey) === false) {
@@ -453,8 +398,7 @@ class Crypt {
*/
protected function isValidPrivateKey($plainKey) {
$res = openssl_get_privatekey($plainKey);
- // TODO: remove resource check one php7.4 is not longer supported
- if (is_resource($res) || (is_object($res) && get_class($res) === 'OpenSSLAsymmetricKey')) {
+ if (is_object($res) && get_class($res) === 'OpenSSLAsymmetricKey') {
$sslInfo = openssl_pkey_get_details($res);
if (isset($sslInfo['key'])) {
return true;
@@ -470,10 +414,11 @@ class Crypt {
* @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) {
+ public function symmetricDecryptFileContent($keyFileContents, $passPhrase, $cipher = self::DEFAULT_CIPHER, $version = 0, $position = 0, bool $binaryEncoding = false) {
if ($keyFileContents == '') {
return '';
}
@@ -493,51 +438,43 @@ class Crypt {
return $this->decrypt($catFile['encrypted'],
$catFile['iv'],
$passPhrase,
- $cipher);
+ $cipher,
+ $binaryEncoding);
}
/**
* check for valid signature
*
- * @param string $data
- * @param string $passPhrase
- * @param string $expectedSignature
* @throws GenericEncryptionException
*/
- private function checkSignature($data, $passPhrase, $expectedSignature) {
- $enforceSignature = !$this->config->getSystemValue('encryption_skip_signature_check', false);
+ 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 && $enforceSignature) {
- throw new GenericEncryptionException('Bad Signature', $this->l->t('Bad Signature'));
- } elseif (!$isCorrectHash && !$enforceSignature) {
- $this->logger->info("Signature check skipped", ['app' => 'encryption']);
+ 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
- *
- * @param string $data
- * @param string $passPhrase
- * @return string
*/
- private function createSignature($data, $passPhrase) {
+ private function createSignature(string $data, string $passPhrase): string {
$passPhrase = hash('sha512', $passPhrase . 'a', true);
return hash_hmac('sha256', $data, $passPhrase);
}
/**
- * remove padding
- *
- * @param string $padded
* @param bool $hasSignature did the block contain a signature, in this case we use a different padding
- * @return string|false
*/
- private function removePadding($padded, $hasSignature = false) {
+ 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') {
@@ -550,12 +487,8 @@ class Crypt {
* 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
- *
- * @param string $catFile
- * @param string $cipher
- * @return array
*/
- private function splitMetaData($catFile, $cipher) {
+ private function splitMetaData(string $catFile, string $cipher): array {
if ($this->hasSignature($catFile, $cipher)) {
$catFile = $this->removePadding($catFile, true);
$meta = substr($catFile, -93);
@@ -580,13 +513,10 @@ class Crypt {
/**
* check if encrypted block is signed
*
- * @param string $catFile
- * @param string $cipher
- * @return bool
* @throws GenericEncryptionException
*/
- private function hasSignature($catFile, $cipher) {
- $skipSignatureCheck = $this->config->getSystemValue('encryption_skip_signature_check', false);
+ 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');
@@ -606,18 +536,14 @@ class Crypt {
/**
- * @param string $encryptedContent
- * @param string $iv
- * @param string $passPhrase
- * @param string $cipher
- * @return string
* @throws DecryptionFailedException
*/
- private function decrypt($encryptedContent, $iv, $passPhrase = '', $cipher = self::DEFAULT_CIPHER) {
+ 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,
- 0,
+ $options,
$iv);
if ($plainContent) {
@@ -656,10 +582,9 @@ class Crypt {
/**
* generate initialization vector
*
- * @return string
* @throws GenericEncryptionException
*/
- private function generateIv() {
+ private function generateIv(): string {
return random_bytes(16);
}
@@ -675,18 +600,31 @@ class Crypt {
}
/**
- * @param $encKeyFile
- * @param $shareKey
- * @param $privateKey
- * @return string
+ * @param \OpenSSLAsymmetricKey|\OpenSSLCertificate|array|string $privateKey
* @throws MultiKeyDecryptException
*/
- public function multiKeyDecrypt($encKeyFile, $shareKey, $privateKey) {
+ 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');
}
- if (openssl_open($encKeyFile, $plainContent, $shareKey, $privateKey, 'RC4')) {
+ $plainContent = '';
+ if ($this->opensslOpen($encKeyFile, $plainContent, $shareKey, $privateKey, 'RC4')) {
return $plainContent;
} else {
throw new MultiKeyDecryptException('multikeydecrypt with share key failed:' . openssl_error_string());
@@ -694,12 +632,55 @@ class Crypt {
}
/**
+ * @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 multiKeyEncrypt($plainContent, array $keyFiles) {
+ public function multiKeyEncryptLegacy($plainContent, array $keyFiles) {
// openssl_seal returns false without errors if plaincontent is empty
// so trigger our own error
if (empty($plainContent)) {
@@ -711,7 +692,7 @@ class Crypt {
$shareKeys = [];
$mappedShareKeys = [];
- if (openssl_seal($plainContent, $sealed, $shareKeys, $keyFiles, 'RC4')) {
+ if ($this->opensslSeal($plainContent, $sealed, $shareKeys, $keyFiles, 'RC4')) {
$i = 0;
// Ensure each shareKey is labelled with its corresponding key id
@@ -728,4 +709,107 @@ class Crypt {
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
index e982da72086..362f43b8672 100644
--- a/apps/encryption/lib/Crypto/DecryptAll.php
+++ b/apps/encryption/lib/Crypto/DecryptAll.php
@@ -1,27 +1,13 @@
<?php
+
/**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Björn Schießle <bjoern@schiessle.org>
- * @author Christoph Wurst <christoph@winzerhof-wurst.at>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
+ * 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;
@@ -33,21 +19,6 @@ use Symfony\Component\Console\Question\Question;
class DecryptAll {
- /** @var Util */
- protected $util;
-
- /** @var QuestionHelper */
- protected $questionHelper;
-
- /** @var Crypt */
- protected $crypt;
-
- /** @var KeyManager */
- protected $keyManager;
-
- /** @var Session */
- protected $session;
-
/**
* @param Util $util
* @param KeyManager $keyManager
@@ -56,17 +27,12 @@ class DecryptAll {
* @param QuestionHelper $questionHelper
*/
public function __construct(
- Util $util,
- KeyManager $keyManager,
- Crypt $crypt,
- Session $session,
- QuestionHelper $questionHelper
+ protected Util $util,
+ protected KeyManager $keyManager,
+ protected Crypt $crypt,
+ protected Session $session,
+ protected QuestionHelper $questionHelper,
) {
- $this->util = $util;
- $this->keyManager = $keyManager;
- $this->crypt = $crypt;
- $this->session = $session;
- $this->questionHelper = $questionHelper;
}
/**
@@ -88,7 +54,7 @@ class DecryptAll {
$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 he activated the recovery key.');
+ $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) ',
@@ -133,7 +99,7 @@ class DecryptAll {
* @param string $user
* @param string $password
* @return bool|string
- * @throws \OCA\Encryption\Exceptions\PrivateKeyMissingException
+ * @throws PrivateKeyMissingException
*/
protected function getPrivateKey($user, $password) {
$recoveryKeyId = $this->keyManager->getRecoveryKeyId();
diff --git a/apps/encryption/lib/Crypto/EncryptAll.php b/apps/encryption/lib/Crypto/EncryptAll.php
index 1889c557cdc..4ed75b85a93 100644
--- a/apps/encryption/lib/Crypto/EncryptAll.php
+++ b/apps/encryption/lib/Crypto/EncryptAll.php
@@ -1,29 +1,9 @@
<?php
+
/**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Bjoern Schiessle <bjoern@schiessle.org>
- * @author Björn Schießle <bjoern@schiessle.org>
- * @author Christoph Wurst <christoph@winzerhof-wurst.at>
- * @author Kenneth Newwood <kenneth@newwood.name>
- * @author Morris Jobke <hey@morrisjobke.de>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- * @author Thomas Müller <thomas.mueller@tmit.eu>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
+ * 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;
@@ -32,11 +12,16 @@ 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;
@@ -46,79 +31,29 @@ use Symfony\Component\Console\Question\ConfirmationQuestion;
class EncryptAll {
- /** @var Setup */
- protected $userSetup;
-
- /** @var IUserManager */
- protected $userManager;
-
- /** @var View */
- protected $rootView;
-
- /** @var KeyManager */
- protected $keyManager;
-
- /** @var Util */
- protected $util;
-
- /** @var array */
+ /** @var array */
protected $userPasswords;
- /** @var IConfig */
- protected $config;
-
- /** @var IMailer */
- protected $mailer;
-
- /** @var IL10N */
- protected $l;
-
- /** @var QuestionHelper */
- protected $questionHelper;
-
- /** @var OutputInterface */
+ /** @var OutputInterface */
protected $output;
- /** @var InputInterface */
+ /** @var InputInterface */
protected $input;
- /** @var ISecureRandom */
- protected $secureRandom;
-
- /**
- * @param Setup $userSetup
- * @param IUserManager $userManager
- * @param View $rootView
- * @param KeyManager $keyManager
- * @param Util $util
- * @param IConfig $config
- * @param IMailer $mailer
- * @param IL10N $l
- * @param QuestionHelper $questionHelper
- * @param ISecureRandom $secureRandom
- */
public function __construct(
- Setup $userSetup,
- IUserManager $userManager,
- View $rootView,
- KeyManager $keyManager,
- Util $util,
- IConfig $config,
- IMailer $mailer,
- IL10N $l,
- QuestionHelper $questionHelper,
- ISecureRandom $secureRandom
+ 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,
) {
- $this->userSetup = $userSetup;
- $this->userManager = $userManager;
- $this->rootView = $rootView;
- $this->keyManager = $keyManager;
- $this->util = $util;
- $this->config = $config;
- $this->mailer = $mailer;
- $this->l = $l;
- $this->questionHelper = $questionHelper;
- $this->secureRandom = $secureRandom;
// store one time passwords for the users
$this->userPasswords = [];
}
@@ -227,7 +162,7 @@ class EncryptAll {
$userNo++;
}
}
- $progress->setMessage("all files encrypted");
+ $progress->setMessage('all files encrypted');
$progress->finish();
}
@@ -268,33 +203,42 @@ class EncryptAll {
while ($root = array_pop($directories)) {
$content = $this->rootView->getDirectoryContent($root);
foreach ($content as $file) {
- $path = $root . '/' . $file['name'];
- if ($this->rootView->is_dir($path)) {
+ $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();
- if ($this->encryptFile($path) === false) {
- $progress->setMessage("encrypt files for user $userCount: $path (already encrypted)");
+ 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,
+ ]
+ );
}
}
}
}
}
- /**
- * encrypt file
- *
- * @param string $path
- * @return bool
- */
- protected function encryptFile($path) {
-
+ protected function encryptFile(FileInfo $fileInfo, string $path): bool {
// skip already encrypted files
- $fileInfo = $this->rootView->getFileInfo($path);
- if ($fileInfo !== false && $fileInfo->isEncrypted()) {
+ if ($fileInfo->isEncrypted()) {
return true;
}
@@ -302,7 +246,14 @@ class EncryptAll {
$target = $path . '.encrypted.' . time();
try {
- $this->rootView->copy($source, $target);
+ $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)) {
@@ -413,6 +364,10 @@ class EncryptAll {
$progress->advance();
if (!empty($password)) {
$recipient = $this->userManager->get($uid);
+ if (!$recipient instanceof IUser) {
+ continue;
+ }
+
$recipientDisplayName = $recipient->getDisplayName();
$to = $recipient->getEMailAddress();
@@ -421,20 +376,33 @@ class EncryptAll {
continue;
}
- $subject = $this->l->t('one-time password for server-side-encryption');
- [$htmlBody, $textBody] = $this->createMailBody($password);
+ $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->setSubject($subject);
$message->setTo([$to => $recipientDisplayName]);
- $message->setHtmlBody($htmlBody);
- $message->setPlainBody($textBody);
- $message->setFrom([
- \OCP\Util::getDefaultEmailAddress('admin-noreply')
- ]);
-
+ $message->useTemplate($template);
+ $message->setAutoSubmitted(AutoSubmitted::VALUE_AUTO_GENERATED);
$this->mailer->send($message);
} catch (\Exception $e) {
$noMail[] = $uid;
@@ -458,22 +426,4 @@ class EncryptAll {
$table->render();
}
}
-
- /**
- * create mail body for plain text and html mail
- *
- * @param string $password one-time encryption password
- * @return array an array of the html mail body and the plain text mail body
- */
- protected function createMailBody($password) {
- $html = new \OC_Template("encryption", "mail", "");
- $html->assign('password', $password);
- $htmlMail = $html->fetchPage();
-
- $plainText = new \OC_Template("encryption", "altmail", "");
- $plainText->assign('password', $password);
- $plainTextMail = $plainText->fetchPage();
-
- return [$htmlMail, $plainTextMail];
- }
}
diff --git a/apps/encryption/lib/Crypto/Encryption.php b/apps/encryption/lib/Crypto/Encryption.php
index 58cefcbe087..6d388624e48 100644
--- a/apps/encryption/lib/Crypto/Encryption.php
+++ b/apps/encryption/lib/Crypto/Encryption.php
@@ -1,48 +1,23 @@
<?php
+
/**
- * @copyright Copyright (c) 2016, ownCloud, Inc.
- *
- * @author Bjoern Schiessle <bjoern@schiessle.org>
- * @author Björn Schießle <bjoern@schiessle.org>
- * @author Christoph Wurst <christoph@winzerhof-wurst.at>
- * @author Clark Tomlinson <fallen013@gmail.com>
- * @author Jan-Christoph Borchardt <hey@jancborchardt.net>
- * @author Joas Schilling <coding@schilljs.com>
- * @author Julius Härtl <jus@bitgrid.net>
- * @author Lukas Reschke <lukas@statuscode.ch>
- * @author Morris Jobke <hey@morrisjobke.de>
- * @author Robin Appelman <robin@icewind.nl>
- * @author Roeland Jago Douma <roeland@famdouma.nl>
- * @author Thomas Müller <thomas.mueller@tmit.eu>
- * @author Valdnet <47037905+Valdnet@users.noreply.github.com>
- *
- * @license AGPL-3.0
- *
- * This code is free software: you can redistribute it and/or modify
- * it under the terms of the GNU Affero General Public License, version 3,
- * as published by the Free Software Foundation.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU Affero General Public License for more details.
- *
- * You should have received a copy of the GNU Affero General Public License, version 3,
- * along with this program. If not, see <http://www.gnu.org/licenses/>
- *
+ * 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 OCP\ILogger;
+use Psr\Log\LoggerInterface;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
@@ -50,11 +25,6 @@ class Encryption implements IEncryptionModule {
public const ID = 'OC_DEFAULT_MODULE';
public const DISPLAY_NAME = 'Default encryption module';
- /**
- * @var Crypt
- */
- private $crypt;
-
/** @var string */
private $cipher;
@@ -64,8 +34,7 @@ class Encryption implements IEncryptionModule {
/** @var string */
private $user;
- /** @var array */
- private $owner;
+ private array $owner;
/** @var string */
private $fileKey;
@@ -73,78 +42,34 @@ class Encryption implements IEncryptionModule {
/** @var string */
private $writeCache;
- /** @var KeyManager */
- private $keyManager;
-
/** @var array */
private $accessList;
/** @var boolean */
private $isWriteOperation;
- /** @var Util */
- private $util;
-
- /** @var Session */
- private $session;
-
- /** @var ILogger */
- private $logger;
-
- /** @var IL10N */
- private $l;
-
- /** @var EncryptAll */
- private $encryptAll;
-
- /** @var bool */
- private $useMasterPassword;
-
- /** @var DecryptAll */
- private $decryptAll;
+ private bool $useMasterPassword;
- /** @var int unencrypted block size if block contains signature */
- private $unencryptedBlockSizeSigned = 6072;
-
- /** @var int unencrypted block size */
- private $unencryptedBlockSize = 6126;
+ private bool $useLegacyBase64Encoding = false;
/** @var int Current version of the file */
- private $version = 0;
+ private int $version = 0;
/** @var array remember encryption signature version */
private static $rememberVersion = [];
-
- /**
- *
- * @param Crypt $crypt
- * @param KeyManager $keyManager
- * @param Util $util
- * @param Session $session
- * @param EncryptAll $encryptAll
- * @param DecryptAll $decryptAll
- * @param ILogger $logger
- * @param IL10N $il10n
- */
- public function __construct(Crypt $crypt,
- KeyManager $keyManager,
- Util $util,
- Session $session,
- EncryptAll $encryptAll,
- DecryptAll $decryptAll,
- ILogger $logger,
- IL10N $il10n) {
- $this->crypt = $crypt;
- $this->keyManager = $keyManager;
- $this->util = $util;
- $this->session = $session;
- $this->encryptAll = $encryptAll;
- $this->decryptAll = $decryptAll;
- $this->logger = $logger;
- $this->l = $il10n;
+ 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 = $util->isMasterKeyEnabled();
+ $this->useMasterPassword = $this->util->isMasterKeyEnabled();
}
/**
@@ -175,8 +100,8 @@ class Encryption implements IEncryptionModule {
* @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
+ * 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);
@@ -184,6 +109,12 @@ class Encryption implements IEncryptionModule {
$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
@@ -193,15 +124,10 @@ class Encryption implements IEncryptionModule {
}
}
- if ($this->session->decryptAllModeActivated()) {
- $encryptedFileKey = $this->keyManager->getEncryptedFileKey($this->path);
- $shareKey = $this->keyManager->getShareKey($this->path, $this->session->getDecryptAllUid());
- $this->fileKey = $this->crypt->multiKeyDecrypt($encryptedFileKey,
- $shareKey,
- $this->session->getDecryptAllKey());
- } else {
- $this->fileKey = $this->keyManager->getFileKey($this->path, $this->user);
- }
+ /* 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
@@ -229,6 +155,7 @@ class Encryption implements IEncryptionModule {
if ($this->isWriteOperation) {
$this->cipher = $this->crypt->getCipher();
+ $this->useLegacyBase64Encoding = $this->crypt->useLegacyBase64Encoding();
} elseif (isset($header['cipher'])) {
$this->cipher = $header['cipher'];
} else {
@@ -237,7 +164,17 @@ class Encryption implements IEncryptionModule {
$this->cipher = $this->crypt->getLegacyCipher();
}
- return ['cipher' => $this->cipher, 'signed' => 'true'];
+ $result = [
+ 'cipher' => $this->cipher,
+ 'signed' => 'true',
+ 'useLegacyFileKey' => 'false',
+ ];
+
+ if ($this->useLegacyBase64Encoding !== true) {
+ $result['encoding'] = Crypt::BINARY_ENCODING_FORMAT;
+ }
+
+ return $result;
}
/**
@@ -246,14 +183,14 @@ class Encryption implements IEncryptionModule {
* buffer.
*
* @param string $path to the file
- * @param int $position
+ * @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 \OCA\Encryption\Exceptions\MultiKeyEncryptException
+ * @throws MultiKeyEncryptException
*/
- public function end($path, $position = 0) {
+ public function end($path, $position = '0') {
$result = '';
if ($this->isWriteOperation) {
// in case of a part file we remember the new signature versions
@@ -288,10 +225,18 @@ class Encryption implements IEncryptionModule {
}
$publicKeys = $this->keyManager->addSystemKeys($this->accessList, $publicKeys, $this->getOwner($path));
- $encryptedKeyfiles = $this->crypt->multiKeyEncrypt($this->fileKey, $publicKeys);
- $this->keyManager->setAllFileKeys($this->path, $encryptedKeyfiles);
+ $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;
+ return $result ?: '';
}
@@ -307,7 +252,6 @@ class Encryption implements IEncryptionModule {
// 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;
@@ -319,15 +263,13 @@ class Encryption implements IEncryptionModule {
$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 6126 byte block
- if ($remainingLength < $this->unencryptedBlockSizeSigned) {
-
+ // 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
@@ -341,16 +283,15 @@ class Encryption implements IEncryptionModule {
// Clear $data ready for next round
$data = '';
} else {
-
// Read the chunk from the start of $data
- $chunk = substr($data, 0, $this->unencryptedBlockSizeSigned);
+ $chunk = substr($data, 0, $this->getUnencryptedBlockSize(true));
- $encrypted .= $this->crypt->symmetricEncryptFileContent($chunk, $this->fileKey, $this->version + 1, $position);
+ $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->unencryptedBlockSizeSigned);
+ $data = substr($data, $this->getUnencryptedBlockSize(true));
}
}
@@ -374,7 +315,7 @@ class Encryption implements IEncryptionModule {
throw new DecryptionFailedException($msg, $hint);
}
- return $this->crypt->symmetricDecryptFileContent($data, $this->fileKey, $this->cipher, $this->version, $position);
+ return $this->crypt->symmetricDecryptFileContent($data, $this->fileKey, $this->cipher, $this->version, $position, !$this->useLegacyBase64Encoding);
}
/**
@@ -383,7 +324,7 @@ class Encryption implements IEncryptionModule {
* @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 boolean
+ * @return bool
*/
public function update($path, $uid, array $accessList) {
if (empty($accessList)) {
@@ -391,10 +332,10 @@ class Encryption implements IEncryptionModule {
$this->keyManager->setVersion($path, self::$rememberVersion[$path], new View());
unset(self::$rememberVersion[$path]);
}
- return;
+ return false;
}
- $fileKey = $this->keyManager->getFileKey($path, $uid);
+ $fileKey = $this->keyManager->getFileKey($path, $uid, null);
if (!empty($fileKey)) {
$publicKeys = [];
@@ -412,11 +353,13 @@ class Encryption implements IEncryptionModule {
$publicKeys = $this->keyManager->addSystemKeys($accessList, $publicKeys, $this->getOwner($path));
- $encryptedFileKey = $this->crypt->multiKeyEncrypt($fileKey, $publicKeys);
+ $shareKeys = $this->crypt->multiKeyEncrypt($fileKey, $publicKeys);
$this->keyManager->deleteAllFileKeys($path);
- $this->keyManager->setAllFileKeys($path, $encryptedFileKey);
+ 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']);
@@ -462,15 +405,27 @@ class Encryption implements IEncryptionModule {
* 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 ($signed === false) {
- return $this->unencryptedBlockSize;
+ if ($this->useLegacyBase64Encoding) {
+ return $signed ? 6072 : 6126;
+ } else {
+ return $signed ? 8096 : 8168;
}
-
- return $this->unencryptedBlockSizeSigned;
}
/**
@@ -478,12 +433,12 @@ class Encryption implements IEncryptionModule {
* e.g. if all encryption keys exists
*
* @param string $path
- * @param string $uid user for whom we want to check if he can read the file
+ * @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);
+ $fileKey = $this->keyManager->getFileKey($path, $uid, null);
if (empty($fileKey)) {
$owner = $this->util->getOwner($path);
if ($owner !== $uid) {
@@ -491,8 +446,8 @@ class Encryption implements IEncryptionModule {
// 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;
+ $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);