Arithmetic Overflow and Underflow | Hack Solidity (0.6)

Smart Contract Programmer
26 Jun 202011:38

Summary

TLDRThis video tutorial delves into the concept of overflow and underflow in smart contracts, particularly using the example of a time-locked contract vulnerable to such issues. It demonstrates how overflow can allow unauthorized early withdrawal by manipulating contract time, and introduces the Safe Math library by OpenZeppelin to prevent such exploits, showcasing its implementation to safeguard against numeric vulnerabilities.

Takeaways

  • πŸ“š Overflow and underflow are vulnerabilities in smart contracts that occur when numbers exceed their maximum or minimum range, causing unexpected results.
  • πŸ”’ In Solidity, the 'uint256' data type can represent numbers from 0 to 2^256 - 1, and exceeding this range leads to overflow.
  • ⏱ Overflow can be exploited to manipulate the 'lock time' in a smart contract, allowing immediate withdrawal instead of waiting for the set period.
  • πŸ’‘ The script demonstrates a smart contract called 'TimeLock' that is vulnerable to overflow, allowing attackers to bypass the intended waiting period.
  • πŸ›  To exploit the vulnerability, an 'attack' contract is created, which sends a specific (overflow-inducing) value to the 'TimeLock' contract to reset the lock time to zero.
  • πŸ”„ The overflow is achieved by calculating a value that, when added to the current lock time, equals 2^256, causing the lock time to wrap around to zero.
  • πŸ›‘ To prevent overflow and underflow vulnerabilities, the script recommends using the 'SafeMath' library, which checks for arithmetic operations that could lead to overflow.
  • πŸ“ The 'SafeMath' library adds functions like 'add', 'sub', 'mul', and 'div' to the 'uint256' type, ensuring that arithmetic operations are safe from overflow.
  • πŸ”¬ The script includes a practical demonstration of how using 'SafeMath' can prevent the overflow exploit, making the 'TimeLock' contract secure against such attacks.
  • πŸ”— The video provides a link to the code in the description for further exploration and learning about overflow, underflow, and smart contract security.

Q & A

  • What is an overflow in the context of the video?

    -An overflow occurs when a number exceeds the maximum range it can represent, causing the excess to wrap around and start counting from zero, resulting in a smaller number than intended.

  • What is underflow, and how does it differ from overflow?

    -Underflow is similar to overflow but happens in the opposite direction. It occurs when a number is smaller than the minimum range, causing it to count backward from the maximum number, resulting in a larger number than intended.

  • What is the significance of the number 2^256 in the context of unsigned integers?

    -The number 2^256 represents the maximum value that an unsigned integer with 256 bits can hold. It signifies the upper limit before an overflow occurs.

  • How does the video demonstrate an overflow example using unsigned integers?

    -The video demonstrates an overflow by showing what happens when a number exceeds the maximum value of 2^256 - 1. It explains that adding 3 to this maximum value would wrap around to 2, illustrating the overflow effect.

  • What is the 'TimeLock' contract mentioned in the video, and what is its purpose?

    -The 'TimeLock' contract is a smart contract that allows users to deposit Ether with the condition that they must wait at least one week before they can withdraw it. It uses mappings to keep track of balances and lock times.

  • How can a vulnerability in the 'TimeLock' contract be exploited to bypass the one-week waiting period?

    -The vulnerability can be exploited by causing an unsigned integer overflow in the lock time mapping. By depositing Ether and then increasing the lock time with a huge number that causes an overflow, the lock time can be reset to zero, allowing immediate withdrawal.

  • What is the 'SafeMath' library, and how does it help prevent overflow and underflow?

    -The 'SafeMath' library is a collection of mathematical functions that automatically check for overflow and underflow conditions. By using this library, operations that would result in an overflow or underflow will revert, preventing the exploit.

  • How can the 'TimeLock' contract be modified to incorporate the 'SafeMath' library and prevent overflows?

    -The 'TimeLock' contract can be modified by importing the 'SafeMath' library and using its functions for arithmetic operations, such as 'add', instead of the default unsigned integer operations. This ensures that any operation that would cause an overflow will be prevented.

  • What is the purpose of the 'attack' contract demonstrated in the video?

    -The 'attack' contract is a demonstration of how an attacker could exploit the overflow vulnerability in the 'TimeLock' contract to withdraw Ether without waiting for the required one-week period.

  • How does the video show the successful prevention of the overflow attack after implementing 'SafeMath'?

    -The video shows that after recompiling and deploying the 'TimeLock' contract with 'SafeMath', attempting the overflow attack with the 'attack' contract results in a transaction failure due to the 'SafeMath' library's overflow check.

  • What is the final recommendation of the video for preventing overflow and underflow in smart contracts?

    -The final recommendation is to use the 'SafeMath' library or similar mathematical libraries that include overflow and underflow checks to secure smart contracts against such vulnerabilities.

