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