Пример #1
0
 /**
  * Adds a secret to config.php
  */
 private function addSecret()
 {
     if (\OC::$server->getConfig()->getSystemValue('secret', null) === null) {
         $secret = \OC_Util::generateRandomBytes(96);
         \OC::$server->getConfig()->setSystemValue('secret', $secret);
     }
 }
Пример #2
0
 public static function sendEmail($args)
 {
     $isEncrypted = \OC_App::isEnabled('files_encryption');
     if (!$isEncrypted || isset($_POST['continue'])) {
         $continue = true;
     } else {
         $continue = false;
     }
     if (\OC_User::userExists($_POST['user']) && $continue) {
         $token = hash('sha256', \OC_Util::generateRandomBytes(30) . \OC_Config::getValue('passwordsalt', ''));
         \OC_Preferences::setValue($_POST['user'], 'owncloud', 'lostpassword', hash('sha256', $token));
         // Hash the token again to prevent timing attacks
         $email = \OC_Preferences::getValue($_POST['user'], 'settings', 'email', '');
         if (!empty($email)) {
             $link = \OC_Helper::linkToRoute('core_lostpassword_reset', array('user' => $_POST['user'], 'token' => $token));
             $link = \OC_Helper::makeURLAbsolute($link);
             $tmpl = new \OC_Template('core/lostpassword', 'email');
             $tmpl->assign('link', $link, false);
             $msg = $tmpl->fetchPage();
             $l = \OC_L10N::get('core');
             $from = \OCP\Util::getDefaultEmailAddress('lostpassword-noreply');
             try {
                 $defaults = new \OC_Defaults();
                 \OC_Mail::send($email, $_POST['user'], $l->t('%s password reset', array($defaults->getName())), $msg, $from, $defaults->getName());
             } catch (Exception $e) {
                 \OC_Template::printErrorPage('A problem occurs during sending the e-mail please contact your administrator.');
             }
             self::displayLostPasswordPage(false, true);
         } else {
             self::displayLostPasswordPage(true, false);
         }
     } else {
         self::displayLostPasswordPage(true, false);
     }
 }
Пример #3
0
 public static function post_login($parameters)
 {
     $uid = $parameters['uid'];
     $casBackend = OC_USER_CAS::getInstance();
     $userDatabase = new OC_User_Database();
     if (phpCAS::isAuthenticated()) {
         // $cas_attributes may vary in name, therefore attributes are fetched to $attributes
         $cas_attributes = phpCAS::getAttributes();
         $cas_uid = phpCAS::getUser();
         // parameters
         $attributes = array();
         if ($cas_uid == $uid) {
             OC_Log::write('cas', 'attr  \\"' . implode(',', $cas_attributes) . '\\" for the user: '******'cas_name'] = $cas_attributes[$casBackend->displayNameMapping];
             } else {
                 $attributes['cas_name'] = $cas_attributes['cn'];
             }
             if (array_key_exists($casBackend->mailMapping, $cas_attributes)) {
                 $attributes['cas_email'] = $cas_attributes[$casBackend->mailMapping];
             } else {
                 $attributes['cas_email'] = $cas_attributes['mail'];
             }
             if (array_key_exists($casBackend->groupMapping, $cas_attributes)) {
                 $attributes['cas_groups'] = $cas_attributes[$casBackend->groupMapping];
             } else {
                 if (!empty($casBackend->defaultGroup)) {
                     $attributes['cas_groups'] = array($casBackend->defaultGroup);
                     OC_Log::write('cas', 'Using default group "' . $casBackend->defaultGroup . '" for the user: '******'/[^a-zA-Z0-9 _\\.@\\-]/', $uid)) {
                     OC_Log::write('cas', 'Invalid username "' . $uid . '", allowed chars "a-zA-Z0-9" and "_.@-" ', OC_Log::DEBUG);
                     return false;
                 } else {
                     $random_password = OC_Util::generateRandomBytes(20);
                     OC_Log::write('cas', 'Creating new user: ' . $uid, OC_Log::DEBUG);
                     $userDatabase->createUser($uid, $random_password);
                     // after creating the user, fill the attributes
                     if ($userDatabase->userExists($uid)) {
                         OC_USER_CAS_Hooks::update_user($uid, $attributes);
                     }
                 }
             }
             // try to update user attributes
             if ($casBackend->updateUserData) {
                 OC_USER_CAS_Hooks::update_user($cas_uid, $attributes);
             }
             return true;
         }
     }
     return false;
 }
Пример #4
0
 public function setupDatabase($username)
 {
     //check if the database user has admin right
     $connection = @mysql_connect($this->dbhost, $this->dbuser, $this->dbpassword);
     if (!$connection) {
         throw new \OC\DatabaseSetupException($this->trans->t('MySQL/MariaDB username and/or password not valid'), $this->trans->t('You need to enter either an existing account or the administrator.'));
     }
     //user already specified in config
     $oldUser = \OC_Config::getValue('dbuser', false);
     //we don't have a dbuser specified in config
     if ($this->dbuser != $oldUser) {
         //add prefix to the admin username to prevent collisions
         $adminUser = substr('oc_' . $username, 0, 16);
         $i = 1;
         while (true) {
             //this should be enough to check for admin rights in mysql
             $query = "SELECT user FROM mysql.user WHERE user='******'";
             $result = mysql_query($query, $connection);
             //current dbuser has admin rights
             if ($result) {
                 //new dbuser does not exist
                 if (mysql_num_rows($result) === 0) {
                     //use the admin login data for the new database user
                     $this->dbuser = $adminUser;
                     //create a random password so we don't need to store the admin password in the config file
                     $this->dbpassword = \OC_Util::generateRandomBytes(30);
                     $this->createDBUser($connection);
                     break;
                 } else {
                     //repeat with different username
                     $length = strlen((string) $i);
                     $adminUser = substr('oc_' . $username, 0, 16 - $length) . $i;
                     $i++;
                 }
             } else {
                 break;
             }
         }
         \OC_Config::setValue('dbuser', $this->dbuser);
         \OC_Config::setValue('dbpassword', $this->dbpassword);
     }
     //create the database
     $this->createDatabase($connection);
     //fill the database if needed
     $query = 'select count(*) from information_schema.tables' . " where table_schema='" . $this->dbname . "' AND table_name = '" . $this->tableprefix . "users';";
     $result = mysql_query($query, $connection);
     if ($result) {
         $row = mysql_fetch_row($result);
     }
     if (!$result or $row[0] == 0) {
         \OC_DB::createDbFromStructure($this->dbDefinitionFile);
     }
     mysql_close($connection);
 }
Пример #5
0
 function setUp()
 {
     $this->username = OC_Util::generateRandomBytes(20);
     OC_User::createUser($this->username, OC_Util::generateRandomBytes(20));
     \OC_Util::tearDownFS();
     \OC_User::setUserId('');
     \OC\Files\Filesystem::tearDown();
     \OC_Util::setupFS($this->username);
     $this->user = \OC::$server->getUserManager()->get($this->username);
     $this->certificateManager = new CertificateManager($this->user);
 }
Пример #6
0
 /**
  * Encrypts a value and adds an HMAC (Encrypt-Then-MAC)
  * @param string $plaintext
  * @param string $password Password to encrypt, if not specified the secret from config.php will be taken
  * @return string Authenticated ciphertext
  */
 public function encrypt($plaintext, $password = '')
 {
     if ($password === '') {
         $password = $this->config->getSystemValue('secret');
     }
     $this->cipher->setPassword($password);
     $iv = \OC_Util::generateRandomBytes($this->ivLength);
     $this->cipher->setIV($iv);
     $ciphertext = bin2hex($this->cipher->encrypt($plaintext));
     $hmac = bin2hex($this->calculateHMAC($ciphertext . $iv, $password));
     return $ciphertext . '|' . $iv . '|' . $hmac;
 }
