3 * @copyright Copyright (C) 2010-2021, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Security;
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;
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;
41 use Friendica\Core\L10n;
42 use Psr\Log\LoggerInterface;
45 * Handle Authentication, Session and Cookies
53 /** @var App\BaseURL */
59 /** @var LoggerInterface */
61 /** @var User\Cookie */
63 /** @var Session\ISession */
69 * Authentication constructor.
71 * @param IConfig $config
72 * @param App\Mode $mode
73 * @param App\BaseURL $baseUrl
75 * @param Database $dba
76 * @param LoggerInterface $logger
77 * @param User\Cookie $cookie
78 * @param Session\ISession $session
79 * @param IPConfig $pConfig
81 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 $this->config = $config;
85 $this->baseUrl = $baseUrl;
88 $this->logger = $logger;
89 $this->cookie = $cookie;
90 $this->session = $session;
91 $this->pConfig = $pConfig;
95 * Tries to auth the user from the cookie or session
97 * @param App $a The Friendica Application context
99 * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
100 * @throws Exception In case of general exceptions (like SQL Grammar)
102 public function withSession(App $a)
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(
110 'uid' => $this->cookie->get('uid'),
112 'account_expired' => false,
113 'account_removed' => false,
117 if ($this->dba->isResult($user)) {
118 if (!$this->cookie->comparePrivateDataHash($this->cookie->get('hash'),
119 $user['password'] ?? '',
120 $user['prvkey'] ?? '')
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();
129 $this->cookie->send();
131 // Do the authentification if not done by now
132 if (!$this->session->get('authenticated')) {
133 $this->setForUser($a, $user);
135 if ($this->config->get('system', 'paranoia')) {
136 $this->session->set('addr', $this->cookie->get('ip'));
142 if ($this->session->get('authenticated')) {
143 if ($this->session->get('visitor_id') && !$this->session->get('uid')) {
144 $contact = $this->dba->selectFirst('contact', [], ['id' => $this->session->get('visitor_id')]);
145 if ($this->dba->isResult($contact)) {
146 $a->contact = $contact;
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']]
159 $this->session->clear();
160 $this->baseUrl->redirect();
163 $user = $this->dba->selectFirst(
167 'uid' => $this->session->get('uid'),
169 'account_expired' => false,
170 'account_removed' => false,
174 if (!$this->dba->isResult($user)) {
175 $this->session->clear();
176 $this->baseUrl->redirect();
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());
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;
190 $this->setForUser($a, $user, false, false, $login_refresh);
196 * Attempts to authenticate using OpenId
198 * @param string $openid_url OpenID URL string
199 * @param bool $remember Whether to set the session remember flag
201 * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
203 public function withOpenId(string $openid_url, bool $remember)
205 $noid = $this->config->get('system', 'no_openid');
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();
213 // Otherwise it's probably an openid.
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());
228 * Attempts to authenticate using login/password
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
235 * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
236 * @throws Exception A general Exception (like SQL Grammar exceptions)
238 public function withPassword(App $a, string $username, string $password, bool $remember)
243 'username' => $username,
244 'password' => $password,
245 'authenticated' => 0,
246 'user_record' => null
250 * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
251 * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
252 * and later addons should not interfere with an earlier one that succeeded.
254 Hook::callAll('authenticate', $addon_auth);
257 if ($addon_auth['authenticated']) {
258 $record = $addon_auth['user_record'];
260 if (empty($record)) {
261 throw new Exception($this->l10n->t('Login failed.'));
264 $record = $this->dba->selectFirst(
267 ['uid' => User::getIdFromPasswordAuthentication($username, $password)]
270 } catch (Exception $e) {
271 $this->logger->warning('authenticate: failed login attempt', ['action' => 'login', 'username' => Strings::escapeTags($username), 'ip' => $_SERVER['REMOTE_ADDR']]);
272 notice($this->l10n->t('Login failed. Please check your credentials.'));
273 $this->baseUrl->redirect();
277 $this->cookie->clear();
280 // if we haven't failed up this point, log them in.
281 $this->session->set('remember', $remember);
282 $this->session->set('last_login_date', DateTimeFormat::utcNow());
284 $openid_identity = $this->session->get('openid_identity');
285 $openid_server = $this->session->get('openid_server');
287 if (!empty($openid_identity) || !empty($openid_server)) {
288 $this->dba->update('user', ['openid' => $openid_identity, 'openidserver' => $openid_server], ['uid' => $record['uid']]);
291 $this->setForUser($a, $record, true, true);
293 $return_path = $this->session->get('return_path', '');
294 $this->session->remove('return_path');
296 $this->baseUrl->redirect($return_path);
300 * Sets the provided user's authenticated session
302 * @param App $a The Friendica application context
303 * @param array $user_record The current "user" record
304 * @param bool $login_initial
305 * @param bool $interactive
306 * @param bool $login_refresh
308 * @throws HTTPException\InternalServerErrorException In case of Friendica specific exceptions
309 * @throws Exception In case of general Exceptions (like SQL Grammar exceptions)
311 public function setForUser(App $a, array $user_record, bool $login_initial = false, bool $interactive = false, bool $login_refresh = false)
313 $this->session->setMultiple([
314 'uid' => $user_record['uid'],
315 'theme' => $user_record['theme'],
316 'mobile-theme' => $this->pConfig->get($user_record['uid'], 'system', 'mobile_theme'),
317 'authenticated' => 1,
318 'page_flags' => $user_record['page-flags'],
319 'my_url' => $this->baseUrl->get() . '/profile/' . $user_record['nickname'],
320 'my_address' => $user_record['nickname'] . '@' . substr($this->baseUrl->get(), strpos($this->baseUrl->get(), '://') + 3),
321 'addr' => ($_SERVER['REMOTE_ADDR'] ?? '') ?: '0.0.0.0'
324 Session::setVisitorsContacts();
326 $member_since = strtotime($user_record['register_date']);
327 $this->session->set('new_member', time() < ($member_since + (60 * 60 * 24 * 14)));
329 if (strlen($user_record['timezone'])) {
330 date_default_timezone_set($user_record['timezone']);
331 $a->timezone = $user_record['timezone'];
334 $masterUid = $user_record['uid'];
336 if ($this->session->get('submanage')) {
337 $user = $this->dba->selectFirst('user', ['uid'], ['uid' => $this->session->get('submanage')]);
338 if ($this->dba->isResult($user)) {
339 $masterUid = $user['uid'];
343 $a->identities = User::identities($masterUid);
345 if ($login_initial) {
346 $this->logger->info('auth_identities: ' . print_r($a->identities, true));
349 if ($login_refresh) {
350 $this->logger->info('auth_identities refresh: ' . print_r($a->identities, true));
353 $contact = $this->dba->selectFirst('contact', [], ['uid' => $user_record['uid'], 'self' => true]);
354 if ($this->dba->isResult($contact)) {
355 $a->contact = $contact;
356 $a->cid = $contact['id'];
357 $this->session->set('cid', $a->cid);
360 header('X-Account-Management-Status: active; name="' . $user_record['username'] . '"; id="' . $user_record['nickname'] . '"');
362 if ($login_initial || $login_refresh) {
363 $this->dba->update('user', ['login_date' => DateTimeFormat::utcNow()], ['uid' => $user_record['uid']]);
365 // Set the login date for all identities of the user
366 $this->dba->update('user', ['login_date' => DateTimeFormat::utcNow()],
367 ['parent-uid' => $masterUid, 'account_removed' => false]);
370 if ($login_initial) {
372 * If the user specified to remember the authentication, then set a cookie
373 * that expires after one week (the default is when the browser is closed).
374 * The cookie will be renewed automatically.
375 * The week ensures that sessions will expire after some inactivity.
377 if ($this->session->get('remember')) {
378 $this->logger->info('Injecting cookie for remembered user ' . $user_record['nickname']);
379 $this->cookie->setMultiple([
380 'uid' => $user_record['uid'],
381 'hash' => $this->cookie->hashPrivateData($user_record['password'], $user_record['prvkey']),
383 $this->session->remove('remember');
387 $this->redirectForTwoFactorAuthentication($user_record['uid'], $a);
390 if ($user_record['login_date'] <= DBA::NULL_DATETIME) {
391 info($this->l10n->t('Welcome %s', $user_record['username']));
392 info($this->l10n->t('Please upload a profile photo.'));
393 $this->baseUrl->redirect('settings/profile/photo/new');
397 $a->user = $user_record;
399 if ($login_initial) {
400 Hook::callAll('logged_in', $a->user);
402 if (DI::module()->getName() !== 'home' && $this->session->exists('return_path')) {
403 $this->baseUrl->redirect($this->session->get('return_path'));
409 * Decides whether to redirect the user to two-factor authentication.
410 * All return calls in this method skip two-factor authentication
412 * @param int $uid The User Identified
413 * @param App $a The Friendica Application context
415 * @throws HTTPException\ForbiddenException In case the two factor authentication is forbidden (e.g. for AJAX calls)
416 * @throws HTTPException\InternalServerErrorException
418 private function redirectForTwoFactorAuthentication(int $uid, App $a)
420 // Check user setting, if 2FA disabled return
421 if (!$this->pConfig->get($uid, '2fa', 'verified')) {
425 // Check current path, if public or 2fa module return
426 if ($a->argc > 0 && in_array($a->argv[0], ['2fa', 'view', 'help', 'api', 'proxy', 'logout'])) {
430 // Case 1a: 2FA session already present: return
431 if ($this->session->get('2fa')) {
435 // Case 1b: Check for trusted browser
436 if ($this->cookie->get('trusted')) {
437 // Retrieve a trusted_browser model based on cookie hash
438 $trustedBrowserRepository = new TrustedBrowser($this->dba, $this->logger);
440 $trustedBrowser = $trustedBrowserRepository->selectOneByHash($this->cookie->get('trusted'));
441 // Verify record ownership
442 if ($trustedBrowser->uid === $uid) {
443 // Update last_used date
444 $trustedBrowser->recordUse();
446 // Save it to the database
447 $trustedBrowserRepository->save($trustedBrowser);
449 // Set 2fa session key and return
450 $this->session->set('2fa', true);
454 // Invalid trusted cookie value, removing it
455 $this->cookie->unset('trusted');
457 } catch (\Throwable $e) {
458 // Local trusted browser record was probably removed by the user, we carry on with 2FA
462 // Case 2: No valid 2FA session: redirect to code verification page
463 if ($this->mode->isAjax()) {
464 throw new HTTPException\ForbiddenException();
466 $this->baseUrl->redirect('2fa');