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