]> git.mxchange.org Git - friendica.git/blobdiff - src/Security/Authentication.php
Merge pull request #10969 from MrPetovan/task/remove-private-contacts
[friendica.git] / src / Security / Authentication.php
index 5c6624a33f1f3972f28b3c3597815e95841c9d16..0b2fc9f9cf3d15850b7c88cd053b6608fe98cf3b 100644 (file)
@@ -1,6 +1,6 @@
 <?php
 /**
- * @copyright Copyright (C) 2020, Friendica
+ * @copyright Copyright (C) 2010-2021, the Friendica project
  *
  * @license GNU AGPL version 3 or any later version
  *
@@ -23,19 +23,20 @@ namespace Friendica\Security;
 
 use Exception;
 use Friendica\App;
-use Friendica\Core\Config\IConfig;
-use Friendica\Core\PConfig\IPConfig;
+use Friendica\Core\Config\Capability\IManageConfigValues;
+use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
 use Friendica\Core\Hook;
 use Friendica\Core\Session;
+use Friendica\Core\Session\Capability\IHandleSessions;
 use Friendica\Core\System;
 use Friendica\Database\Database;
 use Friendica\Database\DBA;
 use Friendica\DI;
 use Friendica\Model\User;
 use Friendica\Network\HTTPException;
+use Friendica\Security\TwoFactor\Repository\TrustedBrowser;
 use Friendica\Util\DateTimeFormat;
 use Friendica\Util\Network;
-use Friendica\Util\Strings;
 use LightOpenID;
 use Friendica\Core\L10n;
 use Psr\Log\LoggerInterface;
@@ -45,7 +46,7 @@ use Psr\Log\LoggerInterface;
  */
 class Authentication
 {
-       /** @var IConfig */
+       /** @var IManageConfigValues */
        private $config;
        /** @var App\Mode */
        private $mode;
@@ -59,25 +60,37 @@ class Authentication
        private $logger;
        /** @var User\Cookie */
        private $cookie;
-       /** @var Session\ISession */
+       /** @var IHandleSessions */
        private $session;
-       /** @var IPConfig */
+       /** @var IManagePersonalConfigValues */
        private $pConfig;
 
+       /**
+        * Sets the X-Account-Management-Status header
+        *
+        * mainly extracted to make it overridable for tests
+        *
+        * @param array $user_record
+        */
+       protected function setXAccMgmtStatusHeader(array $user_record)
+       {
+               header('X-Account-Management-Status: active; name="' . $user_record['username'] . '"; id="' . $user_record['nickname'] . '"');
+       }
+
        /**
         * Authentication constructor.
         *
-        * @param IConfig          $config
-        * @param App\Mode         $mode
-        * @param App\BaseURL      $baseUrl
-        * @param L10n             $l10n
-        * @param Database         $dba
-        * @param LoggerInterface  $logger
-        * @param User\Cookie      $cookie
-        * @param Session\ISession $session
-        * @param IPConfig         $pConfig
+        * @param IManageConfigValues                                $config
+        * @param App\Mode                                           $mode
+        * @param App\BaseURL                                        $baseUrl
+        * @param L10n                                               $l10n
+        * @param Database                                           $dba
+        * @param LoggerInterface                                    $logger
+        * @param User\Cookie                                        $cookie
+        * @param IHandleSessions $session
+        * @param IManagePersonalConfigValues                        $pConfig
         */
-       public function __construct(IConfig $config, App\Mode $mode, App\BaseURL $baseUrl, L10n $l10n, Database $dba, LoggerInterface $logger, User\Cookie $cookie, Session\ISession $session, IPConfig $pConfig)
+       public function __construct(IManageConfigValues $config, App\Mode $mode, App\BaseURL $baseUrl, L10n $l10n, Database $dba, LoggerInterface $logger, User\Cookie $cookie, IHandleSessions $session, IManagePersonalConfigValues $pConfig)
        {
                $this->config  = $config;
                $this->mode    = $mode;
@@ -100,16 +113,13 @@ class Authentication
         */
        public function withSession(App $a)
        {
-               $data = $this->cookie->getData();
-
                // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
-               if (isset($data->uid)) {
-
+               if ($this->cookie->get('uid')) {
                        $user = $this->dba->selectFirst(
                                'user',
                                [],
                                [
-                                       'uid'             => $data->uid,
+                                       'uid'             => $this->cookie->get('uid'),
                                        'blocked'         => false,
                                        'account_expired' => false,
                                        'account_removed' => false,
@@ -117,24 +127,25 @@ class Authentication
                                ]
                        );
                        if ($this->dba->isResult($user)) {
-                               if (!$this->cookie->check($data->hash,
+                               if (!$this->cookie->comparePrivateDataHash($this->cookie->get('hash'),
                                        $user['password'] ?? '',
-                                       $user['prvkey'] ?? '')) {
-                                       $this->logger->notice("Hash doesn't fit.", ['user' => $data->uid]);
+                                       $user['prvkey'] ?? '')
+                               ) {
+                                       $this->logger->notice("Hash doesn't fit.", ['user' => $this->cookie->get('uid')]);
                                        $this->session->clear();
                                        $this->cookie->clear();
                                        $this->baseUrl->redirect();
                                }
 
                                // Renew the cookie
-                               $this->cookie->set($user['uid'], $user['password'], $user['prvkey']);
+                               $this->cookie->send();
 
                                // Do the authentification if not done by now
                                if (!$this->session->get('authenticated')) {
                                        $this->setForUser($a, $user);
 
                                        if ($this->config->get('system', 'paranoia')) {
-                                               $this->session->set('addr', $data->ip);
+                                               $this->session->set('addr', $this->cookie->get('ip'));
                                        }
                                }
                        }
@@ -142,9 +153,9 @@ class Authentication
 
                if ($this->session->get('authenticated')) {
                        if ($this->session->get('visitor_id') && !$this->session->get('uid')) {
-                               $contact = $this->dba->selectFirst('contact', [], ['id' => $this->session->get('visitor_id')]);
+                               $contact = $this->dba->selectFirst('contact', ['id'], ['id' => $this->session->get('visitor_id')]);
                                if ($this->dba->isResult($contact)) {
-                                       $a->contact = $contact;
+                                       $a->setContactId($contact['id']);
                                }
                        }
 
@@ -240,36 +251,14 @@ class Authentication
        {
                $record = null;
 
-               $addon_auth = [
-                       'username'      => $username,
-                       'password'      => $password,
-                       'authenticated' => 0,
-                       'user_record'   => null
-               ];
-
-               /*
-                * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
-                * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
-                * and later addons should not interfere with an earlier one that succeeded.
-                */
-               Hook::callAll('authenticate', $addon_auth);
-
                try {
-                       if ($addon_auth['authenticated']) {
-                               $record = $addon_auth['user_record'];
-
-                               if (empty($record)) {
-                                       throw new Exception($this->l10n->t('Login failed.'));
-                               }
-                       } else {
-                               $record = $this->dba->selectFirst(
-                                       'user',
-                                       [],
-                                       ['uid' => User::getIdFromPasswordAuthentication($username, $password)]
-                               );
-                       }
+                       $record = $this->dba->selectFirst(
+                               'user',
+                               [],
+                               ['uid' => User::getIdFromPasswordAuthentication($username, $password)]
+                       );
                } catch (Exception $e) {
-                       $this->logger->warning('authenticate: failed login attempt', ['action' => 'login', 'username' => Strings::escapeTags($username), 'ip' => $_SERVER['REMOTE_ADDR']]);
+                       $this->logger->warning('authenticate: failed login attempt', ['action' => 'login', 'username' => $username, 'ip' => $_SERVER['REMOTE_ADDR']]);
                        notice($this->l10n->t('Login failed. Please check your credentials.'));
                        $this->baseUrl->redirect();
                }
@@ -328,44 +317,23 @@ class Authentication
                $this->session->set('new_member', time() < ($member_since + (60 * 60 * 24 * 14)));
 
                if (strlen($user_record['timezone'])) {
-                       date_default_timezone_set($user_record['timezone']);
-                       $a->timezone = $user_record['timezone'];
-               }
-
-               $masterUid = $user_record['uid'];
-
-               if ($this->session->get('submanage')) {
-                       $user = $this->dba->selectFirst('user', ['uid'], ['uid' => $this->session->get('submanage')]);
-                       if ($this->dba->isResult($user)) {
-                               $masterUid = $user['uid'];
-                       }
+                       $a->setTimeZone($user_record['timezone']);
                }
 
-               $a->identities = User::identities($masterUid);
-
-               if ($login_initial) {
-                       $this->logger->info('auth_identities: ' . print_r($a->identities, true));
-               }
-
-               if ($login_refresh) {
-                       $this->logger->info('auth_identities refresh: ' . print_r($a->identities, true));
-               }
-
-               $contact = $this->dba->selectFirst('contact', [], ['uid' => $user_record['uid'], 'self' => true]);
+               $contact = $this->dba->selectFirst('contact', ['id'], ['uid' => $user_record['uid'], 'self' => true]);
                if ($this->dba->isResult($contact)) {
-                       $a->contact = $contact;
-                       $a->cid     = $contact['id'];
-                       $this->session->set('cid', $a->cid);
+                       $a->setContactId($contact['id']);
+                       $this->session->set('cid', $contact['id']);
                }
 
-               header('X-Account-Management-Status: active; name="' . $user_record['username'] . '"; id="' . $user_record['nickname'] . '"');
+               $this->setXAccMgmtStatusHeader($user_record);
 
                if ($login_initial || $login_refresh) {
                        $this->dba->update('user', ['login_date' => DateTimeFormat::utcNow()], ['uid' => $user_record['uid']]);
 
                        // Set the login date for all identities of the user
                        $this->dba->update('user', ['login_date' => DateTimeFormat::utcNow()],
-                               ['parent-uid' => $masterUid, 'account_removed' => false]);
+                               ['parent-uid' => $user_record['uid'], 'account_removed' => false]);
                }
 
                if ($login_initial) {
@@ -377,12 +345,15 @@ class Authentication
                         */
                        if ($this->session->get('remember')) {
                                $this->logger->info('Injecting cookie for remembered user ' . $user_record['nickname']);
-                               $this->cookie->set($user_record['uid'], $user_record['password'], $user_record['prvkey']);
+                               $this->cookie->setMultiple([
+                                       'uid'  => $user_record['uid'],
+                                       'hash' => $this->cookie->hashPrivateData($user_record['password'], $user_record['prvkey']),
+                               ]);
                                $this->session->remove('remember');
                        }
                }
 
-               $this->twoFactorCheck($user_record['uid'], $a);
+               $this->redirectForTwoFactorAuthentication($user_record['uid']);
 
                if ($interactive) {
                        if ($user_record['login_date'] <= DBA::NULL_DATETIME) {
@@ -392,10 +363,11 @@ class Authentication
                        }
                }
 
-               $a->user = $user_record;
+               $a->setLoggedInUserId($user_record['uid']);
+               $a->setLoggedInUserNickname($user_record['nickname']);
 
                if ($login_initial) {
-                       Hook::callAll('logged_in', $a->user);
+                       Hook::callAll('logged_in', $user_record);
 
                        if (DI::module()->getName() !== 'home' && $this->session->exists('return_path')) {
                                $this->baseUrl->redirect($this->session->get('return_path'));
@@ -404,28 +376,58 @@ class Authentication
        }
 
        /**
+        * Decides whether to redirect the user to two-factor authentication.
+        * All return calls in this method skip two-factor authentication
+        *
         * @param int $uid The User Identified
-        * @param App $a   The Friendica Application context
         *
         * @throws HTTPException\ForbiddenException In case the two factor authentication is forbidden (e.g. for AJAX calls)
+        * @throws HTTPException\InternalServerErrorException
         */
-       private function twoFactorCheck(int $uid, App $a)
+       private function redirectForTwoFactorAuthentication(int $uid)
        {
                // Check user setting, if 2FA disabled return
                if (!$this->pConfig->get($uid, '2fa', 'verified')) {
                        return;
                }
 
-               // Check current path, if 2fa authentication module return
-               if ($a->argc > 0 && in_array($a->argv[0], ['2fa', 'view', 'help', 'api', 'proxy', 'logout'])) {
+               // Check current path, if public or 2fa module return
+               if (DI::args()->getArgc() > 0 && in_array(DI::args()->getArgv()[0], ['2fa', 'view', 'help', 'api', 'proxy', 'logout'])) {
                        return;
                }
 
-               // Case 1: 2FA session present and valid: return
+               // Case 1a: 2FA session already present: return
                if ($this->session->get('2fa')) {
                        return;
                }
 
+               // Case 1b: Check for trusted browser
+               if ($this->cookie->get('trusted')) {
+                       // Retrieve a trusted_browser model based on cookie hash
+                       $trustedBrowserRepository = new TrustedBrowser($this->dba, $this->logger);
+                       try {
+                               $trustedBrowser = $trustedBrowserRepository->selectOneByHash($this->cookie->get('trusted'));
+                               // Verify record ownership
+                               if ($trustedBrowser->uid === $uid) {
+                                       // Update last_used date
+                                       $trustedBrowser->recordUse();
+
+                                       // Save it to the database
+                                       $trustedBrowserRepository->save($trustedBrowser);
+
+                                       // Set 2fa session key and return
+                                       $this->session->set('2fa', true);
+
+                                       return;
+                               } else {
+                                       // Invalid trusted cookie value, removing it
+                                       $this->cookie->unset('trusted');
+                               }
+                       } catch (\Throwable $e) {
+                               // Local trusted browser record was probably removed by the user, we carry on with 2FA
+                       }
+               }
+
                // Case 2: No valid 2FA session: redirect to code verification page
                if ($this->mode->isAjax()) {
                        throw new HTTPException\ForbiddenException();