[BUGFIX] Revert "[TASK] Use a 401 header if login is not successful"
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Authentication / AbstractUserAuthentication.php
1 <?php
2 namespace TYPO3\CMS\Core\Authentication;
3
4 /***************************************************************
5 * Copyright notice
6 *
7 * (c) 1999-2013 Kasper Skårhøj (kasperYYYY@typo3.com)
8 * All rights reserved
9 *
10 * This script is part of the TYPO3 project. The TYPO3 project is
11 * free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
15 *
16 * The GNU General Public License can be found at
17 * http://www.gnu.org/copyleft/gpl.html.
18 * A copy is found in the text file GPL.txt and important notices to the license
19 * from the author is found in LICENSE.txt distributed with these scripts.
20 *
21 *
22 * This script is distributed in the hope that it will be useful,
23 * but WITHOUT ANY WARRANTY; without even the implied warranty of
24 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 * GNU General Public License for more details.
26 *
27 * This copyright notice MUST APPEAR in all copies of the script!
28 ***************************************************************/
29
30 use TYPO3\CMS\Core\Utility\GeneralUtility;
31
32 /**
33 * Authentication of users in TYPO3
34 *
35 * This class is used to authenticate a login user.
36 * The class is used by both the frontend and backend.
37 * In both cases this class is a parent class to beuserauth and feuserauth
38 *
39 * See Inside TYPO3 for more information about the API of the class and internal variables.
40 *
41 * @author Kasper Skårhøj <kasperYYYY@typo3.com>
42 * @author René Fritz <r.fritz@colorcube.de>
43 */
44 abstract class AbstractUserAuthentication {
45
46 // Which global database to connect to
47 /**
48 * @todo Define visibility
49 */
50 public $global_database = '';
51
52 // Table to use for session data.
53 /**
54 * @todo Define visibility
55 */
56 public $session_table = '';
57
58 // Session/Cookie name
59 /**
60 * @todo Define visibility
61 */
62 public $name = '';
63
64 // Session/GET-var name
65 /**
66 * @todo Define visibility
67 */
68 public $get_name = '';
69
70 // Table in database with userdata
71 /**
72 * @todo Define visibility
73 */
74 public $user_table = '';
75
76 // Column for login-name
77 /**
78 * @todo Define visibility
79 */
80 public $username_column = '';
81
82 // Column for password
83 /**
84 * @todo Define visibility
85 */
86 public $userident_column = '';
87
88 // Column for user-id
89 /**
90 * @todo Define visibility
91 */
92 public $userid_column = '';
93
94 /**
95 * @todo Define visibility
96 */
97 public $lastLogin_column = '';
98
99 /**
100 * @todo Define visibility
101 */
102 public $enablecolumns = array(
103 'rootLevel' => '',
104 // Boolean: If TRUE, 'AND pid=0' will be a part of the query...
105 'disabled' => '',
106 'starttime' => '',
107 'endtime' => '',
108 'deleted' => ''
109 );
110
111 // Formfield with login-name
112 /**
113 * @todo Define visibility
114 */
115 public $formfield_uname = '';
116
117 // Formfield with password
118 /**
119 * @todo Define visibility
120 */
121 public $formfield_uident = '';
122
123 // Formfield with a unique value which is used to encrypt the password and username
124 /**
125 * @todo Define visibility
126 */
127 public $formfield_chalvalue = '';
128
129 // Formfield with status: *'login', 'logout'. If empty login is not verified.
130 /**
131 * @todo Define visibility
132 */
133 public $formfield_status = '';
134
135 /**
136 * Sets the level of security. *'normal' = clear-text. 'challenged' = hashed password/username.
137 * from form in $formfield_uident. 'superchallenged' = hashed password hashed again with username.
138 *
139 * @var string
140 * @deprecated since 4.7 will be removed in 6.1
141 */
142 public $security_level = 'normal';
143
144 // Server session lifetime. If > 0: session-timeout in seconds. If FALSE or
145 // <0: no timeout. If string: The string is a fieldname from the usertable
146 // where the timeout can be found.
147 /**
148 * @todo Define visibility
149 */
150 public $auth_timeout_field = 0;
151
152 // Client session lifetime. 0 = Session-cookies. If session-cookies, the
153 // browser will stop the session when the browser is closed. Otherwise this
154 // specifies the lifetime of a cookie that keeps the session.
155 /**
156 * @todo Define visibility
157 */
158 public $lifetime = 0;
159
160 // GarbageCollection. Purge all server session data older than $gc_time seconds.
161 // 0 = default to $this->timeout or use 86400 seconds (1 day) if $this->lifetime
162 // is 0
163 /**
164 * @todo Define visibility
165 */
166 public $gc_time = 0;
167
168 // Possibility (in percent) for GarbageCollection to be run.
169 /**
170 * @todo Define visibility
171 */
172 public $gc_probability = 1;
173
174 // Decides if the writelog() function is called at login and logout
175 /**
176 * @todo Define visibility
177 */
178 public $writeStdLog = FALSE;
179
180 // If the writelog() functions is called if a login-attempt has be tried
181 // without success
182 /**
183 * @todo Define visibility
184 */
185 public $writeAttemptLog = FALSE;
186
187 // If this is set, headers is sent to assure, caching is NOT done
188 /**
189 * @todo Define visibility
190 */
191 public $sendNoCacheHeaders = TRUE;
192
193 // If this is set, authentication is also accepted by the $_GET.
194 // Notice that the identification is NOT 128bit MD5 hash but reduced.
195 // This is done in order to minimize the size for mobile-devices, such as WAP-phones
196 /**
197 * @todo Define visibility
198 */
199 public $getFallBack = FALSE;
200
201 // The ident-hash is normally 32 characters and should be! But if you are making
202 // sites for WAP-devices og other lowbandwidth stuff, you may shorten the length.
203 // Never let this value drop below 6. A length of 6 would give you more than
204 // 16 mio possibilities.
205 /**
206 * @todo Define visibility
207 */
208 public $hash_length = 32;
209
210 // Setting this flag TRUE lets user-authetication happen from GET_VARS if
211 // POST_VARS are not set. Thus you may supply username/password from the URL.
212 /**
213 * @todo Define visibility
214 */
215 public $getMethodEnabled = FALSE;
216
217 // If set, will lock the session to the users IP address (all four numbers.
218 // Reducing to 1-3 means that only first,
219 // second or third part of the IP address is used).
220 /**
221 * @todo Define visibility
222 */
223 public $lockIP = 4;
224
225 // Keyword list (commalist with no spaces!): "useragent".
226 // Each keyword indicates some information that can be included in
227 // a integer hash made to lock down usersessions. Configurable through
228 // $GLOBALS['TYPO3_CONF_VARS'][TYPO3_MODE]['lockHashKeyWords']
229 /**
230 * @todo Define visibility
231 */
232 public $lockHashKeyWords = 'useragent';
233
234 // warning -emailaddress:
235 /**
236 * @todo Define visibility
237 */
238 public $warningEmail = '';
239
240 // Period back in time (in seconds) in which number of failed logins are collected
241 /**
242 * @todo Define visibility
243 */
244 public $warningPeriod = 3600;
245
246 // The maximum accepted number of warnings before an email is sent
247 /**
248 * @todo Define visibility
249 */
250 public $warningMax = 3;
251
252 // If set, the user-record must $checkPid_value as pid
253 /**
254 * @todo Define visibility
255 */
256 public $checkPid = TRUE;
257
258 // The pid, the user-record must have as page-id
259 /**
260 * @todo Define visibility
261 */
262 public $checkPid_value = 0;
263
264 // Internals
265 // Internal: Will contain session_id (MD5-hash)
266 /**
267 * @todo Define visibility
268 */
269 public $id;
270
271 // Internal: Will contain the session_id gotten from cookie or GET method.
272 // This is used in statistics as a reliable cookie (one which is known
273 // to come from $_COOKIE).
274 /**
275 * @todo Define visibility
276 * @deprecated since TYPO3 CMS 6.2, remove two versions later, use $this->isCookieSet() instead
277 */
278 public $cookieId;
279
280 // Indicates if an authentication was started but failed
281 /**
282 * @todo Define visibility
283 */
284 public $loginFailure = FALSE;
285
286 // Will be set to TRUE if the login session is actually written during auth-check.
287 /**
288 * @todo Define visibility
289 */
290 public $loginSessionStarted = FALSE;
291
292 /**
293 * @var array|NULL contains user- AND session-data from database (joined tables)
294 * @todo Define visibility
295 * @internal
296 */
297 public $user = NULL;
298
299 // Internal: Will will be set to the url--ready (eg. '&login=ab7ef8d...')
300 //GET-auth-var if getFallBack is TRUE. Should be inserted in links!
301 /**
302 * @todo Define visibility
303 */
304 public $get_URL_ID = '';
305
306 // Will be set to TRUE if a new session ID was created
307 /**
308 * @todo Define visibility
309 */
310 public $newSessionID = FALSE;
311
312 // Will force the session cookie to be set every time (lifetime must be 0)
313 /**
314 * @todo Define visibility
315 */
316 public $forceSetCookie = FALSE;
317
318 /**
319 * Will prevent the setting of the session cookie (takes precedence over forceSetCookie)
320 * @var bool
321 * @todo Define visibility
322 */
323 public $dontSetCookie = FALSE;
324
325 /**
326 * is set to know on this current request if a cookie was set
327 * @var bool
328 */
329 protected $cookieWasSetOnCurrentRequest = FALSE;
330
331 // If set, the challenge value will be stored in a session as well so the
332 // server can check that is was not forged.
333 /**
334 * @todo Define visibility
335 */
336 public $challengeStoredInCookie = FALSE;
337
338 // Login type, used for services.
339 /**
340 * @todo Define visibility
341 */
342 public $loginType = '';
343
344 // "auth" services configuration array from $GLOBALS['TYPO3_CONF_VARS']['SVCONF']['auth']
345 /**
346 * @todo Define visibility
347 */
348 public $svConfig = array();
349
350 // Write messages into the devlog?
351 /**
352 * @todo Define visibility
353 */
354 public $writeDevLog = FALSE;
355
356 /**
357 * Starts a user session
358 * Typical configurations will:
359 * a) check if session cookie was set and if not, set one,
360 * b) check if a password/username was sent and if so, try to authenticate the user
361 * c) Lookup a session attached to a user and check timeout etc.
362 * d) Garbage collection, setting of no-cache headers.
363 * If a user is authenticated the database record of the user (array) will be set in the ->user internal variable.
364 *
365 * @return void
366 * @todo Define visibility
367 */
368 public function start() {
369 // Backend or frontend login - used for auth services
370 if (empty($this->loginType)) {
371 throw new \TYPO3\CMS\Core\Exception('No loginType defined, should be set explicitly by subclass');
372 }
373 // Set level to normal if not already set
374 if (!$this->security_level) {
375 // Notice: cannot use TYPO3_MODE here because BE user can be logged in and operate inside FE!
376 $this->security_level = trim($GLOBALS['TYPO3_CONF_VARS'][$this->loginType]['loginSecurityLevel']);
377 if (!$this->security_level) {
378 $this->security_level = 'normal';
379 }
380 }
381 // Enable dev logging if set
382 if ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['writeDevLog']) {
383 $this->writeDevLog = TRUE;
384 }
385 if ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['writeDevLog' . $this->loginType]) {
386 $this->writeDevLog = TRUE;
387 }
388 if (TYPO3_DLOG) {
389 $this->writeDevLog = TRUE;
390 }
391 if ($this->writeDevLog) {
392 GeneralUtility::devLog('## Beginning of auth logging.', 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication');
393 }
394 // Init vars.
395 $mode = '';
396 $this->newSessionID = FALSE;
397 // $id is set to ses_id if cookie is present. Else set to FALSE, which will start a new session
398 $id = $this->getCookie($this->name);
399 $this->svConfig = $GLOBALS['TYPO3_CONF_VARS']['SVCONF']['auth'];
400
401 // If fallback to get mode....
402 if (!$id && $this->getFallBack && $this->get_name) {
403 $id = isset($_GET[$this->get_name]) ? GeneralUtility::_GET($this->get_name) : '';
404 if (strlen($id) != $this->hash_length) {
405 $id = '';
406 }
407 $mode = 'get';
408 }
409
410 // If new session or client tries to fix session...
411 if (!$id || !$this->isExistingSessionRecord($id)) {
412 // New random session-$id is made
413 $id = $this->createSessionId();
414 // New session
415 $this->newSessionID = TRUE;
416 }
417 // Internal var 'id' is set
418 $this->id = $id;
419 // If fallback to get mode....
420 if ($mode == 'get' && $this->getFallBack && $this->get_name) {
421 $this->get_URL_ID = '&' . $this->get_name . '=' . $id;
422 }
423 // Set session hashKey lock keywords from configuration; currently only 'useragent' can be used.
424 $this->lockHashKeyWords = $GLOBALS['TYPO3_CONF_VARS'][$this->loginType]['lockHashKeyWords'];
425 // Make certain that NO user is set initially
426 $this->user = NULL;
427 // Set all possible headers that could ensure that the script is not cached on the client-side
428 if ($this->sendNoCacheHeaders) {
429 header('Expires: 0');
430 header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
431 $cacheControlHeader = 'no-cache, must-revalidate';
432 $pragmaHeader = 'no-cache';
433 // Prevent error message in IE when using a https connection
434 // see http://forge.typo3.org/issues/24125
435 $clientInfo = GeneralUtility::clientInfo();
436 if ($clientInfo['BROWSER'] === 'msie' && GeneralUtility::getIndpEnv('TYPO3_SSL')) {
437 // Some IEs can not handle no-cache
438 // see http://support.microsoft.com/kb/323308/en-us
439 $cacheControlHeader = 'must-revalidate';
440 // IE needs "Pragma: private" if SSL connection
441 $pragmaHeader = 'private';
442 }
443 header('Cache-Control: ' . $cacheControlHeader);
444 header('Pragma: ' . $pragmaHeader);
445 }
446 // Load user session, check to see if anyone has submitted login-information and if so authenticate
447 // the user with the session. $this->user[uid] may be used to write log...
448 $this->checkAuthentication();
449 // Setting cookies
450 if (!$this->dontSetCookie) {
451 $this->setSessionCookie();
452 }
453 // Hook for alternative ways of filling the $this->user array (is used by the "timtaw" extension)
454 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['postUserLookUp'])) {
455 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['postUserLookUp'] as $funcName) {
456 $_params = array(
457 'pObj' => &$this
458 );
459 GeneralUtility::callUserFunction($funcName, $_params, $this);
460 }
461 }
462 // Set $this->gc_time if not explicitely specified
463 if ($this->gc_time == 0) {
464 // Default to 1 day if $this->auth_timeout_field is 0
465 $this->gc_time = $this->auth_timeout_field == 0 ? 86400 : $this->auth_timeout_field;
466 }
467 // If we're lucky we'll get to clean up old sessions....
468 if (rand() % 100 <= $this->gc_probability) {
469 $this->gc();
470 }
471 }
472
473 /**
474 * Sets the session cookie for the current disposal.
475 *
476 * @return void
477 * @throws \TYPO3\CMS\Core\Exception
478 */
479 protected function setSessionCookie() {
480 $isSetSessionCookie = $this->isSetSessionCookie();
481 $isRefreshTimeBasedCookie = $this->isRefreshTimeBasedCookie();
482 if ($isSetSessionCookie || $isRefreshTimeBasedCookie) {
483 $settings = $GLOBALS['TYPO3_CONF_VARS']['SYS'];
484 // Get the domain to be used for the cookie (if any):
485 $cookieDomain = $this->getCookieDomain();
486 // If no cookie domain is set, use the base path:
487 $cookiePath = $cookieDomain ? '/' : GeneralUtility::getIndpEnv('TYPO3_SITE_PATH');
488 // If the cookie lifetime is set, use it:
489 $cookieExpire = $isRefreshTimeBasedCookie ? $GLOBALS['EXEC_TIME'] + $this->lifetime : 0;
490 // Use the secure option when the current request is served by a secure connection:
491 $cookieSecure = (bool) $settings['cookieSecure'] && GeneralUtility::getIndpEnv('TYPO3_SSL');
492 // Deliver cookies only via HTTP and prevent possible XSS by JavaScript:
493 $cookieHttpOnly = (bool) $settings['cookieHttpOnly'];
494 // Do not set cookie if cookieSecure is set to "1" (force HTTPS) and no secure channel is used:
495 if ((int)$settings['cookieSecure'] !== 1 || GeneralUtility::getIndpEnv('TYPO3_SSL')) {
496 setcookie($this->name, $this->id, $cookieExpire, $cookiePath, $cookieDomain, $cookieSecure, $cookieHttpOnly);
497 $this->cookieWasSetOnCurrentRequest = TRUE;
498 } else {
499 throw new \TYPO3\CMS\Core\Exception('Cookie was not set since HTTPS was forced in $TYPO3_CONF_VARS[SYS][cookieSecure].', 1254325546);
500 }
501 if ($this->writeDevLog) {
502 $devLogMessage = ($isRefreshTimeBasedCookie ? 'Updated Cookie: ' : 'Set Cookie: ') . $this->id;
503 GeneralUtility::devLog($devLogMessage . ($cookieDomain ? ', ' . $cookieDomain : ''), 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication');
504 }
505 }
506 }
507
508 /**
509 * Gets the domain to be used on setting cookies.
510 * The information is taken from the value in $GLOBALS['TYPO3_CONF_VARS']['SYS']['cookieDomain'].
511 *
512 * @return string The domain to be used on setting cookies
513 */
514 protected function getCookieDomain() {
515 $result = '';
516 $cookieDomain = $GLOBALS['TYPO3_CONF_VARS']['SYS']['cookieDomain'];
517 // If a specific cookie domain is defined for a given TYPO3_MODE,
518 // use that domain
519 if (!empty($GLOBALS['TYPO3_CONF_VARS'][$this->loginType]['cookieDomain'])) {
520 $cookieDomain = $GLOBALS['TYPO3_CONF_VARS'][$this->loginType]['cookieDomain'];
521 }
522 if ($cookieDomain) {
523 if ($cookieDomain[0] == '/') {
524 $match = array();
525 $matchCnt = @preg_match($cookieDomain, GeneralUtility::getIndpEnv('TYPO3_HOST_ONLY'), $match);
526 if ($matchCnt === FALSE) {
527 GeneralUtility::sysLog('The regular expression for the cookie domain (' . $cookieDomain . ') contains errors. The session is not shared across sub-domains.', 'Core', GeneralUtility::SYSLOG_SEVERITY_ERROR);
528 } elseif ($matchCnt) {
529 $result = $match[0];
530 }
531 } else {
532 $result = $cookieDomain;
533 }
534 }
535 return $result;
536 }
537
538 /**
539 * Get the value of a specified cookie.
540 *
541 * Uses HTTP_COOKIE, if available, to avoid a IE8 bug where multiple
542 * cookies with the same name might be returned if the user accessed
543 * the site without "www." first and switched to "www." later:
544 * Cookie: fe_typo_user=AAA; fe_typo_user=BBB
545 * In this case PHP will set _COOKIE as the first cookie, when we
546 * would need the last one (which is what this function then returns).
547 *
548 * @param string $cookieName The cookie ID
549 * @return string The value stored in the cookie
550 */
551 protected function getCookie($cookieName) {
552 $cookieValue = '';
553 if (isset($_SERVER['HTTP_COOKIE'])) {
554 $cookies = GeneralUtility::trimExplode(';', $_SERVER['HTTP_COOKIE']);
555 foreach ($cookies as $cookie) {
556 list($name, $value) = GeneralUtility::trimExplode('=', $cookie);
557 if (trim($name) === (string)$cookieName) {
558 // Use the last one
559 $cookieValue = urldecode($value);
560 }
561 }
562 } else {
563 // Fallback if there is no HTTP_COOKIE, use original method:
564 $cookieValue = isset($_COOKIE[$cookieName]) ? stripslashes($_COOKIE[$cookieName]) : '';
565 }
566 return $cookieValue;
567 }
568
569 /**
570 * Determine whether a session cookie needs to be set (lifetime=0)
571 *
572 * @return boolean
573 * @internal
574 * @todo Define visibility
575 */
576 public function isSetSessionCookie() {
577 return ($this->newSessionID || $this->forceSetCookie) && $this->lifetime == 0;
578 }
579
580 /**
581 * Determine whether a non-session cookie needs to be set (lifetime>0)
582 *
583 * @return boolean
584 * @internal
585 * @todo Define visibility
586 */
587 public function isRefreshTimeBasedCookie() {
588 return $this->lifetime > 0;
589 }
590
591 /**
592 * Checks if a submission of username and password is present or use other authentication by auth services
593 *
594 * @return void
595 * @internal
596 * @todo Define visibility
597 */
598 public function checkAuthentication() {
599 // No user for now - will be searched by service below
600 $tempuserArr = array();
601 $tempuser = FALSE;
602 // User is not authenticated by default
603 $authenticated = FALSE;
604 // User want to login with passed login data (name/password)
605 $activeLogin = FALSE;
606 // Indicates if an active authentication failed (not auto login)
607 $this->loginFailure = FALSE;
608 if ($this->writeDevLog) {
609 GeneralUtility::devLog('Login type: ' . $this->loginType, 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication');
610 }
611 // The info array provide additional information for auth services
612 $authInfo = $this->getAuthInfoArray();
613 // Get Login/Logout data submitted by a form or params
614 $loginData = $this->getLoginFormData();
615 if ($this->writeDevLog) {
616 GeneralUtility::devLog('Login data: ' . GeneralUtility::arrayToLogString($loginData), 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication');
617 }
618 // Active logout (eg. with "logout" button)
619 if ($loginData['status'] == 'logout') {
620 if ($this->writeStdLog) {
621 // $type,$action,$error,$details_nr,$details,$data,$tablename,$recuid,$recpid
622 $this->writelog(255, 2, 0, 2, 'User %s logged out', array($this->user['username']), '', 0, 0);
623 }
624 // Logout written to log
625 if ($this->writeDevLog) {
626 GeneralUtility::devLog('User logged out. Id: ' . $this->id, 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication', -1);
627 }
628 $this->logoff();
629 }
630 // Active login (eg. with login form)
631 if ($loginData['status'] == 'login') {
632 $activeLogin = TRUE;
633 if ($this->writeDevLog) {
634 GeneralUtility::devLog('Active login (eg. with login form)', 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication');
635 }
636 // check referer for submitted login values
637 if ($this->formfield_status && $loginData['uident'] && $loginData['uname']) {
638 $httpHost = GeneralUtility::getIndpEnv('TYPO3_HOST_ONLY');
639 if (!$this->getMethodEnabled && ($httpHost != $authInfo['refInfo']['host'] && !$GLOBALS['TYPO3_CONF_VARS']['SYS']['doNotCheckReferer'])) {
640 throw new \RuntimeException('TYPO3 Fatal Error: Error: This host address ("' . $httpHost . '") and the referer host ("' . $authInfo['refInfo']['host'] . '") mismatches!<br />
641 It\'s possible that the environment variable HTTP_REFERER is not passed to the script because of a proxy.<br />
642 The site administrator can disable this check in the "All Configuration" section of the Install Tool (flag: TYPO3_CONF_VARS[SYS][doNotCheckReferer]).', 1270853930);
643 }
644 // Delete old user session if any
645 $this->logoff();
646 }
647 // Refuse login for _CLI users, if not processing a CLI request type
648 // (although we shouldn't be here in case of a CLI request type)
649 if (strtoupper(substr($loginData['uname'], 0, 5)) == '_CLI_' && !(TYPO3_REQUESTTYPE & TYPO3_REQUESTTYPE_CLI)) {
650 throw new \RuntimeException('TYPO3 Fatal Error: You have tried to login using a CLI user. Access prohibited!', 1270853931);
651 }
652 }
653 // The following code makes auto-login possible (if configured). No submitted data needed
654 // Determine whether we need to skip session update.
655 // This is used mainly for checking session timeout without
656 // refreshing the session itself while checking.
657 if (GeneralUtility::_GP('skipSessionUpdate')) {
658 $skipSessionUpdate = TRUE;
659 } else {
660 $skipSessionUpdate = FALSE;
661 }
662 $haveSession = FALSE;
663 if (!$this->newSessionID) {
664 // Read user session
665 $authInfo['userSession'] = $this->fetchUserSession($skipSessionUpdate);
666 $haveSession = is_array($authInfo['userSession']) ? TRUE : FALSE;
667 }
668 if ($this->writeDevLog) {
669 if ($haveSession) {
670 GeneralUtility::devLog('User session found: ' . GeneralUtility::arrayToLogString($authInfo['userSession'], array($this->userid_column, $this->username_column)), 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication', 0);
671 } else {
672 GeneralUtility::devLog('No user session found.', 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication', 2);
673 }
674 if (is_array($this->svConfig['setup'])) {
675 GeneralUtility::devLog('SV setup: ' . GeneralUtility::arrayToLogString($this->svConfig['setup']), 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication', 0);
676 }
677 }
678 // Fetch user if ...
679 if ($activeLogin || !$haveSession && $this->svConfig['setup'][$this->loginType . '_fetchUserIfNoSession'] || $this->svConfig['setup'][$this->loginType . '_alwaysFetchUser']) {
680 // Use 'auth' service to find the user
681 // First found user will be used
682 $serviceChain = '';
683 $subType = 'getUser' . $this->loginType;
684 while (is_object($serviceObj = GeneralUtility::makeInstanceService('auth', $subType, $serviceChain))) {
685 $serviceChain .= ',' . $serviceObj->getServiceKey();
686 $serviceObj->initAuth($subType, $loginData, $authInfo, $this);
687 if ($row = $serviceObj->getUser()) {
688 $tempuserArr[] = $row;
689 if ($this->writeDevLog) {
690 GeneralUtility::devLog('User found: ' . GeneralUtility::arrayToLogString($row, array($this->userid_column, $this->username_column)), 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication', 0);
691 }
692 // User found, just stop to search for more if not configured to go on
693 if (!$this->svConfig['setup'][($this->loginType . '_fetchAllUsers')]) {
694 break;
695 }
696 }
697 unset($serviceObj);
698 }
699 unset($serviceObj);
700 if ($this->writeDevLog && $this->svConfig['setup'][$this->loginType . '_alwaysFetchUser']) {
701 GeneralUtility::devLog($this->loginType . '_alwaysFetchUser option is enabled', 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication');
702 }
703 if ($this->writeDevLog && $serviceChain) {
704 GeneralUtility::devLog($subType . ' auth services called: ' . $serviceChain, 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication');
705 }
706 if ($this->writeDevLog && !count($tempuserArr)) {
707 GeneralUtility::devLog('No user found by services', 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication');
708 }
709 if ($this->writeDevLog && count($tempuserArr)) {
710 GeneralUtility::devLog(count($tempuserArr) . ' user records found by services', 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication');
711 }
712 }
713 // If no new user was set we use the already found user session
714 if (!count($tempuserArr) && $haveSession) {
715 $tempuserArr[] = $authInfo['userSession'];
716 $tempuser = $authInfo['userSession'];
717 // User is authenticated because we found a user session
718 $authenticated = TRUE;
719 if ($this->writeDevLog) {
720 GeneralUtility::devLog('User session used: ' . GeneralUtility::arrayToLogString($authInfo['userSession'], array($this->userid_column, $this->username_column)), 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication');
721 }
722 }
723 // Re-auth user when 'auth'-service option is set
724 if ($this->svConfig['setup'][$this->loginType . '_alwaysAuthUser']) {
725 $authenticated = FALSE;
726 if ($this->writeDevLog) {
727 GeneralUtility::devLog('alwaysAuthUser option is enabled', 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication');
728 }
729 }
730 // Authenticate the user if needed
731 if (count($tempuserArr) && !$authenticated) {
732 foreach ($tempuserArr as $tempuser) {
733 // Use 'auth' service to authenticate the user
734 // If one service returns FALSE then authentication failed
735 // a service might return 100 which means there's no reason to stop but the user can't be authenticated by that service
736 if ($this->writeDevLog) {
737 GeneralUtility::devLog('Auth user: ' . GeneralUtility::arrayToLogString($tempuser), 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication');
738 }
739 $serviceChain = '';
740 $subType = 'authUser' . $this->loginType;
741 while (is_object($serviceObj = GeneralUtility::makeInstanceService('auth', $subType, $serviceChain))) {
742 $serviceChain .= ',' . $serviceObj->getServiceKey();
743 $serviceObj->initAuth($subType, $loginData, $authInfo, $this);
744 if (($ret = $serviceObj->authUser($tempuser)) > 0) {
745 // If the service returns >=200 then no more checking is needed - useful for IP checking without password
746 if ((int)$ret >= 200) {
747 $authenticated = TRUE;
748 break;
749 } elseif ((int)$ret >= 100) {
750
751 } else {
752 $authenticated = TRUE;
753 }
754 } else {
755 $authenticated = FALSE;
756 break;
757 }
758 unset($serviceObj);
759 }
760 unset($serviceObj);
761 if ($this->writeDevLog && $serviceChain) {
762 GeneralUtility::devLog($subType . ' auth services called: ' . $serviceChain, 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication');
763 }
764 if ($authenticated) {
765 // Leave foreach() because a user is authenticated
766 break;
767 }
768 }
769 }
770 // If user is authenticated a valid user is in $tempuser
771 if ($authenticated) {
772 // Reset failure flag
773 $this->loginFailure = FALSE;
774 // Insert session record if needed:
775 if (!($haveSession && ($tempuser['ses_id'] == $this->id || $tempuser['uid'] == $authInfo['userSession']['ses_userid']))) {
776 $sessionData = $this->createUserSession($tempuser);
777 if ($sessionData) {
778 $this->user = array_merge(
779 $tempuser,
780 $sessionData
781 );
782 }
783 // The login session is started.
784 $this->loginSessionStarted = TRUE;
785 if ($this->writeDevLog && is_array($this->user)) {
786 GeneralUtility::devLog('User session finally read: ' . GeneralUtility::arrayToLogString($this->user, array($this->userid_column, $this->username_column)), 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication', -1);
787 }
788 } elseif ($haveSession) {
789 $this->user = $authInfo['userSession'];
790 }
791 // User logged in - write that to the log!
792 if ($this->writeStdLog && $activeLogin) {
793 $this->writelog(255, 1, 0, 1, 'User %s logged in from %s (%s)', array($tempuser[$this->username_column], GeneralUtility::getIndpEnv('REMOTE_ADDR'), GeneralUtility::getIndpEnv('REMOTE_HOST')), '', '', '', -1, '', $tempuser['uid']);
794 }
795 if ($this->writeDevLog && $activeLogin) {
796 GeneralUtility::devLog('User ' . $tempuser[$this->username_column] . ' logged in from ' . GeneralUtility::getIndpEnv('REMOTE_ADDR') . ' (' . GeneralUtility::getIndpEnv('REMOTE_HOST') . ')', 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication', -1);
797 }
798 if ($this->writeDevLog && !$activeLogin) {
799 GeneralUtility::devLog('User ' . $tempuser[$this->username_column] . ' authenticated from ' . GeneralUtility::getIndpEnv('REMOTE_ADDR') . ' (' . GeneralUtility::getIndpEnv('REMOTE_HOST') . ')', 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication', -1);
800 }
801 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['lockSSL'] == 3 && $this->user_table == 'be_users') {
802 $requestStr = substr(GeneralUtility::getIndpEnv('TYPO3_REQUEST_SCRIPT'), strlen(GeneralUtility::getIndpEnv('TYPO3_SITE_URL') . TYPO3_mainDir));
803 $backendScript = \TYPO3\CMS\Backend\Utility\BackendUtility::getBackendScript();
804 if ($requestStr == $backendScript && GeneralUtility::getIndpEnv('TYPO3_SSL')) {
805 list(, $url) = explode('://', GeneralUtility::getIndpEnv('TYPO3_SITE_URL'), 2);
806 list($server, $address) = explode('/', $url, 2);
807 if ((int)$GLOBALS['TYPO3_CONF_VARS']['BE']['lockSSLPort']) {
808 $sslPortSuffix = ':' . (int)$GLOBALS['TYPO3_CONF_VARS']['BE']['lockSSLPort'];
809 // strip port from server
810 $server = str_replace($sslPortSuffix, '', $server);
811 }
812 \TYPO3\CMS\Core\Utility\HttpUtility::redirect('http://' . $server . '/' . $address . TYPO3_mainDir . $backendScript);
813 }
814 }
815 } elseif ($activeLogin || count($tempuserArr)) {
816 $this->loginFailure = TRUE;
817 if ($this->writeDevLog && !count($tempuserArr) && $activeLogin) {
818 GeneralUtility::devLog('Login failed: ' . GeneralUtility::arrayToLogString($loginData), 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication', 2);
819 }
820 if ($this->writeDevLog && count($tempuserArr)) {
821 GeneralUtility::devLog('Login failed: ' . GeneralUtility::arrayToLogString($tempuser, array($this->userid_column, $this->username_column)), 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication', 2);
822 }
823 }
824 // If there were a login failure, check to see if a warning email should be sent:
825 if ($this->loginFailure && $activeLogin) {
826 if ($this->writeDevLog) {
827 GeneralUtility::devLog('Call checkLogFailures: ' . GeneralUtility::arrayToLogString(array('warningEmail' => $this->warningEmail, 'warningPeriod' => $this->warningPeriod, 'warningMax' => $this->warningMax)), 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication', -1);
828 }
829 $this->checkLogFailures($this->warningEmail, $this->warningPeriod, $this->warningMax);
830 }
831 }
832
833 /**
834 * Creates a new session ID.
835 *
836 * @return string The new session ID
837 */
838 public function createSessionId() {
839 return GeneralUtility::getRandomHexString($this->hash_length);
840 }
841
842 /*************************
843 *
844 * User Sessions
845 *
846 *************************/
847 /**
848 * Creates a user session record and returns its values.
849 *
850 * @param array $tempuser User data array
851 *
852 * @return array The session data for the newly created session.
853 * @todo Define visibility
854 */
855 public function createUserSession($tempuser) {
856 if ($this->writeDevLog) {
857 GeneralUtility::devLog('Create session ses_id = ' . $this->id, 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication');
858 }
859 // Delete session entry first
860 $GLOBALS['TYPO3_DB']->exec_DELETEquery(
861 $this->session_table,
862 'ses_id = ' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->id, $this->session_table)
863 . ' AND ses_name = ' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->name, $this->session_table)
864 );
865 // Re-create session entry
866 $insertFields = $this->getNewSessionRecord($tempuser);
867 $inserted = (boolean) $GLOBALS['TYPO3_DB']->exec_INSERTquery($this->session_table, $insertFields);
868 if (!$inserted) {
869 $message = 'Session data could not be written to DB. Error: ' . $GLOBALS['TYPO3_DB']->sql_error();
870 GeneralUtility::sysLog($message, 'Core', GeneralUtility::SYSLOG_SEVERITY_WARNING);
871 if ($this->writeDevLog) {
872 GeneralUtility::devLog($message, 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication', 2);
873 }
874 }
875 // Updating lastLogin_column carrying information about last login.
876 if ($this->lastLogin_column && $inserted) {
877 $GLOBALS['TYPO3_DB']->exec_UPDATEquery(
878 $this->user_table,
879 $this->userid_column . '=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($tempuser[$this->userid_column], $this->user_table),
880 array($this->lastLogin_column => $GLOBALS['EXEC_TIME'])
881 );
882 }
883
884 return $inserted ? $insertFields : array();
885 }
886
887 /**
888 * Returns a new session record for the current user for insertion into the DB.
889 * This function is mainly there as a wrapper for inheriting classes to override it.
890 *
891 * @param array $tempuser
892 * @return array User session record
893 * @todo Define visibility
894 */
895 public function getNewSessionRecord($tempuser) {
896 return array(
897 'ses_id' => $this->id,
898 'ses_name' => $this->name,
899 'ses_iplock' => $tempuser['disableIPlock'] ? '[DISABLED]' : $this->ipLockClause_remoteIPNumber($this->lockIP),
900 'ses_hashlock' => $this->hashLockClause_getHashInt(),
901 'ses_userid' => $tempuser[$this->userid_column],
902 'ses_tstamp' => $GLOBALS['EXEC_TIME']
903 );
904 }
905
906 /**
907 * Read the user session from db.
908 *
909 * @param boolean $skipSessionUpdate
910 * @return array User session data
911 * @todo Define visibility
912 */
913 public function fetchUserSession($skipSessionUpdate = FALSE) {
914 $user = FALSE;
915 if ($this->writeDevLog) {
916 GeneralUtility::devLog('Fetch session ses_id = ' . $this->id, 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication');
917 }
918
919 // Fetch the user session from the DB
920 $statement = $this->fetchUserSessionFromDB();
921
922 if ($statement) {
923 $statement->execute();
924 $user = $statement->fetch();
925 $statement->free();
926 }
927 if ($user) {
928 // A user was found
929 if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($this->auth_timeout_field)) {
930 // Get timeout from object
931 $timeout = (int)$this->auth_timeout_field;
932 } else {
933 // Get timeout-time from usertable
934 $timeout = (int)$user[$this->auth_timeout_field];
935 }
936 // If timeout > 0 (TRUE) and currenttime has not exceeded the latest sessions-time plus the timeout in seconds then accept user
937 // Option later on: We could check that last update was at least x seconds ago in order not to update twice in a row if one script redirects to another...
938 if ($timeout > 0 && $GLOBALS['EXEC_TIME'] < $user['ses_tstamp'] + $timeout) {
939 if (!$skipSessionUpdate) {
940 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($this->session_table, 'ses_id=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->id, $this->session_table) . '
941 AND ses_name=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->name, $this->session_table), array('ses_tstamp' => $GLOBALS['EXEC_TIME']));
942 // Make sure that the timestamp is also updated in the array
943 $user['ses_tstamp'] = $GLOBALS['EXEC_TIME'];
944 }
945 } else {
946 // Delete any user set...
947 $this->logoff();
948 }
949 }
950 return $user;
951 }
952
953 /**
954 * Log out current user!
955 * Removes the current session record, sets the internal ->user array to a blank string; Thereby the current user (if any) is effectively logged out!
956 *
957 * @return void
958 * @todo Define visibility
959 */
960 public function logoff() {
961 if ($this->writeDevLog) {
962 GeneralUtility::devLog('logoff: ses_id = ' . $this->id, 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication');
963 }
964 // Release the locked records
965 \TYPO3\CMS\Backend\Utility\BackendUtility::lockRecords();
966 // Hook for pre-processing the logoff() method, requested and implemented by andreas.otto@dkd.de:
967 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['logoff_pre_processing'])) {
968 $_params = array();
969 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['logoff_pre_processing'] as $_funcRef) {
970 if ($_funcRef) {
971 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
972 }
973 }
974 }
975 $GLOBALS['TYPO3_DB']->exec_DELETEquery($this->session_table, 'ses_id = ' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->id, $this->session_table) . '
976 AND ses_name = ' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->name, $this->session_table));
977 $this->user = '';
978 // Hook for post-processing the logoff() method, requested and implemented by andreas.otto@dkd.de:
979 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['logoff_post_processing'])) {
980 $_params = array();
981 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['logoff_post_processing'] as $_funcRef) {
982 if ($_funcRef) {
983 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
984 }
985 }
986 }
987 }
988
989 /**
990 * Empty / unset the cookie
991 *
992 * @param string $cookieName usually, this is $this->name
993 * @return void
994 */
995 public function removeCookie($cookieName) {
996 $cookieDomain = $this->getCookieDomain();
997 // If no cookie domain is set, use the base path
998 $cookiePath = $cookieDomain ? '/' : GeneralUtility::getIndpEnv('TYPO3_SITE_PATH');
999 setcookie($cookieName, NULL, -1, $cookiePath, $cookieDomain);
1000 }
1001
1002 /**
1003 * Determine whether there's an according session record to a given session_id
1004 * in the database. Don't care if session record is still valid or not.
1005 *
1006 * @param integer $id Claimed Session ID
1007 * @return boolean Returns TRUE if a corresponding session was found in the database
1008 * @todo Define visibility
1009 */
1010 public function isExistingSessionRecord($id) {
1011 $statement = $GLOBALS['TYPO3_DB']->prepare_SELECTquery('COUNT(*)', $this->session_table, 'ses_id = :ses_id');
1012 $statement->execute(array(':ses_id' => $id));
1013 $row = $statement->fetch(\TYPO3\CMS\Core\Database\PreparedStatement::FETCH_NUM);
1014 $statement->free();
1015 return $row[0] ? TRUE : FALSE;
1016 }
1017
1018 /**
1019 * Returns whether this request is going to set a cookie
1020 * or a cookie was already found in the system
1021 * replaces the old functionality for "$this->cookieId"
1022 *
1023 * @return boolean Returns TRUE if a cookie is set
1024 */
1025 public function isCookieSet() {
1026 return $this->cookieWasSetOnCurrentRequest || $this->getCookie($this->name);
1027 }
1028
1029 /*************************
1030 *
1031 * SQL Functions
1032 *
1033 *************************/
1034 /**
1035 * The session_id is used to find user in the database.
1036 * Two tables are joined: The session-table with user_id of the session and the usertable with its primary key
1037 * if the client is flash (e.g. from a flash application inside TYPO3 that does a server request)
1038 * then don't evaluate with the hashLockClause, as the client/browser is included in this hash
1039 * and thus, the flash request would be rejected
1040 *
1041 * @return \TYPO3\CMS\Core\Database\PreparedStatement
1042 * @access private
1043 */
1044 protected function fetchUserSessionFromDB() {
1045 $statement = NULL;
1046 $ipLockClause = $this->ipLockClause();
1047 if ($GLOBALS['CLIENT']['BROWSER'] == 'flash') {
1048 // If on the flash client, the veri code is valid, then the user session is fetched
1049 // from the DB without the hashLock clause
1050 if (GeneralUtility::_GP('vC') == $this->veriCode()) {
1051 $statement = $GLOBALS['TYPO3_DB']->prepare_SELECTquery('*', $this->session_table . ',' . $this->user_table, $this->session_table . '.ses_id = :ses_id
1052 AND ' . $this->session_table . '.ses_name = :ses_name
1053 AND ' . $this->session_table . '.ses_userid = ' . $this->user_table . '.' . $this->userid_column . '
1054 ' . $ipLockClause['where'] . '
1055 ' . $this->user_where_clause());
1056 $statement->bindValues(array(
1057 ':ses_id' => $this->id,
1058 ':ses_name' => $this->name
1059 ));
1060 $statement->bindValues($ipLockClause['parameters']);
1061 }
1062 } else {
1063 $statement = $GLOBALS['TYPO3_DB']->prepare_SELECTquery('*', $this->session_table . ',' . $this->user_table, $this->session_table . '.ses_id = :ses_id
1064 AND ' . $this->session_table . '.ses_name = :ses_name
1065 AND ' . $this->session_table . '.ses_userid = ' . $this->user_table . '.' . $this->userid_column . '
1066 ' . $ipLockClause['where'] . '
1067 ' . $this->hashLockClause() . '
1068 ' . $this->user_where_clause());
1069 $statement->bindValues(array(
1070 ':ses_id' => $this->id,
1071 ':ses_name' => $this->name
1072 ));
1073 $statement->bindValues($ipLockClause['parameters']);
1074 }
1075 return $statement;
1076 }
1077
1078 /**
1079 * This returns the where-clause needed to select the user with respect flags like deleted, hidden, starttime, endtime
1080 *
1081 * @return string
1082 * @access private
1083 */
1084 protected function user_where_clause() {
1085 return ($this->enablecolumns['rootLevel'] ? 'AND ' . $this->user_table . '.pid=0 ' : '') . ($this->enablecolumns['disabled'] ? ' AND ' . $this->user_table . '.' . $this->enablecolumns['disabled'] . '=0' : '') . ($this->enablecolumns['deleted'] ? ' AND ' . $this->user_table . '.' . $this->enablecolumns['deleted'] . '=0' : '') . ($this->enablecolumns['starttime'] ? ' AND (' . $this->user_table . '.' . $this->enablecolumns['starttime'] . '<=' . $GLOBALS['EXEC_TIME'] . ')' : '') . ($this->enablecolumns['endtime'] ? ' AND (' . $this->user_table . '.' . $this->enablecolumns['endtime'] . '=0 OR ' . $this->user_table . '.' . $this->enablecolumns['endtime'] . '>' . $GLOBALS['EXEC_TIME'] . ')' : '');
1086 }
1087
1088 /**
1089 * This returns the where prepared statement-clause needed to lock a user to the IP address
1090 *
1091 * @return array
1092 * @access private
1093 */
1094 protected function ipLockClause() {
1095 $statementClause = array(
1096 'where' => '',
1097 'parameters' => array()
1098 );
1099 if ($this->lockIP) {
1100 $statementClause['where'] = 'AND (
1101 ' . $this->session_table . '.ses_iplock = :ses_iplock
1102 OR ' . $this->session_table . '.ses_iplock=\'[DISABLED]\'
1103 )';
1104 $statementClause['parameters'] = array(
1105 ':ses_iplock' => $this->ipLockClause_remoteIPNumber($this->lockIP)
1106 );
1107 }
1108 return $statementClause;
1109 }
1110
1111 /**
1112 * Returns the IP address to lock to.
1113 * The IP address may be partial based on $parts.
1114 *
1115 * @param integer $parts 1-4: Indicates how many parts of the IP address to return. 4 means all, 1 means only first number.
1116 * @return string (Partial) IP address for REMOTE_ADDR
1117 * @access private
1118 */
1119 protected function ipLockClause_remoteIPNumber($parts) {
1120 $IP = GeneralUtility::getIndpEnv('REMOTE_ADDR');
1121 if ($parts >= 4) {
1122 return $IP;
1123 } else {
1124 $parts = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($parts, 1, 3);
1125 $IPparts = explode('.', $IP);
1126 for ($a = 4; $a > $parts; $a--) {
1127 unset($IPparts[$a - 1]);
1128 }
1129 return implode('.', $IPparts);
1130 }
1131 }
1132
1133 /**
1134 * VeriCode returns 10 first chars of a md5 hash of the session cookie AND the encryptionKey from TYPO3_CONF_VARS.
1135 * This code is used as an alternative verification when the JavaScript interface executes cmd's to tce_db.php from eg. MSIE 5.0 because the proper referer is not passed with this browser...
1136 *
1137 * @return string
1138 */
1139 public function veriCode() {
1140 return substr(md5($this->id . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']), 0, 10);
1141 }
1142
1143 /**
1144 * This returns the where-clause needed to lock a user to a hash integer
1145 *
1146 * @return string
1147 * @access private
1148 */
1149 protected function hashLockClause() {
1150 $wherePart = 'AND ' . $this->session_table . '.ses_hashlock=' . $this->hashLockClause_getHashInt();
1151 return $wherePart;
1152 }
1153
1154 /**
1155 * Creates hash integer to lock user to. Depends on configured keywords
1156 *
1157 * @return integer Hash integer
1158 * @access private
1159 */
1160 protected function hashLockClause_getHashInt() {
1161 $hashStr = '';
1162 if (GeneralUtility::inList($this->lockHashKeyWords, 'useragent')) {
1163 $hashStr .= ':' . GeneralUtility::getIndpEnv('HTTP_USER_AGENT');
1164 }
1165 return GeneralUtility::md5int($hashStr);
1166 }
1167
1168 /*************************
1169 *
1170 * Session and Configuration Handling
1171 *
1172 *************************/
1173 /**
1174 * This writes $variable to the user-record. This is a way of providing session-data.
1175 * You can fetch the data again through $this->uc in this class!
1176 * If $variable is not an array, $this->uc is saved!
1177 *
1178 * @param array $variable An array you want to store for the user as session data. If $variable is not supplied (is blank string), the internal variable, ->uc, is stored by default
1179 * @return void
1180 * @todo Define visibility
1181 */
1182 public function writeUC($variable = '') {
1183 if (is_array($this->user) && $this->user[$this->userid_column]) {
1184 if (!is_array($variable)) {
1185 $variable = $this->uc;
1186 }
1187 if ($this->writeDevLog) {
1188 GeneralUtility::devLog('writeUC: ' . $this->userid_column . '=' . (int)$this->user[$this->userid_column], 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication');
1189 }
1190 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($this->user_table, $this->userid_column . '=' . (int)$this->user[$this->userid_column], array('uc' => serialize($variable)));
1191 }
1192 }
1193
1194 /**
1195 * Sets $theUC as the internal variable ->uc IF $theUC is an array. If $theUC is FALSE, the 'uc' content from the ->user array will be unserialized and restored in ->uc
1196 *
1197 * @param mixed $theUC If an array, then set as ->uc, otherwise load from user record
1198 * @return void
1199 * @todo Define visibility
1200 */
1201 public function unpack_uc($theUC = '') {
1202 if (!$theUC) {
1203 $theUC = unserialize($this->user['uc']);
1204 }
1205 if (is_array($theUC)) {
1206 $this->uc = $theUC;
1207 }
1208 }
1209
1210 /**
1211 * Stores data for a module.
1212 * The data is stored with the session id so you can even check upon retrieval if the module data is from a previous session or from the current session.
1213 *
1214 * @param string $module Is the name of the module ($MCONF['name'])
1215 * @param mixed $data Is the data you want to store for that module (array, string, ...)
1216 * @param boolean $noSave If $noSave is set, then the ->uc array (which carries all kinds of user data) is NOT written immediately, but must be written by some subsequent call.
1217 * @return void
1218 * @todo Define visibility
1219 */
1220 public function pushModuleData($module, $data, $noSave = 0) {
1221 $this->uc['moduleData'][$module] = $data;
1222 $this->uc['moduleSessionID'][$module] = $this->id;
1223 if (!$noSave) {
1224 $this->writeUC();
1225 }
1226 }
1227
1228 /**
1229 * Gets module data for a module (from a loaded ->uc array)
1230 *
1231 * @param string $module Is the name of the module ($MCONF['name'])
1232 * @param string $type If $type = 'ses' then module data is returned only if it was stored in the current session, otherwise data from a previous session will be returned (if available).
1233 * @return mixed The module data if available: $this->uc['moduleData'][$module];
1234 * @todo Define visibility
1235 */
1236 public function getModuleData($module, $type = '') {
1237 if ($type != 'ses' || $this->uc['moduleSessionID'][$module] == $this->id) {
1238 return $this->uc['moduleData'][$module];
1239 }
1240 }
1241
1242 /**
1243 * Returns the session data stored for $key.
1244 * The data will last only for this login session since it is stored in the session table.
1245 *
1246 * @param string $key Pointer to an associative key in the session data array which is stored serialized in the field "ses_data" of the session table.
1247 * @return mixed
1248 * @todo Define visibility
1249 */
1250 public function getSessionData($key) {
1251 $sesDat = unserialize($this->user['ses_data']);
1252 return $sesDat[$key];
1253 }
1254
1255 /**
1256 * Sets the session data ($data) for $key and writes all session data (from ->user['ses_data']) to the database.
1257 * The data will last only for this login session since it is stored in the session table.
1258 *
1259 * @param string $key Pointer to an associative key in the session data array which is stored serialized in the field "ses_data" of the session table.
1260 * @param mixed $data The variable to store in index $key
1261 * @return void
1262 * @todo Define visibility
1263 */
1264 public function setAndSaveSessionData($key, $data) {
1265 $sesDat = unserialize($this->user['ses_data']);
1266 $sesDat[$key] = $data;
1267 $this->user['ses_data'] = serialize($sesDat);
1268 if ($this->writeDevLog) {
1269 GeneralUtility::devLog('setAndSaveSessionData: ses_id = ' . $this->user['ses_id'], 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication');
1270 }
1271 $GLOBALS['TYPO3_DB']->exec_UPDATEquery($this->session_table, 'ses_id=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->user['ses_id'], $this->session_table), array('ses_data' => $this->user['ses_data']));
1272 }
1273
1274 /*************************
1275 *
1276 * Misc
1277 *
1278 *************************/
1279 /**
1280 * Returns an info array with Login/Logout data submitted by a form or params
1281 *
1282 * @return array
1283 * @internal
1284 * @todo Define visibility
1285 */
1286 public function getLoginFormData() {
1287 $loginData = array();
1288 if ($this->getMethodEnabled) {
1289 $loginData['status'] = GeneralUtility::_GP($this->formfield_status);
1290 $loginData['uname'] = GeneralUtility::_GP($this->formfield_uname);
1291 $loginData['uident'] = GeneralUtility::_GP($this->formfield_uident);
1292 $loginData['chalvalue'] = GeneralUtility::_GP($this->formfield_chalvalue);
1293 } else {
1294 $loginData['status'] = GeneralUtility::_POST($this->formfield_status);
1295 $loginData['uname'] = GeneralUtility::_POST($this->formfield_uname);
1296 $loginData['uident'] = GeneralUtility::_POST($this->formfield_uident);
1297 $loginData['chalvalue'] = GeneralUtility::_POST($this->formfield_chalvalue);
1298 }
1299 // Only process the login data if a login is requested
1300 if ($loginData['status'] === 'login') {
1301 $loginData = $this->processLoginData($loginData);
1302 }
1303 return $loginData;
1304 }
1305
1306 /**
1307 * Processes Login data submitted by a form or params depending on the
1308 * passwordTransmissionStrategy
1309 *
1310 * @param array $loginData Login data array
1311 * @param string $passwordTransmissionStrategy Alternative passwordTransmissionStrategy. Used when authentication services wants to override the default.
1312 * @return array
1313 * @internal
1314 * @todo Define visibility
1315 */
1316 public function processLoginData($loginData, $passwordTransmissionStrategy = '') {
1317 $passwordTransmissionStrategy = $passwordTransmissionStrategy ?: ($GLOBALS['TYPO3_CONF_VARS'][$this->loginType]['loginSecurityLevel'] ? trim($GLOBALS['TYPO3_CONF_VARS'][$this->loginType]['loginSecurityLevel']) : $this->security_level);
1318 if ($this->writeDevLog) {
1319 GeneralUtility::devLog('Login data before processing: ' . GeneralUtility::arrayToLogString($loginData), 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication');
1320 }
1321 $serviceChain = '';
1322 $subType = 'processLoginData' . $this->loginType;
1323 $authInfo = $this->getAuthInfoArray();
1324 $isLoginDataProcessed = FALSE;
1325 $processedLoginData = $loginData;
1326 while (is_object($serviceObject = GeneralUtility::makeInstanceService('auth', $subType, $serviceChain))) {
1327 $serviceChain .= ',' . $serviceObject->getServiceKey();
1328 $serviceObject->initAuth($subType, $loginData, $authInfo, $this);
1329 $serviceResult = $serviceObject->processLoginData($processedLoginData, $passwordTransmissionStrategy);
1330 if (!empty($serviceResult)) {
1331 $isLoginDataProcessed = TRUE;
1332 // If the service returns >=200 then no more processing is needed
1333 if ((int)$serviceResult >= 200) {
1334 unset($serviceObject);
1335 break;
1336 }
1337 }
1338 unset($serviceObject);
1339 }
1340 if ($isLoginDataProcessed) {
1341 $loginData = $processedLoginData;
1342 if ($this->writeDevLog) {
1343 GeneralUtility::devLog('Processed login data: ' . GeneralUtility::arrayToLogString($processedLoginData), 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication');
1344 }
1345 }
1346 return $loginData;
1347 }
1348
1349 /**
1350 * Returns an info array which provides additional information for auth services
1351 *
1352 * @return array
1353 * @internal
1354 * @todo Define visibility
1355 */
1356 public function getAuthInfoArray() {
1357 $authInfo = array();
1358 $authInfo['loginType'] = $this->loginType;
1359 $authInfo['refInfo'] = parse_url(GeneralUtility::getIndpEnv('HTTP_REFERER'));
1360 $authInfo['HTTP_HOST'] = GeneralUtility::getIndpEnv('HTTP_HOST');
1361 $authInfo['REMOTE_ADDR'] = GeneralUtility::getIndpEnv('REMOTE_ADDR');
1362 $authInfo['REMOTE_HOST'] = GeneralUtility::getIndpEnv('REMOTE_HOST');
1363 /** @deprecated the usage of $authInfo['security_level'] is deprecated since 4.7 */
1364 $authInfo['security_level'] = $this->security_level;
1365 $authInfo['showHiddenRecords'] = $this->showHiddenRecords;
1366 // Can be overidden in localconf by SVCONF:
1367 $authInfo['db_user']['table'] = $this->user_table;
1368 $authInfo['db_user']['userid_column'] = $this->userid_column;
1369 $authInfo['db_user']['username_column'] = $this->username_column;
1370 $authInfo['db_user']['userident_column'] = $this->userident_column;
1371 $authInfo['db_user']['usergroup_column'] = $this->usergroup_column;
1372 $authInfo['db_user']['enable_clause'] = $this->user_where_clause();
1373 if ($this->checkPid && $this->checkPid_value !== NULL) {
1374 $authInfo['db_user']['checkPidList'] = $this->checkPid_value;
1375 $authInfo['db_user']['check_pid_clause'] = ' AND pid IN (' .
1376 $GLOBALS['TYPO3_DB']->cleanIntList($this->checkPid_value) . ')';
1377 } else {
1378 $authInfo['db_user']['checkPidList'] = '';
1379 $authInfo['db_user']['check_pid_clause'] = '';
1380 }
1381 $authInfo['db_groups']['table'] = $this->usergroup_table;
1382 return $authInfo;
1383 }
1384
1385 /**
1386 * Check the login data with the user record data for builtin login methods
1387 *
1388 * @param array $user User data array
1389 * @param array $loginData Login data array
1390 * @param string $passwordCompareStrategy Alternative passwordCompareStrategy. Used when authentication services wants to override the default.
1391 * @return boolean TRUE if login data matched
1392 * @todo Define visibility
1393 */
1394 public function compareUident($user, $loginData, $passwordCompareStrategy = '') {
1395 $OK = FALSE;
1396 $passwordCompareStrategy = $passwordCompareStrategy ?: $this->security_level;
1397 switch ($passwordCompareStrategy) {
1398 case 'superchallenged':
1399
1400 case 'challenged':
1401 // Check challenge stored in cookie:
1402 if ($this->challengeStoredInCookie) {
1403 session_start();
1404 if ($_SESSION['login_challenge'] !== $loginData['chalvalue']) {
1405 if ($this->writeDevLog) {
1406 GeneralUtility::devLog('PHP Session stored challenge "' . $_SESSION['login_challenge'] . '" and submitted challenge "' . $loginData['chalvalue'] . '" did not match, so authentication failed!', 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication', 2);
1407 }
1408 $this->logoff();
1409 return FALSE;
1410 }
1411 }
1412 if ((string) $loginData[('uident_' . $passwordCompareStrategy)] === (string) md5(($user[$this->username_column] . ':' . $user[$this->userident_column] . ':' . $loginData['chalvalue']))) {
1413 $OK = TRUE;
1414 }
1415 break;
1416 default:
1417 // normal
1418 if ((string) $loginData['uident_text'] === (string) $user[$this->userident_column]) {
1419 $OK = TRUE;
1420 }
1421 }
1422 return $OK;
1423 }
1424
1425 /**
1426 * Garbage collector, removing old expired sessions.
1427 *
1428 * @return void
1429 * @internal
1430 * @todo Define visibility
1431 */
1432 public function gc() {
1433 $GLOBALS['TYPO3_DB']->exec_DELETEquery($this->session_table, 'ses_tstamp < ' . (int)($GLOBALS['EXEC_TIME'] - $this->gc_time) . ' AND ses_name = ' . $GLOBALS['TYPO3_DB']->fullQuoteStr($this->name, $this->session_table));
1434 }
1435
1436 /**
1437 * DUMMY: Writes to log database table (in some extension classes)
1438 *
1439 * @param integer $type denotes which module that has submitted the entry. This is the current list: 1=tce_db; 2=tce_file; 3=system (eg. sys_history save); 4=modules; 254=Personal settings changed; 255=login / out action: 1=login, 2=logout, 3=failed login (+ errorcode 3), 4=failure_warning_email sent
1440 * @param integer $action denotes which specific operation that wrote the entry (eg. 'delete', 'upload', 'update' and so on...). Specific for each $type. Also used to trigger update of the interface. (see the log-module for the meaning of each number !!)
1441 * @param integer $error flag. 0 = message, 1 = error (user problem), 2 = System Error (which should not happen), 3 = security notice (admin)
1442 * @param integer $details_nr The message number. Specific for each $type and $action. in the future this will make it possible to translate errormessages to other languages
1443 * @param string $details Default text that follows the message
1444 * @param array $data Data that follows the log. Might be used to carry special information. If an array the first 5 entries (0-4) will be sprintf'ed the details-text...
1445 * @param string $tablename Special field used by tce_main.php. These ($tablename, $recuid, $recpid) holds the reference to the record which the log-entry is about. (Was used in attic status.php to update the interface.)
1446 * @param integer $recuid Special field used by tce_main.php. These ($tablename, $recuid, $recpid) holds the reference to the record which the log-entry is about. (Was used in attic status.php to update the interface.)
1447 * @param integer $recpid Special field used by tce_main.php. These ($tablename, $recuid, $recpid) holds the reference to the record which the log-entry is about. (Was used in attic status.php to update the interface.)
1448 * @return void
1449 * @todo Define visibility
1450 */
1451 public function writelog($type, $action, $error, $details_nr, $details, $data, $tablename, $recuid, $recpid) {
1452
1453 }
1454
1455 /**
1456 * DUMMY: Check login failures (in some extension classes)
1457 *
1458 * @param string $email Email address
1459 * @param integer $secondsBack Number of sections back in time to check. This is a kind of limit for how many failures an hour for instance
1460 * @param integer $maxFailures Max allowed failures before a warning mail is sent
1461 * @return void
1462 * @ignore
1463 * @todo Define visibility
1464 */
1465 public function checkLogFailures($email, $secondsBack, $maxFailures) {
1466
1467 }
1468
1469 /**
1470 * Raw initialization of the be_user with uid=$uid
1471 * This will circumvent all login procedures and select a be_users record from the
1472 * database and set the content of ->user to the record selected.
1473 * Thus the BE_USER object will appear like if a user was authenticated - however without
1474 * a session id and the fields from the session table of course.
1475 * Will check the users for disabled, start/endtime, etc. ($this->user_where_clause())
1476 *
1477 * @param integer $uid The UID of the backend user to set in ->user
1478 * @return void
1479 * @internal
1480 * @see SC_mod_tools_be_user_index::compareUsers(), SC_mod_user_setup_index::simulateUser(), freesite_admin::startCreate()
1481 * @todo Define visibility
1482 */
1483 public function setBeUserByUid($uid) {
1484 $this->user = $this->getRawUserByUid($uid);
1485 }
1486
1487 /**
1488 * Raw initialization of the be_user with username=$name
1489 *
1490 * @param string $name The username to look up.
1491 * @return void
1492 * @see \TYPO3\CMS\Core\Authentication\AbstractUserAuthentication::setBeUserByUid()
1493 * @internal
1494 * @todo Define visibility
1495 */
1496 public function setBeUserByName($name) {
1497 $this->user = $this->getRawUserByName($name);
1498 }
1499
1500 /**
1501 * Fetching raw user record with uid=$uid
1502 *
1503 * @param integer $uid The UID of the backend user to set in ->user
1504 * @return array user record or FALSE
1505 * @internal
1506 * @todo Define visibility
1507 */
1508 public function getRawUserByUid($uid) {
1509 $user = FALSE;
1510 $dbres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $this->user_table, 'uid=' . (int)$uid . ' ' . $this->user_where_clause());
1511 if ($dbres) {
1512 $user = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($dbres);
1513 $GLOBALS['TYPO3_DB']->sql_free_result($dbres);
1514 }
1515 return $user;
1516 }
1517
1518 /**
1519 * Fetching raw user record with username=$name
1520 *
1521 * @param string $name The username to look up.
1522 * @return array user record or FALSE
1523 * @see \TYPO3\CMS\Core\Authentication\AbstractUserAuthentication::getUserByUid()
1524 * @internal
1525 * @todo Define visibility
1526 */
1527 public function getRawUserByName($name) {
1528 $user = FALSE;
1529 $dbres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $this->user_table, 'username=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($name, $this->user_table) . ' ' . $this->user_where_clause());
1530 if ($dbres) {
1531 $user = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($dbres);
1532 $GLOBALS['TYPO3_DB']->sql_free_result($dbres);
1533 }
1534 return $user;
1535 }
1536
1537 /*************************
1538 *
1539 * Create/update user - EXPERIMENTAL
1540 *
1541 *************************/
1542 /**
1543 * Get a user from DB by username
1544 * provided for usage from services
1545 *
1546 * @param array $dbUser User db table definition: $this->db_user
1547 * @param string $username user name
1548 * @param string $extraWhere Additional WHERE clause: " AND ...
1549 * @return mixed User array or FALSE
1550 * @todo Define visibility
1551 */
1552 public function fetchUserRecord($dbUser, $username, $extraWhere = '') {
1553 $user = FALSE;
1554 $usernameClause = $username ? $dbUser['username_column'] . '=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($username, $dbUser['table']) : '1=1';
1555 if ($username || $extraWhere) {
1556 // Look up the user by the username and/or extraWhere:
1557 $dbres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $dbUser['table'], $usernameClause . $dbUser['check_pid_clause'] . $dbUser['enable_clause'] . $extraWhere);
1558 if ($dbres) {
1559 $user = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($dbres);
1560 $GLOBALS['TYPO3_DB']->sql_free_result($dbres);
1561 }
1562 }
1563 return $user;
1564 }
1565
1566 }