Skip to content
Merged
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
165 changes: 164 additions & 1 deletion modules/bitgo/test/v2/unit/enterprise.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@ import nock = require('nock');
import * as sinon from 'sinon';
import { common, ECDSAUtils, Enterprise } from '@bitgo/sdk-core';

require('should-sinon');

import { TestBitGo } from '@bitgo/sdk-test';
import { BitGo } from '../../../src/bitgo';
import { mockChallengeA } from './internal/tssUtils/mocks/ecdsaNtilde';
import { mockChallengeA, mockChallengeB, mockChallengeC } from './internal/tssUtils/mocks/ecdsaNtilde';
import { bip32 } from '@bitgo/utxo-lib';

describe('Enterprise:', function () {
Expand Down Expand Up @@ -111,6 +113,10 @@ describe('Enterprise:', function () {
},
};

afterEach(function () {
sinon.restore();
});

it('should verify and resign enterprise challenge', async function () {
const stubuUploadChallenges = sinon.stub(ECDSAUtils.EcdsaUtils, 'uploadChallengesToEnterprise');
await enterprise
Expand Down Expand Up @@ -171,5 +177,162 @@ describe('Enterprise:', function () {
)
.should.be.rejectedWith('Cannot re-sign. The Enterprise TSS config was signed by another user.');
});

it('should fail when the WP-supplied derivedPubKey does not match the old keychain xprv', async function () {
// oldEcdhKeypair carries a WP-supplied `derivedPubKey` matching the stored signatures, but the xprv is the
// new admin's. Verification must anchor on the xprv, so this must be rejected.
await enterprise
.resignEnterpriseChallenges(
{
xprv: newAdminEcdhKey.xprv,
derivationPath: newAdminDerivationPath,
derivedPubKey: bip32
.fromBase58(oldAdminEcdhKey.xpub)
.derivePath(oldAdminDerivationPath)
.publicKey.toString('hex'),
},
{
xprv: newAdminEcdhKey.xprv,
derivationPath: newAdminDerivationPath,
derivedPubKey: bip32
.fromBase58(newAdminEcdhKey.xpub)
.derivePath(newAdminDerivationPath)
.publicKey.toString('hex'),
},
entChallengeWithVerifiers,
bitgoChallengeWithVerifier,
bitgoChallengeWithVerifier
)
.should.be.rejectedWith('Cannot re-sign. The Enterprise TSS config was signed by another user.');
});
it('should fail when the enterprise challenge is a replayed BitGo HSM challenge', async function () {
// the old keychain genuinely signed the HSM challenge during setup, so the signature verifies; the
// HSM-equality guard must still reject it as the enterprise challenge
const hsmReplayChallenge: ECDSAUtils.SerializedNtildeWithVerifiers = {
...bitgoChallenge,
verifiers: {
adminSignature: signedBitgoChallenge.toString('hex'),
},
};
await enterprise
.resignEnterpriseChallenges(
{
xprv: oldAdminEcdhKey.xprv,
derivationPath: oldAdminDerivationPath,
derivedPubKey: bip32
.fromBase58(oldAdminEcdhKey.xpub)
.derivePath(oldAdminDerivationPath)
.publicKey.toString('hex'),
},
{
xprv: newAdminEcdhKey.xprv,
derivationPath: newAdminDerivationPath,
derivedPubKey: bip32
.fromBase58(newAdminEcdhKey.xpub)
.derivePath(newAdminDerivationPath)
.publicKey.toString('hex'),
},
hsmReplayChallenge,
bitgoChallengeWithVerifier,
bitgoChallengeWithVerifier
)
.should.be.rejectedWith('Cannot re-sign. The enterprise ECDSA challenge matches a BitGo HSM challenge.');
});
});
describe('resignTssEcdsaChallenge', function () {
const bitgo = TestBitGo.decorate(BitGo, { env: 'mock' });
const enterprise = new Enterprise(bitgo, bitgo.coin('tbtc'), { id: '123', name: 'Test Enterprise' });
const bgUrl = common.Environments[bitgo.getEnv()].uri;
const adminEcdhKey = bitgo.keychains().create();
const otherEcdhKey = bitgo.keychains().create();
const path = 'm/0/0';
const userPassword = 'password123';
let encryptedXprv: string;
let uploadStub: sinon.SinonStub;

const sign = (challenge: { ntilde: string; h1: string; h2: string }, key: { xprv: string }) =>
ECDSAUtils.EcdsaUtils.signChallenge(challenge, key.xprv, path).toString('hex');

before(async function () {
encryptedXprv = await bitgo.encrypt({
password: userPassword,
input: adminEcdhKey.xprv,
});
});

beforeEach(function () {
// WP reports `other`'s pubkey: the verification anchor is the decrypted xprv, so this must not matter
sinon.stub(bitgo, 'getSigningKeyForUser').resolves({
userId: 'id',
userEmail: 'user@bitgo.com',
derivedPubkey: bip32.fromBase58(otherEcdhKey.xpub).derivePath(path).publicKey.toString('hex'),
derivationPath: path,
ecdhKeychain: 'my keychain',
});
sinon.stub(bitgo, 'getECDHKeychain').resolves({
encryptedXprv: encryptedXprv,
});
sinon.stub(ECDSAUtils.EcdsaUtils, 'verifyBitGoChallenges').resolves(true);
uploadStub = sinon.stub(ECDSAUtils.EcdsaUtils, 'uploadChallengesToEnterprise').resolves();
nock(bgUrl)
.get('/api/v2/tss/ecdsa/challenges')
.reply(200, { bitgoInstitutionalHsm: mockChallengeA, bitgoNitroHsm: mockChallengeB });
});

afterEach(function () {
sinon.restore();
nock.cleanAll();
});

it('verifies the existing challenge and uploads the admin signatures', async function () {
const entry = { ...mockChallengeC, verifiers: { adminSignature: sign(mockChallengeC, adminEcdhKey) } };
nock(bgUrl)
.get(`/api/v2/enterprise/${enterprise.id}/tssconfig`)
.reply(200, { ecdsa: { challenge: { enterprise: entry } } });

await enterprise.resignTssEcdsaChallenge(userPassword).should.not.be.rejected();
uploadStub.callCount.should.equal(1);
uploadStub.should.be.calledWith(
bitgo,
'123',
{
ntilde: mockChallengeC.ntilde,
h1: mockChallengeC.h1,
h2: mockChallengeC.h2,
ntildeProof: mockChallengeC.ntildeProof,
},
sign(mockChallengeC, adminEcdhKey),
sign(mockChallengeA, adminEcdhKey),
sign(mockChallengeB, adminEcdhKey)
);
});

it('rejects and does not upload when WP serves a challenge signed by another key', async function () {
const entry = { ...mockChallengeC, verifiers: { adminSignature: sign(mockChallengeC, otherEcdhKey) } };
nock(bgUrl)
.get(`/api/v2/enterprise/${enterprise.id}/tssconfig`)
.reply(200, { ecdsa: { challenge: { enterprise: entry } } });

await enterprise
.resignTssEcdsaChallenge(userPassword)
.should.be.rejectedWith(
'Cannot re-sign. The existing enterprise ECDSA challenge was not signed by your ECDH key. Generate a new challenge instead.'
);
uploadStub.callCount.should.equal(0);
});

it('rejects and does not upload when WP serves a BitGo HSM challenge as the enterprise challenge', async function () {
const entry = { ...mockChallengeA, verifiers: { adminSignature: sign(mockChallengeA, adminEcdhKey) } };
nock(bgUrl)
.get(`/api/v2/enterprise/${enterprise.id}/tssconfig`)
.reply(200, { ecdsa: { challenge: { enterprise: entry } } });

await enterprise
.resignTssEcdsaChallenge(userPassword)
.should.be.rejectedWith(
'Cannot re-sign. The existing enterprise ECDSA challenge matches a BitGo HSM challenge.'
);
uploadStub.callCount.should.equal(0);
});
});
});
163 changes: 163 additions & 0 deletions modules/bitgo/test/v2/unit/internal/tssUtils/ecdsa.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1870,6 +1870,169 @@ describe('TSS Ecdsa Utils:', async function () {
});
});

