In-depth Analysis of the Safe Predicament: Can Guard Reconstruct the Contract Babel Tower?

CN
PANews
Follow
6 hours ago

Author: flush & kong

Editor: Liz

Background

On February 21, 2025, the cryptocurrency industry faced the most severe asset management crisis in history. The on-chain multi-signature wallet of the trading platform Bybit was targeted and breached, resulting in nearly $1.5 billion in assets quietly disappearing through a single "legitimate signature" transaction. Subsequent on-chain analysis revealed that the attacker gained multi-signature permissions through sophisticated social engineering attacks, implanted malicious logic using the delegatecall function of the Safe contract, and ultimately bypassed the multi-signature verification mechanism to transfer funds to an anonymous address.

In-depth Analysis of the Safe Dilemma: Can Guard Reconstruct the Contract Babel Tower?

This incident exposed a harsh reality: "multi-signature" does not equal "absolute security." Even a secure mechanism like the Safe multi-signature wallet carries the risk of being compromised if it lacks additional protective measures. This is not the first attack case against Safe multi-signature wallets. Last year, WazirX (which lost $230 million) and Radiant Capital (which lost $50 million) experienced similar attack methods. As analyzed in the article by Slow Mist: The Hacking Techniques and Questions Behind Bybit's Nearly $1.5 Billion Theft, the Safe multi-signature wallet attack incidents exhibit the following technical commonalities:

  • Over-reliance on signature mechanisms: placing all security responsibility on private key management.
  • Lack of dynamic defense: absence of real-time risk scanning before transaction execution.
  • Coarse-grained permission control: no whitelist mechanism established for high-risk operations like delegatecall.

In-depth Analysis of the Safe Dilemma: Can Guard Reconstruct the Contract Babel Tower?

(Bybit Theft Process: Using Safe v1.1.1)

The core issue of this series of events lies not in the Safe contract itself, but in the security vulnerabilities present in the entire system's integration process, particularly in the front-end verification stage. This prompts us to consider: how can we enhance the protective capabilities of multi-signature wallets through additional security measures in Safe?

Safe

Safe is a multi-signature (Multi-Sig) wallet primarily used for the secure storage and transfer of high-value assets and digital currencies. As a foundational infrastructure for decentralized asset management, it ensures the security of fund operations through a multi-party collaborative verification mechanism, preventing a single administrator or hacker from exploiting a single point of failure for malicious operations. It is widely used in scenarios such as DAO governance, corporate fund custody, and decentralized fund pools. The contract is developed by the Safe (formerly Gnosis Safe) team and is the current industry standard for on-chain asset management solutions. The contract implements structured data signing using the EIP-712 standard, thereby enhancing the security and verifiability of transaction data.

Core Uses

  • Fund Security Management: The contract requires multiple pre-defined owners to jointly confirm transactions before execution, effectively preventing single-point errors or malicious operations, ensuring fund security.
  • Transaction Execution and Management: Through the built-in multi-signature verification mechanism, the contract can execute external transfers, call other contracts, or handle complex business logic when the signature threshold conditions are met, supporting payments and fee reimbursements in tokens and native coins.
  • Modular Expansion: The contract adopts a modular design, allowing for the inheritance and combination of multiple management modules (such as OwnerManager, ModuleManager, GuardManager, FallbackManager, etc.), making its functionality flexible and easy to expand, providing customized support for different application scenarios.

Function Analysis

The execTransaction function executes transactions that have undergone multi-signature verification:

  • Calculates a unique hash value for the transaction (combining transaction parameters, nonce, etc.);
  • Verifies the validity of all signatures, ensuring each signature comes from a legitimate owner or pre-approved address;
  • Calls the business logic of the target address and records the success or failure status through events after the transaction execution;
  • Supports flexible gas fee handling, ensuring accurate calculation of transaction costs during reimbursement.

The checkContractSignatures & checkNSignatures functions verify the signature data of transactions or messages:

  • Handles EOA account signatures, contract signatures (EIP-1271), and pre-approved hashes separately;
  • Ensures signatures are arranged in the order of owners and that each signature comes from a valid address, preventing replay attacks and signature tampering.

The getTransactionHash function generates a transaction hash for signature verification and preventing replay attacks:

  • Utilizes the EIP-712 standard to perform structured hashing of transaction data;
  • Uses inline assembly to optimize memory operations, improving computational efficiency;
  • Combines the current nonce value to ensure the uniqueness of each transaction.

The handlePayment function processes gas reimbursement payments during the execution of transactions:

  • Calculates the payment amount based on the actual gas fees consumed and the base fee;
  • Supports payments in ETH and other tokens, ensuring accurate fee reimbursement.

