diff options
author | Sam Tuke <samtuke@owncloud.com> | 2013-02-05 18:43:55 +0000 |
---|---|---|
committer | Sam Tuke <samtuke@owncloud.com> | 2013-02-05 18:43:55 +0000 |
commit | 3b9e2f1babd578312377f846b2da4d30b550c37f (patch) | |
tree | 6f965d04be8ac4a30f029c08aa7f147f1d0fb449 /apps/files_encryption | |
parent | a528f96b842e387f153e4f38d87aebd26ccd39b7 (diff) | |
parent | e6400b305987977d867f1592f3231167903b70b1 (diff) | |
download | nextcloud-server-3b9e2f1babd578312377f846b2da4d30b550c37f.tar.gz nextcloud-server-3b9e2f1babd578312377f846b2da4d30b550c37f.zip |
Merge branch 'master' into files_encryption-style-fixes
Conflicts:
apps/files_encryption/lib/crypt.php
apps/files_encryption/lib/keymanager.php
Diffstat (limited to 'apps/files_encryption')
-rw-r--r-- | apps/files_encryption/appinfo/app.php | 25 | ||||
-rw-r--r-- | apps/files_encryption/appinfo/spec.txt | 19 | ||||
-rw-r--r-- | apps/files_encryption/appinfo/version | 2 | ||||
-rw-r--r-- | apps/files_encryption/hooks/hooks.php | 143 | ||||
-rwxr-xr-x | apps/files_encryption/lib/crypt.php | 1458 | ||||
-rwxr-xr-x | apps/files_encryption/lib/keymanager.php | 684 | ||||
-rw-r--r-- | apps/files_encryption/lib/proxy.php | 160 | ||||
-rw-r--r-- | apps/files_encryption/lib/session.php | 49 | ||||
-rw-r--r-- | apps/files_encryption/lib/stream.php | 89 | ||||
-rw-r--r-- | apps/files_encryption/lib/util.php | 304 | ||||
-rw-r--r-- | apps/files_encryption/settings-personal.php | 24 | ||||
-rw-r--r-- | apps/files_encryption/templates/settings-personal.php | 55 | ||||
-rw-r--r-- | apps/files_encryption/templates/settings.php | 67 | ||||
-rwxr-xr-x | apps/files_encryption/test/crypt.php | 6 | ||||
-rw-r--r-- | apps/files_encryption/test/keymanager.php | 16 | ||||
-rwxr-xr-x | apps/files_encryption/test/util.php | 23 |
16 files changed, 1715 insertions, 1409 deletions
diff --git a/apps/files_encryption/appinfo/app.php b/apps/files_encryption/appinfo/app.php index 31b430d37a9..e426f237bbe 100644 --- a/apps/files_encryption/appinfo/app.php +++ b/apps/files_encryption/appinfo/app.php @@ -10,21 +10,31 @@ OC::$CLASSPATH['OCA\Encryption\Session'] = 'apps/files_encryption/lib/session.ph OC_FileProxy::register( new OCA\Encryption\Proxy() ); -OCP\Util::connectHook( 'OC_User','post_login', 'OCA\Encryption\Hooks', 'login' ); +// User-related hooks +OCP\Util::connectHook( 'OC_User', 'post_login', 'OCA\Encryption\Hooks', 'login' ); +OCP\Util::connectHook( 'OC_User', 'post_setPassword','OCA\Encryption\Hooks', 'setPassphrase' ); + +// Sharing-related hooks +OCP\Util::connectHook( 'OCP\Share', 'post_shared', 'OCA\Encryption\Hooks', 'postShared' ); +OCP\Util::connectHook( 'OCP\Share', 'pre_unshare', 'OCA\Encryption\Hooks', 'preUnshare' ); +OCP\Util::connectHook( 'OCP\Share', 'pre_unshareAll', 'OCA\Encryption\Hooks', 'preUnshareAll' ); + +// Webdav-related hooks OCP\Util::connectHook( 'OC_Webdav_Properties', 'update', 'OCA\Encryption\Hooks', 'updateKeyfile' ); -OCP\Util::connectHook( 'OC_User','post_setPassword','OCA\Encryption\Hooks' ,'setPassphrase' ); stream_wrapper_register( 'crypt', 'OCA\Encryption\Stream' ); $session = new OCA\Encryption\Session(); if ( -! $session->getPrivateKey( \OCP\USER::getUser() ) -&& OCP\User::isLoggedIn() -&& OCA\Encryption\Crypt::mode() == 'server' + ! $session->getPrivateKey( \OCP\USER::getUser() ) + && OCP\User::isLoggedIn() + && OCA\Encryption\Crypt::mode() == 'server' ) { - // Force the user to re-log in if the encryption key isn't unlocked (happens when a user is logged in before the encryption app is enabled) + // Force the user to log-in again if the encryption key isn't unlocked + // (happens when a user is logged in before the encryption app is + // enabled) OCP\User::logout(); header( "Location: " . OC::$WEBROOT.'/' ); @@ -33,5 +43,6 @@ if ( } -OCP\App::registerAdmin( 'files_encryption', 'settings'); +// Reguster settings scripts +OCP\App::registerAdmin( 'files_encryption', 'settings' ); OCP\App::registerPersonal( 'files_encryption', 'settings-personal' );
\ No newline at end of file diff --git a/apps/files_encryption/appinfo/spec.txt b/apps/files_encryption/appinfo/spec.txt new file mode 100644 index 00000000000..2d22dffe08d --- /dev/null +++ b/apps/files_encryption/appinfo/spec.txt @@ -0,0 +1,19 @@ +Encrypted files +--------------- + +- Each encrypted file has at least two components: the encrypted data file + ('catfile'), and it's corresponding key file ('keyfile'). Shared files have an + additional key file ('share key'). The catfile contains the encrypted data + concatenated with delimiter text, followed by the initialisation vector ('IV'), + and padding. e.g.: + + [encrypted data string][delimiter][IV][padding] + [anhAAjAmcGXqj1X9g==][00iv00][MSHU5N5gECP7aAg7][xx] (square braces added) + +Notes +----- + +- The user passphrase is required in order to set up or upgrade the app. New + keypair generation, and the re-encryption of legacy encrypted files requires + it. Therefore an appinfo/update.php script cannot be used, and upgrade logic + is handled in the login hook listener.
\ No newline at end of file diff --git a/apps/files_encryption/appinfo/version b/apps/files_encryption/appinfo/version index 7dff5b89211..1d71ef97443 100644 --- a/apps/files_encryption/appinfo/version +++ b/apps/files_encryption/appinfo/version @@ -1 +1 @@ -0.2.1
\ No newline at end of file +0.3
\ No newline at end of file diff --git a/apps/files_encryption/hooks/hooks.php b/apps/files_encryption/hooks/hooks.php index c2f97247835..065ef9d2410 100644 --- a/apps/files_encryption/hooks/hooks.php +++ b/apps/files_encryption/hooks/hooks.php @@ -1,4 +1,5 @@ <?php
+
/**
* ownCloud
*
@@ -28,7 +29,8 @@ namespace OCA\Encryption; class Hooks {
- # TODO: use passphrase for encrypting private key that is separate to the login password
+ // TODO: use passphrase for encrypting private key that is separate to
+ // the login password
/**
* @brief Startup encryption backend upon user login
@@ -36,49 +38,62 @@ class Hooks { */
public static function login( $params ) {
-// if ( Crypt::mode( $params['uid'] ) == 'server' ) {
-
- # TODO: use lots of dependency injection here
-
- $view = new \OC_FilesystemView( '/' );
-
- $util = new Util( $view, $params['uid'] );
-
- if ( ! $util->ready() ) {
-
- \OC_Log::write( 'Encryption library', 'User account "' . $params['uid'] . '" is not ready for encryption; configuration started' , \OC_Log::DEBUG );
-
- return $util->setupServerSide( $params['password'] );
+ \OC\Files\Filesystem::init( $params['uid'] . '/' . 'files' . '/' );
+
+ $view = new \OC_FilesystemView( '/' );
- }
+ $util = new Util( $view, $params['uid'] );
- \OC_FileProxy::$enabled = false;
-
- $encryptedKey = Keymanager::getPrivateKey( $view, $params['uid'] );
-
- \OC_FileProxy::$enabled = true;
-
- # TODO: dont manually encrypt the private keyfile - use the config options of openssl_pkey_export instead for better mobile compatibility
-
- $privateKey = Crypt::symmetricDecryptFileContent( $encryptedKey, $params['password'] );
-
- $session = new Session();
-
- $session->setPrivateKey( $privateKey, $params['uid'] );
+ if ( ! $util->ready() ) {
- $view1 = new \OC_FilesystemView( '/' . $params['uid'] );
+ \OC_Log::write( 'Encryption library', 'User account "' . $params['uid'] . '" is not ready for encryption; configuration started', \OC_Log::DEBUG );
- // Set legacy encryption key if it exists, to support
- // depreciated encryption system
- if (
+ return $util->setupServerSide( $params['password'] );
+
+ }
+
+ \OC_FileProxy::$enabled = false;
+
+ $encryptedKey = Keymanager::getPrivateKey( $view, $params['uid'] );
+
+ \OC_FileProxy::$enabled = true;
+
+ $privateKey = Crypt::symmetricDecryptFileContent( $encryptedKey, $params['password'] );
+
+ $session = new Session();
+
+ $session->setPrivateKey( $privateKey, $params['uid'] );
+
+ $view1 = new \OC_FilesystemView( '/' . $params['uid'] );
+
+ // Set legacy encryption key if it exists, to support
+ // depreciated encryption system
+ if (
$view1->file_exists( 'encryption.key' )
- && $legacyKey = $view1->file_get_contents( 'encryption.key' )
- ) {
-
- $_SESSION['legacyenckey'] = Crypt::legacyDecrypt( $legacyKey, $params['password'] );
+ && $encLegacyKey = $view1->file_get_contents( 'encryption.key' )
+ ) {
+
+ $plainLegacyKey = Crypt::legacyDecrypt( $encLegacyKey, $params['password'] );
- }
-// }
+ $session->setLegacyKey( $plainLegacyKey );
+
+ }
+
+ $publicKey = Keymanager::getPublicKey( $view, $params['uid'] );
+
+ // Encrypt existing user files:
+ // This serves to upgrade old versions of the encryption
+ // app (see appinfo/spec.txt)
+ if (
+ $util->encryptAll( $publicKey, '/' . $params['uid'] . '/' . 'files', $session->getLegacyKey(), $params['password'] )
+ ) {
+
+ \OC_Log::write(
+ 'Encryption library', 'Encryption of existing files belonging to "' . $params['uid'] . '" started at login'
+ , \OC_Log::INFO
+ );
+
+ }
return true;
@@ -104,9 +119,9 @@ class Hooks { // Save private key
Keymanager::setPrivateKey( $encryptedPrivateKey );
- # NOTE: Session does not need to be updated as the
- # private key has not changed, only the passphrase
- # used to decrypt it has changed
+ // NOTE: Session does not need to be updated as the
+ // private key has not changed, only the passphrase
+ // used to decrypt it has changed
}
@@ -121,8 +136,11 @@ class Hooks { if ( isset( $params['properties']['key'] ) ) {
- Keymanager::setFileKey( $params['path'], $params['properties']['key'] );
-
+ $view = new \OC_FilesystemView( '/' );
+ $userId = \OCP\User::getUser();
+
+ Keymanager::setFileKey( $view, $params['path'], $userId, $params['properties']['key'] );
+
} else {
\OC_Log::write(
@@ -138,6 +156,41 @@ class Hooks { }
+ /**
+ * @brief
+ */
+ public static function postShared( $params ) {
+
+ // Delete existing catfile
+ Keymanager::deleteFileKey( );
+
+ // Generate new catfile and env keys
+ Crypt::multiKeyEncrypt( $plainContent, $publicKeys );
+
+ // Save env keys to user folders
+
+
+ }
+
+ /**
+ * @brief
+ */
+ public static function preUnshare( $params ) {
+
+ // Delete existing catfile
+
+ // Generate new catfile and env keys
+
+ // Save env keys to user folders
+ }
+
+ /**
+ * @brief
+ */
+ public static function preUnshareAll( $params ) {
+
+ trigger_error( "preUnshareAll" );
+
+ }
+
}
-
-?>
\ No newline at end of file diff --git a/apps/files_encryption/lib/crypt.php b/apps/files_encryption/lib/crypt.php index bfffda9ba32..7eb70d5c8c3 100755 --- a/apps/files_encryption/lib/crypt.php +++ b/apps/files_encryption/lib/crypt.php @@ -1,716 +1,748 @@ -<?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
- * @param $content
- * @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
- * @param $content
- * @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' );
- }
-
- }
-
- /**
- * @brief Concatenate encrypted data with its IV and padding
- * @param string $content content to be concatenated
- * @param string $iv IV to be concatenated
- * @return 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 $keyfileContent
- * @param string $passphrase
- * @throws \Exception
- * @return string
- * @internal param string $source
- * @internal param string $target
- * @internal 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
- * @return 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
- * @return array|bool
- * @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 $encryptedContent
- * @param $envKey
- * @param $privateKey
- * @return bool
- * @internal 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 );
-
- }
-
- 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 );
-
- }
-
- return $decrypted;
-
- }
-
- /**
- * @brief Generates a pseudo random initialisation vector
- * @throws Exception
- * @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()' );
-
+<?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: +// - Add a setting "Don´t encrypt files larger than xx because of performance"
+// - Don't use a password directly as encryption key. but a key which is
+// stored on the server and encrypted with the user password. -> change pass
+// faster
+ +/** + * 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 isCatfile( $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\Files\Filesystem out of here + + // Fetch all file metadata from DB + $metadata = \OC\Files\Filesystem::getFileInfo( $path, '' ); + + // Return encryption status + return isset( $metadata['encrypted'] ) and ( bool )$metadata['encrypted']; + + } +
+ /**
+ * @brief Check if a file is encrypted via legacy system
+ * @param string $relPath The path of the file, relative to user/data;
+ * e.g. filename or /Docs/filename, NOT admin/files/filename
+ * @return true / false
+ */
+ public static function isLegacyEncryptedContent( $data, $relPath ) {
+
+ // Fetch all file metadata from DB + $metadata = \OC\Files\Filesystem::getFileInfo( $relPath, '' );
+
+ // 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 (
+ isset( $metadata['encrypted'] )
+ and $metadata['encrypted'] === true
+ and ! self::isCatfile( $data )
+ ) { + + 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 ) { + + // Set empty vars to be set by openssl by reference + $sealed = ''; + $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 $key;
-
- } else {
-
- return false;
-
+
}
-
+
+ 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 string $passphrase
- * @return
- * @internal param \OCA\Encryption\the $key 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 string $passphrase
- * @return string
- * @internal param \OCA\Encryption\the $key 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-encrypts a legacy blowfish encrypted file using AES with integrated IV
- * @param $legacyContent the legacy encrypted content to re-encrypt
- * @param $legacyPassphrase
- * @param $newPassphrase
- * @returns cleartext content
- *
- * This function decrypts an content
- */
- public static function legacyRecrypt( $legacyContent, $legacyPassphrase, $newPassphrase ) {
-
- # TODO: write me
-
- }
-
-}
+
+ /** + * @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/keymanager.php b/apps/files_encryption/lib/keymanager.php index 1b5dc5f7e66..0d0380db6ec 100755 --- a/apps/files_encryption/lib/keymanager.php +++ b/apps/files_encryption/lib/keymanager.php @@ -1,287 +1,267 @@ -<?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
- *
- * @param \OC_FilesystemView $view
- * @param $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
- * @param \OC_FilesystemView $view
- * @param $userId
- * @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)
+<?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 { +
+ /** + * @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 * @param \OC_FilesystemView $view
* @param $userId
- * @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
+ * @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) * @param \OC_FilesystemView $view
* @param $userId
- * @param $filePath
- * @internal 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, $path ) {
-
- $trimmed = ltrim( $path, '/' );
-
- $filepath = '/' . $userId . '/files/' . $trimmed;
-
- // 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
+ * @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' ) ) { + + + + } 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 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( \OC_FilesystemView $view, $path, $userId, $catfile ) { + + $basePath = '/' . $userId . '/files_encryption/keyfiles'; + + $targetPath = self::keySetPreparation( $view, $path, $basePath, $userId ); + + if ( $view->is_dir( $basePath . '/' . $targetPath ) ) { + + + + } else { + + // Save the keyfile in parallel directory + return $view->file_put_contents( $basePath . '/' . $targetPath . '.key', $catfile ); + + } + + } + + /** + * @brief retrieve keyfile for an encrypted file * @param \OC_FilesystemView $view
* @param $userId
* @param $filePath
* @internal param \OCA\Encryption\file $string 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 $path
- * @param string $staticUserClass
- * @internal param \OCA\Encryption\file $string 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( '' );
-
- $result = $view->file_put_contents( $user . '.private.key', $key );
-
- \OC_FileProxy::$enabled = true;
-
- return $result;
-
- }
-
- /**
- * @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( '' );
-
- $result = $view->file_put_contents( \OCP\User::getUser() . '.public.key', $key );
-
- \OC_FileProxy::$enabled = true;
-
- return $result;
-
- }
-
- /**
+ * @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, '/' ); + + $catfilePath = '/' . $userId . '/files_encryption/keyfiles/' . $filePath_f . '.key'; + + if ( $view->file_exists( $catfilePath ) ) { + + return $view->file_get_contents( $catfilePath ); + + } else { + + return false; + + } + + } + + /** + * @brief Delete a keyfile + * + * @param OC_FilesystemView $view
+ * @param string $userId username
+ * @param string $path path of the file the key belongs to
+ * @return bool Outcome of unlink operation
+ * @note $path must be relative to data/user/files. e.g. mydoc.txt NOT
+ * /data/admin/files/mydoc.txt
+ */ + public static function deleteFileKey( \OC_FilesystemView $view, $userId, $path ) { + + $trimmed = ltrim( $path, '/' ); + $keyPath = '/' . $userId . '/files_encryption/keyfiles/' . $trimmed . '.key'; + + // Unlink doesn't tell us if file was deleted (not found returns + // true), so we perform our own test + if ( $view->file_exists( $keyPath ) ) { + + return $view->unlink( $keyPath ); + + } else { + + \OC_Log::write( 'Encryption library', 'Could not delete keyfile; does not exist: "' . $keyPath, \OC_Log::ERROR ); + + return false; + + } + + } + + /** + * @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
@@ -291,96 +271,70 @@ class Keymanager { * @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;
-
+ */ + public static function setShareKey( \OC_FilesystemView $view, $path, $userId, $shareKey ) { + + $basePath = '/' . $userId . '/files_encryption/share-keys'; + + $shareKeyPath = self::keySetPreparation( $view, $path, $basePath, $userId ); + + return $view->file_put_contents( $basePath . '/' . $shareKeyPath . '.shareKey', $shareKey ); + }
-
+
/**
- * @brief Fetch the legacy encryption key from user files
- * @internal param string $login used to locate the legacy key
- * @internal param string $passphrase used to decrypt the legacy key
- * @return true / false
- *
- * if the key is left out, the default handeler will be used
+ * @brief Make preparations to vars and filesystem for saving a keyfile
*/
- public function getLegacyKey() {
-
- $user = \OCP\User::getUser();
- $view = new \OC_FilesystemView( '/' . $user );
- return $view->file_get_contents( 'encryption.key' );
-
- }
-
-}
+ public static function keySetPreparation( \OC_FilesystemView $view, $path, $basePath, $userId ) {
+ + $targetPath = ltrim( $path, '/' ); + + $path_parts = pathinfo( $targetPath ); + + // If the file resides within a subdirectory, create it + if (
+ isset( $path_parts['dirname'] )
+ && ! $view->file_exists( $basePath . '/' . $path_parts['dirname'] )
+ ) { + + $view->mkdir( $basePath . '/' . $path_parts['dirname'] ); + + } + + return $targetPath;
+
+ } + + /** + * @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 52f47dba294..55cddf2bec8 100644 --- a/apps/files_encryption/lib/proxy.php +++ b/apps/files_encryption/lib/proxy.php @@ -22,6 +22,12 @@ * */ +/** +* @brief Encryption proxy which handles filesystem operations before and after +* execution and encrypts, and handles keyfiles accordingly. Used for +* webui. +*/ + namespace OCA\Encryption; class Proxy extends \OC_FileProxy { @@ -42,8 +48,8 @@ class Proxy extends \OC_FileProxy { if ( is_null( self::$enableEncryption ) ) { if ( - \OCP\Config::getAppValue( 'files_encryption', 'enable_encryption', 'true' ) == 'true' - && Crypt::mode() == 'server' + \OCP\Config::getAppValue( 'files_encryption', 'enable_encryption', 'true' ) == 'true' + && Crypt::mode() == 'server' ) { self::$enableEncryption = true; @@ -64,19 +70,19 @@ class Proxy extends \OC_FileProxy { 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' ) ); + self::$blackList = explode(',', \OCP\Config::getAppValue( 'files_encryption', 'type_blacklist', 'jpg,png,jpeg,avi,mpg,mpeg,mkv,mp3,oga,ogv,ogg' ) ); } - if ( Crypt::isEncryptedContent( $path ) ) { + if ( Crypt::isCatfile( $path ) ) { return true; } - $extension = substr( $path, strrpos( $path,'.' ) +1 ); + $extension = substr( $path, strrpos( $path, '.' ) +1 ); - if ( array_search( $extension, self::$blackList ) === false ){ + if ( array_search( $extension, self::$blackList ) === false ) { return true; @@ -101,6 +107,8 @@ class Proxy extends \OC_FileProxy { // Disable encryption proxy to prevent recursive calls \OC_FileProxy::$enabled = false; + // TODO: Check if file is shared, if so, use multiKeyEncrypt + // Encrypt plain data and fetch key $encrypted = Crypt::keyEncryptKeyfile( $data, Keymanager::getPublicKey( $rootView, $userId ) ); @@ -113,14 +121,15 @@ class Proxy extends \OC_FileProxy { $filePath = '/' . implode( '/', $filePath ); - # TODO: make keyfile dir dynamic from app config - $view = new \OC_FilesystemView( '/' . $userId . '/files_encryption/keyfiles' ); + // TODO: make keyfile dir dynamic from app config + + $view = new \OC_FilesystemView( '/' ); // Save keyfile for newly encrypted file in parallel directory tree - Keymanager::setFileKey( $filePath, $encrypted['key'], $view, '\OC_DB' ); + Keymanager::setFileKey( $view, $filePath, $userId, $encrypted['key'] ); // Update the file cache with file info - \OC_FileCache::put( $path, array( 'encrypted'=>true, 'size' => $size ), '' ); + \OC\Files\Filesystem::putFileInfo( $path, array( 'encrypted'=>true, 'size' => $size ), '' ); // Re-enable proxy - our work is done \OC_FileProxy::$enabled = true; @@ -136,15 +145,15 @@ class Proxy extends \OC_FileProxy { */ public function postFile_get_contents( $path, $data ) { - # TODO: Use dependency injection to add required args for view and user etc. to this method + // 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 ) + Crypt::mode() == 'server' + && Crypt::isCatfile( $data ) ) { $split = explode( '/', $path ); @@ -153,12 +162,14 @@ class Proxy extends \OC_FileProxy { $filePath = '/' . implode( '/', $filePath ); - //$cached = \OC_FileCache_Cached::get( $path, '' ); + //$cached = \OC\Files\Filesystem::getFileInfo( $path, '' ); $view = new \OC_FilesystemView( '' ); $userId = \OCP\USER::getUser(); + // TODO: Check if file is shared, if so, use multiKeyDecrypt + $encryptedKeyfile = Keymanager::getFileKey( $view, $userId, $filePath ); $session = new Session(); @@ -187,6 +198,79 @@ class Proxy extends \OC_FileProxy { } + /** + * @brief When a file is deleted, remove its keyfile also + */ + public function preUnlink( $path ) { + + // Disable encryption proxy to prevent recursive calls + \OC_FileProxy::$enabled = false; + + $view = new \OC_FilesystemView( '/' ); + + $userId = \OCP\USER::getUser(); + + // Format path to be relative to user files dir + $trimmed = ltrim( $path, '/' ); + $split = explode( '/', $trimmed ); + $sliced = array_slice( $split, 2 ); + $relPath = implode( '/', $sliced ); + + if ( $view->is_dir( $path ) ) { + + // Dirs must be handled separately as deleteFileKey + // doesn't handle them + $view->unlink( $userId . '/' . 'files_encryption' . '/' . 'keyfiles' . '/'. $relPath ); + + } else { + + // Delete keyfile so it isn't orphaned + $result = Keymanager::deleteFileKey( $view, $userId, $relPath ); + + \OC_FileProxy::$enabled = true; + + return $result; + + } + + } + + /** + * @brief When a file is renamed, rename its keyfile also + * @return bool Result of rename() + * @note This is pre rather than post because using post didn't work + */ + public function preRename( $oldPath, $newPath ) { + + // Disable encryption proxy to prevent recursive calls + \OC_FileProxy::$enabled = false; + + $view = new \OC_FilesystemView( '/' ); + + $userId = \OCP\USER::getUser(); + + // Format paths to be relative to user files dir + $oldTrimmed = ltrim( $oldPath, '/' ); + $oldSplit = explode( '/', $oldTrimmed ); + $oldSliced = array_slice( $oldSplit, 2 ); + $oldRelPath = implode( '/', $oldSliced ); + $oldKeyfilePath = $userId . '/' . 'files_encryption' . '/' . 'keyfiles' . '/' . $oldRelPath . '.key'; + + $newTrimmed = ltrim( $newPath, '/' ); + $newSplit = explode( '/', $newTrimmed ); + $newSliced = array_slice( $newSplit, 2 ); + $newRelPath = implode( '/', $newSliced ); + $newKeyfilePath = $userId . '/' . 'files_encryption' . '/' . 'keyfiles' . '/' . $newRelPath . '.key'; + + // Rename keyfile so it isn't orphaned + $result = $view->rename( $oldKeyfilePath, $newKeyfilePath ); + + \OC_FileProxy::$enabled = true; + + return $result; + + } + public function postFopen( $path, &$result ){ if ( !$result ) { @@ -210,8 +294,8 @@ class Proxy extends \OC_FileProxy { // If file is already encrypted, decrypt using crypto protocol if ( - Crypt::mode() == 'server' - && $util->isEncryptedPath( $path ) + Crypt::mode() == 'server' + && $util->isEncryptedPath( $path ) ) { // Close the original encrypted file @@ -223,9 +307,9 @@ class Proxy extends \OC_FileProxy { } elseif ( - self::shouldEncrypt( $path ) - and $meta ['mode'] != 'r' - and $meta['mode'] != 'rb' + 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) @@ -263,27 +347,43 @@ class Proxy extends \OC_FileProxy { } - public function postGetMimeType($path,$mime){ - if( Crypt::isEncryptedContent($path)){ - $mime = \OCP\Files::getMimeType('crypt://'.$path,'w'); + public function postGetMimeType( $path, $mime ) { + + if ( Crypt::isCatfile( $path ) ) { + + $mime = \OCP\Files::getMimeType( 'crypt://' . $path, 'w' ); + } + return $mime; + } - public function postStat($path,$data){ - if( Crypt::isEncryptedContent($path)){ - $cached= \OC_FileCache_Cached::get($path,''); - $data['size']=$cached['size']; + public function postStat( $path, $data ) { + + if ( Crypt::isCatfile( $path ) ) { + + $cached = \OC\Files\Filesystem::getFileInfo( $path, '' ); + + $data['size'] = $cached['size']; + } + return $data; } - public function postFileSize($path,$size){ - if( Crypt::isEncryptedContent($path)){ - $cached = \OC_FileCache_Cached::get($path,''); + public function postFileSize( $path, $size ) { + + if ( Crypt::isCatfile( $path ) ) { + + $cached = \OC\Files\Filesystem::getFileInfo( $path, '' ); + return $cached['size']; - }else{ + + } else { + return $size; + } } } diff --git a/apps/files_encryption/lib/session.php b/apps/files_encryption/lib/session.php index 85d533fde7a..769a40b359f 100644 --- a/apps/files_encryption/lib/session.php +++ b/apps/files_encryption/lib/session.php @@ -29,11 +29,11 @@ namespace OCA\Encryption; class Session { /** - * @brief Sets user id for session and triggers emit + * @brief Sets user private key to session * @return bool * */ - public function setPrivateKey( $privateKey, $userId ) { + public function setPrivateKey( $privateKey ) { $_SESSION['privateKey'] = $privateKey; @@ -42,15 +42,15 @@ class Session { } /** - * @brief Gets user id for session and triggers emit + * @brief Gets user private key from session * @returns string $privateKey The user's plaintext private key * */ - public function getPrivateKey( $userId ) { + public function getPrivateKey() { if ( - isset( $_SESSION['privateKey'] ) - && !empty( $_SESSION['privateKey'] ) + isset( $_SESSION['privateKey'] ) + && !empty( $_SESSION['privateKey'] ) ) { return $_SESSION['privateKey']; @@ -62,5 +62,42 @@ class Session { } } + + /** + * @brief Sets user legacy key to session + * @return bool + * + */ + public function setLegacyKey( $legacyKey ) { + + if ( $_SESSION['legacyKey'] = $legacyKey ) { + + return true; + + } + + } + + /** + * @brief Gets user legacy key from session + * @returns string $legacyKey The user's plaintext legacy key + * + */ + public function getLegacyKey() { + + if ( + isset( $_SESSION['legacyKey'] ) + && !empty( $_SESSION['legacyKey'] ) + ) { + + return $_SESSION['legacyKey']; + + } 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 index f482e2d75ac..d4b993b4c06 100644 --- a/apps/files_encryption/lib/stream.php +++ b/apps/files_encryption/lib/stream.php @@ -49,9 +49,10 @@ class Stream { public static $sourceStreams = array(); - # TODO: make all below properties private again once unit testing is configured correctly + // 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 + public $path_f; // The raw path formatted to include username and data dir private $userId; private $handle; // Resource returned by fopen private $path; @@ -235,10 +236,12 @@ class Stream { */ public function getKey() { - // If a keyfile already exists for a file named identically to file to be written + // 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 + // TODO: add error handling for when file exists but no + // keyfile // Fetch existing keyfile $this->encKeyfile = Keymanager::getFileKey( $this->rootView, $this->userId, $this->rawPath ); @@ -266,13 +269,14 @@ class Stream { // 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 + // 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?) + // TODO: Add a method for getting the user in case OCP\User:: + // getUser() doesn't work (can that scenario ever occur?) } @@ -287,7 +291,10 @@ class Stream { */ 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 + // 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 @@ -296,14 +303,19 @@ class Stream { // 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 + // 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(); + // TODO: Check if file is shared, if so, use multiKeyEncrypt and + // save shareKeys in necessary user directories + // 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 we're writing a new file (not overwriting an existing + // one), save the newly generated keyfile if ( ! $this->getKey() ) { $this->keyfile = Crypt::generateKey(); @@ -312,26 +324,32 @@ class Stream { $this->encKeyfile = Crypt::keyEncrypt( $this->keyfile, $this->publicKey ); - // Save the new encrypted file key - Keymanager::setFileKey( $this->rawPath, $this->encKeyfile, new \OC_FilesystemView( '/' ) ); + $view = new \OC_FilesystemView( '/' ); + $userId = \OCP\User::getUser(); - # TODO: move this new OCFSV out of here some how, use DI + // Save the new encrypted file key + Keymanager::setFileKey( $view, $this->rawPath, $userId, $this->encKeyfile ); } - // If extra data is left over from the last round, make sure it is integrated into the next 6126 / 8192 block + // 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 + // 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 + if ( 0 != ( $pointer % 8192 ) ) { + // if the current position of + // file indicator is not aligned to a 8192 byte block, fix it + // so that it is // fseek( $this->handle, - ( $pointer % 8192 ), SEEK_CUR ); // @@ -356,14 +374,22 @@ class Stream { // // 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) +// // 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 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(). + // 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 @@ -376,13 +402,17 @@ class Stream { $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 + // 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 + // 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 ); } @@ -396,16 +426,16 @@ class Stream { } - public function stream_set_option($option,$arg1,$arg2) { + public function stream_set_option( $option, $arg1, $arg2 ) { switch($option) { case STREAM_OPTION_BLOCKING: - stream_set_blocking($this->handle,$arg1); + stream_set_blocking( $this->handle, $arg1 ); break; case STREAM_OPTION_READ_TIMEOUT: - stream_set_timeout($this->handle,$arg1,$arg2); + stream_set_timeout( $this->handle, $arg1, $arg2 ); break; case STREAM_OPTION_WRITE_BUFFER: - stream_set_write_buffer($this->handle,$arg1,$arg2); + stream_set_write_buffer( $this->handle, $arg1, $arg2 ); } } @@ -413,13 +443,14 @@ class Stream { return fstat($this->handle); } - public function stream_lock($mode) { - flock($this->handle,$mode); + 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 + return fflush( $this->handle ); + // Not a typo: http://php.net/manual/en/function.fflush.php } @@ -453,7 +484,7 @@ class Stream { and $this->meta['mode']!='rb' ) { - \OC_FileCache::put( $this->path, array( 'encrypted' => true, 'size' => $this->size ), '' ); + \OC\Files\Filesystem::putFileInfo( $this->path, array( 'encrypted' => true, 'size' => $this->size ), '' ); } diff --git a/apps/files_encryption/lib/util.php b/apps/files_encryption/lib/util.php index 8aa926b05f6..5158d6e856c 100644 --- a/apps/files_encryption/lib/util.php +++ b/apps/files_encryption/lib/util.php @@ -24,81 +24,89 @@ // 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 +// - 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 + * @param OC_FilesystemView $view expected to have OC '/' as root path + * @param string $userId ID of the logged in user + * @param int $client indicating status of client side encryption. Currently * unused, likely to become obsolete shortly */ class Util { - # Web UI: + // 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 + //// 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: + // 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 + //// 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: + // 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 + //// 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 + //// 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: + // Admin UI: - ## DONE: changing user password also changes encryption passphrase + //// 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. + //// 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: + // Sharing: - ## TODO: add support for encrypting to multiple public keys - ## TODO: add support for decrypting to multiple private keys + //// TODO: add support for encrypting to multiple public keys + //// TODO: add support for decrypting to multiple private keys - # Integration testing: + // 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 + //// 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 $userId; // ID of the currently logged-in user 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 $publicKeyDir; // Dir containing all public user keys + private $encryptionDir; // Dir containing user's files_encryption + private $keyfilesPath; // Dir containing user's keyfiles + private $shareKeysPath; // Dir containing env keys for shared files private $publicKeyPath; // Path to user's public key private $privateKeyPath; // Path to user's private key @@ -107,9 +115,12 @@ class Util { $this->view = $view; $this->userId = $userId; $this->client = $client; + $this->userDir = '/' . $this->userId; + $this->userFilesDir = '/' . $this->userId . '/' . 'files'; $this->publicKeyDir = '/' . 'public-keys'; $this->encryptionDir = '/' . $this->userId . '/' . 'files_encryption'; $this->keyfilesPath = $this->encryptionDir . '/' . 'keyfiles'; + $this->shareKeysPath = $this->encryptionDir . '/' . 'share-keys'; $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 @@ -118,7 +129,9 @@ class Util { public function ready() { if( - !$this->view->file_exists( $this->keyfilesPath ) + !$this->view->file_exists( $this->encryptionDir ) + or !$this->view->file_exists( $this->keyfilesPath ) + or !$this->view->file_exists( $this->shareKeysPath ) or !$this->view->file_exists( $this->publicKeyPath ) or !$this->view->file_exists( $this->privateKeyPath ) ) { @@ -139,6 +152,20 @@ class Util { */ public function setupServerSide( $passphrase = null ) { + // Create user dir + if( !$this->view->file_exists( $this->userDir ) ) { + + $this->view->mkdir( $this->userDir ); + + } + + // Create user files dir + if( !$this->view->file_exists( $this->userFilesDir ) ) { + + $this->view->mkdir( $this->userFilesDir ); + + } + // Create shared public key directory if( !$this->view->file_exists( $this->publicKeyDir ) ) { @@ -159,16 +186,23 @@ class Util { $this->view->mkdir( $this->keyfilesPath ); } + + // Create mirrored share env keys directory + if( !$this->view->file_exists( $this->shareKeysPath ) ) { + + $this->view->mkdir( $this->shareKeysPath ); + + } // Create user keypair if ( - !$this->view->file_exists( $this->publicKeyPath ) - or !$this->view->file_exists( $this->privateKeyPath ) + ! $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 @@ -188,48 +222,77 @@ class Util { } - public function findFiles( $directory, $type = 'plain' ) { - - # TODO: test finding non plain content + /** + * @brief Find all files and their encryption status within a directory + * @param string $directory The path of the parent directory to search + * @return mixed false if 0 found, array on success. Keys: name, path + + * @note $directory needs to be a path relative to OC data dir. e.g. + * /admin/files NOT /backup OR /home/www/oc/data/admin/files + */ + public function findFiles( $directory ) { + + // Disable proxy - we don't want files to be decrypted before + // we handle them + \OC_FileProxy::$enabled = false; + + $found = array( 'plain' => array(), 'encrypted' => array(), 'legacy' => array() ); + + if ( + $this->view->is_dir( $directory ) + && $handle = $this->view->opendir( $directory ) + ) { - if ( $handle = $this->view->opendir( $directory ) ) { - while ( false !== ( $file = readdir( $handle ) ) ) { - + if ( $file != "." && $file != ".." ) { - - $filePath = $directory . '/' . $this->view->getRelativePath( '/' . $file ); - var_dump($filePath); + $filePath = $directory . '/' . $this->view->getRelativePath( '/' . $file ); + $relPath = $this->stripUserFilesPath( $filePath ); + // If the path is a directory, search + // its contents 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 the path is a file, determine + // its encryption status + } elseif ( $this->view->is_file( $filePath ) ) { - if ( Crypt::isEncryptedContent( $this->view->file_get_contents( $filePath ) ) ) { - - $this->files[] = array( 'name' => $file, 'path' => $filePath ); - - } + // Disable proxies again, some- + // where they got re-enabled :/ + \OC_FileProxy::$enabled = false; - } elseif ( $type == 'legacy' ) { + $data = $this->view->file_get_contents( $filePath ); - if ( Crypt::isLegacyEncryptedContent( $this->view->file_get_contents( $filePath ) ) ) { + // If the file is encrypted + // NOTE: If the userId is + // empty or not set, file will + // detected as plain + // NOTE: This is inefficient; + // scanning every file like this + // will eat server resources :( + if ( + Keymanager::getFileKey( $this->view, $this->userId, $file ) + && Crypt::isCatfile( $filePath ) + ) { + + $found['encrypted'][] = array( 'name' => $file, 'path' => $filePath ); + + // If the file uses old + // encryption system + } elseif ( Crypt::isLegacyEncryptedContent( $this->view->file_get_contents( $filePath ), $relPath ) ) { - $this->files[] = array( 'name' => $file, 'path' => $filePath ); + $found['legacy'][] = array( 'name' => $file, 'path' => $filePath ); - } + // If the file is not encrypted + } else { + + $found['plain'][] = array( 'name' => $file, 'path' => $filePath ); } @@ -239,18 +302,22 @@ class Util { } - if ( !empty( $this->files ) ) { + \OC_FileProxy::$enabled = true; - return $this->files; - - } else { + if ( empty( $found ) ) { return false; + } else { + + return $found; + } } + \OC_FileProxy::$enabled = true; + return false; } @@ -269,20 +336,101 @@ class Util { \OC_FileProxy::$enabled = true; - return Crypt::isEncryptedContent( $data ); + return Crypt::isCatfile( $data ); + + } + + /** + * @brief Format a path to be relative to the /user/files/ directory + */ + public function stripUserFilesPath( $path ) { + + $trimmed = ltrim( $path, '/' ); + $split = explode( '/', $trimmed ); + $sliced = array_slice( $split, 2 ); + $relPath = implode( '/', $sliced ); + + return $relPath; } - public function encryptAll( $directory ) { + /** + * @brief Encrypt all files in a directory + * @param string $publicKey the public key to encrypt files with + * @param string $dirPath the directory whose files will be encrypted + * @note Encryption is recursive + */ + public function encryptAll( $publicKey, $dirPath, $legacyPassphrase = null, $newPassphrase = null ) { - $plainFiles = $this->findFiles( $this->view, 'plain' ); + if ( $found = $this->findFiles( $dirPath ) ) { - if ( $this->encryptFiles( $plainFiles ) ) { + // Disable proxy to prevent file being encrypted twice + \OC_FileProxy::$enabled = false; - return true; + // Encrypt unencrypted files + foreach ( $found['plain'] as $plainFile ) { + + // Fetch data from file + $plainData = $this->view->file_get_contents( $plainFile['path'] ); + + // Encrypt data, generate catfile + $encrypted = Crypt::keyEncryptKeyfile( $plainData, $publicKey ); + + $relPath = $this->stripUserFilesPath( $plainFile['path'] ); + + // Save keyfile + Keymanager::setFileKey( $this->view, $relPath, $this->userId, $encrypted['key'] ); + + // Overwrite the existing file with the encrypted one + $this->view->file_put_contents( $plainFile['path'], $encrypted['data'] ); + + $size = strlen( $encrypted['data'] ); + + // Add the file to the cache + \OC\Files\Filesystem::putFileInfo( $plainFile['path'], array( 'encrypted'=>true, 'size' => $size ), '' ); + } + + // FIXME: Legacy recrypting here isn't finished yet + // Encrypt legacy encrypted files + if ( + ! empty( $legacyPassphrase ) + && ! empty( $newPassphrase ) + ) { + + foreach ( $found['legacy'] as $legacyFile ) { + + // Fetch data from file + $legacyData = $this->view->file_get_contents( $legacyFile['path'] ); + + // Recrypt data, generate catfile + $recrypted = Crypt::legacyKeyRecryptKeyfile( $legacyData, $legacyPassphrase, $publicKey, $newPassphrase ); + + $relPath = $this->stripUserFilesPath( $legacyFile['path'] ); + + // Save keyfile + Keymanager::setFileKey( $this->view, $relPath, $this->userId, $recrypted['key'] ); + + // Overwrite the existing file with the encrypted one + $this->view->file_put_contents( $legacyFile['path'], $recrypted['data'] ); + + $size = strlen( $recrypted['data'] ); + + // Add the file to the cache + \OC\Files\Filesystem::putFileInfo( $legacyFile['path'], array( 'encrypted'=>true, 'size' => $size ), '' ); + + } + + } + + \OC_FileProxy::$enabled = true; + + // If files were found, return true + return true; + } else { + // If no files were found, return false return false; } diff --git a/apps/files_encryption/settings-personal.php b/apps/files_encryption/settings-personal.php index 014288f2efe..6fe4ea6d564 100644 --- a/apps/files_encryption/settings-personal.php +++ b/apps/files_encryption/settings-personal.php @@ -1,29 +1,19 @@ <?php
/**
- * Copyright (c) 2012 Bjoern Schiessle <schiessle@owncloud.com>
+ * Copyright (c) 2013 Sam Tuke <samtuke@owncloud.com>
* This file is licensed under the Affero General Public License version 3 or
* later.
* See the COPYING-README file.
*/
-$sysEncMode = \OC_Appconfig::getValue('files_encryption', 'mode', 'none');
+$tmpl = new OCP\Template( 'files_encryption', 'settings-personal');
-if ($sysEncMode == 'user') {
+$blackList = explode( ',', \OCP\Config::getAppValue( 'files_encryption', 'type_blacklist', 'jpg,png,jpeg,avi,mpg,mpeg,mkv,mp3,oga,ogv,ogg' ) );
- $tmpl = new OCP\Template( 'files_encryption', 'settings-personal');
+$tmpl->assign( 'blacklist', $blackList );
- $query = \OC_DB::prepare( "SELECT mode FROM *PREFIX*encryption WHERE uid = ?" );
- $result = $query->execute(array(\OCP\User::getUser()));
-
- if ($row = $result->fetchRow()){
- $mode = $row['mode'];
- } else {
- $mode = 'none';
- }
-
- OCP\Util::addscript('files_encryption','settings-personal');
- $tmpl->assign('encryption_mode', $mode);
- return $tmpl->fetchPage();
-}
+OCP\Util::addscript('files_encryption','settings-personal');
+
+return $tmpl->fetchPage();
return null;
diff --git a/apps/files_encryption/templates/settings-personal.php b/apps/files_encryption/templates/settings-personal.php index 1274bd3bb5c..1f71efb1735 100644 --- a/apps/files_encryption/templates/settings-personal.php +++ b/apps/files_encryption/templates/settings-personal.php @@ -1,45 +1,22 @@ <form id="encryption">
<fieldset class="personalblock">
- <strong><?php echo $l->t('Choose encryption mode:'); ?></strong>
+ <legend>
+ <?php echo $l->t( 'Encryption' ); ?>
+ </legend>
<p>
- <input
- type="hidden"
- name="prev_encryption_mode"
- id="prev_encryption_mode"
- value="<?php echo $_['encryption_mode']; ?>"
- >
-
- <input
- type="radio"
- name="encryption_mode"
- value="client"
- id='client_encryption'
- style="width:20px;"
- <?php if ($_['encryption_mode'] == 'client') echo "checked='checked'"?>
- />
- <?php echo $l->t('Client side encryption (most secure but makes it impossible to access your data from the web interface)'); ?>
- <br />
-
- <input
- type="radio"
- name="encryption_mode"
- value="server"
- id='server_encryption'
- style="width:20px;" <?php if ($_['encryption_mode'] == 'server') echo "checked='checked'"?>
- />
- <?php echo $l->t('Server side encryption (allows you to access your files from the web interface and the desktop client)'); ?>
- <br />
-
- <input
- type="radio"
- name="encryption_mode"
- value="none"
- id='none_encryption'
- style="width:20px;"
- <?php if ($_['encryption_mode'] == 'none') echo "checked='checked'"?>
- />
- <?php echo $l->t('None (no encryption at all)'); ?>
- <br/>
+ <?php echo $l->t( 'File encryption is enabled.' ); ?>
</p>
+ <?php if ( ! empty( $_["blacklist"] ) ): ?>
+ <p>
+ <?php $l->t( 'The following file types will not be encrypted:' ); ?>
+ </p>
+ <ul>
+ <?php foreach( $_["blacklist"] as $type ): ?>
+ <li>
+ <?php echo $type; ?>
+ </li>
+ <?php endforeach; ?>
+ </p>
+ <?php endif; ?>
</fieldset>
</form>
diff --git a/apps/files_encryption/templates/settings.php b/apps/files_encryption/templates/settings.php index 544ec793f37..f7ef8a8efe6 100644 --- a/apps/files_encryption/templates/settings.php +++ b/apps/files_encryption/templates/settings.php @@ -1,77 +1,18 @@ <form id="encryption"> <fieldset class="personalblock"> - <strong> - <?php echo $l->t('Choose encryption mode:'); ?> - </strong> - - <p> - <i> - <?php echo $l->t('Important: Once you selected an encryption mode there is no way to change it back'); ?> - </i> - </p> - <p> - <input - type="radio" - name="encryption_mode" - id="client_encryption" - value="client" - style="width:20px;" - <?php if ($_['encryption_mode'] == 'client') echo "checked='checked'"; if ($_['encryption_mode'] != 'none') echo "DISABLED"?> - /> + <strong><?php echo $l->t( 'Encryption' ); ?></strong> - <?php echo $l->t("Client side encryption (most secure but makes it impossible to access your data from the web interface)"); ?> + <?php echo $l->t( "Exclude the following file types from encryption:" ); ?> <br /> - <input - type="radio" - name="encryption_mode" - id="server_encryption" - value="server" - style="width:20px;" - <?php if ($_['encryption_mode'] == 'server') echo "checked='checked'"; if ($_['encryption_mode'] != 'none') echo "DISABLED"?> - /> - - <?php echo $l->t('Server side encryption (allows you to access your files from the web interface and the desktop client)'); ?> - <br /> - - <input - type="radio" - name="encryption_mode" - id="user_encryption" - value="user" - style="width:20px;" - <?php if ($_['encryption_mode'] == 'user') echo "checked='checked'"; if ($_['encryption_mode'] != 'none') echo "DISABLED"?> - /> - - <?php echo $l->t('User specific (let the user decide)'); ?> - <br/> - - <input - type="radio" - name="encryption_mode" - id="none_encryption" - value="none" - style="width:20px;" - <?php if ($_['encryption_mode'] == 'none') echo "checked='checked'"; if ($_['encryption_mode'] != 'none') echo "DISABLED"?> - /> - - <?php echo $l->t('None (no encryption at all)'); ?> - <br/> - - </p> - <p> - <strong><?php echo $l->t('Encryption'); ?></strong> - - <?php echo $l->t("Exclude the following file types from encryption"); ?> - <select id='encryption_blacklist' - title="<?php echo $l->t('None')?>" + title="<?php echo $l->t( 'None' )?>" multiple="multiple"> <?php foreach($_["blacklist"] as $type): ?> - <option selected="selected" value="<?php echo $type;?>"> <?php echo $type;?> </option> + <option selected="selected" value="<?php echo $type; ?>"> <?php echo $type; ?> </option> <?php endforeach;?> </select> </p> diff --git a/apps/files_encryption/test/crypt.php b/apps/files_encryption/test/crypt.php index 19c10ab0ab5..aa87ec32821 100755 --- a/apps/files_encryption/test/crypt.php +++ b/apps/files_encryption/test/crypt.php @@ -416,13 +416,13 @@ class Test_Crypt extends \PHPUnit_Framework_TestCase { function testIsEncryptedContent() { - $this->assertFalse( Encryption\Crypt::isEncryptedContent( $this->dataUrl ) ); + $this->assertFalse( Encryption\Crypt::isCatfile( $this->dataUrl ) ); - $this->assertFalse( Encryption\Crypt::isEncryptedContent( $this->legacyEncryptedData ) ); + $this->assertFalse( Encryption\Crypt::isCatfile( $this->legacyEncryptedData ) ); $keyfileContent = Encryption\Crypt::symmetricEncryptFileContent( $this->dataUrl, 'hat' ); - $this->assertTrue( Encryption\Crypt::isEncryptedContent( $keyfileContent ) ); + $this->assertTrue( Encryption\Crypt::isCatfile( $keyfileContent ) ); } diff --git a/apps/files_encryption/test/keymanager.php b/apps/files_encryption/test/keymanager.php index f02d6eb5f7a..bf453fe3163 100644 --- a/apps/files_encryption/test/keymanager.php +++ b/apps/files_encryption/test/keymanager.php @@ -79,15 +79,13 @@ class Test_Keymanager extends \PHPUnit_Framework_TestCase { # NOTE: This cannot be tested until we are able to break out # of the FileSystemView data directory root -// $key = Crypt::symmetricEncryptFileContentKeyfile( $this->data, 'hat' ); -// -// $tmpPath = sys_get_temp_dir(). '/' . 'testSetFileKey'; -// -// $view = new \OC_FilesystemView( '/tmp/' ); -// -// //$view = new \OC_FilesystemView( '/' . $this->userId . '/files_encryption/keyfiles' ); -// -// Encryption\Keymanager::setFileKey( $tmpPath, $key['key'], $view ); + $key = Encryption\Crypt::symmetricEncryptFileContentKeyfile( $this->randomKey, 'hat' ); + + $path = 'unittest-'.time().'txt'; + + //$view = new \OC_FilesystemView( '/' . $this->userId . '/files_encryption/keyfiles' ); + + Encryption\Keymanager::setFileKey( $this->view, $path, $this->userId, $key['key'] ); } diff --git a/apps/files_encryption/test/util.php b/apps/files_encryption/test/util.php index a299ec67f59..1cdeff8008d 100755 --- a/apps/files_encryption/test/util.php +++ b/apps/files_encryption/test/util.php @@ -51,7 +51,7 @@ class Test_Enc_Util extends \PHPUnit_Framework_TestCase { $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 - $this->view = new OC_FilesystemView( '/admin' ); + $this->view = new \OC_FilesystemView( '/' ); $this->mockView = m::mock('OC_FilesystemView'); $this->util = new Encryption\Util( $this->mockView, $this->userId ); @@ -88,8 +88,8 @@ class Test_Enc_Util extends \PHPUnit_Framework_TestCase { $mockView = m::mock('OC_FilesystemView'); - $mockView->shouldReceive( 'file_exists' )->times(4)->andReturn( false ); - $mockView->shouldReceive( 'mkdir' )->times(3)->andReturn( true ); + $mockView->shouldReceive( 'file_exists' )->times(5)->andReturn( false ); + $mockView->shouldReceive( 'mkdir' )->times(4)->andReturn( true ); $mockView->shouldReceive( 'file_put_contents' )->withAnyArgs(); $util = new Encryption\Util( $mockView, $this->userId ); @@ -105,7 +105,7 @@ class Test_Enc_Util extends \PHPUnit_Framework_TestCase { $mockView = m::mock('OC_FilesystemView'); - $mockView->shouldReceive( 'file_exists' )->times(5)->andReturn( true ); + $mockView->shouldReceive( 'file_exists' )->times(6)->andReturn( true ); $mockView->shouldReceive( 'file_put_contents' )->withAnyArgs(); $util = new Encryption\Util( $mockView, $this->userId ); @@ -149,6 +149,21 @@ class Test_Enc_Util extends \PHPUnit_Framework_TestCase { # then false will be returned. Use strict ordering? } + + function testFindFiles() { + +// $this->view->chroot( "/data/{$this->userId}/files" ); + + $util = new Encryption\Util( $this->view, $this->userId ); + + $files = $util->findFiles( '/', 'encrypted' ); + + var_dump( $files ); + + # TODO: Add more tests here to check that if any of the dirs are + # then false will be returned. Use strict ordering? + + } // /** // * @brief test decryption using legacy blowfish method |