server/lib/private/User/Session.php

614 lines
17 KiB
PHP
Raw Normal View History

2013-05-28 21:46:57 +00:00
<?php
/**
2016-05-26 17:56:05 +00:00
* @author Arthur Schiwon <blizzz@arthur-schiwon.de>
2015-03-26 10:44:34 +00:00
* @author Bernhard Posselt <dev@bernhard-posselt.com>
* @author Christoph Wurst <christoph@owncloud.com>
2015-03-26 10:44:34 +00:00
* @author Jörn Friedrich Dreyer <jfd@butonic.de>
2016-05-26 17:56:05 +00:00
* @author Lukas Reschke <lukas@statuscode.ch>
2015-03-26 10:44:34 +00:00
* @author Morris Jobke <hey@morrisjobke.de>
* @author Robin Appelman <icewind@owncloud.com>
2016-01-12 14:02:16 +00:00
* @author Robin McCorkell <robin@mccorkell.me.uk>
2015-03-26 10:44:34 +00:00
* @author Thomas Müller <thomas.mueller@tmit.eu>
* @author Vincent Petry <pvince81@owncloud.com>
*
2016-01-12 14:02:16 +00:00
* @copyright Copyright (c) 2016, ownCloud, Inc.
2015-03-26 10:44:34 +00:00
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
2013-05-28 21:46:57 +00:00
*/
2013-05-28 21:46:57 +00:00
namespace OC\User;
use OC;
use OC\Authentication\Exceptions\InvalidTokenException;
use OC\Authentication\Token\IProvider;
2016-04-27 07:38:30 +00:00
use OC\Authentication\Token\IToken;
2013-05-28 21:46:57 +00:00
use OC\Hooks\Emitter;
use OC_User;
2016-05-02 17:58:19 +00:00
use OC_Util;
use OCA\DAV\Connector\Sabre\Auth;
2016-05-02 17:58:19 +00:00
use OCP\AppFramework\Utility\ITimeFactory;
use OCP\IConfig;
use OCP\IRequest;
use OCP\ISession;
use OCP\IUser;
use OCP\IUserManager;
use OCP\IUserSession;
use OCP\Session\Exceptions\SessionNotAvailableException;
2013-05-28 21:46:57 +00:00
/**
* Class Session
*
* Hooks available in scope \OC\User:
* - preSetPassword(\OC\User\User $user, string $password, string $recoverPassword)
* - postSetPassword(\OC\User\User $user, string $password, string $recoverPassword)
* - preDelete(\OC\User\User $user)
* - postDelete(\OC\User\User $user)
* - preCreateUser(string $uid, string $password)
* - postCreateUser(\OC\User\User $user)
* - preLogin(string $user, string $password)
* - postLogin(\OC\User\User $user, string $password)
* - preRememberedLogin(string $uid)
* - postRememberedLogin(\OC\User\User $user)
2013-05-28 21:46:57 +00:00
* - logout()
*
* @package OC\User
*/
class Session implements IUserSession, Emitter {
/** @var IUserManager $manager */
2013-05-28 21:46:57 +00:00
private $manager;
2016-05-17 15:20:54 +00:00
/** @var ISession $session */
2013-05-28 21:46:57 +00:00
private $session;
2016-05-17 15:20:54 +00:00
/** @var ITimeFactory */
2016-05-02 17:58:19 +00:00
private $timeFacory;
2016-05-17 15:20:54 +00:00
/** @var IProvider */
private $tokenProvider;
/** @var IConfig */
private $config;
2016-05-17 15:20:54 +00:00
/** @var User $activeUser */
2013-05-28 21:46:57 +00:00
protected $activeUser;
/**
* @param IUserManager $manager
* @param ISession $session
2016-05-06 14:31:40 +00:00
* @param ITimeFactory $timeFacory
* @param IProvider $tokenProvider
* @param IConfig $config
2013-05-28 21:46:57 +00:00
*/
public function __construct(IUserManager $manager, ISession $session, ITimeFactory $timeFacory, $tokenProvider, IConfig $config) {
2013-05-28 21:46:57 +00:00
$this->manager = $manager;
$this->session = $session;
2016-05-02 17:58:19 +00:00
$this->timeFacory = $timeFacory;
$this->tokenProvider = $tokenProvider;
$this->config = $config;
2013-05-28 21:46:57 +00:00
}
2016-04-27 10:01:13 +00:00
/**
2016-05-17 15:20:54 +00:00
* @param IProvider $provider
2016-04-27 10:01:13 +00:00
*/
2016-05-17 15:20:54 +00:00
public function setTokenProvider(IProvider $provider) {
2016-04-27 10:01:13 +00:00
$this->tokenProvider = $provider;
}
2013-05-28 21:46:57 +00:00
/**
* @param string $scope
* @param string $method
* @param callable $callback
*/
2015-05-08 12:27:22 +00:00
public function listen($scope, $method, callable $callback) {
2013-05-28 21:46:57 +00:00
$this->manager->listen($scope, $method, $callback);
}
/**
* @param string $scope optional
* @param string $method optional
* @param callable $callback optional
*/
public function removeListener($scope = null, $method = null, callable $callback = null) {
2013-05-28 21:46:57 +00:00
$this->manager->removeListener($scope, $method, $callback);
}
/**
2013-06-03 11:33:56 +00:00
* get the manager object
*
* @return Manager
2013-05-28 21:46:57 +00:00
*/
public function getManager() {
return $this->manager;
}
/**
* get the session object
*
* @return ISession
*/
public function getSession() {
return $this->session;
}
/**
* set the session object
*
* @param ISession $session
*/
public function setSession(ISession $session) {
if ($this->session instanceof ISession) {
$this->session->close();
}
$this->session = $session;
$this->activeUser = null;
}
2013-05-28 21:46:57 +00:00
/**
* set the currently active user
*
* @param User|null $user
2013-05-28 21:46:57 +00:00
*/
public function setUser($user) {
if (is_null($user)) {
$this->session->remove('user_id');
} else {
$this->session->set('user_id', $user->getUID());
}
$this->activeUser = $user;
}
/**
* get the current active user
*
* @return IUser|null Current user, otherwise null
2013-05-28 21:46:57 +00:00
*/
public function getUser() {
// FIXME: This is a quick'n dirty work-around for the incognito mode as
// described at https://github.com/owncloud/core/pull/12912#issuecomment-67391155
if (OC_User::isIncognitoMode()) {
return null;
}
2016-04-28 08:52:28 +00:00
if (is_null($this->activeUser)) {
2013-05-28 21:46:57 +00:00
$uid = $this->session->get('user_id');
2016-04-28 08:52:28 +00:00
if (is_null($uid)) {
return null;
}
$this->activeUser = $this->manager->get($uid);
if (is_null($this->activeUser)) {
2013-05-28 21:46:57 +00:00
return null;
}
2016-04-28 08:52:28 +00:00
$this->validateSession($this->activeUser);
2013-05-28 21:46:57 +00:00
}
2016-04-28 08:52:28 +00:00
return $this->activeUser;
2013-05-28 21:46:57 +00:00
}
2016-04-28 08:52:28 +00:00
protected function validateSession(IUser $user) {
try {
$sessionId = $this->session->getId();
} catch (SessionNotAvailableException $ex) {
return;
}
try {
$token = $this->tokenProvider->getToken($sessionId);
} catch (InvalidTokenException $ex) {
2016-04-28 08:52:28 +00:00
// Session was invalidated
$this->logout();
2016-05-06 14:31:40 +00:00
return;
}
// Check whether login credentials are still valid and the user was not disabled
// This check is performed each 5 minutes
$lastCheck = $this->session->get('last_login_check') ? : 0;
2016-05-02 17:58:19 +00:00
$now = $this->timeFacory->getTime();
if ($lastCheck < ($now - 60 * 5)) {
try {
$pwd = $this->tokenProvider->getPassword($token, $sessionId);
} catch (InvalidTokenException $ex) {
// An invalid token password was used -> log user out
$this->logout();
return;
}
if ($this->manager->checkPassword($token->getLoginName(), $pwd) === false
|| !$user->isEnabled()) {
// Password has changed or user was disabled -> log user out
$this->logout();
2016-05-06 14:31:40 +00:00
return;
}
2016-05-02 17:58:19 +00:00
$this->session->set('last_login_check', $now);
}
// Session is valid, so the token can be refreshed
2016-05-17 15:20:54 +00:00
$this->updateToken($token);
}
/**
2014-12-19 13:36:00 +00:00
* Checks whether the user is logged in
*
* @return bool if logged in
*/
public function isLoggedIn() {
$user = $this->getUser();
if (is_null($user)) {
return false;
}
return $user->isEnabled();
}
/**
* set the login name
*
2014-05-12 22:27:36 +00:00
* @param string|null $loginName for the logged in user
*/
2014-01-09 09:27:47 +00:00
public function setLoginName($loginName) {
if (is_null($loginName)) {
$this->session->remove('loginname');
} else {
2014-01-09 09:27:47 +00:00
$this->session->set('loginname', $loginName);
}
}
/**
* get the login name of the current user
*
* @return string
*/
2014-01-09 09:27:47 +00:00
public function getLoginName() {
if ($this->activeUser) {
return $this->session->get('loginname');
} else {
$uid = $this->session->get('user_id');
if ($uid) {
$this->activeUser = $this->manager->get($uid);
return $this->session->get('loginname');
} else {
return null;
}
}
}
2013-06-03 11:33:56 +00:00
/**
* try to log in with the provided credentials
2013-06-03 11:33:56 +00:00
*
* @param string $uid
* @param string $password
* @return boolean|null
* @throws LoginException
2013-06-03 11:33:56 +00:00
*/
2013-05-28 21:46:57 +00:00
public function login($uid, $password) {
$this->session->regenerateId();
2016-05-19 13:52:38 +00:00
if ($this->validateToken($password)) {
$user = $this->getUser();
// When logging in with token, the password must be decrypted first before passing to login hook
try {
$token = $this->tokenProvider->getToken($password);
$password = $this->tokenProvider->getPassword($token, $password);
$this->manager->emit('\OC\User', 'preLogin', array($uid, $password));
} catch (InvalidTokenException $ex) {
// Invalid token, nothing to do
}
2016-05-19 13:52:38 +00:00
} else {
$this->manager->emit('\OC\User', 'preLogin', array($uid, $password));
$user = $this->manager->checkPassword($uid, $password);
}
if ($user !== false) {
if (!is_null($user)) {
if ($user->isEnabled()) {
$this->setUser($user);
2014-01-09 09:27:47 +00:00
$this->setLoginName($uid);
$this->manager->emit('\OC\User', 'postLogin', array($user, $password));
if ($this->isLoggedIn()) {
2016-04-28 08:52:28 +00:00
$this->prepareUserLogin();
return true;
} else {
// injecting l10n does not work - there is a circular dependency between session and \OCP\L10N\IFactory
$message = \OC::$server->getL10N('lib')->t('Login canceled by app');
throw new LoginException($message);
}
} else {
// injecting l10n does not work - there is a circular dependency between session and \OCP\L10N\IFactory
$message = \OC::$server->getL10N('lib')->t('User disabled');
throw new LoginException($message);
}
2013-05-28 21:46:57 +00:00
}
}
return false;
2013-05-28 21:46:57 +00:00
}
/**
* Tries to log in a client
*
* Checks token auth enforced
* Checks 2FA enabled
*
* @param string $user
* @param string $password
* @throws LoginException
* @return boolean
*/
public function logClientIn($user, $password) {
$isTokenPassword = $this->isTokenPassword($password);
if (!$isTokenPassword && $this->isTokenAuthEnforced()) {
// TODO: throw LoginException instead (https://github.com/owncloud/core/pull/24616)
return false;
}
if (!$isTokenPassword && $this->isTwoFactorEnforced($user)) {
// TODO: throw LoginException instead (https://github.com/owncloud/core/pull/24616)
return false;
}
return $this->login($user, $password);
}
private function isTokenAuthEnforced() {
return $this->config->getSystemValue('token_auth_enforced', false);
}
protected function isTwoFactorEnforced($username) {
\OCP\Util::emitHook(
'\OCA\Files_Sharing\API\Server2Server',
'preLoginNameUsedAsUserName',
array('uid' => &$username)
);
$user = $this->manager->get($username);
if (is_null($user)) {
return true;
}
// DI not possible due to cyclic dependencies :'-/
return OC::$server->getTwoFactorAuthManager()->isTwoFactorAuthenticated($user);
}
/**
* Check if the given 'password' is actually a device token
*
* @param type $password
* @return boolean
*/
public function isTokenPassword($password) {
try {
$this->tokenProvider->getToken($password);
return true;
} catch (InvalidTokenException $ex) {
return false;
}
}
2016-04-28 08:52:28 +00:00
protected function prepareUserLogin() {
// TODO: mock/inject/use non-static
// Refresh the token
\OC::$server->getCsrfTokenManager()->refreshToken();
//we need to pass the user name, which may differ from login name
$user = $this->getUser()->getUID();
2016-05-02 17:58:19 +00:00
OC_Util::setupFS($user);
2016-04-28 08:52:28 +00:00
//trigger creation of user home and /files folder
\OC::$server->getUserFolder($user);
}
/**
* Tries to login the user with HTTP Basic Authentication
2016-04-29 12:00:07 +00:00
*
2016-05-11 09:23:25 +00:00
* @todo do not allow basic auth if the user is 2FA enforced
2016-04-29 12:00:07 +00:00
* @param IRequest $request
2016-04-27 07:38:30 +00:00
* @return boolean if the login was successful
*/
2016-04-29 07:40:33 +00:00
public function tryBasicAuthLogin(IRequest $request) {
2016-05-06 14:31:40 +00:00
if (!empty($request->server['PHP_AUTH_USER']) && !empty($request->server['PHP_AUTH_PW'])) {
$result = $this->logClientIn($request->server['PHP_AUTH_USER'], $request->server['PHP_AUTH_PW']);
if ($result === true) {
/**
* Add DAV authenticated. This should in an ideal world not be
* necessary but the iOS App reads cookies from anywhere instead
* only the DAV endpoint.
* This makes sure that the cookies will be valid for the whole scope
* @see https://github.com/owncloud/core/issues/22893
*/
$this->session->set(
Auth::DAV_AUTHENTICATED, $this->getUser()->getUID()
);
2016-05-06 14:31:40 +00:00
return true;
}
}
2016-04-27 07:38:30 +00:00
return false;
}
private function loginWithToken($uid) {
2016-05-06 14:31:40 +00:00
// TODO: $this->manager->emit('\OC\User', 'preTokenLogin', array($uid));
$user = $this->manager->get($uid);
if (is_null($user)) {
// user does not exist
return false;
}
if (!$user->isEnabled()) {
// disabled users can not log in
return false;
}
//login
$this->setUser($user);
2016-05-06 14:31:40 +00:00
// TODO: $this->manager->emit('\OC\User', 'postTokenLogin', array($user));
return true;
}
/**
* Create a new session token for the given user credentials
*
2016-04-27 07:38:30 +00:00
* @param IRequest $request
* @param string $uid user UID
* @param string $loginName login name
* @param string $password
* @return boolean
*/
public function createSessionToken(IRequest $request, $uid, $loginName, $password) {
if (is_null($this->manager->get($uid))) {
// User does not exist
return false;
}
$name = isset($request->server['HTTP_USER_AGENT']) ? $request->server['HTTP_USER_AGENT'] : 'unknown browser';
2016-05-20 15:54:46 +00:00
try {
$sessionId = $this->session->getId();
$this->tokenProvider->generateToken($sessionId, $uid, $loginName, $password, $name);
2016-05-20 15:54:46 +00:00
} catch (SessionNotAvailableException $ex) {
2016-04-27 10:01:13 +00:00
}
2016-05-20 15:54:46 +00:00
return true;
}
/**
* @param string $token
* @return boolean
*/
2016-05-06 14:31:40 +00:00
private function validateToken($token) {
2016-05-17 15:20:54 +00:00
try {
$token = $this->tokenProvider->validateToken($token);
if (!is_null($token)) {
$result = $this->loginWithToken($token->getUID());
if ($result) {
// Login success
$this->updateToken($token);
return true;
}
}
2016-05-17 15:20:54 +00:00
} catch (InvalidTokenException $ex) {
}
return false;
}
2016-04-27 07:38:30 +00:00
/**
* @param IToken $token
*/
2016-05-17 15:20:54 +00:00
private function updateToken(IToken $token) {
2016-04-27 07:38:30 +00:00
// To save unnecessary DB queries, this is only done once a minute
$lastTokenUpdate = $this->session->get('last_token_update') ? : 0;
2016-05-02 17:58:19 +00:00
$now = $this->timeFacory->getTime();
if ($lastTokenUpdate < ($now - 60)) {
2016-05-17 15:20:54 +00:00
$this->tokenProvider->updateToken($token);
2016-05-02 17:58:19 +00:00
$this->session->set('last_token_update', $now);
2016-04-27 07:38:30 +00:00
}
}
/**
* Tries to login the user with auth token header
*
* @todo check remember me cookie
* @return boolean
*/
2016-04-29 07:40:33 +00:00
public function tryTokenLogin(IRequest $request) {
$authHeader = $request->getHeader('Authorization');
if (strpos($authHeader, 'token ') === false) {
// No auth header, let's try session id
try {
$sessionId = $this->session->getId();
2016-05-06 14:31:40 +00:00
return $this->validateToken($sessionId);
} catch (SessionNotAvailableException $ex) {
return false;
}
} else {
$token = substr($authHeader, 6);
2016-05-06 14:31:40 +00:00
return $this->validateToken($token);
}
}
/**
* perform login using the magic cookie (remember login)
*
* @param string $uid the username
* @param string $currentToken
* @return bool
*/
public function loginWithCookie($uid, $currentToken) {
$this->session->regenerateId();
$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::$server->getConfig()->getUserKeys($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::$server->getConfig()->deleteUserValue($uid, 'login_token', $currentToken);
$newToken = OC::$server->getSecureRandom()->generate(32);
OC::$server->getConfig()->setUserValue($uid, 'login_token', $newToken, time());
$this->setMagicInCookie($user->getUID(), $newToken);
//login
$this->setUser($user);
$this->manager->emit('\OC\User', 'postRememberedLogin', array($user));
return true;
}
2013-06-03 11:33:56 +00:00
/**
* logout the user from the session
*/
2013-05-28 21:46:57 +00:00
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) {
}
}
2013-05-28 21:46:57 +00:00
$this->setUser(null);
2014-01-09 09:27:47 +00:00
$this->setLoginName(null);
2013-05-28 21:46:57 +00:00
$this->unsetMagicInCookie();
$this->session->clear();
2013-05-28 21:46:57 +00:00
}
/**
* Set cookie value to use in next page load
*
* @param string $username username to be set
* @param string $token
*/
public function setMagicInCookie($username, $token) {
$secureCookie = OC::$server->getRequest()->getServerProtocol() === 'https';
$expires = time() + OC::$server->getConfig()->getSystemValue('remember_login_cookie_lifetime', 60 * 60 * 24 * 15);
2016-05-06 14:31:40 +00:00
setcookie('oc_username', $username, $expires, OC::$WEBROOT, '', $secureCookie, true);
setcookie('oc_token', $token, $expires, OC::$WEBROOT, '', $secureCookie, true);
setcookie('oc_remember_login', '1', $expires, OC::$WEBROOT, '', $secureCookie, true);
2013-05-28 21:46:57 +00:00
}
/**
2013-06-03 11:33:56 +00:00
* Remove cookie for "remember username"
2013-05-28 21:46:57 +00:00
*/
public function unsetMagicInCookie() {
//TODO: DI for cookies and IRequest
$secureCookie = OC::$server->getRequest()->getServerProtocol() === 'https';
2016-05-06 14:31:40 +00:00
unset($_COOKIE['oc_username']); //TODO: DI
unset($_COOKIE['oc_token']);
unset($_COOKIE['oc_remember_login']);
setcookie('oc_username', '', time() - 3600, OC::$WEBROOT, '', $secureCookie, true);
setcookie('oc_token', '', time() - 3600, OC::$WEBROOT, '', $secureCookie, true);
setcookie('oc_remember_login', '', time() - 3600, OC::$WEBROOT, '', $secureCookie, true);
// old cookies might be stored under /webroot/ instead of /webroot
// and Firefox doesn't like it!
setcookie('oc_username', '', time() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
setcookie('oc_token', '', time() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
setcookie('oc_remember_login', '', time() - 3600, OC::$WEBROOT . '/', '', $secureCookie, true);
2013-05-28 21:46:57 +00:00
}
2013-05-28 21:46:57 +00:00
}