Sui is an emerging high-performance blockchain platform that offers a range of innovative and unique features. It focus on providing fast and secure transaction experiences for various applications. For foundational knowledge about Sui, refer to Exploring Sui: The Technology Behind High Performance and Contract Security. Unlike commonly used blockchain programming languages like Solidity, Sui utilizes the Move language, which addresses many vulnerabilities frequently found in Solidity, such as reentrancy attacks, integer overflows, double-spending, DoS attacks, and compiler issues. However, developers can still introduce errors in their code, so it’s crucial to understand and pay attention to some of Move’s unique features to ensure the security of smart contracts.
The SlowMist security team has integrated the security development practices shared by the Sui community and combined them with years of security auditing experience to publish the Introduction to Auditing Sui — Move Contracts. This guide aims to help developers better understand the security risks associated with Sui smart contracts and provide practical solutions to reduce potential threats.
Due to space limitations, this article only highlights parts of the Introduction to Auditing Sui — Move Contracts. For the full content, feel free to Watch, Fork, and Star on GitHub: https://github.com/slowmist/Sui-MOVE-Smart-Contract-Auditing-Primer/tree/main
Key Concepts
1. Module Declaration and Visibility
1.1 “public(friend)” Function
Note: In the latest version of Sui, “public(friend)” has been replaced by “public(package).”
Definition: This function, now replaced by “public(package)” in the latest Sui version, allows a function to be accessible only by designated friend modules. It provides finer-grained access control, between “public” and “private.”
Example:
1.2 “entry” Function
Definition: The “entry” function serves as the entry point for a module, allowing direct invocation from transaction blocks. Its parameters must come from the transaction block’s input, and it can only return types with the “drop” capability.
Example:
1.3 “public” Function
Definition: A “public” function can be invoked by both transaction blocks and other modules. It is generally used for external interaction and does not have the same restrictions as the “entry” function.
2. Object Management
2.1 Object Uniqueness
Definition: Each Sui object has a unique “objID,” ensuring its uniqueness on the chain.
2.2 Wrapping and Unwrapping
Definition:
- Direct Wrapping: Embedding a Sui object as a field within another object, where unwrapping requires destroying the wrapping object.
- Object Wrapping: Wrapped objects become part of another object and no longer exist independently. Upon unwrapping, the object’s ID remains unchanged.
2.3 Custom Transfer Strategies
Definition: Custom transfer strategies are defined using “sui::transfer::transfer” for objects with the “store” capability, which can be created through “sui::transfer::public_transfer.”
2.4 Object Properties
Definition: Sui objects have properties like “copy,” “drop,” “store,” and “key,” which determine their behavior.
2.5 Object Permission Checks
- Address-Owned Objects: Objects owned by specific addresses can only be accessed and manipulated by their owner.
- Immutable Objects: Immutable objects cannot be modified or transferred and are accessible by anyone.
- Shared Objects: Shared objects can be accessed and manipulated by multiple users, often used in decentralized applications, but at a higher consensus cost.
- Wrapped Objects: Wrapped objects are embedded within another object and must be accessed through the wrapping object.
3. Security Checks
3.1 Overflow Checks
Sui smart contracts perform default overflow checks during mathematical operations.
3.2 Reentrancy Checks
A reentrancy attack occurs when an unexpected (external) call is inserted into a normal contract transaction, altering the overall business logic flow and enabling malicious actors to gain unauthorized benefits. Reentrancy risks are present wherever external contract calls are made. These risks can be categorized into three types: single-function reentrancy, cross-function reentrancy, and cross-contract reentrancy. However, the Move language has several built-in features that naturally protect against reentrancy attacks:
- No Dynamic Calls: In Move, external calls must first be imported via the `use` statement, meaning all external calls are predetermined and explicit.
- No Fallback Function Triggered by Native Token Transfers: Move does not support triggering fallback functions through native token transfers, eliminating a common reentrancy vulnerability.
- Resource Model: Move’s resource model ensures that a resource can only be accessed by a single execution context at a time. This means that if a function has not completed its execution, other functions cannot access the same resource until the execution is finished.
Auditing Primer
1. Overflow Auditing
Description: Move automatically checks for overflow during mathematical operations. If an overflow occurs, the transaction will fail. However, it’s important to note that bitwise operations in Move do not undergo overflow checks.
Audit Focus: Identify and review all instances of bitwise operations in the code to assess whether there is any risk of overflow.
2. Arithmetic Precision Error Auditing
Description: Move does not support floating-point types. As a result, any arithmetic operation that requires floating-point precision could lead to precision errors. Although some level of precision error may be unavoidable, it can often be mitigated through careful design and optimization.
Audit Focus: Examine all sections of the code involving arithmetic operations, especially those where precision errors might occur. Ensure that these operations do not adversely affect contract logic or the accuracy of values. Provide optimization recommendations to minimize precision errors where possible.
3. Race Condition Auditing
Description: In Sui, validators have the ability to reorder transactions submitted by users. Therefore, it’s essential during the audit to consider the possibility of transactions being reordered within the same block for potential profit.
Audit Focus:
- Check if the contract’s data state is appropriately managed before a function call.
- Ensure proper management of the contract’s data state during function execution.
- Confirm that the data state of the contract after function execution aligns with expectations.
4. Access Control Auditing
Description: Certain critical functions within a contract should be restricted to internal use only, such as functions that can directly update user deposit amounts. If these functions are accidentally exposed to external access, it could bypass permission controls, leading to security vulnerabilities or even asset losses. Therefore, it is essential to strictly enforce access control, ensuring that only authorized roles or modules can invoke these functions, or that these functions are limited to internal usage.
Audit Focus: Review all function access control settings, with particular attention to those functions that should not be publicly accessible. Ensure that these functions are restricted to internal calls. If any function interfaces that should remain private are found to be exposed, mark them as high-risk and recommend corrective actions.
5. Object Management Auditing
Description: In Sui, objects can be converted into shared objects, which means their access permissions could change from private to public. Therefore, it is important to thoroughly audit all objects used in the contract to clarify whether each object is static or shared. Special attention should be given to whether any object has been incorrectly converted from a private object to a shared object, as this could result in unauthorized access by users, posing potential security risks.
Audit Focus: Catalog and analyze all objects involved in the module, checking their types and permission settings. Ensure that each object’s permissions align with business requirements. If any private objects are found to have been incorrectly converted into shared objects, flag them as potential risks and propose corrective suggestions.
6. Token Consumption Auditing
Description: Sui’s token model differs from those of other blockchains. Sui allows objects to hold tokens, and these token objects can be nested within other objects and can also be split. In scenarios involving token consumption, particular attention must be paid to token management and flow to prevent security issues or accidental losses.
Audit Focus:
- Verify that the consumed amounts are accurate.
- Ensure that token objects have been correctly transferred.
- Check whether the splitting and merging of tokens are reasonable.
- Confirm the proper binding of tokens with objects.
7. Flash Loan Attack Auditing
Description: In Sui, the Move language also supports flash loans, commonly referred to as “Hot Potato.” Users can borrow large sums of money within a single transaction, use the funds freely, and repay them within the same transaction. Malicious actors often exploit flash loans to amplify their capital and engage in large-scale attacks such as price manipulation.
Audit Focus: Analyze the protocol’s underlying algorithms, including reward mechanisms, interest rates, and reliance on oracles, to determine whether they are designed to resist flash loan exploitation. Ensure that these components are robust enough to prevent or mitigate the risks associated with flash loan attacks.
8. Permission Vulnerability Auditing
Description: In Sui’s Move contracts, permission vulnerabilities are closely related to business requirements and function design. When auditing complex modules, it is necessary to confirm the calling permissions of each method, typically involving the visibility of functions and their invocation permissions.
Audit Focus:
- Review and confirm the visibility and calling permissions of all functions and methods. During the project evaluation phase, developers should provide design documentation, which will be used during the audit to verify the correctness of permissions.
- Map out the roles within the project and their associated permission scopes. If a role’s permissions could impact user assets, there is a risk of excessive authority that needs to be addressed.
- Analyze the types of objects passed into external functions. For privileged functions, ensure that only specific privileged objects are involved.
9. Contract Upgrade Security Auditing
Description: In Move, external modules are imported using the `use` keyword. It’s important to note that while Sui contracts are upgradeable, the deployed contract package (package) is immutable — once deployed, it cannot be withdrawn or modified. The essence of contract upgrading is to redeploy an updated contract at a new address and migrate the data from the old contract to the new one. Special attention is needed during the contract upgrade process:
- “init” Function: The “init” function is executed only during the initial deployment of the contract and will not be triggered during subsequent upgrades.
- Dependency Updates: Upgrading a contract will not automatically update its dependencies. If the contract package relies on external packages, when those external packages are upgraded, the contract package will not automatically point to the new contract address. Therefore, you must manually upgrade your contract package to specify the new dependencies.
Audit Focus: Thoroughly review the data migration logic during the contract upgrade process to ensure the migration is safe and accurate. Ensure no critical data or dependency updates are missed during the upgrade.
10. External Call Security Auditing
Description: Similar to the auditing of external module usage, since Move requires external modules to be imported before they can be called, the results of external calls are generally what developers expect. The primary concern here is the stability of the external modules being called.
Audit Focus: Check all external libraries introduced into the project to ensure they are stable, secure, and function as intended. This involves verifying that external modules are reliable and do not introduce unforeseen vulnerabilities into the contract.
11. Return Value Checks
Description: Similar to other smart contract languages, in Move, it is crucial to check the return values of certain functions. Ignoring these return values may result in key logic not being executed properly, potentially leading to security issues.
Audit Focus: Review the code to ensure that the return values of every function call are properly handled, especially for those involving external calls or important state updates. If return values are not handled or verified, they could lead to unexpected behavior, and such instances should be flagged as potential risk points.
12. Denial of Service (DoS) Auditing
Description: A Denial of Service (DoS) attack can occur due to logic errors, compatibility issues, or other security vulnerabilities, leading to the disruption of normal contract operations. Such issues could impact the availability of the contract, potentially causing it to become entirely non-functional.
Audit Focus:
- Evaluate the robustness of the business logic to ensure that it can operate correctly under various conditions and does not encounter errors or vulnerabilities that could cause the contract to fail.
- Pay special attention to interactions with external modules, ensuring their compatibility to prevent service interruptions caused by external dependencies.
13. Gas Optimization Auditing
Description: Similar to Ethereum, Sui uses a Gas mechanism, where any module or script call consumes Gas. Therefore, it is necessary to optimize long and complex code to minimize Gas usage.
Audit Focus:
- Analyze complex calls to determine if they can be decoupled or simplified.
- Review high-frequency function calls to see if the efficiency of internal function execution can be improved.
14. Logic Design Auditing
Description: The focus of logic design auditing is to examine the business processes and implementations in the code to ensure there are no design flaws or discrepancies with expected outcomes. If the code implementation does not align with the intended logic, it may lead to unexpected behavior or security risks.
Audit Focus:
- Map out the possible call paths within the business processes, considering the roles and their respective permissions.
- Identify the data scope involved in each business process to ensure that data operations align with the business design.
- Compare actual call paths with the intended business processes to identify and analyze any potential deviations that could lead to unintended outcomes.
15. Miscellaneous
This section covers any content that has not been explicitly mentioned in the previous points.
Conclusion
By adhering to these best practices, developers can significantly enhance the security of their smart contracts, reducing potential risks. The goal of this best practice guide is to assist more developers in creating secure and reliable smart contracts, thereby promoting the healthy development of blockchain technology.
References:
- [1] https://intro.sui-book.com/
- [2] https://docs.sui.io/
- [3] https://move-dao.github.io/move-book-zh/introduction.html
About SlowMist
At SlowMist, we pride ourselves on being a frontrunner in blockchain security, dedicating years to mastering threat intelligence. Our expertise is grounded in providing comprehensive security audits and advanced anti-money laundering tracking to a diverse clientele. We’ve established a robust network for threat intelligence collaboration, positioning ourselves as a key player in the global blockchain security landscape. We offer tailor-made security solutions that span from identifying threats to implementing effective defense mechanisms. This holistic approach has garnered the trust of numerous leading and recognized projects worldwide, including names like Huobi, OKX, Binance, imToken, Crypto.com, Amber Group, Klaytn, EOS, 1inch, PancakeSwap, TUSD, Alpaca Finance, MultiChain, and Cheers UP. Our mission is to ensure the blockchain ecosystem is not only innovative but also secure and reliable.
We offers a variety of services that include but are not limited to security audits, threat intelligence, defense deployment, security consultants, and other security-related services. We also offer AML (Anti-money laundering) solutions, Vulpush (Vulnerability monitoring) , SlowMist Hacked (Crypto hack archives), FireWall.x (Smart contract firewall) , Safe Staking and other SaaS products. We have partnerships with domestic and international firms such as Akamai, BitDefender, FireEye, RC², TianJi Partners, IPIP, etc.
By delivering a comprehensive security solution customized to individual projects, we can identify risks and prevent them from occurring. Our team was able to find and publish several high-risk blockchain security flaws. By doing so, we wish to help spread awareness and raise the security standards in the blockchain ecosystem.