Cointime

Download App
iOS & Android

Hacking Private Data in Smart contracts | QuillAudits

Validated Project

In solidity, “Private” variables can only be read by the contracts and is not accessible to the outside world. But, it is possible to access these data from outside the blockchain. Let’s see how we can read private data from smart contracts.

Table of Contents:

1. State Variable Visibility2. Storage layout in EVM3. Accessing private data using Ethers4. A small challenge5. Remediation6. Reference

State Variable Visibility

According to Solidity Docs, There are three visibility modifiers that users can use: public, internal, or private.

  1. Public: Public means that the variable can be accessed by the contract and by other smart contracts.
  2. Internal: Internal means that the variable can only be used with the contract it is defined in and its subclasses.
  3. Private: Private means that the variable can only be accessed within the contract it is defined. Trying to access it outside this contract gives a compilation error.

In Solidity, “Private” variables are not accessible to the outside world. But wait, if private data can only be accessed within the contract then how can we access these data from outside of the blockchain?We will come to it but let’s first understand storage layout in solidity.

Storage Layout in EVM:

The EVM (Ethereum Virtual Machine) stores smart contract data in a large array with a length of 2**256 in slots on the blockchain. Each memory slot can hold up to 32 bytes of data. The EVM stores smart contract state variables in the order that they were declared in slots on the blockchain. The default value of each slot is always 0, so we do not need to assign a value to 0 when the new declaration is.

Smart contract storage is optimized to minimize space. If two or more variables fit into a single 32-byte slot, they are packed into the same slot, beginning on the right.

Look at the following example for a better understanding of how storage works in EVM.

Storage for Dynamic data types:

Mappings and dynamically-sized array types cannot be stored “in-between” the state variables before and after. Instead, they are considered to occupy only 32 bytes and a different storage slot that is computed using a Keccak-256 hash of the elements they contain.

Accessing Private data from Blockchain:

To access Solidity smart contract private data we can follow the following steps. Here we will be using ethers.js for extracting data.

  1. First, we need to read the contract and understand the order in which the state variables are declared. Let’s suppose we want to access slot0.
  2. We can use ethers.js to read the memory slots of the contract on the blockchain. Use the below function:await ethers.provider.getStorageAt(contract_address, 0);
  3. It will return hex encoded value, we can simply decode it or use ethers utils functions or some sort of hex decoder to decode it.

Ethers.js Script:

You can also use the following js script to fetch private data from the blockchain.

Guide for running script:

  1. Install ethers from npm: npm install ethers
  2. Get a rpc_url of the required network from alchemy and add it to the above script.
  3. Change the contract address and slot in the below script and simply run the js code. Decode the returned hex value.

A small challenge:

Goerli link: 0x4c77de8a0ec0390826f87f227bb8762ab2189194

Objective: Change the value of pwned to true. You can use the above script to extract private data.

Remediation:

In the current state of the blockchain, do not keep sensitive private data in smart contracts. The safest method to keep your private information safe is to avoid storing it on a public blockchain.

Further Reads:

Comments

All Comments

