<?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[Zokyo_io - Medium]]></title>
        <description><![CDATA[Zokyo: Your Web3 security guardians. 👨‍💻🔒 We offer in-depth smart contract audits, rigorous penetration testing, insightful tokenomics design, and proactive threat intelligence to secure your blockchain projects. - Medium]]></description>
        <link>https://medium.com/zokyo-io?source=rss----adc3a5112af0---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Zokyo_io - Medium</title>
            <link>https://medium.com/zokyo-io?source=rss----adc3a5112af0---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 06:09:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/zokyo-io" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Formal Verification: Securing ERC-4626 Vaults with Certora Prover]]></title>
            <link>https://medium.com/zokyo-io/formal-verification-securing-erc-4626-vaults-with-certora-prover-c16f273a002f?source=rss----adc3a5112af0---4</link>
            <guid isPermaLink="false">https://medium.com/p/c16f273a002f</guid>
            <dc:creator><![CDATA[Nuno Teodoro]]></dc:creator>
            <pubDate>Wed, 12 Feb 2025 13:13:02 GMT</pubDate>
            <atom:updated>2025-02-12T13:13:02.502Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*pWv2CtQo3DBHEnUqvAJHYg.png" /></figure><h3>Overview</h3><p>Formal verification provides a rigorous method to mathematically prove that a smart contract adheres to its intended specifications, reducing the risk of vulnerabilities.</p><p>This article explores the process of formally verifying an ERC-4626 vault — a standardized tokenized yield-bearing vault — using Certora Prover. Certora Prover is a powerful rule-based verification tool that allows developers to define custom correctness properties and enforce them on Solidity smart contracts, ensuring their security before deployment.</p><p>We plan to publish additional articles covering more aspects of formal verification in our DeFi example. By the end of this article, you will understand how to set up and run a minimal formal verification using Certora Prover to enhance the security and reliability of smart contracts.</p><h3>Setup</h3><p>To formally verify the ERC-4626 vault, we need to prepare the necessary Solidity smart contracts and Certora files. This example is structured as a Foundry project, though the setup can be adapted to other frameworks. The key components are:</p><ul><li><strong>Smart Contracts</strong></li></ul><p>VaultERC.sol – The ERC-4626 vault implementation that is the subject of formal verification. This contract will be analyzed to ensure it adheres to the expected invariants.</p><p>MockAssetA.sol – A mock ERC-20 token that represents the underlying asset of the vault.</p><ul><li><strong>Certora Files</strong></li></ul><p>VaultERC.spec – Defines the formal verification rules for VaultERC.sol. This file contains the key properties we aim to prove.</p><p>VaultERC.conf – Specifies how Certora should execute the verification, including contract inputs, constraints, and other various configuration settings.</p><p>To run the verification, Certora Prover must be installed. Follow the official installation guide here: 👉 Certora Installation Guide</p><p>With the setup complete, we can focus later on defining verification rules in VaultERC.spec. It is worth noting that we use the Solmate library: forge install transmissions11/solmate</p><h3>Smart Contract Implementation</h3><h4><strong>1. MockAssetA: A Tailored ERC20 Implementation</strong></h4><p>For our testing task, we require an ERC20 token to act as the underlying asset for our ERC4626 vault. While we could use the standard Solmate ERC20 implementation without changes, it presents a challenge due to the use of unchecked arithmetic in its transfer and transferFrom functions:</p><p>unchecked {</p><p>balanceOf[to] += amount;</p><p>}</p><p>Under normal conditions, unchecked arithmetic is not an issue since the overflow is prevented by the fact that the sum of balances is not meant to exceed the ERC20 totalSupply which is guarded by safe maths operations. However, when applying Certora formal verification, the prover introduces <strong>havocing</strong>, a process that randomly manipulates storage variables under specific conditions. This can cause token balances to assume values that lead to overflows, complicating the verification process.</p><p>While we could constrain Certora’s havocing a variable in our specification files by adding an invariant and requiring it to be a precondition, a more straightforward solution right now is to modify the ERC20 implementation itself to strictly adhere to safe arithmetic. Since this token is merely a supporting asset in our tests, this modification does not impact our core ERC4626 contract behavior.</p><p><strong>Implementation: MockAssetA</strong></p><p>To address this, we introduce smart contract MockAssetA, an ERC20 token that overrides the transfer and transferFrom functions to remove unchecked arithmetic:</p><p>contract MockAssetA is ERC20 {</p><p>constructor(string memory name_, string memory symbol_, uint8 decimals_)</p><p>ERC20(name_, symbol_, decimals_) {}</p><p>function transfer(address to, uint256 amount) public override returns (bool) {</p><p>balanceOf[msg.sender] -= amount;</p><p>balanceOf[to] += amount;</p><p>emit Transfer(msg.sender, to, amount);</p><p>return true;</p><p>}</p><p>function transferFrom(address from, address to, uint256 amount) public override returns (bool) {</p><p>uint256 allowed = my allowance[from][msg.sender];</p><p>if (allowed != type(uint256).max) {</p><p>allowance[from][msg.sender] = allowed - amount;</p><p>}</p><p>balanceOf[from] -= amount;</p><p>balanceOf[to] += amount;</p><p>emit Transfer(from, to, amount);</p><p>return true;</p><p>}</p><p>}</p><h4><strong>2. VaultERC: The ERC4626 Implementation Under Test</strong></h4><p>Our primary contract under test is the VaultERC, which follows the ERC4626 standard for tokenized vaults. This contract extends ERC4626 and simply overrides totalAssets() which is a hard requirement by the base contract to reflect the current balance of the underlying asset held by the vault.</p><p><strong>Implementation: VaultERC</strong></p><p>pragma solidity &gt;=0.8.0;</p><p>import {ERC20} from &quot;solmate/tokens/ERC20.sol&quot;;</p><p>import {ERC4626} from &quot;solmate/tokens/ERC4626.sol&quot;;</p><p>import {Owned} from &quot;solmate/auth/Owned.sol&quot;;</p><p>contract VaultERC is Owned, ERC4626 {</p><p>constructor(address _asset)</p><p>Owned(msg.sender)</p><p>ERC4626(ERC20(_asset), &quot;Vault Wrapper&quot;, &quot;4626&quot;)</p><p>{}</p><p>function totalAssets() public view override returns (uint256) {</p><p>return asset.balanceOf(address(this));</p><p>}</p><p>}</p><h3>Formal Verification Specification: ERC4626.spec</h3><p>A spec file in Certora Prover is a formal verification script that defines the rules and constraints a smart contract must satisfy. It serves as the blueprint for how the prover checks correctness by specifying invariants, function behaviors, and assumptions about the smart contract’s state.</p><p>Unlike traditional testing, which relies on specific inputs and outputs, a spec file enables mathematical reasoning over all possible states, ensuring that the smart contract adheres to its intended logic under all conditions, including edge cases.</p><p>We first start the ERC4626.spec specification file by the following statement:</p><h4><strong>ERC4626.spec</strong></h4><p>Using MockAssetA as AssetA;</p><p>This line establishes an alias for the MockAssetA contract, allowing us to refer to it as AssetA throughout the spec file.</p><p>At this point we fill the methods block in the file. The methods block in Certora&#39;s specification file defines which functions from our smart contracts will be used during the verification process.</p><p>methods{</p><p>/// VaultERC methods</p><p>function asset() external returns address envfree;</p><p>function totalSupply() external returns uint256 envfree;</p><p>function deposit(uint256,address) external;</p><p>function mint(uint256,address) external;</p><p>function withdraw(uint256,address,address) external;</p><p>function redeem(uint256,address,address) external;</p><p>function totalAssets() external returns uint256 envfree;</p><p>...</p><p>}</p><p>These function declarations match the actual functions in the VaultERC (ERC4626) contract. Certora will verify their behavior based on the rules we define in the spec. Marking a method with envfree has two effects.</p><p>First, calls to the method from CVL do not require an explicit environment value as the first argument. Second, the Prover ensures that the method&#39;s implementation in the verified contract does not rely on any that is considered an environment variable (e.g. msg.sender).</p><p>During verification, the Prover does not solely execute functions from VaultERC. We must also define additional functions in the methods block to inform the Prover about other relevant methods it should consider.</p><p>function _.balanceOf(address) external =&gt; DISPATCHER(true);</p><p>function _.transfer(address,uint256) external =&gt; DISPATCHER(true);</p><p>function _.transferFrom(address,address,uint256) external =&gt; DISPATCHER(true);</p><p>function AssetA.balanceOf(address) external returns uint256 envfree;</p><p>function AssetA.allowance(address, address) external returns uint256 envfree;</p><p>function AssetA.transferFrom(address,address,uint256) external returns bool;</p><p>The first three entries do not specify a specific contract but instead use _ (a wildcard), meaning they apply to any contract that implements these methods. With DISPATCHER(true), these functions are treated as dispatcher summaries, allowing the Prover to dynamically resolve the actual implementation during the run. When executing these methods, the Prover will identify and apply the correct implementation from any contract included in the verification run, such as ERC20.sol, MockAssetA.sol, or others.</p><p>The last three entries explicitly reference AssetA, which is an alias for the MockAssetA contract. In this case, the Prover directly resolves these method implementations from MockAssetA.sol.</p><h4>Ghost variables and hooks</h4><p>At this stage, we define ghost variables, which serve as an ‘extension’ of the state of the contracts under verification.</p><p>ghost mathint sumOfBalances {</p><p>init_state axiom sumOfBalances == 0;</p><p>}</p><p>init_state axiom sumOfBalances == 0; → Ensures that sumOfBalances is initialized to zero in the initial state. Without an init_state axiom, the value of sumOfBalances would be havoced (randomized).</p><p>The role of this ghost variable is to track the total sum of balances across all users throughout the run.</p><p>To make this ghost variable meaningful, we define hooks, which allow us to attach Certora Verification Language (CVL) code to specific low-level operations, such as reading from (Sload) or writing to (Sstore) storage variables.</p><p>Each hook consists of:</p><ul><li>A pattern that determines which operations will trigger the hook.</li><li>A code block that executes when the specified operation occurs. Here’s an example:</li></ul><p>hook Sstore balanceOf[KEY address a] uint256 newValue (uint256 oldValue) {</p><p>sumOfBalances = sumOfBalances + newValue - oldValue;</p><p>}</p><p>This is triggered whenever the contract updates the storage of the balanceOf mapping for an arbitrary address a. The hook adjusts the total sum by adding the new balance and subtracting the old balance, ensuring that sumOfBalances correctly tracks all balance changes.</p><p>Another example:</p><p>hook Sload uint256 val balanceOf[KEY address a] {</p><p>require sumOfBalances &gt;= val;</p><p>}</p><p>This is triggered whenever the contract reads a value from the balanceOf mapping in storage. It ensures that the total recorded sum of balances is always greater than or equal to the individual balance being read. This prevents inconsistencies, especially in cases where storage values could be havoced (randomized) during verification.</p><h4><strong>Invariants</strong></h4><p>The final step in the spec file is defining the invariant, which specifies a property that must always hold true throughout the execution of the contract.</p><p>Here is the invariant we define:</p><p>invariant totalSupplyIsSumOfBalances()</p><p>totalSupply() == sumOfBalances;</p><p>This condition is straightforward — it asserts that the totalSupply() of the vault token must always be equal to sumOfBalances, which represents the sum of all balances in the balanceOf mapping.</p><p>Since we previously defined hooks to track updates to sumOfBalances, we know that it correctly reflects the cumulative balance of all token holders.</p><p>This invariant is crucial because it ensures that the total supply of tokens is always consistent with the sum of individual balances. If it is ever violated, it indicates an inconsistency in how tokens are being minted, burned, or transferred, requiring further investigation to identify a potential bug.</p><h4>Running the spec file for verification</h4><p><strong>Writing the conf file</strong></p><p>Once we have defined the ERC4626.spec file containing the formal verification rules, the next step is to run the Certora Prover to check whether our ERC4626 implementation adheres to that expected property. This requires configuring a .conf file to specify the contracts involved, the verification setup and other configuration settings.</p><ul><li><strong>Setting Up the Configuration File</strong></li></ul><p>The following configuration file, ERC4626.conf, defines the inputs and settings for the verification process:</p><p>{</p><p>&quot;files&quot;: [</p><p>&quot;src/VaultERC.sol&quot;,</p><p>&quot;src/mocks/MockAssetA.sol&quot;</p><p>],</p><p>&quot;verify&quot;: &quot;VaultERC:certora/VaultERC.spec&quot;,</p><p>&quot;link&quot;: [&quot;VaultERC:asset=MockAssetA&quot;],</p><p>&quot;optimistic_loop&quot;: true,</p><p>&quot;rule_sanity&quot;: &quot;basic&quot;,</p><p>&quot;msg&quot;: &quot;ERC4626 certora formal verification&quot;</p><p>}</p><p>With the configuration file in place, we can initiate the test by executing the following command:</p><p>certoraRun certora/ERC4626.conf</p><p>Once the verification process is completed, Certora will generate a detailed verification report containing:</p><p>✅ Successful Checks — Indicating which properties held true across all possible executions. <br>❌ Failed Checks — Showing violations of the defined rules or invariants.</p><h3><strong>Viewing the Results</strong></h3><p>To inspect the results, Certora provides an output link to its verification dashboard, where a structured breakdown of the results is available.</p><p>The following snapshot presents the test results of this run via the Certora Prover. Initially, the totalSupply variable in the VaultERC contract and the ghost variable sumOfBalances were both havoced and assigned a value of zero before execution.</p><p>The verification test executes a deposit function call with an amount of 0x1128. As expected, both totalSupply and sumOfBalances increase by this exact value, maintaining consistency between the two. This confirms that the total supply of vault tokens correctly reflects the sum of all balances, thereby satisfying the defined invariant.</p><p>It’s important to note how the Certora Prover operates: it attempts to find counterexamples where our defined rules or invariants fail. If it cannot find a violation, it presents one valid example among an infinite number of possible executions where the invariant holds. The image shows such a successful case, reinforcing the correctness of our ERC4626 implementation for this particular scenario.</p><h4><strong>Testing the test!</strong></h4><p>Now, someone proposed a genius implementation (sarcasm intended) that gives away extra minted shares to the owner, modifying the afterDeposit function as follows:</p><p>function afterDeposit(uint256, uint256 shares) internal override {</p><p>balanceOf[owner] += shares / 100;</p><p>}</p><p>This modification was added to VaultERC, where afterDeposit() is an ERC4626 hook that gets triggered after calling deposit and mint.</p><h4><strong>Running the Prover with This Change</strong></h4><p>After executing the verification process with this new implementation, the test results in the screenshot reveal a failure in both mint and deposit.</p><p>The invariant failed to invoke mint and deposit because the balanceOf mapping was modified to grant additional shares to the contract owner. However, totalSupply was not updated accordingly, causing an inconsistency. This led to a mismatch between totalSupply and sumOfBalances, breaking our invariant.</p><p>As a result, the prover correctly detected the issue, demonstrating that this code mutation violates the expected ERC4626 behavior by causing an imbalance between total supply and individual balances. The purpose of introducing this intentional bug was to verify that our spec file can effectively catch such violations. This approach helps ensure that our test is robust and capable of identifying real issues.</p><h3>Conclusion</h3><p>Formal verification using Certora Prover has proven to be a powerful tool for ensuring the correctness of our ERC4626 implementation. Through our test, we confirmed that valid implementations passed that verification, while intentional code mutations introducing inconsistencies were successfully detected. This demonstrates the effectiveness of our specification file in catching bugs and maintaining the integrity of the ERC4626 vault.</p><p><a href="https://github.com/beber89/erc4626-formal-verification">You can find an example in this GitHub repository.</a></p><p>By leveraging formal verification, we gain a higher level of confidence in the security and correctness of our contract, reducing potential vulnerabilities before deployment. This method complements traditional testing approaches by ensuring that the contract behaves correctly under all possible conditions, not just predefined test cases.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c16f273a002f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zokyo-io/formal-verification-securing-erc-4626-vaults-with-certora-prover-c16f273a002f">Formal Verification: Securing ERC-4626 Vaults with Certora Prover</a> was originally published in <a href="https://medium.com/zokyo-io">Zokyo_io</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Art of Writing Security Reports]]></title>
            <link>https://medium.com/zokyo-io/the-art-of-writing-security-reports-a5cd3b971d30?source=rss----adc3a5112af0---4</link>
            <guid isPermaLink="false">https://medium.com/p/a5cd3b971d30</guid>
            <dc:creator><![CDATA[Nuno Teodoro]]></dc:creator>
            <pubDate>Fri, 07 Feb 2025 12:36:03 GMT</pubDate>
            <atom:updated>2025-02-11T15:59:04.649Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4GgXO-uPhRWj4s20zXqnvg.png" /></figure><h3>Introduction</h3><p>Greetings security researchers!</p><p>As auditors, it’s our job to aid our fellow developers in securing their protocols thus making Web3 a safer place for finance. However, no matter the quality of the source code review, if the report presented to the developer is subpar and unclear, the audit itself is useless.</p><p>The developer doesn’t oversee the actual source code review so remember: <strong>the way you write and showcase your findings is the product of your work.</strong> Take pride in this, as this is exactly what the developer is paying for.</p><p>Through the years we’ve read countless reports and provided a lot of feedback on them. Now it’s time to cover the most common issues found in reports, breaking down the various aspects of a finding, and explaining why writing a good report is a core requisite to becoming a skilled security researcher.</p><h3>Report Structure</h3><h4><strong>Title</strong></h4><p>This is the first thing developers and/or business people will read. It should be easily understandable after reading the entire issue, even for non-technical folks.</p><p>A structure that’s used for this is (some examples):</p><ul><li>“Root Cause In SomeContract May Lead To Some Impact/Vulnerability Resulting In Some Damage”</li><li>“Strict Equality in the Staking Contract May Lead To a Denial Of Service Resulting in Stuck Funds”</li><li>“Checks, Effects, and Interactions (CEI) Pattern Is Not Followed in the Withdrawal Function of the Staking Contract May Lead To Reentrancy Resulting in the Theft Of Funds”</li></ul><h4><strong>Summary</strong></h4><p>A high-level overview of the issue and its impact, summarizing the entire report. At Zokyo, we primarily work with developers, so summaries are usually omitted. However, when included, they serve as an executive summary for business stakeholders.</p><h4><strong>Description</strong></h4><p>A more detailed technical description of the issue and where it can be found in the code describing why it’s an issue are needed. A good structure for this is “the code currently does this, but it’s supposed to do that. This is an issue because…”. This is what developers will be interested in as this contains the technical bulk of the details for your bug.</p><p>For example:</p><ul><li>The VotingEscrow contract is responsible for distributing weights depending on time and what users are voting for. Users can deposit and withdraw their tokens which will allow them to be checkpointed and thus determining which user voted for what. There exists a function deposit_for_admin which allows anybody including smart contracts to deposit for someone else but cannot extend their lock time and deposit for a new user.</li><li>The issue lies at the bottom of this function where it will assert that the balance of native tokens within the contract is zero. A malicious user can deploy a contract containing the self destruct opcode (whilst deprecated, still works) to bypass the checks when receive is triggered and ultimately force native token into the contract.</li></ul><h4><strong>Impact</strong></h4><p>This will be an articulation of <strong>why</strong> your issue is important for the developer to fix. What would happen if some hacker exploited this issue or the issue was shipped to staging without a fix? Theft of funds? Bypassing of fees? Denial of service? Frontrunning? It’s up to you to articulate a meaningful impact in your finding so that the developer understands the severity of your issue and will be less likely to acknowledge it or refuse to fix it.</p><p>If you can’t demonstrate or formulate impact, it’s likely that your issue is invalid. It’s also recommended that you justify your severity rating under this section. For example:</p><ul><li>The assertion will always fail causing functionalities (including various functionalities for the FeeDistributor contract) relating to deposit_for_admin to be bricked. This was rated a Critical in severity because it’s an incredibly easy and cheap attack to trigger where the absolute minimal amount needs to be forced into the target contract. In addition to this, the issue also affects other contracts as the deposit_for_admin function is relied upon for compounding.</li></ul><h4><strong>Proof of Concept</strong> (Optional, but Highly Recommended)</h4><p>A Proof of Concept (PoC) is essential to proving that a reported issue is valid. It helps developers quickly understand and verify the vulnerability. For critical issues, a PoC is mandatory unless the issue is self-explanatory or straightforward.</p><p>To maintain clarity in the report, create a <strong>unit test</strong> and host it in a GitHub Gist. Then, provide a high-level overview of what’s happening in your PoC and paste the link at the end of the description.</p><p>Make sure your PoC is:</p><ul><li><strong>Straightforward</strong> — Clear and easy to follow.</li><li><strong>Runnable</strong> — Provide all necessary setup details.</li><li><strong>Well-commented</strong> — Help developers quickly grasp the exploit.</li></ul><p><a href="https://gist.github.com/chris-zokyo/ab7b8014cb4e8e82dfd87cf56d9c0a40#file-mytest-t-sol-L184-L205"><strong>Example PoC (Foundry Test)</strong></a></p><p>If the developer is unsure about running your PoC, specify the <strong>framework</strong> used and include a full file with the required setup. Bonus points if the PoC is well-structured and documented.</p><h4><strong>Recommendations</strong></h4><p>This is probably the most important part of the finding. This is <strong>exactly</strong> what the developers are paying for when they hire you as a security researcher — to help secure their code by demonstrating what they can do to fortify their code further. The best security review money can buy for a set of contracts is of no use if the recommendations are poorly communicated.</p><p>Provide crystal clear recommendations on how the issue can be fixed (no beating around the bush) and some example code on what they can do to refactor the code to prevent the possibility of exploitation for medium to high complexity (NOT severity, complexity) bugs.</p><p>Developers may read your issue without code and interpret it incorrectly and thus accidentally implement the wrong fix, which may lead to an alternate exploit path. Providing a clear, working example of code or a clear articulation of how you would fix this issue prevents this possibility. For example:</p><ul><li>It is recommended that the assertion statement is modified to store the balance before the execution of the deposit_for_admin and check against this value after execution in place of the original assertion. This can be done by refactoring the function to the following: <br> function deposit_for_admin(<br> address _addr,<br> uint256 _value,<br> address _deposit_token,<br> address _transfer_from<br> ) external payable nonReentrant notUnlocked onlyRole(OPERATOR_ROLE) {<br> uint256 balanceBefore = address(this).balance;<br> ============================== SNIP ============================== <br> assert(balanceBefore == address(this).balance); <br>}</li></ul><h3>Correct Judgement of Severity</h3><p>A common issue in report writing is over-inflation of severity for a particular finding without sufficient justification. It is important for security researchers to present a finding with the correct judgement of severity (without over inflation of severity) so that developers can prioritise which issues require fixing first and give the correct gauge of their risks. The following definitions for each severity:</p><h4><strong>Critical</strong></h4><p>Very easy to exploit with a very high amount of economic damage caused to the protocol and/or its users. A reasonable protocol team must <strong>NOT </strong>accept this to be within their risk appetite under any circumstances. Proof of concept is desirable as this is an issue of the highest severity where there should not be a shadow of a doubt of its existence.</p><p>A direct loss or theft of funds (<strong>principal but NOT yield/fees</strong>) without limitations or influence of external conditions (edge cases). Denial of service conditions must have funds locked for more than or equal to 1 year without any chance of releasing those funds during this time period (including via admin functions). This may also include a gross violation of access controls which can cause the total loss of ownership of a contract or aid in the full takeover of the target contract or governance such as voting manipulation.</p><h4><strong>High</strong></h4><p>Results in the direct theft, loss, or freezing of funds (<strong>yield or fees, but</strong> <strong>NOT principle</strong>) with little to some limitations of external conditions where if such conditions exist, causes a high amount of economical damage to a protocol. Issues classed with this severity may also be slightly harder to exploit than critical issues.</p><p>High-severity issues include denial of service conditions that can interrupt or freeze funds in the protocol for more than or equal to a year without any chance of releasing those funds (use of admin rescue functions are acceptable to meet the criteria of high severity, but not critical). A violation of access controls that grant the attacker limited privileges resulting in some disruption to the protocol’s day-to-day operations, but not a full contract takeover, is also considered high severity.</p><h4><strong>Medium</strong></h4><p>A successful exploit results in the theft, loss, or freezing of funds <strong>but requires certain external or edgecase conditions to be met. </strong>This<strong> </strong>includes specific states or relies on human interaction/error where if the bug is triggered, it may result in major economic damage or gross violation of access controls. Any reasonable protocol team must <strong>not </strong>accept that this is within their risk appetite.</p><p>Core functionality for a contract could be broken due to poor coding practices resulting in reverts or logic errors rendering the contract useless if it’s deployed in its current state. Front-running issues that do not meet the impact criteria of High and Critical severity bugs or Denial of service conditions may also be classed as medium in severity if: funds are lost for less than a year (impermanent) or admin rescue functions are used to get the stuck contracts running again.</p><h4><strong>Low</strong></h4><p>Findings under the Low severity class are generally very rarely triggered or require significantly exceptional circumstances to be met. The impact of the vulnerability is minor or may only be just an inconvenience to the protocol team<strong> BUT still presents a security risk</strong> should the issue go unfixed.</p><p>The conditions that require exploitation to be successful may be significantly rare or require a trusted actor to behave maliciously, which includes centralisation issues. In addition to this, sanity checks in which invalid parameters are supplied to a function/constructor/initializer by an admin and result in the unlikely damage to the contracts may also be classed as low in severity.</p><h4><strong>Informational</strong></h4><p>This issue is not lower nor higher in severity than Low, Medium, High, or Critical issues, these are separate issues in their own right and do <strong>NOT </strong>represent a security risk. These issues are raised with the protocol team to recommend best engineering practices and suggest a more efficient way to refactor a function.</p><p>Informational findings may include an attack vector without a security risk (for example a reentrancy attack vector where no funds can be extracted from the contract), which will prompt the security team to make a suggestion. In this case, it could be a reentrancy guard that prevents the attack vector to be used by a malicious actor should there be an attackpath undiscovered by the auditing team. Gas inefficiencies may also fall under the informational rating.</p><h3>Spelling and Grammar</h3><p>When you’re writing your reports, please take into consideration your spelling and grammar as obvious mistakes make the report writer look careless. It’s recommended to utilize any tools you can get your hands on. This will help automate spelling and grammar correction, if this is something you struggle with, thus resulting in higher quality reports.</p><p>Form clear concise sentences to get your point across to the developer. The best way to think about this is to assume that the reader doesn’t know the context of your finding. For example:</p><ul><li>Google spell checker (Available on Google Docs: right-click underlined red or blue and select the correct terminology or spelling)</li><li>ChatGPT (Please take care when pasting sensitive information)</li><li>Grammarly (Paid tool but very effective)</li></ul><h3>Polishing &amp; Submission</h3><p>Once you finish the audit, insert your issues straight into the main draft report, taking care of duplicate issues and styling. Should there be duplicates, paste in your issue and leave a comment referencing the original issue so they can be consolidated for the best possible issue.</p><p>The project manager will divide the issues amongst the auditors for review. For example: issues 1–10 will be reviewed by Alice, 11–20 reviewed by Bob, 21–30 by Charlie, etc. Alternatively, they could be distributed in a random order depending on what the project manager sees fit for the situation and amount of issues.</p><p>Review these issues in accordance with our standards to assess the validity of the issues and provide honest feedback to the auditor, in addition to a justification of your feedback.</p><p>Leave comments within the audit document once the client has provided their remarks. For resolved issues, include a reference to the resolution in GitHub. For unresolved issues, add a comment explaining why the issue remains unresolved or suggesting how it could improved further.</p><h4><strong>Styling</strong></h4><p>Please do try to keep consistent styling with the rest of the issues in the document seeing as we do not have different fonts for different issues. For example:</p><ul><li>Font: Arial</li><li>Font Size: 11</li><li>In sentence code: using default backticks (``)</li><li>In line code: Roboto Mono (Normal), size 10.5, using light grey highlight (as shown below)</li></ul><p>function deposit_for_admin(<br> address _addr,<br> uint256 _value,<br> address _deposit_token,<br> address _transfer_from<br> ) external payable nonReentrant notUnlocked onlyRole(OPERATOR_ROLE) {<br> // Some code here<br> if(_value == 0) {<br> revert(“Value must be more than zero!”);<br> }<br>}</p><h3>Conclusion</h3><p>A well-structured audit report is key to getting vulnerabilities fixed and maximizing payouts in bug bounties.</p><p>The way you present findings determines how effectively developers can address vulnerabilities. By structuring reports clearly, providing actionable recommendations, and maintaining high professional standards, you ensure that your work has real-world impact.</p><p>At Zokyo, we take pride in not only identifying issues but also ensuring they are well-communicated and resolved. A great report today leads to a safer Web3 tomorrow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5cd3b971d30" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zokyo-io/the-art-of-writing-security-reports-a5cd3b971d30">The Art of Writing Security Reports</a> was originally published in <a href="https://medium.com/zokyo-io">Zokyo_io</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Signature Malleability: Risks, Attacks, and Solutions]]></title>
            <link>https://medium.com/zokyo-io/signature-malleability-risks-attacks-and-solutions-0c1c752e944f?source=rss----adc3a5112af0---4</link>
            <guid isPermaLink="false">https://medium.com/p/0c1c752e944f</guid>
            <dc:creator><![CDATA[Nuno Teodoro]]></dc:creator>
            <pubDate>Thu, 09 Jan 2025 12:48:59 GMT</pubDate>
            <atom:updated>2025-01-09T12:48:58.993Z</atom:updated>
            <content:encoded><![CDATA[<p>Learn practical mitigation methods to secure smart contracts against signature malleability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FOq5Js6gBEMQUW34AR45eg.png" /></figure><h3>1. How signatures are used within Smart Contracts</h3><p>Signatures in smart contract functions are fundamental for ensuring security, authenticity, and non-repudiation in decentralized systems.</p><p>A signature, typically generated using asymmetric cryptography, serves as proof that a transaction or function call has been authorized by the private key owner. This mechanism is essential because, in blockchain networks, there is no central authority to verify identities or permissions. Instead, the validity of a function call relies on the cryptographic signature associated with it, which can be verified using the public key corresponding to the private key.</p><p>When a user wishes to interact with a smart contract, they sign the transaction data (which may include details like the contract address, the specific function to be called, and the parameters for the function) using their private key. The signature ensures that only the rightful owner of the private key can initiate the action.</p><h4><strong>Advanced Functionalities</strong></h4><p>Signatures also enable more advanced functionality, such as off-chain computation and delegation of actions.</p><p>For example, a user can sign a message or data off-chain, allowing another party to submit this signed data to a smart contract to execute the permitted action. This approach is widely used in cases like gasless transactions, where the signer does not directly pay the gas fee but authorizes another party (often a relayer) to perform the transaction on their behalf. This improves usability by reducing the burden on end-users.</p><p>Furthermore, off-chain signatures are utilized in meta-transactions, where users sign messages indicating their intent, and these are later relayed to the blockchain. This saves on-chain computation costs, enhances scalability, and provides flexibility for applications like DeFi protocols, NFT marketplaces, and voting systems.</p><p>In these scenarios, the signature serves as a binding authorization, ensuring that the smart contract executes only the exact actions approved by the signer. The smart contract checks the validity of the signature, confirms that the signer has granted the specific permissions encoded in the signed message, and rejects any unauthorized submissions. This pattern reinforces decentralized trust and opens up efficient, user-friendly ways to interact with blockchain-based applications.</p><h4><strong>Key Considerations</strong></h4><p>Ensuring that signatures are correctly handled by smart contracts is critically important, as mishandling them can lead to severe vulnerabilities, malfunctions, or exploitation.</p><p>Smart contracts operate autonomously and cannot be modified once deployed, so any flaw in how signatures are validated can result in irreversible consequences. For instance, if a contract does not properly verify the authenticity of a signature or the permissions it grants, malicious actors could forge transactions or execute unauthorized actions, undermining the security of the system.</p><p>A common risk arises from improperly implemented signature verification logic. If the contract fails to confirm that the signer is indeed the intended party (as determined by the public key), it may execute actions on behalf of unauthorized users.</p><p>Similarly, overlooking critical aspects such as ensuring that the signed message corresponds to the specific action being performed or validating that the signature hasn’t already been used (to prevent replay attacks) can lead to unintended behavior. For example, a failure to check for a nonce or timestamp might allow attackers to reuse a valid signature in a different context, compromising the integrity of the contract.</p><p>In this article, we are focusing on a specific attack: <strong>signature malleability</strong>.</p><h3>2. Understanding Signature Malleability</h3><p>As mentioned earlier in this article, signatures are used by smart contracts to ensure that a specific action has been authorized or submitted by a particular user. However, in the case of signature malleability, an attacker can modify a valid signature in such a way that the altered version is still valid for the same action.</p><p>As a result, there will be two different signatures that can authenticate the same action, both considered valid by the system. This exploit, known as signature malleability, can create significant vulnerabilities, as it undermines the uniqueness and immutability that signatures are meant to provide.</p><p>This issue is particularly problematic when smart contracts rely on signatures to track unique transactions or approvals. If multiple valid signatures exist for the same action, it may allow replay attacks, duplicate transaction execution, or other unintended behaviors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/0*nfZWz_iGfqvKZsCx.png" /></figure><h3>3. ECDSA Signatures</h3><p><strong>ECDSA (Elliptic Curve Digital Signature Algorithm)</strong> is a cryptographic algorithm used for signing and verifying messages, commonly in blockchain systems like Bitcoin, as well as in various security protocols. It is based on elliptic curve cryptography (ECC), which is a form of public-key cryptography that uses the algebraic structure of elliptic curves over finite fields. Here’s a breakdown of ECDSA signatures:</p><h4><strong>Components of ECDSA</strong></h4><p>ECDSA signatures consist of two components: <strong>r</strong> and <strong>s</strong>. These values are generated through the following process:</p><ol><li><strong>Private Key</strong>: This is a secret key, known only to the signer, that is used to generate the signature.</li><li><strong>Message</strong>: The data to be signed (a transaction, document, etc.) is first hashed, typically using a hash function like SHA-256.</li><li><strong>Random Value (k)</strong>: A random integer chosen for each signature to ensure uniqueness and security.</li><li><strong>Signature Generation:<br>- </strong>The message is hashed. <br>- A random number (k) is generated and used in an elliptic curve point multiplication. <br>- Using the private key and k, a pair of numbers (r, s) is created. These values are the signature components.</li><li><strong>Signature (r, s)</strong>: The result of the above process is the signature, which is typically represented as a pair of integers (r, s).</li></ol><h4><strong>Signature Verification</strong></h4><p>To verify a signature, the recipient needs the <strong>public key</strong> (which corresponds to the private key used to generate the signature), the message, and the signature (r, s).</p><ol><li>The message is hashed.</li><li>The verification process uses elliptic curve mathematics to check that the signature (r, s) corresponds to the public key and the hash of the message.</li><li>If the verification algorithm confirms that the signature is valid, the message is authenticated as coming from the owner of the private key.</li></ol><h4><strong>Key Properties of ECDSA</strong></h4><ul><li><strong>Security</strong>: The security of ECDSA is based on the difficulty of the <strong>Elliptic Curve Discrete Logarithm Problem (ECDLP)</strong>, which makes it computationally infeasible to derive the private key from the public key or the signature.</li><li><strong>Compactness</strong>: ECDSA signatures are shorter and more efficient than those based on other algorithms like RSA, making them particularly suitable for environments with limited resources, such as mobile devices or blockchain systems.</li></ul><h3>4. Mathematics of ECDSA</h3><p>To understand the mathematics behind <strong>Elliptic Curve Cryptography (ECC)</strong>, <strong>ECDSA (Elliptic Curve Digital Signature Algorithm)</strong>, and the components of an ECDSA signature — <strong>v, r, and s</strong> — we need to break it down into a few key parts. Let’s go step-by-step to understand these concepts mathematically.</p><h4><strong>Elliptic Curves and Their Mathematical Definition</strong></h4><p>An <strong>elliptic curve</strong> is defined by an equation of the form: <br><strong>y2=x3+ax+b (mod p)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/248/0*voOLAoymfMAonXx7.png" /></figure><p>Image Source: <a href="https://www.desdevpro.com/static/beb70fb9a58907f2431f230f232fa79f/544ba/Bitcoin_Elliptic_Curve.png">Desdevpro</a></p><p>Where:</p><ul><li>x and y are the coordinates of points on the curve;</li><li>a and b are constants that define the curve;</li><li>p is a large prime number, defining a finite field (a set of numbers modulo p).</li></ul><p>The curve is called elliptic because its graph looks like an elongated oval, and the points on the curve have special properties that allow elliptic curve operations (such as point addition and multiplication).</p><h4><strong>ECDSA: Digital Signatures</strong></h4><p>ECDSA uses elliptic curve operations to create and verify signatures. The key parts of the signature generation and verification process rely on elliptic curve point multiplication and modular arithmetic.</p><h4><strong>Signature Generation</strong></h4><p>Let’s assume the private key d and the message m (often hashed before signing). The steps to generate the ECDSA signature are:</p><ol><li><strong>Hash the Message</strong>:<br>- First, hash the message using a cryptographic hash function (like SHA-256), producing H(m), the hash of the message.</li><li><strong>Choose a Random Integer k</strong>:<br>- Select a random integer k from a set of numbers modulo p (the prime used in the curve equation). This is crucial for security to ensure the signature is unique each time.</li><li><strong>Calculate r and s</strong>:<br>- Use elliptic curve point multiplication to calculate the point k⋅G, where G is the base point of the elliptic curve (a fixed point used for generating public keys). The x-coordinate of this point is denoted as r, reduced modulo p: <strong>r = (x(k⋅G)) (mod p)<br></strong>- If r=0, choose a different k.<br>- Calculate s as follows: s=k^−1(H(m)+r⋅d) (mod p) — where k^−1 is the modular inverse of k modulo p−1..</li><li><strong>The Signature</strong>:<br>- The signature consists of the two values r and s. The pair (r,s) is the ECDSA signature for the message m.</li></ol><h4><strong>Signature Verification</strong></h4><p>To verify an ECDSA signature (r,s) for a given message m, follow these steps:</p><ol><li><strong>Verify Validity of r and s</strong>:<br>- Ensure that both r and s are in the valid range 0 &lt; r &lt; p and 0 &lt; s &lt; p.</li><li><strong>Hash the Message</strong>:<br>- Hash the message mmm to get H(m).</li><li><strong>Calculate z1​ and z2​</strong>:<br>- Calculate: z1=s^−1 * H(m) (mod p)<br>- z2=s−¹*r (mod p)</li><li><strong>Point Calculation</strong>:<br>- Compute the elliptic curve points P1=z1⋅G and P2=z2⋅Q, where Q=d⋅G is the public key.</li><li><strong>Calculate r′</strong>:<br>- Add the points P1​ and P2​, then take the x-coordinate of the result modulo p: r′=(x(P1+P2)) (mod p)</li><li><strong>Compare r′ and r</strong>:<br>- If r′=r, the signature is valid. Otherwise, it’s invalid.</li></ol><h4><strong>The Role of v, r, and s in ECDSA</strong></h4><p>In the context of ECDSA:</p><ul><li><strong>r</strong>: The x-coordinate of the elliptic curve point k⋅G modulo p. It’s part of the signature.</li><li><strong>s</strong>: A value derived from the private key, the message hash, and the random number k. It’s the second part of the signature.</li><li><strong>v</strong>: Often seen in signature schemes (like Ethereum), v is used to determine the “recovery” of the public key from the signature. In Ethereum’s case, it helps to find out which of the two possible public keys generated a signature.</li></ul><h4><strong>Point Addition</strong></h4><p><strong>Point addition</strong> on an elliptic curve is a fundamental operation in elliptic curve cryptography. It is the process of adding two points P and Q on an elliptic curve to produce a third point R. This operation forms the basis for more complex operations, such as scalar multiplication, used in cryptographic algorithms like ECDSA.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/0*Yrr3-kFJlX8xgQ6O.png" /></figure><p>Source: <a href="https://hackernoon.com/what-is-the-math-behind-elliptic-curve-cryptography-f61b25253da3">Hackernoon</a></p><p>If you pick two points on the curve, say P and Q, you can combine them to get another point, R. Here’s how:</p><ol><li><strong>Draw a Line</strong>: Imagine a straight line that passes through both P and Q.</li><li><strong>Find Where It Hits the Curve</strong>: This line will touch the curve at a third point.</li><li><strong>Flip It Over the X-Axis</strong>: Take that third point and reflect it across the x-axis to get the result, R.</li></ol><p>That’s it! You’ve added P and Q, and the result is R.</p><h4><strong>Scalar Multiplication</strong></h4><p><strong>Scalar multiplication</strong> refers to taking a single point P on the curve and adding it to itself repeatedly. This is different from standard multiplication of numbers but is critical for elliptic curve cryptography (ECC).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/0*05sPBlQke9oO5H4q.png" /></figure><p>Source: <a href="https://hackernoon.com/what-is-the-math-behind-elliptic-curve-cryptography-f61b25253da3">Hackernoon</a></p><p>When we talk about scalar multiplication, we mean multiplying a point P on the elliptic curve by a scalar K, which is a whole number. For example:</p><p>Q=K⋅P</p><p>Here:</p><ul><li>P is the starting point.</li><li>K is the number of times P is added to itself.</li><li>Q is the resulting point after the operation.</li></ul><p>Mathematically, it means: Q=P+P+P+…+P(K times).</p><h4><strong>How Does Scalar Multiplication Work?</strong></h4><p>To compute Q=K⋅P, we use <strong>point addition</strong> and <strong>point doubling</strong>, as follows:</p><ol><li><strong>Start with P:</strong> The point P is given on the elliptic curve.</li><li><strong>Use Point Doubling:</strong> To compute 2⋅P2, draw a tangent line through P on the curve. The tangent intersects the curve at a new point, which, when reflected across the x-axis, gives 2P.</li><li><strong>Use Point Addition:</strong> Add P to 2P to compute 3P. Keep repeating the process.</li><li><strong>Repeat Efficiently (Binary Method):</strong> Instead of manually adding P one step at a time, cryptographers use an efficient method called the <strong>double-and-add algorithm</strong>. This method leverages the binary representation of K to compute Q=K⋅P much faster.</li></ol><p><strong>Key Generation in Cryptography</strong>: In ECC, scalar multiplication is used to generate a public key from a private key. The private key is a large number K, and the public key is Q=K⋅G, where G is a predefined point on the curve.</p><h3>5. Malleability Attack</h3><p>In blockchain systems, all transactions must be signed before they are included in the blockchain. These signatures use elliptic curve cryptography (ECC) and consist of several parameters: v, r, and s. <strong>Signature malleability</strong> allows an attacker to modify these parameters while still creating a valid signature. Importantly, the attacker doesn’t need access to the original signer’s private key to perform this attack.</p><h4><strong>Why Does It Happen?</strong></h4><p>Elliptic curves are symmetric by nature. This means that for any given signature (v,r,s), there exists another valid signature (v′,r,s′) that satisfies the same cryptographic relationship. Specifically:</p><ul><li>The elliptic curve equation provides multiple valid representations of the same signature due to its inherent symmetry about the x-axis.</li><li>For a valid signature (v,r,s), the values of s can sometimes be replaced by their complements (e.g., −s mod n-), resulting in a new, valid signature.</li></ul><p>This symmetry allows attackers to craft alternate signatures that can bypass verification when only the correctness of the cryptographic relationship is checked.</p><h4><strong>Impact on Smart Contracts</strong></h4><p>Smart contracts often use the Ethereum Virtual Machine (EVM) function ecrecover to verify signatures. This function requires four parameters: v, r, s, and a hash of the message being signed. The function checks if the provided signature corresponds to a valid public key.</p><p>An attacker exploiting signature malleability can:</p><ul><li>Modify the v, r, or s values to generate a different but valid signature.</li><li>Submit the altered signature to the smart contract.</li><li>Cause unintended behavior if the contract logic assumes that each signature is unique or is directly tied to a specific transaction.</li></ul><h4><strong>Example of the malleability attack</strong></h4><p>The contract verifies signatures using ecrecover:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/0*xJKjtG2gvwElmgix.png" /></figure><p><strong>Attack Steps:</strong></p><ol><li>A legitimate user signs a message, producing a signature (v,r,s).</li><li>The attacker modifies the signature by flipping the s-value to n−s, where n is the order of the elliptic curve.</li><li>The attacker submits the modified signature (v,r,n−s) to the smart contract.</li><li>The ecrecover function verifies the altered signature as valid because it still corresponds to the original public key.</li></ol><h3>6. Mitigation of Signature Malleability</h3><h4><strong>Use OpenZeppelin’s ECDSA Library</strong></h4><p>To mitigate signature malleability effectively in Ethereum smart contracts, developers can use OpenZeppelin’s <strong>ECDSA library</strong>, which includes built-in functions to validate signatures and enforce canonical forms. This library ensures that only signatures with the lower half of the elliptic curve are accepted, discarding the other half.</p><p>By leveraging this library, developers can reduce the risk of signature malleability attacks while simplifying signature validation logic.</p><p>The <strong>ECDSA library</strong> in OpenZeppelin includes utility functions for recovering and verifying signatures. Specifically, it implements checks to ensure the s-value of the signature is in the <strong>lower half of the curve</strong>, i.e., 0≤s≤n/2​, where n is the order of the curve. This normalization prevents multiple valid signatures for the same message.</p><h4><strong>Manual Invalidation of Half of the Curve</strong></h4><p>In addition to using libraries like OpenZeppelin’s ECDSA, signature malleability can also be addressed with a simple manual validation of the s-value. By enforcing that s is in the <strong>lower half of the elliptic curve</strong>, you ensure the signature is canonical and cannot be altered to create equivalent but different signatures.</p><h4><strong>Mitigating Signature Malleability Using Direct sss-Value Validation</strong></h4><p>In addition to using libraries like OpenZeppelin’s ECDSA, signature malleability can also be addressed with a simple manual validation of the s-value. By enforcing that s is in the <strong>lower half of the elliptic curve</strong>, you ensure the signature is canonical and cannot be altered to create equivalent but different signatures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/0*9cFc3u3fANqAEALA.png" /></figure><p>Elliptic curves are symmetric, so for every valid signature (v,r,s), there exists another valid signature (v,r,−smod n), where n is the order of the elliptic curve. To avoid this ambiguity, we enforce s≤n/2s.</p><p>0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A00x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A00x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0</p><p>The value above represents n/2n for the SECP256k1 curve, which is the elliptic curve used in Ethereum.</p><h4><strong>Comparison to OpenZeppelin’s ECDSA Library</strong></h4><ul><li><strong>Manual s-Check</strong>:<br>- Lightweight and straightforward.<br>- Requires knowledge of the elliptic curve properties and parameters like n/2n.</li><li><strong>OpenZeppelin’s ECDSA Library</strong>:<br>- Abstracts these checks into reusable functions.<br>- Offers additional utilities like Ethereum-specific message formatting.</li></ul><h3>7. Conclusion</h3><p>In summary, signature malleability presents a notable challenge to blockchain security, enabling vulnerabilities like replay attacks and unauthorized transactions. Developers can proactively mitigate risks by understanding the causes — rooted in the symmetric properties of elliptic curves — and using the right tools and methods, like OpenZeppelin’s ECDSA library and manual validations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c1c752e944f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zokyo-io/signature-malleability-risks-attacks-and-solutions-0c1c752e944f">Signature Malleability: Risks, Attacks, and Solutions</a> was originally published in <a href="https://medium.com/zokyo-io">Zokyo_io</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Complete Guide to Reentrancy Attacks]]></title>
            <link>https://medium.com/zokyo-io/a-complete-guide-to-reentrancy-attacks-ae2558fc4662?source=rss----adc3a5112af0---4</link>
            <guid isPermaLink="false">https://medium.com/p/ae2558fc4662</guid>
            <dc:creator><![CDATA[Nuno Teodoro]]></dc:creator>
            <pubDate>Tue, 17 Dec 2024 10:34:17 GMT</pubDate>
            <atom:updated>2024-12-17T10:34:17.064Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fyVL5uYVEAuLrC596mxLIw.png" /></figure><h4>1. Introduction to Reentrancy Attacks</h4><p>A reentrancy attack is a common vulnerability in smart contracts. It occurs when an attacker repeatedly calls a function in a smart contract before the initial function call is completed.</p><p>In the context of reentrancy attacks, the prevalent association is often with the classic reentrancy attack that arises when the Checks-Effects-Interactions (CEI) pattern is not properly adhered to. This association is understandable, as such scenarios typically highlight a severe vulnerability. Specifically, they can result in unauthorized withdrawal of funds from a contract or unintended modifications to the contract’s state, posing significant security risks.</p><h4>2. Classic Reentrancy Attack</h4><p>The classic reentrancy attack happens when a malicious contract repeatedly calls back into a vulnerable contract before the original function execution is completed, exploiting the incomplete state of the vulnerable contract. This vulnerability arises because external calls are executed before the contract’s state is properly updated. As a result, malicious actors can exploit this sequence to re-enter the contract and manipulate its logic or drain funds, bypassing the intended safeguards.</p><h4>How It Works</h4><p>The key to a reentrancy attack lies in exploiting the control flow of a smart contract. It often targets contracts that interact with external entities, such as other contracts or wallets. Here’s a step-by-step breakdown:</p><p><strong>1. Vulnerable Contract</strong>: The victim contract has a function that:</p><ul><li>Sends Ether to a user (e.g. withdraw).</li><li>Updates the user’s balance <em>after</em> the transfer.</li></ul><p><strong>2. Attacker Contract</strong>: The attacker creates a malicious contract designed to:</p><ul><li>Receive Ether from the vulnerable contract.</li><li>Call the withdraw function of the vulnerable contract recursively before the first invocation completes.</li></ul><p><strong>3. Attack Process</strong>:</p><ul><li>The attacker deposits some Ether into the vulnerable contract.</li><li>The attacker calls the vulnerable contract’s withdraw function.</li><li>During the transfer process, the vulnerable contract invokes the fallback function of the attacker’s contract.</li><li>The attacker’s fallback function re-invokes the vulnerable contract’s withdraw function, draining funds before the original transaction completes.</li></ul><p><strong>4. Funds Drained</strong>: Because the balance in the vulnerable contract is only updated after the withdrawal, the attacker can withdraw funds repeatedly in a single transaction until the contract is drained.</p><h4>Code Example</h4><p>To better illustrate the described reentrancy attack, let us consider the following code example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LUpujPxHRUhlZ46G.png" /></figure><p>While the <strong>classic reentrancy attack</strong> involving recursive calls is the most well-known, <strong>reentrancy variations</strong> can have equally or more severe impacts, depending on the specific protocol and its logic. These variations exploit other indirect forms of reentrancy vulnerabilities and can bypass simple protections, potentially causing significant harm.</p><h4>3. Variations of Reentrancy Attacks</h4><p><strong>A. Cross-Function Reentrancy Attack</strong></p><p>This is a more sophisticated variant of the classic reentrancy attack in smart contracts, where the vulnerability arises not from a single recursive call to the same function, but from the interplay between multiple functions within the same contract. Unlike the traditional reentrancy attack, where a malicious contract repeatedly calls the same function to exploit state inconsistencies (typically with recursive calls), <strong>cross-function reentrancy</strong> manipulates the contract’s behavior by exploiting the sequence of function calls and the interactions between them.</p><p>In a cross-function reentrancy attack, an attacker leverages the dependencies between multiple functions to create a situation where state updates from one function are not fully reflected before another function is called. By carefully timing and ordering function calls, the attacker can exploit inconsistencies in how state is updated or how external calls are made, causing unintended consequences such as fund theft, improper state transitions, or the bypassing of contract logic.</p><p>This type of reentrancy attack is harder to detect because it doesn’t rely on the same function being reentered, but rather on a series of function calls that manipulate shared state variables in a sequence. Since the attacker only needs to exploit the interactions between functions (and not recursion within one function), the attack is often subtler and more difficult to identify during audits.</p><p>The scenario above can present a tricky challenge for developers and auditors, who may assume that a specific variable state does not need to be updated before making an external call, believing that a classic reentrancy attack cannot be executed within the same function. However, this oversight creates the potential for a cross-function reentrancy attack. In such cases, an external call in one function can trigger a reentrancy attack in another function, allowing malicious actors to manipulate the contract’s state in unexpected ways.</p><p><strong>How It Works</strong></p><p>In a typical contract, multiple functions often interact with shared state variables. For example, one function might handle deposits, another might handle withdrawals, and a third might manage rewards or interest calculations. These functions might not have direct reentrancy protection, especially if they don’t expect to interact with each other in unexpected ways. In a cross-function reentrancy attack, the attacker can exploit these interactions by performing an attack that spans across multiple functions.</p><p>The key factor is the <strong>sequence of function calls</strong>. If the contract doesn’t properly update its state before performing an external action (e.g., transferring funds, calling an external contract), an attacker can exploit the order of operations and the dependencies between functions to reenter vulnerable points of the contract before it finishes executing its intended logic.</p><p>To better illustrate the described cross-function reentrancy attack, let us consider the following code example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*K02IjgPov1MmFpVm.png" /></figure><p><strong>Attack Scenario:</strong></p><p><strong>1. Initial Setup</strong>: The attacker stakes tokens using the stake() function and accumulates rewards through the contract.</p><p><strong>2. Exploit Flow</strong>:</p><ul><li>The attacker calls the withdraw() function to withdraw their staked tokens.</li><li>Inside the withdraw() function, a call is made to transfer the requested amount of tokens back to the attacker.</li><li>While the transfer is still in progress, the attacker’s contract has a fallback function that gets triggered whenever Ether is sent to it.</li></ul><p><strong>3. Reentering the Contract</strong>:</p><ul><li>The fallback function in the attacker’s contract reenters the claimRewards() function before the withdraw() function has finished updating the attacker’s balance.</li><li>The attacker can claim rewards based on the old (higher) staked balance, which was not yet updated in the contract state because the withdraw() function hasn&#39;t completed its execution.</li></ul><p><strong>4. Repeat</strong>:</p><ul><li>By reentering, the attacker can keep claiming rewards or withdrawing tokens without updating the contract’s state properly, leading to an exploitation of the contract’s funds.</li></ul><p>This type of reentrancy is particularly dangerous because it can bypass basic protections against reentrancy attacks. While a contract may appear safe at first glance with each individual function seeming to handle its own logic correctly, the combined effect of multiple functions operating on shared state can lead to unexpected behaviors.</p><p><strong>B. Cross-Contract Reentrancy Attack</strong></p><p>Cross contract reentrancy is another variation of the classic reentrancy attack that spans across multiple contracts. In this variation, instead of exploiting reentrant behavior within a single contract, the attacker exploits the interactions between two or more contracts to manipulate state or logic in unintended ways. This attack leverages the complexity of inter-contract dependencies, often making it harder to detect and mitigate than single-contract reentrancy.</p><p><strong>How it works</strong></p><p>Smart contracts frequently interact with other contracts to perform tasks such as token transfers, price calculations, staking, lending, or liquidity provisioning. This reentrancy attack is different from the classic reentrancy one, the attacker uses a callback function in the malicious contract to reenter the vulnerable contract through another function or interaction. This creates a more complex attack chain.</p><p><strong>Key Differences</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/0*4z03_3D5KEvkRidd.png" /></figure><p><strong>C. Read-Only Reentrancy</strong></p><p>Read-only reentrancy is another variation of the reentrancy attack, often undervalued because it seems riskless at first.</p><p>Unlike traditional reentrancy, where the attacker directly manipulates state variables to steal funds or corrupt the contract, read-only reentrancy targets contracts during <strong>read operations</strong> (e.g., view or pure functions) to produce misleading or inconsistent results. While these functions do not modify state directly, their return values might depend on external calls, creating an opportunity for reentrancy if an attacker can influence the logic of these calls.</p><p>The impact of read-only reentrancy is typically less direct than classic reentrancy attacks but can be severe in specific contexts. For example, it could be used to manipulate oracle prices, mislead external systems, or disrupt decision-making processes within smart contracts that rely on the integrity of read operations.</p><p><strong>How it works</strong></p><p><strong>1. Dependency on External Calls</strong>:</p><ul><li>A vulnerable contract performs a view function call to another contract or an external system to fetch data (e.g., token balances, oracle prices).</li></ul><p><strong>2. Reentry During External Call</strong>:</p><ul><li>The external contract is controlled by an attacker or interacts with a malicious contract. During the call, the attacker triggers a callback into the original contract.</li></ul><p><strong>3. Inconsistent State During Reentry</strong>:</p><ul><li>The reentrant call causes the original contract to return a manipulated or incorrect value before its logic has been completed, leading to unexpected or exploitable behavior.</li></ul><p><strong>4. Outcome</strong>:</p><ul><li>While state is not directly corrupted, the contract’s decision-making based on the read-only operation is undermined, enabling indirect exploitation.</li></ul><p>In other words, the function that enables the attack is one that executes an external call without first updating the contract state. This presents a direct risk because the function may, for instance, implement a nonReentrant modifier designed to prevent reentrancy to the same function. However, since the execution flow is now controlled by the malicious contract through its fallback function, it can exploit the fact that the state of the first contract has not been updated.</p><p><strong>Attack Scenario</strong></p><p>Imagine a contract that calculates the price of a token using an oracle during a read operation. The contract calls the oracle’s getPrice() function, which depends on external data. An attacker uses read-only reentrancy to disrupt the calculation.</p><p><strong><em>Vulnerable Contract: Ether Pool</em></strong></p><p>This contract allows users to deposit Ether into a shared pool, tracks each user’s contributions, and provides a function to check the contract’s total balance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yeeUojqKXiEnn3hy.png" /></figure><p>It can be observed that the withdraw() function executes an external call without first updated the balances and totalBalances state. However, classic reentrancy is not possible within the deposit() and withdraw() functions as they implement a nonReentrant modifier. However, getTotalBalance is vulnerable because it returns the totalBalance without being updated.</p><p><strong>External Contract</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IUHYj58xbWH8e8Ve.png" /></figure><p><strong>1. Setup</strong>:</p><ul><li>An attacker deploys a <strong>malicious contract</strong> (see below) and interacts with the vulnerable EtherPool.</li></ul><p><strong>2. Triggering the Attack</strong>:</p><ul><li>The attacker first deposits Ether into the vulnerable EtherPool.</li><li>The attacker then calls withdraw() on EtherPool. During this operation, EtherPool sends Ether to the attacker&#39;s contract, triggering its fallback() function.</li></ul><p><strong>3. Reentering the Vulnerable Contract</strong>:</p><ul><li>Inside the fallback() function of the malicious contract, the attacker calls the distributeRewards() function on the ExternalContract.</li><li>distributeRewards() relies on the outdated getTotalBalance() value, which hasn’t been updated yet in EtherPool (because the state updates in withdraw() happen after the external call).</li></ul><p><strong>4. Exploit</strong>:</p><ul><li>The attacker manipulates the logic of ExternalContract by causing it to act on stale or incorrect data. For example:</li><li>The distributeRewards() function might proceed with reward distribution based on a higher-than-actual balance.</li><li>ExternalContract might use the outdated total balance for any operation, leading to unintended outcomes.</li></ul><h4><strong>4. Conclusion</strong></h4><p>The read-only reentrancy attack is a particularly tricky scenario. It may seem harmless at first, especially if the protocol does not currently have any external integrations. However, if the vulnerability is not addressed, it can evolve into a situation where new parts of the protocol are built on top of the read-only vulnerable contract, as described earlier, making it exploitable. This also poses significant risks to third-party protocols that integrate with the vulnerable one. Therefore, it is always recommended to follow the CEI (Checks-Effects-Interactions) pattern: first performing the necessary checks, then updating the contract state and variables, and finally executing external calls.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae2558fc4662" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zokyo-io/a-complete-guide-to-reentrancy-attacks-ae2558fc4662">A Complete Guide to Reentrancy Attacks</a> was originally published in <a href="https://medium.com/zokyo-io">Zokyo_io</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web3: A Promising Frontier Fraught with Deception — Stay Informed, Stay Safe]]></title>
            <link>https://medium.com/zokyo-io/web3-a-promising-frontier-fraught-with-deception-stay-informed-stay-safe-c657f8c5e2ce?source=rss----adc3a5112af0---4</link>
            <guid isPermaLink="false">https://medium.com/p/c657f8c5e2ce</guid>
            <dc:creator><![CDATA[Nuno Teodoro]]></dc:creator>
            <pubDate>Fri, 18 Oct 2024 11:24:21 GMT</pubDate>
            <atom:updated>2024-10-18T11:24:21.387Z</atom:updated>
            <content:encoded><![CDATA[<h3>Web3: A Promising Frontier Fraught with Deception — Stay Informed, Stay Safe</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xML96Bjj9WclDqpORuOGDw.png" /></figure><p>The rise of Web3 technology represents a powerful shift towards decentralization, offering new opportunities in finance, ownership, and the way we interact online. However, as with any emerging technology, it has also become fertile ground for scammers eager to exploit both experienced and novice users alike.</p><p>It’s important to understand that the presence of bad actors does not undermine the potential of Web3 itself. In Egypt, for example, we see countless incidents of credit card fraud, but no one would suggest abandoning electronic payment systems because of malicious actors. The solution is not avoidance, it is rather awareness and vigilance.</p><h4>Key Takeaways:</h4><ul><li>Avoid scams that promise easy, passive income.</li><li>Beware of unlisted YouTube videos</li><li>Never run code you do not fully understand.</li></ul><h3>The Myth of Easy Passive Income</h3><p>One of the key lessons we should take to heart as Web3 grows is that there is<strong><em> no such thing as “easy passive income.”</em></strong> If something seems too good to be true, it almost certainly is.</p><p>Scammers thrive on painting an enticing, unrealistic picture of effortless profits, hoping to reel you in with the promise of quick gains. Trust me, things are never as simple as they make them seem. Always approach such offers with caution and a healthy dose of skepticism.</p><p>The more informed and careful we become, the harder it is for these scams to succeed. Take every promise with a grain of salt, research thoroughly, and never make impulsive decisions based on enticing propositions.</p><p>At the end of the day, the promise of Web3 remains exciting and real, but it is up to us as users to stay alert and not be swayed by false promises. Just as in traditional finance, <strong><em>due diligence is key.</em></strong></p><h3>Scam Study Case: Unlisted YouTube Videos</h3><p>One of the scams going around in the Web3 space involves the use of <strong><em>unlisted YouTube videos</em></strong>, a tactic that allows scammers to target specific audiences without drawing widespread public attention. One such video has already amassed an alarming 207k views, despite its unlisted status. This shows the scale of the scam and how effectively it’s being spread within certain communities.</p><p>We pick one of these scam videos to talk about in this post. The scammer claims to have developed a <strong><em>“hot” Uniswap arbitrage bot</em></strong>, using none other than the buzzword of the moment: ChatGPT. The scammer taps into the hype surrounding AI, framing the bot as an innovative, cutting-edge tool (i.e., for the laughs) that can supposedly earn you effortless profits through automated arbitrage on decentralized exchanges like Uniswap.</p><h3>False Promises</h3><p>In the video, the scammer presents what he claims is a “game-changing” arbitrage bot, supposedly designed to capitalize on price differences between tokens on decentralized exchanges like Uniswap. He showcases a Solidity smart contract, explaining that this contract opportunistically takes advantage of token price discrepancies to generate profits.</p><p>On the surface, this sounds appealing — the concept of arbitrage, after all, is a legitimate trading strategy. But what the scammer conveniently omits is just how complex the implementation of such an idea truly is.</p><h4>Key Points the Scammer Fails to Mention:</h4><ul><li><strong>Urgency is everything in arbitrage:</strong> Getting ahead in the arbitrage game means competing in a fast-paced environment where speed and capital are everything. The infrastructure required to monitor price changes, execute trades instantly, and pay for gas fees (Ethereum transaction costs) requires far more than just a simple smart contract — it demands a sophisticated setup off-chain as well.</li><li><strong>Smart contracts are not bots:</strong> The scammer provides misleading technical information. One glaring example is his claim that the Solidity smart contract itself is a “bot.” This is completely false. Solidity smart contracts are not bots — they are not self-executing programs. They function as automated agreements that execute specific actions based on predefined conditions, but they still need to be triggered by external actors. Bots, on the other hand, are active off-chain programs written in languages like Python, JavaScript, or Go, which interact with smart contracts on-chain. The role of a bot is to watch for certain conditions (like price differences) and trigger the smart contract when the opportunity arises.</li></ul><h3>Analyzing the Code</h3><p>By looking at the Solidity smart contract presented in the video, it becomes clear that this is nothing more than a disguised trap. Let’s break down the key functions that expose this scam for what it is.</p><h4>1. Constructor Function</h4><p>The contract’s constructor function is empty, meaning nothing happens when the contract is deployed. This is not necessarily a red flag, but it is an indication that the contract offers no real value or functionality.</p><h4>2. The receive() Function</h4><p>The receive()function is also empty, but its mere presence signals that the contract is capable of accepting ETH. While this might seem harmless at first glance, it’s an important clue: the scammer’s intention is to collect ETH sent to the contract by the victim.</p><h4>3. The start() Function</h4><p>Now, things get a little more interesting with the start()function. This function is named to create the illusion that it initiates some kind of meaningful operation. However, its true purpose is far less sophisticated. All this function does is verify that ETH has been sent to the contract, effectively confirming that the victim has deposited funds — ETH that the scammer eventually plans to steal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*HZJSBc9kKlHj1Kt0ig6Sag.png" /></figure><h4>4. The withdrawal() Function</h4><p>Finally, we reach the function where the scam truly unfolds: withdrawal(). The scammer presents this function as the one that will allow the victim to retrieve their ETH, along with any “profits” earned through the arbitrage bot. But the reality is far different.</p><p>The scammer introduces the concept of fetching “mempool data,” a highly misleading claim. Smart contracts cannot fetch mempool data — this is yet another misrepresentation designed to confuse and impress the victim with technical-sounding jargon.</p><p>Let’s dissect what fetchMempoolData()actually does:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bCv723iPFeTm8db012kcpQ.png" /></figure><p>All this function does is concatenate a series of strings (i.e., text) into one longer string. One of the strings returned by this function is:</p><p>This “mempool data” is nothing more than a string that begins to resemble an address. The contract then processes these strings to generate an actual address using the startExploration() function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SIZqsEd6NY9aUY5txIeHLw.png" /></figure><p>While this function might look sophisticated, all it does is convert a string into an address. More importantly, this address is most probably controlled by the scammer.</p><h4>5. The Transfer of Funds</h4><p>Now that the scammer has manipulated the victim into sending ETH to the contract, the final step occurs in the withdrawal()function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*9j1xWWKz_8yvuIOY-xluHA.png" /></figure><p>Here, the address generated from the earlier string manipulation (to) is assigned, and the full balance of the contract (retrieved by getBa()) is transferred to this address — an address controlled by the scammer.</p><h3>Conclusion</h3><p>This scam demonstrates how buzzwords like “AI” and “blockchain” are used to deceive unsuspecting users. The Solidity contract presented in the video is designed not to make profits, but to steal ETH. The scam relies on the false trust of non-developers, many of whom, based on the video comments, ran code they did not understand.</p><p>The lesson here is simple: <strong><em>never run code you do not fully understand.</em></strong> In Web3 and beyond, skepticism and knowledge are your best defenses against scams. Stay informed and cautious as you navigate this evolving space.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c657f8c5e2ce" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zokyo-io/web3-a-promising-frontier-fraught-with-deception-stay-informed-stay-safe-c657f8c5e2ce">Web3: A Promising Frontier Fraught with Deception — Stay Informed, Stay Safe</a> was originally published in <a href="https://medium.com/zokyo-io">Zokyo_io</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best Practices for Web3 Wallet Security]]></title>
            <link>https://medium.com/zokyo-io/best-practices-for-web3-wallet-security-3416a8b8ab45?source=rss----adc3a5112af0---4</link>
            <guid isPermaLink="false">https://medium.com/p/3416a8b8ab45</guid>
            <dc:creator><![CDATA[Nuno Teodoro]]></dc:creator>
            <pubDate>Mon, 30 Sep 2024 11:33:44 GMT</pubDate>
            <atom:updated>2024-09-30T11:33:44.014Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UsIDrExB8pi09Ng-o9RZ0Q.png" /></figure><p>Web3 crypto wallet applications are the gateways to the decentralized world, enabling users to interact with blockchain networks, manage cryptocurrencies, and engage with decentralized applications (dApps). The cornerstone of these wallets is the private key, a cryptographic secret that grants access to the user’s assets.</p><p>However, storing and securing private keys is a critical challenge. If compromised, users could lose their assets irreversibly. This article explores various methods and best practices for securely storing private keys in Web3 crypto wallet applications.</p><h3>1. Understanding the Risks</h3><p>Private keys are the most sensitive piece of information in a crypto wallet. If a malicious actor gains access to a private key, they can sign transactions, effectively taking control of the associated assets. Thus, ensuring that private keys are stored securely is crucial. The main risks associated with private key storage include:</p><ul><li><strong>Malware and Phishing Attacks:</strong> Malware can infiltrate devices and extract private keys stored in insecure locations. Phishing attacks can deceive users into revealing their private keys.</li><li><strong>Device Theft:</strong> If a user’s device is stolen or lost, an attacker could access the private keys if they are stored in an unprotected manner.</li><li><strong>Insider Threats:</strong> Developers or other insiders with access to sensitive parts of the application code or backend systems could potentially exploit vulnerabilities to access private keys.</li></ul><h3>2. Best Practices for Private Key Storage</h3><h4>2.1 Hardware Security Modules (HSMs) and Secure Enclaves</h4><p>One of the most secure ways to store private keys is by using hardware-based solutions.</p><ul><li><strong>Hardware Wallets:</strong> Devices like Ledger and Trezor store private keys in a secure chip that is isolated from the user’s computer or mobile device. These hardware wallets sign transactions internally, meaning the private key never leaves the device.</li><li><strong>Secure Enclaves:</strong> Modern smartphones and some computers come with secure enclaves (e.g., Apple’s Secure Enclave or Android’s Trusted Execution Environment). These enclaves are isolated from the main processor, providing a secure environment to store and manage private keys.</li><li><strong>Hardware Security Modules (HSMs):</strong> Used primarily in enterprise settings, HSMs are specialized devices designed to store and manage cryptographic keys securely. They provide physical and logical protection against unauthorized access and tampering.</li></ul><h4>2.2 Encryption and Key Derivation Techniques</h4><p>For software-based wallets that store private keys on the user’s device, encryption is crucial.</p><ul><li><strong>Symmetric Encryption:</strong> Private keys can be encrypted using a strong symmetric encryption algorithm (e.g., AES-256). The encryption key should be derived from a strong user password using a key derivation function (KDF) like PBKDF2, scrypt, or Argon2.</li><li><strong>Mnemonic Phrases:</strong> Many wallets use a mnemonic phrase (also known as a seed phrase) to back up private keys. This phrase should be stored securely and only used in secure environments to generate the private key.</li><li><strong>Key Splitting:</strong> In some cases, a private key can be split into parts (e.g., Shamir’s Secret Sharing) and distributed across multiple locations. Only by combining all parts can the private key be reconstructed.</li></ul><h4>2.3 Cold Storage Solutions</h4><p>Cold storage refers to keeping private keys offline, away from any networked devices. This significantly reduces the risk of remote attacks.</p><ul><li><strong>Paper Wallets:</strong> Private keys can be printed on paper and stored in a secure physical location. However, this method is not without risks, as paper can degrade over time, and physical theft is still a concern.</li><li><strong>Air-gapped Devices:</strong> These are devices that have never been connected to the internet, reducing the risk of malware. Private keys can be generated and stored on such devices, which are then used to sign transactions offline.</li></ul><h4>2.4 Multi-Factor Authentication (MFA) and Multi-Signature Wallets</h4><ul><li><strong>Multi-Factor Authentication (MFA):</strong> Adding an additional layer of security, such as biometric authentication or a hardware token, can protect access to the wallet and private keys.</li><li><strong>Multi-Signature Wallets:</strong> These wallets require multiple private keys to authorize a transaction. This means that even if one key is compromised, an attacker would still need access to the other keys to steal assets.</li></ul><h3>3. Implementing Security Best Practices</h3><p>When developing Web3 crypto wallet applications, developers should follow a robust security model:</p><ul><li><strong>Minimize Attack Surface:</strong> Only store private keys in environments that are as secure as possible, and limit the exposure of these keys to the internet or untrusted devices.</li><li><strong>Storage</strong>: Never store the private keys either in the storage or in the memory as a plain text.</li><li><strong>Regular Security Audits:</strong> Conduct regular security audits to identify and fix vulnerabilities in the wallet software. This includes both code audits and penetration testing.</li><li><strong>User Education:</strong> Educate users on the importance of safeguarding their private keys and how to recognize phishing attacks and other threats.</li></ul><h3>4. Conclusion</h3><p>Securely storing private keys is the foundation of trust in Web3 crypto wallet applications. By implementing a combination of hardware security, encryption, cold storage, multi-factor authentication, and rigorous security practices, developers can significantly reduce the risk of private key compromise. As the Web3 ecosystem continues to evolve, staying ahead of emerging threats and continuously improving security measures will be essential to protect users and their digital assets.</p><h3>About Zokyo</h3><p>Zokyo is a leading web3 security firm focused on protecting blockchain organizations from cyber threats. We specialize in offensive cybersecurity, token economics, cryptography, and reverse engineering, advising across ecosystems like EVM, Solana, Ton, Move, and more. Zokyo Ventures, our tech-first investment arm, strategically backs early-stage digital asset companies, driving innovation in the space.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3416a8b8ab45" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zokyo-io/best-practices-for-web3-wallet-security-3416a8b8ab45">Best Practices for Web3 Wallet Security</a> was originally published in <a href="https://medium.com/zokyo-io">Zokyo_io</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Preparing for the Challenges of Smart Contract Audits]]></title>
            <link>https://medium.com/zokyo-io/security-audits-are-essential-even-for-the-most-skilled-developers-db6041677abe?source=rss----adc3a5112af0---4</link>
            <guid isPermaLink="false">https://medium.com/p/db6041677abe</guid>
            <dc:creator><![CDATA[Nuno Teodoro]]></dc:creator>
            <pubDate>Mon, 23 Sep 2024 15:26:30 GMT</pubDate>
            <atom:updated>2024-09-30T11:25:46.110Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*miJ1BmPWNczGe3NhRzRD9w.png" /></figure><p>Security audits are essential, even for the most skilled developers. This is because audits bring fresh perspectives to the code that may not be obvious to those who originally wrote it. Developers often develop a kind of tunnel vision, making assumptions about their product or system that can result in overlooked vulnerabilities. Auditors, coming from an external viewpoint, can challenge these assumptions and identify weak spots that the developers might have missed.</p><p>One of the main reasons security audits are crucial is that developers are often focused on delivering a functional product to a client. It is their responsibility to ensure that the product is not only functional but also secure. In domains like information security, this means safeguarding sensitive data, and in the context of blockchain or cryptocurrency, it means ensuring user funds are protected.</p><p>A key benefit of audits is that they involve multiple sets of eyes examining the project. Often, when an audit is conducted by a team, each auditor will identify unique vulnerabilities. This highlights that different types of bugs require different ways of thinking, and no one person will catch everything. Different auditors approach the problem from different angles, leading to a more thorough review of the code.</p><p>Additionally, open bug bounty programs, such as those on CodeArena, provide further evidence of the value of diverse perspectives. Even top contributors, with extensive experience, miss bugs that less experienced participants may find. This shows that factors like creativity, approach, and diverse experience levels play a role in identifying issues.</p><p>Finally, it’s crucial for any software development company, regardless of its budget or the experience level of its developers, to engage in security audits. Even well-funded companies with highly experienced developers have shipped products containing vulnerabilities. Therefore, security audits are a necessary step to ensure the safety and integrity of the product, safeguarding both the company’s reputation and the end-users’ security.</p><h3>The Hacker’s Methodology</h3><p>A hacker’s primary goal is to exploit a system, whether it’s for personal gain, financial profit, or to prove a point. In the context of cryptocurrencies, the motivation is predominantly financial, with attackers aiming to steal user funds or disrupt the platform. Understanding the hacker’s methodology is crucial for defending against these threats.</p><h4>1. Reconnaissance and Information Gathering</h4><p>The first step a hacker takes is gathering as much information as possible about the system, particularly in the case of smart contracts, which are often open source. Open-source code provides attackers with a blueprint of the system, allowing them to study its mechanics and identify potential weaknesses. Since smart contracts frequently handle funds and transfers of value, they become high-value targets for attackers.</p><h4>2. Focusing on Inputs</h4><p>One of the first areas of focus for an attacker is the inputs, as they are often the only direct way to interact with the system. While it may seem obvious, inputs are where vulnerabilities are most likely to be found. Attackers will meticulously analyze these inputs, trying to determine if improper validation or unchecked assumptions can be exploited. This often involves attempting edge cases, unexpected inputs, or invalid data to see if the system behaves in unintended ways.</p><h4>3. Challenging Assumptions</h4><p>Hackers employ a mindset of challenging the assumptions made by developers. They ask heuristic questions such as:</p><ul><li>What is this system supposed to do?</li><li>What assumptions did the developers make about user behavior or system state?</li><li>Can I break these assumptions, and if so, what would happen?</li><li>Are there any critical design flaws that were overlooked?</li></ul><p>The attacker then tests these assumptions by interacting with the smart contract, trying to break the system and exploit any oversights in its design or logic.</p><h4>4. Understanding the Protocol</h4><p>A deep understanding of the protocol is essential for an attacker. Hackers typically study how the system operates under normal conditions so they can identify deviations or weaknesses. They also focus on how assets, such as cryptocurrency, move within the system, seeking out opportunities to misappropriate funds by exploiting gaps in the logic or flow of value.</p><h4>5. Mapping Known Vulnerabilities</h4><p>Most attacks are not entirely novel. Instead, attackers are often well-versed in previous exploits and vulnerabilities. They map known weaknesses from similar protocols or systems and apply these strategies to their target. This can include replay attacks, re-entrancy attacks, integer overflow/underflow, or manipulation of external calls within the contract. For instance, the infamous DAO hack of 2016 exploited a re-entrancy vulnerability, a type of attack that is now well-documented but can still pose a risk to systems that don’t account for it.</p><h4>6. Following the Money</h4><p>A common principle attackers follow is “follow the money.” In the context of smart contracts, this means analyzing how inputs interact with value transfers and looking for areas where they can manipulate the flow of funds. Whether it’s through triggering unexpected re-entrancy loops, exploiting gas limitations, or manipulating token balances, the end goal is often to divert or steal funds.</p><h4>7. Leveraging Attack Frameworks and Tools</h4><p>Hackers often use well-established frameworks and automated tools to analyze smart contracts and identify potential vulnerabilities. Tools like Mythril, Slither, and Manticore allow attackers to conduct static and dynamic analysis on smart contracts, enabling them to uncover subtle bugs that may be missed during manual reviews.</p><ul><li>Links to some static analysis tools:</li></ul><p><a href="https://github.com/crytic/slither">https://github.com/crytic/slither</a><br><a href="https://github.com/Consensys/mythril">https://github.com/Consensys/mythril</a></p><h4>8. Post-Exploitation</h4><p>After identifying and exploiting a vulnerability, the attacker will often focus on covering their tracks and maintaining access. In decentralized systems, once funds are stolen, they are often quickly moved across wallets, mixed through privacy-enhancing protocols like Tornado Cash, and converted into other assets to obfuscate the transaction trail.</p><h3>The Importance of Being Ready for an Audit</h3><p>Once you’ve recognized the need for a security audit, especially for open-source smart contracts handling user funds, the next step is to ensure that you are fully prepared before the audit begins. Preparing thoroughly before the audit not only improves the quality of the review but also saves time, resources, and prevents avoidable issues later on. Here are some key reasons and steps to take before starting an audit:</p><h4>1. Ensure Code Completeness and Feature Finalization</h4><p>The most important aspect of audit readiness is submitting a completed codebase. This means all planned features should be implemented, tested, and finalized before you hand the code over to auditors. Auditors are tasked with reviewing the security of your code as it stands, not the code that you intend to add later. If you introduce new features after the audit starts, you risk invalidating parts of the audit because even small changes can alter the overall security landscape of the contract.</p><p>For example, adding just a couple of new functions can change how the smart contracts interact with each other, introducing unforeseen vulnerabilities that weren’t present during the initial audit. This may force the auditors to restart the audit process or miss critical issues, leaving your code less secure. This situation often arises due to rushed deadlines or lack of preparation, and it compromises the quality of the audit.</p><h4>2. Avoid Post-Audit Additions</h4><p>A major mistake teams make is adding functionality after the audit is completed, assuming that the entire contract is still secure. However, any change to the codebase after the audit, even minor tweaks, could introduce vulnerabilities that weren’t accounted for during the audit. As soon as new functionality is added, the contract is essentially unaudited again and becomes susceptible to exploitation.</p><p>A real-world example of this is the case of <strong>Level Finance</strong>. After their smart contracts were audited, they introduced a new feature — an upgrade to the LevelReferralControllerV2 contract. Unfortunately, this upgrade contained a vulnerability that allowed an attacker to repeatedly claim referral rewards in the same epoch. Despite the contract being audited by reputable firms like Quantstamp and Obelisk, the vulnerability arose because the updated code was not part of the original audit. This oversight led to the loss of over $1.1 million in user funds when the vulnerability was exploited.</p><h4>3. Prepare Documentation and Tests</h4><p>Before starting the audit, ensure that all relevant documentation is complete and up to date. This includes:</p><ul><li><strong>Technical specifications</strong>: Provide detailed documentation that outlines the intended behavior of your smart contracts. This helps auditors understand the purpose and flow of the code.</li><li><strong>Assumptions and invariants</strong>: Document any assumptions or invariants you made while developing the code. Auditors need to challenge these assumptions to ensure they hold up in practice.</li><li><strong>Test coverage</strong>: Ensure that your test suite is comprehensive and includes both unit and integration tests. Having thorough test coverage gives auditors confidence that the core functionality of your system is stable, which allows them to focus more on finding subtle security issues.</li></ul><h4>4. Clear Communication with Auditors</h4><p>Establish clear communication with the auditors from the beginning. Make sure they understand the scope of the audit, what functionality needs the most attention, and any particular concerns your team has about the code. Being transparent and communicative throughout the process helps ensure a more effective and thorough audit.</p><p>Additionally, if there are specific deadlines for the project, communicate this with the auditing team early so they can allocate the appropriate time to thoroughly review the code. Rushed audits increase the likelihood of missed vulnerabilities.</p><h4>5. Understanding the Audit Process</h4><p>Be familiar with the standard audit process, which generally includes:</p><ul><li><strong>Initial review and scoping</strong>: Auditors will scope the audit based on your codebase, identifying areas that are most critical or high-risk.</li><li><strong>Manual code review</strong>: A manual review where auditors look for common vulnerabilities such as reentrancy attacks, unchecked external calls, or integer overflows.</li><li><strong>Automated analysis</strong>: Auditors may also use automated tools like Mythril or Slither to detect potential vulnerabilities that could be missed during manual review.</li><li><strong>Final report</strong>: After the review, the auditors will provide a report detailing any vulnerabilities and suggestions for improving the security of your contract. Addressing these findings promptly is crucial for the safety of your project.</li></ul><h4>6. Budgeting Adequately for Security</h4><p>Preparing for an audit also means budgeting appropriately for security measures, including post-audit revisions. Security audits are not one-time processes. Even after the first audit is completed, ongoing audits may be required as the code evolves or as new features are introduced. Allocating funds and resources for both the initial audit and any necessary follow-up audits will help prevent vulnerabilities from slipping through the cracks.</p><h4>7. Post-Audit Responsibility</h4><p>After receiving the audit report and implementing the necessary changes, your responsibility doesn’t end there. Continuous security monitoring and re-auditing are essential, especially as your project evolves. Auditors can only review the current state of your code at the time of the audit. If new features are added or the code is modified, you must engage auditors again to ensure those changes are secure.</p><p>In summary, the success of a security audit largely depends on how prepared your team is before the audit begins. By finalizing your code, avoiding post-audit changes, providing comprehensive documentation, and maintaining clear communication with auditors, you increase the likelihood of a thorough and effective review. Security is a continuous process, and being audit-ready from the start helps ensure your project’s long-term safety and integrity.</p><h3>The Foundation of a Successful Audit</h3><p>As mentioned in the hacker’s methodology, one of the key steps an attacker takes is understanding the project by comparing what is intended with what is actually implemented. Two pieces of code can appear functionally secure on the surface, yet one may contain a critical vulnerability simply because it deviates from the original intent. The vulnerability could stem not from the code itself, but from the misalignment between its implementation and the original design.</p><p>This is why <strong>comprehensive and accurate documentation</strong> is essential when submitting your code for an audit. The documentation serves to establish the context and intentions behind the code, providing auditors with the necessary understanding to evaluate the security of the implementation. Without this context, auditors may spend a significant amount of time trying to deduce what the code is supposed to accomplish, which introduces several risks:</p><ol><li><strong>Wasted Time and Resources</strong>: If auditors are forced to spend time figuring out the purpose and functionality of the code due to lack of documentation, the actual time spent on identifying vulnerabilities is reduced. This not only delays the audit process but may also affect its depth and thoroughness.</li><li><strong>Inaccurate Assumptions</strong>: Without clear documentation, auditors may make assumptions about the intended functionality of the code. These assumptions can lead to overlooked vulnerabilities, as the auditor might believe the code is functioning as intended, when in fact it deviates from the original design. Even if the code seems secure, it may still introduce unintended behavior that can be exploited.</li><li><strong>Frequent Communication Interruptions</strong>: Poor or missing documentation often forces auditors to continually contact the development team for clarification on code functionality, slowing down the audit process. This back-and-forth communication reduces the efficiency of the audit and detracts from the focus on security testing. A project that is well-documented minimizes the need for these interruptions, allowing auditors to focus fully on their task.</li><li><strong>Challenging Assumptions Like Hackers</strong>: Ethical hackers, or auditors, are tasked with challenging the same assumptions that malicious attackers will target. For them to properly challenge these assumptions, they need to know what the developer’s original intentions were. Detailed documentation gives auditors insight into what assumptions were made during development, enabling them to identify areas where those assumptions might break down. This allows the auditors to identify potential vulnerabilities before a malicious actor has the chance to exploit them.</li></ol><p>Unlike attackers, auditors are working against the clock. They have a limited timeframe to thoroughly review your code. Good documentation ensures they don’t waste any of that valuable time on deciphering the code’s purpose but instead focus on ensuring its security. The more comprehensive the documentation, the more effective the audit.</p><h3>What Should the Documentation Include?</h3><p>When preparing for a smart contract audit, it’s essential to provide clear and comprehensive documentation tailored specifically to the context of smart contract development. This not only ensures that the auditors have a full understanding of the system’s functionality but also helps them efficiently identify vulnerabilities and weaknesses in the code. Here’s what should be included in your documentation, with a focus on smart contract auditing:</p><h4>1. High-Level Overview</h4><ul><li><strong>Purpose of the Smart Contract</strong>: Provide a high-level summary of the smart contract’s purpose and its role within the larger project or protocol. Explain the contract’s core functions, its interaction with other contracts, and any key mechanisms it implements (such as token transfers, staking, or governance).</li><li><strong>UML Diagrams</strong>: Use Unified Modeling Language (UML) diagrams to visually represent the structure and flow of your smart contracts. This helps auditors understand the relationships between different components, the interactions between contracts, and the overall architecture of the system. Common diagrams include:<br>1- <strong>Class Diagrams</strong>: Show the different classes (contracts) and their attributes, methods, and relationships.<br>2- <strong>Sequence Diagrams</strong>: Demonstrate how various functions interact with each other in a sequence, especially in complex multi-contract systems.</li><li><strong>PPT Slides for Overview</strong>: Summarize key points from the documentation in PowerPoint slides or similar presentation formats. This is useful for giving auditors a quick understanding of the system’s architecture and the most important aspects of the smart contract.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vzIQXm95aKe7OEqfqDX8JQ.png" /></figure><h4>2. Detailed Technical Specifications</h4><ul><li><strong>Functionality Specifications</strong>: Provide a breakdown of each smart contract, including its purpose, key functions, and interaction points. For each function, include:</li></ul><p>1- Expected inputs and outputs<br>2- Pre-conditions and post-conditions (what must be true before and after execution)<br>3- Any events emitted by the function<br>4- Description of how it interacts with other contracts or external systems (if applicable)</p><ul><li><strong>Edge Cases</strong>: Describe any potential edge cases or complex scenarios that your smart contract is expected to handle. This helps auditors focus on these areas to ensure they are thoroughly reviewed.</li></ul><h4>3. Inline Commenting</h4><ul><li><strong>Code Annotations</strong>: Ensure your smart contracts include comprehensive inline comments. These comments should describe what each function does, how it works, and the developer’s assumptions behind the implementation. Inline comments help auditors quickly understand specific lines of code without having to refer back to external documents constantly.</li><li><strong>Explanation of Complex Logic</strong>: If there are any areas of the code that involve complex or non-obvious logic, provide additional commentary to make it easier for auditors to follow. Complex algorithms, unusual tokenomics, or custom access control mechanisms should be thoroughly explained within the code.</li></ul><h4>4. Assumptions and Constraints (Specific to Smart Contracts)</h4><ul><li><strong>Developer Assumptions</strong>: Clearly state any assumptions that were made during the development process. For example, assumptions about gas limits, the expected behavior of external oracles, or restrictions on user input. These assumptions will guide the auditors in testing how the system behaves when those assumptions are challenged or broken.</li><li><strong>Security Constraints</strong>: List any specific security measures you have implemented or expect auditors to review. This might include reentrancy protections, safe arithmetic operations, or multi-sig control mechanisms. Specifying these helps auditors verify if the protections are sufficient or if there are any potential gaps.</li></ul><h4>5. Security Considerations (for Smart Contracts)</h4><ul><li><strong>Known Vulnerabilities</strong>: If there are areas in the contract where known vulnerabilities have been considered and mitigated (e.g., handling reentrancy, preventing overflow/underflow, ensuring gas efficiency), document how these issues were addressed.</li><li><strong>External Dependencies</strong>: Highlight any external dependencies or third-party services your smart contracts rely on. For example, if your contract interacts with an external price oracle or a specific blockchain service, make sure this is documented. Auditors need to know about any interactions with external systems that could introduce risks.</li></ul><h4>6. Test Coverage</h4><ul><li><strong>Unit and Integration Tests</strong>: Provide detailed information about the test suite you have implemented for the smart contract. This should include:</li></ul><p>1- Unit tests that cover individual functions. <br>2- Integration tests that simulate interactions between multiple contracts.<br>3- Edge cases and stress tests (e.g., testing large input values or gas limits).</p><ul><li><strong>Test Results</strong>: Include the results of these tests. If any tests failed, explain why and what steps are being taken to address those issues.</li><li><strong>Continuous Integration</strong>: Mention if you are using any CI/CD tools to automatically run tests during development. This shows auditors that the project maintains a high standard of quality control.</li></ul><h4>7. Versioning and Change Log</h4><ul><li><strong>Contract Versions</strong>: Clearly indicate which version of the smart contract is being submitted for audit. If there are multiple versions or iterations, ensure that auditors are reviewing the correct one. Provide a link to a versioned repository (e.g., GitHub) where the auditors can verify the code’s history and compare it to previous versions.</li><li><strong>Change Log</strong>: Maintain a detailed change log that documents any modifications made to the codebase, particularly after the audit begins. This ensures transparency and allows auditors to keep track of any new changes that could impact the security of the contract.</li></ul><h4>8. Flow Diagrams and Interaction Models</h4><ul><li><strong>Transaction Flows</strong>: Use flow diagrams to illustrate how transactions flow through the smart contract system. For instance, show how funds are transferred, how state changes are managed, and how users or external contracts interact with your system.</li><li><strong>Interaction Models</strong>: Provide models that show how various actors (e.g., users, admin, external contracts) interact with the smart contract. This helps auditors assess whether proper access control mechanisms are in place and whether critical functions can be exploited.</li></ul><p>Proper documentation is more than just a courtesy to the audit team — it is an essential part of the security process. Documentation helps bridge the gap between your development team’s understanding of the project and the auditors’ fresh perspective. It reduces inefficiencies, minimizes the risk of missing critical vulnerabilities, and ensures a more thorough and effective audit.</p><p>Inadequate documentation can lead to delays, assumptions that obscure vulnerabilities, and ultimately, less secure code. By prioritizing clear and comprehensive documentation, you set the stage for a successful audit that delivers meaningful security improvements.</p><h3>The Importance of Testing in Auditing</h3><p>Even with the most experienced and capable human auditors, testing remains a crucial element of the auditing process. Human auditors, no matter how skilled, are subject to limitations such as fatigue, lapses in concentration, tunnel vision, and limited stamina. These natural human limitations can result in overlooked vulnerabilities or errors, making it essential to complement manual auditing with rigorous, automated testing.</p><h4>Why Testing Complements Auditors</h4><p>Auditors can thoroughly review code, analyze system architecture, and identify vulnerabilities, but they are still susceptible to missing subtle bugs due to the sheer volume of code or complexity of the system. Moreover, as audits are often performed under time constraints, even the most meticulous auditor may miss issues as their focus narrows or shifts.</p><p>This is where automated testing comes in. Automated tests are highly efficient and unbiased — they run consistently without the limitations of human auditors, helping to ensure that important <strong>invariants</strong> in the codebase are upheld. Invariably, computers excel at tasks that require constant, repeatable processes, such as verifying the correctness of functions and ensuring that critical conditions are maintained under all possible inputs.</p><p>To better illustrate this, consider an analogy: a human auditor is like a detective combing through a crime scene, looking for clues with great attention to detail. They may eventually become tired or miss subtle details after hours of work. However, automated tests are like surveillance cameras — they record and monitor every detail continuously and never tire. They don’t replace the detective’s expertise but act as a reliable supplement, covering more ground than a human could alone.</p><h4>Automated Testing: Why It’s Essential</h4><ul><li><strong>Eliminating Human Error</strong>: Automated testing helps mitigate human error by continuously checking for specific conditions, ensuring that each function or line of code behaves as expected across all potential inputs and scenarios.</li><li><strong>Time Efficiency</strong>: Machines can run thousands of tests in the time it takes for a human auditor to manually review just a few key sections of the code. This drastically speeds up the audit process and ensures that more potential vulnerabilities are tested in less time.</li><li><strong>Consistency and Reliability</strong>: Automated tests run the same checks every time, ensuring that tests are repeatable and accurate. This means auditors can rely on the consistency of test results without worrying about human factors like fatigue or distractions.</li></ul><p>Now, let’s dive into different types of testing that can be applied during an audit and why they are crucial.</p><h3>Unit Testing</h3><p>The first type of testing that plays a significant role in smart contract auditing is <strong>unit testing</strong>. Unit testing focuses on the smallest, individual parts of a system — usually functions or methods — and verifies that each one works correctly in isolation. Here’s why it’s essential:</p><h4>1. Positive and Negative Testing</h4><p>In unit testing, there are two main types of tests: <strong>positive testing</strong> and <strong>negative testing</strong>.</p><ul><li><strong>Positive Testing</strong>: This type of test checks whether a function behaves as expected under normal, valid conditions. For example, if a smart contract function is supposed to transfer tokens, positive tests will verify that the function transfers the correct amount to the intended address when valid input is provided. This ensures that the code works as intended in common use cases.</li><li><strong>Negative Testing</strong>: Negative testing, on the other hand, tests how the system behaves when given invalid or unexpected input. It is designed to break the system, pushing it beyond its normal bounds to uncover potential vulnerabilities. For instance, in a token transfer function, negative tests may attempt to transfer more tokens than the sender owns or to an invalid address. These tests check whether the smart contract handles edge cases gracefully and securely without causing unexpected failures or exploits.</li></ul><p>Both positive and negative testing are crucial for catching a wide range of bugs. Positive tests ensure the system works as intended under typical conditions, while negative tests identify how well it defends against abnormal or malicious input. Without negative testing, it’s easy to overlook edge cases or scenarios that hackers might exploit to break the system.</p><h4>2. Integration Testing</h4><p>Integration testing is crucial in order to test your code in an environment as close to a production environment as possible. Whilst unit testing will address various issues in smaller units of code, this variant of testing involves putting the protocol together and deploying the contract on a forked mainnet environment which will assess how the contracts will react to each other as well as untrusted external contracts. This will allow the developers to make proper assertions about external contracts and the data returned from other contracts to ensure the code is functioning as expected. Node urls for forking can be found on various platforms such as Alchemy and Infura.</p><p>References:</p><ul><li><a href="https://www.infura.io/">https://www.infura.io/</a></li><li><a href="https://www.alchemy.com/">https://www.alchemy.com/</a></li></ul><h4>3. Fuzz Testing (A variant of stress testing code)</h4><p>While you should always be security conscious while writing the code for your protocol in a passive manner, fuzz testing is the first active step to taking security measures when fortifying your code base. Fuzz testing involves inputting a large sample size of random data into your functions to ensure that they are sufficiently handling edge case scenarios which may cause the code to behave in an unexpected way as these edge cases could be exploited by potential attackers.</p><p>This technique is most effective when rigorously testing your mathematical libraries to ensure that under a large amount of data, your code still behaves as expected and is handling input accordingly whether it be invalid or valid input data.</p><p>References:</p><ul><li><a href="https://book.getfoundry.sh/forge/fuzz-testing">https://book.getfoundry.sh/forge/fuzz-testing</a></li></ul><h4>4. Beta Testing</h4><p>Beta testing is quite an uncommon way to test your codebase but is highly recommended as it’s an effective way to test it’s resiliency under a significant amount of user traffic and was used by notable protocols such as Eigen Layer, ZKSync and Starknet. This involves the use of public test nets where you can deploy your contracts and configure them as though they are in a production environment.</p><p>Various test nets exist which may include the following:</p><ul><li>Ethereum (Goerli)</li><li>Arbitrum (Arbitrum Sepolia)</li><li>Optimism (Optimism Sepolia)</li><li>Starknet (Starknet Goerli)</li><li>Solana (Solana Devnet)</li></ul><p>Testnet native currency can be found through the various faucets for their corresponding testnet. You can encourage your users to use your protocol as though it was deployed in production for the purpose of bug fixing.</p><ul><li>Pro Tip: If your protocol is deploying a DAO token, consider offering a small portion of the total supply to your loyal users who use your dapp in beta testing to incentivize the most amount of users. This may also include individual rewards for exploitable bug reports and their suggested fix. The state of the testnet blockchain at a certain point in time can undergo a snapshot to capture addresses who have interacted with your deployed contracts.</li></ul><p>References:</p><ul><li><a href="https://ethereum.org/en/developers/docs/networks/">https://ethereum.org/en/developers/docs/networks/</a></li><li><a href="https://solana.com/docs/core/clusters#devnet">https://solana.com/docs/core/clusters#devnet</a></li></ul><h4>Pre Audit Checks</h4><p><strong>1. Static Analysers</strong></p><p>Static analysers and static code analysis play an important role in securing your code at a basic level. They are responsible for examining your codebase without actually executing the contract. This is used as one of the first techniques by security professionals in order to capture low hanging fruit which may pose a risk to your protocol. These tools will also address the various programming standards which may be violated for the language you are using. The go-to piece of software which can be used for Solidity is the Slither Static Analyser built using Python3 which will assess the inheritance graph and the flow of code execution in the smart contract. Alternatively, if you intend to deploy to Solana, whilst tools for this environment are not as sophisticated as Solidity (but is very quickly improving), semgrep could be a good way to perform static analysis on your codebase. This technique can be very helpful in getting the most bang for your buck during the security review as the personnel assigned to your engagement can draw most of their attention to High and Medium level findings as opposed to using more time than needed on low hanging fruit.</p><p>References and Suggested Tooling:</p><ul><li><a href="https://research.kudelskisecurity.com/2021/04/14/advancing-rust-support-in-semgrep/">https://research.kudelskisecurity.com/2021/04/14/advancing-rust-support-in-semgrep/</a></li><li><a href="https://github.com/crytic/slither">https://github.com/crytic/slither</a></li><li>L3X — An AI-Driven Static Analyzer for Solidity and Rust by VulnPlanet (<a href="https://github.com/VulnPlanet/l3x">https://github.com/VulnPlanet/l3x</a>)</li></ul><p><strong>2. Continuous Integration</strong></p><p>Continuous integration is the process in software development which handles the automation of integrating new code changes and should be one the the first things you set up when you start a new project. When a developer writes new code and pushes such code to the repository, the (unit, integration, fuzz) tests and static analysers are automatically run by the CI/CD pipeline. If any problems are detected, the developer will be required to make the relevant changes and push the code again to the repository as the rules (typically in a .yaml file) in place will not allow the code to be merged. The workflow is as followed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GEusmEQWH0e3Ew-h1IXS2w.png" /></figure><p>This makes it easy to have maximum visibility by all developers over the test results within the codebase which will allow swift action to remediate any issues.</p><p>References:</p><ul><li><a href="https://docs.github.com/en/actions/writing-workflows/quickstart">https://docs.github.com/en/actions/writing-workflows/quickstart</a></li><li><a href="https://docs.gitlab.com/ee/ci/index.html">https://docs.gitlab.com/ee/ci/index.html</a></li></ul><h4>The Importance of the Audit Report and Working with Your Security Team</h4><p>One of the primary values of an audit report is that it provides a <strong>comprehensive overview of security vulnerabilities</strong> present in the system. This allows the development team to clearly understand each vulnerability, its impact, and how to remediate it effectively. Without this thorough understanding, it would be difficult to prioritize and address security issues, leading to potential exploitation. In order to achieve a thorough security audit, the developers should have finished implementing all features and changes. In addition to this, a security audit should be booked well in advance to ensure that there is adequate time for the security team to discover the most critical vulnerabilities as these can take time to find.</p><p>Another critical aspect of the audit report is the <strong>classification of vulnerabilities by severity</strong>, which helps the development team focus on the most critical issues first. Typically, vulnerabilities are classified into categories such as critical, high, medium, and low severity based on both the potential impact and the likelihood of the vulnerability being exploited. By organizing vulnerabilities in this manner, the team can allocate resources efficiently, ensuring that the most dangerous risks are mitigated first.</p><p>A commonly used severity classification system in the industry is the <strong>Immunefi Severity System</strong>, which categorizes vulnerabilities by their impact and the probability of occurrence. This structured system helps developers and auditors stay aligned on which vulnerabilities pose the greatest risk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*eSQr3KRWwab7UXSo-Pm1GQ.png" /></figure><h4>Levels of Effort in Exploitation</h4><p>When assessing vulnerabilities, it’s important to consider the <strong>difficulty of exploitation</strong> — how easy or challenging it would be for an attacker to leverage a specific vulnerability. The difficulty level typically correlates with the resources, skills, and time required to execute the attack successfully. Here’s a breakdown of how effort levels are often categorized:</p><ul><li><strong>Low Effort to Exploit, High Likelihood of Exploitation</strong>: These vulnerabilities are relatively easy for attackers to exploit, typically requiring minimal resources or technical skills. They can often be triggered consistently and may not involve complex attack paths. For instance, attackers may only need to pay minimal gas fees or protocol fees to exploit a flaw, or they could bypass weak access controls with no authentication required.</li><li><strong>Medium Effort to Exploit, Medium Likelihood of Exploitation</strong>: Medium-level vulnerabilities require more resources, time, or collaboration to exploit. Attackers may need a certain level of capital to perform front-running attacks or collaborate with miners to manipulate block ordering. The exploitation process could involve a combination of common techniques, such as manipulating external oracles or using more sophisticated methods to trigger the vulnerability.</li><li><strong>High Effort to Exploit, Low Likelihood of Exploitation</strong>: High-effort exploits involve significant resources, strict conditions, or substantial time to carry out. For example, an attacker may need to gain access to privileged roles, invest large amounts of capital, or exploit unpredictable factors like hash manipulation. These types of vulnerabilities are harder to trigger but may still pose serious risks if left unaddressed.</li></ul><p>By understanding the complexity and cost of exploitation, the security team can assess whether vulnerabilities are likely to be targeted by attackers. Higher-effort exploits are less likely to be pursued but could still result in substantial damage if they are successfully executed. On the other hand, low-effort exploits are more likely to be targeted, as they require minimal effort and can yield significant rewards. Thus, the audit report should clearly explain not only the severity of each vulnerability but also how difficult it is to exploit, helping the development team prioritize fixes effectively.</p><p>Ultimately, the audit report acts as both a diagnostic tool and a roadmap for improving security, enabling the development team to systematically address vulnerabilities and strengthen the system against future attacks. Working closely with the security team ensures that every issue is well-understood, mitigated, and retested, creating a robust defense mechanism for the project.</p><p>Another crucial aspect of the audit report, beyond identifying vulnerabilities, is the <strong>recommended mitigation steps</strong>. This section is as important as discovering the vulnerabilities because it provides a <strong>solution to the problem that has been reviewed and validated by the external auditors</strong>.</p><p>If an audit report discloses vulnerabilities without providing clear mitigation steps, the development team might attempt to fix the issues independently. However, without further review, there’s no guarantee that the new fix is free from additional bugs or security flaws. The mitigations suggested by the external auditors are designed with security in mind, and they have been analyzed to ensure they address the root of the problem without introducing new risks. By following these recommendations, the development team can confidently implement fixes knowing they have been reviewed by security experts.</p><p>That being said, the recommended solutions are just that — <strong>recommendations</strong>. If the proposed fix doesn’t align with certain functionalities or goals of the development team, adjustments can be made. However, it’s crucial that any modifications to the suggested fix are reviewed once again, either by the external auditors or through an additional audit, to ensure the revised solution resolves the vulnerability without introducing new issues. This highlights the importance of ongoing collaboration between the development team and the external audit firm to ensure both functionality and security are maintained.</p><h3>Addressing Post-Audit Changes</h3><p>Once an audit is completed, the development team typically applies the recommended fixes to their codebase, often by pushing new versions to platforms like GitHub. However, it is <strong>crucial</strong> that these post-audit changes are reviewed again by the auditing team. This step ensures that the identified vulnerabilities have not only been addressed but also that the fixes were <strong>implemented correctly and without introducing new issues</strong>.</p><p>In many cases, developers may inadvertently introduce new vulnerabilities while making changes, especially if they opt for a custom solution instead of following the auditor’s recommendations precisely. Alternatively, the recommended fix may have been applied incorrectly, leaving the system exposed. A post-implementation review by the audit team provides a <strong>critical layer of verification</strong>, ensuring that the system is secure after all changes — whether additions or subtractions — are made.</p><p>This process helps maintain the integrity of the audit and reduces the likelihood of introducing further risks, ultimately ensuring the code is secure and ready for production. Regular re-evaluation after fixes is a best practice that prevents regression or the emergence of new security threats.</p><p>Once the audit is completed, it is considered best practice to make the audit report publicly available. Doing so increases <strong>transparency</strong>, allowing stakeholders and users to gain confidence in the security and overall health of the project. By sharing the audit findings, the project demonstrates a strong commitment to security and accountability, which can foster greater trust within the community.</p><p>Additionally, maintaining a close relationship with the audit firm is highly beneficial post-audit. As the project evolves and new changes are implemented, it’s important to ensure that these changes are thoroughly reviewed and rigorously tested. This relationship makes it easier to schedule follow-up audits when needed, ensuring that the code remains secure as the project grows.</p><p>Finally, implementing a <strong>bug bounty program</strong> is another excellent way to enhance security. By having previous audit reports publicly accessible, security researchers and white-hat hackers can better understand the system and identify potential vulnerabilities, contributing to ongoing security improvements. This proactive approach encourages collaboration with the wider security community and strengthens the project’s resilience against threats.</p><h3>Closing Thoughts and Contingency</h3><p>Review this document carefully, and keep it handy while you’re going through your development life cycle. This document can also be used to educate your development team about the processes in addition to integrating security into your Software Development Life Cycle. Even assuming all bases are covered, this process is not a silver bullet and shouldn’t be treated as such. Some of the most elite development teams have also suffered breaches in their contracts due to errors in their code. One should always assume that they are either being targeted or about to be attacked in a security breach, and as a result, your team should always have a contingency plan in place (which should hopefully never need to be used).</p><p>Consider the case study of Conic Finance suffered a loss of approximately $4.2M in funds due to a read only reentrancy vulnerability followed by sandwich attacks due to imbalanced Omni pools after the reentrancy. Many in the community thought that they would never recover and come back from such a devastating attack. However, at the end of 2023 they vowed to make users whole again by creating a debt pool where the LP Token (cncDT) would have a total supply of 4,337,233 — the total amount lost in the breach. Users who were affected by the attack would be able to claim debt tokens which can freely be traded on the open market, as platform fees would be redirected to the debt pool to repay the users their losses which can be redeemed for stablecoin. CNC token surged following the announcement of this plan as they were trusted by the users, which is why it is important to be transparent and open with the community.</p><p>References:</p><ul><li><a href="https://www.immunebytes.com/blog/conic-finance-detailed-hack-analysis-july-21/">https://www.immunebytes.com/blog/conic-finance-detailed-hack-analysis-july-21/</a></li><li><a href="https://www.coindesk.com/markets/2023/12/12/defi-platform-conic-finances-cnc-token-surges-50-as-the-protocol-plots-comeback-after-hack/">https://www.coindesk.com/markets/2023/12/12/defi-platform-conic-finances-cnc-token-surges-50-as-the-protocol-plots-comeback-after-hack/</a></li><li><a href="https://docs.conic.finance/conic-finance/liquidity-providers/conic-debt-pool">https://docs.conic.finance/conic-finance/liquidity-providers/conic-debt-pool</a></li></ul><h4><strong>Ready to secure your project?</strong></h4><p>Zokyo is a leading web3 security firm dedicated to protecting blockchain organizations from cyber threats.</p><p>We specialize in identifying web3 cyber threats and ensuring the security of your code, advising clients across major ecosystems like EVM, Solana, Cosmos, Move, and more. Whether you’re developing wallets, cross-chain infrastructure, or L1s/L2s, we provide tailored, comprehensive security solutions.</p><p>Trust Zokyo to safeguard your reputation and secure your code. <a href="https://zokyo.io/"><strong>Contact us now to schedule your audit</strong></a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db6041677abe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zokyo-io/security-audits-are-essential-even-for-the-most-skilled-developers-db6041677abe">Preparing for the Challenges of Smart Contract Audits</a> was originally published in <a href="https://medium.com/zokyo-io">Zokyo_io</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring AI Attacks: The Top 10 Vulnerabilities in Large Language Models (LLMs)]]></title>
            <link>https://medium.com/zokyo-io/exploring-ai-attacks-the-top-10-vulnerabilities-in-large-language-models-llms-778f68a749f3?source=rss----adc3a5112af0---4</link>
            <guid isPermaLink="false">https://medium.com/p/778f68a749f3</guid>
            <dc:creator><![CDATA[Nuno Teodoro]]></dc:creator>
            <pubDate>Wed, 18 Sep 2024 15:14:50 GMT</pubDate>
            <atom:updated>2024-09-18T15:14:50.169Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2uLDjHzO_sWHBa8VecFNvA.png" /></figure><p>As <strong>Large Language Models (LLMs)</strong> become increasingly integral to various applications, from chatbots to financial services, their vulnerabilities also become a prime target for malicious actors. Security issues in LLMs can lead to devastating consequences, such as data breaches, unauthorized access, and system manipulation.</p><p>Understanding these risks is crucial as technology advances and integrates further into critical systems. In this article, we delve into the top 10 attacks on LLMs, offering real-world examples and mitigation strategies to ensure that organizations can safeguard their AI systems.</p><h3>LLM01: Prompt Injections</h3><p>Prompt injection attacks involve manipulating LLMs by crafting specific inputs that cause the model to behave unexpectedly or disclose sensitive information. These attacks can lead to unauthorized access, data breaches, or compromised decision-making.</p><p><strong>Example</strong>: An attacker could inject a prompt into a chatbot that tricks the LLM into revealing confidential user data, such as account passwords or personal identification numbers (PINs).</p><h3>LLM02: Insecure Output Handling</h3><p>Insecure output handling occurs when the outputs generated by an LLM are used without proper validation or sanitization. This can lead to downstream security exploits, such as executing unintended commands or exposing sensitive data.</p><p><strong>Example</strong>: A financial assistant powered by an LLM might output a code snippet that, if executed without verification, could compromise an entire financial system by transferring funds to an unauthorized account.</p><h3>LLM03: Training Data Poisoning</h3><p>Training data poisoning involves introducing malicious or biased data into the LLM’s training set, which can compromise the model’s accuracy, ethical behavior, or security. This attack targets the foundational data, making the model unreliable.</p><p><strong>Example</strong>: Poisoned data in a recommendation system could lead an LLM to unfairly favor certain products, misleading consumers and distorting market competition.</p><h3>LLM04: Model Denial of Service (DoS)</h3><p>Model Denial of Service (DoS) attacks are when an attacker overloads an LLM with excessive or resource-heavy operations, leading to service disruptions, increased operational costs, or degraded performance.</p><p><strong>Example</strong>: An attacker might flood an LLM-based customer service system with complex queries, causing it to slow down or crash, leading to service outages.</p><h3>LLM05: Supply Chain Vulnerabilities</h3><p>Supply chain vulnerabilities exploit weaknesses in the components, services, or datasets that an LLM depends on. If any part of the supply chain is compromised, it can undermine the entire model, leading to data breaches or system failures.</p><p><strong>Example</strong>: A compromised pre-trained model could contain hidden backdoors, allowing attackers to later control or manipulate the deployed LLM.</p><h3>LLM06: Sensitive Information Disclosure</h3><p>Sensitive information disclosure refers to situations where an LLM inadvertently reveals confidential or sensitive information through its outputs. This can happen if the model was trained on data that includes private information or if it is prompted in a way that elicits such data.</p><p><strong>Example</strong>: An LLM trained on internal company emails might inadvertently disclose sensitive project details or personal employee information in response to a query.</p><h3>LLM07: Insecure Plugin Design</h3><p>Insecure plugin design refers to vulnerabilities in the plugins or extensions that interact with LLMs. If these plugins are designed without proper security measures, they can process untrusted inputs, leading to severe exploits such as remote code execution.</p><p><strong>Example</strong>: A plugin designed to interact with an LLM could be exploited to run unauthorized scripts on the server, compromising the entire system.</p><h3>LLM08: Excessive Agency</h3><p>Excessive agency occurs when LLMs are granted too much autonomy, allowing them to take actions without sufficient oversight. This can lead to unintended consequences that jeopardize the reliability, privacy, and trustworthiness of the system.</p><p><strong>Example</strong>: An autonomous LLM-based trading bot might make risky investments based on flawed logic, leading to significant financial losses.</p><h3>LLM09: Overreliance</h3><p>Overreliance on LLMs involves trusting their outputs without critical assessment, which can lead to compromised decision-making, security vulnerabilities, or legal liabilities. Users may assume the LLM is always correct, which can be dangerous.</p><p><strong>Example</strong>: A legal professional might rely on an LLM-generated contract without thorough review, only to find that it contains errors or omissions that lead to legal disputes.</p><h3>LLM10: Model Theft</h3><p>Model theft refers to unauthorized access to proprietary LLMs, where attackers steal the model itself or the intellectual property within it. This can result in loss of competitive advantage, exposure of sensitive data, or even the illegal distribution of the model.</p><p><strong>Example</strong>: An attacker could leak an LLM’s underlying architecture and weights, then replicate or sell the model, undermining the original developer’s business.</p><h3>Mitigation Strategies</h3><p>To mitigate these risks, organizations must implement robust security practices. Here are some key strategies to protect LLMs:</p><ul><li><strong>Prompt sanitization and validation</strong>: Ensure inputs are carefully checked before being processed by the model.</li><li><strong>Output review mechanisms</strong>: Implement human-in-the-loop systems to validate critical outputs.</li><li><strong>Secure model training</strong>: Use secure environments and training data to prevent poisoning.</li><li><strong>Access controls</strong>: Implement strong authentication and authorization measures to protect models from unauthorized access.</li><li><strong>Undergo security assessments</strong>: Regularly audit and mitigate vulnerabilities in LLMs to prevent exploitation.</li></ul><h3>Conclusion</h3><p>As LLMs continue to play a significant role in industries ranging from finance to healthcare, understanding their vulnerabilities becomes more crucial. By recognizing and addressing the top 10 security threats outlined in this article, organizations can safeguard their AI systems from potential exploitation.</p><p><strong>Reach out to Zokyo</strong> for a comprehensive LLM security assessment and ensure your models remain secure against evolving threats.</p><h3>About Zokyo</h3><p>Zokyo is a leading web3 security firm focused on protecting blockchain organizations from cyber threats. We specialize in offensive cybersecurity, token economics, cryptography, and reverse engineering, advising across ecosystems like EVM, Solana, Ton, Move, and more. Zokyo Ventures, our tech-first investment arm, strategically backs early-stage digital asset companies, driving innovation in the space.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=778f68a749f3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zokyo-io/exploring-ai-attacks-the-top-10-vulnerabilities-in-large-language-models-llms-778f68a749f3">Exploring AI Attacks: The Top 10 Vulnerabilities in Large Language Models (LLMs)</a> was originally published in <a href="https://medium.com/zokyo-io">Zokyo_io</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Penpie PostMortem: Analysis of the $27M Reentrancy Exploit]]></title>
            <link>https://medium.com/zokyo-io/penpie-postmortem-analysis-of-the-27m-reentrancy-exploit-cd9e4aa6f8e7?source=rss----adc3a5112af0---4</link>
            <guid isPermaLink="false">https://medium.com/p/cd9e4aa6f8e7</guid>
            <dc:creator><![CDATA[Nuno Teodoro]]></dc:creator>
            <pubDate>Wed, 04 Sep 2024 18:16:42 GMT</pubDate>
            <atom:updated>2024-09-04T18:16:42.086Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5wbQ4ZdkIU0-5ObO1RJUpA.png" /></figure><p>The Penpie platform — a farming protocol built atop Pendle — suffered a devastating reentrancy attack that led to the loss of $27 million in client funds.</p><p>The attack occurred yesterday, September 3, after a vulnerability in Penpie’s smart contract allowed the hacker to manipulate the system, exploiting a critical flaw in how markets were registered and validated within the protocol.</p><p><a href="https://metasleuth.io/result/eth/0x7a2f4d625fb21f5e51562ce8dc2e722e12a61d1b?source=141cdbc9-83e8-4ce4-97e3-38b95bdf64c9">* <em>Here is a visual representation of the attack.</em></a></p><p>Penpie immediately suspended all deposits and withdrawals and contacted security experts to prevent further damage. The protocol’s swift response, in coordination with Pendle, helped to protect an additional $105 million that could have been at risk.</p><p>We will be analyzing the incident’s root cause, providing analysis from our cybersecurity experts.</p><h3>Attack details</h3><h4>Attack Setup:</h4><ul><li>The main contract for the attack is PendleStaking but other important contracts that lead to the drainage of $27 million from the Penpie pool are PendleMarketRegisterHelper and PendleMarketFactoryV3.</li><li>The attacker could hack into Penpie by passing a fake pool address in the batchHarvestMarketRewards(...) method. Although this method checks if a market is valid or not validity depends on other contracts as well.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h89qDR72dk86p34x8llqJw.png" /></figure><ul><li>A market can be registered using the method registerMarket(...) in the same contract but it can be done only by the contract “PendleMarketRegisterHelper”.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*rkYfM4bekKg4RywJQOEM0Q.png" /></figure><ul><li>When we check the PendleMarketRegisterHelpercontract, it has another method registerPenpiePool, which validates the pool address (but how?) and registers the market in the PendleStaking contract by calling registerPool(...) method.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fQ6jwNBikwUVFiSgVBEqEw.png" /></figure><ul><li>As we can see in the above code, the method registerPenpiePool is permissionless but uses a modifier onlyVerifiedMarket. When we check this modifier, we find that it is checking if the market address is valid or not by calling PendleMarketFactory contract. Let’s check the PendleMarketFactory then.</li><li>The contract PendleMarketFactory has the following method to check the valid market contract.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iA0S5n6rJfmnHvgl1kqGuw.png" /></figure><ul><li>But how are values pushed into the allMarket set and who can do it? The answer is in the below code.​​</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lP-T0RrOT1eUS_VwY_yhmA.png" /></figure><ul><li>As we can see from the above code, anyone can create a new market for a token and get its market validated as the method createNewMarket(...) is permissionless.</li><li>This means any user can register a market (malicious) in the PendleStaking contract and harvest rewards.</li><li>So the attacker prepared a Standard Yield token, created a new market using it, configured two high-value PENDLE-LPT market tokens as reward tokens, and finally resisted it on the PendleStaking contract.</li></ul><h4>Attack Flow:</h4><ul><li>The attacker calls the PendleStaking.batchHarvestMarketRewards(...) method to harvest rewards which were calculated based on the difference in balanceOf() before and after the redeemRewards(...) method was called.</li><li>Method redeemReward(...) calls the claimRewards() for the specific market (malicious) which allowed the attacker to re-enter the PendleStaking.depositMarket(...) method.</li><li>Here attacker deposited the two high-value LP tokens to mint shares and also these LP tokens were considered reward tokens.</li><li>Then attacker can withdraw the deposited LP tokens along with the minted shares and claim the reward to make his profit.</li></ul><h3>Zokyo update</h3><p>The _market parameter received in the batchHarvestMarketRewards(...) method was not expected to be malicious as in the earlier version of the code audited by Zokyo, only the owner (multi-sig) can register a pool.</p><p>Earlier, the registerPool(...) allowed only the owner to register a pool, unlike the current code which allows a contract to do the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*I2ubpY8wUQvJvtm6jR-bDw.png" /></figure><p>This complete attack was possible because the attacker was able to register a pool in the PendleStaking contract, due to the faulty code in the contract PendleMarketRegisterHelper which considers any market valid if it’s created by a permissionless method in PendleMarketfactoryV3 contract.</p><p>After registering the pool, the attacker used the malicious market to re-enter the contract and drain millions of dollars.</p><h3>Conclusion</h3><p>The Penpie exploit highlights a significant vulnerability in DeFi protocols, particularly around permissionless functions and insufficient validation mechanisms. For other DeFi platforms, this incident serves as a crucial lesson in securing smart contracts, maintaining rigorous controls on market creation, and ensuring rapid incident response strategies.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd9e4aa6f8e7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zokyo-io/penpie-postmortem-analysis-of-the-27m-reentrancy-exploit-cd9e4aa6f8e7">Penpie PostMortem: Analysis of the $27M Reentrancy Exploit</a> was originally published in <a href="https://medium.com/zokyo-io">Zokyo_io</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking Security: The Power of Penetration Testing]]></title>
            <link>https://medium.com/zokyo-io/unlocking-security-the-power-of-penetration-testing-b3c288e37ea0?source=rss----adc3a5112af0---4</link>
            <guid isPermaLink="false">https://medium.com/p/b3c288e37ea0</guid>
            <dc:creator><![CDATA[Nuno Teodoro]]></dc:creator>
            <pubDate>Thu, 29 Aug 2024 10:52:28 GMT</pubDate>
            <atom:updated>2024-08-29T10:52:28.742Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t-wklmrIFFyaPUmdhofhLA.png" /></figure><p>As the popularity of blockchain technology continues to rise, the security of crypto wallets — used to store and manage digital assets — has never been more crucial. Penetration testing, or “pen-testing,” plays a vital role in safeguarding these wallets.</p><p>This article delves into why penetration testing is essential for mobile and browser extension crypto wallets and what the process involves.</p><p><strong>Table of Contents</strong></p><blockquote><strong>Why Penetration Testing Matters<br>Lessons Learned from Historical Incidents<br>The Penetration Testing Process<br>Common Vulnerabilities in Crypto Wallets<br>Conclusion</strong></blockquote><h3>Why Penetration Testing Matters</h3><p>Crypto wallets are attractive targets for hackers because they hold valuable digital assets. A single breach can lead to devastating financial losses and severely damage user trust. Penetration testing offers a proactive approach, helping identify and fix potential security vulnerabilities before attackers can exploit them.</p><p><strong><em>Key Benefits of Penetration Testing:</em></strong></p><ul><li><strong>Protect Your Assets:</strong> Pen testing identifies and mitigates vulnerabilities that could result in the theft of digital assets.</li><li><strong>Build Trust:</strong> Demonstrating a strong commitment to security enhances user confidence in your wallet.</li><li><strong>Meet Compliance Standards:</strong> Penetration testing ensures adherence to regulatory and industry security standards.</li></ul><h3>Lessons Learned from Historical Incidents</h3><p>The <strong>Atomic Wallet Hack</strong> of 2023 serves as a stark reminder of the risks associated with crypto wallets. This attack resulted in the theft of over $35 million in digital assets, highlighting the need for:</p><ul><li><strong>Regular Security Audits:</strong> Conduct frequent audits and penetration tests to uncover and address vulnerabilities.</li><li><strong>User Education:</strong> Educate users on the risks and best practices for securing their wallets, particularly against phishing attacks.</li><li><strong>Immediate Response Plans:</strong> Develop and maintain protocols to respond swiftly to security incidents, minimizing their impact.</li></ul><h3>The Penetration Testing Process</h3><p>Penetration testing involves several critical steps to ensure comprehensive security for crypto wallets:</p><ol><li><strong>Information Gathering: </strong>Collect detailed information about the wallet’s architecture and identify potential weaknesses.</li><li><strong>Threat Modeling: </strong>Identify and prioritize potential threats based on their likelihood and impact.</li><li><strong>Vulnerability Analysis: </strong>Use advanced tools and techniques to detect security weaknesses. Also, test for common issues such as insecure communications and data storage vulnerabilities.</li><li><strong>Exploitation: </strong>Attempt to exploit identified vulnerabilities in a controlled environment to understand their potential impact.</li><li><strong>Post-Exploitation: </strong>Assess the potential damage that could result from an exploited vulnerability.</li><li><strong>Reporting: </strong>Compile a comprehensive report detailing the findings and providing actionable recommendations to enhance security.</li></ol><h3>Common Vulnerabilities in Crypto Wallets</h3><p>Crypto wallets often face several common vulnerabilities that need to be addressed through penetration testing:</p><ul><li><strong>Weak Passwords and Lack of MFA: </strong>Ensure strong password policies and implement multi-factor authentication (MFA) to prevent unauthorized access.</li><li><strong>Insecure Data Storage: </strong>Encrypt private keys and sensitive data both at rest and in transit to protect against theft and tampering.</li><li><strong>Unencrypted Communications: U</strong>se secure communication protocols like HTTPS to prevent data interception during transmission.</li><li><strong>API Vulnerabilities: </strong>Secure API endpoints to prevent unauthorized access and potential data leaks.</li><li><strong>Jailbreak and Root Detection Issues: </strong>Implement mechanisms to detect if a device has been jailbroken (iOS) or rooted (Android), as these conditions can compromise the wallet’s security measures.</li></ul><h3>Conclusion</h3><p>Penetration testing is a vital component in the security of crypto wallets. By identifying and addressing vulnerabilities, Zokyo ensures the protection of digital assets and strengthens user trust.</p><p>Regular security assessments and strict adherence to best practices are essential for maintaining a secure and trustworthy crypto wallet. Contact us if you require further assistance with your Web3 protocol or startup.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3c288e37ea0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/zokyo-io/unlocking-security-the-power-of-penetration-testing-b3c288e37ea0">Unlocking Security: The Power of Penetration Testing</a> was originally published in <a href="https://medium.com/zokyo-io">Zokyo_io</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>