Пример #7
0
 public function setUp()
 {
     $dbfile = OC::$SERVERROOT . '/tests/data/db_structure.xml';
     $dbfile2 = OC::$SERVERROOT . '/tests/data/db_structure2.xml';
     $r = '_' . OC_Util::generateRandomBytes(4) . '_';
     $content = file_get_contents($dbfile);
     $content = str_replace('*dbprefix*', '*dbprefix*' . $r, $content);
     file_put_contents($this->schema_file, $content);
     $content = file_get_contents($dbfile2);
     $content = str_replace('*dbprefix*', '*dbprefix*' . $r, $content);
     file_put_contents($this->schema_file2, $content);
     $this->table1 = $r . 'cntcts_addrsbks';
     $this->table2 = $r . 'cntcts_cards';
 }
Пример #8
0
 public function setUp()
 {
     $dbfile = OC::$SERVERROOT . '/tests/data/db_structure.xml';
     $r = '_' . OC_Util::generateRandomBytes(4) . '_';
     $content = file_get_contents($dbfile);
     $content = str_replace('*dbprefix*', '*dbprefix*' . $r, $content);
     file_put_contents(self::$schema_file, $content);
     OC_DB::createDbFromStructure(self::$schema_file);
     $this->test_prefix = $r;
     $this->table1 = $this->test_prefix . 'cntcts_addrsbks';
     $this->table2 = $this->test_prefix . 'cntcts_cards';
     $this->table3 = $this->test_prefix . 'vcategory';
     $this->table4 = $this->test_prefix . 'decimal';
 }
Пример #9
0
 /**
  * Compares whether two strings are equal. To prevent guessing of the string
  * length this is done by comparing two hashes against each other and afterwards
  * a comparison of the real string to prevent against the unlikely chance of
  * collisions.
  *
  * Be aware that this function may leak whether the string to compare have a different
  * length.
  *
  * @param string $expected The expected value
  * @param string $input The input to compare against
  * @return bool True if the two strings are equal, otherwise false.
  */
 public static function equals($expected, $input)
 {
     if (!is_string($expected) || !is_string($input)) {
         return false;
     }
     if (function_exists('hash_equals')) {
         return hash_equals($expected, $input);
     }
     $randomString = \OC_Util::generateRandomBytes(10);
     if (hash('sha512', $expected . $randomString) === hash('sha512', $input . $randomString)) {
         if ($expected === $input) {
             return true;
         }
     }
     return false;
 }
Пример #10
0
 public static function xsetUpBeforeClass()
 {
     $dbfile = __DIR__ . '/../../appinfo/database.xml';
     self::$test_prefix = '_' . OC_Util::generateRandomBytes('4') . '_';
     $content = file_get_contents($dbfile);
     $content = str_replace('*dbprefix*', '*dbprefix*' . self::$test_prefix, $content);
     file_put_contents(self::$schema_file, $content);
     OC_DB::createDbFromStructure(self::$schema_file);
     self::$addressBooksTableName = '*PREFIX*' . self::$test_prefix . 'contacts_addressbooks';
     self::$cardsTableName = '*PREFIX*' . self::$test_prefix . 'contacts_cards';
     OC_User::clearBackends();
     OC_User::useBackend('dummy');
     self::$user = uniqid('user_');
     OC_User::createUser(self::$user, 'pass');
     OC_User::setUserId(self::$user);
     self::$backend = new OCA\Contacts\Backend\Database(self::$user, self::$addressBooksTableName, self::$cardsTableName);
 }
Пример #11
0
 public function setupDatabase($username)
 {
     //check if the database user has admin right
     $connection = @mysql_connect($this->dbhost, $this->dbuser, $this->dbpassword);
     if (!$connection) {
         throw new \DatabaseSetupException($this->trans->t('MySQL username and/or password not valid'), $this->trans->t('You need to enter either an existing account or the administrator.'));
     }
     $oldUser = \OC_Config::getValue('dbuser', false);
     //this should be enough to check for admin rights in mysql
     $query = "SELECT user FROM mysql.user WHERE user='******'";
     if (mysql_query($query, $connection)) {
         //use the admin login data for the new database user
         //add prefix to the mysql user name to prevent collisions
         $this->dbuser = substr('oc_' . $username, 0, 16);
         if ($this->dbuser != $oldUser) {
             //hash the password so we don't need to store the admin config in the config file
             $this->dbpassword = \OC_Util::generateRandomBytes(30);
             $this->createDBUser($connection);
             \OC_Config::setValue('dbuser', $this->dbuser);
             \OC_Config::setValue('dbpassword', $this->dbpassword);
         }
         //create the database
         $this->createDatabase($connection);
     } else {
         if ($this->dbuser != $oldUser) {
             \OC_Config::setValue('dbuser', $this->dbuser);
             \OC_Config::setValue('dbpassword', $this->dbpassword);
         }
         //create the database
         $this->createDatabase($connection);
     }
     //fill the database if needed
     $query = 'select count(*) from information_schema.tables' . " where table_schema='" . $this->dbname . "' AND table_name = '" . $this->tableprefix . "users';";
     $result = mysql_query($query, $connection);
     if ($result) {
         $row = mysql_fetch_row($result);
     }
     if (!$result or $row[0] == 0) {
         \OC_DB::createDbFromStructure($this->dbDefinitionFile);
     }
     mysql_close($connection);
 }
