Crypto Training
Upgradeable Contracts: Initializers, UUPS Footguns, and Storage Discipline
How OpenZeppelin's initializer guard and UUPS upgrade path work at v5.7.0, and the ways they fail in production: uninitialized implementations, guards that can be passed twice, migrations that never ran, unauthorized upgrades and layout drift.
An upgradeable contract is two contracts. A proxy holds the state and the funds, an implementation holds the code, and delegatecall joins them. That split creates three duties that an ordinary contract does not have. State must be set up through a function, since the constructor cannot do it. That function must be closed to everyone except its intended caller, and closed for good after its one use. The storage layout must stay compatible from version to version.
Nearly all the incidents in this area are a failure of one of the three, and usually a plain one. This post uses OpenZeppelin Contracts v5.7.0 as the reference, because most production proxies descend from it, and each failure mode below comes with a case where it cost money or was caught in audit.
Why a constructor cannot do the job#
A constructor runs once, in the storage of the contract being deployed, which for an implementation is the implementation's own storage. The proxy's storage is untouched. Initial values in field declarations (uint256 public feeBps = 30;) compile into the constructor and are lost in the same way, while constant and immutable values survive because they live in the code. OpenZeppelin's guide Writing Upgradeable Contracts lists these rules.
Setup therefore moves into an ordinary external function, which anyone can call at any time unless something stops it. A test suite that deploys the implementation directly and calls initialize on it will pass while the real proxy deployment is broken, so the first thing we look for in a repository is whether its tests go through a proxy at all.
How the guard works#
Initializable keeps two fields, uint64 _initialized and bool _initializing, in an ERC-7201 namespace at slot 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00. Before v5.0 they were ordinary state variables, which in most inheritance orders put them in slot 0. Four pieces of the API read or write them.
| Piece | Passes when | Effect |
|---|---|---|
initializer | _initialized == 0 | sets it to 1 |
reinitializer(n) | _initialized < n | sets it to n |
onlyInitializing | _initializing is true | none, used by the __X_init functions of parent contracts |
_disableInitializers() | no initialization is in progress | sets _initialized to the maximum, so nothing can initialize that contract again |
A minimal UUPS implementation that uses these pieces correctly looks as follows. It compiles with Solidity 0.8.38 against v5.7.0, and its state lives in a namespace of its own.
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
contract VaultV1 is Initializable, OwnableUpgradeable, UUPSUpgradeable {
/// @custom:storage-location erc7201:example.vault
struct VaultStorage {
uint256 feeBps;
mapping(address => uint256) balances;
}
// keccak256(abi.encode(uint256(keccak256("example.vault")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant VAULT_STORAGE = 0xd1921ee58d28820c9487d4d5d3eec1942edd7f5897e909e18a400cd2422da100;
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers(); // locks the implementation contract itself
}
function initialize(address owner_, uint256 feeBps_) external initializer {
__Ownable_init(owner_);
_vault().feeBps = feeBps_;
}
function _authorizeUpgrade(address) internal override onlyOwner {}
function _vault() private pure returns (VaultStorage storage $) {
assembly {
$.slot := VAULT_STORAGE
}
}
}
Deployment and initialization belong in one transaction, which ERC1967Proxy supports through its constructor argument.
address proxy = address(new ERC1967Proxy(address(new VaultV1()), abi.encodeCall(VaultV1.initialize, (owner, 30))));
The initializer is open to someone else#
There are two addresses on which a stranger might call initialize, the proxy and the implementation.
The proxy is exposed when it is deployed in one transaction and initialized in another. That race, and the CPIMP technique that hides a successful one, are the subject of Deployment-Layer Security: CPIMP and the Proxy Initialization Race, so we only add one library fact here. Since v5.6.0 the constructors of ERC1967Proxy and TransparentUpgradeableProxy revert with ERC1967ProxyUninitialized when no initialization call is supplied.
The implementation is exposed whenever its own initialize was never called and never disabled. It is a normal contract at a public address, and whoever initializes it becomes its owner in its own storage. Whether that matters depends on what that owner can make the implementation do.
The Parity multisig library is the oldest answer. Each wallet delegated to one shared library contract, nobody had initialized the library itself, and in November 2017 a user did so, became its owner and called its kill function. The selfdestruct removed the code that 587 wallets depended on and froze 513,774 ETH (writeup).
UUPS brought the same shape back in 2021. In OpenZeppelin Contracts 4.1.0 to 4.3.1, an attacker who initialized a UUPS implementation could call upgradeToAndCall on the implementation directly and have it delegatecall into a contract that self-destructs. Because UUPS keeps the upgrade function in the implementation, every proxy pointing at it would have been left without logic and without a way to upgrade. The post-mortem reports that the team itself initialized more than 150 exposed implementations across networks and knew of no loss. The fix in 4.3.2 was the onlyProxy modifier, which is still in v5.7.0.
Two things have changed since. EIP-6780, part of the Cancun fork, means SELFDESTRUCT no longer removes code that was deployed in an earlier transaction, which takes away the bricking step on chains that have adopted it. And _disableInitializers() in the constructor is now the documented default. We would still report an implementation that can be initialized, because any role or approval that the implementation's own address holds becomes available to whoever claims it, and the fix costs one line.
The guard can be passed a second time#
A proxy that was initialized properly is still at risk if initialize can run again, because the function's whole purpose is to assign owners and parameters.
The guard can be defeated from outside its own code. Audius lost control of its governance in July 2022 because its proxy stored an admin address in slot 0, where the implementation's Initializable kept its flags, and the address bytes made the contract look permanently mid-initialization. Solidity Storage Layout: Slots, Packing, and the Bugs It Enables works through that collision.
An upgrade can also move the guard. OpenZeppelin's v5 relocated the Initializable fields from slot 0 to the namespace above, and the README of the upgradeable package says that it is "unsafe to upgrade from 4.9.3 to 5.0.0". A live proxy that receives code built on a different Initializable reads zero at the new location and looks fresh. An audit of a Linea TokenBridge upgrade reported the same effect from a change that replaced the inherited initializer (finding).
With UUPS, a second initialization is a full takeover, since the owner slot that initialize writes is the same one _authorizeUpgrade reads. Pike Finance lost 479 ETH in April 2024 in that sequence, in which initialize succeeded on the live proxy, the caller became owner, and one upgradeToAndCall to a contract of their own sent the balance out (writeup).
A migration that never ran#
Later versions initialize their new state with reinitializer(n). The modifier only requires that the stored version be lower than n, so it does not enforce that versions run in sequence. In a test against v5.7.0, calling a reinitializer(4) function on a proxy at version 2 succeeded and set the version to 4, after which the reinitializer(3) function reverted with InvalidInitialization and could never run.
That is the mechanism behind the Ronin bridge incident of 6 August 2024. The new gateway implementation defined a v3 and a v4 initializer, and the upgrade called only the v4 one. The skipped v3 initializer was the one that stored the total operator weight, so the minimum vote weight for a withdrawal was computed from zero and withdrawals stopped requiring validator signatures. An MEV bot took about 4,000 ETH and 2M USDC, and its operators returned the funds (Halborn's analysis).
The values passed to an initializer deserve the same attention as the code. Nomad's Replica contract was re-initialized during an upgrade in 2022 with a trusted root of 0x00, which is also the value an unproven message maps to, and from then on every forged message passed as proven (writeup).
The defence is procedural. Each upgrade should go through upgradeToAndCall(newImplementation, data) with the migration call as data, so the new code never runs on unmigrated state, and the upgrade should be rehearsed on a fork of the live proxy with one ordinary user action afterwards. A single withdrawal on a fork would have exposed the Ronin upgrade.
Who can upgrade#
UUPS (the pattern from ERC-1822, built on EIP-1967 slots in OpenZeppelin's version) puts the upgrade function in the implementation.
Three checks run in order. onlyProxy rejects direct calls to the implementation. _authorizeUpgrade is an internal function with no default body, and it is the only access control on the path, so its override is the line to read first. A Code4rena review of Basin found an override that validated the new implementation carefully and never checked the caller, which let anyone upgrade any instance (finding). Finally the new implementation must answer proxiableUUID() with the EIP-1967 implementation slot, which prevents an accidental upgrade to a contract that lacks the UUPS interface. That check says nothing about whether the new contract's own _authorizeUpgrade is sound, so one bad upgrade can still be the last.
A transparent proxy keeps the upgrade logic in the proxy and, in v5, fixes its admin as an immutable ProxyAdmin contract. The implementation cannot break upgradeability there, at the cost of a separate admin contract per proxy. In both patterns, any delegatecall to a caller-influenced address inside the implementation is equivalent to an upgrade function, because the callee can write the implementation slot directly.
Beyond the code, the upgrade key is the protocol's root credential, so who holds it and whether a timelock sits in front of it belong in the review. How signers verify what they approve is covered in Signing Infrastructure Threat Model.
Storage discipline#
The mechanics of slots and packing are in the storage layout post. For upgrades they reduce to this table.
| Change between versions | Safe? | Reason |
|---|---|---|
| Append a variable at the end of the most derived contract | yes | existing slots keep their meaning |
| Append a variable to a base contract whose children have state | only with a reserved gap or ERC-7201 storage | the children's variables shift |
| Insert, reorder or remove a variable | no | later variables shift |
| Change a type or its size | no | packing and interpretation change |
| Change the order of base contracts | no | the linearised layout changes |
| Append a member to a struct | only if the struct is a mapping value or the last item in its namespace | inside arrays and other structs it shifts neighbours |
| Switch the major version of an upgradeable library | no, unless its notes say otherwise | library state may have moved, as with OpenZeppelin v4 to v5 |
OpenZeppelin's own upgradeable contracts have used ERC-7201 namespaces since v5.0, so they no longer depend on __gap arrays. Your contracts need one mechanism or the other wherever a base contract may grow.
Testing and shipping an upgrade#
A test of the new implementation in isolation says little about the upgrade. The test that counts deploys the proxy with initialization data, performs user actions, upgrades through upgradeToAndCall with the migration call, and then asserts both the old state and the new. Next to it belong four negative tests: a second initialize reverts, initialize on the implementation reverts, an upgrade from an unauthorized account reverts, and an upgrade to a contract without proxiableUUID reverts. All four held in our run against v5.7.0.
Before a production upgrade we would want these confirmed:
forge inspect <Contract> storageLayoutof the old and new versions has been compared, or the OpenZeppelin upgrades plugin has validated the new version against a reference contract.- The upgrade and its migration are one
upgradeToAndCalltransaction, and no initializer version is skipped. - The new implementation's constructor calls
_disableInitializers(). - The upgrade was executed on a fork of the live proxy, followed by at least one deposit and one withdrawal.
- After execution, the implementation slot and the
Initializedevent match what was approved. The Proxy Inspector on this site reads the EIP-1967 slots and the upgrade history of a live proxy.
Sources#
- Initializable.sol, UUPSUpgradeable.sol and ERC1967Proxy.sol at v5.7.0
- OpenZeppelin Contracts changelog for 4.3.2 (
onlyProxy), 5.0.0 (namespaced storage, removal ofupgradeTo) and 5.6.0 (mandatory initialization in proxy constructors) - EIP-1967 for the proxy storage slots and ERC-1822 for the original UUPS proposal and
proxiableUUID - GHSA-5vp3-v4hc-gx76, the 2021 UUPS advisory, and EIP-6780 for the change to
SELFDESTRUCT - OpenZeppelin Foundry Upgrades for automated upgrade validation in Foundry
- yAudit Proxy Playground, with a vulnerable and a fixed version of each proxy bug class