summaryrefslogtreecommitdiffstats
path: root/dom/webauthn/tests/test_webauthn_loopback.html
blob: 70905739a0932d14cd3963f3f78752552e84b4ae (plain)
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
<!DOCTYPE html>
<meta charset=utf-8>
<head>
  <title>Full-run test for MakeCredential/GetAssertion for W3C Web Authentication</title>
  <script src="/tests/SimpleTest/SimpleTest.js"></script>
  <script type="text/javascript" src="u2futil.js"></script>
  <script type="text/javascript" src="pkijs/common.js"></script>
  <script type="text/javascript" src="pkijs/asn1.js"></script>
  <script type="text/javascript" src="pkijs/x509_schema.js"></script>
  <script type="text/javascript" src="pkijs/x509_simpl.js"></script>
  <script type="text/javascript" src="cbor.js"></script>
  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css" />
</head>
<body>

<h1>Full-run test for MakeCredential/GetAssertion for W3C Web Authentication</h1>
<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=1309284">Mozilla Bug 1309284</a>

<script class="testbody" type="text/javascript">
"use strict";

add_task(async function() {
  // This test intentionally compares items to themselves.
  /* eslint-disable no-self-compare */
  await SpecialPowers.pushPrefEnv({"set": [["security.webauth.webauthn_testing_allow_direct_attestation", true]]});
  await addVirtualAuthenticator();
  is(navigator.authentication, undefined, "navigator.authentication does not exist any longer");
  isnot(navigator.credentials, undefined, "Credential Management API endpoint must exist");
  isnot(navigator.credentials.create, undefined, "CredentialManagement create API endpoint must exist");
  isnot(navigator.credentials.get, undefined, "CredentialManagement get API endpoint must exist");

  let credm = navigator.credentials;

  let gCredentialChallenge = new Uint8Array(16);
  window.crypto.getRandomValues(gCredentialChallenge);
  let gAssertionChallenge = new Uint8Array(16);
  window.crypto.getRandomValues(gAssertionChallenge);

  await testMakeCredential();

  async function decodeCreatedCredential(aCredInfo) {
    /* PublicKeyCredential : Credential
       - rawId: Key Handle buffer pulled from U2F Register() Response
       - id: Key Handle buffer in base64url form, should == rawId
       - type: Literal 'public-key'
       - response : AuthenticatorAttestationResponse : AuthenticatorResponse
         - attestationObject: CBOR object
         - clientDataJSON: serialized JSON
    */

    is(aCredInfo.type, "public-key", "Credential type must be public-key")

    ok(aCredInfo.rawId.byteLength > 0, "Key ID exists");
    is(aCredInfo.id, bytesToBase64UrlSafe(aCredInfo.rawId), "Encoded Key ID and Raw Key ID match");

    ok(aCredInfo.rawId === aCredInfo.rawId, "PublicKeyCredential.RawID is SameObject");
    ok(aCredInfo.response === aCredInfo.response, "PublicKeyCredential.Response is SameObject");
    ok(aCredInfo.response.clientDataJSON === aCredInfo.response.clientDataJSON, "PublicKeyCredential.Response.ClientDataJSON is SameObject");
    ok(aCredInfo.response.attestationObject === aCredInfo.response.attestationObject, "PublicKeyCredential.Response.AttestationObject is SameObject");

    let clientData = JSON.parse(buffer2string(aCredInfo.response.clientDataJSON));
    is(clientData.challenge, bytesToBase64UrlSafe(gCredentialChallenge), "Challenge is correct");
    is(clientData.origin, window.location.origin, "Origin is correct");
    is(clientData.type, "webauthn.create", "Type is correct");

    let attestationObj = await webAuthnDecodeCBORAttestation(aCredInfo.response.attestationObject);
    // Make sure the RP ID hash matches what we calculate.
    let calculatedRpIdHash = await crypto.subtle.digest("SHA-256", string2buffer(document.domain));
    let calcHashStr = bytesToBase64UrlSafe(new Uint8Array(calculatedRpIdHash));
    let providedHashStr = bytesToBase64UrlSafe(new Uint8Array(attestationObj.authDataObj.rpIdHash));
    is(calcHashStr, providedHashStr, "Calculated RP ID hash must match what the browser derived.");
    ok(true, attestationObj.authDataObj.flags[0] & (flag_TUP | flag_AT));
    ok(attestationObj.authDataObj.flags[0] & (flag_TUP | flag_AT) == (flag_TUP | flag_AT),
       "User presence and Attestation Object flags must be set");
    aCredInfo.clientDataObj = clientData;
    aCredInfo.publicKeyHandle = attestationObj.authDataObj.publicKeyHandle;
    aCredInfo.attestationObject = attestationObj.authDataObj.attestationAuthData;
    return aCredInfo;
  }

  async function checkAssertionAndSigValid(aPublicKey, aAssertion) {
    /* PublicKeyCredential : Credential
       - rawId: ID of Credential from AllowList that succeeded
       - id: Key Handle buffer in base64url form, should == rawId
       - type: Literal 'public-key'
       - response : AuthenticatorAssertionResponse : AuthenticatorResponse
         - clientDataJSON: serialized JSON
         - authenticatorData: RP ID Hash || U2F Sign() Response
         - signature: U2F Sign() Response
    */
    is(aAssertion.type, "public-key", "Credential type must be public-key")
    ok(aAssertion.rawId.byteLength > 0, "Key ID exists");
    is(aAssertion.id, bytesToBase64UrlSafe(new Uint8Array(aAssertion.rawId)), "Encoded Key ID and Raw Key ID match");
    ok(aAssertion.response.authenticatorData === aAssertion.response.authenticatorData, "AuthenticatorAssertionResponse.AuthenticatorData is SameObject");
    ok(aAssertion.response.authenticatorData instanceof ArrayBuffer, "AuthenticatorAssertionResponse.AuthenticatorData is an ArrayBuffer");
    ok(aAssertion.response.signature === aAssertion.response.signature, "AuthenticatorAssertionResponse.Signature is SameObject");
    ok(aAssertion.response.signature instanceof ArrayBuffer, "AuthenticatorAssertionResponse.Signature is an ArrayBuffer");
    ok(aAssertion.response.userHandle === null, "AuthenticatorAssertionResponse.UserHandle is null for u2f authenticators");

    ok(aAssertion.response.authenticatorData.byteLength > 0, "Authenticator data exists");
    let clientData = JSON.parse(buffer2string(aAssertion.response.clientDataJSON));
    is(clientData.challenge, bytesToBase64UrlSafe(gAssertionChallenge), "Challenge is correct");
    is(clientData.origin, window.location.origin, "Origin is correct");
    is(clientData.type, "webauthn.get", "Type is correct");

    let attestation = await webAuthnDecodeAuthDataArray(aAssertion.response.authenticatorData);
    ok(new Uint8Array(attestation.flags)[0] & flag_TUP == flag_TUP, "User presence flag must be set");
    is(attestation.counter.byteLength, 4, "Counter must be 4 bytes");
    let params = await deriveAppAndChallengeParam(window.location.host, aAssertion.response.clientDataJSON, attestation);
    console.log(params);
    console.log("ClientData buffer: ", hexEncode(aAssertion.response.clientDataJSON));
    console.log("ClientDataHash: ", hexEncode(params.challengeParam));
    let signedData = await assembleSignedData(params.appParam, params.attestation.flags,
                                              params.attestation.counter, params.challengeParam);
    console.log(aPublicKey, signedData, aAssertion.response.signature);
    return await verifySignature(aPublicKey, signedData, aAssertion.response.signature);
  }

  async function testMakeCredential() {
    let rp = {id: document.domain, name: "none"};
    let user = {id: new Uint8Array(), name: "none", displayName: "none"};
    let param = {type: "public-key", alg: cose_alg_ECDSA_w_SHA256};
    let makeCredentialOptions = {
      rp,
      user,
      challenge: gCredentialChallenge,
      pubKeyCredParams: [param],
      attestation: "direct"
    };
    let credential = await credm.create({publicKey: makeCredentialOptions})
    let decodedCredential = await decodeCreatedCredential(credential);
    await testMakeDuplicate(decodedCredential);
  }

  async function testMakeDuplicate(aCredInfo) {
    let rp = {id: document.domain, name: "none"};
    let user = {id: new Uint8Array(), name: "none", displayName: "none"};
    let param = {type: "public-key", alg: cose_alg_ECDSA_w_SHA256};
    let makeCredentialOptions = {
      rp,
      user,
      challenge: gCredentialChallenge,
      pubKeyCredParams: [param],
      excludeCredentials: [{type: "public-key", id: new Uint8Array(aCredInfo.rawId),
                     transports: ["usb"]}]
    };
    await credm.create({publicKey: makeCredentialOptions})
    .then(function() {
      // We should have errored here!
      ok(false, "The excludeList didn't stop a duplicate being created!");
    }).catch((aReason) => {
      ok(aReason.toString().startsWith("InvalidStateError"), "Expect InvalidStateError, got " + aReason);
    });
    await testAssertion(aCredInfo);
  }

  async function testAssertion(aCredInfo) {
    let newCredential = {
      type: "public-key",
      id: new Uint8Array(aCredInfo.rawId),
      transports: ["usb"],
    }

    let publicKeyCredentialRequestOptions = {
      challenge: gAssertionChallenge,
      timeout: 5000, // the minimum timeout is actually 15 seconds
      rpId: document.domain,
      allowCredentials: [newCredential]
    };
    let assertion = await credm.get({publicKey: publicKeyCredentialRequestOptions});
    let sigVerifyResult = await checkAssertionAndSigValid(aCredInfo.publicKeyHandle, assertion);
    ok(sigVerifyResult, "Signing signature verified");
  }
});

</script>

</body>
</html>