Debian Codegraph @

templates/misc/ajax.php

raw symbols SCIP
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 $loader = $webauthnManager->createPublicKeyCredentialLoader();
273 if (!$isRegistered) {
274 $registrationObject = $webauthnManager->getRegistrationObject($userDN, $interface);
275 $_SESSION['webauthn_registration'] = $loader->serialize($registrationObject, 'json');
276 echo $loader->serialize(
277 [
278 'action' => 'register',
279 'registration' => $registrationObject
280 ],
281 'json'
282 );
283 }
284 else {
285 $authenticationObject = $webauthnManager->getAuthenticationObject($userDN, $interface);
286 $_SESSION['webauthn_authentication'] = $loader->serialize($authenticationObject, 'json');
287 echo $loader->serialize(
288 [
289 'action' => 'authenticate',
290 'authentication' => $authenticationObject
291 ],
292 'json'
293 );
294 }
295 die();
296 }
297
298 /**
299 * Webauthn device management.
300 */
301 private function manageWebauthnDevices(): void {
302 $action = $_POST['action'];
303 if ($action === 'search') {
304 $searchTerm = $_POST['searchTerm'];
305 if (!empty($searchTerm)) {
306 $this->manageWebauthnDevicesSearch($searchTerm);
307 }
308 }
309 elseif ($action === 'delete') {
310 $dn = $_POST['dn'];
311 $credentialId = $_POST['credentialId'];
312 if (!empty($dn) && !empty($credentialId)) {
313 $this->manageWebauthnDevicesDelete($dn, $credentialId);
314 }
315 }
316 }
317
318 /**
319 * Searches for webauthn devices and prints the results as html.
320 *
321 * @param string $searchTerm search term
322 */
323 private function manageWebauthnDevicesSearch($searchTerm): void {
324 include_once __DIR__ . '/../../lib/webauthn.inc';
325 $webAuthnManager = new WebauthnManager();
326 $database = $webAuthnManager->getDatabase();
327 $results = $database->searchDevices('%' . $searchTerm . '%');
328 $row = new htmlResponsiveRow();
329 $row->addVerticalSpacer('0.5rem');
330 if (empty($results)) {
331 $row->add(new htmlStatusMessage('INFO', _('No devices found.')), 12);
332 }
333 else {
334 $titles = [
335 _('User'),
336 _('Name'),
337 _('Registration'),
338 _('Last use'),
339 _('Delete')
340 ];
341 $data = [];
342 $id = 0;
343 foreach ($results as $result) {
344 $delButton = new htmlButton('deleteDevice' . $id, 'del.svg', true);
345 $delButton->addDataAttribute('credential', $result['credentialId']);
346 $delButton->addDataAttribute('dn', $result['dn']);
347 $delButton->addDataAttribute('dialogtitle', _('Remove device'));
348 $delButton->addDataAttribute('oktext', _('Ok'));
349 $delButton->addDataAttribute('canceltext', _('Cancel'));
350 $delButton->setCSSClasses(['webauthn-delete']);
351 $name = empty($result['name']) ? '' : (string) $result['name'];
352 $data[] = [
353 new htmlOutputText((string) $result['dn']),
354 new htmlOutputText($name),
355 new htmlOutputText(date('Y-m-d H:i:s', $result['registrationTime'])),
356 new htmlOutputText(date('Y-m-d H:i:s', $result['lastUseTime'])),
357 $delButton
358 ];
359 $id++;
360 }
361 $table = new htmlResponsiveTable($titles, $data);
362 $row->add($table, 12);
363 }
364 $row->addVerticalSpacer('2rem');
365 ob_start();
366 $row->generateHTML(null, [], [], false);
367 $content = ob_get_contents();
368 ob_end_clean();
369 echo json_encode(['content' => $content], JSON_THROW_ON_ERROR);
370 }
371
372 /**
373 * Deletes a webauthn device.
374 *
375 * @param string $dn user DN
376 * @param string $credentialId base64 encoded credential id
377 */
378 private function manageWebauthnDevicesDelete($dn, $credentialId): void {
379 include_once __DIR__ . '/../../lib/webauthn.inc';
380 $webAuthnManager = new WebauthnManager();
381 $database = $webAuthnManager->getDatabase();
382 $success = $database->deleteDevice($dn, $credentialId);
383 if ($success) {
384 $message = new htmlStatusMessage('INFO', _('The device was deleted.'));
385 }
386 else {
387 $message = new htmlStatusMessage('ERROR', _('The device was not found.'));
388 }
389 $row = new htmlResponsiveRow();
390 $row->addVerticalSpacer('0.5rem');
391 $row->add($message, 12);
392 $row->addVerticalSpacer('2rem');
393 ob_start();
394 $row->generateHTML(null, [], [], true);
395 $content = ob_get_contents();
396 ob_end_clean();
397 echo json_encode(['content' => $content], JSON_THROW_ON_ERROR);
398 }
399
400 /**
401 * Updates a webauthn device name.
402 *
403 * @param string $dn user DN
404 * @param string $credentialId base64 encoded credential id
405 * @param string $name name
406 */
407 private function manageWebauthnDevicesUpdateName($dn, $credentialId, $name): void {
408 include_once __DIR__ . '/../../lib/webauthn.inc';
409 $webAuthnManager = new WebauthnManager();
410 $database = $webAuthnManager->getDatabase();
411 $success = $database->updateDeviceName($dn, $credentialId, $name);
412 if ($success) {
413 logNewMessage(LOG_DEBUG, 'Changed name of ' . $dn . ' ' . $credentialId . ' to ' . $name);
414 }
415 else {
416 logNewMessage(LOG_ERR, 'Unable to change name of ' . $dn . ' ' . $credentialId . ' to ' . $name);
417 }
418 echo json_encode([]);
419 }
420
421 /**
422 * Manages requests to setup user's own webauthn devices.
423 */
424 private function manageWebauthnOwnDevices(): void {
425 $action = $_POST['action'];
426 $dn = $_POST['dn'];
427 $sessionDn = $_SESSION['ldap']->getUserName();
428 if ($sessionDn !== $dn) {
429 logNewMessage(LOG_ERR, 'WebAuthn delete canceled, DN does not match.');
430 die();
431 }
432 if ($action === 'delete') {
433 $credentialId = $_POST['credentialId'];
434 $this->manageWebauthnDevicesDelete($sessionDn, $credentialId);
435 }
436 elseif ($action === 'setName') {
437 $credentialId = $_POST['credentialId'];
438 $name = $_POST['name'];
439 $this->manageWebauthnDevicesUpdateName($sessionDn, $credentialId, $name);
440 }
441 }
442
443 /**
444 * Handles DN selection fields.
445 *
446 * @return string JSON output
447 */
448 private function dnSelection(): string {
449 $dn = trim((string) $_POST['dn']);
450 $dnList = (empty($dn) || !get_preg($dn, 'dn')) ? $this->getDefaultDns() : $this->getSubDns($dn);
451 $html = $this->buildDnSelectionHtml($dnList, $dn);
452 return json_encode(['dialogData' => $html], JSON_THROW_ON_ERROR);
453 }
454
455 /**
456 * Returns a list of default DNs from account types + tree suffix.
457 *
458 * @return string[] default DNs
459 */
460 private function getDefaultDns() {
461 $typeManager = new TypeManager();
462 $baseDnList = [];
463 foreach ($typeManager->getConfiguredTypes() as $type) {
464 $suffix = $type->getSuffix();
465 if (!empty($suffix)) {
466 $baseDnList[] = $suffix;
467 }
468 }
469 $treeSuffixes = TreeViewTool::getRootDns();
470 foreach ($treeSuffixes as $treeSuffix) {
471 $baseDnList[] = $treeSuffix;
472 }
473 $baseDnList = array_unique($baseDnList);
474 usort($baseDnList, compareDN(...));
475 return $baseDnList;
476 }
477
478 /**
479 * Returns the HTML to build the DN selection list.
480 *
481 * @param string[] $dnList DN list
482 * @param string $currentDn current DN
483 * @return string HTML code
484 */
485 private function buildDnSelectionHtml($dnList, $currentDn): string {
486 $fieldId = trim((string) $_POST['fieldId']);
487 $mainRow = new htmlResponsiveRow();
488 $onclickUp = 'window.lam.html.updateDnSelection(this, \''
489 . htmlspecialchars($fieldId) . '\', \'' . getSecurityTokenName() . '\', \''
490 . getSecurityTokenValue() . '\')';
491 if (!empty($currentDn)) {
492 $row = new htmlResponsiveRow();
493 $row->addDataAttribute('dn', $currentDn);
494 $text = new htmlOutputText($currentDn);
495 $text->setIsBold(true);
496 $row->add($text, 12, 9);
497 $row->setCSSClasses(['text-right']);
498 $buttonId = base64_encode($currentDn);
499 $buttonId = str_replace('=', '', $buttonId);
500 $button = new htmlButton($buttonId, _('Ok'));
501 $button->setOnClick('window.lam.html.selectDn(this, \'' . htmlspecialchars($fieldId) . '\')');
502 $row->add($button, 12, 3, 3, 'text-left');
503 $mainRow->add($row);
504 $mainRow->addVerticalSpacer('1rem');
505 // back up
506 $row = new htmlResponsiveRow();
507 $row->addDataAttribute('dn', extractDNSuffix($currentDn));
508 $text = new htmlLink('..', '#');
509 $text->setCSSClasses(['bold']);
510 $text->setOnClick($onclickUp);
511 $row->add($text, 12, 9);
512 $row->setCSSClasses(['text-right']);
513 $row->add(new htmlSpacer('16px'), 12, 3);
514 $mainRow->add($row);
515 $mainRow->addVerticalSpacer('2rem');
516 }
517 foreach ($dnList as $dn) {
518 $row = new htmlResponsiveRow();
519 $row->addDataAttribute('dn', $dn);
520 $link = new htmlLink($dn, '#');
521 $link->setOnClick($onclickUp);
522 $row->add($link, 12, 9);
523 $row->setCSSClasses(['text-right']);
524 $buttonId = base64_encode($dn);
525 $buttonId = str_replace('=', '', $buttonId);
526 $button = new htmlButton($buttonId, _('Ok'));
527 $button->setOnClick('window.lam.html.selectDn(this, \'' . htmlspecialchars($fieldId) . '\')');
528 $row->add($button, 12, 3, 3, 'text-left');
529 $mainRow->add($row, 12);
530 }
531 ob_start();
532 parseHtml(null, $mainRow, [], false);
533 $out = ob_get_contents();
534 ob_end_clean();
535 if ($out === false) {
536 return '';
537 }
538 return $out;
539 }
540
541 /**
542 * Returns the sub DNs of given DN.
543 *
544 * @param string $dn DN
545 * @return string[] sub DNs
546 */
547 private function getSubDns($dn) {
548 $dnEntries = ldapListDN($dn);
549 $dnList = [];
550 foreach ($dnEntries as $entry) {
551 $dnList[] = $entry['dn'];
552 }
553 usort($dnList, compareDN(...));
554 return $dnList;
555 }
556
557 /**
558 * Checks if the user entered the configuration master password.
559 * Dies if password is not set.
560 */
561 private function enforceUserIsLoggedInToMainConfiguration(): void {
562 $cfg = $_SESSION['cfgMain'] ?? new LAMCfgMain();
563 if (isset($_SESSION["mainconf_password"]) && ($cfg->checkPassword($_SESSION["mainconf_password"]))) {
564 return;
565 }
566 die();
567 }
568
569 /**
570 * Checks if the given password matches the hash value.
571 */
572 private function checkPassword(): void {
573 $hashValue = $_POST['hashValue'];
574 $checkValue = $_POST['checkValue'];
575 $hashPart = preg_replace('/^\\{([A-Z0-9-]+)\\}[!]?/', '', $hashValue);
576 $matches = checkPasswordHash(getHashType($hashValue), $hashPart, $checkValue);
577 $resultRow = new htmlResponsiveRow();
578 if ($matches) {
579 $text = new htmlOutputText(_('Password matches'));
580 $text->setCSSClasses(['text-center', 'display-as-block', 'text-ok']);
581 }
582 else {
583 $text = new htmlOutputText(_('Password does not match'));
584 $text->setCSSClasses(['text-center', 'display-as-block', 'text-error']);
585 }
586 $resultRow->add($text);
587 ob_start();
588 parseHtml(null, $resultRow, [], false);
589 $out = ob_get_contents();
590 ob_end_clean();
591 $result = ['resultHtml' => $out];
592 echo json_encode($result, JSON_THROW_ON_ERROR);
593 }
594
595 /**
596 * Checks if the SMTP settings in main config are valid.
597 */
598 private function testSmtpConnection(): void {
599 $server = $_POST['server'];
600 $user = $_POST['user'];
601 $password = $_POST['password'];
602 $encryption = $_POST['encryption'];
603 $mailFrom = $_POST['mailFrom'];
604 $mailTo = $_POST['mailTo'];
605 if (empty($server)) {
606 $result = ['info' => _('Local SMTP server cannot be tested.')];
607 echo json_encode($result, JSON_THROW_ON_ERROR);
608 return;
609 }
610 try {
611 testSmtpConnection($server, $user, $password, $encryption);
612 $mailOk = sendEMail($mailTo, _('SMTP Test Message'), _('Ok'), $mailFrom, false);
613 if ($mailOk) {
614 $result = ['info' => _('Test email was sent successfully.')];
615 }
616 else {
617 $result = ['error' => _('Connection to SMTP server was successful but email sending failed.')];
618 }
619 echo json_encode($result, JSON_THROW_ON_ERROR);
620 }
621 catch (LAMException $e) {
622 $result = ['error' => _('Unable to connect to SMTP server.'), 'details' => $e->getMessage()];
623 echo json_encode($result, JSON_THROW_ON_ERROR);
624 }
625 }
626
627 /**
628 * Checks if the SMS settings in main config are valid.
629 */
630 private function testSmsConnection(): void {
631 $provider = $_POST['provider'];
632 $apiKey = $_POST['apiKey'];
633 $apiToken = $_POST['apiToken'];
634 $accountId = $_POST['accountId'];
635 $region = $_POST['region'];
636 $from = $_POST['from'];
637 $subject = $_POST['subject'];
638 $number = $_POST['number'];
639 if (empty($provider)) {
640 $result = ['error' => _('Unable to send SMS.')];
641 echo json_encode($result, JSON_THROW_ON_ERROR);
642 return;
643 }
644 try {
645 sendSmsTestMessage($provider, $apiKey, $apiToken, $accountId, $region, $from, $subject, $number);
646 $result = ['info' => _('The test SMS was sent successfully.')];
647 echo json_encode($result, JSON_THROW_ON_ERROR);
648 }
649 catch (LAMException $e) {
650 $result = ['error' => _('Unable to send SMS.'), 'details' => $e->getMessage()];
651 echo json_encode($result, JSON_THROW_ON_ERROR);
652 }
653 }
654
655 }