ETH Basic to Advance Smart Contract Hacking for web3 in 2023

Dr. Gupta
11 min readFeb 6, 2023

--

Objectives of ETH smart contract hacking article by Dr.Gupta

Basic to know about Smart Contracts :

Smart Contract defines as “a set of promises, specified in digital form, including protocols within which the parties perform on the other promises.”

In terms of Ethereum: “smart contracts” to refer to immutable computer programs that run deterministically in the context of an Ethereum Virtual Machine as part of the Ethereum network protocol — i.e., on the decentralized Ethereum world computer.

  • contracts only run if they are called by a transaction. All smart contracts in Ethereum are executed, ultimately, because of a transaction initiated from an EOA.
  • A transaction to a contract address destination will execute the contract in EVM and will call the function named in the data payload of your transaction, if there is no data in your transaction then EVM will call a fallback function and if that function is payable, will execute it to determine what to do next. if no fallback function or non-payable fallback function, transaction will be reverted.
  • A function selector : The first 4 bytes of the Keccak-256 hash of the function’s prototype. This allows the contract to unambiguously identify which function you wish to invoke.

The function arguments

The function’s arguments, encoded according to the rules for the various elementary types defined in the ABI specification.

  • In DollarFactory smart contract example, we defined a function for withdrawals: function withdraw(uint _amount) public {}
  • The prototype of a function is defined as the string containing the name of function, followed by data types of each of its arguments, enclosed in parentheses as separated by commas. The function name here is withdraw and it takes a single argument what is a uint (which is an alias for uint256), so the prototype of withdraw would be: withdraw(uint)256
  • To calculate the Keccak-256 hash of this string in parity;
web3.utils.sha3("withdraw(uint256)");

Multisignature Transfer:

  • transfer ether to a multisig contract
  • want to send funds to another account
  • all the required users will need to send transactions to contract using a regular wallet app, authorizing contract to perform final transaction.

Ethereum HIgh-Level Languages:

Solidity

soliditylang.org

A procedural (imperative) programming language with a syntax similar to JavaScript, C++, or Java. The most popular and frequently used language for Ethereum smart contracts.

Vyper

A more recently developed language, similar to Serpent and again with Python-like syntax. Intended to get closer to a pure-functional Python-like language than Serpent, but not to replace Serpent.

Bamboo

A newly developed language, influenced by Erlang, with explicit state transitions and without iterative flows (loops). Intended to reduce side effects and increase auditability. Very new and yet to be widely adopted.

Others:

LLL, Serpent

Building Smart Contract with Solidity

Official Solidity Documentation website : CLICK HERE

  • Solidity compiler, solc, which converts programs written in the Solidity language to EVM bytecode. The project also manages the important application binary interface (ABI) standard for Ethereum smart contracts
  • https://docs.soliditylang.org/en/latest/installing-solidity.html
  • To install Solidity solc, we will add using Linux Packages: Solidity have PPAs for Ubuntu, use below commands to install:
sudo add-apt-repository ppa:ethereum/ethereum
sudo apt-get update
sudo apt-get install solc

//you can also install solidity using npm:
npm install -g solc

To check it has installed properly or not, check version;

solc --version

Compiling with the Solidity Compiler (solc)

We use the — bin and — optimize arguments of solc to produce an optimized binary of our example contract developed in my previous article of this series. Learn Ethereum smart contract basics for web3 development 2023 https://medium.com/@web3doctor/learn-ethereum-smart-contract-basics-for-web3-2023-611dcc1caff9

solc --optimize --bin DollarFactory.sol

The Ethereum Contract ABI:

ABI = application binary interface ; defines how data structures and functions are encoded and decoded into OR out of machine code

Purpose of ABI: define functions, describe how function will accept arguments and return result.

It will be helpful when you try to solve, Ethernaut CTFs first part.

To interact with deployed contract, an application needs ; an ABI and address of contract.

solc --abi DollarFactory.sol

Data Types in Solidity Programming:

  • Boolean (bool) : true or false, with logical operators; ! (not), && (and), || (or), == (equal), ≠ (not equal).
  • Integer ( int, uint) : signed (int), unsigned (uint), declared in steps of 8 bits of increments from int8 to uint256, without size suffix, 256-bit are used
  • Fixed point (fixed, ufixed) : fixed / ufixed ; Signed and unsigned fixed point number of various sizes. Keywords ufixedMxN and fixedMxN, where Mrepresents the number of bits taken by the type and Nrepresents how many decimal points are available. Its a fancy way of floating point in solidity. Fixed point numbers are not fully supported by solidiy as per version 0.8.18. They can be declared but cannot be assigned to or from.
  • Address (address payable, address) : address payable is an address you can send Ether to with additional members transfer, balance and send, while you are not supposed to send Ether to a plain address as it might be a smart contract.
  • Fixed-size byte arrays : The value types bytes1, bytes2, bytes3, …, bytes32hold a sequence of bytes from one to up to 32.
  • dynamically-sized byte array : can be bytes or string dynamically assigned
  • Enums : user-defined type, convertible to and from all integer types, require at least one member, cannot have more than 256 member; enum NAME { LABEL1, LABEL2, …}
  • Function Types: internal and external functions, internal functions only inside current contract, external functions consist of address and function signature, can be passed via and returned from external function calls function (<parameter types>) {internal|external} [pure|view|payable] [returns (<return types>)]
  • Data Location: memory, storage, calldata
  • Structs : use to define new types in the form of structs
  • Ether Units : wei, gwei, ether ; finnery and szabo removed in version 0.7.0
  • Time Units : seconds, minutes, hours, days, weeks ; years removed in version 0.5.0, cannot be applied to variables