Outlines

00:00

πŸ“ˆ Understanding Overflow and Underflow in Smart Contracts

This paragraph introduces the concepts of overflow and underflow in the context of smart contracts, particularly with unsigned integers. Overflow occurs when a number exceeds the maximum value it can represent, causing it to wrap around to a smaller number. Underflow is the opposite, where a number less than the minimum range wraps around to a larger number. The speaker uses the example of a 256-bit unsigned integer to illustrate these concepts, explaining the range it can represent and how numbers outside this range behave. The importance of being cautious with number handling in Solidity is emphasized due to the lack of warnings or errors for these conditions.

05:02

πŸ’‘ Smart Contract Vulnerability: TimeLock Exploitation

The second paragraph delves into a specific smart contract vulnerability related to overflow and underflow, using a TimeLock contract as an example. This contract allows users to deposit Ether with a one-week lock period before withdrawal. The speaker describes how an attacker can exploit the overflow vulnerability by manipulating the lock time to a very large number, causing an unsigned integer overflow that resets the lock time to zero, thereby allowing immediate withdrawal. The paragraph outlines the steps of the attack, including depositing Ether, increasing the lock time with a crafted large number to trigger overflow, and then withdrawing the funds without waiting.

10:03

πŸ›‘οΈ Preventing Overflow and Underflow with Safe Math Library

The final paragraph discusses how to prevent the overflow and underflow vulnerabilities in smart contracts. The speaker introduces the Safe Math library by OpenZeppelin, which automatically checks for overflow and underflow conditions and reverts transactions if such conditions are detected. The paragraph explains the integration of the Safe Math library into the TimeLock contract to protect against the previously described attack. By using the 'add' function from the Safe Math library, the contract ensures that the lock time cannot be manipulated to cause an overflow, thus securing the contract against such exploits.

Mindmap

Keywords

πŸ’‘Overflow

Overflow in the context of this video refers to a situation in computer programming where a number exceeds the maximum limit that can be stored in a given data type, causing it to wrap around to a smaller number. This is a critical issue in smart contract development, as it can lead to vulnerabilities and unexpected behavior. The script illustrates overflow with an example using an unsigned integer (uint) with a maximum value of 2^256 - 1, where adding 3 to this maximum value results in an overflow, wrapping the number back to 2.

πŸ’‘Underflow

Underflow is the counterpart to overflow, occurring when a number is less than the minimum value that can be represented, causing it to wrap around to a larger number. In the video, underflow is explained in relation to unsigned integers, where subtracting 1 from a value of 0 results in the maximum representable number, 2^256 - 1, due to the underflow effect.

πŸ’‘Smart Contract

A smart contract is a self-executing contract with the terms of the agreement directly written into code. In the video, the script discusses a specific smart contract called 'TimeLock' that is vulnerable to overflow and underflow attacks. The smart contract manages deposits and withdrawals of Ether with a time restriction, which can be manipulated due to numerical vulnerabilities.

πŸ’‘Unsigned Integer (uint)

An unsigned integer, or uint, is a data type that represents non-negative integers. In the video, the script uses uint256, which can represent numbers from 0 to 2^256 - 1. The video demonstrates how operations on unsigned integers can lead to overflow and underflow, which are significant security concerns in smart contract programming.

πŸ’‘TimeLock Contract

The TimeLock contract mentioned in the script is a smart contract that allows users to deposit Ether with the condition that they must wait a specified amount of time before they can withdraw it. The contract uses mappings to keep track of each user's balance and the lock time for their funds. The video uses this contract to demonstrate how overflow and underflow can be exploited.

πŸ’‘Exploit

In the context of the video, an exploit refers to a technique used to take advantage of a bug or vulnerability in a system, such as a smart contract. The script describes how an attacker can manipulate the TimeLock contract's lock time by causing an unsigned integer overflow, allowing them to withdraw funds before the lock period has expired.

πŸ’‘Safe Math Library

