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