diff --git a/modules/bitgo/test/v2/unit/enterprise.ts b/modules/bitgo/test/v2/unit/enterprise.ts index 0ea5211b113..04122bfbfdf 100644 --- a/modules/bitgo/test/v2/unit/enterprise.ts +++ b/modules/bitgo/test/v2/unit/enterprise.ts @@ -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 () { @@ -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 @@ -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); + }); }); }); diff --git a/modules/bitgo/test/v2/unit/internal/tssUtils/ecdsa.ts b/modules/bitgo/test/v2/unit/internal/tssUtils/ecdsa.ts index a5c5b36e8b2..f3dbea3564d 100644 --- a/modules/bitgo/test/v2/unit/internal/tssUtils/ecdsa.ts +++ b/modules/bitgo/test/v2/unit/internal/tssUtils/ecdsa.ts @@ -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. + 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); diff --git a/modules/sdk-core/src/bitgo/enterprise/enterprise.ts b/modules/sdk-core/src/bitgo/enterprise/enterprise.ts index da4f7e61244..7b9e9763037 100644 --- a/modules/sdk-core/src/bitgo/enterprise/enterprise.ts +++ b/modules/sdk-core/src/bitgo/enterprise/enterprise.ts @@ -10,7 +10,6 @@ import { ListWalletOptions, Wallet } from '../wallet'; import { Safes } from '../safe'; import { BitGoProofSignatures, EcdsaUtils, SerializedNtildeWithVerifiers } from '../utils/tss/ecdsa'; import { EcdsaTypes } from '@bitgo/sdk-lib-mpc'; -import { verifyEcdhSignature } from '../ecdh'; import { Buffer } from 'buffer'; import { EcdhDerivedKeypair } from '../keychain'; @@ -127,8 +126,25 @@ export class Enterprise implements IEnterprise { * @param userPassword * @param bitgoInstChallengeProofSignature * @param bitgoNitroChallengeProofSignature - * @param challenge + * @param challenge - deprecated; see overload */ + uploadAndEnableTssEcdsaSigning( + userPassword: string, + bitgoInstChallengeProofSignature: Buffer, + bitgoNitroChallengeProofSignature: Buffer, + openSSLBytes: Uint8Array + ): Promise; + /** + * @deprecated Passing `challenge` signs it without provenance verification. Omit it to generate a fresh + * challenge locally, or use resignTssEcdsaChallenge to re-sign the enterprise's existing challenge. + */ + uploadAndEnableTssEcdsaSigning( + userPassword: string, + bitgoInstChallengeProofSignature: Buffer, + bitgoNitroChallengeProofSignature: Buffer, + openSSLBytes: Uint8Array, + challenge?: EcdsaTypes.DeserializedNtildeWithProofs + ): Promise; async uploadAndEnableTssEcdsaSigning( userPassword: string, bitgoInstChallengeProofSignature: Buffer, @@ -147,12 +163,9 @@ export class Enterprise implements IEnterprise { ); } - /** - * Fetches the existing TSS ECDSA enterprise challenge if one exists. - * Can be used with uploadAndEnableTssEcdsaSigning to re-sign the - * enterprise challenge with new signatures. - */ - async getExistingTssEcdsaChallenge(): Promise { + private async fetchTssEcdsaEnterpriseChallenge(): Promise< + EcdsaTypes.SerializedNtildeWithProofs & { verifiers?: { adminSignature?: string } } + > { const urlPath = `/enterprise/${this.id}/tssconfig`; const tssConfig = await this.bitgo.get(this.bitgo.url(urlPath, 2)).send().result(); const enterpriseChallenge = tssConfig?.ecdsa.challenge?.enterprise; @@ -164,14 +177,63 @@ export class Enterprise implements IEnterprise { 'Existing ECDSA challenge does not have a proof. Please contact your enterprise admin to set this up.' ); } + return enterpriseChallenge; + } + + /** + * Fetches the existing TSS ECDSA enterprise challenge if one exists. + * The returned challenge is NOT verified. + * @deprecated Use {@link resignTssEcdsaChallenge} to re-sign the existing challenge. Signing the value returned here + * without verification lets a compromised server obtain an admin signature on a challenge whose trapdoor it knows. + */ + async getExistingTssEcdsaChallenge(): Promise { + const c = await this.fetchTssEcdsaEnterpriseChallenge(); return EcdsaTypes.deserializeNtildeWithProofs({ - ntilde: enterpriseChallenge.ntilde, - h1: enterpriseChallenge.h1, - h2: enterpriseChallenge.h2, - ntildeProof: enterpriseChallenge.ntildeProof, + ntilde: c.ntilde, + h1: c.h1, + h2: c.h2, + ntildeProof: c.ntildeProof, }); } + /** + * Re-signs the enterprise's existing TSS ECDSA challenge and BitGo's HSM challenges with the admin's ECDH key. + * Before signing, verifies that the existing challenge was previously signed by this admin's own ECDH key + * (pubkey derived from the decrypted xprv), is not a BitGo HSM challenge, and has valid ntilde proofs. + * If verification fails, generate a fresh challenge with uploadAndEnableTssEcdsaSigning instead. + * Takes roughly 30-40 seconds (three 3072-bit ntilde proof verifications). + * @param userPassword - enterprise admin's login password + */ + async resignTssEcdsaChallenge(userPassword: string): Promise { + const existing = await this.fetchTssEcdsaEnterpriseChallenge(); + const ecdhKeypair = await this.bitgo.getEcdhKeypairPrivate(userPassword, this.id); + const bitgoChallenges = await EcdsaUtils.getBitGoChallenges(this.bitgo); + await EcdsaUtils.verifyEnterpriseChallengeForResign(existing, ecdhKeypair, bitgoChallenges); + if (!(await EcdsaUtils.verifyBitGoChallenges(bitgoChallenges))) { + throw new Error( + `Failed to verify BitGo's challenge needed to enable ECDSA signing. Please contact support@bitgo.com` + ); + } + const entChallenge: EcdsaTypes.SerializedNtildeWithProofs = { + ntilde: existing.ntilde, + h1: existing.h1, + h2: existing.h2, + ntildeProof: existing.ntildeProof, + }; + const { xprv, derivationPath } = ecdhKeypair; + const signedEntChallenge = EcdsaUtils.signChallenge(entChallenge, xprv, derivationPath); + const signedInstChallenge = EcdsaUtils.signChallenge(bitgoChallenges.bitgoInstitutionalHsm, xprv, derivationPath); + const signedNitroChallenge = EcdsaUtils.signChallenge(bitgoChallenges.bitgoNitroHsm, xprv, derivationPath); + await EcdsaUtils.uploadChallengesToEnterprise( + this.bitgo, + this.id, + entChallenge, + signedEntChallenge.toString('hex'), + signedInstChallenge.toString('hex'), + signedNitroChallenge.toString('hex') + ); + } + /** * Resigns the enterprise and bitgo challenges with a new ECDH keychain. * Verifies that the old keychain signed the challenges previously. @@ -189,34 +251,24 @@ export class Enterprise implements IEnterprise { bitgoNitroChallenge: SerializedNtildeWithVerifiers ): Promise { // Verify all the challenges were signed by the old keypair - if ( - !verifyEcdhSignature( - EcdsaUtils.getMessageToSignFromChallenge(entChallenge), - entChallenge.verifiers.adminSignature, - Buffer.from(oldEcdhKeypair.derivedPubKey, 'hex') - ) - ) { + if (!EcdsaUtils.isChallengeSignedByEcdhKeypair(entChallenge, oldEcdhKeypair)) { throw new Error(`Cannot re-sign. The Enterprise TSS config was signed by another user.`); } - if ( - !verifyEcdhSignature( - EcdsaUtils.getMessageToSignFromChallenge(bitgoInstChallenge), - bitgoInstChallenge.verifiers.adminSignature, - Buffer.from(oldEcdhKeypair.derivedPubKey, 'hex') - ) - ) { + if (!EcdsaUtils.isChallengeSignedByEcdhKeypair(bitgoInstChallenge, oldEcdhKeypair)) { throw new Error(`Cannot re-sign. The BitGo Institutional TSS config was signed by another user.`); } + if (!EcdsaUtils.isChallengeSignedByEcdhKeypair(bitgoNitroChallenge, oldEcdhKeypair)) { + throw new Error(`Cannot re-sign. The BitGo Nitro TSS config was signed by another user.`); + } + // The old keychain legitimately signed BitGo's HSM challenges during setup, so a valid signature alone + // cannot distinguish the enterprise challenge from a replayed HSM challenge. Compare against the HSM + // challenges being re-signed: if the server serves one of them as the enterprise challenge, refuse. if ( - !verifyEcdhSignature( - EcdsaUtils.getMessageToSignFromChallenge(bitgoNitroChallenge), - bitgoNitroChallenge.verifiers.adminSignature, - Buffer.from(oldEcdhKeypair.derivedPubKey, 'hex') - ) + entChallenge.ntilde.toLowerCase() === bitgoInstChallenge.ntilde.toLowerCase() || + entChallenge.ntilde.toLowerCase() === bitgoNitroChallenge.ntilde.toLowerCase() ) { - throw new Error(`Cannot re-sign. The BitGo Nitro TSS config was signed by another user.`); + throw new Error('Cannot re-sign. The enterprise ECDSA challenge matches a BitGo HSM challenge.'); } - // Once all the challenges are verified, we can re-sign them with the new keypair. const signedEntChallenge = EcdsaUtils.signChallenge( entChallenge, diff --git a/modules/sdk-core/src/bitgo/enterprise/iEnterprise.ts b/modules/sdk-core/src/bitgo/enterprise/iEnterprise.ts index e2727916a93..a52b6bccdad 100644 --- a/modules/sdk-core/src/bitgo/enterprise/iEnterprise.ts +++ b/modules/sdk-core/src/bitgo/enterprise/iEnterprise.ts @@ -24,6 +24,16 @@ export interface IEnterprise { removeUser(params?: any): Promise; getFirstPendingTransaction(params?: Record): Promise; verifyEcdsaBitGoChallengeProofs(userPassword: string): Promise; + uploadAndEnableTssEcdsaSigning( + userPassword: string, + bitgoInstChallengeProofSignature: Buffer, + bitgoNitroChallengeProofSignature: Buffer, + openSSLBytes: Uint8Array + ): Promise; + /** + * @deprecated Passing `challenge` signs it without provenance verification. Omit it to generate a fresh + * challenge locally, or use resignTssEcdsaChallenge to re-sign the enterprise's existing challenge. + */ uploadAndEnableTssEcdsaSigning( userPassword: string, bitgoInstChallengeProofSignature: Buffer, @@ -31,7 +41,9 @@ export interface IEnterprise { openSSLBytes: Uint8Array, challenge?: EcdsaTypes.DeserializedNtildeWithProofs ): Promise; + /** @deprecated Use resignTssEcdsaChallenge. Returns an unverified challenge. */ getExistingTssEcdsaChallenge(): Promise; + resignTssEcdsaChallenge(userPassword: string): Promise; resignEnterpriseChallenges( oldEcdhKeypair: EcdhDerivedKeypair, newEcdhKeypair: EcdhDerivedKeypair, diff --git a/modules/sdk-core/src/bitgo/utils/tss/ecdsa/ecdsa.ts b/modules/sdk-core/src/bitgo/utils/tss/ecdsa/ecdsa.ts index fece8b88d0c..92856257059 100644 --- a/modules/sdk-core/src/bitgo/utils/tss/ecdsa/ecdsa.ts +++ b/modules/sdk-core/src/bitgo/utils/tss/ecdsa/ecdsa.ts @@ -7,7 +7,13 @@ import { EcdsaPaillierProof, EcdsaRangeProof, EcdsaTypes, hexToBigInt, minModulu import { bip32 } from '@bitgo/utxo-lib'; import { ECDSA, Ecdsa } from '../../../../account-lib/mpc/tss'; -import { AddKeychainOptions, Keychain, KeyType, WebauthnKeyEncryptionInfo } from '../../../keychain'; +import { + AddKeychainOptions, + EcdhDerivedKeypair, + Keychain, + KeyType, + WebauthnKeyEncryptionInfo, +} from '../../../keychain'; import ECDSAMethods, { ECDSAMethodTypes } from '../../../tss/ecdsa'; import { KeychainsTriplet } from '../../../baseCoin'; import { @@ -1133,6 +1139,75 @@ export class EcdsaUtils extends BaseEcdsaUtils { return challenge.ntilde.concat(challenge.h1).concat(challenge.h2); } + /** + * Derives the ECDH public key from the decrypted ECDH xprv. + * Use this, never a server-supplied `derivedPubKey`, when the key is the trust anchor for a signature check. + * @param ecdhKeypair - keypair whose xprv was decrypted locally with the user's password + */ + static getEcdhPubKeyFromXprv(ecdhKeypair: Pick): Buffer { + return bip32.fromBase58(ecdhKeypair.xprv).derivePath(ecdhKeypair.derivationPath).publicKey; + } + + /** + * Returns true iff `challenge.verifiers.adminSignature` is a valid signature over the challenge + * by the given ECDH keypair. The verifying pubkey is derived from the xprv. + * @param challenge - challenge with the stored admin signature + * @param ecdhKeypair - expected signer + */ + static isChallengeSignedByEcdhKeypair( + challenge: EcdsaTypes.SerializedNtilde & { verifiers?: { adminSignature?: string } }, + ecdhKeypair: Pick + ): boolean { + const adminSignature = challenge.verifiers?.adminSignature; + if (typeof adminSignature !== 'string' || adminSignature.length === 0) { + return false; + } + return verifyEcdhSignature( + this.getMessageToSignFromChallenge(challenge), + adminSignature, + this.getEcdhPubKeyFromXprv(ecdhKeypair) + ); + } + + /** + * Verifies an existing enterprise challenge before the admin's ECDH key re-signs it. + * Throws unless: + * 1. the stored admin signature was made by this admin's own ECDH key (provenance), + * 2. the challenge is not one of BitGo's current HSM challenges (whose trapdoor BitGo knows), + * 3. both ntilde discrete-log proofs verify (well-formedness; rejects degenerate h1/h2). + * @param challenge - existing enterprise challenge as served by BitGo + * @param ecdhKeypair - the admin's locally decrypted ECDH keypair + * @param bitgoChallenges - BitGo's current HSM challenges + */ + static async verifyEnterpriseChallengeForResign( + challenge: EcdsaTypes.SerializedNtildeWithProofs & { verifiers?: { adminSignature?: string } }, + ecdhKeypair: Pick, + bitgoChallenges: GetBitGoChallengesApi + ): Promise { + if (!this.isChallengeSignedByEcdhKeypair(challenge, ecdhKeypair)) { + throw new Error( + 'Cannot re-sign. The existing enterprise ECDSA challenge was not signed by your ECDH key. Generate a new challenge instead.' + ); + } + const ntilde = hexToBigInt(challenge.ntilde); + if ( + hexToBigInt(bitgoChallenges.bitgoInstitutionalHsm.ntilde) === ntilde || + hexToBigInt(bitgoChallenges.bitgoNitroHsm.ntilde) === ntilde + ) { + throw new Error('Cannot re-sign. The existing enterprise ECDSA challenge matches a BitGo HSM challenge.'); + } + let proofsValid: boolean; + try { + proofsValid = !!challenge.ntildeProof && (await this.verifyBitGoChallenge(challenge)); + } catch (e) { + // malformed hex in the proof makes deserialization throw + proofsValid = false; + } + if (!proofsValid) { + throw new Error('Cannot re-sign. The existing enterprise ECDSA challenge has invalid ntilde proofs.'); + } + } + /** Verifies ZK proofs of BitGo's challenges for both nitro and institutional HSMs which are fetched from the WP API. @@ -1272,7 +1347,7 @@ export class EcdsaUtils extends BaseEcdsaUtils { * @param userPassword - enterprise admin's login pw * @param bitgoInstChallengeProofSignature - signature on bitgo's institutional HSM challenge after verification * @param bitgoNitroChallengeProofSignature - signature on bitgo's nitro HSM challenge after verification - * @param challenge - optionally use the challenge for enterprise challenge + * @param challenge - optional enterprise challenge generated locally by the caller (e.g. EcdsaRangeProof.generateNtilde). It is signed WITHOUT verification; never pass a challenge fetched from BitGo. To re-sign the enterprise's existing challenge use Enterprise.resignTssEcdsaChallenge. */ static async initiateChallengesForEnterprise( bitgo: BitGoBase,