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