TExcelTAD
Home › Solidity › Security: Access Control

Security: Access Control

Most contracts have functions that only certain accounts may call: minting tokens, pausing transfers, changing fees, upgrading code. Access control bugs, where such a function is callable by anyone, are among the most common and most damaging vulnerabilities. They're usually not clever attacks; just a missing check.

Missing checks

solidity
contract Treasury {
    address public owner;
    function setOwner(address newOwner) external {   // BUG: no access check!
        owner = newOwner;
    }
}

Anyone can call setOwner and take over. Typical variants: an initialize function that can be called twice, an internal helper accidentally left public, a check on the wrong variable. Review every state-changing function with the question "who is allowed to call this?"

Ownable, done properly

A single owner is the simplest model. A good implementation emits events and uses a two-step transfer, so a typo in the new owner's address can't lock the contract forever:

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract Ownable2Step {
    address public owner;
    address public pendingOwner;

    event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
    error Unauthorized(address caller);

    constructor() {
        owner = msg.sender;
        emit OwnershipTransferred(address(0), msg.sender);
    }

    modifier onlyOwner() {
        if (msg.sender != owner) revert Unauthorized(msg.sender);
        _;
    }

    function transferOwnership(address newOwner) external onlyOwner {
        pendingOwner = newOwner;                      // step 1: propose
        emit OwnershipTransferStarted(owner, newOwner);
    }

    function acceptOwnership() external {
        if (msg.sender != pendingOwner) revert Unauthorized(msg.sender);
        emit OwnershipTransferred(owner, msg.sender); // step 2: the new owner confirms
        owner = msg.sender;
        pendingOwner = address(0);
    }
}

contract User {
    function accept(Ownable2Step c) external { c.acceptOwnership(); }
    function propose(Ownable2Step c, address to) external { c.transferOwnership(to); }
}

contract Main {
    function main() external {
        Ownable2Step c = new Ownable2Step();
        User alice = new User();
        User mallory = new User();

        c.transferOwnership(address(alice));
        alice.accept(c);
        console.log("owner is alice?", c.owner() == address(alice));

        mallory.propose(c, address(mallory));       // mallory is not the owner
    }
}
owner is alice? true
main() failed: custom error Unauthorized(0xeEBe00Ac0756308ac4AaBfD76c05c4F3088B8883)

Events for ownership changes let monitoring tools alert you when something unexpected happens.

Role-based access control

Bigger systems need several roles: a minter, a pauser, an admin who grants roles. Roles are usually bytes32 constants mapped to sets of accounts. This is the idea behind OpenZeppelin's AccessControl:

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract Roles {
    bytes32 public constant ADMIN = keccak256("ADMIN");
    bytes32 public constant MINTER = keccak256("MINTER");

    mapping(bytes32 => mapping(address => bool)) public hasRole;
    uint256 public supply;

    event RoleGranted(bytes32 indexed role, address indexed account);
    error MissingRole(bytes32 role, address account);

    constructor() {
        hasRole[ADMIN][msg.sender] = true;
    }

    modifier onlyRole(bytes32 role) {
        if (!hasRole[role][msg.sender]) revert MissingRole(role, msg.sender);
        _;
    }

    function grant(bytes32 role, address account) external onlyRole(ADMIN) {
        hasRole[role][account] = true;
        emit RoleGranted(role, account);
    }

    function mint(uint256 amount) external onlyRole(MINTER) {
        supply += amount;
    }
}

contract Minter {
    function mint(Roles r, uint256 amount) external { r.mint(amount); }
}

contract Main {
    function main() external {
        Roles roles = new Roles();
        Minter bot = new Minter();
        Minter stranger = new Minter();

        roles.grant(roles.MINTER(), address(bot));
        bot.mint(roles, 500);
        console.log("supply:", roles.supply());

        stranger.mint(roles, 1);
    }
}
supply: 500
main() failed: custom error MissingRole(0xf0887ba65ee2024ea881d91b74c2450ef19e1557f03bed3ea9f16b037cbe2dc9, 0xeEBe00Ac0756308ac4AaBfD76c05c4F3088B8883)

Give each role the least privilege it needs. A bot that mints rewards shouldn't also be able to upgrade the contract.

Never authorize with tx.origin

tx.origin is the account that signed the transaction, no matter how many contracts sit in between. If a wallet contract checks tx.origin == owner, any contract the owner interacts with can act in the owner's name. Here the owner (the playground's account) is tricked into calling a "free prize" contract:

solidity · try it yourself
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import "hardhat/console.sol";

contract OriginWallet {
    address public owner = tx.origin;
    constructor() payable {}

    function withdrawAll(address payable to) external {
        require(tx.origin == owner, "not owner");     // BUG: tx.origin
        to.transfer(address(this).balance);
    }
}

contract SenderWallet {
    address public owner = tx.origin;
    constructor() payable {}

    function withdrawAll(address payable to) external {
        require(msg.sender == owner, "not owner");    // correct: the direct caller
        to.transfer(address(this).balance);
    }
}

contract FreePrize {
    function claim(OriginWallet w1, SenderWallet w2) external {
        w1.withdrawAll(payable(address(this)));      // succeeds: tx.origin is the victim
        try w2.withdrawAll(payable(address(this))) {} catch Error(string memory reason) {
            console.log("SenderWallet refused:", reason);
        }
    }
    receive() external payable {}
}

contract Main {
    constructor() payable {}

    function main() external {
        OriginWallet w1 = new OriginWallet{value: 5 ether}();
        SenderWallet w2 = new SenderWallet{value: 5 ether}();
        FreePrize prize = new FreePrize();

        // the victim's transaction "claims a prize"
        prize.claim(w1, w2);
        console.log("stolen   :", address(prize).balance / 1 ether, "ETH");
        console.log("w1 left  :", address(w1).balance / 1 ether, "ETH");
        console.log("w2 left  :", address(w2).balance / 1 ether, "ETH");
    }
}
SenderWallet refused: not owner
stolen   : 5 ETH
w1 left  : 0 ETH
w2 left  : 5 ETH

Both wallets record the playground account as owner. The tx.origin check passes inside the malicious contract; the msg.sender check correctly sees FreePrize as the caller and refuses.

Checklist

  • Every state-changing function has an explicit answer to "who may call this?".
  • Admin functions emit events.
  • Initializers can run only once (see Proxies).
  • Use msg.sender, never tx.origin, for authorization.
  • Consider a multisig or timelock as the owner of important contracts, so one stolen key isn't enough.
  • Prefer audited libraries (OpenZeppelin Ownable2Step, AccessControl) over hand-rolled code in production.

Test yourself

Why is a two-step ownership transfer safer?

  1. It costs less gas
  2. The new owner must confirm, so a mistyped address can't take or lose ownership
  3. It prevents reentrancy
  4. It hides the owner

A wallet checks require(tx.origin == owner). What is the risk?

  1. None
  2. Any contract the owner calls can pass the check on the owner's behalf
  3. The owner can't use the wallet from a contract
  4. It always reverts

What does 'least privilege' mean for roles?

  1. Use as few roles as possible
  2. Give each account only the permissions it actually needs
  3. Only the deployer has privileges
  4. Roles expire after a day