123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815 |
- <?php
- 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 {
- public const SUPPORTED_CIPHERS_AND_KEY_SIZE = [
- 'AES-256-CTR' => 32,
- 'AES-128-CTR' => 16,
- 'AES-256-CFB' => 32,
- 'AES-128-CFB' => 16,
- ];
-
- public const DEFAULT_CIPHER = 'AES-256-CTR';
-
- public const LEGACY_CIPHER = 'AES-128-CFB';
- public const SUPPORTED_KEY_FORMATS = ['hash2', 'hash', 'password'];
-
- public const DEFAULT_KEY_FORMAT = 'hash2';
-
-
- public const LEGACY_KEY_FORMAT = 'password';
- public const HEADER_START = 'HBEGIN';
- public const HEADER_END = 'HEND';
-
- public const BINARY_ENCODING_FORMAT = 'binary';
- private string $user;
- private ?string $currentCipher = null;
- private bool $supportLegacy;
-
- 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);
- }
-
- 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;
- }
-
- 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;
- }
-
- 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());
-
- $sig = $this->createSignature($encryptedContent, $passPhrase . '_' . $version . '_' . $position);
-
- $catFile = $this->concatIV($encryptedContent, $iv);
- $catFile = $this->concatSig($catFile, $sig);
- return $this->addPadding($catFile);
- }
-
- 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;
- }
-
- 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;
- }
-
- private function getCachedCipher(): string {
- if (isset($this->currentCipher)) {
- return $this->currentCipher;
- }
-
- $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;
- }
-
- $this->currentCipher = $cipher;
- return $this->currentCipher;
- }
-
- public function getCipher() {
- return $this->getCachedCipher();
- }
-
- 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
- )
- );
- }
-
- 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;
- }
-
- private function addPadding(string $data): string {
- return $data . 'xxx';
- }
-
- 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
- );
- }
-
- public function encryptPrivateKey($privateKey, $password, $uid = '') {
- $cipher = $this->getCipher();
- $hash = $this->generatePasswordHash($password, $cipher, $uid);
- $encryptedKey = $this->symmetricEncryptFileContent(
- $privateKey,
- $hash,
- 0,
- '0'
- );
- return $encryptedKey;
- }
-
- 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 (!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;
- }
-
- 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;
- }
-
- 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 {
-
- $this->checkSignature($catFile['encrypted'], $passPhrase . '_' . $version . '_' . $position, $catFile['signature']);
- } catch (GenericEncryptionException $e) {
-
- $this->checkSignature($catFile['encrypted'], $passPhrase . $version . $position, $catFile['signature']);
- }
- }
- return $this->decrypt($catFile['encrypted'],
- $catFile['iv'],
- $passPhrase,
- $cipher,
- $binaryEncoding);
- }
-
- 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']);
- }
- }
- }
-
- private function createSignature(string $data, string $passPhrase): string {
- $passPhrase = hash('sha512', $passPhrase . 'a', true);
- return hash_hmac('sha256', $data, $passPhrase);
- }
-
- 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;
- }
-
- 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
- ];
- }
-
- 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 (!$skipSignatureCheck && !$this->supportLegacy && $signaturePosition === false) {
- throw new GenericEncryptionException('Missing Signature', $this->l->t('Missing Signature'));
- }
-
- if (!$skipSignatureCheck && $signaturePosition === false && stripos($cipher, 'ctr') !== false) {
- throw new GenericEncryptionException('Missing Signature', $this->l->t('Missing Signature'));
- }
- return ($signaturePosition !== false);
- }
-
- 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());
- }
- }
-
- 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));
-
- $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;
- }
-
- private function generateIv(): string {
- return random_bytes(16);
- }
-
- public function generateFileKey() {
- return random_bytes(32);
- }
-
- public function multiKeyDecrypt(string $shareKey, $privateKey): string {
- $plainContent = '';
-
- 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());
- }
- }
-
- 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());
- }
- }
-
- public function multiKeyEncrypt(string $plainContent, array $keyFiles): array {
- if (empty($plainContent)) {
- throw new MultiKeyEncryptException('Cannot multikeyencrypt empty plain content');
- }
-
- $shareKeys = [];
- $mappedShareKeys = [];
-
- if (count($keyFiles) >= 1) {
-
- $shareKeys = [];
-
-
- foreach ($keyFiles as $tmp_key) {
- if (openssl_public_encrypt($plainContent, $tmp_output, $tmp_key, OPENSSL_PKCS1_OAEP_PADDING)) {
- $shareKeys[] = $tmp_output;
- }
- }
-
- if (count($keyFiles) === count($shareKeys)) {
- $i = 0;
-
- foreach ($keyFiles as $userId => $publicKey) {
- $mappedShareKeys[$userId] = $shareKeys[$i];
- $i++;
- }
- return $mappedShareKeys;
- }
- }
- throw new MultiKeyEncryptException('multikeyencryption failed ' . openssl_error_string());
- }
-
- public function multiKeyEncryptLegacy($plainContent, array $keyFiles) {
-
-
- if (empty($plainContent)) {
- throw new MultiKeyEncryptException('Cannot multikeyencrypt empty plain content');
- }
-
- $sealed = '';
- $shareKeys = [];
- $mappedShareKeys = [];
- if ($this->opensslSeal($plainContent, $sealed, $shareKeys, $keyFiles, 'RC4')) {
- $i = 0;
-
- foreach ($keyFiles as $userId => $publicKey) {
- $mappedShareKeys[$userId] = $shareKeys[$i];
- $i++;
- }
- return [
- 'keys' => $mappedShareKeys,
- 'data' => $sealed
- ];
- } else {
- throw new MultiKeyEncryptException('multikeyencryption failed ' . openssl_error_string());
- }
- }
-
- public function useLegacyBase64Encoding(): bool {
- return $this->useLegacyBase64Encoding;
- }
-
- private function rc4Decrypt(string $data, string $secret): string {
- $rc4 = new RC4();
-
- $rc4->setKey($secret);
- return $rc4->decrypt($data);
- }
-
- private function rc4Encrypt(string $data, string $secret): string {
- $rc4 = new RC4();
-
- $rc4->setKey($secret);
- return $rc4->encrypt($data);
- }
-
- private function opensslOpen(string $data, string &$output, string $encrypted_key, $private_key, string $cipher_algo): bool {
- $result = false;
-
- if (strcasecmp($cipher_algo, 'rc4') === 0) {
-
- if (openssl_private_decrypt($encrypted_key, $intermediate, $private_key, OPENSSL_PKCS1_PADDING)) {
-
-
- $output = $this->rc4Decrypt($data, $intermediate);
- $result = (strlen($output) === strlen($data));
- }
- } else {
- throw new DecryptionFailedException('Unsupported cipher ' . $cipher_algo);
- }
- return $result;
- }
-
- private function opensslSeal(string $data, string &$sealed_data, array &$encrypted_keys, array $public_key, string $cipher_algo): int|false {
- $result = false;
-
- if (strcasecmp($cipher_algo, 'rc4') === 0) {
-
- if (count($public_key) >= 1) {
-
- $intermediate = openssl_random_pseudo_bytes(16, $strong_result);
-
- if ($strong_result) {
-
-
- $sealed_data = $this->rc4Encrypt($data, $intermediate);
- if (strlen($sealed_data) === strlen($data)) {
-
- $encrypted_keys = [];
-
-
- foreach ($public_key as $tmp_key) {
- if (openssl_public_encrypt($intermediate, $tmp_output, $tmp_key, OPENSSL_PKCS1_PADDING)) {
- $encrypted_keys[] = $tmp_output;
- }
- }
-
- if (count($public_key) === count($encrypted_keys)) {
- $result = strlen($sealed_data);
- }
- }
- }
- }
- } else {
- throw new EncryptionFailedException('Unsupported cipher ' . $cipher_algo);
- }
- return $result;
- }
- }
|