Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
3.33% covered (danger)
3.33%
9 / 270
9.09% covered (danger)
9.09%
2 / 22
CRAP
0.00% covered (danger)
0.00%
0 / 1
WebAuthnAuthenticator
3.33% covered (danger)
3.33%
9 / 270
9.09% covered (danger)
9.09%
2 / 22
2688.01
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 isEnabled
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getRequest
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 canAuthenticate
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
6
 canRegister
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 startAuthentication
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 startPasswordlessAuthentication
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 startAuthenticationInternal
0.00% covered (danger)
0.00%
0 / 16
0.00% covered (danger)
0.00%
0 / 1
12
 determineUser
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
20
 continueAuthentication
0.00% covered (danger)
0.00%
0 / 34
0.00% covered (danger)
0.00%
0 / 1
20
 startRegistration
0.00% covered (danger)
0.00%
0 / 13
0.00% covered (danger)
0.00%
0 / 1
6
 continueRegistration
0.00% covered (danger)
0.00%
0 / 51
0.00% covered (danger)
0.00%
0 / 1
72
 getChallengeFromCredential
0.00% covered (danger)
0.00%
0 / 7
0.00% covered (danger)
0.00%
0 / 1
2
 addPendingRequest
0.00% covered (danger)
0.00%
0 / 9
0.00% covered (danger)
0.00%
0 / 1
2
 clearPendingRequests
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getPendingRequests
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
12
 getPendingRequestWithChallenge
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
2
 filterExpiredRequests
0.00% covered (danger)
0.00%
0 / 5
0.00% covered (danger)
0.00%
0 / 1
2
 getAuthInfo
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
42
 getRegisterInfo
0.00% covered (danger)
0.00%
0 / 55
0.00% covered (danger)
0.00%
0 / 1
12
 getServerId