The Safe Math library is a collection of mathematical functions designed to prevent common issues like overflow and underflow in smart contract development. The video script explains how to integrate the Safe Math library into a smart contract to safely perform arithmetic operations, thereby preventing the overflow and underflow vulnerabilities demonstrated in the TimeLock contract.

πŸ’‘Arithmetic Operations

Arithmetic operations such as addition, subtraction, multiplication, and division are fundamental to many smart contract functionalities. The video script discusses how these operations can lead to overflow and underflow if not handled correctly, particularly when dealing with unsigned integers and fixed maximum values.

πŸ’‘Solidity

Solidity is a programming language specifically designed for writing smart contracts on the Ethereum blockchain. The video script uses Solidity to demonstrate the TimeLock contract and the vulnerabilities associated with unsigned integer arithmetic. Solidity does not inherently prevent overflow and underflow, making it crucial for developers to be aware of these issues.

πŸ’‘Attack Contract

The Attack contract in the video is a demonstration of how an attacker might exploit the overflow vulnerability in the TimeLock contract. By sending a specially crafted transaction that manipulates the lock time using an overflow, the Attack contract is able to bypass the withdrawal restrictions and extract funds prematurely.

πŸ’‘Transaction

A transaction in the context of blockchain and smart contracts is a digital signature linked to a script that executes under certain conditions. In the video, transactions are used to demonstrate the normal operation of the TimeLock contract as well as the successful and failed attempts of the Attack contract to exploit the overflow vulnerability.

Highlights

Introduction to overflow and underflow in the context of smart contracts.

Explanation of overflow as a situation where a number exceeds the maximum range and wraps around to a smaller number.

Description of underflow, which is the opposite of overflow, causing numbers to count backwards from the maximum.

Use of the unsigned integer (uint) data type in smart contracts to represent a range of numbers.

Example of how an overflow occurs with a uint256 data type and the resulting wrap-around effect.

Solidity's lack of warnings or errors for overflow and underflow, emphasizing the need for caution.

Introduction of a smart contract called TimeLock that is vulnerable to overflow and underflow attacks.

Explanation of the TimeLock contract's functionality, including depositing and withdrawing with a one-week lock period.

Demonstration of how to exploit the TimeLock contract by causing an overflow in the lock time.

Mathematical approach to finding the exact number that causes an overflow in the contract's lock time.

Creation of an 'attack' contract to exploit the TimeLock contract by manipulating the lock time.

Deployment of the attack contract and the process of exploiting the TimeLock contract to withdraw funds immediately.

Verification of the successful overflow exploit by checking the lock time of the TimeLock contract.

Prevention of overflow and underflow attacks by using the SafeMath library from OpenZeppelin.

Integration of SafeMath into the TimeLock contract to prevent overflow and underflow vulnerabilities.

Testing the updated TimeLock contract with the SafeMath library to ensure the overflow exploit no longer works.

Conclusion summarizing the importance of using SafeMath to secure smart contracts against numerical vulnerabilities.

Transcripts

play00:00

hey everyone in this video we will learn

play00:02

about overflow and on the floor

play00:04

first of all I'll explain what it is and

play00:08

then we'll examine a smart contract that

play00:10

is vulnerable to overflow and on the

play00:13

flow and that's the I'll show how you

play00:15

can protect your smart contract code

play00:17

from overflow and on the flow alright so

play00:20

what are overflow and on the flow

play00:23

overflow occurs when a number is too big

play00:26

the part that exceeds the maximum range

play00:28

is count from zero again so you end up

play00:31

with a number that is smaller than what

play00:33

you started with on the flow is similar

play00:36

to overflow and it happens in the

play00:38

opposite direction when a number is

play00:41

smaller than the minimum range it starts

play00:44

counting back from the maximum number

play00:46

and you end up with a number that is

play00:48

greater than what you started with let's

play00:51

look at an example using youant which

play00:53

stands for unsigned integer now the

play00:57

datatype youant is a short name for you

play00:59

and 256 and what does this 256 tell us

play01:04

well it means that it can represent to

play01:06

the 256 numbers ranging from 0 to 2 to

play01:11

the 256 minus 1 so let's look at

play01:14

overflow what happens when a number is

play01:17

greater than 2 to the 256 minus 1 so

play01:21

over here on the right we have X which

play01:24

is beyond the maximum range how the

play01:26

solidity handle a number that is beyond

play01:29

the range well it wraps around and then

play01:32

starts counting forward from 0 for

play01:35

example let's say that the number X is 3

play01:38

greater than the maximum range and now