The onBeforeExecTransaction is an internal virtual hook function called before the execTransaction function is executed. The purpose of this function is to allow child contracts inheriting from the Safe contract to perform custom logic processing before transaction execution. The received parameter set includes:

  • to: Target address - the contract or account address to be called by the transaction
  • value: Ether value - the amount of Ether sent with the transaction
  • data: Data payload - the call data containing the function selector and parameters
  • operation: Operation type - determines whether it is a CALL or DELEGATECALL
  • safeTxGas: Transaction gas limit - the amount of gas reserved for transaction execution
  • baseGas: Base gas - gas costs independent of transaction execution
  • gasPrice: Gas price - the gas price used to calculate transaction fee reimbursement
  • gasToken: Gas token - the token address used to pay transaction fees
  • refundReceiver: Refund receiver - the address receiving transaction fee reimbursement
  • signatures: Signature set - the signature data of the owners for the transaction

Although multi-signature wallet contracts provide an efficient and secure solution for digital asset management with their rigorous security design and flexible modular structure, achieving full-process security control from transaction initialization to final execution, it is also important to note that victims often rely on hardware wallets for signing, and some hardware devices do not display structured data signatures well, making it easy for users to inaccurately identify transaction data in a short time, leading to "blind signing" risks. To address this phenomenon, in addition to optimizing hardware and its data display effects, measures such as increasing multi-confirmation, smart prompts, and enhancing signature verification tools can be explored to further reduce the security risks posed by blind signing.

Safe Guard

The Safe contract introduced an important security feature in version 1.3.0 - the Safe Guard mechanism. This mechanism aims to provide additional constraints for standard n-out-of-m multi-signature schemes, further enhancing transaction security. The core value of Safe Guard lies in its ability to perform security checks at different stages of transaction execution:

  • Pre-transaction check (checkTransaction): The Guard mechanism can programmatically check all parameters of the transaction before execution, ensuring that the transaction complies with preset security rules.
  • Post-transaction check (checkAfterExecution): After the transaction execution is completed, the Guard will also perform additional security verification to check whether the final state of the Safe wallet after execution meets expectations.

Architecture Analysis

In-depth Analysis of the Safe Dilemma: Can Guard Reconstruct the Contract Babel Tower?

In Safe, multi-signature transactions are generally executed through the execTransaction function. When the Safe Guard is enabled, when a user executes a multi-signature transaction, the Safe contract will call the checkTransaction function of the Guard contract to perform pre-transaction checks, and after the multi-signature transaction is completed, the Safe contract will call the checkAfterExecution function of the Guard contract to check the execution result of the transaction. The specific implementation is as follows:

function execTransaction( … ) external payable override returns (bool success) { … address guard = getGuard(); { if (guard != address(0)) { ITransactionGuard(guard).checkTransaction( // Transaction info to, value, data, operation, safeTxGas, // Payment info baseGas, gasPrice, gasToken, refundReceiver, // Signature info signatures, msg.sender ); } } … { … success = execute(to, value, data, operation, gasPrice == 0 ? (gasleft() - 2500) : safeTxGas); … } { if (guard != address(0)) { ITransactionGuard(guard).checkAfterExecution(txHash, success); } }}

When the Safe contract executes multi-signature transaction pre-checks through the Guard mechanism, its checkTransaction function receives complete transaction context data, including the target contract address, calling method, execution data (such as delegatecall), owner signature information, gas configuration, and payment information. This mechanism enables developers to implement multi-dimensional risk control strategies, such as contract whitelist management (restricting interactive addresses), function-level permission management (disabling high-risk function selectors), transaction frequency limits, and dynamic rules based on fund flows. By reasonably configuring Guard strategies, it can effectively block attackers from exploiting non-contract-level attacks.

In the context of recent security incidents, there is increasing concern from all parties regarding the security of multi-signature wallet contracts. Hardware wallet providers such as KeyStone, OneKey, and RigSec have called for enhanced parsing and protective capabilities of Safe contracts to prevent similar risks from occurring again. Following the Bybit incident, many project teams began to focus on Safe contracts and explore upgrade and expansion solutions based on the Guard mechanism. Among them are innovative applications based on the Guard mechanism, constructing a middle-layer security solution built on the Safe multi-signature wallet, providing additional security guarantees between underlying assets and user assets. Its core function is to achieve extremely fine-grained checks on transactions by passing the target contract, calling method, execution data, owner signature information, payment information, and gas information involved in Safe multi-signature transactions into the checkTransaction function, including whitelist contract calls, whitelist function operations, whitelist transfer targets, transaction frequency, and other permission controls.

It is worth noting that Safe itself only provides Guard management and callback functions, while the actual multi-signature transaction check logic is implemented by the user, and its security depends on the quality of the Guard implementation. For example, Solv Guardian expands on this idea by configuring a dedicated Guardian for each Vault to specify allowed target addresses and operation permissions, achieving three key permission control elements: specifying allowed contracts, defining allowed function operations, and ACL verification requirements. At the same time, a separate governance mechanism is adopted, with the Vault Guardian responsible for execution, while the Governor controls governance permissions, ensuring that even if the Guardian encounters issues, timely remedial measures can be taken to protect user assets. A similar design concept is also applied in Elytro's SecurityControlModule, which intercepts critical operations through the preExecute function and uses a whitelist mechanism to finely control high-risk operations such as module installation, hook settings, and validator management, ensuring that only trusted contracts can be added to the system, providing lasting security for the wallet.

In the attack chain of the Bybit incident, if the Safe contract had deployed a reasonably configured Guard mechanism, the malicious delegatecall initiated by the attacker through execTransaction would have been intercepted by multiple strategies during the pre-check phase: the Guard's checkTransaction function would first identify the delegatecall operation type and trigger disable rules (such as enforcing that the operation is limited to regular calls), then parse the data field to detect an unconventional contract address (0x4622…7242) and high-risk function selector, directly rolling back the transaction through preset contract whitelist and function blacklist strategies, ultimately forming a "strategy interception → logic blockage" defense system, completely blocking storage tampering and fund transfer paths.

In-depth Analysis of the Safe Dilemma: Can Guard Reconstruct the Contract Babel Tower?

(When using Safe version ≥ v1.3.0, the verification operation of the Safe Guard module https://excalidraw.com/#room=fd1df67dd09b3dab6bd8,Q1jeb1MZW7vwbY4NuxaV5A)

In summary, Safe only provided the Guard function after version 1.3.0. Although Guard can offer extremely fine-grained multi-signature transaction checks, there is a significant barrier for users when using the Guard function. They need to implement the Guard check logic themselves, and a rough or flawed Guard implementation may not help users enhance the security of their Safe wallets, making it necessary to conduct security audits on Guard implementations. There is no doubt that a secure and appropriate Guard implementation can greatly enhance the security of Safe wallets.

Conclusion and Outlook

The Bybit attack incident highlights the importance of timely updates to security infrastructure. Bybit was using version v1.1.1 (1.3.0) of the Safe contract, which means they could not utilize the Guard mechanism, a key security feature. If Bybit had upgraded to version 1.3.0 or higher of the Safe contract and implemented an appropriate Guard mechanism, such as specifying a whitelist address for receiving funds and conducting strict contract function ACL verification, they might have avoided this loss. Although this is merely a hypothesis, it provides important insights for future asset security management.

The Safe Guard mechanism is like an intelligent security inspection system added to a digital asset safe, and its effectiveness depends on the rigor of rule design and implementation quality. In the face of increasingly sophisticated attack methods, we need to:

  • Automated Verification: Establish an automated transaction verification mechanism
  • Dynamic Strategy Adjustment: Adjust security strategies in real-time based on threat intelligence
  • Multi-layer Defense: Build a deep defense system by combining various security mechanisms
  • Continuous Auditing: Conduct regular security audits on Guard implementations

The future of digital asset management will be a co-evolution process of smart contract security mechanisms and continuous offensive and defensive evolution. Only by integrating security concepts into every aspect can we build a true security barrier in the game between hackers' "spear" and guardians' "shield."

References

[1] https://github.com/safe-global/safe-smart-account/blob/v1.3.0/CHANGELOG.md

[2] https://docs.safe.global/advanced/smart-account-guards

[3] https://docs.solv.finance/security/solv-guard

[4] https://github.com/safe-global/safe-smart-account/tree/main/contracts/examples/guards

[5] https://github.com/Elytro-eth/soul-wallet-contract/blob/v0.6/contracts/modules/securityControlModule/SecurityControlModule.sol

免责声明:本文章仅代表作者个人观点,不代表本平台的立场和观点。本文章仅供信息分享,不构成对任何人的任何投资建议。用户与作者之间的任何争议,与本平台无关。如网页中刊载的文章或图片涉及侵权,请提供相关的权利证明和身份证明发送邮件到support@aicoin.com,本平台相关工作人员将会进行核查。

Share To
APP

X

Telegram

Facebook

Reddit

CopyLink