describe('verifyEnterpriseChallengeForResign', function () {
const bitgo = TestBitGo.decorate(BitGo, { env: 'mock' });
const admin = bitgo.keychains().create();
const other = bitgo.keychains().create();
const path = 'm/0/0';
// `derivedPubKey` deliberately points at the wrong key: the verification anchor must be the xprv, not this field
const keypair = {
xprv: admin.xprv,
derivationPath: path,
derivedPubKey: bip32.fromBase58(other.xpub).derivePath(path).publicKey.toString('hex'),
};
const bitgoChallenges = {
bitgoInstitutionalHsm: mockChallengeA,
bitgoNitroHsm: mockChallengeB,
};

const sign = (challenge: EcdsaTypes.SerializedNtilde, key: { xprv: string }) =>
ECDSAUtils.EcdsaUtils.signChallenge(challenge, key.xprv, path).toString('hex');
const tamper = (hex: string) => hex.slice(0, -1) + (hex.endsWith('0') ? '1' : '0');

const notSignedMessage =
'Cannot re-sign. The existing enterprise ECDSA challenge was not signed by your ECDH key. Generate a new challenge instead.';
const hsmMessage = 'Cannot re-sign. The existing enterprise ECDSA challenge matches a BitGo HSM challenge.';
const proofsMessage = 'Cannot re-sign. The existing enterprise ECDSA challenge has invalid ntilde proofs.';

it('accepts a challenge signed by the admin keypair derived from the xprv', async function () {
const challenge = { ...mockChallengeC, verifiers: { adminSignature: sign(mockChallengeC, admin) } };
await ECDSAUtils.EcdsaUtils.verifyEnterpriseChallengeForResign(
challenge,
keypair,
bitgoChallenges
).should.not.be.rejected();
});

// bip32 sign/verify consume only the first 32 bytes of the ntilde+h1+h2 message, so only an ntilde-head
// tamper invalidates the signature; tampering h1/h2 (past that prefix) keeps the signature valid and is
// caught by the proof check instead. See follow-up on domain-separated signature messages.
Comment thread
mohammadalfaiyazbitgo marked this conversation as resolved.
Resolved
it('rejects a challenge whose ntilde head was tampered with', async function () {
const challenge = {
...mockChallengeC,
ntilde: (mockChallengeC.ntilde.startsWith('0') ? '1' : '0') + mockChallengeC.ntilde.slice(1),
verifiers: { adminSignature: sign(mockChallengeC, admin) },
};
await ECDSAUtils.EcdsaUtils.verifyEnterpriseChallengeForResign(
challenge,
keypair,
bitgoChallenges
).should.be.rejectedWith(notSignedMessage);
});

for (const field of ['h1', 'h2'] as const) {
it(`rejects a challenge whose ${field} was tampered with`, async function () {
const challenge = {
...mockChallengeC,
[field]: tamper(mockChallengeC[field]),
verifiers: { adminSignature: sign(mockChallengeC, admin) },
};
await ECDSAUtils.EcdsaUtils.verifyEnterpriseChallengeForResign(
challenge,
keypair,
bitgoChallenges
).should.be.rejectedWith(proofsMessage);
});
}

it('rejects a challenge signed by another key, even with a WP-supplied matching derivedPubKey', async function () {
const challenge = { ...mockChallengeC, verifiers: { adminSignature: sign(mockChallengeC, other) } };
await ECDSAUtils.EcdsaUtils.verifyEnterpriseChallengeForResign(
challenge,
keypair,
bitgoChallenges
).should.be.rejectedWith(notSignedMessage);
});

it('rejects a challenge with no verifiers', async function () {
const challenge = { ...mockChallengeC, verifiers: undefined };
await ECDSAUtils.EcdsaUtils.verifyEnterpriseChallengeForResign(
challenge,
keypair,
bitgoChallenges
).should.be.rejectedWith(notSignedMessage);
});

it('rejects a challenge with an empty adminSignature', async function () {
const challenge = { ...mockChallengeC, verifiers: { adminSignature: '' } };
await ECDSAUtils.EcdsaUtils.verifyEnterpriseChallengeForResign(
challenge,
keypair,
bitgoChallenges
).should.be.rejectedWith(notSignedMessage);
});

it('rejects a challenge with a garbage adminSignature', async function () {
const challenge = { ...mockChallengeC, verifiers: { adminSignature: 'deadbeef' } };
await ECDSAUtils.EcdsaUtils.verifyEnterpriseChallengeForResign(
challenge,
keypair,
bitgoChallenges
).should.be.rejectedWith(notSignedMessage);
});

it('rejects a challenge that matches the BitGo institutional HSM challenge', async function () {
const challenge = { ...mockChallengeA, verifiers: { adminSignature: sign(mockChallengeA, admin) } };
await ECDSAUtils.EcdsaUtils.verifyEnterpriseChallengeForResign(
challenge,
keypair,
bitgoChallenges
).should.be.rejectedWith(hsmMessage);
});

it('rejects a challenge that matches the BitGo nitro HSM challenge', async function () {
const challenge = { ...mockChallengeB, verifiers: { adminSignature: sign(mockChallengeB, admin) } };
await ECDSAUtils.EcdsaUtils.verifyEnterpriseChallengeForResign(
challenge,
keypair,
bitgoChallenges
).should.be.rejectedWith(hsmMessage);
});

it('rejects a challenge whose proofs do not match its ntilde', async function () {
const challenge = {
...mockChallengeC,
ntildeProof: mockChallengeA.ntildeProof,
verifiers: { adminSignature: sign(mockChallengeC, admin) },
};
await ECDSAUtils.EcdsaUtils.verifyEnterpriseChallengeForResign(
challenge,
keypair,
bitgoChallenges
).should.be.rejectedWith(proofsMessage);
});

it('rejects a challenge with malformed proof hex', async function () {
const challenge = {
...mockChallengeC,
ntildeProof: {
h1WrtH2: { alpha: ['zz'], t: ['zz'] },
h2WrtH1: { alpha: ['zz'], t: ['zz'] },
},
verifiers: { adminSignature: sign(mockChallengeC, admin) },
};
await ECDSAUtils.EcdsaUtils.verifyEnterpriseChallengeForResign(
challenge,
keypair,
bitgoChallenges
).should.be.rejectedWith(proofsMessage);
});

it('rejects a challenge without a proof', async function () {
// omits the required ntildeProof on purpose; cast keeps the literal assignable
const challenge = {
...mockChallengeC,
ntildeProof: undefined,
verifiers: { adminSignature: sign(mockChallengeC, admin) },
} as unknown as EcdsaTypes.SerializedNtildeWithProofs & { verifiers?: { adminSignature?: string } };
await ECDSAUtils.EcdsaUtils.verifyEnterpriseChallengeForResign(
challenge,
keypair,
bitgoChallenges
).should.be.rejectedWith(proofsMessage);
});
});

it('getMessageToSignFromChallenge concatenates the challenge values only', function () {
const challenge = mockChallengeA;
const expectedMessageToSign = challenge.ntilde.concat(challenge.h1).concat(challenge.h2);
Expand Down
Loading
Loading