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