Delegatecall vulnerability: when borrowed code writes your storage

A delegatecall vulnerability is when a contract runs another contract's code with delegatecall and that code can write the caller's storage, spend its balance or act as the caller in ways the caller never meant to allow. The called code runs in the caller's context, so a delegatecall to an address a user can choose, to code that can change, or to a contract with a different storage layout hands that code full control. Only delegatecall into code you deployed and pinned, check that the layouts match, and never let a caller pick the target.

Last updated . 6 minute read. By the QuillAudits Team.

How does delegatecall work?

With delegatecall, the Solidity docs say, 'the code at the target address is executed in the context (i.e. at the address) of the calling contract', and 'Storage, current address and balance still refer to the calling contract, only the code is taken from the called address.' msg.sender and msg.value keep their values too.

That is how proxies and libraries work: the proxy keeps the storage and the funds, and the implementation supplies the code. It is also why delegatecall is dangerous. The called code writes slot numbers, not names, and it doesn't know or care what the caller keeps in those slots.

When does delegatecall become a vulnerability?

  • The target comes from user input. A router, a multicall or a plugin system that delegatecalls an address the caller passes lets the caller run any code as the contract. SWC-112 says to check a target derived from user input against a whitelist of trusted contracts.
  • The code at the target can change. If the target is upgradeable, or was deployed in a way that lets its code be replaced, a trusted address can start running different code.
  • The storage layouts don't match. The called code writes its first variable to slot 0, where the caller may keep its owner or its implementation address. See storage collision.
  • The target has no code. The EVM treats a call to an address without code as a success, and Solidity skips its code check for low-level calls, so a delegatecall into an empty address does nothing and reports success.
  • The called code assumes its own context. A contract written to be called normally checks msg.sender against its own owner variable. Called with delegatecall, that check reads the caller's storage instead.

What does vulnerable code look like?

This wallet lets anyone run a 'plugin' with delegatecall. It keeps its owner in slot 0, and so does the plugin an attacker writes.

Vulnerable: a delegatecall target chosen by the caller (illustrative, not audited code) PluginWallet.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

contract PluginWallet {
    address public owner; // slot 0

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

    // Meant for trusted plugins, but nothing checks which plugin runs or who asks.
    function runPlugin(address plugin, bytes calldata data) external {
        (bool ok, ) = plugin.delegatecall(data);
        require(ok, "plugin failed");
    }

    function withdraw(address payable to, uint256 amount) external {
        require(msg.sender == owner, "not owner");
        (bool ok, ) = to.call{value: amount}("");
        require(ok, "send failed");
    }

    receive() external payable {}
}

// What an attacker passes in. Run with delegatecall, it writes the wallet's slot 0,
// and msg.sender is still the attacker who called runPlugin.
contract TakeOwnership {
    address public owner; // slot 0, the same slot as PluginWallet.owner

    function run() external {
        owner = msg.sender;
    }
}

The attacker calls runPlugin(takeOwnership, abi.encodeCall(TakeOwnership.run, ())). The plugin's code runs in the wallet's storage, sets slot 0 to the attacker, and the attacker calls withdraw.

How do you fix it?

Only the owner may run plugins, only plugins the owner approved may run, and the approval pins the plugin's code hash, so an address whose code changes stops being approved. As a last line of defence, the wallet checks that its owner didn't change.

Fixed: owner-approved plugins pinned by code hash (illustrative, not audited code) PinnedPluginWallet.sol

// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;

contract PinnedPluginWallet {
    address public owner;
    mapping(address => bytes32) public approvedCodehash;

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

    function approvePlugin(address plugin) external {
        require(msg.sender == owner, "not owner");
        require(plugin.code.length > 0, "no code");
        approvedCodehash[plugin] = plugin.codehash;
    }

    function revokePlugin(address plugin) external {
        require(msg.sender == owner, "not owner");
        delete approvedCodehash[plugin];
    }

    function runPlugin(address plugin, bytes calldata data) external {
        require(msg.sender == owner, "not owner");
        bytes32 approved = approvedCodehash[plugin];
        // The code must be exactly what the owner approved, not just the same address.
        require(approved != bytes32(0) && plugin.codehash == approved, "plugin not approved");
        address ownerBefore = owner;
        (bool ok, ) = plugin.delegatecall(data);
        require(ok, "plugin failed");
        // A plugin must never change who controls the wallet.
        require(owner == ownerBefore, "owner changed");
    }

    function withdraw(address payable to, uint256 amount) external {
        require(msg.sender == owner, "not owner");
        (bool ok, ) = to.call{value: amount}("");
        require(ok, "send failed");
    }

    receive() external payable {}
}
  • Never take the target from calldata. Use a constant, an immutable, or an allowlist that only an owner or governance can change.
  • Pin code, not addresses. Compare codehash with the approved value; the Solidity docs note that codehash can be 0 for an empty account, so check that code exists too.
  • Keep critical state out of the way. Put the owner and any implementation address in hashed or namespaced slots such as ERC-7201 describes, so code written for another layout can't land on them by accident.
  • Use `call` for code you don't control. A normal call runs in the callee's own storage and can only do what the callee itself is allowed to do.
  • Keep delegatecall libraries stateless: no storage variables, no owner, no self-destruct.

