[!!!][TASK] Replace GeneralUtility::sysLog() with Logging API
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Authentication / AuthenticationService.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\Connection;
18 use TYPO3\CMS\Core\Database\ConnectionPool;
19 use TYPO3\CMS\Core\Database\Query\Restriction\HiddenRestriction;
20 use TYPO3\CMS\Core\Utility\GeneralUtility;
21
22 /**
23 * Authentication services class
24 */
25 class AuthenticationService extends AbstractAuthenticationService
26 {
27 /**
28 * Process the submitted credentials.
29 * In this case hash the clear text password if it has been submitted.
30 *
31 * @param array $loginData Credentials that are submitted and potentially modified by other services
32 * @param string $passwordTransmissionStrategy Keyword of how the password has been hashed or encrypted before submission
33 * @return bool
34 */
35 public function processLoginData(array &$loginData, $passwordTransmissionStrategy)
36 {
37 $isProcessed = false;
38 if ($passwordTransmissionStrategy === 'normal') {
39 $loginData['uident_text'] = $loginData['uident'];
40 $isProcessed = true;
41 }
42 return $isProcessed;
43 }
44
45 /**
46 * Find a user (eg. look up the user record in database when a login is sent)
47 *
48 * @return mixed User array or FALSE
49 */
50 public function getUser()
51 {
52 if ($this->login['status'] !== 'login') {
53 return false;
54 }
55 if ((string)$this->login['uident_text'] === '') {
56 // Failed Login attempt (no password given)
57 $this->writelog(255, 3, 3, 2, 'Login-attempt from %s (%s) for username \'%s\' with an empty password!', [
58 $this->authInfo['REMOTE_ADDR'], $this->authInfo['REMOTE_HOST'], $this->login['uname']
59 ]);
60 $this->logger->warning(sprintf('Login-attempt from %s (%s), for username \'%s\' with an empty password!', $this->authInfo['REMOTE_ADDR'], $this->authInfo['REMOTE_HOST'], $this->login['uname']));
61 return false;
62 }
63
64 $user = $this->fetchUserRecord($this->login['uname']);
65 if (!is_array($user)) {
66 // Failed login attempt (no username found)
67 $this->writelog(255, 3, 3, 2, 'Login-attempt from %s (%s), username \'%s\' not found!!', [$this->authInfo['REMOTE_ADDR'], $this->authInfo['REMOTE_HOST'], $this->login['uname']]);
68 $this->logger->warning(sprintf('Login-attempt from %s (%s), username \'%s\' not found!', $this->authInfo['REMOTE_ADDR'], $this->authInfo['REMOTE_HOST'], $this->login['uname']));
69 } else {
70 if ($this->writeDevLog) {
71 GeneralUtility::devLog('User found: ' . GeneralUtility::arrayToLogString($user, [$this->db_user['userid_column'], $this->db_user['username_column']]), self::class);
72 }
73 }
74 return $user;
75 }
76
77 /**
78 * Authenticate a user (Check various conditions for the user that might invalidate its authentication, eg. password match, domain, IP, etc.)
79 *
80 * @param array $user Data of user.
81 * @return int >= 200: User authenticated successfully.
82 * No more checking is needed by other auth services.
83 * >= 100: User not authenticated; this service is not responsible.
84 * Other auth services will be asked.
85 * > 0: User authenticated successfully.
86 * Other auth services will still be asked.
87 * <= 0: Authentication failed, no more checking needed
88 * by other auth services.
89 */
90 public function authUser(array $user)
91 {
92 $OK = 100;
93 // This authentication service can only work correctly, if a non empty username along with a non empty password is provided.
94 // Otherwise a different service is allowed to check for other login credentials
95 if ((string)$this->login['uident_text'] !== '' && (string)$this->login['uname'] !== '') {
96 // Checking password match for user:
97 $OK = $this->compareUident($user, $this->login);
98 if (!$OK) {
99 // Failed login attempt (wrong password) - write that to the log!
100 if ($this->writeAttemptLog) {
101 $this->writelog(255, 3, 3, 1, 'Login-attempt from %s (%s), username \'%s\', password not accepted!', [$this->authInfo['REMOTE_ADDR'], $this->authInfo['REMOTE_HOST'], $this->login['uname']]);
102 $this->logger->warning(sprintf('Login-attempt from %s (%s), username \'%s\', password not accepted!', $this->authInfo['REMOTE_ADDR'], $this->authInfo['REMOTE_HOST'], $this->login['uname']));
103 }
104 if ($this->writeDevLog) {
105 GeneralUtility::devLog('Password not accepted: ' . $this->login['uident'], self::class, 2);
106 }
107 }
108 // Checking the domain (lockToDomain)
109 if ($OK && $user['lockToDomain'] && $user['lockToDomain'] !== $this->authInfo['HTTP_HOST']) {
110 // Lock domain didn't match, so error:
111 if ($this->writeAttemptLog) {
112 $this->writelog(255, 3, 3, 1, 'Login-attempt from %s (%s), username \'%s\', locked domain \'%s\' did not match \'%s\'!', [$this->authInfo['REMOTE_ADDR'], $this->authInfo['REMOTE_HOST'], $user[$this->db_user['username_column']], $user['lockToDomain'], $this->authInfo['HTTP_HOST']]);
113 $this->logger->warning(sprintf('Login-attempt from %s (%s), username \'%s\', locked domain \'%s\' did not match \'%s\'!', $this->authInfo['REMOTE_ADDR'], $this->authInfo['REMOTE_HOST'], $user[$this->db_user['username_column']], $user['lockToDomain'], $this->authInfo['HTTP_HOST']));
114 }
115 $OK = 0;
116 }
117 }
118 return $OK;
119 }
120
121 /**
122 * Find usergroup records, currently only for frontend
123 *
124 * @param array $user Data of user.
125 * @param array $knownGroups Group data array of already known groups. This is handy if you want select other related groups. Keys in this array are unique IDs of those groups.
126 * @return mixed Groups array, keys = uid which must be unique
127 */
128 public function getGroups($user, $knownGroups)
129 {
130 /*
131 * Attention: $knownGroups is not used within this method, but other services can use it.
132 * This parameter should not be removed!
133 * The FrontendUserAuthentication call getGroups and handover the previous detected groups.
134 */
135 $groupDataArr = [];
136 if ($this->mode === 'getGroupsFE') {
137 $groups = [];
138 if (is_array($user) && $user[$this->db_user['usergroup_column']]) {
139 $groupList = $user[$this->db_user['usergroup_column']];
140 $groups = [];
141 $this->getSubGroups($groupList, '', $groups);
142 }
143 // ADD group-numbers if the IPmask matches.
144 if (is_array($GLOBALS['TYPO3_CONF_VARS']['FE']['IPmaskMountGroups'])) {
145 foreach ($GLOBALS['TYPO3_CONF_VARS']['FE']['IPmaskMountGroups'] as $IPel) {
146 if ($this->authInfo['REMOTE_ADDR'] && $IPel[0] && GeneralUtility::cmpIP($this->authInfo['REMOTE_ADDR'], $IPel[0])) {
147 $groups[] = (int)$IPel[1];
148 }
149 }
150 }
151 $groups = array_unique($groups);
152 if (!empty($groups)) {
153 if ($this->writeDevLog) {
154 GeneralUtility::devLog('Get usergroups with id: ' . implode(',', $groups), __CLASS__);
155 }
156 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
157 ->getQueryBuilderForTable($this->db_groups['table']);
158 if (!empty($this->authInfo['showHiddenRecords'])) {
159 $queryBuilder->getRestrictions()->removeByType(HiddenRestriction::class);
160 }
161
162 $res = $queryBuilder->select('*')
163 ->from($this->db_groups['table'])
164 ->where(
165 $queryBuilder->expr()->in(
166 'uid',
167 $queryBuilder->createNamedParameter($groups, Connection::PARAM_INT_ARRAY)
168 ),
169 $queryBuilder->expr()->orX(
170 $queryBuilder->expr()->eq(
171 'lockToDomain',
172 $queryBuilder->createNamedParameter('', \PDO::PARAM_STR)
173 ),
174 $queryBuilder->expr()->isNull('lockToDomain'),
175 $queryBuilder->expr()->eq(
176 'lockToDomain',
177 $queryBuilder->createNamedParameter($this->authInfo['HTTP_HOST'], \PDO::PARAM_STR)
178 )
179 )
180 )
181 ->execute();
182
183 while ($row = $res->fetch()) {
184 $groupDataArr[$row['uid']] = $row;
185 }
186 } else {
187 if ($this->writeDevLog) {
188 GeneralUtility::devLog('No usergroups found.', self::class, 2);
189 }
190 }
191 }
192 return $groupDataArr;
193 }
194
195 /**
196 * Fetches subgroups of groups. Function is called recursively for each subgroup.
197 * Function was previously copied from
198 * \TYPO3\CMS\Core\Authentication\BackendUserAuthentication->fetchGroups and has been slightly modified.
199 *
200 * @param string $grList Commalist of fe_groups uid numbers
201 * @param string $idList List of already processed fe_groups-uids so the function will not fall into an eternal recursion.
202 * @param array $groups
203 * @return array
204 * @access private
205 */
206 public function getSubGroups($grList, $idList = '', &$groups)
207 {
208 // Fetching records of the groups in $grList (which are not blocked by lockedToDomain either):
209 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('fe_groups');
210 if (!empty($this->authInfo['showHiddenRecords'])) {
211 $queryBuilder->getRestrictions()->removeByType(HiddenRestriction::class);
212 }
213
214 $res = $queryBuilder
215 ->select('uid', 'subgroup')
216 ->from($this->db_groups['table'])
217 ->where(
218 $queryBuilder->expr()->in(
219 'uid',
220 $queryBuilder->createNamedParameter(
221 GeneralUtility::intExplode(',', $grList, true),
222 Connection::PARAM_INT_ARRAY
223 )
224 ),
225 $queryBuilder->expr()->orX(
226 $queryBuilder->expr()->eq(
227 'lockToDomain',
228 $queryBuilder->createNamedParameter('', \PDO::PARAM_STR)
229 ),
230 $queryBuilder->expr()->isNull('lockToDomain'),
231 $queryBuilder->expr()->eq(
232 'lockToDomain',
233 $queryBuilder->createNamedParameter($this->authInfo['HTTP_HOST'], \PDO::PARAM_STR)
234 )
235 )
236 )
237 ->execute();
238
239 // Internal group record storage
240 $groupRows = [];
241 // The groups array is filled
242 while ($row = $res->fetch()) {
243 if (!in_array($row['uid'], $groups)) {
244 $groups[] = $row['uid'];
245 }
246 $groupRows[$row['uid']] = $row;
247 }
248 // Traversing records in the correct order
249 $include_staticArr = GeneralUtility::intExplode(',', $grList);
250 // traversing list
251 foreach ($include_staticArr as $uid) {
252 // Get row:
253 $row = $groupRows[$uid];
254 // Must be an array and $uid should not be in the idList, because then it is somewhere previously in the grouplist
255 if (is_array($row) && !GeneralUtility::inList($idList, $uid)) {
256 // Include sub groups
257 if (trim($row['subgroup'])) {
258 // Make integer list
259 $theList = implode(',', GeneralUtility::intExplode(',', $row['subgroup']));
260 // Call recursively, pass along list of already processed groups so they are not processed again.
261 $this->getSubGroups($theList, $idList . ',' . $uid, $groups);
262 }
263 }
264 }
265 }
266 }