Smart Contract Auditing
Course
By Code Eater
Contents
Module A – Smart Contract Attacks
Module B – OpenZeppelin
Module C –Auditing Tools and
Security Techniques
Code Eater
Module A
Reentrancy Attack TOD Attack Short Address Attack
Time Dependence Attack [Link] Attack Short Address Attack
Floating and Precision Entropy Illusion Attack Practical
Visibility Attack DOS Attack Notes
Code Eater
Prerequisite
Blockchain and Solidity
Code Eater
Who is a Smart Contract Auditor?
Smart Contract Auditor
Code Eater
Who is a Smart Contract Auditor?
Reviewing Secure
Testing Specialization Responsibilities Reliable
Operate as
Analyzing
Intended
Smart Contract Auditor
Code Eater
SCA – Final Check Point
Smart Contract Smart Contract
Developer Auditor
Code Eater
SCA Roadmap
To learn about the smart contract auditor roadmap - Click Here.
Code Eater
ATTACK 1
Code Eater
Hacked By Reentrancy Attack
The DAO hack 2016 $60 million worth of Ether
Parity wallet bug 2017 $30 million worth of Ether
KingDice hack 2018 $1 million worth of Ether
SpankChain hack 2018 $38,000 worth of Ether
Code Eater
Receive Function
• In Solidity, the receive function is a special function that is used to receive Ether (the native
cryptocurrency of the Ethereum network) sent to a contract.
• The receive function is a fallback function that is called automatically when a contract receives
Ether without any data. This means that if someone sends Ether to a contract without
specifying a function to call, the receive function will be called automatically.
• A contract can have at most one receive function, declared using receive() external payable { ... }.
• This function cannot have arguments, cannot return anything, and must have external visibility
and payable state mutability.
Code Eater
Code Eater
Reentrancy
Code Eater
Code Eater
Reentrancy
F1(){ F2(){ F3(){
//code //code //code
Return 2
} } }
Code Eater
Code Eater
Reentrancy
receive external payable{ function requestEther(){
requestEther(); ([Link]).transfer(balance[[Link]]);
} balance[[Link]]=0;
}
Code Eater
Code Eater
Reentrancy
function requestEther(){
receive external payable{
([Link]).transfer(balance[[Link]]);
requestEther();
balance[[Link]]=0;
}
}
Code Eater
Code Eater
Reentrancy
function withdraw() public{
uint bal = balances[[Link]];
require(bal > 0);// eth >0
(bool sent, ) = [Link]{value: bal}("");
require(sent, "Failed to send Ether");
balances[[Link]] = 0;
Code Eater
Code Eater
Reentrancy
function withdraw() public{
uint bal = balances[[Link]];
require(bal > 0);// eth >0
(bool sent, ) = [Link]{value: bal}("");
require(sent, "Failed to send Ether");
balances[[Link]] = 0;
Code Eater
Code Eater
Reentrancy
function withdraw() public{
uint bal = balances[[Link]];
require(bal > 0);// eth >0
(bool sent, ) = [Link]{value: bal}("");
require(sent, "Failed to send Ether");
balances[[Link]] = 0;
Code Eater
Code Eater
Reentrancy
function withdraw() public{
uint bal = balances[[Link]];
require(bal > 0);// eth >0
(bool sent, ) = [Link]{value: bal}("");
require(sent, "Failed to send Ether");
balances[[Link]] = 0;
Code Eater
Code Eater
Reentrancy
bool lock=false;
function withdraw() public{
require(lock==false,”Locked”);
uint bal = balances[[Link]];
require(bal > 0);// eth >0
(bool sent, ) = [Link]{value: bal}("");
require(sent, "Failed to send Ether");
balances[[Link]] = 0;
lock=false;
}
Code Eater
Reentrancy
Prevention
Techniques
Limit External Implement
Function Calls Mutex Locks
Reentrancy Attack
Q1) What is a reentrancy attack?
• A reentrancy attack is an exploit that takes advantage of a computer program or smart contract
vulnerability. It allows an attacker to execute malicious code multiple times before the original
function has been completed, potentially causing damage to the program or allowing the attacker
to steal resources or data.
Q2) What happens in it?
• In a reentrancy attack, an attacker exploits a vulnerability in the smart contract code that
allows them to call the same function repeatedly before it has finished executing. In a
reentrancy attack, an attacker exploits a vulnerability in the smart contract code that allows
them to call the same function repeatedly before it has finished executing. It allows an
attacker to execute malicious code multiple times before the original function has been
completed, potentially causing damage to the program or allowing the attacker to steal
resources or data.
Code Eater
Reentrancy Attack
3) How it occurs?
• One way that reentrancy attacks can be carried out is through the use of recursive calls. When a
smart contract function calls another function, it may be possible for the second function to call
the first function again before the first function has finished executing. If this happens, the second
function can execute malicious code before the first function has a chance to complete.
• Another way that reentrancy attacks can be carried out is through the use of external calls.
When a smart contract calls an external contract or function, it may be possible for the
external contract or function to call the original contract again before the original contract
has finished executing. This can create a loop that allows the attacker to repeatedly execute
malicious code.
Code Eater
Reentrancy Attack
4) How to prevent it?
• To prevent reentrancy attacks, it is important for developers to carefully review their code and
identify any vulnerabilities. One way to do this is through the use of automated tools that can
detect potential weaknesses in the code. Additionally, developers should avoid using external calls
whenever possible and should carefully manage the flow of control within their smart contracts.
Another way is to use mutex.
To learn more about it – Click Here
Code Eater
ATTACK 2
Code Eater
Hacked By Time Dependence
Golem Network 2018 $0 million worth of Ether
• In April 2018, a hacker exploited a vulnerability in the Golem Network smart contract that allowed
them to execute a Time Dependence attack.
• The attack involved creating a large number of malicious transactions that contained invalid time
stamps. These transactions were then included in blocks that were mined by a specific miner who
was colluding with the attacker.
• The attack was considered a "white hat" attack, as the attacker did not steal any funds and
worked with the Golem team to resolve the issue.
Code Eater
Time Dependence
1) What time dependence attack?
• Time dependence attacks (also known as timestamp dependence attacks) are attacks that rely on the
current block timestamp to execute or prevent certain actions. Smart contracts that rely on timestamps
to make decisions or execute logic are vulnerable to these attacks.
2) What time dependence attack?
Code Eater
Time Dependence
2) Can [Link] be manipulated by miners?
• The [Link] variable in Solidity returns the current timestamp of the current block in Unix
epoch format (i.e., the number of seconds that have elapsed since January 1, 1970). This value is
determined by the miner that creates the block, and it's based on their system clock.
• While it's difficult for miners to directly manipulate the value of [Link], it's theoretically
possible for them to manipulate the timestamp to some extent. For example, miners could manipulate
the clock on their mining nodes to set a timestamp that's earlier or later than the actual current time. By
doing so, they could potentially affect the outcome of time-dependent operations in a smart contract.
• To mitigate the risk of miner manipulation of timestamps, it's important to design contracts that are
robust against potential timestamp manipulations. This can be done by using alternative time sources or
by implementing mechanisms to detect and handle incorrect timestamps. For example, a contract could
use an external time oracle to obtain the current time instead of relying solely on [Link].
Additionally, a contract could implement checks to ensure that the timestamp is within a reasonable
range and reject transactions with timestamps that are too far off from the expected value.
Code Eater
ATTACK 3
Code Eater
Floating Points and Precision attack
1) What are Floating Points and Precision attack?
• In Solidity, floating-point numbers are not fully supported, and the precision can be lost when
performing arithmetic operations. This can lead to unexpected behavior, including vulnerabilities in
smart contracts.
One example of a floating-point precision attack is when a smart contract uses floating-point
numbers for financial calculations, such as in a decentralized exchange. If the precision is not
carefully managed, an attacker could manipulate the contract to gain an advantage in trading.
Code Eater
ATTACK 4
Code Eater
Hacked By Default Visibility
Parity multi-sig hack 2017 $31million worth of Ether
Code Eater
Hacked By Default Visibility
• In earlier versions of Solidity, functions were set to "public" visibility by default. This means that all
functions in a contract were publicly visible and accessible by anyone, including other contracts on the
blockchain.
• While this made it easier for developers to write and deploy contracts, it also introduced potential
security risks. If a function was not intended to be publicly accessible, but was not explicitly marked as
"private" or "internal", it could be accessed by other contracts and potentially lead to unexpected or
unintended behavior.
• To address this issue, Solidity introduced a new default visibility setting in version 0.5.0. Functions are
now set to "internal" by default, meaning that they can only be called by other functions within the same
contract. This makes it easier for developers to write secure and modular contracts that can be more
easily audited and tested.
• However, it's important to note that even with the new default visibility setting, developers still need to
be careful and deliberate in their use of visibility modifiers to ensure that their contracts are secure and
behave as intended.
Code Eater
Default Visibility
1) What time dependence attack?
• Default visibility attack is a type of security vulnerability in smart contracts where the visibility
modifier for a function is not explicitly defined, allowing it to be accessed by anyone, including
other contracts.
• An attacker can take advantage of this vulnerability by creating a malicious contract that calls the
public function in the victim contract and modifies its state in unexpected ways. This can lead to
loss of funds or other unintended consequences.
Code Eater
ATTACK 5
Code Eater
Hacked By TOD Attack
Bancor decentralized exchange 2020 $460,000 worth of Ether
Code Eater
Transaction-Ordering Dependence Attack?
1) What is Transaction-Ordering Dependence Attack?
• Transaction-Ordering Dependence (TOD) Attack, also known as front-running, is a type of attack where an
attacker exploits the order in which transactions are processed by the network. The attacker monitors the
network for pending transactions and submits their own transaction with a higher gas price to ensure it is
processed before the target transaction.
2) How it happens?
• The TOD attack can be used to manipulate the outcome of certain transactions or to gain an unfair advantage
over other participants in the network. For example, an attacker could front-run a trade on a decentralized
exchange (DEX) by submitting their own trade with a higher gas price to ensure it is processed before the target
trade, allowing the attacker to profit from the price difference.
Code Eater
Transaction-Ordering Dependence
uint public balance;
address public winner;
function deposit() public payable {
balance += [Link];
winner = [Link];
}
function withdraw(uint _amount) public {
require(balance >= _amount, "Insufficient balance");
require([Link] == winner, "You are not the winner");
balance -= _amount;
payable([Link]).transfer(_amount);
}
Code Eater
Transaction-Ordering Dependence Attack
• Now, let's consider the following scenario:
• User A calls the deposit function and deposits 10 Ether, setting lastUser to their
address.
• User B also calls the deposit function and deposits 5 Ether, setting lastUser to their
address.
• Before User A can call the withdraw function, a miner includes User B's deposit
transaction before User A's deposit transaction in the same block.
• User A calls the withdraw function and tries to withdraw 10 Ether, but the require([Link] ==
lastUser) check fails because User B is now the lastUser.
• User A is unable to withdraw the Ether and loses the gas fees paid for the failed transaction.
Code Eater
Hacked By TOD Attack
Bancor decentralized exchange 2020 $460,000 worth of Ether
• The attack involved placing a large buy order for a certain token on the Bancor exchange and then
using a second transaction to intentionally slow down the processing of the first transaction by
including a very high gas price.
• This caused the order to execute at a higher-than-market price, allowing the hackers to profit from
the price difference.
• The hackers then used a third transaction to cancel the original buy order, allowing them to repeat
the attack multiple times.
• Following the attack, Bancor temporarily halted trading and implemented new measures to prevent
similar attacks in the future, including a minimum time requirement for cancelling orders and a gas
price limit for executing trades.
Code Eater
ATTACK 6
Code Eater
[Link]
0x121 0x234 0x534
f1() f2()
[Link] = 0x121 [Link] = 0x234
[Link] = 0x121 [Link] = 0x121
Code Eater
[Link]
1) What is [Link] ?
• [Link] is a global variable in Ethereum smart contracts that represents the external account that
initiated the transaction. It contains the address of the user account that first created and sent the
transaction to the network.
0x121 0x234 0x534
f1() f2()
[Link] = 0x121 [Link] = 0x234
[Link] = 0x234 [Link] = 0x121
Code Eater
[Link]
2) [Link] vs [Link] ?
• With [Link] the owner can be a contract.
• With [Link] the owner can never be a contract.
• It's important to note that [Link] is not the same as [Link], which represents the address of
the immediate sender of the current message or transaction. This is because a transaction can be
forwarded or relayed by multiple contracts before it reaches the current contract, and [Link]
will always represent the immediate sender of the current message, even if it's a contract that
forwarded the transaction.
• [Link] is mainly used for security purposes to ensure that only authorized external accounts can
execute certain operations in a smart contract. However, it's generally recommended to use
[Link] instead of [Link] in most cases, as it provides more flexibility and security in contract
execution.
Code Eater
[Link] Authentication
3) What is [Link] Attack?
• The [Link] authentication attack is a vulnerability that can occur when a contract uses [Link] to
authenticate a message sender instead of [Link]. The [Link] variable returns the address of
the account that originated the transaction, which is not always the same as [Link].
• An attacker can exploit this vulnerability by creating a contract that calls the vulnerable contract
and sends a transaction with a [Link] that is different from the [Link]. The attacker can
then pass a malicious message to the vulnerable contract, which would assume that the [Link]
is the original sender and execute the transaction.
Code Eater
contract Phishable {
address public owner;
constructor (address _owner) {
owner = _owner;
}
receive() external payable{
// collect ether
}
function withdrawAll(address payable _recipient) public {
require([Link] == owner);
_recipient.transfer(address(this).balance);
}
}
Notice this contract authorizes the withdrawAll() function using [Link]. This contract allows for an attacker
to create an attacking contract of the form,
Code Eater
import "./[Link]";
contract AttackContract {
Phishable phishableContract;
address payable attacker; // The attackers address to receive funds.
constructor (Phishable _phishableContract, address payable _attackerAddress) {
phishableContract = _phishableContract;
attacker = _attackerAddress;
}
receive() external payable {
[Link](attacker);
}
}
To utilize this contract, an attacker would deploy it, and then convince the owner of the Phishable contract to
send this contract some amount of ether. The attacker may disguise this contract as their own private address
and social engineer the victim to send some form of transaction to the address. The victim, unless careful,
may not notice that there is code at the attacker's address, or the attacker may pass it off as being a multi-
signature wallet or some advanced storage wallet.
Code Eater
• In any case, if the victim sends a transaction (with enough gas) to the AttackContract address, it will invoke
the receive function, which in turn calls the withdrawal () function of the Phishable contract, with the
parameter attacker. This will result in the withdrawal of all funds from the Phishable contract to the
attacker’s address. This is because the address that first initialized the call was the victim (i.e. the owner of
the Phishable contract). Therefore, tx. origin will be equal to the owner and the require of the Phishable
contract will pass.
Code Eater
ATTACK 7
Code Eater
Entropy Illusion
1) What is Entropy Illusion attack?
• The Entropy Illusion attack is a type of attack where the random number generator used in a smart
contract is not truly random, and instead relies on predictable inputs. This can allow an attacker to
predict the output of the random number generator and manipulate the contract's behavior.
2) Example of it?
• One example of the Entropy Illusion attack is when a smart contract uses the block timestamp as
an input to generate random numbers. Since the block timestamp is a public and predictable
value, an attacker can manipulate the contract's behavior by controlling the timing of their
transactions to influence the random number generated.
Code Eater
Entropy Illusion
3) How to prevent from this?
• To prevent the Entropy Illusion attack, smart contracts should use a reliable source of entropy to
generate random numbers. This can include using a trusted off-chain random number generator, or
using a cryptographic function that is designed to produce random outputs, such as the Keccak-256
hash function. Additionally, contracts should avoid using predictable inputs as a source of entropy,
such as the block timestamp or user-provided values.
Learn about Oracle Click here
Code Eater
ATTACK 8
Code Eater
Denial Of Service(DOS)
Server
Code Eater
Denial Of Service(DOS)
Server
Code Eater
DOS in Smart Contract
Transaction 1
Transaction 2
Transaction 3
Block
Transaction 4
Code Eater
DOS in Smart Contract
Transaction 1
Transaction 1
Transaction 2 Transaction 2
Transaction 3
Transaction 4
Transaction 3
Block
Transaction 4
Code Eater
Denial Of Service(DOS)
1) What is DOS?
• A Denial of Service (DoS) attack is a type of cyber attack in which an attacker attempts to
overwhelm a website, server, or network with traffic or requests, rendering it unavailable to
legitimate users. This is achieved by flooding the targeted system with an overwhelming amount of
traffic, either by sending a large number of requests or by exploiting vulnerabilities in the system
to cause it to crash or become unresponsive.
• A Denial of Service (DoS) attack is a type of cyber attack in which an attacker attempts to
overwhelm a website, server, or network with traffic or requests, rendering it unavailable to
legitimate users. This is achieved by flooding the targeted system with an overwhelming
amount of traffic, either by sending a large number of requests or by exploiting vulnerabilities
in the system to cause it to crash or become unresponsive.
Code Eater
DOS in Smart Contract
2) What is DOS in smart contract?
• In the context of Ethereum smart contracts, DOS (short for Denial of Service) refers to an attack that
exploits vulnerabilities in a smart contract's code to overwhelm the network and prevent
transactions from being processed or validated.
• This type of attack can occur when a smart contract contains a flaw that allows a malicious user to
perform an operation that consumes an excessive amount of resources or computational power.
For example, an attacker could create a smart contract that performs an infinite loop, causing the
network to become overwhelmed with requests and unable to process new transactions.
• To mitigate the risk of DOS attacks, Ethereum developers often use techniques such as gas limits and fee
structures to prevent excessive resource consumption by individual transactions. Additionally, smart
contract audits and code reviews can help identify potential vulnerabilities and prevent them from
being exploited.
Code Eater
DOS in Smart Contract
3) How to prevent from DOS attack?
• To prevent a DOS Attack, it is important to have proper authentication and identity verification
measures in place to ensure that each user has a unique and verified identity on the network. Here
are some ways to prevent a DOS Attack in your smart contract:
1. Implement identity verification
2. Implement a reputation system
3. Limit transactions per user
4. Implement gas limits
5. Monitor network activity
Code Eater
DOS in Smart Contract
1. Implement identity verification: Require users to verify their identity before they can use the
smart contract. This can be done by using third-party identity verification services or by
implementing your own verification system.
2. Implement a reputation system: Require users to build up a reputation on the network before they
can use the smart contract. This can be done by tracking a user's history of transactions and
interactions on the network.
3. Limit transactions per user: Implement a limit on the number of transactions a single user can
make within a given time period. This can help prevent an attacker from flooding the network with
transactions.
4. Implement gas limits: Set a gas limit for each transaction to prevent an attacker from consuming all
available gas on the network.
5. Monitor network activity: Monitor network activity for unusual patterns or spikes in transactions
that could indicate a potential DOS Attack.
It is important to note that these measures are not foolproof and may not completely prevent a determined
attacker from carrying out a DOS Attack. However, they can make it more difficult for an attacker to carry out
an attack and reduce the impact of the attack on the network.
Code Eater
Thank You
Please Like and Subscribe!
Instagram - @codeeater21
LinkedIn - @kshitijWeb3