]> git.mxchange.org Git - friendica.git/blob - src/Module/Login.php
Fix security vulnerbilities.
[friendica.git] / src / Module / Login.php
1 <?php
2
3 /**
4  * @file src/Module/Login.php
5  */
6
7 namespace Friendica\Module;
8
9 use Exception;
10 use Friendica\BaseModule;
11 use Friendica\Core\Authentication;
12 use Friendica\Core\Config;
13 use Friendica\Core\Hook;
14 use Friendica\Core\L10n;
15 use Friendica\Core\Logger;
16 use Friendica\Core\Renderer;
17 use Friendica\Core\Session;
18 use Friendica\Core\System;
19 use Friendica\Database\DBA;
20 use Friendica\Model\User;
21 use Friendica\Util\DateTimeFormat;
22 use Friendica\Util\Network;
23 use Friendica\Util\Strings;
24 use LightOpenID;
25
26 /**
27  * Login module
28  *
29  * @author Hypolite Petovan <hypolite@mrpetovan.com>
30  */
31 class Login extends BaseModule
32 {
33         public static function content()
34         {
35                 $a = self::getApp();
36
37                 if (local_user()) {
38                         $a->internalRedirect();
39                 }
40
41                 return self::form(Session::get('return_path'), intval(Config::get('config', 'register_policy')) !== \Friendica\Module\Register::CLOSED);
42         }
43
44         public static function post()
45         {
46                 $return_path = Session::get('return_path');
47                 session_unset();
48                 Session::set('return_path', $return_path);
49
50                 // OpenId Login
51                 if (
52                         empty($_POST['password'])
53                         && (!empty($_POST['openid_url'])
54                                 || !empty($_POST['username']))
55                 ) {
56                         $openid_url = trim(defaults($_POST, 'openid_url', $_POST['username']));
57
58                         self::openIdAuthentication($openid_url, !empty($_POST['remember']));
59                 }
60
61                 if (!empty($_POST['auth-params']) && $_POST['auth-params'] === 'login') {
62                         self::passwordAuthentication(
63                                 trim($_POST['username']),
64                                 trim($_POST['password']),
65                                 !empty($_POST['remember'])
66                         );
67                 }
68         }
69
70         /**
71          * Attempts to authenticate using OpenId
72          *
73          * @param string $openid_url OpenID URL string
74          * @param bool   $remember   Whether to set the session remember flag
75          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
76          */
77         private static function openIdAuthentication($openid_url, $remember)
78         {
79                 $noid = Config::get('system', 'no_openid');
80
81                 $a = self::getApp();
82
83                 // if it's an email address or doesn't resolve to a URL, fail.
84                 if ($noid || strpos($openid_url, '@') || !Network::isUrlValid($openid_url)) {
85                         notice(L10n::t('Login failed.') . EOL);
86                         $a->internalRedirect();
87                         // NOTREACHED
88                 }
89
90                 // Otherwise it's probably an openid.
91                 try {
92                         $openid = new LightOpenID($a->getHostName());
93                         $openid->identity = $openid_url;
94                         $_SESSION['openid'] = $openid_url;
95                         $_SESSION['remember'] = $remember;
96                         $openid->returnUrl = $a->getBaseURL(true) . '/openid';
97                         System::externalRedirect($openid->authUrl());
98                 } catch (Exception $e) {
99                         notice(L10n::t('We encountered a problem while logging in with the OpenID you provided. Please check the correct spelling of the ID.') . '<br /><br >' . L10n::t('The error message was:') . ' ' . $e->getMessage());
100                 }
101         }
102
103         /**
104          * Attempts to authenticate using login/password
105          *
106          * @param string $username User name
107          * @param string $password Clear password
108          * @param bool   $remember Whether to set the session remember flag
109          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
110          */
111         private static function passwordAuthentication($username, $password, $remember)
112         {
113                 $record = null;
114
115                 $addon_auth = [
116                         'username' => $username,
117                         'password' => $password,
118                         'authenticated' => 0,
119                         'user_record' => null
120                 ];
121
122                 $a = self::getApp();
123
124                 /*
125                  * An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
126                  * Addons should never set 'authenticated' except to indicate success - as hooks may be chained
127                  * and later addons should not interfere with an earlier one that succeeded.
128                  */
129                 Hook::callAll('authenticate', $addon_auth);
130
131                 try {
132                         if ($addon_auth['authenticated']) {
133                                 $record = $addon_auth['user_record'];
134
135                                 if (empty($record)) {
136                                         throw new Exception(L10n::t('Login failed.'));
137                                 }
138                         } else {
139                                 $record = DBA::selectFirst(
140                                         'user',
141                                         [],
142                                         ['uid' => User::getIdFromPasswordAuthentication($username, $password)]
143                                 );
144                         }
145                 } catch (Exception $e) {
146                         Logger::warning('authenticate: failed login attempt', ['action' => 'login', 'username' => Strings::escapeTags($username), 'ip' => $_SERVER['REMOTE_ADDR']]);
147                         info('Login failed. Please check your credentials.' . EOL);
148                         $a->internalRedirect();
149                 }
150
151                 if (!$remember) {
152                         Authentication::setCookie(0); // 0 means delete on browser exit
153                 }
154
155                 // if we haven't failed up this point, log them in.
156                 Session::set('remember', $remember);
157                 Session::set('last_login_date', DateTimeFormat::utcNow());
158
159                 Session::setAuthenticatedForUser($a, $record, true, true);
160
161                 $return_path = Session::get('return_path', '');
162                 Session::remove('return_path');
163
164                 $a->internalRedirect($return_path);
165         }
166
167         /**
168          * @brief Tries to auth the user from the cookie or session
169          *
170          * @todo Should be moved to Friendica\Core\Session when it's created
171          */
172         public static function sessionAuth()
173         {
174                 $a = self::getApp();
175
176                 // When the "Friendica" cookie is set, take the value to authenticate and renew the cookie.
177                 if (isset($_COOKIE["Friendica"])) {
178                         $data = json_decode($_COOKIE["Friendica"]);
179                         if (isset($data->uid)) {
180
181                                 $user = DBA::selectFirst(
182                                         'user',
183                                         [],
184                                         [
185                                                 'uid'             => $data->uid,
186                                                 'blocked'         => false,
187                                                 'account_expired' => false,
188                                                 'account_removed' => false,
189                                                 'verified'        => true,
190                                         ]
191                                 );
192                                 if (DBA::isResult($user)) {
193                                         // Time safe comparision of the two hashes.
194                                         $validSession = hash_equals(
195                                                 Authentication::getCookieHashForUser($user),
196                                                 $data->hash
197                                         );
198
199                                         if (!$validSession) {
200                                                 Logger::log("Hash for user " . $data->uid . " doesn't fit.");
201                                                 Authentication::deleteSession();
202                                                 $a->internalRedirect();
203                                         }
204
205                                         // Renew the cookie
206                                         // Expires after 7 days by default,
207                                         // can be set via system.auth_cookie_lifetime
208                                         $authcookiedays = Config::get('system', 'auth_cookie_lifetime', 7);
209                                         Authentication::setCookie($authcookiedays * 24 * 60 * 60, $user);
210
211                                         // Do the authentification if not done by now
212                                         if (!isset($_SESSION) || !isset($_SESSION['authenticated'])) {
213                                                 Session::setAuthenticatedForUser($a, $user);
214
215                                                 if (Config::get('system', 'paranoia')) {
216                                                         $_SESSION['addr'] = $data->ip;
217                                                 }
218                                         }
219                                 }
220                         }
221                 }
222
223                 if (!empty($_SESSION['authenticated'])) {
224                         if (!empty($_SESSION['visitor_id']) && empty($_SESSION['uid'])) {
225                                 $contact = DBA::selectFirst('contact', [], ['id' => $_SESSION['visitor_id']]);
226                                 if (DBA::isResult($contact)) {
227                                         self::getApp()->contact = $contact;
228                                 }
229                         }
230
231                         if (!empty($_SESSION['uid'])) {
232                                 // already logged in user returning
233                                 $check = Config::get('system', 'paranoia');
234                                 // extra paranoia - if the IP changed, log them out
235                                 if ($check && ($_SESSION['addr'] != $_SERVER['REMOTE_ADDR'])) {
236                                         Logger::log('Session address changed. Paranoid setting in effect, blocking session. ' .
237                                                 $_SESSION['addr'] . ' != ' . $_SERVER['REMOTE_ADDR']);
238                                         Authentication::deleteSession();
239                                         $a->internalRedirect();
240                                 }
241
242                                 $user = DBA::selectFirst(
243                                         'user',
244                                         [],
245                                         [
246                                                 'uid'             => $_SESSION['uid'],
247                                                 'blocked'         => false,
248                                                 'account_expired' => false,
249                                                 'account_removed' => false,
250                                                 'verified'        => true,
251                                         ]
252                                 );
253                                 if (!DBA::isResult($user)) {
254                                         Authentication::deleteSession();
255                                         $a->internalRedirect();
256                                 }
257
258                                 // Make sure to refresh the last login time for the user if the user
259                                 // stays logged in for a long time, e.g. with "Remember Me"
260                                 $login_refresh = false;
261                                 if (empty($_SESSION['last_login_date'])) {
262                                         $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
263                                 }
264                                 if (strcmp(DateTimeFormat::utc('now - 12 hours'), $_SESSION['last_login_date']) > 0) {
265                                         $_SESSION['last_login_date'] = DateTimeFormat::utcNow();
266                                         $login_refresh = true;
267                                 }
268
269                                 Session::setAuthenticatedForUser($a, $user, false, false, $login_refresh);
270                         }
271                 }
272         }
273
274         /**
275          * @brief Wrapper for adding a login box.
276          *
277          * @param string $return_path  The path relative to the base the user should be sent
278          *                             back to after login completes
279          * @param bool   $register     If $register == true provide a registration link.
280          *                             This will most always depend on the value of config.register_policy.
281          * @param array  $hiddens      optional
282          *
283          * @return string Returns the complete html for inserting into the page
284          *
285          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
286          * @hooks 'login_hook' string $o
287          */
288         public static function form($return_path = null, $register = false, $hiddens = [])
289         {
290                 $a = self::getApp();
291                 $o = '';
292                 $reg = false;
293                 if ($register && intval($a->getConfig()->get('config', 'register_policy')) !== Register::CLOSED) {
294                         $reg = [
295                                 'title' => L10n::t('Create a New Account'),
296                                 'desc' => L10n::t('Register')
297                         ];
298                 }
299
300                 $noid = Config::get('system', 'no_openid');
301
302                 if (is_null($return_path)) {
303                         $return_path = $a->query_string;
304                 }
305
306                 if (local_user()) {
307                         $tpl = Renderer::getMarkupTemplate('logout.tpl');
308                 } else {
309                         $a->page['htmlhead'] .= Renderer::replaceMacros(
310                                 Renderer::getMarkupTemplate('login_head.tpl'),
311                                 [
312                                         '$baseurl' => $a->getBaseURL(true)
313                                 ]
314                         );
315
316                         $tpl = Renderer::getMarkupTemplate('login.tpl');
317                         $_SESSION['return_path'] = $return_path;
318                 }
319
320                 $o .= Renderer::replaceMacros(
321                         $tpl,
322                         [
323                                 '$dest_url'     => self::getApp()->getBaseURL(true) . '/login',
324                                 '$logout'       => L10n::t('Logout'),
325                                 '$login'        => L10n::t('Login'),
326
327                                 '$lname'        => ['username', L10n::t('Nickname or Email: '), '', ''],
328                                 '$lpassword'    => ['password', L10n::t('Password: '), '', ''],
329                                 '$lremember'    => ['remember', L10n::t('Remember me'), 0,  ''],
330
331                                 '$openid'       => !$noid,
332                                 '$lopenid'      => ['openid_url', L10n::t('Or login using OpenID: '), '', ''],
333
334                                 '$hiddens'      => $hiddens,
335
336                                 '$register'     => $reg,
337
338                                 '$lostpass'     => L10n::t('Forgot your password?'),
339                                 '$lostlink'     => L10n::t('Password Reset'),
340
341                                 '$tostitle'     => L10n::t('Website Terms of Service'),
342                                 '$toslink'      => L10n::t('terms of service'),
343
344                                 '$privacytitle' => L10n::t('Website Privacy Policy'),
345                                 '$privacylink'  => L10n::t('privacy policy'),
346                         ]
347                 );
348
349                 Hook::callAll('login_hook', $o);
350
351                 return $o;
352         }
353 }