<?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 Gershon Ballas on Medium]]></title>
        <description><![CDATA[Stories by Gershon Ballas on Medium]]></description>
        <link>https://medium.com/@ggballas?source=rss-fad0e5d9d5fc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*SRqzevzNjOJRBr0_-8fKJg.jpeg</url>
            <title>Stories by Gershon Ballas on Medium</title>
            <link>https://medium.com/@ggballas?source=rss-fad0e5d9d5fc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 07:42:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ggballas/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[How to find, exploit, and mitigate reentrancy vulnerabilities in smart contracts]]></title>
            <link>https://medium.com/ginger-security/how-to-find-exploit-and-mitigate-reentrancy-vulnerabilities-in-smart-contracts-6fc69d847a23?source=rss-fad0e5d9d5fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/6fc69d847a23</guid>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[reentrancy-attack]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[crypto]]></category>
            <dc:creator><![CDATA[Gershon Ballas]]></dc:creator>
            <pubDate>Fri, 18 Nov 2022 01:47:13 GMT</pubDate>
            <atom:updated>2022-11-18T01:57:20.686Z</atom:updated>
            <content:encoded><![CDATA[<p>Reentrancy attacks are some of the most lethal vulnerabilities known to the cryptoverse. Heck, <em>the original DAO hack was a reentrancy exploitation</em> (<a href="https://etherscan.io/tx/0x0ec3f2488a93839524add10ea229e773f6bc891b4eb4794c3337d4495263790b">link</a>).</p><p>And unfortunately (or fortunately if you’re a bounty hunter / black-hat), despite years of them being known and understood, they still consistently happen in the wild. Just last week (Nov 10, 2022) there was an attack on DFX Finance, resulting in ~$5m in lost assets (<a href="https://twitter.com/DFXFinance/status/1590858722728972289">tweet</a>, <a href="https://etherscan.io/tx/0x6bfd9e286e37061ed279e4f139fbc03c8bd707a2cdd15f7260549052cbba79b7">transaction</a>).</p><p>But fear not! We’ve got you covered. Today we’re gonna learn about how to <strong>find</strong>,<strong> exploit</strong>, and<strong> mitigate</strong> reentrancy attacks, regardless of blockchain/language. 🧑‍💻</p><h3>Before we begin… what on earth is “reentrancy”?</h3><p>“Reentrancy” simply means causing a function to call (or <strong>re-enter</strong>) itself.</p><p>Wait… so you mean recursion?</p><p>Well, technically yes, it is recursion.</p><p>But in the context of <strong>blockchain security</strong>, it means:</p><ul><li>User calls a function in contract A</li><li>That function in contract A does a <strong>callback</strong> to a contract controlled by the user (contract B)</li><li>Contract B calls contract A again (it <strong>re-enters</strong> it)</li><li>Contract A may call contract B again, and vice-versa, until one of the contracts will stop</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*TQiQED_WxGUAW9Zs_XSHmw.png" /><figcaption>Reentrancy diagram</figcaption></figure><p>In that case, contract A is said to be “<strong>re-entrant</strong>”.</p><h3>Hmm.. so why is that insecure? Lots of contracts do callbacks!</h3><p>That’s true. And there’s nothing wrong with that.</p><p>In fact, every time you transfer an NFT (ERC-721), it does a callback to the receiving address (which of course, may then <strong>re-enter</strong> the calling function by calling it again).</p><p>So where is the problem here?</p><p>Let’s look at a simple Solidity example:</p><pre>interface IPointReceiver {<br>    function onPointReceived() public;<br>}<br><br>contract PointCounter {<br><br>    // Number of points each participant has<br>    mapping(addres =&gt; uint256) public points;<br><br>    // Function that allows first time participants to get a point for free<br>    function getFirstPointForFree() public {<br><br>        // CHECK that sender didn&#39;t already receive their free point<br>        require(points[msg.sender] == 0, &quot;Sender is not a first time participant&quot;);<br><br>        // INTERACT - Notify participant that they received a point via callback<br>        IPointReceiver(msg.sender).onPointReceived();<br><br>        // EFFECT - Give them that point<br>        points[msg.sender] += 1;<br>    }<br>}</pre><p>Looks good right? But what if I as the point receiver implement a contract like this:</p><pre>import &quot;../path/to/PointCounter.sol&quot;;<br><br>contract ExploitContract is IPointReceiver {<br>    PointCounter public constant TARGET = PointCounter(0x777788889999AaAAbBbbCcccddDdeeeEfFFfCcCc);<br><br>    function exploit() public {<br>        TARGET.getFirstPointForFree();<br>    }<br><br>    function onPointReceived() public {<br>        // Keep re-entering until we get at least 5 free points<br>        if (TARGET.points[address(this)] &gt;= 5) {<br>            return;<br>        }<br><br>        // Re-enter getFirstPointForFree() func<br>        TARGET.getFirstPointForFree();        <br>    }<br>}</pre><p>If you run the transaction in your head, beginning with <strong>ExploitContract</strong>’s <strong>exploit()</strong> function, you will see that:</p><ul><li><strong>exploit()</strong> calls <strong>getFirstPointForFree()</strong></li><li><strong>getFirstPointForFree()</strong>’s CHECK is successfully passed</li><li><strong>getFirstPointForFree()</strong> calls <strong>onPointReceived()</strong></li><li><strong>onPointReceived() </strong>calls <strong>getFirstPointForFree()</strong> again</li><li><strong>getFirstPointForFree()</strong>’s CHECK is successfully passed again! (since the EFFECT line wasn’t called yet)</li><li>…</li><li>This happens 5 times and our exploit contract gets 5 free points!</li></ul><p>Okay, so something f*cked up that shouldn’t have happened just did. But how do we formalize and generalize our understanding of it? How do we avoid such attacks?</p><h3>Mitigation #1: CHECKS — EFFECTS — INTERACTIONS</h3><p>If you look at the <strong>getFirstPointForFree()</strong> again you will see that it’s got three parts labeled:</p><ul><li>CHECKS — Checking that conditions are valid</li><li>INTERACTIONS — Interacting with other smart contracts, which may be controlled by a malicious actor (via callback)</li><li>EFFECTS — Changing the contract’s state (updating the <strong>points</strong> mapping)</li></ul><p>Most functions would have parts of them that could be categorized into one of those three.</p><p>Let’s list a couple of axioms:</p><ul><li>The EFFECTS part updates the state of the contract</li><li>The CHECKS part behaves in accordance to the contract state, and will only behave correctly if the state is up to date</li><li>Whenever there is an INTERACTIONS part, the function may be re-entered at that point</li></ul><p>Therefore:</p><ul><li>If the INTERACTIONS part happens before the EFFECTS part, it may be used to re-enter the function, and get to the CHECKS <strong>without having updated the contract state</strong></li><li>This could result in the CHECKS part allowing transactions that it shouldn’t (as it did in the example above — allowing us to claim yet another free point)</li></ul><p>This is exactly what happened in our example contract. It did:</p><p><strong>CHECKS — INTERACTIONS — EFFECTS</strong></p><p>Instead of:</p><p><strong>CHECKS — EFFECTS — INTERACTIONS</strong></p><p>And if you’re serious about blockchain security, you’ll wanna tattoo that so you don’t forget, like this guy did:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*RvKL0eHHIqUipipXILvMcg.png" /><figcaption>CHECKS-EFFECTS-INTERACTIONS</figcaption></figure><p>If you follow the checks-effects-interactions pattern, you will be safe from reentrancy attacks 100% of the time.</p><p>However, some contracts, like Uniswap and other AMM’s, do not follow the checks-effects-interactions pattern on purpose (in order to allow flash-loans, we won’t get into that here).</p><p>For that, there’s the <strong>reentrancy mutex</strong>.</p><h3>Mitigation #2: Reentrancy mutex to the rescue</h3><p>If there’s no conceivable benign circumstance under which your contract should be reentrant, you might as well forbid that altogether. You can simply do that by using a reentrancy mutex like so:</p><pre>contract PointCounter {<br>    uint256 private constant _NOT_ENTERED = 1;<br>    uint256 private constant _ENTERED = 2;<br><br>    uint256 private _status;<br><br>    // Number of points each participant has<br>    mapping(addres =&gt; uint256) public points;<br><br>    constructor() {<br>        _status = _NOT_ENTERED;<br>    }<br><br>    modifier nonReentrant() {<br>        require(_status == _NOT_ENTERED, &quot;Reentrancy blocked.&quot;);<br><br>        _status = _ENTERED;<br><br>        _;<br><br>        _status = _NOT_ENTERED;<br>    }<br><br>    // Function that allows first time participants to get a point for free<br>    function getFirstPointForFree() public {<br>        // CHECK that sender didn&#39;t already receive their free point<br>        require(points[msg.sender] == 0, &quot;Sender is not a first time participant&quot;);<br><br>        // INTERACT - Notify participant that they received a point via callback<br>        IPointReceiver(msg.sender).onPointReceived();<br><br>        // EFFECT - Give them that point<br>        points[msg.sender] += 1;<br>    }<br><br>}</pre><p>If you try the same exploit we did above, you’ll see that this time the reentrancy attack will fail with the message “Reentrancy blocked.”</p><p>Instead of implementing the <strong>nonReentrant()</strong> modifier by yourself, you can simply import OpenZeppelin’s <a href="https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol">ReentrancyGuard.sol</a>.</p><h3>Conclusion</h3><p>Reentrancy attacks are rather simple once you get the gist of it. The most important thing is to <strong>USE THE CHECKS-EFFECTS-INTERACTIONS PATTERN!</strong> (Unless you really know what you’re doing and there’s a good reason for you not to use it, like Uniswap with flash-loans). Either way, as an extra precautionary step, use a reentrancy guard modifier if there’s no reason that your contract/function should be reentrant.</p><p>In next week’s article we will look at an example of a reentrancy attack on StarkNet, a non-EVM blockchain. Stay tuned. 👀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6fc69d847a23" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ginger-security/how-to-find-exploit-and-mitigate-reentrancy-vulnerabilities-in-smart-contracts-6fc69d847a23">How to find, exploit, and mitigate reentrancy vulnerabilities in smart contracts</a> was originally published in <a href="https://medium.com/ginger-security">Ginger Security</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to hack (almost) any Starknet Cairo smart contract]]></title>
            <link>https://medium.com/ginger-security/how-to-hack-almost-any-starknet-cairo-smart-contract-67b4681ac0f6?source=rss-fad0e5d9d5fc------2</link>
            <guid isPermaLink="false">https://medium.com/p/67b4681ac0f6</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[starknet]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[crypto]]></category>
            <dc:creator><![CDATA[Gershon Ballas]]></dc:creator>
            <pubDate>Fri, 11 Nov 2022 16:38:58 GMT</pubDate>
            <atom:updated>2022-11-11T18:43:12.025Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>Disclaimer:</em></strong><em> This is not a hack in the underlying Starknet or Cairo architectures. Instead, it is a very common developer-introduced vulnerability that we’ve been seeing (and disclosing) in the wild. If you’re a Cairo developer — please read and understand this issue to prevent potential hacks in your dapps.</em></p><p>All of us around crypto know and love Starknet by Starkware… Vitalik himself seems to be a fan:</p><h3>vitalik.eth on Twitter: &quot;Eli and the Starkware team have made many crucial contributions to making SNARK and STARK tech more understandable and accessible. I learned a lot from them myself! https://t.co/wDnKJd95ho / Twitter&quot;</h3><p>Eli and the Starkware team have made many crucial contributions to making SNARK and STARK tech more understandable and accessible. I learned a lot from them myself! https://t.co/wDnKJd95ho</p><p>And it’s not for nothing. The Starkware team is absolute god-tier when it comes to ZK-scalability moon math. It’s the main reason their company has <a href="https://www.reuters.com/markets/wealth/blockchain-tech-firm-starkware-raises-100-mln-valued-8-bln-2022-05-25">recently become an $8 bln behemoth</a> and is the leading <a href="https://l2beat.com/scaling/tvl/">ZK-L2 technology by TVL</a> (dYdX and Immutable X both run using Starkware tech).</p><p>However…………. when it comes to Cairo, the language used for writing Starknet contracts…. the Starkware team made a huge flop. And I mean HUGE.</p><p>Today kids, we’re gonna learn about how pretty much any Cairo contract is hackable (potentially).</p><h3>The devil in the details — The Uint256 struct</h3><p><strong>Solidity</strong> has a number of native types developers can use:</p><ul><li><strong>bool</strong></li><li><strong>uint8</strong> to <strong>uint256</strong></li><li><strong>address</strong></li><li><strong>bytes1</strong> to <strong>bytes32</strong></li><li><strong>mapping</strong></li></ul><p>And a couple of others…</p><p><strong>Cairo</strong>, on the other hand, has exactly one type — <strong>felt</strong>.</p><p>The <strong>felt</strong> is a 252-bit type that can be used for anything — signed/unsigned ints, booleans, addresses, and even CairoVM bytecode.</p><p>Why 252 bits? The reason for that has to do with Starkware STARK moon math… you can read more about it <a href="https://www.cairo-lang.org/docs/hello_cairo/intro.html#field-element">here</a>.</p><p>So if you want to…</p><ul><li>represent a <strong>bool</strong> — you use a <strong>felt</strong></li><li>represent a <strong>uint8</strong> — you use a <strong>felt</strong></li><li>represent an <strong>address</strong> — you use a <strong>felt</strong></li><li>you get the point…</li></ul><p>But what if you want to represent a <strong>uint256</strong>? A <strong>felt</strong> is only 252 bits…</p><p>For that you’d need the <strong>Uint256</strong> struct, defined as such (<a href="https://github.com/starkware-libs/cairo-lang/blob/0ba3ff59c1c86f2a30adc8fd144eaacb22c48ce9/src/starkware/cairo/common/uint256.cairo">source</a>):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2cabcd32cc3d8d63120f8d8eca692098/href">https://medium.com/media/2cabcd32cc3d8d63120f8d8eca692098/href</a></iframe><p>A <strong>Uint256</strong> struct is composed of two felts — one to represent the <strong>low 128</strong> bits, and another to represent the <strong>high 128</strong> bits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*6wFHH3TlywjLR67DVnEy5Q.png" /><figcaption>Cairo Uint256 struct</figcaption></figure><p>So basically every Uint256 has 2*124 = 248 bits that are completely ignored and never get used.</p><p>But are they completely ignored? …. 👀</p><h3>”Comparison is the thief of joy”</h3><p>As you may have already guessed… those junk bits are not ignored.</p><p>Let’s look at how <strong>Uint256</strong> comparisons work in Cairo.</p><p>Instead of using &lt;, &gt;, and == like a normal language would for its most used int types, Cairo uses these functions instead:</p><ul><li><strong>uint256_lt()</strong> for &lt;</li><li><strong>uint256_gt()</strong> for &gt;</li><li><strong>uint256_eq()</strong> for ==</li></ul><p>Now let’s deep dive into the uint256_lt() func in order to see whether or not it really ignores those junk bits (<a href="https://github.com/starkware-libs/cairo-lang/blob/0ba3ff59c1c86f2a30adc8fd144eaacb22c48ce9/src/starkware/cairo/common/uint256.cairo">source</a>):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1355280b74cbf0c30d36ae87963d992f/href">https://medium.com/media/1355280b74cbf0c30d36ae87963d992f/href</a></iframe><p>We can see that it calls the <strong>is_le()</strong> func (used for comparing felts, <a href="https://github.com/starkware-libs/cairo-lang/blob/0ba3ff59c1c86f2a30adc8fd144eaacb22c48ce9/src/starkware/cairo/common/math_cmp.cairo">source</a>):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7183fcc06ad44e25f78f435e18a20b74/href">https://medium.com/media/7183fcc06ad44e25f78f435e18a20b74/href</a></iframe><p>I’ll save you the trouble of understanding how <strong>is_nn()</strong> works… what you need to know is that <strong>is_le()</strong> works as described — “Returns 1 if a &lt;= b. Returns 0 otherwise.”</p><p>Hint —<strong> is_le()</strong> looks at the whole 252-bits of the felt, not just the first 128!!! 🤦‍♂️</p><h3>Okay, okay… let’s backtrack a little</h3><p>Let’s say we have two <strong>Uint256</strong> structs, A and B.</p><p>A is:</p><ul><li>A.low = 0</li><li>A.high = 1</li><li>A should represent <strong>0</strong> + <strong>1</strong>*2¹²⁸ = 2¹²⁸ = 340282366920938463463374607431768211456</li></ul><p>B is:</p><ul><li>B.low = 1</li><li>B.high = 1</li><li>B should represent <strong>1</strong> + <strong>1</strong>*2¹²⁸ = 1+2¹²⁸ = 340282366920938463463374607431768211457</li></ul><p>(B is greater than A by 1).</p><p>Let’s run <strong>uint256_le(A, B)</strong>:</p><ol><li><strong>a.high == b.high</strong> is TRUE</li><li>returning<strong> is_le(a.low + 1, b.low)</strong> evaluates to returning<strong> is_le(0 + 1, 1)</strong></li><li><strong>is_le(0 + 1, 1)</strong> returns 1 (meaning TRUE)</li></ol><p>So <strong>uint256_le(A, B)</strong> evaluates to TRUE, just as expected (since A &lt; B).</p><p>So far so good 😌</p><p>But what if we gave the <strong>uint256_le()</strong> a malformed A? Specifically, an A whose <strong>low felt</strong>’s 129th bit has been turned on.</p><p>In this scenario, A_malformed is:</p><ul><li>A_malformed.low = 2¹²⁹</li><li>A_malformed.high = 1</li><li>A_malformed should represent <strong>0</strong> + <strong>1*2</strong>¹²⁸ = 2¹²⁸ = 340282366920938463463374607431768211456</li></ul><p>B is:</p><ul><li>B.low = 1</li><li>B.high = 1</li><li>B should represent <strong>1</strong> + <strong>1*2</strong>¹²⁸ = 1+2¹²⁸ = 340282366920938463463374607431768211457</li></ul><p>Running <strong>uint256_le(A_malformed, B)</strong> should produce the same result as <strong>uint256_le(A, B) </strong>(the junk bits in A_malformed should be ignored).</p><p>However, in reality:</p><ol><li><strong>a.high == b.high</strong> is TRUE</li><li>returning<strong> is_le(a.low + 1, b.low)</strong> evaluates to returning<strong> is_le(2¹²⁹ + 1, 1)</strong></li><li><strong>is_le(2¹²⁹ + 1, 1)</strong> returns 0 (meaning FALSE)</li></ol><p>It’s not the result we’d expect… 😨</p><p>Of course, the same trick (writing to the junk bits to f*ck up Uint256 comparisons) can be achieved by writing to the junk bits of the <strong>high felt</strong>.</p><p>So the Starkware team really flooked that one… Let’s see how we can exploit it.</p><h3>Exploitation</h3><p>The <strong>uint256_le()</strong> func is not the only one that is vulnerable to malformed inputs. Here is a partial list of other vulnerable functions:</p><h4>uint256_add()</h4><ul><li>will not produce malformed output</li><li>output can be made to be much higher than it should be</li></ul><h4>uint256_mul()</h4><ul><li>output can be made to be much higher than it should be</li><li>may produce malformed output as well</li></ul><h4>uint256_sub()</h4><ul><li>like <strong>uint256_add()</strong></li></ul><h4>uint256_lt()</h4><ul><li>result can be chosen either way via malformed input (as we’ve shown above)</li></ul><h4>uint256_eq()</h4><ul><li>func can be made to return FALSE even though inputs are equal</li></ul><p>The savvy among you can already imagine how this may be used to $$$exploit$$$. But if you wanna test your skills, check out the <a href="https://github.com/paradigmxyz/paradigm-ctf-2022/blob/main/cairo-auction/public/contracts/auction.cairo"><strong>cairo-auction</strong></a> challenge from the <a href="https://github.com/paradigmxyz/paradigm-ctf-2022">2022 Paradigm CTF challenge</a>. It may be solved using your newly-acquired knowledge.</p><h3>Mitigation and vulnerabilities in the wild</h3><p>Preventing malformed Uint256 vulnerabilities is fairly simple. Simply call the provided <strong>uint256_check()</strong> func on all Uint256 inputs and you’ll be fine.</p><p>Do Cairo devs actually do that? Mostly no.</p><p>We have not seen the <strong>uint256_check()</strong> func called on inputs in 100% of the contracts that we were tasked with auditing so far. In some of them, this has led to <strong>medium-severity vulnerabilities</strong> (we will not disclose project names since some of them are still being patched).</p><p>And I wouldn’t blame the devs for that. <strong>This Uint256 malformation issue cannot be found anywhere in the Cairo docs.</strong></p><h3>With our eyes on the future</h3><p>Luckily for us and for the Starkware team, Cairo 1.0 fixes all of that. In Cairo 1.0, Uint256 becomes a native type:</p><p><a href="https://medium.com/starkware/cairo-1-0-aa96eefb19a0">Cairo 1.0</a></p><p>(I’m assuming this means the Uint256 malformation check will be built in, but you never know… 😅)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=67b4681ac0f6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ginger-security/how-to-hack-almost-any-starknet-cairo-smart-contract-67b4681ac0f6">How to hack (almost) any Starknet Cairo smart contract</a> was originally published in <a href="https://medium.com/ginger-security">Ginger Security</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>