| 1 |
<?php |
| 2 |
|
| 3 |
namespace LAM\LOGIN\WEBAUTHN; |
| 4 |
|
| 5 |
use Cose\Algorithm\Manager; |
| 6 |
use Cose\Algorithm\Signature\ECDSA\ES256; |
| 7 |
use Cose\Algorithm\Signature\ECDSA\ES384; |
| 8 |
use Cose\Algorithm\Signature\ECDSA\ES512; |
| 9 |
use Cose\Algorithm\Signature\EdDSA\EdDSA; |
| 10 |
use Cose\Algorithm\Signature\RSA\RS1; |
| 11 |
use Cose\Algorithm\Signature\RSA\RS256; |
| 12 |
use Cose\Algorithm\Signature\RSA\RS384; |
| 13 |
use Cose\Algorithm\Signature\RSA\RS512; |
| 14 |
use Cose\Algorithms; |
| 15 |
use LAM\PERSISTENCE\ConfigurationDatabase; |
| 16 |
use LAM_INTERFACE; |
| 17 |
use LAMCfgMain; |
| 18 |
use LAMException; |
| 19 |
use PDO; |
| 20 |
use PDOException; |
| 21 |
use Symfony\Component\Serializer\SerializerInterface; |
| 22 |
use Throwable; |
| 23 |
use Webauthn\AttestationStatement\AndroidKeyAttestationStatementSupport; |
| 24 |
use Webauthn\AttestationStatement\AttestationStatementSupportManager; |
| 25 |
use Webauthn\AttestationStatement\FidoU2FAttestationStatementSupport; |
| 26 |
use Webauthn\AttestationStatement\NoneAttestationStatementSupport; |
| 27 |
use Webauthn\AttestationStatement\PackedAttestationStatementSupport; |
| 28 |
use Webauthn\AttestationStatement\TPMAttestationStatementSupport; |
| 29 |
use Webauthn\AuthenticationExtensions\AuthenticationExtensions; |
| 30 |
use Webauthn\AuthenticationExtensions\ExtensionOutputCheckerHandler; |
| 31 |
use Webauthn\AuthenticatorAssertionResponse; |
| 32 |
use Webauthn\AuthenticatorAssertionResponseValidator; |
| 33 |
use Webauthn\AuthenticatorAttestationResponse; |
| 34 |
use Webauthn\AuthenticatorAttestationResponseValidator; |
| 35 |
use Webauthn\AuthenticatorSelectionCriteria; |
| 36 |
use Webauthn\CeremonyStep\CeremonyStepManagerFactory; |
| 37 |
use Webauthn\Denormalizer\WebauthnSerializerFactory; |
| 38 |
use Webauthn\PublicKeyCredential; |
| 39 |
use Webauthn\PublicKeyCredentialCreationOptions; |
| 40 |
use Webauthn\PublicKeyCredentialDescriptor; |
| 41 |
use Webauthn\PublicKeyCredentialParameters; |
| 42 |
use Webauthn\PublicKeyCredentialRequestOptions; |
| 43 |
use Webauthn\PublicKeyCredentialRpEntity; |
| 44 |
use Webauthn\CredentialRecord; |
| 45 |
use Webauthn\PublicKeyCredentialUserEntity; |
| 46 |
use function LAM\PERSISTENCE\dbTableExists; |
| 47 |
|
| 48 |
/* |
| 49 |
|
| 50 |
This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/) |
| 51 |
Copyright (C) 2019 - 2026 Roland Gruber |
| 52 |
|
| 53 |
This program is free software; you can redistribute it and/or modify |
| 54 |
it under the terms of the GNU General Public License as published by |
| 55 |
the Free Software Foundation; either version 2 of the License, or |
| 56 |
(at your option) any later version. |
| 57 |
|
| 58 |
This program is distributed in the hope that it will be useful, |
| 59 |
but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 60 |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 61 |
GNU General Public License for more details. |
| 62 |
|
| 63 |
You should have received a copy of the GNU General Public License |
| 64 |
along with this program; if not, write to the Free Software |
| 65 |
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA |
| 66 |
|
| 67 |
*/ |
| 68 |
|
| 69 |
/** |
| 70 |
* Manages webauthn requests. |
| 71 |
* |
| 72 |
* @author Roland Gruber |
| 73 |
*/ |
| 74 |
|
| 75 |
include_once __DIR__ . '/3rdParty/composer/autoload.php'; |
| 76 |
|
| 77 |
/** |
| 78 |
* Manages Webauthn registrations and authentications. |
| 79 |
* |
| 80 |
* @package LAM\LOGIN\WEBAUTHN |
| 81 |
*/ |
| 82 |
class WebauthnManager { |
| 83 |
|
| 84 |
/** |
| 85 |
* Returns if the given DN is registered for webauthn. |
| 86 |
* |
| 87 |
* @param string $dn DN |
| 88 |
* @return bool is registered |
| 89 |
*/ |
| 90 |
public function isRegistered($dn): bool { |
| 91 |
$database = $this->getDatabase(); |
| 92 |
$results = $database->findAllForUserDn($dn); |
| 93 |
return !empty($results); |
| 94 |
} |
| 95 |
|
| 96 |
/** |
| 97 |
* Returns a challenge for a new token. |
| 98 |
* |
| 99 |
* @param string $dn DN |
| 100 |
* @param LAM_INTERFACE $interface interface |
| 101 |
* @param string[] $extraExcludedKeys credentialIds that should be added to excluded keys |
| 102 |
* @return PublicKeyCredentialCreationOptions registration object |
| 103 |
*/ |
| 104 |
public function getRegistrationObject($dn, LAM_INTERFACE $interface, $extraExcludedKeys = []) { |
| 105 |
$rpEntity = $this->createRpEntry($interface); |
| 106 |
$_SESSION['webauthn_rp_id'] = $rpEntity->id; |
| 107 |
$userEntity = $this->getUserEntity($dn); |
| 108 |
$challenge = $this->createChallenge(); |
| 109 |
$credentialParameters = $this->getCredentialParameters(); |
| 110 |
$excludedKeys = $this->getExcludedKeys($dn, $extraExcludedKeys); |
| 111 |
$timeout = $this->getTimeout(); |
| 112 |
$authenticatorSelectionCriteria = AuthenticatorSelectionCriteria::create(null, AuthenticatorSelectionCriteria::USER_VERIFICATION_REQUIREMENT_DISCOURAGED); |
| 113 |
$registrationObject = PublicKeyCredentialCreationOptions::create( |
| 114 |
$rpEntity, |
| 115 |
$userEntity, |
| 116 |
$challenge, |
| 117 |
$credentialParameters, |
| 118 |
$authenticatorSelectionCriteria, |
| 119 |
PublicKeyCredentialCreationOptions::ATTESTATION_CONVEYANCE_PREFERENCE_NONE, |
| 120 |
$excludedKeys, |
| 121 |
$timeout, |
| 122 |
new AuthenticationExtensions() |
| 123 |
); |
| 124 |
logNewMessage(LOG_DEBUG, 'WebAuthn registration: ' . json_encode($registrationObject)); |
| 125 |
return $registrationObject; |
| 126 |
} |
| 127 |
|
| 128 |
/** |
| 129 |
* Verifies the registration and stores it in the database. |
| 130 |
* |
| 131 |
* @param PublicKeyCredentialCreationOptions $registration registration object |
| 132 |
* @param string $clientResponse client response |
| 133 |
* @return bool true if response is valid and registration succeeded |
| 134 |
*/ |
| 135 |
public function storeNewRegistration($registration, $clientResponse) { |
| 136 |
$publicKeyCredentialLoader = $this->createPublicKeyCredentialLoader(); |
| 137 |
$repository = $this->getDatabase(); |
| 138 |
$csmFactory = new CeremonyStepManagerFactory(); |
| 139 |
$creationCSM = $csmFactory->creationCeremony(); |
| 140 |
$responseValidator = AuthenticatorAttestationResponseValidator::create($creationCSM); |
| 141 |
try { |
| 142 |
$publicKeyCredential = $publicKeyCredentialLoader->deserialize($clientResponse, PublicKeyCredential::class, 'json'); |
| 143 |
$authenticatorAttestationResponse = $publicKeyCredential->response; |
| 144 |
if (!$authenticatorAttestationResponse instanceof AuthenticatorAttestationResponse) { |
| 145 |
logNewMessage(LOG_ERR, 'Invalid webauthn response: ' . $clientResponse); |
| 146 |
return false; |
| 147 |
} |
| 148 |
$publicKeyCredentialSource = $responseValidator->check($authenticatorAttestationResponse, $registration, $_SESSION['webauthn_rp_id']); |
| 149 |
$repository->saveCredentialSource($publicKeyCredentialSource); |
| 150 |
return true; |
| 151 |
} |
| 152 |
catch (Throwable $exception) { |
| 153 |
logNewMessage(LOG_ERR, 'WebAuthn validation failed: ' . $exception->getMessage() . $exception->getTraceAsString()); |
| 154 |
} |
| 155 |
return false; |
| 156 |
} |
| 157 |
|
| 158 |
/** |
| 159 |
* Returns a public key credential loader. |
| 160 |
* |
| 161 |
* @return SerializerInterface public key credential loader |
| 162 |
*/ |
| 163 |
public function createPublicKeyCredentialLoader() { |
| 164 |
$attestationSupportManager = $this->getAttestationSupportManager(); |
| 165 |
$factory = new WebauthnSerializerFactory($attestationSupportManager); |
| 166 |
return $factory->create(); |
| 167 |
} |
| 168 |
|
| 169 |
/** |
| 170 |
* Returns the user entity for the registration. |
| 171 |
* |
| 172 |
* @param string $dn DN |
| 173 |
* @return PublicKeyCredentialUserEntity user entity |
| 174 |
*/ |
| 175 |
private function getUserEntity($dn) { |
| 176 |
return new PublicKeyCredentialUserEntity( |
| 177 |
self::getUserIdFromDn($dn), |
| 178 |
self::getUserIdFromDn($dn), |
| 179 |
extractRDNValue($dn) |
| 180 |
); |
| 181 |
} |
| 182 |
|
| 183 |
/** |
| 184 |
* Generates the user ID as hash of the user DN. |
| 185 |
* |
| 186 |
* @param string $dn user DN |
| 187 |
* @return string user ID |
| 188 |
*/ |
| 189 |
public static function getUserIdFromDn(string $dn) { |
| 190 |
return hash('sha256', $dn); |
| 191 |
} |
| 192 |
|
| 193 |
/** |
| 194 |
* Returns the part that identifies the server and application. |
| 195 |
* |
| 196 |
* @param LAM_INTERFACE $interface interface |
| 197 |
* @return PublicKeyCredentialRpEntity relying party entry |
| 198 |
*/ |
| 199 |
private function createRpEntry(LAM_INTERFACE $interface) { |
| 200 |
$pathPrefix = in_array($interface, [LAM_INTERFACE::SELF_SERVICE, LAM_INTERFACE::WHITE_PAGES]) ? '../' : ''; |
| 201 |
$icon = $pathPrefix . '../graphics/logo136.png'; |
| 202 |
if ($interface === LAM_INTERFACE::SELF_SERVICE) { |
| 203 |
$domain = $_SESSION['selfServiceProfile']->twoFactorAuthenticationDomain; |
| 204 |
} |
| 205 |
elseif ($interface === LAM_INTERFACE::WHITE_PAGES) { |
| 206 |
$domain = $_SESSION['whitePagesProfile']->twoFactorAuthenticationDomain; |
| 207 |
} |
| 208 |
else { |
| 209 |
$domain = $_SESSION['config']->getTwoFactorAuthenticationDomain(); |
| 210 |
} |
| 211 |
return new PublicKeyCredentialRpEntity( |
| 212 |
'LDAP Account Manager', //Name |
| 213 |
$domain, |
| 214 |
$icon |
| 215 |
); |
| 216 |
} |
| 217 |
|
| 218 |
/** |
| 219 |
* Returns the supported credential algorithms. |
| 220 |
* |
| 221 |
* @return PublicKeyCredentialParameters[] algorithms |
| 222 |
*/ |
| 223 |
private function getCredentialParameters(): array { |
| 224 |
return [ |
| 225 |
new PublicKeyCredentialParameters('public-key', Algorithms::COSE_ALGORITHM_ES256), |
| 226 |
new PublicKeyCredentialParameters('public-key', Algorithms::COSE_ALGORITHM_RS256), |
| 227 |
]; |
| 228 |
} |
| 229 |
|
| 230 |
/** |
| 231 |
* Returns a list of all credential ids that are already registered. |
| 232 |
* |
| 233 |
* @param string $userDn user DN |
| 234 |
* @param string[] $extraExcludedKeys credentialIds that should be added to excluded keys |
| 235 |
* @return PublicKeyCredentialDescriptor[] credential ids |
| 236 |
*/ |
| 237 |
private function getExcludedKeys(string $userDn, $extraExcludedKeys = []) { |
| 238 |
$keys = []; |
| 239 |
$repository = $this->getDatabase(); |
| 240 |
$credentialSources = $repository->findAllForUserDn($userDn); |
| 241 |
foreach ($credentialSources as $credentialSource) { |
| 242 |
$keys[] = new PublicKeyCredentialDescriptor(PublicKeyCredentialDescriptor::CREDENTIAL_TYPE_PUBLIC_KEY, $credentialSource->publicKeyCredentialId); |
| 243 |
} |
| 244 |
foreach ($extraExcludedKeys as $extraExcludedKey) { |
| 245 |
$keys[] = new PublicKeyCredentialDescriptor(PublicKeyCredentialDescriptor::CREDENTIAL_TYPE_PUBLIC_KEY, $extraExcludedKey); |
| 246 |
} |
| 247 |
return $keys; |
| 248 |
} |
| 249 |
|
| 250 |
/** |
| 251 |
* Creates the attestation support manager. |
| 252 |
* |
| 253 |
* @return AttestationStatementSupportManager manager |
| 254 |
*/ |
| 255 |
private function getAttestationSupportManager() { |
| 256 |
$manager = new AttestationStatementSupportManager(); |
| 257 |
$manager->add(new NoneAttestationStatementSupport()); |
| 258 |
$manager->add(new FidoU2FAttestationStatementSupport()); |
| 259 |
$manager->add(new AndroidKeyAttestationStatementSupport()); |
| 260 |
$manager->add(new TPMAttestationStatementSupport()); |
| 261 |
$coseManager = $this->getAlgorithmManager(); |
| 262 |
$manager->add(new PackedAttestationStatementSupport($coseManager)); |
| 263 |
return $manager; |
| 264 |
} |
| 265 |
|
| 266 |
/** |
| 267 |
* Returns the COSE algorithm manager. |
| 268 |
* |
| 269 |
* @return Manager algorithm manager |
| 270 |
*/ |
| 271 |
private function getAlgorithmManager() { |
| 272 |
$coseManager = new Manager(); |
| 273 |
$coseManager->add(new ES256()); |
| 274 |
$coseManager->add(new ES384()); |
| 275 |
$coseManager->add(new ES512()); |
| 276 |
$coseManager->add(new EdDSA()); |
| 277 |
$coseManager->add(new RS1()); |
| 278 |
$coseManager->add(new RS256()); |
| 279 |
$coseManager->add(new RS384); |
| 280 |
$coseManager->add(new RS512()); |
| 281 |
return $coseManager; |
| 282 |
} |
| 283 |
|
| 284 |
/** |
| 285 |
* Returns the webauthn database. |
| 286 |
* |
| 287 |
* @return PublicKeyCredentialSourceRepositoryBase database |
| 288 |
* @throws LAMException error connecting to database |
| 289 |
*/ |
| 290 |
public function getDatabase() { |
| 291 |
try { |
| 292 |
$configDatabase = new ConfigurationDatabase(new LAMCfgMain()); |
| 293 |
if ($configDatabase->useRemoteDb()) { |
| 294 |
return new PublicKeyCredentialSourceRepositoryMySql($configDatabase->getPdo()); |
| 295 |
} |
| 296 |
return new PublicKeyCredentialSourceRepositorySQLite(); |
| 297 |
} |
| 298 |
catch (PDOException $e) { |
| 299 |
throw new LAMException(_('Unable to connect to database.'), $e->getMessage(), $e); |
| 300 |
} |
| 301 |
} |
| 302 |
|
| 303 |
/** |
| 304 |
* Returns the timeout for user operations. |
| 305 |
* |
| 306 |
* @return positive-int timeout in ms |
| 307 |
*/ |
| 308 |
private function getTimeout(): int { |
| 309 |
return 120000; |
| 310 |
} |
| 311 |
|
| 312 |
/** |
| 313 |
* Creates a new challenge. |
| 314 |
* |
| 315 |
* @return String challenge |
| 316 |
*/ |
| 317 |
private function createChallenge() { |
| 318 |
return generateRandomPassword(32, false); |
| 319 |
} |
| 320 |
|
| 321 |
/** |
| 322 |
* Returns the authentication object for a registered user. |
| 323 |
* |
| 324 |
* @param string $userDN user DN |
| 325 |
* @param LAM_INTERFACE $interface interface |
| 326 |
* @return PublicKeyCredentialRequestOptions authentication object |
| 327 |
*/ |
| 328 |
public function getAuthenticationObject($userDN, LAM_INTERFACE $interface) { |
| 329 |
$timeout = $this->getTimeout(); |
| 330 |
$challenge = $this->createChallenge(); |
| 331 |
$database = $this->getDatabase(); |
| 332 |
$publicKeyCredentialSources = $database->findAllForUserDn($userDN); |
| 333 |
$userVerification = PublicKeyCredentialRequestOptions::USER_VERIFICATION_REQUIREMENT_DISCOURAGED; |
| 334 |
$extensions = new AuthenticationExtensions(); |
| 335 |
$relyingParty = $this->createRpEntry($interface); |
| 336 |
$_SESSION['webauthn_rp_id'] = $relyingParty->id; |
| 337 |
$allowCredentials = []; |
| 338 |
foreach ($publicKeyCredentialSources as $publicKeyCredentialSource) { |
| 339 |
$allowCredentials[] = $publicKeyCredentialSource->getPublicKeyCredentialDescriptor(); |
| 340 |
} |
| 341 |
return PublicKeyCredentialRequestOptions::create( |
| 342 |
$challenge, |
| 343 |
$relyingParty->id, |
| 344 |
$allowCredentials, |
| 345 |
$userVerification, |
| 346 |
$timeout, |
| 347 |
$extensions |
| 348 |
); |
| 349 |
} |
| 350 |
|
| 351 |
/** |
| 352 |
* Checks if the provided authentication is valid. |
| 353 |
* |
| 354 |
* @param string $response authentication response |
| 355 |
* @param string $userDn user DN |
| 356 |
* @return bool true if all is ok |
| 357 |
*/ |
| 358 |
public function isValidAuthentication(string $response, string $userDn) { |
| 359 |
$database = $this->getDatabase(); |
| 360 |
$csmFactory = new CeremonyStepManagerFactory(); |
| 361 |
$requestCSM = $csmFactory->requestCeremony(); |
| 362 |
$responseValidator = AuthenticatorAssertionResponseValidator::create( |
| 363 |
$requestCSM |
| 364 |
); |
| 365 |
$publicKeyCredentialLoader = $this->createPublicKeyCredentialLoader(); |
| 366 |
$publicKeyCredential = $publicKeyCredentialLoader->deserialize($response, PublicKeyCredential::class, 'json'); |
| 367 |
$authenticatorAssertionResponse = $publicKeyCredential->response; |
| 368 |
if (!$authenticatorAssertionResponse instanceof AuthenticatorAssertionResponse) { |
| 369 |
logNewMessage(LOG_ERR, 'Invalid authenticator assertion response'); |
| 370 |
return false; |
| 371 |
} |
| 372 |
try { |
| 373 |
$loader = $this->createPublicKeyCredentialLoader(); |
| 374 |
$publicKeyCredentialRequestOptions = $loader->deserialize($_SESSION['webauthn_authentication'], PublicKeyCredentialRequestOptions::class, 'json'); |
| 375 |
unset($_SESSION['webauthn_authentication']); |
| 376 |
$credential = $database->findOneByCredentialId($publicKeyCredential->rawId); |
| 377 |
if ($credential === null) { |
| 378 |
throw new LAMException('', 'Unable to find credential'); |
| 379 |
} |
| 380 |
$userId = $credential->userHandle; |
| 381 |
// old entries use DN as user ID |
| 382 |
$userHandle = ($userId === $userDn) ? $userDn : self::getUserIdFromDn($userDn); |
| 383 |
$responseValidator->check( |
| 384 |
$credential, |
| 385 |
$authenticatorAssertionResponse, |
| 386 |
$publicKeyCredentialRequestOptions, |
| 387 |
$_SESSION['webauthn_rp_id'], |
| 388 |
$userHandle |
| 389 |
); |
| 390 |
return true; |
| 391 |
} |
| 392 |
catch (Throwable $e) { |
| 393 |
logNewMessage(LOG_ERR, 'Error validating webauthn authentication: ' . $e->getMessage()); |
| 394 |
} |
| 395 |
return false; |
| 396 |
} |
| 397 |
|
| 398 |
} |
| 399 |
|
| 400 |
/** |
| 401 |
* Stores the public key credentials in the SQLite database. |
| 402 |
* |
| 403 |
* @package LAM\LOGIN\WEBAUTHN |
| 404 |
*/ |
| 405 |
abstract class PublicKeyCredentialSourceRepositoryBase { |
| 406 |
|
| 407 |
/** |
| 408 |
* Returns the table name to use. |
| 409 |
* |
| 410 |
* @return string table name |
| 411 |
*/ |
| 412 |
protected function getTableName(): string { |
| 413 |
return 'lam_webauthn'; |
| 414 |
} |
| 415 |
|
| 416 |
/** |
| 417 |
* Finds the public key for the given credential id. |
| 418 |
* |
| 419 |
* @param string $publicKeyCredentialId credential id |
| 420 |
* @return CredentialRecord|null credential source |
| 421 |
*/ |
| 422 |
public function findOneByCredentialId(string $publicKeyCredentialId): ?CredentialRecord { |
| 423 |
try { |
| 424 |
$pdo = $this->getPDO(); |
| 425 |
$statement = $pdo->prepare('select * from ' . $this->getTableName() . ' where credentialId = :credentialid'); |
| 426 |
$statement->execute([':credentialid' => base64_encode($publicKeyCredentialId)]); |
| 427 |
$results = $statement->fetchAll(); |
| 428 |
if (!empty($results)) { |
| 429 |
$jsonString = $results[0]['credentialSource']; |
| 430 |
$jsonArray = json_decode($jsonString, true); |
| 431 |
if (!is_array($jsonArray)) { |
| 432 |
return null; |
| 433 |
} |
| 434 |
$manager = new WebauthnManager(); |
| 435 |
$factory = $manager->createPublicKeyCredentialLoader(); |
| 436 |
return $factory->deserialize($jsonString, CredentialRecord::class, 'json'); |
| 437 |
} |
| 438 |
} |
| 439 |
catch (PDOException $e) { |
| 440 |
logNewMessage(LOG_ERR, 'WebAuthn database error: ' . $e->getMessage()); |
| 441 |
} |
| 442 |
return null; |
| 443 |
} |
| 444 |
|
| 445 |
/** |
| 446 |
* Finds all credential entries for the given user. |
| 447 |
* |
| 448 |
* @param string $userDn user DN |
| 449 |
* @return CredentialRecord[] credential sources |
| 450 |
*/ |
| 451 |
public function findAllForUserDn(string $userDn): array { |
| 452 |
$credentials = []; |
| 453 |
try { |
| 454 |
$pdo = $this->getPDO(); |
| 455 |
$statement = $pdo->prepare('select * from ' . $this->getTableName() . ' where userDN = :userDN'); |
| 456 |
$statement->execute([':userDN' => $userDn]); |
| 457 |
$results = $statement->fetchAll(); |
| 458 |
$manager = new WebauthnManager(); |
| 459 |
$factory = $manager->createPublicKeyCredentialLoader(); |
| 460 |
foreach ($results as $result) { |
| 461 |
$jsonString = $result['credentialSource']; |
| 462 |
$jsonArray = json_decode($jsonString, true); |
| 463 |
if (!is_array($jsonArray)) { |
| 464 |
return $credentials; |
| 465 |
} |
| 466 |
$credentials[] = $factory->deserialize($jsonString, CredentialRecord::class, 'json'); |
| 467 |
} |
| 468 |
} |
| 469 |
catch (PDOException $e) { |
| 470 |
logNewMessage(LOG_ERR, 'WebAuthn database error: ' . $e->getMessage()); |
| 471 |
} |
| 472 |
return $credentials; |
| 473 |
} |
| 474 |
|
| 475 |
/** |
| 476 |
* Saves the given credential in the database. |
| 477 |
* |
| 478 |
* @param CredentialRecord $publicKeyCredentialSource credential |
| 479 |
*/ |
| 480 |
public function saveCredentialSource(CredentialRecord $publicKeyCredentialSource): void { |
| 481 |
$webauthnManager = new WebauthnManager(); |
| 482 |
$loader = $webauthnManager->createPublicKeyCredentialLoader(); |
| 483 |
$json = $loader->serialize($publicKeyCredentialSource, 'json'); |
| 484 |
$credentialId = base64_encode($publicKeyCredentialSource->publicKeyCredentialId); |
| 485 |
$userId = $publicKeyCredentialSource->userHandle; |
| 486 |
$currentTime = time(); |
| 487 |
$pdo = $this->getPDO(); |
| 488 |
if (isset($_SESSION['selfService_clientDN'])) { |
| 489 |
$userDn = lamDecrypt($_SESSION['selfService_clientDN'], 'SelfService'); |
| 490 |
} |
| 491 |
else { |
| 492 |
$userDn = $_SESSION['ldap']->getUserName(); |
| 493 |
} |
| 494 |
$statement = $pdo->prepare('select * from ' . $this->getTableName() . ' where userDN = :userDN and credentialId = :credentialId'); |
| 495 |
$statement->execute([ |
| 496 |
':userDN' => $userDn, |
| 497 |
':credentialId' => $credentialId |
| 498 |
]); |
| 499 |
$results = $statement->fetchAll(); |
| 500 |
if (empty($results)) { |
| 501 |
$statement = $pdo->prepare('insert into ' . $this->getTableName() . ' (userId, credentialId, credentialSource, registrationTime, lastUseTime, userDN) VALUES (?, ?, ?, ?, ?, ?)'); |
| 502 |
$statement->execute([ |
| 503 |
$userId, |
| 504 |
$credentialId, |
| 505 |
$json, |
| 506 |
$currentTime, |
| 507 |
$currentTime, |
| 508 |
$userDn |
| 509 |
]); |
| 510 |
logNewMessage(LOG_DEBUG, 'Stored new credential for ' . $userDn); |
| 511 |
} |
| 512 |
else { |
| 513 |
$statement = $pdo->prepare( |
| 514 |
'update ' . $this->getTableName() . |
| 515 |
' set credentialSource = :credentialSource, lastUseTime = :lastUseTime' . |
| 516 |
' WHERE userDN = :userDN AND credentialId = :credentialId' |
| 517 |
); |
| 518 |
$statement->execute([ |
| 519 |
':credentialSource' => $json, |
| 520 |
':lastUseTime' => $currentTime, |
| 521 |
':userDN' => $userDn, |
| 522 |
':credentialId' => $credentialId |
| 523 |
]); |
| 524 |
logNewMessage(LOG_DEBUG, 'Stored updated credential for ' . $userDn); |
| 525 |
} |
| 526 |
} |
| 527 |
|
| 528 |
/** |
| 529 |
* Returns if there are any credentials in the database. |
| 530 |
* |
| 531 |
* @return bool at least one credential in the database |
| 532 |
*/ |
| 533 |
public function hasRegisteredCredentials(): bool { |
| 534 |
try { |
| 535 |
$pdo = $this->getPDO(); |
| 536 |
$statement = $pdo->prepare('select count(*) from ' . $this->getTableName()); |
| 537 |
$statement->execute(); |
| 538 |
$results = $statement->fetchAll(); |
| 539 |
return ($results[0][0] > 0); |
| 540 |
} |
| 541 |
catch (PDOException $e) { |
| 542 |
logNewMessage(LOG_ERR, 'WebAuthn database error: ' . $e->getMessage()); |
| 543 |
} |
| 544 |
return false; |
| 545 |
} |
| 546 |
|
| 547 |
/** |
| 548 |
* Performs a full-text search on the usernames and returns all devices found. |
| 549 |
* |
| 550 |
* @param string $searchTerm search term for user field |
| 551 |
* @return array<array<string, mixed>> list of devices array('dn' => ..., 'credentialId' => ..., 'lastUseTime' => ..., 'registrationTime' => ...) |
| 552 |
*/ |
| 553 |
public function searchDevices(string $searchTerm) { |
| 554 |
$pdo = $this->getPDO(); |
| 555 |
$statement = $pdo->prepare('select * from ' . $this->getTableName() . ' where userDN like :searchTerm order by userId,registrationTime'); |
| 556 |
$statement->execute([ |
| 557 |
':searchTerm' => $searchTerm |
| 558 |
]); |
| 559 |
$results = $statement->fetchAll(); |
| 560 |
$devices = []; |
| 561 |
foreach ($results as $result) { |
| 562 |
$name = empty($result['name']) ? '' : $result['name']; |
| 563 |
$devices[] = [ |
| 564 |
'dn' => $result['userDN'], |
| 565 |
'credentialId' => $result['credentialId'], |
| 566 |
'lastUseTime' => $result['lastUseTime'], |
| 567 |
'registrationTime' => $result['registrationTime'], |
| 568 |
'name' => $name |
| 569 |
]; |
| 570 |
} |
| 571 |
return $devices; |
| 572 |
} |
| 573 |
|
| 574 |
/** |
| 575 |
* Performs a full-text search on the usernames and returns all devices found. |
| 576 |
* |
| 577 |
* @param string $userDn user DN |
| 578 |
* @return array<array<string, mixed>> list of devices array('dn' => ..., 'credentialId' => ..., 'lastUseTime' => ..., 'registrationTime' => ...) |
| 579 |
*/ |
| 580 |
public function getAllUserDevices(string $userDn) { |
| 581 |
$pdo = $this->getPDO(); |
| 582 |
$statement = $pdo->prepare('select * from ' . $this->getTableName() . ' where userDN = :userDn order by userId,registrationTime'); |
| 583 |
$statement->execute([ |
| 584 |
':userDn' => $userDn |
| 585 |
]); |
| 586 |
$results = $statement->fetchAll(); |
| 587 |
$devices = []; |
| 588 |
foreach ($results as $result) { |
| 589 |
$name = empty($result['name']) ? '' : $result['name']; |
| 590 |
$devices[] = [ |
| 591 |
'dn' => $result['userDN'], |
| 592 |
'credentialId' => $result['credentialId'], |
| 593 |
'lastUseTime' => $result['lastUseTime'], |
| 594 |
'registrationTime' => $result['registrationTime'], |
| 595 |
'name' => $name |
| 596 |
]; |
| 597 |
} |
| 598 |
return $devices; |
| 599 |
} |
| 600 |
|
| 601 |
/** |
| 602 |
* Deletes a single device from the database. |
| 603 |
* |
| 604 |
* @param string $dn user DN |
| 605 |
* @param string $credentialId credential id |
| 606 |
* @return bool deletion was ok |
| 607 |
*/ |
| 608 |
public function deleteDevice(string $dn, string $credentialId) { |
| 609 |
logNewMessage(LOG_NOTICE, 'Delete webauthn device ' . $credentialId . ' of ' . $dn); |
| 610 |
$pdo = $this->getPDO(); |
| 611 |
$statement = $pdo->prepare('delete from ' . $this->getTableName() . ' where userDN = :userDN and credentialId = :credentialId'); |
| 612 |
$statement->execute([ |
| 613 |
':userDN' => $dn, |
| 614 |
':credentialId' => $credentialId |
| 615 |
]); |
| 616 |
return $statement->rowCount() > 0; |
| 617 |
} |
| 618 |
|
| 619 |
/** |
| 620 |
* Updates the device name. |
| 621 |
* |
| 622 |
* @param string $dn user DN |
| 623 |
* @param string $credentialId credential id |
| 624 |
* @param string $name new name |
| 625 |
* @return bool success |
| 626 |
*/ |
| 627 |
public function updateDeviceName(string $dn, string $credentialId, $name) { |
| 628 |
$pdo = $this->getPDO(); |
| 629 |
$statement = $pdo->prepare('update ' . $this->getTableName() . ' set name = :name where userDN = :userDN and credentialId = :credentialId'); |
| 630 |
$statement->execute([ |
| 631 |
':userDN' => $dn, |
| 632 |
':credentialId' => $credentialId, |
| 633 |
':name' => $name |
| 634 |
]); |
| 635 |
return $statement->rowCount() > 0; |
| 636 |
} |
| 637 |
|
| 638 |
/** |
| 639 |
* Returns the PDO. |
| 640 |
* |
| 641 |
* @return PDO PDO |
| 642 |
*/ |
| 643 |
abstract protected function getPDO(): PDO; |
| 644 |
|
| 645 |
/** |
| 646 |
* Checks if the schema needs to be updated. |
| 647 |
*/ |
| 648 |
public function checkSchema(): void { |
| 649 |
try { |
| 650 |
$pdo = $this->getPDO(); |
| 651 |
} |
| 652 |
catch (PDOException $e) { |
| 653 |
logNewMessage(LOG_ERR, 'Unable to connect to config database: ' . $e->getMessage()); |
| 654 |
return; |
| 655 |
} |
| 656 |
// initial schema |
| 657 |
if (!dbTableExists($pdo, $this->getTableName())) { |
| 658 |
$this->createInitialSchema($pdo); |
| 659 |
} |
| 660 |
$this->addNameColumn($pdo); |
| 661 |
$this->addUserDnColumn($pdo); |
| 662 |
} |
| 663 |
|
| 664 |
/** |
| 665 |
* Creates the initial schema. |
| 666 |
* |
| 667 |
* @param PDO $pdo PDO object |
| 668 |
*/ |
| 669 |
public function createInitialSchema(PDO $pdo): void { |
| 670 |
logNewMessage(LOG_DEBUG, 'Creating database table ' . $this->getTableName()); |
| 671 |
$sql = 'create table ' . $this->getTableName() . '(' |
| 672 |
. 'userId TEXT NOT NULL,' |
| 673 |
. 'credentialId TEXT NOT NULL,' |
| 674 |
. 'credentialSource TEXT NOT NULL,' |
| 675 |
. 'registrationTime VARCHAR(11) NOT NULL,' |
| 676 |
. 'lastUseTime VARCHAR(11) NOT NULL,' |
| 677 |
. 'PRIMARY KEY(userId,credentialId)' |
| 678 |
. ');'; |
| 679 |
$pdo->exec($sql); |
| 680 |
} |
| 681 |
|
| 682 |
/** |
| 683 |
* Adds the name column if not existing. |
| 684 |
* |
| 685 |
* @param PDO $pdo PDO |
| 686 |
*/ |
| 687 |
protected function addNameColumn(PDO $pdo): void { |
| 688 |
try { |
| 689 |
$statement = $pdo->query("select * from pragma_table_info('" . $this->getTableName() . "') where name = 'name';"); |
| 690 |
if ($statement === false) { |
| 691 |
throw new PDOException('query failed'); |
| 692 |
} |
| 693 |
$results = $statement->fetchAll(); |
| 694 |
if (empty($results)) { |
| 695 |
$sql = 'alter table ' . $this->getTableName() . ' add column name VARCHAR(255);'; |
| 696 |
logNewMessage(LOG_DEBUG, $sql); |
| 697 |
$pdo->exec($sql); |
| 698 |
} |
| 699 |
} |
| 700 |
catch (PDOException $e) { |
| 701 |
logNewMessage(LOG_ERR, 'Unable to add name column to table: ' . $e->getMessage()); |
| 702 |
} |
| 703 |
} |
| 704 |
|
| 705 |
/** |
| 706 |
* Adds the user DN column if not existing. |
| 707 |
* |
| 708 |
* @param PDO $pdo PDO |
| 709 |
*/ |
| 710 |
protected function addUserDnColumn(PDO $pdo): void { |
| 711 |
try { |
| 712 |
$statement = $pdo->query("select * from pragma_table_info('" . $this->getTableName() . "') where name = 'userDN';"); |
| 713 |
if ($statement === false) { |
| 714 |
throw new PDOException('query failed'); |
| 715 |
} |
| 716 |
$results = $statement->fetchAll(); |
| 717 |
if (empty($results)) { |
| 718 |
$sql = 'alter table ' . $this->getTableName() . ' add column userDN VARCHAR(255);'; |
| 719 |
logNewMessage(LOG_DEBUG, $sql); |
| 720 |
$pdo->exec($sql); |
| 721 |
$sql = 'update ' . $this->getTableName() . ' set userDn = userId;'; |
| 722 |
logNewMessage(LOG_DEBUG, $sql); |
| 723 |
$pdo->exec($sql); |
| 724 |
} |
| 725 |
} |
| 726 |
catch (PDOException $e) { |
| 727 |
logNewMessage(LOG_ERR, 'Unable to add userDN column to table: ' . $e->getMessage()); |
| 728 |
} |
| 729 |
} |
| 730 |
|
| 731 |
/** |
| 732 |
* Exports all entries. |
| 733 |
* |
| 734 |
* @return array<array<string, mixed>> data |
| 735 |
*/ |
| 736 |
public function export(): array { |
| 737 |
$pdo = $this->getPDO(); |
| 738 |
$statement = $pdo->prepare('select * from ' . $this->getTableName()); |
| 739 |
$statement->execute(); |
| 740 |
$dbData = $statement->fetchAll(); |
| 741 |
$data = []; |
| 742 |
foreach ($dbData as $dbRow) { |
| 743 |
$data[] = [ |
| 744 |
'userId' => $dbRow['userId'], |
| 745 |
'credentialId' => $dbRow['credentialId'], |
| 746 |
'credentialSource' => $dbRow['credentialSource'], |
| 747 |
'registrationTime' => $dbRow['registrationTime'], |
| 748 |
'lastUseTime' => $dbRow['lastUseTime'], |
| 749 |
'name' => $dbRow['name'], |
| 750 |
'userDN' => $dbRow['userDN'], |
| 751 |
]; |
| 752 |
} |
| 753 |
return $data; |
| 754 |
} |
| 755 |
|
| 756 |
/** |
| 757 |
* Imports entries from export data. |
| 758 |
* |
| 759 |
* @param null|array<array<string, mixed>> $data export data |
| 760 |
*/ |
| 761 |
public function import($data): void { |
| 762 |
$pdo = $this->getPDO(); |
| 763 |
$statement = $pdo->prepare('delete from ' . $this->getTableName()); |
| 764 |
$statement->execute(); |
| 765 |
if ($data === null) { |
| 766 |
return; |
| 767 |
} |
| 768 |
foreach ($data as $dbRow) { |
| 769 |
$statement = $pdo->prepare('insert into ' . $this->getTableName() . ' (userId, credentialId, credentialSource, registrationTime, lastUseTime, name, userDN) VALUES (?, ?, ?, ?, ?, ?, ?)'); |
| 770 |
$statement->execute([ |
| 771 |
$dbRow['userId'], |
| 772 |
$dbRow['credentialId'], |
| 773 |
$dbRow['credentialSource'], |
| 774 |
$dbRow['registrationTime'], |
| 775 |
$dbRow['lastUseTime'], |
| 776 |
$dbRow['name'], |
| 777 |
$dbRow['userDN'], |
| 778 |
]); |
| 779 |
} |
| 780 |
} |
| 781 |
|
| 782 |
} |
| 783 |
|
| 784 |
/** |
| 785 |
* Credential repository that uses SQLite for data access. |
| 786 |
* |
| 787 |
* @package LAM\LOGIN\WEBAUTHN |
| 788 |
*/ |
| 789 |
class PublicKeyCredentialSourceRepositorySQLite extends PublicKeyCredentialSourceRepositoryBase { |
| 790 |
|
| 791 |
/** |
| 792 |
* Constructor |
| 793 |
*/ |
| 794 |
public function __construct() { |
| 795 |
$this->checkSchema(); |
| 796 |
} |
| 797 |
|
| 798 |
/** |
| 799 |
* {@inheritDoc} |
| 800 |
*/ |
| 801 |
protected function getPDO(): PDO { |
| 802 |
return new PDO($this->getPdoUrl(), null, null, [ |
| 803 |
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION |
| 804 |
]); |
| 805 |
} |
| 806 |
|
| 807 |
/** |
| 808 |
* Returns the database URL. |
| 809 |
* |
| 810 |
* @return string the PDO URL |
| 811 |
*/ |
| 812 |
public function getPdoUrl(): string { |
| 813 |
$fileName = __DIR__ . '/../config/__lam.webauthn.sqlite'; |
| 814 |
if (!file_exists($fileName)) { |
| 815 |
$handle = fopen($fileName, 'w'); |
| 816 |
if ($handle === false) { |
| 817 |
throw new PDOException('Unable to write ' . $fileName); |
| 818 |
} |
| 819 |
fclose($handle); |
| 820 |
chmod($fileName, 0600); |
| 821 |
} |
| 822 |
return 'sqlite:' . $fileName; |
| 823 |
} |
| 824 |
|
| 825 |
} |
| 826 |
|
| 827 |
/** |
| 828 |
* Credential repository that uses a given PDO for data access. |
| 829 |
* |
| 830 |
* @package LAM\LOGIN\WEBAUTHN |
| 831 |
*/ |
| 832 |
class PublicKeyCredentialSourceRepositoryMySql extends PublicKeyCredentialSourceRepositoryBase { |
| 833 |
|
| 834 |
/** @var PDO */ |
| 835 |
private $pdo; |
| 836 |
|
| 837 |
/** |
| 838 |
* Constructor |
| 839 |
* |
| 840 |
* @param PDO $pdo PDO |
| 841 |
*/ |
| 842 |
public function __construct(PDO $pdo) { |
| 843 |
$this->pdo = $pdo; |
| 844 |
$this->checkSchema(); |
| 845 |
} |
| 846 |
|
| 847 |
/** |
| 848 |
* @inheritDoc |
| 849 |
*/ |
| 850 |
protected function getPDO(): PDO { |
| 851 |
return $this->pdo; |
| 852 |
} |
| 853 |
|
| 854 |
/** |
| 855 |
* @inheritDoc |
| 856 |
*/ |
| 857 |
protected function getTableName(): string { |
| 858 |
return 'webauthn'; |
| 859 |
} |
| 860 |
|
| 861 |
/** |
| 862 |
* Creates the initial schema. |
| 863 |
* |
| 864 |
* @param PDO $pdo PDO object |
| 865 |
*/ |
| 866 |
public function createInitialSchema(PDO $pdo): void { |
| 867 |
logNewMessage(LOG_DEBUG, 'Creating database table ' . $this->getTableName()); |
| 868 |
$sql = 'create table ' . $this->getTableName() . '(' |
| 869 |
// 350 because primary key length is max 3072 bytes and each character can have 4 bytes |
| 870 |
. 'userId VARCHAR(350) NOT NULL,' |
| 871 |
. 'credentialId VARCHAR(350) NOT NULL,' |
| 872 |
. 'credentialSource TEXT NOT NULL,' |
| 873 |
. 'registrationTime VARCHAR(11) NOT NULL,' |
| 874 |
. 'lastUseTime VARCHAR(11) NOT NULL,' |
| 875 |
. 'name VARCHAR(255),' |
| 876 |
. 'PRIMARY KEY(userId,credentialId)' |
| 877 |
. ');'; |
| 878 |
$pdo->exec($sql); |
| 879 |
$sql = 'insert into ' . ConfigurationDatabase::TABLE_SCHEMA_VERSIONS . ' (name, version) VALUES ("webauthn", 1);'; |
| 880 |
$pdo->exec($sql); |
| 881 |
} |
| 882 |
|
| 883 |
/** |
| 884 |
* Adds the name column if not existing. |
| 885 |
* |
| 886 |
* @param PDO $pdo PDO |
| 887 |
*/ |
| 888 |
protected function addNameColumn(PDO $pdo): void { |
| 889 |
// added via initial schema |
| 890 |
} |
| 891 |
|
| 892 |
/** |
| 893 |
* {@inheritDoc} |
| 894 |
*/ |
| 895 |
protected function addUserDnColumn(PDO $pdo): void { |
| 896 |
try { |
| 897 |
$statement = $pdo->query("show columns from " . $this->getTableName() . " like 'userDN';"); |
| 898 |
if ($statement === false) { |
| 899 |
throw new PDOException('query failed'); |
| 900 |
} |
| 901 |
$results = $statement->fetchAll(); |
| 902 |
if (empty($results)) { |
| 903 |
$sql = 'alter table ' . $this->getTableName() . ' add column userDN VARCHAR(255);'; |
| 904 |
logNewMessage(LOG_DEBUG, $sql); |
| 905 |
$pdo->exec($sql); |
| 906 |
$sql = 'update ' . $this->getTableName() . ' set userDn = userId;'; |
| 907 |
logNewMessage(LOG_DEBUG, $sql); |
| 908 |
$pdo->exec($sql); |
| 909 |
} |
| 910 |
} |
| 911 |
catch (PDOException $e) { |
| 912 |
logNewMessage(LOG_ERR, 'Unable to add userDN column to table: ' . $e->getMessage()); |
| 913 |
} |
| 914 |
} |
| 915 |
|
| 916 |
} |
| 917 |
|
| 918 |
|