Control Structures:

  • if, else, while, do, for, break, continue, return
  • Error handling : Assert, Require, Revert, Exceptions

Constructor is executed as a part of contract creation only once then it is discarded.

Selfdestruct : it should not be in a contract code as it can be used to delete contract and withdraw all money

Function Modifiers: special function, use to create conditions that apply to many functions within a contract

contract inheritance: extend base contract with additional functionality, inherits all the methods, functions, and variable of parent, support multiple inheritance by comma separated contract names ; contract child is Parent1, Parent2 {}

Events: completed transaction produce a receipt, contains log enteries, provide information about action occurred during the execution of transaction.

event Withdrawal(address indexed to, uint amount);
event Deposit(address indexed from, uint amount);

emit: incorporate the event data in the transaction logs

function withdraw(uint _amount) public {
msg.sender.transfer(_amount);
emit withdraw(msg.sender, _amount);
}
receive () external payable {
emit Deposit(msg.sender, msg.value);
}

Gas Considerations:

  • avoid dynamically sized arrays
  • avoid calling other contract without knowing gas cost of their functions,
  • avoid using library not well tested and broadly used

Now you have understood the very basics of Solidity Programming, use above learned points to understand below security and hack leading codes.

Security Considerations:

While it is usually quite easy to build software that works as expected, it is much harder to check that nobody can use it in a way that was not anticipated.

all smart contracts are public, and any user can interact with them simply by creating a transaction, Any vulnerability can be exploited, and losses are almost always impossible to recover.

Security Best Practices

  • Minimalism / simplicity : the simpler the code, the lower the chances are of a bug.
  • code reuse : Try not to reinvent the wheel, don’t repeat yourself
  • code quality : once launched, there’s little to fix any problem
  • Readablility / auditability : the easier it is to read, the easier it is to audit.
  • Test Coverage : test everything that you can

Smart Contract Security Risk and Antipatterns: Be familiar with most common security risks

Reentrancy :

Arithmetic Over / Underflows :

Unexpected Ether :

Delegatecall

call delegatecall useful to modularize the code, call is run in context of external contract/function, delegatecall executed at the targeted address is run in context of calling contract and msg.sender and msg.value remain unchanged.

Default Visibilities:

Entropy Illusion :

External contract Referencing :

Short address / parameter attack :

Unchecked CALL Return Values :

Race Conditions / Front Running :

Denial of Service (DOS) :

  • Looping through externally manipulated mappings or arrays : contracts should not loop through data structures that can be artificially manipulated by external users
  • Owner operations : a privileged user was required to change the state of the contract. In such examples a failsafe can be used in the event that the owner becomes incapacitated, make the owner a multisig contract, use a time-lock,
  • Progressing state based on external calls
  • GovernMental 1100 ether after 2.5M gas : https://www.reddit.com/r/ethereum/comments/4ghzhv/governmentals_1100_eth_jackpot_payout_is_stuck/

Block Timestamp Manipulation :

Constructors with care :

Uninitialized storage pointers :

Tx.origin authetication :

  • travel the entire call stack, contain the address of the account that originally sent the call or transaction and use it for authentication.
  • vulnerable to phising attack
  • prevention : shouldn’t use for authorization, can be use to prevent intermediate contracts to call and only limit contract to regular codeless addresses

“Mastering Ethereum by Andreas M. Antonopoulos and Dr. Gavin Wood (O’Reilly). Copyright 2019 The Ethereum Book LLC and Gavin Wood, 978–1–491–97194–9.”

Follow me on Twitter: https://twitter.com/BgxDoc

New to trading? Try crypto trading bots or copy trading on best crypto exchanges

--

--

Dr. Gupta
Dr. Gupta

Written by Dr. Gupta

ll Insomniac Doctor loves Terminal || #Security_Researcher #DayTrader || Learn and Earn || #Web3_Doctor || Rookie Smart Contract Dev & Security Researcher ||

Responses (1)