Friday, January 19, 2024

Smart Contract Hacking Chapter 2 – Solidity For Penetration Testers Part 2

 

Beyond Hello World

This will be our last week of basics before we hop into actual vulnerabilities. 

In the last chapter, we covered a lot of differences between solidity and a traditional language and the keywords it uses to differentiate functionality within functions and transactions. We also reviewed a simple transaction on Remix.  Hopefully, creating your first transaction and reviewing it was a useful exercise. 

In this chapter, we will cover some other key aspects of understanding before we hop into our vulnerability discovery and exploitation. These key aspects will round off your understanding and really benefit you when attacking smart contracts. This will enable us to look at advanced solidity concepts with an offensive security mindset and help us to determine how to use them to our advantage when hacking smart contracts in the rest of this series.

I am sure you have noticed from the simple hello world example that Solidity is very much like a traditional program from a structural and coding standpoint. It only has some keywords and financial transnational differences due to its use case.

We will now cover another smart contract example where we will learn a lot more about the other key aspects of coding in solidity that makes it different and interesting, yet still is very easy to understand.  This will be a fuller featured contract that covers a large portion of typical functionality. We will break down each part of this smart contract in chunks and explain what the contract does which will provide enough context to jump into the exploitation chapters that follow and start to do some really cool attacks.

I would suggest that you type out this code into Remix and play around with it rather than copy paste or rely on reading this chapter alone.

Note: On the deposit function, just note you will need to add a value to the value field above the deploy options. You can also check the video walk through in the references for a functionality walk through if you get stuck.

Deploying this contract and playing with it, will give you an understanding of how it works in order to better understand what the code does. This is similar to a reconnaissance phase when testing an application where a walk through of the application functionality is the first thing you should do prior to running attacks and scans against your target. The deeper understanding of how an application works at a functional level is always a tremendous asset into subverting its business logic which is where the real vulnerabilities are found that do the most damage. If you do not understand what the application does, you will not find the best attack vectors against it.

 

Hands on Lab – Type out and review contract functionality:

Below is the full contract for your review. Type this out in remix, play with it a bit, and try out the following steps. Then come back for an explanation of each piece of the code.

 

Action  Steps:

ü Type out the code below and try to understand what it does
ü Compile and deploy the code into remix
ü Deposit 1 Ether into your account using the value field and denomination drop down
ü Check your Balance
ü Withdraw your balance (note this is in a smaller denomination we will explain that)
ü Check your Balance again
ü Click the isOwner button from a few of your accounts, and click the owner button to show the      owner
ü Then finally try the withdrawAll from a non-owner account followed by trying withdrawAll  
    from the owner account and note your balances.

 


1.  pragma solidity 0.6.6; 
2.   
3.  contract HelloWorld_Bank{
4.    address public owner;
5.    mapping (address => uint) private balances;
6.    
7.    constructor () public payable {
8.      owner = msg.sender; 
9.     }
10.    
11.//Setting Up authorization
12. function isOwner () public view returns(bool) {
13.   return msg.sender == owner;
14.  }
15. 
16. modifier onlyOwner() {
17.   require(isOwner());
18.   _;
19. }
20.  
21. function deposit () public payable {
22.  require((balances[msg.sender] + msg.value) >= balances[msg.sender]);
23.  balances[msg.sender] += msg.value;
24. }
25. 
26. function withdraw (uint withdrawAmount) public {
27.    require (withdrawAmount <= balances[msg.sender]);
28.        
29.    balances[msg.sender] -= withdrawAmount;
30.    msg.sender.transfer(withdrawAmount);
31. }
32.  
33.  
34. function withdrawAll() public onlyOwner {
35.    msg.sender.transfer(address(this).balance);
36. }
37. 
38. function getBalance () public view returns (uint){
39.    return balances[msg.sender];
40.}
41.}

 

Video Walk Through: 

   



Code Level Walk Through of HelloWorld Bank

While walking through the application in the action steps, you should have gotten a feel for what the contract does. By typing out the code you should also have at least a high-level understanding of the code logic.  We will now break the code into chunks and make sure that your understanding does not hold you back from learning as we move into exploitation in the next section.

