File: WebAuthn.php

package info (click to toggle)
phpmyadmin 4%3A5.2.2-really%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 140,312 kB
  • sloc: javascript: 228,447; php: 166,904; xml: 17,847; sql: 504; sh: 275; makefile: 209; python: 205
file content (246 lines) | stat: -rw-r--r-- 8,276 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
<?php

declare(strict_types=1);

namespace PhpMyAdmin\Plugins\TwoFactor;

use PhpMyAdmin\Plugins\TwoFactorPlugin;
use PhpMyAdmin\ResponseRenderer;
use PhpMyAdmin\TwoFactor;
use PhpMyAdmin\WebAuthn\CustomServer;
use PhpMyAdmin\WebAuthn\Server;
use PhpMyAdmin\WebAuthn\WebauthnLibServer;
use SodiumException;
use Throwable;
use Webauthn\Server as WebauthnServer;
use Webmozart\Assert\Assert;

use function __;
use function class_exists;
use function is_array;
use function is_string;
use function json_decode;
use function json_encode;
use function random_bytes;
use function sodium_base642bin;
use function sodium_bin2base64;

use const SODIUM_BASE64_VARIANT_ORIGINAL;
use const SODIUM_BASE64_VARIANT_URLSAFE_NO_PADDING;

/**
 * Two-factor authentication plugin for the WebAuthn/FIDO2 protocol.
 */
class WebAuthn extends TwoFactorPlugin
{
    /** @var string */
    public static $id = 'WebAuthn';

    /** @var Server */
    private $server;

    public function __construct(TwoFactor $twofactor)
    {
        parent::__construct($twofactor);
        if (
            ! isset($this->twofactor->config['settings']['userHandle'])
            || ! is_string($this->twofactor->config['settings']['userHandle'])
        ) {
            $this->twofactor->config['settings']['userHandle'] = '';
        }

        if (
            ! isset($this->twofactor->config['settings']['credentials'])
            || ! is_array($this->twofactor->config['settings']['credentials'])
        ) {
            $this->twofactor->config['settings']['credentials'] = [];
        }

        $this->server = $this->createServer();
    }

    private function createServer(): Server
    {
        return class_exists(WebauthnServer::class) ? new WebauthnLibServer($this->twofactor) : new CustomServer();
    }

    public function setServer(Server $server): void
    {
        $this->server = $server;
    }

    public function render(): string
    {
        $request = $GLOBALS['request'];
        $userHandle = sodium_base642bin($this->getUserHandleFromSettings(), SODIUM_BASE64_VARIANT_URLSAFE_NO_PADDING);
        $requestOptions = $this->server->getCredentialRequestOptions(
            $this->twofactor->user,
            $userHandle,
            $request->getUri()->getHost(),
            $this->getAllowedCredentials()
        );
        $requestOptionsEncoded = json_encode($requestOptions);
        $_SESSION['WebAuthnCredentialRequestOptions'] = $requestOptionsEncoded;
        $this->loadScripts();

        return $this->template->render(
            'login/twofactor/webauthn_request',
            ['request_options' => $requestOptionsEncoded]
        );
    }

    public function check(): bool
    {
        $this->provided = false;
        $request = $GLOBALS['request'];
        $authenticatorResponse = $request->getParsedBodyParam('webauthn_request_response', '');
        if ($authenticatorResponse === '' || ! isset($_SESSION['WebAuthnCredentialRequestOptions'])) {
            return false;
        }

        $this->provided = true;

        /** @var mixed $credentialRequestOptions */
        $credentialRequestOptions = $_SESSION['WebAuthnCredentialRequestOptions'];
        unset($_SESSION['WebAuthnCredentialRequestOptions']);

        try {
            Assert::stringNotEmpty($authenticatorResponse);
            Assert::stringNotEmpty($credentialRequestOptions);
            $requestOptions = json_decode($credentialRequestOptions, true);
            Assert::isArray($requestOptions);
            Assert::keyExists($requestOptions, 'challenge');
            Assert::stringNotEmpty($requestOptions['challenge']);
            $this->server->parseAndValidateAssertionResponse(
                $authenticatorResponse,
                $this->getAllowedCredentials(),
                $requestOptions['challenge'],
                $request
            );
        } catch (Throwable $exception) {
            $this->message = $exception->getMessage();

            return false;
        }

        return true;
    }

