diff options
Diffstat (limited to 'apps/files_encryption/lib')
-rwxr-xr-x[-rw-r--r--] | apps/files_encryption/lib/crypt.php | 952 | ||||
-rw-r--r-- | apps/files_encryption/lib/cryptstream.php | 177 | ||||
-rwxr-xr-x | apps/files_encryption/lib/keymanager.php | 365 | ||||
-rw-r--r-- | apps/files_encryption/lib/proxy.php | 300 | ||||
-rw-r--r-- | apps/files_encryption/lib/session.php | 66 | ||||
-rw-r--r-- | apps/files_encryption/lib/stream.php | 464 | ||||
-rw-r--r-- | apps/files_encryption/lib/util.php | 330 |
7 files changed, 2183 insertions, 471 deletions
diff --git a/apps/files_encryption/lib/crypt.php b/apps/files_encryption/lib/crypt.php index e62c9b77273..fddc89dae54 100644..100755 --- a/apps/files_encryption/lib/crypt.php +++ b/apps/files_encryption/lib/crypt.php @@ -1,220 +1,732 @@ -<?php -/** - * ownCloud - * - * @author Frank Karlitschek - * @copyright 2012 Frank Karlitschek frank@owncloud.org - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE - * License as published by the Free Software Foundation; either - * version 3 of the License, or any later version. - * - * This library 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 along with this library. If not, see <http://www.gnu.org/licenses/>. - * - */ - - - -// Todo: -// - Crypt/decrypt button in the userinterface -// - Setting if crypto should be on by default -// - Add a setting "DonĀ“t encrypt files larger than xx because of performance reasons" -// - Transparent decrypt/encrypt in filesystem.php. Autodetect if a file is encrypted (.encrypted extension) -// - Don't use a password directly as encryption key, but a key which is stored on the server and encrypted with the -// user password. -> password change faster -// - IMPORTANT! Check if the block lenght of the encrypted data stays the same - - -require_once 'Crypt_Blowfish/Blowfish.php'; - -/** - * This class is for crypting and decrypting - */ -class OC_Crypt { - static private $bf = null; - - public static function loginListener($params) { - self::init($params['uid'], $params['password']); - } - - public static function init($login, $password) { - $view=new \OC\Files\View('/'); - if(!$view->file_exists('/'.$login)) { - $view->mkdir('/'.$login); - } - - OC_FileProxy::$enabled=false; - if ( ! $view->file_exists('/'.$login.'/encryption.key')) {// does key exist? - OC_Crypt::createkey($login, $password); - } - $key=$view->file_get_contents('/'.$login.'/encryption.key'); - OC_FileProxy::$enabled=true; - $_SESSION['enckey']=OC_Crypt::decrypt($key, $password); - } - - - /** - * get the blowfish encryption handeler for a key - * @param string $key (optional) - * @return Crypt_Blowfish - * - * if the key is left out, the default handeler will be used - */ - public static function getBlowfish($key='') { - if ($key) { - return new Crypt_Blowfish($key); - } else { - if ( ! isset($_SESSION['enckey'])) { - return false; - } - if ( ! self::$bf) { - self::$bf=new Crypt_Blowfish($_SESSION['enckey']); - } - return self::$bf; - } - } - - public static function createkey($username,$passcode) { - // generate a random key - $key=mt_rand(10000, 99999).mt_rand(10000, 99999).mt_rand(10000, 99999).mt_rand(10000, 99999); - - // encrypt the key with the passcode of the user - $enckey=OC_Crypt::encrypt($key, $passcode); - - // Write the file - $proxyEnabled=OC_FileProxy::$enabled; - OC_FileProxy::$enabled=false; - $view = new \OC\Files\View('/' . $username); - $view->file_put_contents('/encryption.key', $enckey); - OC_FileProxy::$enabled=$proxyEnabled; - } - - public static function changekeypasscode($oldPassword, $newPassword) { - if (OCP\User::isLoggedIn()) { - $username=OCP\USER::getUser(); - $view=new \OC\Files\View('/'.$username); - - // read old key - $key=$view->file_get_contents('/encryption.key'); - - // decrypt key with old passcode - $key=OC_Crypt::decrypt($key, $oldPassword); - - // encrypt again with new passcode - $key=OC_Crypt::encrypt($key, $newPassword); - - // store the new key - $view->file_put_contents('/encryption.key', $key ); - } - } - - /** - * @brief encrypts an content - * @param $content the cleartext message you want to encrypt - * @param $key the encryption key (optional) - * @returns encrypted content - * - * This function encrypts an content - */ - public static function encrypt( $content, $key='') { - $bf = self::getBlowfish($key); - return $bf->encrypt($content); - } - - /** - * @brief decryption of an content - * @param $content the cleartext message you want to decrypt - * @param $key the encryption key (optional) - * @returns cleartext content - * - * This function decrypts an content - */ - public static function decrypt( $content, $key='') { - $bf = self::getBlowfish($key); - $data=$bf->decrypt($content); - return $data; - } - - /** - * @brief encryption of a file - * @param string $source - * @param string $target - * @param string $key the decryption key - * - * This function encrypts a file - */ - public static function encryptFile( $source, $target, $key='') { - $handleread = fopen($source, "rb"); - if ($handleread!=false) { - $handlewrite = fopen($target, "wb"); - while (!feof($handleread)) { - $content = fread($handleread, 8192); - $enccontent=OC_CRYPT::encrypt( $content, $key); - fwrite($handlewrite, $enccontent); - } - fclose($handlewrite); - fclose($handleread); - } - } - - - /** - * @brief decryption of a file - * @param string $source - * @param string $target - * @param string $key the decryption key - * - * This function decrypts a file - */ - public static function decryptFile( $source, $target, $key='') { - $handleread = fopen($source, "rb"); - if ($handleread!=false) { - $handlewrite = fopen($target, "wb"); - while (!feof($handleread)) { - $content = fread($handleread, 8192); - $enccontent=OC_CRYPT::decrypt( $content, $key); - if (feof($handleread)) { - $enccontent=rtrim($enccontent, "\0"); - } - fwrite($handlewrite, $enccontent); - } - fclose($handlewrite); - fclose($handleread); - } - } - - /** - * encrypt data in 8192b sized blocks - */ - public static function blockEncrypt($data, $key='') { - $result=''; - while (strlen($data)) { - $result.=self::encrypt(substr($data, 0, 8192), $key); - $data=substr($data, 8192); - } - return $result; - } - - /** - * decrypt data in 8192b sized blocks - */ - public static function blockDecrypt($data, $key='', $maxLength=0) { - $result=''; - while (strlen($data)) { - $result.=self::decrypt(substr($data, 0, 8192), $key); - $data=substr($data, 8192); - } - if ($maxLength>0) { - return substr($result, 0, $maxLength); - } else { - return rtrim($result, "\0"); - } - } -} +<?php
+/**
+ * ownCloud
+ *
+ * @author Sam Tuke, Frank Karlitschek, Robin Appelman
+ * @copyright 2012 Sam Tuke samtuke@owncloud.com,
+ * Robin Appelman icewind@owncloud.com, Frank Karlitschek
+ * frank@owncloud.org
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or any later version.
+ *
+ * This library 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 along with this library. If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+namespace OCA\Encryption;
+
+require_once 'Crypt_Blowfish/Blowfish.php';
+
+// Todo:
+// - Crypt/decrypt button in the userinterface
+// - Setting if crypto should be on by default
+// - Add a setting "DonĀ“t encrypt files larger than xx because of performance reasons"
+// - Transparent decrypt/encrypt in filesystem.php. Autodetect if a file is encrypted (.encrypted extension)
+// - Don't use a password directly as encryption key. but a key which is stored on the server and encrypted with the user password. -> password change faster
+// - IMPORTANT! Check if the block lenght of the encrypted data stays the same
+
+/**
+ * Class for common cryptography functionality
+ */
+
+class Crypt {
+
+ /**
+ * @brief return encryption mode client or server side encryption
+ * @param string user name (use system wide setting if name=null)
+ * @return string 'client' or 'server'
+ */
+ public static function mode( $user = null ) {
+
+// $mode = \OC_Appconfig::getValue( 'files_encryption', 'mode', 'none' );
+//
+// if ( $mode == 'user') {
+// if ( !$user ) {
+// $user = \OCP\User::getUser();
+// }
+// $mode = 'none';
+// if ( $user ) {
+// $query = \OC_DB::prepare( "SELECT mode FROM *PREFIX*encryption WHERE uid = ?" );
+// $result = $query->execute(array($user));
+// if ($row = $result->fetchRow()){
+// $mode = $row['mode'];
+// }
+// }
+// }
+//
+// return $mode;
+
+ return 'server';
+
+ }
+
+ /**
+ * @brief Create a new encryption keypair
+ * @return array publicKey, privatekey
+ */
+ public static function createKeypair() {
+
+ $res = openssl_pkey_new();
+
+ // Get private key
+ openssl_pkey_export( $res, $privateKey );
+
+ // Get public key
+ $publicKey = openssl_pkey_get_details( $res );
+
+ $publicKey = $publicKey['key'];
+
+ return( array( 'publicKey' => $publicKey, 'privateKey' => $privateKey ) );
+
+ }
+
+ /**
+ * @brief Add arbitrary padding to encrypted data
+ * @param string $data data to be padded
+ * @return padded data
+ * @note In order to end up with data exactly 8192 bytes long we must add two letters. It is impossible to achieve exactly 8192 length blocks with encryption alone, hence padding is added to achieve the required length.
+ */
+ public static function addPadding( $data ) {
+
+ $padded = $data . 'xx';
+
+ return $padded;
+
+ }
+
+ /**
+ * @brief Remove arbitrary padding to encrypted data
+ * @param string $padded padded data to remove padding from
+ * @return unpadded data on success, false on error
+ */
+ public static function removePadding( $padded ) {
+
+ if ( substr( $padded, -2 ) == 'xx' ) {
+
+ $data = substr( $padded, 0, -2 );
+
+ return $data;
+
+ } else {
+
+ # TODO: log the fact that unpadded data was submitted for removal of padding
+ return false;
+
+ }
+
+ }
+
+ /**
+ * @brief Check if a file's contents contains an IV and is symmetrically encrypted
+ * @return true / false
+ * @note see also OCA\Encryption\Util->isEncryptedPath()
+ */
+ public static function isEncryptedContent( $content ) {
+
+ if ( !$content ) {
+
+ return false;
+
+ }
+
+ $noPadding = self::removePadding( $content );
+
+ // Fetch encryption metadata from end of file
+ $meta = substr( $noPadding, -22 );
+
+ // Fetch IV from end of file
+ $iv = substr( $meta, -16 );
+
+ // Fetch identifier from start of metadata
+ $identifier = substr( $meta, 0, 6 );
+
+ if ( $identifier == '00iv00') {
+
+ return true;
+
+ } else {
+
+ return false;
+
+ }
+
+ }
+
+ /**
+ * Check if a file is encrypted according to database file cache
+ * @param string $path
+ * @return bool
+ */
+ public static function isEncryptedMeta( $path ) {
+
+ # TODO: Use DI to get OC_FileCache_Cached out of here
+
+ // Fetch all file metadata from DB
+ $metadata = \OC_FileCache_Cached::get( $path, '' );
+
+ // Return encryption status
+ return isset( $metadata['encrypted'] ) and ( bool )$metadata['encrypted'];
+
+ }
+
+ /**
+ * @brief Check if a file is encrypted via legacy system
+ * @return true / false
+ */
+ public static function isLegacyEncryptedContent( $content ) {
+
+ // Fetch all file metadata from DB
+ $metadata = \OC_FileCache_Cached::get( $content, '' );
+
+ // If a file is flagged with encryption in DB, but isn't a valid content + IV combination, it's probably using the legacy encryption system
+ if (
+ $content
+ and isset( $metadata['encrypted'] )
+ and $metadata['encrypted'] === true
+ and !self::isEncryptedContent( $content )
+ ) {
+
+ return true;
+
+ } else {
+
+ return false;
+
+ }
+
+ }
+
+ /**
+ * @brief Symmetrically encrypt a string
+ * @returns encrypted file
+ */
+ public static function encrypt( $plainContent, $iv, $passphrase = '' ) {
+
+ if ( $encryptedContent = openssl_encrypt( $plainContent, 'AES-128-CFB', $passphrase, false, $iv ) ) {
+
+ return $encryptedContent;
+
+ } else {
+
+ \OC_Log::write( 'Encryption library', 'Encryption (symmetric) of content failed' , \OC_Log::ERROR );
+
+ return false;
+
+ }
+
+ }
+
+ /**
+ * @brief Symmetrically decrypt a string
+ * @returns decrypted file
+ */
+ public static function decrypt( $encryptedContent, $iv, $passphrase ) {
+
+ if ( $plainContent = openssl_decrypt( $encryptedContent, 'AES-128-CFB', $passphrase, false, $iv ) ) {
+
+ return $plainContent;
+
+
+ } else {
+
+ throw new \Exception( 'Encryption library: Decryption (symmetric) of content failed' );
+
+ return false;
+
+ }
+
+ }
+
+ /**
+ * @brief Concatenate encrypted data with its IV and padding
+ * @param string $content content to be concatenated
+ * @param string $iv IV to be concatenated
+ * @returns string concatenated content
+ */
+ public static function concatIv ( $content, $iv ) {
+
+ $combined = $content . '00iv00' . $iv;
+
+ return $combined;
+
+ }
+
+ /**
+ * @brief Split concatenated data and IV into respective parts
+ * @param string $catFile concatenated data to be split
+ * @returns array keys: encrypted, iv
+ */
+ public static function splitIv ( $catFile ) {
+
+ // Fetch encryption metadata from end of file
+ $meta = substr( $catFile, -22 );
+
+ // Fetch IV from end of file
+ $iv = substr( $meta, -16 );
+
+ // Remove IV and IV identifier text to expose encrypted content
+ $encrypted = substr( $catFile, 0, -22 );
+
+ $split = array(
+ 'encrypted' => $encrypted
+ , 'iv' => $iv
+ );
+
+ return $split;
+
+ }
+
+ /**
+ * @brief Symmetrically encrypts a string and returns keyfile content
+ * @param $plainContent content to be encrypted in keyfile
+ * @returns encrypted content combined with IV
+ * @note IV need not be specified, as it will be stored in the returned keyfile
+ * and remain accessible therein.
+ */
+ public static function symmetricEncryptFileContent( $plainContent, $passphrase = '' ) {
+
+ if ( !$plainContent ) {
+
+ return false;
+
+ }
+
+ $iv = self::generateIv();
+
+ if ( $encryptedContent = self::encrypt( $plainContent, $iv, $passphrase ) ) {
+
+ // Combine content to encrypt with IV identifier and actual IV
+ $catfile = self::concatIv( $encryptedContent, $iv );
+
+ $padded = self::addPadding( $catfile );
+
+ return $padded;
+
+ } else {
+
+ \OC_Log::write( 'Encryption library', 'Encryption (symmetric) of keyfile content failed' , \OC_Log::ERROR );
+
+ return false;
+
+ }
+
+ }
+
+
+ /**
+ * @brief Symmetrically decrypts keyfile content
+ * @param string $source
+ * @param string $target
+ * @param string $key the decryption key
+ * @returns decrypted content
+ *
+ * This function decrypts a file
+ */
+ public static function symmetricDecryptFileContent( $keyfileContent, $passphrase = '' ) {
+
+ if ( !$keyfileContent ) {
+
+ throw new \Exception( 'Encryption library: no data provided for decryption' );
+
+ }
+
+ // Remove padding
+ $noPadding = self::removePadding( $keyfileContent );
+
+ // Split into enc data and catfile
+ $catfile = self::splitIv( $noPadding );
+
+ if ( $plainContent = self::decrypt( $catfile['encrypted'], $catfile['iv'], $passphrase ) ) {
+
+ return $plainContent;
+
+ }
+
+ }
+
+ /**
+ * @brief Creates symmetric keyfile content using a generated key
+ * @param string $plainContent content to be encrypted
+ * @returns array keys: key, encrypted
+ * @note symmetricDecryptFileContent() can be used to decrypt files created using this method
+ *
+ * This function decrypts a file
+ */
+ public static function symmetricEncryptFileContentKeyfile( $plainContent ) {
+
+ $key = self::generateKey();
+
+ if( $encryptedContent = self::symmetricEncryptFileContent( $plainContent, $key ) ) {
+
+ return array(
+ 'key' => $key
+ , 'encrypted' => $encryptedContent
+ );
+
+ } else {
+
+ return false;
+
+ }
+
+ }
+
+ /**
+ * @brief Create asymmetrically encrypted keyfile content using a generated key
+ * @param string $plainContent content to be encrypted
+ * @returns array keys: key, encrypted
+ * @note symmetricDecryptFileContent() can be used to decrypt files created using this method
+ *
+ * This function decrypts a file
+ */
+ public static function multiKeyEncrypt( $plainContent, array $publicKeys ) {
+
+ $envKeys = array();
+
+ if( openssl_seal( $plainContent, $sealed, $envKeys, $publicKeys ) ) {
+
+ return array(
+ 'keys' => $envKeys
+ , 'encrypted' => $sealed
+ );
+
+ } else {
+
+ return false;
+
+ }
+
+ }
+
+ /**
+ * @brief Asymmetrically encrypt a file using multiple public keys
+ * @param string $plainContent content to be encrypted
+ * @returns string $plainContent decrypted string
+ * @note symmetricDecryptFileContent() can be used to decrypt files created using this method
+ *
+ * This function decrypts a file
+ */
+ public static function multiKeyDecrypt( $encryptedContent, $envKey, $privateKey ) {
+
+ if ( !$encryptedContent ) {
+
+ return false;
+
+ }
+
+ if ( openssl_open( $encryptedContent, $plainContent, $envKey, $privateKey ) ) {
+
+ return $plainContent;
+
+ } else {
+
+ \OC_Log::write( 'Encryption library', 'Decryption (asymmetric) of sealed content failed' , \OC_Log::ERROR );
+
+ return false;
+
+ }
+
+ }
+
+ /**
+ * @brief Asymetrically encrypt a string using a public key
+ * @returns encrypted file
+ */
+ public static function keyEncrypt( $plainContent, $publicKey ) {
+
+ openssl_public_encrypt( $plainContent, $encryptedContent, $publicKey );
+
+ return $encryptedContent;
+
+ }
+
+ /**
+ * @brief Asymetrically decrypt a file using a private key
+ * @returns decrypted file
+ */
+ public static function keyDecrypt( $encryptedContent, $privatekey ) {
+
+ openssl_private_decrypt( $encryptedContent, $plainContent, $privatekey );
+
+ return $plainContent;
+
+ }
+
+ /**
+ * @brief Encrypts content symmetrically and generates keyfile asymmetrically
+ * @returns array containing catfile and new keyfile.
+ * keys: data, key
+ * @note this method is a wrapper for combining other crypt class methods
+ */
+ public static function keyEncryptKeyfile( $plainContent, $publicKey ) {
+
+ // Encrypt plain data, generate keyfile & encrypted file
+ $cryptedData = self::symmetricEncryptFileContentKeyfile( $plainContent );
+
+ // Encrypt keyfile
+ $cryptedKey = self::keyEncrypt( $cryptedData['key'], $publicKey );
+
+ return array( 'data' => $cryptedData['encrypted'], 'key' => $cryptedKey );
+
+ }
+
+ /**
+ * @brief Takes catfile, keyfile, and private key, and
+ * performs decryption
+ * @returns decrypted content
+ * @note this method is a wrapper for combining other crypt class methods
+ */
+ public static function keyDecryptKeyfile( $catfile, $keyfile, $privateKey ) {
+
+ // Decrypt the keyfile with the user's private key
+ $decryptedKeyfile = self::keyDecrypt( $keyfile, $privateKey );
+
+ // Decrypt the catfile symmetrically using the decrypted keyfile
+ $decryptedData = self::symmetricDecryptFileContent( $catfile, $decryptedKeyfile );
+
+ return $decryptedData;
+
+ }
+
+ /**
+ * @brief Symmetrically encrypt a file by combining encrypted component data blocks
+ */
+ public static function symmetricBlockEncryptFileContent( $plainContent, $key ) {
+
+ $crypted = '';
+
+ $remaining = $plainContent;
+
+ $testarray = array();
+
+ while( strlen( $remaining ) ) {
+
+ //echo "\n\n\$block = ".substr( $remaining, 0, 6126 );
+
+ // Encrypt a chunk of unencrypted data and add it to the rest
+ $block = self::symmetricEncryptFileContent( substr( $remaining, 0, 6126 ), $key );
+
+ $padded = self::addPadding( $block );
+
+ $crypted .= $block;
+
+ $testarray[] = $block;
+
+ // Remove the data already encrypted from remaining unencrypted data
+ $remaining = substr( $remaining, 6126 );
+
+ }
+
+ //echo "hags ";
+
+ //echo "\n\n\n\$crypted = $crypted\n\n\n";
+
+ //print_r($testarray);
+
+ return $crypted;
+
+ }
+
+
+ /**
+ * @brief Symmetrically decrypt a file by combining encrypted component data blocks
+ */
+ public static function symmetricBlockDecryptFileContent( $crypted, $key ) {
+
+ $decrypted = '';
+
+ $remaining = $crypted;
+
+ $testarray = array();
+
+ while( strlen( $remaining ) ) {
+
+ $testarray[] = substr( $remaining, 0, 8192 );
+
+ // Decrypt a chunk of unencrypted data and add it to the rest
+ $decrypted .= self::symmetricDecryptFileContent( $remaining, $key );
+
+ // Remove the data already encrypted from remaining unencrypted data
+ $remaining = substr( $remaining, 8192 );
+
+ }
+
+ //echo "\n\n\$testarray = "; print_r($testarray);
+
+ return $decrypted;
+
+ }
+
+ /**
+ * @brief Generates a pseudo random initialisation vector
+ * @return String $iv generated IV
+ */
+ public static function generateIv() {
+
+ if ( $random = openssl_random_pseudo_bytes( 12, $strong ) ) {
+
+ if ( !$strong ) {
+
+ // If OpenSSL indicates randomness is insecure, log error
+ \OC_Log::write( 'Encryption library', 'Insecure symmetric key was generated using openssl_random_pseudo_bytes()' , \OC_Log::WARN );
+
+ }
+
+ // We encode the iv purely for string manipulation
+ // purposes - it gets decoded before use
+ $iv = base64_encode( $random );
+
+ return $iv;
+
+ } else {
+
+ throw new Exception( 'Generating IV failed' );
+
+ }
+
+ }
+
+ /**
+ * @brief Generate a pseudo random 1024kb ASCII key
+ * @returns $key Generated key
+ */
+ public static function generateKey() {
+
+ // Generate key
+ if ( $key = base64_encode( openssl_random_pseudo_bytes( 183, $strong ) ) ) {
+
+ if ( !$strong ) {
+
+ // If OpenSSL indicates randomness is insecure, log error
+ throw new Exception ( 'Encryption library, Insecure symmetric key was generated using openssl_random_pseudo_bytes()' );
+
+ }
+
+ return $key;
+
+ } else {
+
+ return false;
+
+ }
+
+ }
+
+ public static function changekeypasscode($oldPassword, $newPassword) {
+
+ if(\OCP\User::isLoggedIn()){
+ $key = Keymanager::getPrivateKey( $user, $view );
+ if ( ($key = Crypt::symmetricDecryptFileContent($key,$oldpasswd)) ) {
+ if ( ($key = Crypt::symmetricEncryptFileContent($key, $newpasswd)) ) {
+ Keymanager::setPrivateKey($key);
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ /**
+ * @brief Get the blowfish encryption handeler for a key
+ * @param $key string (optional)
+ * @return Crypt_Blowfish blowfish object
+ *
+ * if the key is left out, the default handeler will be used
+ */
+ public static function getBlowfish( $key = '' ) {
+
+ if ( $key ) {
+
+ return new \Crypt_Blowfish( $key );
+
+ } else {
+
+ return false;
+
+ }
+
+ }
+
+ public static function legacyCreateKey( $passphrase ) {
+
+ // Generate a random integer
+ $key = mt_rand( 10000, 99999 ) . mt_rand( 10000, 99999 ) . mt_rand( 10000, 99999 ) . mt_rand( 10000, 99999 );
+
+ // Encrypt the key with the passphrase
+ $legacyEncKey = self::legacyEncrypt( $key, $passphrase );
+
+ return $legacyEncKey;
+
+ }
+
+ /**
+ * @brief encrypts content using legacy blowfish system
+ * @param $content the cleartext message you want to encrypt
+ * @param $key the encryption key (optional)
+ * @returns encrypted content
+ *
+ * This function encrypts an content
+ */
+ public static function legacyEncrypt( $content, $passphrase = '' ) {
+
+ $bf = self::getBlowfish( $passphrase );
+
+ return $bf->encrypt( $content );
+
+ }
+
+ /**
+ * @brief decrypts content using legacy blowfish system
+ * @param $content the cleartext message you want to decrypt
+ * @param $key the encryption key (optional)
+ * @returns cleartext content
+ *
+ * This function decrypts an content
+ */
+ public static function legacyDecrypt( $content, $passphrase = '' ) {
+
+ $bf = self::getBlowfish( $passphrase );
+
+ $decrypted = $bf->decrypt( $content );
+
+ $trimmed = rtrim( $decrypted, "\0" );
+
+ return $trimmed;
+
+ }
+
+ public static function legacyKeyRecryptKeyfile( $legacyEncryptedContent, $legacyPassphrase, $publicKey, $newPassphrase ) {
+
+ $decrypted = self::legacyDecrypt( $legacyEncryptedContent, $legacyPassphrase );
+
+ $recrypted = self::keyEncryptKeyfile( $decrypted, $publicKey );
+
+ return $recrypted;
+
+ }
+
+ /**
+ * @brief Re-encryptes a legacy blowfish encrypted file using AES with integrated IV
+ * @param $legacyContent the legacy encrypted content to re-encrypt
+ * @returns cleartext content
+ *
+ * This function decrypts an content
+ */
+ public static function legacyRecrypt( $legacyContent, $legacyPassphrase, $newPassphrase ) {
+
+ # TODO: write me
+
+ }
+
+}
+
+?>
\ No newline at end of file diff --git a/apps/files_encryption/lib/cryptstream.php b/apps/files_encryption/lib/cryptstream.php deleted file mode 100644 index 8d5a9ff9990..00000000000 --- a/apps/files_encryption/lib/cryptstream.php +++ /dev/null @@ -1,177 +0,0 @@ -<?php -/** - * ownCloud - * - * @author Robin Appelman - * @copyright 2011 Robin Appelman icewind1991@gmail.com - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE - * License as published by the Free Software Foundation; either - * version 3 of the License, or any later version. - * - * This library 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 along with this library. If not, see <http://www.gnu.org/licenses/>. - * - */ - -/** - * transparently encrypted filestream - * - * you can use it as wrapper around an existing stream by setting - * OC_CryptStream::$sourceStreams['foo']=array('path'=>$path, 'stream'=>$stream) - * and then fopen('crypt://streams/foo'); - */ - -class OC_CryptStream{ - public static $sourceStreams=array(); - private $source; - private $path; - private $meta=array();//header/meta for source stream - private $writeCache; - private $size; - private static $rootView; - - public function stream_open($path, $mode, $options, &$opened_path) { - if (!self::$rootView) { - self::$rootView=new \OC\Files\View(''); - } - $path=str_replace('crypt://', '', $path); - if (dirname($path)=='streams' and isset(self::$sourceStreams[basename($path)])) { - $this->source=self::$sourceStreams[basename($path)]['stream']; - $this->path=self::$sourceStreams[basename($path)]['path']; - $this->size=self::$sourceStreams[basename($path)]['size']; - } else { - $this->path=$path; - if ($mode=='w' or $mode=='w+' or $mode=='wb' or $mode=='wb+') { - $this->size=0; - } else { - $this->size=self::$rootView->filesize($path, $mode); - } - OC_FileProxy::$enabled=false;//disable fileproxies so we can open the source file - $this->source=self::$rootView->fopen($path, $mode); - OC_FileProxy::$enabled=true; - if ( ! is_resource($this->source)) { - OCP\Util::writeLog('files_encryption', 'failed to open '.$path, OCP\Util::ERROR); - } - } - if (is_resource($this->source)) { - $this->meta=stream_get_meta_data($this->source); - } - return is_resource($this->source); - } - - public function stream_seek($offset, $whence=SEEK_SET) { - $this->flush(); - fseek($this->source, $offset, $whence); - } - - public function stream_tell() { - return ftell($this->source); - } - - public function stream_read($count) { - //$count will always be 8192 https://bugs.php.net/bug.php?id=21641 - //This makes this function a lot simpler but will breake everything the moment it's fixed - $this->writeCache=''; - if ($count!=8192) { - OCP\Util::writeLog('files_encryption', - 'php bug 21641 no longer holds, decryption will not work', - OCP\Util::FATAL); - die(); - } - $pos=ftell($this->source); - $data=fread($this->source, 8192); - if (strlen($data)) { - $result=OC_Crypt::decrypt($data); - } else { - $result=''; - } - $length=$this->size-$pos; - if ($length<8192) { - $result=substr($result, 0, $length); - } - return $result; - } - - public function stream_write($data) { - $length=strlen($data); - $currentPos=ftell($this->source); - if ($this->writeCache) { - $data=$this->writeCache.$data; - $this->writeCache=''; - } - if ($currentPos%8192!=0) { - //make sure we always start on a block start - fseek($this->source, -($currentPos%8192), SEEK_CUR); - $encryptedBlock=fread($this->source, 8192); - fseek($this->source, -($currentPos%8192), SEEK_CUR); - $block=OC_Crypt::decrypt($encryptedBlock); - $data=substr($block, 0, $currentPos%8192).$data; - fseek($this->source, -($currentPos%8192), SEEK_CUR); - } - $currentPos=ftell($this->source); - while ($remainingLength=strlen($data)>0) { - if ($remainingLength<8192) { - $this->writeCache=$data; - $data=''; - } else { - $encrypted=OC_Crypt::encrypt(substr($data, 0, 8192)); - fwrite($this->source, $encrypted); - $data=substr($data, 8192); - } - } - $this->size=max($this->size, $currentPos+$length); - return $length; - } - - public function stream_set_option($option, $arg1, $arg2) { - switch($option) { - case STREAM_OPTION_BLOCKING: - stream_set_blocking($this->source, $arg1); - break; - case STREAM_OPTION_READ_TIMEOUT: - stream_set_timeout($this->source, $arg1, $arg2); - break; - case STREAM_OPTION_WRITE_BUFFER: - stream_set_write_buffer($this->source, $arg1, $arg2); - } - } - - public function stream_stat() { - return fstat($this->source); - } - - public function stream_lock($mode) { - flock($this->source, $mode); - } - - public function stream_flush() { - return fflush($this->source); - } - - public function stream_eof() { - return feof($this->source); - } - - private function flush() { - if ($this->writeCache) { - $encrypted=OC_Crypt::encrypt($this->writeCache); - fwrite($this->source, $encrypted); - $this->writeCache=''; - } - } - - public function stream_close() { - $this->flush(); - if($this->meta['mode']!='r' and $this->meta['mode']!='rb') { - \OC\Files\Filesystem::putFileInfo($this->path, array('encrypted' => true, 'size' => $this->size), ''); - } - return fclose($this->source); - } -} diff --git a/apps/files_encryption/lib/keymanager.php b/apps/files_encryption/lib/keymanager.php new file mode 100755 index 00000000000..706e1c2661e --- /dev/null +++ b/apps/files_encryption/lib/keymanager.php @@ -0,0 +1,365 @@ +<?php
+/***
+ * ownCloud
+ *
+ * @author Bjoern Schiessle
+ * @copyright 2012 Bjoern Schiessle <schiessle@owncloud.com>
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
+ * License as published by the Free Software Foundation; either
+ * version 3 of the License, or any later version.
+ *
+ * This library 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 along with this library. If not, see <http://www.gnu.org/licenses/>.
+ *
+ */
+
+namespace OCA\Encryption;
+
+/**
+ * @brief Class to manage storage and retrieval of encryption keys
+ * @note Where a method requires a view object, it's root must be '/'
+ */
+class Keymanager {
+
+ # TODO: make all dependencies (including static classes) explicit, such as ocfsview objects, by adding them as method arguments (dependency injection)
+
+ /**
+ * @brief retrieve the ENCRYPTED private key from a user
+ *
+ * @return string private key or false
+ * @note the key returned by this method must be decrypted before use
+ */
+ public static function getPrivateKey( \OC_FilesystemView $view, $user ) {
+
+ $path = '/' . $user . '/' . 'files_encryption' . '/' . $user.'.private.key';
+
+ $key = $view->file_get_contents( $path );
+
+ return $key;
+ }
+
+ /**
+ * @brief retrieve public key for a specified user
+ * @return string public key or false
+ */
+ public static function getPublicKey( \OC_FilesystemView $view, $userId ) {
+
+ return $view->file_get_contents( '/public-keys/' . '/' . $userId . '.public.key' );
+
+ }
+
+ /**
+ * @brief retrieve both keys from a user (private and public)
+ * @return array keys: privateKey, publicKey
+ */
+ public static function getUserKeys( \OC_FilesystemView $view, $userId ) {
+
+ return array(
+ 'publicKey' => self::getPublicKey( $view, $userId )
+ , 'privateKey' => self::getPrivateKey( $view, $userId )
+ );
+
+ }
+
+ /**
+ * @brief Retrieve public keys of all users with access to a file
+ * @param string $path Path to file
+ * @return array of public keys for the given file
+ * @note Checks that the sharing app is enabled should be performed
+ * by client code, that isn't checked here
+ */
+ public static function getPublicKeys( \OC_FilesystemView $view, $userId, $filePath ) {
+
+ $path = ltrim( $path, '/' );
+
+ $filepath = '/' . $userId . '/files/' . $filePath;
+
+ // Check if sharing is enabled
+ if ( OC_App::isEnabled( 'files_sharing' ) ) {
+
+// // Check if file was shared with other users
+// $query = \OC_DB::prepare( "
+// SELECT
+// uid_owner
+// , source
+// , target
+// , uid_shared_with
+// FROM
+// `*PREFIX*sharing`
+// WHERE
+// ( target = ? AND uid_shared_with = ? )
+// OR source = ?
+// " );
+//
+// $result = $query->execute( array ( $filepath, $userId, $filepath ) );
+//
+// $users = array();
+//
+// if ( $row = $result->fetchRow() )
+// {
+// $source = $row['source'];
+// $owner = $row['uid_owner'];
+// $users[] = $owner;
+// // get the uids of all user with access to the file
+// $query = \OC_DB::prepare( "SELECT source, uid_shared_with FROM `*PREFIX*sharing` WHERE source = ?" );
+// $result = $query->execute( array ($source));
+// while ( ($row = $result->fetchRow()) ) {
+// $users[] = $row['uid_shared_with'];
+//
+// }
+//
+// }
+
+ } else {
+
+ // check if it is a file owned by the user and not shared at all
+ $userview = new \OC_FilesystemView( '/'.$userId.'/files/' );
+
+ if ( $userview->file_exists( $path ) ) {
+
+ $users[] = $userId;
+
+ }
+
+ }
+
+ $view = new \OC_FilesystemView( '/public-keys/' );
+
+ $keylist = array();
+
+ $count = 0;
+
+ foreach ( $users as $user ) {
+
+ $keylist['key'.++$count] = $view->file_get_contents( $user.'.public.key' );
+
+ }
+
+ return $keylist;
+
+ }
+
+ /**
+ * @brief retrieve keyfile for an encrypted file
+ * @param string file name
+ * @return string file key or false
+ * @note The keyfile returned is asymmetrically encrypted. Decryption
+ * of the keyfile must be performed by client code
+ */
+ public static function getFileKey( \OC_FilesystemView $view, $userId, $filePath ) {
+
+ $filePath_f = ltrim( $filePath, '/' );
+
+// // update $keypath and $userId if path point to a file shared by someone else
+// $query = \OC_DB::prepare( "SELECT uid_owner, source, target FROM `*PREFIX*sharing` WHERE target = ? AND uid_shared_with = ?" );
+//
+// $result = $query->execute( array ('/'.$userId.'/files/'.$keypath, $userId));
+//
+// if ($row = $result->fetchRow()) {
+//
+// $keypath = $row['source'];
+// $keypath_parts = explode( '/', $keypath );
+// $userId = $keypath_parts[1];
+// $keypath = str_replace( '/' . $userId . '/files/', '', $keypath );
+//
+// }
+
+ return $view->file_get_contents( '/' . $userId . '/files_encryption/keyfiles/' . $filePath_f . '.key' );
+
+ }
+
+ /**
+ * @brief retrieve file encryption key
+ *
+ * @param string file name
+ * @return string file key or false
+ */
+ public static function deleteFileKey( $path, $staticUserClass = 'OCP\User' ) {
+
+ $keypath = ltrim( $path, '/' );
+ $user = $staticUserClass::getUser();
+
+ // update $keypath and $user if path point to a file shared by someone else
+// $query = \OC_DB::prepare( "SELECT uid_owner, source, target FROM `*PREFIX*sharing` WHERE target = ? AND uid_shared_with = ?" );
+//
+// $result = $query->execute( array ('/'.$user.'/files/'.$keypath, $user));
+//
+// if ($row = $result->fetchRow()) {
+//
+// $keypath = $row['source'];
+// $keypath_parts = explode( '/', $keypath );
+// $user = $keypath_parts[1];
+// $keypath = str_replace( '/' . $user . '/files/', '', $keypath );
+//
+// }
+
+ $view = new \OC_FilesystemView('/'.$user.'/files_encryption/keyfiles/');
+
+ return $view->unlink( $keypath . '.key' );
+
+ }
+
+ /**
+ * @brief store private key from the user
+ * @param string key
+ * @return bool
+ * @note Encryption of the private key must be performed by client code
+ * as no encryption takes place here
+ */
+ public static function setPrivateKey( $key ) {
+
+ $user = \OCP\User::getUser();
+
+ $view = new \OC_FilesystemView( '/' . $user . '/files_encryption' );
+
+ \OC_FileProxy::$enabled = false;
+
+ if ( !$view->file_exists( '' ) ) $view->mkdir( '' );
+
+ return $view->file_put_contents( $user . '.private.key', $key );
+
+ \OC_FileProxy::$enabled = true;
+
+ }
+
+ /**
+ * @brief store private keys from the user
+ *
+ * @param string privatekey
+ * @param string publickey
+ * @return bool true/false
+ */
+ public static function setUserKeys($privatekey, $publickey) {
+
+ return (self::setPrivateKey($privatekey) && self::setPublicKey($publickey));
+
+ }
+
+ /**
+ * @brief store public key of the user
+ *
+ * @param string key
+ * @return bool true/false
+ */
+ public static function setPublicKey( $key ) {
+
+ $view = new \OC_FilesystemView( '/public-keys' );
+
+ \OC_FileProxy::$enabled = false;
+
+ if ( !$view->file_exists( '' ) ) $view->mkdir( '' );
+
+ return $view->file_put_contents( \OCP\User::getUser() . '.public.key', $key );
+
+ \OC_FileProxy::$enabled = true;
+
+ }
+
+ /**
+ * @brief store file encryption key
+ *
+ * @param string $path relative path of the file, including filename
+ * @param string $key
+ * @return bool true/false
+ * @note The keyfile is not encrypted here. Client code must
+ * asymmetrically encrypt the keyfile before passing it to this method
+ */
+ public static function setFileKey( $path, $key, $view = Null, $dbClassName = '\OC_DB') {
+
+ $targetPath = ltrim( $path, '/' );
+ $user = \OCP\User::getUser();
+
+// // update $keytarget and $user if key belongs to a file shared by someone else
+// $query = $dbClassName::prepare( "SELECT uid_owner, source, target FROM `*PREFIX*sharing` WHERE target = ? AND uid_shared_with = ?" );
+//
+// $result = $query->execute( array ( '/'.$user.'/files/'.$targetPath, $user ) );
+//
+// if ( $row = $result->fetchRow( ) ) {
+//
+// $targetPath = $row['source'];
+//
+// $targetPath_parts = explode( '/', $targetPath );
+//
+// $user = $targetPath_parts[1];
+//
+// $rootview = new \OC_FilesystemView( '/' );
+//
+// if ( ! $rootview->is_writable( $targetPath ) ) {
+//
+// \OC_Log::write( 'Encryption library', "File Key not updated because you don't have write access for the corresponding file", \OC_Log::ERROR );
+//
+// return false;
+//
+// }
+//
+// $targetPath = str_replace( '/'.$user.'/files/', '', $targetPath );
+//
+// //TODO: check for write permission on shared file once the new sharing API is in place
+//
+// }
+
+ $path_parts = pathinfo( $targetPath );
+
+ if ( !$view ) {
+
+ $view = new \OC_FilesystemView( '/' );
+
+ }
+
+ $view->chroot( '/' . $user . '/files_encryption/keyfiles' );
+
+ // If the file resides within a subdirectory, create it
+ if (
+ isset( $path_parts['dirname'] )
+ && ! $view->file_exists( $path_parts['dirname'] )
+ ) {
+
+ $view->mkdir( $path_parts['dirname'] );
+
+ }
+
+ // Save the keyfile in parallel directory
+ return $view->file_put_contents( '/' . $targetPath . '.key', $key );
+
+ }
+
+ /**
+ * @brief change password of private encryption key
+ *
+ * @param string $oldpasswd old password
+ * @param string $newpasswd new password
+ * @return bool true/false
+ */
+ public static function changePasswd($oldpasswd, $newpasswd) {
+
+ if ( \OCP\User::checkPassword(\OCP\User::getUser(), $newpasswd) ) {
+ return Crypt::changekeypasscode($oldpasswd, $newpasswd);
+ }
+ return false;
+
+ }
+
+ /**
+ * @brief Fetch the legacy encryption key from user files
+ * @param string $login used to locate the legacy key
+ * @param string $passphrase used to decrypt the legacy key
+ * @return true / false
+ *
+ * if the key is left out, the default handeler will be used
+ */
+ public function getLegacyKey() {
+
+ $user = \OCP\User::getUser();
+ $view = new \OC_FilesystemView( '/' . $user );
+ return $view->file_get_contents( 'encryption.key' );
+
+ }
+
+}
\ No newline at end of file diff --git a/apps/files_encryption/lib/proxy.php b/apps/files_encryption/lib/proxy.php index ffee394047c..52f47dba294 100644 --- a/apps/files_encryption/lib/proxy.php +++ b/apps/files_encryption/lib/proxy.php @@ -3,8 +3,9 @@ /** * ownCloud * -* @author Robin Appelman -* @copyright 2011 Robin Appelman icewind1991@gmail.com +* @author Sam Tuke, Robin Appelman +* @copyright 2012 Sam Tuke samtuke@owncloud.com, Robin Appelman +* icewind1991@gmail.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE @@ -21,116 +22,267 @@ * */ -/** - * transparent encryption - */ +namespace OCA\Encryption; -class OC_FileProxy_Encryption extends OC_FileProxy{ - private static $blackList=null; //mimetypes blacklisted from encryption - private static $enableEncryption=null; +class Proxy extends \OC_FileProxy { + private static $blackList = null; //mimetypes blacklisted from encryption + + private static $enableEncryption = null; + /** - * check if a file should be encrypted during write + * Check if a file requires encryption * @param string $path * @return bool + * + * Tests if server side encryption is enabled, and file is allowed by blacklists */ - private static function shouldEncrypt($path) { - if (is_null(self::$enableEncryption)) { - self::$enableEncryption=(OCP\Config::getAppValue('files_encryption', 'enable_encryption', 'true')=='true'); + private static function shouldEncrypt( $path ) { + + if ( is_null( self::$enableEncryption ) ) { + + if ( + \OCP\Config::getAppValue( 'files_encryption', 'enable_encryption', 'true' ) == 'true' + && Crypt::mode() == 'server' + ) { + + self::$enableEncryption = true; + + } else { + + self::$enableEncryption = false; + + } + } - if ( ! self::$enableEncryption) { + + if ( !self::$enableEncryption ) { + return false; + } - if (is_null(self::$blackList)) { - self::$blackList=explode(',', OCP\Config::getAppValue('files_encryption', - 'type_blacklist', - 'jpg,png,jpeg,avi,mpg,mpeg,mkv,mp3,oga,ogv,ogg')); + + if ( is_null(self::$blackList ) ) { + + self::$blackList = explode(',', \OCP\Config::getAppValue( 'files_encryption','type_blacklist','jpg,png,jpeg,avi,mpg,mpeg,mkv,mp3,oga,ogv,ogg' ) ); + } - if (self::isEncrypted($path)) { + + if ( Crypt::isEncryptedContent( $path ) ) { + return true; + } - $extension=substr($path, strrpos($path, '.')+1); - if (array_search($extension, self::$blackList)===false) { + + $extension = substr( $path, strrpos( $path,'.' ) +1 ); + + if ( array_search( $extension, self::$blackList ) === false ){ + return true; + } + + return false; } - - /** - * check if a file is encrypted - * @param string $path - * @return bool - */ - private static function isEncrypted($path) { - $rootView = new \OC\Files\View(''); - $metadata=$rootView->getFileInfo($path); - return isset($metadata['encrypted']) and (bool)$metadata['encrypted']; - } - - public function preFile_put_contents($path,&$data) { - if (self::shouldEncrypt($path)) { - if ( ! is_resource($data)) {//stream put contents should have been converter to fopen - $size=strlen($data); - $rootView = new \OC\Files\View(''); - $data=OC_Crypt::blockEncrypt($data); - $rootView->putFileInfo($path, array('encrypted'=>true,'size'=>$size)); + + public function preFile_put_contents( $path, &$data ) { + + if ( self::shouldEncrypt( $path ) ) { + + if ( !is_resource( $data ) ) { //stream put contents should have been converted to fopen + + $userId = \OCP\USER::getUser(); + + $rootView = new \OC_FilesystemView( '/' ); + + // Set the filesize for userland, before encrypting + $size = strlen( $data ); + + // Disable encryption proxy to prevent recursive calls + \OC_FileProxy::$enabled = false; + + // Encrypt plain data and fetch key + $encrypted = Crypt::keyEncryptKeyfile( $data, Keymanager::getPublicKey( $rootView, $userId ) ); + + // Replace plain content with encrypted content by reference + $data = $encrypted['data']; + + $filePath = explode( '/', $path ); + + $filePath = array_slice( $filePath, 3 ); + + $filePath = '/' . implode( '/', $filePath ); + + # TODO: make keyfile dir dynamic from app config + $view = new \OC_FilesystemView( '/' . $userId . '/files_encryption/keyfiles' ); + + // Save keyfile for newly encrypted file in parallel directory tree + Keymanager::setFileKey( $filePath, $encrypted['key'], $view, '\OC_DB' ); + + // Update the file cache with file info + \OC_FileCache::put( $path, array( 'encrypted'=>true, 'size' => $size ), '' ); + + // Re-enable proxy - our work is done + \OC_FileProxy::$enabled = true; + } } + } + + /** + * @param string $path Path of file from which has been read + * @param string $data Data that has been read from file + */ + public function postFile_get_contents( $path, $data ) { + + # TODO: Use dependency injection to add required args for view and user etc. to this method + + // Disable encryption proxy to prevent recursive calls + \OC_FileProxy::$enabled = false; + + // If data is a catfile + if ( + Crypt::mode() == 'server' + && Crypt::isEncryptedContent( $data ) + ) { + + $split = explode( '/', $path ); + + $filePath = array_slice( $split, 3 ); + + $filePath = '/' . implode( '/', $filePath ); + + //$cached = \OC_FileCache_Cached::get( $path, '' ); + + $view = new \OC_FilesystemView( '' ); + + $userId = \OCP\USER::getUser(); + + $encryptedKeyfile = Keymanager::getFileKey( $view, $userId, $filePath ); - public function postFile_get_contents($path, $data) { - if(self::isEncrypted($path)) { - $rootView = new \OC\Files\View(''); - $cached=$rootView->getFileInfo($path, ''); - $data=OC_Crypt::blockDecrypt($data, '', $cached['size']); + $session = new Session(); + + $decrypted = Crypt::keyDecryptKeyfile( $data, $encryptedKeyfile, $session->getPrivateKey( $split[1] ) ); + + } elseif ( + Crypt::mode() == 'server' + && isset( $_SESSION['legacyenckey'] ) + && Crypt::isEncryptedMeta( $path ) + ) { + + $decrypted = Crypt::legacyDecrypt( $data, $_SESSION['legacyenckey'] ); + } - return $data; + + \OC_FileProxy::$enabled = true; + + if ( ! isset( $decrypted ) ) { + + $decrypted = $data; + + } + + return $decrypted; + } - - public function postFopen($path,&$result) { - if ( ! $result) { + + public function postFopen( $path, &$result ){ + + if ( !$result ) { + return $result; + } - $meta=stream_get_meta_data($result); - if (self::isEncrypted($path)) { - fclose($result); - $result=fopen('crypt://'.$path, $meta['mode']); - }elseif(self::shouldEncrypt($path) and $meta['mode']!='r' and $meta['mode']!='rb') { - if(\OC\Files\Filesystem::file_exists($path) and \OC\Files\Filesystem::filesize($path)>0) { - //first encrypt the target file so we don't end up with a half encrypted file - OCP\Util::writeLog('files_encryption','Decrypting '.$path.' before writing', OCP\Util::DEBUG); - $tmp=fopen('php://temp'); - OCP\Files::streamCopy($result, $tmp); - fclose($result); - \OC\Files\Filesystem::file_put_contents($path, $tmp); - fclose($tmp); + + // Reformat path for use with OC_FSV + $path_split = explode( '/', $path ); + $path_f = implode( array_slice( $path_split, 3 ) ); + + // Disable encryption proxy to prevent recursive calls + \OC_FileProxy::$enabled = false; + + $meta = stream_get_meta_data( $result ); + + $view = new \OC_FilesystemView( '' ); + + $util = new Util( $view, \OCP\USER::getUser()); + + // If file is already encrypted, decrypt using crypto protocol + if ( + Crypt::mode() == 'server' + && $util->isEncryptedPath( $path ) + ) { + + // Close the original encrypted file + fclose( $result ); + + // Open the file using the crypto stream wrapper + // protocol and let it do the decryption work instead + $result = fopen( 'crypt://' . $path_f, $meta['mode'] ); + + + } elseif ( + self::shouldEncrypt( $path ) + and $meta ['mode'] != 'r' + and $meta['mode'] != 'rb' + ) { + // If the file is not yet encrypted, but should be + // encrypted when it's saved (it's not read only) + + // NOTE: this is the case for new files saved via WebDAV + + if ( + $view->file_exists( $path ) + and $view->filesize( $path ) > 0 + ) { + $x = $view->file_get_contents( $path ); + + $tmp = tmpfile(); + +// // Make a temporary copy of the original file +// \OCP\Files::streamCopy( $result, $tmp ); +// +// // Close the original stream, we'll return another one +// fclose( $result ); +// +// $view->file_put_contents( $path_f, $tmp ); +// +// fclose( $tmp ); + } - $result=fopen('crypt://'.$path, $meta['mode']); + + $result = fopen( 'crypt://'.$path_f, $meta['mode'] ); + } + + // Re-enable the proxy + \OC_FileProxy::$enabled = true; + return $result; + } - public function postGetMimeType($path, $mime) { - if (self::isEncrypted($path)) { - $mime=OCP\Files::getMimeType('crypt://'.$path, 'w'); + public function postGetMimeType($path,$mime){ + if( Crypt::isEncryptedContent($path)){ + $mime = \OCP\Files::getMimeType('crypt://'.$path,'w'); } return $mime; } - public function postStat($path, $data) { - if(self::isEncrypted($path)) { - $rootView = new \OC\Files\View(''); - $cached=$rootView->getFileInfo($path); + public function postStat($path,$data){ + if( Crypt::isEncryptedContent($path)){ + $cached= \OC_FileCache_Cached::get($path,''); $data['size']=$cached['size']; } return $data; } - public function postFileSize($path, $size) { - if(self::isEncrypted($path)) { - $rootView = new \OC\Files\View(''); - $cached=$rootView->getFileInfo($path); + public function postFileSize($path,$size){ + if( Crypt::isEncryptedContent($path)){ + $cached = \OC_FileCache_Cached::get($path,''); return $cached['size']; - } else { + }else{ return $size; } } diff --git a/apps/files_encryption/lib/session.php b/apps/files_encryption/lib/session.php new file mode 100644 index 00000000000..85d533fde7a --- /dev/null +++ b/apps/files_encryption/lib/session.php @@ -0,0 +1,66 @@ +<?php +/** + * ownCloud + * + * @author Sam Tuke + * @copyright 2012 Sam Tuke samtuke@owncloud.com + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library 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 along with this library. If not, see <http://www.gnu.org/licenses/>. + * + */ + +namespace OCA\Encryption; + +/** + * Class for handling encryption related session data + */ + +class Session { + + /** + * @brief Sets user id for session and triggers emit + * @return bool + * + */ + public function setPrivateKey( $privateKey, $userId ) { + + $_SESSION['privateKey'] = $privateKey; + + return true; + + } + + /** + * @brief Gets user id for session and triggers emit + * @returns string $privateKey The user's plaintext private key + * + */ + public function getPrivateKey( $userId ) { + + if ( + isset( $_SESSION['privateKey'] ) + && !empty( $_SESSION['privateKey'] ) + ) { + + return $_SESSION['privateKey']; + + } else { + + return false; + + } + + } + +}
\ No newline at end of file diff --git a/apps/files_encryption/lib/stream.php b/apps/files_encryption/lib/stream.php new file mode 100644 index 00000000000..f482e2d75ac --- /dev/null +++ b/apps/files_encryption/lib/stream.php @@ -0,0 +1,464 @@ +<?php +/** + * ownCloud + * + * @author Robin Appelman + * @copyright 2012 Sam Tuke <samtuke@owncloud.com>, 2011 Robin Appelman + * <icewind1991@gmail.com> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library 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 along with this library. If not, see <http://www.gnu.org/licenses/>. + * + */ + +/** + * transparently encrypted filestream + * + * you can use it as wrapper around an existing stream by setting CryptStream::$sourceStreams['foo']=array('path'=>$path,'stream'=>$stream) + * and then fopen('crypt://streams/foo'); + */ + +namespace OCA\Encryption; + +/** + * @brief Provides 'crypt://' stream wrapper protocol. + * @note We use a stream wrapper because it is the most secure way to handle + * decrypted content transfers. There is no safe way to decrypt the entire file + * somewhere on the server, so we have to encrypt and decrypt blocks on the fly. + * @note Paths used with this protocol MUST BE RELATIVE. Use URLs like: + * crypt://filename, or crypt://subdirectory/filename, NOT + * crypt:///home/user/owncloud/data. Otherwise keyfiles will be put in + * [owncloud]/data/user/files_encryption/keyfiles/home/user/owncloud/data and + * will not be accessible to other methods. + * @note Data read and written must always be 8192 bytes long, as this is the + * buffer size used internally by PHP. The encryption process makes the input + * data longer, and input is chunked into smaller pieces in order to result in + * a 8192 encrypted block size. + */ +class Stream { + + public static $sourceStreams = array(); + + # TODO: make all below properties private again once unit testing is configured correctly + public $rawPath; // The raw path received by stream_open + public $path_f; // The raw path formatted to include username and data directory + private $userId; + private $handle; // Resource returned by fopen + private $path; + private $readBuffer; // For streams that dont support seeking + private $meta = array(); // Header / meta for source stream + private $count; + private $writeCache; + public $size; + private $publicKey; + private $keyfile; + private $encKeyfile; + private static $view; // a fsview object set to user dir + private $rootView; // a fsview object set to '/' + + public function stream_open( $path, $mode, $options, &$opened_path ) { + + // Get access to filesystem via filesystemview object + if ( !self::$view ) { + + self::$view = new \OC_FilesystemView( $this->userId . '/' ); + + } + + // Set rootview object if necessary + if ( ! $this->rootView ) { + + $this->rootView = new \OC_FilesystemView( $this->userId . '/' ); + + } + + $this->userId = \OCP\User::getUser(); + + // Get the bare file path + $path = str_replace( 'crypt://', '', $path ); + + $this->rawPath = $path; + + $this->path_f = $this->userId . '/files/' . $path; + + if ( + dirname( $path ) == 'streams' + and isset( self::$sourceStreams[basename( $path )] ) + ) { + + // Is this just for unit testing purposes? + + $this->handle = self::$sourceStreams[basename( $path )]['stream']; + + $this->path = self::$sourceStreams[basename( $path )]['path']; + + $this->size = self::$sourceStreams[basename( $path )]['size']; + + } else { + + if ( + $mode == 'w' + or $mode == 'w+' + or $mode == 'wb' + or $mode == 'wb+' + ) { + + $this->size = 0; + + } else { + + + + $this->size = self::$view->filesize( $this->path_f, $mode ); + + //$this->size = filesize( $path ); + + } + + // Disable fileproxies so we can open the source file without recursive encryption + \OC_FileProxy::$enabled = false; + + //$this->handle = fopen( $path, $mode ); + + $this->handle = self::$view->fopen( $this->path_f, $mode ); + + \OC_FileProxy::$enabled = true; + + if ( !is_resource( $this->handle ) ) { + + \OCP\Util::writeLog( 'files_encryption', 'failed to open '.$path, \OCP\Util::ERROR ); + + } + + } + + if ( is_resource( $this->handle ) ) { + + $this->meta = stream_get_meta_data( $this->handle ); + + } + + return is_resource( $this->handle ); + + } + + public function stream_seek( $offset, $whence = SEEK_SET ) { + + $this->flush(); + + fseek( $this->handle, $offset, $whence ); + + } + + public function stream_tell() { + return ftell($this->handle); + } + + public function stream_read( $count ) { + + $this->writeCache = ''; + + if ( $count != 8192 ) { + + // $count will always be 8192 https://bugs.php.net/bug.php?id=21641 + // This makes this function a lot simpler, but will break this class if the above 'bug' gets 'fixed' + \OCP\Util::writeLog( 'files_encryption', 'PHP "bug" 21641 no longer holds, decryption system requires refactoring', OCP\Util::FATAL ); + + die(); + + } + +// $pos = ftell( $this->handle ); +// + // Get the data from the file handle + $data = fread( $this->handle, 8192 ); + + if ( strlen( $data ) ) { + + $this->getKey(); + + $result = Crypt::symmetricDecryptFileContent( $data, $this->keyfile ); + + } else { + + $result = ''; + + } + +// $length = $this->size - $pos; +// +// if ( $length < 8192 ) { +// +// $result = substr( $result, 0, $length ); +// +// } + + return $result; + + } + + /** + * @brief Encrypt and pad data ready for writting to disk + * @param string $plainData data to be encrypted + * @param string $key key to use for encryption + * @return encrypted data on success, false on failure + */ + public function preWriteEncrypt( $plainData, $key ) { + + // Encrypt data to 'catfile', which includes IV + if ( $encrypted = Crypt::symmetricEncryptFileContent( $plainData, $key ) ) { + + return $encrypted; + + } else { + + return false; + + } + + } + + /** + * @brief Get the keyfile for the current file, generate one if necessary + * @param bool $generate if true, a new key will be generated if none can be found + * @return bool true on key found and set, false on key not found and new key generated and set + */ + public function getKey() { + + // If a keyfile already exists for a file named identically to file to be written + if ( self::$view->file_exists( $this->userId . '/'. 'files_encryption' . '/' . 'keyfiles' . '/' . $this->rawPath . '.key' ) ) { + + # TODO: add error handling for when file exists but no keyfile + + // Fetch existing keyfile + $this->encKeyfile = Keymanager::getFileKey( $this->rootView, $this->userId, $this->rawPath ); + + $this->getUser(); + + $session = new Session(); + + $privateKey = $session->getPrivateKey( $this->userId ); + + $this->keyfile = Crypt::keyDecrypt( $this->encKeyfile, $privateKey ); + + return true; + + } else { + + return false; + + } + + } + + public function getuser() { + + // Only get the user again if it isn't already set + if ( empty( $this->userId ) ) { + + # TODO: Move this user call out of here - it belongs elsewhere + $this->userId = \OCP\User::getUser(); + + } + + # TODO: Add a method for getting the user in case OCP\User:: + # getUser() doesn't work (can that scenario ever occur?) + + } + + /** + * @brief Handle plain data from the stream, and write it in 8192 byte blocks + * @param string $data data to be written to disk + * @note the data will be written to the path stored in the stream handle, set in stream_open() + * @note $data is only ever be a maximum of 8192 bytes long. This is set by PHP internally. stream_write() is called multiple times in a loop on data larger than 8192 bytes + * @note Because the encryption process used increases the length of $data, a writeCache is used to carry over data which would not fit in the required block size + * @note Padding is added to each encrypted block to ensure that the resulting block is exactly 8192 bytes. This is removed during stream_read + * @note PHP automatically updates the file pointer after writing data to reflect it's length. There is generally no need to update the poitner manually using fseek + */ + public function stream_write( $data ) { + + // Disable the file proxies so that encryption is not automatically attempted when the file is written to disk - we are handling that separately here and we don't want to get into an infinite loop + \OC_FileProxy::$enabled = false; + + // Get the length of the unencrypted data that we are handling + $length = strlen( $data ); + + // So far this round, no data has been written + $written = 0; + + // Find out where we are up to in the writing of data to the file + $pointer = ftell( $this->handle ); + + // Make sure the userId is set + $this->getuser(); + + // Get / generate the keyfile for the file we're handling + // If we're writing a new file (not overwriting an existing one), save the newly generated keyfile + if ( ! $this->getKey() ) { + + $this->keyfile = Crypt::generateKey(); + + $this->publicKey = Keymanager::getPublicKey( $this->rootView, $this->userId ); + + $this->encKeyfile = Crypt::keyEncrypt( $this->keyfile, $this->publicKey ); + + // Save the new encrypted file key + Keymanager::setFileKey( $this->rawPath, $this->encKeyfile, new \OC_FilesystemView( '/' ) ); + + # TODO: move this new OCFSV out of here some how, use DI + + } + + // If extra data is left over from the last round, make sure it is integrated into the next 6126 / 8192 block + if ( $this->writeCache ) { + + // Concat writeCache to start of $data + $data = $this->writeCache . $data; + + // Clear the write cache, ready for resuse - it has been flushed and its old contents processed + $this->writeCache = ''; + + } +// +// // Make sure we always start on a block start + if ( 0 != ( $pointer % 8192 ) ) { // if the current positoin of file indicator is not aligned to a 8192 byte block, fix it so that it is + +// fseek( $this->handle, - ( $pointer % 8192 ), SEEK_CUR ); +// +// $pointer = ftell( $this->handle ); +// +// $unencryptedNewBlock = fread( $this->handle, 8192 ); +// +// fseek( $this->handle, - ( $currentPos % 8192 ), SEEK_CUR ); +// +// $block = Crypt::symmetricDecryptFileContent( $unencryptedNewBlock, $this->keyfile ); +// +// $x = substr( $block, 0, $currentPos % 8192 ); +// +// $data = $x . $data; +// +// fseek( $this->handle, - ( $currentPos % 8192 ), SEEK_CUR ); +// + } + +// $currentPos = ftell( $this->handle ); + +// // While there still remains somed 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 ( strlen( $data ) < 6126 ) { + + // 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, 6126 ); + + $encrypted = $this->preWriteEncrypt( $chunk, $this->keyfile ); + + // Write the data chunk to disk. This will be addended to the last data chunk if the file being handled totals more than 6126 bytes + fwrite( $this->handle, $encrypted ); + + $writtenLen = strlen( $encrypted ); + //fseek( $this->handle, $writtenLen, SEEK_CUR ); + + // Remove the chunk we just processed from $data, leaving only unprocessed data in $data var, for handling on the next round + $data = substr( $data, 6126 ); + + } + + } + + $this->size = max( $this->size, $pointer + $length ); + + return $length; + + } + + + public function stream_set_option($option,$arg1,$arg2) { + switch($option) { + case STREAM_OPTION_BLOCKING: + stream_set_blocking($this->handle,$arg1); + break; + case STREAM_OPTION_READ_TIMEOUT: + stream_set_timeout($this->handle,$arg1,$arg2); + break; + case STREAM_OPTION_WRITE_BUFFER: + stream_set_write_buffer($this->handle,$arg1,$arg2); + } + } + + public function stream_stat() { + return fstat($this->handle); + } + + public function stream_lock($mode) { + flock($this->handle,$mode); + } + + public function stream_flush() { + + return fflush($this->handle); // Not a typo: http://php.net/manual/en/function.fflush.php + + } + + public function stream_eof() { + return feof($this->handle); + } + + private function flush() { + + if ( $this->writeCache ) { + + // Set keyfile property for file in question + $this->getKey(); + + $encrypted = $this->preWriteEncrypt( $this->writeCache, $this->keyfile ); + + fwrite( $this->handle, $encrypted ); + + $this->writeCache = ''; + + } + + } + + public function stream_close() { + + $this->flush(); + + if ( + $this->meta['mode']!='r' + and $this->meta['mode']!='rb' + ) { + + \OC_FileCache::put( $this->path, array( 'encrypted' => true, 'size' => $this->size ), '' ); + + } + + return fclose( $this->handle ); + + } + +} diff --git a/apps/files_encryption/lib/util.php b/apps/files_encryption/lib/util.php new file mode 100644 index 00000000000..cd46d23108a --- /dev/null +++ b/apps/files_encryption/lib/util.php @@ -0,0 +1,330 @@ +<?php +/** + * ownCloud + * + * @author Sam Tuke, Frank Karlitschek + * @copyright 2012 Sam Tuke samtuke@owncloud.com, + * Frank Karlitschek frank@owncloud.org + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE + * License as published by the Free Software Foundation; either + * version 3 of the License, or any later version. + * + * This library 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 along with this library. If not, see <http://www.gnu.org/licenses/>. + * + */ + +// Todo: +// - Crypt/decrypt button in the userinterface +// - Setting if crypto should be on by default +// - Add a setting "DonĀ“t encrypt files larger than xx because of performance reasons" +// - Transparent decrypt/encrypt in filesystem.php. Autodetect if a file is encrypted (.encrypted extension) +// - Don't use a password directly as encryption key. but a key which is stored on the server and encrypted with the user password. -> password change faster +// - IMPORTANT! Check if the block lenght of the encrypted data stays the same + +namespace OCA\Encryption; + +/** + * @brief Class for utilities relating to encrypted file storage system + * @param $view OC_FilesystemView object, expected to have OC '/' as root path + * @param $client flag indicating status of client side encryption. Currently + * unused, likely to become obsolete shortly + */ + +class Util { + + + # Web UI: + + ## DONE: files created via web ui are encrypted + ## DONE: file created & encrypted via web ui are readable in web ui + ## DONE: file created & encrypted via web ui are readable via webdav + + + # WebDAV: + + ## DONE: new data filled files added via webdav get encrypted + ## DONE: new data filled files added via webdav are readable via webdav + ## DONE: reading unencrypted files when encryption is enabled works via webdav + ## DONE: files created & encrypted via web ui are readable via webdav + + + # Legacy support: + + ## DONE: add method to check if file is encrypted using new system + ## DONE: add method to check if file is encrypted using old system + ## DONE: add method to fetch legacy key + ## DONE: add method to decrypt legacy encrypted data + + ## TODO: add method to encrypt all user files using new system + ## TODO: add method to decrypt all user files using new system + ## TODO: add method to encrypt all user files using old system + ## TODO: add method to decrypt all user files using old system + + + # Admin UI: + + ## DONE: changing user password also changes encryption passphrase + + ## TODO: add support for optional recovery in case of lost passphrase / keys + ## TODO: add admin optional required long passphrase for users + ## TODO: add UI buttons for encrypt / decrypt everything + ## TODO: implement flag system to allow user to specify encryption by folder, subfolder, etc. + + + # Sharing: + + ## TODO: add support for encrypting to multiple public keys + ## TODO: add support for decrypting to multiple private keys + + + # Integration testing: + + ## TODO: test new encryption with webdav + ## TODO: test new encryption with versioning + ## TODO: test new encryption with sharing + ## TODO: test new encryption with proxies + + + private $view; // OC_FilesystemView object for filesystem operations + private $pwd; // User Password + private $client; // Client side encryption mode flag + private $publicKeyDir; // Directory containing all public user keys + private $encryptionDir; // Directory containing user's files_encryption + private $keyfilesPath; // Directory containing user's keyfiles + private $publicKeyPath; // Path to user's public key + private $privateKeyPath; // Path to user's private key + + public function __construct( \OC_FilesystemView $view, $userId, $client = false ) { + + $this->view = $view; + $this->userId = $userId; + $this->client = $client; + $this->publicKeyDir = '/' . 'public-keys'; + $this->encryptionDir = '/' . $this->userId . '/' . 'files_encryption'; + $this->keyfilesPath = $this->encryptionDir . '/' . 'keyfiles'; + $this->publicKeyPath = $this->publicKeyDir . '/' . $this->userId . '.public.key'; // e.g. data/public-keys/admin.public.key + $this->privateKeyPath = $this->encryptionDir . '/' . $this->userId . '.private.key'; // e.g. data/admin/admin.private.key + + } + + public function ready() { + + if( + !$this->view->file_exists( $this->keyfilesPath ) + or !$this->view->file_exists( $this->publicKeyPath ) + or !$this->view->file_exists( $this->privateKeyPath ) + ) { + + return false; + + } else { + + return true; + + } + + } + + /** + * @brief Sets up user folders and keys for serverside encryption + * @param $passphrase passphrase to encrypt server-stored private key with + */ + public function setupServerSide( $passphrase = null ) { + + // Create shared public key directory + if( !$this->view->file_exists( $this->publicKeyDir ) ) { + + $this->view->mkdir( $this->publicKeyDir ); + + } + + // Create encryption app directory + if( !$this->view->file_exists( $this->encryptionDir ) ) { + + $this->view->mkdir( $this->encryptionDir ); + + } + + // Create mirrored keyfile directory + if( !$this->view->file_exists( $this->keyfilesPath ) ) { + + $this->view->mkdir( $this->keyfilesPath ); + + } + + // Create user keypair + if ( + !$this->view->file_exists( $this->publicKeyPath ) + or !$this->view->file_exists( $this->privateKeyPath ) + ) { + + // Generate keypair + $keypair = Crypt::createKeypair(); + + \OC_FileProxy::$enabled = false; + + // Save public key + $this->view->file_put_contents( $this->publicKeyPath, $keypair['publicKey'] ); + + // Encrypt private key with user pwd as passphrase + $encryptedPrivateKey = Crypt::symmetricEncryptFileContent( $keypair['privateKey'], $passphrase ); + + // Save private key + $this->view->file_put_contents( $this->privateKeyPath, $encryptedPrivateKey ); + + \OC_FileProxy::$enabled = true; + + } + + return true; + + } + + public function findFiles( $directory, $type = 'plain' ) { + + # TODO: test finding non plain content + + if ( $handle = $this->view->opendir( $directory ) ) { + + while ( false !== ( $file = readdir( $handle ) ) ) { + + if ( + $file != "." + && $file != ".." + ) { + + $filePath = $directory . '/' . $this->view->getRelativePath( '/' . $file ); + + var_dump($filePath); + + if ( $this->view->is_dir( $filePath ) ) { + + $this->findFiles( $filePath ); + + } elseif ( $this->view->is_file( $filePath ) ) { + + if ( $type == 'plain' ) { + + $this->files[] = array( 'name' => $file, 'path' => $filePath ); + + } elseif ( $type == 'encrypted' ) { + + if ( Crypt::isEncryptedContent( $this->view->file_get_contents( $filePath ) ) ) { + + $this->files[] = array( 'name' => $file, 'path' => $filePath ); + + } + + } elseif ( $type == 'legacy' ) { + + if ( Crypt::isLegacyEncryptedContent( $this->view->file_get_contents( $filePath ) ) ) { + + $this->files[] = array( 'name' => $file, 'path' => $filePath ); + + } + + } + + } + + } + + } + + if ( !empty( $this->files ) ) { + + return $this->files; + + } else { + + return false; + + } + + } + + return false; + + } + + /** + * @brief Check if a given path identifies an encrypted file + * @return true / false + */ + public function isEncryptedPath( $path ) { + + // Disable encryption proxy so data retreived is in its + // original form + \OC_FileProxy::$enabled = false; + + $data = $this->view->file_get_contents( $path ); + + \OC_FileProxy::$enabled = true; + + return Crypt::isEncryptedContent( $data ); + + } + + public function encryptAll( $directory ) { + + $plainFiles = $this->findFiles( $this->view, 'plain' ); + + if ( $this->encryptFiles( $plainFiles ) ) { + + return true; + + } else { + + return false; + + } + + } + + public function getPath( $pathName ) { + + switch ( $pathName ) { + + case 'publicKeyDir': + + return $this->publicKeyDir; + + break; + + case 'encryptionDir': + + return $this->encryptionDir; + + break; + + case 'keyfilesPath': + + return $this->keyfilesPath; + + break; + + case 'publicKeyPath': + + return $this->publicKeyPath; + + break; + + case 'privateKeyPath': + + return $this->privateKeyPath; + + break; + + } + + } + +} |