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