public function setUp() { //clear all proxies and hooks so we can do clean testing \OC_FileProxy::clearProxies(); \OC_Hook::clear('OC_Filesystem'); //disabled atm //enable only the encryption hook if needed //if(OC_App::isEnabled('files_encryption')) { // OC_FileProxy::register(new OC_FileProxy_Encryption()); //} //set up temporary storage \OC\Files\Filesystem::clearMounts(); $storage = new \OC\Files\Storage\Temporary(array()); \OC\Files\Filesystem::mount($storage, array(), '/'); $datadir = str_replace('local::', '', $storage->getId()); $this->datadir = \OC_Config::getValue('cachedirectory', \OC::$SERVERROOT . '/data/cache'); \OC_Config::setValue('cachedirectory', $datadir); \OC_User::clearBackends(); \OC_User::useBackend(new \OC_User_Dummy()); //login \OC_User::createUser('test', 'test'); $this->user = \OC_User::getUser(); \OC_User::setUserId('test'); //set up the users dir $rootView = new \OC\Files\View(''); $rootView->mkdir('/test'); $this->instance = new \OC\Cache\File(); }
public static function setUpBeforeClass() { // note: not using a data provider because these // files all need to coexist to make sure the // share keys are found properly (pattern matching) self::$testFiles = array('t est.txt', 't est_.txt', 't est.doc.txt', 't est(.*).txt', 'multiple.dots.can.happen.too.txt', 't est.' . self::TEST_ENCRYPTION_HOOKS_USER1 . '.txt', 't est_.' . self::TEST_ENCRYPTION_HOOKS_USER1 . '.shareKey.txt', 'who would upload their.shareKey', 'user ones file.txt', 'user ones file.txt.backup', '.t est.txt'); // reset backend \OC_User::clearBackends(); \OC_User::useBackend('database'); \OC_Hook::clear('OC_Filesystem'); \OC_Hook::clear('OC_User'); // clear share hooks \OC_Hook::clear('OCP\\Share'); \OC::registerShareHooks(); \OCP\Util::connectHook('OC_Filesystem', 'setup', '\\OC\\Files\\Storage\\Shared', 'setup'); // Filesystem related hooks \OCA\Encryption\Helper::registerFilesystemHooks(); // Sharing related hooks \OCA\Encryption\Helper::registerShareHooks(); // clear and register proxies \OC_FileProxy::clearProxies(); \OC_FileProxy::register(new OCA\Encryption\Proxy()); // create test user \Test_Encryption_Util::loginHelper(\Test_Encryption_Hooks::TEST_ENCRYPTION_HOOKS_USER1, true); \Test_Encryption_Util::loginHelper(\Test_Encryption_Hooks::TEST_ENCRYPTION_HOOKS_USER2, true); }
public function stream_open($path, $mode, $options, &$opened_path) { if (!self::$rootView) { self::$rootView = new OC_FilesystemView(''); } $path = str_replace('crypt://', '', $path); if (dirname($path) == 'streams' and isset(self::$sourceStreams[basename($path)])) { $this->source = self::$sourceStreams[basename($path)]['stream']; $this->path = self::$sourceStreams[basename($path)]['path']; $this->size = self::$sourceStreams[basename($path)]['size']; } else { $this->path = $path; if ($mode == 'w' or $mode == 'w+' or $mode == 'wb' or $mode == 'wb+') { $this->size = 0; } else { $this->size = self::$rootView->filesize($path, $mode); } OC_FileProxy::$enabled = false; //disable fileproxies so we can open the source file $this->source = self::$rootView->fopen($path, $mode); OC_FileProxy::$enabled = true; if (!is_resource($this->source)) { OCP\Util::writeLog('files_encryption', 'failed to open ' . $path, OCP\Util::ERROR); } } if (is_resource($this->source)) { $this->meta = stream_get_meta_data($this->source); } return is_resource($this->source); }
/** * if session is started, check if ownCloud key pair is set up, if not create it * @param \OC\Files\View $view * * @note The ownCloud key pair is used to allow public link sharing even if encryption is enabled */ public function __construct($view) { $this->view = $view; if (!$this->view->is_dir('files_encryption')) { $this->view->mkdir('files_encryption'); } $appConfig = \OC::$server->getAppConfig(); $publicShareKeyId = Helper::getPublicShareKeyId(); if ($publicShareKeyId === false) { $publicShareKeyId = 'pubShare_' . substr(md5(time()), 0, 8); $appConfig->setValue('files_encryption', 'publicShareKeyId', $publicShareKeyId); } if (!Keymanager::publicShareKeyExists($view)) { $keypair = Crypt::createKeypair(); // Save public key Keymanager::setPublicKey($keypair['publicKey'], $publicShareKeyId); // Encrypt private key empty passphrase $cipher = Helper::getCipher(); $encryptedKey = Crypt::symmetricEncryptFileContent($keypair['privateKey'], '', $cipher); if ($encryptedKey) { Keymanager::setPrivateSystemKey($encryptedKey, $publicShareKeyId); } else { \OCP\Util::writeLog('files_encryption', 'Could not create public share keys', \OCP\Util::ERROR); } } if (Helper::isPublicAccess() && !self::getPublicSharePrivateKey()) { // Disable encryption proxy to prevent recursive calls $proxyStatus = \OC_FileProxy::$enabled; \OC_FileProxy::$enabled = false; $encryptedKey = Keymanager::getPrivateSystemKey($publicShareKeyId); $privateKey = Crypt::decryptPrivateKey($encryptedKey, ''); self::setPublicSharePrivateKey($privateKey); \OC_FileProxy::$enabled = $proxyStatus; } }
public static function setupHooks() { // Filesystem related hooks Helper::registerFilesystemHooks(); // clear and register hooks \OC_FileProxy::clearProxies(); \OC_FileProxy::register(new Files_Encryption\Proxy()); }
public static function tearDownAfterClass() { // cleanup test user \OC_User::deleteUser(\Test_Encryption_Helper::TEST_ENCRYPTION_HELPER_USER1); \OC_User::deleteUser(\Test_Encryption_Helper::TEST_ENCRYPTION_HELPER_USER2); \OC_Hook::clear(); \OC_FileProxy::clearProxies(); }
public static function tearDownAfterClass() { \OC_Hook::clear(); \OC_FileProxy::clearProxies(); // Delete keys in /data/ $view = new \OC\Files\View('/'); $view->deleteAll('files_encryption'); parent::tearDownAfterClass(); }
protected function getDocumentHash($view, $path) { $this->validate($view, $path); $proxyStatus = \OC_FileProxy::$enabled; \OC_FileProxy::$enabled = false; $hash = sha1($view->file_get_contents($path)); \OC_FileProxy::$enabled = $proxyStatus; return $hash; }
public static function tearDownAfterClass() { \OC_Hook::clear(); \OC_FileProxy::clearProxies(); // Delete keys in /data/ $view = new \OC\Files\View('/'); $view->rmdir('public-keys'); $view->rmdir('owncloud_private_key'); }
/** * @brief Can be set up * @param string $user * @return boolean * @description configure the initial filesystem based on the configuration */ public static function setupFS($user = '') { //setting up the filesystem twice can only lead to trouble if (self::$fsSetup) { return false; } // If we are not forced to load a specific user we load the one that is logged in if ($user == "" && OC_User::isLoggedIn()) { $user = OC_User::getUser(); } // load all filesystem apps before, so no setup-hook gets lost if (!isset($RUNTIME_NOAPPS) || !$RUNTIME_NOAPPS) { OC_App::loadApps(array('filesystem')); } // the filesystem will finish when $user is not empty, // mark fs setup here to avoid doing the setup from loading // OC_Filesystem if ($user != '') { self::$fsSetup = true; } $configDataDirectory = OC_Config::getValue("datadirectory", OC::$SERVERROOT . "/data"); //first set up the local "root" storage \OC\Files\Filesystem::initMounts(); if (!self::$rootMounted) { \OC\Files\Filesystem::mount('\\OC\\Files\\Storage\\Local', array('datadir' => $configDataDirectory), '/'); self::$rootMounted = true; } //if we aren't logged in, there is no use to set up the filesystem if ($user != "") { \OC\Files\Filesystem::addStorageWrapper(function ($mountPoint, $storage) { // set up quota for home storages, even for other users // which can happen when using sharing if ($storage instanceof \OC\Files\Storage\Home) { $user = $storage->getUser()->getUID(); $quota = OC_Util::getUserQuota($user); if ($quota !== \OC\Files\SPACE_UNLIMITED) { return new \OC\Files\Storage\Wrapper\Quota(array('storage' => $storage, 'quota' => $quota)); } } return $storage; }); $userDir = '/' . $user . '/files'; $userRoot = OC_User::getHome($user); $userDirectory = $userRoot . '/files'; if (!is_dir($userDirectory)) { mkdir($userDirectory, 0755, true); OC_Util::copySkeleton($userDirectory); } //jail the user into his "home" directory \OC\Files\Filesystem::init($user, $userDir); $fileOperationProxy = new OC_FileProxy_FileOperations(); OC_FileProxy::register($fileOperationProxy); OC_Hook::emit('OC_Filesystem', 'setup', array('user' => $user, 'user_dir' => $userDir)); } return true; }
public static function setupFS($user = "", $root = "files") { // configure the initial filesystem based on the configuration if (self::$fsSetup) { //setting up the filesystem twice can only lead to trouble return false; } $CONFIG_DATADIRECTORY_ROOT = OC_Config::getValue("datadirectory", OC::$SERVERROOT . "/data"); $CONFIG_BACKUPDIRECTORY = OC_Config::getValue("backupdirectory", OC::$SERVERROOT . "/backup"); // Check if config folder is writable. if (!is_writable(OC::$SERVERROOT . "/config/")) { $tmpl = new OC_Template('', 'error', 'guest'); $tmpl->assign('errors', array(1 => array('error' => "Can't write into config directory 'config'", 'hint' => "You can usually fix this by giving the webserver user write access to the config directory in owncloud"))); $tmpl->printPage(); exit; } // Check if apps folder is writable. if (!is_writable(OC::$SERVERROOT . "/apps/")) { $tmpl = new OC_Template('', 'error', 'guest'); $tmpl->assign('errors', array(1 => array('error' => "Can't write into apps directory 'apps'", 'hint' => "You can usually fix this by giving the webserver user write access to the config directory in owncloud"))); $tmpl->printPage(); exit; } // Create root dir. if (!is_dir($CONFIG_DATADIRECTORY_ROOT)) { $success = @mkdir($CONFIG_DATADIRECTORY_ROOT); if (!$success) { $tmpl = new OC_Template('', 'error', 'guest'); $tmpl->assign('errors', array(1 => array('error' => "Can't create data directory (" . $CONFIG_DATADIRECTORY_ROOT . ")", 'hint' => "You can usually fix this by giving the webserver write access to the ownCloud directory '" . OC::$SERVERROOT . "' (in a terminal, use the command 'chown -R www-data:www-data /path/to/your/owncloud/install/data' "))); $tmpl->printPage(); exit; } } // If we are not forced to load a specific user we load the one that is logged in if ($user == "" && OC_User::isLoggedIn()) { $user = OC_User::getUser(); } //first set up the local "root" storage if (!self::$rootMounted) { OC_Filesystem::mount('OC_Filestorage_Local', array('datadir' => $CONFIG_DATADIRECTORY_ROOT), '/'); self::$rootMounted = true; } if ($user != "") { //if we aren't logged in, there is no use to set up the filesystem OC::$CONFIG_DATADIRECTORY = $CONFIG_DATADIRECTORY_ROOT . "/{$user}/{$root}"; if (!is_dir(OC::$CONFIG_DATADIRECTORY)) { mkdir(OC::$CONFIG_DATADIRECTORY, 0755, true); } //jail the user into his "home" directory OC_Filesystem::init('/' . $user . '/' . $root); $quotaProxy = new OC_FileProxy_Quota(); OC_FileProxy::register($quotaProxy); self::$fsSetup = true; } }
public static function setupFS($user = '') { // configure the initial filesystem based on the configuration if (self::$fsSetup) { //setting up the filesystem twice can only lead to trouble return false; } // If we are not forced to load a specific user we load the one that is logged in if ($user == "" && OC_User::isLoggedIn()) { $user = OC_User::getUser(); } // the filesystem will finish when $user is not empty, // mark fs setup here to avoid doing the setup from loading // OC_Filesystem if ($user != '') { self::$fsSetup = true; } $CONFIG_DATADIRECTORY = OC_Config::getValue("datadirectory", OC::$SERVERROOT . "/data"); //first set up the local "root" storage if (!self::$rootMounted) { OC_Filesystem::mount('OC_Filestorage_Local', array('datadir' => $CONFIG_DATADIRECTORY), '/'); self::$rootMounted = true; } if ($user != "") { //if we aren't logged in, there is no use to set up the filesystem $user_dir = '/' . $user . '/files'; $user_root = OC_User::getHome($user); $userdirectory = $user_root . '/files'; if (!is_dir($userdirectory)) { mkdir($userdirectory, 0755, true); } //jail the user into his "home" directory OC_Filesystem::mount('OC_Filestorage_Local', array('datadir' => $user_root), $user); OC_Filesystem::init($user_dir); $quotaProxy = new OC_FileProxy_Quota(); OC_FileProxy::register($quotaProxy); // Load personal mount config if (is_file($user_root . '/mount.php')) { $mountConfig = (include $user_root . '/mount.php'); if (isset($mountConfig['user'][$user])) { foreach ($mountConfig['user'][$user] as $mountPoint => $options) { OC_Filesystem::mount($options['class'], $options['options'], $mountPoint); } } $mtime = filemtime($user_root . '/mount.php'); $previousMTime = OC_Preferences::getValue($user, 'files', 'mountconfigmtime', 0); if ($mtime > $previousMTime) { //mount config has changed, filecache needs to be updated OC_FileCache::triggerUpdate($user); OC_Preferences::setValue($user, 'files', 'mountconfigmtime', $mtime); } } OC_Hook::emit('OC_Filesystem', 'setup', array('user' => $user, 'user_dir' => $user_dir)); } }
public function testSimple() { $file = OC::$SERVERROOT . '/3rdparty/MDB2.php'; $original = file_get_contents($file); OC_Filesystem::file_put_contents('/file', $original); OC_FileProxy::$enabled = false; $stored = OC_Filesystem::file_get_contents('/file'); OC_FileProxy::$enabled = true; $fromFile = OC_Filesystem::file_get_contents('/file'); $this->assertNotEqual($original, $stored); $this->assertEqual($original, $fromFile); }
public static function createkey($username, $passcode) { // generate a random key $key = mt_rand(10000, 99999) . mt_rand(10000, 99999) . mt_rand(10000, 99999) . mt_rand(10000, 99999); // encrypt the key with the passcode of the user $enckey = OC_Crypt::encrypt($key, $passcode); // Write the file $proxyEnabled = OC_FileProxy::$enabled; OC_FileProxy::$enabled = false; $view = new OC_FilesystemView('/' . $username); $view->file_put_contents('/encryption.key', $enckey); OC_FileProxy::$enabled = $proxyEnabled; }
public static function setUpBeforeClass() { // reset backend \OC_User::clearBackends(); \OC_User::useBackend('database'); // Filesystem related hooks \OCA\Encryption\Helper::registerFilesystemHooks(); // clear and register hooks \OC_FileProxy::clearProxies(); \OC_FileProxy::register(new OCA\Encryption\Proxy()); // create test user \Test_Encryption_Util::loginHelper(\Test_Encryption_Stream::TEST_ENCRYPTION_STREAM_USER1, true); }
/** * write key to disk * * * @param string $path path to key directory * @param string $name key name * @param string $key key * @param \OC\Files\View $view * @return bool */ private static function setKey($path, $name, $key, $view) { $proxyStatus = \OC_FileProxy::$enabled; \OC_FileProxy::$enabled = false; self::keySetPreparation($view, $path); $pathToKey = \OC\Files\Filesystem::normalizePath($path . '/' . $name); $result = $view->file_put_contents($pathToKey, $key); \OC_FileProxy::$enabled = $proxyStatus; if (is_int($result) && $result > 0) { self::$key_cache[$pathToKey] = $key; return true; } return false; }
public function set($key, $value, $ttl = 0) { $storage = $this->getStorage(); $result = false; $proxyStatus = \OC_FileProxy::$enabled; \OC_FileProxy::$enabled = false; if ($storage and $storage->file_put_contents($key, $value)) { if ($ttl === 0) { $ttl = 86400; // 60*60*24 } $result = $storage->touch($key, time() + $ttl); } \OC_FileProxy::$enabled = $proxyStatus; return $result; }
public static function setupFS($user = '') { // configure the initial filesystem based on the configuration if (self::$fsSetup) { //setting up the filesystem twice can only lead to trouble return false; } // If we are not forced to load a specific user we load the one that is logged in if ($user == "" && OC_User::isLoggedIn()) { $user = OC_User::getUser(); } // load all filesystem apps before, so no setup-hook gets lost if (!isset($RUNTIME_NOAPPS) || !$RUNTIME_NOAPPS) { OC_App::loadApps(array('filesystem')); } // the filesystem will finish when $user is not empty, // mark fs setup here to avoid doing the setup from loading // OC_Filesystem if ($user != '') { self::$fsSetup = true; } $CONFIG_DATADIRECTORY = OC_Config::getValue("datadirectory", OC::$SERVERROOT . "/data"); //first set up the local "root" storage if (!self::$rootMounted) { OC_Filesystem::mount('OC_Filestorage_Local', array('datadir' => $CONFIG_DATADIRECTORY), '/'); self::$rootMounted = true; } if ($user != "") { //if we aren't logged in, there is no use to set up the filesystem $user_dir = '/' . $user . '/files'; $user_root = OC_User::getHome($user); $userdirectory = $user_root . '/files'; if (!is_dir($userdirectory)) { mkdir($userdirectory, 0755, true); } //jail the user into his "home" directory OC_Filesystem::mount('OC_Filestorage_Local', array('datadir' => $user_root), $user); OC_Filesystem::init($user_dir, $user); $quotaProxy = new OC_FileProxy_Quota(); $fileOperationProxy = new OC_FileProxy_FileOperations(); OC_FileProxy::register($quotaProxy); OC_FileProxy::register($fileOperationProxy); // Load personal mount config self::loadUserMountPoints($user); OC_Hook::emit('OC_Filesystem', 'setup', array('user' => $user, 'user_dir' => $user_dir)); } }
protected function setUp() { parent::setUp(); // load proxies OC::$CLASSPATH['OCA\\Files\\Share\\Proxy'] = 'files_sharing/lib/proxy.php'; OC_FileProxy::register(new OCA\Files\Share\Proxy()); $this->folder = self::TEST_FOLDER_NAME; $this->subfolder = '/subfolder_share_api_test'; $this->subsubfolder = '/subsubfolder_share_api_test'; $this->filename = '/share-api-test'; // save file with content $this->view->mkdir($this->folder); $this->view->mkdir($this->folder . $this->subfolder); $this->view->mkdir($this->folder . $this->subfolder . $this->subsubfolder); $this->view->file_put_contents($this->folder . $this->filename, $this->data); $this->view->file_put_contents($this->folder . $this->subfolder . $this->filename, $this->data); }
/** * if session is started, check if ownCloud key pair is set up, if not create it * @param \OC\Files\View $view * * @note The ownCloud key pair is used to allow public link sharing even if encryption is enabled */ public function __construct($view) { $this->view = $view; if (!$this->view->is_dir('owncloud_private_key')) { $this->view->mkdir('owncloud_private_key'); } $appConfig = \OC::$server->getAppConfig(); $publicShareKeyId = $appConfig->getValue('files_encryption', 'publicShareKeyId'); if ($publicShareKeyId === null) { $publicShareKeyId = 'pubShare_' . substr(md5(time()), 0, 8); $appConfig->setValue('files_encryption', 'publicShareKeyId', $publicShareKeyId); } if (!$this->view->file_exists("/public-keys/" . $publicShareKeyId . ".public.key") || !$this->view->file_exists("/owncloud_private_key/" . $publicShareKeyId . ".private.key")) { $keypair = Crypt::createKeypair(); // Disable encryption proxy to prevent recursive calls $proxyStatus = \OC_FileProxy::$enabled; \OC_FileProxy::$enabled = false; // Save public key if (!$view->is_dir('/public-keys')) { $view->mkdir('/public-keys'); } $this->view->file_put_contents('/public-keys/' . $publicShareKeyId . '.public.key', $keypair['publicKey']); // Encrypt private key empty passphrase $cipher = \OCA\Encryption\Helper::getCipher(); $encryptedKey = \OCA\Encryption\Crypt::symmetricEncryptFileContent($keypair['privateKey'], '', $cipher); if ($encryptedKey) { Keymanager::setPrivateSystemKey($encryptedKey, $publicShareKeyId . '.private.key'); } else { \OCP\Util::writeLog('files_encryption', 'Could not create public share keys', \OCP\Util::ERROR); } \OC_FileProxy::$enabled = $proxyStatus; } if (\OCA\Encryption\Helper::isPublicAccess()) { // Disable encryption proxy to prevent recursive calls $proxyStatus = \OC_FileProxy::$enabled; \OC_FileProxy::$enabled = false; $encryptedKey = $this->view->file_get_contents('/owncloud_private_key/' . $publicShareKeyId . '.private.key'); $privateKey = Crypt::decryptPrivateKey($encryptedKey, ''); $this->setPublicSharePrivateKey($privateKey); $this->setInitialized(\OCA\Encryption\Session::INIT_SUCCESSFUL); \OC_FileProxy::$enabled = $proxyStatus; } }
/** * test deletion of a folder which contains share mount points. Share mount * points should be unshared before the folder gets deleted so * that the mount point doesn't end up at the trash bin */ function testDeleteParentFolder() { $status = \OC_App::isEnabled('files_trashbin'); \OC_App::enable('files_trashbin'); \OCA\Files_Trashbin\Trashbin::registerHooks(); OC_FileProxy::register(new OCA\Files\Share\Proxy()); $fileinfo = \OC\Files\Filesystem::getFileInfo($this->folder); $this->assertTrue($fileinfo instanceof \OC\Files\FileInfo); \OCP\Share::shareItem('folder', $fileinfo->getId(), \OCP\Share::SHARE_TYPE_USER, self::TEST_FILES_SHARING_API_USER2, 31); $this->loginHelper(self::TEST_FILES_SHARING_API_USER2); $view = new \OC\Files\View('/' . self::TEST_FILES_SHARING_API_USER2 . '/files'); // check if user2 can see the shared folder $this->assertTrue($view->file_exists($this->folder)); $foldersShared = \OCP\Share::getItemsSharedWith('folder'); $this->assertSame(1, count($foldersShared)); $view->mkdir("localFolder"); $view->file_put_contents("localFolder/localFile.txt", "local file"); $view->rename($this->folder, 'localFolder/' . $this->folder); // share mount point should now be moved to the subfolder $this->assertFalse($view->file_exists($this->folder)); $this->assertTrue($view->file_exists('localFolder/' . $this->folder)); $view->unlink('localFolder'); $this->loginHelper(self::TEST_FILES_SHARING_API_USER2); // shared folder should be unshared $foldersShared = \OCP\Share::getItemsSharedWith('folder'); $this->assertTrue(empty($foldersShared)); // trashbin should contain the local file but not the mount point $rootView = new \OC\Files\View('/' . self::TEST_FILES_SHARING_API_USER2); $trashContent = \OCA\Files_Trashbin\Helper::getTrashFiles('/', self::TEST_FILES_SHARING_API_USER2); $this->assertSame(1, count($trashContent)); $firstElement = reset($trashContent); $timestamp = $firstElement['mtime']; $this->assertTrue($rootView->file_exists('files_trashbin/files/localFolder.d' . $timestamp . '/localFile.txt')); $this->assertFalse($rootView->file_exists('files_trashbin/files/localFolder.d' . $timestamp . '/' . $this->folder)); //cleanup $rootView->deleteAll('files_trashin'); if ($status === false) { \OC_App::disable('files_trashbin'); } \OC\Files\Filesystem::getLoader()->removeStorageWrapper('oc_trashbin'); }
public static function setUpBeforeClass() { // reset backend \OC_User::clearBackends(); \OC_User::useBackend('database'); \OC_Hook::clear('OC_Filesystem'); \OC_Hook::clear('OC_User'); // clear share hooks \OC_Hook::clear('OCP\\Share'); \OC::registerShareHooks(); \OCP\Util::connectHook('OC_Filesystem', 'setup', '\\OC\\Files\\Storage\\Shared', 'setup'); // Filesystem related hooks \OCA\Encryption\Helper::registerFilesystemHooks(); // Sharing related hooks \OCA\Encryption\Helper::registerShareHooks(); // clear and register proxies \OC_FileProxy::clearProxies(); \OC_FileProxy::register(new OCA\Encryption\Proxy()); // create test user \Test_Encryption_Util::loginHelper(\Test_Encryption_Hooks::TEST_ENCRYPTION_HOOKS_USER1, true); \Test_Encryption_Util::loginHelper(\Test_Encryption_Hooks::TEST_ENCRYPTION_HOOKS_USER2, true); }
public function stream_open($path, $mode, $options, &$opened_path) { $path = str_replace('crypt://', '', $path); if (dirname($path) == 'streams' and isset(self::$sourceStreams[basename($path)])) { $this->source = self::$sourceStreams[basename($path)]['stream']; $this->path = self::$sourceStreams[basename($path)]['path']; } else { $this->path = $path; OCP\Util::writeLog('files_encryption', 'open encrypted ' . $path . ' in ' . $mode, OCP\Util::DEBUG); OC_FileProxy::$enabled = false; //disable fileproxies so we can open the source file $this->source = OC_FileSystem::fopen($path, $mode); OC_FileProxy::$enabled = true; if (!is_resource($this->source)) { OCP\Util::writeLog('files_encryption', 'failed to open ' . $path, OCP\Util::ERROR); } } if (is_resource($this->source)) { $this->meta = stream_get_meta_data($this->source); } return is_resource($this->source); }
public function setUp() { //clear all proxies and hooks so we can do clean testing OC_FileProxy::clearProxies(); OC_Hook::clear('OC_Filesystem'); //enable only the encryption hook if needed if (OC_App::isEnabled('files_encryption')) { OC_FileProxy::register(new OC_FileProxy_Encryption()); } //set up temporary storage OC_Filesystem::clearMounts(); OC_Filesystem::mount('OC_Filestorage_Temporary', array(), '/'); OC_User::clearBackends(); OC_User::useBackend(new OC_User_Dummy()); //login OC_User::createUser('test', 'test'); $this->user = OC_User::getUser(); OC_User::setUserId('test'); //set up the users dir $rootView = new OC_FilesystemView(''); $rootView->mkdir('/test'); $this->instance = new OC_Cache_File(); }
/** * @brief if session is started, check if ownCloud key pair is set up, if not create it * @param \OC_FilesystemView $view * * @note The ownCloud key pair is used to allow public link sharing even if encryption is enabled */ public function __construct($view) { $this->view = $view; if (!$this->view->is_dir('owncloud_private_key')) { $this->view->mkdir('owncloud_private_key'); } $publicShareKeyId = \OC_Appconfig::getValue('files_encryption', 'publicShareKeyId'); if ($publicShareKeyId === null) { $publicShareKeyId = 'pubShare_' . substr(md5(time()), 0, 8); \OC_Appconfig::setValue('files_encryption', 'publicShareKeyId', $publicShareKeyId); } if (!$this->view->file_exists("/public-keys/" . $publicShareKeyId . ".public.key") || !$this->view->file_exists("/owncloud_private_key/" . $publicShareKeyId . ".private.key")) { $keypair = Crypt::createKeypair(); // Disable encryption proxy to prevent recursive calls $proxyStatus = \OC_FileProxy::$enabled; \OC_FileProxy::$enabled = false; // Save public key if (!$view->is_dir('/public-keys')) { $view->mkdir('/public-keys'); } $this->view->file_put_contents('/public-keys/' . $publicShareKeyId . '.public.key', $keypair['publicKey']); // Encrypt private key empty passphrase $encryptedPrivateKey = Crypt::symmetricEncryptFileContent($keypair['privateKey'], ''); // Save private key $this->view->file_put_contents('/owncloud_private_key/' . $publicShareKeyId . '.private.key', $encryptedPrivateKey); \OC_FileProxy::$enabled = $proxyStatus; } if (\OCA\Encryption\Helper::isPublicAccess()) { // Disable encryption proxy to prevent recursive calls $proxyStatus = \OC_FileProxy::$enabled; \OC_FileProxy::$enabled = false; $encryptedKey = $this->view->file_get_contents('/owncloud_private_key/' . $publicShareKeyId . '.private.key'); $privateKey = Crypt::decryptPrivateKey($encryptedKey, ''); $this->setPublicSharePrivateKey($privateKey); \OC_FileProxy::$enabled = $proxyStatus; } }
/** * Encrypt keyfile to multiple users * @param Session $session * @param array $users list of users which should be able to access the file * @param string $filePath path of the file to be shared * @return bool */ public function setSharedFileKeyfiles(Session $session, array $users, $filePath) { // Make sure users are capable of sharing $filteredUids = $this->filterShareReadyUsers($users); // If we're attempting to share to unready users if (!empty($filteredUids['unready'])) { \OCP\Util::writeLog('Encryption library', 'Sharing to these user(s) failed as they are unready for encryption:"' . print_r($filteredUids['unready'], 1), \OCP\Util::WARN); return false; } // Get public keys for each user, ready for generating sharekeys $userPubKeys = Keymanager::getPublicKeys($this->view, $filteredUids['ready']); // Note proxy status then disable it $proxyStatus = \OC_FileProxy::$enabled; \OC_FileProxy::$enabled = false; // Get the current users's private key for decrypting existing keyfile $privateKey = $session->getPrivateKey(); try { // Decrypt keyfile $plainKeyfile = $this->decryptKeyfile($filePath, $privateKey); // Re-enc keyfile to (additional) sharekeys $multiEncKey = Crypt::multiKeyEncrypt($plainKeyfile, $userPubKeys); } catch (Exception\EncryptionException $e) { $msg = 'set shareFileKeyFailed (code: ' . $e->getCode() . '): ' . $e->getMessage(); \OCP\Util::writeLog('files_encryption', $msg, \OCP\Util::FATAL); return false; } catch (\Exception $e) { $msg = 'set shareFileKeyFailed (unknown error): ' . $e->getMessage(); \OCP\Util::writeLog('files_encryption', $msg, \OCP\Util::FATAL); return false; } // Save the recrypted key to it's owner's keyfiles directory // Save new sharekeys to all necessary user directory if (!Keymanager::setFileKey($this->view, $this, $filePath, $multiEncKey['data']) || !Keymanager::setShareKeys($this->view, $this, $filePath, $multiEncKey['keys'])) { \OCP\Util::writeLog('Encryption library', 'Keyfiles could not be saved for users sharing ' . $filePath, \OCP\Util::ERROR); return false; } // Return proxy to original status \OC_FileProxy::$enabled = $proxyStatus; return true; }
/** * rollback to an old version of a file. */ public static function rollback($file, $revision) { if (\OCP\Config::getSystemValue('files_versions', Storage::DEFAULTENABLED) == 'true') { list($uid, $filename) = self::getUidAndFilename($file); $users_view = new \OC\Files\View('/' . $uid); $files_view = new \OC\Files\View('/' . \OCP\User::getUser() . '/files'); $versionCreated = false; //first create a new version $version = 'files_versions' . $filename . '.v' . $users_view->filemtime('files' . $filename); if (!$users_view->file_exists($version)) { // disable proxy to prevent multiple fopen calls $proxyStatus = \OC_FileProxy::$enabled; \OC_FileProxy::$enabled = false; $users_view->copy('files' . $filename, 'files_versions' . $filename . '.v' . $users_view->filemtime('files' . $filename)); // reset proxy state \OC_FileProxy::$enabled = $proxyStatus; $versionCreated = true; } // rollback if (@$users_view->rename('files_versions' . $filename . '.v' . $revision, 'files' . $filename)) { $files_view->touch($file, $revision); Storage::expire($file); return true; } else { if ($versionCreated) { $users_view->unlink($version); } } } return false; }
public function file_assemble($path) { $absolutePath = OC_Filesystem::normalizePath(OC_Filesystem::getView()->getAbsolutePath($path)); $data = ''; // use file_put_contents as method because that best matches what this function does if (OC_FileProxy::runPreProxies('file_put_contents', $absolutePath, $data) && OC_Filesystem::isValidPath($path)) { $path = OC_Filesystem::getView()->getRelativePath($absolutePath); $exists = OC_Filesystem::file_exists($path); $run = true; if (!$exists) { OC_Hook::emit(OC_Filesystem::CLASSNAME, OC_Filesystem::signal_create, array(OC_Filesystem::signal_param_path => $path, OC_Filesystem::signal_param_run => &$run)); } OC_Hook::emit(OC_Filesystem::CLASSNAME, OC_Filesystem::signal_write, array(OC_Filesystem::signal_param_path => $path, OC_Filesystem::signal_param_run => &$run)); if (!$run) { return false; } $target = OC_Filesystem::fopen($path, 'w'); if ($target) { $count = $this->assemble($target); fclose($target); if (!$exists) { OC_Hook::emit(OC_Filesystem::CLASSNAME, OC_Filesystem::signal_post_create, array(OC_Filesystem::signal_param_path => $path)); } OC_Hook::emit(OC_Filesystem::CLASSNAME, OC_Filesystem::signal_post_write, array(OC_Filesystem::signal_param_path => $path)); OC_FileProxy::runPostProxies('file_put_contents', $absolutePath, $count); return $count > 0; } else { return false; } } }
/** * @medium * @brief Test that data that is read by the crypto stream wrapper */ function testSymmetricStreamDecryptShortFileContent() { $filename = 'tmp-' . uniqid(); // Save long data as encrypted file using stream wrapper $cryptedFile = file_put_contents('crypt:///' . $this->userId . '/files/' . $filename, $this->dataShort); // Test that data was successfully written $this->assertTrue(is_int($cryptedFile)); // Disable encryption proxy to prevent recursive calls $proxyStatus = \OC_FileProxy::$enabled; \OC_FileProxy::$enabled = false; $this->assertTrue(Encryption\Crypt::isEncryptedMeta($filename)); \OC_FileProxy::$enabled = $proxyStatus; // Get file decrypted contents $decrypt = file_get_contents('crypt:///' . $this->userId . '/files/' . $filename); $this->assertEquals($this->dataShort, $decrypt); // tear down $this->view->unlink($this->userId . '/files/' . $filename); }
/** * @brief if the file was really deleted we remove the encryption keys * @param array $params * @return boolean */ public static function postDelete($params) { if (!isset(self::$deleteFiles[$params[\OC\Files\Filesystem::signal_param_path]])) { return true; } $deletedFile = self::$deleteFiles[$params[\OC\Files\Filesystem::signal_param_path]]; $path = $deletedFile['path']; $user = $deletedFile['uid']; // we don't need to remember the file any longer unset(self::$deleteFiles[$params[\OC\Files\Filesystem::signal_param_path]]); $view = new \OC\Files\View('/'); // return if the file still exists and wasn't deleted correctly if ($view->file_exists('/' . $user . '/files/' . $path)) { return true; } // Disable encryption proxy to prevent recursive calls $proxyStatus = \OC_FileProxy::$enabled; \OC_FileProxy::$enabled = false; // Delete keyfile & shareKey so it isn't orphaned if (!Keymanager::deleteFileKey($view, $path, $user)) { \OCP\Util::writeLog('Encryption library', 'Keyfile or shareKey could not be deleted for file "' . $user . '/files/' . $path . '"', \OCP\Util::ERROR); } Keymanager::delAllShareKeys($view, $user, $path); \OC_FileProxy::$enabled = $proxyStatus; }