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 testShowLoginFormWithErrorsInSession() { $this->userSession->expects($this->once())->method('isLoggedIn')->willReturn(false); $this->session->expects($this->once())->method('get')->with('loginMessages')->willReturn([['ErrorArray1', 'ErrorArray2'], ['MessageArray1', 'MessageArray2']]); $expectedResponse = new TemplateResponse('core', 'login', ['ErrorArray1' => true, 'ErrorArray2' => true, 'messages' => ['MessageArray1', 'MessageArray2'], 'loginName' => '', 'user_autofocus' => true, 'canResetPassword' => true, 'alt_login' => [], 'rememberLoginAllowed' => \OC_Util::rememberLoginAllowed(), 'rememberLoginState' => 0], 'guest'); $this->assertEquals($expectedResponse, $this->loginController->showLoginForm('', '', '')); }
/** * @NoAdminRequired * @NoSubadminRequired * * @return JSONResponse */ public function create($name) { try { $sessionId = $this->session->getId(); } catch (SessionNotAvailableException $ex) { $resp = new JSONResponse(); $resp->setStatus(Http::STATUS_SERVICE_UNAVAILABLE); return $resp; } try { $sessionToken = $this->tokenProvider->getToken($sessionId); $loginName = $sessionToken->getLoginName(); try { $password = $this->tokenProvider->getPassword($sessionToken, $sessionId); } catch (PasswordlessTokenException $ex) { $password = null; } } catch (InvalidTokenException $ex) { $resp = new JSONResponse(); $resp->setStatus(Http::STATUS_SERVICE_UNAVAILABLE); return $resp; } $token = $this->generateRandomDeviceToken(); $deviceToken = $this->tokenProvider->generateToken($token, $this->uid, $loginName, $password, $name, IToken::PERMANENT_TOKEN); return ['token' => $token, 'deviceToken' => $deviceToken]; }
/** * @NoAdminRequired * @NoCSRFRequired * * @param string $src * * TODO: Cache the proxied content to prevent unnecessary requests from the oC server * The caching should also already happen in a cronjob so that the sender of the * mail does not know whether the mail has been opened. * * @return ProxyDownloadResponse */ public function proxy($src) { // close the session to allow parallel downloads $this->session->close(); $content = $this->helper->getUrlContent($src); return new ProxyDownloadResponse($content, $src, 'application/octet-stream'); }
/** * Makes sure the user is already properly authenticated when a password is required and none * was provided * * @param array|bool $linkItem * * @throws CheckException */ private function checkSession($linkItem) { // Not authenticated ? if (!$this->session->exists('public_link_authenticated') || $this->session->get('public_link_authenticated') !== $linkItem['id']) { throw new CheckException("Missing password", Http::STATUS_UNAUTHORIZED); } }
/** * Makes sure the user is already properly authenticated when a password is required and none * was provided * * @param IShare $share * * @throws CheckException */ private function checkSession($share) { // Not authenticated ? if (!$this->session->exists('public_link_authenticated') || $this->session->get('public_link_authenticated') !== (string) $share->getId()) { throw new CheckException("Missing password", Http::STATUS_UNAUTHORIZED); } }
/** * Get the timezone of the current user, based on his session information and config data * * @param bool|int $timestamp * @return \DateTimeZone */ public function getTimeZone($timestamp = false) { $timeZone = $this->config->getUserValue($this->session->get('user_id'), 'core', 'timezone', null); if ($timeZone === null) { if ($this->session->exists('timezone')) { return $this->guessTimeZoneFromOffset($this->session->get('timezone'), $timestamp); } $timeZone = $this->getDefaultTimeZone(); } try { return new \DateTimeZone($timeZone); } catch (\Exception $e) { \OCP\Util::writeLog('datetimezone', 'Failed to created DateTimeZone "' . $timeZone . "'", \OCP\Util::DEBUG); return new \DateTimeZone($this->getDefaultTimeZone()); } }
/** * @NoAdminRequired * @NoCSRFRequired * * TODO: Cache the proxied content to prevent unnecessary requests from the oC server * The caching should also already happen in a cronjob so that the sender of the * mail does not know whether the mail has been opened. * * @return ProxyDownloadResponse */ public function proxy() { // close the session to allow parallel downloads $this->session->close(); $resourceURL = $this->request->getParam('src'); $content = \OC::$server->getHelper()->getUrlContent($resourceURL); return new ProxyDownloadResponse($content, $resourceURL, 'application/octet-stream'); }
/** * remove keys from session */ public function clear() { $this->session->remove('publicSharePrivateKey'); $this->session->remove('privateKey'); $this->session->remove('encryptionInitialized'); $this->session->remove('decryptAll'); $this->session->remove('decryptAllKey'); $this->session->remove('decryptAllUid'); }
/** * 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(); }
/** * */ protected function setUp() { parent::setUp(); $this->sessionMock = $this->getMock('OCP\\ISession'); $this->sessionMock->expects($this->any())->method('set')->will($this->returnCallback([$this, "setValueTester"])); $this->sessionMock->expects($this->any())->method('get')->will($this->returnCallback([$this, "getValueTester"])); $this->sessionMock->expects($this->any())->method('remove')->will($this->returnCallback([$this, "removeValueTester"])); $this->instance = new Session($this->sessionMock); }
public function testAuthenticateAlreadyLoggedIn() { $server = $this->getMockBuilder('\\Sabre\\DAV\\Server')->disableOriginalConstructor()->getMock(); $this->userSession->expects($this->once())->method('isLoggedIn')->will($this->returnValue(true)); $this->session->expects($this->once())->method('get')->with('AUTHENTICATED_TO_DAV_BACKEND')->will($this->returnValue(null)); $user = $this->getMockBuilder('\\OCP\\IUser')->disableOriginalConstructor()->getMock(); $user->expects($this->once())->method('getUID')->will($this->returnValue('MyWrongDavUser')); $this->userSession->expects($this->once())->method('getUser')->will($this->returnValue($user)); $this->session->expects($this->once())->method('close'); $this->assertTrue($this->auth->authenticate($server, 'TestRealm')); }
/** * @param \Sabre\DAV\Server $server * @param $realm * @return bool */ private function auth(\Sabre\DAV\Server $server, $realm) { if (\OC_User::handleApacheAuth() || $this->userSession->isLoggedIn() && is_null($this->session->get(self::DAV_AUTHENTICATED))) { $user = $this->userSession->getUser()->getUID(); \OC_Util::setupFS($user); $this->currentUser = $user; $this->session->close(); return true; } return parent::authenticate($server, $realm); }
public function testAuthenticateNoBasicAuthenticateHeadersProvidedWithAjaxButUserIsStillLoggedIn() { /** @var \Sabre\HTTP\RequestInterface $httpRequest */ $httpRequest = $this->getMockBuilder('\\Sabre\\HTTP\\RequestInterface')->disableOriginalConstructor()->getMock(); /** @var \Sabre\HTTP\ResponseInterface $httpResponse */ $httpResponse = $this->getMockBuilder('\\Sabre\\HTTP\\ResponseInterface')->disableOriginalConstructor()->getMock(); $this->userSession->expects($this->any())->method('isLoggedIn')->will($this->returnValue(true)); $this->session->expects($this->once())->method('get')->with('AUTHENTICATED_TO_DAV_BACKEND')->will($this->returnValue('MyTestUser')); $httpRequest->expects($this->once())->method('getHeader')->with('Authorization')->will($this->returnValue(null)); $this->auth->check($httpRequest, $httpResponse); }
/** * Get the timezone of the current user, based on his session information and config data * * @return \DateTimeZone */ public function getTimeZone() { $timeZone = $this->config->getUserValue($this->session->get('user_id'), 'core', 'timezone', null); if ($timeZone === null) { if ($this->session->exists('timezone')) { $offsetHours = $this->session->get('timezone'); // Note: the timeZone name is the inverse to the offset, // so a positive offset means negative timeZone // and the other way around. if ($offsetHours > 0) { return new \DateTimeZone('Etc/GMT-' . $offsetHours); } else { return new \DateTimeZone('Etc/GMT+' . abs($offsetHours)); } } else { return new \DateTimeZone('UTC'); } } return new \DateTimeZone($timeZone); }
/** * Update password of the browser session token if there is one * * @param string $password */ public function updateSessionTokenPassword($password) { try { $sessionId = $this->session->getId(); $token = $this->tokenProvider->getToken($sessionId); $this->tokenProvider->setPassword($token, $sessionId, $password); } catch (SessionNotAvailableException $ex) { // Nothing to do } catch (InvalidTokenException $ex) { // Nothing to do } }
public function testAuthenticateAlreadyLoggedIn() { $request = $this->getMockBuilder('Sabre\\HTTP\\RequestInterface')->disableOriginalConstructor()->getMock(); $response = $this->getMockBuilder('Sabre\\HTTP\\ResponseInterface')->disableOriginalConstructor()->getMock(); $this->userSession->expects($this->once())->method('isLoggedIn')->will($this->returnValue(true)); $this->session->expects($this->once())->method('get')->with('AUTHENTICATED_TO_DAV_BACKEND')->will($this->returnValue(null)); $user = $this->getMockBuilder('\\OCP\\IUser')->disableOriginalConstructor()->getMock(); $user->expects($this->once())->method('getUID')->will($this->returnValue('MyWrongDavUser')); $this->userSession->expects($this->once())->method('getUser')->will($this->returnValue($user)); $this->session->expects($this->once())->method('close'); $response = $this->auth->check($request, $response); $this->assertEquals([true, 'principals/users/MyWrongDavUser'], $response); }
public function testSharePasswordLinkInvalidSession() { $share = $this->getMock('OCP\\Share\\IShare'); $share->method('getPassword')->willReturn('password'); $share->method('getShareType')->willReturn(\OCP\Share::SHARE_TYPE_LINK); $share->method('getId')->willReturn('42'); $this->shareManager->expects($this->once())->method('getShareByToken')->willReturn($share); $this->shareManager->method('checkPassword')->with($this->equalTo($share), $this->equalTo('password'))->willReturn(false); $this->session->method('exists')->with('public_link_authenticated')->willReturn(true); $this->session->method('get')->with('public_link_authenticated')->willReturn('43'); $result = $this->invokePrivate($this->auth, 'validateUserPass', ['username', 'password']); $this->assertFalse($result); }
/** * Validates a username and password * * This method should return true or false depending on if login * succeeded. * * @param string $username * @param string $password * * @return bool * @throws \Sabre\DAV\Exception\NotAuthenticated */ protected function validateUserPass($username, $password) { try { $share = $this->shareManager->getShareByToken($username); } catch (ShareNotFound $e) { return false; } $this->share = $share; \OC_User::setIncognitoMode(true); // check if the share is password protected if ($share->getPassword() !== null) { if ($share->getShareType() === \OCP\Share::SHARE_TYPE_LINK) { if ($this->shareManager->checkPassword($share, $password)) { return true; } else { if ($this->session->exists('public_link_authenticated') && $this->session->get('public_link_authenticated') === $share->getId()) { return true; } else { if (in_array('XMLHttpRequest', explode(',', $this->request->getHeader('X-Requested-With')))) { // do not re-authenticate over ajax, use dummy auth name to prevent browser popup http_response_code(401); header('WWW-Authenticate', 'DummyBasic real="ownCloud"'); throw new \Sabre\DAV\Exception\NotAuthenticated('Cannot authenticate over ajax calls'); } return false; } } } else { if ($share->getShareType() === \OCP\Share::SHARE_TYPE_REMOTE) { return true; } else { return false; } } } else { return true; } }
/** * logout the user from the session */ public function logout() { $this->manager->emit('\\OC\\User', 'logout'); $user = $this->getUser(); if (!is_null($user)) { try { $this->tokenProvider->invalidateToken($this->session->getId()); } catch (SessionNotAvailableException $ex) { } } $this->setUser(null); $this->setLoginName(null); $this->unsetMagicInCookie(); $this->session->clear(); }
/** * @PublicPage * @NoCSRFRequired * @UseSession * * @param string $user * @param string $redirect_url * @param string $remember_login * * @return TemplateResponse */ public function showLoginForm($user, $redirect_url, $remember_login) { if ($this->userSession->isLoggedIn()) { return new RedirectResponse(\OC_Util::getDefaultPageUrl()); } $parameters = array(); $loginMessages = $this->session->get('loginMessages'); $errors = []; $messages = []; if (is_array($loginMessages)) { list($errors, $messages) = $loginMessages; } $this->session->remove('loginMessages'); foreach ($errors as $value) { $parameters[$value] = true; } $parameters['messages'] = $messages; if (!is_null($user) && $user !== '') { $parameters['loginName'] = $user; $parameters['user_autofocus'] = false; } else { $parameters['loginName'] = ''; $parameters['user_autofocus'] = true; } if (!empty($redirect_url)) { $parameters['redirect_url'] = $redirect_url; } $parameters['canResetPassword'] = true; if (!$this->config->getSystemValue('lost_password_link')) { if (!is_null($user) && $user !== '') { $userObj = $this->userManager->get($user); if ($userObj instanceof IUser) { $parameters['canResetPassword'] = $userObj->canChangePassword(); } } } $parameters['alt_login'] = \OC_App::getAlternativeLogIns(); $parameters['rememberLoginAllowed'] = \OC_Util::rememberLoginAllowed(); $parameters['rememberLoginState'] = !empty($remember_login) ? $remember_login : 0; if (!is_null($user) && $user !== '') { $parameters['loginName'] = $user; $parameters['user_autofocus'] = false; } else { $parameters['loginName'] = ''; $parameters['user_autofocus'] = true; } return new TemplateResponse($this->appName, 'login', $parameters, 'guest'); }
/** * @NoAdminRequired * @NoCSRFRequired * @UseSession * * @param string $challengeProviderId * @param string $challenge * @param string $redirect_url * @return RedirectResponse */ public function solveChallenge($challengeProviderId, $challenge, $redirect_url = null) { $user = $this->userSession->getUser(); $provider = $this->twoFactorManager->getProvider($user, $challengeProviderId); if (is_null($provider)) { return new RedirectResponse($this->urlGenerator->linkToRoute('core.TwoFactorChallenge.selectChallenge')); } if ($this->twoFactorManager->verifyChallenge($challengeProviderId, $user, $challenge)) { if (!is_null($redirect_url)) { return new RedirectResponse($this->urlGenerator->getAbsoluteURL(urldecode($redirect_url))); } return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index')); } $this->session->set('two_factor_auth_error', true); return new RedirectResponse($this->urlGenerator->linkToRoute('core.TwoFactorChallenge.showChallenge', ['challengeProviderId' => $provider->getId(), 'redirect_url' => $redirect_url])); }
/** * Authenticate a link item with the given password. * Or use the session if no password is provided. * * This is a modified version of Helper::authenticate * TODO: Try to merge back eventually with Helper::authenticate * * @param \OCP\Share\IShare $share * @param string|null $password * @return bool */ private function linkShareAuth(\OCP\Share\IShare $share, $password = null) { if ($password !== null) { if ($this->shareManager->checkPassword($share, $password)) { $this->session->set('public_link_authenticated', (string) $share->getId()); } else { return false; } } else { // not authenticated ? if (!$this->session->exists('public_link_authenticated') || $this->session->get('public_link_authenticated') !== (string) $share->getId()) { return false; } } return true; }
/** * @param \Sabre\DAV\Server $server * @param string $realm * @return bool */ private function auth(\Sabre\DAV\Server $server, $realm) { if (\OC_User::handleApacheAuth() || $this->userSession->isLoggedIn() && is_null($this->session->get(self::DAV_AUTHENTICATED))) { $user = $this->userSession->getUser()->getUID(); \OC_Util::setupFS($user); $this->currentUser = $user; $this->session->close(); return true; } if ($server->httpRequest->getHeader('X-Requested-With') === 'XMLHttpRequest') { // do not re-authenticate over ajax, use dummy auth name to prevent browser popup $server->httpResponse->addHeader('WWW-Authenticate', 'DummyBasic realm="' . $realm . '"'); $server->httpResponse->setStatus(401); throw new \Sabre\DAV\Exception\NotAuthenticated('Cannot authenticate over ajax calls'); } return parent::authenticate($server, $realm); }
/** * @param RequestInterface $request * @param ResponseInterface $response * @return array */ private function auth(RequestInterface $request, ResponseInterface $response) { if (\OC_User::handleApacheAuth() || $this->userSession->isLoggedIn() && is_null($this->session->get(self::DAV_AUTHENTICATED)) || $this->userSession->isLoggedIn() && $this->session->get(self::DAV_AUTHENTICATED) === $this->userSession->getUser()->getUID() && $request->getHeader('Authorization') === null) { $user = $this->userSession->getUser()->getUID(); \OC_Util::setupFS($user); $this->currentUser = $user; $this->session->close(); return [true, $this->principalPrefix . $user]; } if (!$this->userSession->isLoggedIn() && in_array('XMLHttpRequest', explode(',', $request->getHeader('X-Requested-With')))) { // do not re-authenticate over ajax, use dummy auth name to prevent browser popup $response->addHeader('WWW-Authenticate', 'DummyBasic realm="' . $this->realm . '"'); $response->setStatus(401); throw new \Sabre\DAV\Exception\NotAuthenticated('Cannot authenticate over ajax calls'); } return parent::check($request, $response); }
/** * test updatePrivateKeyPassword() with the correct old and new password */ public function testUpdatePrivateKeyPassword() { $oldPassword = '******'; $newPassword = '******'; $this->ocSessionMock->expects($this->once())->method('get')->with('loginname')->willReturn('testUser'); $this->userManagerMock->expects($this->at(0))->method('checkPassword')->with('testUserUid', 'new')->willReturn(false); $this->userManagerMock->expects($this->at(1))->method('checkPassword')->with('testUser', 'new')->willReturn(true); $this->cryptMock->expects($this->once())->method('decryptPrivateKey')->willReturn('decryptedKey'); $this->cryptMock->expects($this->once())->method('encryptPrivateKey')->willReturn('encryptedKey'); $this->cryptMock->expects($this->once())->method('generateHeader')->willReturn('header.'); // methods which must be called after successful changing the key password $this->keyManagerMock->expects($this->once())->method('setPrivateKey')->with($this->equalTo('testUserUid'), $this->equalTo('header.encryptedKey')); $this->sessionMock->expects($this->once())->method('setPrivateKey')->with($this->equalTo('decryptedKey')); $this->sessionMock->expects($this->once())->method('setStatus')->with($this->equalTo(Session::INIT_SUCCESSFUL)); $result = $this->controller->updatePrivateKeyPassword($oldPassword, $newPassword); $data = $result->getData(); $this->assertSame(Http::STATUS_OK, $result->getStatus()); $this->assertSame('Private key password successfully updated.', $data['message']); }
/** * @PublicPage * @UseSession * * @param string $user * @param string $password * @param string $redirect_url * @return RedirectResponse */ public function tryLogin($user, $password, $redirect_url) { $originalUser = $user; // TODO: Add all the insane error handling /* @var $loginResult IUser */ $loginResult = $this->userManager->checkPassword($user, $password); if ($loginResult === false) { $users = $this->userManager->getByEmail($user); // we only allow login by email if unique if (count($users) === 1) { $user = $users[0]->getUID(); $loginResult = $this->userManager->checkPassword($user, $password); } } if ($loginResult === false) { $this->session->set('loginMessages', [['invalidpassword']]); // Read current user and append if possible - we need to return the unmodified user otherwise we will leak the login name $args = !is_null($user) ? ['user' => $originalUser] : []; return new RedirectResponse($this->urlGenerator->linkToRoute('core.login.showLoginForm', $args)); } // TODO: remove password checks from above and let the user session handle failures // requires https://github.com/owncloud/core/pull/24616 $this->userSession->login($user, $password); $this->userSession->createSessionToken($this->request, $loginResult->getUID(), $user, $password); if ($this->twoFactorManager->isTwoFactorAuthenticated($loginResult)) { $this->twoFactorManager->prepareTwoFactorLogin($loginResult); if (!is_null($redirect_url)) { return new RedirectResponse($this->urlGenerator->linkToRoute('core.TwoFactorChallenge.selectChallenge', ['redirect_url' => $redirect_url])); } return new RedirectResponse($this->urlGenerator->linkToRoute('core.TwoFactorChallenge.selectChallenge')); } if (!is_null($redirect_url) && $this->userSession->isLoggedIn()) { $location = $this->urlGenerator->getAbsoluteURL(urldecode($redirect_url)); // Deny the redirect if the URL contains a @ // This prevents unvalidated redirects like ?redirect_url=:user@domain.com if (strpos($location, '@') === false) { return new RedirectResponse($location); } } return new RedirectResponse($this->urlGenerator->linkToRoute('files.view.index')); }
/** * @param RequestInterface $request * @param ResponseInterface $response * @return array * @throws NotAuthenticated */ private function auth(RequestInterface $request, ResponseInterface $response) { $forcedLogout = false; if (!$this->request->passesCSRFCheck() && $this->requiresCSRFCheck()) { // In case of a fail with POST we need to recheck the credentials if ($this->request->getMethod() === 'POST') { $forcedLogout = true; } else { $response->setStatus(401); throw new \Sabre\DAV\Exception\NotAuthenticated('CSRF check not passed.'); } } if ($forcedLogout) { $this->userSession->logout(); } else { if ($this->twoFactorManager->needsSecondFactor()) { throw new \Sabre\DAV\Exception\NotAuthenticated('2FA challenge not passed.'); } if (\OC_User::handleApacheAuth() || $this->userSession->isLoggedIn() && is_null($this->session->get(self::DAV_AUTHENTICATED)) || $this->userSession->isLoggedIn() && $this->session->get(self::DAV_AUTHENTICATED) === $this->userSession->getUser()->getUID() && $request->getHeader('Authorization') === null) { $user = $this->userSession->getUser()->getUID(); \OC_Util::setupFS($user); $this->currentUser = $user; $this->session->close(); return [true, $this->principalPrefix . $user]; } } if (!$this->userSession->isLoggedIn() && in_array('XMLHttpRequest', explode(',', $request->getHeader('X-Requested-With')))) { // do not re-authenticate over ajax, use dummy auth name to prevent browser popup $response->addHeader('WWW-Authenticate', 'DummyBasic realm="' . $this->realm . '"'); $response->setStatus(401); throw new \Sabre\DAV\Exception\NotAuthenticated('Cannot authenticate over ajax calls'); } $data = parent::check($request, $response); if ($data[0] === true) { $startPos = strrpos($data[1], '/') + 1; $user = $this->userSession->getUser()->getUID(); $data[1] = substr_replace($data[1], $user, $startPos); } return $data; }
/** * @NoAdminRequired * @NoSubadminRequired * * @return JSONResponse */ public function create($name) { try { $sessionId = $this->session->getId(); } catch (SessionNotAvailableException $ex) { return $this->getServiceNotAvailableResponse(); } try { $sessionToken = $this->tokenProvider->getToken($sessionId); $loginName = $sessionToken->getLoginName(); try { $password = $this->tokenProvider->getPassword($sessionToken, $sessionId); } catch (PasswordlessTokenException $ex) { $password = null; } } catch (InvalidTokenException $ex) { return $this->getServiceNotAvailableResponse(); } $token = $this->generateRandomDeviceToken(); $deviceToken = $this->tokenProvider->generateToken($token, $this->uid, $loginName, $password, $name, IToken::PERMANENT_TOKEN); return ['token' => $token, 'loginName' => $loginName, 'deviceToken' => $deviceToken]; }