Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions modules/sdk-core/src/bitgo/keychain/iKeychains.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,18 @@ export interface Keychain {
* provider holds. @experimental
*/
keyId?: string;
/**
* The provider's issuance-proof payload for this backup root (`signedPayload` in wallet-platform).
* Set only on a provider-issued safe backup root alongside `provider` and `keyId`.
* The SDK re-verifies it with `signature` before the root may be used. @experimental
*/
signedPayload?: string;
/**
* The provider's base64 DER P-256 signature over `signedPayload`, as wallet-platform returned it.
* Set only on a provider-issued safe backup root alongside `provider` and `keyId`.
* The SDK re-verifies it before the root may be used. @experimental
*/
signature?: string;
commonPub?: string;
commonKeychain?: string;
keyShares?: ApiKeyShare[];
Expand Down
89 changes: 88 additions & 1 deletion modules/sdk-core/src/bitgo/safe/safe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@
* changes) before the public release.
*/
import * as t from 'io-ts';
import { bip32 } from '@bitgo/utxo-lib';
import { FreezeSafeBody, SafeData, SafeShareData, SafeShareState, type RootKeyType } from '@bitgo/public-types';
import { IBaseCoin } from '../baseCoin';
import { BitGoBase } from '../bitgoBase';
import { ApiResponseError, IncorrectPasswordError } from '../errors';
import { decryptKeychainPrivateKey, type Keychain } from '../keychain';
import { Environments } from '../environments';
import { decryptKeychainPrivateKey, type IKeychains, type Keychain } from '../keychain';
import { ECDSAUtils, parseSafeMpcKeyEnvelopes, EDDSAUtils } from '../utils';
import { boundedInt, decodeWithCodec } from '../utils/codecs';
import { postWithCodec } from '../utils/postWithCodec';
Expand Down Expand Up @@ -42,11 +44,16 @@ import {
buildSafeBip44Path,
deriveAndSelfCheckSafeChildHardened,
deriveSafeChildEd25519Hardened,
deriveSoftPathRelative,
DerivedFromParentWithHardenedPath,
getEd25519MultisigCoinEncoders,
getSafeBip44CoinType,
onchainSlotForCoin,
toSoftTwinPath,
tssSlotForCoin,
} from '@bitgo/sdk-lib-safes';
import { verifyCoinCoverSafeRootProof } from './coincoverRootProof';
import { softDeriveChildPubEd25519AtPath } from './derivableEd25519Pub';

const SafeRootKeySlot = t.keyof({
secp256k1Multisig: null,
Expand Down Expand Up @@ -232,9 +239,89 @@ export class Safe implements ISafe {
multisigType,
keys,
}).result();

// CoinCover holds some safes' backup roots. Re-verify the root's issuance proof and the backup
// child the server derived from it before handing back a wallet that would sign with it. One
// root fetch is the only extra cost for non-CoinCover safes.
if (slot === 'secp256k1Multisig' || slot === 'ed25519Multisig') {
const backupRootId = rootIdFromSafe(safeData, slot, 1);
if (backupRootId !== undefined) {
const backupRoot = await keychains.get({ id: backupRootId });
if (backupRoot.provider === 'coincover') {
const walletKeys =
typeof response === 'object' && response !== null && 'keys' in response ? response.keys : undefined;
await this.assertCoinCoverBackupChild({ keychains, coin, slot, backupRoot, walletKeys, path });
}
}
}
return new Wallet(this.bitgo, coin, response);
}

/**
* Re-verify a CoinCover-backed safe's backup root and prove the minted backup child is its soft
* derivation at `path` (the user child is hardened; co-signers derive at the soft twin). Throws
* before any wallet is returned when either check fails.
*/
private async assertCoinCoverBackupChild(params: {
keychains: IKeychains;
coin: IBaseCoin;
slot: 'secp256k1Multisig' | 'ed25519Multisig';
backupRoot: Keychain;
walletKeys: unknown;
path: DerivedFromParentWithHardenedPath;
}): Promise<void> {
const { keychains, coin, slot, backupRoot, walletKeys, path } = params;
const { pub, keyId, signedPayload, signature } = backupRoot;
if (pub === undefined || keyId === undefined || signedPayload === undefined || signature === undefined) {
throw new Error(`CoinCover backup root for ${slot} is missing its issuance proof; refusing to return the wallet`);
}
await verifyCoinCoverSafeRootProof({
pub,
slot,
keyId,
signedPayload,
signature,
enterpriseId: this.enterpriseId(),
safeId: this.id(),
attestationPublicKeys: Environments[this.bitgo.getEnv()].coinCoverAttestationPublicKeys,
});

const keyIds: unknown[] = Array.isArray(walletKeys) ? walletKeys : [];
if (keyIds.length !== 3) {
throw new Error(`minted ${slot} wallet did not return its [user, backup, bitgo] key ids`);
}
const backupChildId = keyIds[1];
if (typeof backupChildId !== 'string') {
throw new Error(`minted ${slot} wallet did not return a backup child key id`);
}
const backupChild = await keychains.get({ id: backupChildId });
if (backupChild.pub === undefined) {
throw new Error(`minted ${slot} wallet backup child ${backupChildId} has no pub`);
}

const softPath = toSoftTwinPath(path);
let derivedPub: string;
let mintedPub: string;
if (slot === 'secp256k1Multisig') {
derivedPub = deriveSoftPathRelative(bip32.fromBase58(pub), softPath).publicKey.toString('hex');
mintedPub = bip32.fromBase58(backupChild.pub).publicKey.toString('hex');
} else {
const encoders = getEd25519MultisigCoinEncoders(coin.getChain());
if (encoders === undefined) {
throw new Error(
`cannot verify the CoinCover backup child for ${slot}: coin '${coin.getChain()}' has no ed25519 multisig encoders`
);
}
derivedPub = encoders.encodePub(await softDeriveChildPubEd25519AtPath(pub, softPath));
mintedPub = backupChild.pub;
}
if (derivedPub !== mintedPub) {
throw new Error(
`Safe wallet minted for ${slot} at ${path}: the backup child does not derive from the CoinCover backup root`
);
}
}