Пример #12
0
 public static function post_login($parameters)
 {
     // Do nothing if we're sharding and not on the master
     if (OCP\App::isEnabled('files_sharding') && !OCA\FilesSharding\Lib::isMaster()) {
         return true;
     }
     $uid = '';
     $userid = $parameters['uid'];
     $samlBackend = new OC_USER_SAML();
     $ocUserDatabase = new OC_User_Database();
     // Redirect regardless of whether the user has authenticated with SAML or not.
     // Since this is a post_login hook, he will have authenticated in some way and have a valid session.
     if ($ocUserDatabase->userExists($userid)) {
         // Set user attributes for sharding
         $display_name = \OCP\User::getDisplayName($userid);
         $email = \OCP\Config::getUserValue($userid, 'settings', 'email');
         $groups = \OC_Group::getUserGroups($userid);
         $quota = \OC_Preferences::getValue($userid, 'files', 'quota');
         OC_Util::teardownFS($userid);
         OC_Util::setupFS($userid);
         OC_Log::write('saml', 'Setting user attributes: ' . $userid . ":" . $display_name . ":" . $email . ":" . join($groups) . ":" . $quota, OC_Log::INFO);
         self::setAttributes($userid, $display_name, $email, $groups, $quota);
         self::user_redirect($userid);
     }
     if (!$samlBackend->auth->isAuthenticated()) {
         return false;
     }
     $attributes = $samlBackend->auth->getAttributes();
     //$email = "<pre>" . print_r($attributes, 1) . "</pre>";
     //$headers = 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
     //error_log($email, 1, '*****@*****.**', $headers);
     $usernameFound = false;
     foreach ($samlBackend->usernameMapping as $usernameMapping) {
         if (array_key_exists($usernameMapping, $attributes) && !empty($attributes[$usernameMapping][0])) {
             $usernameFound = true;
             $uid = $attributes[$usernameMapping][0];
             OC_Log::write('saml', 'Authenticated user ' . $uid, OC_Log::INFO);
             break;
         }
     }
     if (!$usernameFound || $uid !== $userid) {
         return false;
     }
     $attrs = self::get_user_attributes($uid, $samlBackend);
     if (!$ocUserDatabase->userExists($uid)) {
         // If autocreate is not enabled - back off
         if (!$samlBackend->autocreate) {
             return false;
         }
         // Apparently it is necessary to clear the uid first, to be able to create the user in the DB
         $userManager = \OC_User::getManager();
         $userManager->delete($uid);
         // Reject invalid user names
         if (preg_match('/[^a-zA-Z0-9 _\\.@\\-]/', $uid)) {
             OC_Log::write('saml', 'Invalid username "' . $uid . '", allowed chars "a-zA-Z0-9" and "_.@-" ', OC_Log::DEBUG);
             return false;
         }
         $cookiedomain = OCP\App::isEnabled('files_sharding') ? OCA\FilesSharding\Lib::getCookieDomain() : null;
         // Reject users we don't allow to autocreate an account
         if (isset($uid) && trim($uid) != '' && !OC_User::userExists($uid) && !self::check_user_attributes($attributes)) {
             $failCookieName = 'saml_auth_fail';
             $userCookieName = 'saml_auth_fail_user';
             $expire = 0;
             //time()+60*60*24*30;
             $expired = time() - 3600;
             $path = '/';
             setcookie($failCookieName, "notallowed:" . $uid, $expire, $path, $cookiedomain, false, false);
             setcookie($userCookieName, $uid, $expire, $path, $cookiedomain, false, false);
             $spSource = 'default-sp';
             $auth = new SimpleSAML_Auth_Simple($spSource);
             OC_Log::write('saml', 'Rejected user "' . $uid, OC_Log::ERROR);
             if (OCP\App::isEnabled('files_sharding') && !OCA\FilesSharding\Lib::isMaster()) {
                 $auth->logout(!OCA\FilesSharding\Lib::getMasterURL());
             } else {
                 $auth->logout();
             }
             return false;
         }
         // Create new user
         $random_password = OC_Util::generateRandomBytes(20);
         OC_Log::write('saml', 'Creating new user: '******'/' . $uid . '/files';
             \OC\Files\Filesystem::init($uid, $userDir);
             if ($samlBackend->updateUserData) {
                 self::update_user_data($uid, $samlBackend, $attrs, true);
                 if (OCP\App::isEnabled('files_sharding') && OCA\FilesSharding\Lib::isMaster()) {
                     $master_site = OCA\FilesSharding\Lib::dbGetSite(null);
                     $server_id = OCA\FilesSharding\Lib::dbChooseServerForUser($uid, $master_site, 0, null);
                     OC_Log::write('saml', 'Setting server for new user: '******'display_name'], $attrs['email'], $attrs['groups'], $attrs['quota']);
         }
     } else {
         if ($samlBackend->updateUserData) {
             self::update_user_data($uid, $samlBackend, $attrs, false);
         }
     }
     self::user_redirect($userid);
     return true;
 }
Пример #13
0
 public static function post_login($parameters)
 {
     $uid = $parameters['uid'];
     $wuid = $uid;
     $casBackend = new OC_USER_CAS();
     $userDB = new OC_User_Database();
     /*
      * Récupération des données du fichier config général /config/config.php
      */
     $serveur_Search = OCP\Config::getSystemValue('serveur_Search', 'error');
     $port = OCP\Config::getSystemValue('port', 'error');
     $racineAMU = OCP\Config::getSystemValue('racineAMU', 'error');
     $racineAMUGRP = OCP\Config::getSystemValue('racineAMUGRP', 'error');
     $AMU_nuage_dn = OCP\Config::getSystemValue('AMU_nuage_dn', 'error');
     $AMU_nuage_pw = OCP\Config::getSystemValue('AMU_nuage_pw', 'error');
     $PQuota = OCP\Config::getSystemValue('PQuota', 'unManaged');
     $EQuota = OCP\Config::getSystemValue('EQuota', 'unManaged');
     $LDAP = new LDAP_Infos($serveur_Search, $AMU_nuage_dn, $AMU_nuage_pw, $racineAMUGRP, $racineAMUGRP);
     $restrictGrp = array("cn", "member");
     /*
      * Récupération tableau Groupes
      * Si le tableau 'groupMapping' est vide pas de contrôle sur les groupes
      */
     $AccesCloud = 0;
     OCP\Util::writeLog('user_cas', "Authentification (Mapping groups=" . $casBackend->groupMapping . ")", OCP\Util::DEBUG);
     if ($casBackend->groupMapping) {
         $wTabGrp = str_replace(array('<br>', '<br />', "\n", "\r"), array('@', '', '@', ''), $casBackend->groupMapping);
         $tabGRP = explode("@", $wTabGrp);
         $i = 0;
         $mesGroupes = array();
         foreach ($tabGRP as $key => $value) {
             $ListeMembre = $LDAP->getMembersOfGroup($value, $restrictGrp);
             if (in_array($uid, $ListeMembre)) {
                 $AccesCloudAMU = 1;
             }
         }
     } else {
         $AccesCloud = 1;
     }
     /*
      * Si pas d'acces, alors déconnexion
      */
     if ($AccesCloud == 0) {
         /*
          * On vérifie si le compte utilisé est un compte local
          */
         if (!$userDB->userExists($uid)) {
             OCP\Util::writeLog('user_cas', "Aucun droit d'accès pour l'utilisateur " . $uid, OCP\Util::ERROR);
             \OC_User::logout();
         } else {
             OCP\Util::writeLog('user_cas', "Authentification locale pour l'utilisateur " . $uid, OCP\Util::DEBUG);
             OC::$REQUESTEDAPP = '';
             OC_Util::redirectToDefaultPage();
             exit(0);
         }
     }
     /**
      * Récupère les groupes liés à l'utilisateur avec la racine définie dans le formulaire 'cas_group_root'
      * Si 'cas_group_root' n'est pas renseingé => pas de récupération de groupes
      */
     $mesGroupes = array();
     OCP\Util::writeLog('user_cas', "Authentification (Racine Groupes LDAP=" . $casBackend->groupRoot . ")", OCP\Util::DEBUG);
     if ($casBackend->groupRoot) {
         $i = 0;
         $ListeGRP = $LDAP->getMemberOf($uid);
         $a = sizeof($ListeGRP);
         OCP\Util::writeLog('user_cas', "Taille=" . $a . " UID=" . $uid, OCP\Util::ERROR);
         OCP\Util::writeLog('user_cas', "Racine Groupe=" . $casBackend->groupRoot, OCP\Util::ERROR);
         foreach ($ListeGRP as $key => $value) {
             if (strstr($value, $casBackend->groupRoot)) {
                 $mesGroupes[$i] = strtoupper(str_replace(':', '_', substr($value, 8)));
                 OCP\Util::writeLog('user_cas', "Groupe[{$i}]=" . $mesGroupes[$i], OCP\Util::ERROR);
                 $i++;
             }
         }
     }
     if (phpCAS::checkAuthentication()) {
         //$attributes = phpCAS::getAttributes();
         $cas_uid = phpCAS::getUser();
         if ($cas_uid == $uid) {
             /*
              * Récupération des information utilisateur (LDAP)
              */
             $tabLdapUser = $LDAP->getUserInfo($uid);
             if ($tabLdapUser) {
                 $DisplayName = $tabLdapUser['displayName'];
             }
             if (!$userDB->userExists($uid)) {
                 if (preg_match('/[^a-zA-Z0-9 _\\.@\\-]/', $uid)) {
                     OCP\Util::writeLog('cas', 'Utilisateur  invalide "' . $uid . '", caracteres autorises "a-zA-Z0-9" and "_.@-" ', OCP\Util::DEBUG);
                     return false;
                 } else {
                     /*
                      * Dans le cas d'une création
                      */
                     $random_password = \OC_Util::generateRandomBytes(20);
                     $userDB->createUser($uid, $tabLdapUser['userpassword']);
                     $userDB->setDisplayName($uid, $DisplayName);
                     /*
                      * Mise à jour du quota si gestion dans fichier de configuration
                      */
                     if ($EQuota != "unManaged" && $tabLdapUser['eduPersonPrimaryAffiliation'] == 'student') {
                         update_quota($uid, $EQuota);
                     }
                     if ($PQuota != "unManaged" && $tabLdapUser['eduPersonPrimaryAffiliation'] != 'student') {
                         update_quota($uid, $PQuota);
                     }
                 }
             }
             /*
              * Mise à jour des groupes associés
              */
             if (sizeof($mesGroupes) > 0) {
                 $cas_groups = $mesGroupes;
                 update_groups($uid, $cas_groups, $casBackend->protectedGroups, true);
             }
             /*
              * Mise à jour du mail
              */
             update_mail($uid, $tabLdapUser['Mail']);
             /*
              * Mise à jour du display name
              */
             $userDB->setDisplayName($uid, $DisplayName);
             return true;
         }
     }
     return false;
 }
Пример #14
0
 /**
  * @param $options
  * @return array
  */
 public static function install($options)
 {
     $l = self::getTrans();
     $error = array();
     $dbtype = $options['dbtype'];
     if (empty($options['adminlogin'])) {
         $error[] = $l->t('Set an admin username.');
     }
     if (empty($options['adminpass'])) {
         $error[] = $l->t('Set an admin password.');
     }
     if (empty($options['directory'])) {
         $options['directory'] = OC::$SERVERROOT . "/data";
     }
     if (!isset(self::$dbSetupClasses[$dbtype])) {
         $dbtype = 'sqlite';
     }
     $username = htmlspecialchars_decode($options['adminlogin']);
     $password = htmlspecialchars_decode($options['adminpass']);
     $datadir = htmlspecialchars_decode($options['directory']);
     $class = self::$dbSetupClasses[$dbtype];
     /** @var \OC\Setup\AbstractDatabase $dbSetup */
     $dbSetup = new $class(self::getTrans(), 'db_structure.xml');
     $error = array_merge($error, $dbSetup->validate($options));
     // validate the data directory
     if (!is_dir($datadir) and !mkdir($datadir) or !is_writable($datadir)) {
         $error[] = $l->t("Can't create or write into the data directory %s", array($datadir));
     }
     if (count($error) != 0) {
         return $error;
     }
     //no errors, good
     if (isset($options['trusted_domains']) && is_array($options['trusted_domains'])) {
         $trustedDomains = $options['trusted_domains'];
     } else {
         $trustedDomains = array(\OC_Request::getDomainWithoutPort(\OC_Request::serverHost()));
     }
     if (OC_Util::runningOnWindows()) {
         $datadir = rtrim(realpath($datadir), '\\');
     }
     //use sqlite3 when available, otherise sqlite2 will be used.
     if ($dbtype == 'sqlite' and class_exists('SQLite3')) {
         $dbtype = 'sqlite3';
     }
     //generate a random salt that is used to salt the local user passwords
     $salt = OC_Util::generateRandomBytes(30);
     OC_Config::setValue('passwordsalt', $salt);
     OC_Config::setValue('secret', OC_Util::generateRandomBytes(96));
     //write the config file
     OC_Config::setValue('trusted_domains', $trustedDomains);
     OC_Config::setValue('datadirectory', $datadir);
     OC_Config::setValue('overwrite.cli.url', \OC_Request::serverProtocol() . '://' . \OC_Request::serverHost() . OC::$WEBROOT);
     OC_Config::setValue('dbtype', $dbtype);
     OC_Config::setValue('version', implode('.', OC_Util::getVersion()));
     try {
         $dbSetup->initialize($options);
         $dbSetup->setupDatabase($username);
     } catch (DatabaseSetupException $e) {
         $error[] = array('error' => $e->getMessage(), 'hint' => $e->getHint());
         return $error;
     } catch (Exception $e) {
         $error[] = array('error' => 'Error while trying to create admin user: '******'hint' => '');
         return $error;
     }
     //create the user and group
     try {
         OC_User::createUser($username, $password);
     } catch (Exception $exception) {
         $error[] = $exception->getMessage();
     }
     if (count($error) == 0) {
         $appConfig = \OC::$server->getAppConfig();
         $appConfig->setValue('core', 'installedat', microtime(true));
         $appConfig->setValue('core', 'lastupdatedat', microtime(true));
         OC_Group::createGroup('admin');
         OC_Group::addToGroup($username, 'admin');
         OC_User::login($username, $password);
         //guess what this does
         OC_Installer::installShippedApps();
         // create empty file in data dir, so we can later find
         // out that this is indeed an ownCloud data directory
         file_put_contents(OC_Config::getValue('datadirectory', OC::$SERVERROOT . '/data') . '/.ocdata', '');
         // Update htaccess files for apache hosts
         if (isset($_SERVER['SERVER_SOFTWARE']) && strstr($_SERVER['SERVER_SOFTWARE'], 'Apache')) {
             self::updateHtaccess();
             self::protectDataDirectory();
         }
         //and we are done
         OC_Config::setValue('installed', true);
     }
     return $error;
 }
Пример #15
0
	/**
	 * Tries to login a user using the formbased authentication
	 * @return bool|void
	 */
	protected static function tryFormLogin() {
		if (!isset($_POST["user"]) || !isset($_POST['password'])) {
			return false;
		}

		if(!OC_Util::isCallRegistered()) {
			return false;
		}
		OC_App::loadApps();

		//setup extra user backends
		OC_User::setupBackends();

		if (OC_User::login($_POST["user"], $_POST["password"])) {
			// setting up the time zone
			if (isset($_POST['timezone-offset'])) {
				self::$session->set('timezone', $_POST['timezone-offset']);
			}

			$userid = OC_User::getUser();
			self::cleanupLoginTokens($userid);
			if (!empty($_POST["remember_login"])) {
				if (defined("DEBUG") && DEBUG) {
					OC_Log::write('core', 'Setting remember login to cookie', OC_Log::DEBUG);
				}
				$token = OC_Util::generateRandomBytes(32);
				OC_Preferences::setValue($userid, 'login_token', $token, time());
				OC_User::setMagicInCookie($userid, $token);
			} else {
				OC_User::unsetMagicInCookie();
			}
			OC_Util::redirectToDefaultPage();
			exit();
		}
		return true;
	}
Пример #16
0
 protected function getUniqueSessionId()
 {
     $testSession = new Db_Session();
     do {
         // this prevents branching for stable5 for now:
         // OC_Util::generate_random_bytes was camelCased
         if (method_exists('\\OC_Util', 'generate_random_bytes')) {
             $id = \OC_Util::generate_random_bytes(30);
         } else {
             $id = \OC_Util::generateRandomBytes(30);
         }
     } while ($testSession->load($id)->hasData());
     return $id;
 }
Пример #17
0
 public function setupDatabase($username)
 {
     $e_host = addslashes($this->dbhost);
     $e_dbname = addslashes($this->dbname);
     //check if the database user has admin right
     if ($e_host == '') {
         $easy_connect_string = $e_dbname;
         // use dbname as easy connect name
     } else {
         $easy_connect_string = '//' . $e_host . '/' . $e_dbname;
     }
     \OC_Log::write('setup oracle', 'connect string: ' . $easy_connect_string, \OC_Log::DEBUG);
     $connection = @oci_connect($this->dbuser, $this->dbpassword, $easy_connect_string);
     if (!$connection) {
         $errorMessage = $this->getLastError();
         if ($errorMessage) {
             throw new \DatabaseSetupException($this->trans->t('Oracle connection could not be established'), $errorMessage . ' Check environment: ORACLE_HOME=' . getenv('ORACLE_HOME') . ' ORACLE_SID=' . getenv('ORACLE_SID') . ' LD_LIBRARY_PATH=' . getenv('LD_LIBRARY_PATH') . ' NLS_LANG=' . getenv('NLS_LANG') . ' tnsnames.ora is ' . (is_readable(getenv('ORACLE_HOME') . '/network/admin/tnsnames.ora') ? '' : 'not ') . 'readable');
         }
         throw new \DatabaseSetupException($this->trans->t('Oracle username and/or password not valid'), 'Check environment: ORACLE_HOME=' . getenv('ORACLE_HOME') . ' ORACLE_SID=' . getenv('ORACLE_SID') . ' LD_LIBRARY_PATH=' . getenv('LD_LIBRARY_PATH') . ' NLS_LANG=' . getenv('NLS_LANG') . ' tnsnames.ora is ' . (is_readable(getenv('ORACLE_HOME') . '/network/admin/tnsnames.ora') ? '' : 'not ') . 'readable');
     }
     //check for roles creation rights in oracle
     $query = 'SELECT count(*) FROM user_role_privs, role_sys_privs' . " WHERE user_role_privs.granted_role = role_sys_privs.role AND privilege = 'CREATE ROLE'";
     $stmt = oci_parse($connection, $query);
     if (!$stmt) {
         $entry = $this->trans->t('DB Error: "%s"', array($this->getLastError($connection))) . '<br />';
         $entry .= $this->trans->t('Offending command was: "%s"', array($query)) . '<br />';
         \OC_Log::write('setup.oci', $entry, \OC_Log::WARN);
     }
     $result = oci_execute($stmt);
     if ($result) {
         $row = oci_fetch_row($stmt);
     }
     if ($result and $row[0] > 0) {
         //use the admin login data for the new database user
         //add prefix to the oracle user name to prevent collisions
         $this->dbuser = '******' . $username;
         //create a new password so we don't need to store the admin config in the config file
         $this->dbpassword = \OC_Util::generateRandomBytes(30);
         //oracle passwords are treated as identifiers:
         //  must start with alphanumeric char
         //  needs to be shortened to 30 bytes, as the two " needed to escape the identifier count towards the identifier length.
         $this->dbpassword = substr($this->dbpassword, 0, 30);
         $this->createDBUser($connection);
         \OC_Config::setValue('dbuser', $this->dbuser);
         \OC_Config::setValue('dbname', $this->dbuser);
         \OC_Config::setValue('dbpassword', $this->dbpassword);
         //create the database not necessary, oracle implies user = schema
         //$this->createDatabase($this->dbname, $this->dbuser, $connection);
     } else {
         \OC_Config::setValue('dbuser', $this->dbuser);
         \OC_Config::setValue('dbname', $this->dbname);
         \OC_Config::setValue('dbpassword', $this->dbpassword);
         //create the database not necessary, oracle implies user = schema
         //$this->createDatabase($this->dbname, $this->dbuser, $connection);
     }
     //FIXME check tablespace exists: select * from user_tablespaces
     // the connection to dbname=oracle is not needed anymore
     oci_close($connection);
     // connect to the oracle database (schema=$this->dbuser) an check if the schema needs to be filled
     $this->dbuser = \OC_Config::getValue('dbuser');
     //$this->dbname = \OC_Config::getValue('dbname');
     $this->dbpassword = \OC_Config::getValue('dbpassword');
     $e_host = addslashes($this->dbhost);
     $e_dbname = addslashes($this->dbname);
     if ($e_host == '') {
         $easy_connect_string = $e_dbname;
         // use dbname as easy connect name
     } else {
         $easy_connect_string = '//' . $e_host . '/' . $e_dbname;
     }
     $connection = @oci_connect($this->dbuser, $this->dbpassword, $easy_connect_string);
     if (!$connection) {
         throw new \DatabaseSetupException($this->trans->t('Oracle username and/or password not valid'), $this->trans->t('You need to enter either an existing account or the administrator.'));
     }
     $query = "SELECT count(*) FROM user_tables WHERE table_name = :un";
     $stmt = oci_parse($connection, $query);
     $un = $this->tableprefix . 'users';
     oci_bind_by_name($stmt, ':un', $un);
     if (!$stmt) {
         $entry = $this->trans->t('DB Error: "%s"', array($this->getLastError($connection))) . '<br />';
         $entry .= $this->trans->t('Offending command was: "%s"', array($query)) . '<br />';
         \OC_Log::write('setup.oci', $entry, \OC_Log::WARN);
     }
     $result = oci_execute($stmt);
     if ($result) {
         $row = oci_fetch_row($stmt);
     }
     if (!$result or $row[0] == 0) {
         \OC_DB::createDbFromStructure($this->dbDefinitionFile);
     }
 }
Пример #18
0
 protected function getUniqueSessionId()
 {
     $testSession = new Db_Session();
     do {
         $id = \OC_Util::generateRandomBytes(30);
     } while ($testSession->load($id)->hasData());
     return $id;
 }
Пример #19
0
 /**
  * perform login using the magic cookie (remember login)
  *
  * @param string $uid the username
  * @param string $currentToken
  * @return bool
  */
 public function loginWithCookie($uid, $currentToken)
 {
     $this->manager->emit('\\OC\\User', 'preRememberedLogin', array($uid));
     $user = $this->manager->get($uid);
     if (is_null($user)) {
         // user does not exist
         return false;
     }
     // get stored tokens
     $tokens = \OC_Preferences::getKeys($uid, 'login_token');
     // test cookies token against stored tokens
     if (!in_array($currentToken, $tokens, true)) {
         return false;
     }
     // replace successfully used token with a new one
     \OC_Preferences::deleteKey($uid, 'login_token', $currentToken);
     $newToken = \OC_Util::generateRandomBytes(32);
     \OC_Preferences::setValue($uid, 'login_token', $newToken, time());
     $this->setMagicInCookie($user->getUID(), $newToken);
     //login
     $this->setUser($user);
     $this->manager->emit('\\OC\\User', 'postRememberedLogin', array($user));
     return true;
 }
Пример #20
0
 function createContact($addressBookId, $contact, array $options = array())
 {
     $id = \OC_Util::generateRandomBytes('4');
     $this->contacts[$addressBookId][$id] = array('id' => $id, 'displayname' => $contact->FN, 'carddata' => $contact->serialize());
     return $id;
 }
Пример #21
0
 public static function install($options)
 {
     $l = self::getTrans();
     $error = array();
     $dbtype = $options['dbtype'];
     if (empty($options['adminlogin'])) {
         $error[] = $l->t('Set an admin username.');
     }
     if (empty($options['adminpass'])) {
         $error[] = $l->t('Set an admin password.');
     }
     if (empty($options['directory'])) {
         $options['directory'] = OC::$SERVERROOT . "/data";
     }
     if (!isset(self::$dbSetupClasses[$dbtype])) {
         $dbtype = 'sqlite';
     }
     $class = self::$dbSetupClasses[$dbtype];
     $dbSetup = new $class(self::getTrans(), 'db_structure.xml');
     $error = array_merge($error, $dbSetup->validate($options));
     if (count($error) != 0) {
         return $error;
     }
     //no errors, good
     $username = htmlspecialchars_decode($options['adminlogin']);
     $password = htmlspecialchars_decode($options['adminpass']);
     $datadir = htmlspecialchars_decode($options['directory']);
     if (OC_Util::runningOnWindows()) {
         $datadir = rtrim(realpath($datadir), '\\');
     }
     //use sqlite3 when available, otherise sqlite2 will be used.
     if ($dbtype == 'sqlite' and class_exists('SQLite3')) {
         $dbtype = 'sqlite3';
     }
     //generate a random salt that is used to salt the local user passwords
     $salt = OC_Util::generateRandomBytes(30);
     OC_Config::setValue('passwordsalt', $salt);
     //write the config file
     OC_Config::setValue('datadirectory', $datadir);
     OC_Config::setValue('dbtype', $dbtype);
     OC_Config::setValue('version', implode('.', OC_Util::getVersion()));
     try {
         $dbSetup->initialize($options);
         $dbSetup->setupDatabase($username);
     } catch (DatabaseSetupException $e) {
         $error[] = array('error' => $e->getMessage(), 'hint' => $e->getHint());
         return $error;
     } catch (Exception $e) {
         $error[] = array('error' => 'Error while trying to create admin user: '******'hint' => '');
         return $error;
     }
     //create the user and group
     try {
         OC_User::createUser($username, $password);
     } catch (Exception $exception) {
         $error[] = $exception->getMessage();
     }
     if (count($error) == 0) {
         OC_Appconfig::setValue('core', 'installedat', microtime(true));
         OC_Appconfig::setValue('core', 'lastupdatedat', microtime(true));
         OC_AppConfig::setValue('core', 'remote_core.css', '/core/minimizer.php');
         OC_AppConfig::setValue('core', 'remote_core.js', '/core/minimizer.php');
         OC_Group::createGroup('admin');
         OC_Group::addToGroup($username, 'admin');
         OC_User::login($username, $password);
         //guess what this does
         OC_Installer::installShippedApps();
         //create htaccess files for apache hosts
         if (isset($_SERVER['SERVER_SOFTWARE']) && strstr($_SERVER['SERVER_SOFTWARE'], 'Apache')) {
             self::createHtaccess();
         }
         //and we are done
         OC_Config::setValue('installed', true);
     }
     return $error;
 }
Пример #22
0
 function testGenerateRandomBytes()
 {
     $result = strlen(OC_Util::generateRandomBytes(59));
     $this->assertEquals(59, $result);
 }
Пример #23
0
 public function setupDatabase($username)
 {
     $e_host = addslashes($this->dbHost);
     $e_user = addslashes($this->dbUser);
     $e_password = addslashes($this->dbPassword);
     // Fix database with port connection
     if (strpos($e_host, ':')) {
         list($e_host, $port) = explode(':', $e_host, 2);
     } else {
         $port = false;
     }
     //check if the database user has admin rights
     $connection_string = "host='{$e_host}' dbname=postgres user='******' port='{$port}' password='******'";
     $connection = @pg_connect($connection_string);
     if (!$connection) {
         // Try if we can connect to the DB with the specified name
         $e_dbname = addslashes($this->dbName);
         $connection_string = "host='{$e_host}' dbname='{$e_dbname}' user='******' port='{$port}' password='******'";
         $connection = @pg_connect($connection_string);
         if (!$connection) {
             throw new \OC\DatabaseSetupException($this->trans->t('PostgreSQL username and/or password not valid'), $this->trans->t('You need to enter either an existing account or the administrator.'));
         }
     }
     $e_user = pg_escape_string($this->dbUser);
     //check for roles creation rights in postgresql
     $query = "SELECT 1 FROM pg_roles WHERE rolcreaterole=TRUE AND rolname='{$e_user}'";
     $result = pg_query($connection, $query);
     if ($result and pg_num_rows($result) > 0) {
         //use the admin login data for the new database user
         //add prefix to the postgresql user name to prevent collisions
         $this->dbUser = '******' . $username;
         //create a new password so we don't need to store the admin config in the config file
         $this->dbPassword = \OC_Util::generateRandomBytes(30);
         $this->createDBUser($connection);
     }
     $systemConfig = \OC::$server->getSystemConfig();
     $systemConfig->setValues(['dbuser' => $this->dbUser, 'dbpassword' => $this->dbPassword]);
     //create the database
     $this->createDatabase($connection);
     // the connection to dbname=postgres is not needed anymore
     pg_close($connection);
     // connect to the ownCloud database (dbname=$this->dbname) and check if it needs to be filled
     $this->dbUser = $systemConfig->getValue('dbuser');
     $this->dbPassword = $systemConfig->getValue('dbpassword');
     $e_host = addslashes($this->dbHost);
     $e_dbname = addslashes($this->dbName);
     $e_user = addslashes($this->dbUser);
     $e_password = addslashes($this->dbPassword);
     // Fix database with port connection
     if (strpos($e_host, ':')) {
         list($e_host, $port) = explode(':', $e_host, 2);
     } else {
         $port = false;
     }
     $connection_string = "host='{$e_host}' dbname='{$e_dbname}' user='******' port='{$port}' password='******'";
     $connection = @pg_connect($connection_string);
     if (!$connection) {
         throw new \OC\DatabaseSetupException($this->trans->t('PostgreSQL username and/or password not valid'), $this->trans->t('You need to enter either an existing account or the administrator.'));
     }
     $query = "select count(*) FROM pg_class WHERE relname='" . $this->tablePrefix . "users' limit 1";
     $result = pg_query($connection, $query);
     if ($result) {
         $row = pg_fetch_row($result);
     }
     if (!$result or $row[0] == 0) {
         \OC_DB::createDbFromStructure($this->dbDefinitionFile);
     }
 }
Пример #24
0
 /**
  * Share an item with a user, group, or via private link
  * @param string $itemType
  * @param string $itemSource
  * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
  * @param string $shareWith User or group the item is being shared with
  * @param int $permissions CRUDS
  * @param string $itemSourceName
  * @param \DateTime $expirationDate
  * @return boolean|string Returns true on success or false on failure, Returns token on success for links
  * @throws \Exception
  */
 public static function shareItem($itemType, $itemSource, $shareType, $shareWith, $permissions, $itemSourceName = null, \DateTime $expirationDate = null)
 {
     $uidOwner = \OC_User::getUser();
     $shareWithinGroupOnly = self::shareWithGroupMembersOnly();
     $l = \OC_L10N::get('lib');
     if (is_null($itemSourceName)) {
         $itemSourceName = $itemSource;
     }
     // check if file can be shared
     if ($itemType === 'file' or $itemType === 'folder') {
         $path = \OC\Files\Filesystem::getPath($itemSource);
         // verify that the file exists before we try to share it
         if (!$path) {
             $message = 'Sharing %s failed, because the file does not exist';
             $message_t = $l->t('Sharing %s failed, because the file does not exist', array($itemSourceName));
             \OC_Log::write('OCP\\Share', sprintf($message, $itemSourceName), \OC_Log::ERROR);
             throw new \Exception($message_t);
         }
         // verify that the user has share permission
         if (!\OC\Files\Filesystem::isSharable($path)) {
             $message = 'You are not allowed to share %s';
             $message_t = $l->t('You are not allowed to share %s', array($itemSourceName));
             \OC_Log::write('OCP\\Share', sprintf($message, $itemSourceName), \OC_Log::ERROR);
             throw new \Exception($message_t);
         }
     }
     //verify that we don't share a folder which already contains a share mount point
     if ($itemType === 'folder') {
         $path = '/' . $uidOwner . '/files' . \OC\Files\Filesystem::getPath($itemSource) . '/';
         $mountManager = \OC\Files\Filesystem::getMountManager();
         $mounts = $mountManager->findIn($path);
         foreach ($mounts as $mount) {
             if ($mount->getStorage()->instanceOfStorage('\\OCA\\Files_Sharing\\ISharedStorage')) {
                 $message = 'Sharing "' . $itemSourceName . '" failed, because it contains files shared with you!';
                 \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR);
                 throw new \Exception($message);
             }
         }
     }
     // single file shares should never have delete permissions
     if ($itemType === 'file') {
         $permissions = (int) $permissions & ~\OCP\PERMISSION_DELETE;
     }
     // Verify share type and sharing conditions are met
     if ($shareType === self::SHARE_TYPE_USER) {
         if ($shareWith == $uidOwner) {
             $message = 'Sharing %s failed, because the user %s is the item owner';
             $message_t = $l->t('Sharing %s failed, because the user %s is the item owner', array($itemSourceName, $shareWith));
             \OC_Log::write('OCP\\Share', sprintf($message, $itemSourceName, $shareWith), \OC_Log::ERROR);
             throw new \Exception($message_t);
         }
         if (!\OC_User::userExists($shareWith)) {
             $message = 'Sharing %s failed, because the user %s does not exist';
             $message_t = $l->t('Sharing %s failed, because the user %s does not exist', array($itemSourceName, $shareWith));
             \OC_Log::write('OCP\\Share', sprintf($message, $itemSourceName, $shareWith), \OC_Log::ERROR);
             throw new \Exception($message_t);
         }
         if ($shareWithinGroupOnly) {
             $inGroup = array_intersect(\OC_Group::getUserGroups($uidOwner), \OC_Group::getUserGroups($shareWith));
             if (empty($inGroup)) {
                 $message = 'Sharing %s failed, because the user ' . '%s is not a member of any groups that %s is a member of';
                 $message_t = $l->t('Sharing %s failed, because the user %s is not a member of any groups that %s is a member of', array($itemSourceName, $shareWith, $uidOwner));
                 \OC_Log::write('OCP\\Share', sprintf($message, $itemSourceName, $shareWith, $uidOwner), \OC_Log::ERROR);
                 throw new \Exception($message_t);
             }
         }
         // Check if the item source is already shared with the user, either from the same owner or a different user
         if ($checkExists = self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups, $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
             // Only allow the same share to occur again if it is the same
             // owner and is not a user share, this use case is for increasing
             // permissions for a specific user
             if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
                 $message = 'Sharing %s failed, because this item is already shared with %s';
                 $message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
                 \OC_Log::write('OCP\\Share', sprintf($message, $itemSourceName, $shareWith), \OC_Log::ERROR);
                 throw new \Exception($message_t);
             }
         }
     } else {
         if ($shareType === self::SHARE_TYPE_GROUP) {
             if (!\OC_Group::groupExists($shareWith)) {
                 $message = 'Sharing %s failed, because the group %s does not exist';
                 $message_t = $l->t('Sharing %s failed, because the group %s does not exist', array($itemSourceName, $shareWith));
                 \OC_Log::write('OCP\\Share', sprintf($message, $itemSourceName, $shareWith), \OC_Log::ERROR);
                 throw new \Exception($message_t);
             }
             if ($shareWithinGroupOnly && !\OC_Group::inGroup($uidOwner, $shareWith)) {
                 $message = 'Sharing %s failed, because ' . '%s is not a member of the group %s';
                 $message_t = $l->t('Sharing %s failed, because %s is not a member of the group %s', array($itemSourceName, $uidOwner, $shareWith));
                 \OC_Log::write('OCP\\Share', sprintf($message, $itemSourceName, $uidOwner, $shareWith), \OC_Log::ERROR);
                 throw new \Exception($message_t);
             }
             // Check if the item source is already shared with the group, either from the same owner or a different user
             // The check for each user in the group is done inside the put() function
             if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_GROUP, $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
                 // Only allow the same share to occur again if it is the same
                 // owner and is not a group share, this use case is for increasing
                 // permissions for a specific user
                 if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
                     $message = 'Sharing %s failed, because this item is already shared with %s';
                     $message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
                     \OC_Log::write('OCP\\Share', sprintf($message, $itemSourceName, $shareWith), \OC_Log::ERROR);
                     throw new \Exception($message_t);
                 }
             }
             // Convert share with into an array with the keys group and users
             $group = $shareWith;
             $shareWith = array();
             $shareWith['group'] = $group;
             $shareWith['users'] = array_diff(\OC_Group::usersInGroup($group), array($uidOwner));
         } else {
             if ($shareType === self::SHARE_TYPE_LINK) {
                 $updateExistingShare = false;
                 if (\OC_Appconfig::getValue('core', 'shareapi_allow_links', 'yes') == 'yes') {
                     // when updating a link share
                     // FIXME Don't delete link if we update it
                     if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_LINK, null, $uidOwner, self::FORMAT_NONE, null, 1)) {
                         // remember old token
                         $oldToken = $checkExists['token'];
                         $oldPermissions = $checkExists['permissions'];
                         //delete the old share
                         Helper::delete($checkExists['id']);
                         $updateExistingShare = true;
                     }
                     // Generate hash of password - same method as user passwords
                     if (!empty($shareWith)) {
                         $forcePortable = CRYPT_BLOWFISH != 1;
                         $hasher = new \PasswordHash(8, $forcePortable);
                         $shareWith = $hasher->HashPassword($shareWith . \OC_Config::getValue('passwordsalt', ''));
                     } else {
                         // reuse the already set password, but only if we change permissions
                         // otherwise the user disabled the password protection
                         if ($checkExists && (int) $permissions !== (int) $oldPermissions) {
                             $shareWith = $checkExists['share_with'];
                         }
                     }
                     if (\OCP\Util::isPublicLinkPasswordRequired() && empty($shareWith)) {
                         $message = 'You need to provide a password to create a public link, only protected links are allowed';
                         $message_t = $l->t('You need to provide a password to create a public link, only protected links are allowed');
                         \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR);
                         throw new \Exception($message_t);
                     }
                     if ($updateExistingShare === false && self::isDefaultExpireDateEnabled() && empty($expirationDate)) {
                         $expirationDate = Helper::calcExpireDate();
                     }
                     // Generate token
                     if (isset($oldToken)) {
                         $token = $oldToken;
                     } else {
                         $token = \OC_Util::generateRandomBytes(self::TOKEN_LENGTH);
                     }
                     $result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, $token, $itemSourceName, $expirationDate);
                     if ($result) {
                         return $token;
                     } else {
                         return false;
                     }
                 }
                 $message = 'Sharing %s failed, because sharing with links is not allowed';
                 $message_t = $l->t('Sharing %s failed, because sharing with links is not allowed', array($itemSourceName));
                 \OC_Log::write('OCP\\Share', sprintf($message, $itemSourceName), \OC_Log::ERROR);
                 throw new \Exception($message_t);
                 return false;
             } else {
                 // Future share types need to include their own conditions
                 $message = 'Share type %s is not valid for %s';
                 $message_t = $l->t('Share type %s is not valid for %s', array($shareType, $itemSource));
                 \OC_Log::write('OCP\\Share', sprintf($message, $shareType, $itemSource), \OC_Log::ERROR);
                 throw new \Exception($message_t);
             }
         }
     }
     // Put the item into the database
     return self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, null, $itemSourceName, $expirationDate);
 }
