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