play01:41

let's calculate where this number is

play01:42

going to end up well 1 beyond the

play01:45

maximum number will get us back to 0 2

play01:49

beyond the maximum number will land at 1

play01:51

and finally 3 beyond the maximum number

play01:55

will land at 2 so if the number is 3

play01:58

plus the maximum number then it wraps

play02:01

around and we end up at 2 so this is

play02:04

overflow and when a number overflows so

play02:07

Lily does not give you any warnings or

play02:09

errors it just doesn't care on the floor

play02:13

things in the opposite direction of

play02:15

overflow so here we have a number that

play02:18

is less than zero which is the minimum

play02:20

range in this case what will happen is

play02:23

that the number will be counted

play02:24

backwards from the maximum number let's

play02:28

see an example using the number negative

play02:30

two

play02:31

where would negative two end up on the

play02:34

range between 0 and 2 to the 256 minus 1

play02:38

well minus 1 will give us the maximum

play02:41

number which is 2 to the 256 minus 1 and

play02:45

negative 2 will be 1 less than that

play02:48

which is 2 to 256 minus 2 this is on the

play02:53

flow and again solidity will not give

play02:56

you any warnings or errors so when

play02:59

you're dealing with numbers and solidity

play03:01

you gotta be careful of overflow and

play03:04

underflow let's now examine a contract

play03:07

that is born wall to this behavior time

play03:10

mark is a contract where you can deposit

play03:12

eater and you have to wait at least one

play03:15

week before you can withdraw the amount

play03:17

of meter that you deposit into this

play03:19

contract is kept in a mapping called

play03:22

balances the time at which you can

play03:25

withdraw is kept in a mapping called

play03:27

lock time we need to posit either into

play03:30

this contract it does two things it

play03:33

first updates your balance and then it

play03:36

updates long time to one week from now

play03:39

so this means that you won't be able to

play03:41

withdraw from this contract for at least

play03:44

one week and you can see how this

play03:46

mapping is used in the withdrawal

play03:48

function so let's take a look so you

play03:51

deposited some meter into this contract

play03:53

waited one week and now you want to

play03:56

withdraw from it the function withdrawal

play03:59

will first check that you have some

play04:00

meters deposited into this contract and

play04:04

this is done by checking that the

play04:05

balances mapping of your address is

play04:07

greater than 0

play04:09

next it checks that the current time is

play04:11

greater than the law of time so if you

play04:14

try to call this function before one

play04:16

week has passed since you deposited this

play04:20

check will fail and you won't be able to

play04:23

withdraw after the two checks about pass

play04:26

we update the

play04:27

and then send the ether back to you

play04:30

that's how the withdrawal function works

play04:33

now if you want to increased a lot of

play04:35

time say one month then you can do that

play04:38

by calling this function increase long

play04:41

time for the input you passing the

play04:44

settings to increased a lot time by and

play04:46

then it will add the settings to

play04:48

increase to the current log time so this

play04:52

is how the contract time table works it

play04:54

allows you to deposit but you have to

play04:57

wait a minimum of one week before you

play04:59

can withdraw and you can also increase

play05:02

the time log by calling increased log

play05:05

time this contract is vulnerable to you

play05:08

and overflow I'm going to show you how

play05:10

you can withdraw from this contract

play05:12

without waiting one week and the basic

play05:16

idea behind this hack is to update Bob

play05:19

time with a very huge number the

play05:22

contract that's going to hack the time

play05:24

they'll contract above will name it

play05:25

attack will store the contract that's

play05:28

going to be exploited in a state

play05:30

variable called time bok and using a

play05:33

constructor we'll set our target here

play05:36

we're going to need a payable fallback

play05:38

function so that we can receive the

play05:40

liter withdrawn from the time log

play05:42

contract to initiate the attack will

play05:45

create a function called attack we're

play05:48

going to be sending some meter to the

play05:50

time log contract so we will declare

play05:52

this function as payable and when we

play05:55

call this function will sense a meter to

play05:57

this function and then send the heater

play06:00

that is sent to this function to the

play06:02

time-lock contract you'll first deposit

play06:05

ether into the time of contract by

play06:07

calling time not deposit and this will

play06:11

set the time that to one week from now

play06:13

so that if you try to withdraw

play06:15

immediately then they will fail so

play06:18

before we can call the withdrawal

play06:20

function will increase the lap time by

play06:23

some huge number which will cause a

play06:25

youant to overflow and then we can call

