Debian Codegraph @

lib/modules/posixAccount.inc

raw
1 <?php
2
3 use LAM\REMOTE\Remote;
4 use LAM\REMOTE\RemoteServerConfiguration;
5 use LAM\TYPES\TypeManager;
6 use function LAM\TYPES\getScopeFromTypeId;
7 use LAM\TYPES\ConfiguredType;
8
9 /*
10
11 This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
12 Copyright (C) 2003 - 2006 Tilo Lutz
13 Copyright (C) 2005 - 2026 Roland Gruber
14
15 This program is free software; you can redistribute it and/or modify
16 it under the terms of the GNU General Public License as published by
17 the Free Software Foundation; either version 2 of the License, or
18 (at your option) any later version.
19
20 This program is distributed in the hope that it will be useful,
21 but WITHOUT ANY WARRANTY; without even the implied warranty of
22 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 GNU General Public License for more details.
24
25 You should have received a copy of the GNU General Public License
26 along with this program; if not, write to the Free Software
27 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
28 */
29
30 /**
31 * Manages Unix accounts for users and hosts.
32 *
33 * @package modules
34 *
35 * @author Tilo Lutz
36 * @author Roland Gruber
37 * @author Michael Duergner
38 * @author Thomas Manninger
39 */
40
41 /**
42 * Manages the object class "posixAccount" for users and hosts.
43 *
44 * @package modules
45 */
46 class posixAccount extends baseModule implements passwordService, AccountStatusProvider {
47
48 // Variables
49 /** delimiter for lamdaemon commands */
50 private static string $SPLIT_DELIMITER = "###x##y##x###";
51
52 /**
53 * ID for locked password status.
54 */
55 private const STATUS_PASSWORD_LOCKED = "POSIX_ACCOUNT_PASSWORD_LOCKED";
56
57 /**
58 * ID for removing Unix groups of user.
59 */
60 private const STATUS_REMOVE_UNIX_GROUPS = "POSIX_ACCOUNT_REMOVE_UNIX_GROUPS";
61
62 /**
63 * ID for removing group of names groups of user.
64 */
65 private const STATUS_REMOVE_GON_GROUPS = "POSIX_ACCOUNT_REMOVE_GON_GROUPS";
66
67 /**
68 * Marker for GID number to create a group with the same name
69 */
70 private const CREATE_GROUP_WITH_SAME_NAME = '*create_group_with_same_name*';
71
72 /* These two variables keep an array of groups the user is also member of. */
73 /** @var string[] $groups current group list */
74 private array $groups = [];
75 /** @var string[] $groups_orig original group list */
76 private array $groups_orig = [];
77
78 /* list of group of names that the user is member of */
79 /** @var string[] $gonList current group of names list */
80 private array $gonList = [];
81 /** @var string[] $gonList_orig original group of names list */
82 private array $gonList_orig = [];
83 /** @var string[] $lamdaemonServers lamdaemon servers */
84 private array $lamdaemonServers = [];
85 /** @var string[][]|null $groupCache cache for group objects */
86 private ?array $groupCache = null;
87 /** @var array<string, array<string, string[]|string>>|null $gonCache cache for group of names objects */
88 private ?array $gonCache = null;
89 /** clear text password */
90 private ?string $clearTextPassword = null;
91 /** @var string[]|null $cachedUIDList caches the list of known UIDs */
92 private ?array $cachedUIDList = null;
93 /** @var array<string, string>|null $cachedUserNameList caches the list of known user names */
94 private ?array $cachedUserNameList = null;
95
96 /** @var array<string, string> $umlautReplacements replacements for common umlauts */
97 private array $umlautReplacements = [
98 'ä' => 'ae', 'Ä' => 'Ae', 'ö' => 'oe', 'Ö' => 'Oe', 'ü' => 'ue', 'Ü' => 'Ue',
99 'ß' => 'ss', 'é' => 'e', 'è' => 'e', 'ô' => 'o', 'ç' => 'c'
100 ];
101
102 /**
103 * {@inheritDoc}
104 */
105 protected function load_Messages(): void {
106 // error messages for input checks
107 $this->messages['minUID'][0] = ['ERROR', _('Users') . ': &nbsp;' . _('Minimum UID number'), _("Minimum UID number is invalid!")];
108 $this->messages['maxUID'][0] = ['ERROR', _('Users') . ': &nbsp;' . _('Maximum UID number'), _("Maximum UID number is invalid!")];
109 $this->messages['minMachine'][0] = ['ERROR', _('Hosts') . ': &nbsp;' . _('Minimum UID number'), _("Minimum UID number is invalid!")];
110 $this->messages['maxMachine'][0] = ['ERROR', _('Hosts') . ': &nbsp;' . _('Maximum UID number'), _("Maximum UID number is invalid!")];
111 $this->messages['cmp_UID'][0] = ['ERROR', _('Users') . ': &nbsp;' . _('Maximum UID number'), _("Maximum UID number must be greater than minimum UID number!")];
112 $this->messages['cmp_Machine'][0] = ['ERROR', _('Hosts') . ': &nbsp;' . _('Maximum UID number'), _("Maximum UID number must be greater than minimum UID number!")];
113 $this->messages['cmp_both'][0] = ['ERROR', _('UID ranges for Unix accounts'), _("The UID ranges for users and hosts overlap! This is a problem because LAM uses the highest UID in use + 1 for new accounts. Please set the minimum UID to equal values or use independent ranges.")];
114 $this->messages['homeDirectory'][0] = ['ERROR', _('Home directory'), _('Homedirectory contains invalid characters.')];
115 $this->messages['homeDirectory'][1] = ['INFO', _('Home directory'), _('Replaced $user or $group in homedir.')];
116 $this->messages['homeDirectory'][2] = ['ERROR', _('Account %s:') . ' posixAccount_homedir', _('Homedirectory contains invalid characters.')];
117 $this->messages['homeDirectory'][3] = ['INFO', _('Home directory'), _('Home directory changed. To keep home directory you have to run the following command as root: \'mv %s %s\'')];
118 $this->messages['homeDirectory'][4] = ['ERROR', _('Account %s:') . ' posixAccount_createHomeDir', _('Invalid remote server name.')];
119 $this->messages['uidNumber'][1] = ['ERROR', _('ID-Number'), _('No free ID-Number!')];
120 $this->messages['uidNumber'][2] = ['WARN', _('ID-Number'), _('It is possible that this ID-number is reused. This can cause several problems because files with old permissions might still exist. To avoid this warning set maxUID to a higher value.')];
121 $this->messages['uidNumber'][3] = ['ERROR', _('ID-Number'), _('ID is already in use')];
122 $this->messages['uidNumber'][4] = ['ERROR', _('Account %s:') . ' posixAccount_uid', _('UID must be a number. It has to be inside the UID range which is defined in your configuration profile.')];
123 $this->messages['uidNumber'][5] = ['INFO', _('UID number'), _('UID number has changed. To keep file ownership you have to run the following command as root: \'find / -uid %s -exec chown %s {} \;\'')];
124 $this->messages['userPassword'][0] = ['ERROR', _('Password'), _('Please enter the same password in both password fields.')];
125 $this->messages['userPassword'][1] = ['ERROR', _('Password'), _('Password contains invalid characters. Valid characters are:') . ' a-z, A-Z, 0-9 and #*,.;:_-+!%&/|?{[()]}=@$ §°!'];
126 $this->messages['userPassword'][4] = ['ERROR', _('Account %s:') . ' posixAccount_password', _('Password contains invalid characters. Valid characters are:') . ' a-z, A-Z, 0-9 and #*,.;:_-+!%&/|?{[()]}=@$ §°!'];
127 $this->messages['uid'][0] = ['INFO', _('UID'), _('UID has changed. Do you want to change home directory?')];
128 $this->messages['uid'][1] = ['WARN', _('User name'), _('You are using capital letters. This can cause problems because Windows is not case-sensitive.')];
129 $this->messages['uid'][2] = ['ERROR', _('User name'), _('User name contains invalid characters. Valid characters are: a-z, A-Z, 0-9 and .-_ !')];
130 $this->messages['uid'][3] = ['WARN', _('Host name'), _('You are using capital letters. This can cause problems because Windows is not case-sensitive.')];
131 $this->messages['uid'][4] = ['ERROR', _('Host name'), _('Host name contains invalid characters. Valid characters are: a-z, A-Z, 0-9 and .-_ !')];
132 $this->messages['uid'][5] = ['WARN', _('User name'), _('User name in use (%s). Selected next free user name.')];
133 $this->messages['uid'][6] = ['WARN', _('Host name'), _('Host name in use (%s). Selected next free host name.')];
134 $this->messages['uid'][7] = ['ERROR', _('Account %s:') . ' posixAccount_userName', _('User name contains invalid characters. Valid characters are: a-z, A-Z, 0-9 and .-_ !')];
135 $this->messages['uid'][8] = ['ERROR', _('Account %s:') . ' posixAccount_hostName', _('Host name contains invalid characters. Valid characters are: a-z, A-Z, 0-9 and .-_ !')];
136 $this->messages['uid'][9] = ['WARN', _('Account %s:') . ' posixAccount_userName', _('User name already exists!') . ' ' . _('You might want to use %s instead of %s.') . ' %s'];
137 $this->messages['uid'][10] = ['WARN', _('Account %s:') . ' posixAccount_hostName', _('Host name already exists!') . ' ' . _('You might want to use %s instead of %s.') . ' %s'];
138 $this->messages['gidNumber'][0] = ['ERROR', _('Account %s:') . ' posixAccount_group', _('LAM was unable to find a group with this name!')];
139 $this->messages['gidNumber'][1] = ['ERROR', _('Account %s:') . ' posixAccount_group', _('This GID number is invalid! Please provide either a number or a group name.')];
140 $this->messages['gidNumber'][2] = ['INFO', _('GID number'), _('GID number has changed. To keep file ownership you have to run the following command as root: \'find / -gid %s -uid %s -exec chgrp %s {} \;\'')];
141 $this->messages['gecos'][0] = ['ERROR', _('Account %s:') . ' posixAccount_gecos', _('This gecos value is invalid!')];
142 $this->messages['shell'][0] = ['ERROR', _('Account %s:') . ' posixAccount_shell', _('This login shell is invalid!')];
143 $this->messages['passwordDisabled'][0] = ['ERROR', _('Account %s:') . ' posixAccount_passwordDisabled', _('This value can only be "true" or "false".')];
144 $this->messages['cn'][0] = ['ERROR', _('Common name'), _('Please enter a valid common name!')];
145 $this->messages['cn'][1] = ['ERROR', _('Account %s:') . ' posixAccount_cn', _('Please enter a valid common name!')];
146 $this->messages['sambaIDPoolDN'][0] = ['ERROR', _('Samba ID pool DN'), _('This is not a valid DN!')];
147 $this->messages['windowsIDPoolDN'][0] = ['ERROR', _('Windows domain info DN'), _('This is not a valid DN!')];
148 }
149
150 /**
151 * {@inheritDoc}
152 */
153 public function can_manage(): bool {
154 return in_array($this->get_scope(), ['user', 'host']);
155 }
156
157 /**
158 * {@inheritDoc}
159 */
160 public function get_metaData(): array {
161 $return = [];
162 // icon
163 $return['icon'] = 'tux.svg';
164 // user specific data
165 if ($this->get_scope() == "user") {
166 // LDAP filter
167 $return["ldap_filter"] = ['or' => "(objectClass=posixAccount)", 'and' => "(!(uid=*$))"];
168 // module dependencies
169 $return['dependencies'] = ['depends' => [], 'conflicts' => []];
170 }
171 elseif ($this->get_scope() == "host") {
172 // LDAP filter
173 $return["ldap_filter"] = ['or' => "(objectClass=posixAccount)"];
174 // module dependencies
175 $return['dependencies'] = ['depends' => [], 'conflicts' => []];
176 }
177 // alias name
178 $return["alias"] = _("Unix");
179 // RDN attributes
180 $return["RDN"] = ["uid" => "high", "cn" => "low"];
181 // managed object classes
182 $return['objectClasses'] = ['posixAccount'];
183 // LDAP aliases
184 $return['LDAPaliases'] = ['commonName' => 'cn', 'userid' => 'uid'];
185 // managed attributes
186 $return['attributes'] = ['uid', 'uidNumber', 'gidNumber',
187 'loginShell', 'gecos', 'INFO.userPasswordClearText'];
188 if ($this->get_scope() == "user") {
189 // self-service search attributes
190 $return['selfServiceSearchAttributes'] = ['uid'];
191 // self-service field settings
192 $return['selfServiceFieldSettings'] = [
193 'password' => _('Password'),
194 'cn' => _('Common name'),
195 'loginShell' => _('Login shell'),
196 'syncWindowsPassword' => _('Sync Unix password with Windows password'),
197 'unixgroups' => _('Groups (read-only)')
198 ];
199 // possible self-service read-only fields
200 $return['selfServiceReadOnlyFields'] = ['cn', 'loginShell'];
201 // self-service configuration settings
202 $selfServiceContainer = new htmlResponsiveRow();
203 $selfServiceContainer->add(new htmlResponsiveSelect('posixAccount_pwdHash', getSupportedHashTypes(),
204 ['CRYPT-SHA512'], _("Password hash type"), ['pwdHash', static::class]));
205 $selfServiceContainer->add(new htmlResponsiveInputTextarea('posixAccount_shells', implode("\r\n", $this->getShells()), 30, 4, _('Login shells'), ['loginShells', static::class]));
206 $selfServiceContainer->add(new htmlResponsiveInputField(_('Group DN'), 'posixAccount_groupDn', '', ['groupDn', static::class]));
207 $selfServiceContainer->add(new htmlResponsiveInputCheckbox('posixAccount_useOldPwd', false, _('Password change with old password'), ['useOldPwd', static::class]));
208 $return['selfServiceSettings'] = $selfServiceContainer;
209 }
210 // profile checks
211 $return['profile_checks']['posixAccount_homeDirectory'] = ['type' => 'ext_preg', 'regex' => 'homeDirectory',
212 'error_message' => $this->messages['homeDirectory'][0]];
213 // profile mappings
214 $return['profile_mappings'] = [
215 'posixAccount_loginShell' => 'loginShell'
216 ];
217 // upload
218 $return['upload_preDepends'] = ['inetOrgPerson'];
219 // user specific upload options
220 if (($this->get_scope() == 'user') && isLoggedIn()) {
221 $lamdaemonServers = $_SESSION['config']->getConfiguredScriptServers();
222 $lamdaemonOptions = [];
223 foreach ($lamdaemonServers as $lamdaemonServer) {
224 $lamdaemonOptions[] = $lamdaemonServer->getServer();
225 }
226 $return['upload_columns'] = [
227 [
228 'name' => 'posixAccount_userName',
229 'description' => _('User name'),
230 'help' => 'uidUser',
231 'example' => _('smiller'),
232 'required' => true,
233 'unique' => true
234 ],
235 [
236 'name' => 'posixAccount_uid',
237 'description' => _('UID number'),
238 'help' => 'uidNumber',
239 'example' => '1234'
240 ],
241 [
242 'name' => 'posixAccount_group',
243 'description' => _('Primary group'),
244 'help' => 'group_upload',
245 'example' => _('users'),
246 'required' => true
247 ],
248 [
249 'name' => 'posixAccount_additionalGroups',
250 'description' => _('Additional groups'),
251 'help' => 'addgroup_upload',
252 'example' => _('group01,group02')
253 ],
254 [
255 'name' => 'posixAccount_homedir',
256 'description' => _('Home directory'),
257 'help' => 'homeDirectory_upload',
258 'example' => _('/home/smiller'),
259 'default' => '/home/{posixAccount_userName}'
260 ],
261 ];
262 if (!empty($lamdaemonOptions)) {
263 $return['upload_columns'][] = [
264 'name' => 'posixAccount_createHomeDir',
265 'description' => _('Create home directory'),
266 'help' => 'createhomedir',
267 'example' => 'localhost',
268 'values' => implode(', ', $lamdaemonOptions)
269 ];
270 }
271 $return['upload_columns'][] = [
272 'name' => 'posixAccount_shell',
273 'description' => _('Login shell'),
274 'help' => 'loginShell',
275 'example' => '/bin/bash',
276 'values' => implode(", ", $this->getShells()),
277 'default' => '/bin/bash'
278 ];
279 if (self::areGroupOfNamesActive()) {
280 $return['upload_columns'][] = [
281 'name' => 'posixAccount_gon',
282 'description' => _('Groups of names'),
283 'help' => 'addgroup_upload',
284 'example' => _('group01,group02')
285 ];
286 }
287 }
288 // host specific upload options
289 elseif ($this->get_scope() == 'host') {
290 $return['upload_columns'] = [
291 [
292 'name' => 'posixAccount_hostName',
293 'description' => _('Host name'),
294 'help' => 'uidHost',
295 'example' => _('pc01$'),
296 'required' => true,
297 'unique' => true
298 ],
299 [
300 'name' => 'posixAccount_uid',
301 'description' => _('UID number'),
302 'help' => 'uidNumber',
303 'example' => '1234'
304 ],
305 [
306 'name' => 'posixAccount_group',
307 'description' => _('Primary group'),
308 'help' => 'group_upload',
309 'example' => _('machines'),
310 'required' => true
311 ],
312 ];
313 }
314 // available PDF fields
315 $return['PDF_fields'] = ($this->get_scope() === 'host') ? ['uid' => _('Host name')] : ['uid' => _('User name')];
316 $return['PDF_fields'] = array_merge($return['PDF_fields'], [
317 'uidNumber' => _('UID number'),
318 'gidNumber' => _('GID number'),
319 'primaryGroup' => _('Primary group'),
320 'additionalGroups' => _('Additional groups'),
321 'homeDirectory' => _('Home directory'),
322 'loginShell' => _('Login shell'),
323 'userPassword' => _('Password')
324 ]);
325 if (self::areGroupOfNamesActive()) {
326 $return['PDF_fields']['gon'] = _('Groups of names');
327 }
328 // help Entries
329 $return['help'] = [
330 'autoAdd' => [
331 "Headline" => _("Automatically add this extension"),
332 "Text" => _("This will enable the extension automatically if this profile is loaded.")
333 ],
334 'userNameSuggestion' => [
335 "Headline" => _("User name suggestion"),
336 "Text" => _("LAM will suggest a user name based on e.g. first and last name. Here you can specify the suggestion. %sn% will be replaced by the last name. @givenname@ will be replaced by the first character of first name. Only attributes of tab Personal may be used.")
337 . '<br>' . _('Common examples are "@givenname@%sn%" or "%givenname%.%sn%".')
338 ],
339 'hiddenOptions' => [
340 "Headline" => _("Hidden options"),
341 "Text" => _("The selected options will not be managed inside LAM. You can use this to reduce the number of displayed input fields.")
342 ],
343 'primaryGroupAsSecondary' => [
344 'Headline' => _('Set primary group as memberUid'),
345 'Text' => _('Usually, users are not added to groups as memberUid if they have this group as primary group. If your application ignores primary groups then you can select this option to override this behaviour.')
346 ],
347 'minMaxUser' => [
348 'Headline' => _('UID number'),
349 'Text' => _('These are the minimum and maximum numbers to use for user IDs when creating new user accounts. The range should be different from that of machines. New user accounts will always get the highest number in use plus one.')
350 ],
351 'minMaxHost' => [
352 'Headline' => _('UID number'),
353 'Text' => _('These are the minimum and maximum numbers to use for machine IDs when creating new accounts for hosts. The range should be different from that of users. New host accounts will always get the highest number in use plus one.')
354 ],
355 'pwdHash' => [
356 "Headline" => _("Password hash type"),
357 "Text" => _("LAM supports a large number of possibilities to generate the hash value of passwords. CRYPT-SHA512 and SSHA are the most common. We do not recommend to use plain text passwords unless passwords are hashed server-side.")
358 . ' ' . _('K5KEY is only needed if you use Kerberos with smbk5pwd.')
359 ],
360 'uidNumber' => [
361 "Headline" => _("UID number"), 'attr' => 'uidNumber',
362 "Text" => _("If empty UID number will be generated automatically.")
363 ],
364 'group_upload' => [
365 "Headline" => _("Primary group"),
366 "Text" => _("The primary group for this account. You can insert a GID number or a group name.")
367 ],
368 'addgroup_upload' => [
369 "Headline" => _("Additional groups"),
370 "Text" => _("Here you can enter a list of additional group memberships. The group names are separated by commas.")
371 ],
372 'homeDirectory_upload' => [
373 "Headline" => _("Home directory"), 'attr' => 'homeDirectory',
374 "Text" => _("Please enter the path to the user's home directory.")
375 ],
376 'homeDirectory' => [
377 "Headline" => _("Home directory"), 'attr' => 'homeDirectory',
378 "Text" => _("Please enter the path to the user's home directory.")
379 ],
380 'deletehomedir' => [
381 "Headline" => _("Home directory"),
382 "Text" => _("Activating this checkbox will remove the user's home directory.")
383 ],
384 'createhomedir' => [
385 "Headline" => _("Home directory"),
386 "Text" => _("This will create the user's home directory on the specified server.")
387 ],
388 'deleteSudoers' => [
389 "Headline" => _("Delete sudo rights"),
390 "Text" => _("Deletes the user from all existing sudo rights.")
391 ],
392 'uidCheckSuffix' => [
393 "Headline" => _("Suffix for UID/user name check"),
394 "Text" => _("LAM checks if the entered user name and UID are unique. Here you can enter the LDAP suffix that is used to search for duplicates. By default, the account type suffix is used. You only need to change this if you use multiple server profiles with different OUs but need unique user names or UIDs.")
395 ],
396 'loginShells' => [
397 "Headline" => _("Login shells"),
398 "Text" => _("This is the list of valid login shells.")
399 ],
400 'uidGenerator' => [
401 "Headline" => _("UID generator"),
402 "Text" => _("LAM will automatically suggest UID/GID numbers. You can either use a fixed range of numbers or an LDAP entry with object class \"sambaUnixIdPool\" or \"msSFU30DomainInfo\".")
403 . ' ' . _('Magic number will set a fixed value that must match your server configuration.')
404 ],
405 'sambaIDPoolDN' => [
406 "Headline" => _("Samba ID pool DN"),
407 "Text" => _("Please enter the DN of the LDAP entry with object class \"sambaUnixIdPool\".")
408 ],
409 'windowsIDPoolDN' => [
410 "Headline" => _("Windows domain info DN"),
411 "Text" => _("Please enter the DN of the LDAP entry with object class \"msSFU30DomainInfo\".")
412 ],
413 'magicNumber' => [
414 "Headline" => _("Magic number"),
415 "Text" => _("Please enter the magic number you configured on server side.")
416 ],
417 'noObjectClass' => [
418 "Headline" => _("Do not add object class"),
419 "Text" => _("This will not add the posixAccount object class to the account.")
420 ],
421 'excludeFromGroupSync' => [
422 "Headline" => _('Exclude from group sync'),
423 "Text" => _('Enter one group per line that should be ignored when syncing groups.')
424 ],
425 'groupDn' => [
426 "Headline" => _('Group DN'),
427 "Text" => _('Enter the base DN of your groups here. This is only required if you want to display memberships on the self-service page.')
428 ],
429 'userPassword' => [
430 "Headline" => _("Password"), 'attr' => 'userPassword',
431 "Text" => _("Please enter the password which you want to set for this account.")
432 ],
433 'userPassword_lock' => [
434 "Headline" => _("Lock password"),
435 "Text" => _("If checked then the password will be deactivated by putting a \"!\" before the encrypted password.")
436 ],
437 'useOldPwd' => [
438 "Headline" => _('Password change with old password'),
439 "Text" => _('Sends the old password together with the new password when the user sets a new password.')
440 ],
441 'loginShell' => [
442 "Headline" => _("Login shell"), 'attr' => 'loginShell',
443 "Text" => _("To disable login use /bin/false.")
444 ],
445 'addgroup' => [
446 "Headline" => _("Additional groups"),
447 "Text" => _("Hold the CTRL-key to (de)select multiple groups.") . ' ' . _("Can be left empty.")
448 ],
449 'description' => [
450 "Headline" => _("Description"), 'attr' => 'description',
451 "Text" => _("Host description. If left empty host name will be used.")
452 ],
453 'uidUser' => [
454 "Headline" => _("User name"), 'attr' => 'uid',
455 "Text" => _("User name of the user who should be created. Valid characters are: a-z,A-Z,0-9, @.-_. If user name is already used user name will be expanded with a number. The next free number will be used.")
456 ],
457 'gecosUser' => [
458 "Headline" => _("Gecos"), 'attr' => 'gecos',
459 "Text" => _("User description.")
460 ],
461 'gidNumberUser' => [
462 "Headline" => _("Primary group"), 'attr' => 'gidNumber',
463 "Text" => _("The primary group the user should be member of.")
464 ],
465 'cnUser' => [
466 "Headline" => _("Common name"), 'attr' => 'cn',
467 "Text" => _("This is the natural name of the user. If empty, the first and last name or user name is used.")
468 ],
469 'uidHost' => [
470 "Headline" => _("Host name"), 'attr' => 'uid',
471 "Text" => _("Host name of the host which should be created. Valid characters are: a-z,A-Z,0-9, .-_$. Host names are always ending with $. If last character is not $ it will be added. If host name is already used host name will be expanded with a number. The next free number will be used.")
472 ],
473 'gecosHost' => [
474 "Headline" => _("Gecos"), 'attr' => 'gecos',
475 "Text" => _("Host description.")
476 ],
477 'gidNumberHost' => [
478 "Headline" => _("Primary group"), 'attr' => 'gidNumber',
479 "Text" => _("The primary group the host should be member of.")
480 ],
481 'cnHost' => [
482 "Headline" => _("Common name"), 'attr' => 'cn',
483 "Text" => _("This is the natural name of the host. If empty, the host name will be used.")
484 ]
485 ];
486
487 return $return;
488 }
489
490 /**
491 * {@inheritDoc}
492 */
493 public function init(string $base): void {
494 // make optional if needed
495 $modules = $_SESSION[$base]->get_type()->getModules();
496 $this->autoAddObjectClasses = !$this->isOptional($modules) && !$this->skipObjectClass();
497 // call parent init
498 parent::init($base);
499 $this->groups = [];
500 $this->groups_orig = [];
501 // list of all group names
502 $groups = $this->findGroups($modules);
503 if (count($groups) === 0) {
504 StatusMessage("ERROR", _('No Unix groups found in LDAP! Please create one first.'));
505 return;
506 }
507 $this->gonList = [];
508 $this->gonList_orig = [];
509 }
510
511 /**
512 * {@inheritDoc}
513 */
514 public function getManagedAttributes(string $typeId): array {
515 $attrs = parent::getManagedAttributes($typeId);
516 $typeManager = new TypeManager();
517 if (!$typeManager->hasConfig()) {
518 return $attrs;
519 }
520 $modules = $typeManager->getConfiguredType($typeId)->getModules();
521 if ($this->manageCn($modules)) {
522 $attrs[] = 'cn';
523 }
524 $attrs[] = $this->getHomedirAttrName($modules);
525 $attrs[] = $this->getPasswordAttrName($modules);
526 return $attrs;
527 }
528
529 /**
530 * {@inheritDoc}
531 */
532 public function module_complete(): bool {
533 if (!$this->skipObjectClass() && (!isset($this->attributes['objectClass']) || !in_array('posixAccount', $this->attributes['objectClass']))) {
534 // no checks if object class is not set
535 return true;
536 }
537 if (!isset($this->attributes['uid'][0]) || ($this->attributes['uid'][0] == '')) {
538 return false;
539 }
540 if (!isset($this->attributes['uidNumber'][0]) || ($this->attributes['uidNumber'][0] == '')) {
541 return false;
542 }
543 return (isset($this->attributes['gidNumber'][0]) && ($this->attributes['gidNumber'][0] != ''));
544 }
545
546 /**
547 * {@inheritDoc}
548 */
549 public function load_attributes(array $attributes): void {
550 parent::load_attributes($attributes);
551 // get additional group memberships
552 if (!isset($attributes['uid'][0])) {
553 return;
554 }
555 $this->groups = $this->getUnixGroupMemberships($attributes['uid'][0]);
556 $this->groups_orig = $this->groups;
557 // get additional group of names memberships
558 if (self::areGroupOfNamesActive()) {
559 $this->gonList_orig = $this->getGoNMemberships($this->getAccountContainer()->dn_orig);
560 $this->gonList = $this->gonList_orig;
561 }
562 }
563
564 /**
565 * Returns the list of group names for the given user id.
566 *
567 * @param string $uid UID
568 * @return string[] group names
569 */
570 private function getUnixGroupMemberships(string $uid): array {
571 $typeSettings = $_SESSION['config']->get_typeSettings();
572 $groups = [];
573 $groupFilter = '(&(objectClass=posixGroup)(memberUid=' . $uid . '))';
574 if (!empty($typeSettings['filter_group'])) {
575 $typeFilter = $typeSettings['filter_group'];
576 if (!str_starts_with($typeFilter, '(')) {
577 $typeFilter = '(' . $typeFilter . ')';
578 }
579 $groupFilter = '(&' . $groupFilter . $typeFilter . ')';
580 }
581 $groupList = searchLDAPByFilter($groupFilter, ['cn'], ['group']);
582 for ($i = 0; $i < count($groupList); $i++) {
583 $groups[] = $groupList[$i]['cn'][0];
584 }
585 return $groups;
586 }
587
588 /**
589 * Returns the list of group of names for the given user id.
590 *
591 * @param string $dn DN
592 * @return string[] group of names
593 */
594 private function getGoNMemberships(string $dn): array {
595 $typeSettings = $_SESSION['config']->get_typeSettings();
596 $userGoNs = [];
597 $types = ['gon', 'group'];
598 $gonList = [];
599 foreach ($types as $type) {
600 $gonFilter = '(|(&(objectClass=groupOfNames)(member=' . ldap_escape($dn, '', LDAP_ESCAPE_FILTER) . '))(&(objectClass=groupOfMembers)(member=' . ldap_escape($dn) . '))(&(objectClass=groupOfUniqueNames)(uniquemember=' . ldap_escape($dn) . ')))';
601 if (!empty($typeSettings['filter_' . $type])) {
602 $typeFilter = $typeSettings['filter_' . $type];
603 if (!str_starts_with($typeFilter, '(')) {
604 $typeFilter = '(' . $typeFilter . ')';
605 }
606 $gonFilter = '(&' . $gonFilter . $typeFilter . ')';
607 }
608 $gonListPart = searchLDAPByFilter($gonFilter, ['dn'], [$type]);
609 $gonList = array_merge($gonList, $gonListPart);
610 }
611 for ($i = 0; $i < count($gonList); $i++) {
612 $userGoNs[] = $gonList[$i]['dn'];
613 }
614 return array_values(array_unique($userGoNs));
615 }
616
617 /**
618 * {@inheritDoc}
619 */
620 public function loadAttributesFromAccountCopy(array $ldapAttributes, array $attributesToIgnore = []): void {
621 parent::loadAttributesFromAccountCopy($ldapAttributes, $attributesToIgnore);
622 if (!empty($ldapAttributes['uid'][0])) {
623 $this->groups = $this->getUnixGroupMemberships($ldapAttributes['uid'][0]);
624 }
625 if (self::areGroupOfNamesActive()) {
626 $this->gonList = $this->getGoNMemberships($ldapAttributes['dn']);
627 }
628 }
629
630 /**
631 * {@inheritDoc}
632 */
633 public function save_attributes(): array {
634 if (!$this->skipObjectClass() && (!in_array('posixAccount', $this->attributes['objectClass']) && !in_array('posixAccount', $this->orig['objectClass']))) {
635 // skip saving if the extension was not added/modified
636 return [];
637 }
638 if ($this->allowsToCreateGroupWithSameName() && isset($this->attributes['gidNumber'][0]) && ($this->attributes['gidNumber'][0] === self::CREATE_GROUP_WITH_SAME_NAME)) {
639 $newGroupName = $this->attributes['uid'][0];
640 $existingGid = $this->getGID($newGroupName);
641 if ($existingGid !== null) {
642 $this->attributes['gidNumber'][0] = $existingGid;
643 }
644 else {
645 $groupType = $this->getPosixGroupType();
646 $sessionKey = 'TMP' . generateRandomText();
647 $accountContainerTmp = new accountContainer($groupType, $sessionKey);
648 $_SESSION[$sessionKey] = &$accountContainerTmp;
649 $accountContainerTmp->new_account();
650 $isRfc2307bis = false;
651 $posixGroupModule = $accountContainerTmp->getAccountModule('posixGroup');
652 $posixGroupRfc2307bisModule = $accountContainerTmp->getAccountModule('rfc2307bisPosixGroup');
653 if (($posixGroupModule === null) && ($posixGroupRfc2307bisModule !== null)) {
654 $posixGroupModule = $posixGroupRfc2307bisModule;
655 $isRfc2307bis = true;
656 }
657 $errors = [];
658 $nextGid = $posixGroupModule->getNextGIDs(1, $errors, $groupType);
659 unset($_SESSION[$sessionKey]);
660 if ($nextGid !== null) {
661 $dnNewGroup = 'cn=' . $newGroupName . ',' . $groupType->getSuffix();
662 if ($isRfc2307bis) {
663 $attributesNewGroup = [
664 'cn' => [$newGroupName],
665 'gidNumber' => $nextGid[0],
666 'objectClass' => ['namedObject', 'posixGroup'],
667 ];
668 }
669 else {
670 $attributesNewGroup = [
671 'cn' => [$newGroupName],
672 'gidNumber' => $nextGid[0],
673 'objectClass' => ['posixGroup'],
674 ];
675 }
676 $newGroupSuccess = @ldap_add(getLDAPServerHandle(), $dnNewGroup, $attributesNewGroup);
677 if ($newGroupSuccess) {
678 logNewMessage(LOG_NOTICE, 'Created new group: ' . $newGroupName);
679 $this->attributes['gidNumber'][0] = (string) $nextGid[0];
680 $this->groupCache = null;
681 }
682 else {
683 logNewMessage(LOG_ERR, 'Unable to create new group: ' . getDefaultLDAPErrorString(getLDAPServerHandle()));
684 }
685 }
686 }
687 }
688 $modules = $this->getAccountContainer()->get_type()->getModules();
689 // get default changes
690 $return = parent::save_attributes();
691 // add information about clear text password and password status change
692 $return[$this->getAccountContainer()->dn_orig]['info']['userPasswordClearText'][0] = $this->clearTextPassword;
693 $pwdAttrName = $this->getPasswordAttrName($modules);
694 if (isset($this->orig[$pwdAttrName][0]) && isset($this->attributes[$pwdAttrName][0])) {
695 if ((pwd_is_enabled($this->orig[$pwdAttrName][0]) && pwd_is_enabled($this->attributes[$pwdAttrName][0]))
696 || (!pwd_is_enabled($this->orig[$pwdAttrName][0]) && !pwd_is_enabled($this->attributes[$pwdAttrName][0]))) {
697 $return[$this->getAccountContainer()->dn_orig]['info']['userPasswordStatusChange'][0] = 'unchanged';
698 }
699 elseif (pwd_is_enabled($this->orig[$pwdAttrName][0])) {
700 $return[$this->getAccountContainer()->dn_orig]['info']['userPasswordStatusChange'][0] = 'locked';
701 }
702 else {
703 $return[$this->getAccountContainer()->dn_orig]['info']['userPasswordStatusChange'][0] = 'unlocked';
704 }
705 }
706 if ($this->skipObjectClass() || in_array('posixAccount', $this->attributes['objectClass'])) {
707 // Remove primary group from additional groups
708 if (!isset($this->moduleSettings['posixAccount_primaryGroupAsSecondary'][0])
709 || ($this->moduleSettings['posixAccount_primaryGroupAsSecondary'][0] != 'true')) {
710 for ($i = 0; $i < count($this->groups); $i++) {
711 if ($this->groups[$i] == $this->getGroupName($this->attributes['gidNumber'][0])) {
712 unset($this->groups[$i]);
713 }
714 }
715 }
716 else {
717 // add user as memberuid in primary group
718 $primaryGroupName = $this->getGroupName($this->attributes['gidNumber'][0]);
719 if (!in_array($primaryGroupName, $this->groups)) {
720 $this->groups[] = $primaryGroupName;
721 }
722 // add user as member in group of names if auto-sync is activated
723 if ($this->isBooleanConfigOptionSet('posixGroup_autoSyncGon')) {
724 $allGons = $this->findGroupOfNames();
725 foreach ($allGons as $gonDn => $gonData) {
726 if (in_array_ignore_case('posixGroup', $gonData['objectclass'])) {
727 $gonCn = $gonData['cn'][0];
728 if (($gonCn === $primaryGroupName) && !in_array($gonDn, $this->gonList)) {
729 $this->gonList[] = $gonDn;
730 }
731 }
732 }
733 }
734 }
735
736 // Set additional group memberships
737 if (isset($this->orig['uid'][0]) && ($this->orig['uid'][0] != '') && ($this->attributes['uid'][0] != $this->orig['uid'][0])) {
738 // find affected groups
739 $groupList = searchLDAPByAttribute('memberUid', $this->orig['uid'][0], 'posixGroup', ['dn'], ['group']);
740 for ($i = 0; $i < count($groupList); $i++) {
741 // replace old user name with new one
742 $return[$groupList[$i]['dn']]['remove']['memberUid'][] = $this->orig['uid'][0];
743 $return[$groupList[$i]['dn']]['add']['memberUid'][] = $this->attributes['uid'][0];
744 }
745 }
746 else {
747 // update groups.
748 $add = array_delete($this->groups_orig, $this->groups);
749 $remove = array_delete($this->groups, $this->groups_orig);
750 $groupList = searchLDAPByAttribute('cn', '*', 'posixGroup', ['cn', 'dn'], ['group']);
751 $cn2dn = [];
752 for ($i = 0; $i < count($groupList); $i++) {
753 $cn2dn[$groupList[$i]['cn'][0]] = $groupList[$i]['dn'];
754 }
755 for ($i = 0; $i < count($add); $i++) {
756 if (isset($cn2dn[$add[$i]])) {
757 $return[$cn2dn[$add[$i]]]['add']['memberUid'][] = $this->attributes['uid'][0];
758 }
759 }
760 for ($i = 0; $i < count($remove); $i++) {
761 if (isset($cn2dn[$remove[$i]])) {
762 $return[$cn2dn[$remove[$i]]]['remove']['memberUid'][] = $this->attributes['uid'][0];
763 }
764 }
765 }
766 }
767 elseif (in_array('posixAccount', $this->orig['objectClass']) && !empty($this->orig['uid'][0])) {
768 // Unix extension was removed, clean group memberships
769 $groupList = searchLDAPByAttribute('memberUid', $this->orig['uid'][0], 'posixGroup', ['dn'], ['group']);
770 for ($i = 0; $i < count($groupList); $i++) {
771 // remove user name
772 $return[$groupList[$i]['dn']]['remove']['memberUid'][] = $this->orig['uid'][0];
773 }
774 }
775 return $return;
776 }
777
778 /**
779 * {@inheritDoc}
780 */
781 public function postModifyActions(bool $newAccount, array $attributes): array {
782 $messages = [];
783 $accountContainer = $this->getAccountContainer();
784 if (($accountContainer == null) || empty($accountContainer->finalDN)) {
785 return $messages;
786 }
787 $modules = $accountContainer->get_type()->getModules();
788 // set exop password
789 $messages = array_merge($messages, $this->setExopPassword($this->moduleSettings));
790 // create home directories if needed
791 $homeDirAttr = $this->getHomedirAttrName($modules);
792 $lamdaemonServerList = $_SESSION['config']->getConfiguredScriptServers();
793 if (count($this->lamdaemonServers) > 0) {
794 foreach ($lamdaemonServerList as $lamdaemonServer) {
795 if (!in_array($lamdaemonServer->getServer(), $this->lamdaemonServers)) {
796 continue;
797 }
798 $remote = new Remote();
799 try {
800 $remote->connect($lamdaemonServer);
801 }
802 catch (LAMException $e) {
803 $messages[] = ['ERROR', $e->getTitle(), $e->getMessage()];
804 continue;
805 }
806 $result = self::createHomeDirectory($remote, $lamdaemonServer, $this->attributes['uid'][0],
807 $this->attributes[$homeDirAttr][0], $this->attributes['uidNumber'][0],
808 $this->attributes['gidNumber'][0], $_SESSION['config']->get_scriptRights());
809 $remote->disconnect();
810 // lamdaemon results
811 if (!empty($result)) {
812 $singleresult = explode(",", $result);
813 $messages[] = in_array($singleresult[0], ['ERROR', 'INFO', 'WARN'], true) ? $singleresult : ['ERROR', $result];
814 }
815 }
816 }
817 // move home directory if needed
818 if (!empty($this->orig[$homeDirAttr][0]) && !empty($this->attributes[$homeDirAttr][0])
819 && ($this->orig[$homeDirAttr][0] != $this->attributes[$homeDirAttr][0])) {
820 foreach ($lamdaemonServerList as $lamdaemonServer) {
821 $remote = new Remote();
822 try {
823 $remote->connect($lamdaemonServer);
824 }
825 catch (LAMException $e) {
826 $messages[] = ['ERROR', $e->getTitle(), $e->getMessage()];
827 continue;
828 }
829 $result = $remote->execute(
830 implode(
831 self::$SPLIT_DELIMITER,
832 [
833 $this->attributes['uid'][0],
834 "home",
835 "move",
836 $lamdaemonServer->getHomeDirPrefix() . $this->orig[$homeDirAttr][0],
837 $this->attributes['uidNumber'][0],
838 $lamdaemonServer->getHomeDirPrefix() . $this->attributes[$homeDirAttr][0]]
839 ));
840 $remote->disconnect();
841 // lamdaemon results
842 if (!empty($result)) {
843 $singleresult = explode(",", $result);
844 if (in_array($singleresult[0], ['ERROR', 'INFO', 'WARN'], true)) {
845 $messages[] = $singleresult;
846 }
847 }
848 }
849 }
850 // set new group on homedirectory
851 if (!empty($this->orig[$homeDirAttr][0]) && !empty($this->attributes[$homeDirAttr][0])
852 && ($this->orig['gidNumber'][0] != $this->attributes['gidNumber'][0])) {
853 foreach ($lamdaemonServerList as $lamdaemonServer) {
854 $remote = new Remote();
855 try {
856 $remote->connect($lamdaemonServer);
857 }
858 catch (LAMException $e) {
859 $messages[] = ['ERROR', $e->getTitle(), $e->getMessage()];
860 continue;
861 }
862 $result = $remote->execute(
863 implode(
864 self::$SPLIT_DELIMITER,
865 [
866 $this->attributes['uid'][0],
867 "home",
868 "chgrp",
869 $lamdaemonServer->getHomeDirPrefix() . $this->attributes[$homeDirAttr][0],
870 $this->attributes['uidNumber'][0],
871 $this->attributes['gidNumber'][0]]
872 ));
873 $remote->disconnect();
874 // lamdaemon results
875 if (!empty($result)) {
876 $singleresult = explode(",", $result);
877 if (in_array($singleresult[0], ['ERROR', 'INFO', 'WARN'], true)) {
878 $messages[] = $singleresult;
879 }
880 }
881 }
882 }
883 // set group of names
884 if (self::areGroupOfNamesActive()) {
885 $gons = $this->findGroupOfNames();
886 $toAdd = array_values(array_diff($this->gonList, $this->gonList_orig));
887 $toRem = array_values(array_diff($this->gonList_orig, $this->gonList));
888 // update groups if DN changed
889 if (isset($accountContainer->dn_orig) && (strtolower($accountContainer->dn_orig) !== strtolower($accountContainer->finalDN))) {
890 // update owner/member/uniqueMember attributes
891 $searchAttrs = ['member', 'uniquemember', 'owner'];
892 foreach ($searchAttrs as $searchAttr) {
893 $ownerGroups = searchLDAPByAttribute($searchAttr, $accountContainer->dn_orig, null, ['dn', $searchAttr], ['gon', 'group']);
894 for ($i = 0; $i < count($ownerGroups); $i++) {
895 $found = false;
896 $newOwners = $ownerGroups[$i][$searchAttr];
897 for ($o = 0; $o < count($newOwners); $o++) {
898 if ($newOwners[$o] == $accountContainer->dn_orig) {
899 $newOwners[$o] = $accountContainer->finalDN;
900 $found = true;
901 break;
902 }
903 }
904 if ($found) {
905 $attributesToModify = [$searchAttr => $newOwners];
906 $success = @ldap_mod_replace($_SESSION['ldap']->server(), $ownerGroups[$i]['dn'], $attributesToModify);
907 if (!$success) {
908 $ldapError = getDefaultLDAPErrorString($_SESSION['ldap']->server());
909 logNewMessage(LOG_ERR, 'Unable to modify attributes of DN: ' . $ownerGroups[$i]['dn'] . ' (' . $ldapError . ').');
910 logNewMessage(LOG_DEBUG, print_r($attributesToModify, true));
911 $messages[] = ['ERROR', sprintf(_('Was unable to modify attributes of DN: %s.'), $ownerGroups[$i]['dn']), $ldapError];
912 }
913 }
914 }
915 }
916 }
917 // add groups
918 for ($i = 0; $i < count($toAdd); $i++) {
919 if (isset($gons[$toAdd[$i]])) {
920 $attrName = 'member';
921 if (in_array_ignore_case('groupOfUniqueNames', $gons[$toAdd[$i]]['objectclass'])) {
922 $attrName = 'uniquemember';
923 }
924 $success = @ldap_mod_add($_SESSION['ldap']->server(), $toAdd[$i], [$attrName => [$accountContainer->finalDN]]);
925 if (!$success) {
926 logNewMessage(LOG_ERR, 'Unable to add user ' . $accountContainer->finalDN . ' to group: ' . $toAdd[$i] . ' (' . ldap_error($_SESSION['ldap']->server()) . ').');
927 $messages[] = ['ERROR', sprintf(_('Was unable to add attributes to DN: %s.'), $toAdd[$i]), getDefaultLDAPErrorString($_SESSION['ldap']->server())];
928 }
929 else {
930 logNewMessage(LOG_NOTICE, 'Added user ' . $accountContainer->finalDN . ' to group: ' . $toAdd[$i]);
931 }
932 }
933 }
934 // remove groups
935 for ($i = 0; $i < count($toRem); $i++) {
936 if (isset($gons[$toRem[$i]])) {
937 $attrName = 'member';
938 if (in_array_ignore_case('groupOfUniqueNames', $gons[$toRem[$i]]['objectclass'])) {
939 $attrName = 'uniquemember';
940 }
941 $success = @ldap_mod_del($_SESSION['ldap']->server(), $toRem[$i], [$attrName => [$accountContainer->dn_orig]]);
942 if (!$success) {
943 logNewMessage(LOG_ERR, 'Unable to delete user ' . $accountContainer->finalDN . ' from group: ' . $toRem[$i] . ' (' . ldap_error($_SESSION['ldap']->server()) . ').');
944 $messages[] = ['ERROR', sprintf(_('Was unable to remove attributes from DN: %s.'), $toRem[$i]), getDefaultLDAPErrorString($_SESSION['ldap']->server())];
945 }
946 else {
947 logNewMessage(LOG_NOTICE, 'Removed user ' . $accountContainer->finalDN . ' from group: ' . $toRem[$i]);
948 }
949 }
950 }
951 }
952 return $messages;
953 }
954
955 /**
956 * Creates a user home directory.
957 *
958 * @param Remote $remote remote connection
959 * @param RemoteServerConfiguration $config remote configuration
960 * @param string $userName user name
961 * @param string $path home directory path
962 * @param string $uidNumber uid number
963 * @param string $gidNumber gid number
964 * @param string $rights rights (e.g. 750)
965 * @return string output
966 */
967 public static function createHomeDirectory(Remote $remote, RemoteServerConfiguration $config, string $userName,
968 string $path, string $uidNumber, string $gidNumber, string $rights) {
969 if ($rights === '') {
970 $rights = '750';
971 }
972 if (!str_starts_with($rights, '0')) {
973 $rights = '0' . $rights;
974 }
975 return $remote->execute(
976 implode(
977 self::$SPLIT_DELIMITER,
978 [
979 $userName,
980 "home",
981 "add",
982 $config->getHomeDirPrefix() . $path,
983 $rights,
984 $uidNumber,
985 $gidNumber]
986 ));
987 }
988
989 /**
990 * Sets the password via ldap_exop if configured.
991 *
992 * @param array<string, string[]> $settings settings
993 * @return array<string|string[]>[] error message parameters if any
994 */
995 private function setExopPassword($settings): array {
996 if (!empty($this->clearTextPassword) && !empty($settings['posixAccount_pwdHash'][0])
997 && ($settings['posixAccount_pwdHash'][0] === 'LDAP_EXOP')) {
998 $success = ldap_exop_passwd($_SESSION['ldap']->server(), $this->getAccountContainer()->finalDN, '', $this->clearTextPassword);
999 if (!$success) {
1000 return [['ERROR', _('Unable to set password'), getExtendedLDAPErrorMessage($_SESSION['ldap']->server())]];
1001 }
1002 }
1003 return [];
1004 }
1005
1006 /**
1007 * {@inheritDoc}
1008 */
1009 public function delete_attributes(): array {
1010 $return = [];
1011 // remove memberUids if set
1012 $groups = searchLDAPByAttribute('memberUid', $this->attributes['uid'][0], 'posixGroup', ['dn'], ['group']);
1013 for ($i = 0; $i < count($groups); $i++) {
1014 $return[$groups[$i]['dn']]['remove']['memberUid'][] = $this->attributes['uid'][0];
1015 }
1016 // stop here if referential integrity overlay is active
1017 $config = $this->getAccountContainer()->get_type()->getTypeManager()->getConfig();
1018 if ($config->isReferentialIntegrityOverlayActive()) {
1019 return $return;
1020 }
1021 // remove from group of names
1022 $dn = $this->getAccountContainer()->dn_orig;
1023 $filter = '(&(|(member=' . $dn . ')(uniquemember=' . $dn . '))(|(objectClass=groupOfNames)(objectClass=groupOfUniqueNames)(objectClass=groupOfMembers)))';
1024 $gons = searchLDAPByFilter($filter, ['member', 'uniquemember'], ['group', 'gon']);
1025 for ($i = 0; $i < count($gons); $i++) {
1026 if (isset($gons[$i]['member'])) {
1027 $return[$gons[$i]['dn']]['remove']['member'][] = $dn;
1028 }
1029 elseif (isset($gons[$i]['uniquemember'])) {
1030 $return[$gons[$i]['dn']]['remove']['uniquemember'][] = $dn;
1031 }
1032 }
1033 return $return;
1034 }
1035
1036 /**
1037 * {@inheritDoc}
1038 */
1039 public function preDeleteActions(): array {
1040 $return = [];
1041 // delete home directory
1042 if (isset($_POST['deletehomedir']) && ($_POST['deletehomedir'] == 'on')) {
1043 $modules = $this->getAccountContainer()->get_type()->getModules();
1044 $homeDirAttr = $this->getHomedirAttrName($modules);
1045 // get list of lamdaemon servers
1046 $lamdaemonServers = $_SESSION['config']->getConfiguredScriptServers();
1047 // try to delete directory on all servers
1048 foreach ($lamdaemonServers as $lamdaemonServer) {
1049 $remote = new Remote();
1050 try {
1051 $remote->connect($lamdaemonServer);
1052 $result = $remote->execute(
1053 implode(
1054 self::$SPLIT_DELIMITER,
1055 [
1056 $this->attributes['uid'][0],
1057 "home",
1058 "rem",
1059 $lamdaemonServer->getHomeDirPrefix() . $this->attributes[$homeDirAttr][0],
1060 $this->attributes['uidNumber'][0]
1061 ]
1062 ));
1063 $remote->disconnect();
1064 }
1065 catch (LAMException $e) {
1066 $return[] = ['ERROR', $e->getTitle(), $e->getMessage()];
1067 }
1068 // lamdaemon results
1069 if (!empty($result)) {
1070 $singleresult = explode(",", $result);
1071 if (in_array($singleresult[0], ['ERROR', 'WARN', 'INFO'], true)) {
1072 $return[] = $singleresult;
1073 }
1074 }
1075 }
1076 }
1077 // delete sudo rights
1078 if (isset($_POST['deleteSudoers']) && ($_POST['deleteSudoers'] == 'on')) {
1079 $result = searchLDAPByAttribute('sudoUser', $this->attributes['uid'][0], 'sudoRole', ['dn'], ['sudo']);
1080 foreach ($result as $attrs) {
1081 $dn = $attrs['dn'];
1082 $success = @ldap_mod_del($_SESSION['ldap']->server(), $dn, ['sudoUser' => [$this->attributes['uid'][0]]]);
1083 if (!$success) {
1084 $return[] = ['ERROR', getDefaultLDAPErrorString($_SESSION['ldap']->server())];
1085 }
1086 }
1087 }
1088 return $return;
1089 }
1090
1091 /**
1092 * {@inheritDoc}
1093 */
1094 public function process_attributes(): array {
1095 $this->getAccountContainer()->replaceWildcardsInPOST($this->getWildcardTargetAttributeNames());
1096 $modules = $this->getAccountContainer()->get_type()->getModules();
1097 $typeId = $this->getAccountContainer()->get_type()->getId();
1098 $errors = [];
1099 if (isset($_POST['addObjectClass'])) {
1100 if (!isset($this->attributes['objectClass'])) {
1101 $this->attributes['objectClass'] = [];
1102 }
1103 if (!in_array('posixAccount', $this->attributes['objectClass'])) {
1104 $this->attributes['objectClass'][] = 'posixAccount';
1105 }
1106 return $errors;
1107 }
1108 if (isset($_POST['remObjectClass'])) {
1109 $this->attributes['objectClass'] = array_delete(['posixAccount'], $this->attributes['objectClass']);
1110 $attrs = $this->getManagedAttributes($this->getAccountContainer()->get_type()->getId());
1111 foreach ($attrs as $name) {
1112 if (isset($this->attributes[$name])) {
1113 unset($this->attributes[$name]);
1114 }
1115 }
1116 return $errors;
1117 }
1118 // skip processing if object class is not set
1119 if ($this->isOptional($modules) && !$this->skipObjectClass() && (!isset($this->attributes['objectClass']) || !in_array('posixAccount', $this->attributes['objectClass']))) {
1120 return $errors;
1121 }
1122 $groups = $this->findGroups($modules); // list of all group names
1123 if (count($groups) === 0) {
1124 // abort if no groups were found
1125 return [];
1126 }
1127 if (isset($_POST['loginShell'])) {
1128 $this->attributes['loginShell'][0] = $_POST['loginShell'];
1129 }
1130 if (!$this->isBooleanConfigOptionSet('posixAccount_' . $typeId . '_hidegecos') && isset($_POST['gecos'])) {
1131 $this->attributes['gecos'][0] = $_POST['gecos'];
1132 }
1133 if (isset($this->orig['uid'][0]) && ($this->orig['uid'][0] != '') && (trim($_POST['uid']) != $this->attributes['uid'][0])) {
1134 $errors[] = $this->messages['uid'][0];
1135 }
1136 if (isset($this->orig['gidNumber'][0]) && ($this->orig['gidNumber'][0] != '') && ($_POST['gidNumber'] != $this->attributes['gidNumber'][0])) {
1137 $errorMessage = $this->messages['gidNumber'][2];
1138 $errorMessage[] = [$this->orig['gidNumber'][0], $this->orig['uidNumber'][0], $_POST['gidNumber']];
1139 $errors[] = $errorMessage;
1140 if ($this->isBooleanConfigOptionSet('posixAccount_primaryGroupAsSecondary') && !empty($this->attributes['gidNumber'][0])) {
1141 // change primary group in $this->groups
1142 $oldGroupName = $this->getGroupName($this->attributes['gidNumber'][0]);
1143 $newGroupName = $this->getGroupName($_POST['gidNumber']);
1144 if (!empty($oldGroupName) && !empty($newGroupName)) {
1145 $this->groups = array_delete([$oldGroupName], $this->groups);
1146 $this->groups[] = $newGroupName;
1147 // sync group of names if needed
1148 if ($this->isBooleanConfigOptionSet('posixGroup_autoSyncGon')) {
1149 $allGons = $this->findGroupOfNames();
1150 foreach ($allGons as $gonDn => $gonData) {
1151 if (in_array_ignore_case('posixGroup', $gonData['objectclass'])) {
1152 $gonCn = $gonData['cn'][0];
1153 if (($gonCn === $newGroupName) && !in_array($gonDn, $this->gonList)) {
1154 $this->gonList[] = $gonDn;
1155 }
1156 if (($gonCn === $oldGroupName) && in_array($gonDn, $this->gonList)) {
1157 $this->gonList = array_delete([$gonDn], $this->gonList);
1158 }
1159 }
1160 }
1161 }
1162 }
1163 }
1164 }
1165 if (isset($this->orig['uidNumber'][0]) && $this->orig['uidNumber'][0] != '' && trim($_POST['uidNumber']) != $this->attributes['uidNumber'][0]) {
1166 $errorMessage = $this->messages['uidNumber'][5];
1167 $errorMessage[] = [$this->orig['uidNumber'][0], $_POST['uidNumber']];
1168 $errors[] = $errorMessage;
1169 }
1170 $homedirAttrName = $this->getHomedirAttrName($modules);
1171 if (isset($_POST['homeDirectory']) && isset($this->orig[$homedirAttrName][0]) && ($this->orig[$homedirAttrName][0] != '') && ($_POST['homeDirectory'] != $this->attributes[$homedirAttrName][0])) {
1172 $errorMessage = $this->messages['homeDirectory'][3];
1173 $errorMessage[] = [$this->orig[$homedirAttrName][0], $_POST['homeDirectory']];
1174 $errors[] = $errorMessage;
1175 }
1176 // get list of DNS names or IPs
1177 $lamdaemonServers = $_SESSION['config']->getConfiguredScriptServers();
1178 $this->lamdaemonServers = [];
1179 for ($h = 0; $h < count($lamdaemonServers); $h++) {
1180 if (isset($_POST['createhomedir_' . $h]) && ($_POST['createhomedir_' . $h] === 'on')) {
1181 $this->lamdaemonServers[] = $lamdaemonServers[$h]->getServer();
1182 }
1183 }
1184 if (isset($_POST['homeDirectory'])) {
1185 $this->attributes[$homedirAttrName][0] = $_POST['homeDirectory'];
1186 }
1187 // Load attributes
1188 if ($this->isPasswordManaged()) {
1189 if (isset($_POST['lockPassword'])) {
1190 $this->lock($modules);
1191 }
1192 if (isset($_POST['unlockPassword'])) {
1193 $this->unlock($modules);
1194 }
1195 if (isset($_POST['removePassword'])) {
1196 unset($this->attributes[$this->getPasswordAttrName($modules)]);
1197 }
1198 }
1199 if ($this->manageCn($modules)) {
1200 $this->processMultiValueInputTextField('cn', $errors, 'cn');
1201 }
1202 $this->attributes['uidNumber'][0] = trim($_POST['uidNumber']);
1203 $this->attributes['gidNumber'][0] = $_POST['gidNumber'];
1204 if ($this->get_scope() == 'user') {
1205 if (($this->attributes['uid'][0] != $_POST['uid']) && !get_preg($_POST['uid'], '!upper')) {
1206 $errors[] = $this->messages['uid'][1];
1207 }
1208 if (!get_preg($this->attributes[$homedirAttrName][0], 'homeDirectory')) {
1209 $errors[] = $this->messages['homeDirectory'][0];
1210 }
1211 }
1212 $this->attributes['uid'][0] = trim($_POST['uid']);
1213 // Check if UID is valid. If none value was entered, the next usable value will be inserted
1214 // load min and may uidNumber
1215 if ($this->get_scope() == 'user') {
1216 $minID = intval($this->moduleSettings['posixAccount_' . $typeId . '_minUID'][0]);
1217 $maxID = intval($this->moduleSettings['posixAccount_' . $typeId . '_maxUID'][0]);
1218 }
1219 else {
1220 $minID = intval($this->moduleSettings['posixAccount_' . $typeId . '_minMachine'][0]);
1221 $maxID = intval($this->moduleSettings['posixAccount_' . $typeId . '_maxMachine'][0]);
1222 }
1223 $uids = $this->getUIDs($typeId);
1224 if ($this->attributes['uidNumber'][0] === '') {
1225 // No id-number given
1226 if (!isset($this->orig['uidNumber'][0]) || ($this->orig['uidNumber'][0] == '')) {
1227 // new account -> we have to find a free id-number
1228 $newUID = $this->getNextUIDs(1, $errors, $typeId);
1229 if (is_array($newUID)) {
1230 $this->attributes['uidNumber'][0] = $newUID[0];
1231 }
1232 else {
1233 $errors[] = $this->messages['uidNumber'][3];
1234 }
1235 }
1236 else {
1237 $this->attributes['uidNumber'][0] = $this->orig['uidNumber'][0];
1238 }
1239 // old account -> return id-number which has been used
1240 }
1241 elseif ($this->getAccountContainer()->isNewAccount || !isset($this->orig['uidNumber'][0]) || ($this->orig['uidNumber'][0] != $this->attributes['uidNumber'][0])) {
1242 // check manual ID
1243 // check range
1244 if (($this->get_scope() === 'user')
1245 && (!isset($this->moduleSettings['posixAccount_' . $typeId . '_uidGeneratorUsers']) || ($this->moduleSettings['posixAccount_' . $typeId . '_uidGeneratorUsers'][0] === 'range'))
1246 && (!is_numeric($this->attributes['uidNumber'][0]) || ($this->attributes['uidNumber'][0] < $minID) || ($this->attributes['uidNumber'][0] > $maxID))) {
1247 $errors[] = ['ERROR', _('ID-Number'), sprintf(_('Please enter a value between %s and %s!'), $minID, $maxID)];
1248 }
1249 if (($this->get_scope() === 'host')
1250 && (!isset($this->moduleSettings['posixAccount_' . $typeId . '_uidGeneratorHosts']) || ($this->moduleSettings['posixAccount_' . $typeId . '_uidGeneratorHosts'][0] == 'range'))
1251 && (!is_numeric($this->attributes['uidNumber'][0]) || ($this->attributes['uidNumber'][0] < $minID) || ($this->attributes['uidNumber'][0] > $maxID))) {
1252 $errors[] = ['ERROR', _('ID-Number'), sprintf(_('Please enter a value between %s and %s!'), $minID, $maxID)];
1253 }
1254 // id-number is in use and account is a new account
1255 if ((in_array($this->attributes['uidNumber'][0], $uids)) && !isset($this->orig['uidNumber'][0])) {
1256 $errors[] = $this->messages['uidNumber'][3];
1257 }
1258 // id-number is in use, account is existing account and id-number is not used by itself
1259 if ((in_array($this->attributes['uidNumber'][0], $uids))
1260 && isset($this->orig['uidNumber'][0])
1261 && ($this->orig['uidNumber'][0] != $this->attributes['uidNumber'][0])) {
1262 $errors[] = $this->messages['uidNumber'][3];
1263 $this->attributes['uidNumber'][0] = $this->orig['uidNumber'][0];
1264 }
1265 }
1266 // Create automatic useraccount with number if original user already exists
1267 // Reset name to original name if new name is in use
1268 // Set username back to original name if new username is in use
1269 if ($this->userNameExists($this->attributes['uid'][0], $typeId) && isset($this->orig['uid'][0]) && ($this->orig['uid'][0] != '')) {
1270 $this->attributes['uid'][0] = $this->orig['uid'][0];
1271 }
1272 else {
1273 // Change uid to a new uid until a free uid is found
1274 while ($this->userNameExists($this->attributes['uid'][0], $typeId)) {
1275 $this->attributes['uid'][0] = $this->getNextUserName($this->attributes['uid'][0], array_keys($this->getAccountContainer()->getAccountModules()));
1276 }
1277 }
1278 // Show warning if LAM has changed username
1279 if ($this->attributes['uid'][0] != trim($_POST['uid'])) {
1280 $userNames = $this->getUserNames($typeId);
1281 if ($this->get_scope() == 'user') {
1282 $error = $this->messages['uid'][5];
1283 $error[] = [htmlspecialchars($userNames[trim($_POST['uid'])])];
1284 $errors[] = $error;
1285 }
1286 if ($this->get_scope() == 'host') {
1287 $error = $this->messages['uid'][6];
1288 $error[] = [htmlspecialchars($userNames[trim($_POST['uid'])])];
1289 $errors[] = $error;
1290 }
1291 }
1292 if (($this->get_scope() == 'user') && !get_preg($this->attributes['uid'][0], 'username')) {
1293 // Check if Username contains only valid characters
1294 $errors[] = $this->messages['uid'][2];
1295 }
1296 if ($this->get_scope() == 'host') {
1297 // Check if Hostname contains only valid characters
1298 if (!get_preg($this->attributes['uid'][0], 'hostname')) {
1299 $errors[] = $this->messages['uid'][4];
1300 }
1301 if (!isset($this->attributes[$homedirAttrName][0])) {
1302 $this->attributes[$homedirAttrName][0] = '/dev/null';
1303 }
1304 if (!isset($this->attributes['loginShell'][0])) {
1305 $this->attributes['loginShell'][0] = '/bin/false';
1306 }
1307 }
1308 $attributeList = [$homedirAttrName];
1309 if (!$this->isBooleanConfigOptionSet('posixAccount_' . $typeId . '_hidegecos')) {
1310 $attributeList[] = 'gecos';
1311 }
1312 for ($i = 0; $i < count($attributeList); $i++) {
1313 if (isset($this->attributes[$attributeList[$i]][0])) {
1314 $value = $this->attributes[$attributeList[$i]][0];
1315 $replacedValue = $this->checkASCII($value);
1316 if ($value != $replacedValue) {
1317 $this->attributes[$attributeList[$i]][0] = $replacedValue;
1318 $errors[] = ['WARN', $attributeList[$i], _('Changed value because only ASCII characters are allowed.')];
1319 }
1320 }
1321 }
1322 if ($this->get_scope() == 'user') {
1323 // set SASL password for new and renamed users
1324 if (!empty($this->attributes['uid'][0]) && !empty($this->moduleSettings['posixAccount_pwdHash'][0])
1325 && ($this->moduleSettings['posixAccount_pwdHash'][0] === 'SASL')) {
1326 $this->attributes[$this->getPasswordAttrName($modules)][0] = '{SASL}' . $this->attributes['uid'][0];
1327 }
1328 // set K5KEY password for new users
1329 if (!empty($this->moduleSettings['posixAccount_pwdHash'][0]) && ($this->moduleSettings['posixAccount_pwdHash'][0] === 'K5KEY')) {
1330 $this->attributes[$this->getPasswordAttrName($modules)][0] = pwd_hash('x', true, $this->moduleSettings['posixAccount_pwdHash'][0]);
1331 }
1332 }
1333 // Return error-messages
1334 return $errors;
1335 }
1336
1337 /**
1338 * Returns if groups with same name can be created.
1339 *
1340 * @param ?string $typeId type ID
1341 * @return bool creation is possible
1342 */
1343 private function allowsToCreateGroupWithSameName(?string $typeId = null): bool {
1344 if ($typeId === null) {
1345 $typeId = $this->getAccountContainer()->get_type()->getId();
1346 }
1347 if (($this->get_scope() !== 'user')
1348 || $this->isBooleanConfigOptionSet('posixAccount_' . $typeId . '_hideCreateGroup')) {
1349 return false;
1350 }
1351 $groupType = $this->getPosixGroupType();
1352 return ($groupType !== null);
1353 }
1354
1355 /**
1356 * Returns the first found group type that contains posixGroup.
1357 *
1358 * @return ConfiguredType|null type
1359 */
1360 private function getPosixGroupType() {
1361 $typeManager = new TypeManager();
1362 $groupTypes = $typeManager->getConfiguredTypesForScope('group');
1363 foreach ($groupTypes as $groupType) {
1364 $modules = $groupType->getModules();
1365 if (in_array('posixGroup', $modules)) {
1366 return $groupType;
1367 }
1368 if (in_array('rfc2307bisPosixGroup', $modules)) {
1369 return $groupType;
1370 }
1371 }
1372 return null;
1373 }
1374
1375 /**
1376 * Checks if an attribute contains only ASCII characters and replaces invalid characters.
1377 *
1378 * @param string $attribute attribute value
1379 * @return string attribute value with replaced non-ASCII characters
1380 */
1381 private function checkASCII(string $attribute): string {
1382 if ($attribute === '') {
1383 return '';
1384 }
1385 // replace special characters
1386 $attribute = str_replace(array_keys($this->umlautReplacements), array_values($this->umlautReplacements), $attribute);
1387 // remove remaining UTF-8 characters
1388 for ($c = 0; $c < strlen($attribute); $c++) {
1389 if (ord($attribute[$c]) > 127) {
1390 $attribute = str_replace($attribute[$c], "", $attribute);
1391 $c--;
1392 }
1393 }
1394 return $attribute;
1395 }
1396
1397 /**
1398 * Processes user input of the group selection page.
1399 * It checks if all input values are correct and updates the associated LDAP attributes.
1400 *
1401 * @return array<string|string[]>[] list of info/error messages
1402 */
1403 public function process_group(): array {
1404 $typeId = $this->getAccountContainer()->get_type()->getId();
1405 // Unix groups
1406 if ($this->isBooleanConfigOptionSet('posixGroup_autoSyncGon')) {
1407 $this->syncGonToGroups();
1408 }
1409 elseif (!$this->isBooleanConfigOptionSet('posixAccount_' . $typeId . '_hideposixGroups')) {
1410 if (isset($_POST['groups_2']) && isset($_POST['groups_left'])) { // Add groups to list
1411 // add new group
1412 $this->groups = @array_merge($this->groups, $_POST['groups_2']);
1413 }
1414 elseif (isset($_POST['groups_1']) && isset($_POST['groups_right'])) { // remove groups from list
1415 $this->groups = array_delete($_POST['groups_1'], $this->groups);
1416 }
1417 }
1418 // group of names
1419 if (self::areGroupOfNamesActive() && !$this->isBooleanConfigOptionSet('posixAccount_' . $typeId . '_hidegon')) {
1420 if (isset($_POST['gon_2']) && isset($_POST['gon_left'])) { // Add groups to list
1421 // add new group
1422 $this->gonList = @array_merge($this->gonList, $_POST['gon_2']);
1423 }
1424 elseif (isset($_POST['gon_1']) && isset($_POST['gon_right'])) { // remove groups from list
1425 $this->gonList = array_delete($_POST['gon_1'], $this->gonList);
1426 }
1427 }
1428 // sync Unix to GoN
1429 if (isset($_POST['form_subpage_posixAccount_group_syncU2GON'])) {
1430 $this->manualSyncUnixToGon($typeId);
1431 }
1432 // sync GoN to Unix
1433 if (isset($_POST['form_subpage_posixAccount_group_syncGON2U'])) {
1434 $this->manualSyncGonToUnix($this->getAccountContainer()->get_type());
1435 }
1436 // sync Windows to Unix
1437 if (isset($_POST['form_subpage_posixAccount_group_syncWin2U'])) {
1438 $this->manualSyncWindowsToUnix($this->getAccountContainer()->get_type());
1439 }
1440 return [];
1441 }
1442
1443 /**
1444 * Syncs the Unix groups to group of names.
1445 *
1446 * @param string $typeId type ID
1447 */
1448 private function manualSyncUnixToGon($typeId): void {
1449 $allGons = $this->findGroupOfNames();
1450 $namesToIgnore = [];
1451 if (!empty($this->moduleSettings['posixAccount_' . $typeId . '_syncGroupsExclusions'])) {
1452 $namesToIgnore = $this->moduleSettings['posixAccount_' . $typeId . '_syncGroupsExclusions'];
1453 array_map(trim(...), $namesToIgnore);
1454 }
1455 // remove all groups that are not in Unix
1456 if (isset($_POST['syncDeleteGroups']) && ($_POST['syncDeleteGroups'] == 'on')) {
1457 $toDelete = [];
1458 foreach ($this->gonList as $currentGon) {
1459 $gonName = $this->getGonName($currentGon, $allGons);
1460 if (in_array($gonName, $namesToIgnore) || in_array($gonName, $this->groups)) {
1461 continue;
1462 }
1463 $toDelete[] = $currentGon;
1464 }
1465 $this->gonList = array_delete($toDelete, $this->gonList);
1466 }
1467 // add groups that are not yet in groups of names
1468 foreach ($this->groups as $currentName) {
1469 if (in_array($currentName, $namesToIgnore)) {
1470 continue;
1471 }
1472 $found = false;
1473 foreach ($this->gonList as $currentGon) {
1474 if ($currentName == $this->getGonName($currentGon, $allGons)) {
1475 $found = true;
1476 break;
1477 }
1478 }
1479 if ($found) {
1480 continue;
1481 }
1482 foreach ($allGons as $currentGon) {
1483 if ($currentName == $this->getGonName($currentGon['dn'], $allGons)) {
1484 $this->gonList[] = $currentGon['dn'];
1485 break;
1486 }
1487 }
1488 }
1489 }
1490
1491 /**
1492 * Syncs the group of names to Unix groups.
1493 *
1494 * @param ConfiguredType $type type
1495 */
1496 private function manualSyncGonToUnix($type): void {
1497 $allGons = $this->findGroupOfNames();
1498 $modules = $type->getModules();
1499 $allGroups = $this->findGroups($modules);
1500 foreach ($allGroups as $index => $groupData) {
1501 $allGroups[$index] = $groupData[1];
1502 }
1503 $namesToIgnore = [];
1504 if (!empty($this->moduleSettings['posixAccount_' . $type->getId() . '_syncGroupsExclusions'])) {
1505 $namesToIgnore = $this->moduleSettings['posixAccount_' . $type->getId() . '_syncGroupsExclusions'];
1506 array_map(trim(...), $namesToIgnore);
1507 }
1508 // remove all groups that are not in group of names
1509 if (isset($_POST['syncDeleteGroups']) && ($_POST['syncDeleteGroups'] == 'on')) {
1510 $toDelete = [];
1511 foreach ($this->groups as $currentName) {
1512 if (in_array($currentName, $namesToIgnore)) {
1513 continue;
1514 }
1515 $found = false;
1516 foreach ($this->gonList as $currentGon) {
1517 $gonName = $this->getGonName($currentGon, $allGons);
1518 if ($gonName == $currentName) {
1519 $found = true;
1520 break;
1521 }
1522 }
1523 if (!$found) {
1524 $toDelete[] = $currentName;
1525 }
1526 }
1527 $this->groups = array_delete($toDelete, $this->groups);
1528 }
1529 // add groups that are not yet in Unix groups
1530 foreach ($this->gonList as $currentGon) {
1531 $gonName = $this->getGonName($currentGon, $allGons);
1532 if (in_array($gonName, $namesToIgnore)) {
1533 continue;
1534 }
1535 if (!in_array($gonName, $this->groups) && in_array($gonName, $allGroups)) {
1536 $this->groups[] = $gonName;
1537 }
1538 }
1539 }
1540
1541 /**
1542 * Syncs the Windows to Unix groups.
1543 *
1544 * @param ConfiguredType $type type
1545 */
1546 private function manualSyncWindowsToUnix($type): void {
1547 $windowsGroups = $this->getAccountContainer()->getAccountModule('windowsUser')->getGroupList();
1548 $allWindowsGroups = searchLDAPByAttribute('gidNumber', '*', null, ['cn'], ['group']);
1549 $allGroups = $this->findGroups($modules);
1550 foreach ($allGroups as $index => $groupData) {
1551 $allGroups[$index] = $groupData[1];
1552 }
1553 $namesToIgnore = [];
1554 if (!empty($this->moduleSettings['posixAccount_' . $type->getId() . '_syncGroupsExclusions'])) {
1555 $namesToIgnore = $this->moduleSettings['posixAccount_' . $type->getId() . '_syncGroupsExclusions'];
1556 array_map(trim(...), $namesToIgnore);
1557 }
1558 // remove all groups that are not in Windows groups
1559 if (isset($_POST['syncDeleteGroups']) && ($_POST['syncDeleteGroups'] == 'on')) {
1560 $toDelete = [];
1561 foreach ($this->groups as $currentName) {
1562 if (in_array($currentName, $namesToIgnore)) {
1563 continue;
1564 }
1565 $found = false;
1566 foreach ($windowsGroups as $currentWindowsGroup) {
1567 $windowsGroupName = $this->getWindowsGroupName($allWindowsGroups, $currentWindowsGroup);
1568 if ($windowsGroupName == $currentName) {
1569 $found = true;
1570 break;
1571 }
1572 }
1573 if (!$found) {
1574 $toDelete[] = $currentName;
1575 }
1576 }
1577 $this->groups = array_delete($toDelete, $this->groups);
1578 }
1579 // add groups that are not yet in Unix groups
1580 foreach ($windowsGroups as $currentWindowsGroup) {
1581 $windowsGroupName = $this->getWindowsGroupName($allWindowsGroups, $currentWindowsGroup);
1582 if (in_array($windowsGroupName, $namesToIgnore)) {
1583 continue;
1584 }
1585 if (!in_array($windowsGroupName, $this->groups) && in_array($windowsGroupName, $allGroups)) {
1586 $this->groups[] = $windowsGroupName;
1587 }
1588 }
1589 }
1590
1591 /**
1592 * Returns the cn of the given group of names.
1593 *
1594 * @param string $dn DN of group of names
1595 * @param array<string, string[]|string>[] $allGons list of all group of names
1596 * @return string|null cn value
1597 */
1598 public function getGonName($dn, &$allGons): ?string {
1599 if (!empty($allGons[$dn]['cn'][0])) {
1600 return $allGons[$dn]['cn'][0];
1601 }
1602 return extractRDNValue($dn);
1603 }
1604
1605 /**
1606 * Returns the Windows group name.
1607 *
1608 * @param array<string, string[]|string>[] $allWindowsGroups LDAP data of all Windows groups
1609 * @param string $dn DN
1610 * @return string|null group name
1611 */
1612 private function getWindowsGroupName(&$allWindowsGroups, $dn): ?string {
1613 foreach ($allWindowsGroups as $data) {
1614 if ($data['dn'] == $dn) {
1615 return $data['cn'][0];
1616 }
1617 }
1618 return null;
1619 }
1620
1621 /**
1622 * Processes user input of the homedir check page.
1623 * It checks if all input values are correct and updates the associated LDAP attributes.
1624 *
1625 * @return array<string|string[]>[] list of info/error messages
1626 */
1627 public function process_homedir(): array {
1628 $return = [];
1629 // get list of lamdaemon servers
1630 $lamdaemonServers = $_SESSION['config']->getConfiguredScriptServers();
1631 $modules = $this->getAccountContainer()->get_type()->getModules();
1632 $homeDirAttr = $this->getHomedirAttrName($modules);
1633 for ($i = 0; $i < count($lamdaemonServers); $i++) {
1634 if (isset($_POST['form_subpage_' . static::class . '_homedir_create_' . $i])) {
1635 $remote = new Remote();
1636 try {
1637 $remote->connect($lamdaemonServers[$i]);
1638 }
1639 catch (LAMException $e) {
1640 $return[] = ['ERROR', $e->getTitle(), $e->getMessage()];
1641 continue;
1642 }
1643 $result = self::createHomeDirectory($remote, $lamdaemonServers[$i], $this->attributes['uid'][0],
1644 $this->attributes[$homeDirAttr][0], $this->attributes['uidNumber'][0],
1645 $this->attributes['gidNumber'][0], $_SESSION['config']->get_scriptRights());
1646 $remote->disconnect();
1647 // lamdaemon results
1648 if (!empty($result)) {
1649 $singleresult = explode(",", $result);
1650 if (in_array($singleresult[0], ['ERROR', 'WARN', 'INFO'], true)) {
1651 $return[] = $singleresult;
1652 }
1653 }
1654 }
1655 elseif (isset($_POST['form_subpage_' . static::class . '_homedir_delete_' . $i])) {
1656 $remote = new Remote();
1657 try {
1658 $remote->connect($lamdaemonServers[$i]);
1659 }
1660 catch (LAMException $e) {
1661 $return[] = ['ERROR', $e->getTitle(), $e->getMessage()];
1662 continue;
1663 }
1664 $result = $remote->execute(
1665 implode(
1666 self::$SPLIT_DELIMITER,
1667 [
1668 $this->attributes['uid'][0],
1669 "home",
1670 "rem",
1671 $lamdaemonServers[$i]->getHomeDirPrefix() . $this->attributes[$homeDirAttr][0],
1672 $this->attributes['uidNumber'][0]
1673 ]
1674 ));
1675 $remote->disconnect();
1676 // lamdaemon results
1677 if (!empty($result)) {
1678 $singleresult = explode(",", $result);
1679 if (in_array($singleresult[0], ['ERROR', 'WARN', 'INFO'], true)) {
1680 $return[] = $singleresult;
1681 }
1682 }
1683 }
1684 }
1685 return $return;
1686 }
1687
1688 /**
1689 * {@inheritdoc}
1690 */
1691 public function getWildcardTargetAttributeNames(): array {
1692 return ['cn', 'gecos', 'homeDirectory'];
1693 }
1694
1695 /**
1696 * {@inheritDoc}
1697 */
1698 public function display_html_attributes(): htmlElement|array {
1699 $return = new htmlResponsiveRow();
1700 $this->checkForInvalidConfiguration($return);
1701 $modules = $this->getAccountContainer()->get_type()->getModules();
1702 $typeId = $this->getAccountContainer()->get_type()->getId();
1703 if (!$this->isOptional($modules) || $this->skipObjectClass() || (isset($this->attributes['objectClass']) && in_array('posixAccount', $this->attributes['objectClass']))) {
1704 $this->getAccountContainer()->replaceWildcardsInArray($this->getWildcardTargetAttributeNames(), $this->attributes);
1705 $homeDirAttr = $this->getHomedirAttrName($modules);
1706 $allowToCreateGroupWithUserName = $this->getAccountContainer()->isNewAccount
1707 && $this->allowsToCreateGroupWithSameName();
1708 $groupList = $this->findGroups($modules); // list of all group names
1709 $groups = [];
1710 for ($i = 0; $i < count($groupList); $i++) {
1711 $groups[$groupList[$i][1]] = $groupList[$i][0];
1712 }
1713 $groups = natCaseKeySort($groups);
1714 if ($allowToCreateGroupWithUserName) {
1715 $groups = [_('Create group with same name') => self::CREATE_GROUP_WITH_SAME_NAME] + $groups;
1716 }
1717 if (empty($groups)) {
1718 $return->add(new htmlStatusMessage("ERROR", _('No Unix groups found in LDAP! Please create one first.')));
1719 return $return;
1720 }
1721 $shelllist = $this->getShells(); // list of all valid shells
1722
1723 // set default values
1724 if (empty($this->attributes['uid'][0])) {
1725 if ($this->getAccountContainer()->getAccountModule('inetOrgPerson') != null) {
1726 // fill default value for user ID with first/last name
1727 $attrs = $this->getAccountContainer()->getAccountModule('inetOrgPerson')->getAttributes();
1728 $this->attributes['uid'][0] = $this->getUserNameSuggestion($attrs, $typeId);
1729 $firstSuggestion = $this->attributes['uid'][0];
1730 if (!empty($this->attributes['uid'][0]) && $this->userNameExists($this->attributes['uid'][0], $typeId)) {
1731 while ($this->userNameExists($this->attributes['uid'][0], $typeId)) {
1732 $this->attributes['uid'][0] = $this->getNextUserName($this->attributes['uid'][0], array_keys($this->getAccountContainer()->getAccountModules()));
1733 }
1734 $users = $this->getUserNames($typeId);
1735 $msg = new htmlStatusMessage($this->messages['uid'][5][0],
1736 $this->messages['uid'][5][1], $this->messages['uid'][5][2],
1737 [htmlspecialchars($users[$firstSuggestion])]);
1738 $return->add($msg);
1739 }
1740 }
1741 elseif ($this->getAccountContainer()->getAccountModule('windowsUser') != null) {
1742 // fill default value for user ID with AD user name
1743 $attrs = $this->getAccountContainer()->getAccountModule('windowsUser')->getAttributes();
1744 if (!empty($attrs['userPrincipalName'][0])) {
1745 $parts = explode('@', $attrs['userPrincipalName'][0]);
1746 $this->attributes['uid'][0] = $parts[0];
1747 }
1748 }
1749 }
1750 if ($this->manageCn($modules) && (!isset($this->attributes['cn'][0]) || ($this->attributes['cn'][0] == ''))) {
1751 // set a default value for common name
1752 if (($this->get_scope() == 'host') && isset($_POST['uid'])) {
1753 if (str_ends_with($_POST['uid'], '$')) {
1754 $this->attributes['cn'][0] = substr($_POST['uid'], 0, strlen($_POST['uid']) - 1);
1755 }
1756 else {
1757 $this->attributes['cn'][0] = $_POST['uid'];
1758 }
1759 }
1760 elseif ($this->getAccountContainer()->getAccountModule('inetOrgPerson') != null) {
1761 $attrs = $this->getAccountContainer()->getAccountModule('inetOrgPerson')->getAttributes();
1762 if ($attrs['givenName'][0]) {
1763 $this->attributes['cn'][0] = $attrs['givenName'][0] . " " . $attrs['sn'][0];
1764 }
1765 elseif ($attrs['sn'][0]) {
1766 $this->attributes['cn'][0] = $attrs['sn'][0];
1767 }
1768 else {
1769 $this->attributes['cn'][0] = $_POST['uid'];
1770 }
1771 }
1772 elseif (isset($_POST['uid'])) {
1773 $this->attributes['cn'][0] = $_POST['uid'];
1774 }
1775 }
1776
1777 $uidLabel = _("User name");
1778 if ($this->get_scope() == 'host') {
1779 $uidLabel = _("Host name");
1780 }
1781 $uidInput = $this->addSimpleInputTextField($return, 'uid', $uidLabel, true);
1782 $uidInput->setFieldMaxLength(100);
1783 $uidHelpId = ($this->get_scope() === 'user') ? 'uidUser' : 'uidHost';
1784 $uidInput->setHelpId($uidHelpId);
1785
1786 if ($this->manageCn($modules)) {
1787 $cnHelpId = ($this->get_scope() === 'user') ? 'cnUser' : 'cnHost';
1788 $cnIds = [];
1789 $this->addMultiValueInputTextField($return, 'cn', _("Common name"), false,
1790 null, false, null, null, $cnIds, '', $cnHelpId);
1791 }
1792 $uidNumber = '';
1793 if (isset($this->attributes['uidNumber'][0])) {
1794 $uidNumber = $this->attributes['uidNumber'][0];
1795 }
1796 $uidNumberInput = new htmlResponsiveInputField(_('UID number'), 'uidNumber', $uidNumber, 'uidNumber');
1797 $uidNumberInput->setFieldMaxLength(20);
1798 $uidNumberInput->setMinimumAndMaximumNumber();
1799 $return->add($uidNumberInput);
1800 if (!$this->isBooleanConfigOptionSet('posixAccount_' . $typeId . '_hidegecos')) {
1801 $gecos = '';
1802 if (isset($this->attributes['gecos'][0])) {
1803 $gecos = $this->attributes['gecos'][0];
1804 }
1805 $gecosHelpId = ($this->get_scope() === 'user') ? 'gecosUser' : 'gecosHost';
1806 $return->add(new htmlResponsiveInputField(_('Gecos'), 'gecos', $gecos, $gecosHelpId));
1807 }
1808 $primaryGroup = [];
1809 if (isset($this->attributes['gidNumber'][0])) {
1810 $primaryGroup = [$this->attributes['gidNumber'][0]];
1811 }
1812 $gidNumberHelpId = ($this->get_scope() === 'user') ? 'gidNumberUser' : 'gidNumberHost';
1813 $gidNumberSelect = new htmlResponsiveSelect('gidNumber', $groups, $primaryGroup, _('Primary group'), $gidNumberHelpId);
1814 $gidNumberSelect->setHasDescriptiveElements(true);
1815 $gidNumberSelect->setSortElements(false);
1816 $return->add($gidNumberSelect);
1817
1818 if ($this->get_scope() == 'user') {
1819 // additional groups
1820 if (!$this->isBooleanConfigOptionSet('posixAccount_' . $typeId . '_hidegon') || !$this->isBooleanConfigOptionSet('posixAccount_' . $typeId . '_hideposixGroups')) {
1821 $return->addLabel(new htmlOutputText(_('Additional groups')));
1822 $additionalGroups = new htmlGroup();
1823 $additionalGroups->addElement(new htmlAccountPageButton(static::class, 'group', 'open', _('Edit groups')));
1824 $additionalGroups->addElement(new htmlHelpLink('addgroup'));
1825 $return->addField($additionalGroups);
1826 }
1827 // home directory
1828 $homeDir = $this->attributes[$homeDirAttr][0] ?? '';
1829 $homedirInput = new htmlResponsiveInputField(_('Home directory'), 'homeDirectory', $homeDir, 'homeDirectory');
1830 $homedirInput->setRequired(true);
1831 $return->add($homedirInput);
1832 if (($_SESSION['config']->get_scriptPath() != null) && ($_SESSION['config']->get_scriptPath() != '')) {
1833 if ($this->getAccountContainer()->isNewAccount) {
1834 // get list of lamdaemon servers
1835 $lamdaemonServers = $_SESSION['config']->getConfiguredScriptServers();
1836 $homeDirLabel = new htmlOutputText(_('Create home directory'));
1837 $return->addLabel($homeDirLabel);
1838 $homeServerContainer = new htmlResponsiveRow();
1839 for ($h = 0; $h < count($lamdaemonServers); $h++) {
1840 $createHomedirGroup = new htmlGroup();
1841 $createHomedirGroup->addElement(new htmlInputCheckbox('createhomedir_' . $h, in_array($lamdaemonServers[$h]->getServer(), $this->lamdaemonServers)));
1842 $createHomedirGroup->addElement(new htmlOutputText($lamdaemonServers[$h]->getLabel()));
1843 if ($h === 0) {
1844 $createHomedirGroup->addElement(new htmlSpacer('0.2rem'));
1845 $homeDirHelp = new htmlHelpLink('createhomedir');
1846 $createHomedirGroup->addElement($homeDirHelp);
1847 }
1848 $homeServerContainer->add($createHomedirGroup);
1849 }
1850 $return->addField($homeServerContainer);
1851 }
1852 else {
1853 $return->addLabel(new htmlOutputText('&nbsp;', false));
1854 $return->addField(new htmlAccountPageButton(static::class, 'homedir', 'open', _('Check home directories')));
1855 }
1856 }
1857 $selectedShell = [];
1858 if (isset($this->attributes['loginShell'][0])) {
1859 $selectedShell = [$this->attributes['loginShell'][0]];
1860 if (!in_array($this->attributes['loginShell'][0], $shelllist)) {
1861 $shelllist[] = $this->attributes['loginShell'][0];
1862 }
1863 }
1864 $return->add(new htmlResponsiveSelect('loginShell', $shelllist, $selectedShell, _('Login shell'), 'loginShell'));
1865 }
1866 // password buttons
1867 if (checkIfWriteAccessIsAllowed($this->get_scope())
1868 && isset($this->attributes[$this->getPasswordAttrName($modules)][0])
1869 && $this->isPasswordManaged()) {
1870 $return->addLabel(new htmlOutputText(_('Password')));
1871 $pwdContainer = new htmlGroup();
1872 if (pwd_is_enabled($this->attributes[$this->getPasswordAttrName($modules)][0])) {
1873 $pwdContainer->addElement(new htmlButton('lockPassword', _('Lock password')));
1874 }
1875 else {
1876 $pwdContainer->addElement(new htmlButton('unlockPassword', _('Unlock password')));
1877 }
1878 $pwdContainer->addElement(new htmlButton('removePassword', _('Remove password')));
1879 $return->addField($pwdContainer);
1880 }
1881 // remove button
1882 if ($this->isOptional($modules) && !$this->skipObjectClass()) {
1883 $return->addVerticalSpacer('2rem');
1884 $remButton = new htmlButton('remObjectClass', _('Remove Unix extension'));
1885 $remButton->setCSSClasses(['lam-danger']);
1886 $return->add($remButton, 12, 12, 12, 'text-center');
1887 }
1888 }
1889 else {
1890 // add button
1891 $return->add(new htmlButton('addObjectClass', _('Add Unix extension')));
1892 }
1893 return $return;
1894 }
1895
1896 /**
1897 * Checks if the configuration is valid and prints an error if not.
1898 *
1899 * @param htmlResponsiveRow $content content area
1900 */
1901 private function checkForInvalidConfiguration(htmlResponsiveRow $content): void {
1902 $typeId = $this->getAccountContainer()->get_type()->getId();
1903 if ($this->get_scope() == 'user') {
1904 $generatorOption = 'posixAccount_' . $typeId . '_uidGeneratorUsers';
1905 }
1906 else {
1907 $generatorOption = 'posixAccount_' . $typeId . '_uidGeneratorHosts';
1908 }
1909 if (empty($this->moduleSettings[$generatorOption])) {
1910 $message = new htmlStatusMessage('ERROR', _('Invalid configuration detected. Please edit your server profile (module settings) and fill all required fields.'));
1911 $content->add($message);
1912 }
1913 }
1914
1915 /**
1916 * Displays the delete homedir option for the delete page.
1917 *
1918 * @return htmlElement meta HTML code
1919 */
1920 public function display_html_delete() {
1921 $return = new htmlResponsiveRow();
1922 if ($this->get_scope() == 'user' && ($_SESSION['config']->get_scriptPath() != null)) {
1923 $return->add(new htmlResponsiveInputCheckbox('deletehomedir', true, _('Delete home directory'), 'deletehomedir'));
1924 }
1925 $typeManager = new TypeManager();
1926 $sudoTypes = $typeManager->getConfiguredTypesForScope('sudo');
1927 if (($this->get_scope() == 'user') && !empty($sudoTypes)) {
1928 $return->add(new htmlResponsiveInputCheckbox('deleteSudoers', true, _('Delete sudo rights'), 'deleteSudoers'));
1929 }
1930 return $return;
1931 }
1932
1933 /**
1934 * Displays the group selection.
1935 *
1936 * @return htmlElement meta HTML code
1937 */
1938 public function display_html_group(): htmlElement {
1939 $return = new htmlResponsiveRow();
1940 $modules = $this->getAccountContainer()->get_type()->getModules();
1941 $typeId = $this->getAccountContainer()->get_type()->getId();
1942 $showUnix = !$this->isBooleanConfigOptionSet('posixAccount_' . $typeId . '_hideposixGroups');
1943 $autoSyncGon = $this->isBooleanConfigOptionSet('posixGroup_autoSyncGon');
1944 if ($showUnix) {
1945 // load list with all groups
1946 $groups = $this->findGroups($modules);
1947 for ($i = 0; $i < count($groups); $i++) {
1948 $groups[$i] = $groups[$i][1];
1949 }
1950 // remove groups the user is member of from grouplist
1951 $groups = array_delete($this->groups, $groups);
1952 // Remove primary group from group list
1953 $group = $this->getGroupName($this->attributes['gidNumber'][0]);
1954 unset ($groups[$group]);
1955 $groups = array_values($groups);
1956
1957 $unixContainer = new htmlResponsiveRow();
1958 $unixContainer->add(new htmlSubTitle(_("Unix groups")));
1959 if ($autoSyncGon) {
1960 $this->syncGonToGroups();
1961 foreach ($this->groups as $group) {
1962 $unixContainer->add(new htmlOutputText($group));
1963 }
1964 }
1965 else {
1966 $groupsAvailable = [];
1967 foreach ($groups as $group) {
1968 $groupsAvailable[$group] = $group;
1969 }
1970 natcasesort($groupsAvailable);
1971 $groupsSelected = [];
1972 foreach ($this->groups as $group) {
1973 $groupsSelected[$group] = $group;
1974 }
1975 natcasesort($groupsSelected);
1976 $this->addDoubleSelectionArea($unixContainer, _("Selected groups"), _("Available groups"),
1977 $groupsSelected, [], $groupsAvailable, [], 'groups', false, true);
1978 }
1979
1980 $return->add($unixContainer);
1981 $return->addVerticalSpacer('3rem');
1982 }
1983
1984 $showGon = self::areGroupOfNamesActive() && !$this->isBooleanConfigOptionSet('posixAccount_' . $typeId . '_hidegon');
1985 if ($showGon) {
1986 $gons = $this->findGroupOfNames();
1987
1988 $gonContainer = new htmlResponsiveRow();
1989 $gonContainer->add(new htmlSubTitle(_("Groups of names")));
1990
1991 $selectedGons = [];
1992 for ($i = 0; $i < count($this->gonList); $i++) {
1993 if (isset($gons[$this->gonList[$i]])) {
1994 $selectedGons[getAbstractDN($this->gonList[$i])] = $this->gonList[$i];
1995 }
1996 }
1997 uksort($selectedGons, compareDN(...));
1998 $availableGons = [];
1999 foreach (array_keys($gons) as $dn) {
2000 if (!in_array($dn, $this->gonList)) {
2001 $availableGons[getAbstractDN($dn)] = $dn;
2002 }
2003 }
2004 uksort($availableGons, compareDN(...));
2005
2006 $this->addDoubleSelectionArea($gonContainer, _("Selected groups"), _("Available groups"),
2007 $selectedGons, [], $availableGons, [], 'gon', true, true);
2008
2009 $return->add($gonContainer);
2010 $return->addVerticalSpacer('3rem');
2011 }
2012
2013 $showGonSync = $showGon && !$autoSyncGon;
2014 $showUnixSync = $showUnix && !$this->isBooleanConfigOptionSet('posixAccount_' . $typeId . '_syncGroups');
2015 $moduleList = $this->getAccountContainer()->get_type()->getModules();
2016 $showWindowsSync = $this->isWindows($moduleList);
2017 if ($showUnixSync && ($showGonSync || $showWindowsSync)) {
2018 $return->add(new htmlSubTitle(_('Sync groups')));
2019 $return->add(new htmlResponsiveInputCheckbox('syncDeleteGroups', true, _('Delete non-matching entries')));
2020 $return->addVerticalSpacer('1rem');
2021 if ($showGonSync) {
2022 $syncButtons = new htmlGroup();
2023 $u2gonButton = new htmlAccountPageButton(static::class, 'group', 'syncU2GON', _('Sync Unix to group of names'));
2024 $syncButtons->addElement($u2gonButton);
2025 $syncButtons->addElement(new htmlSpacer('2rem', null));
2026 $gon2uButton = new htmlAccountPageButton(static::class, 'group', 'syncGON2U', _('Sync group of names to Unix'));
2027 $syncButtons->addElement($gon2uButton);
2028 $return->add($syncButtons, 12, 12, 12, 'text-center');
2029 if ($showWindowsSync) {
2030 $syncButtons->addElement(new htmlSpacer('2rem', null));
2031 }
2032 }
2033 if ($showWindowsSync) {
2034 $syncButtons = new htmlGroup();
2035 $gon2uButton = new htmlAccountPageButton(static::class, 'group', 'syncWin2U', _('Sync Windows to Unix'));
2036 $syncButtons->addElement($gon2uButton);
2037 $return->add($syncButtons, 12, 12, 12, 'text-center');
2038 }
2039 }
2040
2041 $return->addVerticalSpacer('2rem');
2042 $backButton = new htmlAccountPageButton(static::class, 'attributes', 'back', _('Back'));
2043 $return->add($backButton);
2044 return $return;
2045 }
2046
2047 /**
2048 * Displays the delete homedir option for the homedir page.
2049 *
2050 * @return htmlElement meta HTML code
2051 */
2052 public function display_html_homedir() {
2053 $modules = $this->getAccountContainer()->get_type()->getModules();
2054 $homeDirAttr = $this->getHomedirAttrName($modules);
2055 $return = new htmlResponsiveRow();
2056 $return->addLabel(new htmlOutputText(_('Home directory')));
2057 $return->addField(new htmlOutputText($this->attributes[$homeDirAttr][0]));
2058 $return->addVerticalSpacer('2rem');
2059 // get list of lamdaemon servers
2060 $lamdaemonServers = $_SESSION['config']->getConfiguredScriptServers();
2061 for ($i = 0; $i < count($lamdaemonServers); $i++) {
2062 $label = $lamdaemonServers[$i]->getLabel();
2063 $remote = new Remote();
2064 try {
2065 $remote->connect($lamdaemonServers[$i]);
2066 }
2067 catch (LAMException $e) {
2068 $return->add(new htmlStatusMessage('ERROR', $e->getTitle(), $e->getMessage()));
2069 continue;
2070 }
2071 $result = $remote->execute(
2072 implode(
2073 self::$SPLIT_DELIMITER,
2074 [
2075 $this->attributes['uid'][0],
2076 "home",
2077 "check",
2078 $lamdaemonServers[$i]->getHomeDirPrefix() . $this->attributes[$homeDirAttr][0]]
2079 ));
2080 $remote->disconnect();
2081 // lamdaemon results
2082 if (!empty($result)) {
2083 $returnValue = trim($result);
2084 if ($returnValue === 'ok') {
2085 $return->addLabel(new htmlOutputText($label));
2086 $okGroup = new htmlGroup();
2087 $okGroup->addElement(new htmlImage('../../graphics/pass.svg', '16', '16'));
2088 $okGroup->addElement(new htmlSpacer('5px', null));
2089 $okGroup->addElement(new htmlAccountPageButton(static::class, 'homedir', 'delete_' . $i, _('Delete')));
2090 $return->addField($okGroup);
2091 }
2092 elseif ($returnValue === 'missing') {
2093 $return->addLabel(new htmlOutputText($label));
2094 $failGroup = new htmlGroup();
2095 $failGroup->addElement(new htmlImage('../../graphics/del.svg', '16', '16'));
2096 $failGroup->addElement(new htmlSpacer('5px', null));
2097 $failGroup->addElement(new htmlAccountPageButton(static::class, 'homedir', 'create_' . $i, _('Create')));
2098 $return->addField($failGroup);
2099 }
2100 elseif (trim($returnValue) !== '') {
2101 $messageParams = explode(",", $returnValue);
2102 if (isset($messageParams[2])) {
2103 $message = new htmlStatusMessage($messageParams[0], htmlspecialchars($messageParams[1]), htmlspecialchars($messageParams[2]));
2104 }
2105 elseif (in_array($messageParams[0], ['ERROR', 'WARN', 'INFO'], true)) {
2106 $message = new htmlStatusMessage($messageParams[0], htmlspecialchars($messageParams[1]));
2107 }
2108 else {
2109 $message = new htmlStatusMessage('WARN', htmlspecialchars($messageParams[0]));
2110 }
2111 $return->add($message);
2112 }
2113 }
2114 }
2115 $return->addVerticalSpacer('2rem');
2116 $return->add(new htmlAccountPageButton(static::class, 'attributes', 'back', _('Back')), 12, 12, 12, 'text-center');
2117 return $return;
2118 }
2119
2120 /**
2121 * {@inheritDoc}
2122 */
2123 public function get_profileOptions(string $typeId): ?htmlResponsiveRow {
2124 $return = new htmlResponsiveRow();
2125 $typeManager = new TypeManager();
2126 $modules = $typeManager->getConfiguredType($typeId)->getModules();
2127 $groupList = $this->findGroups($modules);
2128 $groups = [];
2129 for ($i = 0; $i < count($groupList); $i++) {
2130 $groups[$groupList[$i][1]] = $groupList[$i][1];
2131 }
2132 $groups = natCaseKeySort($groups);
2133 if ($this->get_scope() == 'user') {
2134 // primary Unix group
2135 $primaryGroups = $groups;
2136 $allowToCreateGroupWithUserName = $this->allowsToCreateGroupWithSameName($typeId);
2137 if ($allowToCreateGroupWithUserName) {
2138 $primaryGroups = [_('Create group with same name') => self::CREATE_GROUP_WITH_SAME_NAME] + $primaryGroups;
2139 }
2140 $primaryGroupSelect = new htmlResponsiveSelect('posixAccount_primaryGroup', $primaryGroups, [], _('Primary group'), 'gidNumberUser');
2141 $primaryGroupSelect->setHasDescriptiveElements(true);
2142 $primaryGroupSelect->setSortElements(false);
2143 $return->add($primaryGroupSelect);
2144 // additional group memberships
2145 $addGroupSelect = new htmlResponsiveSelect('posixAccount_additionalGroup', $groups, [], _('Additional groups'), 'addgroup', 10);
2146 $addGroupSelect->setMultiSelect(true);
2147 $addGroupSelect->setTransformSingleSelect(false);
2148 $addGroupSelect->setHasDescriptiveElements(true);
2149 $addGroupSelect->setSortElements(false);
2150 $return->add($addGroupSelect);
2151 // group of names
2152 if (self::areGroupOfNamesActive()) {
2153 $gons = $this->findGroupOfNames();
2154 $gonList = [];
2155 foreach ($gons as $dn => $attr) {
2156 $gonList[$attr['cn'][0]] = $dn;
2157 }
2158 $gonSelect = new htmlResponsiveSelect('posixAccount_gon', $gonList, [], _('Groups of names'), 'addgroup', 10);
2159 $gonSelect->setHasDescriptiveElements(true);
2160 $gonSelect->setMultiSelect(true);
2161 $gonSelect->setTransformSingleSelect(false);
2162 $return->add($gonSelect);
2163 }
2164 // common name
2165 if ($this->manageCn($modules)) {
2166 $return->add(new htmlResponsiveInputField(_('Common name'), 'posixAccount_cn', '', 'cnUser'));
2167 }
2168 // gecos
2169 $return->add(new htmlResponsiveInputField(_('Gecos'), 'posixAccount_gecos', '$firstname $lastname', 'gecosUser'));
2170 // home directory
2171 $return->add(new htmlResponsiveInputField(_('Home directory'), 'posixAccount_homeDirectory', '/home/$user', 'homeDirectory'));
2172 // login shell
2173 $shelllist = $this->getShells(); // list of all valid shells
2174 $return->add(new htmlResponsiveSelect('posixAccount_loginShell', $shelllist, ["/bin/bash"], _('Login shell'), 'loginShell'));
2175 // lamdaemon settings
2176 if ($_SESSION['config']->get_scriptPath() != null) {
2177 $return->add(new htmlSubTitle(_('Create home directory')));
2178 $lamdaemonServers = $_SESSION['config']->getConfiguredScriptServers();
2179 for ($h = 0; $h < count($lamdaemonServers); $h++) {
2180 $server = $lamdaemonServers[$h]->getServer();
2181 $label = $lamdaemonServers[$h]->getLabel();
2182 $return->add(new htmlResponsiveInputCheckbox('posixAccount_createHomedir_' . $h, in_array($server, $this->lamdaemonServers), $label, 'createhomedir', false));
2183 }
2184 }
2185 }
2186 elseif ($this->get_scope() == 'host') {
2187 // primary Unix group
2188 $primaryGroupSelect = new htmlResponsiveSelect('posixAccount_primaryGroup', $groups, [], _('Primary group'), 'gidNumberHost');
2189 $primaryGroupSelect->setHasDescriptiveElements(true);
2190 $primaryGroupSelect->setSortElements(false);
2191 $return->add($primaryGroupSelect);
2192 }
2193 if ($this->isOptional($modules)) {
2194 $return->add(new htmlResponsiveInputCheckbox('posixAccount_addExt', false, _('Automatically add this extension'), 'autoAdd'));
2195 }
2196 return $return;
2197 }
2198
2199 /**
2200 * {@inheritDoc}
2201 */
2202 public function load_profile(array $profile): void {
2203 // profile mappings in meta data
2204 parent::load_profile($profile);
2205 $modules = $this->getAccountContainer()->get_type()->getModules();
2206 // cn
2207 if ($this->manageCn($modules) && !empty($profile['posixAccount_cn'][0])) {
2208 $this->attributes['cn'][0] = $profile['posixAccount_cn'][0];
2209 }
2210 // home directory
2211 $homeDirAttr = $this->getHomedirAttrName($modules);
2212 if (!empty($profile['posixAccount_homeDirectory'][0])) {
2213 $this->attributes[$homeDirAttr][0] = $profile['posixAccount_homeDirectory'][0];
2214 }
2215 // gecos
2216 if (!empty($profile['posixAccount_gecos'][0])) {
2217 $this->attributes['gecos'][0] = $profile['posixAccount_gecos'][0];
2218 }
2219 // special profile options
2220 // GID
2221 if (isset($profile['posixAccount_primaryGroup'][0])) {
2222 if ($this->allowsToCreateGroupWithSameName() && ($profile['posixAccount_primaryGroup'][0] === self::CREATE_GROUP_WITH_SAME_NAME)) {
2223 $this->attributes['gidNumber'][0] = self::CREATE_GROUP_WITH_SAME_NAME;
2224 }
2225 else {
2226 $gid = $this->getGID($profile['posixAccount_primaryGroup'][0]);
2227 if ($gid != null) {
2228 $this->attributes['gidNumber'][0] = $gid;
2229 }
2230 }
2231 }
2232 // other group memberships
2233 if (isset($profile['posixAccount_additionalGroup'][0])) {
2234 $this->groups = $profile['posixAccount_additionalGroup'];
2235 }
2236 // group of names
2237 if (isset($profile['posixAccount_gon'][0])) {
2238 $this->gonList = $profile['posixAccount_gon'];
2239 }
2240 // lamdaemon
2241 if (($this->get_scope() == 'user') && $this->getAccountContainer()->isNewAccount) {
2242 $lamdaemonServers = $_SESSION['config']->getConfiguredScriptServers();
2243 $this->lamdaemonServers = [];
2244 for ($h = 0; $h < count($lamdaemonServers); $h++) {
2245 if (isset($profile['posixAccount_createHomedir_' . $h][0]) && ($profile['posixAccount_createHomedir_' . $h][0] == 'true')) {
2246 $this->lamdaemonServers[] = $lamdaemonServers[$h]->getServer();
2247 }
2248 }
2249 }
2250 // add extension
2251 if (isset($profile['posixAccount_addExt'][0])
2252 && ($profile['posixAccount_addExt'][0] == "true")
2253 && !$this->skipObjectClass()
2254 && !in_array('posixAccount', $this->attributes['objectClass'])) {
2255 $this->attributes['objectClass'][] = 'posixAccount';
2256 }
2257 }
2258
2259 /**
2260 * {@inheritDoc}
2261 */
2262 public function get_pdfFields(string $typeId): array {
2263 $fields = parent::get_pdfFields($typeId);
2264 $typeManager = new TypeManager();
2265 $modules = $typeManager->getConfiguredType($typeId)->getModules();
2266 if ($this->manageCn($modules)) {
2267 $fields['cn'] = _('Common name');
2268 }
2269 if (!$this->isBooleanConfigOptionSet('posixAccount_' . $typeId . '_hidegecos')) {
2270 $fields['gecos'] = _('Gecos');
2271 }
2272 return $fields;
2273 }
2274
2275 /**
2276 * {@inheritDoc}
2277 */
2278 public function get_pdfEntries(array $pdfKeys, string $typeId): array {
2279 $uidLabel = _('User name');
2280 if ($this->get_scope() == 'host') {
2281 $uidLabel = _('Host name');
2282 }
2283 $additionalGroups = [];
2284 if (!empty($this->groups)) {
2285 $additionalGroups = $this->groups;
2286 natcasesort($additionalGroups);
2287 }
2288 $modules = $this->getAccountContainer()->get_type()->getModules();
2289 $homeDirAttr = $this->getHomedirAttrName($modules);
2290 $return = [];
2291 if (isset($this->attributes['gidNumber'][0])) {
2292 $this->addPDFKeyValue($return, 'primaryGroup', _('Primary group'), $this->getGroupName($this->attributes['gidNumber'][0]));
2293 }
2294 $this->addPDFKeyValue($return, 'additionalGroups', _('Additional groups'), implode(", ", $additionalGroups));
2295 $this->addSimplePDFField($return, 'uid', $uidLabel);
2296 $this->addSimplePDFField($return, 'cn', _('Common name'));
2297 $this->addSimplePDFField($return, 'uidNumber', _('UID number'));
2298 $this->addSimplePDFField($return, 'gidNumber', _('GID number'));
2299 $this->addSimplePDFField($return, 'homeDirectory', _('Home directory'), $homeDirAttr);
2300 $this->addSimplePDFField($return, 'loginShell', _('Login shell'));
2301 $this->addSimplePDFField($return, 'gecos', _('Gecos'));
2302 if (self::areGroupOfNamesActive()) {
2303 $gons = [];
2304 for ($i = 0; $i < count($this->gonList); $i++) {
2305 $gons[] = $this->gonList[$i];
2306 }
2307 usort($gons, compareDN(...));
2308 $gonCount = count($gons);
2309 for ($i = 0; $i < $gonCount; $i++) {
2310 $gons[$i] = getAbstractDN($gons[$i]);
2311 }
2312 $this->addPDFKeyValue($return, 'gon', _('Groups of names'), $gons, "\n");
2313 }
2314 if ($this->clearTextPassword !== null) {
2315 $this->addPDFKeyValue($return, 'userPassword', _('Password'), $this->clearTextPassword);
2316 }
2317 elseif (isset($this->attributes['INFO.userPasswordClearText'])) {
2318 $this->addPDFKeyValue($return, 'userPassword', _('Password'), $this->attributes['INFO.userPasswordClearText']);
2319 }
2320 return $return;
2321 }
2322
2323 /**
2324 * {@inheritDoc}
2325 */
2326 public function get_configOptions(array $scopes, array $allScopes): htmlElement|array {
2327 $typeManager = new TypeManager($_SESSION['conf_config']);
2328 $isWindows = array_key_exists('windowsUser', $allScopes);
2329 $return = [];
2330 $generatorOptions = [
2331 _('Fixed range') => 'range',
2332 _('Samba ID pool') => 'sambaPool',
2333 _('Windows domain info') => 'windowsDomain',
2334 _('Magic number') => 'magicNumber'
2335 ];
2336 $hasUserConfig = false;
2337 $hasHostConfig = false;
2338 foreach ($scopes as $typeId) {
2339 if (getScopeFromTypeId($typeId) === 'user') {
2340 $hasUserConfig = true;
2341 }
2342 elseif (getScopeFromTypeId($typeId) === 'host') {
2343 $hasHostConfig = true;
2344 }
2345 }
2346 if ($hasUserConfig) {
2347 // user options
2348 $configUserContainer = new htmlResponsiveRow();
2349 $configUserContainer->add(new htmlSubTitle(_("Users")));
2350 foreach ($allScopes[static::class] as $typeId) {
2351 if (getScopeFromTypeId($typeId) !== 'user') {
2352 continue;
2353 }
2354 if (count($allScopes[static::class]) > 1) {
2355 $title = new htmlDiv(null, new htmlOutputText($typeManager->getConfiguredType($typeId)->getAlias()));
2356 $title->setCSSClasses(['bold', 'responsiveLabel']);
2357 $configUserContainer->add($title, 12, 6);
2358 $configUserContainer->add(new htmlOutputText('&nbsp;', false), 0, 6);
2359 }
2360 $uidGeneratorSelect = new htmlResponsiveSelect('posixAccount_' . $typeId . '_uidGeneratorUsers', $generatorOptions, ['range'], _('UID generator'), 'uidGenerator');
2361 $uidGeneratorSelect->setHasDescriptiveElements(true);
2362 $uidGeneratorSelect->setTableRowsToHide([
2363 'range' => ['posixAccount_' . $typeId . '_sambaIDPoolDNUsers', 'posixAccount_' . $typeId . '_windowsIDPoolDNUsers',
2364 'posixAccount_' . $typeId . '_magicNumberUser'],
2365 'sambaPool' => ['posixAccount_' . $typeId . '_minUID', 'posixAccount_' . $typeId . '_maxUID',
2366 'posixAccount_' . $typeId . '_windowsIDPoolDNUsers', 'posixAccount_' . $typeId . '_magicNumberUser'],
2367 'windowsDomain' => ['posixAccount_' . $typeId . '_minUID', 'posixAccount_' . $typeId . '_maxUID',
2368 'posixAccount_' . $typeId . '_sambaIDPoolDNUsers', 'posixAccount_' . $typeId . '_magicNumberUser'],
2369 'magicNumber' => ['posixAccount_' . $typeId . '_minUID', 'posixAccount_' . $typeId . '_maxUID',
2370 'posixAccount_' . $typeId . '_windowsIDPoolDNUsers', 'posixAccount_' . $typeId . '_sambaIDPoolDNUsers']
2371 ]);
2372 $uidGeneratorSelect->setTableRowsToShow([
2373 'range' => ['posixAccount_' . $typeId . '_minUID', 'posixAccount_' . $typeId . '_maxUID'],
2374 'sambaPool' => ['posixAccount_' . $typeId . '_sambaIDPoolDNUsers'],
2375 'windowsDomain' => ['posixAccount_' . $typeId . '_windowsIDPoolDNUsers'],
2376 'magicNumber' => ['posixAccount_' . $typeId . '_magicNumberUser']
2377 ]);
2378 $configUserContainer->add($uidGeneratorSelect);
2379 $uidUsersGeneratorDN = new htmlResponsiveInputField(_('Samba ID pool DN'), 'posixAccount_' . $typeId . '_sambaIDPoolDNUsers', null, 'sambaIDPoolDN');
2380 $uidUsersGeneratorDN->setRequired(true);
2381 $configUserContainer->add($uidUsersGeneratorDN);
2382 $uidUsersGeneratorWinDN = new htmlResponsiveInputField(_('Windows domain info DN'), 'posixAccount_' . $typeId . '_windowsIDPoolDNUsers', null, 'windowsIDPoolDN');
2383 $uidUsersGeneratorWinDN->setRequired(true);
2384 $configUserContainer->add($uidUsersGeneratorWinDN);
2385 $minUid = new htmlResponsiveInputField(_('Minimum UID number'), 'posixAccount_' . $typeId . '_minUID', null, 'minMaxUser');
2386 $minUid->setRequired(true);
2387 $configUserContainer->add($minUid);
2388 $maxUid = new htmlResponsiveInputField(_('Maximum UID number'), 'posixAccount_' . $typeId . '_maxUID', null, 'minMaxUser');
2389 $maxUid->setRequired(true);
2390 $configUserContainer->add($maxUid);
2391 $magicNumberUser = new htmlResponsiveInputField(_('Magic number'), 'posixAccount_' . $typeId . '_magicNumberUser', null, 'magicNumber');
2392 $magicNumberUser->setRequired(true);
2393 $configUserContainer->add($magicNumberUser);
2394 $configUserContainer->add(new htmlResponsiveInputField(_('Suffix for UID/user name check'), 'posixAccount_' . $typeId . '_uidCheckSuffixUser', '', 'uidCheckSuffix'));
2395 $configUserContainer->add(new htmlResponsiveInputField(_('User name suggestion'), 'posixAccount_' . $typeId . '_userNameSuggestion', '@givenname@%sn%', 'userNameSuggestion'));
2396 $configUserContainer->addVerticalSpacer('2rem');
2397 $hiddenOptionsContainerHead = new htmlGroup();
2398 $hiddenOptionsContainerHead->addElement(new htmlOutputText(_('Hidden options')));
2399 $hiddenOptionsContainerHead->addElement(new htmlHelpLink('hiddenOptions'));
2400 $configUserContainer->add($hiddenOptionsContainerHead);
2401 $configUserContainer->addVerticalSpacer('0.5rem');
2402 $configUserContainer->add(new htmlResponsiveInputCheckbox('posixAccount_' . $typeId . '_hidegecos', false, _('Gecos'), null, true), 12, 4, 4);
2403 $configUserContainer->add(new htmlResponsiveInputCheckbox('posixAccount_' . $typeId . '_hidepassword', false, _('Password'), null, true), 12, 4, 4);
2404 $confActiveGONModules = array_merge($_SESSION['conf_config']->get_AccountModules('group'), $_SESSION['conf_config']->get_AccountModules('gon'));
2405 if (in_array('groupOfNames', $confActiveGONModules) || in_array('groupOfMembers', $confActiveGONModules) || in_array('groupOfUniqueNames', $confActiveGONModules)) {
2406 $configUserContainer->add(new htmlResponsiveInputCheckbox('posixAccount_' . $typeId . '_hidegon', false, _('Groups of names'), null, true), 12, 4, 4);
2407 $configUserContainer->add(new htmlResponsiveInputCheckbox('posixAccount_' . $typeId . '_hideCreateGroup', false, _('Create group with same name'), null, true), 12, 4, 4);
2408 $configUserContainer->add(new htmlResponsiveInputCheckbox('posixAccount_' . $typeId . '_hideposixGroups', false, _('Unix groups'), null, true), 12, 4, 4);
2409 $syncGroupsCheckbox = new htmlResponsiveInputCheckbox('posixAccount_' . $typeId . '_syncGroups', false, _('Sync groups'), null, true);
2410 $syncGroupsCheckbox->setTableRowsToHide(['posixAccount_' . $typeId . '_syncGroupsExclusions']);
2411 $configUserContainer->add($syncGroupsCheckbox, 12, 4, 4);
2412 $configUserContainer->add(new htmlResponsiveInputTextarea('posixAccount_' . $typeId . '_syncGroupsExclusions', '', 20, 4, _('Exclude from group sync'), 'excludeFromGroupSync'));
2413 }
2414 }
2415 $return[] = $configUserContainer;
2416 }
2417 // host options
2418 if ($hasHostConfig) {
2419 $configHostContainer = new htmlResponsiveRow();
2420 $configHostContainer->add(new htmlSubTitle(_("Hosts")));
2421 foreach ($allScopes[static::class] as $typeId) {
2422 if (getScopeFromTypeId($typeId) !== 'host') {
2423 continue;
2424 }
2425 if (count($allScopes[static::class]) > 1) {
2426 $title = new htmlDiv(null, new htmlOutputText($typeManager->getConfiguredType($typeId)->getAlias()));
2427 $title->setCSSClasses(['bold', 'responsiveLabel']);
2428 $configHostContainer->add($title, 12, 6);
2429 $configHostContainer->add(new htmlOutputText('&nbsp;', false), 0, 6);
2430 }
2431 $uidHostGeneratorSelect = new htmlResponsiveSelect('posixAccount_' . $typeId . '_uidGeneratorHosts', $generatorOptions, ['range'], _('UID generator'), 'uidGenerator');
2432 $uidHostGeneratorSelect->setHasDescriptiveElements(true);
2433 $uidHostGeneratorSelect->setTableRowsToHide([
2434 'range' => ['posixAccount_' . $typeId . '_sambaIDPoolDNHosts', 'posixAccount_' . $typeId . '_windowsIDPoolDNHosts',
2435 'posixAccount_' . $typeId . '_magicNumberHost'],
2436 'sambaPool' => ['posixAccount_' . $typeId . '_minMachine', 'posixAccount_' . $typeId . '_maxMachine',
2437 'posixAccount_' . $typeId . '_windowsIDPoolDNHosts', 'posixAccount_' . $typeId . '_magicNumberHost'],
2438 'windowsDomain' => ['posixAccount_' . $typeId . '_minMachine', 'posixAccount_' . $typeId . '_maxMachine',
2439 'posixAccount_' . $typeId . '_sambaIDPoolDNHosts', 'posixAccount_' . $typeId . '_magicNumberHost'],
2440 'magicNumber' => ['posixAccount_' . $typeId . '_minMachine', 'posixAccount_' . $typeId . '_maxMachine',
2441 'posixAccount_' . $typeId . '_windowsIDPoolDNHosts', 'posixAccount_' . $typeId . '_sambaIDPoolDNHosts']
2442 ]);
2443 $uidHostGeneratorSelect->setTableRowsToShow([
2444 'range' => ['posixAccount_' . $typeId . '_minMachine', 'posixAccount_' . $typeId . '_maxMachine'],
2445 'sambaPool' => ['posixAccount_' . $typeId . '_sambaIDPoolDNHosts'],
2446 'windowsDomain' => ['posixAccount_' . $typeId . '_windowsIDPoolDNHosts'],
2447 'magicNumber' => ['posixAccount_' . $typeId . '_magicNumberHost']
2448 ]);
2449 $configHostContainer->add($uidHostGeneratorSelect);
2450 $uidHostsGeneratorDN = new htmlResponsiveInputField(_('Samba ID pool DN'), 'posixAccount_' . $typeId . '_sambaIDPoolDNHosts', null, 'sambaIDPoolDN');
2451 $uidHostsGeneratorDN->setRequired(true);
2452 $configHostContainer->add($uidHostsGeneratorDN);
2453 $uidHostsGeneratorWinDN = new htmlResponsiveInputField(_('Windows domain info DN'), 'posixAccount_' . $typeId . '_windowsIDPoolDNHosts', null, 'windowsIDPoolDN');
2454 $uidHostsGeneratorWinDN->setRequired(true);
2455 $configHostContainer->add($uidHostsGeneratorWinDN);
2456 $minUid = new htmlResponsiveInputField(_('Minimum UID number'), 'posixAccount_' . $typeId . '_minMachine', null, 'minMaxHost');
2457 $minUid->setRequired(true);
2458 $configHostContainer->add($minUid);
2459 $maxUid = new htmlResponsiveInputField(_('Maximum UID number'), 'posixAccount_' . $typeId . '_maxMachine', null, 'minMaxHost');
2460 $maxUid->setRequired(true);
2461 $configHostContainer->add($maxUid);
2462 $magicNumberHost = new htmlResponsiveInputField(_('Magic number'), 'posixAccount_' . $typeId . '_magicNumberHost', null, 'magicNumber');
2463 $magicNumberHost->setRequired(true);
2464 $configHostContainer->add($magicNumberHost);
2465 $configHostContainer->add(new htmlResponsiveInputField(_('Suffix for UID/user name check'), 'posixAccount_' . $typeId . '_uidCheckSuffixHost', '', 'uidCheckSuffix'));
2466 $hiddenOptionsContainerHead = new htmlGroup();
2467 $hiddenOptionsContainerHead->addElement(new htmlOutputText(_('Hidden options')));
2468 $hiddenOptionsContainerHead->addElement(new htmlHelpLink('hiddenOptions'));
2469 $configHostContainer->addLabel($hiddenOptionsContainerHead);
2470 $configHostContainer->addField(new htmlOutputText(''));
2471 $configHostContainer->addVerticalSpacer('0.5rem');
2472 $configHostContainer->add(new htmlResponsiveInputCheckbox('posixAccount_' . $typeId . '_hidegecos', false, _('Gecos'), null, false));
2473 $configHostContainer->addVerticalSpacer('2rem');
2474 }
2475 $return[] = $configHostContainer;
2476 }
2477 // common options
2478 $configOptionsContainer = new htmlResponsiveRow();
2479 $configOptionsContainer->add(new htmlSubTitle(_('Options')));
2480 $configOptionsContainer->add(new htmlResponsiveSelect('posixAccount_pwdHash', getSupportedHashTypes(),
2481 ['CRYPT-SHA512'], _("Password hash type"), 'pwdHash'));
2482 $configOptionsContainer->add(new htmlResponsiveInputTextarea('posixAccount_shells', implode("\r\n", $this->getShells()), 30, 4, _('Login shells'), 'loginShells'));
2483 $configOptionsContainer->add(new htmlResponsiveInputCheckbox('posixAccount_primaryGroupAsSecondary', false, _('Set primary group as memberUid'), 'primaryGroupAsSecondary'));
2484 if ($isWindows) {
2485 $configOptionsContainer->add(new htmlResponsiveInputCheckbox('posixAccount_noObjectClass', false, _('Do not add object class'), 'noObjectClass'));
2486 }
2487 $return[] = $configOptionsContainer;
2488
2489 return $return;
2490 }
2491
2492 /**
2493 * {@inheritDoc}
2494 */
2495 public function check_configOptions(array $typeIds, array &$options): array {
2496 $return = [];
2497 $ranges = [];
2498 foreach ($typeIds as $typeId) {
2499 // user settings
2500 if (getScopeFromTypeId($typeId) === 'user') {
2501 if ($options['posixAccount_' . $typeId . '_uidGeneratorUsers'][0] == 'range') {
2502 // min/maxUID are required, check if they are numeric
2503 if (!isset($options['posixAccount_' . $typeId . '_minUID'][0]) || !preg_match('/^\d+$/', $options['posixAccount_' . $typeId . '_minUID'][0])) {
2504 $return[] = $this->messages['minUID'][0];
2505 }
2506 if (!isset($options['posixAccount_' . $typeId . '_maxUID'][0]) || !preg_match('/^\d+$/', $options['posixAccount_' . $typeId . '_maxUID'][0])) {
2507 $return[] = $this->messages['maxUID'][0];
2508 }
2509 // minUID < maxUID
2510 if (isset($options['posixAccount_' . $typeId . '_minUID'][0])
2511 && isset($options['posixAccount_' . $typeId . '_maxUID'][0])
2512 && ($options['posixAccount_' . $typeId . '_minUID'][0] >= $options['posixAccount_' . $typeId . '_maxUID'][0])) {
2513 $return[] = $this->messages['cmp_UID'][0];
2514 }
2515 $ranges[] = [$options['posixAccount_' . $typeId . '_minUID'][0], $options['posixAccount_' . $typeId . '_maxUID'][0]];
2516 }
2517 elseif ($options['posixAccount_' . $typeId . '_uidGeneratorUsers'][0] == 'sambaPool') {
2518 if (!isset($options['posixAccount_' . $typeId . '_sambaIDPoolDNUsers'][0]) || !get_preg($options['posixAccount_' . $typeId . '_sambaIDPoolDNUsers'][0], 'dn')) {
2519 $return[] = $this->messages['sambaIDPoolDN'][0];
2520 }
2521 }
2522 elseif ($options['posixAccount_' . $typeId . '_uidGeneratorUsers'][0] == 'windowsDomain') {
2523 if (!isset($options['posixAccount_' . $typeId . '_windowsIDPoolDNUsers'][0]) || !get_preg($options['posixAccount_' . $typeId . '_windowsIDPoolDNUsers'][0], 'dn')) {
2524 $return[] = $this->messages['windowsIDPoolDN'][0];
2525 }
2526 }
2527 }
2528 // host settings
2529 if (getScopeFromTypeId($typeId) === 'host') {
2530 if ($options['posixAccount_' . $typeId . '_uidGeneratorHosts'][0] == 'range') {
2531 // min/maxUID are required, check if they are numeric
2532 if (!isset($options['posixAccount_' . $typeId . '_minMachine'][0]) || !preg_match('/^\d+$/', $options['posixAccount_' . $typeId . '_minMachine'][0])) {
2533 $return[] = $this->messages['minMachine'][0];
2534 }
2535 if (!isset($options['posixAccount_' . $typeId . '_maxMachine'][0]) || !preg_match('/^\d+$/', $options['posixAccount_' . $typeId . '_maxMachine'][0])) {
2536 $return[] = $this->messages['maxMachine'][0];
2537 }
2538 // minUID < maxUID
2539 if (isset($options['posixAccount_' . $typeId . '_minMachine'][0])
2540 && isset($options['posixAccount_' . $typeId . '_maxMachine'][0])
2541 && ($options['posixAccount_' . $typeId . '_minMachine'][0] >= $options['posixAccount_' . $typeId . '_maxMachine'][0])) {
2542 $return[] = $this->messages['cmp_Machine'][0];
2543 }
2544 $ranges[] = [$options['posixAccount_' . $typeId . '_minMachine'][0], $options['posixAccount_' . $typeId . '_maxMachine'][0]];
2545 }
2546 elseif ($options['posixAccount_' . $typeId . '_uidGeneratorHosts'][0] == 'sambaPool') {
2547 if (!isset($options['posixAccount_' . $typeId . '_sambaIDPoolDNHosts'][0]) || !get_preg($options['posixAccount_' . $typeId . '_sambaIDPoolDNHosts'][0], 'dn')) {
2548 $return[] = $this->messages['sambaIDPoolDN'][0];
2549 }
2550 }
2551 elseif ($options['posixAccount_' . $typeId . '_uidGeneratorHosts'][0] == 'windowsDomain') {
2552 if (!isset($options['posixAccount_' . $typeId . '_windowsIDPoolDNHosts'][0]) || !get_preg($options['posixAccount_' . $typeId . '_windowsIDPoolDNHosts'][0], 'dn')) {
2553 $return[] = $this->messages['windowsIDPoolDN'][0];
2554 }
2555 }
2556 }
2557 }
2558 // check if user and host ranges overlap
2559 foreach ($ranges as $range) {
2560 foreach ($ranges as $rangeToCompare) {
2561 // check if minimum is inside other range
2562 if (($rangeToCompare[0] > $range[0]) && ($rangeToCompare[0] < $range[1])) {
2563 $return[] = $this->messages['cmp_both'][0];
2564 break 2;
2565 }
2566 // check if maximum is inside other range
2567 if (($rangeToCompare[1] > $range[0]) && ($rangeToCompare[1] < $range[1])) {
2568 $return[] = $this->messages['cmp_both'][0];
2569 break 2;
2570 }
2571 }
2572 }
2573 return $return;
2574 }
2575
2576 /**
2577 * {@inheritDoc}
2578 */
2579 public function get_uploadColumns(array $selectedModules, ConfiguredType $type): array {
2580 $typeId = $type->getId();
2581 $return = parent::get_uploadColumns($selectedModules, $type);
2582 if ($this->isPasswordManaged($typeId)) {
2583 $return[] = [
2584 'name' => 'posixAccount_password',
2585 'description' => _('Password'),
2586 'help' => 'userPassword',
2587 'example' => _('secret')
2588 ];
2589 $return[] = [
2590 'name' => 'posixAccount_passwordDisabled',
2591 'description' => _('Lock password'),
2592 'help' => 'userPassword_lock',
2593 'example' => 'false',
2594 'values' => 'true, false',
2595 'default' => 'false'
2596 ];
2597 }
2598 if (($this->get_scope() == 'user') && $this->manageCn($selectedModules)) {
2599 array_unshift($return, [
2600 'name' => 'posixAccount_cn',
2601 'description' => _('Common name'),
2602 'help' => 'cnUser',
2603 'example' => _('Steve Miller')
2604 ]);
2605 }
2606 if (($this->get_scope() == 'host') && $this->manageCn($selectedModules)) {
2607 array_unshift($return, [
2608 'name' => 'posixAccount_cn',
2609 'description' => _('Common name'),
2610 'help' => 'cnHost',
2611 'example' => _('pc01$')
2612 ]);
2613 }
2614 if (($this->get_scope() == 'user') && !$this->isBooleanConfigOptionSet('posixAccount_' . $typeId . '_hidegecos')) {
2615 $return[] = [
2616 'name' => 'posixAccount_gecos',
2617 'description' => _('Gecos'),
2618 'help' => 'gecosUser',
2619 'example' => _('Steve Miller,Room 2.14,123-123-1234,123-123-1234')
2620 ];
2621 }
2622 if (($this->get_scope() == 'host') && !$this->isBooleanConfigOptionSet('posixAccount_' . $typeId . '_hidegecos')) {
2623 $return[] = [
2624 'name' => 'posixAccount_gecos',
2625 'description' => _('Gecos'),
2626 'help' => 'gecosHost',
2627 'example' => _('pc01,Room 2.34')
2628 ];
2629 }
2630 return $return;
2631 }
2632
2633 /**
2634 * {@inheritDoc}
2635 */
2636 public function build_uploadAccounts(array $rawAccounts, array $ids, array &$partialAccounts, array $selectedModules, ConfiguredType &$type): array {
2637 $errors = [];
2638 $typeId = $type->getId();
2639 $pwdAttrName = $this->getPasswordAttrName($selectedModules);
2640 $homedirAttrName = $this->getHomedirAttrName($selectedModules);
2641 $needAutoUID = [];
2642 // get list of existing users
2643 $existingUsers = $this->getUserNames($typeId);
2644 // get list of existing groups
2645 $groupList = $this->findGroups($selectedModules);
2646 $groupMap = [];
2647 for ($i = 0; $i < count($groupList); $i++) {
2648 $groupMap[$groupList[$i][1]] = $groupList[$i][0];
2649 }
2650 $existingGroups = array_keys($groupMap);
2651 // get list of existing group of names
2652 if (self::areGroupOfNamesActive()) {
2653 $gons = $this->findGroupOfNames();
2654 $gonList = [];
2655 foreach ($gons as $attr) {
2656 $gonList[] = $attr['cn'][0];
2657 }
2658 }
2659 $lamdaemonServers = $_SESSION['config']->getConfiguredScriptServers();
2660 // check input
2661 foreach ($rawAccounts as $i => $rawAccount) {
2662 if (!$this->skipObjectClass() && !in_array("posixAccount", $partialAccounts[$i]['objectClass'])) {
2663 $partialAccounts[$i]['objectClass'][] = "posixAccount";
2664 }
2665 // UID
2666 if ($rawAccount[$ids['posixAccount_uid']] == "") {
2667 // autoUID
2668 $needAutoUID[] = $i;
2669 }
2670 elseif (get_preg($rawAccount[$ids['posixAccount_uid']], 'digit')) {
2671 if (($this->get_scope() == 'user') && ($this->moduleSettings['posixAccount_' . $typeId . '_uidGeneratorUsers'][0] == 'range')) {
2672 if (($rawAccount[$ids['posixAccount_uid']] > $this->moduleSettings['posixAccount_' . $typeId . '_minUID'][0]) &&
2673 ($rawAccount[$ids['posixAccount_uid']] < $this->moduleSettings['posixAccount_' . $typeId . '_maxUID'][0])) {
2674 $partialAccounts[$i]['uidNumber'] = trim($rawAccount[$ids['posixAccount_uid']]);
2675 }
2676 else {
2677 $errMsg = $this->messages['uidNumber'][4];
2678 $errMsg[] = [$i];
2679 $errors[] = $errMsg;
2680 }
2681 }
2682 elseif (($this->get_scope() == 'host') && ($this->moduleSettings['posixAccount_' . $typeId . '_uidGeneratorHosts'][0] == 'range')) {
2683 if (($rawAccount[$ids['posixAccount_uid']] > $this->moduleSettings['posixAccount_' . $typeId . '_minMachine'][0]) &&
2684 ($rawAccount[$ids['posixAccount_uid']] < $this->moduleSettings['posixAccount_' . $typeId . '_maxMachine'][0])) {
2685 $partialAccounts[$i]['uidNumber'] = trim($rawAccount[$ids['posixAccount_uid']]);
2686 }
2687 else {
2688 $errMsg = $this->messages['uidNumber'][4];
2689 $errMsg[] = [$i];
2690 $errors[] = $errMsg;
2691 }
2692 }
2693 }
2694 else {
2695 $errMsg = $this->messages['uidNumber'][4];
2696 $errMsg[] = [$i];
2697 $errors[] = $errMsg;
2698 }
2699 // GID number
2700 if (get_preg($rawAccount[$ids['posixAccount_group']], 'digit')) {
2701 $partialAccounts[$i]['gidNumber'] = $rawAccount[$ids['posixAccount_group']];
2702 }
2703 if (get_preg($rawAccount[$ids['posixAccount_group']], 'groupname')) {
2704 $groupName = $rawAccount[$ids['posixAccount_group']];
2705 $gid = nuLL;
2706 if (isset($groupMap[$groupName])) {
2707 $gid = $groupMap[$groupName];
2708 }
2709 if (is_numeric($gid)) {
2710 $partialAccounts[$i]['gidNumber'] = $gid;
2711 }
2712 else {
2713 $errMsg = $this->messages['gidNumber'][0];
2714 $errMsg[] = [$i];
2715 $errors[] = $errMsg;
2716 }
2717 }
2718 else {
2719 $errMsg = $this->messages['gidNumber'][1];
2720 $errMsg[] = [$i];
2721 $errors[] = $errMsg;
2722 }
2723 // GECOS
2724 if (!$this->isBooleanConfigOptionSet('posixAccount_' . $typeId . '_hidegecos')) {
2725 if (isset($ids['posixAccount_gecos']) && !empty($rawAccount[$ids['posixAccount_gecos']])) {
2726 if (get_preg($rawAccount[$ids['posixAccount_gecos']], 'gecos')) {
2727 $partialAccounts[$i]['gecos'] = $this->checkASCII($rawAccount[$ids['posixAccount_gecos']]);
2728 }
2729 else {
2730 $errMsg = $this->messages['gecos'][0];
2731 $errMsg[] = [$i];
2732 $errors[] = $errMsg;
2733 }
2734 }
2735 else {
2736 $gecos = "";
2737 if (($rawAccount[$ids['inetOrgPerson_firstName']] != "") && ($rawAccount[$ids['inetOrgPerson_lastName']] != "")) {
2738 $gecos = $rawAccount[$ids['inetOrgPerson_firstName']] . " " . $rawAccount[$ids['inetOrgPerson_lastName']];
2739 if (isset($ids['inetOrgPerson_telephone']) && !empty($rawAccount[$ids['inetOrgPerson_telephone']])) {
2740 $gecos = $gecos . ",," . $rawAccount[$ids['inetOrgPerson_telephone']]; // double "," because room is unknown
2741 if (!empty($rawAccount[$ids['inetOrgPerson_fax']])) {
2742 $gecos = $gecos . "," . $rawAccount[$ids['inetOrgPerson_fax']];
2743 }
2744 }
2745 }
2746 if (!empty($gecos)) {
2747 $partialAccounts[$i]['gecos'] = $this->checkASCII($gecos);
2748 }
2749 }
2750 }
2751 // user specific attributes
2752 if ($this->get_scope() == 'user') {
2753 // additional groups
2754 if ($rawAccount[$ids['posixAccount_additionalGroups']] != "") {
2755 $groups = explode(",", $rawAccount[$ids['posixAccount_additionalGroups']]);
2756 for ($g = 0; $g < count($groups); $g++) {
2757 if (!in_array($groups[$g], $existingGroups)) {
2758 $errors[] = ['ERROR', _('Unable to find group in LDAP.'), $groups[$g]];
2759 }
2760 }
2761 }
2762 // group of names
2763 if (self::areGroupOfNamesActive() && isset($ids['posixAccount_gon']) && ($rawAccount[$ids['posixAccount_gon']] != "")) {
2764 $groups = explode(",", $rawAccount[$ids['posixAccount_gon']]);
2765 for ($g = 0; $g < count($groups); $g++) {
2766 if (!in_array($groups[$g], $gonList)) {
2767 $errors[] = ['ERROR', _('Unable to find group in LDAP.'), $groups[$g]];
2768 }
2769 }
2770 }
2771 // user name
2772 if (array_key_exists($rawAccount[$ids['posixAccount_userName']], $existingUsers)) {
2773 $userName = $rawAccount[$ids['posixAccount_userName']];
2774 while (array_key_exists($userName, $existingUsers)) {
2775 $userName = $this->getNextUserName($userName, $selectedModules);
2776 }
2777 $errMsg = $this->messages['uid'][9];
2778 $errMsg[] = [$i, $userName, $rawAccount[$ids['posixAccount_userName']],
2779 htmlspecialchars($existingUsers[$rawAccount[$ids['posixAccount_userName']]])];
2780 $errors[] = $errMsg;
2781 }
2782 if (get_preg($rawAccount[$ids['posixAccount_userName']], 'username')) {
2783 $partialAccounts[$i]['uid'] = $rawAccount[$ids['posixAccount_userName']];
2784 }
2785 else {
2786 $errMsg = $this->messages['uid'][7];
2787 $errMsg[] = [$i];
2788 $errors[] = $errMsg;
2789 }
2790 // home directory
2791 if ($rawAccount[$ids['posixAccount_homedir']] == "") {
2792 $partialAccounts[$i][$homedirAttrName] = '/home/' . $partialAccounts[$i]['uid'];
2793 }
2794 elseif (get_preg($rawAccount[$ids['posixAccount_homedir']], 'homeDirectory')) {
2795 $partialAccounts[$i][$homedirAttrName] = $rawAccount[$ids['posixAccount_homedir']];
2796 }
2797 else {
2798 $errMsg = $this->messages['homeDirectory'][2];
2799 $errMsg[] = [$i];
2800 $errors[] = $errMsg;
2801 }
2802 // create home directory
2803 if (isset($ids['posixAccount_createHomeDir']) && !empty($rawAccount[$ids['posixAccount_createHomeDir']])) {
2804 $lamdaemonServerValid = false;
2805 foreach ($lamdaemonServers as $lamdaemonServer) {
2806 if ($lamdaemonServer->getServer() === $rawAccount[$ids['posixAccount_createHomeDir']]) {
2807 $lamdaemonServerValid = true;
2808 break;
2809 }
2810 }
2811 if (!$lamdaemonServerValid) {
2812 $errMsg = $this->messages['homeDirectory'][4];
2813 $errMsg[] = [$i];
2814 $errors[] = $errMsg;
2815 }
2816 }
2817 // login shell
2818 if ($rawAccount[$ids['posixAccount_shell']] == "") {
2819 $partialAccounts[$i]['loginShell'] = '/bin/bash';
2820 }
2821 elseif (in_array($rawAccount[$ids['posixAccount_shell']], $this->getShells())) {
2822 $partialAccounts[$i]['loginShell'] = $rawAccount[$ids['posixAccount_shell']];
2823 }
2824 else {
2825 $errMsg = $this->messages['shell'][0];
2826 $errMsg[] = [$i];
2827 $errors[] = $errMsg;
2828 }
2829 if ($this->isPasswordManaged($typeId)) {
2830 $pwd_enabled = true;
2831 // password enabled/disabled
2832 if ($rawAccount[$ids['posixAccount_passwordDisabled']] == "") {
2833 $pwd_enabled = true;
2834 }
2835 elseif (in_array($rawAccount[$ids['posixAccount_passwordDisabled']], ['true', 'false'])) {
2836 if ($rawAccount[$ids['posixAccount_passwordDisabled']] == 'true') {
2837 $pwd_enabled = false;
2838 }
2839 }
2840 else {
2841 $errMsg = $this->messages['passwordDisabled'][0];
2842 $errMsg[] = [$i];
2843 $errors[] = $errMsg;
2844 }
2845 // password
2846 // delay exop passwords
2847 if (!empty($this->moduleSettings['posixAccount_pwdHash'][0]) && ($this->moduleSettings['posixAccount_pwdHash'][0] === 'LDAP_EXOP')) {
2848 // changed in post action
2849 }
2850 // set SASL passwords
2851 elseif (!empty($this->moduleSettings['posixAccount_pwdHash'][0]) && ($this->moduleSettings['posixAccount_pwdHash'][0] === 'SASL')) {
2852 $partialAccounts[$i][$pwdAttrName] = '{SASL}' . $partialAccounts[$i]['uid'];
2853 }
2854 // set K5KEY password
2855 elseif (!empty($this->moduleSettings['posixAccount_pwdHash'][0]) && ($this->moduleSettings['posixAccount_pwdHash'][0] === 'K5KEY')) {
2856 $partialAccounts[$i][$pwdAttrName] = pwd_hash('x', true, $this->moduleSettings['posixAccount_pwdHash'][0]);
2857 }
2858 elseif ($rawAccount[$ids['posixAccount_password']] != "") {
2859 $strengthResult = checkPasswordStrength($rawAccount[$ids['posixAccount_password']], [$rawAccount[$ids['posixAccount_userName']]], []);
2860 if (!$strengthResult->isValid()) {
2861 $errors[] = ['ERROR', _('Account %s:') . ' posixAccount_password', $strengthResult->getTextMessage(), [$i]];
2862 }
2863 elseif (!get_preg($rawAccount[$ids['posixAccount_password']], 'password')) {
2864 $errMsg = $this->messages['userPassword'][4];
2865 $errMsg[2] = str_replace('%', '%%', $errMsg[2]); // double "%" because of later sprintf
2866 $errMsg[] = [$i];
2867 $errors[] = $errMsg;
2868 }
2869 else {
2870 $partialAccounts[$i][$pwdAttrName] = pwd_hash($rawAccount[$ids['posixAccount_password']], $pwd_enabled, $this->moduleSettings['posixAccount_pwdHash'][0]);
2871 // for custom scripts etc.
2872 $partialAccounts[$i]['INFO.userPasswordClearText'] = $rawAccount[$ids['posixAccount_password']];
2873 }
2874 }
2875 }
2876 // cn
2877 if ($this->manageCn($selectedModules)) {
2878 if ($rawAccount[$ids['posixAccount_cn']] != "") {
2879 if (get_preg($rawAccount[$ids['posixAccount_cn']], 'cn')) {
2880 $partialAccounts[$i]['cn'] = $rawAccount[$ids['posixAccount_cn']];
2881 }
2882 else {
2883 $errMsg = $this->messages['cn'][1];
2884 $errMsg[] = [$i];
2885 $errors[] = $errMsg;
2886 }
2887 }
2888 elseif ($partialAccounts[$i]['givenName']) {
2889 $partialAccounts[$i]['cn'] = $partialAccounts[$i]['givenName'] . " " . $partialAccounts[$i]['sn'];
2890 }
2891 elseif ($partialAccounts[$i]['sn']) {
2892 $partialAccounts[$i]['cn'] = $partialAccounts[$i]['sn'];
2893 }
2894 else {
2895 $partialAccounts[$i]['cn'] = $partialAccounts[$i]['uid'];
2896 }
2897 }
2898 }
2899 // host specific attributes
2900 elseif ($this->get_scope() == 'host') {
2901 // host name
2902 if (array_key_exists($rawAccount[$ids['posixAccount_hostName']], $existingUsers)) {
2903 $userName = $rawAccount[$ids['posixAccount_hostName']];
2904 while (array_key_exists($userName, $existingUsers)) {
2905 $userName = $this->getNextUserName($userName, $selectedModules);
2906 }
2907 $errMsg = $this->messages['uid'][10];
2908 $errMsg[] = [$i, $userName, $rawAccount[$ids['posixAccount_hostName']],
2909 htmlspecialchars($existingUsers[$rawAccount[$ids['posixAccount_hostName']]])];
2910 $errors[] = $errMsg;
2911 }
2912 if (get_preg($rawAccount[$ids['posixAccount_hostName']], 'hostname')) {
2913 $partialAccounts[$i]['uid'] = $rawAccount[$ids['posixAccount_hostName']];
2914 $partialAccounts[$i]['cn'] = $rawAccount[$ids['posixAccount_hostName']];
2915 }
2916 else {
2917 $errMsg = $this->messages['uid'][8];
2918 $errMsg[] = [$i];
2919 $errors[] = $errMsg;
2920 }
2921 // description
2922 if (isset($ids['posixAccount_description']) && isset($rawAccount[$ids['posixAccount_description']]) && ($rawAccount[$ids['posixAccount_description']] != '')) {
2923 $partialAccounts[$i]['description'] = $rawAccount[$ids['posixAccount_description']];
2924 }
2925 else {
2926 $partialAccounts[$i]['description'] = $rawAccount[$ids['posixAccount_hostName']];
2927 }
2928 $partialAccounts[$i][$homedirAttrName] = '/dev/null';
2929 $partialAccounts[$i]['loginShell'] = '/bin/false';
2930 }
2931 }
2932 // fill in autoUIDs
2933 if ($needAutoUID !== []) {
2934 $errorsTemp = [];
2935 $uids = $this->getNextUIDs(count($needAutoUID), $errorsTemp, $typeId);
2936 if (is_array($uids)) {
2937 foreach ($needAutoUID as $i => $index) {
2938 $partialAccounts[$index]['uidNumber'] = $uids[$i];
2939 }
2940 }
2941 else {
2942 $errors[] = $this->messages['uidNumber'][2];
2943 }
2944 }
2945 return $errors;
2946 }
2947
2948 /**
2949 * {@inheritDoc}
2950 */
2951 public function doUploadPostActions(array &$data, array $ids, array $failed, array &$temp, array &$accounts,
2952 array $selectedModules, ConfiguredType $type): array {
2953 if (!checkIfWriteAccessIsAllowed($this->get_scope())) {
2954 die();
2955 }
2956 $homeDirAttr = $this->getHomedirAttrName($selectedModules);
2957 if ($this->get_scope() != 'user') {
2958 return [
2959 'status' => 'finished',
2960 'progress' => 100,
2961 'errors' => []
2962 ];
2963 }
2964 // on first call generate list of ldap operations
2965 if (!isset($temp['counter'])) {
2966 $temp['groups'] = [];
2967 $temp['dn_gon'] = [];
2968 $temp['createHomes'] = [];
2969 $temp['exop'] = [];
2970 $temp['counter'] = 0;
2971 $col = $ids['posixAccount_additionalGroups'];
2972 // get list of existing groups
2973 $groupList = $this->findGroups($selectedModules);
2974 $groupMap = [];
2975 for ($i = 0; $i < count($groupList); $i++) {
2976 $groupMap[$groupList[$i][0]] = $groupList[$i][1];
2977 }
2978 // get list of existing group of names
2979 if (self::areGroupOfNamesActive()) {
2980 $gonList = $this->findGroupOfNames();
2981 $gonMap = [];
2982 foreach ($gonList as $dn => $attr) {
2983 $gonMap[$attr['cn'][0]] = $dn;
2984 }
2985 }
2986 foreach ($data as $i => $dataRow) {
2987 if (in_array($i, $failed)) {
2988 continue; // ignore failed accounts
2989 }
2990 $groups = [];
2991 if ($dataRow[$col] != "") {
2992 $groups = explode(",", $dataRow[$col]);
2993 }
2994 if (isset($this->moduleSettings['posixAccount_primaryGroupAsSecondary'][0])
2995 && ($this->moduleSettings['posixAccount_primaryGroupAsSecondary'][0] === 'true')) {
2996 if (get_preg($dataRow[$ids['posixAccount_group']], 'digit')) {
2997 if (!in_array($groupMap[$dataRow[$ids['posixAccount_group']]], $groups)) {
2998 $groups[] = $groupMap[$dataRow[$ids['posixAccount_group']]];
2999 }
3000 }
3001 elseif (!in_array($groupMap[$dataRow[$ids['posixAccount_group']]], $groups)) {
3002 $groups[] = $dataRow[$ids['posixAccount_group']];
3003 }
3004 }
3005 for ($g = 0; $g < count($groups); $g++) {
3006 if (!in_array($groups[$g], $temp['groups'])) {
3007 $temp['groups'][] = $groups[$g];
3008 }
3009 $temp['members'][$groups[$g]][] = $dataRow[$ids['posixAccount_userName']];
3010 }
3011 if (self::areGroupOfNamesActive() && isset($ids['posixAccount_gon']) && ($dataRow[$ids['posixAccount_gon']] != "")) {
3012 $gons = explode(",", $dataRow[$ids['posixAccount_gon']]);
3013 $memberAttr = 'member';
3014 for ($g = 0; $g < count($gons); $g++) {
3015 if (in_array_ignore_case('groupOfUniqueNames', $gonList[$gonMap[$gons[$g]]]['objectclass'])) {
3016 $memberAttr = 'uniquemember';
3017 }
3018 $temp['dn_gon'][$gonMap[$gons[$g]]][$memberAttr][] = $accounts[$i]['dn'];
3019 }
3020 }
3021 if (isset($ids['posixAccount_createHomeDir']) && !empty($dataRow[$ids['posixAccount_createHomeDir']])) {
3022 $temp['createHomes'][] = $i;
3023 }
3024 if (!empty($this->moduleSettings['posixAccount_pwdHash'][0])
3025 && ($this->moduleSettings['posixAccount_pwdHash'][0] === 'LDAP_EXOP')
3026 && isset($ids['posixAccount_password'])
3027 && !empty($dataRow[$ids['posixAccount_password']])) {
3028 $temp['exop'][] = [$accounts[$i]['dn'], $dataRow[$ids['posixAccount_password']]];
3029 }
3030 }
3031 $temp['dn_gon_keys'] = array_keys($temp['dn_gon']);
3032 return [
3033 'status' => 'inProgress',
3034 'progress' => 0,
3035 'errors' => []
3036 ];
3037 }
3038 // get DNs of groups
3039 elseif (!isset($temp['dn'])) {
3040 $temp['dn'] = [];
3041 $ldapEntries = searchLDAPByAttribute('cn', '*', 'posixGroup', ['dn', 'cn'], ['group']);
3042 for ($i = 0; $i < count($ldapEntries); $i++) {
3043 $temp['dn'][$ldapEntries[$i]['cn'][0]] = $ldapEntries[$i]['dn'];
3044 }
3045 return [
3046 'status' => 'inProgress',
3047 'progress' => 0,
3048 'errors' => []
3049 ];
3050 }
3051 // add users to groups
3052 elseif ($temp['counter'] < count($temp['groups'])) {
3053 if (isset($temp['dn'][$temp['groups'][$temp['counter']]])) {
3054 $memberUid = $temp['members'][$temp['groups'][$temp['counter']]];
3055 $dnToUpdate = $temp['dn'][$temp['groups'][$temp['counter']]];
3056 $groupAttrs = ldapGetDN($dnToUpdate, ['memberUID']);
3057 if (!empty($groupAttrs['memberuid'])) {
3058 // skip members that are already set
3059 $memberUid = array_delete($groupAttrs['memberuid'], $memberUid);
3060 }
3061 $errors = [];
3062 if (!empty($memberUid)) {
3063 $toAdd = ['memberUID' => $memberUid];
3064 $success = @ldap_mod_add($_SESSION['ldap']->server(), $dnToUpdate, $toAdd);
3065 if (!$success) {
3066 $errors[] = [
3067 "ERROR",
3068 _("LAM was unable to modify group memberships for group: %s"),
3069 getDefaultLDAPErrorString($_SESSION['ldap']->server()),
3070 [$temp['groups'][$temp['counter']]]
3071 ];
3072 }
3073 }
3074 $temp['counter']++;
3075 return [
3076 'status' => 'inProgress',
3077 'progress' => ($temp['counter'] * 100) / (count($temp['groups']) + count($temp['createHomes']) + count($temp['dn_gon']) + count($temp['exop'])),
3078 'errors' => $errors
3079 ];
3080 }
3081 else {
3082 $temp['counter']++;
3083 return [
3084 'status' => 'inProgress',
3085 'progress' => ($temp['counter'] * 100) / (count($temp['groups']) + count($temp['createHomes']) + count($temp['dn_gon']) + count($temp['exop'])),
3086 'errors' => [['ERROR', _('Unable to find group in LDAP.'), $temp['groups'][$temp['counter']]]]
3087 ];
3088 }
3089 }
3090 // create home directories
3091 elseif ($temp['counter'] < (count($temp['groups']) + count($temp['createHomes']))) {
3092 $pos = $temp['createHomes'][$temp['counter'] - count($temp['groups'])];
3093 try {
3094 $remote = new Remote();
3095 $remoteServer = $_SESSION['config']->getScriptServerByName($data[$pos][$ids['posixAccount_createHomeDir']]);
3096 $remote->connect($remoteServer);
3097 $result = self::createHomeDirectory($remote, $remoteServer, $data[$pos][$ids['posixAccount_userName']],
3098 $accounts[$pos][$homeDirAttr], $accounts[$pos]['uidNumber'], $accounts[$pos]['gidNumber'],
3099 $_SESSION['config']->get_scriptRights());
3100 $remote->disconnect();
3101 $errors = [];
3102 if (!empty($result)) {
3103 $parts = explode(",", $result);
3104 if (in_array($parts[0], ['ERROR', 'WARN'])) {
3105 $errors[] = $parts;
3106 }
3107 }
3108 }
3109 catch (LAMException $e) {
3110 $errors[] = ['ERROR', $e->getTitle(), $e->getMessage()];
3111 }
3112 $temp['counter']++;
3113 return [
3114 'status' => 'inProgress',
3115 'progress' => ($temp['counter'] * 100) / (count($temp['groups']) + count($temp['createHomes']) + count($temp['dn_gon']) + count($temp['exop'])),
3116 'errors' => $errors
3117 ];
3118 }
3119 // add users to group of names
3120 elseif ($temp['counter'] < (count($temp['groups']) + count($temp['createHomes']) + count($temp['dn_gon']))) {
3121 $gonDn = $temp['dn_gon_keys'][$temp['counter'] - count($temp['groups']) - count($temp['createHomes'])];
3122 $gonAttrToAdd = $temp['dn_gon'][$gonDn];
3123 $gonAttrNames = array_keys($gonAttrToAdd);
3124 $gonAttrs = ldapGetDN($gonDn, $gonAttrNames);
3125 foreach ($gonAttrNames as $gonAttrName) {
3126 $gonAttrNameLower = strtolower($gonAttrName);
3127 if (!empty($gonAttrs[$gonAttrNameLower])) {
3128 $gonAttrToAdd[$gonAttrName] = array_delete($gonAttrs[$gonAttrNameLower], $gonAttrToAdd[$gonAttrName]);
3129 }
3130 if (empty($gonAttrToAdd[$gonAttrName])) {
3131 unset($gonAttrToAdd[$gonAttrName]);
3132 }
3133 }
3134 $errors = [];
3135 if (!empty($gonAttrToAdd)) {
3136 $success = @ldap_mod_add($_SESSION['ldap']->server(), $gonDn, $gonAttrToAdd);
3137 if (!$success) {
3138 $errors[] = [
3139 "ERROR",
3140 _("LAM was unable to modify group memberships for group: %s"),
3141 getDefaultLDAPErrorString($_SESSION['ldap']->server()),
3142 [$temp['groups'][$temp['counter']]]
3143 ];
3144 }
3145 }
3146 $temp['counter']++;
3147 return [
3148 'status' => 'inProgress',
3149 'progress' => ($temp['counter'] * 100) / (count($temp['groups']) + count($temp['createHomes']) + count($temp['dn_gon']) + count($temp['exop'])),
3150 'errors' => $errors
3151 ];
3152 }
3153 // run password exop commands
3154 elseif ($temp['counter'] < (count($temp['groups']) + count($temp['createHomes']) + count($temp['dn_gon']) + count($temp['exop']))) {
3155 $data = $temp['exop'][$temp['counter'] - count($temp['groups']) - count($temp['createHomes']) - count($temp['dn_gon'])];
3156 $dn = $data[0];
3157 $password = $data[1];
3158 $success = ldap_exop_passwd($_SESSION['ldap']->server(), $dn, '', $password);
3159 $errors = [];
3160 if (!$success) {
3161 $errors[] = [
3162 "ERROR",
3163 _('Unable to set password'),
3164 $dn . '<br>' . getDefaultLDAPErrorString($_SESSION['ldap']->server()),
3165 [$temp['exop'][$temp['counter']]]
3166 ];
3167 }
3168 $temp['counter']++;
3169 return [
3170 'status' => 'inProgress',
3171 'progress' => ($temp['counter'] * 100) / (count($temp['groups']) + count($temp['createHomes']) + count($temp['dn_gon']) + count($temp['exop'])),
3172 'errors' => $errors
3173 ];
3174 }
3175 // all modifications are done
3176 else {
3177 return [
3178 'status' => 'finished',
3179 'progress' => 100,
3180 'errors' => []
3181 ];
3182 }
3183 }
3184
3185 /**
3186 * Returns one or more free UID numbers.
3187 *
3188 * @param integer $count Number of needed free UIDs.
3189 * @param array<string|string[]>[] $errors list of error messages where errors can be added
3190 * @param string $typeId type id (e.g. user)
3191 * @return string[]|null null if no UIDs are free else an array of free UIDs.
3192 */
3193 private function getNextUIDs($count, &$errors, $typeId): ?array {
3194 // check if UIDs should be taken from Samba pool entry
3195 if (($this->get_scope() == 'user') && isset($this->moduleSettings['posixAccount_' . $typeId . '_uidGeneratorUsers']) && ($this->moduleSettings['posixAccount_' . $typeId . '_uidGeneratorUsers'][0] == 'sambaPool')) {
3196 return $this->getNextSambaPoolUIDs($count, $typeId);
3197 }
3198 if (($this->get_scope() == 'host') && isset($this->moduleSettings['posixAccount_' . $typeId . '_uidGeneratorHosts']) && ($this->moduleSettings['posixAccount_' . $typeId . '_uidGeneratorHosts'][0] == 'sambaPool')) {
3199 return $this->getNextSambaPoolUIDs($count, $typeId);
3200 }
3201 // check if UIDs should be taken from domain info pool entry
3202 if (($this->get_scope() == 'user') && isset($this->moduleSettings['posixAccount_' . $typeId . '_uidGeneratorUsers']) && ($this->moduleSettings['posixAccount_' . $typeId . '_uidGeneratorUsers'][0] == 'windowsDomain')) {
3203 return $this->getNextDomainInfoUIDs($count, $typeId);
3204 }
3205 if (($this->get_scope() == 'host') && isset($this->moduleSettings['posixAccount_' . $typeId . '_uidGeneratorHosts']) && ($this->moduleSettings['posixAccount_' . $typeId . '_uidGeneratorHosts'][0] == 'windowsDomain')) {
3206 return $this->getNextDomainInfoUIDs($count, $typeId);
3207 }
3208 // check if a magic number should be used
3209 if (($this->get_scope() == 'user') && isset($this->moduleSettings['posixAccount_' . $typeId . '_uidGeneratorUsers']) && ($this->moduleSettings['posixAccount_' . $typeId . '_uidGeneratorUsers'][0] == 'magicNumber')) {
3210 $return = [];
3211 for ($i = 0; $i < $count; $i++) {
3212 $return[] = $this->moduleSettings['posixAccount_' . $typeId . '_magicNumberUser'][0];
3213 }
3214 return $return;
3215 }
3216 if (($this->get_scope() == 'host') && isset($this->moduleSettings['posixAccount_' . $typeId . '_uidGeneratorHosts']) && ($this->moduleSettings['posixAccount_' . $typeId . '_uidGeneratorHosts'][0] == 'magicNumber')) {
3217 $return = [];
3218 for ($i = 0; $i < $count; $i++) {
3219 $return[] = $this->moduleSettings['posixAccount_' . $typeId . '_magicNumberHost'][0];
3220 }
3221 return $return;
3222 }
3223 $ret = [];
3224 if ($this->get_scope() == "user") {
3225 $minID = intval($this->moduleSettings['posixAccount_' . $typeId . '_minUID'][0]);
3226 $maxID = intval($this->moduleSettings['posixAccount_' . $typeId . '_maxUID'][0]);
3227 }
3228 else {
3229 $minID = intval($this->moduleSettings['posixAccount_' . $typeId . '_minMachine'][0]);
3230 $maxID = intval($this->moduleSettings['posixAccount_' . $typeId . '_maxMachine'][0]);
3231 }
3232 $uidList = $this->getUIDs($typeId);
3233 $uids = [];
3234 foreach ($uidList as $uid) {
3235 if (($uid <= $maxID) && ($uid >= $minID)) {
3236 $uids[] = $uid;
3237 } // ignore UIDs > maxID and UIDs < minID
3238 }
3239 for ($i = 0; $i < $count; $i++) {
3240 if (count($uids) !== 0) {
3241 // there already are some uids
3242 // store highest id-number
3243 $id = $uids[count($uids) - 1];
3244 // Return minimum allowed id-number if all found id-numbers are too low
3245 if ($id < $minID) {
3246 $ret[] = $minID;
3247 $uids[] = $minID;
3248 }
3249 // return highest used id-number + 1 if it's still in valid range
3250 elseif ($id < $maxID) {
3251 $ret[] = $id + 1;
3252 $uids[] = $id + 1;
3253 }
3254 // find free numbers between existing ones
3255 else {
3256 $k = $minID;
3257 while (in_array($k, $uids)) {
3258 $k++;
3259 }
3260 if ($k > $maxID) {
3261 return null;
3262 }
3263 else {
3264 $ret[] = $k;
3265 $uids[] = $k;
3266 sort($uids, SORT_NUMERIC);
3267 }
3268 // show warning message
3269 $errors[] = $this->messages['uidNumber'][2];
3270 }
3271 }
3272 else {
3273 // return minimum allowed id-number if no id-numbers are found
3274 $ret[] = $minID;
3275 $uids[] = $minID;
3276 }
3277 }
3278 return $ret;
3279 }
3280
3281 /**
3282 * Gets the free UID numbers from an Samba pool entry in LDAP.
3283 *
3284 * @param integer $count number of needed free UIDs.
3285 * @param string $typeId type id (e.g. user)
3286 * @return mixed null if no UIDs are free else an array of free UIDs
3287 */
3288 private function getNextSambaPoolUIDs($count, $typeId) {
3289 if ($this->get_scope() == 'user') {
3290 $dn = $this->moduleSettings['posixAccount_' . $typeId . '_sambaIDPoolDNUsers'][0];
3291 }
3292 else {
3293 $dn = $this->moduleSettings['posixAccount_' . $typeId . '_sambaIDPoolDNHosts'][0];
3294 }
3295 $attrs = ldapGetDN($dn, ['uidNumber']);
3296 if (isset($attrs['uidnumber'][0]) && ($attrs['uidnumber'][0] != '')) {
3297 $newValue = intval($attrs['uidnumber'][0]) + $count;
3298 $ldapHandle = $_SESSION['ldap']->server();
3299 ldap_modify($ldapHandle, $dn, ['uidnumber' => [$newValue]]);
3300 logNewMessage(LOG_DEBUG, 'Updated Samba ID pool ' . $dn . ' with UID number ' . $newValue . ' and LDAP code ' . ldap_errno($ldapHandle));
3301 if (ldap_errno($ldapHandle) !== 0) {
3302 logNewMessage(LOG_NOTICE, 'Updating Samba ID pool ' . $dn . ' with UID number ' . $newValue . ' failed. ' . ldap_error($ldapHandle));
3303 return null;
3304 }
3305 $result = [];
3306 for ($i = 0; $i < $count; $i++) {
3307 $result[] = intval($attrs['uidnumber'][0]) + $i;
3308 }
3309 return $result;
3310 }
3311 return null;
3312 }
3313
3314 /**
3315 * Gets the free UID numbers from a domain info entry in LDAP.
3316 *
3317 * @param integer $count number of needed free UIDs.
3318 * @param string $typeId type id (e.g. user)
3319 * @return mixed null if no UIDs are free else an array of free UIDs
3320 */
3321 private function getNextDomainInfoUIDs($count, $typeId) {
3322 if ($this->get_scope() == 'user') {
3323 $dn = $this->moduleSettings['posixAccount_' . $typeId . '_windowsIDPoolDNUsers'][0];
3324 }
3325 else {
3326 $dn = $this->moduleSettings['posixAccount_' . $typeId . '_windowsIDPoolDNHosts'][0];
3327 }
3328 $attrs = ldapGetDN($dn, ['msSFU30MaxUidNumber']);
3329 if (!empty($attrs['mssfu30maxuidnumber'][0])) {
3330 $newValue = intval($attrs['mssfu30maxuidnumber'][0]) + $count;
3331 $ldapHandle = $_SESSION['ldap']->server();
3332 ldap_modify($ldapHandle, $dn, ['mssfu30maxuidnumber' => [$newValue]]);
3333 logNewMessage(LOG_DEBUG, 'Updated domain info ' . $dn . ' with UID number ' . $newValue . ' and LDAP code ' . ldap_errno($ldapHandle));
3334 if (ldap_errno($ldapHandle) !== 0) {
3335 logNewMessage(LOG_NOTICE, 'Updating domain info ' . $dn . ' with UID number ' . $newValue . ' failed. ' . ldap_error($ldapHandle));
3336 return null;
3337 }
3338 $result = [];
3339 for ($i = 0; $i < $count; $i++) {
3340 $result[] = intval($attrs['mssfu30maxuidnumber'][0]) + $i;
3341 }
3342 return $result;
3343 }
3344 return null;
3345 }
3346
3347 /**
3348 * {@inheritDoc}
3349 */
3350 public function getSelfServiceOptions(array $fields, array $attributes, bool $passwordChangeOnly, array $readOnlyFields): array {
3351 $return = [];
3352 if (in_array('password', $fields)) {
3353 $row = new htmlResponsiveRow();
3354 if (!empty($this->selfServiceSettings->moduleSettings['posixAccount_useOldPwd']) && ($this->selfServiceSettings->moduleSettings['posixAccount_useOldPwd'][0] == 'true')) {
3355 $pwd0 = new htmlResponsiveInputField(_('Old password'), 'posixAccount_passwordOld');
3356 $pwd0->setIsPassword(true);
3357 $row->add($pwd0);
3358 }
3359 $pwd1 = new htmlResponsiveInputField($this->getSelfServiceLabel('password', _('New password')), 'posixAccount_password');
3360 $pwd1->setIsPassword(true, true);
3361 $row->add($pwd1);
3362 $pwd2 = new htmlResponsiveInputField(_('Reenter password'), 'posixAccount_password2');
3363 $pwd2->setIsPassword(true);
3364 $pwd2->setSameValueFieldID('posixAccount_password');
3365 $row->add($pwd2);
3366 $return['password'] = $row;
3367 }
3368 if ($passwordChangeOnly) {
3369 return $return; // only password fields as long no LDAP content can be read
3370 }
3371 $this->addSimpleSelfServiceTextField($return, 'cn', _('Common name'), $fields, $attributes,
3372 $readOnlyFields, true);
3373 if (in_array('loginShell', $fields)) {
3374 $shelllist = $this->getShells(); // list of all valid shells
3375 $loginShell = '';
3376 if (isset($attributes['loginShell'][0])) {
3377 $loginShell = $attributes['loginShell'][0];
3378 }
3379 $loginShellField = new htmlSelect('posixAccount_loginShell', $shelllist, [$loginShell]);
3380 if (in_array('loginShell', $readOnlyFields)) {
3381 $loginShellField = new htmlOutputText($loginShell);
3382 }
3383 $row = new htmlResponsiveRow();
3384 $row->addLabel(new htmlOutputText($this->getSelfServiceLabel('loginShell', _('Login shell'))));
3385 $row->addField($loginShellField);
3386 $return['loginShell'] = $row;
3387 }
3388 if (in_array('unixgroups', $fields) && !empty($this->selfServiceSettings->moduleSettings['posixAccount_groupDn'][0])) {
3389 $groupDn = $this->selfServiceSettings->moduleSettings['posixAccount_groupDn'][0];
3390 $gidNumber = $attributes['gidNumber'][0];
3391 $userName = $attributes['uid'][0];
3392 if (!empty($userName)) {
3393 $filter = '(&(objectClass=posixGroup)(|(gidNumber=' . $gidNumber . ')(memberUid=' . $userName . ')))';
3394 $results = searchLDAP($groupDn, $filter, ['cn']);
3395 $groups = [];
3396 foreach ($results as $result) {
3397 $groups[] = $result['cn'][0];
3398 }
3399 $groups = array_unique($groups);
3400 natcasesort($groups);
3401 $row = new htmlResponsiveRow();
3402 $row->addLabel(new htmlOutputText($this->getSelfServiceLabel('unixgroups', _('Groups'))));
3403 $row->addField(new htmlOutputText(implode(', ', $groups)));
3404 $return['unixgroups'] = $row;
3405 }
3406 }
3407 return $return;
3408 }
3409
3410 /**
3411 * {@inheritDoc}
3412 */
3413 public function checkSelfServiceOptions(array $fields, array $attributes, bool $passwordChangeOnly, array $readOnlyFields): array {
3414 $return = ['messages' => [], 'add' => [], 'del' => [], 'mod' => [], 'info' => []];
3415 if (in_array('password', $fields)
3416 && (isset($_POST['posixAccount_password']) && ($_POST['posixAccount_password'] != ''))) {
3417 if ($_POST['posixAccount_password'] != $_POST['posixAccount_password2']) {
3418 $return['messages'][] = $this->messages['userPassword'][0];
3419 }
3420 elseif (!get_preg($_POST['posixAccount_password'], 'password')) {
3421 $return['messages'][] = $this->messages['userPassword'][1];
3422 }
3423 else {
3424 $userName = empty($attributes['uid'][0]) ? null : $attributes['uid'][0];
3425 $additionalAttrs = [];
3426 if (!empty($attributes['sn'][0])) {
3427 $additionalAttrs[] = $attributes['sn'][0];
3428 }
3429 if (!empty($attributes['givenName'][0])) {
3430 $additionalAttrs[] = $attributes['givenName'][0];
3431 }
3432 $pwdPolicyResult = checkPasswordStrength($_POST['posixAccount_password'], $userName, $additionalAttrs);
3433 if ($pwdPolicyResult->isValid()) {
3434 $passwordHash = $this->selfServiceSettings->moduleSettings['posixAccount_pwdHash'][0];
3435 if (empty($this->selfServiceSettings->moduleSettings['posixAccount_useOldPwd']) || ($this->selfServiceSettings->moduleSettings['posixAccount_useOldPwd'][0] != 'true')) {
3436 // set SASL password
3437 if (!empty($attributes['uid'][0]) && ($passwordHash === 'SASL')) {
3438 $return['mod']['userpassword'][0] = '{SASL}' . $attributes['uid'][0];
3439 }
3440 elseif ($passwordHash === 'LDAP_EXOP') {
3441 // no LDAP modify action, use ldap_exop_passwd
3442 $return['info']['userPasswordModify'][0] = 'exop';
3443 }
3444 // set other password hashes
3445 else {
3446 $return['mod']['userpassword'][0] = pwd_hash($_POST['posixAccount_password'], true, $passwordHash);
3447 }
3448
3449 }
3450 else {
3451 $return['add']['userpassword'][0] = pwd_hash($_POST['posixAccount_password'], true, $passwordHash);
3452 $return['del']['userpassword'][0] = $_POST['posixAccount_passwordOld'];
3453 }
3454 $return['info']['userPasswordClearText'][0] = $_POST['posixAccount_password'];
3455 if (isset($attributes['shadowlastchange'][0])) {
3456 $return['mod']['shadowlastchange'][0] = intval(time() / 3600 / 24);
3457 }
3458 $_SESSION['selfService_clientPasswordNew'] = $_POST['posixAccount_password'];
3459 }
3460 else {
3461 $return['messages'][] = ['ERROR', $pwdPolicyResult->getTextMessage()];
3462 }
3463 }
3464 }
3465 // stop processing if only a password change is done
3466 if ($passwordChangeOnly) {
3467 return $return;
3468 }
3469 // sync from Windows password
3470 if (in_array('syncWindowsPassword', $fields) && !empty($_POST['windowsUser_unicodePwd'])) {
3471 $password = $_POST['windowsUser_unicodePwd'];
3472 $return['mod']['unixUserPassword'][0] = pwd_hash($password, true, $this->selfServiceSettings->moduleSettings['posixAccount_pwdHash'][0]);
3473 if (isset($attributes['shadowlastchange'][0])) {
3474 $return['mod']['shadowlastchange'][0] = intval(time() / 3600 / 24);
3475 }
3476 }
3477 // cn
3478 $this->checkSimpleSelfServiceTextField($return, 'cn', $attributes, $fields, $readOnlyFields,
3479 'cn', $this->messages['cn'][0], $this->messages['cn'][0]);
3480 // shell
3481 if (in_array('loginShell', $fields) && !in_array('loginShell', $readOnlyFields)) {
3482 $shelllist = $this->getShells(); // list of all valid shells
3483 if (in_array($_POST['posixAccount_loginShell'], $shelllist)) {
3484 $this->checkSimpleSelfServiceTextField($return, 'loginShell', $attributes, $fields,
3485 $readOnlyFields);
3486 }
3487 }
3488 return $return;
3489 }
3490
3491 /**
3492 * {@inheritDoc}
3493 */
3494 public function postModifySelfService(bool $newAccount, array $attributes): bool {
3495 if (isset($attributes['INFO.userPasswordModify'][0])
3496 && ($attributes['INFO.userPasswordModify'][0] === 'exop')) {
3497 $password = $attributes['INFO.userPasswordClearText'][0];
3498 $dn = $attributes['dn'][0];
3499 $success = ldap_exop_passwd($_SESSION['ldapHandle']->getServer(), $dn, '', $password);
3500 if (!$success) {
3501 StatusMessage('ERROR', _('Unable to set password'), getExtendedLDAPErrorMessage($_SESSION['ldapHandle']->getServer()));
3502 }
3503 else {
3504 StatusMessage('INFO', _('Password changed.'));
3505 }
3506 return $success;
3507 }
3508 return true;
3509 }
3510
3511 /**
3512 * Returns if the module manages the password attribute.
3513 *
3514 * @param string $typeId account type id
3515 * @return boolean manages password
3516 */
3517 private function isPasswordManaged($typeId = null) {
3518 if ($typeId === null) {
3519 $typeId = $this->getAccountContainer()->get_type()->getId();
3520 }
3521 return !$this->isBooleanConfigOptionSet('posixAccount_' . $typeId . '_hidepassword')
3522 && (empty($this->moduleSettings['posixAccount_pwdHash'][0])
3523 || ($this->moduleSettings['posixAccount_pwdHash'][0] !== 'SASL'));
3524 }
3525
3526 /**
3527 * {@inheritDoc}
3528 */
3529 public function managesPasswordAttributes(): bool {
3530 return $this->isPasswordManaged();
3531 }
3532
3533 /**
3534 * {@inheritDoc}
3535 */
3536 public function supportsForcePasswordChange(): bool {
3537 return false;
3538 }
3539
3540 /**
3541 * {@inheritDoc}
3542 */
3543 public function passwordChangeRequested(string $password, array $modules, bool $forcePasswordChange): array {
3544 if (!in_array(static::class, $modules)) {
3545 return [];
3546 }
3547 $accountModules = $this->getAccountContainer()->get_type()->getModules();
3548 // check password strength
3549 $user = empty($this->attributes['uid'][0]) ? null : $this->attributes['uid'][0];
3550 $additionalAttrs = [];
3551 if ($this->getAccountContainer()->getAccountModule('inetOrgPerson') != null) {
3552 $attrs = $this->getAccountContainer()->getAccountModule('inetOrgPerson')->getAttributes();
3553 if (!empty($attrs['sn'][0])) {
3554 $additionalAttrs[] = $attrs['sn'][0];
3555 }
3556 if (!empty($attrs['givenName'][0])) {
3557 $additionalAttrs[] = $attrs['givenName'][0];
3558 }
3559 }
3560 $checkResult = checkPasswordStrength($password, $user, $additionalAttrs);
3561 if (!$checkResult->isValid()) {
3562 return [['ERROR', $checkResult->getTextMessage()]];
3563 }
3564 // set new password
3565 $this->clearTextPassword = $password;
3566 // set SASL password
3567 if (!empty($this->attributes['uid'][0]) && !empty($this->moduleSettings['posixAccount_pwdHash'][0])
3568 && ($this->moduleSettings['posixAccount_pwdHash'][0] === 'SASL')) {
3569 $this->attributes[$this->getPasswordAttrName($accountModules)][0] = '{SASL}' . $this->attributes['uid'][0];
3570 }
3571 // delay on ldap_exop
3572 elseif (!empty($this->moduleSettings['posixAccount_pwdHash'][0]) && ($this->moduleSettings['posixAccount_pwdHash'][0] === 'LDAP_EXOP')) {
3573 logNewMessage(LOG_DEBUG, 'Setting password in post action, exop');
3574 }
3575 // set normal password
3576 else {
3577 $this->attributes[$this->getPasswordAttrName($accountModules)][0] = pwd_hash($password, true, $this->moduleSettings['posixAccount_pwdHash'][0]);
3578 }
3579 return [];
3580 }
3581
3582 /**
3583 * Returns the group ID of the given group.
3584 *
3585 * @param string $groupname group name
3586 * @return string|null GID
3587 */
3588 private function getGID($groupname): ?string {
3589 $results = searchLDAPByAttribute('cn', $groupname, 'posixGroup', ['gidnumber'], ['group']);
3590 if ((count($results) > 0) && isset($results[0]['gidnumber'][0])) {
3591 return $results[0]['gidnumber'][0];
3592 }
3593 return null;
3594 }
3595
3596 /**
3597 * Returns the group name of the group with the given group ID.
3598 *
3599 * @param string $groupID group ID
3600 * @return string|null group name
3601 */
3602 private function getGroupName($groupID): ?string {
3603 $results = searchLDAPByAttribute('gidNumber', $groupID, 'posixGroup', ['cn'], ['group']);
3604 if ((count($results) > 0) && isset($results[0]['cn'][0])) {
3605 return $results[0]['cn'][0];
3606 }
3607 return null;
3608 }
3609
3610 /**
3611 * Finds all existing LDAP groups.
3612 *
3613 * @param string[] $modules account modules
3614 * @return string[][] groups array(array(gidnumber, cn), array(gidnumber, cn), ...)
3615 */
3616 private function findGroups(&$modules) {
3617 if ($this->groupCache !== null) {
3618 return $this->groupCache;
3619 }
3620 $this->groupCache = [];
3621 $typeManager = new TypeManager();
3622 foreach ($typeManager->getConfiguredTypesForScope('group') as $type) {
3623 $filter = '(objectClass=posixGroup)';
3624 if ($this->isWindows($modules)) {
3625 $filter = '(&(objectClass=group)(gidNumber=*))';
3626 }
3627 $typeFilter = $type->getAdditionalLdapFilter();
3628 if (!empty($typeFilter)) {
3629 if (!str_starts_with($typeFilter, '(')) {
3630 $typeFilter = '(' . $typeFilter . ')';
3631 }
3632 $filter = '(&' . $filter . $typeFilter . ')';
3633 }
3634 $results = searchLDAP($type->getSuffix(), $filter, ['cn', 'gidnumber']);
3635 for ($i = 0; $i < count($results); $i++) {
3636 if (isset($results[$i]['cn'][0]) && isset($results[$i]['gidnumber'][0])) {
3637 $this->groupCache[] = [$results[$i]['gidnumber'][0], $results[$i]['cn'][0]];
3638 }
3639 }
3640 }
3641 return $this->groupCache;
3642 }
3643
3644 /**
3645 * Finds all existing LDAP group of names.
3646 *
3647 * @return array<string, array<string, string[]|string>> groups array(dn => array('cn' => array('groupName'), 'objectclass' => array('top', 'groupOfNames')))
3648 */
3649 public function findGroupOfNames(): array {
3650 if ($this->gonCache !== null) {
3651 return $this->gonCache;
3652 }
3653 $return = [];
3654 $typeManager = new TypeManager();
3655 $types = $typeManager->getConfiguredTypesForScopes(['gon', 'group']);
3656 foreach ($types as $type) {
3657 $typeFilter = get_ldap_filter($type->getId());
3658 $results = searchLDAP($type->getSuffix(), $typeFilter, ['cn', 'dn', 'objectClass']);
3659 for ($i = 0; $i < count($results); $i++) {
3660 if ((in_array_ignore_case('groupOfNames', $results[$i]['objectclass'])
3661 || in_array_ignore_case('groupOfMembers', $results[$i]['objectclass'])
3662 || in_array_ignore_case('groupOfUniqueNames', $results[$i]['objectclass']))
3663 && isset($results[$i]['cn'][0])) {
3664 $return[$results[$i]['dn']] = $results[$i];
3665 }
3666 }
3667 }
3668 $this->gonCache = $return;
3669 return $return;
3670 }
3671
3672 /**
3673 * Returns a list of existing UID numbers.
3674 *
3675 * @param string $typeId type id (e.g. user)
3676 * @return string[] list of UID numbers
3677 */
3678 private function getUIDs($typeId): array {
3679 if ($this->cachedUIDList !== null) {
3680 return $this->cachedUIDList;
3681 }
3682 $this->cachedUIDList = [];
3683 $attrs = ['uidNumber'];
3684 $filter = '(&(objectClass=posixAccount)(uidNumber=*))';
3685 if ($this->skipObjectClass()) {
3686 $filter = '(uidNumber=*)';
3687 }
3688 $typeManager = new TypeManager();
3689 $typesUser = $typeManager->getConfiguredTypesForScope('user');
3690 $typesHost = $typeManager->getConfiguredTypesForScope('host');
3691 $suffixes = [];
3692 if (!empty($typesUser)) {
3693 if (!empty($this->moduleSettings['posixAccount_' . $typeId . '_uidCheckSuffixUser'][0])) {
3694 $suffixes[] = $this->moduleSettings['posixAccount_' . $typeId . '_uidCheckSuffixUser'][0];
3695 }
3696 else {
3697 foreach ($typesUser as $type) {
3698 $suffixes[] = $type->getSuffix();
3699 }
3700 }
3701 }
3702 if (!empty($typesHost)) {
3703 if (!empty($this->moduleSettings['posixAccount_' . $typeId . '_uidCheckSuffixHost'][0])) {
3704 $suffixes[] = $this->moduleSettings['posixAccount_' . $typeId . '_uidCheckSuffixHost'][0];
3705 }
3706 else {
3707 foreach ($typesHost as $type) {
3708 $suffixes[] = $type->getSuffix();
3709 }
3710 }
3711 }
3712 $suffixes = array_unique($suffixes);
3713 foreach ($suffixes as $suffix) {
3714 $result = searchLDAP($suffix, $filter, $attrs);
3715 foreach ($result as $resultEntry) {
3716 $this->cachedUIDList[] = $resultEntry['uidnumber'][0];
3717 }
3718 }
3719 $this->cachedUIDList = array_values(array_unique($this->cachedUIDList));
3720 sort($this->cachedUIDList, SORT_NUMERIC);
3721 return $this->cachedUIDList;
3722 }
3723
3724 /**
3725 * Checks if the given user name already exists in LDAP.
3726 *
3727 * @param String $userName user name
3728 * @param string $typeId type id (e.g. user)
3729 * @return boolean true if already exists
3730 */
3731 private function userNameExists($userName, $typeId) {
3732 return array_key_exists($userName, $this->getUserNames($typeId));
3733 }
3734
3735 /**
3736 * Returns a list of all user names in LDAP.
3737 *
3738 * @param string $typeId type id (e.g. user)
3739 * @return array<string, string> user name => DN
3740 */
3741 private function getUserNames($typeId): array {
3742 if ($this->cachedUserNameList !== null) {
3743 return $this->cachedUserNameList;
3744 }
3745 $this->cachedUserNameList = [];
3746 $attrs = ['uid'];
3747 $filter = '(&(objectClass=posixAccount)(uid=*))';
3748 if ($this->skipObjectClass()) {
3749 $filter = '(uid=*)';
3750 }
3751 $typeManager = new TypeManager();
3752 $typesUser = $typeManager->getConfiguredTypesForScope('user');
3753 $typesHost = $typeManager->getConfiguredTypesForScope('host');
3754 $suffixes = [];
3755 if (!empty($typesUser)) {
3756 if (!empty($this->moduleSettings['posixAccount_' . $typeId . '_uidCheckSuffixUser'][0])) {
3757 $suffixes[] = $this->moduleSettings['posixAccount_' . $typeId . '_uidCheckSuffixUser'][0];
3758 }
3759 else {
3760 foreach ($typesUser as $type) {
3761 $suffixes[] = $type->getSuffix();
3762 }
3763 }
3764 }
3765 if (!empty($typesHost)) {
3766 if (!empty($this->moduleSettings['posixAccount_' . $typeId . '_uidCheckSuffixHost'][0])) {
3767 $suffixes[] = $this->moduleSettings['posixAccount_' . $typeId . '_uidCheckSuffixHost'][0];
3768 }
3769 else {
3770 foreach ($typesHost as $type) {
3771 $suffixes[] = $type->getSuffix();
3772 }
3773 }
3774 }
3775 $suffixes = array_unique($suffixes);
3776 foreach ($suffixes as $suffix) {
3777 $result = searchLDAP($suffix, $filter, $attrs);
3778 foreach ($result as $resultEntry) {
3779 $this->cachedUserNameList[$resultEntry['uid'][0]] = $resultEntry['dn'];
3780 }
3781 }
3782 return $this->cachedUserNameList;
3783 }
3784
3785 /**
3786 * Returns if LAM manages group of names entries.
3787 *
3788 * @return bool group of names are active
3789 */
3790 public static function areGroupOfNamesActive(): bool {
3791 if (!isset($_SESSION['config'])) {
3792 return false;
3793 }
3794 $typeManager = new TypeManager();
3795 $types = $typeManager->getConfiguredTypesForScopes(['group', 'gon']);
3796 foreach ($types as $type) {
3797 $modules = $type->getModules();
3798 if (in_array('groupOfNames', $modules)
3799 || in_array('groupOfMembers', $modules)
3800 || in_array('groupOfUniqueNames', $modules)) {
3801 return true;
3802 }
3803 }
3804 return false;
3805 }
3806
3807 /**
3808 * Returns a suggestion for the user name.
3809 * By default this will be the first character of the first name plus the last name.
3810 *
3811 * @param array<string, string[]|string> $attrs LDAP attributes
3812 * @param string $typeId type id (e.g. user)
3813 * @return string user name
3814 */
3815 protected function getUserNameSuggestion($attrs, $typeId): string {
3816 $attributes = array_change_key_case($attrs);
3817 $format = '@givenname@%sn%';
3818 if (isset($this->moduleSettings['posixAccount_' . $typeId . '_userNameSuggestion'][0])) {
3819 $format = strtolower($this->moduleSettings['posixAccount_' . $typeId . '_userNameSuggestion'][0]);
3820 }
3821 // search for @key@ wildcards in format string and replace with first character of attribute
3822 $wildcards = [];
3823 if (preg_match_all('/@([a-zA-Z_-])+@/', $format, $wildcards) > 0) {
3824 for ($i = 0; $i < count($wildcards[0]); $i++) {
3825 $wc = substr($wildcards[0][$i], 1, strlen($wildcards[0][$i]) - 2);
3826 $value = '';
3827 if (!empty($attributes[$wc][0])) {
3828 $value = $this->cleanSuggestionPart($attributes[$wc][0][0]);
3829 }
3830 $format = str_replace('@' . $wc . '@', $value, $format);
3831 }
3832 }
3833 // search for %key% wildcards in format string and replace with attribute
3834 $wildcards = [];
3835 if (preg_match_all('/%([a-zA-Z_-])+%/', $format, $wildcards) > 0) {
3836 for ($i = 0; $i < count($wildcards[0]); $i++) {
3837 $wc = substr($wildcards[0][$i], 1, strlen($wildcards[0][$i]) - 2);
3838 $value = '';
3839 if (isset($attributes[$wc][0])) {
3840 $value = $this->cleanSuggestionPart($attributes[$wc][0]);
3841 }
3842 $format = str_replace('%' . $wc . '%', $value, $format);
3843 }
3844 }
3845 return $format;
3846 }
3847
3848 /**
3849 * Cleans a string that is injected in user name suggestion.
3850 *
3851 * @param string $part injected part
3852 * @return string cleaned by removing umlauts, spaces, dashes and underscores
3853 */
3854 private function cleanSuggestionPart($part): string {
3855 $result = str_replace(array_keys($this->umlautReplacements), array_values($this->umlautReplacements), strtolower($part));
3856 return str_replace([' ', '_', '-'], ['', '', ''], $result);
3857 }
3858
3859 /**
3860 * Returns if this account can be locked.
3861 * This is the case if a hashed password is set ("{" at the beginning).
3862 *
3863 * @param string[] $modules account modules
3864 * @return bool lockable
3865 */
3866 public function isLockable(&$modules): bool {
3867 return isset($this->attributes[$this->getPasswordAttrName($modules)][0])
3868 && pwd_is_lockable($this->attributes[$this->getPasswordAttrName($modules)][0]);
3869 }
3870
3871 /**
3872 * Returns if the Unix part of the current account is locked.
3873 *
3874 * @param string[] $modules account modules
3875 * @param array<string, string[]|string>|null $attributes LDAP attribute data
3876 * @return bool password is locked
3877 */
3878 public function isLocked($modules, ?array $attributes = null): bool {
3879 if ($attributes === null) {
3880 $attributes = array_change_key_case($this->attributes);
3881 }
3882 $passwordAttribute = strtolower($this->getPasswordAttrName($modules));
3883 return isset($attributes[$passwordAttribute][0])
3884 && !pwd_is_enabled($attributes[$passwordAttribute][0]);
3885 }
3886
3887 /**
3888 * Locks the user password of this account.
3889 *
3890 * @param string[] $modules account modules
3891 */
3892 public function lock(&$modules): void {
3893 $pwdAttrName = $this->getPasswordAttrName($modules);
3894 if (isset($this->attributes[$pwdAttrName][0])) {
3895 $this->attributes[$pwdAttrName][0] = pwd_disable($this->attributes[$pwdAttrName][0]);
3896 }
3897 }
3898
3899 /**
3900 * Unlocks the user password of this account.
3901 *
3902 * @param string[] $modules account modules
3903 */
3904 public function unlock(&$modules): void {
3905 $pwdAttrName = $this->getPasswordAttrName($modules);
3906 if (isset($this->attributes[$pwdAttrName][0])) {
3907 $this->attributes[$pwdAttrName][0] = pwd_enable($this->attributes[$pwdAttrName][0]);
3908 }
3909 }
3910
3911 /**
3912 * Removes all Unix group memberships from this user.
3913 */
3914 public function removeFromUnixGroups(): void {
3915 $this->groups = [];
3916 }
3917
3918 /**
3919 * Removes all group of names memberships from this user.
3920 */
3921 public function removeFromGONGroups(): void {
3922 $this->gonList = [];
3923 }
3924
3925 /**
3926 * Returns the next possible user name based on the given one.
3927 * If the user name does not end with a number then a "2" is added.
3928 * User names with numbers at the end are simply increased by one.
3929 * <br>
3930 * <br>Attention: This user name might still be in use. This needs to be checked separately.
3931 *
3932 * @param String $userName user name
3933 * @param string[] $moduleNames list of account module names
3934 * @return String new user name
3935 */
3936 protected function getNextUserName($userName, $moduleNames) {
3937 if ($this->get_scope() == 'host' && in_array('sambaSamAccount', $moduleNames)) {
3938 $userName = substr($userName, 0, -1);
3939 }
3940 // get last character of username
3941 $lastchar = substr($userName, strlen($userName) - 1, 1);
3942 $suffix = '';
3943 if (($this->get_scope() == 'host') && in_array('sambaSamAccount', $moduleNames)) {
3944 $suffix = '$';
3945 }
3946 // Last character is no number
3947 if (!preg_match('/^(\d)+$/', $lastchar)) {
3948 // Last character is no number. Therefore we only have to add "2" to it.
3949 $userName = $userName . '2' . $suffix;
3950 }
3951 else {
3952 /* Last character is a number -> we have to increase the number until we've
3953 * found a groupname with trailing number which is not in use.
3954 *
3955 * $i will show us were we have to split groupname so we get a part
3956 * with the groupname and a part with the trailing number
3957 */
3958 $i = strlen($userName) - 1;
3959 $mark = false;
3960 // Set $i to the last character which is a number in $account_new->general_username
3961 while (!$mark && ($i >= 0)) {
3962 if (preg_match('/^(\d)+$/', substr($userName, $i, strlen($userName) - $i))) {
3963 $i--;
3964 }
3965 else {
3966 $mark = true;
3967 }
3968 }
3969 // increase last number with one
3970 $firstchars = substr($userName, 0, $i + 1);
3971 $lastchars = substr($userName, $i + 1, strlen($userName) - $i);
3972 // Put username together
3973 $userName = $firstchars . (intval($lastchars) + 1) . $suffix;
3974 }
3975 return $userName;
3976 }
3977
3978 /**
3979 * Returns the list of possible login shells.
3980 *
3981 * @return string[] login shells
3982 */
3983 private function getShells() {
3984 // self-service
3985 if (!isLoggedIn() && ($this->selfServiceSettings !== null)
3986 && isset($this->selfServiceSettings->moduleSettings['posixAccount_shells'])
3987 && (count($this->selfServiceSettings->moduleSettings['posixAccount_shells'])) > 0) {
3988 return $this->selfServiceSettings->moduleSettings['posixAccount_shells'];
3989 }
3990 // server profile
3991 if (($this->selfServiceSettings === null) && ($this->moduleSettings !== null)
3992 && isset($this->moduleSettings['posixAccount_shells'])
3993 && (count($this->moduleSettings['posixAccount_shells'])) > 0) {
3994 return $this->moduleSettings['posixAccount_shells'];
3995 }
3996 // fall back to default
3997 return [
3998 '/bin/bash',
3999 '/bin/csh',
4000 '/bin/dash',
4001 '/bin/false',
4002 '/bin/ksh',
4003 '/bin/sh'
4004 ];
4005 }
4006
4007 /**
4008 * Returns if the cn attribute should be managed.
4009 * If Windows modules are active then cn will not be managed.
4010 *
4011 * @param string[] $modules account modules
4012 * @return bool manage cn attribute
4013 */
4014 private function manageCn($modules): bool {
4015 return !$this->isWindows($modules);
4016 }
4017
4018 /**
4019 * Returns if the Unix part can be added and removed.
4020 *
4021 * @param string[] $modules account modules
4022 * @return bool is optional
4023 */
4024 private function isOptional($modules): bool {
4025 return !$this->manageCn($modules);
4026 }
4027
4028 /**
4029 * Returns if the Windows module is active.
4030 *
4031 * @param string[] $modules account modules
4032 * @return bool is Windows
4033 */
4034 private function isWindows($modules): bool {
4035 return in_array('windowsUser', $modules);
4036 }
4037
4038 /**
4039 * Returns if the PPolicy module is active.
4040 *
4041 * @param string[] $modules account modules
4042 * @return bool is PPolicy enabled
4043 */
4044 private function hasPPolicy($modules): bool {
4045 return in_array('ppolicyUser', $modules);
4046 }
4047
4048 /**
4049 * Returns the password attribute.
4050 * Usually, this is userPassword. If Windows modules are active this is unixUserPassword.
4051 *
4052 * @param string[] $modules account modules
4053 * @return string attribute name
4054 */
4055 private function getPasswordAttrName($modules): string {
4056 if ($this->isWindows($modules)) {
4057 return 'unixUserPassword';
4058 }
4059 return 'userpassword';
4060 }
4061
4062 /**
4063 * Returns the home directory attribute.
4064 * Usually, this is homeDirectory. If Windows modules are active this is unixHomeDirectory.
4065 *
4066 * @param string[] $modules account modules
4067 * @return string attribute name
4068 */
4069 private function getHomedirAttrName($modules): string {
4070 if ($this->isWindows($modules)) {
4071 return 'unixHomeDirectory';
4072 }
4073 return 'homeDirectory';
4074 }
4075
4076 /**
4077 * Syncs the group of names with groups.
4078 */
4079 private function syncGonToGroups(): void {
4080 $this->groups = [];
4081 $allGons = $this->findGroupOfNames();
4082 foreach ($this->gonList as $dn) {
4083 if (!isset($allGons[$dn])) {
4084 continue;
4085 }
4086 $gon = $this->gonCache[$dn];
4087 if (in_array_ignore_case('posixGroup', $gon['objectclass']) && !empty($gon['cn'])) {
4088 $this->groups[] = $gon['cn'][0];
4089 }
4090 }
4091 }
4092
4093 /**
4094 * Returns if the object class should not be added.
4095 *
4096 * @return bool do not add
4097 */
4098 private function skipObjectClass(): bool {
4099 return $this->isBooleanConfigOptionSet('posixAccount_noObjectClass');
4100 }
4101
4102 /**
4103 * {@inheritdoc}
4104 */
4105 public function getWildCardReplacements(): array {
4106 $replacements = [];
4107 // user name
4108 if (!empty($_POST['uid'])) {
4109 $replacements['user'] = $_POST['uid'];
4110 }
4111 elseif (!empty($this->attributes['uid'][0])) {
4112 $replacements['user'] = $this->attributes['uid'][0];
4113 }
4114 // group name
4115 if (!empty($_POST['gidNumber']) && ($_POST['gidNumber'] !== self::CREATE_GROUP_WITH_SAME_NAME)) {
4116 $replacements['group'] = $this->getGroupName($_POST['gidNumber']);
4117 }
4118 elseif (isset($this->attributes['gidNumber'][0])
4119 && ($this->attributes['gidNumber'][0] === self::CREATE_GROUP_WITH_SAME_NAME)) {
4120 if (isset($replacements['user'])) {
4121 $replacements['group'] = $replacements['user'];
4122 }
4123 }
4124 elseif (!empty($this->attributes['gidNumber'][0])) {
4125 $replacements['group'] = $this->getGroupName($this->attributes['gidNumber'][0]);
4126 }
4127 return $replacements;
4128 }
4129
4130 /**
4131 * Returns the current group names.
4132 *
4133 * @return string[] group names
4134 */
4135 public function getGroups() {
4136 return $this->groups;
4137 }
4138
4139 /**
4140 * Returns the list of group of names where this user is member.
4141 *
4142 * @return string[] list of DNs
4143 */
4144 public function getGroupOfNames() {
4145 return $this->gonList;
4146 }
4147
4148 /**
4149 * @inheritDoc
4150 */
4151 public function supportsPasswordQuickChangePage(): bool {
4152 return true;
4153 }
4154
4155 /**
4156 * @inheritDoc
4157 */
4158 public function addPasswordQuickChangeAccountDetails(htmlResponsiveRow $row): void {
4159 if (!empty($this->attributes['uid'][0])) {
4160 $row->addLabel(new htmlOutputText(_('User name')));
4161 $row->addField(new htmlOutputText($this->attributes['uid'][0]));
4162 }
4163 }
4164
4165 /**
4166 * @inheritDoc
4167 */
4168 public function getPasswordQuickChangeOptions(bool $forcePasswordChangeByDefault): array {
4169 if (!in_array_ignore_case('posixAccount', $this->attributes['objectClass'])) {
4170 return [];
4171 }
4172 $typeId = $this->getAccountContainer()->get_type()->getId();
4173 if ($this->isBooleanConfigOptionSet('posixAccount_' . $typeId . '_hidepassword')
4174 || (!empty($this->moduleSettings['posixAccount_pwdHash'][0])
4175 && ($this->moduleSettings['posixAccount_pwdHash'][0] === 'SASL'))) {
4176 return [];
4177 }
4178 return [
4179 new PasswordQuickChangeOption('updateUnixPwd', _('Change Unix password'))
4180 ];
4181 }
4182
4183 /**
4184 * @inheritDoc
4185 */
4186 public function getPasswordQuickChangeChanges(string $password): array {
4187 if (!in_array_ignore_case('posixAccount', $this->attributes['objectClass'])) {
4188 return [];
4189 }
4190 $attrs = [];
4191 if (isset($_POST['updateUnixPwd'])) {
4192 $hashType = $this->moduleSettings['posixAccount_pwdHash'][0];
4193 if ($hashType === 'LDAP_EXOP') {
4194 $this->clearTextPassword = $password;
4195 }
4196 else {
4197 $attrs['userpassword'][0] = pwd_hash($password, true, $hashType);
4198 }
4199 }
4200 return $attrs;
4201 }
4202
4203 /**
4204 * @inheritDoc
4205 */
4206 public function getPasswordQuickChangePasswordStrengthUserName(): ?string {
4207 return $this->attributes['uid'][0] ?? null;
4208 }
4209
4210 /**
4211 * @inheritDoc
4212 */
4213 public function getPasswordQuickChangePasswordStrengthAttributes(): array {
4214 return [];
4215 }
4216
4217 /**
4218 * @inheritDoc
4219 */
4220 public function getPasswordQuickChangeIsPasswordInHistory(string $password): bool {
4221 return false;
4222 }
4223
4224 /**
4225 * @inheritDoc
4226 */
4227 public function getAccountStatusDetails(ConfiguredType $type, ?array &$attributes): array {
4228 if (!$this->isPasswordManaged($type->getId())) {
4229 return [];
4230 }
4231 if ($attributes === null) {
4232 $attributes = $this->attributes;
4233 }
4234 $details = [];
4235 if (self::isLocked($type->getModules(), $attributes)) {
4236 if ($this->isWindows($type->getModules())) {
4237 $details[] = AccountStatusDetails::newPartiallyLocked(_('Unix'), self::STATUS_PASSWORD_LOCKED);
4238 }
4239 else {
4240 $details[] = AccountStatusDetails::newLocked(_('Unix'), self::STATUS_PASSWORD_LOCKED);
4241 }
4242 }
4243 return $details;
4244 }
4245
4246 /**
4247 * @inheritDoc
4248 */
4249 public function getAccountStatusRequiredAttributes(ConfiguredType $type): array {
4250 if (!$this->isPasswordManaged($type->getId())) {
4251 return [];
4252 }
4253 return [$this->getPasswordAttrName($type->getModules()), 'uid'];
4254 }
4255
4256 /**
4257 * @inheritDoc
4258 */
4259 public function getAccountStatusPossibleLockOptions(ConfiguredType $type, ?array &$attributes): array {
4260 if (!$this->isPasswordManaged($type->getId())) {
4261 return [];
4262 }
4263 if ($attributes === null) {
4264 $attributes = $this->attributes;
4265 }
4266 $options = [];
4267 $attributeName = $this->getPasswordAttrName($type->getModules());
4268 if (!self::isLocked($type->getModules(), $attributes) && isset($attributes[$attributeName][0]) && pwd_is_lockable($attributes[$attributeName][0])) {
4269 if ($this->hasPPolicy($type->getModules())) {
4270 $options[] = AccountStatusDetails::newPartiallyLocked(_('Unix'), self::STATUS_PASSWORD_LOCKED);
4271 }
4272 else {
4273 $options[] = AccountStatusDetails::newLocked(_('Unix'), self::STATUS_PASSWORD_LOCKED);
4274 }
4275 if (isset($attributes['uid'][0])) {
4276 $options[] = AccountStatusDetails::newPartiallyLocked(_('Remove from all Unix groups'), self::STATUS_REMOVE_UNIX_GROUPS);
4277 }
4278 if (self::areGroupOfNamesActive()) {
4279 $options[] = AccountStatusDetails::newPartiallyLocked(_('Remove from all group of (unique) names'), self::STATUS_REMOVE_GON_GROUPS);
4280 }
4281 }
4282 return $options;
4283 }
4284
4285 /**
4286 * @inheritDoc
4287 */
4288 public function accountStatusPerformLock(ConfiguredType $type, ?array &$attributes, array $lockIds): void {
4289 if ($attributes === null) {
4290 $attributes = &$this->attributes;
4291 }
4292 $attributeName = $this->getPasswordAttrName($type->getModules());
4293 if (in_array(self::STATUS_PASSWORD_LOCKED, $lockIds)) {
4294 $attributes[$attributeName][0] = pwd_disable($attributes[$attributeName][0]);
4295 }
4296 if (in_array(self::STATUS_REMOVE_UNIX_GROUPS, $lockIds)) {
4297 if ($this->attributes === null) {
4298 $this->clearPosixGroupMemberships($attributes);
4299 }
4300 else {
4301 $this->removeFromUnixGroups();
4302 }
4303 }
4304 if (in_array(self::STATUS_REMOVE_GON_GROUPS, $lockIds)) {
4305 if ($this->attributes === null) {
4306 $this->clearGroupOfNamesMemberships($attributes);
4307 }
4308 else {
4309 $this->removeFromGONGroups();
4310 }
4311 }
4312 }
4313
4314 /**
4315 * Clears the group of names memberships of the user.
4316 *
4317 * @param array<string, string[]|string> $attributes LDAP attributes
4318 * @throws LAMException error during group modify
4319 */
4320 private function clearGroupOfNamesMemberships(array $attributes): void {
4321 $searchAttrs = ['member', 'uniquemember', 'owner'];
4322 foreach ($searchAttrs as $searchAttr) {
4323 $groups = searchLDAPByAttribute($searchAttr, $attributes['dn'], null, ['dn'], ['gon', 'group']);
4324 foreach ($groups as $group) {
4325 logNewMessage(LOG_DEBUG, 'Removing ' . $attributes['dn'] . ' from ' . $group['dn'] . ' (' . $searchAttr . ')');
4326 $attributesToDelete = [$searchAttr => [$attributes['dn']]];
4327 $success = @ldap_mod_del($_SESSION['ldap']->server(), $group['dn'], $attributesToDelete);
4328 if (!$success) {
4329 $ldapError = getDefaultLDAPErrorString($_SESSION['ldap']->server());
4330 logNewMessage(LOG_ERR, 'Unable to delete attributes of DN: ' . $group['dn'] . ' (' . $ldapError . ').');
4331 logNewMessage(LOG_DEBUG, print_r($attributesToDelete, true));
4332 throw new LAMException(sprintf(_('Was unable to modify attributes of DN: %s.'), $group['dn']), $ldapError);
4333 }
4334 }
4335 }
4336 }
4337
4338 /**
4339 * Clears the posix group memberships of the user.
4340 *
4341 * @param array<string, string[]|string> $attributes LDAP attributes
4342 * @throws LAMException error during group modify
4343 */
4344 private function clearPosixGroupMemberships(array $attributes): void {
4345 $searchAttr = 'memberuid';
4346 $uid = $attributes['uid'][0];
4347 $groups = searchLDAPByAttribute($searchAttr, $uid, null, ['dn'], ['group']);
4348 foreach ($groups as $group) {
4349 logNewMessage(LOG_DEBUG, 'Removing ' . $uid . ' from ' . $group['dn'] . ' (' . $searchAttr . ')');
4350 $attributesToDelete = [$searchAttr => [$uid]];
4351 $success = @ldap_mod_del($_SESSION['ldap']->server(), $group['dn'], $attributesToDelete);
4352 if (!$success) {
4353 $ldapError = getDefaultLDAPErrorString($_SESSION['ldap']->server());
4354 logNewMessage(LOG_ERR, 'Unable to delete attributes of DN: ' . $group['dn'] . ' (' . $ldapError . ').');
4355 logNewMessage(LOG_DEBUG, print_r($attributesToDelete, true));
4356 throw new LAMException(sprintf(_('Was unable to modify attributes of DN: %s.'), $group['dn']), $ldapError);
4357 }
4358 }
4359 }
4360
4361 /**
4362 * @inheritDoc
4363 */
4364 public function accountStatusPerformUnlock(ConfiguredType $type, ?array &$attributes, array $lockIds): void {
4365 if ($attributes === null) {
4366 $attributes = &$this->attributes;
4367 }
4368 $attributeName = $this->getPasswordAttrName($type->getModules());
4369 if (in_array(self::STATUS_PASSWORD_LOCKED, $lockIds)) {
4370 $attributes[$attributeName][0] = pwd_enable($attributes[$attributeName][0]);
4371 }
4372 }
4373
4374 /**
4375 * @inheritDoc
4376 */
4377 public function getListAttributeDescriptions(ConfiguredType $type): array {
4378 return [
4379 'uid' => _('User name'),
4380 'cn' => _('Common name'),
4381 'gecos' => _('Gecos'),
4382 'uidnumber' => _('UID number'),
4383 'gidnumber' => _('GID number'),
4384 'homedirectory' => _('Home directory'),
4385 'loginshell' => _('Login shell'),
4386 ];
4387 }
4388
4389 }