Debian Codegraph @

lib/modules/freeRadius.inc

raw
1 <?php
2 /*
3
4 This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
5 Copyright (C) 2011 - 2026 Roland Gruber
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program; if not, write to the Free Software
19 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 */
21
22 /**
23 * Manages FreeRadius accounts.
24 *
25 * @package modules
26 * @author Roland Gruber
27 */
28
29 use LAM\TYPES\ConfiguredType;
30
31 /**
32 * Manages FreeRadius accounts.
33 *
34 * @package modules
35 */
36 class freeRadius extends baseModule {
37
38 /**
39 * These attributes will be ignored by default if a new account is copied from an existing one.
40 */
41 private const ATTRIBUTES_TO_IGNORE_ON_COPY = ['radiusFramedIPAddress'];
42
43 /** @var string[]|null $profileCache cache for profile DNs */
44 private ?array $profileCache = null;
45
46
47 /**
48 * Creates a new freeRadius object.
49 *
50 * @param string $scope account type (user, group, host)
51 */
52 public function __construct($scope) {
53 parent::__construct($scope);
54 $this->autoAddObjectClasses = false;
55 }
56
57 /**
58 * {@inheritDoc}
59 */
60 public function can_manage(): bool {
61 return $this->get_scope() === 'user';
62 }
63
64 /**
65 * {@inheritDoc}
66 */
67 public function get_metaData(): array {
68 $return = [];
69 // icon
70 $return['icon'] = 'freeRadius.png';
71 // alias name
72 $return["alias"] = _("FreeRadius");
73 // module dependencies
74 $return['dependencies'] = ['depends' => [['posixAccount', 'inetOrgPerson']], 'conflicts' => []];
75 // managed object classes
76 $return['objectClasses'] = ['radiusprofile'];
77 // managed attributes
78 $return['attributes'] = ['radiusFramedIPAddress', 'radiusFramedIPNetmask', 'radiusRealm', 'radiusGroupName',
79 'radiusExpiration', 'radiusIdleTimeout', 'dialupAccess', 'radiusProfileDn'];
80 // help Entries
81 $return['help'] = [
82 'radiusFramedIPAddress' => [
83 "Headline" => _("IP address"), 'attr' => 'radiusFramedIPAddress',
84 "Text" => _("This is the IP address for the user (e.g. 123.123.123.123).")
85 ],
86 'radiusFramedIPNetmask' => [
87 "Headline" => _("Net mask"), 'attr' => 'radiusFramedIPNetmask',
88 "Text" => _("The net mask for the IP address.")
89 ],
90 'radiusRealm' => [
91 "Headline" => _("Realm"), 'attr' => 'radiusRealm',
92 "Text" => _("The Radius realm of this account.")
93 ],
94 'radiusGroupName' => [
95 "Headline" => _("Group names"), 'attr' => 'radiusGroupName',
96 "Text" => _("The group names for this account.")
97 ],
98 'radiusGroupNameList' => [
99 "Headline" => _("Group names"), 'attr' => 'radiusGroupName',
100 "Text" => _("The group names for this account.") . ' ' . _("Multiple values are separated by semicolon.")
101 ],
102 'radiusExpiration' => [
103 "Headline" => _("Expiration date"), 'attr' => 'radiusExpiration',
104 "Text" => _("The account will be locked after this date.")
105 ],
106 'radiusIdleTimeout' => [
107 "Headline" => _("Idle timeout"), 'attr' => 'radiusIdleTimeout',
108 "Text" => _("Specifies the maximum number of seconds that a connection can be idle before the session is terminated.")
109 ],
110 'dialupAccess' => [
111 "Headline" => _("Enabled"), 'attr' => 'dialupAccess',
112 "Text" => _("Specifies if the user may authenticate with FreeRadius.")
113 ],
114 'profileDN' => [
115 "Headline" => _("Profile DN"), 'attr' => 'radiusProfileDn',
116 "Text" => _('DN where Radius profile templates are stored.')
117 ],
118 'radiusProfileDn' => [
119 "Headline" => _("Profile"), 'attr' => 'radiusProfileDn',
120 "Text" => _('Radius profile for this user.')
121 ],
122 'hiddenOptions' => [
123 "Headline" => _("Hidden options"),
124 "Text" => _("The selected options will not be managed inside LAM. You can use this to reduce the number of displayed input fields.")
125 ],
126 'autoAdd' => [
127 "Headline" => _("Automatically add this extension"),
128 "Text" => _("This will enable the extension automatically if this profile is loaded.")
129 ],
130 ];
131 // profile settings
132 $profileElements = [];
133 // auto add extension
134 $profileElements[] = new htmlResponsiveInputCheckbox('freeRadius_addExt', false, _('Automatically add this extension'), 'autoAdd');
135 if (!$this->isBooleanConfigOptionSet('freeRadius_hideRadiusFramedIPNetmask')) {
136 $profileElements[] = new htmlResponsiveInputField(_('Net mask'), 'freeRadius_radiusFramedIPNetmask', null, 'radiusFramedIPNetmask');
137 $return['profile_checks']['freeRadius_radiusFramedIPNetmask'] = [
138 'type' => 'ext_preg',
139 'regex' => 'ip',
140 'error_message' => $this->messages['radiusFramedIPNetmask'][0]];
141 $return['profile_mappings']['freeRadius_radiusFramedIPNetmask'] = 'radiusFramedIPNetmask';
142 }
143 if (!$this->isBooleanConfigOptionSet('freeRadius_hideRadiusRealm')) {
144 $profileElements[] = new htmlResponsiveInputField(_('Realm'), 'freeRadius_radiusRealm', null, 'radiusRealm');
145 $return['profile_checks']['freeRadius_radiusRealm'] = [
146 'type' => 'ext_preg',
147 'regex' => 'DNSname',
148 'error_message' => $this->messages['radiusRealm'][0]];
149 $return['profile_mappings']['freeRadius_radiusRealm'] = 'radiusRealm';
150 }
151 if (!$this->isBooleanConfigOptionSet('freeRadius_hideRadiusGroupName')) {
152 $profileElements[] = new htmlResponsiveInputField(_('Group names'), 'freeRadius_radiusGroupName', null, 'radiusGroupNameList');
153 }
154 if (!$this->isBooleanConfigOptionSet('freeRadius_hideRadiusIdleTimeout')) {
155 $profileElements[] = new htmlResponsiveInputField(_('Idle timeout'), 'freeRadius_radiusIdleTimeout', null, 'radiusIdleTimeout');
156 $return['profile_checks']['freeRadius_radiusIdleTimeout'] = [
157 'type' => 'ext_preg',
158 'regex' => 'digit',
159 'error_message' => $this->messages['radiusIdleTimeout'][0]];
160 $return['profile_mappings']['freeRadius_radiusIdleTimeout'] = 'radiusIdleTimeout';
161 }
162 if (!$this->isBooleanConfigOptionSet('freeRadius_hideDialupAccess')) {
163 $enabledOptions = ['-' => '', _('Yes') => 'true', _('No') => 'false'];
164 $dialupAccessSelect = new htmlResponsiveSelect('freeRadius_dialupAccess', $enabledOptions, ['true'], _('Enabled'), 'dialupAccess');
165 $dialupAccessSelect->setHasDescriptiveElements(true);
166 $profileElements[] = $dialupAccessSelect;
167 $return['profile_mappings']['freeRadius_dialupAccess'] = 'dialupAccess';
168 }
169 if (!$this->isBooleanConfigOptionSet('freeRadius_hideRadiusProfileDn') && isLoggedIn()) {
170 $profileOptions = ['-' => ''];
171 foreach ($this->getProfiles() as $dn) {
172 $profileOptions[getAbstractDN($dn)] = $dn;
173 }
174 $profileSelect = new htmlResponsiveSelect('freeRadius_radiusProfileDn', $profileOptions, [''], _('Profile'), 'radiusProfileDn');
175 $profileSelect->setHasDescriptiveElements(true);
176 $profileElements[] = $profileSelect;
177 $return['profile_mappings']['freeRadius_radiusProfileDn'] = 'radiusProfileDn';
178 }
179 $profileContainer = new htmlResponsiveRow();
180 for ($i = 0; $i < count($profileElements); $i++) {
181 $profileContainer->add($profileElements[$i]);
182 }
183 $return['profile_options'] = $profileContainer;
184 // upload fields
185 $return['upload_columns'] = [];
186 if (!$this->isBooleanConfigOptionSet('freeRadius_hideRadiusRealm')) {
187 $return['upload_columns'][] = [
188 'name' => 'freeRadius_radiusRealm',
189 'description' => _('Realm'),
190 'help' => 'radiusRealm',
191 'example' => _('company.com')
192 ];
193 }
194 if (!$this->isBooleanConfigOptionSet('freeRadius_hideRadiusGroupName')) {
195 $return['upload_columns'][] = [
196 'name' => 'freeRadius_radiusGroupName',
197 'description' => _('Group names'),
198 'help' => 'radiusGroupNameList',
199 'example' => _('group01;group02')
200 ];
201 }
202 if (!$this->isBooleanConfigOptionSet('freeRadius_hideRadiusFramedIPAddress')) {
203 $return['upload_columns'][] = [
204 'name' => 'freeRadius_radiusFramedIPAddress',
205 'description' => _('IP address'),
206 'help' => 'radiusFramedIPAddress',
207 'example' => '123.123.123.123',
208 ];
209 }
210 if (!$this->isBooleanConfigOptionSet('freeRadius_hideRadiusFramedIPNetmask')) {
211 $return['upload_columns'][] = [
212 'name' => 'freeRadius_radiusFramedIPNetmask',
213 'description' => _('Net mask'),
214 'help' => 'radiusFramedIPNetmask',
215 'example' => '255.255.255.0'
216 ];
217 }
218 if (!$this->isBooleanConfigOptionSet('freeRadius_hideRadiusExpiration')) {
219 $return['upload_columns'][] = [
220 'name' => 'freeRadius_radiusExpiration',
221 'description' => _('Expiration date'),
222 'help' => 'radiusExpiration',
223 'example' => '2035-11-22 00:00'
224 ];
225 }
226 if (!$this->isBooleanConfigOptionSet('freeRadius_hideRadiusIdleTimeout')) {
227 $return['upload_columns'][] = [
228 'name' => 'freeRadius_radiusIdleTimeout',
229 'description' => _('Idle timeout'),
230 'help' => 'radiusIdleTimeout',
231 'example' => '3600'
232 ];
233 }
234 if (!$this->isBooleanConfigOptionSet('freeRadius_hideDialupAccess')) {
235 $return['upload_columns'][] = [
236 'name' => 'freeRadius_dialupAccess',
237 'description' => _('Enabled'),
238 'help' => 'dialupAccess',
239 'example' => 'true',
240 'values' => 'true, false'
241 ];
242 }
243 if (!$this->isBooleanConfigOptionSet('freeRadius_hideRadiusProfileDn')) {
244 $return['upload_columns'][] = [
245 'name' => 'freeRadius_radiusProfileDn',
246 'description' => _('Profile'),
247 'help' => 'radiusProfileDn',
248 'example' => 'cn=profile,ou=radiusProfile,dc=example,dc=com'
249 ];
250 }
251 // available PDF fields
252 $return['PDF_fields'] = [];
253 if (!$this->isBooleanConfigOptionSet('freeRadius_hideRadiusFramedIPAddress')) {
254 $return['PDF_fields']['radiusFramedIPAddress'] = _('IP address');
255 }
256 if (!$this->isBooleanConfigOptionSet('freeRadius_hideRadiusFramedIPNetmask')) {
257 $return['PDF_fields']['radiusFramedIPNetmask'] = _('Net mask');
258 }
259 if (!$this->isBooleanConfigOptionSet('freeRadius_hideRadiusRealm')) {
260 $return['PDF_fields']['radiusRealm'] = _('Realm');
261 }
262 if (!$this->isBooleanConfigOptionSet('freeRadius_hideRadiusGroupName')) {
263 $return['PDF_fields']['radiusGroupName'] = _('Group names');
264 }
265 if (!$this->isBooleanConfigOptionSet('freeRadius_hideRadiusExpiration')) {
266 $return['PDF_fields']['radiusExpiration'] = _('Expiration date');
267 }
268 if (!$this->isBooleanConfigOptionSet('freeRadius_hideRadiusIdleTimeout')) {
269 $return['PDF_fields']['radiusIdleTimeout'] = _('Idle timeout');
270 }
271 if (!$this->isBooleanConfigOptionSet('freeRadius_hideDialupAccess')) {
272 $return['PDF_fields']['dialupAccess'] = _('Enabled');
273 }
274 if (!$this->isBooleanConfigOptionSet('freeRadius_hideRadiusProfileDn')) {
275 $return['PDF_fields']['radiusProfileDn'] = _('Profile');
276 }
277 return $return;
278 }
279
280 /**
281 * {@inheritDoc}
282 */
283 public function get_configOptions(array $scopes, array $allScopes): htmlElement|array {
284 $configContainer = new htmlResponsiveRow();
285 $configContainer->add(new htmlResponsiveInputField(_('Profile DN'), 'freeRadius_profileDN', '', 'profileDN'));
286 $configContainer->addVerticalSpacer('1rem');
287 $hiddenGroup = new htmlGroup();
288 $hiddenGroup->addElement(new htmlOutputText(_('Hidden options')));
289 $hiddenGroup->addElement(new htmlHelpLink('hiddenOptions'));
290 $configContainer->add($hiddenGroup);
291 $configContainer->addVerticalSpacer('0.5rem');
292 $configContainer->add(new htmlResponsiveInputCheckbox('freeRadius_hideRadiusFramedIPAddress', false, _('IP address'), null, true), 12, 4);
293 $configContainer->add(new htmlResponsiveInputCheckbox('freeRadius_hideRadiusFramedIPNetmask', false, _('Net mask'), null, true), 12, 4);
294 $configContainer->add(new htmlResponsiveInputCheckbox('freeRadius_hideRadiusRealm', false, _('Realm'), null, true), 12, 4);
295 $configContainer->add(new htmlResponsiveInputCheckbox('freeRadius_hideRadiusGroupName', false, _('Group names'), null, true), 12, 4);
296 $configContainer->add(new htmlResponsiveInputCheckbox('freeRadius_hideRadiusExpiration', false, _('Expiration date'), null, true), 12, 4);
297 $configContainer->add(new htmlResponsiveInputCheckbox('freeRadius_hideRadiusIdleTimeout', false, _('Idle timeout'), null, true), 12, 4);
298 $configContainer->add(new htmlResponsiveInputCheckbox('freeRadius_hideRadiusProfileDn', false, _('Profile'), null, true), 12, 4);
299 $configContainer->add(new htmlResponsiveInputCheckbox('freeRadius_hideDialupAccess', false, _('Enabled'), null, true), 12, 4);
300 return $configContainer;
301 }
302
303 /**
304 * {@inheritDoc}
305 */
306 protected function load_Messages(): void {
307 $this->messages['radiusFramedIPAddress'][0] = ['ERROR', _('The IP address is invalid.')];
308 $this->messages['radiusFramedIPAddress'][1] = ['ERROR', _('Account %s:') . ' freeRadius_radiusFramedIPAddress', _('The IP address is invalid.')];
309 $this->messages['radiusFramedIPNetmask'][0] = ['ERROR', _('The net mask is invalid.')];
310 $this->messages['radiusFramedIPNetmask'][1] = ['ERROR', _('Account %s:') . ' freeRadius_radiusFramedIPNetmask', _('The net mask is invalid.')];
311 $this->messages['radiusRealm'][0] = ['ERROR', _('Please enter a valid realm.')];
312 $this->messages['radiusRealm'][1] = ['ERROR', _('Account %s:') . ' freeRadius_radiusRealm', _('Please enter a valid realm.')];
313 $this->messages['radiusGroupName'][0] = ['ERROR', _('Please enter a valid list of group names.')];
314 $this->messages['radiusGroupName'][1] = ['ERROR', _('Account %s:') . ' freeRadius_radiusGroupName', _('Please enter a valid list of group names.')];
315 $this->messages['radiusExpiration'][0] = ['ERROR', _('The expiration date must be in format DD.MM.YYYY HH:MM.')];
316 $this->messages['radiusExpiration'][1] = ['ERROR', _('Account %s:') . ' freeRadius_radiusExpiration', _('The expiration date must be in format DD.MM.YYYY HH:MM.')];
317 $this->messages['radiusIdleTimeout'][0] = ['ERROR', _('Please enter a numeric value for the idle timeout.')];
318 $this->messages['radiusIdleTimeout'][1] = ['ERROR', _('Account %s:') . ' freeRadius_radiusIdleTimeout', _('Please enter a numeric value for the idle timeout.')];
319 $this->messages['dialupAccess'][0] = ['ERROR', _('Account %s:') . ' freeRadius_dialupAccess', _('This value can only be "true" or "false".')];
320 $this->messages['radiusProfileDn'][0] = ['ERROR', _('Account %s:') . ' freeRadius_radiusProfileDn', _('This is not a valid DN!')];
321 }
322
323 /**
324 * {@inheritDoc}
325 */
326 public function loadAttributesFromAccountCopy(array $ldapAttributes, array $attributesToIgnore = []): void {
327 parent::loadAttributesFromAccountCopy($ldapAttributes, array_merge(baseModule::ATTRIBUTES_TO_IGNORE_ON_COPY_DEFAULT, self::ATTRIBUTES_TO_IGNORE_ON_COPY));
328 }
329
330 /**
331 * {@inheritDoc}
332 */
333 public function display_html_attributes(): htmlElement|array {
334 $return = new htmlResponsiveRow();
335 if (in_array('radiusprofile', $this->attributes['objectClass'])) {
336 // realm
337 if (!$this->isBooleanConfigOptionSet('freeRadius_hideRadiusRealm')) {
338 $this->addSimpleInputTextField($return, 'radiusRealm', _('Realm'));
339 }
340 // group names
341 if (!$this->isBooleanConfigOptionSet('freeRadius_hideRadiusGroupName')) {
342 $this->addMultiValueInputTextField($return, 'radiusGroupName', _('Group names'));
343 }
344 // IP address
345 if (!$this->isBooleanConfigOptionSet('freeRadius_hideRadiusFramedIPAddress')) {
346 $this->addSimpleInputTextField($return, 'radiusFramedIPAddress', _('IP address'));
347 }
348 // net mask
349 if (!$this->isBooleanConfigOptionSet('freeRadius_hideRadiusFramedIPNetmask')) {
350 $this->addSimpleInputTextField($return, 'radiusFramedIPNetmask', _('Net mask'));
351 }
352 // idle timeout
353 if (!$this->isBooleanConfigOptionSet('freeRadius_hideRadiusIdleTimeout')) {
354 $radiusIdleTimeoutInput = $this->addSimpleInputTextField($return, 'radiusIdleTimeout', _('Idle timeout'));
355 $radiusIdleTimeoutInput->setMinimumAndMaximumNumber();
356 }
357 // expiration date
358 if (!$this->isBooleanConfigOptionSet('freeRadius_hideRadiusExpiration')) {
359 $radiusExpiration = '&nbsp;&nbsp;-';
360 if (isset($this->attributes['radiusExpiration'][0])) {
361 $radiusExpiration = $this->formatExpirationDate($this->attributes['radiusExpiration'][0]);
362 }
363 $return->addLabel(new htmlOutputText('Expiration date'));
364 $radiusExpirationList = new htmlGroup();
365 $radiusExpirationList->addElement(new htmlOutputText($radiusExpiration . ' &nbsp;&nbsp;&nbsp;&nbsp;', false));
366 $radiusExpirationList->addElement(new htmlAccountPageButton(static::class, 'expiration', 'change', _('Change')));
367 $radiusExpirationList->addElement(new htmlHelpLink('radiusExpiration'));
368 $return->addField($radiusExpirationList);
369 }
370 // profile DN
371 if (!$this->isBooleanConfigOptionSet('freeRadius_hideRadiusProfileDn')) {
372 $profiles = ['-' => '-'];
373 foreach ($this->getProfiles() as $dn) {
374 $profiles[getAbstractDN($dn)] = $dn;
375 }
376 $profile = [];
377 if (!empty($this->attributes['radiusProfileDn'][0])) {
378 $profile = $this->attributes['radiusProfileDn'];
379 if (!in_array($this->attributes['radiusProfileDn'][0], $profiles)) {
380 $profiles[getAbstractDN($this->attributes['radiusProfileDn'][0])] = $this->attributes['radiusProfileDn'][0];
381 }
382 }
383 $profileSelect = new htmlResponsiveSelect('radiusProfileDn', $profiles, $profile, _('Profile'), 'radiusProfileDn');
384 $profileSelect->setHasDescriptiveElements(true);
385 $return->add($profileSelect);
386 }
387 // enabled
388 if (!$this->isBooleanConfigOptionSet('freeRadius_hideDialupAccess')) {
389 $enabled = [''];
390 if (!empty($this->attributes['dialupAccess'][0])) {
391 $enabled = [$this->attributes['dialupAccess'][0]];
392 // value in LDAP may be anything other than "false" to count as "true"
393 if (!in_array($this->attributes['dialupAccess'][0], ['true', 'false', 'TRUE', 'FALSE'])) {
394 $enabled = ['true'];
395 }
396 }
397 $enabledOptions = ['-' => '', _('Yes') => 'true', _('No') => 'false'];
398 $enabledSelect = new htmlResponsiveSelect('dialupAccess', $enabledOptions, $enabled, _('Enabled'), 'dialupAccess');
399 $enabledSelect->setHasDescriptiveElements(true);
400 $return->add($enabledSelect);
401 }
402 // button to remove extension
403 $return->addVerticalSpacer('2rem');
404 $remButton = new htmlButton('remObjectClass', _('Remove FreeRadius extension'));
405 $remButton->setCSSClasses(['lam-danger']);
406 $return->add($remButton, 12, 12, 12, 'text-center');
407 }
408 else {
409 $return->add(new htmlButton('addObjectClass', _('Add FreeRadius extension')));
410 }
411 return $return;
412 }
413
414 /**
415 * {@inheritDoc}
416 */
417 public function process_attributes(): array {
418 if (isset($_POST['addObjectClass'])) {
419 $this->attributes['objectClass'][] = 'radiusprofile';
420 return [];
421 }
422 elseif (isset($_POST['remObjectClass'])) {
423 $this->attributes['objectClass'] = array_delete(['radiusprofile'], $this->attributes['objectClass']);
424 for ($i = 0; $i < count($this->meta['attributes']); $i++) {
425 if (isset($this->attributes[$this->meta['attributes'][$i]])) {
426 unset($this->attributes[$this->meta['attributes'][$i]]);
427 }
428 }
429 return [];
430 }
431 // skip processing if extension is not active
432 if (!in_array('radiusprofile', $this->attributes['objectClass'])) {
433 return [];
434 }
435 $errors = [];
436 // IP address
437 if (!$this->isBooleanConfigOptionSet('freeRadius_hideRadiusFramedIPAddress')) {
438 $this->attributes['radiusFramedIPAddress'][0] = $_POST['radiusFramedIPAddress'];
439 if (($_POST['radiusFramedIPAddress'] != '') && !get_preg($_POST['radiusFramedIPAddress'], 'ip')) {
440 $errors[] = $this->messages['radiusFramedIPAddress'][0];
441 }
442 }
443 // net mask
444 if (!$this->isBooleanConfigOptionSet('freeRadius_hideRadiusFramedIPNetmask')) {
445 $this->attributes['radiusFramedIPNetmask'][0] = $_POST['radiusFramedIPNetmask'];
446 if (($_POST['radiusFramedIPNetmask'] != '') && !get_preg($_POST['radiusFramedIPNetmask'], 'ip')) {
447 $errors[] = $this->messages['radiusFramedIPNetmask'][0];
448 }
449 }
450 // realm
451 if (!$this->isBooleanConfigOptionSet('freeRadius_hideRadiusRealm')) {
452 $this->attributes['radiusRealm'][0] = $_POST['radiusRealm'];
453 if (($_POST['radiusRealm'] != '') && !get_preg($_POST['radiusRealm'], 'DNSname')) {
454 $errors[] = $this->messages['radiusRealm'][0];
455 }
456 }
457 // group names
458 if (!$this->isBooleanConfigOptionSet('freeRadius_hideRadiusGroupName')) {
459 $this->processMultiValueInputTextField('radiusGroupName', $errors, 'groupname');
460 }
461 // idle timeout
462 if (!$this->isBooleanConfigOptionSet('freeRadius_hideRadiusIdleTimeout')) {
463 $this->attributes['radiusIdleTimeout'][0] = $_POST['radiusIdleTimeout'];
464 if (($_POST['radiusIdleTimeout'] != '') && !get_preg($_POST['radiusIdleTimeout'], 'digit')) {
465 $errors[] = $this->messages['radiusIdleTimeout'][0];
466 }
467 }
468 // enabled
469 if (!$this->isBooleanConfigOptionSet('freeRadius_hideDialupAccess')) {
470 if (!empty($this->attributes['dialupAccess']) && ($_POST['dialupAccess'] === '')) {
471 unset($this->attributes['dialupAccess']);
472 }
473 elseif ($_POST['dialupAccess'] === 'false') {
474 $this->attributes['dialupAccess'][0] = 'false';
475 }
476 elseif ($_POST['dialupAccess'] === 'true') {
477 $this->attributes['dialupAccess'][0] = 'true';
478 }
479 }
480 // profile DN
481 if (!$this->isBooleanConfigOptionSet('freeRadius_hideRadiusProfileDn')) {
482 if (($_POST['radiusProfileDn'] == '-') && !empty($this->attributes['radiusProfileDn'])) {
483 unset($this->attributes['radiusProfileDn']);
484 }
485 elseif ($_POST['radiusProfileDn'] != '-') {
486 $this->attributes['radiusProfileDn'][0] = $_POST['radiusProfileDn'];
487 }
488 }
489 return $errors;
490 }
491
492 /**
493 * This function will create the meta HTML code to show a page to change the expiration date.
494 *
495 * @return htmlElement meta HTML code
496 */
497 public function display_html_expiration(): htmlElement {
498 $return = new htmlResponsiveRow();
499 $attr = 'radiusExpiration';
500 $date = new DateTime('@' . (time() + 3600 * 24 * 365), getTimeZone());
501 if (!empty($this->attributes[$attr][0])) {
502 $date = DateTime::createFromFormat('d M Y H:i', $this->attributes[$attr][0], new DateTimeZone('UTC'));
503 $date->setTimezone(getTimeZone());
504 }
505 $dateInput = new htmlResponsiveInputField(_('Expiration date'), 'expirationTime', $date->format('Y-m-d H:i'), 'radiusExpiration');
506 $dateInput->showCalendar('Y-m-d H:i', true);
507 $return->add($dateInput);
508
509 $return->addVerticalSpacer('2rem');
510 $buttons = new htmlGroup();
511 $buttons->addElement(new htmlAccountPageButton(static::class, 'attributes', 'change' . $attr, _('Change')));
512 $buttons->addElement(new htmlSpacer('0.5rem', null));
513 if (isset($this->attributes[$attr][0])) {
514 $buttons->addElement(new htmlAccountPageButton(static::class, 'attributes', 'del' . $attr, _('Remove')));
515 $buttons->addElement(new htmlSpacer('0.5rem', null));
516 }
517 $buttons->addElement(new htmlAccountPageButton(static::class, 'attributes', 'back' . $attr, _('Cancel')));
518 $return->add($buttons);
519 return $return;
520 }
521
522 /**
523 * Processes user input of the time selection page.
524 *
525 * @return array<string|string[]>[] list of info/error messages
526 */
527 public function process_expiration(): array {
528 $return = [];
529 // find button name
530 $buttonName = '';
531 $postKeys = array_keys($_POST);
532 for ($i = 0; $i < count($postKeys); $i++) {
533 if (str_contains($postKeys[$i], 'form_subpage_freeRadius_attributes_')) {
534 $buttonName = $postKeys[$i];
535 }
536 }
537 if (($buttonName == '') || (str_contains($buttonName, '_back'))) {
538 return [];
539 }
540 // get attribute name
541 $attr = '';
542 if (str_contains($buttonName, 'radiusExpiration')) {
543 $attr = 'radiusExpiration';
544 }
545 if ($attr === '') {
546 return [];
547 }
548 // determine action
549 if (str_contains($buttonName, '_change')) {
550 // set new expiration date
551 $date = DateTime::createFromFormat('Y-m-d H:i', $_POST['expirationTime'], getTimeZone());
552 $date->setTimezone(new DateTimeZone('UTC'));
553 $this->attributes[$attr][0] = $date->format('d M Y H:i');
554 }
555 elseif (str_contains($buttonName, '_del')) {
556 // remove attribute value
557 unset($this->attributes[$attr]);
558 }
559 return $return;
560 }
561
562 /**
563 * {@inheritDoc}
564 */
565 public function save_attributes(): array {
566 if (!in_array('radiusprofile', $this->attributes['objectClass']) && !in_array('radiusprofile', $this->orig['objectClass'])) {
567 // skip saving if the extension was not added/modified
568 return [];
569 }
570 return parent::save_attributes();
571 }
572
573 /**
574 * {@inheritDoc}
575 */
576 public function build_uploadAccounts(array $rawAccounts, array $ids, array &$partialAccounts, array $selectedModules, ConfiguredType &$type): array {
577 $errors = [];
578 for ($i = 0; $i < count($rawAccounts); $i++) {
579 // add object class
580 if (!in_array("radiusprofile", $partialAccounts[$i]['objectClass'])) {
581 $partialAccounts[$i]['objectClass'][] = "radiusprofile";
582 }
583 // IP address
584 $this->mapSimpleUploadField($rawAccounts, $ids, $partialAccounts, $i, 'freeRadius_radiusFramedIPAddress', 'radiusFramedIPAddress',
585 'ip', $this->messages['radiusFramedIPAddress'][1], $errors);
586 // net mask
587 $this->mapSimpleUploadField($rawAccounts, $ids, $partialAccounts, $i, 'freeRadius_radiusFramedIPNetmask', 'radiusFramedIPNetmask',
588 'ip', $this->messages['radiusFramedIPNetmask'][1], $errors);
589 // realm
590 $this->mapSimpleUploadField($rawAccounts, $ids, $partialAccounts, $i, 'freeRadius_radiusRealm', 'radiusRealm',
591 'DNSname', $this->messages['radiusRealm'][1], $errors);
592 // group names
593 $this->mapSimpleUploadField($rawAccounts, $ids, $partialAccounts, $i, 'freeRadius_radiusGroupName', 'radiusGroupName', 'groupname', $this->messages['radiusGroupName'][1], $errors, '/;[ ]*/');
594 // expiration date
595 if ($rawAccounts[$i][$ids['freeRadius_radiusExpiration']] != "") {
596 $date = DateTime::createFromFormat('Y-m-d H:i', $rawAccounts[$i][$ids['freeRadius_radiusExpiration']], getTimeZone());
597 if ($date !== false) {
598 $date->setTimezone(new DateTimeZone('UTC'));
599 $partialAccounts[$i]['radiusExpiration'] = $date->format('d M Y H:i');
600 }
601 else {
602 $errMsg = $this->messages['radiusExpiration'][1];
603 $errMsg[] = [$i];
604 $errors[] = $errMsg;
605 }
606 }
607 // idle timeout
608 $this->mapSimpleUploadField($rawAccounts, $ids, $partialAccounts, $i, 'freeRadius_radiusIdleTimeout', 'radiusIdleTimeout',
609 'digit', $this->messages['radiusIdleTimeout'][1], $errors);
610 // enabled
611 if (!empty($rawAccounts[$i][$ids['freeRadius_dialupAccess']])) {
612 if (in_array($rawAccounts[$i][$ids['freeRadius_dialupAccess']], ['true', 'false'])) {
613 $partialAccounts[$i]['dialupAccess'] = $rawAccounts[$i][$ids['freeRadius_dialupAccess']];
614 }
615 else {
616 $errMsg = $this->messages['dialupAccess'][0];
617 $errMsg[] = [$i];
618 $errors[] = $errMsg;
619 }
620 }
621 // profile DN
622 $this->mapSimpleUploadField($rawAccounts, $ids, $partialAccounts, $i, 'freeRadius_radiusProfileDn', 'radiusProfileDn', 'dn', $this->messages['radiusProfileDn'][0], $errors);
623 }
624 return $errors;
625 }
626
627 /**
628 * {@inheritDoc}
629 */
630 public function get_pdfEntries(array $pdfKeys, string $typeId): array {
631 $return = [];
632 $this->addSimplePDFField($return, 'radiusFramedIPAddress', _('IP address'));
633 $this->addSimplePDFField($return, 'radiusFramedIPNetmask', _('Net mask'));
634 $this->addSimplePDFField($return, 'radiusRealm', _('Realm'));
635 $this->addSimplePDFField($return, 'radiusGroupName', _('Group names'));
636 $this->addSimplePDFField($return, 'radiusIdleTimeout', _('Idle timeout'));
637 $this->addSimplePDFField($return, 'radiusProfileDn', _('Profile'));
638 if (isset($this->attributes['radiusExpiration'][0])) {
639 $this->addPDFKeyValue($return, 'radiusExpiration', _('Expiration date'), $this->formatExpirationDate($this->attributes['radiusExpiration'][0]));
640 }
641 if (isset($this->attributes['dialupAccess'][0])) {
642 $enabled = _('Yes');
643 if (in_array($this->attributes['dialupAccess'][0], ['false', 'FALSE'])) {
644 $enabled = _('No');
645 }
646 $this->addPDFKeyValue($return, 'dialupAccess', _('Enabled'), $enabled);
647 }
648 return $return;
649 }
650
651 /**
652 * {@inheritDoc}
653 */
654 public function check_profileOptions(array $options, string $typeId): array {
655 $messages = parent::check_profileOptions($options, $typeId);
656 // group names
657 if (!$this->isBooleanConfigOptionSet('freeRadius_hideRadiusGroupName')
658 && isset($options['freeRadius_radiusGroupName'][0])
659 && ($options['freeRadius_radiusGroupName'][0] != '')) {
660 $list = preg_split('/;[ ]*/', $options['freeRadius_radiusGroupName'][0]);
661 for ($i = 0; $i < count($list); $i++) {
662 if (!get_preg($list[$i], 'groupname')) {
663 $messages[] = $this->messages['radiusGroupName'][0];
664 break;
665 }
666 }
667 }
668 return $messages;
669 }
670
671 /**
672 * {@inheritDoc}
673 */
674 public function load_profile(array $profile): void {
675 // profile mappings in meta data
676 parent::load_profile($profile);
677 // add extension
678 if (isset($profile['freeRadius_addExt'][0])
679 && ($profile['freeRadius_addExt'][0] === "true")
680 && !in_array('radiusprofile', $this->attributes['objectClass'])) {
681 $this->attributes['objectClass'][] = 'radiusprofile';
682 }
683 // group names
684 if (!$this->isBooleanConfigOptionSet('freeRadius_hideRadiusGroupName')
685 && isset($profile['freeRadius_radiusGroupName'][0])
686 && ($profile['freeRadius_radiusGroupName'][0] != '')) {
687 $this->attributes['radiusGroupName'] = preg_split('/;[ ]*/', $profile['freeRadius_radiusGroupName'][0]);
688 }
689 }
690
691 /**
692 * Formats the expiration date attribute.
693 *
694 * @param string $date date value
695 * @return string formatted date
696 */
697 private function formatExpirationDate($date): string {
698 if (empty($date)) {
699 return $date;
700 }
701 $dateTime = DateTime::createFromFormat('d M Y H:i', $date, new DateTimeZone('UTC'));
702 $dateTime->setTimezone(getTimeZone());
703 return $dateTime->format('Y-m-d H:i');
704 }
705
706 /**
707 * Returns a list of possible profile DNs.
708 *
709 * @return string[] list of profile DNs
710 */
711 private function getProfiles(): array {
712 if ($this->profileCache !== null) {
713 return $this->profileCache;
714 }
715 if (empty($this->moduleSettings['freeRadius_profileDN'][0])) {
716 return [];
717 }
718 $this->profileCache = [];
719 $list = searchLDAP($this->moduleSettings['freeRadius_profileDN'][0], '(objectClass=radiusProfile)', ['dn']);
720 if (empty($list)) {
721 return [];
722 }
723 foreach ($list as $attr) {
724 $this->profileCache[] = $attr['dn'];
725 }
726 usort($this->profileCache, compareDN(...));
727 return $this->profileCache;
728 }
729
730 /**
731 * {@inheritDoc}
732 */
733 public function getSupportedJobs(LAMConfig $config): array {
734 return [
735 new FreeRadiusAccountExpirationCleanupJob(),
736 new FreeRadiusAccountExpirationNotifyJob()
737 ];
738 }
739
740 /**
741 * @inheritDoc
742 */
743 public function getListAttributeDescriptions(ConfiguredType $type): array {
744 return [
745 'radiusframedipaddress' => _('IP address'),
746 'radiusframedipnetmask' => _('Net mask'),
747 'radiusrealm' => _('Realm'),
748 'radiusgroupname' => _('Group names'),
749 'radiusexpiration' => _('Expiration date'),
750 'radiusidletimeout' => _('Idle timeout'),
751 'dialupaccess' => _('Enabled'),
752 'radiusprofiledn' => _('Profile'),
753 ];
754 }
755
756 }
757
758 if (interface_exists('\LAM\JOB\Job', false)) {
759
760 include_once __DIR__ . '/../passwordExpirationJob.inc';
761
762 /**
763 * Job to delete or move users on account expiration.
764 *
765 * @package jobs
766 */
767 class FreeRadiusAccountExpirationCleanupJob extends \LAM\JOB\AccountExpirationCleanupJob {
768
769 /**
770 * {@inheritDoc}
771 */
772 public function getAlias(): string {
773 return _('FreeRadius') . ': ' . _('Cleanup expired user accounts');
774 }
775
776 /**
777 * {@inheritDoc}
778 */
779 public function getDescription(): string {
780 return _('This job deletes or moves user accounts when they expire.');
781 }
782
783 /**
784 * {@inheritDoc}
785 */
786 protected function findUsers(string $jobID, array $options): array {
787 // read users
788 $attrs = ['radiusExpiration'];
789 return searchLDAPByFilter('(radiusExpiration=*)', $attrs, ['user']);
790 }
791
792 /**
793 * {@inheritDoc}
794 */
795 protected function checkSingleUser(string $jobID, array $options, PDO $pdo, DateTime $now, array $policyOptions, array $user, bool $isDryRun): void {
796 $expireTime = DateTime::createFromFormat('d M Y H:i', $user['radiusexpiration'][0], new DateTimeZone('UTC'));
797 $this->jobResultLog->logDebug("Expiration on " . $expireTime->format('Y-m-d'));
798 $delay = 0;
799 if (!empty($options[$this->getConfigPrefix() . '_delay' . $jobID][0])) {
800 $delay = $options[$this->getConfigPrefix() . '_delay' . $jobID][0];
801 }
802 $actionTime = clone $expireTime;
803 if ($delay != 0) {
804 $actionTime->add(new DateInterval('P' . $delay . 'D'));
805 }
806 $actionTime->setTimeZone(getTimeZone());
807 $this->jobResultLog->logDebug("Action time on " . $actionTime->format('Y-m-d'));
808 if ($actionTime <= $now) {
809 $this->performAction($jobID, $options, $user, $isDryRun);
810 }
811 }
812
813 }
814
815 /**
816 * Job to notify users about account expiration.
817 *
818 * @package jobs
819 */
820 class FreeRadiusAccountExpirationNotifyJob extends \LAM\JOB\PasswordExpirationJob {
821
822 /**
823 * {@inheritDoc}
824 */
825 public function getAlias(): string {
826 return _('FreeRadius') . ': ' . _('Notify users about account expiration');
827 }
828
829 /**
830 * {@inheritDoc}
831 */
832 public function getDescription(): string {
833 return _('This job sends out emails to inform your users that their account will expire soon.');
834 }
835
836 /**
837 * {@inheritDoc}
838 */
839 protected function findUsers(string $jobID, array $options): array {
840 // read users
841 $sysattrs = ['radiusExpiration', $_SESSION['cfgMain']->getMailAttribute()];
842 $attrs = $this->getAttrWildcards($jobID, $options);
843 $attrs = array_values(array_unique(array_merge($attrs, $sysattrs)));
844 return searchLDAPByFilter('(&(radiusExpiration=*)(' . $_SESSION['cfgMain']->getMailAttribute() . '=*))', $attrs, ['user']);
845 }
846
847 /**
848 * {@inheritDoc}
849 */
850 protected function checkSingleUser(string $jobID, array $options, PDO $pdo, DateTime $now, array $policyOptions, array $user, bool $isDryRun): void {
851 $dn = $user['dn'];
852 // get time when account expires
853 $expirationTime = DateTime::createFromFormat('d M Y H:i', $user['radiusexpiration'][0], new DateTimeZone('UTC'));
854 $this->jobResultLog->logDebug("Account expiration on " . $expirationTime->format('Y-m-d'));
855 // skip if account itself is expired
856 if ($expirationTime <= $now) {
857 $this->jobResultLog->logDebug($dn . ' already expired');
858 return;
859 }
860 $numDaysToWarn = $options[$this->getConfigPrefix() . '_mailNotificationPeriod' . $jobID][0];
861 $this->jobResultLog->logDebug("Number of days before warning " . $numDaysToWarn);
862 // calculate time of notification
863 $notifyTime = clone $expirationTime;
864 $notifyTime->sub(new DateInterval('P' . $numDaysToWarn . 'D'));
865 $notifyTime->setTimeZone(getTimeZone());
866 $this->jobResultLog->logDebug("Account expiration notification on " . $notifyTime->format('Y-m-d H:i'));
867 // skip if notification is in the future
868 if ($notifyTime > $now) {
869 $this->jobResultLog->logDebug($dn . ' does not need notification yet.');
870 return;
871 }
872 $dbLastChange = $this->getDBLastPwdChangeTime($jobID, $pdo, $dn);
873 // skip entries where mail was already sent
874 if ($dbLastChange == $user['radiusexpiration'][0]) {
875 $this->jobResultLog->logDebug($dn . ' was already notified.');
876 return;
877 }
878 if ($isDryRun) {
879 // no action for dry run
880 $this->jobResultLog->logInfo('Not sending email to ' . $dn . ' because of dry run.');
881 return;
882 }
883 // send email
884 $success = $this->sendMail($options, $jobID, $user, $expirationTime);
885 // update DB if mail was sent successfully
886 if ($success) {
887 $this->setDBLastPwdChangeTime($jobID, $pdo, $dn, $user['radiusexpiration'][0]);
888 }
889 }
890
891 }
892
893 }