How has delegatecall been exploited?

Protocol Furucombo
Date 27 February 2021
Chain Ethereum
Loss about $15M across 21 assets, by Furucombo's count
What happened Furucombo's proxy ran actions through delegatecall into handlers listed in a registry, and it used the same isValid check for the contracts allowed to call it and the contracts it would delegatecall into. Aave V2's lending pool proxy was registered as a valid caller, so it also counted as a valid target. The attacker had Furucombo delegatecall into that proxy's initialize function; the implementation slot it read was empty in Furucombo's own storage, so the call succeeded and set the implementation to the attacker's contract, which then pulled tokens from about 22 users who had approved Furucombo's proxy.
Sources Furucombo, rekt.news

The exploit ran at 16:47:53 UTC on 27 February 2021, and Furucombo's post-mortem records the Aave V2 lending pool being removed from the registry just under an hour later. rekt.news reported the loss as $14 million; the team counts 21 assets worth about $15 million.

Two of the conditions above met in one call: the target was chosen by the caller, limited only by a registry that mixed two kinds of trust, and the code that ran assumed its own context. An initializer that was safe inside Aave's proxy was open inside Furucombo's storage, so approvals users had given Furucombo became the attacker's to spend.

What should a reviewer check?

  • Search for every delegatecall, including in inline assembly, in inherited contracts and in helper functions that wrap it.
  • Where does each target address come from: a constant, an immutable, storage only an admin can write, or calldata?
  • Can the code at each target change: an upgradeable proxy, a contract whose code can be replaced, an address computed before anything was deployed there?
  • Do the caller and every possible target agree on the storage layout, slot by slot?
  • Does the called code use msg.sender, msg.value or its own balance, and is that still safe when they belong to the caller?
  • If a target has no code, does the caller notice, or does the empty delegatecall count as a success?
  • Is there a test that passes an attacker-written target and expects a revert, and one that checks the owner and implementation slots are unchanged after every allowed delegatecall?

How does QuillShield check for delegatecall vulnerabilities?

A delegatecall bug sits between two contracts, the one that delegates and the one whose code runs, so it shows up only when both are read together. In a QuillShield full audit of a Solidity codebase in a Foundry project, QuillShield builds a security graph of the code, lists the invariants it must keep, and has a separate reviewer agent try to disprove each finding before it reaches you. Each finding that holds up includes the exact lines, the impact, a recommended fix and, on full audits, a proof of concept.

Tell the audit which targets you trust: you can add context such as the whitepaper, trust assumptions, privileged roles and previous audit reports before it starts. When a pull request adds a module, a plugin or a new upgrade path, QuillShield checks it on GitHub or GitLab.com against the audit's security graph before you merge.

Run a full audit, priced from the lines of Solidity in scope and starting at $49 as the pricing page shows. Sign-up is free, and you see the exact price before anything is charged.

FAQ

What is the difference between call and delegatecall?

call runs the target's code in the target's own storage, with your contract as msg.sender. delegatecall runs the target's code in your contract's storage and balance, and keeps the original msg.sender and msg.value.

Is delegatecall safe in a proxy?

Yes, when only an admin can change the implementation, the storage layouts match, and nobody else can initialize the implementation. See uninitialized proxy for the last part.

Can a delegatecall target be trusted by its address alone?

Not if the code at that address can change. Compare its codehash with the one you approved, and re-approve after any upgrade.

Can a library still be destroyed under contracts that delegatecall into it?

Not as it once could. The Solidity docs say selfdestruct was deprecated in 0.8.18 and that from Cancun onwards it only sends the account's Ether to the recipient. Before that, Parity's post-mortem describes how killing one shared library in November 2017 blocked funds in 587 wallets that depended on it.

Sources

QuillShield is building the security layer between AI and money, so you can keep shipping between audits.

Sign-up is free, and new accounts get $50 in credit, good for up to half of an order.

  1. 1Sign up and import a repo
  2. 2See the exact price before anything is charged
  3. 3Approve it, and the audit starts