Пример #25
0
 /**
  * @brief Autogenerate a password
  * @return string
  *
  * generates a password
  */
 public static function generatePassword()
 {
     return OC_Util::generateRandomBytes(30);
 }
Пример #26
0
 /**
  * Generates a cryptographic secure pseudo-random string
  * @param int $length of the random string
  * @return string
  * @deprecated 8.0.0 Use \OC::$server->getSecureRandom()->getMediumStrengthGenerator()->generate($length); instead
  * @since 7.0.0
  */
 public static function generateRandomBytes($length = 30)
 {
     return \OC_Util::generateRandomBytes($length);
 }
Пример #27
0
 /**
  * Share an item with a user, group, or via private link
  * @param string $itemType
  * @param string $itemSource
  * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
  * @param string $shareWith User or group the item is being shared with
  * @param int $permissions CRUDS
  * @param null $itemSourceName
  * @throws \Exception
  * @internal param \OCP\Item $string type
  * @internal param \OCP\Item $string source
  * @internal param \OCP\SHARE_TYPE_USER $int , SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
  * @internal param \OCP\User $string or group the item is being shared with
  * @internal param \OCP\CRUDS $int permissions
  * @return bool|string Returns true on success or false on failure, Returns token on success for links
  */
 public static function shareItem($itemType, $itemSource, $shareType, $shareWith, $permissions, $itemSourceName = null)
 {
     $uidOwner = \OC_User::getUser();
     $sharingPolicy = \OC_Appconfig::getValue('core', 'shareapi_share_policy', 'global');
     if (is_null($itemSourceName)) {
         $itemSourceName = $itemSource;
     }
     // verify that the file exists before we try to share it
     if ($itemType === 'file' or $itemType === 'folder') {
         $path = \OC\Files\Filesystem::getPath($itemSource);
         if (!$path) {
             $message = 'Sharing ' . $itemSourceName . ' failed, because the file does not exist';
             \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR);
             throw new \Exception($message);
         }
     }
     // Verify share type and sharing conditions are met
     if ($shareType === self::SHARE_TYPE_USER) {
         if ($shareWith == $uidOwner) {
             $message = 'Sharing ' . $itemSourceName . ' failed, because the user ' . $shareWith . ' is the item owner';
             \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR);
             throw new \Exception($message);
         }
         if (!\OC_User::userExists($shareWith)) {
             $message = 'Sharing ' . $itemSourceName . ' failed, because the user ' . $shareWith . ' does not exist';
             \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR);
             throw new \Exception($message);
         }
         if ($sharingPolicy == 'groups_only') {
             $inGroup = array_intersect(\OC_Group::getUserGroups($uidOwner), \OC_Group::getUserGroups($shareWith));
             if (empty($inGroup)) {
                 $message = 'Sharing ' . $itemSourceName . ' failed, because the user ' . $shareWith . ' is not a member of any groups that ' . $uidOwner . ' is a member of';
                 \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR);
                 throw new \Exception($message);
             }
         }
         // Check if the item source is already shared with the user, either from the same owner or a different user
         if ($checkExists = self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups, $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
             // Only allow the same share to occur again if it is the same
             // owner and is not a user share, this use case is for increasing
             // permissions for a specific user
             if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
                 $message = 'Sharing ' . $itemSourceName . ' failed, because this item is already shared with ' . $shareWith;
                 \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR);
                 throw new \Exception($message);
             }
         }
     } else {
         if ($shareType === self::SHARE_TYPE_GROUP) {
             if (!\OC_Group::groupExists($shareWith)) {
                 $message = 'Sharing ' . $itemSourceName . ' failed, because the group ' . $shareWith . ' does not exist';
                 \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR);
                 throw new \Exception($message);
             }
             if ($sharingPolicy == 'groups_only' && !\OC_Group::inGroup($uidOwner, $shareWith)) {
                 $message = 'Sharing ' . $itemSourceName . ' failed, because ' . $uidOwner . ' is not a member of the group ' . $shareWith;
                 \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR);
                 throw new \Exception($message);
             }
             // Check if the item source is already shared with the group, either from the same owner or a different user
             // The check for each user in the group is done inside the put() function
             if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_GROUP, $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
                 // Only allow the same share to occur again if it is the same
                 // owner and is not a group share, this use case is for increasing
                 // permissions for a specific user
                 if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
                     $message = 'Sharing ' . $itemSourceName . ' failed, because this item is already shared with ' . $shareWith;
                     \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR);
                     throw new \Exception($message);
                 }
             }
             // Convert share with into an array with the keys group and users
             $group = $shareWith;
             $shareWith = array();
             $shareWith['group'] = $group;
             $shareWith['users'] = array_diff(\OC_Group::usersInGroup($group), array($uidOwner));
         } else {
             if ($shareType === self::SHARE_TYPE_LINK) {
                 if (\OC_Appconfig::getValue('core', 'shareapi_allow_links', 'yes') == 'yes') {
                     // when updating a link share
                     if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_LINK, null, $uidOwner, self::FORMAT_NONE, null, 1)) {
                         // remember old token
                         $oldToken = $checkExists['token'];
                         $oldPermissions = $checkExists['permissions'];
                         //delete the old share
                         self::delete($checkExists['id']);
                     }
                     // Generate hash of password - same method as user passwords
                     if (isset($shareWith)) {
                         $forcePortable = CRYPT_BLOWFISH != 1;
                         $hasher = new \PasswordHash(8, $forcePortable);
                         $shareWith = $hasher->HashPassword($shareWith . \OC_Config::getValue('passwordsalt', ''));
                     } else {
                         // reuse the already set password, but only if we change permissions
                         // otherwise the user disabled the password protection
                         if ($checkExists && (int) $permissions !== (int) $oldPermissions) {
                             $shareWith = $checkExists['share_with'];
                         }
                     }
                     // Generate token
                     if (isset($oldToken)) {
                         $token = $oldToken;
                     } else {
                         $token = \OC_Util::generateRandomBytes(self::TOKEN_LENGTH);
                     }
                     $result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, $token, $itemSourceName);
                     if ($result) {
                         return $token;
                     } else {
                         return false;
                     }
                 }
                 $message = 'Sharing ' . $itemSourceName . ' failed, because sharing with links is not allowed';
                 \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR);
                 throw new \Exception($message);
                 return false;
                 // 		} else if ($shareType === self::SHARE_TYPE_CONTACT) {
                 // 			if (!\OC_App::isEnabled('contacts')) {
                 // 				$message = 'Sharing '.$itemSource.' failed, because the contacts app is not enabled';
                 // 				\OC_Log::write('OCP\Share', $message, \OC_Log::ERROR);
                 // 				return false;
                 // 			}
                 // 			$vcard = \OC_Contacts_App::getContactVCard($shareWith);
                 // 			if (!isset($vcard)) {
                 // 				$message = 'Sharing '.$itemSource.' failed, because the contact does not exist';
                 // 				\OC_Log::write('OCP\Share', $message, \OC_Log::ERROR);
                 // 				throw new \Exception($message);
                 // 			}
                 // 			$details = \OC_Contacts_VCard::structureContact($vcard);
                 // 			// TODO Add ownCloud user to contacts vcard
                 // 			if (!isset($details['EMAIL'])) {
                 // 				$message = 'Sharing '.$itemSource.' failed, because no email address is associated with the contact';
                 // 				\OC_Log::write('OCP\Share', $message, \OC_Log::ERROR);
                 // 				throw new \Exception($message);
                 // 			}
                 // 			return self::shareItem($itemType, $itemSource, self::SHARE_TYPE_EMAIL, $details['EMAIL'], $permissions);
             } else {
                 // Future share types need to include their own conditions
                 $message = 'Share type ' . $shareType . ' is not valid for ' . $itemSource;
                 \OC_Log::write('OCP\\Share', $message, \OC_Log::ERROR);
                 throw new \Exception($message);
             }
         }
     }
     // If the item is a folder, scan through the folder looking for equivalent item types
     // 		if ($itemType == 'folder') {
     // 			$parentFolder = self::put('folder', $itemSource, $shareType, $shareWith, $uidOwner, $permissions, true);
     // 			if ($parentFolder && $files = \OC\Files\Filesystem::getDirectoryContent($itemSource)) {
     // 				for ($i = 0; $i < count($files); $i++) {
     // 					$name = substr($files[$i]['name'], strpos($files[$i]['name'], $itemSource) - strlen($itemSource));
     // 					if ($files[$i]['mimetype'] == 'httpd/unix-directory'
     // 						&& $children = \OC\Files\Filesystem::getDirectoryContent($name, '/')
     // 					) {
     // 						// Continue scanning into child folders
     // 						array_push($files, $children);
     // 					} else {
     // 						// Check file extension for an equivalent item type to convert to
     // 						$extension = strtolower(substr($itemSource, strrpos($itemSource, '.') + 1));
     // 						foreach (self::$backends as $type => $backend) {
     // 							if (isset($backend->dependsOn) && $backend->dependsOn == 'file' && isset($backend->supportedFileExtensions) && in_array($extension, $backend->supportedFileExtensions)) {
     // 								$itemType = $type;
     // 								break;
     // 							}
     // 						}
     // 						// Pass on to put() to check if this item should be converted, the item won't be inserted into the database unless it can be converted
     // 						self::put($itemType, $name, $shareType, $shareWith, $uidOwner, $permissions, $parentFolder);
     // 					}
     // 				}
     // 				return true;
     // 			}
     // 			return false;
     // 		} else {
     // Put the item into the database
     return self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, null, $itemSourceName);
     // 		}
 }
