<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Logesh N on Medium]]></title>
        <description><![CDATA[Stories by Logesh N on Medium]]></description>
        <link>https://medium.com/@logesh21n?source=rss-d25cd9352fc3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*aSYWl3-Wjb1WuFHe</url>
            <title>Stories by Logesh N on Medium</title>
            <link>https://medium.com/@logesh21n?source=rss-d25cd9352fc3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 13:49:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@logesh21n/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[COMMON VULNERABILITIES: DEFAULT VISIBILITY]]></title>
            <link>https://coinsbench.com/common-vulnerabilities-default-visibility-93252988991d?source=rss-d25cd9352fc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/93252988991d</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[smart-contract-security]]></category>
            <category><![CDATA[smart-contract-auditing]]></category>
            <dc:creator><![CDATA[Logesh N]]></dc:creator>
            <pubDate>Fri, 29 Mar 2024 14:34:31 GMT</pubDate>
            <atom:updated>2024-04-08T09:28:47.178Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gk-LxbTi0qwkj0AOoAOFeg.jpeg" /></figure><p>In Solidity, if you declare a state variable or function without explicitly specifying its visibility (i.e., public, internal, private, or external), it defaults to internal visibility. This default visibility can sometimes lead to unexpected behavior or vulnerabilities in smart contracts, which are referred to as “<strong><em>Default Visibility Bugs</em></strong>”.</p><p>1. <strong>Default Visibility</strong>:</p><ul><li>In Solidity, if you do not specify the visibility of a state variable or function, it defaults to internal visibility.</li><li>Internal visibility means that the state variable or function is accessible within the contract and derived contracts but not from external contracts or accounts.</li></ul><p>2. <strong>Consequences of Default Visibility Bugs</strong>:</p><p>Default visibility bugs can lead to various security vulnerabilities, including:</p><ul><li><strong>Unauthorized access</strong>: External contracts or accounts may access or manipulate sensitive state variables or functions that should only be accessed internally.</li><li><strong>Data exposure</strong>: Sensitive data stored in the contract may be exposed to unauthorized parties, leading to privacy violations or data leaks.</li><li><strong>Contract integrity</strong>: Unexpected external access to critical functions or state variables can compromise the integrity and security of the contract.</li></ul><p>4. <strong>Mitigation Strategies</strong>:</p><ul><li><strong>Explicitly specify visibility</strong>: Always explicitly specify the visibility of state variables and functions to ensure clarity and prevent default visibility bugs.</li><li><strong>Use </strong>private<strong> or </strong>internal<strong> where applicable</strong>: Mark state variables and functions as private or internal when they should only be accessed within the contract or its derived contracts.</li><li><strong>Minimize external access</strong>: Limit external access to critical functions or state variables by marking them as private or internal whenever possible.</li></ul><h3><strong>Examples</strong></h3><p>If the intention was to make the variable or function publicly accessible but not specified the visibility can lead to internal visibility. Let’s look at an example to illustrate the default visibility bug:</p><p>1. <strong>Default Visibility Bug Example</strong>:</p><pre>pragma solidity ^0.8.0;<br><br>contract DefaultVisibilityBug {<br>    uint public defaultVariable = 42; // This variable is publicly accessible<br>    uint internalVariable = 100; // This variable is only accessible within the contract but not specified private visibility<br><br>    function getValue() view returns(uint) {<br>        return internalVariable; // This function is publicly accessible due to default `internal` visibility<br>    }<br><br>    function setValue(uint _value) {<br>        internalVariable = _value; // This function is publicly accessible due to default `internal` visibility<br>    }<br>}</pre><p><strong>Explanation</strong>:</p><ul><li>In this contract, the defaultVariable is intended to be publicly accessible, so it’s explicitly declared as public. This means that anyone can read its value.</li><li>The internalVariable, however, is intended to be private and only accessible within the contract. However, due to a default visibility bug, it’s also accessible from outside the contract because no visibility modifier is specified.</li><li>Similarly, both the getValue() and setValue() functions are intended to be public methods. However, since no visibility modifier is specified, they default to internal visibility, making them accessible from outside the contract.</li></ul><p>2. <strong>Default Visibility Bug Example</strong>:</p><pre>pragma solidity ^0.8.0;<br><br>contract DefaultVisibilityBug {<br>    uint public value; // This state variable is intended to be publicly accessible<br><br>    function setValue(uint newValue) { // This function is intended to be externally accessible<br>        value = newValue;<br>    }<br><br>    function getValue() returns (uint) { // This function is intended to be externally accessible<br>        return value;<br>    }<br>}</pre><p><strong>Explanation:</strong></p><ul><li>In this example, the value state variable and both functions setValue and getValue are declared without an explicit visibility specifier.</li><li>By default, these elements have internal visibility, meaning they can only be accessed within the contract.</li><li>However, the intent is for value and both functions to be externally accessible, allowing other contracts or external accounts to interact with them.</li><li>Omitting the visibility specifier results in a default visibility bug, as these elements are not accessible externally.</li></ul><p>These examples highlight the importance of explicitly specifying visibility modifiers in Solidity contracts to ensure the intended accessibility of state variables and functions. By providing the correct visibility specifier (public, internal, private, or external), we can prevent default visibility bugs and ensure the correct behavior of their contracts.</p><blockquote><strong>Note</strong>: The default visibility bug in Solidity occurs when developers omit the visibility specifier when declaring state variables or functions in a contract. In Solidity, state variables and functions without an explicit visibility specifier default to internal visibility, which means they are accessible within the current contract and derived contracts, but not externally. However, if developers intend for these state variables or functions to be externally accessible, omitting the visibility specifier results in a bug.</blockquote><h3><strong>Mitigation Steps</strong></h3><p>To mitigate the default visibility bug in the provided contract, we need to ensure that the visibility of state variables and functions is explicitly specified according to the intended accessibility. Here are the mitigation steps:</p><p>1. <strong>Mitigation Default Visibility Bug</strong>:</p><pre>pragma solidity ^0.8.0;<br><br>contract FixedVisibilityBug {<br>    uint public defaultVariable = 42; // Explicitly specify &#39;public&#39; visibility<br><br>    uint private internalVariable = 100; // Explicitly specify &#39;private&#39; visibility<br><br>    function getValue() public view returns (uint) { // Explicitly specify &#39;public&#39; visibility<br>        return internalVariable;<br>    }<br><br>    function setValue(uint _value) public { // Explicitly specify &#39;public&#39; visibility<br>        internalVariable = _value;<br>    }<br>}</pre><p><strong>Explanation:</strong></p><ul><li>The defaultVariable state variable is intended to be publicly accessible, so we explicitly specify public visibility.</li><li>The internalVariable state variable is intended to be only accessible within the contract, so we explicitly specify private visibility.</li><li>Both the getValue and setValue functions are intended to be publicly accessible, so we explicitly specify public visibility for them.</li><li>By providing the correct visibility specifiers, we eliminate the default visibility bug and ensure the intended accessibility of state variables and functions.</li></ul><p>2. <strong>Mitigation Default Visibility Bug</strong>:</p><pre>pragma solidity ^0.8.0;<br><br>contract DefaultVisibilityBug {<br>    uint public value; // Explicitly specify public visibility for external access<br><br>    function setValue(uint newValue) public { // Explicitly specify public visibility<br>        value = newValue;<br>    }<br><br>    function getValue() public view returns (uint) { // Explicitly specify public visibility<br>        return value;<br>    }<br>}</pre><p><strong>Explanation</strong>:</p><ul><li>Specify public visibility for state variables and functions intended to be externally accessible.</li><li>By explicitly specifying the public modifier, developers ensure that these elements can be accessed externally by other contracts or external accounts.</li></ul><blockquote>Note: State variables can declared as public or private or internal visibilities but not as external. But in functions we can also declare as external.</blockquote><p><strong>For more</strong>: <a href="https://github.com/logesh21n/Solidity-Common-Vulnerabilities">https://github.com/logesh21n/Solidity-Common-Vulnerabilities</a></p><p>If you have any doubts in Solidity smart contract and smart contract bugs or if you’re stuck somewhere, feel free to DM me. You can also follow me and ask your doubts on:</p><p>Twitter: <a href="https://twitter.com/NLogesh21">https://twitter.com/NLogesh21</a><br>GitHub: <a href="https://github.com/logesh21n">https://github.com/logesh21n</a><br>Discord: logesh_n</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93252988991d" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/common-vulnerabilities-default-visibility-93252988991d">COMMON VULNERABILITIES: DEFAULT VISIBILITY</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[COMMON VULNERABILITIES: FRONT RUNNING PART — I]]></title>
            <link>https://medium.com/coinmonks/common-vulnerabilities-front-running-part-i-9272d60b11b5?source=rss-d25cd9352fc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/9272d60b11b5</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[front-running]]></category>
            <category><![CDATA[smart-contract-security]]></category>
            <category><![CDATA[smart-contract-auditing]]></category>
            <dc:creator><![CDATA[Logesh N]]></dc:creator>
            <pubDate>Thu, 28 Mar 2024 17:34:32 GMT</pubDate>
            <atom:updated>2024-03-28T17:34:32.305Z</atom:updated>
            <content:encoded><![CDATA[<h3>COMMON VULNERABILITIES: FRONT RUNNING PART — I</h3><h3>What is Front Running?</h3><p>Transactions take some time before they are mined. An attacker can watch the transaction pool and send a transaction, have it included in a block before the original transaction. Front-running occurs when an attacker exploits the time delay between the submission of a transaction and its inclusion in a block to manipulate the order of transactions and gain an advantage, such as front-running trades.</p><h3><strong>Front Running in Solidity</strong></h3><p>Front-running in the context of Solidity refers to a type of transaction ordering manipulation where an attacker exploits their position to execute trades or transactions in a blockchain network before legitimate transactions are processed. This allows the attacker to gain an unfair advantage by front-running the intended transaction, typically to profit at the expense of others. Front-running bugs in Solidity smart contracts occur when vulnerabilities in the contract logic allow attackers to exploit the order of transaction execution for malicious purposes.</p><h3><strong>Transaction Ordering Vulnerabilities</strong></h3><ul><li>Blockchain networks process transactions in the order they are received, typically based on factors such as gas price or nonce value.</li><li>Attackers exploit vulnerabilities in transaction ordering to manipulate the sequence in which transactions are executed, allowing them to front-run specific transactions.</li></ul><h3><strong>What is Transaction Ordering Vulnerabilities?</strong></h3><p>Transaction ordering vulnerabilities in Solidity refer to weaknesses in the ordering or sequencing of transactions within a blockchain network, particularly in Ethereum and similar smart contract platforms. These vulnerabilities can be exploited by attackers to manipulate the order in which transactions are executed, potentially leading to undesirable outcomes or financial losses.</p><p>1. <strong>Blockchain Transaction Order</strong>:</p><ul><li>Blockchain networks, including Ethereum, process transactions in a sequential order, typically based on factors such as gas price, nonce value, or time of submission.</li><li>Miners or validators include transactions in blocks and order them according to predefined criteria, ensuring consistency and integrity in the transaction execution process.</li></ul><p>2. <strong>Transaction Ordering Manipulation</strong>:</p><ul><li>Transaction ordering vulnerabilities arise when attackers exploit weaknesses in the blockchain’s transaction ordering mechanism to manipulate the sequence in which transactions are executed.</li><li>Attackers may attempt to reorder transactions to gain an unfair advantage, disrupt contract functionality, or exploit vulnerabilities in smart contracts.</li></ul><p>3. <strong>Types of Transaction Ordering Vulnerabilities</strong>:</p><ul><li><strong>Front-running</strong>: Attackers exploit their position to execute transactions before legitimate transactions are processed, typically to profit at the expense of others.</li><li><strong>Back-running:</strong> Attackers exploit delays in transaction execution to submit transactions that take advantage of updated market conditions or pricing information.</li><li><strong>Timestamp manipulation</strong>: Attackers manipulate the timestamp of transactions to alter their position in the transaction queue, potentially influencing the order in which transactions are executed.</li></ul><p>4. <strong>Impact of Transaction Ordering Vulnerabilities</strong>:</p><ul><li><strong>Financial losses</strong>: Attackers may exploit transaction ordering vulnerabilities to manipulate prices, front-run trades, or disrupt contract executions, resulting in financial losses for affected parties.</li><li><strong>Market manipulation</strong>: Transaction ordering vulnerabilities can be used to manipulate market prices, liquidity, or trading volumes, undermining the integrity and efficiency of Decentralized Finance (DeFi) platforms.</li><li><strong>Contract exploitation</strong>: Vulnerabilities in smart contract logic or ordering mechanisms can be exploited to manipulate contract state, drain funds, or disrupt contract operations, leading to security breaches or disruptions in blockchain applications.</li></ul><p>5. <strong>Mitigation Strategies</strong>:</p><ul><li>Use <strong><em>commit-reveal schemes</em></strong> or <strong><em>batching transactions</em></strong> to reduce transaction predictability and minimize the impact of front-running attacks.</li><li>Implement <strong><em>decentralized oracle services</em></strong> or <strong><em>secure off-chain computations</em></strong> to handle sensitive information or price data securely.</li></ul><blockquote><strong>Note</strong>: Transaction ordering vulnerabilities in Solidity contracts stem from weaknesses in the blockchain’s transaction processing mechanism, allowing attackers to manipulate the order of transaction execution for malicious purposes.</blockquote><h3><strong>Arbitrage Opportunities</strong></h3><ul><li>Front-running is often associated with arbitrage opportunities, where attackers profit by exploiting price discrepancies or inefficiencies in Decentralized Exchanges (DEXs) or other financial applications.</li><li>By front-running a transaction, attackers can execute trades at a more favorable price before the original transaction is processed, enabling them to profit from the price difference.</li></ul><h3><strong>What is Arbitrage?</strong></h3><p>Arbitrage in the context of Solidity and blockchain refers to the practice of exploiting price differences or inefficiencies across <em>different markets</em> or <em>decentralized exchanges</em> (DEXs) to profit from trading opportunities. Arbitrageurs buy assets from one market where the price is lower and sell them in another market where the price is higher, thus capitalizing on the price discrepancy.</p><p><strong>Example to understand Arbitrage:</strong></p><p>You decide to trade 10 ether, a type of digital currency, on two different decentralized exchanges, let’s call them DEX-A and DEX-B. First, you go to DEX-A and use $1000 to buy 10 ether. This transaction happens securely and directly between you and the exchange, without any banks or middlemen involved. Now, you have 10 ether in your digital wallet.</p><p>Next, you head over to DEX-B to sell your 10 ether. Here’s where it gets interesting: you find that the price of ether has gone up since you bought it on DEX-A! You manage to sell your 10 ether for $1100. That means you’ve made a profit of $100!. This profit is known as <strong>Arbitrage</strong>.</p><h3><strong>But how does this happen?</strong></h3><ol><li><strong>Price Discrepancies</strong>:</li></ol><ul><li>Price discrepancies can occur between different trading pairs, exchanges, or liquidity pools within decentralized finance (DeFi) ecosystems.</li><li>These discrepancies may arise due to variations in supply and demand, trading volumes, liquidity constraints, or inefficiencies in market mechanisms.</li></ul><p>2. <strong>Arbitrage Opportunities</strong>:</p><ul><li>Arbitrageurs identify and exploit these price differences to execute trades profitably, leveraging the principle of buy low, sell high.</li><li>In decentralized finance (DeFi) platforms built on blockchain networks like Ethereum, arbitrage opportunities often arise due to the fragmentation of liquidity across different DEXs or liquidity pools.</li></ul><p>3. <strong>Types of Arbitrage</strong>:</p><ul><li><strong>Spot Arbitrage:</strong> Involves buying and selling assets simultaneously on different markets to exploit price differences in real-time.</li><li><strong>Triangular Arbitrage</strong>: Involves trading between three different assets or currencies to profit from imbalances in their exchange rates.</li><li><strong>Flash Arbitrage</strong>: Involves exploiting temporary price discrepancies or inefficiencies that arise due to delayed transaction execution or network congestion.</li></ul><p>4. <strong>Arbitrage Strategies</strong>:</p><ul><li><strong>Simple Arbitrage</strong>: Involves manual execution of trades based on observed price differentials between markets or exchanges.</li><li><strong>Automated Arbitrage</strong>: Involves using bots, algorithms, or smart contracts to execute trades automatically in response to predefined trading signals or market conditions.</li><li><strong>Statistical Arbitrage</strong>: Involves analyzing historical price data, market trends, or trading patterns to identify and exploit arbitrage opportunities.</li></ul><p>5. <strong>Arbitrage in Solidity Contracts</strong>:</p><ul><li>Smart contracts deployed on blockchain networks can facilitate arbitrage trading by automating the execution of trades, managing assets, and interacting with decentralized exchanges or liquidity pools.</li><li>Arbitrage strategies implemented in Solidity contracts may involve token swaps, liquidity provision, flash loans, or other financial instruments to capitalize on price differentials and generate profits for arbitrageurs.</li></ul><blockquote><strong>Note</strong>: Front-running bugs in Solidity contracts stem from vulnerabilities that allow attackers to manipulate transaction ordering for malicious purposes, typically for financial gain. Developers must implement robust security measures and mitigation strategies to protect against front-running attacks and safeguard the integrity of decentralized applications and smart contracts.</blockquote><p><strong>For more</strong>: <a href="https://github.com/logesh21n/Solidity-Common-Vulnerabilities">https://github.com/logesh21n/Solidity-Common-Vulnerabilities</a></p><p>If you have any doubts in Solidity smart contract and smart contract bugs or if you’re stuck somewhere, feel free to DM me. You can also follow me and ask your doubts on:</p><p>Twitter: <a href="https://twitter.com/NLogesh21">https://twitter.com/NLogesh21</a><br>GitHub: <a href="https://github.com/logesh21n">https://github.com/logesh21n</a><br>Discord: logesh_n</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9272d60b11b5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/common-vulnerabilities-front-running-part-i-9272d60b11b5">COMMON VULNERABILITIES: FRONT RUNNING PART — I</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unveiling the $16 Million Exploit: Inside the CurioDAO Breach]]></title>
            <link>https://medium.com/coinmonks/unveiling-the-16-million-exploit-inside-the-curiodao-breach-cfb55d49f302?source=rss-d25cd9352fc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfb55d49f302</guid>
            <category><![CDATA[dao-hack]]></category>
            <category><![CDATA[smart-contract-auditing]]></category>
            <category><![CDATA[smart-contract-security]]></category>
            <category><![CDATA[dao]]></category>
            <dc:creator><![CDATA[Logesh N]]></dc:creator>
            <pubDate>Wed, 27 Mar 2024 16:17:40 GMT</pubDate>
            <atom:updated>2024-03-28T17:34:36.808Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DZeSVO5rjzcmPajqTP9m_A.jpeg" /><figcaption><strong>CURIO EXPLOIT — Is Governance Manipulation?</strong></figcaption></figure><p>On Tuesday, March 26, 2024, the Curio’s DAO smart contract was exploited for $16 million. A critical vulnerability involving voting power privileges.</p><h3><strong>Governance Manipulation</strong></h3><p>Governance manipulation refers to the act of changing or influencing the rules, decisions, or organization to benefit certain individuals or groups at the expense of others. In the context of Decentralized Finance (DeFi), governance manipulation often involves exploiting vulnerabilities in smart contracts or decentralized autonomous organizations (DAOs) to gain control over decision-making processes.</p><p>Imagine a community where everyone has a say in how things are run. This community might have rules in place for voting on important matters, like how to allocate funds or which upgrades to implement. Now, imagine someone finding a way to unfairly tip the scales in their favor. They might acquire extra voting power, bypass rules, or manipulate the voting process to get what they want <strong>$M$O$N$E$Y</strong>.</p><p>In Smart contracts, governance manipulation can have serious consequences, such as funds being misallocated, upgrades being pushed through without proper scrutiny, or even the entire system being compromised. It’s like someone cheating in a game where the rules are supposed to be fair for everyone.</p><p>Let’s look the vulnerable code in Curio:</p><pre>function cook(address _cgt, uint amount, uint wethMin, uint daiMin) external onlyPans { <br>    // Move CGT tokens to this contract<br>    cgt.transferFrom(msg.sender, address(this), amount); <br>    // Approve tokens for use<br>    cgt.approve(address(chief), amount);<br>    // Lock tokens to increase voting power<br>    chief.lock(amount);<br><br>    ...<br><br>    // Cast a vote in favor of something<br>    chief.vote(yays);<br>    // Lift the lock on tokens<br>    chief.lift(address(this));<br><br>    ...<br><br>    // Generate a signature for a function call<br>    bytes memory sig = abi.encodeWithSignature(&quot;act(address, address)&quot;, address(this), address(cgt));<br>    // Trigger an action on a pause contract<br>    pause.plot(address(spell), tag, sig, delay);<br>    pause.exec(address(spell), tag, sig, delay);<br><br>    ...<br>}</pre><h3><strong>About the vulnerable code of CurioDAO?</strong></h3><p>1. <strong>Transfer CGT Tokens</strong>: The function cook takes four parameters: _cgt (address of the CGT token contract), amount (number of tokens to transfer), wethMin, and daiMin. The function starts by transferring amount of CGT tokens from the msg.sender (presumably the attacker) to the contract executing the cook function.</p><p>2. <strong>Approve Tokens</strong>: After transferring the tokens, the contract approves amount of CGT tokens to be spent by the chief contract. This suggests that the chief contract is involved in the governance system and requires approval to interact with CGT tokens.</p><p>3. <strong>Lock Tokens and Vote</strong>: The chief.lock(amount) function call locks the transferred tokens, likely to increase the attacker’s voting power within the governance system. The chief.vote(yays) function call then casts a vote in favor of some proposal (yays), further leveraging the attacker’s influence over governance decisions.</p><p>4. <strong>Lift Lock</strong>: The chief.lift(address(this)) function call appears to lift the lock on the tokens, potentially freeing them up for further manipulation or transfer.</p><p>5. <strong>Generate Signature</strong>: The abi.encodeWithSignature function is used to generate a signature for the act function, which takes two addresses as arguments. The purpose of this signature generation is not entirely clear from the provided code snippet, but it likely prepares data for a subsequent function call.</p><p>6. <strong>Plot and Execute on Pause Contract</strong>: Finally, the pause.plot and pause.exec function calls interact with a pause contract, passing it the address of another contract (spell), a tag, a signature (sig), and a delay. This interaction likely triggers some action within the pause contract, potentially executing the malicious actions orchestrated by the attacker.</p><h3><strong>How does the attacker intiated attack?</strong></h3><p>This is my perspective from the attacker’s point of view::</p><ul><li>The attacker calls the cook function of the vulnerable contract, passing it parameters including the address of the CGT token contract and the amount of tokens to transfer.</li><li>The attacker transfers CGT tokens to the vulnerable contract, thereby gaining control over them within the contract’s scope.</li><li>The attacker leverages the transferred tokens to increase their voting power within the governance system by locking tokens and casting votes.</li><li>The attacker generates a signature and interacts with a pause contract, likely triggering further actions that enable unauthorized transactions, such as minting tokens or manipulating governance parameters.</li><li>These unauthorized actions, combined with sophistciated financial strategies like token swaps and cross-chain transfers, enable the attacker to exploit vulnerabilities in the system and carry out the attack.</li></ul><p>The attack exploits vulnerabilities in the contract’s functionality, combined with manipulation of governance parameters and interaction with other contracts, to execute unauthorized actions and potentially cause significant financial losses.</p><p><strong>For more</strong>: <a href="https://github.com/logesh21n/Solidity-Common-Vulnerabilities">https://github.com/logesh21n/Solidity-Common-Vulnerabilities</a></p><p>If you have any doubts in Solidity smart contract and smart contract bugs or if you’re stuck somewhere, feel free to DM me. You can also follow me and ask your doubts on:</p><p>Twitter: <a href="https://twitter.com/NLogesh21">https://twitter.com/NLogesh21</a><br>GitHub: <a href="https://github.com/logesh21n">https://github.com/logesh21n</a><br>Discord: logesh_n</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfb55d49f302" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/unveiling-the-16-million-exploit-inside-the-curiodao-breach-cfb55d49f302">Unveiling the $16 Million Exploit: Inside the CurioDAO Breach</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[COMMON VULNERABILITIES: Uninitialized Storage Variables]]></title>
            <link>https://coinsbench.com/common-vulnerabilities-uninitialized-storage-variables-8ee1cc2bd8d3?source=rss-d25cd9352fc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ee1cc2bd8d3</guid>
            <category><![CDATA[smart-contract-security]]></category>
            <category><![CDATA[smart-contract-blockchain]]></category>
            <category><![CDATA[smart-contract-auditing]]></category>
            <dc:creator><![CDATA[Logesh N]]></dc:creator>
            <pubDate>Mon, 25 Mar 2024 16:24:27 GMT</pubDate>
            <atom:updated>2024-04-08T09:29:09.023Z</atom:updated>
            <content:encoded><![CDATA[<p>Uninitialized storage variables (<em>state variables</em>) bugs in Solidity occur when storage variables are accessed or used without being properly initialized. This can lead to unexpected behavior, vulnerabilities, or even contract exploits. Here’s a more detailed explanation:</p><p>1. <strong>Storage Variables in Solidity</strong>:</p><ul><li>Solidity contracts can define state variables, which are stored permanently on the blockchain.</li><li>These state variables reside in storage and retain their values between function calls.</li></ul><p>2. <strong>Initialization of Storage Variables</strong>:</p><ul><li>In Solidity, storage variables are not automatically initialized to default values. They must be explicitly initialized before being accessed or used in contracts.</li><li>Failure to initialize storage variables can result in their values being undefined or inconsistent, leading to unexpected behavior or vulnerabilities.</li><li>This can happen due to oversight in contract logic, incomplete initialization sequences, or incorrect assumptions about the default values of storage variables.</li></ul><p>3. <strong>Potential Risks and Consequences</strong>:</p><ul><li>Uninitialized storage variables bugs can have various consequences, depending on how they are exploited or manipulated.</li><li>They may lead to contract state inconsistencies, incorrect data processing, unauthorized access to sensitive information, or even contract vulnerabilities that can be exploited by attackers.</li></ul><p>4. <strong>Examples of Uninitialized Storage Variables Bugs</strong>:</p><ul><li>Accessing uninitialized storage variables directly or indirectly in contract functions.</li><li>Using storage variables as part of calculations, comparisons, or state transitions without ensuring proper initialization.</li><li>Storing or retrieving data from uninitialized storage slots, which can result in unpredictable behavior or contract failures.</li></ul><p>5. <strong>Mitigation Strategies</strong>:</p><ul><li>Initialize storage variables explicitly before accessing or using them in contracts. Ensure that all storage variables are properly initialized during contract construction time or initialization phases.</li><li>Implement validation checks and error handling mechanisms to detect and handle cases where storage variables may be uninitialized or in an inconsistent state.</li></ul><h3><strong>Examples</strong></h3><p>Here are a few examples demonstrating uninitialized storage variables bugs in Solidity contracts:</p><p>1. <strong>Accessing Uninitialized Storage Variable</strong>:</p><pre>pragma solidity ^0.8.0;<br><br>contract UninitializedStorageBug {<br>    uint public uninitializedValue; // uninitialized storage variable<br>    <br>    constructor() {}<br><br>    function setValue(uint _newValue) public {<br>        uninitializedValue = _newValue;<br>    }<br>    <br>    function getValue() public view returns (uint) {<br>        return uninitializedValue; // Accessing uninitialized storage variable without initializing<br>    }<br>}</pre><p><strong>Explanation:</strong></p><ul><li>In this contract, uninitializedValue is a storage variable that is not explicitly initialized.</li><li>The getValue function attempts to read the value of uninitializedValue without ensuring that it has been initialized.</li><li>Accessing uninitializedValue in the getValue function may result in reading an undefined or inconsistent value, leading to unexpected behavior or vulnerabilities.</li></ul><p>2. <strong>Using Uninitialized Storage Variable in Calculation</strong>:</p><pre>pragma solidity ^0.8.0;<br><br>contract UninitializedStorageBug {<br>    uint public uninitializedValue; // uninitialized storage variable<br><br>    constructor() {}<br><br>    function setValue(uint _newValue) public {<br>        uninitializedValue = _newValue;<br>    }<br>    <br>    function doubleValue() public view returns (uint) {<br>        return uninitializedValue * 2; // Using uninitialized storage variable in calculation<br>    }<br>}</pre><p><strong>Explanation:</strong></p><ul><li>Similar to the previous example, uninitializedValue is not initialized explicitly.</li><li>The doubleValue function attempts to double the value of uninitializedValue without ensuring that it has been initialized.</li><li>Performing calculations with an uninitialized storage variable may result in undefined behavior or unexpected results, potentially leading to vulnerabilities or contract failures.</li></ul><p>3. <strong>Storing Data in Uninitialized Storage Slot</strong>:</p><pre>pragma solidity ^0.8.0;<br><br>contract UninitializedStorageBug {<br>    uint public uninitializedValue; // uninitialized storage variable<br>    uint[] public uninitializedArray; // uninitialized storage array<br><br>    constructor() {}<br><br>    function setValue(uint _newValue) public {<br>        uninitializedValue = _newValue;<br>    }<br>    <br>    function pushToArray(uint _newValue) public {<br>        uninitializedArray.push(_newValue); // Storing data in uninitialized storage slot<br>    }<br>}</pre><p><strong>Explanation</strong>:</p><ul><li>In this contract, uninitializedArray is a storage array that is not initialized explicitly.</li><li>The pushToArray function attempts to push a new value into uninitializedArray without ensuring that it has been initialized.</li><li>Storing data in an uninitialized storage slot may result in unexpected behavior, data corruption, or contract vulnerabilities.</li></ul><p>4. <strong>Complex data type is declared as a local variable</strong>:</p><p>The uninitialized storage variable bug in Solidity can occur also when a complex data type such as a struct is declared as a local variable in a function but not properly initialized. This can lead to the variable pointing to other storage slots unexpectedly, potentially causing unintended changes to the contract’s state.</p><p>Here’s an example code to demonstrate the issue:</p><ul><li>Solidity stores state variables sequentially in storage slots, which are <strong>32 bytes</strong> each.</li><li>When a complex data type, like a struct, is declared as a local variable in a function, it is not automatically initialized and becomes a pointer to storage.</li><li>If the pointer is uninitialized, it may point to another storage slot, potentially causing unintended changes to the contract’s state.</li></ul><p>Here’s an example code that demonstrates the bug:</p><pre>pragma solidity ^0.8.0;<br><br>contract UninitializedStorage {<br>    struct Record {<br>        bool unlocked;<br>    }<br><br>    Record[] records;<br><br>    function addRecord(bool unlocked) public {<br>        Record memory newRecord;<br>        newRecord.unlocked = unlocked;<br><br>        // Uninitialized storage pointer bug:<br>        // newRecord is a pointer to storage, but it&#39;s not properly initialized,<br>        // which may cause the unlocked variable to be stored in slot 0.<br>        records.push(newRecord);<br>    }<br><br>    function checkRecord(uint256 index) public view returns (bool) {<br>        return records[index].unlocked;<br>    }<br>}</pre><p><strong>Explanation</strong>:</p><ul><li>In the addRecord() function, a new Record struct is created in memory but not properly initialized before being pushed to the records array.</li><li>As a result, the unlocked variable in the Record struct may be stored in slot 0, which could lead to unintended behavior or vulnerabilities.</li></ul><blockquote><strong>Note</strong>: In all these examples, uninitialized storage variables are accessed, used in calculations, stored without proper initialization and complex data type such as a struct is declared as a local variable. This can lead to unpredictable behavior, vulnerabilities, or contract failures, highlighting the importance of ensuring that all storage variables are initialized correctly in Solidity contracts.</blockquote><h3><strong>Mitigation Steps</strong></h3><p>Here are some mitigation steps for the uninitialized storage variables bugs for the above Solidity contracts:</p><p>1. <strong>Mitigation for Accessing Uninitialized Storage Variable</strong>:</p><pre>pragma solidity ^0.8.0;<br><br>contract UninitializedStorageBug {<br>    uint public uninitializedValue; // uninitialized storage variable<br>    <br>    // Initialize uninitializedValue in the constructor<br>    constructor() {<br>        uninitializedValue = 0; // Initialized uninitializedValue to a default value<br>    }<br>    <br>    function setValue(uint _newValue) public {<br>        uninitializedValue = _newValue;<br>    }<br>    <br>    function getValue() public view returns (uint) {<br>        return uninitializedValue; // Accessing initialized storage variable<br>    }<br>}</pre><p><strong>Mitigation Steps</strong>:</p><ul><li>Initialize the uninitialized storage variable uninitializedValue in the contract constructor to ensure it has a defined initial value.</li><li>By initializing the storage variable in the constructor, you ensure that it is always initialized before any other functions access or use it.</li><li>This helps prevent accessing uninitialized storage variables and ensures predictable behavior when reading their values.</li></ul><p>2. <strong>Mitigation for Using Uninitialized Storage Variable in Calculation</strong>:</p><pre>pragma solidity ^0.8.0;<br><br>contract UninitializedStorageBug {<br>    uint public uninitializedValue; // uninitialized storage variable<br>    <br>    // Initialize uninitializedValue in the constructor<br>    constructor() {<br>        uninitializedValue = 0; // Initialize uninitializedValue to a default value<br>    }<br>    <br>    function setValue(uint _newValue) public {<br>        uninitializedValue = _newValue;<br>    }<br>    <br>    function doubleValue() public view returns (uint) {<br>        return uninitializedValue * 2; // Using initialized storage variable in calculation<br>    }<br>}</pre><p><strong>Mitigation Steps</strong>:</p><ul><li>Similar to the previous example, initialize the uninitialized storage variable uninitializedValue in the contract constructor to ensure it has a defined initial value.</li><li>By initializing the storage variable in the constructor, you prevent using uninitialized storage variables in calculations, ensuring consistent and predictable behavior.</li></ul><p>3. <strong>Mitigation for Storing Data in Uninitialized Storage Slot</strong>:</p><pre>pragma solidity ^0.8.0;<br><br>contract UninitializedStorageBug {<br>    uint public uninitializedValue; // uninitialized storage variable<br>    uint[] public uninitializedArray; // uninitialized storage array<br>    <br>    // Initialize uninitializedValue and uninitializedArray in the constructor<br>    constructor() {<br>        uninitializedValue = 0; // Initialize uninitializedValue to a default value<br>        uninitializedArray = new uint[](0); // Initialize uninitializedArray with an empty array<br>    }<br>    <br>    function setValue(uint _newValue) public {<br>        uninitializedValue = _newValue;<br>    }<br>    <br>    function pushToArray(uint _newValue) public {<br>        uninitializedArray.push(_newValue); // Storing data in initialized storage array<br>    }<br>}</pre><p><strong>Mitigation Steps</strong>:</p><ul><li>Initialize the uninitialized storage array uninitializedArray in the contract constructor with an empty array to ensure it is initialized before use.</li><li>By initializing the storage array in the constructor, you prevent storing data in uninitialized storage slots, ensuring data integrity and preventing potential vulnerabilities.</li></ul><p>4. <strong>Mitigation for Complex data type is declared as a local variable</strong>:</p><pre>pragma solidity ^0.8.0;<br><br>contract UninitializedStorage {<br>    struct Record {<br>        bool unlocked;<br>    }<br><br>    Record[] records;<br><br>    function addRecord(bool unlocked) public {<br>        Record memory newRecord = Record(unlocked);<br><br>        // Properly initialized storage pointer:<br>        // newRecord is a pointer to storage, and it&#39;s properly initialized<br>        // before being pushed to the records array.<br>        records.push(newRecord);<br>    }<br><br>    function checkRecord(uint256 index) public view returns (bool) {<br>        return records[index].unlocked;<br>    }<br>}</pre><p><strong>Mitigation Steps</strong>:</p><ul><li>In the updated code, the Record struct is initialized with the unlocked value before being pushed to the records array, ensuring that the storage slots are used correctly and avoiding the uninitialized storage variable bug.</li></ul><h3><strong>Conclusion</strong></h3><p>By initializing storage variables (<em>state variables</em>) in the contract constructor and ensuring they have defined initial values, you can mitigate uninitialized storage variables bugs in Solidity contracts.</p><p><strong>For more</strong>: <a href="https://github.com/logesh21n/Solidity-Common-Vulnerabilities">https://github.com/logesh21n/Solidity-Common-Vulnerabilities</a></p><p>If you have any doubts in Solidity smart contract and smart contract bugs or if you’re stuck somewhere, feel free to DM me. You can also follow me and ask your doubts on:</p><p>Twitter: <a href="https://twitter.com/NLogesh21">https://twitter.com/NLogesh21</a><br>GitHub: <a href="https://github.com/logesh21n">https://github.com/logesh21n</a><br>Discord: logesh_n</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ee1cc2bd8d3" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/common-vulnerabilities-uninitialized-storage-variables-8ee1cc2bd8d3">COMMON VULNERABILITIES: Uninitialized Storage Variables</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[COMMON VULNERABILITIES: ACCESS CONTROL]]></title>
            <link>https://coinsbench.com/common-vulnerabilities-access-control-37a72326b068?source=rss-d25cd9352fc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/37a72326b068</guid>
            <category><![CDATA[smart-contract-auditing]]></category>
            <category><![CDATA[smart-contract-blockchain]]></category>
            <category><![CDATA[smart-contract-security]]></category>
            <category><![CDATA[access-control]]></category>
            <dc:creator><![CDATA[Logesh N]]></dc:creator>
            <pubDate>Sun, 24 Mar 2024 16:05:05 GMT</pubDate>
            <atom:updated>2024-04-08T09:28:55.233Z</atom:updated>
            <content:encoded><![CDATA[<p>Access control issues in Solidity refer to vulnerabilities related to improper management of permissions and privileges within smart contracts. These vulnerabilities can allow unauthorized users to perform actions they should not be allowed to execute, leading to security breaches, loss of funds, or manipulation of contract state. Let’s delve into more detail about access control issues:</p><p>1. <strong>Lack of Access Controls</strong>:</p><ul><li>One of the most common access control issues is the absence of proper access controls altogether. Contracts may allow any user to execute sensitive functions without verifying their authorization status.</li><li>For example, a contract may have functions that transfer ownership, mint tokens, or modify critical state variables without checking if the caller has the appropriate permissions.</li></ul><p>2. <strong>Public Functions with Sensitive Logic</strong>:</p><ul><li>Public functions that perform sensitive operations should have appropriate access controls to restrict their execution to authorized users.</li><li>If such functions lack access controls, any user can invoke them, potentially causing undesired outcomes or compromising the contract’s security.</li></ul><p>3. <a href="https://medium.com/@logeshnanjundan/common-vulnerabilities-unchecked-external-calls-7eea119138b2"><strong>Unchecked External Calls</strong></a>:</p><ul><li>External calls made within a contract should also be subject to access controls. Contracts may inadvertently expose sensitive functions to unauthorized external contracts or addresses, leading to unauthorized access or manipulation.</li><li>In addition to direct function calls, external calls such as call, delegatecall, or send should also be carefully managed to prevent unauthorized access.</li></ul><p>4. <strong>Insecure State Manipulation</strong>:</p><ul><li>Access controls should extend to state variables and critical contract state. Unauthorized modifications to state variables can lead to unexpected behavior or exploitation of vulnerabilities.</li><li>Contracts should validate the permissions of callers before allowing them to modify state variables or execute critical state-changing functions.</li></ul><p>5. <strong>Privilege Escalation</strong>:</p><ul><li>Contracts should guard against privilege escalation attacks where attackers exploit vulnerabilities to elevate their privileges within the contract.</li><li>For example, an attacker may manipulate the contract’s state to gain administrative privileges or access restricted functionality.</li></ul><p><strong>6. Mitigation Steps:</strong></p><ul><li>Implement <strong>Role-Based Access Control</strong> (RBAC) to define and manage user roles and permissions within the contract.</li><li>Use modifiers to enforce access controls in a reusable and concise manner, reducing code duplication and potential errors.</li><li>Secure sensitive functions and state variables by restricting access to authorized users only.</li><li>Validate user permissions and inputs rigorously to prevent unauthorized actions or inputs that may lead to access control issues.</li></ul><h3><strong>Examples</strong></h3><p>1. <strong>Lack of Access Controls</strong>:</p><pre>contract Token {<br>    mapping(address =&gt; uint256) public balances;<br>    address public owner;<br><br>    constructor() {<br>        owner = msg.sender;<br>    }<br><br>    // This function does not has any require statement for who can call this function.<br>    // Anyone in the network can able to access to this function without any revert.<br>    // So this is considered to access control issue.<br>    function mint(address recipient, uint256 amount) public {<br>        // Lack of access control: Anyone can mint tokens<br>        balances[recipient] += amount;<br>    }<br>}</pre><p><strong>Explanation</strong>:</p><ul><li>In this example, the mint function lacks proper access controls, allowing anyone to mint tokens by calling the function.</li><li>Without checking if the caller has the appropriate permissions (such as being the contract owner or having a specific role), the contract is vulnerable to unauthorized token creation.</li></ul><p>2. <strong>Public Functions with Sensitive Logic</strong>:</p><pre>contract Voting {<br>    mapping(address =&gt; bool) public hasVoted;<br>    address public admin;<br><br>    constructor() {<br>        admin = msg.sender;<br>    }<br>    // This function does not checks that the voter can only vote once.<br>    // Anyone can vote multiple times. It is against the Voting protocol.<br>    // So this is considered to access control issue.<br>    function vote(uint256 option) public {<br>        // Lack of access control: Anyone can vote multiple times<br>        hasVoted[msg.sender] = true;<br>        // Record the vote<br>    }<br>}</pre><p><strong>Explanation:</strong></p><ul><li>In this example, the vote function, which should only allow each user to vote once, lacks proper access controls.</li><li>Without checking if the caller has already voted, any user can call the function multiple times and skew the voting results.</li></ul><p>3. <strong>Unchecked External Calls</strong>:</p><pre>contract PaymentGateway {<br>    address public admin;<br><br>    constructor() {<br>        admin = msg.sender;<br>    }<br><br>    // This function does not has any require statement for who can transfer `amount`.<br>    // Anyone in the network can able to access to this function without any revert.<br>    // So this is considered to access control issue.<br>    function processPayment(address payable recipient, uint256 amount) public {<br>        // Lack of access control: External call without permission check<br>        recipient.transfer(amount);<br>    }<br>}</pre><p><strong>Explanation:</strong></p><ul><li>In this example, the processPayment function allows anyone to trigger payments to arbitrary addresses without proper authorization checks.</li><li>An attacker can exploit this vulnerability to drain funds from the contract or manipulate payment operations.</li></ul><p>4. <strong>Insecure State Manipulation</strong>:</p><pre>contract Bank {<br>    mapping(address =&gt; uint256) public balances;<br>    address public owner;<br><br>    constructor() {<br>        owner = msg.sender;<br>    }<br>    // This function does not has any require statement for who can deposit.<br>    // Anyone can deposit and can modify their balances.<br>    // So this is considered to access control issue.<br>    function deposit() public payable {<br>        // Insecure state manipulation: No access control for deposit function<br>        balances[msg.sender] += msg.value;<br>    }<br>}</pre><p><strong>Explanation:</strong></p><ul><li>In this example, the deposit function lacks access controls, allowing any user to deposit funds into the bank contract and modify their balance.</li><li>Without proper authorization checks, unauthorized users can manipulate their balances or those of other users.</li></ul><h3><strong>Mitigations Steps</strong></h3><p>Let’s discuss mitigation steps for each of the example contracts provided earlier, addressing the access control issues they exhibit:</p><p>1. <strong>Lack of Access Controls</strong>:</p><pre>contract Token {<br>    mapping(address =&gt; uint256) public balances;<br>    address public owner;<br><br>    constructor() {<br>        owner = msg.sender;<br>    }<br><br>    // We implemented checks for who can mint the Tokens.<br>    function mint(address recipient, uint256 amount) public {<br>        // Mitigation: Implement access control to restrict minting to the contract owner<br>        require(msg.sender == owner, &quot;Only owner can mint tokens&quot;);<br>        balances[recipient] += amount;<br>    }<br>}</pre><p><strong>Mitigation Steps</strong>:</p><ul><li>Add a modifier or require statement to the mint function to ensure that only the contract owner can mint tokens.</li></ul><p>2. <strong>Public Functions with Sensitive Logic</strong>:</p><pre>contract Voting {<br>    mapping(address =&gt; bool) public hasVoted;<br>    address public admin;<br><br>    constructor() {<br>        admin = msg.sender;<br>    }<br><br>    // We implemented the checks to prevent from mulitiple votes by single person. <br>    function vote(uint256 option) public {<br>        // Mitigation: Add access control to prevent multiple votes from the same address.<br>        require(!hasVoted[msg.sender], &quot;Already voted&quot;);<br>        hasVoted[msg.sender] = true;<br>        // Record the vote<br>    }<br>}</pre><p><strong>Mitigation Steps</strong>:</p><ul><li>Modify the vote function to include a check to ensure that the caller has not voted before allowing them to vote.</li></ul><p>3. <strong>Unchecked External Calls</strong>:</p><pre>contract PaymentGateway {<br>    address public admin;<br><br>    constructor() {<br>        admin = msg.sender;<br>    }<br><br>    // We implemented the checks for who can transfer the amount.<br>    function processPayment(address payable recipient, uint256 amount) public {<br>        // Mitigation: Add access control to restrict payment processing to authorized users<br>        require(msg.sender == admin, &quot;Unauthorized&quot;);<br>        recipient.transfer(amount);<br>    }<br>}</pre><p><strong>Mitigation Steps</strong>:</p><ul><li>Restrict access to the processPayment function to only authorized users, such as the contract administrator or specific roles.</li><li>Implement access control checks before performing any external calls.</li></ul><p>4. <strong>Insecure State Manipulation</strong>:</p><pre>contract Bank {<br>    mapping(address =&gt; uint256) public balances;<br>    address public owner;<br><br>    constructor() {<br>        owner = msg.sender;<br>    }<br><br>    // We implemented the checks for who can deposit into Bank.<br>    function deposit() public payable {<br>        // Mitigation: Add access control to restrict deposits to authorized users<br>        require(msg.sender == owner, &quot;Unauthorized&quot;);<br>        balances[msg.sender] += msg.value;<br>    }<br>}</pre><p><strong>Mitigation Steps</strong>:</p><ul><li>Modify the deposit function to include access control checks to ensure that only authorized users can deposit funds.</li><li>Consider implementing RBAC if multiple roles are involved in managing the contract’s functionality.</li></ul><h3>Conclusion</h3><p>It is crucial to ensure that sensitive state variables or functions are accessible only to authorized users. Access control mechanisms should be implemented rigorously to prevent unauthorized access. Failure to implement proper access control mechanisms can leave state variables or functions vulnerable to exploitation. Without adequate protection, unauthorized users or hacker may exploit these vulnerabilities, compromising the security and integrity of the smart contract.</p><p><strong>For more</strong>: <a href="https://github.com/logesh21n/Solidity-Common-Vulnerabilities">https://github.com/logesh21n/Solidity-Common-Vulnerabilities</a></p><p>If you have any doubts in Solidity smart contract and smart contract bugs or if you’re stuck somewhere, feel free to DM me. You can also follow me and ask your doubts on:</p><p>Twitter: <a href="https://twitter.com/NLogesh21">https://twitter.com/NLogesh21</a><br>GitHub: <a href="https://github.com/logesh21n">https://github.com/logesh21n</a><br>Discord: logesh_n</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37a72326b068" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/common-vulnerabilities-access-control-37a72326b068">COMMON VULNERABILITIES: ACCESS CONTROL</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[COMMON VULNERABILITIES: Denial of Service (DoS)]]></title>
            <link>https://coinsbench.com/common-vulnerabilities-denial-of-service-dos-f9f0669dc852?source=rss-d25cd9352fc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/f9f0669dc852</guid>
            <category><![CDATA[denial-of-service-attack]]></category>
            <category><![CDATA[smart-contract-security]]></category>
            <category><![CDATA[smart-contract-auditing]]></category>
            <category><![CDATA[denial-of-service]]></category>
            <dc:creator><![CDATA[Logesh N]]></dc:creator>
            <pubDate>Sun, 24 Mar 2024 04:09:33 GMT</pubDate>
            <atom:updated>2024-03-25T12:51:24.635Z</atom:updated>
            <content:encoded><![CDATA[<p>Denial of Service (DoS) attacks in the context of Solidity and blockchain refer to malicious activities aimed at disrupting the normal operation of smart contracts, decentralized applications (dApps), or blockchain networks. These attacks exploit vulnerabilities in Solidity contracts or blockchain protocols to exhaust system resources, delay transaction processing, or disrupt contract functionality, thereby denying legitimate users access to services or resources.</p><p>Here’s a more detailed explanation of Denial of Service (DoS) bugs in Solidity:</p><p>1. <strong>Resource Exhaustion</strong>:</p><ul><li>DoS attacks in Solidity often involve exhausting system resources, such as gas, computation, or storage, to render smart contracts or dApps makes unusable.</li><li>Attackers may deploy contracts or execute transactions that consume excessive gas, overwhelm the Ethereum Virtual Machine (EVM), or cause out-of-gas exceptions, leading to transaction failures or contract halts.</li></ul><p>2. <strong>Gas Limit Manipulation</strong>:</p><ul><li>Attackers may attempt to manipulate the gas limit or gas price of transactions to disrupt transaction processing or congest the network.</li><li>By submitting transactions with excessively high gas limits or high gas prices, attackers can cause delays in transaction confirmation, increase transaction costs for legitimate users, or create network congestion.</li></ul><p>3. <strong>Infinite Loops</strong>:</p><ul><li>A function that enters an infinite loop can consume all available gas, making the contract unresponsive. This is a common issue in smart contracts that do not have proper checks or conditions to break out of loops.</li></ul><p>4. <strong>Reentrancy Vulnerabilities</strong>:</p><ul><li>Reentrancy vulnerabilities, where an attacker reenters a contract during its execution, can be exploited to perform DoS attacks by repeatedly consuming gas or triggering costly operations within the contract.</li><li>Attackers may exploit reentrancy vulnerabilities to drain contract funds, disrupt contract logic, or cause contract freezes by executing recursive calls or loops.</li></ul><p>5. <strong>Smart Contract Vulnerabilities</strong>:</p><ul><li>DoS bugs in Solidity contracts often stem from vulnerabilities in contract logic, access controls, or state management.</li><li>Common vulnerabilities include unbounded loops, excessive gas consumption, inefficient algorithms, or lack of proper validation checks, allowing attackers to exploit these weaknesses to disrupt contract functionality.</li></ul><p>6. <strong>Impact on Decentralized Applications</strong>:</p><ul><li>DoS attacks can have severe consequences for decentralized applications, impacting user experience, disrupting service availability, and causing financial losses.</li><li>In addition to immediate disruptions, DoS attacks can undermine user trust, damage reputation, and hinder adoption of blockchain-based systems.</li></ul><p>7. <strong>Mitigation Strategies</strong>:</p><ul><li>Implement gas-efficient coding practices, such as using optimized algorithms, minimizing storage operations, and avoiding unbounded loops.</li><li>Implement access controls and permission checks to prevent unauthorized access to sensitive functionality or resources.</li><li>Use circuit breakers or emergency stop mechanisms to temporarily halt contract operations in the event of abnormal behavior or DoS attacks.</li><li>Regularly audit and test contracts for vulnerabilities, including gas-related vulnerabilities and reentrancy issues, to identify and mitigate potential attack vectors.</li></ul><blockquote><strong>Summary</strong>: Denial of Service (DoS) bugs in Solidity contracts and blockchain networks involve exploiting vulnerabilities to disrupt normal operations, exhaust system resources, or congest the network, thereby denying legitimate users access to services or resources.</blockquote><h3><strong>Examples</strong></h3><p>Here are examples of Denial of Service (DoS) bugs in Solidity contracts:</p><p>1. <strong>Gas Limit DoS</strong>:</p><pre>contract GasLimitDoS {<br>    mapping(address =&gt; uint) public balances;<br><br>    // Vulnerability: Gas refund mechanism can be exploited for DoS attack<br>    function withdraw() public {<br>        uint amount = balances[msg.sender];<br>        require(amount &gt; 0, &quot;No balance to withdraw&quot;);<br>        <br>        // Vulnerability: Expensive loop that consumes excessive gas<br>        for (uint i = 0; i &lt; amount; i++) {<br>            balances[msg.sender]--;<br>        }<br>        <br>        // Vulnerability: Refund remaining gas to attacker, allowing them to perform DoS attack<br>        selfdestruct(msg.sender);<br>    }<br>}</pre><p><strong>Explanation</strong>:</p><ul><li>This contract contains a withdraw function that allows users to withdraw their balances.</li><li>The vulnerability lies in the withdraw function’s loop, which consumes gas proportionate to the user’s balance.</li><li>Attackers can exploit this by depositing a small balance and repeatedly calling withdraw, consuming all available gas and preventing other transactions from being processed.</li></ul><p>2. <strong>Reentrancy DoS</strong>:</p><pre>contract ReentrancyDoS {<br>    mapping(address =&gt; uint) public balances;<br><br>    function withdraw(uint _amount) public {<br>        require(balances[msg.sender] &gt;= _amount, &quot;Insufficient balance&quot;);<br>        <br>        // Vulnerability: Reentrancy vulnerability allows an attacker to repeatedly withdraw funds<br>        msg.sender.call.value(_amount)(&quot;&quot;);<br>        balances[msg.sender] -= _amount;<br>    }<br>    <br>    // Vulnerability: Malicious contract with fallback function that invokes withdraw<br>    function() external payable {<br>        withdraw(balances[msg.sender]);<br>    }<br>}</pre><p><strong>Explanation</strong>:</p><ul><li>This contract allows users to withdraw funds with the withdraw function.</li><li>The vulnerability arises from a <a href="https://www.evm.codes/#f1?fork=cancun">reentrancy vulnerability</a> (search for opcode F1) in the withdraw function, allowing an attacker to recursively call withdraw before the balance is updated.</li><li>Attackers can deploy a malicious contract with a fallback function that invokes withdraw, causing a recursive loop that drains the contract’s balance and prevents legitimate transactions from being processed.</li></ul><blockquote><strong>Summary: </strong>In both examples, attackers exploit vulnerabilities in Solidity contracts to execute DoS attacks, either by consuming excessive gas or by exploiting reentrancy vulnerabilities to drain contract funds. These vulnerabilities can have severe consequences, including disruption of contract functionality, financial losses, and degradation of user experience.</blockquote><h3><strong>Mitigation Steps</strong></h3><p>Let’s discuss mitigation steps for the Denial of Service (DoS) vulnerabilities identified in the above example contracts:</p><p>1. <strong>Mitigation for Gas Limit DoS</strong>:</p><pre>contract GasLimitDoS {<br>    mapping(address =&gt; uint) public balances;<br>    event Withdraw(address, uint256);<br>    <br>    // Mitigation: Use withdrawal pattern to limit gas consumption<br>    function withdraw() public {<br>        uint amount = balances[msg.sender];<br>        require(amount &gt; 0, &quot;No balance to withdraw&quot;);<br>        <br>        // Mitigation: Limit gas consumption by transferring funds in chunks<br>        // Calculate maximum amount to transfer in a single transaction<br>        uint maxTransfer = (gasleft() - 2300) / 14154; // 2300 is the stipend for transfer and 14154 is the gas cost for a transfer<br>        // Limit transfer amount to avoid exceeding gas limit<br>        uint transferAmount = amount &gt; maxTransfer ? maxTransfer : amount;<br>        <br>        // Transfer funds to sender<br>        balances[msg.sender] -= transferAmount;<br>        msg.sender.transfer(transferAmount);<br>        <br>        // Emit event to indicate successful withdrawal<br>        emit Withdrawal(msg.sender, transferAmount);<br>    }<br>}</pre><p><strong>Explanation</strong>:</p><ul><li>Implement the withdrawal pattern to limit gas consumption by transferring funds to users in smaller chunks.</li><li>Calculate the maximum amount that can be transferred in a single transaction based on the available gas and gas cost for a transfer operation.</li><li>Limit the transfer amount to prevent exceeding the gas limit and ensure successful transaction execution.</li><li>Emit events to provide transparency and visibility into the withdrawal process, allowing users to track their transactions.</li></ul><p>2. <strong>Mitigation for Reentrancy DoS</strong>:</p><pre>contract ReentrancyDoS {<br>    mapping(address =&gt; uint) public balances;<br>    mapping(address =&gt; bool) private _locked;<br>    <br>    function withdraw(uint _amount) public {<br>        require(balances[msg.sender] &gt;= _amount, &quot;Insufficient balance&quot;);<br>        require(!_locked[msg.sender], &quot;Withdrawal in progress&quot;);<br>        <br>        // Lock user&#39;s balance to prevent reentrancy<br>        _locked[msg.sender] = true;<br>        <br>        // Update user&#39;s balance before transferring funds<br>        uint amountToTransfer = _amount;<br>        balances[msg.sender] -= _amount;<br>        <br>        // Transfer funds to user<br>        msg.sender.transfer(amountToTransfer);<br>        <br>        // Unlock user&#39;s balance after successful transfer<br>        _locked[msg.sender] = false;<br>        <br>        // Emit event to indicate successful withdrawal<br>        emit Withdrawal(msg.sender, amountToTransfer);<br>    }<br>}</pre><p><strong>Explanation</strong>:</p><ul><li>Using call or low level calls like delegatecall,send can cause gas exhaustion. Therefore, we can use transfer instead of call.</li><li>Refer gas costs for low level calls: <a href="https://www.evm.codes/?fork=cancun">https://www.evm.codes/?fork=cancun</a></li><li>Also implement a locking mechanism to prevent reentrancy attacks by ensuring that withdrawals cannot be initiated while a withdrawal is in progress for a particular user.</li><li>Lock the user’s balance before updating the balance and transferring funds to prevent reentrancy.</li><li>Unlock the user’s balance after successfully transferring funds to allow subsequent withdrawals.</li><li>Emit events to provide visibility into the withdrawal process and help identify potential issues.</li></ul><p><strong>For more</strong>: <a href="https://github.com/logesh21n/Solidity-Common-Vulnerabilities">https://github.com/logesh21n/Solidity-Common-Vulnerabilities</a></p><p>If you have any doubts in Solidity smart contract and smart contract bugs or if you’re stuck somewhere, feel free to DM me. You can also follow me and ask your doubts on:</p><p>Twitter: <a href="https://twitter.com/NLogesh21">https://twitter.com/NLogesh21</a><br>GitHub: <a href="https://github.com/logesh21n">https://github.com/logesh21n</a><br>Discord: logesh_n</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f9f0669dc852" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/common-vulnerabilities-denial-of-service-dos-f9f0669dc852">COMMON VULNERABILITIES: Denial of Service (DoS)</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Super Sushi Samurai Exploit]]></title>
            <link>https://coinsbench.com/super-sushi-samurai-exploit-aebf2d4d2a0c?source=rss-d25cd9352fc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/aebf2d4d2a0c</guid>
            <category><![CDATA[smart-contract-auditing]]></category>
            <category><![CDATA[smart-contract-security]]></category>
            <dc:creator><![CDATA[Logesh N]]></dc:creator>
            <pubDate>Sat, 23 Mar 2024 05:10:50 GMT</pubDate>
            <atom:updated>2024-03-25T12:51:26.486Z</atom:updated>
            <content:encoded><![CDATA[<p>A contract that doesn’t check if the sender and recipient addresses are the same is vulnerable to an exploit similar to the <a href="https://rekt.news/sss-rekt/">Super Sushi Samurai LP</a> hack. An attacker could double their token balance by transferring tokens to their own address.</p><h3><strong>Unintended Behavior</strong></h3><p>This functionality would likely lead to unexpected behavior and potential loss of funds for users. Sending tokens to your own address should not modify the total balance.</p><h3><strong>Example Vulnerable Contract</strong></h3><pre>pragma solidity ^0.8.0;<br>  <br>// Basic token contract<br>contract Token {<br><br>  mapping(address =&gt; uint) public balances;<br><br>  // Transfer tokens from one address to another<br>  function transfer(address from, address to, uint amount) public {<br>    // Check sender has enough tokens<br>    // But failed to check the `from` and `to` address are same.<br>    require(balances[from] &gt;= amount, &quot;Insufficient balance&quot;);<br>    // Transfer tokens<br>    balances[from] -= amount;<br>    balances[to] += amount;<br>  }<br>}</pre><h3><strong>Explanation</strong></h3><ul><li>This contract template is for a basic token contract with a transfer function.</li><li>The transfer function moves tokens from one address (from) to another address (to).</li><li>It includes a basic check to ensure that the sender (from) has sufficient balance before transferring tokens.</li></ul><h3><strong>Best Practices</strong></h3><ul><li><strong>Balance Check:</strong> The function verifies that the sender has enough tokens to transfer, preventing overspending.</li><li><strong>No Same Address Check:</strong> This version intentionally omits the check for from and to being the same address. In a real-world scenario, you should add a check to prevent transferring tokens to same address (from != to).</li></ul><p><strong>Mitigation Step:</strong></p><pre>pragma solidity ^0.8.0;<br>  <br>// Basic token contract<br>contract Token {<br><br>  mapping(address =&gt; uint) public balances;<br><br>  // Transfer tokens from one address to another<br>  function transfer(address from, address to, uint amount) public {<br>    // Check sender has enough tokens<br>    require(balances[from] &gt;= amount, &quot;Insufficient balance&quot;);<br><br>    // Check for different addresses<br>    require(from != to, &quot;Can&#39;t transfer tokens to the same address&quot;);<br><br>    // Transfer tokens<br>    balances[from] -= amount;<br>    balances[to] += amount;<br>  }<br>}</pre><p><strong>Explanation:</strong></p><ul><li>The updated Token contract now includes an additional check to ensure that the sender’s (from) and recipient’s (to) addresses are not the same.</li><li>This prevents tokens from being transferred to the same address, enhancing security and preventing unintended behavior.</li></ul><p><strong>For more</strong>: <a href="https://github.com/logesh21n/Solidity-Common-Vulnerabilities">https://github.com/logesh21n/Solidity-Common-Vulnerabilities</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aebf2d4d2a0c" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/super-sushi-samurai-exploit-aebf2d4d2a0c">Super Sushi Samurai Exploit</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[COMMON VULNERABILITIES: UNCHECKED EXTERNAL CALLS]]></title>
            <link>https://coinsbench.com/common-vulnerabilities-unchecked-external-calls-7eea119138b2?source=rss-d25cd9352fc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/7eea119138b2</guid>
            <category><![CDATA[smart-contract-auditing]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[smart-contract-security]]></category>
            <dc:creator><![CDATA[Logesh N]]></dc:creator>
            <pubDate>Fri, 22 Mar 2024 04:52:42 GMT</pubDate>
            <atom:updated>2024-03-22T17:20:16.624Z</atom:updated>
            <content:encoded><![CDATA[<p>The “<em>Unchecked External Calls</em>” vulnerability refers to situations in Solidity smart contracts where external calls are made to other contracts or external addresses without proper validation of the return values or handling of potential errors. This vulnerability can lead to various security issues, including loss of funds, unexpected behavior, and contract compromise. Let’s break down this vulnerability in more detail:</p><p>1. <strong>External Calls in Solidity</strong>:</p><p>Solidity allows contracts to interact with other contracts or external addresses using functions like call, delegatecall, and send. These functions are commonly used to invoke functions on other contracts, transfer Ether, or perform other actions outside the contract’s scope.</p><p>2. <strong>Unchecked Return Values</strong>:</p><p>When making an external call, it’s crucial to validate the return values to ensure that the call was successful and the expected behavior occurred. Ignoring or not properly handling the return values can lead to vulnerabilities. For example, if an external call fails (<em>due to out-of-gas exceptions, reverted transactions, or other errors</em>), it may leave the contract in an inconsistent state.</p><p>3. <strong>Reentrancy Vulnerabilities</strong>:</p><p>Unchecked external calls are often associated with reentrancy vulnerabilities. If an external call is made before the contract’s state changes are finalized, an attacker may exploit this window of opportunity to reenter the contract and manipulate its state. This can lead to scenarios where the contract’s funds are drained, unauthorized operations are performed, or contract logic is bypassed.</p><p>4. <strong>Examples of Unchecked External Calls</strong>:</p><ul><li><strong>Sending Ether</strong>: When using send or transfer to send Ether to an external address, the contract should handle potential failures by checking the return value (`<em>bool success</em>`) and reverting if the transfer fails.</li><li><strong>Calling External Functions</strong>: When calling functions on other contracts using call or delegatecall, it’s essential to validate the return value to ensure that the called function executed as expected. Failure to do so may allow attackers to exploit unexpected behavior or vulnerabilities in the called contract.</li></ul><p>5. <strong>Mitigation Strategies</strong>:</p><p>To mitigate the risks associated with unchecked external calls, developers should:</p><ul><li>Always validate return values and handle errors when making external calls.</li><li>Follow the Checks-Effects-Interactions pattern to ensure that state changes are finalized before interacting with external contracts.</li><li>Use the latest Solidity version and follow best practices recommended by the Ethereum community.</li><li>Consider using higher-level abstractions or security libraries that provide safer methods for interacting with external contracts.</li></ul><h3><strong>Example 1</strong></h3><p>The Unchecked External Calls bug in Solidity with a simple example involving two contracts: a token contract and a contract that interacts with the token contract. We’ll use the names Alice and Bob to represent two different users interacting with these contracts.</p><p><strong>Scenario Setup:</strong></p><p>1. <strong>Alice</strong> is the owner of a token contract. This contract has a function transfer that allows transferring tokens to another address.</p><p>2. <strong>Bob</strong> is a user who wants to transfer tokens from Alice’s contract to his own address.</p><p><strong>Alice’s token contract:</strong></p><pre>pragma solidity ^0.8.0;<br><br>contract AliceToken {<br>  <br>  mapping(address =&gt; uint256) public balances;<br>  <br>  constructor(uint256 initialSupply) {<br>    balances[msg.sender] = initialSupply;<br>  }<br><br>  function transfer(address to, uint256 amount) external {<br>    require(balances[msg.sender] &gt;= amount, &quot;Insufficient balance&quot;);<br>    balances[msg.sender] -= amount;<br>    balances[to] += amount;<br>  }<br>}</pre><p><strong>The Contract Interacting with Alice’s Token Contract :</strong></p><p>Bob’s contract, which interacts with Alice’s token contract, might look like this:</p><pre>pragma solidity ^0.8.0;<br><br> // Interface of ALice&#39;s Token Contract<br>interface IAliceToken {<br>  function transfer(address to, uint256 amount) external;<br>  }<br><br>contract BobContract {<br><br>  IAliceToken public aliceToken;<br><br>  constructor(address _aliceToken) {<br>    aliceToken = IAliceToken(_aliceToken);<br>  }<br><br>  function transferTokens(address to, uint256 amount) external {<br>    // Unchecked external call<br>    aliceToken.transfer(to, amount);<br>  }<br>}</pre><p><strong>The Unchecked External Call Bug :</strong></p><p>In the transferTokens function of Bob’s contract, there’s an unchecked external call to the transfer function of Alice’s token contract. This means that if the transfer function call fails (<em>for example, if Bob does not have enough tokens to transfer</em>), Bob’s contract will not be aware of this failure. It will continue executing as if the transfer was successful, which could lead to incorrect state updates or other unexpected behavior.</p><p><strong>Mitigation Example :</strong></p><p>To mitigate the risk of the Unchecked External Calls bug, we can modify Bob’s contract to check the return value of the external call. However, since <strong><em>Solidity 0.6.0</em></strong>, the call function is low-level and does not return a boolean indicating success or failure. Instead, we can use the transfer function directly, which reverts on failure, or use the call function with a try-catch pattern to handle failures gracefully.</p><p>Here’s how Bob’s contract could be modified to use the transfer function directly:</p><pre>pragma solidity ^0.8.0;<br><br>interface IAliceToken {<br>  function transfer(address to, uint256 amount) external;<br>  }<br><br>contract BobContract {<br><br>  IAliceToken public aliceToken;<br><br>  constructor(address _aliceToken) {<br>    aliceToken = IAliceToken(_aliceToken);<br>  }<br><br>  function transferTokens(address to, uint256 amount) external {<br>    // Direct call to transfer function with revert<br>    (bool success, ) = aliceToken.transfer(to, amount);<br>    require(success, &quot;Transfer failed&quot;);<br>  }<br>}</pre><p>By adding the revert(require) statement the contract can make updates of the failure transactions and Bob will aware of that failure.</p><h3><strong>Example 2</strong></h3><pre>function withdraw(uint256 amount) external nonReentrant {<br>  weth.transferFrom(msg.sender, address(this), amount); // Unchecked External Call<br>  weth.withdraw(amount);<br>  Address.sendValue(payable(msg.sender), amount);<br>}</pre><p>1. <strong>Unsafe </strong><strong>transferFrom Call</strong>:</p><ul><li>The contract has a function called withdraw, which calls an unsafe transferFrom function from an ERC20 token contract.</li><li>The transferFrom function is used to transfer tokens from one address to another, but if insufficient tokens are present, it may return false instead of reverting.</li><li>In this case, if the transferFrom function returns false, indicating that the transfer failed due to insufficient tokens, the withdraw function continues execution without reverting.</li></ul><p>2. <strong>Potential Exploitation</strong>:</p><ul><li>If the transferFrom function returns false, indicating a failed transfer due to insufficient tokens, the withdraw function continues execution.</li><li>As a result, the caller of the withdraw function (<em>e.g., Alice</em>) receives tokens for free, without actually having the required balance to cover the withdrawal.</li></ul><h3><strong>The Unchecked External Call Bug</strong></h3><p>1. Alice calls the withdraw function with a certain amount of tokens (<em>e.g., 100</em>).</p><p>2. The transferFrom function inside the withdraw function fails due to insufficient tokens and returns false, but it does not revert the transaction.</p><p>3. Despite the failed transfer, the withdraw function continues execution and calls weth.withdraw().</p><p>4. Alice receives tokens (<em>e.g., WETH</em>) for free, as the contract fails to properly handle the failed transfer and continues execution.</p><h3><strong>Mitigation Steps</strong></h3><p>1. <strong>Check the Result of </strong><strong>transferFrom and </strong><strong>transfer</strong>:</p><ul><li>Before proceeding with any further actions, the contract should validate the result of the transferFrom function call. If it returns false, indicating a failed transfer, the contract should revert the transaction to prevent further execution.</li></ul><pre>function withdraw(uint256 amount) external nonReentrant {<br>  // Check the return value of transferFrom<br>   require(weth.transferFrom(msg.sender, address(this), amount), &quot;TransferFrom failed&quot;);<br>  // Withdraw WETH<br>   weth.withdraw(amount);<br>  // Send Ether to the caller<br>    Address.sendValue(payable(msg.sender), amount);<br>  }</pre><p>2. <strong>Use SafeERC20 Library</strong>:</p><ul><li>Alternatively, the contract can make use of the SafeERC20 library, which provides safe versions of the transfer and transferFrom functions. These safe functions revert the transaction if the transfer fails, ensuring that funds are not transferred erroneously.</li></ul><h3><strong>Example 3</strong></h3><p>Let’s consider another example involving a decentralized exchange (<em>DEX</em>) contract and two users, Alice and Bob. In this scenario, Alice wants to sell some tokens on the DEX, and Bob wants to exploit a vulnerability in the DEX contract through an unchecked external call.</p><p>Here’s a simplified version of the contracts:</p><pre>// Decentralized Exchange (DEX) contract<br>contract DEX {<br><br>  mapping(address =&gt; uint256) public balances;<br><br>  function deposit() public payable {<br>    // Deposit Ether into the DEX<br>    balances[msg.sender] += msg.value;<br>  }<br><br>  function withdraw(uint256 amount) public {<br>    // Withdraw Ether from the DEX<br>    require(balances[msg.sender] &gt;= amount, &quot;Insufficient balance&quot;);<br>    balances[msg.sender] -= amount;<br>    msg.sender.transfer(amount);<br>  }<br><br>  function sellTokens(uint256 amount) public {<br>    // Buy tokens from the DEX<br>    amount &lt;= balances[msg.sender]<br>    balances[msg.sender] -= amount;<br>    // Vulnerability: No validation of token transfer success<br>    (bool success, ) = msg.sender.call.value(amount)(&quot;&quot;);<br>    require(success, &quot;Transfer failed&quot;);<br>  }<br>}<br><br>// User contract representing Alice<br>contract Alice {<br><br>  DEX public dex;<br><br>  constructor(DEX _dex) public {<br>    dex = _dex;<br>  }<br><br>  function sell(uint256 amount) public {<br>    // Alice sells tokens on the DEX<br>    // Assume token transfer logic here<br>    dex.sellTokens(amount);<br>  }<br>}<br><br>// User contract representing Bob (attacker)<br>contract Bob {<br><br>  DEX public dex;<br>  constructor(DEX _dex) public {<br>    dex = _dex;<br>  }<br><br>  function attack() public payable {<br>    // Bob initiates an attack on the DEX<br>    // Bob deposits some Ether into the DEX<br>    dex.deposit.value(msg.value)();<br>    // Bob calls Alice&#39;s function to trigger token sale<br>    Alice alice = Alice(address(this));<br>    alice.sell(msg.value);<br>  }<br><br>  // Function to receive Ether (fallback function)<br>    receive() external payable {}<br>  }</pre><p><strong>In this example</strong>:</p><ul><li>The `<strong>DEX</strong>` contract represents a decentralized exchange where users can deposit Ether, withdraw Ether, and buy tokens.</li><li>The `<strong>Alice</strong>` contract represents Alice, who wants to sell tokens on the DEX.</li><li>The `<strong>Bob</strong>` contract represents Bob, the attacker, who wants to exploit a vulnerability in the DEX contract.</li></ul><p>Now, let’s walk through the <strong>attack scenario</strong>:</p><p>1. Bob initiates an attack by depositing some Ether into the DEX and then calls Alice’s function to trigger a token sale.</p><p>2. Inside the sell function of the DEX, an external call is made to transfer Ether to Alice as payment for the tokens.</p><p>3. Before the sell function completes, the fallback function of Bob’s `<strong>Bob</strong>` contract is triggered due to the external call, allowing Bob to reenter the DEX contract.</p><p>4. Since the DEX contract does not properly validate the return value of the external call, Bob’s `<strong>Bob</strong>` contract can exploit this vulnerability to perform a reentrancy attack, potentially draining funds from the DEX contract or causing other unexpected behavior.</p><p>By this Unchecked External Call all the tokens sold by Alice is transfered to Bob.</p><h3><strong>Mitigation Steps</strong></h3><p>To mitigate the vulnerability in the DEX contract and prevent reentrancy attacks, we can implement several security measures:</p><p>1. <strong>Checks-Effects-Interactions Pattern</strong>:</p><ul><li>Follow the <em>Checks-Effects-Interactions</em> (<em>CEI</em>) pattern to ensure that state changes are made before any external interactions take place.</li><li>Ensure that all state changes are finalized and validated before making external calls.</li></ul><p>2. <strong>Use of Withdrawal Pattern</strong>:</p><ul><li>Separate the transfer of funds from the execution of other contract logic to prevent reentrancy attacks.</li><li>Implement a withdrawal pattern where users can withdraw their funds in a separate transaction after the trade is completed.</li></ul><p>3. <strong>Validation of External Call Results</strong>:</p><ul><li>Validate the return value of external calls to ensure that the intended action was executed successfully.</li><li>Revert the transaction if the external call fails or if the return value indicates an unexpected outcome.</li></ul><p>4. <strong>Limitations on Ether Transfer</strong>:</p><ul><li>Consider limiting the amount of Ether that can be transferred in a single transaction to reduce the impact of potential attacks.</li><li>Implement mechanisms such as withdrawal limits or cooldown periods to mitigate the risk of large-scale fund withdrawals.</li></ul><p>Here’s an updated version of the DEX contract with these mitigations:</p><pre>contract DEX {<br><br>  mapping(address =&gt; uint256) public balances;<br>  <br>  function deposit() public payable {<br>    // Deposit Ether into the DEX<br>    balances[msg.sender] += msg.value;<br>  }<br><br>  function withdraw(uint256 amount) public {<br>    // Withdraw Ether from the DEX<br>    require(balances[msg.sender] &gt;= amount, &quot;Insufficient balance&quot;);<br>    balances[msg.sender] -= amount;<br>    msg.sender.transfer(amount);<br>  }<br><br>  function buyTokens(uint256 amount) public {<br>    // Buy tokens from the DEX<br>    // Assume token transfer logic here<br>    require(amount &lt;= balances[msg.sender], &quot;Insufficient balance&quot;);<br>    balances[msg.sender] -= amount;<br>    // External call to transfer Ether<br>    (bool success, ) = msg.sender.call.value(amount)(&quot;&quot;);<br>    require(success, &quot;Transfer failed&quot;);<br>  }<br>}</pre><p><strong>In this updated version</strong>:</p><ul><li>The buyTokens function now verifies that the user has sufficient balance before deducting the token amount.</li><li>External calls are made after state changes are finalized, following the CEI pattern.</li><li>The return value of the external call is checked, and the transaction is reverted if the transfer fails.</li></ul><blockquote><strong>Note</strong>: Always the external call should revert when the transactions are failed. Always use a revert or require or an if statements to check whether the transactions are failed and should not use a bool has the return value.</blockquote><pre>(bool success, ) = msg.sender.call.value(amount)(&quot;&quot;);<br>require(success, &quot;Transfer failed&quot;);</pre><p>By implementing these mitigations, we can significantly reduce the risk of <em>Unchecked External Calls</em> issues and <em>Reentrancy attacks</em> and improve the security of the contract.</p><h3><strong>Conclusion</strong></h3><p>By always checking the return value of external calls or using the direct function call which inherently reverts on failure, developers can prevent the Unchecked External Calls bug in Solidity contracts. This practice is crucial for ensuring the correct behavior and security of contracts that interact with external contracts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7eea119138b2" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/common-vulnerabilities-unchecked-external-calls-7eea119138b2">COMMON VULNERABILITIES: UNCHECKED EXTERNAL CALLS</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[COMMON VULNERABILITIES: INTEGER OVERFLOW / UNDERFLOW]]></title>
            <link>https://coinsbench.com/common-vulnerabilities-integer-overflow-underflow-7ed958ba8ef9?source=rss-d25cd9352fc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ed958ba8ef9</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[smart-contract-security]]></category>
            <category><![CDATA[integer-overflow]]></category>
            <category><![CDATA[smart-contract-auditing]]></category>
            <dc:creator><![CDATA[Logesh N]]></dc:creator>
            <pubDate>Fri, 22 Mar 2024 04:16:22 GMT</pubDate>
            <atom:updated>2024-03-22T17:20:14.593Z</atom:updated>
            <content:encoded><![CDATA[<p>Integer overflow and underflow bugs in Solidity occur when the result of an arithmetic operation exceeds the maximum or minimum value representable by the data type used. These bugs typically arise when developers perform arithmetic operations on unsigned integers (uint) without proper bounds checking, leading to unexpected behavior or vulnerabilities in the contract.</p><blockquote><strong>Note</strong>:<em> In version 0.8.0 the solidity provides a default checks for Integer Overflow and Underflow.</em></blockquote><p>Here’s a more detailed explanation of integer overflow and underflow bugs:</p><p>1. <strong>Integer Overflow</strong>:</p><ul><li>Integer overflow occurs when the result of an arithmetic operation exceeds the maximum representable value of the data type.</li><li>In Solidity, unsigned integers (uint) wrap around upon overflow, meaning that if the result exceeds the maximum value, it “wraps” back to zero.</li><li>Adding 1 to the maximum value of a uint8(255) results in 0 due to overflow (1 + 255 = 256 but it results in `0` due to overflow of uint8).</li></ul><p>2. <strong>Integer Underflow</strong>:</p><ul><li>Integer underflow occurs when the result of an arithmetic operation falls below the minimum representable value of the data type.</li><li>In Solidity, underflow typically results in unexpected behavior, such as producing a large positive value instead of the expected negative value.</li><li>Subtracting 1 from zero in an unsigned integer uint8 (255) results in the maximum value of the data type due to underflow (0 — 1 = — 1 but it results in 255 due to underflow of uint8).</li></ul><p>3. <strong>Consequences of Integer Overflow/Underflow</strong>:</p><p>Integer overflow/underflow bugs can lead to various security vulnerabilities, including:</p><ul><li><strong>Loss of funds or tokens</strong>: If arithmetic operations involve account balances or token balances, integer overflow/underflow can result in incorrect balance calculations, leading to loss of funds.</li><li><strong>Unauthorized access or manipulation</strong>: Attackers can exploit integer overflow/underflow vulnerabilities to bypass security checks, gain unauthorized access, or manipulate contract behavior.</li><li><strong>Denial of service</strong>: Integer overflow/underflow bugs can disrupt contract functionality or cause unexpected behavior, leading to denial of service attacks.</li></ul><p>4. <strong>Mitigation Strategies</strong>:</p><ul><li><strong>Use SafeMath library</strong>: Implement arithmetic operations using safe math libraries, such as OpenZeppelin’s SafeMath, which provide functions to perform arithmetic operations with overflow/underflow checks.</li><li><strong>Bounds checking</strong>: Perform explicit bounds checking before executing arithmetic operations to ensure that the result does not exceed the maximum or minimum representable values.</li><li><strong>Use larger data types</strong>: Consider using larger data types (`uint256`) to minimize the risk of overflow/underflow, especially for operations involving large numbers or cumulative values.</li></ul><h3><strong>Examples</strong></h3><p>Here are examples illustrating integer overflow and underflow bugs in Solidity:</p><p>1. <strong>Integer Overflow Example</strong>:</p><pre>pragma solidity ^0.8.0;<br><br>contract IntegerOverflow {<br><br>  uint8 public maxUint8 = 255;<br><br>  function overflow() public view returns (uint8) {<br>    return maxUint8 + 1; // Integer overflow occurs here results in 0 due to overflow<br>  }<br>}</pre><p><strong>Explanation</strong>:</p><ul><li>In this example, maxUint8 is initialized to the maximum value representable by a uint8, which is 255.</li><li>The overflow function attempts to add 1 to maxUint8, resulting in an integer overflow because the result (256) exceeds the maximum value representable by uint8.</li><li>Due to overflow, the result wraps around to 0, producing unexpected behavior.</li></ul><p>2. <strong>Integer Underflow Example</strong>:</p><pre>pragma solidity ^0.8.0;<br><br>contract IntegerUnderflow {<br>  <br>  uint8 public minUint8 = 0;<br><br>  function underflow() public view returns (uint8) {<br>    return minUint8 – 1; // Integer underflow occurs here results in 255 due to underflow<br>  }<br>}</pre><p><strong>Explanation</strong>:</p><ul><li>In this example, minUint8 is initialized to the minimum value representable by a uint8, which is 0.</li><li>The underflow function attempts to subtract 1 from minUint8, resulting in an integer underflow because the result (-1) falls below the minimum value representable by uint8.</li><li>Solidity does not have signed integer types, so underflow typically results in unexpected behavior, such as producing a large positive value (255) instead of the expected negative value.</li></ul><p><strong>Summary</strong>:</p><p>These examples demonstrate how integer overflow and underflow bugs can lead to unexpected behavior and vulnerabilities in Solidity contracts. It’s essential for developers to implement proper bounds checking and use safe arithmetic operations to prevent these types of bugs and ensure the correctness and security of their smart contracts.</p><h3><strong>Mitigation Steps</strong></h3><p>Here are mitigation steps for the contracts provided earlier to address integer overflow and underflow vulnerabilities:</p><p>1. <strong>Mitigation for Integer Overflow</strong>:</p><pre>pragma solidity ^0.8.0;<br><br>library SafeMath {<br><br>  function add(uint256 a, uint256 b) internal pure returns (uint256) {<br>    uint256 c = a + b;<br>    require(c &gt;= a, &quot;SafeMath: addition overflow&quot;);<br>    return c;<br>  }<br>}<br><br>contract IntegerOverflow {<br><br>  using SafeMath for uint8;<br><br>  uint8 public maxUint8 = 255;<br><br>  function overflow() public view returns (uint8) {<br>    return maxUint8.add(1); // Safe addition with overflow check<br>  }<br>}</pre><p><strong>Mitigation Steps</strong>:</p><ul><li>Implement safe arithmetic operations using a library like SafeMath.</li><li>Replace arithmetic operations (`+`, `-`, `*`, `/`, etc.) with equivalent functions from the SafeMath library.</li><li>Use the `add` function from SafeMath, which includes an overflow check to ensure that the result does not exceed the maximum value representable by the data type and it returns `1` instead of `0`.</li></ul><p>2. <strong>Mitigation for Integer Underflow</strong>:</p><pre>pragma solidity ^0.8.0;<br><br>library SafeMath {<br><br>  function sub(uint256 a, uint256 b) internal pure returns (uint256) {<br>    require(b &lt;= a, &quot;SafeMath: subtraction overflow&quot;);<br>    return a - b;<br>  }<br>}<br><br>contract IntegerUnderflow {<br>  <br>  using SafeMath for uint8;<br><br>  uint8 public minUint8 = 0;<br>  function underflow() public view returns (uint8) {<br>    return minUint8.sub(1); // Safe subtraction with underflow check<br>  }<br>}</pre><p><strong>Mitigation Steps:</strong></p><ul><li>Implement safe arithmetic operations using a library like SafeMath.</li><li>Replace arithmetic operations (`+`, `-`, `*`, `/`, etc.) with equivalent functions from the SafeMath library.</li><li>Use the `sub` function from SafeMath, which includes an underflow check to ensure that the result does not fall below the minimum value representable by the data type and it returns `1` instead of `-1`.</li></ul><p><strong>For more visit my Github</strong>: <a href="https://github.com/logesh21n/Solidity-Common-Vulnerabilities">https://github.com/logesh21n/Solidity-Common-Vulnerabilities</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ed958ba8ef9" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/common-vulnerabilities-integer-overflow-underflow-7ed958ba8ef9">COMMON VULNERABILITIES: INTEGER OVERFLOW / UNDERFLOW</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[COMMON VULNERABILITIES: REENTRANCY PART — II]]></title>
            <link>https://coinsbench.com/common-vulnerabilities-reentrancy-part-ii-98cb1719c0e2?source=rss-d25cd9352fc3------2</link>
            <guid isPermaLink="false">https://medium.com/p/98cb1719c0e2</guid>
            <category><![CDATA[smart-contract-auditing]]></category>
            <category><![CDATA[reentrancy-attack]]></category>
            <category><![CDATA[reentrancy-bug]]></category>
            <category><![CDATA[smart-contract-security]]></category>
            <dc:creator><![CDATA[Logesh N]]></dc:creator>
            <pubDate>Thu, 21 Mar 2024 06:51:38 GMT</pubDate>
            <atom:updated>2024-03-22T17:20:12.784Z</atom:updated>
            <content:encoded><![CDATA[<h3><a href="https://medium.com/p/3fe928489ef0?source=post_stats_page-------------------------------------">COMMON VULNERABILITIES: REENTRANCY PART — I</a>I</h3><p>To understand this concept please visit my previous post of <a href="https://medium.com/p/3fe928489ef0?source=post_stats_page-------------------------------------">COMMON VULNERABILITIES: REENTRANCY PART — I</a></p><h3><strong>Types of reentrancy</strong></h3><p>The reentrancy vulnerability is divided into four different types. They are,</p><ol><li>Single function reentrancy</li><li>Cross-function reentrancy</li><li>Cross-contract Reentrancy</li><li>Read-only Reentrancy</li></ol><h3>Single function reentrancy</h3><ol><li>In single-function reentrancy, the vulnerability occurs within the same function of a contract. This typically happens when the contract performs external calls to other contracts or accounts before completing its internal state changes.</li><li>An attacker exploits this vulnerability by recursively calling the same function of the contract before the previous call completes, allowing them to manipulate the contract’s state unpredictably.</li><li>Single function reentrancy vulnerability is often the result of improper sequencing of state changes and external calls within a function.</li><li>This type of attack is the simplest and easiest to prevent. It occurs when the vulnerable function is the same function the attacker is trying to recursively call. For example:</li></ol><pre>contract Vulnerable {<br>    mapping (address =&gt; uint) private balances;<br><br>    function withdraw() public {<br>      // Effects<br>      uint amount = balances[msg.sender]; <br>      // Interactions   <br>      (bool success, ) = msg.sender.call.value(amount)(&quot;&quot;);<br>      require(success);<br>      // Additional Effects (this line is vulnerable to Single function reentrancy)<br>      balances[msg.sender] = 0;<br>    }<br>}</pre><p>In the above code, the <em>withdraw()</em> function is vulnerable to a single function reentrancy attack. An attacker can repeatedly call the <em>withdraw()</em> function before updating the <em>balance</em>, resulting in multiple withdrawals.</p><h3><strong>Cross-function reentrancy</strong></h3><ol><li>Cross-function reentrancy involves multiple functions within the same contract. The vulnerability arises when one function makes an external call to another function before completing its own state changes.</li><li>An attacker can exploit this vulnerability by calling into the same contract from within the externally called function, potentially reentering the original function or other functions within the contract.</li><li>Cross-function reentrancy vulnerability can be challenging to detect as it involves interactions between different functions within the same contract.</li><li>This type of attack is more complex and harder to prevent. It occurs when the vulnerable function calls another function that is also vulnerable to reentrancy. For example:</li></ol><pre>contract Vulnerable {<br>    mapping (address =&gt; uint) private balances;<br><br>    function transfer(address to, uint amount) public {<br><br>        // Checks<br>        if (balances[msg.sender] &gt;= amount) {<br><br>        // Effects<br>        balances[to] += amount;<br>        balances[msg.sender] -= amount;<br><br>        // Interactions<br>        to.transfer(amount);<br>        }<br>    }<br><br>    function withdraw() public {<br><br>        // Checks<br>        uint amount = balances[msg.sender];<br><br>        // Interactions<br>        (bool success, ) = msg.sender.call.value(amount)(&quot;&quot;);<br>        require(success);<br><br>        // Effects<br>        balances[msg.sender] = 0;<br>    }<br>}</pre><ul><li>The <em>withdraw</em> function initiates a <em>transfer</em> of funds to the caller using a low-level <em>call</em>.</li><li>Before the function completes and sets the <em>balance</em> to zero, it does not prevent other functions (such as <em>transfer</em>) from being called.</li><li>An attacker can exploit this by calling the <em>withdraw</em> function and, during the <em>call</em>, reentering the contract through another function like <em>transfer</em>, taking advantage of the fact that the <em>balance</em> has not yet been set to zero.</li></ul><p>The <strong>Vulnerable</strong> contract does not strictly adhere to the <em>Checks-Effects-Interactions</em> pattern.</p><p>1. <strong>Transfer Function</strong>:</p><ul><li><strong>Checks</strong>: The <em>transfer</em> function checks if the sender (<em>msg.sender</em>) has a sufficient <em>balance</em> to perform the <em>transfer</em>. This check ensures that the <em>transfer</em> is only executed when the sender has enough funds.</li><li><strong>Effects</strong>: If the sender has a sufficient <em>balance</em>, the function updates the balances of the sender and the recipient accordingly.</li><li><strong>Interactions</strong>: There is no interactions in <em>transfer</em> function.</li></ul><p>2. <strong>Withdraw Function</strong>:</p><ul><li><strong>Checks</strong>: The <em>withdraw</em> function retrieves the balance of the caller (<em>msg.sender</em>) and uses it for the withdrawal. However, it does not explicitly check if the <em>balance</em> is greater than zero before initiating the withdrawal, which could lead to unnecessary gas expenditure if the balance is zero.(i.e, <em>amount = 0</em>)</li><li><strong>Effects</strong>: After retrieving the <em>balance</em>, the function initiates an <em>external call</em> using <em>msg.sender.call.value(amount)(“”)</em> to transfer funds to the caller. Then, it immediately sets the caller’s <em>balance</em> to zero.</li><li><strong>Interactions</strong>: The external call to transfer funds is performed before the state change of setting the balance to zero, violating the sequencing principle of the <em>Checks-Effects-Interactions</em> pattern.</li></ul><p>While the <em>transfer</em> function in the <strong>Vulnerable</strong> contract follows the Checks-Effects-Interactions pattern by performing state changes before interactions, the <em>withdraw</em> function violates this pattern by initiating an external call before completing its internal state changes. This violation exposes the contract to reentrancy vulnerabilities. To mitigate this vulnerability, developers should ensure that all state changes are completed before interacting with external contracts or accounts, following the Checks-Effects-Interactions pattern consistently across all contract functions.</p><h3><strong>Cross-contract Reentrancy</strong></h3><ol><li>Cross-contract reentrancy occurs when a contract interacts with external contracts, and the vulnerability lies in the interaction between different contracts.</li><li>An attacker exploits this vulnerability by recursively calling back into the vulnerable contract from within an external contract before the original call completes, potentially causing unexpected behavior or manipulating the state of the contracts involved.</li><li>This type of reentrancy vulnerability often arises when contracts trust external contracts to perform certain actions without properly validating or handling the consequences of the interactions.</li></ol><pre>contract Vulnerable {<br>    mapping(address =&gt; uint256) public balances;<br><br>    function withdraw(uint256 amount) public {<br><br>        // Checks: Whether the `user` has neccessary amount<br>        require(balances[msg.sender] &gt;= amount, &quot;Insufficient balance&quot;);<br><br>        // Effects: Update sender&#39;s balance<br>        balances[msg.sender] -= amount;<br><br>        // Interactions: External contract call<br>        ExternalContract externalContract = ExternalContract(msg.sender);<br>        externalContract.withdraw(amount);<br><br>        // Additional effects (this line is vulnerable to reentrancy)<br>        balances[msg.sender] += amount;<br>    }<br>}<br><br>contract ExternalContract {<br>    function withdraw(uint256 amount) external {<br>        // Some logic<br>        // Vulnerable to reentrancy attack<br>        msg.sender.call(&quot;&quot;);<br>    }<br>}</pre><p>In this example, the <em>withdraw</em> function of the <strong>ExternalContract</strong> is vulnerable to reentrancy. When called by the <strong>Vulnerable</strong> contract, an attacker can exploit this vulnerability to reenter the <strong>Vulnerable</strong> contract and manipulate the sender’s <em>balance</em>.</p><h3><strong>Read-only Reentrancy</strong></h3><ol><li>Read-only reentrancy is a specific type of reentrancy vulnerability where the attacker is limited to reading contract state during the reentrant call, without the ability to modify state directly.</li><li>While read-only reentrancy may seem less severe than other types, it can still lead to information leakage or manipulation of contract behavior based on the observed state.</li><li>This type of vulnerability may occur when contracts allow external calls to view certain state variables without adequate protection against reentrancy attacks.</li></ol><p>In the example below, a banking contract is presented that permits users to deposit and withdraw:</p><pre>import &quot;@openzeppelin/contracts/security/ReentrancyGuard.sol&quot;;<br><br>contract Bank is ReentrancyGuard {<br>    mapping (address =&gt; uint) public balances;<br><br>    function deposit() external payable {<br>        balances[msg.sender] += msg.value;<br>    }<br><br>    function withdraw() public nonReentrant {<br><br>        // Checks<br>        uint amount = balances[msg.sender];<br><br>        // Interactions<br>        (bool success, ) = payable(msg.sender).call{value: amount}(&quot;&quot;);<br>        require(success);<br><br>        // Effects<br>        balances[msg.sender] = 0;<br>    }<br>}</pre><p>The Bank contract protects itself against reentrancy issues by using OpenZeppelin’s ReentrancyGuard. Additionally, a third-party smart contract exists that uses the bank’s publicly available balances mapping for its own business logic, e.g. managing shares based on a user’s investment in the bank:</p><pre>contract BankConsumer {<br>    Bank private bank;<br><br>    constructor(address _bank) {<br>        bank = Bank(_bank);<br>    }<br>    function getBalance(address account) public view returns (uint256) {<br>        return bank.balances(account);<br>    }<br>}</pre><p>The bank’s `<em>withdraw</em>` function is safeguarded against reentrancy. Still, this guard only applies to the contract itself and does not extend to other systems. The execution flow of the external call in `<em>withdraw</em>` can be taken over by an attacker, who can then craft a smart contract that presents a misleading balance while interacting with other projects.</p><p>In this case, <strong>BankConsumer</strong> is such a project, merely exposing a <em>view</em> function for illustration purposes. Such a <em>view</em> function could be internally utilized elsewhere, e.g. for assigning shares and a check preventing users to liquidate more shares than they own. An outdated <em>balance</em> exposed by the <strong>Bank</strong> contract can be exploited by designing a malicious receive function:</p><pre>contract Attacker {<br>    event Checkpoint(uint256 balance);<br><br>    Bank private bank;<br>    BankConsumer private consumer;<br><br>    constructor(address _bank, address _consumer) payable {<br>        bank = Bank(_bank);<br>        consumer = BankConsumer(_consumer);<br>    }<br><br>    function attack() public {<br>        emit Checkpoint(consumer.getBalance(address(this)));<br>        bank.deposit{value: 1 ether}();<br>        bank.withdraw();<br>        emit Checkpoint(consumer.getBalance(address(this)));<br>    }<br><br>    receive() external payable  {<br>        emit Checkpoint(consumer.getBalance(address(this)));<br>        // more malicious code here<br>    }<br>}</pre><p>The Attacker contract records Checkpoint events, illustrating that the balances visible to the <strong>BankConsumer</strong> contract are outdated. When the system is set up in <strong>Remix</strong>, and the attack function is executed, the following events are logged by the Attacker contract:</p><pre>[<br>    {<br>        &quot;from&quot;: &quot;0xE3Ca443c9fd7AF40A2B5a95d43207E763e56005F&quot;,<br>        &quot;topic&quot;: &quot;0xde5ae8a37da230f7df39b8ea385fa1ab48e7caa55f1c25eaaef1ed8690f36998&quot;,<br>        &quot;event&quot;: &quot;Checkpoint&quot;,<br>        &quot;args&quot;: {<br>            &quot;0&quot;: &quot;0&quot;,<br>            &quot;balance&quot;: &quot;0&quot;<br>        }<br>    },<br>    {<br>        &quot;from&quot;: &quot;0xE3Ca443c9fd7AF40A2B5a95d43207E763e56005F&quot;,<br>        &quot;topic&quot;: &quot;0xde5ae8a37da230f7df39b8ea385fa1ab48e7caa55f1c25eaaef1ed8690f36998&quot;,<br>        &quot;event&quot;: &quot;Checkpoint&quot;,<br>        &quot;args&quot;: {<br>            &quot;0&quot;: &quot;1000000000000000000&quot;,<br>            &quot;balance&quot;: &quot;1000000000000000000&quot;<br>        }<br>    },<br>    {<br>        &quot;from&quot;: &quot;0xE3Ca443c9fd7AF40A2B5a95d43207E763e56005F&quot;,<br>        &quot;topic&quot;: &quot;0xde5ae8a37da230f7df39b8ea385fa1ab48e7caa55f1c25eaaef1ed8690f36998&quot;,<br>        &quot;event&quot;: &quot;Checkpoint&quot;,<br>        &quot;args&quot;: {<br>            &quot;0&quot;: &quot;0&quot;,<br>            &quot;balance&quot;: &quot;0&quot;<br>        }<br>    }<br>]</pre><p>The second Checkpoint event indicates that, during the <em>receive</em> function, the <strong>Bank</strong> contract still presents a <em>balance</em> of 1 ETH for the Attacker contract address despite the funds having been transferred to the attacker. This outdated information can be manipulated to mislead third-party infrastructure building on the Bank contract, such as <strong>BankConsumer</strong>.</p><h3><strong>Another Example</strong></h3><pre>contract Vulnerable {<br>    mapping(address =&gt; uint256) public balances;<br><br>    function viewBalance(address account) external view returns (uint256) {<br>        // Vulnerable to read-only reentrancy<br>        return balances[account];<br>    }<br>}<br><br>contract Attacker {<br>    Vulnerable vulnerableContract;<br><br>    constructor(address vulnerableAddress) public {<br>        vulnerableContract = Vulnerable(vulnerableAddress);<br>    }<br><br>    function viewAndManipulateBalance(address account) external {<br>        // Read the balance<br>        uint256 balance = vulnerableContract.viewBalance(account);<br><br>        // Manipulate contract behavior based on the observed balance<br>        if (balance &gt; 100) {<br>            // Do something<br>        }<br>    }<br>}</pre><p>In this example, the <em>viewBalance</em> function of the Vulnerable contract is vulnerable to read-only reentrancy. An attacker can call this function recursively, observing the <em>balance</em> of multiple accounts, and manipulate the behavior of another contract (<em>Attacker</em>) based on the observed balances.</p><h3><strong>Conclusion</strong></h3><p>Each type of reentrancy vulnerability presents unique challenges and risks, but they all share the common characteristic of allowing attackers to exploit the sequential execution of contract code to their advantage. Solidity developers should be aware of these vulnerabilities and follow best practices, such as using mutex patterns or reentrancy guards, to prevent and mitigate their impact.</p><p>To prevent reentrancy attacks, you should avoid making <em>external calls</em> in critical sections of your code, and use the <em>nonReentrant</em> modifier provided by the <em>OpenZeppelin</em> <em>library</em> or implement the <em>Checks-Effects-Interactions</em> pattern.</p><p><strong>For more visit my Github</strong>: <a href="https://github.com/logesh21n/Solidity-Common-Vulnerabilities">https://github.com/logesh21n/Solidity-Common-Vulnerabilities</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98cb1719c0e2" width="1" height="1" alt=""><hr><p><a href="https://coinsbench.com/common-vulnerabilities-reentrancy-part-ii-98cb1719c0e2">COMMON VULNERABILITIES: REENTRANCY PART — II</a> was originally published in <a href="https://coinsbench.com/">CoinsBench</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>