1.  pragma solidity 0.6.6; 
2.   
3.  contract HelloWorld_Bank{
4.    address public owner;
5.    mapping (address => uint) private balances;

 

Our first chunk of code starts off similarly with our pragma line which states the compiler version used for execution of the smart contract as seen in the last chapter followed by the contract name.  Next, we have two variables which are created on lines 4 and 5. Both of these variables have a great importance to the flow of the application.

The first variable created is "owner" on line 4. This will be the contracts administrator which is not explicitly defined here, but instead defined in the next chunk of code in the constructor. Defining an owner in the constructor is common convention used in solidity to have an administrative user to limit usage of specific functionality. Usually, authorization of functionality is handled in a security library, for example Openzeppelin, which we will cover extensively when fixing smart contract vulnerabilities. However, in this case, we will show a simple implementation of authorization.

The second variable created "balances" on line 5 is something called a mapping in solidity. Mappings are similar to a dictionary lookup. It is a key value pair where in this case the address is mapped to a uint value.  The key is the address of the user, while the value is the users balance within the contract.  So, if you were to perform a dictionary lookup of a user's address you would be provided back their bank balance. You will also note that this is a private variable meaning that you cannot retrieve this value directly outside of the contract by referencing it. However, private variables as we will in later chapters are not as private as we think on the blockchain.


1.    constructor () public payable {
2.           owner = msg.sender; 
3.    }
4.      
5.    function isOwner () public view returns(bool) {
6.           return msg.sender == owner;
7.    }

 

This next section of code is called the constructor. The constructor runs one time when the contract is deployed and will set things up for the contract. In this case we are creating a constructor which is payable meaning that when you deploy the contract you can send Ethereum and that Ethereum will be stored within the contract's balance. This is useful if the contract requires a balance for some of its actions right out of the gate.

In line 2 we see our previously created owner variable being set to msg.sender. This is a way for the contract to set an administrative user when the contract is created. Since the constructor runs only one time, it's a good place to set an initial user. Often you will see this paired with a change owner function that is protected by the owner's authorization level and allows the current owner to set a new administrative user. The msg.sender variable in solidity is simply the users address who called the function, or in this case the user who published the contract initially. This is tied to the user's public address they use for transactions. 

Each time a user interacts with a contract, their address is known by the contract as the msg.sender value and this address is used to associate values with their account sort of like a session variable in a sense.  You can use this value to map functionality to that user. In the context of this contract you will see the msg.sender value used to set the Owner, validate the Owner, map balances on accounts and transfer value back to the user.

On line 5 you will see a function created solely for the purpose of checking if the user interacting with a contract is the owner of the application. It checks this by returning true if the msg.sender value equals the current owners address. This is how the application enforces its authorization level on administrative users. For example, if you used require(isOwner) in the beginning of a function the function would refuse to run the rest of its code if the user calling the contract was not the owner:

 

1.     modifier onlyOwner() {
2.        require(isOwner());
3.        _;
4.     }

 

Above you will see an authorization modifier using isOwner implemented in line 2. This modifier is used to return a simple true or false based on the same require statement we referenced using isOwner. However, with a modifier we can check within the definition of a function instead of the body of the function as you will see further below with the withdrawAll function.  For now, as an example of a modifiers usage check out the following doesSomethingCool function definition, note onlyOwner within the definition.  This is how we would use a modifier for authorization checks.

1.  function doesSomeThingCool() public onlyOwner

 If the modifier is referenced in the function definition as shown in doesSomethingCool, the function body will not run unless the user's msg.sender value equals that of the owner of the contract.  After it checks for a true or false value on line 2 and the modifier code ends, the calling function will continue running as normal following the _; from line 3.   This _; value simply means continue running calling code as normal within the function provided the require modifier returned true. This is a much cleaner way to handle authorization across multiple functions with code reuse and ability to change code in one location rather than hunting down every function that needs authorization of some sort.

These next two functions should be pretty self-explanatory by now, but in the spirit of learning Solidity in this chapter we will deep dive all of the code.

 

1.   function deposit () public payable {
2.     require((balances[msg.sender] + msg.value) >= balances[msg.sender]);
3.     balances[msg.sender] += msg.value;
4.   }
5.   
6.   function withdraw (uint withdrawAmount) public {
7.     require (withdrawAmount <= balances[msg.sender]);
8.         
9.     balances[msg.sender] -= withdrawAmount;
10.   msg.sender.transfer(withdrawAmount);
11.}

 

Above we have two functions, a deposit function for filling your account with Ether from an external account and a withdraw function for removing your Ether from the contract. You will notice on line 1 that the definition of deposit has the words public and payable. The reason being that in order to deposit value to an account the function must be marked as a payable function. This goes for addresses as well, when using addresses within value transfers those addresses must also be marked as payable. This was something that was added the Solidity as of version 5, prior to version 5 if you are auditing code you will not see this keyword required within all portions of value transfer events.

In line 2 you will see a require line, the require line is a conditional check that if it fails the transaction will halt and revert back to the state before it was called. In this instance, if the value is not a positive value, it will fail and the function will return an error.  If the value is indeed a positive number, the next line will run and increase the account value of the user by the value that was sent.

The withdraw function at line 6 only receives a withdraw amount that is checked on line 7 to require that amount to be withdrawn is less than or equal to the account balance of that user. If this check fails and the user does not have a high enough balance for the withdraw, then transaction returns an error.  If it succeeds, then on lines 9 and 10 we decrease the balance of the user internally followed by transferring the approved amount back to the users account address.

 

Checks Effects Interactions:

Also note that this code follows the proper Solidity secure coding pattern of Checks, Effects, Interactions (CHI). We will go through Solidity coding patterns throughout the book. These are coding patterns which hinder attack vectors by design. In the CHI pattern, we always want to first check that the data is valid for the transaction which we did with the require statement. Then we want to do the effect of the transaction which is to reduce the balance of the user internally to the system. Finally, we want to interact with the external address we are transferring the value to. This pattern will become clear within the Reentrancy attack chapter.

Effectively an attacker could re-enter the contract and perform more actions bypassing initial checks if the value being transferred is not updating the balance prior to interacting with an un-trusted external party. In order to prevent the attacker from continually removing value from the contract, we always make sure to update the balance before transferring the value out of the contract.  If the transaction happens to fail, the transfer function will revert the actions taken in the contract effectively refilling the users account. 

At this point you are probably starting to notice that Solidity is pretty easy to understand. However, there are a lot of Gotchas if secure coding patterns are not used or dangerous low level functionality is handled incorrectly.

The final snippet of code should be easy to understand. At this point we have covered all of these concepts.

 

1.     function withdrawAll() public onlyOwner {
2.           msg.sender.transfer(address(this).balance);
3.     }
4.   
5.      function getBalance () public view returns (uint){
6.           return balances[msg.sender];
7.      }
8.   

 

The first thing to note is on line 1 which has the onlyOwner modifier created in the beginning of the contract. If you remember from the explanation earlier, when this modifier is added to the function definition, it will run the code within isOwner which checks if the user is the original contract owner created in the constructor when the contract was deployed. If this user is the owner, then the call within the body of the function executes and transfers all of the Ethereum value out of the contracts balance.  It does this by simply using a transfer function with the address of the contract and this.balance.  

That should all make sense if you have been following along but what doesn't make sense is a bit less obvious. Can you guess what that is?

Before reading the next paragraph, think about what's wrong with this function?

So, did you think about it? Did you ask yourself the question, "Why does this function even exist?"  This is an immediate red flag within the code, that the contract being used in this banking application might have nefarious purposes by the creators of the contract. At no time should the owner of the contract have the ability to empty the contract of all its funds. Including that of all of the users funds who are holding their Ethereum within their personal accounts on the contract.  Often you will see functions like this within less the reputable games which are planning an exit scam as soon as the contract balance reaches a desired threshold.

 

So, while its good to look for obvious vulnerabilities within code also think about the use case of the code being reviewed and if something looks off it probably is.

The final getBalance function on line 5 is simply a function that returns the balance of the user who calls the function. You will notice that within the function definition it uses the "view" keyword indicating that it is not modifying anything and should not incur fees for processing. It also indicates that it is returning a uint value which it does in line 6. The function returns the msg.sender's balance by querying the balances mapping with the msg.sender key.

 

Summary

This chapter should round out your knowledge of solidity enough to get started looking at vulnerabilities. We have covered a lot of common coding themes within solidity which may not be seen in other languages. We will be covering a lot of coding patterns along with vulnerable functionality within the following chapters on exploitation. We will walk through each vulnerability and why it's an issue within Solidity and then we will walk through how to attack it with examples of how an attacker would craft requests or additional attacking code to exploit the flaws. For additional information on the code above and a walk through of the functionality in real time, check out the chapters video in the references below.

 

Contact Info:

@ficti0n

http://cclabs.io

http://consolecowboys.com


References:

https://www.youtube.com/watch?v=U9IWSHcfR08

Open Zeppelin

https://github.com/OpenZeppelin/openzeppelin-contracts

Checks Effects Interactions

https://solidity.readthedocs.io/en/v0.6.0/security-considerations.html?highlight=checks%20effects#use-the-checks-effects-interactions-pattern

Related articles
  1. Hack Tools For Ubuntu
  2. Install Pentest Tools Ubuntu
  3. Nsa Hacker Tools
  4. Hacking Tools
  5. Pentest Tools Website Vulnerability
  6. Hacker
  7. Hacking Tools Free Download
  8. Hack Tools Online
  9. Top Pentest Tools
  10. Hack Tools 2019
  11. Hacking Tools For Pc
  12. Pentest Tools List
  13. Pentest Tools For Windows
  14. Best Hacking Tools 2019
  15. Hacker Tools Mac
  16. Best Hacking Tools 2019
  17. Pentest Tools Windows
  18. Install Pentest Tools Ubuntu
  19. Hacker Security Tools
  20. Hacking Tools
  21. Install Pentest Tools Ubuntu
  22. Hack Rom Tools
  23. Best Hacking Tools 2019
  24. Hacking Tools Name
  25. Hacker Tools List
  26. Hacking Tools For Windows 7
  27. Physical Pentest Tools
  28. Hacker Tools Windows
  29. Hack Tools Mac
  30. Hacking Tools For Windows 7
  31. Computer Hacker
  32. Pentest Tools Subdomain
  33. Hacking Tools Pc
  34. Hack Tools Github
  35. Tools For Hacker
  36. Tools Used For Hacking
  37. Computer Hacker
  38. Pentest Tools Windows
  39. Hacking Tools Windows
  40. Pentest Tools Android
  41. Hacker Tools Online
  42. New Hacker Tools
  43. Pentest Tools Android
  44. Hacker Tools For Pc
  45. Pentest Tools Subdomain
  46. Termux Hacking Tools 2019
  47. Best Pentesting Tools 2018
  48. How To Hack
  49. Hack Apps
  50. Best Pentesting Tools 2018
  51. Nsa Hack Tools
  52. Hacker Tools Apk
  53. Hacker Techniques Tools And Incident Handling
  54. Hacker Tool Kit
  55. How To Hack
  56. Hak5 Tools
  57. Hacking Tools Windows
  58. Termux Hacking Tools 2019
  59. Wifi Hacker Tools For Windows
  60. Pentest Tools Online
  61. Hacker Tools
  62. Hacking Tools Free Download
  63. Hacker Tools For Windows
  64. Pentest Recon Tools
  65. Hacking Tools Kit
  66. Hacking Tools Online
  67. Pentest Tools Download
  68. Hacking Tools For Pc
  69. Hacker Tools Windows
  70. Pentest Tools Linux
  71. Hacking Tools 2019
  72. Top Pentest Tools
  73. Nsa Hack Tools Download
  74. Hack Tools For Mac
  75. Hacking Tools Pc
  76. Easy Hack Tools
  77. Kik Hack Tools
  78. Hacker Tools Linux
  79. Kik Hack Tools
  80. Hack Tools
  81. Hack And Tools
  82. Hack Tools For Mac
  83. Growth Hacker Tools
  84. World No 1 Hacker Software
  85. Pentest Tools For Ubuntu
  86. Computer Hacker
  87. Nsa Hack Tools
  88. Hacker Tools
  89. Hacker Search Tools
  90. Hacking Tools
  91. Pentest Tools Bluekeep
  92. Pentest Tools Bluekeep
  93. Hacking Tools Mac
  94. Pentest Box Tools Download
  95. Hack Tools For Windows
  96. Hack Apps
  97. Hacker Tools 2020
  98. Hack Tools
  99. Install Pentest Tools Ubuntu
  100. Hack App
  101. Hack Tools For Games
  102. Hacker Tools 2020
  103. Pentest Tools For Ubuntu
  104. Pentest Tools Bluekeep
  105. Bluetooth Hacking Tools Kali
  106. Game Hacking
  107. Hacks And Tools
  108. Hacking Tools For Mac
  109. Best Pentesting Tools 2018
  110. Hack Tools Github
  111. Pentest Tools Find Subdomains
  112. Hacker Tools Hardware
  113. Hacker Tools Apk
  114. Hacking Tools For Windows Free Download
  115. Pentest Tools For Windows
  116. Nsa Hack Tools Download
  117. Pentest Tools Free
  118. Hackers Toolbox
  119. Hacking Tools Free Download
  120. Hack Website Online Tool
  121. Pentest Tools Kali Linux
  122. Pentest Tools For Windows
  123. Hacker Search Tools
  124. Physical Pentest Tools
  125. Hack Tools Online
  126. Free Pentest Tools For Windows
  127. Tools Used For Hacking
  128. Pentest Reporting Tools
  129. Pentest Tools List
  130. Easy Hack Tools
  131. Hack Tools Pc
  132. Hacker Tools 2020
  133. Hacks And Tools
  134. Hacker Techniques Tools And Incident Handling
  135. Hack And Tools
  136. Hack Tools For Pc
  137. Pentest Tools
  138. Best Hacking Tools 2020
  139. Nsa Hacker Tools
  140. Pentest Tools Website
  141. Hack Tools
  142. Computer Hacker
  143. Hacking Tools 2019
  144. Hak5 Tools
  145. Hacker Tools Online
  146. Hacker Tools For Ios
  147. Pentest Reporting Tools
  148. Nsa Hacker Tools
  149. Pentest Tools
  150. Pentest Tools For Mac
  151. Hacker Tool Kit
  152. Hacking Tools For Windows
  153. Pentest Tools Tcp Port Scanner
  154. Tools Used For Hacking
  155. Hacker Tools List
  156. Hacking Tools For Games