Bug 1380529 - Use CBOR for the Create Credential WebAuthn call (2/3) r=ttaubert
authorJ.C. Jones <jjones@mozilla.com>
Thu, 13 Jul 2017 18:12:50 -0700
changeset 418941 070367125549ebd34250ffc4078784890ebea619
parent 418940 45b4405c24ca291e24053c708c4620a9bda73438
child 418942 1f66a39c19f1e8889c7fb802001b4838436f85dd
push id7566
push usermtabara@mozilla.com
push dateWed, 02 Aug 2017 08:25:16 +0000
treeherdermozilla-beta@86913f512c3c [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersttaubert
bugs1380529
milestone56.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1380529 - Use CBOR for the Create Credential WebAuthn call (2/3) r=ttaubert The WebAuthn Create Credential method should encode its results using CBOR; this patch changes to that format. The CBOR formats for the U2F data are specified in [1][2] The attestation data format is in [3] The high-level layout is in [4] [1] https://w3c.github.io/webauthn/#generating-an-attestation-object [2] https://w3c.github.io/webauthn/#fido-u2f-attestation [3] https://w3c.github.io/webauthn/#sec-attestation-data [4] https://w3c.github.io/webauthn/#sctn-attestation MozReview-Commit-ID: BYoFCJSxlLt
dom/webauthn/WebAuthnCBORUtil.cpp
dom/webauthn/WebAuthnCBORUtil.h
dom/webauthn/WebAuthnManager.cpp
dom/webauthn/WebAuthnUtil.cpp
dom/webauthn/WebAuthnUtil.h
dom/webauthn/moz.build
dom/webauthn/tests/cbor/cbor.js
dom/webauthn/tests/mochitest.ini
dom/webauthn/tests/test_webauthn_loopback.html
dom/webauthn/tests/u2futil.js
new file mode 100644
--- /dev/null
+++ b/dom/webauthn/WebAuthnCBORUtil.cpp
@@ -0,0 +1,105 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim:set ts=2 sw=2 sts=2 et cindent: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this file,
+ * You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#include "cbor-cpp/src/cbor.h"
+#include "mozilla/dom/WebAuthnCBORUtil.h"
+#include "mozilla/dom/WebAuthnUtil.h"
+
+namespace mozilla {
+namespace dom {
+
+nsresult
+CBOREncodePublicKeyObj(const CryptoBuffer& aPubKeyBuf,
+                       /* out */ CryptoBuffer& aPubKeyObj)
+{
+  mozilla::dom::CryptoBuffer xBuf, yBuf;
+  nsresult rv = U2FDecomposeECKey(aPubKeyBuf, xBuf, yBuf);
+  if (NS_FAILED(rv)) {
+    return rv;
+  }
+
+  /*
+  Public Key Object, encoded in CBOR (description is CDDL)
+
+  pubKey = $pubKeyFmt
+
+  pubKeyFmt /= eccPubKey
+  eccPubKey = { alg: eccAlgName, x: biguint, y: biguint }
+  eccAlgName = "ES256" / "ES384" / "ES512"
+  */
+  cbor::output_dynamic cborPubKeyOut;
+  cbor::encoder encoder(cborPubKeyOut);
+  encoder.write_map(3);
+  {
+    encoder.write_string("alg");
+    encoder.write_string(JWK_ALG_ECDSA_P_256); // Always ES256 for U2F
+
+    encoder.write_string("x");
+    encoder.write_bytes(xBuf.Elements(), xBuf.Length());
+
+    encoder.write_string("y");
+    encoder.write_bytes(yBuf.Elements(), yBuf.Length());
+  }
+
+  if (!aPubKeyObj.Assign(cborPubKeyOut.data(), cborPubKeyOut.size())) {
+    return NS_ERROR_OUT_OF_MEMORY;
+  }
+  return NS_OK;
+}
+
+nsresult
+CBOREncodeAttestationObj(const CryptoBuffer& aAuthDataBuf,
+                         const CryptoBuffer& aAttestationCertBuf,
+                         const CryptoBuffer& aSignatureBuf,
+                         /* out */ CryptoBuffer& aAttestationObj)
+{
+  /*
+  Attestation Object, encoded in CBOR (description is CDDL)
+
+  attObj = {
+              authData: bytes,
+              $$attStmtType
+           }
+  $$attStmtType //= (
+                        fmt: "fido-u2f",
+                        attStmt: u2fStmtFormat
+                    )
+  u2fStmtFormat = {
+                      x5c: [ attestnCert: bytes, * (caCert: bytes) ],
+                      sig: bytes
+                  }
+  */
+  cbor::output_dynamic cborAttOut;
+  cbor::encoder encoder(cborAttOut);
+  encoder.write_map(3);
+  {
+    encoder.write_string("authData");
+    encoder.write_bytes(aAuthDataBuf.Elements(), aAuthDataBuf.Length());
+
+    encoder.write_string("fmt");
+    encoder.write_string("fido-u2f");
+
+    encoder.write_string("attStmt");
+    encoder.write_map(2);
+    {
+      encoder.write_string("x5c");
+      // U2F wire protocol can only deliver 1 certificate, so it's never a chain
+      encoder.write_array(1);
+      encoder.write_bytes(aAttestationCertBuf.Elements(), aAttestationCertBuf.Length());
+
+      encoder.write_string("sig");
+      encoder.write_bytes(aSignatureBuf.Elements(), aSignatureBuf.Length());
+    }
+  }
+
+  if (!aAttestationObj.Assign(cborAttOut.data(), cborAttOut.size())) {
+    return NS_ERROR_OUT_OF_MEMORY;
+  }
+  return NS_OK;
+}
+
+}
+}
new file mode 100644
--- /dev/null
+++ b/dom/webauthn/WebAuthnCBORUtil.h
@@ -0,0 +1,32 @@
+/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim:set ts=2 sw=2 sts=2 et cindent: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+#ifndef mozilla_dom_WebAuthnCBORUtil_h
+#define mozilla_dom_WebAuthnCBORUtil_h
+
+/*
+ * Serialize and deserialize CBOR data formats for WebAuthn
+ */
+
+#include "mozilla/dom/CryptoBuffer.h"
+
+namespace mozilla {
+namespace dom {
+
+nsresult
+CBOREncodePublicKeyObj(const CryptoBuffer& aPubKeyBuf,
+                       /* out */ CryptoBuffer& aPubKeyObj);
+
+nsresult
+CBOREncodeAttestationObj(const CryptoBuffer& aAuthDataBuf,
+                         const CryptoBuffer& aAttestationCertBuf,
+                         const CryptoBuffer& aSignatureBuf,
+                         /* out */ CryptoBuffer& aAttestationObj);
+
+} // namespace dom
+} // namespace mozilla
+
+#endif // mozilla_dom_WebAuthnCBORUtil_h
--- a/dom/webauthn/WebAuthnManager.cpp
+++ b/dom/webauthn/WebAuthnManager.cpp
@@ -7,30 +7,38 @@
 #include "hasht.h"
 #include "nsICryptoHash.h"
 #include "nsNetCID.h"
 #include "nsNetUtil.h" // Used by WD-05 compat support (Remove in Bug 1381126)
 #include "nsThreadUtils.h"
 #include "mozilla/ClearOnShutdown.h"
 #include "mozilla/dom/AuthenticatorAttestationResponse.h"
 #include "mozilla/dom/Promise.h"
+#include "mozilla/dom/WebAuthnCBORUtil.h"
 #include "mozilla/dom/WebAuthnManager.h"
 #include "mozilla/dom/WebAuthnUtil.h"
 #include "mozilla/dom/PWebAuthnTransaction.h"
 #include "mozilla/dom/WebAuthnTransactionChild.h"
 #include "mozilla/dom/WebCryptoCommon.h"
 #include "mozilla/ipc/PBackgroundChild.h"
 #include "mozilla/ipc/BackgroundChild.h"
 
 using namespace mozilla::ipc;
 
 namespace mozilla {
 namespace dom {
 
 /***********************************************************************
+ * Protocol Constants
+ **********************************************************************/
+
+const uint8_t FLAG_TUP = 0x01; // Test of User Presence required
+const uint8_t FLAG_AT = 0x40; // Authenticator Data is provided
+
+/***********************************************************************
  * Statics
  **********************************************************************/
 
 namespace {
 StaticRefPtr<WebAuthnManager> gWebAuthnManager;
 static mozilla::LazyLogModule gWebAuthnManagerLog("webauthnmanager");
 }
 
@@ -649,32 +657,45 @@ WebAuthnManager::GetAssertion(nsPIDOMWin
 void
 WebAuthnManager::FinishMakeCredential(nsTArray<uint8_t>& aRegBuffer)
 {
   MOZ_ASSERT(mTransactionPromise);
   MOZ_ASSERT(mInfo.isSome());
 
   CryptoBuffer regData;
   if (NS_WARN_IF(!regData.Assign(aRegBuffer.Elements(), aRegBuffer.Length()))) {
-    mTransactionPromise->MaybeReject(NS_ERROR_OUT_OF_MEMORY);
+    Cancel(NS_ERROR_OUT_OF_MEMORY);
     return;
   }
 
+  mozilla::dom::CryptoBuffer aaguidBuf;
+  if (NS_WARN_IF(!aaguidBuf.SetCapacity(16, mozilla::fallible))) {
+    Cancel(NS_ERROR_OUT_OF_MEMORY);
+    return;
+  }
+  // TODO: Adjust the AAGUID from all zeroes in Bug 1381575 (if needed)
+  // See https://github.com/w3c/webauthn/issues/506
+  for (int i=0; i<16; i++) {
+    aaguidBuf.AppendElement(0x00, mozilla::fallible);
+  }
+
   // Decompose the U2F registration packet
   CryptoBuffer pubKeyBuf;
   CryptoBuffer keyHandleBuf;
   CryptoBuffer attestationCertBuf;
   CryptoBuffer signatureBuf;
 
+  // Only handles attestation cert chains of length=1.
   nsresult rv = U2FDecomposeRegistrationResponse(regData, pubKeyBuf, keyHandleBuf,
                                                  attestationCertBuf, signatureBuf);
   if (NS_WARN_IF(NS_FAILED(rv))) {
     Cancel(rv);
     return;
   }
+  MOZ_ASSERT(keyHandleBuf.Length() <= 0xFFFF);
 
   CryptoBuffer clientDataBuf;
   if (!clientDataBuf.Assign(mClientData.ref())) {
     Cancel(NS_ERROR_OUT_OF_MEMORY);
     return;
   }
 
   CryptoBuffer rpIdHashBuf;
@@ -686,23 +707,74 @@ WebAuthnManager::FinishMakeCredential(ns
   CryptoBuffer authenticatorDataBuf;
   rv = U2FAssembleAuthenticatorData(authenticatorDataBuf, rpIdHashBuf,
                                     signatureBuf);
   if (NS_WARN_IF(NS_FAILED(rv))) {
     Cancel(NS_ERROR_OUT_OF_MEMORY);
     return;
   }
 
+  // Construct the public key object
+  CryptoBuffer pubKeyObj;
+  rv = CBOREncodePublicKeyObj(pubKeyBuf, pubKeyObj);
+  if (NS_FAILED(rv)) {
+    Cancel(rv);
+    return;
+  }
+
+  // Format:
+  // 32 bytes: SHA256 of the RP ID
+  // 1 byte: flags (TUP & AT)
+  // 4 bytes: sign counter
+  // variable: attestation data struct
+  // - 16 bytes: AAGUID
+  // - 2 bytes: Length of Credential ID
+  // - L bytes: Credential ID
+  // - variable: CBOR-format public key
+  // variable: CBOR-format extension auth data (optional, not flagged)
+
+  mozilla::dom::CryptoBuffer authDataBuf;
+  if (NS_WARN_IF(!authDataBuf.SetCapacity(32 + 1 + 4 + aaguidBuf.Length() + 2 +
+                                          keyHandleBuf.Length() +
+                                          pubKeyObj.Length(),
+                                          mozilla::fallible))) {
+    Cancel(NS_ERROR_OUT_OF_MEMORY);
+    return;
+  }
+
+  authDataBuf.AppendElements(rpIdHashBuf, mozilla::fallible);
+  authDataBuf.AppendElement(FLAG_TUP | FLAG_AT, mozilla::fallible);
+  // During create credential, counter is always 0 for U2F
+  // See https://github.com/w3c/webauthn/issues/507
+  authDataBuf.AppendElement(0x00, mozilla::fallible);
+  authDataBuf.AppendElement(0x00, mozilla::fallible);
+  authDataBuf.AppendElement(0x00, mozilla::fallible);
+  authDataBuf.AppendElement(0x00, mozilla::fallible);
+
+  authDataBuf.AppendElements(aaguidBuf, mozilla::fallible);
+  authDataBuf.AppendElement((keyHandleBuf.Length() >> 8) & 0xFF, mozilla::fallible);
+  authDataBuf.AppendElement((keyHandleBuf.Length() >> 0) & 0xFF, mozilla::fallible);
+  authDataBuf.AppendElements(keyHandleBuf, mozilla::fallible);
+  authDataBuf.AppendElements(pubKeyObj, mozilla::fallible);
+
+  CryptoBuffer attObj;
+  rv = CBOREncodeAttestationObj(authDataBuf, attestationCertBuf, signatureBuf,
+                                attObj);
+  if (NS_FAILED(rv)) {
+    Cancel(rv);
+    return;
+  }
+
   // Create a new PublicKeyCredential object and populate its fields with the
   // values returned from the authenticator as well as the clientDataJSON
   // computed earlier.
   RefPtr<AuthenticatorAttestationResponse> attestation =
       new AuthenticatorAttestationResponse(mCurrentParent);
   attestation->SetClientDataJSON(clientDataBuf);
-  attestation->SetAttestationObject(regData);
+  attestation->SetAttestationObject(attObj);
 
   RefPtr<PublicKeyCredential> credential = new PublicKeyCredential(mCurrentParent);
   credential->SetRawId(keyHandleBuf);
   credential->SetResponse(attestation);
 
   mTransactionPromise->MaybeResolve(credential);
   MaybeClearTransaction();
 }
--- a/dom/webauthn/WebAuthnUtil.cpp
+++ b/dom/webauthn/WebAuthnUtil.cpp
@@ -13,17 +13,19 @@ namespace dom {
 nsresult
 ReadToCryptoBuffer(pkix::Reader& aSrc, /* out */ CryptoBuffer& aDest,
                    uint32_t aLen)
 {
   if (aSrc.EnsureLength(aLen) != pkix::Success) {
     return NS_ERROR_DOM_UNKNOWN_ERR;
   }
 
-  aDest.ClearAndRetainStorage();
+  if (!aDest.SetCapacity(aLen, mozilla::fallible)) {
+    return NS_ERROR_OUT_OF_MEMORY;
+  }
 
   for (uint32_t offset = 0; offset < aLen; ++offset) {
     uint8_t b;
     if (aSrc.Read(b) != pkix::Success) {
       return NS_ERROR_DOM_UNKNOWN_ERR;
     }
     if (!aDest.AppendElement(b, mozilla::fallible)) {
       return NS_ERROR_OUT_OF_MEMORY;
@@ -99,17 +101,17 @@ U2FDecomposeRegistrationResponse(const C
   rv = ReadToCryptoBuffer(input, aKeyHandleBuf, handleLen);
   if (NS_FAILED(rv)) {
     return rv;
   }
 
   // We have to parse the ASN.1 SEQUENCE on the outside to determine the cert's
   // length.
   pkix::Input cert;
-  if (pkix::der::ExpectTagAndGetValue(input, pkix::der::SEQUENCE, cert)
+  if (pkix::der::ExpectTagAndGetTLV(input, pkix::der::SEQUENCE, cert)
       != pkix::Success) {
     return NS_ERROR_DOM_UNKNOWN_ERR;
   }
 
   pkix::Reader certInput(cert);
   rv = ReadToCryptoBuffer(certInput, aAttestationCertBuf, cert.GetLength());
   if (NS_FAILED(rv)) {
     return rv;
@@ -119,13 +121,45 @@ U2FDecomposeRegistrationResponse(const C
   pkix::Input u2fSig;
   input.SkipToEnd(u2fSig);
   pkix::Reader sigInput(u2fSig);
   rv = ReadToCryptoBuffer(sigInput, aSignatureBuf, u2fSig.GetLength());
   if (NS_FAILED(rv)) {
     return rv;
   }
 
+  MOZ_ASSERT(input.AtEnd());
+  return NS_OK;
+}
+
+nsresult
+U2FDecomposeECKey(const CryptoBuffer& aPubKeyBuf,
+                  /* out */ CryptoBuffer& aXcoord,
+                  /* out */ CryptoBuffer& aYcoord)
+{
+  pkix::Input pubKey;
+  pubKey.Init(aPubKeyBuf.Elements(), aPubKeyBuf.Length());
+
+  pkix::Reader input(pubKey);
+  uint8_t b;
+  if (input.Read(b) != pkix::Success) {
+    return NS_ERROR_DOM_UNKNOWN_ERR;
+  }
+  if (b != 0x04) {
+    return NS_ERROR_DOM_UNKNOWN_ERR;
+  }
+
+  nsresult rv = ReadToCryptoBuffer(input, aXcoord, 32);
+  if (NS_FAILED(rv)) {
+    return rv;
+  }
+
+  rv = ReadToCryptoBuffer(input, aYcoord, 32);
+  if (NS_FAILED(rv)) {
+    return rv;
+  }
+
+  MOZ_ASSERT(input.AtEnd());
   return NS_OK;
 }
 
 }
 }
--- a/dom/webauthn/WebAuthnUtil.h
+++ b/dom/webauthn/WebAuthnUtil.h
@@ -27,12 +27,17 @@ U2FDecomposeRegistrationResponse(const C
                                  /* out */ CryptoBuffer& aKeyHandleBuf,
                                  /* out */ CryptoBuffer& aAttestationCertBuf,
                                  /* out */ CryptoBuffer& aSignatureBuf);
 
 nsresult
 ReadToCryptoBuffer(pkix::Reader& aSrc, /* out */ CryptoBuffer& aDest,
                    uint32_t aLen);
 
+nsresult
+U2FDecomposeECKey(const CryptoBuffer& aPubKeyBuf,
+                  /* out */ CryptoBuffer& aXcoord,
+                  /* out */ CryptoBuffer& aYcoord);
+
 } // namespace dom
 } // namespace mozilla
 
 #endif // mozilla_dom_WebAuthnUtil_h
--- a/dom/webauthn/moz.build
+++ b/dom/webauthn/moz.build
@@ -16,16 +16,17 @@ EXPORTS.mozilla.dom += [
     'AuthenticatorAttestationResponse.h',
     'AuthenticatorResponse.h',
     'NSSU2FTokenRemote.h',
     'PublicKeyCredential.h',
     'U2FHIDTokenManager.h',
     'U2FSoftTokenManager.h',
     'U2FTokenManager.h',
     'U2FTokenTransport.h',
+    'WebAuthnCBORUtil.h',
     'WebAuthnManager.h',
     'WebAuthnRequest.h',
     'WebAuthnTransactionChild.h',
     'WebAuthnTransactionParent.h',
     'WebAuthnUtil.h',
 ]
 
 UNIFIED_SOURCES += [
@@ -34,16 +35,17 @@ UNIFIED_SOURCES += [
     'AuthenticatorResponse.cpp',
     'cbor-cpp/src/encoder.cpp',
     'cbor-cpp/src/output_dynamic.cpp',
     'NSSU2FTokenRemote.cpp',
     'PublicKeyCredential.cpp',
     'U2FHIDTokenManager.cpp',
     'U2FSoftTokenManager.cpp',
     'U2FTokenManager.cpp',
+    'WebAuthnCBORUtil.cpp',
     'WebAuthnManager.cpp',
     'WebAuthnTransactionChild.cpp',
     'WebAuthnTransactionParent.cpp',
     'WebAuthnUtil.cpp',
 ]
 
 include('/ipc/chromium/chromium-config.mozbuild')
 
new file mode 100644
--- /dev/null
+++ b/dom/webauthn/tests/cbor/cbor.js
@@ -0,0 +1,406 @@
+/*
+ * The MIT License (MIT)
+ *
+ * Copyright (c) 2014-2016 Patrick Gansterer <paroga@paroga.com>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+(function(global, undefined) { "use strict";
+var POW_2_24 = 5.960464477539063e-8,
+    POW_2_32 = 4294967296,
+    POW_2_53 = 9007199254740992;
+
+function encode(value) {
+  var data = new ArrayBuffer(256);
+  var dataView = new DataView(data);
+  var lastLength;
+  var offset = 0;
+
+  function prepareWrite(length) {
+    var newByteLength = data.byteLength;
+    var requiredLength = offset + length;
+    while (newByteLength < requiredLength)
+      newByteLength <<= 1;
+    if (newByteLength !== data.byteLength) {
+      var oldDataView = dataView;
+      data = new ArrayBuffer(newByteLength);
+      dataView = new DataView(data);
+      var uint32count = (offset + 3) >> 2;
+      for (var i = 0; i < uint32count; ++i)
+        dataView.setUint32(i << 2, oldDataView.getUint32(i << 2));
+    }
+
+    lastLength = length;
+    return dataView;
+  }
+  function commitWrite() {
+    offset += lastLength;
+  }
+  function writeFloat64(value) {
+    commitWrite(prepareWrite(8).setFloat64(offset, value));
+  }
+  function writeUint8(value) {
+    commitWrite(prepareWrite(1).setUint8(offset, value));
+  }
+  function writeUint8Array(value) {
+    var dataView = prepareWrite(value.length);
+    for (var i = 0; i < value.length; ++i)
+      dataView.setUint8(offset + i, value[i]);
+    commitWrite();
+  }
+  function writeUint16(value) {
+    commitWrite(prepareWrite(2).setUint16(offset, value));
+  }
+  function writeUint32(value) {
+    commitWrite(prepareWrite(4).setUint32(offset, value));
+  }
+  function writeUint64(value) {
+    var low = value % POW_2_32;
+    var high = (value - low) / POW_2_32;
+    var dataView = prepareWrite(8);
+    dataView.setUint32(offset, high);
+    dataView.setUint32(offset + 4, low);
+    commitWrite();
+  }
+  function writeTypeAndLength(type, length) {
+    if (length < 24) {
+      writeUint8(type << 5 | length);
+    } else if (length < 0x100) {
+      writeUint8(type << 5 | 24);
+      writeUint8(length);
+    } else if (length < 0x10000) {
+      writeUint8(type << 5 | 25);
+      writeUint16(length);
+    } else if (length < 0x100000000) {
+      writeUint8(type << 5 | 26);
+      writeUint32(length);
+    } else {
+      writeUint8(type << 5 | 27);
+      writeUint64(length);
+    }
+  }
+
+  function encodeItem(value) {
+    var i;
+
+    if (value === false)
+      return writeUint8(0xf4);
+    if (value === true)
+      return writeUint8(0xf5);
+    if (value === null)
+      return writeUint8(0xf6);
+    if (value === undefined)
+      return writeUint8(0xf7);
+
+    switch (typeof value) {
+      case "number":
+        if (Math.floor(value) === value) {
+          if (0 <= value && value <= POW_2_53)
+            return writeTypeAndLength(0, value);
+          if (-POW_2_53 <= value && value < 0)
+            return writeTypeAndLength(1, -(value + 1));
+        }
+        writeUint8(0xfb);
+        return writeFloat64(value);
+
+      case "string":
+        var utf8data = [];
+        for (i = 0; i < value.length; ++i) {
+          var charCode = value.charCodeAt(i);
+          if (charCode < 0x80) {
+            utf8data.push(charCode);
+          } else if (charCode < 0x800) {
+            utf8data.push(0xc0 | charCode >> 6);
+            utf8data.push(0x80 | charCode & 0x3f);
+          } else if (charCode < 0xd800) {
+            utf8data.push(0xe0 | charCode >> 12);
+            utf8data.push(0x80 | (charCode >> 6)  & 0x3f);
+            utf8data.push(0x80 | charCode & 0x3f);
+          } else {
+            charCode = (charCode & 0x3ff) << 10;
+            charCode |= value.charCodeAt(++i) & 0x3ff;
+            charCode += 0x10000;
+
+            utf8data.push(0xf0 | charCode >> 18);
+            utf8data.push(0x80 | (charCode >> 12)  & 0x3f);
+            utf8data.push(0x80 | (charCode >> 6)  & 0x3f);
+            utf8data.push(0x80 | charCode & 0x3f);
+          }
+        }
+
+        writeTypeAndLength(3, utf8data.length);
+        return writeUint8Array(utf8data);
+
+      default:
+        var length;
+        if (Array.isArray(value)) {
+          length = value.length;
+          writeTypeAndLength(4, length);
+          for (i = 0; i < length; ++i)
+            encodeItem(value[i]);
+        } else if (value instanceof Uint8Array) {
+          writeTypeAndLength(2, value.length);
+          writeUint8Array(value);
+        } else {
+          var keys = Object.keys(value);
+          length = keys.length;
+          writeTypeAndLength(5, length);
+          for (i = 0; i < length; ++i) {
+            var key = keys[i];
+            encodeItem(key);
+            encodeItem(value[key]);
+          }
+        }
+    }
+  }
+
+  encodeItem(value);
+
+  if ("slice" in data)
+    return data.slice(0, offset);
+
+  var ret = new ArrayBuffer(offset);
+  var retView = new DataView(ret);
+  for (var i = 0; i < offset; ++i)
+    retView.setUint8(i, dataView.getUint8(i));
+  return ret;
+}
+
+function decode(data, tagger, simpleValue) {
+  var dataView = new DataView(data);
+  var offset = 0;
+
+  if (typeof tagger !== "function")
+    tagger = function(value) { return value; };
+  if (typeof simpleValue !== "function")
+    simpleValue = function() { return undefined; };
+
+  function commitRead(length, value) {
+    offset += length;
+    return value;
+  }
+  function readArrayBuffer(length) {
+    return commitRead(length, new Uint8Array(data, offset, length));
+  }
+  function readFloat16() {
+    var tempArrayBuffer = new ArrayBuffer(4);
+    var tempDataView = new DataView(tempArrayBuffer);
+    var value = readUint16();
+
+    var sign = value & 0x8000;
+    var exponent = value & 0x7c00;
+    var fraction = value & 0x03ff;
+
+    if (exponent === 0x7c00)
+      exponent = 0xff << 10;
+    else if (exponent !== 0)
+      exponent += (127 - 15) << 10;
+    else if (fraction !== 0)
+      return (sign ? -1 : 1) * fraction * POW_2_24;
+
+    tempDataView.setUint32(0, sign << 16 | exponent << 13 | fraction << 13);
+    return tempDataView.getFloat32(0);
+  }
+  function readFloat32() {
+    return commitRead(4, dataView.getFloat32(offset));
+  }
+  function readFloat64() {
+    return commitRead(8, dataView.getFloat64(offset));
+  }
+  function readUint8() {
+    return commitRead(1, dataView.getUint8(offset));
+  }
+  function readUint16() {
+    return commitRead(2, dataView.getUint16(offset));
+  }
+  function readUint32() {
+    return commitRead(4, dataView.getUint32(offset));
+  }
+  function readUint64() {
+    return readUint32() * POW_2_32 + readUint32();
+  }
+  function readBreak() {
+    if (dataView.getUint8(offset) !== 0xff)
+      return false;
+    offset += 1;
+    return true;
+  }
+  function readLength(additionalInformation) {
+    if (additionalInformation < 24)
+      return additionalInformation;
+    if (additionalInformation === 24)
+      return readUint8();
+    if (additionalInformation === 25)
+      return readUint16();
+    if (additionalInformation === 26)
+      return readUint32();
+    if (additionalInformation === 27)
+      return readUint64();
+    if (additionalInformation === 31)
+      return -1;
+    throw "Invalid length encoding";
+  }
+  function readIndefiniteStringLength(majorType) {
+    var initialByte = readUint8();
+    if (initialByte === 0xff)
+      return -1;
+    var length = readLength(initialByte & 0x1f);
+    if (length < 0 || (initialByte >> 5) !== majorType)
+      throw "Invalid indefinite length element";
+    return length;
+  }
+
+  function appendUtf16Data(utf16data, length) {
+    for (var i = 0; i < length; ++i) {
+      var value = readUint8();
+      if (value & 0x80) {
+        if (value < 0xe0) {
+          value = (value & 0x1f) <<  6
+                | (readUint8() & 0x3f);
+          length -= 1;
+        } else if (value < 0xf0) {
+          value = (value & 0x0f) << 12
+                | (readUint8() & 0x3f) << 6
+                | (readUint8() & 0x3f);
+          length -= 2;
+        } else {
+          value = (value & 0x0f) << 18
+                | (readUint8() & 0x3f) << 12
+                | (readUint8() & 0x3f) << 6
+                | (readUint8() & 0x3f);
+          length -= 3;
+        }
+      }
+
+      if (value < 0x10000) {
+        utf16data.push(value);
+      } else {
+        value -= 0x10000;
+        utf16data.push(0xd800 | (value >> 10));
+        utf16data.push(0xdc00 | (value & 0x3ff));
+      }
+    }
+  }
+
+  function decodeItem() {
+    var initialByte = readUint8();
+    var majorType = initialByte >> 5;
+    var additionalInformation = initialByte & 0x1f;
+    var i;
+    var length;
+
+    if (majorType === 7) {
+      switch (additionalInformation) {
+        case 25:
+          return readFloat16();
+        case 26:
+          return readFloat32();
+        case 27:
+          return readFloat64();
+      }
+    }
+
+    length = readLength(additionalInformation);
+    if (length < 0 && (majorType < 2 || 6 < majorType))
+      throw "Invalid length";
+
+    switch (majorType) {
+      case 0:
+        return length;
+      case 1:
+        return -1 - length;
+      case 2:
+        if (length < 0) {
+          var elements = [];
+          var fullArrayLength = 0;
+          while ((length = readIndefiniteStringLength(majorType)) >= 0) {
+            fullArrayLength += length;
+            elements.push(readArrayBuffer(length));
+          }
+          var fullArray = new Uint8Array(fullArrayLength);
+          var fullArrayOffset = 0;
+          for (i = 0; i < elements.length; ++i) {
+            fullArray.set(elements[i], fullArrayOffset);
+            fullArrayOffset += elements[i].length;
+          }
+          return fullArray;
+        }
+        return readArrayBuffer(length);
+      case 3:
+        var utf16data = [];
+        if (length < 0) {
+          while ((length = readIndefiniteStringLength(majorType)) >= 0)
+            appendUtf16Data(utf16data, length);
+        } else
+          appendUtf16Data(utf16data, length);
+        return String.fromCharCode.apply(null, utf16data);
+      case 4:
+        var retArray;
+        if (length < 0) {
+          retArray = [];
+          while (!readBreak())
+            retArray.push(decodeItem());
+        } else {
+          retArray = new Array(length);
+          for (i = 0; i < length; ++i)
+            retArray[i] = decodeItem();
+        }
+        return retArray;
+      case 5:
+        var retObject = {};
+        for (i = 0; i < length || length < 0 && !readBreak(); ++i) {
+          var key = decodeItem();
+          retObject[key] = decodeItem();
+        }
+        return retObject;
+      case 6:
+        return tagger(decodeItem(), length);
+      case 7:
+        switch (length) {
+          case 20:
+            return false;
+          case 21:
+            return true;
+          case 22:
+            return null;
+          case 23:
+            return undefined;
+          default:
+            return simpleValue(length);
+        }
+    }
+  }
+
+  var ret = decodeItem();
+  if (offset !== data.byteLength)
+    throw "Remaining bytes";
+  return ret;
+}
+
+var obj = { encode: encode, decode: decode };
+
+if (typeof define === "function" && define.amd)
+  define("cbor/cbor", obj);
+else if (typeof module !== "undefined" && module.exports)
+  module.exports = obj;
+else if (!global.CBOR)
+  global.CBOR = obj;
+
+})(this);
--- a/dom/webauthn/tests/mochitest.ini
+++ b/dom/webauthn/tests/mochitest.ini
@@ -1,10 +1,11 @@
 [DEFAULT]
 support-files =
+  cbor/cbor.js
   pkijs/asn1.js
   pkijs/common.js
   pkijs/x509_schema.js
   pkijs/x509_simpl.js
   u2futil.js
 
 [test_webauthn_loopback.html]
 skip-if = !e10s
--- a/dom/webauthn/tests/test_webauthn_loopback.html
+++ b/dom/webauthn/tests/test_webauthn_loopback.html
@@ -3,16 +3,17 @@
 <head>
   <title>Full-run test for MakeCredential/GetAssertion for W3C Web Authentication</title>
   <script type="text/javascript" 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/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">
@@ -34,36 +35,37 @@ function() {
 
   let gCredentialChallenge = new Uint8Array(16);
   window.crypto.getRandomValues(gCredentialChallenge);
   let gAssertionChallenge = new Uint8Array(16);
   window.crypto.getRandomValues(gAssertionChallenge);
 
   testMakeCredential();
 
-  function checkCredentialValid(aCredInfo) {
+  function decodeCreatedCredential(aCredInfo) {
     /* PublicKeyCredential : Credential
        - rawId: Key Handle buffer pulled from U2F Register() Response
        - response : AuthenticatorAttestationResponse : AuthenticatorResponse
-         - attestationObject: RP ID Hash || U2F Sign() Response
+         - attestationObject: CBOR object
          - clientDataJSON: serialized JSON
        - clientExtensionResults: (not yet supported)
     */
 
     ok(aCredInfo.rawId.length > 0, "Key ID exists");
 
-    is(aCredInfo.response.attestationObject[0], 0x05, "Reserved byte is correct");
     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.hashAlg, "S256", "Hash algorithm is correct");
 
-    return decodeU2FRegistration(aCredInfo.response.attestationObject)
-    .then(function(u2fObj) {
-      aCredInfo.u2fReg = u2fObj;
+    return webAuthnDecodeAttestation(aCredInfo.response.attestationObject.buffer)
+    .then(function(decodedResult) {
+      aCredInfo.clientDataObj = clientData;
+      aCredInfo.publicKeyHandle = decodedResult.publicKeyHandle;
+      aCredInfo.attestationObject = decodedResult.attestationObject;
       return aCredInfo;
     });
   }
 
   function checkAssertionAndSigValid(aPublicKey, aAssertion) {
     /* PublicKeyCredential : Credential
        - rawId: ID of Credential from AllowList that succeeded
        - response : AuthenticatorAssertionResponse : AuthenticatorResponse
@@ -109,17 +111,17 @@ function() {
     let param = {type: "public-key", algorithm: "P-256"};
     let makeCredentialOptions = {
       rp: rp,
       user: user,
       challenge: gCredentialChallenge,
       parameters: [param]
     };
     credm.create({publicKey: makeCredentialOptions})
-    .then(checkCredentialValid)
+    .then(decodeCreatedCredential)
     .then(testMakeDuplicate)
     .catch(function(aReason) {
       ok(false, aReason);
       SimpleTest.finish();
     });
   }
 
   function testMakeDuplicate(aCredInfo) {
@@ -157,17 +159,17 @@ function() {
       challenge: gAssertionChallenge,
       timeout: 5000, // the minimum timeout is actually 15 seconds
       rpId: document.domain,
       allowList: [newCredential]
     };
     credm.get({publicKey: publicKeyCredentialRequestOptions})
     .then(function(aAssertion) {
       /* Pass along the pubKey. */
-      return checkAssertionAndSigValid(aCredInfo.u2fReg.publicKey, aAssertion);
+      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();
--- a/dom/webauthn/tests/u2futil.js
+++ b/dom/webauthn/tests/u2futil.js
@@ -122,34 +122,63 @@ function hexEncode(buf) {
               .map(x => ("0"+x.toString(16)).substr(-2))
               .join("");
 }
 
 function hexDecode(str) {
   return new Uint8Array(str.match(/../g).map(x => parseInt(x, 16)));
 }
 
-function decodeU2FRegistration(aRegData) {
-  if (aRegData[0] != 0x05) {
-    return Promise.reject("Sentinal byte != 0x05");
+function webAuthnDecodeAttestation(aAttestationBuf) {
+  let attObj = CBOR.decode(aAttestationBuf);
+  console.log("Attestation CBOR Object:", attObj);
+  if (!("authData" in attObj && "fmt" in attObj && "attStmt" in attObj)) {
+    throw "Invalid CBOR Attestation Object";
+  }
+  if (!("sig" in attObj.attStmt && "x5c" in attObj.attStmt)) {
+    throw "Invalid CBOR Attestation Statement";
   }
 
-  let keyHandleLength = aRegData[66];
-  let u2fRegObj = {
-    publicKeyBytes: aRegData.slice(1, 66),
-    keyHandleBytes: aRegData.slice(67, 67 + keyHandleLength),
-    attestationBytes: aRegData.slice(67 + keyHandleLength)
+  let rpIdHash = attObj.authData.slice(0, 32);
+  let flags = attObj.authData.slice(32, 33);
+  let counter = attObj.authData.slice(33, 37);
+  let attData = {};
+  attData.aaguid = attObj.authData.slice(37, 53);
+  attData.credIdLen = (attObj.authData[53] << 8) + attObj.authData[54];
+  attData.credId = attObj.authData.slice(55, 55 + attData.credIdLen);
+
+  console.log(":: CBOR Attestation Object Data ::");
+  console.log("RP ID Hash: " + hexEncode(rpIdHash));
+  console.log("Counter: " + hexEncode(counter) + " Flags: " + flags);
+  console.log("AAGUID: " + hexEncode(attData.aaguid));
+
+  cborPubKey = attObj.authData.slice(55 + attData.credIdLen);
+  var pubkeyObj = CBOR.decode(cborPubKey.buffer);
+  if (!("alg" in pubkeyObj && "x" in pubkeyObj && "y" in pubkeyObj)) {
+    throw "Invalid CBOR Public Key Object";
+  }
+  if (pubkeyObj.alg != "ES256") {
+    throw "Unexpected public key algorithm";
   }
 
-  u2fRegObj.keyHandle = bytesToBase64UrlSafe(u2fRegObj.keyHandleBytes);
+  let pubKeyBytes = assemblePublicKeyBytesData(pubkeyObj.x, pubkeyObj.y);
+  console.log(":: CBOR Public Key Object Data ::");
+  console.log("Algorithm: " + pubkeyObj.alg);
+  console.log("X: " + pubkeyObj.x);
+  console.log("Y: " + pubkeyObj.y);
+  console.log("Uncompressed (hex): " + hexEncode(pubKeyBytes));
 
-  return importPublicKey(u2fRegObj.publicKeyBytes)
-  .then(function(keyObj) {
-    u2fRegObj.publicKey = keyObj;
-    return u2fRegObj;
+  return importPublicKey(pubKeyBytes)
+  .then(function(aKeyHandle) {
+    return {
+      attestationObject: attObj,
+      attestationAuthData: attData,
+      publicKeyBytes: pubKeyBytes,
+      publicKeyHandle: aKeyHandle,
+    };
   });
 }
 
 function importPublicKey(keyBytes) {
   if (keyBytes[0] != 0x04 || keyBytes.byteLength != 65) {
     throw "Bad public key octet string";
   }
   var jwk = {
@@ -170,16 +199,29 @@ function deriveAppAndChallengeParam(appI
   .then(function(digests) {
     return {
       appParam: new Uint8Array(digests[0]),
       challengeParam: new Uint8Array(digests[1]),
     };
   });
 }
 
+function assemblePublicKeyBytesData(xCoord, yCoord) {
+  // Produce an uncompressed EC key point. These start with 0x04, and then
+  // two 32-byte numbers denoting X and Y.
+  if (xCoord.length != 32 || yCoord.length != 32) {
+    throw ("Coordinates must be 32 bytes long");
+  }
+  let keyBytes = new Uint8Array(65);
+  keyBytes[0] = 0x04;
+  xCoord.map((x, i) => keyBytes[1 + i] = x);
+  yCoord.map((x, i) => keyBytes[33 + i] = x);
+  return keyBytes;
+}
+
 function assembleSignedData(appParam, presenceAndCounter, challengeParam) {
   let signedData = new Uint8Array(32 + 1 + 4 + 32);
   appParam.map((x, i) => signedData[0 + i] = x);
   presenceAndCounter.map((x, i) => signedData[32 + i] = x);
   challengeParam.map((x, i) => signedData[37 + i] = x);
   return signedData;
 }