/**
* TSS wallet mint: decrypt the user root blob, run the user/BitGo hard-derive
* ceremony, register the ordered child documents, then mint.
Expand Down
71 changes: 71 additions & 0 deletions modules/sdk-core/src/bitgo/safe/safes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
} from '@bitgo/public-types';
import { BitGoBase } from '../bitgoBase';
import { ApiResponseError } from '../errors';
import { Environments } from '../environments';
import { decodeWithCodec } from '../utils/codecs';
import {
decodeEd25519StrKeyPublicKey,
Expand All @@ -39,6 +40,7 @@ import {
SafeMultisigRootKeyOptions,
SafeMultisigRootKeys,
} from './iSafes';
import { verifyCoinCoverSafeRootProof } from './coincoverRootProof';
import { coinForRoot, SAFE_ROOT_SLOTS } from './rootCoin';
import { Safe } from './safe';
import type { SafeKeychainRoots } from './keycard';
Expand Down Expand Up @@ -125,6 +127,38 @@ function prepareExternalBackupPub(
return pub;
}

/**
* Verify the issuance proof a KRS returns with a safe backup root. Wallet platform saying a root
* came from the provider is not enough; every proof part is required — a missing piece fails closed
* rather than skipping the check.
*/
async function verifyCoinCoverBackupRoot(params: {
backupKeychain: Keychain;
slot: MultisigRootKeyType;
enterpriseId: string;
safeId: string;
attestationPublicKeys: readonly string[];
}): Promise<void> {
const { backupKeychain, slot, enterpriseId, safeId, attestationPublicKeys } = params;
const { provider, pub, keyId, signedPayload, signature } = backupKeychain;
if (provider !== 'coincover') {
throw new Error('the registered root is not identified as a CoinCover root');
}
if (pub === undefined || keyId === undefined || signedPayload === undefined || signature === undefined) {
throw new Error('the registered root is missing its pub, key id, signed payload or signature');
}
await verifyCoinCoverSafeRootProof({
pub,
slot,
keyId,
signedPayload,
signature,
enterpriseId,
safeId,
attestationPublicKeys,
});
}

