diff --git a/modules/sdk-coin-sol/src/sol.ts b/modules/sdk-coin-sol/src/sol.ts index 8f2150566b..1aae1f293c 100644 --- a/modules/sdk-coin-sol/src/sol.ts +++ b/modules/sdk-coin-sol/src/sol.ts @@ -3,7 +3,7 @@ */ import { TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID } from '@solana/spl-token'; -import { AccountInfo, Connection, PublicKey as SolPublicKey } from '@solana/web3.js'; +import { AccountInfo, Connection, PublicKey as SolPublicKey, SystemInstruction, SystemProgram } from '@solana/web3.js'; import BigNumber from 'bignumber.js'; import * as base58 from 'bs58'; import * as _ from 'lodash'; @@ -52,6 +52,7 @@ import { RecoveryTxRequest, SignedTransaction, SignTransactionOptions, + SolInstruction, SolVersionedTransactionData, TokenEnablement, TokenEnablementConfig, @@ -85,7 +86,7 @@ import { ExtraAccountMeta, TransactionExplanation as SolLibTransactionExplanation, } from './lib/iface'; -import { InstructionBuilderTypes } from './lib/constants'; +import { InstructionBuilderTypes, MEMO_PROGRAM_PK } from './lib/constants'; import { ResolvePermissionlessThawResult, SolAccountFetcher, @@ -99,6 +100,8 @@ import { getSolTokenFromAddress, getSolTokenFromTokenName, isValidAddress, + isValidBase64, + isValidHex, isValidPrivateKey, isValidPublicKey, validateRawTransaction, @@ -509,6 +512,116 @@ export class Sol extends BaseCoin { return 'solVersionedTransactionData' in txParams && txParams.solVersionedTransactionData !== undefined; } + private hasSolInstructions( + txParams: TransactionParams + ): txParams is TransactionParams & { solInstructions: SolInstruction[] } { + const p = txParams as unknown as { solInstructions?: unknown }; + return Array.isArray(p.solInstructions) && (p.solInstructions as unknown[]).length > 0; + } + + /** + * Compare the user-supplied solInstructions against the actual instructions in a CustomTx prebuild. + * Exactly two server-added wrapper instructions are stripped by position before comparison: + * - Index 0: AdvanceNonceAccount (nonce infrastructure, never user-supplied). Only stripped + * if it is the very first instruction; any further AdvanceNonceAccount instructions are + * treated as user-supplied and must appear in solInstructions. + * - Last index: the 'WalletConnectDefiCustomTx' memo (CustomTx classification marker added + * by the server). Only stripped when it is the last instruction; a user-supplied memo at + * any other position is left in place and verified against solInstructions. + * All other instructions — including ComputeBudget — are treated as user-supplied and must + * appear in txParams.solInstructions exactly and in order. + * + * Note: the server never auto-adds ComputeBudget instructions for CustomTx. If ComputeBudget + * instructions are present, the user included them in solInstructions. + * + * Throws if the instructions differ in count, programId, keys, or data. + */ + private verifyCustomTxInstructions(transaction: Transaction, expectedInstructions: SolInstruction[]): void { + const SYSTEM_PROGRAM_ID = SystemProgram.programId.toString(); + const MEMO_PROGRAM_ID = new SolPublicKey(MEMO_PROGRAM_PK).toString(); + const allInstructions = transaction.solTransaction.instructions; + + // Strip only index 0 if it is an AdvanceNonceAccount (server-added nonce infra). + // A second AdvanceNonceAccount at any other position is NOT stripped and causes a + // count mismatch, preventing a rogue injected nonce advance from being silently ignored. + let startIdx = 0; + if (allInstructions.length > 0) { + const first = allInstructions[0]; + if (first.programId.toString() === SYSTEM_PROGRAM_ID) { + try { + if (SystemInstruction.decodeInstructionType(first) === 'AdvanceNonceAccount') { + startIdx = 1; + } + } catch { + // Not a recognised system instruction; treat as user-supplied + } + } + } + + // Strip only the last instruction if it is the WalletConnectDefiCustomTx marker memo + // (server-added CustomTx classifier). A user-supplied memo at any other position is NOT + // stripped, so it must appear in solInstructions and will be verified byte-for-byte. + let endIdx = allInstructions.length; + if (endIdx > startIdx) { + const last = allInstructions[endIdx - 1]; + if ( + last.programId.toString() === MEMO_PROGRAM_ID && + last.data.toString('utf-8').includes('WalletConnectDefiCustomTx') + ) { + endIdx--; + } + } + + const userInstructions = allInstructions.slice(startIdx, endIdx); + + if (userInstructions.length !== expectedInstructions.length) { + throw new Error( + `CustomTx prebuild instruction count mismatch: expected ${expectedInstructions.length}, got ${userInstructions.length}` + ); + } + + for (let i = 0; i < expectedInstructions.length; i++) { + const expected = expectedInstructions[i]; + const actual = userInstructions[i]; + + if (actual.programId.toString() !== expected.programId) { + throw new Error( + `CustomTx prebuild instruction ${i} programId mismatch: expected ${ + expected.programId + }, got ${actual.programId.toString()}` + ); + } + + if (actual.keys.length !== expected.keys.length) { + throw new Error( + `CustomTx prebuild instruction ${i} key count mismatch: expected ${expected.keys.length}, got ${actual.keys.length}` + ); + } + + for (let j = 0; j < expected.keys.length; j++) { + const ak = actual.keys[j]; + const ek = expected.keys[j]; + if (ak.pubkey.toString() !== ek.pubkey || ak.isSigner !== ek.isSigner || ak.isWritable !== ek.isWritable) { + throw new Error(`CustomTx prebuild instruction ${i} key ${j} mismatch`); + } + } + + // Normalize expected.data to Buffer using the same encoding logic as the builder + let expectedData: Buffer; + if (isValidBase64(expected.data)) { + expectedData = Buffer.from(expected.data, 'base64'); + } else if (isValidHex(expected.data)) { + expectedData = Buffer.from(expected.data, 'hex'); + } else { + expectedData = Buffer.from(expected.data, 'utf8'); + } + + if (!actual.data.equals(expectedData)) { + throw new Error(`CustomTx prebuild instruction ${i} data mismatch`); + } + } + } + /** * Verify a versioned Solana transaction with basic structural validation * @param params - verification parameters @@ -611,6 +724,24 @@ export class Sol extends BaseCoin { const explainedTx = transaction.explainTransaction(); const isCloseAssociatedTokenAccountTx = transaction.type === TransactionType.CloseAssociatedTokenAccount; + // CustomTx-specific verification (CHALO-2055): + // + // Exploit 2: A malicious prebuild can use the 'WalletConnectDefiCustomTx' memo to launder + // Transfer/TokenTransfer instructions into CustomTx classification, bypassing the consolidation + // output check (which loops over zero outputs for CustomTx). Reject any CustomTx consolidation. + // + // Exploit 1: When the user supplied solInstructions, compare them byte-for-byte against the + // prebuild to prevent an attacker from substituting arbitrary instructions (drain, Approve, etc.) + // while the wallet signs without noticing. + if (transaction.type === TransactionType.CustomTx) { + if (consolidateId !== undefined) { + throw new Error('CustomTx transactions are not valid for consolidation'); + } + if (this.hasSolInstructions(txParams)) { + this.verifyCustomTxInstructions(transaction, txParams.solInstructions); + } + } + // A Marinade unstake produces no explained outputs, so the only thing tying its transfer to this wallet // is the source. The source is the wallet root, not the fee payer, since sponsored fee payers exist. if (transaction.type === TransactionType.StakingDeactivate) { diff --git a/modules/sdk-coin-sol/test/unit/sol.ts b/modules/sdk-coin-sol/test/unit/sol.ts index c306848714..16ed66510b 100644 --- a/modules/sdk-coin-sol/test/unit/sol.ts +++ b/modules/sdk-coin-sol/test/unit/sol.ts @@ -1393,6 +1393,262 @@ describe('SOL:', function () { } as any); validTransaction.should.equal(true); }); + + describe('CustomTx verification (CHALO-2055)', function () { + // Build a simple raw CustomTx using the factory, with a WalletConnectDefiCustomTx memo. + // The user instruction is a "dummy" instruction with an arbitrary program ID. + const dummyProgramId = stakeAccount.pub; // any valid base58 pubkey used as program ID + const dummyInstructionData = Buffer.from('deadbeef', 'hex'); + + async function buildCustomTx( + solInstructions: { + programId: string; + keys: { pubkey: string; isSigner: boolean; isWritable: boolean }[]; + data: string; + }[] + ): Promise { + const txBuilder = factory.getCustomInstructionBuilder(); + txBuilder.sender(wallet.pub); + txBuilder.nonce(blockHash); + txBuilder.memo('WalletConnectDefiCustomTx'); + for (const ix of solInstructions) { + txBuilder.addCustomInstruction(ix); + } + const tx = await txBuilder.build(); + return tx.toBroadcastFormat(); + } + + const userInstruction = { + programId: dummyProgramId, + keys: [{ pubkey: wallet.pub, isSigner: true, isWritable: true }], + data: dummyInstructionData.toString('hex'), + }; + + it('should pass when solInstructions match the prebuild exactly', async function () { + const txBase64 = await buildCustomTx([userInstruction]); + const result = await basecoin.verifyTransaction({ + txParams: { solInstructions: [userInstruction] }, + txPrebuild: { txBase64 }, + wallet: walletObj, + } as any); + result.should.equal(true); + }); + + it('should fail when the prebuild contains a substituted instruction (Exploit 1)', async function () { + // Attacker replaces the user instruction with a transfer to themselves + const maliciousInstruction = { + programId: dummyProgramId, + keys: [{ pubkey: stakeAccount.pub, isSigner: false, isWritable: true }], // different key + data: dummyInstructionData.toString('hex'), + }; + const txBase64 = await buildCustomTx([maliciousInstruction]); + await basecoin + .verifyTransaction({ + txParams: { solInstructions: [userInstruction] }, + txPrebuild: { txBase64 }, + wallet: walletObj, + } as any) + .should.be.rejectedWith('CustomTx prebuild instruction 0 key 0 mismatch'); + }); + + it('should fail when the prebuild has more instructions than solInstructions (extra injected instruction)', async function () { + const extraInstruction = { + programId: dummyProgramId, + keys: [{ pubkey: stakeAccount.pub, isSigner: false, isWritable: true }], + data: Buffer.from('extra').toString('hex'), + }; + const txBase64 = await buildCustomTx([userInstruction, extraInstruction]); + await basecoin + .verifyTransaction({ + txParams: { solInstructions: [userInstruction] }, + txPrebuild: { txBase64 }, + wallet: walletObj, + } as any) + .should.be.rejectedWith('CustomTx prebuild instruction count mismatch: expected 1, got 2'); + }); + + it('should fail when the prebuild instruction data is tampered', async function () { + const tamperedInstruction = { + programId: dummyProgramId, + keys: [{ pubkey: wallet.pub, isSigner: true, isWritable: true }], + data: Buffer.from('cafebabe', 'hex').toString('hex'), // different data + }; + const txBase64 = await buildCustomTx([tamperedInstruction]); + await basecoin + .verifyTransaction({ + txParams: { solInstructions: [userInstruction] }, + txPrebuild: { txBase64 }, + wallet: walletObj, + } as any) + .should.be.rejectedWith('CustomTx prebuild instruction 0 data mismatch'); + }); + + it('should reject a CustomTx consolidation (Exploit 2)', async function () { + const txBase64 = await buildCustomTx([userInstruction]); + await basecoin + .verifyTransaction({ + txParams: { solInstructions: [userInstruction] }, + txPrebuild: { txBase64, consolidateId: 'consolidate-123' }, + wallet: walletObj, + } as any) + .should.be.rejectedWith('CustomTx transactions are not valid for consolidation'); + }); + + it('should pass when no solInstructions are provided (non-customtx-intent path)', async function () { + // Some transactions may fall through to CustomTx classification without solInstructions. + // Without solInstructions there is nothing to compare, so the check is skipped. + // Gap is deliberate: Exploit 2 (consolidation hijack) is blocked above. Exploit 1 only + // applies when the user provided solInstructions to verify against. + const txBase64 = await buildCustomTx([userInstruction]); + const result = await basecoin.verifyTransaction({ + txParams: {}, + txPrebuild: { txBase64 }, + wallet: walletObj, + } as any); + result.should.equal(true); + }); + + it('should pass when prebuild has durable nonce advance and WalletConnectDefiCustomTx memo (both stripped by position)', async function () { + // Builds a durable-nonce CustomTx: [AdvanceNonce(0), UserIx(1), Memo(last)] + // Verifier strips index 0 and last → compares [UserIx] against solInstructions + async function buildCustomTxWithDurableNonce( + solInstructions: { + programId: string; + keys: { pubkey: string; isSigner: boolean; isWritable: boolean }[]; + data: string; + }[] + ): Promise { + const txBuilder = factory.getCustomInstructionBuilder(); + txBuilder.sender(wallet.pub); + txBuilder.nonce(blockHash, durableNonce); + txBuilder.memo('WalletConnectDefiCustomTx'); + for (const ix of solInstructions) { + txBuilder.addCustomInstruction(ix); + } + const tx = await txBuilder.build(); + return tx.toBroadcastFormat(); + } + const txBase64 = await buildCustomTxWithDurableNonce([userInstruction]); + const result = await basecoin.verifyTransaction({ + txParams: { solInstructions: [userInstruction] }, + txPrebuild: { txBase64 }, + wallet: walletObj, + } as any); + result.should.equal(true); + }); + + it('should fail when a second AdvanceNonceAccount is injected (position-based stripping only removes index 0)', async function () { + // Old filter-based code would silently drop ALL AdvanceNonceAccount instructions, + // allowing an attacker to inject an extra one without detection. + // Position-based fix only removes index 0; the injected second one causes a count mismatch. + async function buildCustomTxWithDurableNonce( + solInstructions: { + programId: string; + keys: { pubkey: string; isSigner: boolean; isWritable: boolean }[]; + data: string; + }[] + ): Promise { + const txBuilder = factory.getCustomInstructionBuilder(); + txBuilder.sender(wallet.pub); + txBuilder.nonce(blockHash, durableNonce); + txBuilder.memo('WalletConnectDefiCustomTx'); + for (const ix of solInstructions) { + txBuilder.addCustomInstruction(ix); + } + const tx = await txBuilder.build(); + return tx.toBroadcastFormat(); + } + // Construct a rogue nonce advance instruction to inject into the transaction + const rogueNonceWeb3Ix = SystemProgram.nonceAdvance({ + noncePubkey: new PublicKey(durableNonce.walletNonceAddress), + authorizedPubkey: new PublicKey(durableNonce.authWalletAddress), + }); + const rogueNonceInstruction = { + programId: rogueNonceWeb3Ix.programId.toString(), + keys: rogueNonceWeb3Ix.keys.map((k) => ({ + pubkey: k.pubkey.toString(), + isSigner: k.isSigner, + isWritable: k.isWritable, + })), + data: Buffer.from(rogueNonceWeb3Ix.data).toString('base64'), + }; + // Tx: [AdvanceNonce(0, legit), RogueNonce(1, injected), UserIx(2), Memo(last)] + // After position-based strip: [RogueNonce, UserIx] → count=2, expected=1 → mismatch + const txBase64 = await buildCustomTxWithDurableNonce([rogueNonceInstruction, userInstruction]); + await basecoin + .verifyTransaction({ + txParams: { solInstructions: [userInstruction] }, + txPrebuild: { txBase64 }, + wallet: walletObj, + } as any) + .should.be.rejectedWith('CustomTx prebuild instruction count mismatch: expected 1, got 2'); + }); + + it('should NOT strip a user-supplied memo at a non-last position', async function () { + // A memo supplied by the user inside solInstructions is at a non-last position + // (the WalletConnectDefiCustomTx marker is last). It must NOT be stripped and + // must appear in solInstructions for verification to pass. + const userMemoInstruction = { + programId: 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr', + keys: [], + data: Buffer.from('user memo text').toString('base64'), + }; + // Tx: [UserIx(0), UserMemo(1), WalletConnectMemo(last)] + const txBase64 = await buildCustomTx([userInstruction, userMemoInstruction]); + const result = await basecoin.verifyTransaction({ + txParams: { solInstructions: [userInstruction, userMemoInstruction] }, + txPrebuild: { txBase64 }, + wallet: walletObj, + } as any); + result.should.equal(true); + }); + + it('should fail when a key isSigner flag is tampered', async function () { + // Use a non-sender account (stakeAccount) so web3.js does not override isSigner. + // The prebuild lists stakeAccount as a signer; the user expects it as non-signer. + const prebuildInstruction = { + programId: dummyProgramId, + keys: [{ pubkey: stakeAccount.pub, isSigner: true, isWritable: false }], // server promoted to signer + data: dummyInstructionData.toString('hex'), + }; + const expectedInstruction = { + programId: dummyProgramId, + keys: [{ pubkey: stakeAccount.pub, isSigner: false, isWritable: false }], // user expects non-signer + data: dummyInstructionData.toString('hex'), + }; + const txBase64 = await buildCustomTx([prebuildInstruction]); + await basecoin + .verifyTransaction({ + txParams: { solInstructions: [expectedInstruction] }, + txPrebuild: { txBase64 }, + wallet: walletObj, + } as any) + .should.be.rejectedWith('CustomTx prebuild instruction 0 key 0 mismatch'); + }); + + it('should fail when a key isWritable flag is tampered', async function () { + // Use a non-sender account (stakeAccount) so web3.js does not override isWritable. + // The prebuild lists stakeAccount as writable; the user expects it as read-only. + const prebuildInstruction = { + programId: dummyProgramId, + keys: [{ pubkey: stakeAccount.pub, isSigner: false, isWritable: true }], // server made writable + data: dummyInstructionData.toString('hex'), + }; + const expectedInstruction = { + programId: dummyProgramId, + keys: [{ pubkey: stakeAccount.pub, isSigner: false, isWritable: false }], // user expects read-only + data: dummyInstructionData.toString('hex'), + }; + const txBase64 = await buildCustomTx([prebuildInstruction]); + await basecoin + .verifyTransaction({ + txParams: { solInstructions: [expectedInstruction] }, + txPrebuild: { txBase64 }, + wallet: walletObj, + } as any) + .should.be.rejectedWith('CustomTx prebuild instruction 0 key 0 mismatch'); + }); + }); }); describe('getAmountBasedOnEndianness', () => {