Recommended for you

  • Farcaster's social client Kiosk completes $10 million financing, led by Electric Capital

    Farcaster's integrated social client Kiosk has announced the completion of a $10 million financing round on the X platform, led by Electric Capital, with participation from a16z Crypto, USV, and Variant Fund. Kiosk aims to promote community building and commerce within applications, enabling creators to establish communities, share rich media content, mint NFTs, interact with like-minded individuals, and seamlessly customize channel economics, while emphasizing the integration of on-chain assets into social interactions and envisioning a more inclusive and interconnected Web3 experience.

  • A whale sold 224 WBTC worth $14.4 million in the past three hours

    According to on-chain analyst @ai_9684xtpa, address 0x486...1505e sold 224 WBTC tokens worth $14.4 million through Cowswap in the past three hours, making a profit of $830,000 (selling at an average price of $64,203). The seller had bought 371 WBTC tokens at an average price of $60,504 between November 2023 and April 2024, and still holds 280 WBTC tokens.

  • CryptoQuant CEO: BTC needs to remain above $80,000 for miners to remain profitable after halving

    Bitcoin mining revenue significantly decreased in May due to the impact of the fourth Bitcoin halving event. On May 1st, the total revenue from block rewards and transaction fees reached a new low of only $26.3 million.CryptoQuant CEO Ki Young Ju calculated that, based on current conditions, Bitcoin needs to stay above $80,000 for miners to remain profitable after the halving. However, most miners have taken proactive measures to upgrade their mining equipment to lower long-term operating costs and remain competitive.

  • BTC returns to above 65,000 USDT, up 2.08% in 24 hours

    OKX market shows that BTC has returned to above 65000 USDT, now reporting 65102 USDT, with a 24-hour increase of 2.08%.

  • Hundre Finance attackers have withdrawn 162.2 ETH worth of crypto assets from Curve

    According to PeckShield monitoring, the attacker of Hundre Finance withdrew 784,000 3Crv from Curve and exchanged it for 273 ETH. In addition, they also exchanged 305.6 WOO, 39 PAXG, 200,000 FRAX, and 100,000 DAI, totaling 162.2 ETH. The attacker then bridged 1,034 ETH (2.17 million USD), 842.8K DAI, 1.11 million USDT, 1.27 million USDC, and 457.3 FRAX from Optimism to Ethereum. They also exchanged a total of 480,000 USDC for 142.6 WETH, 306 WOO, and 39 PAXG. They also exchanged 1.11 million USDT for 500.3 thousand USD worth of DAI and 613.8 thousand USD worth of FRAX. Additionally, on April 15, 2023, approximately 786,000 USD worth of USDC was added to Curve3Pool.

  • LayerZero co-founder: "Self-reporting of witch activities" is not aimed at individuals, but at industrial witch studios

    Bryan Pellegrino, co-founder and CEO of LayerZero, stated on social media that the "Self-Report Sybil Activity" is not targeting individual users, but rather large industrial witch farms (studios).Earlier, LayerZero Labs launched the "Self-Report Sybil Activity" plan, which allows witch addresses to self-report related addresses on a designated page and receive an expected allocation of 15%, without answering any questions. The deadline is May 17th, 19:59:59.

  • Argentina’s House of Representatives Passes Bill to Regularize Cryptocurrency Taxation

    The Argentine Chamber of Deputies has passed a cryptocurrency tax normalization bill aimed at advancing a series of important government reforms. The bill introduces the possibility of regularizing previously undeclared cryptocurrency assets, up to a maximum of $100,000, without paying government collection fees. However, if the value of cryptocurrency assets exceeds this limit, the government will apply preferential tax rates based on the taxpayer's declaration date.

  • GNUS on Fantom was attacked, with a loss of about $1.27 million

    According to Beosin's monitoring, GNUS on Fantom was attacked, resulting in a loss of approximately $1.27 million. GNUS stated on the X platform that due to recent vulnerabilities, hackers were able to mint fake GNUS tokens on Fantom, transfer them to Ethereum and Polygon through the Axelar Bridge, and sell them to existing liquidity pools. We will take a snapshot of the blocks before the exploit. To ensure fairness, please do not purchase GNUS tokens after the exploit, as we will issue new tokens.

  • Pandu Financial Group received the first round of strategic equity investment of tens of millions of Hong Kong dollars, led by Longling Capital

    Pando Financial Group announced it has received tens of millions of Hong Kong dollars in strategic equity investment led by Longling Investment. Pando Financial Group stated that it plans to use the newly injected funds for key growth areas, including market expansion, innovative product development, key talent recruitment, and technology upgrades, aiming to accelerate the layout of opportunities in the era of virtual assets through these strategic initiatives. Currently, the group's asset management scale has reached $500 million. Pando Asset, a subsidiary of Pando Financial Group, established its headquarters in Zurich in 2022 and issued the Pando 6 spot virtual asset fund (Bitcoin/Ethereum spot ETPs) on the Swiss Exchange. Another subsidiary of Pando Financial Group, Pando Limited, obtained licenses from the Securities and Futures Commission in Hong Kong, including Type 1 (securities trading), Type 4 (advising on securities), and Type 9 (asset management), as well as public fund qualifications, and was approved to manage investment portfolios with more than 10% invested in virtual assets and issued several excellent performance actively managed ETF products.

  • Hong Kong Monetary Authority launches industry consultation on “renaming virtual banks as licensed digital banks”

    Hong Kong virtual banks released their annual reports for 2023 last week. The eight virtual banks collectively lost about 2.99 billion yuan last year, a decrease of about 12% compared to the total loss of about 3.4 billion yuan in 2022. In response to the occasional feeling of "unreality" brought about by the term "virtual" in recent years, the Hong Kong Monetary Authority has initiated a consultation on renaming with the eight virtual banks, the Hong Kong Bankers Association, the Hong Kong Restricted Licensed Banks and Deposit-taking Companies Association, with the aim of renaming virtual banks as licensed digital banks, for a period of one month. It is reported that in the Asian region, similar banks have different names in different places. South Korea and Singapore issue licenses under the name of "digital bank", with Singapore further dividing them into digital full banks (DFB) and digital wholesale banks (DWB).