]> git.mxchange.org Git - friendica.git/blob - src/Security/Authentication.php
d8d8ba4b424330eea6c00a549d96940a19057d43
[friendica.git] / src / Security / Authentication.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Security;
23
24 use Exception;
25 use Friendica\App;
26 use Friendica\Core\Config\Capability\IManageConfigValues;
27 use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
28 use Friendica\Core\Hook;
29 use Friendica\Core\Session;
30 use Friendica\Core\Session\Capability\IHandleSessions;
31 use Friendica\Core\System;
32 use Friendica\Database\Database;
33 use Friendica\Database\DBA;
34 use Friendica\DI;
35 use Friendica\Model\User;
36 use Friendica\Network\HTTPException;
37 use Friendica\Security\TwoFactor\Repository\TrustedBrowser;
38 use Friendica\Util\DateTimeFormat;
39 use Friendica\Util\Network;
40 use Friendica\Util\Strings;
41 use LightOpenID;
42 use Friendica\Core\L10n;
43 use Psr\Log\LoggerInterface;
44
45 /**
46  * Handle Authentication, Session and Cookies
47  */
48 class Authentication
49 {
50         /** @var IManageConfigValues */
51         private $config;
52         /** @var App\Mode */
53         private $mode;
54         /** @var App\BaseURL */
55         private $baseUrl;
56         /** @var L10n */
57         private $l10n;
58         /** @var Database */
59         private $dba;
60         /** @var LoggerInterface */
61         private $logger;
62         /** @var User\Cookie */
63         private $cookie;
64         /** @var IHandleSessions */
65         private $session;
66         /** @var IManagePersonalConfigValues */
67         private $pConfig;
68
69         /**
70          * Authentication constructor.
71          *
72          * @param IManageConfigValues                                $config
73          * @param App\Mode                                           $mode
74          * @param App\BaseURL                                        $baseUrl
75          * @param L10n                                               $l10n
76          * @param Database                                           $dba
77          * @param LoggerInterface                                    $logger
78          * @param User\Cookie                                        $cookie
79          * @param IHandleSessions $session
80          * @param IManagePersonalConfigValues                        $pConfig
81          */
82         public function __construct(IManageConfigValues $config, App\Mode $mode, App\BaseURL $baseUrl, L10n $l10n, Database $dba, LoggerInterface $logger, User\Cookie $cookie, IHandleSessions $session, IManagePersonalConfigValues $pConfig)
83         {
84                 $this->config  = $config;
85                 $this->mode    = $mode;
86                 $this->baseUrl = $baseUrl;
87                 $this->l10n    = $l10n;
88                 $this->dba     = $dba;
89                 $this->logger  = $logger;
90                 $this->cookie  = $cookie;
91                 $this->session = $session;
92                 $this->pConfig = $pConfig;
93         }
94
95         /**
96          * Tries to auth the user from the cookie or session
97          *
98          * @param App   $a      The Friendica Application context
99          *
100          * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
101          * @throws Exception In case of general exceptions (like SQL Grammar)
102          */
103         public function withSession(App $a)
104         {
105                 // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
106                 if ($this->cookie->get('uid')) {
107                         $user = $this->dba->selectFirst(
108                                 'user',
109                                 [],
110                                 [
111                                         'uid'             => $this->cookie->get('uid'),
112                                         'blocked'         => false,
113                                         'account_expired' => false,
114                                         'account_removed' => false,
115                                         'verified'        => true,
116                                 ]
117                         );
118                         if ($this->dba->isResult($user)) {
119                                 if (!$this->cookie->comparePrivateDataHash($this->cookie->get('hash'),
120                                         $user['password'] ?? '',
121                                         $user['prvkey'] ?? '')
122                                 ) {
123                                         $this->logger->notice("Hash doesn't fit.", ['user' => $this->cookie->get('uid')]);
124                                         $this->session->clear();
125                                         $this->cookie->clear();
126                                         $this->baseUrl->redirect();
127                                 }
128
129                                 // Renew the cookie
130                                 $this->cookie->send();
131
132                                 // Do the authentification if not done by now
133                                 if (!$this->session->get('authenticated')) {
134                                         $this->setForUser($a, $user);
135
136                                         if ($this->config->get('system', 'paranoia')) {
137                                                 $this->session->set('addr', $this->cookie->get('ip'));
138                                         }
139                                 }
140                         }
141                 }
142
143                 if ($this->session->get('authenticated')) {
144                         if ($this->session->get('visitor_id') && !$this->session->get('uid')) {
145                                 $contact = $this->dba->selectFirst('contact', ['id'], ['id' => $this->session->get('visitor_id')]);
146                                 if ($this->dba->isResult($contact)) {
147                                         $a->setContactId($contact['id']);
148                                 }
149                         }
150
151                         if ($this->session->get('uid')) {
152                                 // already logged in user returning
153                                 $check = $this->config->get('system', 'paranoia');
154                                 // extra paranoia - if the IP changed, log them out
155                                 if ($check && ($this->session->get('addr') != $_SERVER['REMOTE_ADDR'])) {
156                                         $this->logger->notice('Session address changed. Paranoid setting in effect, blocking session. ', [
157                                                         'addr'        => $this->session->get('addr'),
158                                                         'remote_addr' => $_SERVER['REMOTE_ADDR']]
159                                         );
160                                         $this->session->clear();
161                                         $this->baseUrl->redirect();
162                                 }
163
164                                 $user = $this->dba->selectFirst(
165                                         'user',
166                                         [],
167                                         [
168                                                 'uid'             => $this->session->get('uid'),
169                                                 'blocked'         => false,
170                                                 'account_expired' => false,
171                                                 'account_removed' => false,
172                                                 'verified'        => true,
173                                         ]
174                                 );
175                                 if (!$this->dba->isResult($user)) {
176                                         $this->session->clear();
177                                         $this->baseUrl->redirect();
178                                 }
179
180                                 // Make sure to refresh the last login time for the user if the user
181                                 // stays logged in for a long time, e.g. with "Remember Me"
182                                 $login_refresh = false;
183                                 if (!$this->session->get('last_login_date')) {
184                                         $this->session->set('last_login_date', DateTimeFormat::utcNow());
185                                 }
186                                 if (strcmp(DateTimeFormat::utc('now - 12 hours'), $this->session->get('last_login_date')) > 0) {
187                                         $this->session->set('last_login_date', DateTimeFormat::utcNow());
188                                         $login_refresh = true;
189                                 }
190
191                                 $this->setForUser($a, $user, false, false, $login_refresh);
192                         }
193                 }
194         }
195
196         /**
197          * Attempts to authenticate using OpenId
198          *
199          * @param string $openid_url OpenID URL string
200          * @param bool   $remember   Whether to set the session remember flag
201          *
202          * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
203          */
204         public function withOpenId(string $openid_url, bool $remember)
205         {
206                 $noid = $this->config->get('system', 'no_openid');
207
208                 // if it's an email address or doesn't resolve to a URL, fail.
209                 if ($noid || strpos($openid_url, '@') || !Network::isUrlValid($openid_url)) {
210                         notice($this->l10n->t('Login failed.'));
211                         $this->baseUrl->redirect();
212                 }
213
214                 // Otherwise it's probably an openid.
215                 try {
216                         $openid           = new LightOpenID($this->baseUrl->getHostname());
217                         $openid->identity = $openid_url;
218                         $this->session->set('openid', $openid_url);
219                         $this->session->set('remember', $remember);
220                         $openid->returnUrl = $this->baseUrl->get(true) . '/openid';
221                         $openid->optional  = ['namePerson/friendly', 'contact/email', 'namePerson', 'namePerson/first', 'media/image/aspect11', 'media/image/default'];
222                         System::externalRedirect($openid->authUrl());
223                 } catch (Exception $e) {
224                         notice($this->l10n->t('We encountered a problem while logging in with the OpenID you provided. Please check the correct spelling of the ID.') . '<br /><br >' . $this->l10n->t('The error message was:') . ' ' . $e->getMessage());
225                 }
226         }
227
228         /**
229          * Attempts to authenticate using login/password
230          *
231          * @param App    $a        The Friendica Application context
232          * @param string $username User name
233          * @param string $password Clear password
234          * @param bool   $remember Whether to set the session remember flag
235          *
236          * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
237          * @throws Exception A general Exception (like SQL Grammar exceptions)
238          */
239         public function withPassword(App $a, string $username, string $password, bool $remember)
240         {
241                 $record = null;
242
243                 try {
244                         $record = $this->dba->selectFirst(
245                                 'user',
246                                 [],
247                                 ['uid' => User::getIdFromPasswordAuthentication($username, $password)]
248                         );
249                 } catch (Exception $e) {
250                         $this->logger->warning('authenticate: failed login attempt', ['action' => 'login', 'username' => Strings::escapeTags($username), 'ip' => $_SERVER['REMOTE_ADDR']]);
251                         notice($this->l10n->t('Login failed. Please check your credentials.'));
252                         $this->baseUrl->redirect();
253                 }
254
255                 if (!$remember) {
256                         $this->cookie->clear();
257                 }
258
259                 // if we haven't failed up this point, log them in.
260                 $this->session->set('remember', $remember);
261                 $this->session->set('last_login_date', DateTimeFormat::utcNow());
262
263                 $openid_identity = $this->session->get('openid_identity');
264                 $openid_server   = $this->session->get('openid_server');
265
266                 if (!empty($openid_identity) || !empty($openid_server)) {
267                         $this->dba->update('user', ['openid' => $openid_identity, 'openidserver' => $openid_server], ['uid' => $record['uid']]);
268                 }
269
270                 $this->setForUser($a, $record, true, true);
271
272                 $return_path = $this->session->get('return_path', '');
273                 $this->session->remove('return_path');
274
275                 $this->baseUrl->redirect($return_path);
276         }
277
278         /**
279          * Sets the provided user's authenticated session
280          *
281          * @param App   $a           The Friendica application context
282          * @param array $user_record The current "user" record
283          * @param bool  $login_initial
284          * @param bool  $interactive
285          * @param bool  $login_refresh
286          *
287          * @throws HTTPException\InternalServerErrorException In case of Friendica specific exceptions
288          * @throws Exception In case of general Exceptions (like SQL Grammar exceptions)
289          */
290         public function setForUser(App $a, array $user_record, bool $login_initial = false, bool $interactive = false, bool $login_refresh = false)
291         {
292                 $this->session->setMultiple([
293                         'uid'           => $user_record['uid'],
294                         'theme'         => $user_record['theme'],
295                         'mobile-theme'  => $this->pConfig->get($user_record['uid'], 'system', 'mobile_theme'),
296                         'authenticated' => 1,
297                         'page_flags'    => $user_record['page-flags'],
298                         'my_url'        => $this->baseUrl->get() . '/profile/' . $user_record['nickname'],
299                         'my_address'    => $user_record['nickname'] . '@' . substr($this->baseUrl->get(), strpos($this->baseUrl->get(), '://') + 3),
300                         'addr'          => ($_SERVER['REMOTE_ADDR'] ?? '') ?: '0.0.0.0'
301                 ]);
302
303                 Session::setVisitorsContacts();
304
305                 $member_since = strtotime($user_record['register_date']);
306                 $this->session->set('new_member', time() < ($member_since + (60 * 60 * 24 * 14)));
307
308                 if (strlen($user_record['timezone'])) {
309                         $a->setTimeZone($user_record['timezone']);
310                 }
311
312                 $contact = $this->dba->selectFirst('contact', ['id'], ['uid' => $user_record['uid'], 'self' => true]);
313                 if ($this->dba->isResult($contact)) {
314                         $a->setContactId($contact['id']);
315                         $this->session->set('cid', $contact['id']);
316                 }
317
318                 header('X-Account-Management-Status: active; name="' . $user_record['username'] . '"; id="' . $user_record['nickname'] . '"');
319
320                 if ($login_initial || $login_refresh) {
321                         $this->dba->update('user', ['login_date' => DateTimeFormat::utcNow()], ['uid' => $user_record['uid']]);
322
323                         // Set the login date for all identities of the user
324                         $this->dba->update('user', ['login_date' => DateTimeFormat::utcNow()],
325                                 ['parent-uid' => $user_record['uid'], 'account_removed' => false]);
326                 }
327
328                 if ($login_initial) {
329                         /*
330                          * If the user specified to remember the authentication, then set a cookie
331                          * that expires after one week (the default is when the browser is closed).
332                          * The cookie will be renewed automatically.
333                          * The week ensures that sessions will expire after some inactivity.
334                          */
335                         if ($this->session->get('remember')) {
336                                 $this->logger->info('Injecting cookie for remembered user ' . $user_record['nickname']);
337                                 $this->cookie->setMultiple([
338                                         'uid'  => $user_record['uid'],
339                                         'hash' => $this->cookie->hashPrivateData($user_record['password'], $user_record['prvkey']),
340                                 ]);
341                                 $this->session->remove('remember');
342                         }
343                 }
344
345                 $this->redirectForTwoFactorAuthentication($user_record['uid']);
346
347                 if ($interactive) {
348                         if ($user_record['login_date'] <= DBA::NULL_DATETIME) {
349                                 info($this->l10n->t('Welcome %s', $user_record['username']));
350                                 info($this->l10n->t('Please upload a profile photo.'));
351                                 $this->baseUrl->redirect('settings/profile/photo/new');
352                         }
353                 }
354
355                 $a->setLoggedInUserId($user_record['uid']);
356                 $a->setLoggedInUserNickname($user_record['nickname']);
357
358                 if ($login_initial) {
359                         Hook::callAll('logged_in', $user_record);
360
361                         if (DI::module()->getName() !== 'home' && $this->session->exists('return_path')) {
362                                 $this->baseUrl->redirect($this->session->get('return_path'));
363                         }
364                 }
365         }
366
367         /**
368          * Decides whether to redirect the user to two-factor authentication.
369          * All return calls in this method skip two-factor authentication
370          *
371          * @param int $uid The User Identified
372          *
373          * @throws HTTPException\ForbiddenException In case the two factor authentication is forbidden (e.g. for AJAX calls)
374          * @throws HTTPException\InternalServerErrorException
375          */
376         private function redirectForTwoFactorAuthentication(int $uid)
377         {
378                 // Check user setting, if 2FA disabled return
379                 if (!$this->pConfig->get($uid, '2fa', 'verified')) {
380                         return;
381                 }
382
383                 // Check current path, if public or 2fa module return
384                 if (DI::args()->getArgc() > 0 && in_array(DI::args()->getArgv()[0], ['2fa', 'view', 'help', 'api', 'proxy', 'logout'])) {
385                         return;
386                 }
387
388                 // Case 1a: 2FA session already present: return
389                 if ($this->session->get('2fa')) {
390                         return;
391                 }
392
393                 // Case 1b: Check for trusted browser
394                 if ($this->cookie->get('trusted')) {
395                         // Retrieve a trusted_browser model based on cookie hash
396                         $trustedBrowserRepository = new TrustedBrowser($this->dba, $this->logger);
397                         try {
398                                 $trustedBrowser = $trustedBrowserRepository->selectOneByHash($this->cookie->get('trusted'));
399                                 // Verify record ownership
400                                 if ($trustedBrowser->uid === $uid) {
401                                         // Update last_used date
402                                         $trustedBrowser->recordUse();
403
404                                         // Save it to the database
405                                         $trustedBrowserRepository->save($trustedBrowser);
406
407                                         // Set 2fa session key and return
408                                         $this->session->set('2fa', true);
409
410                                         return;
411                                 } else {
412                                         // Invalid trusted cookie value, removing it
413                                         $this->cookie->unset('trusted');
414                                 }
415                         } catch (\Throwable $e) {
416                                 // Local trusted browser record was probably removed by the user, we carry on with 2FA
417                         }
418                 }
419
420                 // Case 2: No valid 2FA session: redirect to code verification page
421                 if ($this->mode->isAjax()) {
422                         throw new HTTPException\ForbiddenException();
423                 } else {
424                         $this->baseUrl->redirect('2fa');
425                 }
426         }
427 }