Пример #28
0
 private function createUser($uid)
 {
     if (preg_match('/[^a-zA-Z0-9 _\\.@\\-]/', $uid)) {
         OCP\Util::writeLog('saml', 'Invalid username "' . $uid . '", allowed chars "a-zA-Z0-9" and "_.@-" ', OCP\Util::DEBUG);
         return false;
     } else {
         $random_password = \OC_Util::generateRandomBytes(64);
         OCP\Util::writeLog('saml', 'Creating new user: ' . $uid, OCP\Util::DEBUG);
         OC_User::createUser($uid, $random_password);
         return $uid;
     }
 }
Пример #29
0
 protected function sendEmail($user, $proceed)
 {
     if ($this->isDataEncrypted && !$proceed) {
         throw new EncryptedDataException();
     }
     if (!$this->userManager->userExists($user)) {
         throw new \Exception($this->l10n->t('Couldn\'t send reset email. Please make sure ' . 'your username is correct.'));
     }
     $token = hash('sha256', \OC_Util::generateRandomBytes(30));
     // Hash the token again to prevent timing attacks
     $this->config->setUserValue($user, 'owncloud', 'lostpassword', hash('sha256', $token));
     $email = $this->config->getUserValue($user, 'settings', 'email');
     if (empty($email)) {
         throw new \Exception($this->l10n->t('Couldn\'t send reset email because there is no ' . 'email address for this username. Please ' . 'contact your administrator.'));
     }
     $link = $this->getLink('core.lost.resetform', $user, $token);
     $tmpl = new \OC_Template('core/lostpassword', 'email');
     $tmpl->assign('link', $link, false);
     $msg = $tmpl->fetchPage();
     try {
         // FIXME: should be added to the container and injected in here
         \OC_Mail::send($email, $user, $this->l10n->t('%s password reset', array($this->defaults->getName())), $msg, $this->from, $this->defaults->getName());
     } catch (\Exception $e) {
         throw new \Exception($this->l10n->t('Couldn\'t send reset email. Please contact your administrator.'));
     }
 }