Passed
Push — master ( b33c2e...bab30e )
by Tim
02:08
created

WebAuthnRegistrationEvent::der2pem()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 5
rs 10
c 3
b 0
f 0
1
<?php
2
3
namespace SimpleSAML\Module\webauthn\WebAuthn;
4
5
use Cose\Key\Ec2Key;
6
use SimpleSAML\Logger;
7
use SimpleSAML\Utils;
8
9
/**
10
 * FIDO2/WebAuthn Authentication Processing filter
11
 *
12
 * Filter for registering or authenticating with a FIDO2/WebAuthn token after
13
 * having authenticated with the primary authsource.
14
 *
15
 * @author Stefan Winter <[email protected]>
16
 * @package SimpleSAMLphp
17
 */
18
class WebAuthnRegistrationEvent extends WebAuthnAbstractEvent
19
{
20
    /**
21
     * Public key algorithm supported. This is -7 - ECDSA with curve P-256
22
     */
23
    public const PK_ALGORITHM = "-7";
24
    public const AAGUID_ASSURANCE_LEVEL_NONE = 0;
25
    public const AAGUID_ASSURANCE_LEVEL_SELF = 1;
26
    public const AAGUID_ASSURANCE_LEVEL_BASIC = 2;
27
    public const AAGUID_ASSURANCE_LEVEL_ATTCA = 3;
28
29
    /**
30
     * the AAGUID of the newly registered authenticator
31
     * @var string
32
     */
33
    protected $AAGUID;
34
35
    /**
36
     * how sure are we about the AAGUID?
37
     * @var int
38
     */
39
    protected $AAGUIDAssurance;
40
41
    /**
42
     * An array of known hardware tokens
43
     *
44
     * @var AAGUID
45
     */
46
    protected $AAGUIDDictionary;
47
48
    /**
49
     * Initialize the event object.
50
     *
51
     * Validates and parses the configuration.
52
     *
53
     * @param string $pubkeyCredType  PublicKeyCredential.type
54
     * @param string $scope           the scope of the event
55
     * @param string $challenge       the challenge which was used to trigger this event
56
     * @param string $idpEntityId     the entity ID of our IdP
57
     * @param string $attestationData the attestation data CBOR blob
58
     * @param string $responseId      the response ID
59
     * @param string $clientDataJSON  the client data JSON string which is present in all types of events
60
     * @param bool $debugMode         print debugging statements?
61
     */
62
    public function __construct(
63
        string $pubkeyCredType,
64
        string $scope,
65
        string $challenge,
66
        string $idpEntityId,
67
        string $attestationData,
68
        string $responseId,
69
        string $clientDataJSON,
70
        bool $debugMode = false
71
    ) {
72
        $this->debugBuffer .= "attestationData raw: " . $attestationData . "<br/>";
73
        /**
74
         * §7.1 STEP 9 : CBOR decode attestationData.
75
         */
76
        $attestationArray = $this->cborDecode($attestationData);
77
        $authData = $attestationArray['authData'];
78
        $this->eventType = "REG";
79
        parent::__construct($pubkeyCredType, $scope, $challenge, $idpEntityId, $authData, $clientDataJSON, $debugMode);
80
81
        $this->AAGUIDDictionary = AAGUID::getInstance();
82
83
        // this function extracts the public key
84
        $this->validateAttestedCredentialData(substr($authData, 37), $responseId);
85
        // this function may need the public key to have been previously extracted
86
        $this->validateAttestationData($attestationData);
87
        // the following function sets the credential properties
88
        $this->debugBuffer .= "Attestation Data (bin2hex): " . bin2hex(substr($authData, 37)) . "<br/>";
89
    }
90
91
92
    /**
93
     * Validate the incoming attestation data CBOR blob and return the embedded authData
94
     * @param string $attestationData
95
     * @return void
96
     */
97
    private function validateAttestationData(string $attestationData): void
98
    {
99
        /**
100
         * STEP 9 of the validation procedure in § 7.1 of the spec: CBOR-decode the attestationObject
101
         */
102
        $attestationArray = $this->cborDecode($attestationData);
103
        $this->debugBuffer .= "<pre>";
104
        $this->debugBuffer .= print_r($attestationArray, true);
105
        $this->debugBuffer .= "</pre>";
106
107
        /**
108
         * STEP 15 of the validation procedure in § 7.1 of the spec: verify attStmt values
109
         */
110
        switch ($attestationArray['fmt']) {
111
            case "none":
112
                $this->validateAttestationFormatNone($attestationArray);
113
                break;
114
            case "packed":
115
                $this->validateAttestationFormatPacked($attestationArray);
116
                break;
117
            case "fido-u2f":
118
                $this->validateAttestationFormatFidoU2F($attestationArray);
119
                break;
120
            case "android-safetynet":
121
                $this->validateAttestationFormatAndroidSafetyNet($attestationArray);
122
                break;
123
            case "tpm":
124
            case "android-key":
125
                $this->fail("Attestation format " . $attestationArray['fmt'] . " validation not supported right now.");
126
                break;
127
            default:
128
                $this->fail("Unknown attestation format.");
129
                break;
130
        }
131
    }
132
133
134
    /**
135
     * @param array $attestationArray
136
     * @return void
137
     */
138
    private function validateAttestationFormatNone(array $attestationArray): void
139
    {
140
        // § 8.7 of the spec
141
        /**
142
         * § 7.1 Step 16 && §8.7 Verification Procedure: stmt must be an empty array
143
         * § 7.1 Step 17+18 are a NOOP if the format was "none" (which is acceptable as per this RPs policy)
144
         */
145
        if (count($attestationArray['attStmt']) === 0) {
146
            $this->pass("Attestation format and statement as expected, and no attestation authorities to retrieve.");
147
            $this->AAGUIDAssurance = self::AAGUID_ASSURANCE_LEVEL_NONE;
148
            return;
149
        } else {
150
            $this->fail("Non-empty attestation authorities are not expected with 'attestationFormat = none'.");
151
        }
152
    }
153
154
155
    /**
156
     * @param array $attestationArray
157
     * @return void
158
     */
159
    private function validateAttestationFormatPacked(array $attestationArray): void
160
    {
161
        $stmtDecoded = $attestationArray['attStmt'];
162
        $this->debugBuffer .= "AttStmt: " . print_r($stmtDecoded, true) . "<br/>";
163
        /**
164
         * §7.1 Step 16: attestation is either done with x5c or ecdaa.
165
         */
166
        if (isset($stmtDecoded['x5c'])) {
167
            $this->validateAttestationFormatPackedX5C($attestationArray);
168
        } elseif (isset($stmtDecoded['ecdaa'])) {
169
            $this->fail("ecdaa attestation not supported right now.");
170
        } else {
171
            // if we are still here, we are in the "self" type.
172
            $this->validateAttestationFormatPackedSelf($attestationArray);
173
        }
174
    }
175
176
177
    /**
178
     * @param array $attestationArray
179
     * @return void
180
     */
181
    private function validateAttestationFormatPackedX5C(array $attestationArray): void
182
    {
183
        $stmtDecoded = $attestationArray['attStmt'];
184
        /**
185
         * §8.2 Step 2: check x5c attestation
186
         */
187
        $sigdata = $attestationArray['authData'] . $this->clientDataHash;
188
        $keyResource = openssl_pkey_get_public(Utils\Crypto::der2pem($stmtDecoded['x5c'][0]));
189
        if ($keyResource === false) {
190
            $this->fail("Unable to construct public key resource from PEM.");
191
        }
192
        /**
193
         * §8.2 Step 2 Bullet 1: check signature
194
         */
195
        if (openssl_verify($sigdata, $stmtDecoded['sig'], $keyResource, OPENSSL_ALGO_SHA256) !== 1) {
196
            $this->fail("x5c attestation failed.");
197
        }
198
        $this->pass("x5c sig check passed.");
199
        // still need to perform sanity checks on the attestation certificate
200
        /**
201
         * §8.2 Step 2 Bullet 2: check certificate properties listed in §8.2.1
202
         */
203
        $certProps = openssl_x509_parse(Utils\Crypto::der2pem($stmtDecoded['x5c'][0]));
204
        $this->debugBuffer .= "Attestation Certificate:" . print_r($certProps, true) . "<br/>";
205
        if (
206
            $certProps['version'] !== 2 || /** §8.2.1 Bullet 1 */
207
            $certProps['subject']['OU'] !== "Authenticator Attestation" || /** §8.2.1 Bullet 2 [Subject-OU] */
208
            !isset($certProps['subject']['CN']) || /** §8.2.1 Bullet 2 [Subject-CN] */
209
            !isset($certProps['extensions']['basicConstraints']) ||
210
            strstr("CA:FALSE", $certProps['extensions']['basicConstraints']) === false /** §8.2.1 Bullet 4 */
211
        ) {
212
            $this->fail("Attestation certificate properties are no good.");
213
        }
214
215
        if ($this->AAGUIDDictionary->hasToken($this->AAGUID)) {
216
            $token = $this->AAGUIDDictionary->get($this->AAGUID);
217
            if (
218
                $certProps['subject']['O'] !== $token['O'] ||
219
                // §8.2.1 Bullet 2 [Subject-O]
220
                $certProps['subject']['C'] !== $token['C']
221
                // §8.2ubject-C]
222
            ) {
223
                $this->fail("AAGUID does not match vendor data.");
224
            }
225
            if ($token['multi'] === true) { // need to check the OID
226
                if (!isset($certProps['extensions']['1.3.6.1.4.1.45724.1.1.4']) || empty($certProps['extensions']['1.3.6.1.4.1.45724.1.1.4'])) { /** §8.2.1 Bullet 3 */
227
                    $this->fail(
228
                        "This vendor uses one cert for multiple authenticator model attestations, but lacks the AAGUID OID."
229
                    );
230
                }
231
                /**
232
                 * §8.2 Step 2 Bullet 3: compare AAGUID values
233
                 */
234
                $AAGUIDFromOid = substr(bin2hex($certProps['extensions']['1.3.6.1.4.1.45724.1.1.4']), 4);
235
                $this->debugBuffer .= "AAGUID from OID = $AAGUIDFromOid<br/>";
236
                if (strtolower($AAGUIDFromOid) !== strtolower($this->AAGUID)) {
237
                    $this->fail("AAGUID mismatch between attestation certificate and attestation statement.");
238
                }
239
            }
240
            // we would need to verify the attestation certificate against a known-good
241
            // root CA certificate to get more than basic
242
            /*
243
             * §7.1 Step 17 is to look at $token['RootPEMs']
244
             */
245
            /*
246
             * §7.1 Step 18 is skipped, and we unconditionally return "only" Basic.
247
             */
248
            $this->AAGUIDAssurance = self::AAGUID_ASSURANCE_LEVEL_BASIC;
249
        } else {
250
            $this->warn("Unknown authenticator model found: " . $this->AAGUID . ".");
251
            // unable to verify all cert properties, so this is not enough for BASIC.
252
            // but it's our own fault, we should add the device to our DB.
253
            $this->AAGUIDAssurance = self::AAGUID_ASSURANCE_LEVEL_SELF;
254
        }
255
        $this->pass("x5c attestation passed.");
256
        return;
257
    }
258
259
260
    /**
261
     * @param array $attestationArray
262
     * @return void
263
     */
264
    private function validateAttestationFormatPackedSelf(array $attestationArray): void
265
    {
266
        $stmtDecoded = $attestationArray['attStmt'];
267
        /**
268
         * §8.2 Step 4 Bullet 1: check algorithm
269
         */
270
        if ($stmtDecoded['alg'] !== self::PK_ALGORITHM) {
271
            $this->fail("Unexpected algorithm type in packed basic attestation: " . $stmtDecoded['alg'] . ".");
272
        }
273
        $keyObject = new Ec2Key($this->cborDecode(hex2bin($this->credential)));
274
        $keyResource = openssl_pkey_get_public($keyObject->asPEM());
275
        if ($keyResource === false) {
276
            $this->fail("Unable to construct public key resource from PEM.");
277
        }
278
        $sigdata = $attestationArray['authData'] . $this->clientDataHash;
279
        /**
280
         * §8.2 Step 4 Bullet 2: verify signature
281
         */
282
        if (openssl_verify($sigdata, $stmtDecoded['sig'], $keyResource, OPENSSL_ALGO_SHA256) === 1) {
283
            $this->pass("Self-Attestation veried.");
284
            /**
285
             * §8.2 Step 4 Bullet 3: return Self level
286
             */
287
            $this->AAGUIDAssurance = self::AAGUID_ASSURANCE_LEVEL_SELF;
288
        } else {
289
            $this->fail("Self-Attestation failed.");
290
        }
291
    }
292
293
294
    /**
295
     * support legacy U2F tokens
296
     *
297
     * @param array $attestationData the incoming attestation data
298
     * @return void
299
     */
300
    private function validateAttestationFormatFidoU2F(array $attestationData): void
301
    {
302
        /**
303
         * §8.6 Verification Step 1 is a NOOP: if we're here, the attStmt was
304
         * already successfully CBOR decoded
305
         */
306
        $stmtDecoded = $attestationData['attStmt'];
307
        if (!isset($stmtDecoded['x5c'])) {
308
            $this->fail("FIDO U2F attestation needs to have the 'x5c' key");
309
        }
310
        /**
311
         * §8.6 Verification Step 2: extract attCert and sanity check it
312
         */
313
        if (count($stmtDecoded['x5c']) !== 1) {
314
            $this->fail("FIDO U2F attestation requires 'x5c' to have only exactly one key.");
315
        }
316
        $attCert = Utils\Crypto::der2pem($stmtDecoded['x5c'][0]);
317
        $key = openssl_pkey_get_public($attCert);
318
        $keyProps = openssl_pkey_get_details($key);
319
        if (!isset($keyProps['ec']['curve_name']) || $keyProps['ec']['curve_name'] !== "prime256v1") {
320
            $this->fail("FIDO U2F attestation public key is not P-256!");
321
        }
322
        /**
323
         * §8.6 Verification Step 3 is a NOOP as these properties are already
324
         * available as class members:
325
         *
326
         * $this->rpIdHash;
327
         * $this->credentialId;
328
         * $this->credential;
329
         */
330
        /**
331
         * §8.6 Verification Step 4: encode the public key in ANSI X9.62 format
332
         */
333
        if (
334
            isset($this->credential[-2]) &&
335
            strlen($this->credential[-2]) === 32 &&
336
            isset($this->credential[-3]) &&
337
            strlen($this->credential[-3]) === 32
338
        ) {
339
            $publicKeyU2F = chr(4) . $this->credential[-2] . $this->credential[-3];
340
        } else {
341
            $publicKeyU2F = false;
342
            $this->fail("FIDO U2F attestation: the public key is not as expected.");
343
        }
344
        /**
345
         * §8.6 Verification Step 5: create verificationData
346
         *
347
         * @psalm-var string $publicKeyU2F
348
         */
349
        $verificationData = chr(0) . $this->rpIdHash . $this->clientDataHash . $this->credentialId . $publicKeyU2F;
350
        /**
351
         * §8.6 Verification Step 6: verify signature
352
         */
353
        if (openssl_verify($verificationData, $stmtDecoded['sig'], $attCert, OPENSSL_ALGO_SHA256) !== 1) {
354
            $this->fail("FIDO U2F Attestation verification failed.");
355
        } else {
356
            $this->pass("Successfully verified FIDO U2F signature.");
357
        }
358
        /**
359
         * §8.6 Verification Step 7: not performed, this is optional as per spec
360
         */
361
        /**
362
         * §8.6 Verification Step 8: so we always settle for "Basic"
363
         */
364
        $this->AAGUIDAssurance = self::AAGUID_ASSURANCE_LEVEL_BASIC;
365
    }
366
367
368
    /**
369
     * support Android authenticators (fingerprint etc.)
370
     *
371
     * @param array $attestationData the incoming attestation data
372
     * @return void
373
     */
374
    private function validateAttestationFormatAndroidSafetyNet(array $attestationData): void
0 ignored issues
show
Unused Code introduced by
The parameter $attestationData is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

374
    private function validateAttestationFormatAndroidSafetyNet(/** @scrutinizer ignore-unused */ array $attestationData): void

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
375
    {
376
    }
377
378
379
    /**
380
     * The registration contains the actual credential. This function parses it.
381
     * @param string $attData    the attestation data binary blob
382
     * @param string $responseId the response ID
383
     * @return void
384
     */
385
    private function validateAttestedCredentialData(string $attData, string $responseId): void
386
    {
387
        $aaguid = substr($attData, 0, 16);
388
        $credIdLenBytes = substr($attData, 16, 2);
389
        $credIdLen = intval(bin2hex($credIdLenBytes), 16);
390
        $credId = substr($attData, 18, $credIdLen);
391
        $this->debugBuffer .= "AAGUID (hex) = " . bin2hex($aaguid) . "</br/>";
392
        $this->AAGUID = bin2hex($aaguid);
393
        $this->debugBuffer .= "Length Raw = " . bin2hex($credIdLenBytes) . "<br/>";
394
        $this->debugBuffer .= "Credential ID Length (decimal) = " . $credIdLen . "<br/>";
395
        $this->debugBuffer .= "Credential ID (hex) = " . bin2hex($credId) . "<br/>";
396
        if (bin2hex(WebAuthnAbstractEvent::base64urlDecode($responseId)) === bin2hex($credId)) {
397
            $this->pass("Credential IDs in authenticator response and in attestation data match.");
398
        } else {
399
            $this->fail(
400
                "Mismatch of credentialId (" . bin2hex($credId) . ") vs. response ID (" .
401
                bin2hex(WebAuthnAbstractEvent::base64urlDecode($responseId)) . ")."
402
            );
403
        }
404
        // so far so good. Now extract the actual public key from its COSE
405
        // encoding.
406
        // finding out the number of bytes to CBOR decode appears non-trivial.
407
        // The simple case is if no ED is present as the CBOR data then goes to
408
        // the end of the byte sequence.
409
        // Since we made sure above that no ED is in the sequence, take the rest
410
        // of the sequence in its entirety.
411
        $pubKeyCBOR = substr($attData, 18 + $credIdLen);
412
        $arrayPK = $this->cborDecode($pubKeyCBOR);
413
        $this->debugBuffer .= "pubKey in canonical form: <pre>" . print_r($arrayPK, true) . "</pre>";
414
        /**
415
         * STEP 13 of the validation procedure in § 7.1 of the spec: is the algorithm the expected one?
416
         */
417
        if ($arrayPK['3'] === self::PK_ALGORITHM) { // we requested -7, so want to see it here
418
            $this->pass("Public Key Algorithm is the expected one (-7, ECDSA).");
419
        } else {
420
            $this->fail("Public Key Algorithm mismatch!");
421
        }
422
        $this->credentialId = bin2hex($credId);
423
        $this->credential = bin2hex($pubKeyCBOR);
424
    }
425
426
427
    /**
428
     * @return string
429
     */
430
    public function getAAGUID(): string
431
    {
432
        return $this->AAGUID;
433
    }
434
}
435