Debian Codegraph @

lib/modules/yubiKeyUser.inc

raw
1 <?php
2
3 use LAM\PDF\PDFTable;
4 use LAM\PDF\PDFTableCell;
5 use LAM\PDF\PDFTableRow;
6 use LAM\TYPES\ConfiguredType;
7
8 /*
9
10 This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
11 Copyright (C) 2018 - 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 * Manages YubiKey keys.
30 *
31 * @package modules
32 * @author Roland Gruber
33 */
34
35 /**
36 * Manages YubiKey keys.
37 *
38 * @package modules
39 */
40 class yubiKeyUser extends baseModule {
41
42 /** session variable for existing keys in self-service */
43 const SESS_KEY_LIST = 'yubiKeyUser_keyList';
44
45 /**
46 * Creates a new yubiKeyUser object.
47 *
48 * @param string $scope account type (user, group, host)
49 */
50 public function __construct($scope) {
51 // call parent constructor
52 parent::__construct($scope);
53 $this->autoAddObjectClasses = false;
54 }
55
56 /**
57 * {@inheritDoc}
58 */
59 public function can_manage(): bool {
60 return $this->get_scope() === 'user';
61 }
62
63 /**
64 * {@inheritDoc}
65 */
66 public function get_metaData(): array {
67 $return = [];
68 // icon
69 $return['icon'] = 'yubikey.png';
70 // alias name
71 $return["alias"] = "YubiKey";
72 // module dependencies
73 $return['dependencies'] = ['depends' => [], 'conflicts' => []];
74 // managed object classes
75 $objectClass = $this->getObjectClassName();
76 if (!empty($objectClass)) {
77 $return['objectClasses'] = [$objectClass];
78 }
79 // managed attributes
80 $attributeName = $this->getAttributeName();
81 $return['attributes'] = [$attributeName];
82 // help Entries
83 $return['help'] = [
84 $attributeName => [
85 "Headline" => _("YubiKey ids"), 'attr' => $attributeName,
86 "Text" => _("The YubiKey id are the first 12 letters of the key output. Simply touch your YubiKey in an empty field to set it.")
87 ],
88 'keyList' => [
89 "Headline" => _("YubiKey ids"), 'attr' => $attributeName,
90 "Text" => _("Please a comma separated list of your YubiKey ids.")
91 ],
92 'objectClass' => [
93 "Headline" => _("Object class"),
94 "Text" => _("Please enter the object class that should be used for YubiKey (e.g. 'yubiKeyUser').")
95 ],
96 'attributeName' => [
97 "Headline" => _("Attribute name"),
98 "Text" => _("Please enter the attribute name that should be used for YubiKey (e.g. 'yubiKeyId').")
99 ],
100 'whereToFind' => [
101 "Headline" => _("YubiKey ids"),
102 "Text" => _("The YubiKey id are the first 12 letters of the key output. Simply touch your YubiKey in an empty field to set it.")
103 ],
104 ];
105 // upload fields
106 $return['upload_columns'] = [
107 [
108 'name' => 'yubiKeyUser_yubiKeyId',
109 'description' => _('YubiKey ids'),
110 'help' => 'keyList',
111 'example' => 'abcd1234, vwyxz12345'
112 ]
113 ];
114 // available PDF fields
115 $return['PDF_fields'] = [
116 'yubiKeyId' => _('YubiKey ids')
117 ];
118 // self-service field settings
119 $return['selfServiceFieldSettings'] = [
120 'yubiKeyId' => _('YubiKey ids'),
121 ];
122 $return['selfServiceReadOnlyFields'] = ['yubiKeyId'];
123 return $return;
124 }
125
126 /**
127 * {@inheritDoc}
128 */
129 protected function load_Messages(): void {
130 $this->messages['yubiKeyId'][0] = ['ERROR', _('Please enter a valid key id.')];
131 $this->messages['yubiKeyId'][1] = ['ERROR', _('Account %s:') . ' yubiKeyUser_yubiKeyId', _('Please enter a valid key id.')];
132 }
133
134 /**
135 * {@inheritDoc}
136 */
137 public function loadAttributesFromAccountCopy(array $ldapAttributes, array $attributesToIgnore = []): void {
138 parent::loadAttributesFromAccountCopy($ldapAttributes, array_merge(baseModule::ATTRIBUTES_TO_IGNORE_ON_COPY_DEFAULT, [$this->getAttributeName()]));
139 }
140
141 /**
142 * {@inheritDoc}
143 */
144 public function display_html_attributes(): htmlElement|array {
145 $return = new htmlResponsiveRow();
146 $objectClass = $this->getObjectClassName();
147 $attributeName = $this->getAttributeName();
148 if (empty($attributeName)) {
149 $message = new htmlStatusMessage('ERROR', _('Invalid configuration detected. Please edit your server profile (module settings) and fill all required fields.'));
150 $return->add($message);
151 return $return;
152 }
153 if (empty($objectClass) || in_array($objectClass, $this->attributes['objectClass'])) {
154 $htmlIds = [];
155 $this->addMultiValueInputTextField($return, $attributeName, _('YubiKey ids'), false, 12, false, null, null, $htmlIds, 'lam-prevent-enter');
156 if (!empty($objectClass)) {
157 $return->addVerticalSpacer('2rem');
158 $remButton = new htmlButton('remObjectClass', _('Remove YubiKey extension'));
159 $remButton->setCSSClasses(['lam-danger']);
160 $return->add($remButton, 12, 12, 12, 'text-center');
161 }
162 }
163 else {
164 $return->add(new htmlButton('addObjectClass', _('Add YubiKey extension')));
165 }
166 return $return;
167 }
168
169 /**
170 * {@inheritDoc}
171 */
172 public function process_attributes(): array {
173 $messages = [];
174 $objectClass = $this->getObjectClassName();
175 $attributeName = $this->getAttributeName();
176 // add extension
177 if (isset($_POST['addObjectClass'])) {
178 $this->attributes['objectClass'][] = $objectClass;
179 return [];
180 }
181 // remove extension
182 elseif (isset($_POST['remObjectClass'])) {
183 $this->attributes['objectClass'] = array_delete([$objectClass], $this->attributes['objectClass']);
184 if (!empty($this->attributes[$attributeName])) {
185 unset($this->attributes[$attributeName]);
186 }
187 return [];
188 }
189 // skip processing if extension is not active
190 if (!empty($objectClass) && !in_array($objectClass, $this->attributes['objectClass'])) {
191 return [];
192 }
193 $this->processMultiValueInputTextField($attributeName, $messages, 'ascii');
194 $this->attributes[$attributeName] = array_values(array_unique($this->attributes[$attributeName]));
195 return $messages;
196 }
197
198 /**
199 * {@inheritDoc}
200 */
201 public function save_attributes(): array {
202 $objectClass = $this->getObjectClassName();
203 if (!empty($objectClass) && !in_array($objectClass, $this->attributes['objectClass']) && !in_array($objectClass, $this->orig['objectClass'])) {
204 // skip saving if the extension was not added/modified
205 return [];
206 }
207 return parent::save_attributes();
208 }
209
210 /**
211 * {@inheritDoc}
212 */
213 public function build_uploadAccounts(array $rawAccounts, array $ids, array &$partialAccounts, array $selectedModules, ConfiguredType &$type): array {
214 $objectClass = $this->getObjectClassName();
215 $attributeName = $this->getAttributeName();
216 $messages = [];
217 for ($i = 0; $i < count($rawAccounts); $i++) {
218 // add object class
219 if (!empty($objectClass) && !in_array($objectClass, $partialAccounts[$i]['objectClass'])) {
220 $partialAccounts[$i]['objectClass'][] = $objectClass;
221 }
222 // add keys
223 $message = $this->messages['yubiKeyId'][1];
224 $this->mapSimpleUploadField($rawAccounts, $ids, $partialAccounts, $i, 'yubiKeyUser_yubiKeyId', $attributeName, 'ascii', $message, $messages, '/,[ ]*/');
225 }
226 return $messages;
227 }
228
229 /**
230 * {@inheritDoc}
231 */
232 public function get_pdfEntries(array $pdfKeys, string $typeId): array {
233 $return = [];
234 $attributeName = $this->getAttributeName();
235 if (!empty($this->attributes[$attributeName])) {
236 $pdfTable = new PDFTable(_('YubiKey ids'));
237 for ($i = 0; $i < count($this->attributes[$attributeName]); $i++) {
238 $pdfRow = new PDFTableRow();
239 $pdfRow->cells[] = new PDFTableCell($this->attributes[$attributeName][$i]);
240 $pdfTable->rows[] = $pdfRow;
241 }
242 $this->addPDFTable($return, 'yubiKeyId', $pdfTable);
243 }
244 return $return;
245 }
246
247 /**
248 * {@inheritDoc}
249 */
250 public function getSelfServiceOptions(array $fields, array $attributes, bool $passwordChangeOnly, array $readOnlyFields): array {
251 $return = [];
252 if ($passwordChangeOnly) {
253 return $return; // no fields as long no LDAP content can be read
254 }
255 $attributes = array_change_key_case($attributes);
256 $objectClass = strtolower($this->getObjectClassName());
257 if (!empty($objectClass) && !in_array_ignore_case($objectClass, $attributes['objectclass'])) {
258 return $return;
259 }
260 if (in_array('yubiKeyId', $fields)) {
261 $attributeName = strtolower($this->getAttributeName());
262 $keyIds = [];
263 if (isset($attributes[$attributeName][0])) {
264 $keyIds = $attributes[$attributeName];
265 }
266 $_SESSION[self::SESS_KEY_LIST] = $keyIds;
267 $row = new htmlResponsiveRow();
268 // JavaScript functions
269 $row->add($this->getSelfServiceKeysJSBlock(), 0);
270 // input fields
271 $keyLabel = new htmlOutputText($this->getSelfServiceLabel('yubiKeyId', _('YubiKey ids')));
272 $row->addLabel($keyLabel);
273 $row->addField(new htmlDiv('yubiKeyIdDiv', $this->getSelfServiceKeys()));
274 $return['yubiKeyId'] = $row;
275 }
276 return $return;
277 }
278
279 /**
280 * Returns the meta HTML code to display the key area.
281 * This also includes the file upload.
282 *
283 * @return htmlResponsiveRow key content
284 */
285 private function getSelfServiceKeys() {
286 $keys = $_SESSION[self::SESS_KEY_LIST];
287 $content = new htmlResponsiveRow();
288 if (count($keys) > 0) {
289 for ($i = 0; $i < count($keys); $i++) {
290 $group = new htmlGroup();
291 $keyInput = new htmlInputField('yubiKeyId_' . $i, $keys[$i]);
292 $keyInput->setFieldMaxLength(12);
293 $keyInput->setCSSClasses(['lam-prevent-enter']);
294 $keyInput->setAccessibilityLabel($this->getSelfServiceLabel('yubiKeyId', _('YubiKey ids')));
295 $group->addElement($keyInput);
296 $delLink = new htmlLink('', '#', '../../graphics/del.svg');
297 $delLink->setTitle(_('Delete'));
298 $delLink->setOnClick('yubiKeyIdDeleteKey(' . $i . ', ' . count($keys) . ');return false;');
299 $delLink->setCSSClasses(['icon']);
300 $group->addElement($delLink);
301 $content->add($group, 12, 12, 12, 'nowrap');
302 }
303 }
304 $addGroup = new htmlGroup();
305 $addLink = new htmlLink(_('Add'), '#', '../../graphics/add.svg');
306 $addLink->setTitle(_('Add'));
307 $addLink->setOnClick('yubiKeyIdAddKey(' . count($keys) . ');return false;');
308 $addLink->setCSSClasses(['icon']);
309 $addGroup->addElement($addLink);
310 $addGroup->addElement(new htmlSpacer('0.5rem', null));
311 $addGroup->addElement(new htmlHelpLink('whereToFind', 'yubiKeyUser'));
312 $content->add($addGroup);
313 return $content;
314 }
315
316 /**
317 * Returns the Java Script functions to manage the keys.
318 *
319 * @return htmlJavaScript JS block
320 */
321 private function getSelfServiceKeysJSBlock() {
322 $content = '
323 function yubiKeyIdDeleteKey(id, count) {
324 var actionJSON = {
325 "action": "deleteKey",
326 "id": id
327 };
328 for (c = 0; c < count; c++) {
329 actionJSON["yubiKeyId_" + c] = document.getElementById(\'yubiKeyId_\' + c).value;
330 }
331 let data = new FormData();
332 data.append("' . getSecurityTokenName() . '", "' . getSecurityTokenValue() . '");
333 data.append("jsonInput", JSON.stringify(actionJSON));
334 fetch(\'../misc/ajax.php?selfservice=1&module=yubiKeyUser&scope=user\', {
335 method: "POST",
336 body: data
337 })
338 .then(async response => {
339 const jsonData = await response.json();
340 yubiKeyIdDeleteKeyHandleReply(jsonData);
341 });
342 }
343
344 function yubiKeyIdDeleteKeyHandleReply(data) {
345 if (data.errorsOccurred == "false") {
346 document.getElementById(\'yubiKeyIdDiv\').innerHTML = data.html;
347 }
348 else {
349 window.lam.dialog.showError(data.errormessage, null, "' . _('Ok') . '");
350 }
351 }
352
353 function yubiKeyIdAddKey(count) {
354 var actionJSON = {
355 "action": "addKey"
356 };
357 for (c = 0; c < count; c++) {
358 actionJSON["yubiKeyId_" + c] = document.getElementById(\'yubiKeyId_\' + c).value;
359 }
360 let data = new FormData();
361 data.append("' . getSecurityTokenName() . '", "' . getSecurityTokenValue() . '");
362 data.append("jsonInput", JSON.stringify(actionJSON));
363 fetch(\'../misc/ajax.php?selfservice=1&module=yubiKeyUser&scope=user\', {
364 method: "POST",
365 body: data
366 })
367 .then(async response => {
368 const jsonData = await response.json();
369 yubiKeyIdAddKeyHandleReply(jsonData);
370 });
371 }
372
373 function yubiKeyIdAddKeyHandleReply(data) {
374 if (data.errorsOccurred == "false") {
375 document.getElementById(\'yubiKeyIdDiv\').innerHTML = data.html;
376 window.lam.html.preventEnter();
377 }
378 else {
379 window.lam.dialog.showError(data.errormessage, null, "' . _('Ok') . '");
380 }
381 }
382
383 ';
384 return new htmlJavaScript($content);
385 }
386
387 /**
388 * {@inheritDoc}
389 */
390 public function checkSelfServiceOptions(array $fields, array $attributes, bool $passwordChangeOnly, array $readOnlyFields): array {
391 $return = ['messages' => [], 'add' => [], 'del' => [], 'mod' => [], 'info' => []];
392 if ($passwordChangeOnly) {
393 return $return; // skip processing if only a password change is done
394 }
395 $attributes = array_change_key_case($attributes);
396 $objectClass = strtolower($this->getObjectClassName());
397 if (!in_array_ignore_case($objectClass, $attributes['objectclass'])) {
398 return $return;
399 }
400 if (in_array('yubiKeyId', $fields)) {
401 $attributeName = strtolower($this->getAttributeName());
402 $newKeys = [];
403 $counter = 0;
404 while (isset($_POST['yubiKeyId_' . $counter])) {
405 $newKeys[] = $_POST['yubiKeyId_' . $counter];
406 $counter++;
407 }
408 $count = count($newKeys);
409 for ($i = 0; $i < $count; $i++) {
410 if (trim($newKeys[$i]) === '') {
411 unset($newKeys[$i]);
412 }
413 elseif (!get_preg($newKeys[$i], 'ascii')) {
414 $return['messages'][] = ['ERROR', _('Please enter a valid key id.'), htmlspecialchars($newKeys[$i])];
415 }
416 }
417 $newKeys = array_values(array_unique($newKeys));
418 $oldKeys = [];
419 if (isset($attributes[$attributeName][0])) {
420 $oldKeys = $attributes[$attributeName];
421 }
422 $update = false;
423 if (count($newKeys) !== count($oldKeys)) {
424 $update = true;
425 }
426 else {
427 for ($i = 0; $i < count($newKeys); $i++) {
428 if (!in_array($newKeys[$i], $oldKeys)) {
429 $update = true;
430 break;
431 }
432 }
433 }
434 if ($update) {
435 if (count($oldKeys) === 0) {
436 $return['add'][$attributeName] = $newKeys;
437 }
438 elseif (count($newKeys) === 0) {
439 $return['del'][$attributeName] = $newKeys;
440 }
441 else {
442 $return['mod'][$attributeName] = $newKeys;
443 }
444 }
445 }
446 return $return;
447 }
448
449 /**
450 * {@inheritDoc}
451 */
452 public function handleAjaxRequest(): void {
453 $jsonInput = json_decode($_POST['jsonInput'], true);
454 $jsonReturn = self::invalidAjaxRequest();
455 if (isset($jsonInput['action'])) {
456 if ($jsonInput['action'] == 'deleteKey') {
457 $jsonReturn = $this->ajaxDeleteSelfServiceKey($jsonInput);
458 }
459 elseif ($jsonInput['action'] == 'addKey') {
460 $_SESSION[self::SESS_KEY_LIST][] = '';
461 ob_start();
462 $contentElement = $this->getSelfServiceKeys();
463 ob_end_clean();
464 ob_start();
465 parseHtml(null, $contentElement, [], true);
466 $content = ob_get_contents();
467 ob_end_clean();
468 $jsonReturn = [
469 'errorsOccurred' => 'false',
470 'html' => $content,
471 ];
472 }
473 }
474 echo json_encode($jsonReturn);
475 }
476
477 /**
478 * Manages the deletion of a key.
479 *
480 * @param array<string, string> $data JSON data
481 * @return array<string, string> result data
482 */
483 private function ajaxDeleteSelfServiceKey(array $data): array {
484 if (!isset($data['id'])) {
485 return self::invalidAjaxRequest();
486 }
487 $index = $data['id'];
488 if (array_key_exists($index, $_SESSION[self::SESS_KEY_LIST])) {
489 unset($_SESSION[self::SESS_KEY_LIST][$index]);
490 $_SESSION[self::SESS_KEY_LIST] = array_values($_SESSION[self::SESS_KEY_LIST]);
491 }
492 ob_start();
493 $contentElement = $this->getSelfServiceKeys();
494 ob_end_clean();
495 ob_start();
496 parseHtml(null, $contentElement, [], true);
497 $content = ob_get_contents();
498 ob_end_clean();
499 return [
500 'errorsOccurred' => 'false',
501 'html' => $content,
502 ];
503 }
504
505 /**
506 * Invalid AJAX request received.
507 *
508 * @return array<string, string> error data
509 */
510 public static function invalidAjaxRequest(): array {
511 $message = _('Invalid request');
512 return ['errorsOccurred' => 'true', 'errormessage' => $message];
513 }
514
515 /**
516 * Returns the object class used for YubiKey.
517 *
518 * @return string|null object class
519 */
520 private function getObjectClassName(): ?string {
521 if (!empty($this->moduleSettings['yubiKeyUser_objectClass'][0])) {
522 return $this->moduleSettings['yubiKeyUser_objectClass'][0];
523 }
524 elseif (!empty($this->selfServiceSettings->moduleSettings['yubiKeyUser_objectClass'][0])) {
525 return $this->selfServiceSettings->moduleSettings['yubiKeyUser_objectClass'][0];
526 }
527 return null;
528 }
529
530 /**
531 * Returns the attribute name used for YubiKey.
532 *
533 * @return string attribute name
534 */
535 private function getAttributeName(): string {
536 if (!empty($this->moduleSettings['yubiKeyUser_attributeName'][0])) {
537 return strtolower($this->moduleSettings['yubiKeyUser_attributeName'][0]);
538 }
539 elseif (!empty($this->selfServiceSettings->moduleSettings['yubiKeyUser_attributeName'][0])) {
540 return strtolower($this->selfServiceSettings->moduleSettings['yubiKeyUser_attributeName'][0]);
541 }
542 return 'yubikeyid';
543 }
544
545 /**
546 * {@inheritDoc}
547 */
548 public function get_configOptions(array $scopes, array $allScopes): htmlElement|array {
549 $configContainer = new htmlResponsiveRow();
550 $configContainer->add(new htmlResponsiveInputField(_('Object class'), 'yubiKeyUser_objectClass', null, 'objectClass'));
551 $configContainer->add(new htmlResponsiveInputField(_('Attribute name'), 'yubiKeyUser_attributeName', 'yubiKeyId', 'attributeName', true));
552 return $configContainer;
553 }
554
555 /**
556 * {@inheritDoc}
557 */
558 public function getSelfServiceSettings(selfServiceProfile $profile): ?htmlElement {
559 $container = new htmlResponsiveRow();
560 $container->add(new htmlResponsiveInputField(_('Object class'), 'yubiKeyUser_objectClass', null, ['objectClass', 'yubiKeyUser']));
561 $container->add(new htmlResponsiveInputField(_('Attribute name'), 'yubiKeyUser_attributeName', 'yubiKeyId', ['attributeName', 'yubiKeyUser']));
562 return $container;
563 }
564
565 }