Debian Codegraph @

lib/selfService.inc

raw
1 <?php
2
3 use LAM\LIB\TWO_FACTOR\TwoFactorProviderService;
4 use LAM\PERSISTENCE\ConfigurationDatabase;
5 use LDAP\Connection;
6 use function LAM\PERSISTENCE\dbTableExists;
7
8 /*
9
10 This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
11 Copyright (C) 2006 - 2026 Roland Gruber
12
13 This program is free software; you can redistribute it and/or modify
14 it under the terms of the GNU General Public License as published by
15 the Free Software Foundation; either version 2 of the License, or
16 (at your option) any later version.
17
18 This program is distributed in the hope that it will be useful,
19 but WITHOUT ANY WARRANTY; without even the implied warranty of
20 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 GNU General Public License for more details.
22
23 You should have received a copy of the GNU General Public License
24 along with this program; if not, write to the Free Software
25 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26
27
28 */
29
30 /**
31 * Interface between modules and self-service pages.
32 * This file also includes the self-service profile class and helper functions.
33 *
34 * @package selfService
35 * @author Roland Gruber
36 */
37
38 /** modules */
39 include_once __DIR__ . "/modules.inc";
40 /** account types */
41 include_once __DIR__ . "/types.inc";
42 /** 2-factor */
43 include_once __DIR__ . '/2factor.inc';
44
45 /**
46 * Returns if this is a LAM Pro installation.
47 *
48 * @return boolean LAM Pro installation
49 */
50 function isLAMProVersion() {
51 $dir = substr(__FILE__, 0, strlen(__FILE__) - 20) . "/templates/selfService";
52 return is_dir($dir);
53 }
54
55 /**
56 * Returns a list of possible search attributes for the self-service.
57 *
58 * @param string $scope account type
59 * @return string[] attributes
60 */
61 function getSelfServiceSearchAttributes($scope): array {
62 $return = [];
63 $modules = getAvailableModules($scope);
64 for ($i = 0; $i < count($modules); $i++) {
65 $m = moduleCache::getModule($modules[$i], $scope);
66 $attributes = $m->getSelfServiceSearchAttributes();
67 $return = array_merge($return, $attributes);
68 }
69 $return = array_unique($return);
70 return array_values($return);
71 }
72
73 /**
74 * Returns the field settings for the self-service.
75 *
76 * @param string $scope account type
77 * @return array<string, array<string, string>> settings
78 */
79 function getSelfServiceFieldSettings($scope) {
80 $return = [];
81 $modules = getAvailableModules($scope);
82 for ($i = 0; $i < count($modules); $i++) {
83 $m = moduleCache::getModule($modules[$i], $scope);
84 $settings = $m->getSelfServiceFields();
85 if (count($settings) > 0) {
86 $return[$modules[$i]] = $settings;
87 }
88 }
89 return $return;
90 }
91
92 /**
93 * Returns meta HTML code for each self-service field.
94 *
95 * @param string $scope account type
96 * @param array<string, string[]> $fields input fields (array(<moduleName> => array(<field1>, <field2>, ...)))
97 * @param array<string, string[]|string> $attributes LDAP attributes (attribute names in lower-case)
98 * @param boolean $passwordChangeOnly indicates that the user is only allowed to change his password and no LDAP content is readable
99 * @param string[] $readOnlyFields list of read-only fields
100 * @return array<string, array<string, htmlResponsiveRow>> meta HTML code (array(<moduleName> => array(<optionName> => htmlResponsiveRow)))
101 */
102 function getSelfServiceOptions($scope, $fields, $attributes, $passwordChangeOnly, $readOnlyFields) {
103 $return = [];
104 $modules = getAvailableModules($scope);
105 foreach ($modules as $module) {
106 if (!isset($fields[$module])) {
107 continue;
108 }
109 $m = moduleCache::getModule($module, $scope);
110 $modReadOnlyFields = [];
111 for ($r = 0; $r < count($readOnlyFields); $r++) {
112 $parts = explode('_', $readOnlyFields[$r]);
113 if ($parts[0] == $module) {
114 $modReadOnlyFields[] = $parts[1];
115 }
116 }
117 $code = $m->getSelfServiceOptions($fields[$module], $attributes, $passwordChangeOnly, $modReadOnlyFields);
118 if (count($code) > 0) {
119 $return[$module] = $code;
120 }
121 }
122 return $return;
123 }
124
125 /**
126 * Checks if all input values are correct and returns the LDAP commands which should be executed.
127 *
128 * @param string $scope account type
129 * @param array<string, string[]> $fields input fields (array(<moduleName> => array(<field1>, <field2>, ...)))
130 * @param array<string, string[]|string> $attributes LDAP attributes
131 * @param boolean $passwordChangeOnly indicates that the user is only allowed to change his password and no LDAP content is readable
132 * @param string[] $readOnlyFields list of read-only fields
133 * @return array<string, string[]|array<string, string[]|string>> messages and LDAP commands (array('messages' => [], 'add' => [], 'del' => [], 'mod' => []))
134 */
135 function checkSelfServiceOptions($scope, $fields, $attributes, $passwordChangeOnly, $readOnlyFields) {
136 $return = ['messages' => [], 'add' => [], 'del' => [], 'mod' => [], 'info' => []];
137 $modules = getAvailableModules($scope);
138 for ($i = 0; $i < count($modules); $i++) {
139 if (!isset($fields[$modules[$i]])) {
140 continue;
141 }
142 $m = moduleCache::getModule($modules[$i], $scope);
143 $modReadOnlyFields = [];
144 for ($r = 0; $r < count($readOnlyFields); $r++) {
145 $parts = explode('_', $readOnlyFields[$r]);
146 if ($parts[0] == $modules[$i]) {
147 $modReadOnlyFields[] = $parts[1];
148 }
149 }
150 $result = $m->checkSelfServiceOptions($fields[$modules[$i]], $attributes, $passwordChangeOnly, $modReadOnlyFields);
151 if (count($result['messages']) > 0) {
152 $return['messages'] = array_merge($result['messages'], $return['messages']);
153 }
154 if (count($result['add']) > 0) {
155 $return['add'] = array_merge($result['add'], $return['add']);
156 }
157 if (count($result['del']) > 0) {
158 $return['del'] = array_merge($result['del'], $return['del']);
159 }
160 if (count($result['mod']) > 0) {
161 $return['mod'] = array_merge($result['mod'], $return['mod']);
162 }
163 if (count($result['info']) > 0) {
164 $return['info'] = array_merge($result['info'], $return['info']);
165 }
166 }
167 return $return;
168 }
169
170 /**
171 * Returns a hash array (module name => elements) of all module options for the configuration page.
172 *
173 * @param string $scope account type
174 * @param selfServiceProfile $profile currently edited profile
175 * @return array<string, htmlElement> configuration options
176 */
177 function getSelfServiceSettings(string $scope, selfServiceProfile $profile): array {
178 $return = [];
179 $modules = getAvailableModules($scope);
180 for ($i = 0; $i < count($modules); $i++) {
181 $m = moduleCache::getModule($modules[$i], $scope);
182 $modSettings = $m->getSelfServiceSettings($profile);
183 if ($modSettings === null) {
184 continue;
185 }
186 $return[$modules[$i]] = $modSettings;
187 }
188 return $return;
189 }
190
191 /**
192 * Checks if the self-service settings are valid
193 *
194 * @param string $scope account type
195 * @param array<string, string[]> $options hash array containing all options (name => array(...))
196 * @param selfServiceProfile $profile profile
197 * @return string[][] list of error messages
198 */
199 function checkSelfServiceSettings($scope, &$options, &$profile) {
200 $return = [];
201 $modules = getAvailableModules($scope);
202 for ($i = 0; $i < count($modules); $i++) {
203 $m = moduleCache::getModule($modules[$i], $scope);
204 $errors = $m->checkSelfServiceSettings($options, $profile);
205 $return = array_merge($return, $errors);
206 }
207 return $return;
208 }
209
210 /**
211 * Returns if script runs inside self-service.
212 *
213 * @return boolean is self-service
214 */
215 function isSelfService() {
216 return session_name() == 'SELFSERVICE';
217 }
218
219 /**
220 * Opens the LDAP connection and returns the handle. No bind is done.
221 *
222 * @param selfServiceProfile $profile profile
223 * @return Connection|null LDAP handle or null if connection failed
224 */
225 function openSelfServiceLdapConnection($profile): ?Connection {
226 $server = connectToLDAP($profile->serverURL, $profile->useTLS);
227 if ($server != null) {
228 // follow referrals
229 ldap_set_option($server, LDAP_OPT_REFERRALS, $profile->followReferrals);
230 }
231 return $server;
232 }
233
234 /**
235 * Binds the LDAP connections with given user and password.
236 *
237 * @param Connection $handle LDAP handle
238 * @param selfServiceProfile $profile profile
239 * @param string $userDn bind DN
240 * @param string $password bind password
241 * @return bool binding successful
242 */
243 function bindLdapUser($handle, $profile, $userDn, $password): bool {
244 if ($profile->useForAllOperations) {
245 $userDn = $profile->LDAPUser;
246 $password = deobfuscateText($profile->LDAPPassword);
247 }
248 return @ldap_bind($handle, $userDn, $password);
249 }
250
251 /**
252 * Manages reading and writing self-service profiles.
253 */
254 class SelfServicePersistence {
255
256 /**
257 * @var SelfServicePersistenceStrategy
258 */
259 private $strategy;
260
261 /**
262 * Constructor
263 *
264 * @throws LAMException error connecting database
265 */
266 public function __construct() {
267 $configDb = new ConfigurationDatabase(new LAMCfgMain());
268 if ($configDb->useRemoteDb()) {
269 try {
270 $this->strategy = new SelfServicePersistenceStrategyPdo($configDb->getPdo());
271 }
272 catch (PDOException $e) {
273 logNewMessage(LOG_ERR, _('Unable to connect to configuration database.') . ' ' . $e->getMessage());
274 throw new LAMException(_('Unable to connect to configuration database.'), '', $e);
275 }
276 }
277 else {
278 $this->strategy = new SelfServicePersistenceStrategyFileSystem();
279 }
280 }
281
282 /**
283 * Returns a list of available self-service profiles.
284 *
285 * @return array<string, string[]> profile names (array('account type' => array('profile1', 'profile2')))
286 */
287 public function getProfiles(): array {
288 $profiles = $this->strategy->getProfiles();
289 ksort($profiles);
290 foreach (array_keys($profiles) as $key) {
291 sort($profiles[$key]);
292 }
293 return $profiles;
294 }
295
296 /**
297 * Returns if the profile with given name can be written.
298 *
299 * @param string $name profile name
300 * @param string $scope user/group/host
301 * @return bool can be written
302 */
303 public function canWrite(string $name, string $scope): bool {
304 return $this->strategy->canWrite($name, $scope);
305 }
306
307 /**
308 * Loads the given self-service profile.
309 *
310 * @param string $name profile name
311 * @param string $scope user/group/host
312 * @return selfServiceProfile profile
313 * @throws LAMException error during loading
314 */
315 public function load(string $name, string $scope): selfServiceProfile {
316 return $this->strategy->load($name, $scope);
317 }
318
319 /**
320 * Stores the given profile.
321 *
322 * @param string $name profile name
323 * @param string $scope user/group/host
324 * @param selfServiceProfile $profile profile
325 * @throws LAMException error during saving
326 */
327 public function save(string $name, string $scope, selfServiceProfile $profile): void {
328 $this->strategy->save($name, $scope, $profile);
329 }
330
331 /**
332 * Deletes a self-service profile.
333 *
334 * @param string $name profile name
335 * @param string $scope user/group/host
336 * @throws LAMException error deleting profile
337 */
338 public function delete(string $name, string $scope): void {
339 $profileList = $this->getProfiles();
340 if (!preg_match("/^[a-z]+$/i", $scope)
341 || !preg_match("/^[a-z0-9_-]+$/i", $name)
342 || empty($profileList[$scope])
343 || !in_array($name, $profileList[$scope])) {
344 throw new LAMException(_("Unable to delete profile!"));
345 }
346 $this->strategy->delete($name, $scope);
347 }
348
349 /**
350 * Renames a self-service profile.
351 *
352 * @param string $oldName existing profile name
353 * @param string $newName new profile name
354 * @param string $scope user/group/host
355 * @throws LAMException error renaming profile
356 */
357 public function rename(string $oldName, string $newName, string $scope): void {
358 $profileList = $this->getProfiles();
359 if (!preg_match("/^[a-z]+$/i", $scope)
360 || !preg_match("/^[a-z0-9_-]+$/i", $newName)
361 || empty($profileList[$scope])
362 || !in_array($oldName, $profileList[$scope])) {
363 throw new LAMException(_("Profile name is invalid!"));
364 }
365 $this->strategy->rename($oldName, $newName, $scope);
366 }
367
368 }
369
370 /**
371 * Interface for self-service profile persistence.
372 */
373 interface SelfServicePersistenceStrategy {
374
375 /**
376 * Returns a list of available self-service profiles.
377 *
378 * @return array<string, string[]> profile names (array('account type' => array('profile1', 'profile2')))
379 */
380 public function getProfiles(): array;
381
382 /**
383 * Returns if the profile with the given name can be written.
384 *
385 * @param string $name profile name
386 * @param string $scope user/group/host
387 * @return bool can be written
388 */
389 public function canWrite(string $name, string $scope): bool;
390
391 /**
392 * Loads the given self-service profile.
393 *
394 * @param string $name profile name
395 * @param string $scope user/group/host
396 * @return selfServiceProfile profile
397 * @throws LAMException error during loading
398 */
399 public function load(string $name, string $scope): selfServiceProfile;
400
401 /**
402 * Stores the given profile.
403 *
404 * @param string $name profile name
405 * @param string $scope user/group/host
406 * @param selfServiceProfile $profile profile
407 * @throws LAMException error during saving
408 */
409 public function save(string $name, string $scope, selfServiceProfile $profile): void;
410
411 /**
412 * Deletes a self-service profile.
413 *
414 * @param string $name profile name
415 * @param string $scope account type
416 * @throws LAMException error renaming profile
417 */
418 public function delete(string $name, string $scope): void;
419
420 /**
421 * Renames a self-service profile.
422 *
423 * @param string $oldName existing profile name
424 * @param string $newName new profile name
425 * @param string $scope user/group/host
426 * @throws LAMException error renaming profile
427 */
428 public function rename(string $oldName, string $newName, string $scope): void;
429
430 }
431
432 /**
433 * Uses local file system for storing self-service profiles.
434 */
435 class SelfServicePersistenceStrategyFileSystem implements SelfServicePersistenceStrategy {
436
437 /**
438 * @inheritDoc
439 */
440 public function getProfiles(): array {
441 $types = LAM\TYPES\getTypes();
442 $dir = dir(__DIR__ . "/../config/selfService");
443 $ret = [];
444 if ($dir === false) {
445 logNewMessage(LOG_ERR, 'Unable to read self-service profiles');
446 return $ret;
447 }
448 while ($entry = $dir->read()) {
449 $ext = substr($entry, strrpos($entry, '.') + 1);
450 $name = substr($entry, 0, strrpos($entry, '.'));
451 // check if extension is right, add to profile list
452 if (in_array($ext, $types)) {
453 $ret[$ext][] = $name;
454 }
455 }
456 return $ret;
457 }
458
459 /**
460 * @inheritDoc
461 */
462 public function canWrite(string $name, string $scope): bool {
463 // check profile name
464 if (!preg_match("/^[0-9a-z _-]+$/i", $scope) || !preg_match("/^[0-9a-z _-]+$/i", $name)) {
465 return false;
466 }
467 $path = __DIR__ . "/../config/selfService/" . $name . "." . $scope;
468 return is_writable($path);
469 }
470
471 /**
472 * @inheritDoc
473 */
474 public function load(string $name, string $scope): selfServiceProfile {
475 if (!preg_match("/^[0-9a-z _-]+$/i", $name) || !preg_match("/^[0-9a-z _-]+$/i", $scope)) {
476 throw new LAMException(_("Profile name is invalid!"));
477 }
478 $profile = new selfServiceProfile();
479 $file = __DIR__ . "/../config/selfService/" . $name . "." . $scope;
480 if (is_file($file)) {
481 $file = @fopen($file, "r");
482 if ($file) {
483 $data = fread($file, 10000000);
484 $profileData = @json_decode($data, true);
485 if ($profileData === null) {
486 logNewMessage(LOG_ERR, "Unable to load profile because not in JSON format: " . $name);
487 throw new LAMException(_("Unable to load profile!"), $name);
488 }
489 $profile = selfServiceProfile::import($profileData);
490 fclose($file);
491 }
492 else {
493 throw new LAMException(_("Unable to load profile!"), $name);
494 }
495 }
496 else {
497 throw new LAMException(_("Unable to load profile!"), $name);
498 }
499 return $profile;
500 }
501
502 /**
503 * @inheritDoc
504 */
505 public function save(string $name, string $scope, selfServiceProfile $profile): void {
506 // check profile name
507 if (!preg_match("/^[0-9a-z _-]+$/i", $scope) || !preg_match("/^[0-9a-z _-]+$/i", $name)) {
508 throw new LAMException(_("Profile name is invalid!"));
509 }
510 $path = __DIR__ . "/../config/selfService/" . $name . "." . $scope;
511 $file = @fopen($path, "w");
512 if ($file) {
513 // write settings to file
514 fwrite($file, json_encode($profile->export()));
515 // close file
516 fclose($file);
517 @chmod($path, 0600);
518 }
519 else {
520 throw new LAMException(_("Unable to save profile!"));
521 }
522 }
523
524 /**
525 * @inheritDoc
526 */
527 public function delete(string $name, string $scope): void {
528 if (!unlink("../../config/selfService/" . $name . "." . $scope)) {
529 throw new LAMException(_("Unable to delete profile!"));
530 }
531 }
532
533 /**
534 * @inheritDoc
535 */
536 public function rename(string $oldName, string $newName, string $scope): void {
537 if (!@rename(__DIR__ . "/../config/selfService/" . $oldName . "." . $scope,
538 __DIR__ . "/../config/selfService/" . $newName . "." . $scope)) {
539 throw new LAMException(_("Could not rename file!"));
540 }
541 }
542
543 }
544
545 /**
546 * Uses PDO for storing self-service profiles.
547 */
548 class SelfServicePersistenceStrategyPdo implements SelfServicePersistenceStrategy {
549
550 /**
551 * @var PDO
552 */
553 private $pdo;
554
555 private const TABLE_NAME = 'self_service_profiles';
556
557 /**
558 * Constructor
559 *
560 * @param PDO $pdo PDO
561 */
562 public function __construct(PDO $pdo) {
563 $this->pdo = $pdo;
564 $this->checkSchema();
565 }
566
567 /**
568 * Checks if the schema has latest version.
569 */
570 private function checkSchema(): void {
571 if (!dbTableExists($this->pdo, self::TABLE_NAME)) {
572 $this->createInitialSchema();
573 }
574 }
575
576 /**
577 * Creates the initial schema.
578 */
579 public function createInitialSchema(): void {
580 logNewMessage(LOG_DEBUG, 'Creating database table ' . self::TABLE_NAME);
581 $sql = 'create table ' . self::TABLE_NAME . '('
582 . 'scope VARCHAR(100) NOT NULL,'
583 . 'name VARCHAR(300) NOT NULL,'
584 . 'data TEXT NOT NULL,'
585 . 'PRIMARY KEY(scope,name)'
586 . ');';
587 $this->pdo->exec($sql);
588 $sql = 'insert into ' . ConfigurationDatabase::TABLE_SCHEMA_VERSIONS . ' (name, version) VALUES ("self_service", 1);';
589 $this->pdo->exec($sql);
590 }
591
592 /**
593 * @inheritDocm
594 */
595 public function getProfiles(): array {
596 $statement = $this->pdo->prepare("SELECT scope, name FROM " . self::TABLE_NAME);
597 $statement->execute();
598 $results = $statement->fetchAll();
599 $profiles = [];
600 foreach ($results as $result) {
601 $profiles[$result['scope']][] = $result['name'];
602 }
603 return $profiles;
604 }
605
606 /**
607 * @inheritDoc
608 */
609 public function canWrite(string $name, string $scope): bool {
610 return true;
611 }
612
613 /**
614 * @inheritDoc
615 */
616 public function load(string $name, string $scope): selfServiceProfile {
617 $statement = $this->pdo->prepare("SELECT data FROM " . self::TABLE_NAME . " WHERE scope = ? AND name = ?");
618 $statement->execute([$scope, $name]);
619 $results = $statement->fetchAll();
620 if (empty($results)) {
621 logNewMessage(LOG_ERR, 'Self-service profile not found');
622 throw new LAMException(_("Unable to load profile!"), $name);
623 }
624 $data = json_decode($results[0]['data'], true);
625 return selfServiceProfile::import($data);
626 }
627
628 /**
629 * @inheritDoc
630 */
631 public function save(string $name, string $scope, selfServiceProfile $profile): void {
632 $data = json_encode($profile->export());
633 $statement = $this->pdo->prepare("SELECT data FROM " . self::TABLE_NAME . " WHERE scope = ? AND name = ?");
634 $statement->execute([$scope, $name]);
635 $results = $statement->fetchAll();
636 if (empty($results)) {
637 $statement = $this->pdo->prepare("INSERT INTO " . self::TABLE_NAME . " (scope, name, data) VALUES (?, ?, ?)");
638 $statement->execute([$scope, $name, $data]);
639 }
640 else {
641 $statement = $this->pdo->prepare("UPDATE " . self::TABLE_NAME . " SET data = ? WHERE scope = ? AND name = ?");
642 $statement->execute([$data, $scope, $name]);
643 }
644 }
645
646 /**
647 * @inheritDoc
648 */
649 public function delete(string $name, string $scope): void {
650 $statement = $this->pdo->prepare("DELETE FROM " . self::TABLE_NAME . " WHERE scope = ? AND name = ?");
651 $statement->execute([$scope, $name]);
652 }
653
654 /**
655 * @inheritDoc
656 */
657 public function rename(string $oldName, string $newName, string $scope): void {
658 $statement = $this->pdo->prepare("UPDATE " . self::TABLE_NAME . " SET name = ? WHERE scope = ? AND name = ?");
659 $statement->execute([$newName, $scope, $oldName]);
660 }
661
662 }
663
664 /**
665 * Includes all settings of a self-service profile.
666 *
667 * @package selfService
668 */
669 class selfServiceProfile {
670
671 /** server address */
672 public string $serverURL = "localhost";
673
674 /** use TLS */
675 public bool $useTLS = false;
676
677 /** LDAP suffix */
678 public string $LDAPSuffix = "dc=my-domain,dc=com";
679
680 /** LDAP user DN*/
681 public string $LDAPUser = "";
682
683 /** LDAP password */
684 public string $LDAPPassword = "";
685
686 /** use bind user also for read/modify operations */
687 public ?bool $useForAllOperations = false;
688
689 /** LDAP search attribute */
690 public string $searchAttribute = "uid";
691
692 /**
693 * @var string|null login handler ID
694 */
695 public ?string $loginHandler = SelfServiceUserPasswordLoginHandler::ID;
696
697 /** header for self-service pages */
698 public string $pageHeader = '<p><a href="https://www.ldap-account-manager.org/" target="new_window"><img alt="help" class="align-middle" src="../../graphics/logo.svg" style="height:24px; width:24px" /> LDAP Account Manager </a></p><p>&nbsp;</p>';
699
700 /** base color */
701 public string $baseColor = '#fffde2';
702
703 /** list of additional CSS links (separated by \n) */
704 public string $additionalCSS = '';
705
706 /** describing text for user login */
707 public string $loginCaption = '';
708
709 /** describing text for user login */
710 public ?string $loginFooter = '';
711
712 /** label for password input */
713 public ?string $passwordLabel = '';
714
715 /** describing text for search attribute */
716 public string $loginAttributeText = '';
717
718 /** additional LDAP filter for accounts */
719 public ?string $additionalLDAPFilter = '';
720
721 /** describing text for self-service main page */
722 public string $mainPageText;
723
724 /** describing text for self-service main page */
725 public ?string $mainPageFooter = '';
726
727 /**
728 * @var array<string, string|string[]>[] $inputFields input fields
729 * Format: array(
730 * <br> array(array('name' => <group name 1>, 'fields' => array(<field1>, <field2>))),
731 * <br> array(array('name' => <group name 2>, 'fields' => array(<field3>, <field4>)))
732 * <br> )
733 */
734 public array $inputFields = [];
735
736 /**
737 * @var string[] $readOnlyFields list of fields that are set in read-only mode.
738 */
739 public array $readOnlyFields = [];
740
741 /** @var array<string, string>|null $relabelFields list of override values for field labels: array(<field ID> => label) */
742 public ?array $relabelFields = [];
743
744 /** @var array<string, string[]> $moduleSettings configuration settings of modules */
745 public array $moduleSettings = [];
746
747 /** language for self-service */
748 public string $language = 'en_GB.utf8';
749 /** disallow user to change language */
750 public bool $enforceLanguage = false;
751
752 public int $followReferrals = 0;
753
754 public string $timeZone = 'Europe/London';
755
756 public string $twoFactorAuthentication = TwoFactorProviderService::TWO_FACTOR_NONE;
757 public string $twoFactorAuthenticationURL = 'https://localhost';
758 public bool $twoFactorAuthenticationInsecure = false;
759 public ?string $twoFactorAuthenticationLabel = '';
760 public bool $twoFactorAuthenticationOptional = false;
761 public string $twoFactorAuthenticationCaption = '';
762 public string $twoFactorAuthenticationClientId = '';
763 public string $twoFactorAuthenticationSecretKey = '';
764 public string $twoFactorAuthenticationAttribute = 'uid';
765 public string $twoFactorAuthenticationDomain = '';
766 public string $twoFactorAllowToRememberDevice = 'false';
767 public string $twoFactorRememberDeviceDuration = '28800';
768 public string $twoFactorRememberDevicePassword = '';
769
770 /** provider for captcha (-/google/hCaptcha/friendlyCaptcha) */
771 public string $captchaProvider = '-';
772 /** Google reCAPTCHA site key */
773 public string $reCaptchaSiteKey = '';
774 /** Google reCAPTCHA secret key */
775 public string $reCaptchaSecretKey = '';
776 /** enable captcha on self-service login */
777 public bool $captchaOnLogin = false;
778
779 /** base URL for the website (e.g. https://example.com) for link generation */
780 public string $baseUrl = '';
781
782 /**
783 * Path to external lamdaemon script on server where it is executed
784 *
785 * This is used for managing quota and home directories.
786 * optional setting, may not be defined
787 */
788 public ?string $scriptPath = '';
789
790 /**
791 * The rights for the home directory
792 */
793 public string $scriptRights = '750';
794
795 /**
796 * Servers where lamdaemon script is executed
797 *
798 * This is used for managing quota and home directories.
799 * optional setting, may not be defined
800 */
801 public ?string $scriptServer = '';
802
803 /**
804 * user name for lamdaemon
805 */
806 public ?string $scriptUserName = '';
807
808 /**
809 * File name of SSH key for lamdaemon.
810 */
811 public ?string $scriptSSHKey = '';
812
813 /**
814 * Password for lamdaemon SSH key.
815 */
816 public ?string $scriptSSHKeyPassword = '';
817
818 /**
819 * Constructor
820 */
821 public function __construct() {
822 $this->loginCaption = '<b>' . _("Welcome to LAM self-service. Please enter your user name and password.") . '</b>';
823 $this->loginAttributeText = _('User name');
824 $this->mainPageText = "<h1>LAM self-service</h1>\n" . _("Here you can change your personal settings.");
825 $this->inputFields = [
826 ['name' => _('Personal data'),
827 'fields' => ['inetOrgPerson_firstName', 'inetOrgPerson_lastName', 'inetOrgPerson_mail',
828 'inetOrgPerson_telephoneNumber', 'inetOrgPerson_mobile', 'inetOrgPerson_faxNumber',
829 'inetOrgPerson_street', 'inetOrgPerson_postalAddress']],
830 ['name' => _('Password'),
831 'fields' => ['posixAccount_password']]
832 ];
833 }
834
835 /**
836 * Converts the export data back to a self-service profile.
837 *
838 * @param array<string, string|int|null> $data export data
839 * @return selfServiceProfile profile
840 */
841 public static function import($data): selfServiceProfile {
842 $profile = new selfServiceProfile();
843 $vars = get_class_vars(selfServiceProfile::class);
844 foreach ($data as $key => $value) {
845 if (array_key_exists($key, $vars) && ($value !== null)) {
846 $profile->$key = $value;
847 }
848 }
849 return $profile;
850 }
851
852 /**
853 * Returns a representation of the self-service profile.
854 *
855 * @return array<string, string|int> self-service profile data
856 */
857 public function export() {
858 return json_decode(json_encode($this), true);
859 }
860
861 /**
862 * Returns the server's base URL (e.g. https://www.example.com).
863 *
864 * @return string URL
865 */
866 public function getBaseUrl() {
867 if (!empty($this->baseUrl)) {
868 return $this->baseUrl;
869 }
870 $callingUrl = getCallingURL();
871 $matches = [];
872 if (preg_match('/^(http(s)?:\\/\\/[^\\/]+)\\/.+$/', $callingUrl, $matches)) {
873 return $matches[1];
874 }
875 return '';
876 }
877
878 /**
879 * Sets the server's base URL (e.g. https://www.example.com).
880 *
881 * @param string $url URL
882 */
883 public function setBaseUrl($url): void {
884 $this->baseUrl = $url;
885 if (!empty($url) && (str_ends_with($url, '/'))) {
886 $this->baseUrl = substr($url, 0, -1);
887 }
888 }
889
890 /**
891 * Returns the login handler.
892 *
893 * @return SelfServiceLoginHandler handler
894 */
895 public function getLoginHandler(): SelfServiceLoginHandler {
896 return match ($this->loginHandler) {
897 SelfServiceHttpAuthLoginHandler::ID => new SelfServiceHttpAuthLoginHandler($this),
898 SelfService2FaLoginHandler::ID => new SelfService2FaLoginHandler($this),
899 default => new SelfServiceUserPasswordLoginHandler($this),
900 };
901 }
902
903 }
904
905 /**
906 * LDAP connection for self-service.
907 */
908 class SelfServiceLdapConnection {
909
910 private Connection|null $server = null;
911
912 private selfServiceProfile $profile;
913
914 /**
915 * Constructor
916 *
917 * @param selfServiceProfile $profile profile
918 */
919 public function __construct(selfServiceProfile $profile) {
920 $this->profile = $profile;
921 }
922
923 /**
924 * Returns the LDAP handle.
925 *
926 * @return Connection|null LDAP handle
927 */
928 public function getServer(): ?Connection {
929 if ($this->server !== null) {
930 return $this->server;
931 }
932 $this->server = openSelfServiceLdapConnection($this->profile);
933 return $this->server;
934 }
935
936 /**
937 * Binds with the given credentials.
938 *
939 * @param string $userDn user DN
940 * @param string $password password
941 * @return bool bind successful
942 */
943 public function bind(string $userDn, string $password): bool {
944 return bindLdapUser($this->getServer(), $this->profile, $userDn, $password);
945 }
946
947 /**
948 * Closes connection to the LDAP server before serialization.
949 *
950 * @return array<string, selfServiceProfile> data
951 */
952 public function __serialize(): array {
953 if ($this->server !== null) {
954 @ldap_close($this->server);
955 $this->server = null;
956 }
957 // define which attributes to save
958 return ['profile' => $this->profile];
959 }
960
961 /**
962 * Restores the profile.
963 *
964 * @param array<string, selfServiceProfile> $data data
965 */
966 public function __unserialize(array $data): void {
967 $this->profile = $data['profile'];
968 }
969
970 }
971
972 /**
973 * Login handler for self-service
974 */
975 interface SelfServiceLoginHandler {
976
977 /**
978 * Returns a unique ID for the handler.
979 *
980 * @return string ID
981 */
982 public function getId(): string;
983
984 /**
985 * Adds necessary fields to the login dialog (e.g. user + password).
986 *
987 * @param htmlResponsiveRow $content dialog content
988 */
989 public function addLoginFields(htmlResponsiveRow $content): void;
990
991 /**
992 * Returns the login name.
993 *
994 * @return string login name
995 */
996 public function getLoginName(): string;
997
998 /**
999 * Returns the login password.
1000 *
1001 * @return string password
1002 */
1003 public function getLoginPassword(): string;
1004
1005 /**
1006 * Returns if the login handler manages authentication on its own.
1007 *
1008 * @return bool manages authentication
1009 */
1010 public function managesAuthentication(): bool;
1011
1012 /**
1013 * Returns if the authentication was successful.
1014 * Only valid if managesAuthentication() returns true.
1015 *
1016 * @return bool authentication successful
1017 * @throws LAMException error during authentication
1018 */
1019 public function isAuthenticationSuccessful(): bool;
1020
1021 /**
1022 * Authorizes an user that was provided by 2FA provider.
1023 *
1024 * @param string $userName user name
1025 * @throws LAMException error during authentication
1026 */
1027 public function authorize2FaUser(string $userName): void;
1028
1029 }
1030
1031 /**
1032 * Performs login with user and password.
1033 */
1034 class SelfServiceUserPasswordLoginHandler implements SelfServiceLoginHandler {
1035
1036 public const ID = "user_password";
1037
1038 private selfServiceProfile $profile;
1039
1040 /**
1041 * Constructor
1042 *
1043 * @param selfServiceProfile $profile profile
1044 */
1045 public function __construct(selfServiceProfile $profile) {
1046 $this->profile = $profile;
1047 }
1048
1049 /**
1050 * @inheritDoc
1051 */
1052 public function getId(): string {
1053 return self::ID;
1054 }
1055
1056 /**
1057 * @inheritDoc
1058 */
1059 public function addLoginFields(htmlResponsiveRow $content): void {
1060 // user name
1061 $userNameVal = empty($_POST['username']) ? '' : $_POST['username'];
1062 $userField = new htmlResponsiveInputField($this->profile->loginAttributeText, 'username', $userNameVal);
1063 $userField->setCSSClasses(['lam-initial-focus']);
1064 $content->add($userField);
1065 // password field
1066 $passwordText = _("Password");
1067 if (!empty($this->profile->passwordLabel)) {
1068 $passwordText = $this->profile->passwordLabel;
1069 }
1070 $passwordVal = empty($_POST['password']) ? '' : $_POST['password'];
1071 $passwordField = new htmlResponsiveInputField($passwordText, 'password', $passwordVal);
1072 $passwordField->setIsPassword(true);
1073 $content->add($passwordField);
1074 }
1075
1076 /**
1077 * @inheritDoc
1078 */
1079 public function getLoginName(): string {
1080 return $_POST['username'];
1081 }
1082
1083 /**
1084 * @inheritDoc
1085 */
1086 public function getLoginPassword(): string {
1087 return $_POST['password'];
1088 }
1089
1090 /**
1091 * @inheritDoc
1092 */
1093 public function managesAuthentication(): bool {
1094 return false;
1095 }
1096
1097 /**
1098 * @inheritDoc
1099 */
1100 public function isAuthenticationSuccessful(): bool {
1101 throw new LAMException('Not implemented');
1102 }
1103
1104 /**
1105 * @inheritDoc
1106 */
1107 public function authorize2FaUser(string $userName): void {
1108 // no action
1109 }
1110
1111 }
1112
1113 /**
1114 * Performs login with HTTP authentication.
1115 */
1116 class SelfServiceHttpAuthLoginHandler implements SelfServiceLoginHandler {
1117
1118 public const ID = "http_auth";
1119
1120 private selfServiceProfile $profile;
1121
1122 /**
1123 * Constructor
1124 *
1125 * @param selfServiceProfile $profile profile
1126 */
1127 public function __construct(selfServiceProfile $profile) {
1128 $this->profile = $profile;
1129 }
1130
1131 /**
1132 * @inheritDoc
1133 */
1134 public function getId(): string {
1135 return self::ID;
1136 }
1137
1138 /**
1139 * @inheritDoc
1140 */
1141 public function addLoginFields(htmlResponsiveRow $content): void {
1142 // user name
1143 $userLabel = new htmlLabel('username', $this->profile->loginAttributeText);
1144 $content->addLabel($userLabel);
1145 $userName = empty($_SERVER['PHP_AUTH_USER']) ? '-' : $_SERVER['PHP_AUTH_USER'];
1146 $userField = new htmlOutputText($userName);
1147 $content->addField($userField);
1148 // password field
1149 $passwordText = _("Password");
1150 if (!empty($this->profile->passwordLabel)) {
1151 $passwordText = $this->profile->passwordLabel;
1152 }
1153 $passwordLabel = new htmlLabel('password', $passwordText);
1154 $content->addLabel($passwordLabel);
1155 $passwordField = new htmlOutputText('**********');
1156 $content->addField($passwordField);
1157 }
1158
1159 /**
1160 * @inheritDoc
1161 */
1162 public function getLoginName(): string {
1163 return $_SERVER['PHP_AUTH_USER'];
1164 }
1165
1166 /**
1167 * @inheritDoc
1168 */
1169 public function getLoginPassword(): string {
1170 return $_SERVER['PHP_AUTH_PW'];
1171 }
1172
1173 /**
1174 * @inheritDoc
1175 */
1176 public function managesAuthentication(): bool {
1177 return false;
1178 }
1179
1180 /**
1181 * @inheritDoc
1182 */
1183 public function isAuthenticationSuccessful(): bool {
1184 throw new LAMException('Not implemented');
1185 }
1186
1187 /**
1188 * @inheritDoc
1189 */
1190 public function authorize2FaUser(string $userName): void {
1191 // no action
1192 }
1193
1194 }
1195
1196 /**
1197 * Performs login with pure 2FA.
1198 */
1199 class SelfService2FaLoginHandler implements SelfServiceLoginHandler {
1200
1201 public const ID = "2fa";
1202
1203 private selfServiceProfile $profile;
1204
1205 /**
1206 * Constructor
1207 *
1208 * @param selfServiceProfile $profile profile
1209 */
1210 public function __construct(selfServiceProfile $profile) {
1211 $this->profile = $profile;
1212 }
1213
1214 /**
1215 * @inheritDoc
1216 */
1217 public function getId(): string {
1218 return self::ID;
1219 }
1220
1221 /**
1222 * @inheritDoc
1223 */
1224 public function addLoginFields(htmlResponsiveRow $content): void {
1225 // no input fields
1226 }
1227
1228 /**
1229 * @inheritDoc
1230 */
1231 public function getLoginName(): string {
1232 return '';
1233 }
1234
1235 /**
1236 * @inheritDoc
1237 */
1238 public function getLoginPassword(): string {
1239 return '';
1240 }
1241
1242 /**
1243 * @inheritDoc
1244 */
1245 public function managesAuthentication(): bool {
1246 return true;
1247 }
1248
1249 /**
1250 * @inheritDoc
1251 */
1252 public function isAuthenticationSuccessful(): bool {
1253 if (($this->profile->twoFactorAuthentication !== TwoFactorProviderService::TWO_FACTOR_OKTA)
1254 && ($this->profile->twoFactorAuthentication !== TwoFactorProviderService::TWO_FACTOR_OPENID)) {
1255 logNewMessage(LOG_ERR, 'Unsupported 2FA provider: ' . $this->profile->twoFactorAuthentication);
1256 return false;
1257 }
1258 if (!$this->profile->useForAllOperations) {
1259 logNewMessage(LOG_ERR, 'Use for all operations must be set');
1260 return false;
1261 }
1262 // authentication will be checked on 2FA page
1263 return true;
1264 }
1265
1266 /**
1267 * @inheritDoc
1268 */
1269 public function authorize2FaUser(string $userName): void {
1270 $bindUser = $this->profile->LDAPUser;
1271 if (empty($bindUser)) {
1272 throw new LAMException('SelfService2FaLoginHandler', 'No bind user set');
1273 }
1274 $bindPassword = deobfuscateText($this->profile->LDAPPassword);
1275 $server = connectToLDAP($this->profile->serverURL, $this->profile->useTLS);
1276 if ($server === null) {
1277 throw new LAMException('SelfService2FaLoginHandler', 'Unable to match provided user with LDAP entry - LDAP connect failed');
1278 }
1279 ldap_set_option($server, LDAP_OPT_REFERRALS, $this->profile->followReferrals);
1280 $bind = @ldap_bind($server, $bindUser, $bindPassword);
1281 if (!$bind) {
1282 throw new LAMException('SelfService2FaLoginHandler', 'Unable to match provided user with LDAP entry - LDAP bind failed');
1283 }
1284 $filter = '(' . $this->profile->twoFactorAuthenticationAttribute . "=" . ldap_escape($userName, '', LDAP_ESCAPE_FILTER) . ')';
1285 if (!empty($this->profile->additionalLDAPFilter)) {
1286 $filter = '(&' . $filter . $this->profile->additionalLDAPFilter . ')';
1287 }
1288 $result = @ldap_search($server, $this->profile->LDAPSuffix, $filter, ['DN'], 0, 1, 0, LDAP_DEREF_NEVER);
1289 if ($result === false) {
1290 throw new LAMException('SelfService2FaLoginHandler', 'Unable to match provided user with LDAP entry - LDAP search failed');
1291 }
1292 $entries = @ldap_get_entries($server, $result);
1293 if ($entries === false) {
1294 throw new LAMException('SelfService2FaLoginHandler', 'Unable to match provided user with LDAP entry - LDAP search failed');
1295 }
1296 $info = $entries;
1297 cleanLDAPResult($info);
1298 if (count($info) === 1) {
1299 $userDN = $info[0]['dn'];
1300 $_SESSION['selfService_clientDN'] = lamEncrypt($userDN, 'SelfService');
1301 return;
1302 }
1303 throw new LAMException('SelfService2FaLoginHandler', 'Multiple or no results for ' . $userName . ' ' . print_r($info, true));
1304 }
1305
1306 }