Debian Codegraph @

templates/misc/ajax.php

raw
1 <?php
2
3 namespace LAM\AJAX;
4
5 use htmlResponsiveTable;
6 use htmlSpacer;
7 use htmlStatusMessage;
8 use \LAM\TOOLS\IMPORT_EXPORT\Importer;
9 use \LAM\TOOLS\IMPORT_EXPORT\Exporter;
10 use LAM\TOOLS\TREEVIEW\TreeView;
11 use LAM\TOOLS\TREEVIEW\TreeViewTool;
12 use \LAM\TYPES\TypeManager;
13 use \htmlResponsiveRow;
14 use \htmlLink;
15 use \htmlOutputText;
16 use \htmlButton;
17 use \LAM\LOGIN\WEBAUTHN\WebauthnManager;
18 use LAM\UPLOAD\Uploader;
19 use LAM\WHITE_PAGES\WhitePagesAjaxHandler;
20 use LAM_INTERFACE;
21 use \LAMCfgMain;
22 use LAMException;
23
24 /*
25
26 This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
27 Copyright (C) 2011 - 2026 Roland Gruber
28
29 This program is free software; you can redistribute it and/or modify
30 it under the terms of the GNU General Public License as published by
31 the Free Software Foundation; either version 2 of the License, or
32 (at your option) any later version.
33
34 This program is distributed in the hope that it will be useful,
35 but WITHOUT ANY WARRANTY; without even the implied warranty of
36 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
37 GNU General Public License for more details.
38
39 You should have received a copy of the GNU General Public License
40 along with this program; if not, write to the Free Software
41 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
42
43 */
44
45 /**
46 * Manages all AJAX requests.
47 *
48 * @author Roland Gruber
49 * @package tools
50 */
51
52 /** security functions */
53 include_once(__DIR__ . "/../../lib/security.inc");
54 /** LDIF import */
55 include_once(__DIR__ . "/../../lib/import.inc");
56 /** schema for tree view */
57 include_once __DIR__ . "/../../lib/schema.inc";
58 /** tree view tool */
59 include_once __DIR__ . "/../../lib/tools.inc";
60 include_once __DIR__ . "/../../lib/tools/treeview.inc";
61
62 // start session
63 if (isset($_GET['selfservice'])) {
64 // self-service uses a different session name
65 session_name('SELFSERVICE');
66 }
67 elseif (isset($_GET['whitepages'])) {
68 // self-service uses a different session name
69 session_name('WHITEPAGES');
70 }
71
72 // return standard JSON response if session expired
73 if (startSecureSession(false, true) === false) {
74 Ajax::setHeader();
75 echo json_encode(['sessionExpired' => "true"]);
76 die();
77 }
78
79 setlanguage();
80
81 $ajax = new Ajax();
82 $ajax->handleRequest();
83
84 /**
85 * Manages all AJAX requests.
86 */
87 class Ajax {
88
89 /**
90 * Manages an AJAX request.
91 */
92 public function handleRequest(): void {
93 static::setHeader();
94 // check token
95 validateSecurityToken();
96 if (isset($_GET['module']) && isset($_GET['scope']) && in_array($_GET['module'], getAvailableModules($_GET['scope']))) {
97 enforceUserIsLoggedIn();
98 if (isset($_GET['useContainer']) && ($_GET['useContainer'] == '1')) {
99 $sessionKey = htmlspecialchars((string) $_GET['editKey']);
100 if (!isset($_SESSION[$sessionKey])) {
101 logNewMessage(LOG_ERR, 'Unable to find account container');
102 die();
103 }
104 $module = $_SESSION[$sessionKey]->getAccountModule($_GET['module']);
105 $module->handleAjaxRequest();
106 }
107 else {
108 $module = new $_GET['module']($_GET['scope']);
109 $module->handleAjaxRequest();
110 }
111 die();
112 }
113 if (!isset($_GET['function'])) {
114 die();
115 }
116 $function = $_GET['function'];
117
118 if (($function === 'passwordStrengthCheck') && isset($_POST['jsonInput'])) {
119 $this->checkPasswordStrength(json_decode((string) $_POST['jsonInput'], true, 512, JSON_THROW_ON_ERROR));
120 die();
121 }
122 if ($function === 'webauthn') {
123 enforceUserIsLoggedIn(false);
124 $interface = LAM_INTERFACE::ADMIN;
125 if (isset($_GET['selfservice'])) {
126 $interface = LAM_INTERFACE::SELF_SERVICE;
127 }
128 elseif (isset($_GET['whitepages'])) {
129 $interface = LAM_INTERFACE::WHITE_PAGES;
130 }
131 $this->manageWebauthn($interface);
132 die();
133 }
134 if ($function === 'webauthnDevices') {
135 $this->enforceUserIsLoggedInToMainConfiguration();
136 $this->manageWebauthnDevices();
137 die();
138 }
139 if ($function === 'testSmtp') {
140 $this->enforceUserIsLoggedInToMainConfiguration();
141 $this->testSmtpConnection();
142 die();
143 }
144 if ($function === 'testSms') {
145 $this->enforceUserIsLoggedInToMainConfiguration();
146 $this->testSmsConnection();
147 die();
148 }
149 if ($function === 'whitePages') {
150 include_once(__DIR__ . "/../../lib/whitePagesData.inc");
151 $wpHandler = new WhitePagesAjaxHandler();
152 $wpHandler->dispatchAjaxRequest();
153 die();
154 }
155 enforceUserIsLoggedIn();
156 if (($function === 'passwordChange') && isset($_POST['jsonInput'])) {
157 $this->managePasswordChange(json_decode((string) $_POST['jsonInput'], true, 512, JSON_THROW_ON_ERROR));
158 }
159 elseif ($function === 'import') {
160 include_once(__DIR__ . '/../../lib/import.inc');
161 $importer = new Importer();
162 ob_start();
163 $jsonOut = $importer->doImport();
164 ob_end_clean();
165 echo $jsonOut;
166 }
167 elseif ($function === 'export') {
168 include_once(__DIR__ . '/../../lib/export.inc');
169 $attributes = (string) $_POST['attributes'];
170 $baseDn = (string) $_POST['baseDn'];
171 $ending = (string) $_POST['ending'];
172 $filter = (string) $_POST['filter'];
173 $format = (string) $_POST['format'];
174 $includeSystem = ($_POST['includeSystem'] === 'true');
175 $saveAsFile = ($_POST['saveAsFile'] === 'true');
176 $searchScope = (string) $_POST['searchScope'];
177 $exporter = new Exporter($baseDn, $searchScope, $filter, $attributes, $includeSystem, $saveAsFile, $format, $ending);
178 ob_start();
179 $jsonOut = $exporter->doExport();
180 ob_end_clean();
181 echo $jsonOut;
182 }
183 elseif ($function === 'upload') {
184 include_once(__DIR__ . '/../../lib/upload.inc');
185 $typeManager = new TypeManager();
186 $type = $typeManager->getConfiguredType($_GET['typeId']);
187 if ($type === null) {
188 logNewMessage(LOG_ERR, 'Unable to load type: ' . $_GET['typeId']);
189 die();
190 }
191 $uploader = new Uploader($type);
192 ob_start();
193 $jsonOut = $uploader->doUpload();
194 ob_end_clean();
195 echo $jsonOut;
196 }
197 elseif ($function === 'dnselection') {
198 ob_start();
199 $jsonOut = $this->dnSelection();
200 ob_end_clean();
201 echo $jsonOut;
202 }
203 elseif ($function === 'webauthnOwnDevices') {
204 $this->manageWebauthnOwnDevices();
205 }
206 elseif ($function === 'treeview') {
207 include_once(__DIR__ . "/../../lib/treeview.inc");
208 $treeView = new TreeView();
209 ob_start();
210 $jsonOut = $treeView->answerAjaxCall();
211 ob_end_clean();
212 echo $jsonOut;
213 }
214 elseif ($function === 'checkPassword') {
215 $this->checkPassword();
216 }
217 }
218
219 /**
220 * Sets JSON HTTP header.
221 */
222 public static function setHeader(): void {
223 if (!headers_sent()) {
224 header('Content-Type: application/json; charset=utf-8');
225 }
226 }
227
228 /**
229 * Manages a password change request on the edit account page.
230 *
231 * @param array<mixed> $input input parameters
232 */
233 private function managePasswordChange(array $input): void {
234 $sessionKey = htmlspecialchars((string) $_GET['editKey']);
235 $return = $_SESSION[$sessionKey]->setNewPassword($input);
236 echo json_encode($return, JSON_THROW_ON_ERROR);
237 }
238
239 /**
240 * Checks if a password is accepted by LAM's password policy.
241 *
242 * @param array<mixed> $input input parameters
243 */
244 private function checkPasswordStrength(array $input): void {
245 $password = $input['password'];
246 $check = checkPasswordStrength($password, [], []);
247 echo json_encode([
248 'result' => $check->isValid(),
249 'message' => $check->getTextMessage(),
250 'issues' => $check->getIssues()
251 ], JSON_THROW_ON_ERROR);
252 }
253
254 /**
255 * Manages webauthn requests.
256 *
257 * @param LAM_INTERFACE $interface interface
258 */
259 private function manageWebauthn(LAM_INTERFACE $interface): void {
260 include_once __DIR__ . '/../../lib/webauthn.inc';
261 if ($interface === LAM_INTERFACE::SELF_SERVICE) {
262 $userDN = lamDecrypt($_SESSION['selfService_clientDN'], 'SelfService');
263 }
264 elseif ($interface === LAM_INTERFACE::WHITE_PAGES) {
265 $userDN = lamDecrypt($_SESSION['whitePages_clientDN'], 'WhitePages');
266 }
267 else {
268 $userDN = $_SESSION['ldap']->getUserName();
269 }
270 $webauthnManager = new WebauthnManager();
271 $isRegistered = $webauthnManager->isRegistered($userDN);
272 if (!$isRegistered) {
273 $registrationObject = $webauthnManager->getRegistrationObject($userDN, $interface);
274 $_SESSION['webauthn_registration'] = json_encode($registrationObject, JSON_THROW_ON_ERROR);
275 echo json_encode(
276 [
277 'action' => 'register',
278 'registration' => $registrationObject
279 ],
280 JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR
281 );
282 }
283 else {
284 $authenticationObject = $webauthnManager->getAuthenticationObject($userDN, $interface);
285 $_SESSION['webauthn_authentication'] = json_encode($authenticationObject, JSON_THROW_ON_ERROR);
286 echo json_encode(
287 [
288 'action' => 'authenticate',
289 'authentication' => $authenticationObject
290 ],
291 JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR
292 );
293 }
294 die();
295 }
296
297 /**
298 * Webauthn device management.
299 */
300 private function manageWebauthnDevices(): void {
301 $action = $_POST['action'];
302 if ($action === 'search') {
303 $searchTerm = $_POST['searchTerm'];
304 if (!empty($searchTerm)) {
305 $this->manageWebauthnDevicesSearch($searchTerm);
306 }
307 }
308 elseif ($action === 'delete') {
309 $dn = $_POST['dn'];
310 $credentialId = $_POST['credentialId'];
311 if (!empty($dn) && !empty($credentialId)) {
312 $this->manageWebauthnDevicesDelete($dn, $credentialId);
313 }
314 }
315 }
316
317 /**
318 * Searches for webauthn devices and prints the results as html.
319 *
320 * @param string $searchTerm search term
321 */
322 private function manageWebauthnDevicesSearch($searchTerm): void {
323 include_once __DIR__ . '/../../lib/webauthn.inc';
324 $webAuthnManager = new WebauthnManager();
325 $database = $webAuthnManager->getDatabase();
326 $results = $database->searchDevices('%' . $searchTerm . '%');
327 $row = new htmlResponsiveRow();
328 $row->addVerticalSpacer('0.5rem');
329 if (empty($results)) {
330 $row->add(new htmlStatusMessage('INFO', _('No devices found.')), 12);
331 }
332 else {
333 $titles = [
334 _('User'),
335 _('Name'),
336 _('Registration'),
337 _('Last use'),
338 _('Delete')
339 ];
340 $data = [];
341 $id = 0;
342 foreach ($results as $result) {
343 $delButton = new htmlButton('deleteDevice' . $id, 'del.svg', true);
344 $delButton->addDataAttribute('credential', $result['credentialId']);
345 $delButton->addDataAttribute('dn', $result['dn']);
346 $delButton->addDataAttribute('dialogtitle', _('Remove device'));
347 $delButton->addDataAttribute('oktext', _('Ok'));
348 $delButton->addDataAttribute('canceltext', _('Cancel'));
349 $delButton->setCSSClasses(['webauthn-delete']);
350 $name = empty($result['name']) ? '' : (string) $result['name'];
351 $data[] = [
352 new htmlOutputText((string) $result['dn']),
353 new htmlOutputText($name),
354 new htmlOutputText(date('Y-m-d H:i:s', $result['registrationTime'])),
355 new htmlOutputText(date('Y-m-d H:i:s', $result['lastUseTime'])),
356 $delButton
357 ];
358 $id++;
359 }
360 $table = new htmlResponsiveTable($titles, $data);
361 $row->add($table, 12);
362 }
363 $row->addVerticalSpacer('2rem');
364 ob_start();
365 $row->generateHTML(null, [], [], false, null);
366 $content = ob_get_contents();
367 ob_end_clean();
368 echo json_encode(['content' => $content], JSON_THROW_ON_ERROR);
369 }
370
371 /**
372 * Deletes a webauthn device.
373 *
374 * @param string $dn user DN
375 * @param string $credentialId base64 encoded credential id
376 */
377 private function manageWebauthnDevicesDelete($dn, $credentialId): void {
378 include_once __DIR__ . '/../../lib/webauthn.inc';
379 $webAuthnManager = new WebauthnManager();
380 $database = $webAuthnManager->getDatabase();
381 $success = $database->deleteDevice($dn, $credentialId);
382 if ($success) {
383 $message = new htmlStatusMessage('INFO', _('The device was deleted.'));
384 }
385 else {
386 $message = new htmlStatusMessage('ERROR', _('The device was not found.'));
387 }
388 $row = new htmlResponsiveRow();
389 $row->addVerticalSpacer('0.5rem');
390 $row->add($message, 12);
391 $row->addVerticalSpacer('2rem');
392 ob_start();
393 $row->generateHTML(null, [], [], true, null);
394 $content = ob_get_contents();
395 ob_end_clean();
396 echo json_encode(['content' => $content], JSON_THROW_ON_ERROR);
397 }
398
399 /**
400 * Updates a webauthn device name.
401 *
402 * @param string $dn user DN
403 * @param string $credentialId base64 encoded credential id
404 * @param string $name name
405 */
406 private function manageWebauthnDevicesUpdateName($dn, $credentialId, $name): void {
407 include_once __DIR__ . '/../../lib/webauthn.inc';
408 $webAuthnManager = new WebauthnManager();
409 $database = $webAuthnManager->getDatabase();
410 $success = $database->updateDeviceName($dn, $credentialId, $name);
411 if ($success) {
412 logNewMessage(LOG_DEBUG, 'Changed name of ' . $dn . ' ' . $credentialId . ' to ' . $name);
413 }
414 else {
415 logNewMessage(LOG_ERR, 'Unable to change name of ' . $dn . ' ' . $credentialId . ' to ' . $name);
416 }
417 echo json_encode([]);
418 }
419
420 /**
421 * Manages requests to setup user's own webauthn devices.
422 */
423 private function manageWebauthnOwnDevices(): void {
424 $action = $_POST['action'];
425 $dn = $_POST['dn'];
426 $sessionDn = $_SESSION['ldap']->getUserName();
427 if ($sessionDn !== $dn) {
428 logNewMessage(LOG_ERR, 'WebAuthn delete canceled, DN does not match.');
429 die();
430 }
431 if ($action === 'delete') {
432 $credentialId = $_POST['credentialId'];
433 $this->manageWebauthnDevicesDelete($sessionDn, $credentialId);
434 }
435 elseif ($action === 'setName') {
436 $credentialId = $_POST['credentialId'];
437 $name = $_POST['name'];
438 $this->manageWebauthnDevicesUpdateName($sessionDn, $credentialId, $name);
439 }
440 }
441
442 /**
443 * Handles DN selection fields.
444 *
445 * @return string JSON output
446 */
447 private function dnSelection(): string {
448 $dn = trim((string) $_POST['dn']);
449 $dnList = (empty($dn) || !get_preg($dn, 'dn')) ? $this->getDefaultDns() : $this->getSubDns($dn);
450 $html = $this->buildDnSelectionHtml($dnList, $dn);
451 return json_encode(['dialogData' => $html], JSON_THROW_ON_ERROR);
452 }
453
454 /**
455 * Returns a list of default DNs from account types + tree suffix.
456 *
457 * @return string[] default DNs
458 */
459 private function getDefaultDns() {
460 $typeManager = new TypeManager();
461 $baseDnList = [];
462 foreach ($typeManager->getConfiguredTypes() as $type) {
463 $suffix = $type->getSuffix();
464 if (!empty($suffix)) {
465 $baseDnList[] = $suffix;
466 }
467 }
468 $treeSuffixes = TreeViewTool::getRootDns();
469 foreach ($treeSuffixes as $treeSuffix) {
470 $baseDnList[] = $treeSuffix;
471 }
472 $baseDnList = array_unique($baseDnList);
473 usort($baseDnList, compareDN(...));
474 return $baseDnList;
475 }
476
477 /**
478 * Returns the HTML to build the DN selection list.
479 *
480 * @param string[] $dnList DN list
481 * @param string $currentDn current DN
482 * @return string HTML code
483 */
484 private function buildDnSelectionHtml($dnList, $currentDn): string {
485 $fieldId = trim((string) $_POST['fieldId']);
486 $mainRow = new htmlResponsiveRow();
487 $onclickUp = 'window.lam.html.updateDnSelection(this, \''
488 . htmlspecialchars($fieldId) . '\', \'' . getSecurityTokenName() . '\', \''
489 . getSecurityTokenValue() . '\')';
490 if (!empty($currentDn)) {
491 $row = new htmlResponsiveRow();
492 $row->addDataAttribute('dn', $currentDn);
493 $text = new htmlOutputText($currentDn);
494 $text->setIsBold(true);
495 $row->add($text, 12, 9);
496 $row->setCSSClasses(['text-right']);
497 $buttonId = base64_encode($currentDn);
498 $buttonId = str_replace('=', '', $buttonId);
499 $button = new htmlButton($buttonId, _('Ok'));
500 $button->setOnClick('window.lam.html.selectDn(this, \'' . htmlspecialchars($fieldId) . '\')');
501 $row->add($button, 12, 3, 3, 'text-left');
502 $mainRow->add($row);
503 $mainRow->addVerticalSpacer('1rem');
504 // back up
505 $row = new htmlResponsiveRow();
506 $row->addDataAttribute('dn', extractDNSuffix($currentDn));
507 $text = new htmlLink('..', '#');
508 $text->setCSSClasses(['bold']);
509 $text->setOnClick($onclickUp);
510 $row->add($text, 12, 9);
511 $row->setCSSClasses(['text-right']);
512 $row->add(new htmlSpacer('16px'), 12, 3);
513 $mainRow->add($row);
514 $mainRow->addVerticalSpacer('2rem');
515 }
516 foreach ($dnList as $dn) {
517 $row = new htmlResponsiveRow();
518 $row->addDataAttribute('dn', $dn);
519 $link = new htmlLink($dn, '#');
520 $link->setOnClick($onclickUp);
521 $row->add($link, 12, 9);
522 $row->setCSSClasses(['text-right']);
523 $buttonId = base64_encode($dn);
524 $buttonId = str_replace('=', '', $buttonId);
525 $button = new htmlButton($buttonId, _('Ok'));
526 $button->setOnClick('window.lam.html.selectDn(this, \'' . htmlspecialchars($fieldId) . '\')');
527 $row->add($button, 12, 3, 3, 'text-left');
528 $mainRow->add($row, 12);
529 }
530 ob_start();
531 parseHtml(null, $mainRow, [], false, 'user');
532 $out = ob_get_contents();
533 ob_end_clean();
534 if ($out === false) {
535 return '';
536 }
537 return $out;
538 }
539
540 /**
541 * Returns the sub DNs of given DN.
542 *
543 * @param string $dn DN
544 * @return string[] sub DNs
545 */
546 private function getSubDns($dn) {
547 $dnEntries = ldapListDN($dn);
548 $dnList = [];
549 foreach ($dnEntries as $entry) {
550 $dnList[] = $entry['dn'];
551 }
552 usort($dnList, compareDN(...));
553 return $dnList;
554 }
555
556 /**
557 * Checks if the user entered the configuration master password.
558 * Dies if password is not set.
559 */
560 private function enforceUserIsLoggedInToMainConfiguration(): void {
561 $cfg = $_SESSION['cfgMain'] ?? new LAMCfgMain();
562 if (isset($_SESSION["mainconf_password"]) && ($cfg->checkPassword($_SESSION["mainconf_password"]))) {
563 return;
564 }
565 die();
566 }
567
568 /**
569 * Checks if the given password matches the hash value.
570 */
571 private function checkPassword(): void {
572 $hashValue = $_POST['hashValue'];
573 $checkValue = $_POST['checkValue'];
574 $hashPart = preg_replace('/^\\{([A-Z0-9-]+)\\}[!]?/', '', $hashValue);
575 $matches = checkPasswordHash(getHashType($hashValue), $hashPart, $checkValue);
576 $resultRow = new htmlResponsiveRow();
577 if ($matches) {
578 $text = new htmlOutputText(_('Password matches'));
579 $text->setCSSClasses(['text-center', 'display-as-block', 'text-ok']);
580 }
581 else {
582 $text = new htmlOutputText(_('Password does not match'));
583 $text->setCSSClasses(['text-center', 'display-as-block', 'text-error']);
584 }
585 $resultRow->add($text);
586 ob_start();
587 parseHtml(null, $resultRow, [], false, 'user');
588 $out = ob_get_contents();
589 ob_end_clean();
590 $result = ['resultHtml' => $out];
591 echo json_encode($result, JSON_THROW_ON_ERROR);
592 }
593
594 /**
595 * Checks if the SMTP settings in main config are valid.
596 */
597 private function testSmtpConnection(): void {
598 $server = $_POST['server'];
599 $user = $_POST['user'];
600 $password = $_POST['password'];
601 $encryption = $_POST['encryption'];
602 $mailFrom = $_POST['mailFrom'];
603 $mailTo = $_POST['mailTo'];
604 if (empty($server)) {
605 $result = ['info' => _('Local SMTP server cannot be tested.')];
606 echo json_encode($result, JSON_THROW_ON_ERROR);
607 return;
608 }
609 try {
610 testSmtpConnection($server, $user, $password, $encryption);
611 $mailOk = sendEMail($mailTo, _('SMTP Test Message'), _('Ok'), $mailFrom, false);
612 if ($mailOk) {
613 $result = ['info' => _('Test email was sent successfully.')];
614 }
615 else {
616 $result = ['error' => _('Connection to SMTP server was successful but email sending failed.')];
617 }
618 echo json_encode($result, JSON_THROW_ON_ERROR);
619 }
620 catch (LAMException $e) {
621 $result = ['error' => _('Unable to connect to SMTP server.'), 'details' => $e->getMessage()];
622 echo json_encode($result, JSON_THROW_ON_ERROR);
623 }
624 }
625
626 /**
627 * Checks if the SMS settings in main config are valid.
628 */
629 private function testSmsConnection(): void {
630 $provider = $_POST['provider'];
631 $apiKey = $_POST['apiKey'];
632 $apiToken = $_POST['apiToken'];
633 $accountId = $_POST['accountId'];
634 $region = $_POST['region'];
635 $from = $_POST['from'];
636 $subject = $_POST['subject'];
637 $number = $_POST['number'];
638 if (empty($provider)) {
639 $result = ['error' => _('Unable to send SMS.')];
640 echo json_encode($result, JSON_THROW_ON_ERROR);
641 return;
642 }
643 try {
644 sendSmsTestMessage($provider, $apiKey, $apiToken, $accountId, $region, $from, $subject, $number);
645 $result = ['info' => _('The test SMS was sent successfully.')];
646 echo json_encode($result, JSON_THROW_ON_ERROR);
647 }
648 catch (LAMException $e) {
649 $result = ['error' => _('Unable to send SMS.'), 'details' => $e->getMessage()];
650 echo json_encode($result, JSON_THROW_ON_ERROR);
651 }
652 }
653
654 }