]> git.mxchange.org Git - friendica.git/blob - src/Security/Authentication.php
An empty user id does not have children
[friendica.git] / src / Security / Authentication.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, 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\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\Security\TwoFactor\Repository\TrustedBrowser;
37 use Friendica\Util\DateTimeFormat;
38 use Friendica\Util\Network;
39 use Friendica\Util\Strings;
40 use LightOpenID;
41 use Friendica\Core\L10n;
42 use Friendica\Core\Logger;
43 use Psr\Log\LoggerInterface;
44
45 /**
46  * Handle Authentication, Session and Cookies
47  */
48 class Authentication
49 {
50         /** @var IConfig */
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 Session\ISession */
65         private $session;
66         /** @var IPConfig */
67         private $pConfig;
68
69         /**
70          * Authentication constructor.
71          *
72          * @param IConfig          $config
73          * @param App\Mode         $mode
74          * @param App\BaseURL      $baseUrl
75          * @param L10n             $l10n
76          * @param Database         $dba
77          * @param LoggerInterface  $logger
78          * @param User\Cookie      $cookie
79          * @param Session\ISession $session
80          * @param IPConfig         $pConfig
81          */
82         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)
83         {
84                 $this->config  = $config;
85                 $this->mode    = $mode;
86                 $this->baseUrl = $baseUrl;
87                 $this->l10n    = $l10n;
88                 $this->dba     = $dba;
89                 $this->logger  = $logger;
90                 $this->cookie  = $cookie;
91                 $this->session = $session;
92                 $this->pConfig = $pConfig;
93         }
94
95         /**
96          * Tries to auth the user from the cookie or session
97          *
98          * @param App   $a      The Friendica Application context
99          *
100          * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
101          * @throws Exception In case of general exceptions (like SQL Grammar)
102          */
103         public function withSession(App $a)
104         {
105                 // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
106                 if ($this->cookie->get('uid')) {
107                         $user = $this->dba->selectFirst(
108                                 'user',
109                                 [],
110                                 [
111                                         'uid'             => $this->cookie->get('uid'),
112                                         'blocked'         => false,
113                                         'account_expired' => false,
114                                         'account_removed' => false,
115                                         'verified'        => true,
116                                 ]
117                         );
118                         if ($this->dba->isResult($user)) {
119                                 if (!$this->cookie->comparePrivateDataHash($this->cookie->get('hash'),
120                                         $user['password'] ?? '',
121                                         $user['prvkey'] ?? '')
122                                 ) {
123                                         $this->logger->notice("Hash doesn't fit.", ['user' => $this->cookie->get('uid')]);
124                                         $this->session->clear();
125                                         $this->cookie->clear();
126                                         $this->baseUrl->redirect();
127                                 }
128
129                                 // Renew the cookie
130                                 $this->cookie->send();
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', $this->cookie->get('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                 try {
244                         $record = $this->dba->selectFirst(
245                                 'user',
246                                 [],
247                                 ['uid' => User::getIdFromPasswordAuthentication($username, $password)]
248                         );
249                 } catch (Exception $e) {
250                         $this->logger->warning('authenticate: failed login attempt', ['action' => 'login', 'username' => Strings::escapeTags($username), 'ip' => $_SERVER['REMOTE_ADDR']]);
251                         notice($this->l10n->t('Login failed. Please check your credentials.'));
252                         $this->baseUrl->redirect();
253                 }
254
255                 if (!$remember) {
256                         $this->cookie->clear();
257                 }
258
259                 // if we haven't failed up this point, log them in.
260                 $this->session->set('remember', $remember);
261                 $this->session->set('last_login_date', DateTimeFormat::utcNow());
262
263                 $openid_identity = $this->session->get('openid_identity');
264                 $openid_server   = $this->session->get('openid_server');
265
266                 if (!empty($openid_identity) || !empty($openid_server)) {
267                         $this->dba->update('user', ['openid' => $openid_identity, 'openidserver' => $openid_server], ['uid' => $record['uid']]);
268                 }
269
270                 $this->setForUser($a, $record, true, true);
271
272                 $return_path = $this->session->get('return_path', '');
273                 $this->session->remove('return_path');
274
275                 $this->baseUrl->redirect($return_path);
276         }
277
278         /**
279          * Sets the provided user's authenticated session
280          *
281          * @param App   $a           The Friendica application context
282          * @param array $user_record The current "user" record
283          * @param bool  $login_initial
284          * @param bool  $interactive
285          * @param bool  $login_refresh
286          *
287          * @throws HTTPException\InternalServerErrorException In case of Friendica specific exceptions
288          * @throws Exception In case of general Exceptions (like SQL Grammar exceptions)
289          */
290         public function setForUser(App $a, array $user_record, bool $login_initial = false, bool $interactive = false, bool $login_refresh = false)
291         {
292                 $this->session->setMultiple([
293                         'uid'           => $user_record['uid'],
294                         'theme'         => $user_record['theme'],
295                         'mobile-theme'  => $this->pConfig->get($user_record['uid'], 'system', 'mobile_theme'),
296                         'authenticated' => 1,
297                         'page_flags'    => $user_record['page-flags'],
298                         'my_url'        => $this->baseUrl->get() . '/profile/' . $user_record['nickname'],
299                         'my_address'    => $user_record['nickname'] . '@' . substr($this->baseUrl->get(), strpos($this->baseUrl->get(), '://') + 3),
300                         'addr'          => ($_SERVER['REMOTE_ADDR'] ?? '') ?: '0.0.0.0'
301                 ]);
302
303                 Session::setVisitorsContacts();
304
305                 $member_since = strtotime($user_record['register_date']);
306                 $this->session->set('new_member', time() < ($member_since + (60 * 60 * 24 * 14)));
307
308                 if (strlen($user_record['timezone'])) {
309                         date_default_timezone_set($user_record['timezone']);
310                         $a->timezone = $user_record['timezone'];
311                 }
312
313                 $masterUid = $user_record['uid'];
314
315                 if ($this->session->get('submanage')) {
316                         $user = $this->dba->selectFirst('user', ['uid'], ['uid' => $this->session->get('submanage')]);
317                         if ($this->dba->isResult($user)) {
318                                 $masterUid = $user['uid'];
319                         }
320                 }
321
322                 $a->identities = User::identities($masterUid);
323
324                 if ($login_initial) {
325                         $this->logger->info('auth_identities: ' . print_r($a->identities, true));
326                 }
327
328                 if ($login_refresh) {
329                         $this->logger->info('auth_identities refresh: ' . print_r($a->identities, true));
330                 }
331
332                 $contact = $this->dba->selectFirst('contact', [], ['uid' => $user_record['uid'], 'self' => true]);
333                 if ($this->dba->isResult($contact)) {
334                         $a->contact = $contact;
335                         $a->cid     = $contact['id'];
336                         $this->session->set('cid', $a->cid);
337                 }
338
339                 header('X-Account-Management-Status: active; name="' . $user_record['username'] . '"; id="' . $user_record['nickname'] . '"');
340
341                 if ($login_initial || $login_refresh) {
342                         $this->dba->update('user', ['login_date' => DateTimeFormat::utcNow()], ['uid' => $user_record['uid']]);
343
344                         // Set the login date for all identities of the user
345                         if (!empty($masterUid)) {
346                                 $this->dba->update('user', ['login_date' => DateTimeFormat::utcNow()],
347                                         ['parent-uid' => $masterUid, 'account_removed' => false]);
348                         }
349                 }
350
351                 if ($login_initial) {
352                         /*
353                          * If the user specified to remember the authentication, then set a cookie
354                          * that expires after one week (the default is when the browser is closed).
355                          * The cookie will be renewed automatically.
356                          * The week ensures that sessions will expire after some inactivity.
357                          */
358                         if ($this->session->get('remember')) {
359                                 $this->logger->info('Injecting cookie for remembered user ' . $user_record['nickname']);
360                                 $this->cookie->setMultiple([
361                                         'uid'  => $user_record['uid'],
362                                         'hash' => $this->cookie->hashPrivateData($user_record['password'], $user_record['prvkey']),
363                                 ]);
364                                 $this->session->remove('remember');
365                         }
366                 }
367
368                 $this->redirectForTwoFactorAuthentication($user_record['uid'], $a);
369
370                 if ($interactive) {
371                         if ($user_record['login_date'] <= DBA::NULL_DATETIME) {
372                                 info($this->l10n->t('Welcome %s', $user_record['username']));
373                                 info($this->l10n->t('Please upload a profile photo.'));
374                                 $this->baseUrl->redirect('settings/profile/photo/new');
375                         }
376                 }
377
378                 $a->user = $user_record;
379
380                 if ($login_initial) {
381                         Hook::callAll('logged_in', $a->user);
382
383                         if (DI::module()->getName() !== 'home' && $this->session->exists('return_path')) {
384                                 $this->baseUrl->redirect($this->session->get('return_path'));
385                         }
386                 }
387         }
388
389         /**
390          * Decides whether to redirect the user to two-factor authentication.
391          * All return calls in this method skip two-factor authentication
392          *
393          * @param int $uid The User Identified
394          * @param App $a   The Friendica Application context
395          *
396          * @throws HTTPException\ForbiddenException In case the two factor authentication is forbidden (e.g. for AJAX calls)
397          * @throws HTTPException\InternalServerErrorException
398          */
399         private function redirectForTwoFactorAuthentication(int $uid, App $a)
400         {
401                 // Check user setting, if 2FA disabled return
402                 if (!$this->pConfig->get($uid, '2fa', 'verified')) {
403                         return;
404                 }
405
406                 // Check current path, if public or 2fa module return
407                 if ($a->argc > 0 && in_array($a->argv[0], ['2fa', 'view', 'help', 'api', 'proxy', 'logout'])) {
408                         return;
409                 }
410
411                 // Case 1a: 2FA session already present: return
412                 if ($this->session->get('2fa')) {
413                         return;
414                 }
415
416                 // Case 1b: Check for trusted browser
417                 if ($this->cookie->get('trusted')) {
418                         // Retrieve a trusted_browser model based on cookie hash
419                         $trustedBrowserRepository = new TrustedBrowser($this->dba, $this->logger);
420                         try {
421                                 $trustedBrowser = $trustedBrowserRepository->selectOneByHash($this->cookie->get('trusted'));
422                                 // Verify record ownership
423                                 if ($trustedBrowser->uid === $uid) {
424                                         // Update last_used date
425                                         $trustedBrowser->recordUse();
426
427                                         // Save it to the database
428                                         $trustedBrowserRepository->save($trustedBrowser);
429
430                                         // Set 2fa session key and return
431                                         $this->session->set('2fa', true);
432
433                                         return;
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 }