public function save($email)
 {
     $query = $this->db->prepareQuery('INSERT INTO `*PREFIX*registration`' . ' ( `email`, `token`, `requested` ) VALUES( ?, ?, NOW() )');
     $token = $this->random->generate(30);
     $query->execute(array($email, $token));
     return $token;
 }
Example #2
0
 /**
  * @return DataResponse
  */
 public function createCredentials()
 {
     // Create a new job and store the creation date
     $this->jobList->add('OCA\\UpdateNotification\\ResetTokenBackgroundJob');
     $this->config->setAppValue('core', 'updater.secret.created', $this->timeFactory->getTime());
     // Create a new token
     $newToken = $this->secureRandom->generate(64);
     $this->config->setSystemValue('updater.secret', password_hash($newToken, PASSWORD_DEFAULT));
     return new DataResponse($newToken);
 }
Example #3
0
 /**
  * add server to the list of trusted ownCloud servers
  *
  * @param $url
  * @return int server id
  */
 public function addServer($url)
 {
     $url = $this->updateProtocol($url);
     $result = $this->dbHandler->addServer($url);
     if ($result) {
         $token = $this->secureRandom->generate(16);
         $this->dbHandler->addToken($url, $token);
         $this->jobList->add('OCA\\Federation\\BackgroundJob\\RequestSharedSecret', ['url' => $url, 'token' => $token]);
     }
     return $result;
 }
