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