    public function setup(): string
    {
        $request = $GLOBALS['request'];
        $userId = sodium_bin2base64(random_bytes(32), SODIUM_BASE64_VARIANT_ORIGINAL);
        $host = $request->getUri()->getHost();
        $creationOptions = $this->server->getCredentialCreationOptions($this->twofactor->user, $userId, $host);
        $creationOptionsEncoded = json_encode($creationOptions);
        $_SESSION['WebAuthnCredentialCreationOptions'] = $creationOptionsEncoded;
        $this->loadScripts();

        return $this->template->render(
            'login/twofactor/webauthn_creation',
            ['creation_options' => $creationOptionsEncoded]
        );
    }

    public function configure(): bool
    {
        $this->provided = false;
        $request = $GLOBALS['request'];
        $authenticatorResponse = $request->getParsedBodyParam('webauthn_creation_response', '');
        if ($authenticatorResponse === '' || ! isset($_SESSION['WebAuthnCredentialCreationOptions'])) {
            return false;
        }

        $this->provided = true;

        /** @var mixed $credentialCreationOptions */
        $credentialCreationOptions = $_SESSION['WebAuthnCredentialCreationOptions'];
        unset($_SESSION['WebAuthnCredentialCreationOptions']);

        try {
            Assert::stringNotEmpty($authenticatorResponse);
            Assert::stringNotEmpty($credentialCreationOptions);
            $credential = $this->server->parseAndValidateAttestationResponse(
                $authenticatorResponse,
                $credentialCreationOptions,
                $request
            );
            $this->saveCredential($credential);
        } catch (Throwable $exception) {
            $this->message = $exception->getMessage();

            return false;
        }

        return true;
    }

    public static function getName(): string
    {
        return __('Hardware Security Key (WebAuthn/FIDO2)');
    }

    public static function getDescription(): string
    {
        return __(
            'Provides authentication using hardware security tokens supporting the WebAuthn/FIDO2 protocol,'
            . ' such as a YubiKey.'
        );
    }

    private function loadScripts(): void
    {
        $response = ResponseRenderer::getInstance();
        $scripts = $response->getHeader()->getScripts();
        $scripts->addFile('webauthn.js');
    }

    /**
     * @psalm-return list<array{id: non-empty-string, type: non-empty-string}>
     */
    private function getAllowedCredentials(): array
    {
        $allowedCredentials = [];
        /** @psalm-var array<array<string, mixed>> $credentials */
        $credentials = $this->twofactor->config['settings']['credentials'];
        foreach ($credentials as $credential) {
            if (
                ! is_string($credential['publicKeyCredentialId']) || $credential['publicKeyCredentialId'] === ''
                || ! is_string($credential['type']) || $credential['type'] === ''
            ) {
                continue;
            }

            $allowedCredentials[] = ['type' => $credential['type'], 'id' => $credential['publicKeyCredentialId']];
        }

        return $allowedCredentials;
    }

    /**
     * @psalm-param mixed[] $credential
     *
     * @throws SodiumException
     */
    private function saveCredential(array $credential): void
    {
        Assert::keyExists($credential, 'publicKeyCredentialId');
        Assert::stringNotEmpty($credential['publicKeyCredentialId']);
        Assert::keyExists($credential, 'userHandle');
        Assert::string($credential['userHandle']);
        Assert::isArray($this->twofactor->config['settings']['credentials']);
        $id = sodium_bin2base64(
            sodium_base642bin($credential['publicKeyCredentialId'], SODIUM_BASE64_VARIANT_URLSAFE_NO_PADDING),
            SODIUM_BASE64_VARIANT_ORIGINAL
        );
        $this->twofactor->config['settings']['credentials'][$id] = $credential;
        $this->twofactor->config['settings']['userHandle'] = $credential['userHandle'];
    }

    private function getUserHandleFromSettings(): string
    {
        Assert::string($this->twofactor->config['settings']['userHandle']);

        return $this->twofactor->config['settings']['userHandle'];
    }
}