Example #4
0
 /**
  * @param string $user
  * @throws \Exception
  */
 protected function sendEmail($user)
 {
     if (!$this->userManager->userExists($user)) {
         throw new \Exception($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
     }
     $userObject = $this->userManager->get($user);
     $email = $userObject->getEMailAddress();
     if (empty($email)) {
         throw new \Exception($this->l10n->t('Could not send reset email because there is no email address for this username. Please contact your administrator.'));
     }
     $token = $this->secureRandom->generate(21, ISecureRandom::CHAR_DIGITS . ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER);
     $this->config->setUserValue($user, 'owncloud', 'lostpassword', $this->timeFactory->getTime() . ':' . $token);
     $link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', array('userId' => $user, 'token' => $token));
     $tmpl = new \OC_Template('core/lostpassword', 'email');
     $tmpl->assign('link', $link);
     $msg = $tmpl->fetchPage();
     try {
         $message = $this->mailer->createMessage();
         $message->setTo([$email => $user]);
         $message->setSubject($this->l10n->t('%s password reset', [$this->defaults->getName()]));
         $message->setPlainBody($msg);
         $message->setFrom([$this->from => $this->defaults->getName()]);
         $this->mailer->send($message);
     } catch (\Exception $e) {
         throw new \Exception($this->l10n->t('Couldn\'t send reset email. Please contact your administrator.'));
     }
 }
 /**
  * Return a 20 digit device password
  *
  * Example: ABCDE-FGHIJ-KLMNO-PQRST
  *
  * @return string
  */
 private function generateRandomDeviceToken()
 {
     $groups = [];
     for ($i = 0; $i < 4; $i++) {
         $groups[] = $this->random->generate(5, implode('', range('A', 'Z')));
     }
     return implode('-', $groups);
 }
Example #6
0
 /**
  * Share a path
  *
  * @param \OCP\Share\IShare $share
  * @return Share The share object
  * @throws \Exception
  *
  * TODO: handle link share permissions or check them
  */
 public function createShare(\OCP\Share\IShare $share)
 {
     if (!$this->canShare($share)) {
         throw new \Exception('The Share API is disabled');
     }
     $this->generalCreateChecks($share);
     //Verify share type
     if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER) {
         $this->userCreateChecks($share);
     } else {
         if ($share->getShareType() === \OCP\Share::SHARE_TYPE_GROUP) {
             $this->groupCreateChecks($share);
         } else {
             if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) {
                 $this->linkCreateChecks($share);
                 $this->setLinkParent($share);
                 /*
                  * For now ignore a set token.
                  */
                 $share->setToken($this->secureRandom->generate(\OC\Share\Constants::TOKEN_LENGTH, \OCP\Security\ISecureRandom::CHAR_LOWER . \OCP\Security\ISecureRandom::CHAR_UPPER . \OCP\Security\ISecureRandom::CHAR_DIGITS));
                 //Verify the expiration date
                 $this->validateExpirationDate($share);
                 //Verify the password
                 $this->verifyPassword($share->getPassword());
                 // If a password is set. Hash it!
                 if ($share->getPassword() !== null) {
                     $share->setPassword($this->hasher->hash($share->getPassword()));
                 }
             }
         }
     }
     // Verify if there are any issues with the path
     $this->pathCreateChecks($share->getNode());
     // On creation of a share the owner is always the owner of the path
     $share->setShareOwner($share->getNode()->getOwner()->getUID());
     // Cannot share with the owner
     if ($share->getShareType() === \OCP\Share::SHARE_TYPE_USER && $share->getSharedWith() === $share->getShareOwner()) {
         throw new \InvalidArgumentException('Can\'t share with the share owner');
     }
     // Generate the target
     $target = $this->config->getSystemValue('share_folder', '/') . '/' . $share->getNode()->getName();
     $target = \OC\Files\Filesystem::normalizePath($target);
     $share->setTarget($target);
     // Pre share hook
     $run = true;
     $error = '';
     $preHookData = ['itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder', 'itemSource' => $share->getNode()->getId(), 'shareType' => $share->getShareType(), 'uidOwner' => $share->getSharedBy(), 'permissions' => $share->getPermissions(), 'fileSource' => $share->getNode()->getId(), 'expiration' => $share->getExpirationDate(), 'token' => $share->getToken(), 'itemTarget' => $share->getTarget(), 'shareWith' => $share->getSharedWith(), 'run' => &$run, 'error' => &$error];
     \OC_Hook::emit('OCP\\Share', 'pre_shared', $preHookData);
     if ($run === false) {
         throw new \Exception($error);
     }
     $provider = $this->factory->getProviderForType($share->getShareType());
     $share = $provider->create($share);
     // Post share hook
     $postHookData = ['itemType' => $share->getNode() instanceof \OCP\Files\File ? 'file' : 'folder', 'itemSource' => $share->getNode()->getId(), 'shareType' => $share->getShareType(), 'uidOwner' => $share->getSharedBy(), 'permissions' => $share->getPermissions(), 'fileSource' => $share->getNode()->getId(), 'expiration' => $share->getExpirationDate(), 'token' => $share->getToken(), 'id' => $share->getId(), 'shareWith' => $share->getSharedWith(), 'itemTarget' => $share->getTarget(), 'fileTarget' => $share->getTarget()];
     \OC_Hook::emit('OCP\\Share', 'post_shared', $postHookData);
     return $share;
 }
Example #7
0
 /**
  * Returns an ID for the request, value is not guaranteed to be unique and is mostly meant for logging
  * If `mod_unique_id` is installed this value will be taken.
  * @return string
  */
 public function getId()
 {
     if (isset($this->server['UNIQUE_ID'])) {
         return $this->server['UNIQUE_ID'];
     }
     if (empty($this->requestId)) {
         $this->requestId = $this->secureRandom->generate(20);
     }
     return $this->requestId;
 }
Example #8
0
 /**
  * @param IConfig $config
  * @param ICrypto $crypto
  * @param ISecureRandom $random
  * @param IRequest $request
  */
 public function __construct(IConfig $config, ICrypto $crypto, ISecureRandom $random, IRequest $request)
 {
     $this->crypto = $crypto;
     $this->config = $config;
     $this->random = $random;
     if (!is_null($request->getCookie(self::COOKIE_NAME))) {
         $this->passphrase = $request->getCookie(self::COOKIE_NAME);
     } else {
         $this->passphrase = $this->random->generate(128);
         $secureCookie = $request->getServerProtocol() === 'https';
         // FIXME: Required for CI
         if (!defined('PHPUNIT_RUN')) {
             $webRoot = \OC::$WEBROOT;
             if ($webRoot === '') {
                 $webRoot = '/';
             }
             setcookie(self::COOKIE_NAME, $this->passphrase, 0, $webRoot, '', $secureCookie, true);
         }
     }
 }
