1
0
mirror of https://github.com/bitwarden/browser.git synced 2025-02-08 00:01:28 +01:00

[EC-598] feat: complete implementation of makeCredential

This commit is contained in:
Andreas Coroiu 2023-03-27 13:38:21 +02:00
parent 343df7efdb
commit f31bd3eca9
No known key found for this signature in database
GPG Key ID: E70B5FFC81DFEC1A
4 changed files with 295 additions and 10 deletions

View File

@ -33,6 +33,9 @@ export class Utils {
static readonly validHosts: string[] = ["localhost"];
static readonly minimumPasswordLength = 10;
/** Used by guidToStandardFormat */
private static byteToHex: string[] = [];
static init() {
if (Utils.inited) {
return;
@ -56,6 +59,10 @@ export class Utils {
// If it's not browser or node then it must be a service worker
Utils.global = self;
}
for (let i = 0; i < 256; ++i) {
Utils.byteToHex.push((i + 0x100).toString(16).substring(1));
}
}
static fromB64ToArray(str: string): Uint8Array {
@ -561,6 +568,93 @@ export class Utils {
return null;
}
/*
License for: guidToRawFormat, guidToStandardFormat
Source: https://github.com/uuidjs/uuid/
The MIT License (MIT)
Copyright (c) 2010-2020 Robert Kieffer and other contributors
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.*/
/** Convert standard format (XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX) UUID to raw 16 byte array. */
static guidToRawFormat(guid: string) {
if (!Utils.isGuid(guid)) {
throw TypeError("GUID parameter is invalid");
}
let v;
const arr = new Uint8Array(16);
// Parse ########-....-....-....-............
arr[0] = (v = parseInt(guid.slice(0, 8), 16)) >>> 24;
arr[1] = (v >>> 16) & 0xff;
arr[2] = (v >>> 8) & 0xff;
arr[3] = v & 0xff;
// Parse ........-####-....-....-............
arr[4] = (v = parseInt(guid.slice(9, 13), 16)) >>> 8;
arr[5] = v & 0xff;
// Parse ........-....-####-....-............
arr[6] = (v = parseInt(guid.slice(14, 18), 16)) >>> 8;
arr[7] = v & 0xff;
// Parse ........-....-....-####-............
arr[8] = (v = parseInt(guid.slice(19, 23), 16)) >>> 8;
arr[9] = v & 0xff;
// Parse ........-....-....-....-############
// (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes)
arr[10] = ((v = parseInt(guid.slice(24, 36), 16)) / 0x10000000000) & 0xff;
arr[11] = (v / 0x100000000) & 0xff;
arr[12] = (v >>> 24) & 0xff;
arr[13] = (v >>> 16) & 0xff;
arr[14] = (v >>> 8) & 0xff;
arr[15] = v & 0xff;
return arr;
}
/** Convert raw 16 byte array to standard format (XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX) UUID. */
static guidToStandardFormat(arr: Uint8Array) {
// Note: Be careful editing this code! It's been tuned for performance
// and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
const guid = (
Utils.byteToHex[arr[0]] +
Utils.byteToHex[arr[1]] +
Utils.byteToHex[arr[2]] +
Utils.byteToHex[arr[3]] +
"-" +
Utils.byteToHex[arr[4]] +
Utils.byteToHex[arr[5]] +
"-" +
Utils.byteToHex[arr[6]] +
Utils.byteToHex[arr[7]] +
"-" +
Utils.byteToHex[arr[8]] +
Utils.byteToHex[arr[9]] +
"-" +
Utils.byteToHex[arr[10]] +
Utils.byteToHex[arr[11]] +
Utils.byteToHex[arr[12]] +
Utils.byteToHex[arr[13]] +
Utils.byteToHex[arr[14]] +
Utils.byteToHex[arr[15]]
).toLowerCase();
// Consistency check for valid UUID. If this throws, it's likely due to one
// of the following:
// - One or more input array values don't map to a hex octet (leading to
// "undefined" in the uuid)
// - Invalid input values for the RFC `version` or `variant` fields
if (!Utils.isGuid(guid)) {
throw TypeError("Converted GUID is invalid");
}
return guid;
}
}
Utils.init();

View File

@ -1,5 +1,10 @@
export abstract class Fido2AuthenticatorService {
makeCredential: (params: Fido2AuthenticatorMakeCredentialsParams) => void;
/**
* This method triggers the generation of a new credential in the authenticator
*
* @return {Uint8Array} Attestation object
**/
makeCredential: (params: Fido2AuthenticatorMakeCredentialsParams) => Promise<Uint8Array>;
}
export enum Fido2AlgorithmIdentifier {

View File

@ -1,5 +1,6 @@
import { TextEncoder } from "util";
import { CBOR } from "cbor-redux";
import { mock, MockProxy } from "jest-mock-extended";
import { Utils } from "../../misc/utils";
@ -19,7 +20,7 @@ import {
import { Fido2Utils } from "../abstractions/fido2-utils";
import { Fido2Key } from "../models/domain/fido2-key";
import { Fido2AuthenticatorService } from "./fido2-authenticator.service";
import { AAGUID, Fido2AuthenticatorService } from "./fido2-authenticator.service";
const RpId = "bitwarden.com";
@ -159,6 +160,11 @@ describe("FidoAuthenticatorService", () => {
* */
it("should request confirmation from user", async () => {
userInterface.confirmNewCredential.mockResolvedValue(true);
cipherService.encrypt.mockResolvedValue({} as unknown as Cipher);
cipherService.createWithServer.mockImplementation(async (cipher) => {
cipher.id = Utils.newGuid();
return cipher;
});
await authenticator.makeCredential(params);
@ -169,9 +175,13 @@ describe("FidoAuthenticatorService", () => {
});
it("should save credential to vault if request confirmed by user", async () => {
const encryptedCipher = Symbol();
const encryptedCipher = {};
userInterface.confirmNewCredential.mockResolvedValue(true);
cipherService.encrypt.mockResolvedValue(encryptedCipher as unknown as Cipher);
cipherService.createWithServer.mockImplementation(async (cipher) => {
cipher.id = Utils.newGuid();
return cipher;
});
await authenticator.makeCredential(params);
@ -207,7 +217,7 @@ describe("FidoAuthenticatorService", () => {
/** Spec: If any error occurred while creating the new credential object, return an error code equivalent to "UnknownError" and terminate the operation. */
it("should throw unkown error if creation fails", async () => {
const encryptedCipher = Symbol();
const encryptedCipher = {};
userInterface.confirmNewCredential.mockResolvedValue(true);
cipherService.encrypt.mockResolvedValue(encryptedCipher as unknown as Cipher);
cipherService.createWithServer.mockRejectedValue(new Error("Internal error"));
@ -299,6 +309,57 @@ describe("FidoAuthenticatorService", () => {
await expect(result).rejects.toThrowError(Fido2AutenticatorErrorCode.Unknown);
});
});
describe("attestation of new credential", () => {
const cipherId = "75280e7e-a72e-4d6c-bf1e-d37238352f9b";
const cipherIdBytes = new Uint8Array([
0x75, 0x28, 0x0e, 0x7e, 0xa7, 0x2e, 0x4d, 0x6c, 0xbf, 0x1e, 0xd3, 0x72, 0x38, 0x35, 0x2f,
0x9b,
]);
let params: Fido2AuthenticatorMakeCredentialsParams;
beforeEach(async () => {
params = await createCredentialParams({ requireResidentKey: true });
userInterface.confirmNewCredential.mockResolvedValue(true);
cipherService.encrypt.mockResolvedValue({} as unknown as Cipher);
cipherService.createWithServer.mockImplementation(async (cipher) => {
cipher.id = cipherId;
return cipher;
});
});
it.only("should throw error if user denies creation request", async () => {
const result = await authenticator.makeCredential(params);
const attestationObject = CBOR.decode(result.buffer);
const encAuthData: Uint8Array = attestationObject.authData;
const rpIdHash = encAuthData.slice(0, 32);
const flags = encAuthData.slice(32, 33);
const counter = encAuthData.slice(33, 37);
const aaguid = encAuthData.slice(37, 53);
const credentialIdLength = encAuthData.slice(53, 55);
const credentialId = encAuthData.slice(55, 71);
// Public key format is not tested here since it will be tested
// by the assertion tests.
// const publicKey = encAuthData.slice(87);
expect(attestationObject.fmt).toBe("none");
expect(attestationObject.attStmt).toEqual({});
expect(rpIdHash).toEqual(
new Uint8Array([
0x22, 0x6b, 0xb3, 0x92, 0x02, 0xff, 0xf9, 0x22, 0xdc, 0x74, 0x05, 0xcd, 0x28, 0xa8,
0x34, 0x5a, 0xc4, 0xf2, 0x64, 0x51, 0xd7, 0x3d, 0x0b, 0x40, 0xef, 0xf3, 0x1d, 0xc1,
0xd0, 0x5c, 0x3d, 0xc3,
])
);
expect(flags).toEqual(new Uint8Array([0b00000001])); // UP = true
expect(counter).toEqual(new Uint8Array([0, 0, 0, 0])); // 0 because of new counter
expect(aaguid).toEqual(AAGUID);
expect(credentialIdLength).toEqual(new Uint8Array([0, 16])); // 16 bytes because we're using GUIDs
expect(credentialId).toEqual(cipherIdBytes);
});
});
});
});

View File

@ -1,3 +1,6 @@
import { CBOR } from "cbor-redux";
import { Utils } from "../../misc/utils";
import { CipherType } from "../../vault/enums/cipher-type";
import { CipherView } from "../../vault/models/view/cipher.view";
import { CipherService } from "../../vault/services/cipher.service";
@ -12,6 +15,11 @@ import { Fido2UserInterfaceService } from "../abstractions/fido2-user-interface.
import { Fido2Utils } from "../abstractions/fido2-utils";
import { Fido2KeyView } from "../models/view/fido2-key.view";
// AAGUID: 6e8248d5-b479-40db-a3d8-11116f7e8349
export const AAGUID = new Uint8Array([
0xd5, 0x48, 0x82, 0x6e, 0x79, 0xb4, 0xdb, 0x40, 0xa3, 0xd8, 0x11, 0x11, 0x6f, 0x7e, 0x83, 0x49,
]);
const KeyUsages: KeyUsage[] = ["sign"];
/**
@ -24,7 +32,7 @@ export class Fido2AuthenticatorService implements Fido2AuthenticatorServiceAbstr
private userInterface: Fido2UserInterfaceService
) {}
async makeCredential(params: Fido2AuthenticatorMakeCredentialsParams): Promise<void> {
async makeCredential(params: Fido2AuthenticatorMakeCredentialsParams): Promise<Uint8Array> {
if (params.credTypesAndPubKeyAlgs.every((p) => p.alg !== Fido2AlgorithmIdentifier.ES256)) {
throw new Fido2AutenticatorError(Fido2AutenticatorErrorCode.NotSupported);
}
@ -60,6 +68,8 @@ export class Fido2AuthenticatorService implements Fido2AuthenticatorServiceAbstr
throw new Fido2AutenticatorError(Fido2AutenticatorErrorCode.NotAllowed);
}
let cipher: CipherView;
let keyPair: CryptoKeyPair;
if (params.requireResidentKey) {
const userVerification = await this.userInterface.confirmNewCredential({
credentialName: params.rpEntity.name,
@ -71,14 +81,15 @@ export class Fido2AuthenticatorService implements Fido2AuthenticatorServiceAbstr
}
try {
const keyPair = await this.createKeyPair();
keyPair = await this.createKeyPair();
const cipher = new CipherView();
cipher = new CipherView();
cipher.type = CipherType.Fido2Key;
cipher.name = params.rpEntity.name;
cipher.fido2Key = await this.createKeyView(params, keyPair.privateKey);
const encrypted = await this.cipherService.encrypt(cipher);
await this.cipherService.createWithServer(encrypted);
await this.cipherService.createWithServer(encrypted); // encrypted.id is assigned inside here
cipher.id = encrypted.id;
} catch {
throw new Fido2AutenticatorError(Fido2AutenticatorErrorCode.Unknown);
}
@ -93,10 +104,10 @@ export class Fido2AuthenticatorService implements Fido2AuthenticatorServiceAbstr
}
try {
const keyPair = await this.createKeyPair();
keyPair = await this.createKeyPair();
const encrypted = await this.cipherService.get(cipherId);
const cipher = await encrypted.decrypt();
cipher = await encrypted.decrypt();
cipher.fido2Key = await this.createKeyView(params, keyPair.privateKey);
const reencrypted = await this.cipherService.encrypt(cipher);
await this.cipherService.updateWithServer(reencrypted);
@ -104,6 +115,23 @@ export class Fido2AuthenticatorService implements Fido2AuthenticatorServiceAbstr
throw new Fido2AutenticatorError(Fido2AutenticatorErrorCode.Unknown);
}
}
const attestationObject = new Uint8Array(
CBOR.encode({
fmt: "none",
attStmt: {},
authData: await generateAuthData({
rpId: params.rpEntity.id,
credentialId: cipher.id,
counter: cipher.fido2Key.counter,
userPresence: true,
userVerification: false,
keyPair,
}),
})
);
return attestationObject;
}
private async vaultContainsId(ids: string[]): Promise<boolean> {
@ -147,3 +175,100 @@ export class Fido2AuthenticatorService implements Fido2AuthenticatorServiceAbstr
return fido2Key;
}
}
interface AuthDataParams {
rpId: string;
credentialId: string;
userPresence: boolean;
userVerification: boolean;
counter: number;
keyPair?: CryptoKeyPair;
}
async function generateAuthData(params: AuthDataParams) {
const authData: Array<number> = [];
const rpIdHash = new Uint8Array(
await crypto.subtle.digest({ name: "SHA-256" }, Utils.fromByteStringToArray(params.rpId))
);
authData.push(...rpIdHash);
const flags = authDataFlags({
extensionData: false,
attestationData: false,
userVerification: params.userVerification,
userPresence: params.userPresence,
});
authData.push(flags);
// add 4 bytes of counter - we use time in epoch seconds as monotonic counter
// TODO: Consider changing this to a cryptographically safe random number
const counter = params.counter;
authData.push(
((counter & 0xff000000) >> 24) & 0xff,
((counter & 0x00ff0000) >> 16) & 0xff,
((counter & 0x0000ff00) >> 8) & 0xff,
counter & 0x000000ff
);
// attestedCredentialData
const attestedCredentialData: Array<number> = [];
attestedCredentialData.push(...AAGUID);
// credentialIdLength (2 bytes) and credential Id
const rawId = Utils.guidToRawFormat(params.credentialId);
const credentialIdLength = [(rawId.length - (rawId.length & 0xff)) / 256, rawId.length & 0xff];
attestedCredentialData.push(...credentialIdLength);
attestedCredentialData.push(...rawId);
if (params.keyPair) {
const publicKeyJwk = await crypto.subtle.exportKey("jwk", params.keyPair.publicKey);
// COSE format of the EC256 key
const keyX = Utils.fromUrlB64ToArray(publicKeyJwk.x);
const keyY = Utils.fromUrlB64ToArray(publicKeyJwk.y);
// Can't get `cbor-redux` to encode in CTAP2 canonical CBOR. So we do it manually:
const coseBytes = new Uint8Array(77);
coseBytes.set([0xa5, 0x01, 0x02, 0x03, 0x26, 0x20, 0x01, 0x21, 0x58, 0x20], 0);
coseBytes.set(keyX, 10);
coseBytes.set([0x22, 0x58, 0x20], 10 + 32);
coseBytes.set(keyY, 10 + 32 + 3);
// credential public key - convert to array from CBOR encoded COSE key
attestedCredentialData.push(...coseBytes);
authData.push(...attestedCredentialData);
}
return new Uint8Array(authData);
}
interface Flags {
extensionData: boolean;
attestationData: boolean;
userVerification: boolean;
userPresence: boolean;
}
function authDataFlags(options: Flags): number {
let flags = 0;
if (options.extensionData) {
flags |= 0b1000000;
}
if (options.attestationData) {
flags |= 0b01000000;
}
if (options.userVerification) {
flags |= 0b00000100;
}
if (options.userPresence) {
flags |= 0b00000001;
}
return flags;
}