[SECURITY] Session timeout can be circumvented once
[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 $this->newSessionID = TRUE;
710 }
711 // Refuse login for _CLI users, if not processing a CLI request type
712 // (although we shouldn't be here in case of a CLI request type)
713 if (strtoupper(substr($loginData['uname'], 0, 5)) == '_CLI_' && !(TYPO3_REQUESTTYPE & TYPO3_REQUESTTYPE_CLI)) {
714 throw new \RuntimeException('TYPO3 Fatal Error: You have tried to login using a CLI user. Access prohibited!', 1270853931);
715 }
716 }
717 // The following code makes auto-login possible (if configured). No submitted data needed
718 // Determine whether we need to skip session update.
719 // This is used mainly for checking session timeout without
720 // refreshing the session itself while checking.
721 $skipSessionUpdate = (bool)GeneralUtility::_GP('skipSessionUpdate');
722 $haveSession = FALSE;
723 if (!$this->newSessionID) {
724 // Read user session
725 $authInfo['userSession'] = $this->fetchUserSession($skipSessionUpdate);
726 $haveSession = is_array($authInfo['userSession']) ? TRUE : FALSE;
727 }
728 if ($this->writeDevLog) {
729 if ($haveSession) {
730 GeneralUtility::devLog('User session found: ' . GeneralUtility::arrayToLogString($authInfo['userSession'], array($this->userid_column, $this->username_column)), 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication', 0);
731 } else {
732 GeneralUtility::devLog('No user session found.', 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication', 2);
733 }
734 if (is_array($this->svConfig['setup'])) {
735 GeneralUtility::devLog('SV setup: ' . GeneralUtility::arrayToLogString($this->svConfig['setup']), 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication', 0);
736 }
737 }
738 // Fetch user if ...
739 if (
740 $activeLogin || $this->svConfig['setup'][$this->loginType . '_alwaysFetchUser']
741 || !$haveSession && $this->svConfig['setup'][$this->loginType . '_fetchUserIfNoSession']
742 ) {
743 // Use 'auth' service to find the user
744 // First found user will be used
745 $serviceChain = '';
746 $subType = 'getUser' . $this->loginType;
747 while (is_object($serviceObj = GeneralUtility::makeInstanceService('auth', $subType, $serviceChain))) {
748 $serviceChain .= ',' . $serviceObj->getServiceKey();
749 $serviceObj->initAuth($subType, $loginData, $authInfo, $this);
750 if ($row = $serviceObj->getUser()) {
751 $tempuserArr[] = $row;
752 if ($this->writeDevLog) {
753 GeneralUtility::devLog('User found: ' . GeneralUtility::arrayToLogString($row, array($this->userid_column, $this->username_column)), 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication', 0);
754 }
755 // User found, just stop to search for more if not configured to go on
756 if (!$this->svConfig['setup'][($this->loginType . '_fetchAllUsers')]) {
757 break;
758 }
759 }
760 unset($serviceObj);
761 }
762 unset($serviceObj);
763 if ($this->writeDevLog && $this->svConfig['setup'][$this->loginType . '_alwaysFetchUser']) {
764 GeneralUtility::devLog($this->loginType . '_alwaysFetchUser option is enabled', 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication');
765 }
766 if ($this->writeDevLog && $serviceChain) {
767 GeneralUtility::devLog($subType . ' auth services called: ' . $serviceChain, 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication');
768 }
769 if ($this->writeDevLog && !count($tempuserArr)) {
770 GeneralUtility::devLog('No user found by services', 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication');
771 }
772 if ($this->writeDevLog && count($tempuserArr)) {
773 GeneralUtility::devLog(count($tempuserArr) . ' user records found by services', 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication');
774 }
775 }
776 // If no new user was set we use the already found user session
777 if (!count($tempuserArr) && $haveSession) {
778 $tempuserArr[] = $authInfo['userSession'];
779 $tempuser = $authInfo['userSession'];
780 // User is authenticated because we found a user session
781 $authenticated = TRUE;
782 if ($this->writeDevLog) {
783 GeneralUtility::devLog('User session used: ' . GeneralUtility::arrayToLogString($authInfo['userSession'], array($this->userid_column, $this->username_column)), 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication');
784 }
785 }
786 // Re-auth user when 'auth'-service option is set
787 if ($this->svConfig['setup'][$this->loginType . '_alwaysAuthUser']) {
788 $authenticated = FALSE;
789 if ($this->writeDevLog) {
790 GeneralUtility::devLog('alwaysAuthUser option is enabled', 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication');
791 }
792 }
793 // Authenticate the user if needed
794 if (count($tempuserArr) && !$authenticated) {
795 foreach ($tempuserArr as $tempuser) {
796 // Use 'auth' service to authenticate the user
797 // If one service returns FALSE then authentication failed
798 // a service might return 100 which means there's no reason to stop but the user can't be authenticated by that service
799 if ($this->writeDevLog) {
800 GeneralUtility::devLog('Auth user: ' . GeneralUtility::arrayToLogString($tempuser), 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication');
801 }
802 $serviceChain = '';
803 $subType = 'authUser' . $this->loginType;
804 while (is_object($serviceObj = GeneralUtility::makeInstanceService('auth', $subType, $serviceChain))) {
805 $serviceChain .= ',' . $serviceObj->getServiceKey();
806 $serviceObj->initAuth($subType, $loginData, $authInfo, $this);
807 if (($ret = $serviceObj->authUser($tempuser)) > 0) {
808 // If the service returns >=200 then no more checking is needed - useful for IP checking without password
809 if ((int)$ret >= 200) {
810 $authenticated = TRUE;
811 break;
812 } elseif ((int)$ret >= 100) {
813
814 } else {
815 $authenticated = TRUE;
816 }
817 } else {
818 $authenticated = FALSE;
819 break;
820 }
821 unset($serviceObj);
822 }
823 unset($serviceObj);
824 if ($this->writeDevLog && $serviceChain) {
825 GeneralUtility::devLog($subType . ' auth services called: ' . $serviceChain, 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication');
826 }
827 if ($authenticated) {
828 // Leave foreach() because a user is authenticated
829 break;
830 }
831 }
832 }
833 // If user is authenticated a valid user is in $tempuser
834 if ($authenticated) {
835 // Reset failure flag
836 $this->loginFailure = FALSE;
837 // Insert session record if needed:
838 if (!($haveSession && ($tempuser['ses_id'] == $this->id || $tempuser['uid'] == $authInfo['userSession']['ses_userid']))) {
839 $sessionData = $this->createUserSession($tempuser);
840 if ($sessionData) {
841 $this->user = array_merge(
842 $tempuser,
843 $sessionData
844 );
845 }
846 // The login session is started.
847 $this->loginSessionStarted = TRUE;
848 if ($this->writeDevLog && is_array($this->user)) {
849 GeneralUtility::devLog('User session finally read: ' . GeneralUtility::arrayToLogString($this->user, array($this->userid_column, $this->username_column)), 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication', -1);
850 }
851 } elseif ($haveSession) {
852 $this->user = $authInfo['userSession'];
853 }
854 // User logged in - write that to the log!
855 if ($this->writeStdLog && $activeLogin) {
856 $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']);
857 }
858 if ($this->writeDevLog && $activeLogin) {
859 GeneralUtility::devLog('User ' . $tempuser[$this->username_column] . ' logged in from ' . GeneralUtility::getIndpEnv('REMOTE_ADDR') . ' (' . GeneralUtility::getIndpEnv('REMOTE_HOST') . ')', 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication', -1);
860 }
861 if ($this->writeDevLog && !$activeLogin) {
862 GeneralUtility::devLog('User ' . $tempuser[$this->username_column] . ' authenticated from ' . GeneralUtility::getIndpEnv('REMOTE_ADDR') . ' (' . GeneralUtility::getIndpEnv('REMOTE_HOST') . ')', 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication', -1);
863 }
864 if ($GLOBALS['TYPO3_CONF_VARS']['BE']['lockSSL'] == 3 && $this->user_table == 'be_users') {
865 $requestStr = substr(GeneralUtility::getIndpEnv('TYPO3_REQUEST_SCRIPT'), strlen(GeneralUtility::getIndpEnv('TYPO3_SITE_URL') . TYPO3_mainDir));
866 $backendScript = \TYPO3\CMS\Backend\Utility\BackendUtility::getBackendScript();
867 if ($requestStr == $backendScript && GeneralUtility::getIndpEnv('TYPO3_SSL')) {
868 list(, $url) = explode('://', GeneralUtility::getIndpEnv('TYPO3_SITE_URL'), 2);
869 list($server, $address) = explode('/', $url, 2);
870 if ((int)$GLOBALS['TYPO3_CONF_VARS']['BE']['lockSSLPort']) {
871 $sslPortSuffix = ':' . (int)$GLOBALS['TYPO3_CONF_VARS']['BE']['lockSSLPort'];
872 // strip port from server
873 $server = str_replace($sslPortSuffix, '', $server);
874 }
875 \TYPO3\CMS\Core\Utility\HttpUtility::redirect('http://' . $server . '/' . $address . TYPO3_mainDir . $backendScript);
876 }
877 }
878 } elseif ($activeLogin || count($tempuserArr)) {
879 $this->loginFailure = TRUE;
880 if ($this->writeDevLog && !count($tempuserArr) && $activeLogin) {
881 GeneralUtility::devLog('Login failed: ' . GeneralUtility::arrayToLogString($loginData), 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication', 2);
882 }
883 if ($this->writeDevLog && count($tempuserArr)) {
884 GeneralUtility::devLog('Login failed: ' . GeneralUtility::arrayToLogString($tempuser, array($this->userid_column, $this->username_column)), 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication', 2);
885 }
886 }
887 // If there were a login failure, check to see if a warning email should be sent:
888 if ($this->loginFailure && $activeLogin) {
889 if ($this->writeDevLog) {
890 GeneralUtility::devLog('Call checkLogFailures: ' . GeneralUtility::arrayToLogString(array('warningEmail' => $this->warningEmail, 'warningPeriod' => $this->warningPeriod, 'warningMax' => $this->warningMax)), 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication', -1);
891 }
892 $this->checkLogFailures($this->warningEmail, $this->warningPeriod, $this->warningMax);
893 }
894 }
895
896 /**
897 * Creates a new session ID.
898 *
899 * @return string The new session ID
900 */
901 public function createSessionId() {
902 return GeneralUtility::getRandomHexString($this->hash_length);
903 }
904
905 /*************************
906 *
907 * User Sessions
908 *
909 *************************/
910 /**
911 * Creates a user session record and returns its values.
912 *
913 * @param array $tempuser User data array
914 *
915 * @return array The session data for the newly created session.
916 * @todo Define visibility
917 */
918 public function createUserSession($tempuser) {
919 if ($this->writeDevLog) {
920 GeneralUtility::devLog('Create session ses_id = ' . $this->id, 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication');
921 }
922 // Delete session entry first
923 $this->db->exec_DELETEquery(
924 $this->session_table,
925 'ses_id = ' . $this->db->fullQuoteStr($this->id, $this->session_table)
926 . ' AND ses_name = ' . $this->db->fullQuoteStr($this->name, $this->session_table)
927 );
928 // Re-create session entry
929 $insertFields = $this->getNewSessionRecord($tempuser);
930 $inserted = (boolean) $this->db->exec_INSERTquery($this->session_table, $insertFields);
931 if (!$inserted) {
932 $message = 'Session data could not be written to DB. Error: ' . $this->db->sql_error();
933 GeneralUtility::sysLog($message, 'Core', GeneralUtility::SYSLOG_SEVERITY_WARNING);
934 if ($this->writeDevLog) {
935 GeneralUtility::devLog($message, 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication', 2);
936 }
937 }
938 // Updating lastLogin_column carrying information about last login.
939 if ($this->lastLogin_column && $inserted) {
940 $this->db->exec_UPDATEquery(
941 $this->user_table,
942 $this->userid_column . '=' . $this->db->fullQuoteStr($tempuser[$this->userid_column], $this->user_table),
943 array($this->lastLogin_column => $GLOBALS['EXEC_TIME'])
944 );
945 }
946
947 return $inserted ? $insertFields : array();
948 }
949
950 /**
951 * Returns a new session record for the current user for insertion into the DB.
952 * This function is mainly there as a wrapper for inheriting classes to override it.
953 *
954 * @param array $tempuser
955 * @return array User session record
956 * @todo Define visibility
957 */
958 public function getNewSessionRecord($tempuser) {
959 return array(
960 'ses_id' => $this->id,
961 'ses_name' => $this->name,
962 'ses_iplock' => $tempuser['disableIPlock'] ? '[DISABLED]' : $this->ipLockClause_remoteIPNumber($this->lockIP),
963 'ses_hashlock' => $this->hashLockClause_getHashInt(),
964 'ses_userid' => $tempuser[$this->userid_column],
965 'ses_tstamp' => $GLOBALS['EXEC_TIME']
966 );
967 }
968
969 /**
970 * Read the user session from db.
971 *
972 * @param boolean $skipSessionUpdate
973 * @return array User session data
974 * @todo Define visibility
975 */
976 public function fetchUserSession($skipSessionUpdate = FALSE) {
977 $user = FALSE;
978 if ($this->writeDevLog) {
979 GeneralUtility::devLog('Fetch session ses_id = ' . $this->id, 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication');
980 }
981
982 // Fetch the user session from the DB
983 $statement = $this->fetchUserSessionFromDB();
984
985 if ($statement) {
986 $statement->execute();
987 $user = $statement->fetch();
988 $statement->free();
989 }
990 if ($user) {
991 // A user was found
992 if (\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($this->auth_timeout_field)) {
993 // Get timeout from object
994 $timeout = (int)$this->auth_timeout_field;
995 } else {
996 // Get timeout-time from usertable
997 $timeout = (int)$user[$this->auth_timeout_field];
998 }
999 // If timeout > 0 (TRUE) and current time has not exceeded the latest sessions-time plus the timeout in seconds then accept user
1000 // 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...
1001 if ($timeout > 0 && $GLOBALS['EXEC_TIME'] < $user['ses_tstamp'] + $timeout) {
1002 if (!$skipSessionUpdate) {
1003 $this->db->exec_UPDATEquery($this->session_table, 'ses_id=' . $this->db->fullQuoteStr($this->id, $this->session_table)
1004 . ' AND ses_name=' . $this->db->fullQuoteStr($this->name, $this->session_table), array('ses_tstamp' => $GLOBALS['EXEC_TIME']));
1005 // Make sure that the timestamp is also updated in the array
1006 $user['ses_tstamp'] = $GLOBALS['EXEC_TIME'];
1007 }
1008 } else {
1009 // Delete any user set...
1010 $this->logoff();
1011 $user = FALSE;
1012 }
1013 }
1014 return $user;
1015 }
1016
1017 /**
1018 * Log out current user!
1019 * Removes the current session record, sets the internal ->user array to a blank string;
1020 * Thereby the current user (if any) is effectively logged out!
1021 *
1022 * @return void
1023 * @todo Define visibility
1024 */
1025 public function logoff() {
1026 if ($this->writeDevLog) {
1027 GeneralUtility::devLog('logoff: ses_id = ' . $this->id, 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication');
1028 }
1029 // Release the locked records
1030 \TYPO3\CMS\Backend\Utility\BackendUtility::lockRecords();
1031 // Hook for pre-processing the logoff() method, requested and implemented by andreas.otto@dkd.de:
1032 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['logoff_pre_processing'])) {
1033 $_params = array();
1034 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['logoff_pre_processing'] as $_funcRef) {
1035 if ($_funcRef) {
1036 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1037 }
1038 }
1039 }
1040 $this->db->exec_DELETEquery($this->session_table, 'ses_id = ' . $this->db->fullQuoteStr($this->id, $this->session_table) . '
1041 AND ses_name = ' . $this->db->fullQuoteStr($this->name, $this->session_table));
1042 $this->user = '';
1043 // Hook for post-processing the logoff() method, requested and implemented by andreas.otto@dkd.de:
1044 if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['logoff_post_processing'])) {
1045 $_params = array();
1046 foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['t3lib/class.t3lib_userauth.php']['logoff_post_processing'] as $_funcRef) {
1047 if ($_funcRef) {
1048 GeneralUtility::callUserFunction($_funcRef, $_params, $this);
1049 }
1050 }
1051 }
1052 }
1053
1054 /**
1055 * Empty / unset the cookie
1056 *
1057 * @param string $cookieName usually, this is $this->name
1058 * @return void
1059 */
1060 public function removeCookie($cookieName) {
1061 $cookieDomain = $this->getCookieDomain();
1062 // If no cookie domain is set, use the base path
1063 $cookiePath = $cookieDomain ? '/' : GeneralUtility::getIndpEnv('TYPO3_SITE_PATH');
1064 setcookie($cookieName, NULL, -1, $cookiePath, $cookieDomain);
1065 }
1066
1067 /**
1068 * Determine whether there's an according session record to a given session_id
1069 * in the database. Don't care if session record is still valid or not.
1070 *
1071 * @param integer $id Claimed Session ID
1072 * @return boolean Returns TRUE if a corresponding session was found in the database
1073 * @todo Define visibility
1074 */
1075 public function isExistingSessionRecord($id) {
1076 $statement = $this->db->prepare_SELECTquery('COUNT(*)', $this->session_table, 'ses_id = :ses_id');
1077 $statement->execute(array(':ses_id' => $id));
1078 $row = $statement->fetch(\TYPO3\CMS\Core\Database\PreparedStatement::FETCH_NUM);
1079 $statement->free();
1080 return $row[0] ? TRUE : FALSE;
1081 }
1082
1083 /**
1084 * Returns whether this request is going to set a cookie
1085 * or a cookie was already found in the system
1086 * replaces the old functionality for "$this->cookieId"
1087 *
1088 * @return boolean Returns TRUE if a cookie is set
1089 */
1090 public function isCookieSet() {
1091 return $this->cookieWasSetOnCurrentRequest || $this->getCookie($this->name);
1092 }
1093
1094 /*************************
1095 *
1096 * SQL Functions
1097 *
1098 *************************/
1099 /**
1100 * The session_id is used to find user in the database.
1101 * Two tables are joined: The session-table with user_id of the session and the usertable with its primary key
1102 * if the client is flash (e.g. from a flash application inside TYPO3 that does a server request)
1103 * then don't evaluate with the hashLockClause, as the client/browser is included in this hash
1104 * and thus, the flash request would be rejected
1105 *
1106 * @return \TYPO3\CMS\Core\Database\PreparedStatement
1107 * @access private
1108 */
1109 protected function fetchUserSessionFromDB() {
1110 $statement = NULL;
1111 $ipLockClause = $this->ipLockClause();
1112 if ($GLOBALS['CLIENT']['BROWSER'] == 'flash') {
1113 // If on the flash client, the veri code is valid, then the user session is fetched
1114 // from the DB without the hashLock clause
1115 if (GeneralUtility::_GP('vC') == $this->veriCode()) {
1116 $statement = $this->db->prepare_SELECTquery('*', $this->session_table . ',' . $this->user_table, $this->session_table . '.ses_id = :ses_id
1117 AND ' . $this->session_table . '.ses_name = :ses_name
1118 AND ' . $this->session_table . '.ses_userid = ' . $this->user_table . '.' . $this->userid_column . '
1119 ' . $ipLockClause['where'] . '
1120 ' . $this->user_where_clause());
1121 $statement->bindValues(array(
1122 ':ses_id' => $this->id,
1123 ':ses_name' => $this->name
1124 ));
1125 $statement->bindValues($ipLockClause['parameters']);
1126 }
1127 } else {
1128 $statement = $this->db->prepare_SELECTquery('*', $this->session_table . ',' . $this->user_table, $this->session_table . '.ses_id = :ses_id
1129 AND ' . $this->session_table . '.ses_name = :ses_name
1130 AND ' . $this->session_table . '.ses_userid = ' . $this->user_table . '.' . $this->userid_column . '
1131 ' . $ipLockClause['where'] . '
1132 ' . $this->hashLockClause() . '
1133 ' . $this->user_where_clause());
1134 $statement->bindValues(array(
1135 ':ses_id' => $this->id,
1136 ':ses_name' => $this->name
1137 ));
1138 $statement->bindValues($ipLockClause['parameters']);
1139 }
1140 return $statement;
1141 }
1142
1143 /**
1144 * This returns the where-clause needed to select the user
1145 * with respect flags like deleted, hidden, starttime, endtime
1146 *
1147 * @return string
1148 * @access private
1149 */
1150 protected function user_where_clause() {
1151 $whereClause = '';
1152 if ($this->enablecolumns['rootLevel']) {
1153 $whereClause .= 'AND ' . $this->user_table . '.pid=0 ';
1154 }
1155 if ($this->enablecolumns['disabled']) {
1156 $whereClause .= ' AND ' . $this->user_table . '.' . $this->enablecolumns['disabled'] . '=0';
1157 }
1158 if ($this->enablecolumns['deleted']) {
1159 $whereClause .= ' AND ' . $this->user_table . '.' . $this->enablecolumns['deleted'] . '=0';
1160 }
1161 if ($this->enablecolumns['starttime']) {
1162 $whereClause .= ' AND (' . $this->user_table . '.' . $this->enablecolumns['starttime'] . '<=' . $GLOBALS['EXEC_TIME'] . ')';
1163 }
1164 if ($this->enablecolumns['endtime']) {
1165 $whereClause .= ' AND (' . $this->user_table . '.' . $this->enablecolumns['endtime'] . '=0 OR '
1166 . $this->user_table . '.' . $this->enablecolumns['endtime'] . '>' . $GLOBALS['EXEC_TIME'] . ')';
1167 }
1168 return $whereClause;
1169 }
1170
1171 /**
1172 * This returns the where prepared statement-clause needed to lock a user to the IP address
1173 *
1174 * @return array
1175 * @access private
1176 */
1177 protected function ipLockClause() {
1178 $statementClause = array(
1179 'where' => '',
1180 'parameters' => array()
1181 );
1182 if ($this->lockIP) {
1183 $statementClause['where'] = 'AND (
1184 ' . $this->session_table . '.ses_iplock = :ses_iplock
1185 OR ' . $this->session_table . '.ses_iplock=\'[DISABLED]\'
1186 )';
1187 $statementClause['parameters'] = array(
1188 ':ses_iplock' => $this->ipLockClause_remoteIPNumber($this->lockIP)
1189 );
1190 }
1191 return $statementClause;
1192 }
1193
1194 /**
1195 * Returns the IP address to lock to.
1196 * The IP address may be partial based on $parts.
1197 *
1198 * @param integer $parts 1-4: Indicates how many parts of the IP address to return. 4 means all, 1 means only first number.
1199 * @return string (Partial) IP address for REMOTE_ADDR
1200 * @access private
1201 */
1202 protected function ipLockClause_remoteIPNumber($parts) {
1203 $IP = GeneralUtility::getIndpEnv('REMOTE_ADDR');
1204 if ($parts >= 4) {
1205 return $IP;
1206 } else {
1207 $parts = \TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($parts, 1, 3);
1208 $IPparts = explode('.', $IP);
1209 for ($a = 4; $a > $parts; $a--) {
1210 unset($IPparts[$a - 1]);
1211 }
1212 return implode('.', $IPparts);
1213 }
1214 }
1215
1216 /**
1217 * VeriCode returns 10 first chars of a md5 hash of the session cookie AND the encryptionKey from TYPO3_CONF_VARS.
1218 * This code is used as an alternative verification when the JavaScript interface executes cmd's to
1219 * tce_db.php from eg. MSIE 5.0 because the proper referer is not passed with this browser...
1220 *
1221 * @return string
1222 */
1223 public function veriCode() {
1224 return substr(md5($this->id . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey']), 0, 10);
1225 }
1226
1227 /**
1228 * This returns the where-clause needed to lock a user to a hash integer
1229 *
1230 * @return string
1231 * @access private
1232 */
1233 protected function hashLockClause() {
1234 return 'AND ' . $this->session_table . '.ses_hashlock=' . $this->hashLockClause_getHashInt();
1235 }
1236
1237 /**
1238 * Creates hash integer to lock user to. Depends on configured keywords
1239 *
1240 * @return integer Hash integer
1241 * @access private
1242 */
1243 protected function hashLockClause_getHashInt() {
1244 $hashStr = '';
1245 if (GeneralUtility::inList($this->lockHashKeyWords, 'useragent')) {
1246 $hashStr .= ':' . GeneralUtility::getIndpEnv('HTTP_USER_AGENT');
1247 }
1248 return GeneralUtility::md5int($hashStr);
1249 }
1250
1251 /*************************
1252 *
1253 * Session and Configuration Handling
1254 *
1255 *************************/
1256 /**
1257 * This writes $variable to the user-record. This is a way of providing session-data.
1258 * You can fetch the data again through $this->uc in this class!
1259 * If $variable is not an array, $this->uc is saved!
1260 *
1261 * @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
1262 * @return void
1263 * @todo Define visibility
1264 */
1265 public function writeUC($variable = '') {
1266 if (is_array($this->user) && $this->user[$this->userid_column]) {
1267 if (!is_array($variable)) {
1268 $variable = $this->uc;
1269 }
1270 if ($this->writeDevLog) {
1271 GeneralUtility::devLog('writeUC: ' . $this->userid_column . '=' . (int)$this->user[$this->userid_column], 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication');
1272 }
1273 $this->db->exec_UPDATEquery($this->user_table, $this->userid_column . '=' . (int)$this->user[$this->userid_column], array('uc' => serialize($variable)));
1274 }
1275 }
1276
1277 /**
1278 * Sets $theUC as the internal variable ->uc IF $theUC is an array.
1279 * If $theUC is FALSE, the 'uc' content from the ->user array will be unserialized and restored in ->uc
1280 *
1281 * @param mixed $theUC If an array, then set as ->uc, otherwise load from user record
1282 * @return void
1283 * @todo Define visibility
1284 */
1285 public function unpack_uc($theUC = '') {
1286 if (!$theUC && isset($this->user['uc'])) {
1287 $theUC = unserialize($this->user['uc']);
1288 }
1289 if (is_array($theUC)) {
1290 $this->uc = $theUC;
1291 }
1292 }
1293
1294 /**
1295 * Stores data for a module.
1296 * The data is stored with the session id so you can even check upon retrieval
1297 * if the module data is from a previous session or from the current session.
1298 *
1299 * @param string $module Is the name of the module ($MCONF['name'])
1300 * @param mixed $data Is the data you want to store for that module (array, string, ...)
1301 * @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.
1302 * @return void
1303 * @todo Define visibility
1304 */
1305 public function pushModuleData($module, $data, $noSave = 0) {
1306 $this->uc['moduleData'][$module] = $data;
1307 $this->uc['moduleSessionID'][$module] = $this->id;
1308 if (!$noSave) {
1309 $this->writeUC();
1310 }
1311 }
1312
1313 /**
1314 * Gets module data for a module (from a loaded ->uc array)
1315 *
1316 * @param string $module Is the name of the module ($MCONF['name'])
1317 * @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).
1318 * @return mixed The module data if available: $this->uc['moduleData'][$module];
1319 * @todo Define visibility
1320 */
1321 public function getModuleData($module, $type = '') {
1322 if ($type != 'ses' || $this->uc['moduleSessionID'][$module] == $this->id) {
1323 return $this->uc['moduleData'][$module];
1324 }
1325 return NULL;
1326 }
1327
1328 /**
1329 * Returns the session data stored for $key.
1330 * The data will last only for this login session since it is stored in the session table.
1331 *
1332 * @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.
1333 * @return mixed
1334 * @todo Define visibility
1335 */
1336 public function getSessionData($key) {
1337 $sesDat = unserialize($this->user['ses_data']);
1338 return $sesDat[$key];
1339 }
1340
1341 /**
1342 * Sets the session data ($data) for $key and writes all session data (from ->user['ses_data']) to the database.
1343 * The data will last only for this login session since it is stored in the session table.
1344 *
1345 * @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.
1346 * @param mixed $data The variable to store in index $key
1347 * @return void
1348 * @todo Define visibility
1349 */
1350 public function setAndSaveSessionData($key, $data) {
1351 $sesDat = unserialize($this->user['ses_data']);
1352 $sesDat[$key] = $data;
1353 $this->user['ses_data'] = serialize($sesDat);
1354 if ($this->writeDevLog) {
1355 GeneralUtility::devLog('setAndSaveSessionData: ses_id = ' . $this->user['ses_id'], 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication');
1356 }
1357 $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']));
1358 }
1359
1360 /*************************
1361 *
1362 * Misc
1363 *
1364 *************************/
1365 /**
1366 * Returns an info array with Login/Logout data submitted by a form or params
1367 *
1368 * @return array
1369 * @internal
1370 * @todo Define visibility
1371 */
1372 public function getLoginFormData() {
1373 $loginData = array();
1374 if ($this->getMethodEnabled) {
1375 $loginData['status'] = GeneralUtility::_GP($this->formfield_status);
1376 $loginData['uname'] = GeneralUtility::_GP($this->formfield_uname);
1377 $loginData['uident'] = GeneralUtility::_GP($this->formfield_uident);
1378 $loginData['chalvalue'] = GeneralUtility::_GP($this->formfield_chalvalue);
1379 } else {
1380 $loginData['status'] = GeneralUtility::_POST($this->formfield_status);
1381 $loginData['uname'] = GeneralUtility::_POST($this->formfield_uname);
1382 $loginData['uident'] = GeneralUtility::_POST($this->formfield_uident);
1383 $loginData['chalvalue'] = GeneralUtility::_POST($this->formfield_chalvalue);
1384 }
1385 // Only process the login data if a login is requested
1386 if ($loginData['status'] === 'login') {
1387 $loginData = $this->processLoginData($loginData);
1388 }
1389 return $loginData;
1390 }
1391
1392 /**
1393 * Processes Login data submitted by a form or params depending on the
1394 * passwordTransmissionStrategy
1395 *
1396 * @param array $loginData Login data array
1397 * @param string $passwordTransmissionStrategy Alternative passwordTransmissionStrategy. Used when authentication services wants to override the default.
1398 * @return array
1399 * @internal
1400 * @todo Define visibility
1401 */
1402 public function processLoginData($loginData, $passwordTransmissionStrategy = '') {
1403 $loginSecurityLevel = $GLOBALS['TYPO3_CONF_VARS'][$this->loginType]['loginSecurityLevel']
1404 ? trim($GLOBALS['TYPO3_CONF_VARS'][$this->loginType]['loginSecurityLevel'])
1405 : 'normal';
1406 $passwordTransmissionStrategy = $passwordTransmissionStrategy ?: $loginSecurityLevel;
1407 if ($this->writeDevLog) {
1408 GeneralUtility::devLog('Login data before processing: ' . GeneralUtility::arrayToLogString($loginData), 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication');
1409 }
1410 $serviceChain = '';
1411 $subType = 'processLoginData' . $this->loginType;
1412 $authInfo = $this->getAuthInfoArray();
1413 $isLoginDataProcessed = FALSE;
1414 $processedLoginData = $loginData;
1415 while (is_object($serviceObject = GeneralUtility::makeInstanceService('auth', $subType, $serviceChain))) {
1416 $serviceChain .= ',' . $serviceObject->getServiceKey();
1417 $serviceObject->initAuth($subType, $loginData, $authInfo, $this);
1418 $serviceResult = $serviceObject->processLoginData($processedLoginData, $passwordTransmissionStrategy);
1419 if (!empty($serviceResult)) {
1420 $isLoginDataProcessed = TRUE;
1421 // If the service returns >=200 then no more processing is needed
1422 if ((int)$serviceResult >= 200) {
1423 unset($serviceObject);
1424 break;
1425 }
1426 }
1427 unset($serviceObject);
1428 }
1429 if ($isLoginDataProcessed) {
1430 $loginData = $processedLoginData;
1431 if ($this->writeDevLog) {
1432 GeneralUtility::devLog('Processed login data: ' . GeneralUtility::arrayToLogString($processedLoginData), 'TYPO3\\CMS\\Core\\Authentication\\AbstractUserAuthentication');
1433 }
1434 }
1435 return $loginData;
1436 }
1437
1438 /**
1439 * Returns an info array which provides additional information for auth services
1440 *
1441 * @return array
1442 * @internal
1443 * @todo Define visibility
1444 */
1445 public function getAuthInfoArray() {
1446 $authInfo = array();
1447 $authInfo['loginType'] = $this->loginType;
1448 $authInfo['refInfo'] = parse_url(GeneralUtility::getIndpEnv('HTTP_REFERER'));
1449 $authInfo['HTTP_HOST'] = GeneralUtility::getIndpEnv('HTTP_HOST');
1450 $authInfo['REMOTE_ADDR'] = GeneralUtility::getIndpEnv('REMOTE_ADDR');
1451 $authInfo['REMOTE_HOST'] = GeneralUtility::getIndpEnv('REMOTE_HOST');
1452 $authInfo['showHiddenRecords'] = $this->showHiddenRecords;
1453 // Can be overidden in localconf by SVCONF:
1454 $authInfo['db_user']['table'] = $this->user_table;
1455 $authInfo['db_user']['userid_column'] = $this->userid_column;
1456 $authInfo['db_user']['username_column'] = $this->username_column;
1457 $authInfo['db_user']['userident_column'] = $this->userident_column;
1458 $authInfo['db_user']['usergroup_column'] = $this->usergroup_column;
1459 $authInfo['db_user']['enable_clause'] = $this->user_where_clause();
1460 if ($this->checkPid && $this->checkPid_value !== NULL) {
1461 $authInfo['db_user']['checkPidList'] = $this->checkPid_value;
1462 $authInfo['db_user']['check_pid_clause'] = ' AND pid IN (' .
1463 $this->db->cleanIntList($this->checkPid_value) . ')';
1464 } else {
1465 $authInfo['db_user']['checkPidList'] = '';
1466 $authInfo['db_user']['check_pid_clause'] = '';
1467 }
1468 $authInfo['db_groups']['table'] = $this->usergroup_table;
1469 return $authInfo;
1470 }
1471
1472 /**
1473 * Check the login data with the user record data for builtin login methods
1474 *
1475 * @param array $user User data array
1476 * @param array $loginData Login data array
1477 * @param string $passwordCompareStrategy Alternative passwordCompareStrategy. Used when authentication services wants to override the default.
1478 * @return boolean TRUE if login data matched
1479 * @todo Define visibility
1480 */
1481 public function compareUident($user, $loginData, $passwordCompareStrategy = '') {
1482 $OK = FALSE;
1483 switch ($passwordCompareStrategy) {
1484 case 'superchallenged':
1485
1486 case 'challenged':
1487 // Check challenge stored in cookie:
1488 if ($this->challengeStoredInCookie) {
1489 session_start();
1490 if ($_SESSION['login_challenge'] !== $loginData['chalvalue']) {
1491 if ($this->writeDevLog) {
1492 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);
1493 }
1494 $this->logoff();
1495 return FALSE;
1496 }
1497 }
1498 $compareStrategyHash = md5($user[$this->username_column] . ':' . $user[$this->userident_column] . ':' . $loginData['chalvalue']);
1499 if ((string)$loginData[('uident_' . $passwordCompareStrategy)] === $compareStrategyHash) {
1500 $OK = TRUE;
1501 }
1502 break;
1503 default:
1504 // normal
1505 if ((string)$loginData['uident_text'] === (string)$user[$this->userident_column]) {
1506 $OK = TRUE;
1507 }
1508 }
1509 return $OK;
1510 }
1511
1512 /**
1513 * Garbage collector, removing old expired sessions.
1514 *
1515 * @return void
1516 * @internal
1517 * @todo Define visibility
1518 */
1519 public function gc() {
1520 $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));
1521 }
1522
1523 /**
1524 * DUMMY: Writes to log database table (in some extension classes)
1525 *
1526 * @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
1527 * @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 !!)
1528 * @param integer $error flag. 0 = message, 1 = error (user problem), 2 = System Error (which should not happen), 3 = security notice (admin)
1529 * @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
1530 * @param string $details Default text that follows the message
1531 * @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...
1532 * @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.)
1533 * @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.)
1534 * @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.)
1535 * @return void
1536 * @todo Define visibility
1537 */
1538 public function writelog($type, $action, $error, $details_nr, $details, $data, $tablename, $recuid, $recpid) {
1539
1540 }
1541
1542 /**
1543 * DUMMY: Check login failures (in some extension classes)
1544 *
1545 * @param string $email Email address
1546 * @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
1547 * @param integer $maxFailures Max allowed failures before a warning mail is sent
1548 * @return void
1549 * @ignore
1550 * @todo Define visibility
1551 */
1552 public function checkLogFailures($email, $secondsBack, $maxFailures) {
1553
1554 }
1555
1556 /**
1557 * Raw initialization of the be_user with uid=$uid
1558 * This will circumvent all login procedures and select a be_users record from the
1559 * database and set the content of ->user to the record selected.
1560 * Thus the BE_USER object will appear like if a user was authenticated - however without
1561 * a session id and the fields from the session table of course.
1562 * Will check the users for disabled, start/endtime, etc. ($this->user_where_clause())
1563 *
1564 * @param integer $uid The UID of the backend user to set in ->user
1565 * @return void
1566 * @internal
1567 * @see SC_mod_tools_be_user_index::compareUsers(), SC_mod_user_setup_index::simulateUser(), freesite_admin::startCreate()
1568 * @todo Define visibility
1569 */
1570 public function setBeUserByUid($uid) {
1571 $this->user = $this->getRawUserByUid($uid);
1572 }
1573
1574 /**
1575 * Raw initialization of the be_user with username=$name
1576 *
1577 * @param string $name The username to look up.
1578 * @return void
1579 * @see \TYPO3\CMS\Core\Authentication\AbstractUserAuthentication::setBeUserByUid()
1580 * @internal
1581 * @todo Define visibility
1582 */
1583 public function setBeUserByName($name) {
1584 $this->user = $this->getRawUserByName($name);
1585 }
1586
1587 /**
1588 * Fetching raw user record with uid=$uid
1589 *
1590 * @param integer $uid The UID of the backend user to set in ->user
1591 * @return array user record or FALSE
1592 * @internal
1593 * @todo Define visibility
1594 */
1595 public function getRawUserByUid($uid) {
1596 $user = FALSE;
1597 $dbres = $this->db->exec_SELECTquery('*', $this->user_table, 'uid=' . (int)$uid . ' ' . $this->user_where_clause());
1598 if ($dbres) {
1599 $user = $this->db->sql_fetch_assoc($dbres);
1600 $this->db->sql_free_result($dbres);
1601 }
1602 return $user;
1603 }
1604
1605 /**
1606 * Fetching raw user record with username=$name
1607 *
1608 * @param string $name The username to look up.
1609 * @return array user record or FALSE
1610 * @see \TYPO3\CMS\Core\Authentication\AbstractUserAuthentication::getUserByUid()
1611 * @internal
1612 * @todo Define visibility
1613 */
1614 public function getRawUserByName($name) {
1615 $user = FALSE;
1616 $dbres = $this->db->exec_SELECTquery('*', $this->user_table, 'username=' . $this->db->fullQuoteStr($name, $this->user_table) . ' ' . $this->user_where_clause());
1617 if ($dbres) {
1618 $user = $this->db->sql_fetch_assoc($dbres);
1619 $this->db->sql_free_result($dbres);
1620 }
1621 return $user;
1622 }
1623
1624 /*************************
1625 *
1626 * Create/update user - EXPERIMENTAL
1627 *
1628 *************************/
1629 /**
1630 * Get a user from DB by username
1631 * provided for usage from services
1632 *
1633 * @param array $dbUser User db table definition: $this->db_user
1634 * @param string $username user name
1635 * @param string $extraWhere Additional WHERE clause: " AND ...
1636 * @return mixed User array or FALSE
1637 * @todo Define visibility
1638 */
1639 public function fetchUserRecord($dbUser, $username, $extraWhere = '') {
1640 $user = FALSE;
1641 $usernameClause = $username ? $dbUser['username_column'] . '=' . $this->db->fullQuoteStr($username, $dbUser['table']) : '1=1';
1642 if ($username || $extraWhere) {
1643 // Look up the user by the username and/or extraWhere:
1644 $dbres = $this->db->exec_SELECTquery('*', $dbUser['table'], $usernameClause . $dbUser['check_pid_clause'] . $dbUser['enable_clause'] . $extraWhere);
1645 if ($dbres) {
1646 $user = $this->db->sql_fetch_assoc($dbres);
1647 $this->db->sql_free_result($dbres);
1648 }
1649 }
1650 return $user;
1651 }
1652
1653 /**
1654 * Get global database connection
1655 * @return DatabaseConnection
1656 */
1657 protected function getDatabaseConnection() {
1658 return $GLOBALS['TYPO3_DB'];
1659 }
1660 }