Example #9
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 = $this->random->generate($this->ivLength);
     $this->cipher->setIV($iv);
     $ciphertext = bin2hex($this->cipher->encrypt($plaintext));
     $hmac = bin2hex($this->calculateHMAC($ciphertext . $iv, $password));
     return $ciphertext . '|' . $iv . '|' . $hmac;
 }
Example #10
0
 /**
  * @NoAdminRequired
  *
  * @param string $enable	'true' if the feed is enabled
  * @return DataResponse
  */
 public function feed($enable)
 {
     $token = $tokenUrl = '';
     if ($enable === 'true') {
         $conflicts = true;
         // Check for collisions
         while (!empty($conflicts)) {
             $token = $this->random->generate(30);
             $conflicts = $this->config->getUsersForUserValue('activity', 'rsstoken', $token);
         }
         $tokenUrl = $this->urlGenerator->linkToRouteAbsolute('activity.Feed.show', ['token' => $token]);
     }
     $this->config->setUserValue($this->user, 'activity', 'rsstoken', $token);
     return new DataResponse(array('data' => array('message' => (string) $this->l10n->t('Your settings have been updated.'), 'rsslink' => $tokenUrl)));
 }
Example #11
0
 /**
  * create shared secret and return it
  *
  * @return \OC_OCS_Result
  */
 public function getSharedSecret()
 {
     $url = $this->request->getParam('url');
     $token = $this->request->getParam('token');
     if ($this->trustedServers->isTrustedServer($url) === false) {
         $this->logger->log(\OCP\Util::ERROR, 'remote server not trusted (' . $url . ') while getting shared secret');
         return new \OC_OCS_Result(null, HTTP::STATUS_FORBIDDEN);
     }
     if ($this->isValidToken($url, $token) === false) {
         $this->logger->log(\OCP\Util::ERROR, 'remote server (' . $url . ') didn\'t send a valid token (got ' . $token . ') while getting shared secret');
         return new \OC_OCS_Result(null, HTTP::STATUS_FORBIDDEN);
     }
     $sharedSecret = $this->secureRandom->generate(32);
     $this->trustedServers->addSharedSecret($url, $sharedSecret);
     // reset token after the exchange of the shared secret was successful
     $this->dbHandler->addToken($url, '');
     return new \OC_OCS_Result(['sharedSecret' => $sharedSecret], Http::STATUS_OK);
 }
Example #12
0
 /**
  * @param \Doctrine\DBAL\Schema\Table $table
  * @param string $newName
  * @return \Doctrine\DBAL\Schema\Table
  */
 protected function renameTableSchema(Table $table, $newName)
 {
     /**
      * @var \Doctrine\DBAL\Schema\Index[] $indexes
      */
     $indexes = $table->getIndexes();
     $newIndexes = array();
     foreach ($indexes as $index) {
         if ($index->isPrimary()) {
             // do not rename primary key
             $indexName = $index->getName();
         } else {
             // avoid conflicts in index names
             $indexName = $this->config->getSystemValue('dbtableprefix', 'oc_') . $this->random->generate(13, ISecureRandom::CHAR_LOWER);
         }
         $newIndexes[] = new Index($indexName, $index->getColumns(), $index->isUnique(), $index->isPrimary());
     }
     // foreign keys are not supported so we just set it to an empty array
     return new Table($newName, $table->getColumns(), $newIndexes, array(), 0, $table->getOptions());
 }
 /**
  * Generate a new access token clients can authenticate with
  *
  * @PublicPage
  * @NoCSRFRequired
  *
  * @param string $user
  * @param string $password
  * @param string $name the name of the client
  * @return JSONResponse
  */
 public function generateToken($user, $password, $name = 'unknown client')
 {
     if (is_null($user) || is_null($password)) {
         $response = new JSONResponse();
         $response->setStatus(Http::STATUS_UNPROCESSABLE_ENTITY);
         return $response;
     }
     $loginName = $user;
     $user = $this->userManager->checkPassword($loginName, $password);
     if ($user === false) {
         $response = new JSONResponse();
         $response->setStatus(Http::STATUS_UNAUTHORIZED);
         return $response;
     }
     if ($this->twoFactorAuthManager->isTwoFactorAuthenticated($user)) {
         $resp = new JSONResponse();
         $resp->setStatus(Http::STATUS_UNAUTHORIZED);
         return $resp;
     }
     $token = $this->secureRandom->generate(128);
     $this->tokenProvider->generateToken($token, $user->getUID(), $loginName, $password, $name, IToken::PERMANENT_TOKEN);
     return ['token' => $token];
 }
