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