summaryrefslogtreecommitdiffstats
path: root/dom/webauthn/tests/test_webauthn_loopback.html
blob: 5eb5df5c8c3475f8fa7e4db3192ff8bbc9b9fae2 (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
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
<!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";

// Execute the full-scope test
SimpleTest.waitForExplicitFinish();

SpecialPowers.pushPrefEnv({"set": [["security.webauth.webauthn_testing_allow_direct_attestation", true]]},
function() {
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);

  testMakeCredential();

  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");

  return webAuthnDecodeCBORAttestation(aCredInfo.response.attestationObject)
  .then(function(aAttestationObj) {
    // Make sure the RP ID hash matches what we calculate.
    return crypto.subtle.digest("SHA-256", string2buffer(document.domain))
    .then(function(calculatedRpIdHash) {
      let calcHashStr = bytesToBase64UrlSafe(new Uint8Array(calculatedRpIdHash));
      let providedHashStr = bytesToBase64UrlSafe(new Uint8Array(aAttestationObj.authDataObj.rpIdHash));

      is(calcHashStr, providedHashStr,
         "Calculated RP ID hash must match what the browser derived.");
      return Promise.resolve(aAttestationObj);
    });
  })
  .then(function(aAttestationObj) {
    ok(aAttestationObj.authDataObj.flags == (flag_TUP | flag_AT),
       "User presence and Attestation Object must be the only flags set");

    aCredInfo.clientDataObj = clientData;
    aCredInfo.publicKeyHandle = aAttestationObj.authDataObj.publicKeyHandle;
    aCredInfo.attestationObject = aAttestationObj.authDataObj.attestationAuthData;
    return aCredInfo;
  });
}

  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");

  return webAuthnDecodeAuthDataArray(aAssertion.response.authenticatorData)
  .then(function(aAttestation) {
    ok(new Uint8Array(aAttestation.flags) == flag_TUP, "User presence must be the only flag set");
    is(aAttestation.counter.byteLength, 4, "Counter must be 4 bytes");
    return deriveAppAndChallengeParam(window.location.host, aAssertion.response.clientDataJSON, aAttestation)
  })
  .then(function(aParams) {
    console.log(aParams);
    console.log("ClientData buffer: ", hexEncode(aAssertion.response.clientDataJSON));
    console.log("ClientDataHash: ", hexEncode(aParams.challengeParam));
    return assembleSignedData(aParams.appParam, aParams.attestation.flags,
                              aParams.attestation.counter, aParams.challengeParam);
  })
  .then(function(aSignedData) {
    console.log(aPublicKey, aSignedData, aAssertion.response.signature);
    return verifySignature(aPublicKey, aSignedData, aAssertion.response.signature);
  })
}

  function testMakeCredential() {
  let rp = {id: document.domain, name: "none", icon: "none"};
  let user = {id: new Uint8Array(), name: "none", icon: "none", displayName: "none"};
  let param = {type: "public-key", alg: cose_alg_ECDSA_w_SHA256};
  let makeCredentialOptions = {
    rp,
    user,
    challenge: gCredentialChallenge,
    pubKeyCredParams: [param],
    attestation: "direct"
  };
    credm.create({publicKey: makeCredentialOptions})
  .then(decodeCreatedCredential)
  .then(testMakeDuplicate)
  .catch(function(aReason) {
    ok(false, aReason);
      SimpleTest.finish();
  });
}

  function testMakeDuplicate(aCredInfo) {
  let rp = {id: document.domain, name: "none", icon: "none"};
  let user = {id: new Uint8Array(), name: "none", icon: "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"]}]
  };
    credm.create({publicKey: makeCredentialOptions})
  .then(function() {
    // We should have errored here!
    ok(false, "The excludeList didn't stop a duplicate being created!");
      SimpleTest.finish();
  })
  .catch(function(aReason) {
    ok(aReason.toString().startsWith("InvalidStateError"), "Expect InvalidStateError, got " + aReason);
    testAssertion(aCredInfo);
  });
}

  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]
  };
    credm.get({publicKey: publicKeyCredentialRequestOptions})
  .then(function(aAssertion) {
    /* Pass along the pubKey. */
    return checkAssertionAndSigValid(aCredInfo.publicKeyHandle, aAssertion);
  })
  .then(function(aSigVerifyResult) {
    ok(aSigVerifyResult, "Signing signature verified");
      SimpleTest.finish();
  })
  .catch(function(reason) {
    ok(false, "Signing signature invalid: " + reason);
      SimpleTest.finish();
  });
}
});

</script>

</body>
</html>