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