Blockchain Defi contract authorization theft U principle detailed

Blockchain Defi ContractAuthorizationTheft U principleDetailed explanation

Author:DexNav              Development Editor: Dex

With the continuous development of blockchain technology, decentralized finance (DeFi) has become an important area of blockchain technology application, attracting more and more capital and users. the DeFi protocol provides more opportunities for blockchain financial ecology, but with it, there are also various security risks. In the DeFi protocol, theAuthorization mechanismis an important security risk point, and many attacks are achieved by malicious exploitation of contract authorization. In this paper, we will analyze the theft principle of DeFi contract authorization and propose some defensive measures.

I. DeFi contract authorization theft principle

The authorization mechanism of the DeFi protocol allows users to authorize other contracts or individuals to access or manage their token assets on their own behalf, and this authorization is permanent. Authorization represents a user's trust in the authorized party and allows it to perform some operations on its behalf, such as trading, storing and transferring assets. However, this authorization mechanism can be exploited by attackers, which can lead to the theft of user tokens.

The following is a real-world example of how DeFi contract authorization theft works. in August 2020, shortly after going live, the YAM protocol (a new type of DeFi contract) was brought to a standstill due to a contract code flaw that caused the smart contract to fall from $30 to $0.01, near zero. This case highlights the security risks of the authorization mechanism in DeFi contracts.

By constructing a series of transactions, the attacker first initiates an authorized transaction to a contract and grants the malicious contract access to the user's tokens. The attacker then transfers the user's tokens through the authorized contract, ultimately resulting in the theft of the user's tokens. This type of attack is known as an "authorized theft attack" and is a relatively common attack method in the DeFi space.

Common defenses against authorization theft attacks include minimizing the scope of authorization and revocation of authorization, increasing security checks, and enhancing user education. Let's explain in detail the code implementation scheme of DeFi contract authorization.

II. DeFi contract authorization code implementation scheme. Contract development contact telegram

InSolidityIn this case, the contractual authorization mechanism can be implemented by the following code.

pragma solidity ^0.8.0;

contract MyContract {
    address public owner;
    mapping(address => bool) public authorized;

    constructor() {
        owner = msg.sender;

    modifier onlyOwner() {
        require(msg.sender == owner, "Only the contract owner can call this function.");

    modifier onlyAuthorized() {
        require(authorized[msg.sender], "Only authorized callers can call this function.");

    function authorize(address _address) public onlyOwner {
        authorized[_address] = true;

    function revokeAuthorization(address _address) public onlyOwner {
        authorized[_address] = false;

    function authorizedFunction() public onlyAuthorized {
        // do something only authorized callers can do

This sample contract contains a license management system where owner You can authorize other users to execute authorizedFunction()The authorization may also be revoked.onlyOwner modifier requires that only the contract owner can call the functions that authorize and revoke authorization, while the onlyAuthorized The modifier requires that the call to authorizedFunction() The address must be in the authorization list.

In terms of authorization implementation, one common approach is to use the ERC20 standard approve() function. This function allows a user to authorize a certain number of tokens to an address, after which the address can call the user's tokens and implement certain business logic. For example, in an exchange, the user can authorize the exchange to use their tokens for trading by calling the approve() function.

However, there is also a potential security risk in using the approve() function for authorization. This is because once the user has authorized the token usage permission, then the address can use the user's tokens at will, including operations such as transferring and trading. If the address authorized by the user has the risk of being attacked, then the user's tokens will also be at risk of being stolen.

To solve this problem, a new authorization mechanism is proposed, namely Token Authorization Front-running Attack (TAA). This mechanism is implemented through smart contracts and can prevent user tokens from being stolen during the authorization process.

The specific implementation is that the user calls a smart contract function before authorizing the token access. The function generates a random number and hashes that random number along with the user's address, token address, and authorization address to generate a hash value. This hash value is stored in the smart contract as an identifier for this authorization process.

Next, the user then calls the approve() function to authorize the token. This authorization transaction is also hashed and the hash value is compared with the previously generated token, and if it does not match, it is considered invalid.

After the authorization transaction is confirmed, the smart contract automatically removes the hash value from the smart contract. In this way, even if there is an attacker monitoring the user authorization process, he or she cannot forge the authorization transaction because the correct hash value is not available, thus protecting the user's token security.

The above is the implementation principle of the token authorization theft U principle, the following we will be specific through the code to achieve.

Code implementation.

In a smart contract, we need to define a structure that holds information such as the hash value and expiration time of the authorized transaction. The code is as follows.

struct TokenAuth {
    bytes32 hash;
    uint256 expiration;

Where hash is the hash value of the authorization transaction and expiration is the time when the authorization expires. We can define a mapping that maps the user address to the TokenAuth structure, then we need to define a function to generate the hash and save it, the code is as follows.

mapping (address => TokenAuth) public tokenAuthMap;

Now let's see how to implement authorization and revocation of authorization in Solidity.

In Solidity, we can use mapping to implement authorization and revocation of authorization. We can set the key of mapping to the user address and the value to a boolean type, indicating whether the address is authorized or not. When implementing authorization, we only need to set the value of the address to true. When revoking authorization, we only need to set the value of the address to false.

The following is sample code for implementing authorization and revocation of authorization in Solidity.

contract Auth {
    mapping (address => bool) authorized;

    function authorize(address user) public {
        authorized[user] = true;

    function revokeAuthorization(address user) public {
        authorized[user] = false;

    function isAuthorized(address user) public view returns (bool) {
        return authorized[user];

In this sample code, we define a code namedauthorizedof mapping, which is used to hold the authorized addresses. We also define three functions.

  • authorizeFunction: Used to authorize an address.
  • revokeAuthorizationFunction: Used to revoke authorization for an address.
  • isAuthorizedfunction: used to check if an address is authorized.

When we need to check if an address is authorized in a smart contract, we simply callisAuthorizedfunction, and just pass that address as an argument.

In blockchain Defi contracts, the authorization mechanism is an important safeguard used to protect users' digital assets. However, at the same time, attackers are constantly exploring and exploiting vulnerabilities to steal. Therefore, we, as developers of Defi contracts, need to continuously learn and explore new security mechanisms to ensure that our contracts can remain secure under the ever-changing attacks.

When developing a Defi contract, we need to consider all possible ways of attack and prevent them with appropriate security mechanisms. Only in this way can we ensure thatContract SecurityThe premise is to provide users with better digital asset trading and management services.

Therefore, we call on practitioners in the entire blockchain industry to not only pay attention to security issues, but also to invest more in the research and practice of security mechanisms, so as to contribute to the creation of a safer and more reliable digital financial world for the whole industry.

CustomizedDevelop blockchain contracts, applications.Contact by telegram :Dex
Welcome to join the Scientist Development Community :Dexnav
Copyrights:Dexnav Posted on February 26, 2023 at 12:59 pm.
Please specify source if reproducedBlockchain Defi contract authorization theft U principle in detail | Dexnav Blockchain navigation network

Related posts

No comments

No comments...