Example #14
0
 /**
  * Generate a new CSRF token.
  *
  * @param int $length Length of the token in characters.
  * @return string
  */
 public function generateToken($length = 32)
 {
     return $this->random->generate($length);
 }
Example #15
0
 /**
  * generate one time password for the user and store it in a array
  *
  * @param string $uid
  * @return string password
  */
 protected function generateOneTimePassword($uid)
 {
     $password = $this->secureRandom->generate(8);
     $this->userPasswords[$uid] = $password;
     return $password;
 }
Example #16
0
File: setup.php Project: kenwi/core
 /**
  * @param $options
  * @return array
  */
 public function install($options)
 {
     $l = $this->l10n;
     $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($l, 'db_structure.xml', $this->config, $this->logger, $this->random);
     $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;
     }
     $request = \OC::$server->getRequest();
     //no errors, good
     if (isset($options['trusted_domains']) && is_array($options['trusted_domains'])) {
         $trustedDomains = $options['trusted_domains'];
     } else {
         $trustedDomains = [$request->getInsecureServerHost()];
     }
     if (\OC_Util::runningOnWindows()) {
         $dataDir = rtrim(realpath($dataDir), '\\');
     }
     //use sqlite3 when available, otherwise 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 = $this->random->generate(30);
     // generate a secret
     $secret = $this->random->generate(48);
     //write the config file
     $this->config->setSystemValues(['passwordsalt' => $salt, 'secret' => $secret, 'trusted_domains' => $trustedDomains, 'datadirectory' => $dataDir, 'overwrite.cli.url' => $request->getServerProtocol() . '://' . $request->getInsecureServerHost() . \OC::$WEBROOT, 'dbtype' => $dbType, 'version' => implode('.', \OCP\Util::getVersion())]);
     try {
         $dbSetup->initialize($options);
         $dbSetup->setupDatabase($username);
     } catch (\OC\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
     $user = null;
     try {
         $user = \OC::$server->getUserManager()->createUser($username, $password);
         if (!$user) {
             $error[] = "User <{$username}> could not be created.";
         }
     } catch (Exception $exception) {
         $error[] = $exception->getMessage();
     }
     if (count($error) == 0) {
         $config = \OC::$server->getConfig();
         $config->setAppValue('core', 'installedat', microtime(true));
         $config->setAppValue('core', 'lastupdatedat', microtime(true));
         $group = \OC::$server->getGroupManager()->createGroup('admin');
         $group->addUser($user);
         \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($config->getSystemValue('datadirectory', \OC::$SERVERROOT . '/data') . '/.ocdata', '');
         // Update .htaccess files
         Setup::updateHtaccess();
         Setup::protectDataDirectory();
         //try to write logtimezone
         if (date_default_timezone_get()) {
             $config->setSystemValue('logtimezone', date_default_timezone_get());
         }
         //and we are done
         $config->setSystemValue('installed', true);
     }
     return $error;
 }
Example #17
0
 /**
  * generate to token used to authenticate federated shares
  *
  * @return string
  */
 public function generateToken()
 {
     $token = $this->secureRandom->generate(self::TOKEN_LENGTH, ISecureRandom::CHAR_LOWER . ISecureRandom::CHAR_UPPER . ISecureRandom::CHAR_DIGITS);
     return $token;
 }