/**
* Collection accessor for a single enterprise's safes, mirroring Wallets / Enterprises.
* Safe routes are enterprise-scoped (/api/v2/enterprise/:eId/safes), so the accessor is
Expand Down Expand Up @@ -372,6 +406,43 @@ export class Safes implements ISafes {
}
}

// A provider-held backup root is not trusted because wallet platform returned it: verify the
// provider's issuance proof before the root is assembled into the triplets, so a bad root can
// never reach finalize. Runs after registration so a failure follows the same abandonment path.
for (const registration of settledTriplets) {
if (registration.providerBackup !== true || provider !== 'coincover') {
continue;
}
const slot = registration.slot;
const backupKeychain: Keychain | undefined = registration.triplet.backupKeychain;
if (backupKeychain === undefined) {
throw new Error(`internal error: ${slot} backup keychain was not registered`);
}
if (slot !== 'secp256k1Multisig' && slot !== 'ed25519Multisig') {
throw new Error(`internal error: ${slot} cannot hold a CoinCover backup root`);
}
try {
await verifyCoinCoverBackupRoot({
backupKeychain,
slot,
enterpriseId: enterprise,
safeId,
attestationPublicKeys: Environments[this.bitgo.getEnv()].coinCoverAttestationPublicKeys,
});
} catch (e) {
const reasonText = e instanceof Error ? e.message : String(e);
try {
await this.archiveSafe(safeId);
} catch (archiveError) {
// The primary error carries the verification failure; note it if the cleanup also failed.
}
throw new Error(
`unable to verify the CoinCover backup root for ${slot}: ${reasonText}. The safe (${safeId}) has been ` +
'archived; no backup root was registered for it'
);
}
}

const hot: RootKeysByType = {};
const rootKeychains: SafeKeychainRoots = {};
for (const { slot, triplet } of settledTriplets) {
Expand Down
90 changes: 90 additions & 0 deletions modules/sdk-core/test/unit/bitgo/safe/safe.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import * as sinon from 'sinon';
import 'should';
import { createHash } from 'crypto';
import { p256 } from '@noble/curves/p256';
import { bip32 } from '@bitgo/utxo-lib';
import { SafeData } from '@bitgo/public-types';
import {
ECDSAUtils,
EDDSAUtils,
Environments,
IncorrectPasswordError,
buildSafeMpcKeyEnvelopes,
Safe,
Expand Down Expand Up @@ -48,6 +52,7 @@ describe('Safe', function () {
post: sinon.stub(),
put: sinon.stub(),
get: sinon.stub(),
getEnv: sinon.stub().returns('test'),
};
safeData = {
id: 'test-safe-id',
Expand Down Expand Up @@ -277,6 +282,91 @@ describe('Safe', function () {
addArgs.should.not.have.property('derivedFromParentWithSeed');
});

it('refuses to return a wallet whose backup child does not derive from the CoinCover root', async function () {
// Fixed scalar mirrors the WCN-4832 verifier fixtures.
const attestationPrivateKey = Buffer.from(
'c9afa9d845ba75166b5c215767b1d6934e50c3db36e89b127b8a622b120f6721',
'hex'
);
const attestationPublicKeyHex = Buffer.from(p256.getPublicKey(attestationPrivateKey, true)).toString('hex');
const backupRoot = bip32.fromSeed(Buffer.alloc(32, 0x31)).neutered();
const signedPayload = JSON.stringify({
external_customer_id: 'test-enterprise-id',
external_package_id: 'test-safe-id',
key_id: 'cc-key-id',
public_key: Buffer.concat([backupRoot.publicKey, backupRoot.chainCode]).toString('hex'),
});
const signature = Buffer.from(
p256
.sign(createHash('sha256').update(Buffer.from(signedPayload, 'utf8')).digest(), attestationPrivateKey, {
lowS: false,
})
.toDERRawBytes()
).toString('base64');
// A valid xpub that is not the root's soft child at m/44/0/1/0.
const wrongChildPub = bip32.fromSeed(Buffer.alloc(32, 0x32)).derivePath('m/44/0/1/0').neutered().toBase58();

keychainsGet.callsFake(async ({ id }: { id: string }) => {
if (id === 'backup-root-id') {
return {
id,
source: 'backup',
pub: backupRoot.toBase58(),
provider: 'coincover',
keyId: 'cc-key-id',
signedPayload,
signature,
type: 'independent',
};
}
if (id === 'backup-child-id') {
return { id, pub: wrongChildPub, type: 'independent' };
}
return {
id: 'user-root-id',
source: 'user',
encryptedPrv: `enc:${ROOT_XPRV}`,
pub: 'root-xpub',
type: 'independent',
};
});
mockBitGo.post.returns({
send: sinon.stub().returns({
result: sinon.stub().resolves({
id: 'wallet-id',
coin: 'tbtc',
keys: ['child-key-id', 'backup-child-id', 'bitgo-child-id'],
type: 'hot',
multisigType: 'onchain',
enterprise: 'test-enterprise-id',
safe: 'test-safe-id',
}),
}),
});

// The environment config is the SDK's pinned-key source, so inject this test's attestation key.
const testEnv = Environments.test as { coinCoverAttestationPublicKeys: readonly string[] };
const previousAttestationKeys = testEnv.coinCoverAttestationPublicKeys;
testEnv.coinCoverAttestationPublicKeys = [attestationPublicKeyHex];
let wallet: unknown;
let error: unknown;
try {
wallet = await safe.createWallet({ coin: 'tbtc', label: 'desk 1', passphrase: 'pw' });
} catch (e) {
error = e;
} finally {
testEnv.coinCoverAttestationPublicKeys = previousAttestationKeys;
}

(wallet === undefined).should.be.true();
if (!(error instanceof Error)) {
throw new Error('expected createWallet to throw');
}
error.message.should.match(
/Safe wallet minted for secp256k1Multisig at m\/44'\/0'\/1'\/0': the backup child does not derive from the CoinCover backup root/
);
});

it('rejects a server coinType that differs from local statics before registering anything', async function () {
derivationQuery.returns({
result: sinon.stub().resolves({ slot: 'secp256k1Multisig', coinType: 60, account: 0 }),
Expand Down
Loading
Loading