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