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\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;
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;
41 use Friendica\Core\L10n;
42 use Psr\Log\LoggerInterface;
45 * Handle Authentication, Session and Cookies
49 /** @var IManageConfigValues */
53 /** @var App\BaseURL */
59 /** @var LoggerInterface */
61 /** @var User\Cookie */
63 /** @var IHandleSessions */
65 /** @var IManagePersonalConfigValues */
69 * Sets the X-Account-Management-Status header
71 * mainly extracted to make it overridable for tests
73 * @param array $user_record
75 protected function setXAccMgmtStatusHeader(array $user_record)
77 header('X-Account-Management-Status: active; name="' . $user_record['username'] . '"; id="' . $user_record['nickname'] . '"');
81 * Authentication constructor.
83 * @param IManageConfigValues $config
84 * @param App\Mode $mode
85 * @param App\BaseURL $baseUrl
87 * @param Database $dba
88 * @param LoggerInterface $logger
89 * @param User\Cookie $cookie
90 * @param IHandleSessions $session
91 * @param IManagePersonalConfigValues $pConfig
93 public function __construct(IManageConfigValues $config, App\Mode $mode, App\BaseURL $baseUrl, L10n $l10n, Database $dba, LoggerInterface $logger, User\Cookie $cookie, IHandleSessions $session, IManagePersonalConfigValues $pConfig)
95 $this->config = $config;
97 $this->baseUrl = $baseUrl;
100 $this->logger = $logger;
101 $this->cookie = $cookie;
102 $this->session = $session;
103 $this->pConfig = $pConfig;
107 * Tries to auth the user from the cookie or session
109 * @param App $a The Friendica Application context
111 * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
112 * @throws Exception In case of general exceptions (like SQL Grammar)
114 public function withSession(App $a)
116 // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
117 if ($this->cookie->get('uid')) {
118 $user = $this->dba->selectFirst(
122 'uid' => $this->cookie->get('uid'),
124 'account_expired' => false,
125 'account_removed' => false,
129 if ($this->dba->isResult($user)) {
130 if (!$this->cookie->comparePrivateDataHash($this->cookie->get('hash'),
131 $user['password'] ?? '',
132 $user['prvkey'] ?? '')
134 $this->logger->notice("Hash doesn't fit.", ['user' => $this->cookie->get('uid')]);
135 $this->session->clear();
136 $this->cookie->clear();
137 $this->baseUrl->redirect();
141 $this->cookie->send();
143 // Do the authentification if not done by now
144 if (!$this->session->get('authenticated')) {
145 $this->setForUser($a, $user);
147 if ($this->config->get('system', 'paranoia')) {
148 $this->session->set('addr', $this->cookie->get('ip'));
154 if ($this->session->get('authenticated')) {
155 if ($this->session->get('visitor_id') && !$this->session->get('uid')) {
156 $contact = $this->dba->selectFirst('contact', ['id'], ['id' => $this->session->get('visitor_id')]);
157 if ($this->dba->isResult($contact)) {
158 $a->setContactId($contact['id']);
162 if ($this->session->get('uid')) {
163 // already logged in user returning
164 $check = $this->config->get('system', 'paranoia');
165 // extra paranoia - if the IP changed, log them out
166 if ($check && ($this->session->get('addr') != $_SERVER['REMOTE_ADDR'])) {
167 $this->logger->notice('Session address changed. Paranoid setting in effect, blocking session. ', [
168 'addr' => $this->session->get('addr'),
169 'remote_addr' => $_SERVER['REMOTE_ADDR']]
171 $this->session->clear();
172 $this->baseUrl->redirect();
175 $user = $this->dba->selectFirst(
179 'uid' => $this->session->get('uid'),
181 'account_expired' => false,
182 'account_removed' => false,
186 if (!$this->dba->isResult($user)) {
187 $this->session->clear();
188 $this->baseUrl->redirect();
191 // Make sure to refresh the last login time for the user if the user
192 // stays logged in for a long time, e.g. with "Remember Me"
193 $login_refresh = false;
194 if (!$this->session->get('last_login_date')) {
195 $this->session->set('last_login_date', DateTimeFormat::utcNow());
197 if (strcmp(DateTimeFormat::utc('now - 12 hours'), $this->session->get('last_login_date')) > 0) {
198 $this->session->set('last_login_date', DateTimeFormat::utcNow());
199 $login_refresh = true;
202 $this->setForUser($a, $user, false, false, $login_refresh);
208 * Attempts to authenticate using OpenId
210 * @param string $openid_url OpenID URL string
211 * @param bool $remember Whether to set the session remember flag
213 * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
215 public function withOpenId(string $openid_url, bool $remember)
217 $noid = $this->config->get('system', 'no_openid');
219 // if it's an email address or doesn't resolve to a URL, fail.
220 if ($noid || strpos($openid_url, '@') || !Network::isUrlValid($openid_url)) {
221 notice($this->l10n->t('Login failed.'));
222 $this->baseUrl->redirect();
225 // Otherwise it's probably an openid.
227 $openid = new LightOpenID($this->baseUrl->getHostname());
228 $openid->identity = $openid_url;
229 $this->session->set('openid', $openid_url);
230 $this->session->set('remember', $remember);
231 $openid->returnUrl = $this->baseUrl->get(true) . '/openid';
232 $openid->optional = ['namePerson/friendly', 'contact/email', 'namePerson', 'namePerson/first', 'media/image/aspect11', 'media/image/default'];
233 System::externalRedirect($openid->authUrl());
234 } catch (Exception $e) {
235 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());
240 * Attempts to authenticate using login/password
242 * @param App $a The Friendica Application context
243 * @param string $username User name
244 * @param string $password Clear password
245 * @param bool $remember Whether to set the session remember flag
247 * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
248 * @throws Exception A general Exception (like SQL Grammar exceptions)
250 public function withPassword(App $a, string $username, string $password, bool $remember)
255 $record = $this->dba->selectFirst(
258 ['uid' => User::getIdFromPasswordAuthentication($username, $password)]
260 } catch (Exception $e) {
261 $this->logger->warning('authenticate: failed login attempt', ['action' => 'login', 'username' => $username, 'ip' => $_SERVER['REMOTE_ADDR']]);
262 notice($this->l10n->t('Login failed. Please check your credentials.'));
263 $this->baseUrl->redirect();
267 $this->cookie->clear();
270 // if we haven't failed up this point, log them in.
271 $this->session->set('remember', $remember);
272 $this->session->set('last_login_date', DateTimeFormat::utcNow());
274 $openid_identity = $this->session->get('openid_identity');
275 $openid_server = $this->session->get('openid_server');
277 if (!empty($openid_identity) || !empty($openid_server)) {
278 $this->dba->update('user', ['openid' => $openid_identity, 'openidserver' => $openid_server], ['uid' => $record['uid']]);
281 $this->setForUser($a, $record, true, true);
283 $return_path = $this->session->get('return_path', '');
284 $this->session->remove('return_path');
286 $this->baseUrl->redirect($return_path);
290 * Sets the provided user's authenticated session
292 * @param App $a The Friendica application context
293 * @param array $user_record The current "user" record
294 * @param bool $login_initial
295 * @param bool $interactive
296 * @param bool $login_refresh
298 * @throws HTTPException\InternalServerErrorException In case of Friendica specific exceptions
299 * @throws Exception In case of general Exceptions (like SQL Grammar exceptions)
301 public function setForUser(App $a, array $user_record, bool $login_initial = false, bool $interactive = false, bool $login_refresh = false)
303 $this->session->setMultiple([
304 'uid' => $user_record['uid'],
305 'theme' => $user_record['theme'],
306 'mobile-theme' => $this->pConfig->get($user_record['uid'], 'system', 'mobile_theme'),
307 'authenticated' => 1,
308 'page_flags' => $user_record['page-flags'],
309 'my_url' => $this->baseUrl->get() . '/profile/' . $user_record['nickname'],
310 'my_address' => $user_record['nickname'] . '@' . substr($this->baseUrl->get(), strpos($this->baseUrl->get(), '://') + 3),
311 'addr' => ($_SERVER['REMOTE_ADDR'] ?? '') ?: '0.0.0.0'
314 Session::setVisitorsContacts();
316 $member_since = strtotime($user_record['register_date']);
317 $this->session->set('new_member', time() < ($member_since + (60 * 60 * 24 * 14)));
319 if (strlen($user_record['timezone'])) {
320 $a->setTimeZone($user_record['timezone']);
323 $contact = $this->dba->selectFirst('contact', ['id'], ['uid' => $user_record['uid'], 'self' => true]);
324 if ($this->dba->isResult($contact)) {
325 $a->setContactId($contact['id']);
326 $this->session->set('cid', $contact['id']);
329 $this->setXAccMgmtStatusHeader($user_record);
331 if ($login_initial || $login_refresh) {
332 $this->dba->update('user', ['login_date' => DateTimeFormat::utcNow()], ['uid' => $user_record['uid']]);
334 // Set the login date for all identities of the user
335 $this->dba->update('user', ['login_date' => DateTimeFormat::utcNow()],
336 ['parent-uid' => $user_record['uid'], 'account_removed' => false]);
339 if ($login_initial) {
341 * If the user specified to remember the authentication, then set a cookie
342 * that expires after one week (the default is when the browser is closed).
343 * The cookie will be renewed automatically.
344 * The week ensures that sessions will expire after some inactivity.
346 if ($this->session->get('remember')) {
347 $this->logger->info('Injecting cookie for remembered user ' . $user_record['nickname']);
348 $this->cookie->setMultiple([
349 'uid' => $user_record['uid'],
350 'hash' => $this->cookie->hashPrivateData($user_record['password'], $user_record['prvkey']),
352 $this->session->remove('remember');
356 $this->redirectForTwoFactorAuthentication($user_record['uid']);
359 if ($user_record['login_date'] <= DBA::NULL_DATETIME) {
360 info($this->l10n->t('Welcome %s', $user_record['username']));
361 info($this->l10n->t('Please upload a profile photo.'));
362 $this->baseUrl->redirect('settings/profile/photo/new');
366 $a->setLoggedInUserId($user_record['uid']);
367 $a->setLoggedInUserNickname($user_record['nickname']);
369 if ($login_initial) {
370 Hook::callAll('logged_in', $user_record);
372 if (DI::args()->getModuleName() !== 'home' && $this->session->exists('return_path')) {
373 $this->baseUrl->redirect($this->session->get('return_path'));
379 * Decides whether to redirect the user to two-factor authentication.
380 * All return calls in this method skip two-factor authentication
382 * @param int $uid The User Identified
384 * @throws HTTPException\ForbiddenException In case the two factor authentication is forbidden (e.g. for AJAX calls)
385 * @throws HTTPException\InternalServerErrorException
387 private function redirectForTwoFactorAuthentication(int $uid)
389 // Check user setting, if 2FA disabled return
390 if (!$this->pConfig->get($uid, '2fa', 'verified')) {
394 // Check current path, if public or 2fa module return
395 if (DI::args()->getArgc() > 0 && in_array(DI::args()->getArgv()[0], ['2fa', 'view', 'help', 'api', 'proxy', 'logout'])) {
399 // Case 1a: 2FA session already present: return
400 if ($this->session->get('2fa')) {
404 // Case 1b: Check for trusted browser
405 if ($this->cookie->get('trusted')) {
406 // Retrieve a trusted_browser model based on cookie hash
407 $trustedBrowserRepository = new TrustedBrowser($this->dba, $this->logger);
409 $trustedBrowser = $trustedBrowserRepository->selectOneByHash($this->cookie->get('trusted'));
410 // Verify record ownership
411 if ($trustedBrowser->uid === $uid) {
412 // Update last_used date
413 $trustedBrowser->recordUse();
415 // Save it to the database
416 $trustedBrowserRepository->save($trustedBrowser);
418 // Set 2fa session key and return
419 $this->session->set('2fa', true);
423 // Invalid trusted cookie value, removing it
424 $this->cookie->unset('trusted');
426 } catch (\Throwable $e) {
427 // Local trusted browser record was probably removed by the user, we carry on with 2FA
431 // Case 2: No valid 2FA session: redirect to code verification page
432 if ($this->mode->isAjax()) {
433 throw new HTTPException\ForbiddenException();
435 $this->baseUrl->redirect('2fa');