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