play06:28

withdrawal so what's the huge number

play06:31

that we need to pass in here to cause a

play06:33

UN overflow

play06:35

well let's do some math we'll say that T

play06:39

is a current of time

play06:41

we need to do is find X such that X plus

play06:45

T is equal to 2 to the 256 and 2 to the

play06:50

256 is equal to 0 since the overflow

play06:53

causes the number to wrap back to 0 we

play06:57

do some simple algebra - in T from both

play07:00

sides of the equation and we get X is

play07:02

equal to minus T so this means that if

play07:06

we pass minus T to this function here

play07:09

then this will cause an overflow and the

play07:12

current valvetime will equal to 0 we can

play07:15

get the current bulk time by calling

play07:17

time log log time and then pass in the

play07:21

address of this contract and you'll put

play07:23

a negative sign up in front and then

play07:28

cast it into a you end by wrapping it in

play07:31

you and now this doesn't look like a big

play07:34

number but it is over here we're using

play07:37

on the flow to create a real big number

play07:40

and what this number represents is 2 to

play07:43

the 256

play07:44

minus T word he is the current long time

play07:47

and this completes the function that's

play07:50

going to be able to deposit and then

play07:53

immediately withdraw by exploiting

play07:56

youant overflow let's see this in action

play07:59

here I have the time of contract and

play08:02

attack contract deploy the attack

play08:05

contract was deployed using the address

play08:08

of the time log which was passed him by

play08:11

copying the address of the time of

play08:13

contract and then pasting it in here and

play08:16

then hitting deploy let's say that

play08:19

account 1 is Eve and she's going to

play08:23

deposit one meter into the time log

play08:27

contract so you'll call the function

play08:29

deposit with one meter and now if you

play08:36

try to withdraw you can see here that

play08:41

the transaction fails with long time not

play08:44

expired so you'll have to wait at least

play08:47

one week before you can withdraw from

play08:50

this contract but using the attack

play08:52

contract that we wrote here

play08:55

we will be able to deposit and then

play08:57

immediately withdraw so you'll send one

play09:01

meter again and then call attack and you

play09:05

can see here that the transaction was

play09:07

successful so we were able to withdraw

play09:10

without waiting one week and this is

play09:13

because we caused the overflow on the

play09:15

lab time and we can check that the log

play09:18

time did indeed overflow by copying the

play09:21

address and then checking the long time

play09:24

of that contract

play09:26

so over here we are passing the address

play09:28

of the attack contract and then hit long

play09:32

time and you can see here that this is

play09:35

equal to zero so that's you and overflow

play09:39

let's now see how we can prevent this

play09:41

exploit the way you prevent agent

play09:44

overflow is by using math libraries like

play09:47

safe math by opens up in the library

play09:51

works by Turing on air when there is an

play09:53

overflow or on the floor we will import

play09:56

the safe math library from github and

play10:00

inside the time lock contract you'll say

play10:02

using safe math for you and and this

play10:06

will add extra functions to the you

play10:08

entered data type so that you'll be able

play10:11

to do is something like my youant dot

play10:13

add one two three inside the function

play10:16

increased long time we'll update this

play10:19

line by saying the new dot time is equal

play10:23

to the current valve time plus the

play10:26

settings to increase and this add

play10:28

function over here will take care of you

play10:31

and overflow if the addition of these

play10:34

number results you know you and overflow

play10:38

then this function will turn on air and

play10:41

call to this function will fail so

play10:44

that's how you use safe math to prevent

play10:47

you and overflow and on the phone let's

play10:50

check that this works by using the

play10:52

attack contract again so i recompile the

play10:56

time lock contract and attack contract

play10:58

and then we deploy them here so you call

play11:02

the attack function so will send one

play11:04

eater and

play11:06

all that and you can see here that the

play11:09

transaction fail with safe math edition

play11:12

overflow so in summary using safe math

play11:16

we were able to prevent attacks from you

play11:19

and overflow and on the flow that's all

play11:22

I got to say for this video I'll put the

play11:24

link to this code here in the

play11:26

descriptions below if you have any

play11:28

questions or comments you can comment

play11:30

below or you can send me a message on

play11:33

this cord have a nice weekend and see

play11:36

you later

Rate This
β˜…
β˜…
β˜…
β˜…
β˜…

5.0 / 5 (0 votes)

Related Tags
Smart ContractsOverflowUnderflowSecurityHackingSoliditySafe MathEthereumBlockchainCybersecurity