diff --git a/src/__tests__/api/advancedWalletManager/mpcFinalize.test.ts b/src/__tests__/api/advancedWalletManager/mpcFinalize.test.ts index 41a9cf44..d2920bf8 100644 --- a/src/__tests__/api/advancedWalletManager/mpcFinalize.test.ts +++ b/src/__tests__/api/advancedWalletManager/mpcFinalize.test.ts @@ -9,6 +9,12 @@ import { BitGoAPI } from '@bitgo-beta/sdk-api'; import * as middleware from '../../../shared/middleware'; import { BitGoRequest } from '../../../types/request'; import * as utils from '../../../advancedWalletManager/handlers/utils/utils'; +import { + buildStateBindingAdata, + sealStateBlob, + STATE_BINDING_DOMAIN, + STATE_BINDING_MISMATCH_ERROR, +} from '../../../advancedWalletManager/handlers/utils/stateBinding'; const ENCRYPTED_DATA_KEY = '1,2,3,0,120,222,140,157,217,111,195,208,47,200,213,217,82,189,16,171,207,16,138,46,228,224,190,138,63,132,239,80,164,8,124,105,140,1,27,61,180,40,45,94,243,196,95,71,146,240,249,140,231,178,0,0,0,126,48,124,6,9,42,134,72,134,247,13,1,7,6,160,111,48,109,2,1,0,48,104,6,9,42,134,72,134,247,13,1,7,1,48,30,6,9,96,134,72,1,101,3,4,1,46,48,17,4,12,115,239,175,219,100,1,209,88,93,117,98,167,2,1,16,128,59,21,22,232,220,65,90,225,157,209,67,125,11,176,151,84,9,229,154,164,67,17,135,158,106,222,220,93,124,231,14,167,59,236,161,55,34,249,62,170,252,0,170,211,100,168,123,50,23,187,247,30,140,221,224,150,25,180,142,14'; @@ -19,6 +25,10 @@ const USER_GPG_PUB = const USER_PUBLIC_SHARE = 'b50eef93f764af40da7561d302bed1e14707fb73633f60e267b3d4b25fb9a94a56e56301b217ebdf27e6e8e1dcdfcb5de5e9c2fda6aba998b754c8baaba2ebe2'; +/** The plaintext KMS data key the /decryptDataKey nock hands back. */ +const MOCK_PLAINTEXT_KEY = + '115,23,145,49,185,59,87,165,87,53,233,8,177,59,137,233,118,9,5,73,119,147,55,122,141,249,161,156,19,13,224,101'; + describe('MPC Finalize', () => { let agent: request.SuperAgentTest; let app: express.Application; @@ -26,6 +36,22 @@ describe('MPC Finalize', () => { const keyProviderUrl = 'http://key-provider.test'; let bitgo: BitGoAPI; + /** + * Seals a keygen state blob the way `eddsaInitialize` does, bound to the given + * source and coin. The plaintext must be the finalize state fixture: the + * request's bitgo instance is the app's own (the middleware stub does not + * rebind its captured import), so the handler performs a real decrypt for the + * user source. The backup source stubs `BitGoAPI.prototype.decrypt`, which + * intercepts on any instance and serves the state itself. + */ + async function sealedKeygenState(source: 'user' | 'backup', stateJson: string, coin = 'tnear') { + return sealStateBlob(bitgo, { + plaintextKey: MOCK_PLAINTEXT_KEY, + plaintext: stateJson, + adata: buildStateBindingAdata(STATE_BINDING_DOMAIN.EDDSA_KEYGEN_INIT, { source, coin }), + }); + } + before(() => { nock.disableNetConnect(); nock.enableNetConnect('127.0.0.1'); @@ -245,8 +271,11 @@ describe('MPC Finalize', () => { source: 'user', coin: 'tnear', encryptedDataKey: ENCRYPTED_DATA_KEY, - encryptedData: - '{"iv":"YhMumA0FhhN1jbFODNsYZw==","v":1,"iter":10000,"ks":256,"ts":64,"mode":"ccm","adata":"","cipher":"aes","salt":"ViawevIgxJ0=","ct":"GTgvU0G3wI098jxZZ83M0mzJDpWVcFTv2qHzvP5Sg6BjUXPlgjaop/WfA7APDyGa6SDnVMCcxjEkxwaeNPK3D1DF0PHdiWX7RFuFVDRvc7l5mG8gAzfhIPsklK3JkGGwUZridXaVBhSBMpy00AXw7awKHCog7amybqpBfzdD6CUpG9MycnpGN0NbuWmoRMWJjFsGl0/BCjwJRVieOQngaL8Yn1qqXPoyjFjUPIKYJuRGFND6/XBD1Zc4Dt4wEIp4iGyYQ5im3G4NLku8TkJOEkSttB9yCm12CxEPJTrKqfSSKRRvJRpn9qusdtooK/AD5lwPp8LfBv3YEid7JqUnD4QmDyoB4QGk0ktLzMR6D/qk1w74MLxLPFWiUvC8zYqdBYCJV6/BrbprD8UL5xzhio7Rqkc0MMX/Yk1j7qdbAi8mbdUd62JKQ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SF7LbsoifFDDtR62LYZjn6jMmKT3/QID9yb/2xtICQTvYn1a7yAmXSY6DBYgdGh6iH+G0wgpcqyVyJjwur97aoOE3dbGBWcN+U81ZbfyRuIXgCj4/ubdJ4YvKOZ5eLKv2KgHGg80sIEnj7lugGXfGpU9PBSuhM/0WZDrr4UsEyGwoKGGZtxTb9qwPs0JrfDHngkyNbnfJsNVa9NPQWLrM+oTy8010pAlPmf/+6r8E7UwgkXlt/945mK7wGFyaY4yZxqloGEY3VSwHVb7wk1nixvDpBdfQpWrKVuak9DhQdd1IPJLRmNawMru4RZmSviylH6LPYxW6O8yTZsj1J478Cu6d9OjWassAdTDjbceohKTLIpW7IpQ/noiPkN2lMY+EYl5F99RfuFlFnzZmG0jFcoDA5GcV9/NJhlADWZ5uXnr+fhEAlQVxO8gCqU1IET9hUq3GdqGKQB6B+z9lnEaR6UFcmnYoGMrnvwDO9XeXRyX1BEYth7cjboVhXkCEfQ6gWQW9CMT+/VD3OKsZIxgSXoQD1zdgiL8KjQiOfELtOK5wGnAqsNqt973znG0o/y/uWbLydDA+Gu+9VTBpBafVUvENKrZUuoSF5jlXsrlHinlRV/CEE4VmekJjiSm4Cqo5AOBWJH9irSmhOe4nAKCZYRUDjQJoLr9wfKagceATgl6ubXAezpb0+Xhw5GkkbNps74S55hHOhga8XeMg6gu85s1lt4Wat+OwIxfV099EGvJNjQquUfn56zW4ySc0UWb3KN8WUpdW7Nu6q2wiSODE/VJ31NI/QGmBPhtMpkdnibgJcrtGka6t1q2rbApA1E7oNxiHZ6deOOXAvWGnya3m257Cyacs7TaDMBZ2L/67EoDmtqlGkvHCP0wjaPvSCKOezfNRrRsdQm3gKDHtVX6zbgr9v5SkbPuGaRhy4yU3JQBAbjwEU60iP+4wCfYdEqTNfns/OYRAHQFcmJd/0C8Wt9qxqTjHMA=="}', + encryptedData: await sealedKeygenState( + 'user', + // the decrypt stub below is the single source of truth for the state + await bitgo.decrypt({ input: '', password: '' }), + ), counterPartyKeyShare: { from: 'backup', to: 'user', @@ -266,7 +295,6 @@ describe('MPC Finalize', () => { 'cXRNGpOdAQD0VWVgbXmPiqXOzk9Aqwo4iuxiMpoSjcOGjelJhtiI685TBGiK\n' + 'QMASBSuBBAAKAgMEfASPaxeQfF8fbxj+IxA1IvBNUTVnfdavndamohiBY208\n' + 'fiyFttYfh6aTww6QqlWzqPXY9kU3/+PkgIhDI/Za2AMBCAfCeAQYEwgAKgWC\n' + - 'aIpAwAmQFvKwNF9M/BICmwwWIQRyXP44VjLqqZqNDT4W8rA0X0z8EgAAov8B\n' + 'AM92AiJU5QupKoVPSmNyaHoVSUC1zaFqUub2huTY0lliAQCWhmA0x9ZDWlCs\n' + 'B3oLcs3H7MksK2f2DcOkRnTpmEyMLs4zBGiKQMAWCSsGAQQB2kcPAQEHQJz+\n' + 'NwYGNBFZSUNzAtDD3h2eNNvvN8DHaPq0bpqF7SPlwngEGBMIACoFgmiKQMAJ\n' + @@ -472,8 +500,11 @@ describe('MPC Finalize', () => { source: 'backup', coin: 'tnear', encryptedDataKey: ENCRYPTED_DATA_KEY, - encryptedData: - '{"iv":"YhMumA0FhhN1jbFODNsYZw==","v":1,"iter":10000,"ks":256,"ts":64,"mode":"ccm","adata":"","cipher":"aes","salt":"ViawevIgxJ0=","ct":"backup-encrypted-data"}', + encryptedData: await sealedKeygenState( + 'backup', + // the prototype decrypt stub below serves the backup fixture + 'backup finalize state placeholder', + ), counterPartyKeyShare: { from: 'user', to: 'backup', @@ -499,4 +530,82 @@ describe('MPC Finalize', () => { result.body.counterpartyKeyShare.should.have.property('from', 'backup'); result.body.counterpartyKeyShare.should.have.property('to', 'user'); }); + + it('should reject a keygen state blob replayed for the other source', async () => { + // Key provider unwraps the data key; the binding check then rejects the + // user-sealed blob before any state is decrypted. + nock(keyProviderUrl).post('/decryptDataKey').reply(200, { plaintextKey: MOCK_PLAINTEXT_KEY }); + + const result = await agent.post('/api/tnear/mpc/key/finalize').send({ + source: 'backup', + coin: 'tnear', + encryptedDataKey: ENCRYPTED_DATA_KEY, + encryptedData: await sealedKeygenState( + 'user', + // rejected at the binding check before any decryption + 'unused placeholder state', + ), + counterPartyGpgPub: USER_GPG_PUB, + bitgoKeyChain: { + id: '688a40c546bf78887fd5880e255b5963', + source: 'bitgo', + type: 'tss', + commonKeychain: + '821273e7e8ad33fd73d4b924bc83322b5a57027b3db9005355153c57d0512a9e97398fa3ac5f3f0cc6d2fe82c8d8b12c85e8ff572b212aa41ba384201552c9e0', + verifiedVssProof: true, + keyShares: [], + }, + counterPartyKeyShare: { + from: 'user', + to: 'backup', + publicShare: USER_PUBLIC_SHARE, + privateShare: '00', + privateShareProof: USER_GPG_PUB, + vssProof: '00', + gpgKey: USER_GPG_PUB, + }, + }); + + result.should.have.property('statusCode', 400); + result.body.should.have.property('details', STATE_BINDING_MISMATCH_ERROR); + }); + + it('should reject a keygen state blob replayed for another coin', async () => { + // Key provider unwraps the data key; the binding check then rejects the + // tnear-sealed blob before any state is decrypted. + nock(keyProviderUrl).post('/decryptDataKey').reply(200, { plaintextKey: MOCK_PLAINTEXT_KEY }); + + const result = await agent.post('/api/tsol/mpc/key/finalize').send({ + source: 'user', + coin: 'tsol', + encryptedDataKey: ENCRYPTED_DATA_KEY, + encryptedData: await sealedKeygenState( + 'user', + // rejected at the binding check before any decryption + 'unused placeholder state', + ), + counterPartyGpgPub: USER_GPG_PUB, + bitgoKeyChain: { + id: '688a40c546bf78887fd5880e255b5963', + source: 'bitgo', + type: 'tss', + commonKeychain: + '821273e7e8ad33fd73d4b924bc83322b5a57027b3db9005355153c57d0512a9e97398fa3ac5f3f0cc6d2fe82c8d8b12c85e8ff572b212aa41ba384201552c9e0', + verifiedVssProof: true, + keyShares: [], + }, + counterPartyKeyShare: { + from: 'backup', + to: 'user', + publicShare: USER_PUBLIC_SHARE, + privateShare: '00', + privateShareProof: USER_GPG_PUB, + vssProof: '00', + gpgKey: USER_GPG_PUB, + }, + }); + + result.should.have.property('statusCode', 400); + result.body.should.have.property('details', STATE_BINDING_MISMATCH_ERROR); + }); }); diff --git a/src/__tests__/api/advancedWalletManager/postMpcV2Key.test.ts b/src/__tests__/api/advancedWalletManager/postMpcV2Key.test.ts index 26be2410..6d65deb0 100644 --- a/src/__tests__/api/advancedWalletManager/postMpcV2Key.test.ts +++ b/src/__tests__/api/advancedWalletManager/postMpcV2Key.test.ts @@ -10,6 +10,7 @@ import * as configModule from '../../../initConfig'; import * as bitgoSdk from '@bitgo-beta/sdk-core'; import { DklsComms, DklsDkg, DklsTypes } from '@bitgo-beta/sdk-lib-mpc'; import { MPCv2PartiesEnum } from '@bitgo-beta/sdk-core/dist/src/bitgo/utils/tss/ecdsa'; +import { STATE_BINDING_MISMATCH_ERROR } from '../../../advancedWalletManager/handlers/utils/stateBinding'; describe('postMpcV2Key', () => { let cfg: AdvancedWalletManagerConfig; @@ -534,8 +535,10 @@ describe('postMpcV2Key', () => { }, }); - skipRoundResponse.status.should.equal(422); - skipRoundResponse.body.should.have.property('details', 'Round mismatch: expected 2, got 3'); + // the round-1 state is sealed for round 2; the binding check rejects the + // out-of-sequence replay before the state's own round comparison runs + skipRoundResponse.status.should.equal(400); + skipRoundResponse.body.should.have.property('details', STATE_BINDING_MISMATCH_ERROR); // repeating round 1 const repeatRoundResponse = await agent @@ -550,8 +553,8 @@ describe('postMpcV2Key', () => { counterPartyGpgPub: backupInitResponse.body.gpgPub, }); - repeatRoundResponse.status.should.equal(422); - repeatRoundResponse.body.should.have.property('details', 'Round mismatch: expected 2, got 1'); + repeatRoundResponse.status.should.equal(400); + repeatRoundResponse.body.should.have.property('details', STATE_BINDING_MISMATCH_ERROR); }); it('should throw error if broadcastMessages or p2pMessages does not contain all required messages', async () => { @@ -724,4 +727,33 @@ describe('postMpcV2Key', () => { 'p2pMessages did not contain all required messages', ); }); + + it('should reject a keygen state blob replayed for the other source', async () => { + const userInitResponse = await agent + .post(`/api/${coin}/mpcv2/initialize`) + .set('Authorization', `Bearer ${accessToken}`) + .send({ source: 'user' }); + + const backupInitResponse = await agent + .post(`/api/${coin}/mpcv2/initialize`) + .set('Authorization', `Bearer ${accessToken}`) + .send({ source: 'backup' }); + + // The user's initialize state is sealed for source 'user'; replaying it + // against a backup round request must be rejected before decryption. + const response = await agent + .post(`/api/${coin}/mpcv2/round`) + .set('Authorization', `Bearer ${accessToken}`) + .send({ + source: 'backup', + encryptedData: userInitResponse.body.encryptedData, + encryptedDataKey: userInitResponse.body.encryptedDataKey, + round: 1, + bitgoGpgPub: userInitResponse.body.gpgPub, + counterPartyGpgPub: backupInitResponse.body.gpgPub, + }); + + response.status.should.equal(400); + response.body.should.have.property('details', STATE_BINDING_MISMATCH_ERROR); + }); }); diff --git a/src/__tests__/api/advancedWalletManager/signMpcTransaction.test.ts b/src/__tests__/api/advancedWalletManager/signMpcTransaction.test.ts index 16b99343..5c7241bf 100644 --- a/src/__tests__/api/advancedWalletManager/signMpcTransaction.test.ts +++ b/src/__tests__/api/advancedWalletManager/signMpcTransaction.test.ts @@ -15,6 +15,14 @@ import assert from 'assert'; import { signBitgoMPCv2Round1, signBitgoMPCv2Round2, signBitgoMPCv2Round3 } from './ecdsaUtils'; import { Hash } from 'crypto'; import createKeccakHash from 'keccak'; +import { BitGoAPI } from '@bitgo-beta/sdk-api'; +import { + buildStateBindingAdata, + getSignableBindingParts, + sealStateBlob, + STATE_BINDING_DOMAIN, + STATE_BINDING_MISMATCH_ERROR, +} from '../../../advancedWalletManager/handlers/utils/stateBinding'; import { bitgoGpgKey } from '../../mocks/gpgKeys'; describe('signMpcTransaction', () => { @@ -260,6 +268,149 @@ describe('signMpcTransaction', () => { gDecryptDataKeyNock.done(); }); + it('should reject an R-share blob replayed from the keygen flow', async () => { + // A keygen state blob sealed under the same KMS data key, bound to the + // keygen flow. Replaying it into the signing R round must be rejected + // before any plaintext is returned. + const keygenBlob = await sealStateBlob(new BitGoAPI({ env: 'test' }), { + plaintextKey: 'mock-plaintext-data-key', + plaintext: JSON.stringify({ + sourceGpgPub: 'source-gpg-pub', + sourceGpgPrv: 'source-gpg-prv', + sourcePrivateShare: 'source-private-share', + }), + adata: buildStateBindingAdata(STATE_BINDING_DOMAIN.EDDSA_KEYGEN_INIT, { + source: 'user', + }), + }); + const rInput = { + source: 'user', + pub: 'DSqMPMsMAbEJVNuPKv1ZFdzt6YvJaDPDddfeW7ajtqds', + txRequest: mockTxRequest, + encryptedUserToBitgoRShare: { + from: 'user', + to: 'bitgo', + type: 'encryptedSignerShare', + share: keygenBlob, + }, + encryptedDataKey: 'mock-encrypted-data-key', + }; + + const rKeyProviderNock = nock(keyProviderUrl) + .get(`/key/${rInput.pub}`) + .query({ source: 'user' }) + .reply(200, { prv: 'mock-prv', pub: rInput.pub, source: 'user', type: 'independent' }); + const decryptDataKeyNock = nock(keyProviderUrl) + .post('/decryptDataKey') + .reply(200, { plaintextKey: 'mock-plaintext-data-key' }); + + const rResponse = await agent + .post(`/api/${coin}/mpc/sign/r`) + .set('Authorization', `Bearer ${accessToken}`) + .send(rInput); + + rResponse.status.should.equal(400); + rResponse.body.should.not.have.property('rShare'); + rResponse.body.details.should.equal(STATE_BINDING_MISMATCH_ERROR); + rKeyProviderNock.done(); + decryptDataKeyNock.done(); + }); + + it('should reject an R-share blob with no context binding', async () => { + // A legacy envelope encrypted under the data key without associated data. + const unboundBlob = await new BitGoAPI({ env: 'test' }).encrypt({ + input: 'state sealed before blobs carried a binding', + password: 'mock-plaintext-data-key', + encryptionVersion: 1, + }); + const rInput = { + source: 'user', + pub: 'DSqMPMsMAbEJVNuPKv1ZFdzt6YvJaDPDddfeW7ajtqds', + txRequest: mockTxRequest, + encryptedUserToBitgoRShare: { + from: 'user', + to: 'bitgo', + type: 'encryptedSignerShare', + share: unboundBlob, + }, + encryptedDataKey: 'mock-encrypted-data-key', + }; + + const rKeyProviderNock = nock(keyProviderUrl) + .get(`/key/${rInput.pub}`) + .query({ source: 'user' }) + .reply(200, { prv: 'mock-prv', pub: rInput.pub, source: 'user', type: 'independent' }); + const decryptDataKeyNock = nock(keyProviderUrl) + .post('/decryptDataKey') + .reply(200, { plaintextKey: 'mock-plaintext-data-key' }); + + const rResponse = await agent + .post(`/api/${coin}/mpc/sign/r`) + .set('Authorization', `Bearer ${accessToken}`) + .send(rInput); + + rResponse.status.should.equal(400); + rResponse.body.should.not.have.property('rShare'); + rResponse.body.details.should.equal(STATE_BINDING_MISMATCH_ERROR); + rKeyProviderNock.done(); + decryptDataKeyNock.done(); + }); + + it('should reject an R-share blob bound to a different signing session', async () => { + // Sealed with the signing domain, but for a different signable payload. + const otherTxRequest = { + ...mockTxRequest, + transactions: [ + { + unsignedTx: { + derivationPath: 'm/0', + signableHex: 'a-different-signable', + }, + }, + ], + } as typeof mockTxRequest; + const otherSessionBlob = await sealStateBlob(new BitGoAPI({ env: 'test' }), { + plaintextKey: 'mock-plaintext-data-key', + plaintext: 'sign share for another signable', + adata: buildStateBindingAdata(STATE_BINDING_DOMAIN.EDDSA_SIGN_R_SHARE, { + source: 'user', + pub: 'DSqMPMsMAbEJVNuPKv1ZFdzt6YvJaDPDddfeW7ajtqds', + ...getSignableBindingParts(otherTxRequest as unknown as TxRequest), + }), + }); + const rInput = { + source: 'user', + pub: 'DSqMPMsMAbEJVNuPKv1ZFdzt6YvJaDPDddfeW7ajtqds', + txRequest: mockTxRequest, + encryptedUserToBitgoRShare: { + from: 'user', + to: 'bitgo', + type: 'encryptedSignerShare', + share: otherSessionBlob, + }, + encryptedDataKey: 'mock-encrypted-data-key', + }; + + const rKeyProviderNock = nock(keyProviderUrl) + .get(`/key/${rInput.pub}`) + .query({ source: 'user' }) + .reply(200, { prv: 'mock-prv', pub: rInput.pub, source: 'user', type: 'independent' }); + const decryptDataKeyNock = nock(keyProviderUrl) + .post('/decryptDataKey') + .reply(200, { plaintextKey: 'mock-plaintext-data-key' }); + + const rResponse = await agent + .post(`/api/${coin}/mpc/sign/r`) + .set('Authorization', `Bearer ${accessToken}`) + .send(rInput); + + rResponse.status.should.equal(400); + rResponse.body.should.not.have.property('rShare'); + rResponse.body.details.should.equal(STATE_BINDING_MISMATCH_ERROR); + rKeyProviderNock.done(); + decryptDataKeyNock.done(); + }); + it('should fail G share generation without the encrypted commitment round state', async () => { const input = { source: 'user', diff --git a/src/advancedWalletManager/handlers/ecdsaEddsaSignTransaction.ts b/src/advancedWalletManager/handlers/ecdsaEddsaSignTransaction.ts index 15a2b89e..96003607 100644 --- a/src/advancedWalletManager/handlers/ecdsaEddsaSignTransaction.ts +++ b/src/advancedWalletManager/handlers/ecdsaEddsaSignTransaction.ts @@ -3,6 +3,13 @@ import { EddsaUserToBitgoRShare, } from '../routers/advancedWalletManagerApiSpec'; import { decryptDataKey, generateDataKey, retrieveKeyProviderPrvKey } from './utils/utils'; +import { + buildStateBindingAdata, + getSignableBindingParts, + openStateBlob, + sealStateBlob, + STATE_BINDING_DOMAIN, +} from './utils/stateBinding'; import logger from '../../shared/logger'; import { BaseCoin, @@ -70,6 +77,8 @@ interface EddsaSigningParams { shareType: string; txRequest: TxRequest; prv: string; + pub: string; + source: string; encryptedDataKey?: string; bitgoToUserRShare?: SignatureShareRecord; encryptedUserToBitgoRShare?: EncryptedSignerShareRecord; @@ -128,6 +137,8 @@ export async function signMpcTransaction(req: AwmApiSpecRouteRequest<'v1.mpc.sig shareType, txRequest: req.decoded.txRequest, prv, + pub, + source, encryptedDataKey, bitgoToUserRShare: req.decoded.bitgoToUserRShare, encryptedUserToBitgoRShare: req.decoded.encryptedUserToBitgoRShare, @@ -176,6 +187,8 @@ async function handleEddsaSigning( shareType, txRequest, prv, + pub, + source, encryptedDataKey, bitgoToUserRShare, encryptedUserToBitgoRShare, @@ -198,17 +211,36 @@ async function handleEddsaSigning( walletPassphrase: dataKey.plaintextKey, bitgoGpgPubKey: bitgoPublicGpgKey, }; + const commitment = await eddsaUtils.createCommitmentShareFromTxRequest(commitmentParams); + // Bind the R-share envelope to this wallet and signing session so the R + // and G rounds reject blobs replayed from any other flow. + const adata = buildStateBindingAdata(STATE_BINDING_DOMAIN.EDDSA_SIGN_R_SHARE, { + source, + pub, + ...getSignableBindingParts(txRequest), + }); return { - ...(await eddsaUtils.createCommitmentShareFromTxRequest(commitmentParams)), + userToBitgoCommitment: commitment.userToBitgoCommitment, + encryptedSignerShare: commitment.encryptedSignerShare, + encryptedUserToBitgoRShare: { + ...commitment.encryptedUserToBitgoRShare, + share: await sealStateBlob(bitgo, { + plaintextKey: dataKey.plaintextKey, + plaintext: commitment.encryptedUserToBitgoRShare.share, + adata, + }), + }, encryptedDataKey: dataKey.encryptedKey, }; } case ShareType.R: { - const userSignShare = await decryptUserSignShare(eddsaUtils, cfg, { + const userSignShare = await decryptUserSignShare(eddsaUtils, bitgo, cfg, { shareType: ShareType.R, txRequest, encryptedDataKey, encryptedUserToBitgoRShare, + pub, + source, }); const rShare = userSignShare.rShares[ShareKeyPosition.BITGO]; if (!rShare) { @@ -224,11 +256,13 @@ async function handleEddsaSigning( if (!bitgoToUserCommitment) { throw new Error('bitgoToUserCommitment is required for G share generation'); } - const userToBitgoRShare = await decryptUserSignShare(eddsaUtils, cfg, { + const userToBitgoRShare = await decryptUserSignShare(eddsaUtils, bitgo, cfg, { shareType: ShareType.G, txRequest, encryptedDataKey, encryptedUserToBitgoRShare, + pub, + source, }); const gShareParams: GShareParams = { txRequest, @@ -249,15 +283,18 @@ async function handleEddsaSigning( async function decryptUserSignShare( eddsaUtils: EddsaUtils, + bitgo: BitGoAPI, cfg: AdvancedWalletManagerConfig, params: { shareType: ShareType; txRequest: TxRequest; encryptedDataKey?: string; encryptedUserToBitgoRShare?: EncryptedSignerShareRecord; + pub: string; + source: string; }, ): Promise { - const { txRequest, encryptedDataKey, encryptedUserToBitgoRShare } = params; + const { txRequest, encryptedDataKey, encryptedUserToBitgoRShare, pub, source } = params; const shareType = params.shareType.toUpperCase(); if (!encryptedUserToBitgoRShare) { throw new Error(`encryptedUserToBitgoRShare is required for ${shareType} share generation`); @@ -268,10 +305,22 @@ async function decryptUserSignShare( ); } const plaintextDataKey = await decryptDataKey({ encryptedDataKey, cfg }); + // Verify the blob was sealed by the commitment round for this wallet and + // signable before handing the inner envelope to the SDK for decryption. + const expectedAdata = buildStateBindingAdata(STATE_BINDING_DOMAIN.EDDSA_SIGN_R_SHARE, { + source, + pub, + ...getSignableBindingParts(txRequest), + }); + const boundShare = await openStateBlob(bitgo, { + plaintextKey: plaintextDataKey, + ciphertext: encryptedUserToBitgoRShare.share, + expectedAdata, + }); const rShareParams: RShareParams = { txRequest, walletPassphrase: plaintextDataKey, - encryptedUserToBitgoRShare, + encryptedUserToBitgoRShare: { ...encryptedUserToBitgoRShare, share: boundShare }, }; const { rShare } = await eddsaUtils.createRShareFromTxRequest(rShareParams); return rShare; diff --git a/src/advancedWalletManager/handlers/ecdsaMPCV2WalletGenerationFinalize.ts b/src/advancedWalletManager/handlers/ecdsaMPCV2WalletGenerationFinalize.ts index 320d93e8..2fc71054 100644 --- a/src/advancedWalletManager/handlers/ecdsaMPCV2WalletGenerationFinalize.ts +++ b/src/advancedWalletManager/handlers/ecdsaMPCV2WalletGenerationFinalize.ts @@ -6,6 +6,7 @@ import { } from '../routers/advancedWalletManagerApiSpec'; import { KeyProviderClient } from '../keyProviderClient/keyProviderClient'; import assert from 'assert'; +import { buildStateBindingAdata, openStateBlob, STATE_BINDING_DOMAIN } from './utils/stateBinding'; export async function ecdsaMPCv2Finalize( req: AwmApiSpecRouteRequest<'v1.mpcv2.finalize', 'post'>, @@ -16,12 +17,18 @@ export async function ecdsaMPCv2Finalize( // setup clients const keyProvider = new KeyProviderClient(req.config); - // fetch previous state of execution + // fetch previous state of execution. The state must be bound to this keygen + // flow, source, and finalize stage; blobs replayed from any other flow or + // round slot are rejected before decryption. const { plaintextKey } = await keyProvider.decryptDataKey({ encryptedKey: encryptedDataKey }); const state: MpcV2RoundState = JSON.parse( - await req.bitgo.decrypt({ - input: encryptedData, - password: plaintextKey, + await openStateBlob(req.bitgo, { + plaintextKey, + ciphertext: encryptedData, + expectedAdata: buildStateBindingAdata(STATE_BINDING_DOMAIN.ECDSA_MPCV2_KEYGEN, { + source, + round: 'finalize', + }), }), ); if (!state.bitgoGpgPub || !state.counterPartyGpgPub) { diff --git a/src/advancedWalletManager/handlers/ecdsaMPCV2WalletGenerationInitialize.ts b/src/advancedWalletManager/handlers/ecdsaMPCV2WalletGenerationInitialize.ts index 460804d6..c21bdb50 100644 --- a/src/advancedWalletManager/handlers/ecdsaMPCV2WalletGenerationInitialize.ts +++ b/src/advancedWalletManager/handlers/ecdsaMPCV2WalletGenerationInitialize.ts @@ -7,6 +7,7 @@ import { KeyProviderClient } from '../keyProviderClient/keyProviderClient'; import * as bitgoSdk from '@bitgo-beta/sdk-core'; import logger from '../../shared/logger'; import { MPCv2PartiesEnum } from '@bitgo-beta/sdk-core/dist/src/bitgo/utils/tss/ecdsa'; +import { buildStateBindingAdata, sealStateBlob, STATE_BINDING_DOMAIN } from './utils/stateBinding'; export async function ecdsaMPCv2Initialize( req: AwmApiSpecRouteRequest<'v1.mpcv2.initialize', 'post'>, @@ -30,10 +31,15 @@ export async function ecdsaMPCv2Initialize( }; try { - // Encrypt the state with the plaintext key - const encryptedData = await req.bitgo.encrypt({ - input: JSON.stringify(state), - password: plaintextKey, + // Bind the keygen state to its flow, source, and consuming round so it + // cannot be replayed into any other decrypt path or round slot. + const encryptedData = await sealStateBlob(req.bitgo, { + plaintextKey, + plaintext: JSON.stringify(state), + adata: buildStateBindingAdata(STATE_BINDING_DOMAIN.ECDSA_MPCV2_KEYGEN, { + source, + round: '1', + }), }); return { diff --git a/src/advancedWalletManager/handlers/ecdsaMPCV2WalletGenerationRound.ts b/src/advancedWalletManager/handlers/ecdsaMPCV2WalletGenerationRound.ts index 1d0881c6..7bac0bc9 100644 --- a/src/advancedWalletManager/handlers/ecdsaMPCV2WalletGenerationRound.ts +++ b/src/advancedWalletManager/handlers/ecdsaMPCV2WalletGenerationRound.ts @@ -8,6 +8,12 @@ import { MPCv2PartiesEnum } from '@bitgo-beta/sdk-core/dist/src/bitgo/utils/tss/ import { KeyProviderClient } from '../keyProviderClient/keyProviderClient'; import logger from '../../shared/logger'; import { BadRequestError, ValidationError } from '../../shared/errors'; +import { + buildStateBindingAdata, + openStateBlob, + sealStateBlob, + STATE_BINDING_DOMAIN, +} from './utils/stateBinding'; export async function ecdsaMPCv2Round( req: AwmApiSpecRouteRequest<'v1.mpcv2.round', 'post'>, @@ -37,12 +43,18 @@ export async function ecdsaMPCv2Round( throw new BadRequestError('p2pMessages did not contain all required messages'); } - // fetch previous state of execution + // fetch previous state of execution. The state must be bound to this keygen + // flow and source; blobs replayed from any other flow are rejected before + // decryption. const { plaintextKey } = await keyProvider.decryptDataKey({ encryptedKey: encryptedDataKey }); const state: MpcV2RoundState = JSON.parse( - await req.bitgo.decrypt({ - input: encryptedData, - password: plaintextKey, + await openStateBlob(req.bitgo, { + plaintextKey, + ciphertext: encryptedData, + expectedAdata: buildStateBindingAdata(STATE_BINDING_DOMAIN.ECDSA_MPCV2_KEYGEN, { + source, + round: String(round), + }), }), ); @@ -136,16 +148,20 @@ export async function ecdsaMPCv2Round( [sourceGpgPrv], ); - // re-encrypt state + // re-encrypt state, preserving the flow, source, and next-consuming-stage binding let newEncryptedData; try { - newEncryptedData = await req.bitgo.encrypt({ - input: JSON.stringify({ + newEncryptedData = await sealStateBlob(req.bitgo, { + plaintextKey, + plaintext: JSON.stringify({ ...state, round: state.round + 1, sessionData: session.getSessionData(), }), - password: plaintextKey, + adata: buildStateBindingAdata(STATE_BINDING_DOMAIN.ECDSA_MPCV2_KEYGEN, { + source, + round: state.round === 4 ? 'finalize' : String(state.round + 1), + }), }); } catch (error) { logger.error('Encryption error details:', error); diff --git a/src/advancedWalletManager/handlers/eddsaMPCWalletGenerationFinalize.ts b/src/advancedWalletManager/handlers/eddsaMPCWalletGenerationFinalize.ts index 96172b0b..f69d8487 100644 --- a/src/advancedWalletManager/handlers/eddsaMPCWalletGenerationFinalize.ts +++ b/src/advancedWalletManager/handlers/eddsaMPCWalletGenerationFinalize.ts @@ -7,6 +7,7 @@ import { } from '../routers/advancedWalletManagerApiSpec'; import { KeyProviderClient } from '../keyProviderClient/keyProviderClient'; import { eddsaKeyCombine, gpgDecrypt, gpgEncrypt, verifyWalletSignatures } from './utils/utils'; +import { buildStateBindingAdata, openStateBlob, STATE_BINDING_DOMAIN } from './utils/stateBinding'; import coinFactory from '../../shared/coinFactory'; const debugLogger = debug('bitgo:advancedWalletManager:mpcFinalize'); @@ -32,15 +33,20 @@ export async function eddsaFinalize(req: AwmApiSpecRouteRequest<'v1.mpc.key.fina const counterPartyIndex = source === 'user' ? 2 : 1; const bitgoIndex = 3; - // Decrypt the encrypted payload using encryptedDataKey to retrieve the previous state of computation + // Decrypt the encrypted payload using encryptedDataKey to retrieve the previous state of computation. + // The state must be bound to this keygen flow and source; blobs replayed from + // any other flow are rejected before decryption. const decryptedDataKey = await keyProvider.decryptDataKey({ encryptedKey: encryptedDataKey }); const previousState = JSON.parse( - await req.bitgo.decrypt({ - input: encryptedData, - password: decryptedDataKey.plaintextKey, + await openStateBlob(req.bitgo, { + plaintextKey: decryptedDataKey.plaintextKey, + ciphertext: encryptedData, + expectedAdata: buildStateBindingAdata(STATE_BINDING_DOMAIN.EDDSA_KEYGEN_INIT, { + source, + coin, + }), }), ); - const { sourceGpgPub, sourceGpgPrv, sourcePrivateShare } = previousState; let sourceToCounterPartyKeyShare = previousState.counterPartyKeyShare; diff --git a/src/advancedWalletManager/handlers/eddsaMPCWalletGenerationInitialize.ts b/src/advancedWalletManager/handlers/eddsaMPCWalletGenerationInitialize.ts index 02707b6b..447ec98b 100644 --- a/src/advancedWalletManager/handlers/eddsaMPCWalletGenerationInitialize.ts +++ b/src/advancedWalletManager/handlers/eddsaMPCWalletGenerationInitialize.ts @@ -9,6 +9,7 @@ import { } from '../routers/advancedWalletManagerApiSpec'; import { gpgEncrypt } from './utils/utils'; import { BadRequestError } from '../../shared/errors'; +import { buildStateBindingAdata, sealStateBlob, STATE_BINDING_DOMAIN } from './utils/stateBinding'; const debugLogger = debug('bitgo:awm:mpcInitialize'); @@ -17,6 +18,7 @@ export async function eddsaInitialize( ) { // request parsing. counterPartyGpgPub can be undefined const { source, bitgoGpgPub, counterPartyGpgPub }: MpcInitializeRequestType = req.decoded; + const { coin } = req.decoded; if (source === 'backup' && !counterPartyGpgPub) { throw new BadRequestError('gpgKey is required on backup key share generation'); } @@ -101,9 +103,12 @@ export async function eddsaInitialize( }; const { plaintextKey, encryptedKey } = await keyProvider.generateDataKey({ keyType: 'AES-256' }); try { - const encryptedPayload = await req.bitgo.encrypt({ - input: JSON.stringify(payload), - password: plaintextKey, + // Bind the keygen state to its flow, source, and coin so it cannot be + // replayed into any other decrypt path (e.g. the signing rounds). + const encryptedPayload = await sealStateBlob(req.bitgo, { + plaintextKey, + plaintext: JSON.stringify(payload), + adata: buildStateBindingAdata(STATE_BINDING_DOMAIN.EDDSA_KEYGEN_INIT, { source, coin }), }); return { encryptedDataKey: encryptedKey, diff --git a/src/advancedWalletManager/handlers/utils/stateBinding.ts b/src/advancedWalletManager/handlers/utils/stateBinding.ts new file mode 100644 index 00000000..df546f13 --- /dev/null +++ b/src/advancedWalletManager/handlers/utils/stateBinding.ts @@ -0,0 +1,121 @@ +import { createHash } from 'crypto'; +import { BadRequestError } from '../../../shared/errors'; +import { TxRequest } from '@bitgo-beta/sdk-core'; + +/** + * Context binding for encrypted MPC state blobs. + * + * AWM seals inter-round secrets under KMS data keys and the ciphertext travels + * through the untrusted orchestrator. Without a binding, any handler that + * unwraps a caller-supplied data key and decrypts a caller-supplied blob acts + * as a decryption oracle for blobs from any other flow (for example, keygen + * state replayed into the EdDSA R-share round). + * + * Every seal call stamps the blob's AEAD associated data with the context it + * was created for (flow, blob type, source wallet, signable). Every unseal + * site recomputes the expected context from the request and rejects a mismatch + * before any plaintext is used or returned. The associated data is covered by + * the AES-GCM tag, so it cannot be stripped or altered without breaking + * decryption, and it cannot be forged without the data key. + */ + +export const STATE_BINDING_DOMAIN = { + EDDSA_SIGN_R_SHARE: 'AWM_EDDSA_SIGN_RSHARE_STATE', + EDDSA_KEYGEN_INIT: 'AWM_EDDSA_KEYGEN_INIT_STATE', + ECDSA_MPCV2_KEYGEN: 'AWM_ECDSA_MPCV2_KEYGEN_STATE', +} as const; + +export const STATE_BINDING_MISMATCH_ERROR = + 'Encrypted state is not bound to this request; restart the session'; + +interface EncryptionSessionLike { + encrypt(plaintext: string, adata?: string): Promise; + decrypt(ciphertext: string): Promise; + destroy(): void; +} + +export interface StateBindingBitGo { + createEncryptionSession(password: string): Promise; + decrypt(params: { input: string; password: string }): Promise; +} + +/** + * Builds the associated-data string for a state blob: `:v1|k=v|k=v|...` + * with parts in sorted key order so the context is canonical. + */ +export function buildStateBindingAdata( + domain: (typeof STATE_BINDING_DOMAIN)[keyof typeof STATE_BINDING_DOMAIN], + parts: Record, +): string { + const core = [ + 'v1', + ...Object.keys(parts) + .sort() + .map((key) => `${key}=${parts[key]}`), + ].join('|'); + return `${domain}:${core}`; +} + +/** + * Extracts the signing-session binding parts from a txRequest. Mirrors how the + * SDK resolves the unsigned transaction (full: transactions[0].unsignedTx, else + * unsignedTxs[0]) so the context matches the payload the blob was sealed for. + * Keep in sync with the SDK's unsignedTx resolution: a drift fails closed here + * (sealed and expected adata stop matching) rather than weakening the binding. + */ +export function getSignableBindingParts(txRequest: TxRequest): { + signable: string; + path: string; +} { + const unsignedTx = + txRequest.apiVersion === 'full' + ? txRequest.transactions?.[0]?.unsignedTx + : txRequest.unsignedTxs?.[0]; + if (!unsignedTx?.signableHex || !unsignedTx.derivationPath) { + throw new BadRequestError( + 'txRequest is missing an unsigned transaction with signableHex and derivationPath', + ); + } + return { + signable: createHash('sha256').update(unsignedTx.signableHex).digest('hex'), + path: unsignedTx.derivationPath, + }; +} + +/** + * Seals a state blob under the KMS data key, binding it to the given context. + */ +export async function sealStateBlob( + bitgo: StateBindingBitGo, + params: { plaintextKey: string; plaintext: string; adata: string }, +): Promise { + const session = await bitgo.createEncryptionSession(params.plaintextKey); + try { + return await session.encrypt(params.plaintext, params.adata); + } finally { + session.destroy(); + } +} + +/** + * Unseals a state blob: verifies that its associated data matches the expected + * context, then decrypts. A blob from another flow, wallet, or session fails + * the binding check before any decryption is attempted, and the error never + * includes blob contents. + */ +export async function openStateBlob( + bitgo: StateBindingBitGo, + params: { plaintextKey: string; ciphertext: string; expectedAdata: string }, +): Promise { + let storedAdata: unknown; + try { + storedAdata = JSON.parse(params.ciphertext)?.adata; + } catch { + throw new BadRequestError(STATE_BINDING_MISMATCH_ERROR); + } + // v1 (SJCL) envelopes percent-encode the adata (':' -> '%3A'); decode before comparing. + if (typeof storedAdata !== 'string' || decodeURIComponent(storedAdata) !== params.expectedAdata) { + throw new BadRequestError(STATE_BINDING_MISMATCH_ERROR); + } + return bitgo.decrypt({ input: params.ciphertext, password: params.plaintextKey }); +}