75.00% covered (warning)
75.00%
6 / 8
0.00% covered (danger)
0.00%
0 / 1
4.25
 getServerName
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
12
1<?php
2declare( strict_types=1 );
3
4/**
5 * @license GPL-2.0-or-later
6 */
7
8namespace MediaWiki\Extension\OATHAuth;
9
10use Cose\Algorithms;
11use Exception;
12use MediaWiki\Auth\AuthManager;
13use MediaWiki\Config\ServiceOptions;
14use MediaWiki\Extension\OATHAuth\HTMLForm\KeySessionStorageTrait;
15use MediaWiki\Extension\OATHAuth\Key\WebAuthnKey;
16use MediaWiki\Extension\OATHAuth\Module\RecoveryCodes;
17use MediaWiki\Extension\OATHAuth\Module\WebAuthn;
18use MediaWiki\MainConfigNames;
19use MediaWiki\Request\WebRequest;
20use MediaWiki\Status\Status;
21use MediaWiki\User\UserFactory;
22use MediaWiki\Utils\UrlUtils;
23use MediaWiki\WikiMap\WikiMap;
24use Psr\Log\LoggerInterface;
25use RuntimeException;
26use Throwable;
27use Webauthn\AuthenticatorAssertionResponse;
28use Webauthn\AuthenticatorSelectionCriteria;
29use Webauthn\PublicKeyCredential;
30use Webauthn\PublicKeyCredentialCreationOptions;
31use Webauthn\PublicKeyCredentialDescriptor;
32use Webauthn\PublicKeyCredentialOptions;
33use Webauthn\PublicKeyCredentialParameters;
34use Webauthn\PublicKeyCredentialRequestOptions;
35use Webauthn\PublicKeyCredentialRpEntity;
36use Webauthn\PublicKeyCredentialUserEntity;
37
38/**
39 * This class serves as an authentication/registration
40 * proxy, connecting the users to their keys and carrying out
41 * the authentication process
42 */
43class WebAuthnAuthenticator {
44    use KeySessionStorageTrait;
45
46    private const string SESSION_KEY = 'webauthn_session_data';
47
48    /** 5 minutes in ms */
49    private const int CLIENT_ACTION_TIMEOUT = 300000;
50
51    private const int MAX_ACTIVE_CHALLENGES = 5;
52
53    /** @internal Only public for service wiring usage. */
54    public const CONSTRUCTOR_OPTIONS = [
55        MainConfigNames::Sitename,
56        MainConfigNames::Server,
57        'WebAuthnRelyingPartyID',
58        'WebAuthnRelyingPartyName',
59    ];
60
61    private ?string $serverId;
62
63    public function __construct(
64        private readonly ServiceOptions $options,
65        private readonly OATHUserRepository $userRepo,
66        private readonly WebAuthn $module,
67        private readonly RecoveryCodes $recoveryCodesModule,
68        private readonly OATHAuthLogger $oathLogger,
69        private readonly LoggerInterface $logger,
70        private readonly AuthManager $authManager,
71        private readonly UrlUtils $urlUtils,
72        private readonly UserFactory $userFactory,
73    ) {
74        $this->options->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
75        $this->serverId = $this->getServerId();
76    }
77
78    public function isEnabled( OATHUser $user ): bool {
79        return $this->module->isEnabled( $user );
80    }
81
82    public function getRequest(): WebRequest {
83        return $this->authManager->getRequest();
84    }
85
86    public function canAuthenticate( OATHUser $user ): Status {
87        if ( !$this->isEnabled( $user ) ) {
88            return Status::newFatal(
89                'oathauth-webauthn-error-module-not-enabled',
90                $this->module->getName(),
91                $user->getUser()->getName()
92            );
93        }
94
95        return Status::newGood();
96    }
97
98    public function canRegister( OATHUser $user ): Status {
99        if ( $this->userFactory->newFromUserIdentity( $user->getUser() )->isAllowed( 'oathauth-enable' ) ) {
100            return Status::newGood();
101        }
102
103        return Status::newFatal(
104            'oathauth-webauthn-error-cannot-register',
105            $user->getUser()->getName()
106        );
107    }
108
109    public function startAuthentication( OATHUser $user ): Status {
110        return $this->startAuthenticationInternal( $user, false );
111    }
112
113    /**
114     * Initiate a new passwordless authentication session.
115     *
116     * This returns a credential request that is not specific to any given user, unless $user is set.
117     * @param ?OATHUser $user If set, make the credential request specific to this user's keys.
118     *   Only use this when reauthenticating a user who is already logged in.
119     */
120    public function startPasswordlessAuthentication( ?OATHUser $user = null ): Status {
121        return $this->startAuthenticationInternal( $user, true );
122    }
123
124    private function startAuthenticationInternal( ?OATHUser $user, bool $userVerificationRequired ): Status {
125        if ( $user ) {
126            $canAuthenticate = $this->canAuthenticate( $user );
127            if ( !$canAuthenticate->isGood() ) {
128                $this->logger->info(
129                    "User {user} cannot authenticate using WebAuthn", [
130                        'user' => $user->getUser()->getName(),
131                    ]
132                );
133                return $canAuthenticate;
134            }
135        }
136        $authInfo = $this->getAuthInfo( $user, $userVerificationRequired );
137        $this->addPendingRequest( $authInfo );
138
139        $serializer = ( new WebAuthnSerializerFactory( WebAuthnKey::getAttestationSupportManager() ) )->create();
140
141        return Status::newGood( [
142            'json' => $serializer->serialize( $authInfo, 'json' ),
143            'raw' => $authInfo
144        ] );
145    }
146
147    public function determineUser( string $credential ): ?OATHUser {
148        $serializer = ( new WebAuthnSerializerFactory( WebAuthnKey::getAttestationSupportManager() ) )->create();
149        try {
150            $publicKeyCredential = $serializer->deserialize(
151                $credential,
152                PublicKeyCredential::class,
153                'json',
154            );
155        } catch ( Throwable ) {
156            return null;
157        }
158        $response = $publicKeyCredential->response;
159        if ( !$response instanceof AuthenticatorAssertionResponse ) {
160            return null;
161        }
162        $userHandle = $response->userHandle;
163        if ( $userHandle === null ) {
164            return null;
165        }
166        return $this->userRepo->findByUserHandle( $userHandle );
167    }
168
169    public function continueAuthentication(
170        OATHUser $user,
171        string $credential
172    ): Status {
173        $canAuthenticate = $this->canAuthenticate( $user );
174        if ( !$canAuthenticate->isGood() ) {
175            $this->logger->warning(
176                "User {user} lost ability to authenticate using WebAuthn mid-request", [
177                    'user' => $user->getUser()->getName(),
178                ]
179            );
180            return $canAuthenticate;
181        }
182
183        $request = $this->getPendingRequestWithChallenge(
184            PublicKeyCredentialRequestOptions::class,
185            $this->getChallengeFromCredential( $credential )
186        );
187        $this->clearPendingRequests( PublicKeyCredentialRequestOptions::class );
188        if ( $request === null ) {
189            $this->oathLogger->logFailedVerification( $user->getUser() );
190            return Status::newFatal( 'oathauth-webauthn-error-verification-failed' );
191        }
192
193        $verificationData = [
194            'authInfo' => $request,
195            'credential' => $credential
196        ];
197
198        // TODO: At some point we may start preventing login using known bad/deprecated algorithms etc in keys.
199        // Will need to handle the exception similar to continueRegistration
200        if ( $this->module->verify( $user, $verificationData ) ) {
201            $this->logger->info(
202                "User {user} logged in using WebAuthn", [
203                    'user' => $user->getUser()->getName(),
204                ]
205            );
206            return Status::newGood( $user );
207        }
208        $this->logger->warning(
209            'WebAuthn login failed for user {user}', [
210                'user' => $user->getUser()->getName(),
211            ]
212        );
213
214        $this->oathLogger->logFailedVerification( $user->getUser() );
215
216        return Status::newFatal( 'oathauth-webauthn-error-verification-failed' );
217    }
218
219    public function startRegistration( OATHUser $user, bool $passkeyMode = false ): Status {
220        $canRegister = $this->canRegister( $user );
221        if ( !$canRegister->isGood() ) {
222            $this->logger->info(
223                "User {user} cannot register a WebAuthn credential"
224            );
225            return $canRegister;
226        }
227        $registerInfo = $this->getRegisterInfo( $user, $passkeyMode );
228        $this->addPendingRequest( $registerInfo );
229
230        $serializer = ( new WebAuthnSerializerFactory( WebAuthnKey::getAttestationSupportManager() ) )->create();
231
232        return Status::newGood( [
233            'json' => $serializer->serialize( $registerInfo, 'json' ),
234            'raw' => $registerInfo
235        ] );
236    }
237
238    public function continueRegistration(
239        OATHUser $user, string $credential, string $friendlyName = '', bool $passkeyMode = false
240    ): Status {
241        $canRegister = $this->canRegister( $user );
242        if ( !$canRegister->isGood() ) {
243            $this->logger->warning(
244                "User {user} lost ability to register using WebAuthn ability mid-request",
245                [
246                    'user' => $user->getUser()->getName(),
247                ]
248            );
249            return $canRegister;
250        }
251
252        $registerInfo = $this->getPendingRequestWithChallenge(
253            PublicKeyCredentialCreationOptions::class,
254            $this->getChallengeFromCredential( $credential )
255        );
256        if ( $registerInfo === null ) {
257            return Status::newFatal( 'oathauth-webauthn-error-registration-failed' );
258        }
259
260        $key = $this->module->newKey();
261        try {
262            $registered = $key->verifyRegistration(
263                $friendlyName,
264                $credential,
265                $registerInfo,
266                $user
267            );
268
269            if ( $registered ) {
270                if ( $passkeyMode ) {
271                    // Passwordless (passkey) credentials must use User Verification.
272                    // Only mark the key as passwordless-capable if the credential was
273                    // actually registered with UV; otherwise refuse to register it.
274                    if ( !$key->wasUserVerified() ) {
275                        throw new RuntimeException(
276                            'Passwordless registration requires user verification, ' .
277                            'but the credential was registered without it'
278                        );
279                    }
280                    $key->setPasswordlessSupport( true );
281                }
282                $this->userRepo->createKey(
283                    $user,
284                    $this->module,
285                    $key->jsonSerialize(),
286                    $this->getRequest()->getIP()
287                );
288
289                $this->recoveryCodesModule->ensureExistence(
290                    $user,
291                    $this->getKeyDataInSession( 'RecoveryCodeKeys' )
292                );
293
294                $this->clearPendingRequests( PublicKeyCredentialCreationOptions::class );
295
296                return Status::newGood();
297            }
298        } catch ( DeprecatedKeyException $ex ) {
299            return Status::newFatal( $ex->getMessage() );
300        } catch ( Exception $ex ) {
301            $this->logger->warning( 'WebAuthn registration failed due to: {message}', [
302                'message' => $ex->getMessage(),
303                'exception' => $ex,
304                'user' => $user->getUser()->getName(),
305            ] );
306        }
307        return Status::newFatal( 'oathauth-webauthn-error-registration-failed' );
308    }
309
310    private function getChallengeFromCredential( string $credential ): string {
311        $serializer = ( new WebAuthnSerializerFactory( WebAuthnKey::getAttestationSupportManager() ) )->create();
312        $publicKeyCredential = $serializer->deserialize(
313            $credential,
314            PublicKeyCredential::class,
315            'json',
316        );
317        return $publicKeyCredential->response->clientDataJSON->challenge;
318    }
319
320    private function addPendingRequest( PublicKeyCredentialOptions $data ) {
321        $serializer = ( new WebAuthnSerializerFactory( WebAuthnKey::getAttestationSupportManager() ) )->create();
322        $sessionKey = self::SESSION_KEY . '_' . $data::class;
323        $requests = $this->getRequest()->getSession()->getSecret( $sessionKey ) ?? [];
324        $requests[] = [
325            'json' => $serializer->serialize( $data, 'json' ),
326            'expires' => time() + ceil( $data->timeout / 1000 )
327        ];
328        $requests = $this->filterExpiredRequests( $requests );
329        $this->getRequest()->getSession()->setSecret( $sessionKey, $requests );
330    }
331
332    private function clearPendingRequests( string $returnClass ) {
333        $this->getRequest()->getSession()->remove( self::SESSION_KEY . '_' . $returnClass );
334    }
335
336    /**
337     * @template T of PublicKeyCredentialOptions
338     * @param class-string<T> $returnClass
339     * @return T[]
340     */
341    private function getPendingRequests( string $returnClass ): array {
342        $sessionKey = self::SESSION_KEY . '_' . $returnClass;
343        $requests = $this->getRequest()->getSession()->getSecret( $sessionKey );
344        if ( $requests === null ) {
345            return [];
346        }
347        $filteredRequests = $this->filterExpiredRequests( $requests );
348        if ( count( $filteredRequests ) < count( $requests ) ) {
349            $this->getRequest()->getSession()->setSecret( $sessionKey, $filteredRequests );
350        }
351        $serializer = ( new WebAuthnSerializerFactory( WebAuthnKey::getAttestationSupportManager() ) )->create();
352        return array_map(
353            static fn ( $r ) => $serializer->deserialize( $r['json'], $returnClass, 'json' ),
354            $filteredRequests
355        );
356    }
357
358    /**
359     * @template T of PublicKeyCredentialOptions
360     * @param class-string<T> $returnClass
361     * @param string $challenge
362     * @return T|null
363     */
364    private function getPendingRequestWithChallenge( string $returnClass, string $challenge ) {
365        $requests = $this->getPendingRequests( $returnClass );
366        return array_find( $requests, static fn ( $request ) => $request->challenge === $challenge );
367    }
368
369    private function filterExpiredRequests( array $requests ): array {
370        $now = time();
371        return array_slice(
372            array_filter( $requests, static fn ( $r ) => $r['expires'] >= $now ),
373            -self::MAX_ACTIVE_CHALLENGES
374        );
375    }
376
377    /**
378     * Information to be sent to the client to start the authentication process
379     */
380    private function getAuthInfo( ?OATHUser $user, bool $userVerificationRequired ): PublicKeyCredentialRequestOptions {
381        $keys = $user ? WebAuthn::getWebAuthnKeys( $user ) : [];
382        $credentialDescriptors = [];
383        foreach ( $keys as $key ) {
384            // If user verification is required, skip keys that don't support UV
385            if ( $userVerificationRequired && !$key->supportsPasswordlessLogin() ) {
386                continue;
387            }
388            $credentialDescriptors[] = new PublicKeyCredentialDescriptor(
389                $key->getType(),
390                $key->getAttestedCredentialData()->credentialId,
391                $key->getTransports()
392            );
393        }
394
395        return PublicKeyCredentialRequestOptions::create(
396            random_bytes( 32 ),
397            $this->serverId,
398            $credentialDescriptors,
399            $userVerificationRequired ?
400                PublicKeyCredentialRequestOptions::USER_VERIFICATION_REQUIREMENT_REQUIRED :
401                PublicKeyCredentialRequestOptions::USER_VERIFICATION_REQUIREMENT_PREFERRED,
402            self::CLIENT_ACTION_TIMEOUT
403        );
404    }
405
406    /**
407     * Information to be sent to the client to start the registration process
408     */
409    private function getRegisterInfo(
410        OATHUser $user,
411        bool $passkeyMode = false
412    ): PublicKeyCredentialCreationOptions {
413        $serverName = $this->getServerName();
414        $rpEntity = new PublicKeyCredentialRpEntity( $serverName, $this->serverId );
415
416        // Exclude all already registered keys for user
417        /** @var WebAuthnKey[] $webauthnKeys */
418        $webauthnKeys = $user->getKeysForModule( WebAuthn::MODULE_NAME );
419        '@phan-var WebAuthnKey[] $webauthnKeys';
420        $excludedPublicKeyDescriptors = array_map( static fn ( $key ) => new PublicKeyCredentialDescriptor(
421            PublicKeyCredentialDescriptor::CREDENTIAL_TYPE_PUBLIC_KEY,
422            $key->getAttestedCredentialData()->credentialId
423        ), $webauthnKeys );
424
425        $mwUser = $this->userFactory->newFromUserIdentity( $user->getUser() );
426        $userHandle = $user->getUserHandle() ?? random_bytes( 64 );
427        $realName = $mwUser->getRealName() ?: $mwUser->getName();
428        $userEntity = new PublicKeyCredentialUserEntity(
429            $mwUser->getName(),
430            $userHandle,
431            $realName
432        );
433
434        $publicKeyCredParametersList = [
435            new PublicKeyCredentialParameters(
436                'public-key',
437                Algorithms::COSE_ALGORITHM_ES256
438            ),
439            new PublicKeyCredentialParameters(
440                'public-key',
441                Algorithms::COSE_ALGORITHM_ES512
442            ),
443            new PublicKeyCredentialParameters(
444                'public-key',
445                Algorithms::COSE_ALGORITHM_EDDSA
446            ),
447            new PublicKeyCredentialParameters(
448                'public-key',
449                Algorithms::COSE_ALGORITHM_RS256
450            ),
451            new PublicKeyCredentialParameters(
452                'public-key',
453                Algorithms::COSE_ALGORITHM_RS512
454            ),
455        ];
456
457        if ( $passkeyMode ) {
458            $authSelectorCriteria = AuthenticatorSelectionCriteria::create(
459                userVerification: AuthenticatorSelectionCriteria::USER_VERIFICATION_REQUIREMENT_REQUIRED,
460                residentKey: AuthenticatorSelectionCriteria::RESIDENT_KEY_REQUIREMENT_REQUIRED,
461            );
462        } else {
463            $authSelectorCriteria = AuthenticatorSelectionCriteria::create(
464                authenticatorAttachment: AuthenticatorSelectionCriteria::AUTHENTICATOR_ATTACHMENT_CROSS_PLATFORM,
465            );
466        }
467
468        return PublicKeyCredentialCreationOptions::create(
469            $rpEntity,
470            $userEntity,
471            random_bytes( 32 ),
472            $publicKeyCredParametersList,
473            $authSelectorCriteria,
474            PublicKeyCredentialCreationOptions::ATTESTATION_CONVEYANCE_PREFERENCE_NONE,
475            $excludedPublicKeyDescriptors,
476            self::CLIENT_ACTION_TIMEOUT
477        );
478    }
479
480    /**
481     * Get identifier for this server
482     */
483    private function getServerId(): ?string {
484        $rpId = $this->options->get( 'WebAuthnRelyingPartyID' );
485        if ( $rpId && is_string( $rpId ) ) {
486            return $rpId;
487        }
488
489        $server = $this->options->get( MainConfigNames::Server );
490        $serverBits = $this->urlUtils->parse( $server );
491        if ( $serverBits !== null ) {
492            return $serverBits['host'];
493        }
494
495        return null;
496    }
497
498    /**
499     * Get the name for this server
500     */
501    private function getServerName(): string {
502        $serverName = $this->options->get( 'WebAuthnRelyingPartyName' );
503        if ( $serverName && is_string( $serverName ) ) {
504            return $serverName;
505        }
506        return $this->options->get( MainConfigNames::Sitename ) ?? WikiMap::getCurrentWikiId();
507    }
508}