[!!!][TASK] Always use logging in authentication processes
[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->info('Login-attempt from username \'' . $this->login['uname'] . '\' not found!', [
69 'REMOTE_ADDR' => $this->authInfo['REMOTE_ADDR'],
70 'REMOTE_HOST' => $this->authInfo['REMOTE_HOST'],
71 ]);
72 } else {
73 $this->logger->debug('User found', [
74 $this->db_user['userid_column'] => $user[$this->db_user['userid_column']],
75 $this->db_user['username_column'] => $user[$this->db_user['username_column']]
76 ]);
77 }
78 return $user;
79 }
80
81 /**
82 * Authenticate a user (Check various conditions for the user that might invalidate its authentication, eg. password match, domain, IP, etc.)
83 *
84 * @param array $user Data of user.
85 * @return int >= 200: User authenticated successfully.
86 * No more checking is needed by other auth services.
87 * >= 100: User not authenticated; this service is not responsible.
88 * Other auth services will be asked.
89 * > 0: User authenticated successfully.
90 * Other auth services will still be asked.
91 * <= 0: Authentication failed, no more checking needed
92 * by other auth services.
93 */
94 public function authUser(array $user)
95 {
96 $OK = 100;
97 // This authentication service can only work correctly, if a non empty username along with a non empty password is provided.
98 // Otherwise a different service is allowed to check for other login credentials
99 if ((string)$this->login['uident_text'] !== '' && (string)$this->login['uname'] !== '') {
100 // Checking password match for user:
101 $OK = $this->compareUident($user, $this->login);
102 if (!$OK) {
103 // Failed login attempt (wrong password) - write that to the log!
104 if ($this->writeAttemptLog) {
105 $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']]);
106 $this->logger->info('Login-attempt username \'' . $this->login['uname'] . '\', password not accepted!', [
107 'REMOTE_ADDR' => $this->authInfo['REMOTE_ADDR'],
108 'REMOTE_HOST' => $this->authInfo['REMOTE_HOST'],
109 ]);
110 }
111 $this->logger->debug('Password not accepted: ' . $this->login['uident']);
112 }
113 // Checking the domain (lockToDomain)
114 if ($OK && $user['lockToDomain'] && $user['lockToDomain'] !== $this->authInfo['HTTP_HOST']) {
115 // Lock domain didn't match, so error:
116 if ($this->writeAttemptLog) {
117 $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']]);
118 $this->logger->info('Login-attempt from username \'' . $user[$this->db_user['username_column']] . '\', locked domain did not match!', [
119 'HTTP_HOST' => $this->authInfo['HTTP_HOST'],
120 'REMOTE_ADDR' => $this->authInfo['REMOTE_ADDR'],
121 'REMOTE_HOST' => $this->authInfo['REMOTE_HOST'],
122 'lockToDomain' => $user['lockToDomain'],
123 ]);
124 }
125 $OK = 0;
126 }
127 }
128 return $OK;
129 }
130
131 /**
132 * Find usergroup records, currently only for frontend
133 *
134 * @param array $user Data of user.
135 * @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.
136 * @return mixed Groups array, keys = uid which must be unique
137 */
138 public function getGroups($user, $knownGroups)
139 {
140 /*
141 * Attention: $knownGroups is not used within this method, but other services can use it.
142 * This parameter should not be removed!
143 * The FrontendUserAuthentication call getGroups and handover the previous detected groups.
144 */
145 $groupDataArr = [];
146 if ($this->mode === 'getGroupsFE') {
147 $groups = [];
148 if (is_array($user) && $user[$this->db_user['usergroup_column']]) {
149 $groupList = $user[$this->db_user['usergroup_column']];
150 $groups = [];
151 $this->getSubGroups($groupList, '', $groups);
152 }
153 // ADD group-numbers if the IPmask matches.
154 if (is_array($GLOBALS['TYPO3_CONF_VARS']['FE']['IPmaskMountGroups'])) {
155 foreach ($GLOBALS['TYPO3_CONF_VARS']['FE']['IPmaskMountGroups'] as $IPel) {
156 if ($this->authInfo['REMOTE_ADDR'] && $IPel[0] && GeneralUtility::cmpIP($this->authInfo['REMOTE_ADDR'], $IPel[0])) {
157 $groups[] = (int)$IPel[1];
158 }
159 }
160 }
161 $groups = array_unique($groups);
162 if (!empty($groups)) {
163 $this->logger->debug('Get usergroups with id: ' . implode(',', $groups));
164 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)
165 ->getQueryBuilderForTable($this->db_groups['table']);
166 if (!empty($this->authInfo['showHiddenRecords'])) {
167 $queryBuilder->getRestrictions()->removeByType(HiddenRestriction::class);
168 }
169
170 $res = $queryBuilder->select('*')
171 ->from($this->db_groups['table'])
172 ->where(
173 $queryBuilder->expr()->in(
174 'uid',
175 $queryBuilder->createNamedParameter($groups, Connection::PARAM_INT_ARRAY)
176 ),
177 $queryBuilder->expr()->orX(
178 $queryBuilder->expr()->eq(
179 'lockToDomain',
180 $queryBuilder->createNamedParameter('', \PDO::PARAM_STR)
181 ),
182 $queryBuilder->expr()->isNull('lockToDomain'),
183 $queryBuilder->expr()->eq(
184 'lockToDomain',
185 $queryBuilder->createNamedParameter($this->authInfo['HTTP_HOST'], \PDO::PARAM_STR)
186 )
187 )
188 )
189 ->execute();
190
191 while ($row = $res->fetch()) {
192 $groupDataArr[$row['uid']] = $row;
193 }
194 } else {
195 $this->logger->debug('No usergroups found.');
196 }
197 }
198 return $groupDataArr;
199 }
200
201 /**
202 * Fetches subgroups of groups. Function is called recursively for each subgroup.
203 * Function was previously copied from
204 * \TYPO3\CMS\Core\Authentication\BackendUserAuthentication->fetchGroups and has been slightly modified.
205 *
206 * @param string $grList Commalist of fe_groups uid numbers
207 * @param string $idList List of already processed fe_groups-uids so the function will not fall into an eternal recursion.
208 * @param array $groups
209 * @return array
210 * @access private
211 */
212 public function getSubGroups($grList, $idList = '', &$groups)
213 {
214 // Fetching records of the groups in $grList (which are not blocked by lockedToDomain either):
215 $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('fe_groups');
216 if (!empty($this->authInfo['showHiddenRecords'])) {
217 $queryBuilder->getRestrictions()->removeByType(HiddenRestriction::class);
218 }
219
220 $res = $queryBuilder
221 ->select('uid', 'subgroup')
222 ->from($this->db_groups['table'])
223 ->where(
224 $queryBuilder->expr()->in(
225 'uid',
226 $queryBuilder->createNamedParameter(
227 GeneralUtility::intExplode(',', $grList, true),
228 Connection::PARAM_INT_ARRAY
229 )
230 ),
231 $queryBuilder->expr()->orX(
232 $queryBuilder->expr()->eq(
233 'lockToDomain',
234 $queryBuilder->createNamedParameter('', \PDO::PARAM_STR)
235 ),
236 $queryBuilder->expr()->isNull('lockToDomain'),
237 $queryBuilder->expr()->eq(
238 'lockToDomain',
239 $queryBuilder->createNamedParameter($this->authInfo['HTTP_HOST'], \PDO::PARAM_STR)
240 )
241 )
242 )
243 ->execute();
244
245 // Internal group record storage
246 $groupRows = [];
247 // The groups array is filled
248 while ($row = $res->fetch()) {
249 if (!in_array($row['uid'], $groups)) {
250 $groups[] = $row['uid'];
251 }
252 $groupRows[$row['uid']] = $row;
253 }
254 // Traversing records in the correct order
255 $include_staticArr = GeneralUtility::intExplode(',', $grList);
256 // traversing list
257 foreach ($include_staticArr as $uid) {
258 // Get row:
259 $row = $groupRows[$uid];
260 // Must be an array and $uid should not be in the idList, because then it is somewhere previously in the grouplist
261 if (is_array($row) && !GeneralUtility::inList($idList, $uid)) {
262 // Include sub groups
263 if (trim($row['subgroup'])) {
264 // Make integer list
265 $theList = implode(',', GeneralUtility::intExplode(',', $row['subgroup']));
266 // Call recursively, pass along list of already processed groups so they are not processed again.
267 $this->getSubGroups($theList, $idList . ',' . $uid, $groups);
268 }
269 }
270 }
271 }
272 }