Debian Codegraph @

lib/2factor.inc

raw
1 <?php
2
3 namespace LAM\LIB\TWO_FACTOR;
4
5 use DateInterval;
6 use DateTime;
7 use Duo\DuoUniversal\Client;
8 use Duo\DuoUniversal\DuoException;
9 use Exception;
10 use Facile\OpenIDClient\Client\ClientBuilder;
11 use Facile\OpenIDClient\Client\ClientInterface;
12 use Facile\OpenIDClient\Client\Metadata\ClientMetadata;
13 use Facile\OpenIDClient\Issuer\IssuerBuilder;
14 use GuzzleHttp\Psr7\ServerRequest;
15 use htmlResponsiveRow;
16 use LAM\LOGIN\WEBAUTHN\WebauthnManager;
17 use LAM\WHITE_PAGES\WhitePagesLoginHandler;
18 use LAM\WHITE_PAGES\WhitePagesProfile;
19 use LAM_INTERFACE;
20 use SelfServiceLoginHandler;
21 use selfServiceProfile;
22 use LAMConfig;
23 use htmlImage;
24 use htmlButton;
25 use htmlJavaScript;
26 use htmlStatusMessage;
27 use htmlOutputText;
28 use htmlDiv;
29 use LAMException;
30 use Webauthn\PublicKeyCredentialCreationOptions;
31
32 /*
33 This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/)
34 Copyright (C) 2017 - 2026 Roland Gruber
35
36 This program is free software; you can redistribute it and/or modify
37 it under the terms of the GNU General Public License as published by
38 the Free Software Foundation; either version 2 of the License, or
39 (at your option) any later version.
40
41 This program is distributed in the hope that it will be useful,
42 but WITHOUT ANY WARRANTY; without even the implied warranty of
43 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
44 GNU General Public License for more details.
45
46 You should have received a copy of the GNU General Public License
47 along with this program; if not, write to the Free Software
48 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
49 */
50
51 /**
52 * 2-factor authentication
53 *
54 * @package two_factor
55 * @author Roland Gruber
56 */
57 interface TwoFactorProvider {
58
59 /**
60 * Returns a list of serial numbers of the user's tokens.
61 *
62 * @param string $user user name
63 * @param string $password password
64 * @return string[] serials
65 * @throws Exception error getting serials
66 */
67 public function getSerials($user, $password);
68
69 /**
70 * Verifies if the provided 2nd factor is valid.
71 *
72 * @param string $user user name
73 * @param string $password password
74 * @param string $serial serial number of token
75 * @param string $twoFactorInput input for 2nd factor
76 * @return bool true if verified and false if verification failed
77 * @throws Exception error during check
78 */
79 public function verify2ndFactor($user, $password, $serial, $twoFactorInput);
80
81 /**
82 * Returns if the service has a custom input form.
83 * In this case the token field is not displayed.
84 *
85 * @return bool has custom input form
86 */
87 public function hasCustomInputForm();
88
89 /**
90 * Adds the custom input fields to the form.
91 *
92 * @param htmlResponsiveRow $row row where to add the input fields
93 * @param string $userDn user DN
94 * @throws LAMException error building custom input
95 */
96 public function addCustomInput(htmlResponsiveRow $row, string $userDn): void;
97
98 /**
99 * Returns if the submit button should be shown.
100 *
101 * @return bool show submit button
102 */
103 public function isShowSubmitButton(): bool;
104
105 /**
106 * Returns if the provider supports to remember the device.
107 *
108 * @return bool device remembering supported
109 */
110 public function supportsToRememberDevice(): bool;
111 }
112
113 /**
114 * Base class for 2-factor authentication providers.
115 *
116 * @author Roland Gruber
117 */
118 abstract class BaseProvider implements TwoFactorProvider {
119
120 protected TwoFactorConfiguration $config;
121
122 /**
123 * {@inheritDoc}
124 * @see TwoFactorProvider::hasCustomInputForm
125 */
126 public function hasCustomInputForm() {
127 return false;
128 }
129
130 /**
131 * {@inheritDoc}
132 */
133 public function addCustomInput(htmlResponsiveRow $row, string $userDn): void {
134 // must be filled by subclass if used
135 }
136
137 /**
138 * Returns the value of the user attribute in LDAP.
139 *
140 * @param string $userDn user DN
141 * @return string|null user name
142 */
143 protected function getLoginAttributeValue($userDn) {
144 $attrName = $this->config->twoFactorAuthenticationSerialAttributeName;
145 $handle = getLDAPServerHandle();
146 $userData = ldapGetDN($userDn, [$attrName], $handle);
147 if (empty($userData[$attrName])) {
148 logNewMessage(LOG_DEBUG, getDefaultLDAPErrorString($handle));
149 return null;
150 }
151 if (is_array($userData[$attrName])) {
152 return $userData[$attrName][0];
153 }
154 return $userData[$attrName];
155 }
156
157 /**
158 * {@inheritDoc}
159 * @see TwoFactorProvider::isShowSubmitButton
160 */
161 public function isShowSubmitButton(): bool {
162 return true;
163 }
164
165 }
166
167 /**
168 * Provider for privacyIDEA.
169 */
170 class PrivacyIDEAProvider extends BaseProvider {
171
172 /**
173 * Constructor.
174 *
175 * @param TwoFactorConfiguration $config configuration
176 */
177 public function __construct(&$config) {
178 $this->config = $config;
179 }
180
181 /**
182 * {@inheritDoc}
183 * @see TwoFactorProvider::getSerials
184 */
185 public function getSerials($user, $password) {
186 logNewMessage(LOG_DEBUG, 'PrivacyIDEAProvider: Getting serials for ' . $user);
187 $loginAttribute = $this->getLoginAttributeValue($user);
188 $token = $this->authenticate($loginAttribute, $password);
189 return $this->getSerialsForUser($loginAttribute, $token);
190 }
191
192 /**
193 * {@inheritDoc}
194 * @see TwoFactorProvider::verify2ndFactor
195 */
196 public function verify2ndFactor($user, $password, $serial, $twoFactorInput) {
197 logNewMessage(LOG_DEBUG, 'PrivacyIDEAProvider: Checking 2nd factor for ' . $user);
198 $loginAttribute = $this->getLoginAttributeValue($user);
199 $token = $this->authenticate($loginAttribute, $password);
200 return $this->verify($token, $serial, $twoFactorInput);
201 }
202
203 /**
204 * Authenticates against the server
205 *
206 * @param string $user user name
207 * @param string $password password
208 * @return string token
209 * @throws Exception error during authentication
210 */
211 private function authenticate($user, $password) {
212 $curl = $this->getCurl();
213 $url = $this->config->twoFactorAuthenticationURL . "/auth";
214 curl_setopt($curl, CURLOPT_URL, $url);
215 $header = ['Accept: application/json'];
216 curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
217 $options = [
218 'username' => $user,
219 'password' => $password,
220 ];
221 curl_setopt($curl, CURLOPT_POSTFIELDS, $options);
222 $json = curl_exec($curl);
223 if (empty($json)) {
224 throw new Exception("Unable to get server response from $url.");
225 }
226 $output = json_decode($json);
227 if (empty($output) || !isset($output->result) || !isset($output->result->status)) {
228 throw new Exception("Unable to get json from $url.");
229 }
230 $status = $output->result->status;
231 if ($status != 1) {
232 $errCode = $output->result->error->code ?? '';
233 $errMessage = $output->result->error->message ?? '';
234 throw new Exception("Unable to login: " . $errCode . ' ' . $errMessage);
235 }
236 if (!isset($output->result->value) || !isset($output->result->value->token)) {
237 throw new Exception("Unable to get token.");
238 }
239 return $output->result->value->token;
240 }
241
242 /**
243 * Returns the curl object.
244 *
245 * @return \CurlHandle curl handle
246 * @throws Exception error during curl creation
247 */
248 private function getCurl() {
249 $curl = curl_init();
250 if ($this->config->twoFactorAuthenticationInsecure) {
251 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
252 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
253 }
254 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
255 return $curl;
256 }
257
258 /**
259 * Returns the serial numbers of the user.
260 *
261 * @param string $user user name
262 * @param string $token login token
263 * @return string[] serials
264 * @throws Exception error during serial reading
265 */
266 private function getSerialsForUser($user, $token): array {
267 $curl = $this->getCurl();
268 $url = $this->config->twoFactorAuthenticationURL . "/token/?user=" . $user;
269 curl_setopt($curl, CURLOPT_URL, $url);
270 $header = ['Authorization: ' . $token, 'Accept: application/json'];
271 curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
272 $json = curl_exec($curl);
273 if (empty($json)) {
274 throw new Exception("Unable to get server response from $url.");
275 }
276 $output = json_decode($json);
277 if (empty($output) || !isset($output->result) || !isset($output->result->status)) {
278 throw new Exception("Unable to get json from $url.");
279 }
280 $status = $output->result->status;
281 if (($status != 1) || !isset($output->result->value) || !isset($output->result->value->tokens)) {
282 $errCode = $output->result->error->code ?? '';
283 $errMessage = $output->result->error->message ?? '';
284 throw new Exception("Unable to get serials: " . $errCode . ' ' . $errMessage);
285 }
286 $serials = [];
287 foreach ($output->result->value->tokens as $tokenEntry) {
288 if (!isset($tokenEntry->active) || ($tokenEntry->active != 1) || !isset($tokenEntry->serial)) {
289 continue;
290 }
291 $serials[] = $tokenEntry->serial;
292 }
293 return $serials;
294 }
295
296 /**
297 * Verifies if the given 2nd factor input is valid.
298 *
299 * @param string $token login token
300 * @param string $serial serial number
301 * @param string $twoFactorInput 2factor pin + password
302 * @return bool is verified
303 */
304 private function verify($token, $serial, $twoFactorInput): bool {
305 $curl = $this->getCurl();
306 $url = $this->config->twoFactorAuthenticationURL . "/validate/check";
307 curl_setopt($curl, CURLOPT_URL, $url);
308 $options = [
309 'pass' => $twoFactorInput,
310 'serial' => $serial,
311 ];
312 curl_setopt($curl, CURLOPT_POSTFIELDS, $options);
313 $header = ['Authorization: ' . $token, 'Accept: application/json'];
314 curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
315 $json = curl_exec($curl);
316 $output = json_decode($json);
317 if (empty($output) || !isset($output->result) || !isset($output->result->status) || !isset($output->result->value)) {
318 throw new Exception("Unable to get json from $url.");
319 }
320 $status = $output->result->status;
321 $value = $output->result->value;
322 if (($status == 'true') && ($value == 'true')) {
323 return true;
324 }
325 logNewMessage(LOG_DEBUG, "Unable to verify token: " . print_r($output, true));
326 return false;
327 }
328
329 /**
330 * @inheritDoc
331 */
332 public function supportsToRememberDevice(): bool {
333 return $this->config->twoFactorAllowToRememberDevice;
334 }
335
336 }
337
338 /**
339 * Authentication via YubiKeys.
340 *
341 * @author Roland Gruber
342 */
343 class YubicoProvider extends BaseProvider {
344
345 /**
346 * Constructor.
347 *
348 * @param TwoFactorConfiguration $config configuration
349 */
350 public function __construct(&$config) {
351 $this->config = $config;
352 }
353
354 /**
355 * {@inheritDoc}
356 * @see TwoFactorProvider::getSerials
357 */
358 public function getSerials($user, $password) {
359 $keyAttributeName = strtolower($this->config->twoFactorAuthenticationSerialAttributeName);
360 if (isset($_SESSION['selfService_clientDN'])) {
361 $loginDn = lamDecrypt($_SESSION['selfService_clientDN'], 'SelfService');
362 }
363 elseif (isset($_SESSION['whitePages_clientDN'])) {
364 $loginDn = lamDecrypt($_SESSION['whitePages_clientDN'], 'WhitePages');
365 }
366 else {
367 $loginDn = $_SESSION['ldap']->getUserName();
368 }
369 $handle = getLDAPServerHandle();
370 $ldapData = ldapGetDN($loginDn, [$keyAttributeName], $handle);
371 if (empty($ldapData[$keyAttributeName])) {
372 return [];
373 }
374 return [implode(', ', $ldapData[$keyAttributeName])];
375 }
376
377 /**
378 * {@inheritDoc}
379 * @see TwoFactorProvider::verify2ndFactor
380 */
381 public function verify2ndFactor($user, $password, $serial, $twoFactorInput) {
382 include_once(__DIR__ . "/3rdParty/yubico/Yubico.php");
383 $serialData = $this->getSerials($user, $password);
384 if (empty($serialData)) {
385 return false;
386 }
387 $serials = explode(', ', $serialData[0]);
388 $serialMatched = false;
389 foreach ($serials as $serial) {
390 if (str_starts_with($twoFactorInput, $serial)) {
391 $serialMatched = true;
392 break;
393 }
394 }
395 if (!$serialMatched) {
396 throw new Exception(_('YubiKey id does not match allowed list of key ids.'));
397 }
398 $urls = $this->config->twoFactorAuthenticationURL;
399 shuffle($urls);
400 $httpsverify = !$this->config->twoFactorAuthenticationInsecure;
401 $clientId = $this->config->twoFactorAuthenticationClientId;
402 $secretKey = $this->config->twoFactorAuthenticationSecretKey;
403 foreach ($urls as $url) {
404 try {
405 $auth = new \Auth_Yubico($clientId, $secretKey, $url, $httpsverify);
406 $auth->verify($twoFactorInput);
407 return true;
408 }
409 catch (LAMException $e) {
410 logNewMessage(LOG_DEBUG, 'Unable to verify 2FA: ' . $e->getMessage());
411 }
412 }
413 return false;
414 }
415
416 /**
417 * @inheritDoc
418 */
419 public function supportsToRememberDevice(): bool {
420 return $this->config->twoFactorAllowToRememberDevice;
421 }
422
423 }
424
425 /**
426 * Provider for DUO.
427 */
428 class DuoProvider extends BaseProvider {
429
430 /**
431 * Constructor.
432 *
433 * @param TwoFactorConfiguration $config configuration
434 */
435 public function __construct(&$config) {
436 $this->config = $config;
437 }
438
439 /**
440 * {@inheritDoc}
441 * @see TwoFactorProvider::getSerials
442 */
443 public function getSerials($user, $password) {
444 return ['DUO'];
445 }
446
447 /**
448 * {@inheritDoc}
449 * @see TwoFactorProvider::isShowSubmitButton
450 */
451 public function isShowSubmitButton(): bool {
452 return false;
453 }
454
455 /**
456 * {@inheritDoc}
457 * @see TwoFactorProvider::hasCustomInputForm
458 */
459 public function hasCustomInputForm() {
460 return true;
461 }
462
463 /**
464 * {@inheritDoc}
465 */
466 public function addCustomInput(htmlResponsiveRow $row, string $userDn): void {
467 $pathPrefix = in_array($this->config->interface, [LAM_INTERFACE::SELF_SERVICE, LAM_INTERFACE::WHITE_PAGES]) ? '../' : '';
468 $row->add(new htmlImage($pathPrefix . '../graphics/duo.png'));
469 if (!empty($_GET['duo_code'])) {
470 // authentication is verified
471 return;
472 }
473 // authentication was not started, provide redirect URL
474 if (empty($_GET['duoRedirect'])) {
475 $jsBlock = '
476 document.addEventListener("DOMContentLoaded", function(event) {
477 var currentLocation = window.location.href;
478 if (currentLocation.includes("?")) {
479 currentLocation = currentLocation.substring(0, currentLocation.indexOf("?"));
480 }
481 if (currentLocation.includes("#")) {
482 currentLocation = currentLocation.substring(0, currentLocation.indexOf("#"));
483 }
484 var targetUrl = currentLocation + "?duoRedirect=" + currentLocation;
485 window.location.href = targetUrl;
486 });
487 ';
488 $row->add(new htmlJavaScript($jsBlock));
489 }
490 // start authentication
491 else {
492 include_once __DIR__ . '/3rdParty/composer/autoload.php';
493 try {
494 $duoClient = new Client(
495 $this->config->twoFactorAuthenticationClientId,
496 $this->config->twoFactorAuthenticationSecretKey,
497 $this->config->twoFactorAuthenticationURL,
498 $_GET['duoRedirect']
499 );
500 $duoClient->healthCheck();
501 $state = $duoClient->generateState();
502 $_SESSION['duo_state'] = $state;
503 $_SESSION['duo_redirect'] = $_GET['duoRedirect'];
504 $loginAttribute = $this->getLoginAttributeValue($userDn);
505 $redirectUrl = $duoClient->createAuthUrl($loginAttribute, $state);
506 $jsBlock = '
507 document.addEventListener("DOMContentLoaded", function(event) {
508 window.location.href = "' . $redirectUrl . '";
509 });
510 ';
511 $row->add(new htmlJavaScript($jsBlock));
512 }
513 catch (DuoException $e) {
514 $row->add(new htmlStatusMessage('ERROR', _('Duo connection failed'), $e->getMessage()));
515 }
516 }
517 }
518
519 /**
520 * {@inheritDoc}
521 * @see TwoFactorProvider::verify2ndFactor
522 */
523 public function verify2ndFactor($user, $password, $serial, $twoFactorInput) {
524 logNewMessage(LOG_DEBUG, 'DuoProvider: Checking 2nd factor for ' . $user);
525 $loginAttribute = $this->getLoginAttributeValue($user);
526 $state = $_GET['state'];
527 $code = $_GET['duo_code'];
528 if ($state !== $_SESSION['duo_state']) {
529 logNewMessage(LOG_ERR, 'DUO state does not match');
530 return false;
531 }
532 include_once __DIR__ . '/3rdParty/composer/autoload.php';
533 try {
534 $duoClient = new Client(
535 $this->config->twoFactorAuthenticationClientId,
536 $this->config->twoFactorAuthenticationSecretKey,
537 $this->config->twoFactorAuthenticationURL,
538 $_SESSION['duo_redirect']
539 );
540 $duoResult = $duoClient->exchangeAuthorizationCodeFor2FAResult($code, $loginAttribute);
541 logNewMessage(LOG_DEBUG, print_r($duoResult, true));
542 return true;
543 }
544 catch (DuoException $e) {
545 logNewMessage(LOG_ERR, 'DUO error: ' . $e->getMessage());
546 return false;
547 }
548 }
549
550 /**
551 * @inheritDoc
552 */
553 public function supportsToRememberDevice(): bool {
554 return false;
555 }
556
557 }
558
559 /**
560 * Provider for Okta.
561 */
562 class OktaProvider extends BaseProvider {
563
564 private bool $verificationFailed = false;
565
566 /**
567 * Constructor.
568 *
569 * @param TwoFactorConfiguration $config configuration
570 */
571 public function __construct(&$config) {
572 $this->config = $config;
573 if (empty($this->config->twoFactorAuthenticationSerialAttributeName)) {
574 $this->config->twoFactorAuthenticationSerialAttributeName = 'mail';
575 }
576 }
577
578 /**
579 * {@inheritDoc}
580 * @see TwoFactorProvider::getSerials
581 */
582 public function getSerials($user, $password) {
583 return ['OKTA'];
584 }
585
586 /**
587 * {@inheritDoc}
588 * @see TwoFactorProvider::isShowSubmitButton
589 */
590 public function isShowSubmitButton(): bool {
591 return false;
592 }
593
594 /**
595 * {@inheritDoc}
596 * @see TwoFactorProvider::hasCustomInputForm
597 */
598 public function hasCustomInputForm() {
599 return true;
600 }
601
602 /**
603 * {@inheritDoc}
604 */
605 public function addCustomInput(htmlResponsiveRow $row, string $userDn): void {
606 if (($this->config->loginHandler === null) || !$this->config->loginHandler->managesAuthentication()) {
607 $loginAttribute = $this->getLoginAttributeValue($userDn);
608 if (empty($loginAttribute)) {
609 throw new LAMException('Unable to read login attribute from ' . $userDn);
610 }
611 }
612 if ($this->verificationFailed) {
613 return;
614 }
615
616 $pathPrefix = in_array($this->config->interface, [LAM_INTERFACE::SELF_SERVICE, LAM_INTERFACE::WHITE_PAGES]) ? '../' : '';
617 $row->add(new htmlImage($pathPrefix . '../graphics/okta.png'));
618 $_SESSION['okta_state'] = bin2hex(random_bytes(10));
619 $_SESSION['okta_code_verifier'] = bin2hex(random_bytes(50));
620 $hash = hash('sha256', $_SESSION['okta_code_verifier'], true);
621 $codeChallenge = rtrim(strtr(base64_encode($hash), '+/', '-_'), '=');
622 $jsBlock = '
623 document.addEventListener("DOMContentLoaded", function(event) {
624 if (window.location.href.indexOf("code=") < 0) {
625 var currentLocation = window.location.href;
626 if (currentLocation.includes("#")) {
627 currentLocation = currentLocation.substring(0, currentLocation.indexOf("#"));
628 }
629 window.location.href = "' . $this->config->twoFactorAuthenticationURL
630 . '/oauth2/default/v1/authorize?code_challenge_method=S256&response_type=code&scope=openid email profile&client_id='
631 . $this->config->twoFactorAuthenticationClientId
632 . '&code_challenge=' . $codeChallenge
633 . '&state=' . $_SESSION['okta_state']
634 . '&redirect_uri=" + currentLocation
635 }
636 });
637 ';
638 $row->add(new htmlJavaScript($jsBlock));
639 }
640
641 /**
642 * {@inheritDoc}
643 * @see TwoFactorProvider::verify2ndFactor
644 */
645 public function verify2ndFactor($user, $password, $serial, $twoFactorInput) {
646 $this->verificationFailed = true;
647 logNewMessage(LOG_DEBUG, 'OktaProvider: Checking 2nd factor for ' . $user);
648 if (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['okta_state'])) {
649 logNewMessage(LOG_ERR, 'Okta state does not match.');
650 return false;
651 }
652 if (!empty($_GET['error'])) {
653 logNewMessage(LOG_ERR, 'Okta reported an error: ' . $_GET['error']);
654 return false;
655 }
656 $code = $_GET['code'];
657 if (empty($code)) {
658 logNewMessage(LOG_DEBUG, 'No code provided for 2FA verification.');
659 return false;
660 }
661 $accessCode = $this->getAccessCode($code);
662 if (empty($accessCode)) {
663 logNewMessage(LOG_DEBUG, 'No access code readable for Okta 2FA verification.');
664 return false;
665 }
666 try {
667 $claims = json_decode(base64_decode(explode('.', $accessCode)[1]), true);
668 logNewMessage(LOG_DEBUG, 'Okta claims: ' . print_r($claims, true));
669 $oktaUser = $claims['sub'];
670 if (($this->config->loginHandler !== null) && $this->config->loginHandler->managesAuthentication()) {
671 $this->config->loginHandler->authorize2FaUser($oktaUser);
672 }
673 else {
674 $loginAttribute = $this->getLoginAttributeValue($user);
675 if ($loginAttribute !== $oktaUser) {
676 logNewMessage(LOG_ERR, 'User name ' . $loginAttribute . ' does not match claim sub: ' . $oktaUser);
677 return false;
678 }
679 }
680 $this->verificationFailed = false;
681 return true;
682 }
683 catch (Exception $e) {
684 logNewMessage(LOG_ERR, 'Unable to validate access code - ' . $e->getMessage());
685 }
686 return false;
687 }
688
689 /**
690 * Reads the access code using code.
691 *
692 * @param string $code code parameter from request
693 * @return string|null access token
694 */
695 private function getAccessCode($code) {
696 $curl = curl_init();
697 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
698 $url = $this->config->twoFactorAuthenticationURL . '/oauth2/default/v1/token';
699 curl_setopt($curl, CURLOPT_URL, $url);
700 curl_setopt($curl, CURLOPT_POST, true);
701 $callingUrl = getCallingURL();
702 $callingUrl = substr($callingUrl, 0, strpos($callingUrl, '?'));
703 logNewMessage(LOG_DEBUG, 'Get Okta access code.');
704 curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query([
705 'grant_type' => 'authorization_code',
706 'code' => $code,
707 'code_verifier' => $_SESSION['okta_code_verifier'],
708 'redirect_uri' => $callingUrl,
709 'client_id' => $this->config->twoFactorAuthenticationClientId,
710 'client_secret' => $this->config->twoFactorAuthenticationSecretKey
711 ]));
712 curl_setopt($curl, CURLOPT_HTTPHEADER, [
713 'accept: application/json',
714 'content-type: application/x-www-form-urlencoded',
715 ]);
716 $results = curl_exec($curl);
717 $returnCode = curl_errno($curl);
718 logNewMessage(LOG_DEBUG, 'Okta responded with ' . $returnCode . ': ' . $results);
719 if ($returnCode !== 0) {
720 logNewMessage(LOG_ERR, 'Error calling Okta ' . $url
721 . '. ' . $returnCode);
722 return null;
723 }
724 $jsonData = json_decode($results, true);
725 if (empty($jsonData['access_token'])) {
726 return null;
727 }
728 return $jsonData['access_token'];
729 }
730
731 /**
732 * @inheritDoc
733 */
734 public function supportsToRememberDevice(): bool {
735 return false;
736 }
737
738 }
739
740 /**
741 * Provider for OpenId.
742 */
743 class OpenIdProvider extends BaseProvider {
744
745 private bool $verificationFailed = false;
746
747 /**
748 * Constructor.
749 *
750 * @param TwoFactorConfiguration $config configuration
751 */
752 public function __construct(&$config) {
753 $this->config = $config;
754 if (empty($this->config->twoFactorAuthenticationSerialAttributeName)) {
755 $this->config->twoFactorAuthenticationSerialAttributeName = 'uid';
756 }
757 }
758
759 /**
760 * {@inheritDoc}
761 * @see TwoFactorProvider::getSerials
762 */
763 public function getSerials($user, $password) {
764 return ['OpenID'];
765 }
766
767 /**
768 * {@inheritDoc}
769 * @see TwoFactorProvider::isShowSubmitButton
770 */
771 public function isShowSubmitButton(): bool {
772 return false;
773 }
774
775 /**
776 * {@inheritDoc}
777 * @see TwoFactorProvider::hasCustomInputForm
778 */
779 public function hasCustomInputForm() {
780 return true;
781 }
782
783 /**
784 * {@inheritDoc}
785 */
786 public function addCustomInput(htmlResponsiveRow $row, string $userDn): void {
787 $loginAttribute = '';
788 if (($this->config->loginHandler === null) || !$this->config->loginHandler->managesAuthentication()) {
789 $loginAttribute = $this->getLoginAttributeValue($userDn);
790 if (empty($loginAttribute)) {
791 throw new LAMException('Unable to read login attribute from ' . $userDn);
792 }
793 }
794 if ($this->verificationFailed) {
795 return;
796 }
797 $content = new htmlResponsiveRow();
798 $pathPrefix = ($this->config->interface === LAM_INTERFACE::SELF_SERVICE) ? '../' : '';
799 $row->add(new htmlImage($pathPrefix . '../graphics/openid.png'));
800 include_once __DIR__ . '/3rdParty/composer/autoload.php';
801 try {
802 $client = $this->getOpenIdClient();
803 $authorizationService = $this->getAuthorizationService();
804 $redirectAuthorizationUri = $authorizationService->getAuthorizationUri(
805 $client,
806 ['login_hint' => $loginAttribute]
807 );
808 $jsBlock = '
809 document.addEventListener("DOMContentLoaded", function(event) {
810 var currentLocation = window.location.href;
811 if (currentLocation.includes("?")) {
812 currentLocation = currentLocation.substring(0, currentLocation.indexOf("?"));
813 }
814 if (currentLocation.includes("#")) {
815 currentLocation = currentLocation.substring(0, currentLocation.indexOf("#"));
816 }
817 if (window.location.href.indexOf("code=") > 0) {
818 var targetUrl = window.location.href + "&redirect_uri=" + currentLocation;
819 window.location.href = targetUrl;
820 }
821 else {
822 window.location.href = "' . $redirectAuthorizationUri . '&redirect_uri=" + currentLocation
823 }
824 });
825 ';
826 $content->add(new htmlJavaScript($jsBlock));
827 }
828 catch (Exception $e) {
829 $content->add(new htmlStatusMessage('ERROR', _('OpenID connection failed'), $e->getMessage()));
830 }
831 $row->add($content);
832 }
833
834 /**
835 * Returns the client object.
836 *
837 * @return ClientInterface client
838 */
839 private function getOpenIdClient(): ClientInterface {
840 $issuer = (new IssuerBuilder())->build($this->config->twoFactorAuthenticationURL . '/.well-known/openid-configuration');
841 $meta = [
842 'client_id' => $this->config->twoFactorAuthenticationClientId,
843 'client_secret' => $this->config->twoFactorAuthenticationSecretKey,
844 'token_endpoint_auth_method' => 'client_secret_basic',
845 ];
846 if (!empty($_GET['redirect_uri'])) {
847 $meta['redirect_uri'] = $_GET['redirect_uri'];
848 }
849 $clientMetadata = ClientMetadata::fromArray($meta);
850 return (new ClientBuilder())
851 ->setIssuer($issuer)
852 ->setClientMetadata($clientMetadata)
853 ->build();
854 }
855
856 /**
857 * Returns the authorization service.
858 *
859 * @return \Facile\OpenIDClient\Service\AuthorizationService service
860 */
861 private function getAuthorizationService(): \Facile\OpenIDClient\Service\AuthorizationService {
862 return (new \Facile\OpenIDClient\Service\Builder\AuthorizationServiceBuilder())->build();
863 }
864
865 /**
866 * {@inheritDoc}
867 * @see TwoFactorProvider::verify2ndFactor
868 */
869 public function verify2ndFactor($user, $password, $serial, $twoFactorInput) {
870 $this->verificationFailed = true;
871 logNewMessage(LOG_DEBUG, 'OpenIdProvider: Checking 2nd factor for ' . $user);
872 $code = $_GET['code'];
873 if (empty($code)) {
874 logNewMessage(LOG_DEBUG, 'No code provided for 2FA verification.');
875 return false;
876 }
877 include_once __DIR__ . '/3rdParty/composer/autoload.php';
878 $client = $this->getOpenIdClient();
879 $authorizationService = $this->getAuthorizationService();
880 $serverRequest = ServerRequest::fromGlobals();
881 try {
882 $callbackParams = $authorizationService->getCallbackParams($serverRequest, $client);
883 $tokenSet = $authorizationService->callback($client, $callbackParams, $_GET['redirect_uri']);
884 $claims = $tokenSet->claims();
885 logNewMessage(LOG_DEBUG, print_r($claims, true));
886 $openIdUser = $claims['preferred_username'];
887 if (($this->config->loginHandler !== null) && $this->config->loginHandler->managesAuthentication()) {
888 $this->config->loginHandler->authorize2FaUser($openIdUser);
889 }
890 else {
891 $loginAttribute = $this->getLoginAttributeValue($user);
892 if ($loginAttribute !== $openIdUser) {
893 logNewMessage(LOG_ERR, 'User name ' . $loginAttribute . ' does not match claim preferred_username: ' . $openIdUser);
894 return false;
895 }
896 }
897 $this->verificationFailed = false;
898 return true;
899 }
900 catch (Exception $e) {
901 logNewMessage(LOG_ERR, 'Unable to validate JWT - ' . $e->getMessage());
902 }
903 return false;
904 }
905
906 /**
907 * @inheritDoc
908 */
909 public function supportsToRememberDevice(): bool {
910 return false;
911 }
912
913 }
914
915 /**
916 * Provider for Webauthn.
917 */
918 class WebauthnProvider extends BaseProvider {
919
920 /**
921 * Constructor.
922 *
923 * @param TwoFactorConfiguration $config configuration
924 */
925 public function __construct($config) {
926 $this->config = $config;
927 }
928
929 /**
930 * {@inheritDoc}
931 * @see TwoFactorProvider::getSerials
932 */
933 public function getSerials($user, $password) {
934 return ['WEBAUTHN'];
935 }
936
937 /**
938 * {@inheritDoc}
939 * @see TwoFactorProvider::isShowSubmitButton
940 */
941 public function isShowSubmitButton(): bool {
942 return false;
943 }
944
945 /**
946 * {@inheritDoc}
947 * @see TwoFactorProvider::hasCustomInputForm
948 */
949 public function hasCustomInputForm() {
950 return true;
951 }
952
953 /**
954 * {@inheritDoc}
955 */
956 public function addCustomInput(htmlResponsiveRow $row, string $userDn): void {
957 if (!extension_loaded('PDO')) {
958 $row->add(new htmlStatusMessage('ERROR', 'WebAuthn requires the PDO extension for PHP.'));
959 return;
960 }
961 $pdoDrivers = \PDO::getAvailableDrivers();
962 if (!in_array('sqlite', $pdoDrivers)) {
963 $row->add(new htmlStatusMessage('ERROR', 'WebAuthn requires the sqlite PDO driver for PHP.'));
964 return;
965 }
966 include_once __DIR__ . '/webauthn.inc';
967 $webauthnManager = $this->getWebauthnManager();
968 $hasTokens = $webauthnManager->isRegistered($userDn);
969 if ($hasTokens) {
970 $row->add(new htmlStatusMessage('INFO', _('Please authenticate with your security device.')));
971 }
972 else {
973 $row->add(new htmlStatusMessage('INFO', _('Please register a security device.')));
974 }
975 $row->addVerticalSpacer('2rem');
976 $pathPrefix = in_array($this->config->interface, [LAM_INTERFACE::SELF_SERVICE, LAM_INTERFACE::WHITE_PAGES]) ? '../' : '';
977 $interfaceTypeParam = '';
978 if ($this->config->interface === LAM_INTERFACE::SELF_SERVICE) {
979 $interfaceTypeParam = 'selfservice=true';
980 }
981 elseif ($this->config->interface === LAM_INTERFACE::WHITE_PAGES) {
982 $interfaceTypeParam = 'whitepages=true';
983 }
984 $row->add(new htmlImage($pathPrefix . '../graphics/webauthn.svg', '50%'));
985 $row->addVerticalSpacer('1rem');
986 $errorMessage = new htmlStatusMessage('ERROR', '', _('This service requires a browser with "WebAuthn" support.'));
987 $row->add(new htmlDiv(null, $errorMessage, ['hidden webauthn-error']));
988 if (($this->config->twoFactorAuthenticationOptional === true) && !$hasTokens) {
989 $registerButton = new htmlButton('register_webauthn', _('Register new key'));
990 $registerButton->setType('button');
991 $registerButton->setCSSClasses(['fullwidth']);
992 $row->add($registerButton);
993 $skipButton = new htmlButton('skip_webauthn', _('Skip'));
994 $skipButton->setCSSClasses(['fullwidth']);
995 $row->add($skipButton);
996 }
997 $errorMessageDiv = new htmlDiv('generic-webauthn-error', new htmlOutputText(''));
998 $errorMessageDiv->addDataAttribute('button', _('Ok'));
999 $errorMessageDiv->addDataAttribute('title', _('WebAuthn failed'));
1000 $row->add($errorMessageDiv);
1001 $row->add(new htmlJavaScript('window.lam.webauthn.start(\'' . $pathPrefix . '\', \'' . $interfaceTypeParam . '\',' .
1002 ' \'' . _('Do you want to set a name for this device?') . '\', \'' . _('Name') . '\',' .
1003 ' \'' . _('Ok') . '\', \'' . _('Cancel') . '\');'), 0);
1004 }
1005
1006 /**
1007 * Returns the webauthn manager.
1008 *
1009 * @return WebauthnManager manager
1010 */
1011 public function getWebauthnManager() {
1012 return new WebauthnManager();
1013 }
1014
1015 /**
1016 * {@inheritDoc}
1017 * @see TwoFactorProvider::verify2ndFactor
1018 */
1019 public function verify2ndFactor($user, $password, $serial, $twoFactorInput) {
1020 logNewMessage(LOG_DEBUG, 'WebauthnProvider: Checking 2nd factor for ' . $user);
1021 include_once __DIR__ . '/webauthn.inc';
1022 $webauthnManager = $this->getWebauthnManager();
1023 $userDn = null;
1024 if (!empty($_SESSION['ldap'])) {
1025 $userDn = $_SESSION['ldap']->getUserName();
1026 }
1027 elseif (isset($_SESSION['selfService_clientDN'])) {
1028 $userDn = lamDecrypt($_SESSION['selfService_clientDN'], 'SelfService');
1029 }
1030 elseif (isset($_SESSION['whitePages_clientDN'])) {
1031 $userDn = lamDecrypt($_SESSION['whitePages_clientDN'], 'WhitePages');
1032 }
1033 if (empty($userDn)) {
1034 return false;
1035 }
1036 $hasTokens = $webauthnManager->isRegistered($userDn);
1037 if (!$hasTokens) {
1038 if ($this->config->twoFactorAuthenticationOptional && !$webauthnManager->isRegistered($user) && ($_POST['sig_response'] === 'skip')) {
1039 logNewMessage(LOG_DEBUG, 'Skipped 2FA for ' . $user . ' as no devices are registered and 2FA is optional.');
1040 return true;
1041 }
1042 $response = base64_decode($_POST['sig_response']);
1043 $loader = $webauthnManager->createPublicKeyCredentialLoader();
1044 $registrationObject = $loader->deserialize($_SESSION['webauthn_registration'], PublicKeyCredentialCreationOptions::class, 'json');
1045 if (!$webauthnManager->storeNewRegistration($registrationObject, $response)) {
1046 return false;
1047 }
1048 if (!empty($_POST['newName'])) {
1049 $deviceList = $webauthnManager->getDatabase()->findAllForUserDn($userDn);
1050 $webauthnManager->getDatabase()->updateDeviceName($userDn, base64_encode($deviceList[0]->publicKeyCredentialId), $_POST['newName']);
1051 }
1052 return true;
1053 }
1054 else {
1055 logNewMessage(LOG_DEBUG, 'Checking WebAuthn response of ' . $userDn);
1056 $response = base64_decode($_POST['sig_response']);
1057 return $webauthnManager->isValidAuthentication($response, $userDn);
1058 }
1059 }
1060
1061 /**
1062 * @inheritDoc
1063 */
1064 public function supportsToRememberDevice(): bool {
1065 return $this->config->twoFactorAllowToRememberDevice;
1066 }
1067
1068 }
1069
1070 /**
1071 * Returns the correct 2 factor provider.
1072 */
1073 class TwoFactorProviderService {
1074
1075 /** 2factor authentication disabled */
1076 public const TWO_FACTOR_NONE = 'none';
1077 /** 2factor authentication via privacyIDEA */
1078 public const TWO_FACTOR_PRIVACYIDEA = 'privacyidea';
1079 /** 2factor authentication via YubiKey */
1080 public const TWO_FACTOR_YUBICO = 'yubico';
1081 /** 2factor authentication via DUO */
1082 public const TWO_FACTOR_DUO = 'duo';
1083 /** 2factor authentication via webauthn */
1084 public const TWO_FACTOR_WEBAUTHN = 'webauthn';
1085 /** 2factor authentication via Okta */
1086 public const TWO_FACTOR_OKTA = 'okta';
1087 /** 2factor authentication via OpenId */
1088 public const TWO_FACTOR_OPENID = 'openid';
1089
1090 /** date format when remembering devices */
1091 private const DEVICE_REMEMBER_DATE_FORMAT = 'Y-m-d H:i:s';
1092
1093 private TwoFactorConfiguration $config;
1094
1095 /**
1096 * Constructor.
1097 *
1098 * @param selfServiceProfile|WhitePagesProfile|LAMConfig $configObj profile
1099 */
1100 public function __construct(selfServiceProfile|WhitePagesProfile|LAMConfig $configObj) {
1101 if ($configObj instanceof selfServiceProfile) {
1102 $this->config = $this->getConfigSelfService($configObj);
1103 }
1104 elseif ($configObj instanceof WhitePagesProfile) {
1105 $this->config = $this->getConfigWhitePages($configObj);
1106 }
1107 else {
1108 $this->config = $this->getConfigAdmin($configObj);
1109 }
1110 }
1111
1112 /**
1113 * Returns the provider for the given type.
1114 *
1115 * @return TwoFactorProvider provider
1116 * @throws Exception unable to get provider
1117 */
1118 public function getProvider() {
1119 if ($this->config->twoFactorAuthentication == TwoFactorProviderService::TWO_FACTOR_PRIVACYIDEA) {
1120 return new PrivacyIDEAProvider($this->config);
1121 }
1122 elseif ($this->config->twoFactorAuthentication == TwoFactorProviderService::TWO_FACTOR_YUBICO) {
1123 return new YubicoProvider($this->config);
1124 }
1125 elseif ($this->config->twoFactorAuthentication == TwoFactorProviderService::TWO_FACTOR_DUO) {
1126 return new DuoProvider($this->config);
1127 }
1128 elseif ($this->config->twoFactorAuthentication == TwoFactorProviderService::TWO_FACTOR_WEBAUTHN) {
1129 return new WebauthnProvider($this->config);
1130 }
1131 elseif ($this->config->twoFactorAuthentication == TwoFactorProviderService::TWO_FACTOR_OKTA) {
1132 return new OktaProvider($this->config);
1133 }
1134 elseif ($this->config->twoFactorAuthentication == TwoFactorProviderService::TWO_FACTOR_OPENID) {
1135 return new OpenIdProvider($this->config);
1136 }
1137 throw new Exception('Invalid provider: ' . $this->config->twoFactorAuthentication);
1138 }
1139
1140 /**
1141 * Remembers the users device.
1142 *
1143 * @param string $user user name
1144 * @throws Exception error getting provider
1145 */
1146 public function rememberDevice(string $user): void {
1147 if (!$this->getProvider()->supportsToRememberDevice()) {
1148 logNewMessage(LOG_ERR, 'The selected 2FA provider does not support to remember devices.');
1149 return;
1150 }
1151 if (empty($this->config->twoFactorRememberDevicePassword)) {
1152 logNewMessage(LOG_ERR, 'The selected 2FA password to remember devices is empty.');
1153 return;
1154 }
1155 $dataToEncrypt = [
1156 'user' => $user,
1157 'timestamp' => getFormattedTime(self::DEVICE_REMEMBER_DATE_FORMAT),
1158 ];
1159 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
1160 $dataToEncrypt['userAgent'] = $_SERVER['HTTP_USER_AGENT'];
1161 }
1162 if (!empty($_SERVER['REMOTE_ADDR'])) {
1163 $dataToEncrypt['clientIp'] = $_SERVER['REMOTE_ADDR'];
1164 }
1165 $iv = openssl_random_pseudo_bytes(16);
1166 $encryptedData = openssl_encrypt(json_encode($dataToEncrypt), lamEncryptionAlgo(),
1167 $this->config->twoFactorRememberDevicePassword, 0, $iv);
1168 $data = [
1169 'iv' => base64_encode($iv),
1170 'data' => base64_encode($encryptedData)
1171 ];
1172 $cookieOptions = lamDefaultCookieOptions();
1173 $cookieOptions['expires'] = time() + intval($this->config->twoFactorRememberDeviceDuration);
1174 $this->setCookie('lam_remember_2fa', json_encode($data), $cookieOptions);
1175 }
1176
1177 /**
1178 * Sets a cookie.
1179 *
1180 * @param string $name cookie name
1181 * @param string $value cookie value
1182 * @param array<string, string|bool|int> $options cookie options
1183 */
1184 protected function setCookie(string $name, string $value, array $options): void {
1185 setcookie($name, $value, $options);
1186 }
1187
1188 /**
1189 * Returns if the user has selected to save the device before.
1190 *
1191 * @param string $user user name
1192 * @return bool valid remembered device
1193 * @throws Exception error getting provider
1194 */
1195 public function isValidRememberedDevice(string $user): bool {
1196 if (!$this->getProvider()->supportsToRememberDevice()) {
1197 logNewMessage(LOG_ERR, 'The selected 2FA provider does not support to remember devices.');
1198 return false;
1199 }
1200 if (empty($this->config->twoFactorRememberDevicePassword)) {
1201 logNewMessage(LOG_ERR, 'The selected 2FA password to remember devices is empty.');
1202 return false;
1203 }
1204 if (empty($this->config->twoFactorRememberDeviceDuration)) {
1205 logNewMessage(LOG_ERR, 'The selected 2FA remember device period is empty.');
1206 return false;
1207 }
1208 if (!isset($_COOKIE['lam_remember_2fa'])) {
1209 return false;
1210 }
1211 $data = json_decode($_COOKIE['lam_remember_2fa'], true);
1212 if (($data === null) || empty($data['iv']) || empty($data['data'])) {
1213 return false;
1214 }
1215 $iv = base64_decode($data['iv']);
1216 $decryptedData = openssl_decrypt(base64_decode($data['data']), lamEncryptionAlgo(),
1217 $this->config->twoFactorRememberDevicePassword, 0, $iv);
1218 if ($decryptedData === false) {
1219 return false;
1220 }
1221 $decryptedData = json_decode($decryptedData, true);
1222 if (!isset($decryptedData['user'])) {
1223 return false;
1224 }
1225 if ($decryptedData['user'] !== $user) {
1226 logNewMessage(LOG_DEBUG, 'User name for remembered device does not match. ' . $user . ' - ' . $decryptedData['user']);
1227 return false;
1228 }
1229 if (!empty($decryptedData['userAgent'])
1230 && (empty($_SERVER['HTTP_USER_AGENT']) || ($decryptedData['userAgent'] !== $_SERVER['HTTP_USER_AGENT']))) {
1231 logNewMessage(LOG_DEBUG, 'User agent for remembered device does not match. ' . $decryptedData['user']);
1232 return false;
1233 }
1234 if (!empty($decryptedData['clientIp'])
1235 && (empty($_SERVER['REMOTE_ADDR']) || ($decryptedData['clientIp'] !== $_SERVER['REMOTE_ADDR']))) {
1236 logNewMessage(LOG_DEBUG, 'Client IP for remembered device does not match. ' . $decryptedData['clientIp']);
1237 return false;
1238 }
1239 try {
1240 $acceptedTime = new DateTime('now', getTimeZone());
1241 $acceptedTime = $acceptedTime->sub(new DateInterval('PT' . $this->config->twoFactorRememberDeviceDuration . 'S'));
1242 $deviceDate = DateTime::createFromFormat(self::DEVICE_REMEMBER_DATE_FORMAT, $decryptedData['timestamp'], getTimeZone());
1243 if ($deviceDate > $acceptedTime) {
1244 return true;
1245 }
1246 }
1247 catch (Exception $e) {
1248 logNewMessage(LOG_ERR, 'Unable to check remembered device of ' . $user . ': ' . $e->getMessage());
1249 }
1250 return false;
1251 }
1252
1253 /**
1254 * Returns the configuration from self-service.
1255 *
1256 * @param selfServiceProfile $profile profile
1257 * @return TwoFactorConfiguration configuration
1258 */
1259 private function getConfigSelfService(&$profile): TwoFactorConfiguration {
1260 $tfConfig = new TwoFactorConfiguration();
1261 $tfConfig->interface = LAM_INTERFACE::SELF_SERVICE;
1262 $tfConfig->twoFactorAuthentication = $profile->twoFactorAuthentication;
1263 $tfConfig->twoFactorAuthenticationInsecure = $profile->twoFactorAuthenticationInsecure;
1264 $tfConfig->twoFactorAuthenticationOptional = $profile->twoFactorAuthenticationOptional;
1265 if ($tfConfig->twoFactorAuthentication == TwoFactorProviderService::TWO_FACTOR_YUBICO) {
1266 $tfConfig->twoFactorAuthenticationURL = explode("\r\n", $profile->twoFactorAuthenticationURL);
1267 }
1268 else {
1269 $tfConfig->twoFactorAuthenticationURL = $profile->twoFactorAuthenticationURL;
1270 }
1271 $tfConfig->twoFactorAuthenticationClientId = $profile->twoFactorAuthenticationClientId;
1272 $tfConfig->twoFactorAuthenticationSecretKey = $profile->twoFactorAuthenticationSecretKey;
1273 if ($tfConfig->twoFactorAuthentication == TwoFactorProviderService::TWO_FACTOR_YUBICO) {
1274 $moduleSettings = $profile->moduleSettings;
1275 if (!empty($moduleSettings['yubiKeyUser_attributeName'][0])) {
1276 $tfConfig->twoFactorAuthenticationSerialAttributeName = $moduleSettings['yubiKeyUser_attributeName'][0];
1277 }
1278 else {
1279 $tfConfig->twoFactorAuthenticationSerialAttributeName = 'yubiKeyId';
1280 }
1281 }
1282 if (in_array($tfConfig->twoFactorAuthentication, [TwoFactorProviderService::TWO_FACTOR_PRIVACYIDEA,
1283 TwoFactorProviderService::TWO_FACTOR_DUO, TwoFactorProviderService::TWO_FACTOR_OKTA,
1284 TwoFactorProviderService::TWO_FACTOR_OPENID])) {
1285 $attrName = $profile->twoFactorAuthenticationAttribute;
1286 if (empty($attrName)) {
1287 $attrName = 'uid';
1288 }
1289 $tfConfig->twoFactorAuthenticationSerialAttributeName = strtolower($attrName);
1290 }
1291 if (in_array($tfConfig->twoFactorAuthentication, [TwoFactorProviderService::TWO_FACTOR_PRIVACYIDEA,
1292 TwoFactorProviderService::TWO_FACTOR_WEBAUTHN, TwoFactorProviderService::TWO_FACTOR_YUBICO])) {
1293 $tfConfig->twoFactorAllowToRememberDevice = ($profile->twoFactorAllowToRememberDevice === 'true');
1294 $tfConfig->twoFactorRememberDeviceDuration = $profile->twoFactorRememberDeviceDuration;
1295 $tfConfig->twoFactorRememberDevicePassword = $profile->twoFactorRememberDevicePassword;
1296 }
1297 $tfConfig->loginHandler = $profile->getLoginHandler();
1298 return $tfConfig;
1299 }
1300
1301 /**
1302 * Returns the configuration from white pages.
1303 *
1304 * @param WhitePagesProfile $profile profile
1305 * @return TwoFactorConfiguration configuration
1306 */
1307 private function getConfigWhitePages(WhitePagesProfile &$profile): TwoFactorConfiguration {
1308 $tfConfig = new TwoFactorConfiguration();
1309 $tfConfig->interface = LAM_INTERFACE::WHITE_PAGES;
1310 $tfConfig->twoFactorAuthentication = $profile->twoFactorAuthenticationType;
1311 $tfConfig->twoFactorAuthenticationInsecure = $profile->twoFactorAuthenticationInsecure;
1312 if ($tfConfig->twoFactorAuthentication == TwoFactorProviderService::TWO_FACTOR_YUBICO) {
1313 $tfConfig->twoFactorAuthenticationURL = explode("\r\n", $profile->twoFactorAuthenticationURL);
1314 }
1315 else {
1316 $tfConfig->twoFactorAuthenticationURL = $profile->twoFactorAuthenticationURL;
1317 }
1318 $tfConfig->twoFactorAuthenticationClientId = $profile->twoFactorAuthenticationClientId;
1319 $tfConfig->twoFactorAuthenticationSecretKey = $profile->twoFactorAuthenticationSecretKey;
1320 if ($tfConfig->twoFactorAuthentication == TwoFactorProviderService::TWO_FACTOR_YUBICO) {
1321 $tfConfig->twoFactorAuthenticationSerialAttributeName = 'yubiKeyId';
1322 }
1323 if (in_array($tfConfig->twoFactorAuthentication, [TwoFactorProviderService::TWO_FACTOR_PRIVACYIDEA,
1324 TwoFactorProviderService::TWO_FACTOR_DUO, TwoFactorProviderService::TWO_FACTOR_OKTA,
1325 TwoFactorProviderService::TWO_FACTOR_OPENID])) {
1326 $attrName = $profile->twoFactorAuthenticationAttribute;
1327 if (empty($attrName)) {
1328 $attrName = 'uid';
1329 }
1330 $tfConfig->twoFactorAuthenticationSerialAttributeName = strtolower($attrName);
1331 }
1332 if (in_array($tfConfig->twoFactorAuthentication, [TwoFactorProviderService::TWO_FACTOR_PRIVACYIDEA,
1333 TwoFactorProviderService::TWO_FACTOR_WEBAUTHN, TwoFactorProviderService::TWO_FACTOR_YUBICO])) {
1334 $tfConfig->twoFactorAllowToRememberDevice = $profile->twoFactorAllowToRememberDevice;
1335 $tfConfig->twoFactorRememberDeviceDuration = (string) $profile->twoFactorRememberDeviceDuration;
1336 $tfConfig->twoFactorRememberDevicePassword = $profile->twoFactorRememberDevicePassword;
1337 }
1338 $tfConfig->loginHandler = $profile->getLoginHandler();
1339 return $tfConfig;
1340 }
1341
1342 /**
1343 * Returns the configuration for admin interface.
1344 *
1345 * @param LAMConfig $conf configuration
1346 * @return TwoFactorConfiguration configuration
1347 */
1348 private function getConfigAdmin($conf): TwoFactorConfiguration {
1349 $tfConfig = new TwoFactorConfiguration();
1350 $tfConfig->interface = LAM_INTERFACE::ADMIN;
1351 $tfConfig->twoFactorAuthentication = $conf->getTwoFactorAuthentication();
1352 $tfConfig->twoFactorAuthenticationInsecure = $conf->getTwoFactorAuthenticationInsecure();
1353 $tfConfig->twoFactorAuthenticationOptional = $conf->getTwoFactorAuthenticationOptional();
1354 if ($tfConfig->twoFactorAuthentication == TwoFactorProviderService::TWO_FACTOR_YUBICO) {
1355 $tfConfig->twoFactorAuthenticationURL = explode("\r\n", $conf->getTwoFactorAuthenticationURL());
1356 }
1357 else {
1358 $tfConfig->twoFactorAuthenticationURL = $conf->getTwoFactorAuthenticationURL();
1359 }
1360 $tfConfig->twoFactorAuthenticationClientId = $conf->getTwoFactorAuthenticationClientId();
1361 $tfConfig->twoFactorAuthenticationSecretKey = $conf->getTwoFactorAuthenticationSecretKey();
1362 if ($tfConfig->twoFactorAuthentication == TwoFactorProviderService::TWO_FACTOR_YUBICO) {
1363 $moduleSettings = $conf->get_moduleSettings();
1364 if (!empty($moduleSettings['yubiKeyUser_attributeName'][0])) {
1365 $tfConfig->twoFactorAuthenticationSerialAttributeName = $moduleSettings['yubiKeyUser_attributeName'][0];
1366 }
1367 else {
1368 $tfConfig->twoFactorAuthenticationSerialAttributeName = 'yubiKeyId';
1369 }
1370 }
1371 if (in_array($tfConfig->twoFactorAuthentication, [TwoFactorProviderService::TWO_FACTOR_PRIVACYIDEA,
1372 TwoFactorProviderService::TWO_FACTOR_DUO, TwoFactorProviderService::TWO_FACTOR_OKTA,
1373 TwoFactorProviderService::TWO_FACTOR_OPENID])) {
1374 $tfConfig->twoFactorAuthenticationSerialAttributeName = strtolower($conf->getTwoFactorAuthenticationAttribute());
1375 }
1376 if (in_array($tfConfig->twoFactorAuthentication, [TwoFactorProviderService::TWO_FACTOR_PRIVACYIDEA,
1377 TwoFactorProviderService::TWO_FACTOR_WEBAUTHN, TwoFactorProviderService::TWO_FACTOR_YUBICO])) {
1378 $tfConfig->twoFactorAllowToRememberDevice = ($conf->getTwoFactorAllowToRememberDevice() === 'true');
1379 $tfConfig->twoFactorRememberDeviceDuration = $conf->getTwoFactorRememberDeviceDuration();
1380 $tfConfig->twoFactorRememberDevicePassword = $conf->getTwoFactorRememberDevicePassword();
1381 }
1382 return $tfConfig;
1383 }
1384
1385 }
1386
1387 /**
1388 * Configuration settings for 2-factor authentication.
1389 *
1390 * @author Roland Gruber
1391 */
1392 class TwoFactorConfiguration {
1393
1394 /** LAM UI */
1395 public LAM_INTERFACE $interface = LAM_INTERFACE::ADMIN;
1396
1397 /**
1398 * @var string|null provider id
1399 */
1400 public ?string $twoFactorAuthentication = null;
1401
1402 /**
1403 * @var string|string[] service URL(s)
1404 */
1405 public $twoFactorAuthenticationURL;
1406
1407 /**
1408 * @var bool disable certificate check
1409 */
1410 public bool $twoFactorAuthenticationInsecure = false;
1411
1412 /**
1413 * @var ?string client ID for API access
1414 */
1415 public ?string $twoFactorAuthenticationClientId = null;
1416
1417 /**
1418 * @var ?string secret key for API access
1419 */
1420 public ?string $twoFactorAuthenticationSecretKey = null;
1421
1422 /**
1423 * @var ?string LDAP attribute name that stores the token serials
1424 */
1425 public ?string $twoFactorAuthenticationSerialAttributeName = null;
1426
1427 /**
1428 * @var bool 2FA is optional
1429 */
1430 public bool $twoFactorAuthenticationOptional = false;
1431
1432 /**
1433 * @var bool allow to remember 2nd factor
1434 */
1435 public bool $twoFactorAllowToRememberDevice = false;
1436
1437 /**
1438 * @var string duration for remembering
1439 */
1440 public string $twoFactorRememberDeviceDuration = '';
1441
1442 /**
1443 * @var string password for remembering
1444 */
1445 public string $twoFactorRememberDevicePassword = '';
1446
1447 /**
1448 * @var SelfServiceLoginHandler|WhitePagesLoginHandler|null login handler
1449 */
1450 public SelfServiceLoginHandler|WhitePagesLoginHandler|null $loginHandler = null;
1451
1452 }