reformat code added and changed phpdoc

This commit is contained in:
Florin Peter 2013-05-20 01:24:36 +02:00
parent b1d0e8f40b
commit 3b850a2524
11 changed files with 3175 additions and 2935 deletions

View File

@ -27,24 +27,20 @@ namespace OCA\Encryption;
require_once 'Crypt_Blowfish/Blowfish.php'; 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 for common cryptography functionality
*/ */
class Crypt { class Crypt
{
/** /**
* @brief return encryption mode client or server side encryption * @brief return encryption mode client or server side encryption
* @param string user name (use system wide setting if name=null) * @param string $user name (use system wide setting if name=null)
* @return string 'client' or 'server' * @return string 'client' or 'server'
*/ */
public static function mode( $user = null ) { public static function mode($user = null)
{
return 'server'; return 'server';
@ -54,7 +50,8 @@ class Crypt {
* @brief Create a new encryption keypair * @brief Create a new encryption keypair
* @return array publicKey, privatekey * @return array publicKey, privatekey
*/ */
public static function createKeypair() { public static function createKeypair()
{
$res = openssl_pkey_new(array('private_key_bits' => 4096)); $res = openssl_pkey_new(array('private_key_bits' => 4096));
@ -73,13 +70,14 @@ class Crypt {
/** /**
* @brief Add arbitrary padding to encrypted data * @brief Add arbitrary padding to encrypted data
* @param string $data data to be padded * @param string $data data to be padded
* @return padded data * @return string padded data
* @note In order to end up with data exactly 8192 bytes long we must * @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 * add two letters. It is impossible to achieve exactly 8192 length
* blocks with encryption alone, hence padding is added to achieve the * blocks with encryption alone, hence padding is added to achieve the
* required length. * required length.
*/ */
public static function addPadding( $data ) { public static function addPadding($data)
{
$padded = $data . 'xx'; $padded = $data . 'xx';
@ -90,9 +88,10 @@ class Crypt {
/** /**
* @brief Remove arbitrary padding to encrypted data * @brief Remove arbitrary padding to encrypted data
* @param string $padded padded data to remove padding from * @param string $padded padded data to remove padding from
* @return unpadded data on success, false on error * @return string unpadded data on success, false on error
*/ */
public static function removePadding( $padded ) { public static function removePadding($padded)
{
if (substr($padded, -2) == 'xx') { if (substr($padded, -2) == 'xx') {
@ -111,10 +110,12 @@ class Crypt {
/** /**
* @brief Check if a file's contents contains an IV and is symmetrically encrypted * @brief Check if a file's contents contains an IV and is symmetrically encrypted
* @return true / false * @param $content
* @return boolean
* @note see also OCA\Encryption\Util->isEncryptedPath() * @note see also OCA\Encryption\Util->isEncryptedPath()
*/ */
public static function isCatfileContent( $content ) { public static function isCatfileContent($content)
{
if (!$content) { if (!$content) {
@ -150,7 +151,8 @@ class Crypt {
* @param string $path * @param string $path
* @return bool * @return bool
*/ */
public static function isEncryptedMeta( $path ) { public static function isEncryptedMeta($path)
{
// TODO: Use DI to get \OC\Files\Filesystem out of here // TODO: Use DI to get \OC\Files\Filesystem out of here
@ -164,11 +166,13 @@ class Crypt {
/** /**
* @brief Check if a file is encrypted via legacy system * @brief Check if a file is encrypted via legacy system
* @param $data
* @param string $relPath The path of the file, relative to user/data; * @param string $relPath The path of the file, relative to user/data;
* e.g. filename or /Docs/filename, NOT admin/files/filename * e.g. filename or /Docs/filename, NOT admin/files/filename
* @return true / false * @return boolean
*/ */
public static function isLegacyEncryptedContent( $data, $relPath ) { public static function isLegacyEncryptedContent($data, $relPath)
{
// Fetch all file metadata from DB // Fetch all file metadata from DB
$metadata = \OC\Files\Filesystem::getFileInfo($relPath, ''); $metadata = \OC\Files\Filesystem::getFileInfo($relPath, '');
@ -194,9 +198,10 @@ class Crypt {
/** /**
* @brief Symmetrically encrypt a string * @brief Symmetrically encrypt a string
* @returns encrypted file * @return string encrypted file content
*/ */
public static function encrypt( $plainContent, $iv, $passphrase = '' ) { public static function encrypt($plainContent, $iv, $passphrase = '')
{
if ($encryptedContent = openssl_encrypt($plainContent, 'AES-128-CFB', $passphrase, false, $iv)) { if ($encryptedContent = openssl_encrypt($plainContent, 'AES-128-CFB', $passphrase, false, $iv)) {
@ -214,9 +219,10 @@ class Crypt {
/** /**
* @brief Symmetrically decrypt a string * @brief Symmetrically decrypt a string
* @returns decrypted file * @return string decrypted file content
*/ */
public static function decrypt( $encryptedContent, $iv, $passphrase ) { public static function decrypt($encryptedContent, $iv, $passphrase)
{
if ($plainContent = openssl_decrypt($encryptedContent, 'AES-128-CFB', $passphrase, false, $iv)) { if ($plainContent = openssl_decrypt($encryptedContent, 'AES-128-CFB', $passphrase, false, $iv)) {
@ -239,7 +245,8 @@ class Crypt {
* @param string $iv IV to be concatenated * @param string $iv IV to be concatenated
* @returns string concatenated content * @returns string concatenated content
*/ */
public static function concatIv ( $content, $iv ) { public static function concatIv($content, $iv)
{
$combined = $content . '00iv00' . $iv; $combined = $content . '00iv00' . $iv;
@ -252,7 +259,8 @@ class Crypt {
* @param string $catFile concatenated data to be split * @param string $catFile concatenated data to be split
* @returns array keys: encrypted, iv * @returns array keys: encrypted, iv
*/ */
public static function splitIv ( $catFile ) { public static function splitIv($catFile)
{
// Fetch encryption metadata from end of file // Fetch encryption metadata from end of file
$meta = substr($catFile, -22); $meta = substr($catFile, -22);
@ -274,12 +282,15 @@ class Crypt {
/** /**
* @brief Symmetrically encrypts a string and returns keyfile content * @brief Symmetrically encrypts a string and returns keyfile content
* @param $plainContent content to be encrypted in keyfile * @param string $plainContent content to be encrypted in keyfile
* @returns encrypted content combined with IV * @param string $passphrase
* @return bool|string
* @return string encrypted content combined with IV
* @note IV need not be specified, as it will be stored in the returned keyfile * @note IV need not be specified, as it will be stored in the returned keyfile
* and remain accessible therein. * and remain accessible therein.
*/ */
public static function symmetricEncryptFileContent( $plainContent, $passphrase = '' ) { public static function symmetricEncryptFileContent($plainContent, $passphrase = '')
{
if (!$plainContent) { if (!$plainContent) {
@ -311,14 +322,19 @@ class Crypt {
/** /**
* @brief Symmetrically decrypts keyfile content * @brief Symmetrically decrypts keyfile content
* @param string $source * @param $keyfileContent
* @param string $target * @param string $passphrase
* @param string $key the decryption key * @throws \Exception
* @returns decrypted content * @return bool|string
* @internal param string $source
* @internal param string $target
* @internal param string $key the decryption key
* @returns string decrypted content
* *
* This function decrypts a file * This function decrypts a file
*/ */
public static function symmetricDecryptFileContent( $keyfileContent, $passphrase = '' ) { public static function symmetricDecryptFileContent($keyfileContent, $passphrase = '')
{
if (!$keyfileContent) { if (!$keyfileContent) {
@ -348,7 +364,8 @@ class Crypt {
* *
* This function decrypts a file * This function decrypts a file
*/ */
public static function symmetricEncryptFileContentKeyfile( $plainContent ) { public static function symmetricEncryptFileContentKeyfile($plainContent)
{
$key = self::generateKey(); $key = self::generateKey();
@ -374,7 +391,8 @@ class Crypt {
* @returns array keys: keys (array, key = userId), data * @returns array keys: keys (array, key = userId), data
* @note symmetricDecryptFileContent() can decrypt files created using this method * @note symmetricDecryptFileContent() can decrypt files created using this method
*/ */
public static function multiKeyEncrypt( $plainContent, array $publicKeys ) { public static function multiKeyEncrypt($plainContent, array $publicKeys)
{
// openssl_seal returns false without errors if $plainContent // openssl_seal returns false without errors if $plainContent
// is empty, so trigger our own error // is empty, so trigger our own error
@ -417,13 +435,18 @@ class Crypt {
/** /**
* @brief Asymmetrically encrypt a file using multiple public keys * @brief Asymmetrically encrypt a file using multiple public keys
* @param string $plainContent content to be encrypted * @param $encryptedContent
* @param $shareKey
* @param $privateKey
* @return bool
* @internal param string $plainContent content to be encrypted
* @returns string $plainContent decrypted string * @returns string $plainContent decrypted string
* @note symmetricDecryptFileContent() can be used to decrypt files created using this method * @note symmetricDecryptFileContent() can be used to decrypt files created using this method
* *
* This function decrypts a file * This function decrypts a file
*/ */
public static function multiKeyDecrypt( $encryptedContent, $shareKey, $privateKey ) { public static function multiKeyDecrypt($encryptedContent, $shareKey, $privateKey)
{
if (!$encryptedContent) { if (!$encryptedContent) {
@ -447,9 +470,10 @@ class Crypt {
/** /**
* @brief Asymetrically encrypt a string using a public key * @brief Asymetrically encrypt a string using a public key
* @returns encrypted file * @return string encrypted file
*/ */
public static function keyEncrypt( $plainContent, $publicKey ) { public static function keyEncrypt($plainContent, $publicKey)
{
openssl_public_encrypt($plainContent, $encryptedContent, $publicKey); openssl_public_encrypt($plainContent, $encryptedContent, $publicKey);
@ -459,9 +483,10 @@ class Crypt {
/** /**
* @brief Asymetrically decrypt a file using a private key * @brief Asymetrically decrypt a file using a private key
* @returns decrypted file * @return string decrypted file
*/ */
public static function keyDecrypt( $encryptedContent, $privatekey ) { public static function keyDecrypt($encryptedContent, $privatekey)
{
$result = @openssl_private_decrypt($encryptedContent, $plainContent, $privatekey); $result = @openssl_private_decrypt($encryptedContent, $plainContent, $privatekey);
@ -477,7 +502,8 @@ class Crypt {
* @brief Generates a pseudo random initialisation vector * @brief Generates a pseudo random initialisation vector
* @return String $iv generated IV * @return String $iv generated IV
*/ */
public static function generateIv() { public static function generateIv()
{
if ($random = openssl_random_pseudo_bytes(12, $strong)) { if ($random = openssl_random_pseudo_bytes(12, $strong)) {
@ -496,7 +522,7 @@ class Crypt {
} else { } else {
throw new Exception( 'Generating IV failed' ); throw new \Exception('Generating IV failed');
} }
@ -506,7 +532,8 @@ class Crypt {
* @brief Generate a pseudo random 1024kb ASCII key * @brief Generate a pseudo random 1024kb ASCII key
* @returns $key Generated key * @returns $key Generated key
*/ */
public static function generateKey() { public static function generateKey()
{
// Generate key // Generate key
if ($key = base64_encode(openssl_random_pseudo_bytes(183, $strong))) { if ($key = base64_encode(openssl_random_pseudo_bytes(183, $strong))) {
@ -514,7 +541,7 @@ class Crypt {
if (!$strong) { if (!$strong) {
// If OpenSSL indicates randomness is insecure, log error // If OpenSSL indicates randomness is insecure, log error
throw new Exception ( 'Encryption library, Insecure symmetric key was generated using openssl_random_pseudo_bytes()' ); throw new \Exception('Encryption library, Insecure symmetric key was generated using openssl_random_pseudo_bytes()');
} }
@ -535,7 +562,8 @@ class Crypt {
* *
* if the key is left out, the default handeler will be used * if the key is left out, the default handeler will be used
*/ */
public static function getBlowfish( $key = '' ) { public static function getBlowfish($key = '')
{
if ($key) { if ($key) {
@ -549,7 +577,12 @@ class Crypt {
} }
public static function legacyCreateKey( $passphrase ) { /**
* @param $passphrase
* @return mixed
*/
public static function legacyCreateKey($passphrase)
{
// Generate a random integer // Generate a random integer
$key = mt_rand(10000, 99999) . mt_rand(10000, 99999) . mt_rand(10000, 99999) . mt_rand(10000, 99999); $key = mt_rand(10000, 99999) . mt_rand(10000, 99999) . mt_rand(10000, 99999) . mt_rand(10000, 99999);
@ -563,13 +596,16 @@ class Crypt {
/** /**
* @brief encrypts content using legacy blowfish system * @brief encrypts content using legacy blowfish system
* @param $content the cleartext message you want to encrypt * @param string $content the cleartext message you want to encrypt
* @param $key the encryption key (optional) * @param string $passphrase
* @returns encrypted content * @return
* @internal param \OCA\Encryption\the $key encryption key (optional)
* @returns string encrypted content
* *
* This function encrypts an content * This function encrypts an content
*/ */
public static function legacyEncrypt( $content, $passphrase = '' ) { public static function legacyEncrypt($content, $passphrase = '')
{
$bf = self::getBlowfish($passphrase); $bf = self::getBlowfish($passphrase);
@ -579,13 +615,16 @@ class Crypt {
/** /**
* @brief decrypts content using legacy blowfish system * @brief decrypts content using legacy blowfish system
* @param $content the cleartext message you want to decrypt * @param string $content the cleartext message you want to decrypt
* @param $key the encryption key (optional) * @param string $passphrase
* @returns cleartext content * @return string
* @internal param \OCA\Encryption\the $key encryption key (optional)
* @return string cleartext content
* *
* This function decrypts an content * This function decrypts an content
*/ */
public static function legacyDecrypt( $content, $passphrase = '' ) { public static function legacyDecrypt($content, $passphrase = '')
{
$bf = self::getBlowfish($passphrase); $bf = self::getBlowfish($passphrase);
@ -595,7 +634,14 @@ class Crypt {
} }
private static function legacyBlockDecrypt($data, $key='',$maxLength=0) { /**
* @param $data
* @param string $key
* @param int $maxLength
* @return string
*/
private static function legacyBlockDecrypt($data, $key = '', $maxLength = 0)
{
$result = ''; $result = '';
while (strlen($data)) { while (strlen($data)) {
$result .= self::legacyDecrypt(substr($data, 0, 8192), $key); $result .= self::legacyDecrypt(substr($data, 0, 8192), $key);
@ -608,7 +654,16 @@ class Crypt {
} }
} }
public static function legacyKeyRecryptKeyfile( $legacyEncryptedContent, $legacyPassphrase, $publicKeys, $newPassphrase, $path ) { /**
* @param $legacyEncryptedContent
* @param $legacyPassphrase
* @param $publicKeys
* @param $newPassphrase
* @param $path
* @return array
*/
public static function legacyKeyRecryptKeyfile($legacyEncryptedContent, $legacyPassphrase, $publicKeys, $newPassphrase, $path)
{
$decrypted = self::legacyBlockDecrypt($legacyEncryptedContent, $legacyPassphrase); $decrypted = self::legacyBlockDecrypt($legacyEncryptedContent, $legacyPassphrase);

View File

@ -30,13 +30,15 @@ namespace OCA\Encryption;
* Class Helper * Class Helper
* @package OCA\Encryption * @package OCA\Encryption
*/ */
class Helper { class Helper
{
/** /**
* @brief register share related hooks * @brief register share related hooks
* *
*/ */
public static function registerShareHooks() { public static function registerShareHooks()
{
\OCP\Util::connectHook('OCP\Share', 'pre_shared', 'OCA\Encryption\Hooks', 'preShared'); \OCP\Util::connectHook('OCP\Share', 'pre_shared', 'OCA\Encryption\Hooks', 'preShared');
\OCP\Util::connectHook('OCP\Share', 'post_shared', 'OCA\Encryption\Hooks', 'postShared'); \OCP\Util::connectHook('OCP\Share', 'post_shared', 'OCA\Encryption\Hooks', 'postShared');
@ -47,7 +49,8 @@ class Helper {
* @brief register user related hooks * @brief register user related hooks
* *
*/ */
public static function registerUserHooks() { public static function registerUserHooks()
{
\OCP\Util::connectHook('OC_User', 'post_login', 'OCA\Encryption\Hooks', 'login'); \OCP\Util::connectHook('OC_User', 'post_login', 'OCA\Encryption\Hooks', 'login');
\OCP\Util::connectHook('OC_User', 'post_setPassword', 'OCA\Encryption\Hooks', 'setPassphrase'); \OCP\Util::connectHook('OC_User', 'post_setPassword', 'OCA\Encryption\Hooks', 'setPassphrase');
@ -59,7 +62,8 @@ class Helper {
* @brief register webdav related hooks * @brief register webdav related hooks
* *
*/ */
public static function registerWebdavHooks() { public static function registerWebdavHooks()
{
} }
@ -68,7 +72,8 @@ class Helper {
* @brief register filesystem related hooks * @brief register filesystem related hooks
* *
*/ */
public static function registerFilesystemHooks() { public static function registerFilesystemHooks()
{
\OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OCA\Encryption\Hooks', 'postRename'); \OCP\Util::connectHook('OC_Filesystem', 'post_rename', 'OCA\Encryption\Hooks', 'postRename');
} }
@ -80,7 +85,8 @@ class Helper {
* @param string $password * @param string $password
* @return bool * @return bool
*/ */
public static function setupUser($util, $password) { public static function setupUser($util, $password)
{
// Check files_encryption infrastructure is ready for action // Check files_encryption infrastructure is ready for action
if (!$util->ready()) { if (!$util->ready()) {
@ -103,7 +109,8 @@ class Helper {
* @internal param string $password * @internal param string $password
* @return bool * @return bool
*/ */
public static function adminEnableRecovery($recoveryKeyId, $recoveryPassword) { public static function adminEnableRecovery($recoveryKeyId, $recoveryPassword)
{
$view = new \OC\Files\View('/'); $view = new \OC\Files\View('/');
if ($recoveryKeyId === null) { if ($recoveryKeyId === null) {
@ -170,7 +177,8 @@ class Helper {
* @param $recoveryPassword * @param $recoveryPassword
* @return bool * @return bool
*/ */
public static function adminDisableRecovery($recoveryPassword) { public static function adminDisableRecovery($recoveryPassword)
{
$util = new Util(new \OC_FilesystemView('/'), \OCP\User::getUser()); $util = new Util(new \OC_FilesystemView('/'), \OCP\User::getUser());
$return = $util->checkRecoveryPassword($recoveryPassword); $return = $util->checkRecoveryPassword($recoveryPassword);

View File

@ -27,7 +27,8 @@ namespace OCA\Encryption;
* @brief Class to manage storage and retrieval of encryption keys * @brief Class to manage storage and retrieval of encryption keys
* @note Where a method requires a view object, it's root must be '/' * @note Where a method requires a view object, it's root must be '/'
*/ */
class Keymanager { class Keymanager
{
/** /**
* @brief retrieve the ENCRYPTED private key from a user * @brief retrieve the ENCRYPTED private key from a user
@ -37,7 +38,8 @@ class Keymanager {
* @return string private key or false (hopefully) * @return string private key or false (hopefully)
* @note the key returned by this method must be decrypted before use * @note the key returned by this method must be decrypted before use
*/ */
public static function getPrivateKey( \OC_FilesystemView $view, $user ) { public static function getPrivateKey(\OC_FilesystemView $view, $user)
{
$path = '/' . $user . '/' . 'files_encryption' . '/' . $user . '.private.key'; $path = '/' . $user . '/' . 'files_encryption' . '/' . $user . '.private.key';
@ -57,7 +59,8 @@ class Keymanager {
* @param $userId * @param $userId
* @return string public key or false * @return string public key or false
*/ */
public static function getPublicKey( \OC_FilesystemView $view, $userId ) { public static function getPublicKey(\OC_FilesystemView $view, $userId)
{
$proxyStatus = \OC_FileProxy::$enabled; $proxyStatus = \OC_FileProxy::$enabled;
\OC_FileProxy::$enabled = false; \OC_FileProxy::$enabled = false;
@ -76,7 +79,8 @@ class Keymanager {
* @param $userId * @param $userId
* @return array keys: privateKey, publicKey * @return array keys: privateKey, publicKey
*/ */
public static function getUserKeys( \OC_FilesystemView $view, $userId ) { public static function getUserKeys(\OC_FilesystemView $view, $userId)
{
return array( return array(
'publicKey' => self::getPublicKey($view, $userId) 'publicKey' => self::getPublicKey($view, $userId)
@ -91,7 +95,8 @@ class Keymanager {
* @param array $userIds * @param array $userIds
* @return array of public keys for the specified users * @return array of public keys for the specified users
*/ */
public static function getPublicKeys( \OC_FilesystemView $view, array $userIds ) { public static function getPublicKeys(\OC_FilesystemView $view, array $userIds)
{
$keys = array(); $keys = array();
@ -108,13 +113,17 @@ class Keymanager {
/** /**
* @brief store file encryption key * @brief store file encryption key
* *
* @param \OC_FilesystemView $view
* @param string $path relative path of the file, including filename * @param string $path relative path of the file, including filename
* @param string $key * @param $userId
* @param $catfile
* @internal param string $key
* @return bool true/false * @return bool true/false
* @note The keyfile is not encrypted here. Client code must * @note The keyfile is not encrypted here. Client code must
* asymmetrically encrypt the keyfile before passing it to this method * asymmetrically encrypt the keyfile before passing it to this method
*/ */
public static function setFileKey( \OC_FilesystemView $view, $path, $userId, $catfile ) { public static function setFileKey(\OC_FilesystemView $view, $path, $userId, $catfile)
{
$proxyStatus = \OC_FileProxy::$enabled; $proxyStatus = \OC_FileProxy::$enabled;
\OC_FileProxy::$enabled = false; \OC_FileProxy::$enabled = false;
@ -163,7 +172,8 @@ class Keymanager {
* @return string File path without .part extension * @return string File path without .part extension
* @note this is needed for reusing keys * @note this is needed for reusing keys
*/ */
public static function fixPartialFilePath( $path ) { public static function fixPartialFilePath($path)
{
if (preg_match('/\.part$/', $path)) { if (preg_match('/\.part$/', $path)) {
@ -185,7 +195,8 @@ class Keymanager {
* @param string $path Path that may identify a .part file * @param string $path Path that may identify a .part file
* @return bool * @return bool
*/ */
public static function isPartialFilePath( $path ) { public static function isPartialFilePath($path)
{
if (preg_match('/\.part$/', $path)) { if (preg_match('/\.part$/', $path)) {
@ -198,6 +209,7 @@ class Keymanager {
} }
} }
/** /**
* @brief retrieve keyfile for an encrypted file * @brief retrieve keyfile for an encrypted file
* @param \OC_FilesystemView $view * @param \OC_FilesystemView $view
@ -208,7 +220,8 @@ class Keymanager {
* @note The keyfile returned is asymmetrically encrypted. Decryption * @note The keyfile returned is asymmetrically encrypted. Decryption
* of the keyfile must be performed by client code * of the keyfile must be performed by client code
*/ */
public static function getFileKey( \OC_FilesystemView $view, $userId, $filePath ) { public static function getFileKey(\OC_FilesystemView $view, $userId, $filePath)
{
// try reusing key file if part file // try reusing key file if part file
if (self::isPartialFilePath($filePath)) { if (self::isPartialFilePath($filePath)) {
@ -251,14 +264,15 @@ class Keymanager {
/** /**
* @brief Delete a keyfile * @brief Delete a keyfile
* *
* @param OC_FilesystemView $view * @param \OC_FilesystemView $view
* @param string $userId username * @param string $userId username
* @param string $path path of the file the key belongs to * @param string $path path of the file the key belongs to
* @return bool Outcome of unlink operation * @return bool Outcome of unlink operation
* @note $path must be relative to data/user/files. e.g. mydoc.txt NOT * @note $path must be relative to data/user/files. e.g. mydoc.txt NOT
* /data/admin/files/mydoc.txt * /data/admin/files/mydoc.txt
*/ */
public static function deleteFileKey( \OC_FilesystemView $view, $userId, $path ) { public static function deleteFileKey(\OC_FilesystemView $view, $userId, $path)
{
$trimmed = ltrim($path, '/'); $trimmed = ltrim($path, '/');
$keyPath = '/' . $userId . '/files_encryption/keyfiles/' . $trimmed; $keyPath = '/' . $userId . '/files_encryption/keyfiles/' . $trimmed;
@ -287,12 +301,13 @@ class Keymanager {
/** /**
* @brief store private key from the user * @brief store private key from the user
* @param string key * @param string $key
* @return bool * @return bool
* @note Encryption of the private key must be performed by client code * @note Encryption of the private key must be performed by client code
* as no encryption takes place here * as no encryption takes place here
*/ */
public static function setPrivateKey( $key ) { public static function setPrivateKey($key)
{
$user = \OCP\User::getUser(); $user = \OCP\User::getUser();
@ -314,11 +329,12 @@ class Keymanager {
/** /**
* @brief store private keys from the user * @brief store private keys from the user
* *
* @param string privatekey * @param string $privatekey
* @param string publickey * @param string $publickey
* @return bool true/false * @return bool true/false
*/ */
public static function setUserKeys($privatekey, $publickey) { public static function setUserKeys($privatekey, $publickey)
{
return (self::setPrivateKey($privatekey) && self::setPublicKey($publickey)); return (self::setPrivateKey($privatekey) && self::setPublicKey($publickey));
@ -327,10 +343,11 @@ class Keymanager {
/** /**
* @brief store public key of the user * @brief store public key of the user
* *
* @param string key * @param string $key
* @return bool true/false * @return bool true/false
*/ */
public static function setPublicKey( $key ) { public static function setPublicKey($key)
{
$view = new \OC_FilesystemView('/public-keys'); $view = new \OC_FilesystemView('/public-keys');
@ -350,15 +367,18 @@ class Keymanager {
/** /**
* @brief store share key * @brief store share key
* *
* @param \OC_FilesystemView $view
* @param string $path relative path of the file, including filename * @param string $path relative path of the file, including filename
* @param string $key * @param $userId
* @param null $view * @param $shareKey
* @param string $dbClassName * @internal param string $key
* @internal param string $dbClassName
* @return bool true/false * @return bool true/false
* @note The keyfile is not encrypted here. Client code must * @note The keyfile is not encrypted here. Client code must
* asymmetrically encrypt the keyfile before passing it to this method * asymmetrically encrypt the keyfile before passing it to this method
*/ */
public static function setShareKey( \OC_FilesystemView $view, $path, $userId, $shareKey ) { public static function setShareKey(\OC_FilesystemView $view, $path, $userId, $shareKey)
{
// Here we need the currently logged in user, while userId can be a different user // Here we need the currently logged in user, while userId can be a different user
$util = new Util($view, \OCP\User::getUser()); $util = new Util($view, \OCP\User::getUser());
@ -404,9 +424,13 @@ class Keymanager {
/** /**
* @brief store multiple share keys for a single file * @brief store multiple share keys for a single file
* @param \OC_FilesystemView $view
* @param $path
* @param array $shareKeys
* @return bool * @return bool
*/ */
public static function setShareKeys( \OC_FilesystemView $view, $path, array $shareKeys ) { public static function setShareKeys(\OC_FilesystemView $view, $path, array $shareKeys)
{
// $shareKeys must be an array with the following format: // $shareKeys must be an array with the following format:
// [userId] => [encrypted key] // [userId] => [encrypted key]
@ -439,7 +463,8 @@ class Keymanager {
* @note The sharekey returned is encrypted. Decryption * @note The sharekey returned is encrypted. Decryption
* of the keyfile must be performed by client code * of the keyfile must be performed by client code
*/ */
public static function getShareKey( \OC_FilesystemView $view, $userId, $filePath ) { public static function getShareKey(\OC_FilesystemView $view, $userId, $filePath)
{
// try reusing key file if part file // try reusing key file if part file
if (self::isPartialFilePath($filePath)) { if (self::isPartialFilePath($filePath)) {
@ -482,10 +507,11 @@ class Keymanager {
/** /**
* @brief delete all share keys of a given file * @brief delete all share keys of a given file
* @param \OC_FilesystemView $view * @param \OC_FilesystemView $view
* @param type $userId owner of the file * @param string $userId owner of the file
* @param type $filePath path to the file, relative to the owners file dir * @param string $filePath path to the file, relative to the owners file dir
*/ */
public static function delAllShareKeys(\OC_FilesystemView $view, $userId, $filePath) { public static function delAllShareKeys(\OC_FilesystemView $view, $userId, $filePath)
{
if ($view->is_dir($userId . '/files/' . $filePath)) { if ($view->is_dir($userId . '/files/' . $filePath)) {
$view->unlink($userId . '/files_encryption/share-keys/' . $filePath); $view->unlink($userId . '/files_encryption/share-keys/' . $filePath);
@ -501,7 +527,8 @@ class Keymanager {
/** /**
* @brief Delete a single user's shareKey for a single file * @brief Delete a single user's shareKey for a single file
*/ */
public static function delShareKey( \OC_FilesystemView $view, $userIds, $filePath ) { public static function delShareKey(\OC_FilesystemView $view, $userIds, $filePath)
{
$proxyStatus = \OC_FileProxy::$enabled; $proxyStatus = \OC_FileProxy::$enabled;
\OC_FileProxy::$enabled = false; \OC_FileProxy::$enabled = false;
@ -544,14 +571,16 @@ class Keymanager {
/** /**
* @brief recursively delete share keys from given users * @brief recursively delete share keys from given users
* *
* @param type $dir directory * @param string $dir directory
* @param type $userIds user ids for which the share keys should be deleted * @param array $userIds user ids for which the share keys should be deleted
*/ */
private static function recursiveDelShareKeys($dir, $userIds) { private static function recursiveDelShareKeys($dir, $userIds)
{
foreach ($userIds as $userId) { foreach ($userIds as $userId) {
$completePath = $dir . '/.*' . '.' . $userId . '.shareKey'; $completePath = $dir . '/.*' . '.' . $userId . '.shareKey';
$matches = glob(preg_quote($dir) . '/*' . preg_quote('.' . $userId . '.shareKey')); $matches = glob(preg_quote($dir) . '/*' . preg_quote('.' . $userId . '.shareKey'));
} }
/** @var $matches array */
foreach ($matches as $ma) { foreach ($matches as $ma) {
unlink($ma); unlink($ma);
} }
@ -565,7 +594,8 @@ class Keymanager {
/** /**
* @brief Make preparations to vars and filesystem for saving a keyfile * @brief Make preparations to vars and filesystem for saving a keyfile
*/ */
public static function keySetPreparation( \OC_FilesystemView $view, $path, $basePath, $userId ) { public static function keySetPreparation(\OC_FilesystemView $view, $path, $basePath, $userId)
{
$targetPath = ltrim($path, '/'); $targetPath = ltrim($path, '/');
@ -590,31 +620,16 @@ class Keymanager {
} }
/**
* @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 * @brief Fetch the legacy encryption key from user files
* @param string $login used to locate the legacy key * @internal param string $login used to locate the legacy key
* @param string $passphrase used to decrypt the legacy key * @internal param string $passphrase used to decrypt the legacy key
* @return true / false * @return boolean
* *
* if the key is left out, the default handeler will be used * if the key is left out, the default handeler will be used
*/ */
public function getLegacyKey() { public function getLegacyKey()
{
$user = \OCP\User::getUser(); $user = \OCP\User::getUser();
$view = new \OC_FilesystemView('/' . $user); $view = new \OC_FilesystemView('/' . $user);

View File

@ -30,7 +30,12 @@
namespace OCA\Encryption; namespace OCA\Encryption;
class Proxy extends \OC_FileProxy { /**
* Class Proxy
* @package OCA\Encryption
*/
class Proxy extends \OC_FileProxy
{
private static $blackList = null; //mimetypes blacklisted from encryption private static $blackList = null; //mimetypes blacklisted from encryption
@ -43,7 +48,8 @@ class Proxy extends \OC_FileProxy {
* *
* Tests if server side encryption is enabled, and file is allowed by blacklists * Tests if server side encryption is enabled, and file is allowed by blacklists
*/ */
private static function shouldEncrypt( $path ) { private static function shouldEncrypt($path)
{
if (is_null(self::$enableEncryption)) { if (is_null(self::$enableEncryption)) {
@ -91,7 +97,13 @@ class Proxy extends \OC_FileProxy {
return false; return false;
} }
public function preFile_put_contents( $path, &$data ) { /**
* @param $path
* @param $data
* @return bool
*/
public function preFile_put_contents($path, &$data)
{
if (self::shouldEncrypt($path)) { if (self::shouldEncrypt($path)) {
@ -174,7 +186,8 @@ class Proxy extends \OC_FileProxy {
* @param string $path Path of file from which has been read * @param string $path Path of file from which has been read
* @param string $data Data that has been read from file * @param string $data Data that has been read from file
*/ */
public function postFile_get_contents( $path, $data ) { public function postFile_get_contents($path, $data)
{
// FIXME: $path for shared files is just /uid/files/Shared/filepath // FIXME: $path for shared files is just /uid/files/Shared/filepath
@ -236,7 +249,8 @@ class Proxy extends \OC_FileProxy {
/** /**
* @brief When a file is deleted, remove its keyfile also * @brief When a file is deleted, remove its keyfile also
*/ */
public function preUnlink( $path ) { public function preUnlink($path)
{
// let the trashbin handle this // let the trashbin handle this
if (\OCP\App::isEnabled('files_trashbin')) { if (\OCP\App::isEnabled('files_trashbin')) {
@ -280,6 +294,7 @@ class Proxy extends \OC_FileProxy {
/** /**
* @brief When a file is renamed, rename its keyfile also * @brief When a file is renamed, rename its keyfile also
* @param $path
* @return bool Result of rename() * @return bool Result of rename()
* @note This is pre rather than post because using post didn't work * @note This is pre rather than post because using post didn't work
*/ */
@ -290,6 +305,10 @@ class Proxy extends \OC_FileProxy {
return true; return true;
} }
/**
* @param $path
* @return bool
*/
public function postTouch($path) public function postTouch($path)
{ {
$this->handleFile($path); $this->handleFile($path);
@ -297,7 +316,13 @@ class Proxy extends \OC_FileProxy {
return true; return true;
} }
public function postFopen( $path, &$result ){ /**
* @param $path
* @param $result
* @return resource
*/
public function postFopen($path, &$result)
{
if (!$result) { if (!$result) {
@ -343,33 +368,7 @@ class Proxy extends \OC_FileProxy {
and $meta ['mode'] != 'r' and $meta ['mode'] != 'r'
and $meta['mode'] != 'rb' and $meta['mode'] != 'rb'
) { ) {
// If the file is not yet encrypted, but should be
// encrypted when it's saved (it's not read only)
// NOTE: this is the case for new files saved via WebDAV
// if (
// $view->file_exists( $path )
// and $view->filesize( $path ) > 0
// ) {
// $x = $view->file_get_contents( $path );
//
// $tmp = tmpfile();
// // Make a temporary copy of the original file
// \OCP\Files::streamCopy( $result, $tmp );
//
// // Close the original stream, we'll return another one
// fclose( $result );
//
// $view->file_put_contents( $path_f, $tmp );
//
// fclose( $tmp );
// }
$result = fopen('crypt://' . $path_f, $meta['mode']); $result = fopen('crypt://' . $path_f, $meta['mode']);
} }
// Re-enable the proxy // Re-enable the proxy
@ -379,7 +378,13 @@ class Proxy extends \OC_FileProxy {
} }
public function postGetMimeType( $path, $mime ) { /**
* @param $path
* @param $mime
* @return string
*/
public function postGetMimeType($path, $mime)
{
if (Crypt::isCatfileContent($path)) { if (Crypt::isCatfileContent($path)) {
@ -391,7 +396,13 @@ class Proxy extends \OC_FileProxy {
} }
public function postGetFileInfo( $path, $data ) { /**
* @param $path
* @param $data
* @return array
*/
public function postGetFileInfo($path, $data)
{
// if path is a folder do nothing // if path is a folder do nothing
if (is_array($data) && array_key_exists('size', $data)) { if (is_array($data) && array_key_exists('size', $data)) {
@ -410,6 +421,11 @@ class Proxy extends \OC_FileProxy {
return $data; return $data;
} }
/**
* @param $path
* @param $data
* @return mixed
*/
public function postStat($path, $data) public function postStat($path, $data)
{ {
// check if file is encrypted // check if file is encrypted
@ -425,6 +441,11 @@ class Proxy extends \OC_FileProxy {
return $data; return $data;
} }
/**
* @param $path
* @param $size
* @return bool
*/
public function postFileSize($path, $size) public function postFileSize($path, $size)
{ {
@ -470,7 +491,11 @@ class Proxy extends \OC_FileProxy {
return $size; return $size;
} }
public function handleFile($path) { /**
* @param $path
*/
public function handleFile($path)
{
// Disable encryption proxy to prevent recursive calls // Disable encryption proxy to prevent recursive calls
$proxyStatus = \OC_FileProxy::$enabled; $proxyStatus = \OC_FileProxy::$enabled;

View File

@ -26,20 +26,22 @@ namespace OCA\Encryption;
* Class for handling encryption related session data * Class for handling encryption related session data
*/ */
class Session { class Session
{
private $view; private $view;
/** /**
* @brief if session is started, check if ownCloud key pair is set up, if not create it * @brief if session is started, check if ownCloud key pair is set up, if not create it
* @param \OC_FilesystemView $view
* *
* The ownCloud key pair is used to allow public link sharing even if encryption is enabled * @note The ownCloud key pair is used to allow public link sharing even if encryption is enabled
*/ */
public function __construct( $view ) { public function __construct($view)
{
$this->view = $view; $this->view = $view;
if (!$this->view->is_dir('owncloud_private_key')) { if (!$this->view->is_dir('owncloud_private_key')) {
$this->view->mkdir('owncloud_private_key'); $this->view->mkdir('owncloud_private_key');
@ -100,7 +102,8 @@ class Session {
* @param string $privateKey * @param string $privateKey
* @return bool * @return bool
*/ */
public function setPrivateKey( $privateKey ) { public function setPrivateKey($privateKey)
{
$_SESSION['privateKey'] = $privateKey; $_SESSION['privateKey'] = $privateKey;
@ -113,7 +116,8 @@ class Session {
* @returns string $privateKey The user's plaintext private key * @returns string $privateKey The user's plaintext private key
* *
*/ */
public function getPrivateKey() { public function getPrivateKey()
{
if ( if (
isset($_SESSION['privateKey']) isset($_SESSION['privateKey'])
@ -132,17 +136,15 @@ class Session {
/** /**
* @brief Sets user legacy key to session * @brief Sets user legacy key to session
* @param $legacyKey
* @return bool * @return bool
*
*/ */
public function setLegacyKey( $legacyKey ) { public function setLegacyKey($legacyKey)
{
if ( $_SESSION['legacyKey'] = $legacyKey ) { $_SESSION['legacyKey'] = $legacyKey;
return true; return true;
}
} }
/** /**
@ -150,7 +152,8 @@ class Session {
* @returns string $legacyKey The user's plaintext legacy key * @returns string $legacyKey The user's plaintext legacy key
* *
*/ */
public function getLegacyKey() { public function getLegacyKey()
{
if ( if (
isset($_SESSION['legacyKey']) isset($_SESSION['legacyKey'])

View File

@ -48,14 +48,15 @@ namespace OCA\Encryption;
* previous version deleted, this is handled by OC\Files\View, and thus the * previous version deleted, this is handled by OC\Files\View, and thus the
* encryption proxies are used and keyfiles deleted. * encryption proxies are used and keyfiles deleted.
*/ */
class Stream { class Stream
{
public static $sourceStreams = array(); public static $sourceStreams = array();
private $plainKey;
private $encKeyfiles;
// TODO: make all below properties private again once unit testing is private $rawPath; // The raw path relative to the data dir
// configured correctly private $relPath; // rel path to users file dir
public $rawPath; // The raw path relative to the data dir
public $relPath; // rel path to users file dir
private $userId; private $userId;
private $handle; // Resource returned by fopen private $handle; // Resource returned by fopen
private $path; private $path;
@ -63,15 +64,23 @@ class Stream {
private $meta = array(); // Header / meta for source stream private $meta = array(); // Header / meta for source stream
private $count; private $count;
private $writeCache; private $writeCache;
public $size; private $size;
public $unencryptedSize; private $unencryptedSize;
private $publicKey; private $publicKey;
private $keyfile; private $keyfile;
private $encKeyfile; private $encKeyfile;
private static $view; // a fsview object set to user dir private static $view; // a fsview object set to user dir
private $rootView; // a fsview object set to '/' private $rootView; // a fsview object set to '/'
public function stream_open( $path, $mode, $options, &$opened_path ) { /**
* @param $path
* @param $mode
* @param $options
* @param $opened_path
* @return bool
*/
public function stream_open($path, $mode, $options, &$opened_path)
{
if (!isset($this->rootView)) { if (!isset($this->rootView)) {
$this->rootView = new \OC_FilesystemView('/'); $this->rootView = new \OC_FilesystemView('/');
@ -121,12 +130,8 @@ class Stream {
$this->size = $this->rootView->filesize($this->rawPath, $mode); $this->size = $this->rootView->filesize($this->rawPath, $mode);
//$this->size = filesize( $this->rawPath );
} }
//$this->handle = fopen( $this->rawPath, $mode );
$this->handle = $this->rootView->fopen($this->rawPath, $mode); $this->handle = $this->rootView->fopen($this->rawPath, $mode);
\OC_FileProxy::$enabled = $proxyStatus; \OC_FileProxy::$enabled = $proxyStatus;
@ -147,7 +152,12 @@ class Stream {
} }
public function stream_seek( $offset, $whence = SEEK_SET ) { /**
* @param $offset
* @param int $whence
*/
public function stream_seek($offset, $whence = SEEK_SET)
{
$this->flush(); $this->flush();
@ -155,11 +165,21 @@ class Stream {
} }
public function stream_tell() { /**
* @return int
*/
public function stream_tell()
{
return ftell($this->handle); return ftell($this->handle);
} }
public function stream_read( $count ) { /**
* @param $count
* @return bool|string
* @throws \Exception
*/
public function stream_read($count)
{
$this->writeCache = ''; $this->writeCache = '';
@ -173,8 +193,6 @@ class Stream {
} }
// $pos = ftell( $this->handle );
//
// Get the data from the file handle // Get the data from the file handle
$data = fread($this->handle, 8192); $data = fread($this->handle, 8192);
@ -194,14 +212,6 @@ class Stream {
} }
// $length = $this->size - $pos;
//
// if ( $length < 8192 ) {
//
// $result = substr( $result, 0, $length );
//
// }
return $result; return $result;
} }
@ -210,9 +220,10 @@ class Stream {
* @brief Encrypt and pad data ready for writing to disk * @brief Encrypt and pad data ready for writing to disk
* @param string $plainData data to be encrypted * @param string $plainData data to be encrypted
* @param string $key key to use for encryption * @param string $key key to use for encryption
* @return encrypted data on success, false on failure * @return string encrypted data on success, false on failure
*/ */
public function preWriteEncrypt( $plainData, $key ) { public function preWriteEncrypt($plainData, $key)
{
// Encrypt data to 'catfile', which includes IV // Encrypt data to 'catfile', which includes IV
if ($encrypted = Crypt::symmetricEncryptFileContent($plainData, $key)) { if ($encrypted = Crypt::symmetricEncryptFileContent($plainData, $key)) {
@ -229,10 +240,11 @@ class Stream {
/** /**
* @brief Fetch the plain encryption key for the file and set it as plainKey property * @brief Fetch the plain encryption key for the file and set it as plainKey property
* @param bool $generate if true, a new key will be generated if none can be found * @internal param bool $generate if true, a new key will be generated if none can be found
* @return bool true on key found and set, false on key not found and new key generated and set * @return bool true on key found and set, false on key not found and new key generated and set
*/ */
public function getKey() { public function getKey()
{
// Check if key is already set // Check if key is already set
if (isset($this->plainKey) && isset($this->encKeyfile)) { if (isset($this->plainKey) && isset($this->encKeyfile)) {
@ -267,7 +279,8 @@ class Stream {
} }
public function setUserProperty() { public function setUserProperty()
{
// Only get the user again if it isn't already set // Only get the user again if it isn't already set
if (empty($this->userId)) { if (empty($this->userId)) {
@ -292,7 +305,8 @@ class Stream {
* @note Padding is added to each encrypted block to ensure that the resulting block is exactly 8192 bytes. This is removed during stream_read * @note Padding is added to each encrypted block to ensure that the resulting block is exactly 8192 bytes. This is removed during stream_read
* @note PHP automatically updates the file pointer after writing data to reflect it's length. There is generally no need to update the poitner manually using fseek * @note PHP automatically updates the file pointer after writing data to reflect it's length. There is generally no need to update the poitner manually using fseek
*/ */
public function stream_write( $data ) { public function stream_write($data)
{
// Disable the file proxies so that encryption is not // Disable the file proxies so that encryption is not
// automatically attempted when the file is written to disk - // automatically attempted when the file is written to disk -
@ -324,7 +338,6 @@ class Stream {
} }
// If extra data is left over from the last round, make sure it // If extra data is left over from the last round, make sure it
// is integrated into the next 6126 / 8192 block // is integrated into the next 6126 / 8192 block
if ($this->writeCache) { if ($this->writeCache) {
@ -337,42 +350,17 @@ class Stream {
$this->writeCache = ''; $this->writeCache = '';
} }
//
// // Make sure we always start on a block start
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 );
//
// $pointer = ftell( $this->handle );
//
// $unencryptedNewBlock = fread( $this->handle, 8192 );
//
// fseek( $this->handle, - ( $currentPos % 8192 ), SEEK_CUR );
//
// $block = Crypt::symmetricDecryptFileContent( $unencryptedNewBlock, $this->plainKey );
//
// $x = substr( $block, 0, $currentPos % 8192 );
//
// $data = $x . $data;
//
// fseek( $this->handle, - ( $currentPos % 8192 ), SEEK_CUR );
//
}
// $currentPos = ftell( $this->handle ); // While there still remains somed data to be processed & written
// // While there still remains somed data to be processed & written
while (strlen($data) > 0) { while (strlen($data) > 0) {
// // Remaining length for this iteration, not of the // Remaining length for this iteration, not of the
// // entire file (may be greater than 8192 bytes) // entire file (may be greater than 8192 bytes)
// $remainingLength = strlen( $data ); $remainingLength = strlen( $data );
//
// // If data remaining to be written is less than the // If data remaining to be written is less than the
// // size of 1 6126 byte block // size of 1 6126 byte block
if (strlen($data) < 6126) { if (strlen($data) < 6126) {
// Set writeCache to contents of $data // Set writeCache to contents of $data
@ -401,7 +389,6 @@ class Stream {
fwrite($this->handle, $encrypted); fwrite($this->handle, $encrypted);
$writtenLen = strlen($encrypted); $writtenLen = strlen($encrypted);
//fseek( $this->handle, $writtenLen, SEEK_CUR );
// Remove the chunk we just processed from // Remove the chunk we just processed from
// $data, leaving only unprocessed data in $data // $data, leaving only unprocessed data in $data
@ -422,7 +409,13 @@ class Stream {
} }
public function stream_set_option( $option, $arg1, $arg2 ) { /**
* @param $option
* @param $arg1
* @param $arg2
*/
public function stream_set_option($option, $arg1, $arg2)
{
switch ($option) { switch ($option) {
case STREAM_OPTION_BLOCKING: case STREAM_OPTION_BLOCKING:
stream_set_blocking($this->handle, $arg1); stream_set_blocking($this->handle, $arg1);
@ -435,26 +428,43 @@ class Stream {
} }
} }
public function stream_stat() { /**
* @return array
*/
public function stream_stat()
{
return fstat($this->handle); return fstat($this->handle);
} }
public function stream_lock( $mode ) { /**
* @param $mode
*/
public function stream_lock($mode)
{
flock($this->handle, $mode); flock($this->handle, $mode);
} }
public function stream_flush() { /**
* @return bool
*/
public function stream_flush()
{
return fflush($this->handle); return fflush($this->handle);
// Not a typo: http://php.net/manual/en/function.fflush.php // Not a typo: http://php.net/manual/en/function.fflush.php
} }
public function stream_eof() { /**
* @return bool
*/
public function stream_eof()
{
return feof($this->handle); return feof($this->handle);
} }
private function flush() { private function flush()
{
if ($this->writeCache) { if ($this->writeCache) {
@ -471,7 +481,11 @@ class Stream {
} }
public function stream_close() { /**
* @return bool
*/
public function stream_close()
{
$this->flush(); $this->flush();

View File

@ -55,8 +55,8 @@ namespace OCA\Encryption;
* unused, likely to become obsolete shortly * unused, likely to become obsolete shortly
*/ */
class Util { class Util
{
// Web UI: // Web UI:
@ -112,7 +112,13 @@ class Util {
private $recoveryKeyId; private $recoveryKeyId;
private $isPublic; private $isPublic;
public function __construct( \OC_FilesystemView $view, $userId, $client = false ) { /**
* @param \OC_FilesystemView $view
* @param $userId
* @param bool $client
*/
public function __construct(\OC_FilesystemView $view, $userId, $client = false)
{
$this->view = $view; $this->view = $view;
$this->userId = $userId; $this->userId = $userId;
@ -153,7 +159,11 @@ class Util {
} }
} }
public function ready() { /**
* @return bool
*/
public function ready()
{
if ( if (
!$this->view->file_exists($this->encryptionDir) !$this->view->file_exists($this->encryptionDir)
@ -175,9 +185,10 @@ class Util {
/** /**
* @brief Sets up user folders and keys for serverside encryption * @brief Sets up user folders and keys for serverside encryption
* @param $passphrase passphrase to encrypt server-stored private key with * @param string $passphrase passphrase to encrypt server-stored private key with
*/ */
public function setupServerSide( $passphrase = null ) { public function setupServerSide($passphrase = null)
{
// Set directories to check / create // Set directories to check / create
$setUpDirs = array( $setUpDirs = array(
@ -239,17 +250,23 @@ class Util {
} }
public function getPublicShareKeyId() { /**
* @return string
*/
public function getPublicShareKeyId()
{
return $this->publicShareKeyId; return $this->publicShareKeyId;
} }
/** /**
* @brief Check whether pwd recovery is enabled for a given user * @brief Check whether pwd recovery is enabled for a given user
* @return 1 = yes, 0 = no, false = no record * @return bool 1 = yes, 0 = no, false = no record
*
* @note If records are not being returned, check for a hidden space * @note If records are not being returned, check for a hidden space
* at the start of the uid in db * at the start of the uid in db
*/ */
public function recoveryEnabledForUser() { public function recoveryEnabledForUser()
{
$sql = 'SELECT $sql = 'SELECT
recovery_enabled recovery_enabled
@ -291,7 +308,8 @@ class Util {
* @param bool $enabled Whether to enable or disable recovery * @param bool $enabled Whether to enable or disable recovery
* @return bool * @return bool
*/ */
public function setRecoveryForUser( $enabled ) { public function setRecoveryForUser($enabled)
{
$recoveryStatus = $this->recoveryEnabledForUser(); $recoveryStatus = $this->recoveryEnabledForUser();
@ -339,7 +357,8 @@ class Util {
* @note $directory needs to be a path relative to OC data dir. e.g. * @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 * /admin/files NOT /backup OR /home/www/oc/data/admin/files
*/ */
public function findEncFiles( $directory ) { public function findEncFiles($directory)
{
// Disable proxy - we don't want files to be decrypted before // Disable proxy - we don't want files to be decrypted before
// we handle them // we handle them
@ -436,7 +455,8 @@ class Util {
* @note Safe to use on large files; does not read entire file to memory * @note Safe to use on large files; does not read entire file to memory
* @note Derivative of http://tekkie.flashbit.net/php/tail-functionality-in-php * @note Derivative of http://tekkie.flashbit.net/php/tail-functionality-in-php
*/ */
public function tail( $filename, $numLines ) { public function tail($filename, $numLines)
{
\OC_FileProxy::$enabled = false; \OC_FileProxy::$enabled = false;
@ -476,9 +496,11 @@ class Util {
/** /**
* @brief Check if a given path identifies an encrypted file * @brief Check if a given path identifies an encrypted file
* @return true / false * @param $path
* @return boolean
*/ */
public function isEncryptedPath( $path ) { public function isEncryptedPath($path)
{
// Disable encryption proxy so data retrieved is in its // Disable encryption proxy so data retrieved is in its
// original form // original form
@ -501,11 +523,11 @@ class Util {
/** /**
* @brief get the file size of the unencrypted file * @brief get the file size of the unencrypted file
* @param $path absolute path * @param string $path absolute path
* @return bool * @return bool
*/ */
public function getFileSize($path)
public function getFileSize( $path ) { {
$result = 0; $result = 0;
@ -557,8 +579,8 @@ class Util {
* @param $path absolute path * @param $path absolute path
* @return true / false if file is encrypted * @return true / false if file is encrypted
*/ */
public function fixFileSize($path)
public function fixFileSize( $path ) { {
$result = false; $result = false;
@ -592,7 +614,8 @@ class Util {
* @brief Format a path to be relative to the /user/files/ directory * @brief Format a path to be relative to the /user/files/ directory
* @note e.g. turns '/admin/files/test.txt' into 'test.txt' * @note e.g. turns '/admin/files/test.txt' into 'test.txt'
*/ */
public function stripUserFilesPath( $path ) { public function stripUserFilesPath($path)
{
$trimmed = ltrim($path, '/'); $trimmed = ltrim($path, '/');
$split = explode('/', $trimmed); $split = explode('/', $trimmed);
@ -607,7 +630,8 @@ class Util {
* @brief Format a path to be relative to the /user directory * @brief Format a path to be relative to the /user directory
* @note e.g. turns '/admin/files/test.txt' into 'files/test.txt' * @note e.g. turns '/admin/files/test.txt' into 'files/test.txt'
*/ */
public function stripFilesPath( $path ) { public function stripFilesPath($path)
{
$trimmed = ltrim($path, '/'); $trimmed = ltrim($path, '/');
$split = explode('/', $trimmed); $split = explode('/', $trimmed);
@ -622,7 +646,8 @@ class Util {
* @brief Format a shared path to be relative to the /user/files/ directory * @brief Format a shared path to be relative to the /user/files/ directory
* @note Expects a path like /uid/files/Shared/filepath * @note Expects a path like /uid/files/Shared/filepath
*/ */
public function stripSharedFilePath( $path ) { public function stripSharedFilePath($path)
{
$trimmed = ltrim($path, '/'); $trimmed = ltrim($path, '/');
$split = explode('/', $trimmed); $split = explode('/', $trimmed);
@ -633,7 +658,12 @@ class Util {
} }
public function isSharedPath( $path ) { /**
* @param $path
* @return bool
*/
public function isSharedPath($path)
{
$trimmed = ltrim($path, '/'); $trimmed = ltrim($path, '/');
$split = explode('/', $trimmed); $split = explode('/', $trimmed);
@ -653,9 +683,13 @@ class Util {
/** /**
* @brief Encrypt all files in a directory * @brief Encrypt all files in a directory
* @param string $dirPath the directory whose files will be encrypted * @param string $dirPath the directory whose files will be encrypted
* @param null $legacyPassphrase
* @param null $newPassphrase
* @return bool
* @note Encryption is recursive * @note Encryption is recursive
*/ */
public function encryptAll($dirPath, $legacyPassphrase = null, $newPassphrase = null) { public function encryptAll($dirPath, $legacyPassphrase = null, $newPassphrase = null)
{
if ($found = $this->findEncFiles($dirPath)) { if ($found = $this->findEncFiles($dirPath)) {
@ -762,7 +796,8 @@ class Util {
* @param string $pathName Name of the directory to return the path of * @param string $pathName Name of the directory to return the path of
* @return string path * @return string path
*/ */
public function getPath( $pathName ) { public function getPath($pathName)
{
switch ($pathName) { switch ($pathName) {
@ -802,10 +837,11 @@ class Util {
/** /**
* @brief get path of a file. * @brief get path of a file.
* @param $fileId id of the file * @param int $fileId id of the file
* @return path of the file * @return string path of the file
*/ */
public static function fileIdToPath( $fileId ) { public static function fileIdToPath($fileId)
{
$query = \OC_DB::prepare('SELECT `path`' $query = \OC_DB::prepare('SELECT `path`'
. ' FROM `*PREFIX*filecache`' . ' FROM `*PREFIX*filecache`'
@ -824,7 +860,8 @@ class Util {
* @param array $unfilteredUsers users to be checked for sharing readiness * @param array $unfilteredUsers users to be checked for sharing readiness
* @return multi-dimensional array. keys: ready, unready * @return multi-dimensional array. keys: ready, unready
*/ */
public function filterShareReadyUsers( $unfilteredUsers ) { public function filterShareReadyUsers($unfilteredUsers)
{
// This array will collect the filtered IDs // This array will collect the filtered IDs
$readyIds = $unreadyIds = array(); $readyIds = $unreadyIds = array();
@ -875,7 +912,8 @@ class Util {
* @note This was used when 2 types of encryption for keyfiles was used, * @note This was used when 2 types of encryption for keyfiles was used,
* but now we've switched to exclusively using openssl_seal() * but now we've switched to exclusively using openssl_seal()
*/ */
public function decryptUnknownKeyfile( $filePath, $fileOwner, $privateKey ) { public function decryptUnknownKeyfile($filePath, $fileOwner, $privateKey)
{
// Get the encrypted keyfile // Get the encrypted keyfile
// NOTE: the keyfile format depends on how it was encrypted! At // NOTE: the keyfile format depends on how it was encrypted! At
@ -909,11 +947,13 @@ class Util {
/** /**
* @brief Encrypt keyfile to multiple users * @brief Encrypt keyfile to multiple users
* @param Session $session
* @param array $users list of users which should be able to access the file * @param array $users list of users which should be able to access the file
* @param string $filePath path of the file to be shared * @param string $filePath path of the file to be shared
* @return bool * @return bool
*/ */
public function setSharedFileKeyfiles( Session $session, array $users, $filePath ) { public function setSharedFileKeyfiles(Session $session, array $users, $filePath)
{
// Make sure users are capable of sharing // Make sure users are capable of sharing
$filteredUids = $this->filterShareReadyUsers($users); $filteredUids = $this->filterShareReadyUsers($users);
@ -968,7 +1008,8 @@ class Util {
* @brief Find, sanitise and format users sharing a file * @brief Find, sanitise and format users sharing a file
* @note This wraps other methods into a portable bundle * @note This wraps other methods into a portable bundle
*/ */
public function getSharingUsersArray( $sharingEnabled, $filePath, $currentUserId = false ) { public function getSharingUsersArray($sharingEnabled, $filePath, $currentUserId = false)
{
// Check if key recovery is enabled // Check if key recovery is enabled
if ( if (
@ -1026,9 +1067,11 @@ class Util {
/** /**
* @brief Set file migration status for user * @brief Set file migration status for user
* @param $status
* @return bool * @return bool
*/ */
public function setMigrationStatus( $status ) { public function setMigrationStatus($status)
{
$sql = 'UPDATE $sql = 'UPDATE
*PREFIX*encryption *PREFIX*encryption
@ -1055,11 +1098,12 @@ class Util {
/** /**
* @brief Check whether pwd recovery is enabled for a given user * @brief Check whether pwd recovery is enabled for a given user
* @return 1 = yes, 0 = no, false = no record * @return bool 1 = yes, 0 = no, false = no record
* @note If records are not being returned, check for a hidden space * @note If records are not being returned, check for a hidden space
* at the start of the uid in db * at the start of the uid in db
*/ */
public function getMigrationStatus() { public function getMigrationStatus()
{
$sql = 'SELECT $sql = 'SELECT
migration_status migration_status
@ -1098,12 +1142,13 @@ class Util {
/** /**
* @brief get uid of the owners of the file and the path to the file * @brief get uid of the owners of the file and the path to the file
* @param $path Path of the file to check * @param string $path Path of the file to check
* @note $shareFilePath must be relative to data/UID/files. Files * @note $shareFilePath must be relative to data/UID/files. Files
* relative to /Shared are also acceptable * relative to /Shared are also acceptable
* @return array * @return array
*/ */
public function getUidAndFilename( $path ) { public function getUidAndFilename($path)
{
$view = new \OC\Files\View($this->userFilesDir); $view = new \OC\Files\View($this->userFilesDir);
$fileOwnerUid = $view->getOwner($path); $fileOwnerUid = $view->getOwner($path);
@ -1148,10 +1193,11 @@ class Util {
/** /**
* @brief geo recursively through a dir and collect all files and sub files. * @brief geo recursively through a dir and collect all files and sub files.
* @param type $dir relative to the users files folder * @param string $dir relative to the users files folder
* @return array with list of files relative to the users files folder * @return array with list of files relative to the users files folder
*/ */
public function getAllFiles( $dir ) { public function getAllFiles($dir)
{
$result = array(); $result = array();
@ -1211,7 +1257,8 @@ class Util {
* @param int $id of the current share * @param int $id of the current share
* @return array of the parent * @return array of the parent
*/ */
public static function getShareParent( $id ) { public static function getShareParent($id)
{
$query = \OC_DB::prepare('SELECT `file_target`, `item_type`' $query = \OC_DB::prepare('SELECT `file_target`, `item_type`'
. ' FROM `*PREFIX*share`' . ' FROM `*PREFIX*share`'
@ -1230,7 +1277,8 @@ class Util {
* @param int $id of the current share * @param int $id of the current share
* @return array of the parent * @return array of the parent
*/ */
public static function getParentFromShare( $id ) { public static function getParentFromShare($id)
{
$query = \OC_DB::prepare('SELECT `parent`' $query = \OC_DB::prepare('SELECT `parent`'
. ' FROM `*PREFIX*share`' . ' FROM `*PREFIX*share`'
@ -1246,10 +1294,12 @@ class Util {
/** /**
* @brief get owner of the shared files. * @brief get owner of the shared files.
* @param int $Id of a share * @param $id
* @return owner * @internal param int $Id of a share
* @return string owner
*/ */
public function getOwnerFromSharedFile( $id ) { public function getOwnerFromSharedFile($id)
{
$query = \OC_DB::prepare('SELECT `parent`, `uid_owner` FROM `*PREFIX*share` WHERE `id` = ?', 1); $query = \OC_DB::prepare('SELECT `parent`, `uid_owner` FROM `*PREFIX*share` WHERE `id` = ?', 1);
$source = $query->execute(array($id))->fetchRow(); $source = $query->execute(array($id))->fetchRow();
@ -1286,17 +1336,28 @@ class Util {
} }
/**
* @return string
*/
public function getUserId() public function getUserId()
{ {
return $this->userId; return $this->userId;
} }
/**
* @return string
*/
public function getUserFilesDir() public function getUserFilesDir()
{ {
return $this->userFilesDir; return $this->userFilesDir;
} }
public function checkRecoveryPassword($password) { /**
* @param $password
* @return bool
*/
public function checkRecoveryPassword($password)
{
$pathKey = '/owncloud_private_key/' . $this->recoveryKeyId . ".private.key"; $pathKey = '/owncloud_private_key/' . $this->recoveryKeyId . ".private.key";
$pathControlData = '/control-file/controlfile.enc'; $pathControlData = '/control-file/controlfile.enc';
@ -1320,14 +1381,19 @@ class Util {
return false; return false;
} }
public function getRecoveryKeyId() { /**
* @return string
*/
public function getRecoveryKeyId()
{
return $this->recoveryKeyId; return $this->recoveryKeyId;
} }
/** /**
* @brief add recovery key to all encrypted files * @brief add recovery key to all encrypted files
*/ */
public function addRecoveryKeys($path = '/') { public function addRecoveryKeys($path = '/')
{
$dirContent = $this->view->getDirectoryContent($this->keyfilesPath . $path); $dirContent = $this->view->getDirectoryContent($this->keyfilesPath . $path);
foreach ($dirContent as $item) { foreach ($dirContent as $item) {
$filePath = substr($item['path'], 25); $filePath = substr($item['path'], 25);
@ -1346,7 +1412,8 @@ class Util {
/** /**
* @brief remove recovery key to all encrypted files * @brief remove recovery key to all encrypted files
*/ */
public function removeRecoveryKeys($path = '/') { public function removeRecoveryKeys($path = '/')
{
$dirContent = $this->view->getDirectoryContent($this->keyfilesPath . $path); $dirContent = $this->view->getDirectoryContent($this->keyfilesPath . $path);
foreach ($dirContent as $item) { foreach ($dirContent as $item) {
$filePath = substr($item['path'], 25); $filePath = substr($item['path'], 25);
@ -1361,10 +1428,11 @@ class Util {
/** /**
* @brief decrypt given file with recovery key and encrypt it again to the owner and his new key * @brief decrypt given file with recovery key and encrypt it again to the owner and his new key
* @param type $file * @param string $file
* @param type $privateKey recovery key to decrypt the file * @param string $privateKey recovery key to decrypt the file
*/ */
private function recoverFile($file, $privateKey) { private function recoverFile($file, $privateKey)
{
$sharingEnabled = \OCP\Share::isEnabled(); $sharingEnabled = \OCP\Share::isEnabled();
@ -1405,10 +1473,11 @@ class Util {
/** /**
* @brief collect all files and recover them one by one * @brief collect all files and recover them one by one
* @param type $path to look for files keys * @param string $path to look for files keys
* @param type $privateKey private recovery key which is used to decrypt the files * @param string $privateKey private recovery key which is used to decrypt the files
*/ */
private function recoverAllFiles($path, $privateKey) { private function recoverAllFiles($path, $privateKey)
{
$dirContent = $this->view->getDirectoryContent($this->keyfilesPath . $path); $dirContent = $this->view->getDirectoryContent($this->keyfilesPath . $path);
foreach ($dirContent as $item) { foreach ($dirContent as $item) {
$filePath = substr($item['path'], 25); $filePath = substr($item['path'], 25);
@ -1423,9 +1492,10 @@ class Util {
/** /**
* @brief recover users files in case of password lost * @brief recover users files in case of password lost
* @param type $recoveryPassword * @param string $recoveryPassword
*/ */
public function recoverUsersFiles($recoveryPassword) { public function recoverUsersFiles($recoveryPassword)
{
// Disable encryption proxy to prevent recursive calls // Disable encryption proxy to prevent recursive calls
$proxyStatus = \OC_FileProxy::$enabled; $proxyStatus = \OC_FileProxy::$enabled;

View File

@ -22,7 +22,8 @@ use OCA\Encryption;
/** /**
* Class Test_Encryption_Crypt * Class Test_Encryption_Crypt
*/ */
class Test_Encryption_Crypt extends \PHPUnit_Framework_TestCase { class Test_Encryption_Crypt extends \PHPUnit_Framework_TestCase
{
public $userId; public $userId;
public $pass; public $pass;
@ -38,7 +39,8 @@ class Test_Encryption_Crypt extends \PHPUnit_Framework_TestCase {
public $genPrivateKey; public $genPrivateKey;
public $genPublicKey; public $genPublicKey;
function setUp() { function setUp()
{
// reset backend // reset backend
\OC_User::clearBackends(); \OC_User::clearBackends();
\OC_User::useBackend('database'); \OC_User::useBackend('database');
@ -90,7 +92,8 @@ class Test_Encryption_Crypt extends \PHPUnit_Framework_TestCase {
} }
function tearDown() { function tearDown()
{
\OC_FileProxy::clearProxies(); \OC_FileProxy::clearProxies();
// reset app files_trashbin // reset app files_trashbin
@ -101,7 +104,8 @@ class Test_Encryption_Crypt extends \PHPUnit_Framework_TestCase {
} }
} }
function testGenerateKey() { function testGenerateKey()
{
# TODO: use more accurate (larger) string length for test confirmation # TODO: use more accurate (larger) string length for test confirmation
@ -114,7 +118,8 @@ class Test_Encryption_Crypt extends \PHPUnit_Framework_TestCase {
/** /**
* @return String * @return String
*/ */
function testGenerateIv() { function testGenerateIv()
{
$iv = Encryption\Crypt::generateIv(); $iv = Encryption\Crypt::generateIv();
@ -127,7 +132,8 @@ class Test_Encryption_Crypt extends \PHPUnit_Framework_TestCase {
/** /**
* @depends testGenerateIv * @depends testGenerateIv
*/ */
function testConcatIv( $iv ) { function testConcatIv($iv)
{
$catFile = Encryption\Crypt::concatIv($this->dataLong, $iv); $catFile = Encryption\Crypt::concatIv($this->dataLong, $iv);
@ -158,7 +164,8 @@ class Test_Encryption_Crypt extends \PHPUnit_Framework_TestCase {
/** /**
* @depends testConcatIv * @depends testConcatIv
*/ */
function testSplitIv( $testConcatIv ) { function testSplitIv($testConcatIv)
{
// Split catfile into components // Split catfile into components
$splitCatfile = Encryption\Crypt::splitIv($testConcatIv['catfile']); $splitCatfile = Encryption\Crypt::splitIv($testConcatIv['catfile']);
@ -174,7 +181,8 @@ class Test_Encryption_Crypt extends \PHPUnit_Framework_TestCase {
/** /**
* @return string padded * @return string padded
*/ */
function testAddPadding() { function testAddPadding()
{
$padded = Encryption\Crypt::addPadding($this->dataLong); $padded = Encryption\Crypt::addPadding($this->dataLong);
@ -189,7 +197,8 @@ class Test_Encryption_Crypt extends \PHPUnit_Framework_TestCase {
/** /**
* @depends testAddPadding * @depends testAddPadding
*/ */
function testRemovePadding( $padded ) { function testRemovePadding($padded)
{
$noPadding = Encryption\Crypt::RemovePadding($padded); $noPadding = Encryption\Crypt::RemovePadding($padded);
@ -197,7 +206,8 @@ class Test_Encryption_Crypt extends \PHPUnit_Framework_TestCase {
} }
function testEncrypt() { function testEncrypt()
{
$random = openssl_random_pseudo_bytes(13); $random = openssl_random_pseudo_bytes(13);
@ -209,7 +219,8 @@ class Test_Encryption_Crypt extends \PHPUnit_Framework_TestCase {
} }
function testDecrypt() { function testDecrypt()
{
$random = openssl_random_pseudo_bytes(13); $random = openssl_random_pseudo_bytes(13);
@ -223,7 +234,8 @@ class Test_Encryption_Crypt extends \PHPUnit_Framework_TestCase {
} }
function testSymmetricEncryptFileContent() { function testSymmetricEncryptFileContent()
{
# TODO: search in keyfile for actual content as IV will ensure this test always passes # TODO: search in keyfile for actual content as IV will ensure this test always passes
@ -238,7 +250,8 @@ class Test_Encryption_Crypt extends \PHPUnit_Framework_TestCase {
} }
function testSymmetricStreamEncryptShortFileContent() { function testSymmetricStreamEncryptShortFileContent()
{
$filename = 'tmp-' . time() . '.test'; $filename = 'tmp-' . time() . '.test';
@ -293,7 +306,8 @@ class Test_Encryption_Crypt extends \PHPUnit_Framework_TestCase {
* @note If this test fails with truncate content, check that enough array slices are being rejoined to form $e, as the crypt.php file may have gotten longer and broken the manual * @note If this test fails with truncate content, check that enough array slices are being rejoined to form $e, as the crypt.php file may have gotten longer and broken the manual
* reassembly of its data * reassembly of its data
*/ */
function testSymmetricStreamEncryptLongFileContent() { function testSymmetricStreamEncryptLongFileContent()
{
// Generate a a random filename // Generate a a random filename
$filename = 'tmp-' . time() . '.test'; $filename = 'tmp-' . time() . '.test';
@ -369,7 +383,8 @@ class Test_Encryption_Crypt extends \PHPUnit_Framework_TestCase {
/** /**
* @brief Test that data that is read by the crypto stream wrapper * @brief Test that data that is read by the crypto stream wrapper
*/ */
function testSymmetricStreamDecryptShortFileContent() { function testSymmetricStreamDecryptShortFileContent()
{
$filename = 'tmp-' . time(); $filename = 'tmp-' . time();
@ -396,7 +411,8 @@ class Test_Encryption_Crypt extends \PHPUnit_Framework_TestCase {
$this->view->unlink($this->userId . '/files/' . $filename); $this->view->unlink($this->userId . '/files/' . $filename);
} }
function testSymmetricStreamDecryptLongFileContent() { function testSymmetricStreamDecryptLongFileContent()
{
$filename = 'tmp-' . time(); $filename = 'tmp-' . time();
@ -438,7 +454,8 @@ class Test_Encryption_Crypt extends \PHPUnit_Framework_TestCase {
// //
// } // }
function testSymmetricEncryptFileContentKeyfile() { function testSymmetricEncryptFileContentKeyfile()
{
# TODO: search in keyfile for actual content as IV will ensure this test always passes # TODO: search in keyfile for actual content as IV will ensure this test always passes
@ -453,7 +470,8 @@ class Test_Encryption_Crypt extends \PHPUnit_Framework_TestCase {
} }
function testIsEncryptedContent() { function testIsEncryptedContent()
{
$this->assertFalse(Encryption\Crypt::isCatfileContent($this->dataUrl)); $this->assertFalse(Encryption\Crypt::isCatfileContent($this->dataUrl));
@ -465,7 +483,8 @@ class Test_Encryption_Crypt extends \PHPUnit_Framework_TestCase {
} }
function testMultiKeyEncrypt() { function testMultiKeyEncrypt()
{
# TODO: search in keyfile for actual content as IV will ensure this test always passes # TODO: search in keyfile for actual content as IV will ensure this test always passes
@ -489,7 +508,8 @@ class Test_Encryption_Crypt extends \PHPUnit_Framework_TestCase {
} }
function testKeyEncrypt() { function testKeyEncrypt()
{
// Generate keypair // Generate keypair
$pair1 = Encryption\Crypt::createKeypair(); $pair1 = Encryption\Crypt::createKeypair();
@ -509,7 +529,8 @@ class Test_Encryption_Crypt extends \PHPUnit_Framework_TestCase {
/** /**
* @brief test encryption using legacy blowfish method * @brief test encryption using legacy blowfish method
*/ */
function testLegacyEncryptShort() { function testLegacyEncryptShort()
{
$crypted = Encryption\Crypt::legacyEncrypt($this->dataShort, $this->pass); $crypted = Encryption\Crypt::legacyEncrypt($this->dataShort, $this->pass);
@ -526,7 +547,8 @@ class Test_Encryption_Crypt extends \PHPUnit_Framework_TestCase {
* @brief test decryption using legacy blowfish method * @brief test decryption using legacy blowfish method
* @depends testLegacyEncryptShort * @depends testLegacyEncryptShort
*/ */
function testLegacyDecryptShort( $crypted ) { function testLegacyDecryptShort($crypted)
{
$decrypted = Encryption\Crypt::legacyDecrypt($crypted, $this->pass); $decrypted = Encryption\Crypt::legacyDecrypt($crypted, $this->pass);
@ -537,7 +559,8 @@ class Test_Encryption_Crypt extends \PHPUnit_Framework_TestCase {
/** /**
* @brief test encryption using legacy blowfish method * @brief test encryption using legacy blowfish method
*/ */
function testLegacyEncryptLong() { function testLegacyEncryptLong()
{
$crypted = Encryption\Crypt::legacyEncrypt($this->dataLong, $this->pass); $crypted = Encryption\Crypt::legacyEncrypt($this->dataLong, $this->pass);
@ -554,7 +577,8 @@ class Test_Encryption_Crypt extends \PHPUnit_Framework_TestCase {
* @brief test decryption using legacy blowfish method * @brief test decryption using legacy blowfish method
* @depends testLegacyEncryptLong * @depends testLegacyEncryptLong
*/ */
function testLegacyDecryptLong( $crypted ) { function testLegacyDecryptLong($crypted)
{
$decrypted = Encryption\Crypt::legacyDecrypt($crypted, $this->pass); $decrypted = Encryption\Crypt::legacyDecrypt($crypted, $this->pass);
@ -566,7 +590,8 @@ class Test_Encryption_Crypt extends \PHPUnit_Framework_TestCase {
* @brief test generation of legacy encryption key * @brief test generation of legacy encryption key
* @depends testLegacyDecryptShort * @depends testLegacyDecryptShort
*/ */
function testLegacyCreateKey() { function testLegacyCreateKey()
{
// Create encrypted key // Create encrypted key
$encKey = Encryption\Crypt::legacyCreateKey($this->pass); $encKey = Encryption\Crypt::legacyCreateKey($this->pass);
@ -585,7 +610,8 @@ class Test_Encryption_Crypt extends \PHPUnit_Framework_TestCase {
* @brief test decryption using legacy blowfish method * @brief test decryption using legacy blowfish method
* @depends testLegacyEncryptLong * @depends testLegacyEncryptLong
*/ */
function testLegacyKeyRecryptKeyfileEncrypt( $crypted ) { function testLegacyKeyRecryptKeyfileEncrypt($crypted)
{
$recrypted = Encryption\Crypt::LegacyKeyRecryptKeyfile($crypted, $this->pass, array($this->genPublicKey), $this->pass, ''); $recrypted = Encryption\Crypt::LegacyKeyRecryptKeyfile($crypted, $this->pass, array($this->genPublicKey), $this->pass, '');
@ -598,7 +624,8 @@ class Test_Encryption_Crypt extends \PHPUnit_Framework_TestCase {
} }
function testRenameFile() { function testRenameFile()
{
$filename = 'tmp-' . time(); $filename = 'tmp-' . time();
@ -626,7 +653,8 @@ class Test_Encryption_Crypt extends \PHPUnit_Framework_TestCase {
$view->unlink($newFilename); $view->unlink($newFilename);
} }
function testMoveFileIntoFolder() { function testMoveFileIntoFolder()
{
$filename = 'tmp-' . time(); $filename = 'tmp-' . time();
@ -656,7 +684,8 @@ class Test_Encryption_Crypt extends \PHPUnit_Framework_TestCase {
$view->unlink($newFolder); $view->unlink($newFolder);
} }
function testMoveFolder() { function testMoveFolder()
{
$view = new \OC\Files\View('/' . $this->userId . '/files'); $view = new \OC\Files\View('/' . $this->userId . '/files');
@ -689,7 +718,8 @@ class Test_Encryption_Crypt extends \PHPUnit_Framework_TestCase {
$view->unlink($newFolder); $view->unlink($newFolder);
} }
function testRenameFolder() { function testRenameFolder()
{
$filename = '/tmp-' . time(); $filename = '/tmp-' . time();
@ -721,7 +751,8 @@ class Test_Encryption_Crypt extends \PHPUnit_Framework_TestCase {
$view->unlink($newFolder); $view->unlink($newFolder);
} }
function testChangePassphrase() { function testChangePassphrase()
{
$filename = 'tmp-' . time(); $filename = 'tmp-' . time();
@ -756,7 +787,8 @@ class Test_Encryption_Crypt extends \PHPUnit_Framework_TestCase {
$view->unlink($filename); $view->unlink($filename);
} }
function testViewFilePutAndGetContents() { function testViewFilePutAndGetContents()
{
$filename = '/tmp-' . time(); $filename = '/tmp-' . time();
$view = new \OC\Files\View('/' . $this->userId . '/files'); $view = new \OC\Files\View('/' . $this->userId . '/files');
@ -787,7 +819,8 @@ class Test_Encryption_Crypt extends \PHPUnit_Framework_TestCase {
$view->unlink($filename); $view->unlink($filename);
} }
function testTouchExistingFile() { function testTouchExistingFile()
{
$filename = '/tmp-' . time(); $filename = '/tmp-' . time();
$view = new \OC\Files\View('/' . $this->userId . '/files'); $view = new \OC\Files\View('/' . $this->userId . '/files');
@ -808,7 +841,8 @@ class Test_Encryption_Crypt extends \PHPUnit_Framework_TestCase {
$view->unlink($filename); $view->unlink($filename);
} }
function testTouchFile() { function testTouchFile()
{
$filename = '/tmp-' . time(); $filename = '/tmp-' . time();
$view = new \OC\Files\View('/' . $this->userId . '/files'); $view = new \OC\Files\View('/' . $this->userId . '/files');
@ -829,7 +863,8 @@ class Test_Encryption_Crypt extends \PHPUnit_Framework_TestCase {
$view->unlink($filename); $view->unlink($filename);
} }
function testFopenFile() { function testFopenFile()
{
$filename = '/tmp-' . time(); $filename = '/tmp-' . time();
$view = new \OC\Files\View('/' . $this->userId . '/files'); $view = new \OC\Files\View('/' . $this->userId . '/files');

View File

@ -20,7 +20,8 @@ use OCA\Encryption;
/** /**
* Class Test_Encryption_Keymanager * Class Test_Encryption_Keymanager
*/ */
class Test_Encryption_Keymanager extends \PHPUnit_Framework_TestCase { class Test_Encryption_Keymanager extends \PHPUnit_Framework_TestCase
{
public $userId; public $userId;
public $pass; public $pass;
@ -31,7 +32,8 @@ class Test_Encryption_Keymanager extends \PHPUnit_Framework_TestCase {
public $view; public $view;
public $randomKey; public $randomKey;
function setUp() { function setUp()
{
// reset backend // reset backend
\OC_User::clearBackends(); \OC_User::clearBackends();
\OC_User::useBackend('database'); \OC_User::useBackend('database');
@ -81,7 +83,8 @@ class Test_Encryption_Keymanager extends \PHPUnit_Framework_TestCase {
OCA\Encryption\Hooks::login($params); OCA\Encryption\Hooks::login($params);
} }
function tearDown(){ function tearDown()
{
\OC_FileProxy::$enabled = true; \OC_FileProxy::$enabled = true;
\OC_FileProxy::clearProxies(); \OC_FileProxy::clearProxies();
@ -94,7 +97,8 @@ class Test_Encryption_Keymanager extends \PHPUnit_Framework_TestCase {
} }
} }
function testGetPrivateKey() { function testGetPrivateKey()
{
$key = Encryption\Keymanager::getPrivateKey($this->view, $this->userId); $key = Encryption\Keymanager::getPrivateKey($this->view, $this->userId);
@ -110,7 +114,8 @@ class Test_Encryption_Keymanager extends \PHPUnit_Framework_TestCase {
} }
function testGetPublicKey() { function testGetPublicKey()
{
$publiceKey = Encryption\Keymanager::getPublicKey($this->view, $this->userId); $publiceKey = Encryption\Keymanager::getPublicKey($this->view, $this->userId);
@ -123,7 +128,8 @@ class Test_Encryption_Keymanager extends \PHPUnit_Framework_TestCase {
$this->assertArrayHasKey('key', $sslInfo); $this->assertArrayHasKey('key', $sslInfo);
} }
function testSetFileKey() { function testSetFileKey()
{
# NOTE: This cannot be tested until we are able to break out # NOTE: This cannot be tested until we are able to break out
# of the FileSystemView data directory root # of the FileSystemView data directory root
@ -172,7 +178,8 @@ class Test_Encryption_Keymanager extends \PHPUnit_Framework_TestCase {
// //
// } // }
function testGetUserKeys() { function testGetUserKeys()
{
$keys = Encryption\Keymanager::getUserKeys($this->view, $this->userId); $keys = Encryption\Keymanager::getUserKeys($this->view, $this->userId);

View File

@ -19,7 +19,8 @@ use OCA\Encryption;
/** /**
* Class Test_Encryption_Util * Class Test_Encryption_Util
*/ */
class Test_Encryption_Util extends \PHPUnit_Framework_TestCase { class Test_Encryption_Util extends \PHPUnit_Framework_TestCase
{
public $userId; public $userId;
public $encryptionDir; public $encryptionDir;
@ -38,7 +39,8 @@ class Test_Encryption_Util extends \PHPUnit_Framework_TestCase {
public $util; public $util;
public $dataShort; public $dataShort;
function setUp() { function setUp()
{
// reset backend // reset backend
\OC_User::useBackend('database'); \OC_User::useBackend('database');
@ -87,7 +89,8 @@ class Test_Encryption_Util extends \PHPUnit_Framework_TestCase {
$this->util = new Encryption\Util($this->view, $this->userId); $this->util = new Encryption\Util($this->view, $this->userId);
} }
function tearDown(){ function tearDown()
{
\OC_FileProxy::clearProxies(); \OC_FileProxy::clearProxies();
} }
@ -95,7 +98,8 @@ class Test_Encryption_Util extends \PHPUnit_Framework_TestCase {
/** /**
* @brief test that paths set during User construction are correct * @brief test that paths set during User construction are correct
*/ */
function testKeyPaths() { function testKeyPaths()
{
$util = new Encryption\Util($this->view, $this->userId); $util = new Encryption\Util($this->view, $this->userId);
@ -110,7 +114,8 @@ class Test_Encryption_Util extends \PHPUnit_Framework_TestCase {
/** /**
* @brief test setup of encryption directories * @brief test setup of encryption directories
*/ */
function testSetupServerSide() { function testSetupServerSide()
{
$this->assertEquals(true, $this->util->setupServerSide($this->pass)); $this->assertEquals(true, $this->util->setupServerSide($this->pass));
} }
@ -118,12 +123,14 @@ class Test_Encryption_Util extends \PHPUnit_Framework_TestCase {
/** /**
* @brief test checking whether account is ready for encryption, * @brief test checking whether account is ready for encryption,
*/ */
function testUserIsReady() { function testUserIsReady()
{
$this->assertEquals(true, $this->util->ready()); $this->assertEquals(true, $this->util->ready());
} }
function testRecoveryEnabledForUser() { function testRecoveryEnabledForUser()
{
$util = new Encryption\Util($this->view, $this->userId); $util = new Encryption\Util($this->view, $this->userId);
@ -143,7 +150,8 @@ class Test_Encryption_Util extends \PHPUnit_Framework_TestCase {
} }
function testGetUidAndFilename() { function testGetUidAndFilename()
{
\OC_User::setUserId('admin'); \OC_User::setUserId('admin');