public function testUnwrappingGet() { $unencryptedValue = 'foobar'; $encryptedValue = $this->crypto->encrypt($unencryptedValue); $this->wrappedSession->expects($this->once())->method('get')->with('encrypted_session_data')->willReturnCallback(function () use($encryptedValue) { return $encryptedValue; }); $this->assertSame($unencryptedValue, $this->wrappedSession->get('encrypted_session_data')); }
public function manipulateStorageConfig(StorageConfig &$storage) { $encrypted = $this->session->get('password::sessioncredentials/credentials'); if (!isset($encrypted)) { throw new InsufficientDataForMeaningfulAnswerException('No session credentials saved'); } $credentials = json_decode($this->crypto->decrypt($encrypted), true); $storage->setBackendOption('user', $this->session->get('loginname')); $storage->setBackendOption('password', $credentials['password']); }
public function testRetrieve() { $userId = 'abc'; $identifier = 'foo'; $this->crypto->expects($this->once())->method('decrypt')->with('baz')->willReturn(json_encode('bar')); $qb = $this->getMockBuilder('\\OC\\DB\\QueryBuilder\\QueryBuilder')->setConstructorArgs([$this->dbConnection])->setMethods(['execute'])->getMock(); $qb->expects($this->once())->method('execute')->willReturn($this->getQeuryResult(['credentials' => 'baz'])); $this->dbConnection->expects($this->once())->method('getQueryBuilder')->willReturn($qb); $this->manager->retrieve($userId, $identifier); }
/** * Retrieve a set of credentials * * @param string|null $userId Null for system-wide credentials * @param string $identifier * @return mixed */ public function retrieve($userId, $identifier) { $qb = $this->dbConnection->getQueryBuilder(); $qb->select('credentials')->from(self::DB_TABLE)->where($qb->expr()->eq('user', $qb->createNamedParameter($userId)))->andWhere($qb->expr()->eq('identifier', $qb->createNamedParameter($identifier))); $result = $qb->execute()->fetch(); if (!$result) { return null; } $value = $result['credentials']; return json_decode($this->crypto->decrypt($value), true); }
protected function setUp() { parent::setUp(); $this->wrappedSession = new \OC\Session\Memory($this->getUniqueID()); $this->crypto = $this->getMockBuilder('OCP\\Security\\ICrypto')->disableOriginalConstructor()->getMock(); $this->crypto->expects($this->any())->method('encrypt')->willReturnCallback(function ($input) { return '#' . $input . '#'; }); $this->crypto->expects($this->any())->method('decrypt')->willReturnCallback(function ($input) { return substr($input, 1, -1); }); $this->instance = new CryptoSessionData($this->wrappedSession, $this->crypto, 'PASS'); }
public function getKey($key) { try { $query = \OCP\DB::prepare("SELECT `value` FROM `*PREFIX*ocsms_config` WHERE `key` = ? AND `user` = ?"); $result = $query->execute(array($key, $this->user)); while ($row = $result->fetchRow()) { return $this->crypto->decrypt($row["value"]); } return false; } catch (DoesNotExistException $e) { return false; } }
/** * Get a value from the session * * @param string $key * @return string|null Either the value or null */ public function get($key) { $encryptedValue = $this->session->get($key); if ($encryptedValue === null) { return null; } try { $value = $this->crypto->decrypt($encryptedValue, $this->passphrase); return json_decode($value); } catch (\Exception $e) { return null; } }
/** * Checks if the CSRF check was correct * @return bool true if CSRF check passed * @see OC_Util::callRegister() */ public function passesCSRFCheck() { if ($this->items['requesttoken'] === false) { return false; } if (isset($this->items['get']['requesttoken'])) { $token = $this->items['get']['requesttoken']; } elseif (isset($this->items['post']['requesttoken'])) { $token = $this->items['post']['requesttoken']; } elseif (isset($this->items['server']['HTTP_REQUESTTOKEN'])) { $token = $this->items['server']['HTTP_REQUESTTOKEN']; } else { //no token found. return false; } // Decrypt token to prevent BREACH like attacks $token = explode(':', $token); if (count($token) !== 2) { return false; } $encryptedToken = $token[0]; $secret = $token[1]; try { $decryptedToken = $this->crypto->decrypt($encryptedToken, $secret); } catch (\Exception $e) { return false; } // Check if the token is valid if (\OCP\Security\StringUtils::equals($decryptedToken, $this->items['requesttoken'])) { return true; } else { return false; } }
/** * @NoAdminRequired * * @param string $accountName * @param string $emailAddress * @param string $password * @param string $imapHost * @param int $imapPort * @param string $imapSslMode * @param string $imapUser * @param string $imapPassword * @param string $smtpHost * @param int $smtpPort * @param string $smtpSslMode * @param string $smtpUser * @param string $smtpPassword * @param bool $autoDetect * @return JSONResponse */ public function create($accountName, $emailAddress, $password, $imapHost, $imapPort, $imapSslMode, $imapUser, $imapPassword, $smtpHost, $smtpPort, $smtpSslMode, $smtpUser, $smtpPassword, $autoDetect) { try { if ($autoDetect) { $this->logger->info('setting up auto detected account'); $newAccount = $this->autoConfig->createAutoDetected($emailAddress, $password, $accountName); } else { $this->logger->info('Setting up manually configured account'); $newAccount = new MailAccount(['accountName' => $accountName, 'emailAddress' => $emailAddress, 'imapHost' => $imapHost, 'imapPort' => $imapPort, 'imapSslMode' => $imapSslMode, 'imapUser' => $imapUser, 'imapPassword' => $imapPassword, 'smtpHost' => $smtpHost, 'smtpPort' => $smtpPort, 'smtpSslMode' => $smtpSslMode, 'smtpUser' => $smtpUser, 'smtpPassword' => $smtpPassword]); $newAccount->setUserId($this->currentUserId); $newAccount->setInboundPassword($this->crypto->encrypt($newAccount->getInboundPassword())); $newAccount->setOutboundPassword($this->crypto->encrypt($newAccount->getOutboundPassword())); $a = new Account($newAccount); $this->logger->debug('Connecting to account {account}', ['account' => $newAccount->getEmail()]); $a->testConnectivity(); } if ($newAccount) { $this->accountService->save($newAccount); $this->logger->debug("account created " . $newAccount->getId()); return new JSONResponse(['data' => ['id' => $newAccount->getId()]], Http::STATUS_CREATED); } } catch (\Exception $ex) { $this->logger->error('Creating account failed: ' . $ex->getMessage()); return new JSONResponse(array('message' => $this->l10n->t('Creating account failed: ') . $ex->getMessage()), HTTP::STATUS_BAD_REQUEST); } $this->logger->info('Auto detect failed'); return new JSONResponse(array('message' => $this->l10n->t('Auto detect failed. Please use manual mode.')), HTTP::STATUS_BAD_REQUEST); }
private function decryptValue($value) { try { return $this->crypto->decrypt($value); } catch (\Exception $e) { return $value; } }
/** * @param MailAccount $account * @param $host * @param $users * @param $password * @param bool $withHostPrefix * @return bool */ public function test(MailAccount $account, $host, $users, $password, $withHostPrefix = false) { if (!is_array($users)) { $users = [$users]; } // port 25 should be the last one to test $ports = [587, 465, 25]; $protocols = ['ssl', 'tls', null]; $hostPrefixes = ['']; if ($withHostPrefix) { $hostPrefixes = ['', 'imap.']; } foreach ($hostPrefixes as $hostPrefix) { $url = $hostPrefix . $host; if (gethostbyname($url) === $url) { continue; } foreach ($ports as $port) { if (!$this->canConnect($url, $port)) { continue; } foreach ($protocols as $protocol) { foreach ($users as $user) { try { $account->setOutboundHost($url); $account->setOutboundPort($port); $account->setOutboundUser($user); $password = $this->crypto->encrypt($password); $account->setOutboundPassword($password); $account->setOutboundSslMode($protocol); $a = new Account($account); $smtp = $a->createTransport(); $smtp->getSMTPObject(); $this->logger->info("Test-Account-Successful: {$this->userId}, {$url}, {$port}, {$user}, {$protocol}"); return true; } catch (\Exception $e) { $error = $e->getMessage(); $this->logger->info("Test-Account-Failed: {$this->userId}, {$url}, {$port}, {$user}, {$protocol} -> {$error}"); } } } } } return false; }
/** * Close the session and release the lock, also writes all changed data in batch */ public function close() { if ($this->isModified) { $encryptedValue = $this->crypto->encrypt(json_encode($this->sessionValues), $this->passphrase); $this->session->set(self::encryptedSessionName, $encryptedValue); $this->isModified = false; } $this->session->close(); }
/** * Decrypt the given password * * The token is used as key * * @param string $password * @param string $token * @throws InvalidTokenException * @return string the decrypted key */ private function decryptPassword($password, $token) { $secret = $this->config->getSystemValue('secret'); try { return $this->crypto->decrypt($password, $token . $secret); } catch (Exception $ex) { // Delete the invalid token $this->invalidateToken($token); throw new InvalidTokenException(); } }
/** * @return Horde_Mail_Transport */ public function createTransport() { $transport = $this->config->getSystemValue('app.mail.transport', 'smtp'); if ($transport === 'php-mail') { return new Horde_Mail_Transport_Mail(); } $password = $this->account->getOutboundPassword(); $password = $this->crypto->decrypt($password); $params = ['host' => $this->account->getOutboundHost(), 'password' => $password, 'port' => $this->account->getOutboundPort(), 'username' => $this->account->getOutboundUser(), 'secure' => $this->convertSslMode($this->account->getOutboundSslMode()), 'timeout' => 2]; return new Horde_Mail_Transport_Smtphorde($params); }
/** * @param $backend id of the backend * @param $key key of the config value * @param $value the config value */ public function set($backend, $key, $value) { $value = $this->crypto->encrypt($value); if ($this->hasKey($backend, $key, $value)) { $sql = <<<SQL \t\t\t\tUPDATE \t\t\t\t\t`*PREFIX*chat_config` \t\t\t\tSET \t\t\t\t\t`value` = ? \t\t\t\tWHERE \t\t\t\t\t`user` = ? \t\t\t\tAND \t\t\t\t\t`backend` = ? \t\t\t\tAND \t\t\t\t\t`key` = ? SQL; $this->execute($sql, array($value, $this->user, $backend, $key)); } else { $sql = <<<SQL \t\t\t\tINSERT \t\t\t\tINTO \t\t\t\t\t`*PREFIX*chat_config` \t\t\t\t( \t\t\t\t\t`user`, \t\t\t\t\t`key`, \t\t\t\t\t`value`, \t\t\t\t\t`backend` \t\t\t\t) VALUES ( \t\t\t\t\t?, \t\t\t\t\t?, \t\t\t\t\t?, \t\t\t\t\t? \t\t\t\t) SQL; $this->execute($sql, array($this->user, $key, $value, $backend)); } }
/** * @param $email * @param $password * @param $name * @param $host * @param $port * @param string|null $encryptionProtocol * @param $user * @return MailAccount */ private function connectImap($email, $password, $name, $host, $port, $encryptionProtocol, $user) { $account = new MailAccount(); $account->setUserId($this->userId); $account->setName($name); $account->setEmail($email); $account->setInboundHost($host); $account->setInboundPort($port); $account->setInboundSslMode($encryptionProtocol); $account->setInboundUser($user); $password = $this->crypto->encrypt($password); $account->setInboundPassword($password); $a = new Account($account); $a->getImapConnection(); $this->logger->info("Test-Account-Successful: {$this->userId}, {$host}, {$port}, {$user}, {$encryptionProtocol}"); return $account; }
/** * @param $email * @param $password * @param $name * @return MailAccount|null */ public function createAutoDetected($email, $password, $name) { // splitting the email address into user and host part // TODO: use horde libs for email address parsing list(, $host) = explode("@", $email); $ispdb = $this->mozillaIspDb->query($host); if (!empty($ispdb)) { $account = null; if (isset($ispdb['imap'])) { foreach ($ispdb['imap'] as $imap) { $host = $imap['hostname']; $port = $imap['port']; $encryptionProtocol = null; if ($imap['socketType'] === 'SSL') { $encryptionProtocol = 'ssl'; } if ($imap['socketType'] === 'STARTTLS') { $encryptionProtocol = 'tls'; } if ($imap['username'] === '%EMAILADDRESS%') { $user = $email; } elseif ($imap['username'] === '%EMAILLOCALPART%') { list($user, ) = explode("@", $email); } else { $this->logger->info("Unknown username variable: " . $imap['username']); return null; } try { $account = $this->imapConnector->connect($email, $password, $name, $host, $port, $encryptionProtocol, $user); break; } catch (\Horde_Imap_Client_Exception $e) { $error = $e->getMessage(); $this->logger->info("Test-Account-Failed: {$this->userId}, {$host}, {$port}, {$user}, {$encryptionProtocol} -> {$error}"); } } } if (!is_null($account)) { foreach ($ispdb['smtp'] as $smtp) { try { if ($smtp['username'] === '%EMAILADDRESS%') { $user = $email; } elseif ($smtp['username'] === '%EMAILLOCALPART%') { list($user, ) = explode("@", $email); } else { $this->logger->info("Unknown username variable: " . $smtp['username']); return null; } $account->setOutboundHost($smtp['hostname']); $account->setOutboundPort($smtp['port']); $password = $this->crypto->encrypt($password); $account->setOutboundPassword($password); $account->setOutboundUser($user); $account->setOutboundSslMode(strtolower($smtp['socketType'])); $a = new Account($account); $smtp = $a->createTransport(); if ($smtp instanceof Horde_Mail_Transport_Smtphorde) { $smtp->getSMTPObject(); } break; } catch (\PEAR_Exception $ex) { $error = $ex->getMessage(); $this->logger->info("Test-Account-Failed(smtp): {$error}"); } } return $account; } } $account = $this->detectImapAndSmtp($email, $password, $name); if (!is_null($account)) { return $account; } return null; }