3 * @copyright Copyright (C) 2010-2022, 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\Capability\IManageConfigValues;
27 use Friendica\Core\PConfig\Capability\IManagePersonalConfigValues;
28 use Friendica\Core\Hook;
29 use Friendica\Core\Session\Capability\IHandleUserSessions;
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;
40 use Friendica\Core\L10n;
41 use Friendica\Core\Worker;
42 use Friendica\Model\Contact;
43 use Psr\Log\LoggerInterface;
46 * Handle Authentication, Session and Cookies
50 /** @var IManageConfigValues */
54 /** @var App\BaseURL */
60 /** @var LoggerInterface */
62 /** @var User\Cookie */
64 /** @var IHandleUserSessions */
66 /** @var IManagePersonalConfigValues */
69 private $remoteAddress;
72 * Sets the X-Account-Management-Status header
74 * mainly extracted to make it overridable for tests
76 * @param array $user_record
78 protected function setXAccMgmtStatusHeader(array $user_record)
80 header('X-Account-Management-Status: active; name="' . $user_record['username'] . '"; id="' . $user_record['nickname'] . '"');
84 * Authentication constructor.
86 * @param IManageConfigValues $config
87 * @param App\Mode $mode
88 * @param App\BaseURL $baseUrl
90 * @param Database $dba
91 * @param LoggerInterface $logger
92 * @param User\Cookie $cookie
93 * @param IHandleUserSessions $session
94 * @param IManagePersonalConfigValues $pConfig
95 * @param App\Request $request
97 public function __construct(IManageConfigValues $config, App\Mode $mode, App\BaseURL $baseUrl, L10n $l10n, Database $dba, LoggerInterface $logger, User\Cookie $cookie, IHandleUserSessions $session, IManagePersonalConfigValues $pConfig, App\Request $request)
99 $this->config = $config;
101 $this->baseUrl = $baseUrl;
104 $this->logger = $logger;
105 $this->cookie = $cookie;
106 $this->session = $session;
107 $this->pConfig = $pConfig;
108 $this->remoteAddress = $request->getRemoteAddress();
112 * Tries to auth the user from the cookie or session
114 * @param App $a The Friendica Application context
116 * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
117 * @throws Exception In case of general exceptions (like SQL Grammar)
119 public function withSession(App $a)
121 // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
122 if ($this->cookie->get('uid')) {
123 $user = $this->dba->selectFirst(
127 'uid' => $this->cookie->get('uid'),
129 'account_expired' => false,
130 'account_removed' => false,
134 if ($this->dba->isResult($user)) {
135 if (!$this->cookie->comparePrivateDataHash($this->cookie->get('hash'),
136 $user['password'] ?? '',
137 $user['prvkey'] ?? '')
139 $this->logger->notice("Hash doesn't fit.", ['user' => $this->cookie->get('uid')]);
140 $this->session->clear();
141 $this->cookie->clear();
142 $this->baseUrl->redirect();
146 $this->cookie->send();
148 // Do the authentication if not done by now
149 if (!$this->session->get('authenticated')) {
150 $this->setForUser($a, $user);
152 if ($this->config->get('system', 'paranoia')) {
153 $this->session->set('addr', $this->cookie->get('ip'));
159 if ($this->session->get('authenticated')) {
160 if ($this->session->get('visitor_id') && !$this->session->get('uid')) {
161 $contact = $this->dba->selectFirst('contact', ['id'], ['id' => $this->session->get('visitor_id')]);
162 if ($this->dba->isResult($contact)) {
163 $a->setContactId($contact['id']);
167 if ($this->session->get('uid')) {
168 // already logged in user returning
169 $check = $this->config->get('system', 'paranoia');
170 // extra paranoia - if the IP changed, log them out
171 if ($check && ($this->session->get('addr') != $this->remoteAddress)) {
172 $this->logger->notice('Session address changed. Paranoid setting in effect, blocking session. ', [
173 'addr' => $this->session->get('addr'),
174 'remote_addr' => $this->remoteAddress
177 $this->session->clear();
178 $this->baseUrl->redirect();
181 $user = $this->dba->selectFirst(
185 'uid' => $this->session->get('uid'),
187 'account_expired' => false,
188 'account_removed' => false,
192 if (!$this->dba->isResult($user)) {
193 $this->session->clear();
194 $this->baseUrl->redirect();
197 // Make sure to refresh the last login time for the user if the user
198 // stays logged in for a long time, e.g. with "Remember Me"
199 $login_refresh = false;
200 if (!$this->session->get('last_login_date')) {
201 $this->session->set('last_login_date', DateTimeFormat::utcNow());
203 if (strcmp(DateTimeFormat::utc('now - 12 hours'), $this->session->get('last_login_date')) > 0) {
204 $this->session->set('last_login_date', DateTimeFormat::utcNow());
205 $login_refresh = true;
208 $this->setForUser($a, $user, false, false, $login_refresh);
214 * Attempts to authenticate using OpenId
216 * @param string $openid_url OpenID URL string
217 * @param bool $remember Whether to set the session remember flag
219 * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
221 public function withOpenId(string $openid_url, bool $remember)
223 $noid = $this->config->get('system', 'no_openid');
225 // if it's an email address or doesn't resolve to a URL, fail.
226 if ($noid || strpos($openid_url, '@') || !Network::isUrlValid($openid_url)) {
227 DI::sysmsg()->addNotice($this->l10n->t('Login failed.'));
228 $this->baseUrl->redirect();
231 // Otherwise it's probably an openid.
233 $openid = new LightOpenID($this->baseUrl->getHostname());
234 $openid->identity = $openid_url;
235 $this->session->set('openid', $openid_url);
236 $this->session->set('remember', $remember);
237 $openid->returnUrl = $this->baseUrl->get(true) . '/openid';
238 $openid->optional = ['namePerson/friendly', 'contact/email', 'namePerson', 'namePerson/first', 'media/image/aspect11', 'media/image/default'];
239 System::externalRedirect($openid->authUrl());
240 } catch (Exception $e) {
241 DI::sysmsg()->addNotice($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());
246 * Attempts to authenticate using login/password
248 * @param App $a The Friendica Application context
249 * @param string $username
250 * @param string $password Clear password
251 * @param bool $remember Whether to set the session remember flag
252 * @param string $return_path The relative path to redirect the user to after authentication
254 * @throws HTTPException\ForbiddenException
255 * @throws HTTPException\FoundException
256 * @throws HTTPException\InternalServerErrorException In case of Friendica internal exceptions
257 * @throws HTTPException\MovedPermanentlyException
258 * @throws HTTPException\TemporaryRedirectException
260 public function withPassword(App $a, string $username, string $password, bool $remember, string $return_path = '')
265 $record = $this->dba->selectFirst(
268 ['uid' => User::getIdFromPasswordAuthentication($username, $password)]
270 } catch (Exception $e) {
271 $this->logger->warning('authenticate: failed login attempt', ['action' => 'login', 'username' => $username, 'ip' => $this->remoteAddress]);
272 DI::sysmsg()->addNotice($this->l10n->t('Login failed. Please check your credentials.'));
273 $this->baseUrl->redirect();
277 $trusted = $this->cookie->get('2fa_cookie_hash') ?? null;
278 $this->cookie->clear();
280 $this->cookie->set('2fa_cookie_hash', $trusted);
284 // if we haven't failed up this point, log them in.
285 $this->session->set('remember', $remember);
286 $this->session->set('last_login_date', DateTimeFormat::utcNow());
288 $openid_identity = $this->session->get('openid_identity');
289 $openid_server = $this->session->get('openid_server');
291 if (!empty($openid_identity) || !empty($openid_server)) {
292 $this->dba->update('user', ['openid' => $openid_identity, 'openidserver' => $openid_server], ['uid' => $record['uid']]);
296 * @see User::getPasswordRegExp()
298 if (PASSWORD_DEFAULT === PASSWORD_BCRYPT && strlen($password) > 72) {
299 $return_path = '/security/password_too_long?' . http_build_query(['return_path' => $return_path]);
302 $this->setForUser($a, $record, true, true);
304 $this->baseUrl->redirect($return_path);
308 * Sets the provided user's authenticated session
310 * @param App $a The Friendica application context
311 * @param array $user_record The current "user" record
312 * @param bool $login_initial
313 * @param bool $interactive
314 * @param bool $login_refresh
316 * @throws HTTPException\FoundException
317 * @throws HTTPException\MovedPermanentlyException
318 * @throws HTTPException\TemporaryRedirectException
319 * @throws HTTPException\ForbiddenException
321 * @throws HTTPException\InternalServerErrorException In case of Friendica specific exceptions
324 public function setForUser(App $a, array $user_record, bool $login_initial = false, bool $interactive = false, bool $login_refresh = false)
326 $this->session->setMultiple([
327 'uid' => $user_record['uid'],
328 'theme' => $user_record['theme'],
329 'mobile-theme' => $this->pConfig->get($user_record['uid'], 'system', 'mobile_theme'),
330 'authenticated' => 1,
331 'page_flags' => $user_record['page-flags'],
332 'my_url' => $this->baseUrl->get() . '/profile/' . $user_record['nickname'],
333 'my_address' => $user_record['nickname'] . '@' . substr($this->baseUrl->get(), strpos($this->baseUrl->get(), '://') + 3),
334 'addr' => $this->remoteAddress,
335 'nickname' => $user_record['nickname'],
338 $this->session->setVisitorsContacts();
340 $member_since = strtotime($user_record['register_date']);
341 $this->session->set('new_member', time() < ($member_since + (60 * 60 * 24 * 14)));
343 if (strlen($user_record['timezone'])) {
344 $a->setTimeZone($user_record['timezone']);
347 $contact = $this->dba->selectFirst('contact', ['id'], ['uid' => $user_record['uid'], 'self' => true]);
348 if ($this->dba->isResult($contact)) {
349 $a->setContactId($contact['id']);
350 $this->session->set('cid', $contact['id']);
353 $this->setXAccMgmtStatusHeader($user_record);
355 if ($login_initial || $login_refresh) {
356 $this->dba->update('user', ['last-activity' => DateTimeFormat::utcNow('Y-m-d'), 'login_date' => DateTimeFormat::utcNow()], ['uid' => $user_record['uid']]);
358 // Set the login date for all identities of the user
359 $this->dba->update('user', ['last-activity' => DateTimeFormat::utcNow('Y-m-d'), 'login_date' => DateTimeFormat::utcNow()],
360 ['parent-uid' => $user_record['uid'], 'account_removed' => false]);
362 // Regularly update suggestions
363 if (Contact\Relation::areSuggestionsOutdated($user_record['uid'])) {
364 Worker::add(Worker::PRIORITY_MEDIUM, 'UpdateSuggestions', $user_record['uid']);
368 if ($login_initial) {
370 * If the user specified to remember the authentication, then set a cookie
371 * that expires after one week (the default is when the browser is closed).
372 * The cookie will be renewed automatically.
373 * The week ensures that sessions will expire after some inactivity.
375 if ($this->session->get('remember')) {
376 $this->logger->info('Injecting cookie for remembered user ' . $user_record['nickname']);
377 $this->cookie->setMultiple([
378 'uid' => $user_record['uid'],
379 'hash' => $this->cookie->hashPrivateData($user_record['password'], $user_record['prvkey']),
381 $this->session->remove('remember');
385 $this->redirectForTwoFactorAuthentication($user_record['uid']);
388 if ($user_record['login_date'] <= DBA::NULL_DATETIME) {
389 DI::sysmsg()->addInfo($this->l10n->t('Welcome %s', $user_record['username']));
390 DI::sysmsg()->addInfo($this->l10n->t('Please upload a profile photo.'));
391 $this->baseUrl->redirect('settings/profile/photo/new');
395 $a->setLoggedInUserId($user_record['uid']);
396 $a->setLoggedInUserNickname($user_record['nickname']);
398 if ($login_initial) {
399 Hook::callAll('logged_in', $user_record);
404 * Decides whether to redirect the user to two-factor authentication.
405 * All return calls in this method skip two-factor authentication
407 * @param int $uid The User Identified
409 * @throws HTTPException\ForbiddenException In case the two factor authentication is forbidden (e.g. for AJAX calls)
410 * @throws HTTPException\InternalServerErrorException
412 private function redirectForTwoFactorAuthentication(int $uid)
414 // Check user setting, if 2FA disabled return
415 if (!$this->pConfig->get($uid, '2fa', 'verified')) {
419 // Check current path, if public or 2fa module return
420 if (DI::args()->getArgc() > 0 && in_array(DI::args()->getArgv()[0], ['2fa', 'view', 'help', 'api', 'proxy', 'logout'])) {
424 // Case 1a: 2FA session already present: return
425 if ($this->session->get('2fa')) {
429 // Case 1b: Check for trusted browser
430 if ($this->cookie->get('2fa_cookie_hash')) {
431 // Retrieve a trusted_browser model based on cookie hash
432 $trustedBrowserRepository = new TrustedBrowser($this->dba, $this->logger);
434 $trustedBrowser = $trustedBrowserRepository->selectOneByHash($this->cookie->get('2fa_cookie_hash'));
435 // Verify record ownership
436 if ($trustedBrowser->uid === $uid) {
437 // Update last_used date
438 $trustedBrowser->recordUse();
440 // Save it to the database
441 $trustedBrowserRepository->save($trustedBrowser);
443 // Only use this entry, if its really trusted, otherwise just update the record and proceed
444 if ($trustedBrowser->trusted) {
445 // Set 2fa session key and return
446 $this->session->set('2fa', true);
451 // Invalid trusted cookie value, removing it
452 $this->cookie->unset('trusted');
454 } catch (\Throwable $e) {
455 // Local trusted browser record was probably removed by the user, we carry on with 2FA
459 // Case 2: No valid 2FA session: redirect to code verification page
460 if ($this->mode->isAjax()) {
461 throw new HTTPException\ForbiddenException();
463 $this->baseUrl->redirect('2fa');