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 Friendica\Core\Logger;
43 use Psr\Log\LoggerInterface;
46 * Handle Authentication, Session and Cookies
54 /** @var App\BaseURL */
60 /** @var LoggerInterface */
62 /** @var User\Cookie */
64 /** @var Session\ISession */
70 * Authentication constructor.
72 * @param IConfig $config
73 * @param App\Mode $mode
74 * @param App\BaseURL $baseUrl
76 * @param Database $dba
77 * @param LoggerInterface $logger
78 * @param User\Cookie $cookie
79 * @param Session\ISession $session
80 * @param IPConfig $pConfig
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)
84 $this->config = $config;
86 $this->baseUrl = $baseUrl;
89 $this->logger = $logger;
90 $this->cookie = $cookie;
91 $this->session = $session;
92 $this->pConfig = $pConfig;
96 * Tries to auth the user from the cookie or session
98 * @param App $a The Friendica Application context
100 * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
101 * @throws Exception In case of general exceptions (like SQL Grammar)
103 public function withSession(App $a)
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(
111 'uid' => $this->cookie->get('uid'),
113 'account_expired' => false,
114 'account_removed' => false,
118 if ($this->dba->isResult($user)) {
119 if (!$this->cookie->comparePrivateDataHash($this->cookie->get('hash'),
120 $user['password'] ?? '',
121 $user['prvkey'] ?? '')
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();
130 $this->cookie->send();
132 // Do the authentification if not done by now
133 if (!$this->session->get('authenticated')) {
134 $this->setForUser($a, $user);
136 if ($this->config->get('system', 'paranoia')) {
137 $this->session->set('addr', $this->cookie->get('ip'));
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;
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']]
160 $this->session->clear();
161 $this->baseUrl->redirect();
164 $user = $this->dba->selectFirst(
168 'uid' => $this->session->get('uid'),
170 'account_expired' => false,
171 'account_removed' => false,
175 if (!$this->dba->isResult($user)) {
176 $this->session->clear();
177 $this->baseUrl->redirect();
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());
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;
191 $this->setForUser($a, $user, false, false, $login_refresh);
197 * Attempts to authenticate using OpenId
199 * @param string $openid_url OpenID URL string
200 * @param bool $remember Whether to set the session remember flag
202 * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
204 public function withOpenId(string $openid_url, bool $remember)
206 $noid = $this->config->get('system', 'no_openid');
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();
214 // Otherwise it's probably an openid.
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());
229 * Attempts to authenticate using login/password
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
236 * @throws HttpException\InternalServerErrorException In case of Friendica internal exceptions
237 * @throws Exception A general Exception (like SQL Grammar exceptions)
239 public function withPassword(App $a, string $username, string $password, bool $remember)
244 $record = $this->dba->selectFirst(
247 ['uid' => User::getIdFromPasswordAuthentication($username, $password)]
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();
256 $this->cookie->clear();
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());
263 $openid_identity = $this->session->get('openid_identity');
264 $openid_server = $this->session->get('openid_server');
266 if (!empty($openid_identity) || !empty($openid_server)) {
267 $this->dba->update('user', ['openid' => $openid_identity, 'openidserver' => $openid_server], ['uid' => $record['uid']]);
270 $this->setForUser($a, $record, true, true);
272 $return_path = $this->session->get('return_path', '');
273 $this->session->remove('return_path');
275 $this->baseUrl->redirect($return_path);
279 * Sets the provided user's authenticated session
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
287 * @throws HTTPException\InternalServerErrorException In case of Friendica specific exceptions
288 * @throws Exception In case of general Exceptions (like SQL Grammar exceptions)
290 public function setForUser(App $a, array $user_record, bool $login_initial = false, bool $interactive = false, bool $login_refresh = false)
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'
303 Session::setVisitorsContacts();
305 $member_since = strtotime($user_record['register_date']);
306 $this->session->set('new_member', time() < ($member_since + (60 * 60 * 24 * 14)));
308 if (strlen($user_record['timezone'])) {
309 date_default_timezone_set($user_record['timezone']);
310 $a->timezone = $user_record['timezone'];
313 $masterUid = $user_record['uid'];
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'];
322 $a->identities = User::identities($masterUid);
324 if ($login_initial) {
325 $this->logger->info('auth_identities: ' . print_r($a->identities, true));
328 if ($login_refresh) {
329 $this->logger->info('auth_identities refresh: ' . print_r($a->identities, true));
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);
339 header('X-Account-Management-Status: active; name="' . $user_record['username'] . '"; id="' . $user_record['nickname'] . '"');
341 if ($login_initial || $login_refresh) {
342 $this->dba->update('user', ['login_date' => DateTimeFormat::utcNow()], ['uid' => $user_record['uid']]);
344 // Set the login date for all identities of the user
345 $this->dba->update('user', ['login_date' => DateTimeFormat::utcNow()],
346 ['parent-uid' => $masterUid, 'account_removed' => false]);
349 if ($login_initial) {
351 * If the user specified to remember the authentication, then set a cookie
352 * that expires after one week (the default is when the browser is closed).
353 * The cookie will be renewed automatically.
354 * The week ensures that sessions will expire after some inactivity.
356 if ($this->session->get('remember')) {
357 $this->logger->info('Injecting cookie for remembered user ' . $user_record['nickname']);
358 $this->cookie->setMultiple([
359 'uid' => $user_record['uid'],
360 'hash' => $this->cookie->hashPrivateData($user_record['password'], $user_record['prvkey']),
362 $this->session->remove('remember');
366 $this->redirectForTwoFactorAuthentication($user_record['uid'], $a);
369 if ($user_record['login_date'] <= DBA::NULL_DATETIME) {
370 info($this->l10n->t('Welcome %s', $user_record['username']));
371 info($this->l10n->t('Please upload a profile photo.'));
372 $this->baseUrl->redirect('settings/profile/photo/new');
376 $a->user = $user_record;
378 if ($login_initial) {
379 Hook::callAll('logged_in', $a->user);
381 if (DI::module()->getName() !== 'home' && $this->session->exists('return_path')) {
382 $this->baseUrl->redirect($this->session->get('return_path'));
388 * Decides whether to redirect the user to two-factor authentication.
389 * All return calls in this method skip two-factor authentication
391 * @param int $uid The User Identified
392 * @param App $a The Friendica Application context
394 * @throws HTTPException\ForbiddenException In case the two factor authentication is forbidden (e.g. for AJAX calls)
395 * @throws HTTPException\InternalServerErrorException
397 private function redirectForTwoFactorAuthentication(int $uid, App $a)
399 // Check user setting, if 2FA disabled return
400 if (!$this->pConfig->get($uid, '2fa', 'verified')) {
404 // Check current path, if public or 2fa module return
405 if ($a->argc > 0 && in_array($a->argv[0], ['2fa', 'view', 'help', 'api', 'proxy', 'logout'])) {
409 // Case 1a: 2FA session already present: return
410 if ($this->session->get('2fa')) {
414 // Case 1b: Check for trusted browser
415 if ($this->cookie->get('trusted')) {
416 // Retrieve a trusted_browser model based on cookie hash
417 $trustedBrowserRepository = new TrustedBrowser($this->dba, $this->logger);
419 $trustedBrowser = $trustedBrowserRepository->selectOneByHash($this->cookie->get('trusted'));
420 // Verify record ownership
421 if ($trustedBrowser->uid === $uid) {
422 // Update last_used date
423 $trustedBrowser->recordUse();
425 // Save it to the database
426 $trustedBrowserRepository->save($trustedBrowser);
428 // Set 2fa session key and return
429 $this->session->set('2fa', true);
433 // Invalid trusted cookie value, removing it
434 $this->cookie->unset('trusted');
436 } catch (\Throwable $e) {
437 // Local trusted browser record was probably removed by the user, we carry on with 2FA
441 // Case 2: No valid 2FA session: redirect to code verification page
442 if ($this->mode->isAjax()) {
443 throw new HTTPException\ForbiddenException();
445 $this->baseUrl->redirect('2fa');