Vulnerability Type
stringclasses
10 values
File Name
stringlengths
9
47
Source Code
stringlengths
228
96.8k
input
stringlengths
116
49.7k
denial_of_service
dos_simple.sol
/* * @source: https://github.com/SmartContractSecurity/SWC-registry/blob/master/test_cases/dos_gas_limit/dos_simple.sol * @author: - * @vulnerable_at_lines: 17,18 */ pragma solidity ^0.4.25; contract DosOneFunc { address[] listAddresses; function ifillArray() public returns (bool){ if(listAddresses.length<1500) { // <yes> <report> DENIAL_OF_SERVICE for(uint i=0;i<350;i++) { listAddresses.push(msg.sender); } return true; } else { listAddresses = new address[](0); return false; } } }
pragma solidity ^0.4.25; contract DosOneFunc { address[] listAddresses; function ifillArray() public returns (bool){ if(listAddresses.length<1500) { for(uint i=0;i<350;i++) { listAddresses.push(msg.sender); } return true; } else { listAddresses = new address[](0); return false; } } }
front_running
ERC20.sol
/* * @source: https://github.com/SmartContractSecurity/SWC-registry/blob/master/test_cases/transaction_order_dependence/ERC20.sol * @author: - * @vulnerable_at_lines: 110,113 */ pragma solidity ^0.4.24; /** Taken from the OpenZeppelin github * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } contract ERC20 { event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value); using SafeMath for *; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; constructor(uint totalSupply){ _balances[msg.sender] = totalSupply; } function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } function transfer(address to, uint256 value) public returns (bool) { require(value <= _balances[msg.sender]); require(to != address(0)); _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(msg.sender, to, value); return true; } // <yes> <report> FRONT_RUNNING function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); // <yes> <report> FRONT_RUNNING _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function transferFrom(address from, address to, uint256 value) public returns (bool) { require(value <= _balances[from]); require(value <= _allowed[from][msg.sender]); require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); emit Transfer(from, to, value); return true; } }
pragma solidity ^0.4.24; library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } contract ERC20 { event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value); using SafeMath for *; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; constructor(uint totalSupply){ _balances[msg.sender] = totalSupply; } function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } function transfer(address to, uint256 value) public returns (bool) { require(value <= _balances[msg.sender]); require(to != address(0)); _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(msg.sender, to, value); return true; } function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function transferFrom(address from, address to, uint256 value) public returns (bool) { require(value <= _balances[from]); require(value <= _allowed[from][msg.sender]); require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); emit Transfer(from, to, value); return true; } }
front_running
FindThisHash.sol
/* * @source: https://github.com/sigp/solidity-security-blog * @author: - * @vulnerable_at_lines: 17 */ pragma solidity ^0.4.22; contract FindThisHash { bytes32 constant public hash = 0xb5b5b97fafd9855eec9b41f74dfb6c38f5951141f9a3ecd7f44d5479b630ee0a; constructor() public payable {} // load with ether function solve(string solution) public { // If you can find the pre image of the hash, receive 1000 ether // <yes> <report> FRONT_RUNNING require(hash == sha3(solution)); msg.sender.transfer(1000 ether); } }
pragma solidity ^0.4.22; contract FindThisHash { bytes32 constant public hash = 0xb5b5b97fafd9855eec9b41f74dfb6c38f5951141f9a3ecd7f44d5479b630ee0a; constructor() public payable {} function solve(string solution) public { require(hash == sha3(solution)); msg.sender.transfer(1000 ether); } }
front_running
eth_tx_order_dependence_minimal.sol
/* * @source: https://github.com/ConsenSys/evm-analyzer-benchmark-suite * @author: Suhabe Bugrara * @vulnerable_at_lines: 23,31 */ pragma solidity ^0.4.16; contract EthTxOrderDependenceMinimal { address public owner; bool public claimed; uint public reward; function EthTxOrderDependenceMinimal() public { owner = msg.sender; } function setReward() public payable { require (!claimed); require(msg.sender == owner); // <yes> <report> FRONT_RUNNING owner.transfer(reward); reward = msg.value; } function claimReward(uint256 submission) { require (!claimed); require(submission < 10); // <yes> <report> FRONT_RUNNING msg.sender.transfer(reward); claimed = true; } }
pragma solidity ^0.4.16; contract EthTxOrderDependenceMinimal { address public owner; bool public claimed; uint public reward; function EthTxOrderDependenceMinimal() public { owner = msg.sender; } function setReward() public payable { require (!claimed); require(msg.sender == owner); owner.transfer(reward); reward = msg.value; } function claimReward(uint256 submission) { require (!claimed); require(submission < 10); msg.sender.transfer(reward); claimed = true; } }
front_running
odds_and_evens.sol
/* * @source: http://blockchain.unica.it/projects/ethereum-survey/attacks.html#oddsandevens * @author: - * @vulnerable_at_lines: 25,28 */ pragma solidity ^0.4.2; contract OddsAndEvens{ struct Player { address addr; uint number; } Player[2] public players; //public only for debug purpose uint8 tot; address owner; function OddsAndEvens() { owner = msg.sender; } // <yes> <report> FRONT_RUNNING function play(uint number) payable{ if (msg.value != 1 ether) throw; // <yes> <report> FRONT_RUNNING players[tot] = Player(msg.sender, number); tot++; if (tot==2) andTheWinnerIs(); } function andTheWinnerIs() private { bool res ; uint n = players[0].number+players[1].number; if (n%2==0) { res = players[0].addr.send(1800 finney); } else { res = players[1].addr.send(1800 finney); } delete players; tot=0; } function getProfit() { if(msg.sender!=owner) throw; bool res = msg.sender.send(this.balance); } }
pragma solidity ^0.4.2; contract OddsAndEvens{ struct Player { address addr; uint number; } Player[2] public players; uint8 tot; address owner; function OddsAndEvens() { owner = msg.sender; } function play(uint number) payable{ if (msg.value != 1 ether) throw; players[tot] = Player(msg.sender, number); tot++; if (tot==2) andTheWinnerIs(); } function andTheWinnerIs() private { bool res ; uint n = players[0].number+players[1].number; if (n%2==0) { res = players[0].addr.send(1800 finney); } else { res = players[1].addr.send(1800 finney); } delete players; tot=0; } function getProfit() { if(msg.sender!=owner) throw; bool res = msg.sender.send(this.balance); } }
access_control
multiowned_vulnerable.sol
/* * @source: https://github.com/SmartContractSecurity/SWC-registry/blob/master/test_cases/solidity/unprotected_critical_functions/multiowned_vulnerable/multiowned_vulnerable.sol * @author: - * @vulnerable_at_lines: 38 */ pragma solidity ^0.4.23; /** * @title MultiOwnable */ contract MultiOwnable { address public root; mapping (address => address) public owners; // owner => parent of owner /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { root = msg.sender; owners[root] = root; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owners[msg.sender] != 0); _; } /** * @dev Adding new owners * Note that the "onlyOwner" modifier is missing here. */ // <yes> <report> ACCESS_CONTROL function newOwner(address _owner) external returns (bool) { require(_owner != 0); owners[_owner] = msg.sender; return true; } /** * @dev Deleting owners */ function deleteOwner(address _owner) onlyOwner external returns (bool) { require(owners[_owner] == msg.sender || (owners[_owner] != 0 && msg.sender == root)); owners[_owner] = 0; return true; } } contract TestContract is MultiOwnable { function withdrawAll() onlyOwner { msg.sender.transfer(this.balance); } function() payable { } }
pragma solidity ^0.4.23; contract MultiOwnable { address public root; mapping (address => address) public owners; constructor() public { root = msg.sender; owners[root] = root; } modifier onlyOwner() { require(owners[msg.sender] != 0); _; } function newOwner(address _owner) external returns (bool) { require(_owner != 0); owners[_owner] = msg.sender; return true; } function deleteOwner(address _owner) onlyOwner external returns (bool) { require(owners[_owner] == msg.sender || (owners[_owner] != 0 && msg.sender == root)); owners[_owner] = 0; return true; } } contract TestContract is MultiOwnable { function withdrawAll() onlyOwner { msg.sender.transfer(this.balance); } function() payable { } }
access_control
phishable.sol
/* * @source: https://github.com/sigp/solidity-security-blog * @author: - * @vulnerable_at_lines: 20 */ pragma solidity ^0.4.22; contract Phishable { address public owner; constructor (address _owner) { owner = _owner; } function () public payable {} // collect ether function withdrawAll(address _recipient) public { // <yes> <report> ACCESS_CONTROL require(tx.origin == owner); _recipient.transfer(this.balance); } }
pragma solidity ^0.4.22; contract Phishable { address public owner; constructor (address _owner) { owner = _owner; } function () public payable {} function withdrawAll(address _recipient) public { require(tx.origin == owner); _recipient.transfer(this.balance); } }
access_control
incorrect_constructor_name1.sol
/* * @source: https://github.com/trailofbits/not-so-smart-contracts/blob/master/wrong_constructor_name/incorrect_constructor.sol * @author: Ben Perez * @vulnerable_at_lines: 20 */ pragma solidity ^0.4.24; contract Missing{ address private owner; modifier onlyowner { require(msg.sender==owner); _; } // The name of the constructor should be Missing // Anyone can call the IamMissing once the contract is deployed // <yes> <report> ACCESS_CONTROL function IamMissing() public { owner = msg.sender; } function () payable {} function withdraw() public onlyowner { owner.transfer(this.balance); } }
pragma solidity ^0.4.24; contract Missing{ address private owner; modifier onlyowner { require(msg.sender==owner); _; } function IamMissing() public { owner = msg.sender; } function () payable {} function withdraw() public onlyowner { owner.transfer(this.balance); } }
access_control
wallet_03_wrong_constructor.sol
/* * @source: https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-105#wallet-03-wrong-constructorsol * @author: - * @vulnerable_at_lines: 19,20 */ pragma solidity ^0.4.24; /* User can add pay in and withdraw Ether. The constructor is wrongly named, so anyone can become 'creator' and withdraw all funds. */ contract Wallet { address creator; mapping(address => uint256) balances; // <yes> <report> ACCESS_CONTROL function initWallet() public { creator = msg.sender; } function deposit() public payable { assert(balances[msg.sender] + msg.value > balances[msg.sender]); balances[msg.sender] += msg.value; } function withdraw(uint256 amount) public { require(amount <= balances[msg.sender]); msg.sender.transfer(amount); balances[msg.sender] -= amount; } // In an emergency the owner can migrate allfunds to a different address. function migrateTo(address to) public { require(creator == msg.sender); to.transfer(this.balance); } }
pragma solidity ^0.4.24; contract Wallet { address creator; mapping(address => uint256) balances; function initWallet() public { creator = msg.sender; } function deposit() public payable { assert(balances[msg.sender] + msg.value > balances[msg.sender]); balances[msg.sender] += msg.value; } function withdraw(uint256 amount) public { require(amount <= balances[msg.sender]); msg.sender.transfer(amount); balances[msg.sender] -= amount; } function migrateTo(address to) public { require(creator == msg.sender); to.transfer(this.balance); } }
access_control
incorrect_constructor_name2.sol
/* * @source: https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-118#incorrect-constructor-name1sol * @author: Ben Perez * @vulnerable_at_lines: 18 */ pragma solidity ^0.4.24; contract Missing{ address private owner; modifier onlyowner { require(msg.sender==owner); _; } // <yes> <report> ACCESS_CONTROL function missing() public { owner = msg.sender; } function () payable {} function withdraw() public onlyowner { owner.transfer(this.balance); } }
pragma solidity ^0.4.24; contract Missing{ address private owner; modifier onlyowner { require(msg.sender==owner); _; } function missing() public { owner = msg.sender; } function () payable {} function withdraw() public onlyowner { owner.transfer(this.balance); } }
access_control
incorrect_constructor_name3.sol
/* * @source: https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-118#incorrect-constructor-name2sol * @author: Ben Perez * @vulnerable_at_lines: 17 */ pragma solidity ^0.4.24; contract Missing{ address private owner; modifier onlyowner { require(msg.sender==owner); _; } // <yes> <report> ACCESS_CONTROL function Constructor() public { owner = msg.sender; } function () payable {} function withdraw() public onlyowner { owner.transfer(this.balance); } }
pragma solidity ^0.4.24; contract Missing{ address private owner; modifier onlyowner { require(msg.sender==owner); _; } function Constructor() public { owner = msg.sender; } function () payable {} function withdraw() public onlyowner { owner.transfer(this.balance); } }
access_control
proxy.sol
/* * @source: https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-112#proxysol * @author: - * @vulnerable_at_lines: 19 */ pragma solidity ^0.4.24; contract Proxy { address owner; constructor() public { owner = msg.sender; } function forward(address callee, bytes _data) public { // <yes> <report> ACCESS_CONTROL require(callee.delegatecall(_data)); //Use delegatecall with caution and make sure to never call into untrusted contracts } }
pragma solidity ^0.4.24; contract Proxy { address owner; constructor() public { owner = msg.sender; } function forward(address callee, bytes _data) public { require(callee.delegatecall(_data)); } }
access_control
parity_wallet_bug_1.sol
/* * @source: https://github.com/paritytech/parity-ethereum/blob/4d08e7b0aec46443bf26547b17d10cb302672835/js/src/contracts/snippets/enhanced-wallet.sol#L216 * @author: parity * @vulnerable_at_lines: 223,437 */ //sol Wallet // Multi-sig, daily-limited account proxy/wallet. // @authors: // Gav Wood <g@ethdev.com> // inheritable "property" contract that enables methods to be protected by requiring the acquiescence of either a // single, or, crucially, each of a number of, designated owners. // usage: // use modifiers onlyowner (just own owned) or onlymanyowners(hash), whereby the same hash must be provided by // some number (specified in constructor) of the set of owners (specified in the constructor, modifiable) before the // interior is executed. pragma solidity 0.4.9; /* originally ^0.4.9, but doesn't compile with ^0.4.11 */ contract WalletEvents { // EVENTS // this contract only has six types of events: it can accept a confirmation, in which case // we record owner and operation (hash) alongside it. event Confirmation(address owner, bytes32 operation); event Revoke(address owner, bytes32 operation); // some others are in the case of an owner changing. event OwnerChanged(address oldOwner, address newOwner); event OwnerAdded(address newOwner); event OwnerRemoved(address oldOwner); // the last one is emitted if the required signatures change event RequirementChanged(uint newRequirement); // Funds has arrived into the wallet (record how much). event Deposit(address _from, uint value); // Single transaction going out of the wallet (record who signed for it, how much, and to whom it's going). event SingleTransact(address owner, uint value, address to, bytes data, address created); // Multi-sig transaction going out of the wallet (record who signed for it last, the operation hash, how much, and to whom it's going). event MultiTransact(address owner, bytes32 operation, uint value, address to, bytes data, address created); // Confirmation still needed for a transaction. event ConfirmationNeeded(bytes32 operation, address initiator, uint value, address to, bytes data); } contract WalletAbi { // Revokes a prior confirmation of the given operation function revoke(bytes32 _operation) external; // Replaces an owner `_from` with another `_to`. function changeOwner(address _from, address _to) external; function addOwner(address _owner) external; function removeOwner(address _owner) external; function changeRequirement(uint _newRequired) external; function isOwner(address _addr) constant returns (bool); function hasConfirmed(bytes32 _operation, address _owner) external constant returns (bool); // (re)sets the daily limit. needs many of the owners to confirm. doesn't alter the amount already spent today. function setDailyLimit(uint _newLimit) external; function execute(address _to, uint _value, bytes _data) external returns (bytes32 o_hash); function confirm(bytes32 _h) returns (bool o_success); } contract WalletLibrary is WalletEvents { // TYPES // struct for the status of a pending operation. struct PendingState { uint yetNeeded; uint ownersDone; uint index; } // Transaction structure to remember details of transaction lest it need be saved for a later call. struct Transaction { address to; uint value; bytes data; } // MODIFIERS // simple single-sig function modifier. modifier onlyowner { if (isOwner(msg.sender)) _; } // multi-sig function modifier: the operation must have an intrinsic hash in order // that later attempts can be realised as the same underlying operation and // thus count as confirmations. modifier onlymanyowners(bytes32 _operation) { if (confirmAndCheck(_operation)) _; } // METHODS // gets called when no other function matches function() payable { // just being sent some cash? if (msg.value > 0) Deposit(msg.sender, msg.value); } // constructor is given number of sigs required to do protected "onlymanyowners" transactions // as well as the selection of addresses capable of confirming them. function initMultiowned(address[] _owners, uint _required) { m_numOwners = _owners.length + 1; m_owners[1] = uint(msg.sender); m_ownerIndex[uint(msg.sender)] = 1; for (uint i = 0; i < _owners.length; ++i) { m_owners[2 + i] = uint(_owners[i]); m_ownerIndex[uint(_owners[i])] = 2 + i; } m_required = _required; } // Revokes a prior confirmation of the given operation function revoke(bytes32 _operation) external { uint ownerIndex = m_ownerIndex[uint(msg.sender)]; // make sure they're an owner if (ownerIndex == 0) return; uint ownerIndexBit = 2**ownerIndex; var pending = m_pending[_operation]; if (pending.ownersDone & ownerIndexBit > 0) { pending.yetNeeded++; pending.ownersDone -= ownerIndexBit; Revoke(msg.sender, _operation); } } // Replaces an owner `_from` with another `_to`. function changeOwner(address _from, address _to) onlymanyowners(sha3(msg.data)) external { if (isOwner(_to)) return; uint ownerIndex = m_ownerIndex[uint(_from)]; if (ownerIndex == 0) return; clearPending(); m_owners[ownerIndex] = uint(_to); m_ownerIndex[uint(_from)] = 0; m_ownerIndex[uint(_to)] = ownerIndex; OwnerChanged(_from, _to); } function addOwner(address _owner) onlymanyowners(sha3(msg.data)) external { if (isOwner(_owner)) return; clearPending(); if (m_numOwners >= c_maxOwners) reorganizeOwners(); if (m_numOwners >= c_maxOwners) return; m_numOwners++; m_owners[m_numOwners] = uint(_owner); m_ownerIndex[uint(_owner)] = m_numOwners; OwnerAdded(_owner); } function removeOwner(address _owner) onlymanyowners(sha3(msg.data)) external { uint ownerIndex = m_ownerIndex[uint(_owner)]; if (ownerIndex == 0) return; if (m_required > m_numOwners - 1) return; m_owners[ownerIndex] = 0; m_ownerIndex[uint(_owner)] = 0; clearPending(); reorganizeOwners(); //make sure m_numOwner is equal to the number of owners and always points to the optimal free slot OwnerRemoved(_owner); } function changeRequirement(uint _newRequired) onlymanyowners(sha3(msg.data)) external { if (_newRequired > m_numOwners) return; m_required = _newRequired; clearPending(); RequirementChanged(_newRequired); } // Gets an owner by 0-indexed position (using numOwners as the count) function getOwner(uint ownerIndex) external constant returns (address) { return address(m_owners[ownerIndex + 1]); } function isOwner(address _addr) constant returns (bool) { return m_ownerIndex[uint(_addr)] > 0; } function hasConfirmed(bytes32 _operation, address _owner) external constant returns (bool) { var pending = m_pending[_operation]; uint ownerIndex = m_ownerIndex[uint(_owner)]; // make sure they're an owner if (ownerIndex == 0) return false; // determine the bit to set for this owner. uint ownerIndexBit = 2**ownerIndex; return !(pending.ownersDone & ownerIndexBit == 0); } // constructor - stores initial daily limit and records the present day's index. function initDaylimit(uint _limit) { m_dailyLimit = _limit; m_lastDay = today(); } // (re)sets the daily limit. needs many of the owners to confirm. doesn't alter the amount already spent today. function setDailyLimit(uint _newLimit) onlymanyowners(sha3(msg.data)) external { m_dailyLimit = _newLimit; } // resets the amount already spent today. needs many of the owners to confirm. function resetSpentToday() onlymanyowners(sha3(msg.data)) external { m_spentToday = 0; } // constructor - just pass on the owner array to the multiowned and // the limit to daylimit // <yes> <report> ACCESS_CONTROL function initWallet(address[] _owners, uint _required, uint _daylimit) { initDaylimit(_daylimit); initMultiowned(_owners, _required); } // kills the contract sending everything to `_to`. function kill(address _to) onlymanyowners(sha3(msg.data)) external { suicide(_to); } // Outside-visible transact entry point. Executes transaction immediately if below daily spend limit. // If not, goes into multisig process. We provide a hash on return to allow the sender to provide // shortcuts for the other confirmations (allowing them to avoid replicating the _to, _value // and _data arguments). They still get the option of using them if they want, anyways. function execute(address _to, uint _value, bytes _data) external onlyowner returns (bytes32 o_hash) { // first, take the opportunity to check that we're under the daily limit. if ((_data.length == 0 && underLimit(_value)) || m_required == 1) { // yes - just execute the call. address created; if (_to == 0) { created = create(_value, _data); } else { if (!_to.call.value(_value)(_data)) throw; } SingleTransact(msg.sender, _value, _to, _data, created); } else { // determine our operation hash. o_hash = sha3(msg.data, block.number); // store if it's new if (m_txs[o_hash].to == 0 && m_txs[o_hash].value == 0 && m_txs[o_hash].data.length == 0) { m_txs[o_hash].to = _to; m_txs[o_hash].value = _value; m_txs[o_hash].data = _data; } if (!confirm(o_hash)) { ConfirmationNeeded(o_hash, msg.sender, _value, _to, _data); } } } function create(uint _value, bytes _code) internal returns (address o_addr) { assembly { o_addr := create(_value, add(_code, 0x20), mload(_code)) jumpi(invalidJumpLabel, iszero(extcodesize(o_addr))) } } // confirm a transaction through just the hash. we use the previous transactions map, m_txs, in order // to determine the body of the transaction from the hash provided. function confirm(bytes32 _h) onlymanyowners(_h) returns (bool o_success) { if (m_txs[_h].to != 0 || m_txs[_h].value != 0 || m_txs[_h].data.length != 0) { address created; if (m_txs[_h].to == 0) { created = create(m_txs[_h].value, m_txs[_h].data); } else { if (!m_txs[_h].to.call.value(m_txs[_h].value)(m_txs[_h].data)) throw; } MultiTransact(msg.sender, _h, m_txs[_h].value, m_txs[_h].to, m_txs[_h].data, created); delete m_txs[_h]; return true; } } // INTERNAL METHODS function confirmAndCheck(bytes32 _operation) internal returns (bool) { // determine what index the present sender is: uint ownerIndex = m_ownerIndex[uint(msg.sender)]; // make sure they're an owner if (ownerIndex == 0) return; var pending = m_pending[_operation]; // if we're not yet working on this operation, switch over and reset the confirmation status. if (pending.yetNeeded == 0) { // reset count of confirmations needed. pending.yetNeeded = m_required; // reset which owners have confirmed (none) - set our bitmap to 0. pending.ownersDone = 0; pending.index = m_pendingIndex.length++; m_pendingIndex[pending.index] = _operation; } // determine the bit to set for this owner. uint ownerIndexBit = 2**ownerIndex; // make sure we (the message sender) haven't confirmed this operation previously. if (pending.ownersDone & ownerIndexBit == 0) { Confirmation(msg.sender, _operation); // ok - check if count is enough to go ahead. if (pending.yetNeeded <= 1) { // enough confirmations: reset and run interior. delete m_pendingIndex[m_pending[_operation].index]; delete m_pending[_operation]; return true; } else { // not enough: record that this owner in particular confirmed. pending.yetNeeded--; pending.ownersDone |= ownerIndexBit; } } } function reorganizeOwners() private { uint free = 1; while (free < m_numOwners) { while (free < m_numOwners && m_owners[free] != 0) free++; while (m_numOwners > 1 && m_owners[m_numOwners] == 0) m_numOwners--; if (free < m_numOwners && m_owners[m_numOwners] != 0 && m_owners[free] == 0) { m_owners[free] = m_owners[m_numOwners]; m_ownerIndex[m_owners[free]] = free; m_owners[m_numOwners] = 0; } } } // checks to see if there is at least `_value` left from the daily limit today. if there is, subtracts it and // returns true. otherwise just returns false. function underLimit(uint _value) internal onlyowner returns (bool) { // reset the spend limit if we're on a different day to last time. if (today() > m_lastDay) { m_spentToday = 0; m_lastDay = today(); } // check to see if there's enough left - if so, subtract and return true. // overflow protection // dailyLimit check if (m_spentToday + _value >= m_spentToday && m_spentToday + _value <= m_dailyLimit) { m_spentToday += _value; return true; } return false; } // determines today's index. function today() private constant returns (uint) { return now / 1 days; } function clearPending() internal { uint length = m_pendingIndex.length; for (uint i = 0; i < length; ++i) { delete m_txs[m_pendingIndex[i]]; if (m_pendingIndex[i] != 0) delete m_pending[m_pendingIndex[i]]; } delete m_pendingIndex; } // FIELDS address constant _walletLibrary = 0xcafecafecafecafecafecafecafecafecafecafe; // the number of owners that must confirm the same operation before it is run. uint public m_required; // pointer used to find a free slot in m_owners uint public m_numOwners; uint public m_dailyLimit; uint public m_spentToday; uint public m_lastDay; // list of owners uint[256] m_owners; uint constant c_maxOwners = 250; // index on the list of owners to allow reverse lookup mapping(uint => uint) m_ownerIndex; // the ongoing operations. mapping(bytes32 => PendingState) m_pending; bytes32[] m_pendingIndex; // pending transactions we have at present. mapping (bytes32 => Transaction) m_txs; } contract Wallet is WalletEvents { // WALLET CONSTRUCTOR // calls the `initWallet` method of the Library in this context function Wallet(address[] _owners, uint _required, uint _daylimit) { // Signature of the Wallet Library's init function bytes4 sig = bytes4(sha3("initWallet(address[],uint256,uint256)")); address target = _walletLibrary; // Compute the size of the call data : arrays has 2 // 32bytes for offset and length, plus 32bytes per element ; // plus 2 32bytes for each uint uint argarraysize = (2 + _owners.length); uint argsize = (2 + argarraysize) * 32; assembly { // Add the signature first to memory mstore(0x0, sig) // Add the call data, which is at the end of the // code codecopy(0x4, sub(codesize, argsize), argsize) // Delegate call to the library delegatecall(sub(gas, 10000), target, 0x0, add(argsize, 0x4), 0x0, 0x0) } } // METHODS // gets called when no other function matches function() payable { // just being sent some cash? if (msg.value > 0) Deposit(msg.sender, msg.value); else if (msg.data.length > 0) // <yes> <report> ACCESS_CONTROL _walletLibrary.delegatecall(msg.data); //it should have whitelisted specific methods that the user is allowed to call } // Gets an owner by 0-indexed position (using numOwners as the count) function getOwner(uint ownerIndex) constant returns (address) { return address(m_owners[ownerIndex + 1]); } // As return statement unavailable in fallback, explicit the method here function hasConfirmed(bytes32 _operation, address _owner) external constant returns (bool) { return _walletLibrary.delegatecall(msg.data); } function isOwner(address _addr) constant returns (bool) { return _walletLibrary.delegatecall(msg.data); } // FIELDS address constant _walletLibrary = 0xcafecafecafecafecafecafecafecafecafecafe; // the number of owners that must confirm the same operation before it is run. uint public m_required; // pointer used to find a free slot in m_owners uint public m_numOwners; uint public m_dailyLimit; uint public m_spentToday; uint public m_lastDay; // list of owners uint[256] m_owners; }
pragma solidity 0.4.9; contract WalletEvents { event Confirmation(address owner, bytes32 operation); event Revoke(address owner, bytes32 operation); event OwnerChanged(address oldOwner, address newOwner); event OwnerAdded(address newOwner); event OwnerRemoved(address oldOwner); event RequirementChanged(uint newRequirement); event Deposit(address _from, uint value); event SingleTransact(address owner, uint value, address to, bytes data, address created); event MultiTransact(address owner, bytes32 operation, uint value, address to, bytes data, address created); event ConfirmationNeeded(bytes32 operation, address initiator, uint value, address to, bytes data); } contract WalletAbi { function revoke(bytes32 _operation) external; function changeOwner(address _from, address _to) external; function addOwner(address _owner) external; function removeOwner(address _owner) external; function changeRequirement(uint _newRequired) external; function isOwner(address _addr) constant returns (bool); function hasConfirmed(bytes32 _operation, address _owner) external constant returns (bool); function setDailyLimit(uint _newLimit) external; function execute(address _to, uint _value, bytes _data) external returns (bytes32 o_hash); function confirm(bytes32 _h) returns (bool o_success); } contract WalletLibrary is WalletEvents { struct PendingState { uint yetNeeded; uint ownersDone; uint index; } struct Transaction { address to; uint value; bytes data; } modifier onlyowner { if (isOwner(msg.sender)) _; } modifier onlymanyowners(bytes32 _operation) { if (confirmAndCheck(_operation)) _; } function() payable { if (msg.value > 0) Deposit(msg.sender, msg.value); } function initMultiowned(address[] _owners, uint _required) { m_numOwners = _owners.length + 1; m_owners[1] = uint(msg.sender); m_ownerIndex[uint(msg.sender)] = 1; for (uint i = 0; i < _owners.length; ++i) { m_owners[2 + i] = uint(_owners[i]); m_ownerIndex[uint(_owners[i])] = 2 + i; } m_required = _required; } function revoke(bytes32 _operation) external { uint ownerIndex = m_ownerIndex[uint(msg.sender)]; if (ownerIndex == 0) return; uint ownerIndexBit = 2**ownerIndex; var pending = m_pending[_operation]; if (pending.ownersDone & ownerIndexBit > 0) { pending.yetNeeded++; pending.ownersDone -= ownerIndexBit; Revoke(msg.sender, _operation); } } function changeOwner(address _from, address _to) onlymanyowners(sha3(msg.data)) external { if (isOwner(_to)) return; uint ownerIndex = m_ownerIndex[uint(_from)]; if (ownerIndex == 0) return; clearPending(); m_owners[ownerIndex] = uint(_to); m_ownerIndex[uint(_from)] = 0; m_ownerIndex[uint(_to)] = ownerIndex; OwnerChanged(_from, _to); } function addOwner(address _owner) onlymanyowners(sha3(msg.data)) external { if (isOwner(_owner)) return; clearPending(); if (m_numOwners >= c_maxOwners) reorganizeOwners(); if (m_numOwners >= c_maxOwners) return; m_numOwners++; m_owners[m_numOwners] = uint(_owner); m_ownerIndex[uint(_owner)] = m_numOwners; OwnerAdded(_owner); } function removeOwner(address _owner) onlymanyowners(sha3(msg.data)) external { uint ownerIndex = m_ownerIndex[uint(_owner)]; if (ownerIndex == 0) return; if (m_required > m_numOwners - 1) return; m_owners[ownerIndex] = 0; m_ownerIndex[uint(_owner)] = 0; clearPending(); reorganizeOwners(); OwnerRemoved(_owner); } function changeRequirement(uint _newRequired) onlymanyowners(sha3(msg.data)) external { if (_newRequired > m_numOwners) return; m_required = _newRequired; clearPending(); RequirementChanged(_newRequired); } function getOwner(uint ownerIndex) external constant returns (address) { return address(m_owners[ownerIndex + 1]); } function isOwner(address _addr) constant returns (bool) { return m_ownerIndex[uint(_addr)] > 0; } function hasConfirmed(bytes32 _operation, address _owner) external constant returns (bool) { var pending = m_pending[_operation]; uint ownerIndex = m_ownerIndex[uint(_owner)]; if (ownerIndex == 0) return false; uint ownerIndexBit = 2**ownerIndex; return !(pending.ownersDone & ownerIndexBit == 0); } function initDaylimit(uint _limit) { m_dailyLimit = _limit; m_lastDay = today(); } function setDailyLimit(uint _newLimit) onlymanyowners(sha3(msg.data)) external { m_dailyLimit = _newLimit; } function resetSpentToday() onlymanyowners(sha3(msg.data)) external { m_spentToday = 0; } function initWallet(address[] _owners, uint _required, uint _daylimit) { initDaylimit(_daylimit); initMultiowned(_owners, _required); } function kill(address _to) onlymanyowners(sha3(msg.data)) external { suicide(_to); } function execute(address _to, uint _value, bytes _data) external onlyowner returns (bytes32 o_hash) { if ((_data.length == 0 && underLimit(_value)) || m_required == 1) { address created; if (_to == 0) { created = create(_value, _data); } else { if (!_to.call.value(_value)(_data)) throw; } SingleTransact(msg.sender, _value, _to, _data, created); } else { o_hash = sha3(msg.data, block.number); if (m_txs[o_hash].to == 0 && m_txs[o_hash].value == 0 && m_txs[o_hash].data.length == 0) { m_txs[o_hash].to = _to; m_txs[o_hash].value = _value; m_txs[o_hash].data = _data; } if (!confirm(o_hash)) { ConfirmationNeeded(o_hash, msg.sender, _value, _to, _data); } } } function create(uint _value, bytes _code) internal returns (address o_addr) { assembly { o_addr := create(_value, add(_code, 0x20), mload(_code)) jumpi(invalidJumpLabel, iszero(extcodesize(o_addr))) } } function confirm(bytes32 _h) onlymanyowners(_h) returns (bool o_success) { if (m_txs[_h].to != 0 || m_txs[_h].value != 0 || m_txs[_h].data.length != 0) { address created; if (m_txs[_h].to == 0) { created = create(m_txs[_h].value, m_txs[_h].data); } else { if (!m_txs[_h].to.call.value(m_txs[_h].value)(m_txs[_h].data)) throw; } MultiTransact(msg.sender, _h, m_txs[_h].value, m_txs[_h].to, m_txs[_h].data, created); delete m_txs[_h]; return true; } } function confirmAndCheck(bytes32 _operation) internal returns (bool) { uint ownerIndex = m_ownerIndex[uint(msg.sender)]; if (ownerIndex == 0) return; var pending = m_pending[_operation]; if (pending.yetNeeded == 0) { pending.yetNeeded = m_required; pending.ownersDone = 0; pending.index = m_pendingIndex.length++; m_pendingIndex[pending.index] = _operation; } uint ownerIndexBit = 2**ownerIndex; if (pending.ownersDone & ownerIndexBit == 0) { Confirmation(msg.sender, _operation); if (pending.yetNeeded <= 1) { delete m_pendingIndex[m_pending[_operation].index]; delete m_pending[_operation]; return true; } else { pending.yetNeeded--; pending.ownersDone |= ownerIndexBit; } } } function reorganizeOwners() private { uint free = 1; while (free < m_numOwners) { while (free < m_numOwners && m_owners[free] != 0) free++; while (m_numOwners > 1 && m_owners[m_numOwners] == 0) m_numOwners--; if (free < m_numOwners && m_owners[m_numOwners] != 0 && m_owners[free] == 0) { m_owners[free] = m_owners[m_numOwners]; m_ownerIndex[m_owners[free]] = free; m_owners[m_numOwners] = 0; } } } function underLimit(uint _value) internal onlyowner returns (bool) { if (today() > m_lastDay) { m_spentToday = 0; m_lastDay = today(); } if (m_spentToday + _value >= m_spentToday && m_spentToday + _value <= m_dailyLimit) { m_spentToday += _value; return true; } return false; } function today() private constant returns (uint) { return now / 1 days; } function clearPending() internal { uint length = m_pendingIndex.length; for (uint i = 0; i < length; ++i) { delete m_txs[m_pendingIndex[i]]; if (m_pendingIndex[i] != 0) delete m_pending[m_pendingIndex[i]]; } delete m_pendingIndex; } address constant _walletLibrary = 0xcafecafecafecafecafecafecafecafecafecafe; uint public m_required; uint public m_numOwners; uint public m_dailyLimit; uint public m_spentToday; uint public m_lastDay; uint[256] m_owners; uint constant c_maxOwners = 250; mapping(uint => uint) m_ownerIndex; mapping(bytes32 => PendingState) m_pending; bytes32[] m_pendingIndex; mapping (bytes32 => Transaction) m_txs; } contract Wallet is WalletEvents { function Wallet(address[] _owners, uint _required, uint _daylimit) { bytes4 sig = bytes4(sha3("initWallet(address[],uint256,uint256)")); address target = _walletLibrary; uint argarraysize = (2 + _owners.length); uint argsize = (2 + argarraysize) * 32; assembly { mstore(0x0, sig) codecopy(0x4, sub(codesize, argsize), argsize) delegatecall(sub(gas, 10000), target, 0x0, add(argsize, 0x4), 0x0, 0x0) } } function() payable { if (msg.value > 0) Deposit(msg.sender, msg.value); else if (msg.data.length > 0) _walletLibrary.delegatecall(msg.data); } function getOwner(uint ownerIndex) constant returns (address) { return address(m_owners[ownerIndex + 1]); } function hasConfirmed(bytes32 _operation, address _owner) external constant returns (bool) { return _walletLibrary.delegatecall(msg.data); } function isOwner(address _addr) constant returns (bool) { return _walletLibrary.delegatecall(msg.data); } address constant _walletLibrary = 0xcafecafecafecafecafecafecafecafecafecafe; uint public m_required; uint public m_numOwners; uint public m_dailyLimit; uint public m_spentToday; uint public m_lastDay; uint[256] m_owners; }
access_control
parity_wallet_bug_2.sol
/* * @source: https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-106#walletlibrarysol * @author: - * @vulnerable_at_lines: 226,233 */ //sol Wallet // Multi-sig, daily-limited account proxy/wallet. // @authors: // Gav Wood <g@ethdev.com> // inheritable "property" contract that enables methods to be protected by requiring the acquiescence of either a // single, or, crucially, each of a number of, designated owners. // usage: // use modifiers onlyowner (just own owned) or onlymanyowners(hash), whereby the same hash must be provided by // some number (specified in constructor) of the set of owners (specified in the constructor, modifiable) before the // interior is executed. pragma solidity ^0.4.9; contract WalletEvents { // EVENTS // this contract only has six types of events: it can accept a confirmation, in which case // we record owner and operation (hash) alongside it. event Confirmation(address owner, bytes32 operation); event Revoke(address owner, bytes32 operation); // some others are in the case of an owner changing. event OwnerChanged(address oldOwner, address newOwner); event OwnerAdded(address newOwner); event OwnerRemoved(address oldOwner); // the last one is emitted if the required signatures change event RequirementChanged(uint newRequirement); // Funds has arrived into the wallet (record how much). event Deposit(address _from, uint value); // Single transaction going out of the wallet (record who signed for it, how much, and to whom it's going). event SingleTransact(address owner, uint value, address to, bytes data, address created); // Multi-sig transaction going out of the wallet (record who signed for it last, the operation hash, how much, and to whom it's going). event MultiTransact(address owner, bytes32 operation, uint value, address to, bytes data, address created); // Confirmation still needed for a transaction. event ConfirmationNeeded(bytes32 operation, address initiator, uint value, address to, bytes data); } contract WalletAbi { // Revokes a prior confirmation of the given operation function revoke(bytes32 _operation) external; // Replaces an owner `_from` with another `_to`. function changeOwner(address _from, address _to) external; function addOwner(address _owner) external; function removeOwner(address _owner) external; function changeRequirement(uint _newRequired) external; function isOwner(address _addr) constant returns (bool); function hasConfirmed(bytes32 _operation, address _owner) external constant returns (bool); // (re)sets the daily limit. needs many of the owners to confirm. doesn't alter the amount already spent today. function setDailyLimit(uint _newLimit) external; function execute(address _to, uint _value, bytes _data) external returns (bytes32 o_hash); function confirm(bytes32 _h) returns (bool o_success); } contract WalletLibrary is WalletEvents { // TYPES // struct for the status of a pending operation. struct PendingState { uint yetNeeded; uint ownersDone; uint index; } // Transaction structure to remember details of transaction lest it need be saved for a later call. struct Transaction { address to; uint value; bytes data; } // MODIFIERS // simple single-sig function modifier. modifier onlyowner { if (isOwner(msg.sender)) _; } // multi-sig function modifier: the operation must have an intrinsic hash in order // that later attempts can be realised as the same underlying operation and // thus count as confirmations. modifier onlymanyowners(bytes32 _operation) { if (confirmAndCheck(_operation)) _; } // METHODS // gets called when no other function matches function() payable { // just being sent some cash? if (msg.value > 0) Deposit(msg.sender, msg.value); } // constructor is given number of sigs required to do protected "onlymanyowners" transactions // as well as the selection of addresses capable of confirming them. function initMultiowned(address[] _owners, uint _required) only_uninitialized { m_numOwners = _owners.length + 1; m_owners[1] = uint(msg.sender); m_ownerIndex[uint(msg.sender)] = 1; for (uint i = 0; i < _owners.length; ++i) { m_owners[2 + i] = uint(_owners[i]); m_ownerIndex[uint(_owners[i])] = 2 + i; } m_required = _required; } // Revokes a prior confirmation of the given operation function revoke(bytes32 _operation) external { uint ownerIndex = m_ownerIndex[uint(msg.sender)]; // make sure they're an owner if (ownerIndex == 0) return; uint ownerIndexBit = 2**ownerIndex; var pending = m_pending[_operation]; if (pending.ownersDone & ownerIndexBit > 0) { pending.yetNeeded++; pending.ownersDone -= ownerIndexBit; Revoke(msg.sender, _operation); } } // Replaces an owner `_from` with another `_to`. function changeOwner(address _from, address _to) onlymanyowners(sha3(msg.data)) external { if (isOwner(_to)) return; uint ownerIndex = m_ownerIndex[uint(_from)]; if (ownerIndex == 0) return; clearPending(); m_owners[ownerIndex] = uint(_to); m_ownerIndex[uint(_from)] = 0; m_ownerIndex[uint(_to)] = ownerIndex; OwnerChanged(_from, _to); } function addOwner(address _owner) onlymanyowners(sha3(msg.data)) external { if (isOwner(_owner)) return; clearPending(); if (m_numOwners >= c_maxOwners) reorganizeOwners(); if (m_numOwners >= c_maxOwners) return; m_numOwners++; m_owners[m_numOwners] = uint(_owner); m_ownerIndex[uint(_owner)] = m_numOwners; OwnerAdded(_owner); } function removeOwner(address _owner) onlymanyowners(sha3(msg.data)) external { uint ownerIndex = m_ownerIndex[uint(_owner)]; if (ownerIndex == 0) return; if (m_required > m_numOwners - 1) return; m_owners[ownerIndex] = 0; m_ownerIndex[uint(_owner)] = 0; clearPending(); reorganizeOwners(); //make sure m_numOwner is equal to the number of owners and always points to the optimal free slot OwnerRemoved(_owner); } function changeRequirement(uint _newRequired) onlymanyowners(sha3(msg.data)) external { if (_newRequired > m_numOwners) return; m_required = _newRequired; clearPending(); RequirementChanged(_newRequired); } // Gets an owner by 0-indexed position (using numOwners as the count) function getOwner(uint ownerIndex) external constant returns (address) { return address(m_owners[ownerIndex + 1]); } function isOwner(address _addr) constant returns (bool) { return m_ownerIndex[uint(_addr)] > 0; } function hasConfirmed(bytes32 _operation, address _owner) external constant returns (bool) { var pending = m_pending[_operation]; uint ownerIndex = m_ownerIndex[uint(_owner)]; // make sure they're an owner if (ownerIndex == 0) return false; // determine the bit to set for this owner. uint ownerIndexBit = 2**ownerIndex; return !(pending.ownersDone & ownerIndexBit == 0); } // constructor - stores initial daily limit and records the present day's index. function initDaylimit(uint _limit) only_uninitialized { m_dailyLimit = _limit; m_lastDay = today(); } // (re)sets the daily limit. needs many of the owners to confirm. doesn't alter the amount already spent today. function setDailyLimit(uint _newLimit) onlymanyowners(sha3(msg.data)) external { m_dailyLimit = _newLimit; } // resets the amount already spent today. needs many of the owners to confirm. function resetSpentToday() onlymanyowners(sha3(msg.data)) external { m_spentToday = 0; } // throw unless the contract is not yet initialized. modifier only_uninitialized { if (m_numOwners > 0) throw; _; } // constructor - just pass on the owner array to the multiowned and // the limit to daylimit // <yes> <report> ACCESS_CONTROL function initWallet(address[] _owners, uint _required, uint _daylimit) only_uninitialized { initDaylimit(_daylimit); initMultiowned(_owners, _required); } // kills the contract sending everything to `_to`. // <yes> <report> ACCESS_CONTROL function kill(address _to) onlymanyowners(sha3(msg.data)) external { suicide(_to); } // Outside-visible transact entry point. Executes transaction immediately if below daily spend limit. // If not, goes into multisig process. We provide a hash on return to allow the sender to provide // shortcuts for the other confirmations (allowing them to avoid replicating the _to, _value // and _data arguments). They still get the option of using them if they want, anyways. function execute(address _to, uint _value, bytes _data) external onlyowner returns (bytes32 o_hash) { // first, take the opportunity to check that we're under the daily limit. if ((_data.length == 0 && underLimit(_value)) || m_required == 1) { // yes - just execute the call. address created; if (_to == 0) { created = create(_value, _data); } else { if (!_to.call.value(_value)(_data)) throw; } SingleTransact(msg.sender, _value, _to, _data, created); } else { // determine our operation hash. o_hash = sha3(msg.data, block.number); // store if it's new if (m_txs[o_hash].to == 0 && m_txs[o_hash].value == 0 && m_txs[o_hash].data.length == 0) { m_txs[o_hash].to = _to; m_txs[o_hash].value = _value; m_txs[o_hash].data = _data; } if (!confirm(o_hash)) { ConfirmationNeeded(o_hash, msg.sender, _value, _to, _data); } } } function create(uint _value, bytes _code) internal returns (address o_addr) { /* assembly { o_addr := create(_value, add(_code, 0x20), mload(_code)) jumpi(invalidJumpLabel, iszero(extcodesize(o_addr))) } */ } // confirm a transaction through just the hash. we use the previous transactions map, m_txs, in order // to determine the body of the transaction from the hash provided. function confirm(bytes32 _h) onlymanyowners(_h) returns (bool o_success) { if (m_txs[_h].to != 0 || m_txs[_h].value != 0 || m_txs[_h].data.length != 0) { address created; if (m_txs[_h].to == 0) { created = create(m_txs[_h].value, m_txs[_h].data); } else { if (!m_txs[_h].to.call.value(m_txs[_h].value)(m_txs[_h].data)) throw; } MultiTransact(msg.sender, _h, m_txs[_h].value, m_txs[_h].to, m_txs[_h].data, created); delete m_txs[_h]; return true; } } // INTERNAL METHODS function confirmAndCheck(bytes32 _operation) internal returns (bool) { // determine what index the present sender is: uint ownerIndex = m_ownerIndex[uint(msg.sender)]; // make sure they're an owner if (ownerIndex == 0) return; var pending = m_pending[_operation]; // if we're not yet working on this operation, switch over and reset the confirmation status. if (pending.yetNeeded == 0) { // reset count of confirmations needed. pending.yetNeeded = m_required; // reset which owners have confirmed (none) - set our bitmap to 0. pending.ownersDone = 0; pending.index = m_pendingIndex.length++; m_pendingIndex[pending.index] = _operation; } // determine the bit to set for this owner. uint ownerIndexBit = 2**ownerIndex; // make sure we (the message sender) haven't confirmed this operation previously. if (pending.ownersDone & ownerIndexBit == 0) { Confirmation(msg.sender, _operation); // ok - check if count is enough to go ahead. if (pending.yetNeeded <= 1) { // enough confirmations: reset and run interior. delete m_pendingIndex[m_pending[_operation].index]; delete m_pending[_operation]; return true; } else { // not enough: record that this owner in particular confirmed. pending.yetNeeded--; pending.ownersDone |= ownerIndexBit; } } } function reorganizeOwners() private { uint free = 1; while (free < m_numOwners) { while (free < m_numOwners && m_owners[free] != 0) free++; while (m_numOwners > 1 && m_owners[m_numOwners] == 0) m_numOwners--; if (free < m_numOwners && m_owners[m_numOwners] != 0 && m_owners[free] == 0) { m_owners[free] = m_owners[m_numOwners]; m_ownerIndex[m_owners[free]] = free; m_owners[m_numOwners] = 0; } } } // checks to see if there is at least `_value` left from the daily limit today. if there is, subtracts it and // returns true. otherwise just returns false. function underLimit(uint _value) internal onlyowner returns (bool) { // reset the spend limit if we're on a different day to last time. if (today() > m_lastDay) { m_spentToday = 0; m_lastDay = today(); } // check to see if there's enough left - if so, subtract and return true. // overflow protection // dailyLimit check if (m_spentToday + _value >= m_spentToday && m_spentToday + _value <= m_dailyLimit) { m_spentToday += _value; return true; } return false; } // determines today's index. function today() private constant returns (uint) { return now / 1 days; } function clearPending() internal { uint length = m_pendingIndex.length; for (uint i = 0; i < length; ++i) { delete m_txs[m_pendingIndex[i]]; if (m_pendingIndex[i] != 0) delete m_pending[m_pendingIndex[i]]; } delete m_pendingIndex; } // FIELDS address constant _walletLibrary = 0xcafecafecafecafecafecafecafecafecafecafe; // the number of owners that must confirm the same operation before it is run. uint public m_required; // pointer used to find a free slot in m_owners uint public m_numOwners; uint public m_dailyLimit; uint public m_spentToday; uint public m_lastDay; // list of owners uint[256] m_owners; uint constant c_maxOwners = 250; // index on the list of owners to allow reverse lookup mapping(uint => uint) m_ownerIndex; // the ongoing operations. mapping(bytes32 => PendingState) m_pending; bytes32[] m_pendingIndex; // pending transactions we have at present. mapping (bytes32 => Transaction) m_txs; }
pragma solidity ^0.4.9; contract WalletEvents { event Confirmation(address owner, bytes32 operation); event Revoke(address owner, bytes32 operation); event OwnerChanged(address oldOwner, address newOwner); event OwnerAdded(address newOwner); event OwnerRemoved(address oldOwner); event RequirementChanged(uint newRequirement); event Deposit(address _from, uint value); event SingleTransact(address owner, uint value, address to, bytes data, address created); event MultiTransact(address owner, bytes32 operation, uint value, address to, bytes data, address created); event ConfirmationNeeded(bytes32 operation, address initiator, uint value, address to, bytes data); } contract WalletAbi { function revoke(bytes32 _operation) external; function changeOwner(address _from, address _to) external; function addOwner(address _owner) external; function removeOwner(address _owner) external; function changeRequirement(uint _newRequired) external; function isOwner(address _addr) constant returns (bool); function hasConfirmed(bytes32 _operation, address _owner) external constant returns (bool); function setDailyLimit(uint _newLimit) external; function execute(address _to, uint _value, bytes _data) external returns (bytes32 o_hash); function confirm(bytes32 _h) returns (bool o_success); } contract WalletLibrary is WalletEvents { struct PendingState { uint yetNeeded; uint ownersDone; uint index; } struct Transaction { address to; uint value; bytes data; } modifier onlyowner { if (isOwner(msg.sender)) _; } modifier onlymanyowners(bytes32 _operation) { if (confirmAndCheck(_operation)) _; } function() payable { if (msg.value > 0) Deposit(msg.sender, msg.value); } function initMultiowned(address[] _owners, uint _required) only_uninitialized { m_numOwners = _owners.length + 1; m_owners[1] = uint(msg.sender); m_ownerIndex[uint(msg.sender)] = 1; for (uint i = 0; i < _owners.length; ++i) { m_owners[2 + i] = uint(_owners[i]); m_ownerIndex[uint(_owners[i])] = 2 + i; } m_required = _required; } function revoke(bytes32 _operation) external { uint ownerIndex = m_ownerIndex[uint(msg.sender)]; if (ownerIndex == 0) return; uint ownerIndexBit = 2**ownerIndex; var pending = m_pending[_operation]; if (pending.ownersDone & ownerIndexBit > 0) { pending.yetNeeded++; pending.ownersDone -= ownerIndexBit; Revoke(msg.sender, _operation); } } function changeOwner(address _from, address _to) onlymanyowners(sha3(msg.data)) external { if (isOwner(_to)) return; uint ownerIndex = m_ownerIndex[uint(_from)]; if (ownerIndex == 0) return; clearPending(); m_owners[ownerIndex] = uint(_to); m_ownerIndex[uint(_from)] = 0; m_ownerIndex[uint(_to)] = ownerIndex; OwnerChanged(_from, _to); } function addOwner(address _owner) onlymanyowners(sha3(msg.data)) external { if (isOwner(_owner)) return; clearPending(); if (m_numOwners >= c_maxOwners) reorganizeOwners(); if (m_numOwners >= c_maxOwners) return; m_numOwners++; m_owners[m_numOwners] = uint(_owner); m_ownerIndex[uint(_owner)] = m_numOwners; OwnerAdded(_owner); } function removeOwner(address _owner) onlymanyowners(sha3(msg.data)) external { uint ownerIndex = m_ownerIndex[uint(_owner)]; if (ownerIndex == 0) return; if (m_required > m_numOwners - 1) return; m_owners[ownerIndex] = 0; m_ownerIndex[uint(_owner)] = 0; clearPending(); reorganizeOwners(); OwnerRemoved(_owner); } function changeRequirement(uint _newRequired) onlymanyowners(sha3(msg.data)) external { if (_newRequired > m_numOwners) return; m_required = _newRequired; clearPending(); RequirementChanged(_newRequired); } function getOwner(uint ownerIndex) external constant returns (address) { return address(m_owners[ownerIndex + 1]); } function isOwner(address _addr) constant returns (bool) { return m_ownerIndex[uint(_addr)] > 0; } function hasConfirmed(bytes32 _operation, address _owner) external constant returns (bool) { var pending = m_pending[_operation]; uint ownerIndex = m_ownerIndex[uint(_owner)]; if (ownerIndex == 0) return false; uint ownerIndexBit = 2**ownerIndex; return !(pending.ownersDone & ownerIndexBit == 0); } function initDaylimit(uint _limit) only_uninitialized { m_dailyLimit = _limit; m_lastDay = today(); } function setDailyLimit(uint _newLimit) onlymanyowners(sha3(msg.data)) external { m_dailyLimit = _newLimit; } function resetSpentToday() onlymanyowners(sha3(msg.data)) external { m_spentToday = 0; } modifier only_uninitialized { if (m_numOwners > 0) throw; _; } function initWallet(address[] _owners, uint _required, uint _daylimit) only_uninitialized { initDaylimit(_daylimit); initMultiowned(_owners, _required); } function kill(address _to) onlymanyowners(sha3(msg.data)) external { suicide(_to); } function execute(address _to, uint _value, bytes _data) external onlyowner returns (bytes32 o_hash) { if ((_data.length == 0 && underLimit(_value)) || m_required == 1) { address created; if (_to == 0) { created = create(_value, _data); } else { if (!_to.call.value(_value)(_data)) throw; } SingleTransact(msg.sender, _value, _to, _data, created); } else { o_hash = sha3(msg.data, block.number); if (m_txs[o_hash].to == 0 && m_txs[o_hash].value == 0 && m_txs[o_hash].data.length == 0) { m_txs[o_hash].to = _to; m_txs[o_hash].value = _value; m_txs[o_hash].data = _data; } if (!confirm(o_hash)) { ConfirmationNeeded(o_hash, msg.sender, _value, _to, _data); } } } function create(uint _value, bytes _code) internal returns (address o_addr) { } function confirm(bytes32 _h) onlymanyowners(_h) returns (bool o_success) { if (m_txs[_h].to != 0 || m_txs[_h].value != 0 || m_txs[_h].data.length != 0) { address created; if (m_txs[_h].to == 0) { created = create(m_txs[_h].value, m_txs[_h].data); } else { if (!m_txs[_h].to.call.value(m_txs[_h].value)(m_txs[_h].data)) throw; } MultiTransact(msg.sender, _h, m_txs[_h].value, m_txs[_h].to, m_txs[_h].data, created); delete m_txs[_h]; return true; } } function confirmAndCheck(bytes32 _operation) internal returns (bool) { uint ownerIndex = m_ownerIndex[uint(msg.sender)]; if (ownerIndex == 0) return; var pending = m_pending[_operation]; if (pending.yetNeeded == 0) { pending.yetNeeded = m_required; pending.ownersDone = 0; pending.index = m_pendingIndex.length++; m_pendingIndex[pending.index] = _operation; } uint ownerIndexBit = 2**ownerIndex; if (pending.ownersDone & ownerIndexBit == 0) { Confirmation(msg.sender, _operation); if (pending.yetNeeded <= 1) { delete m_pendingIndex[m_pending[_operation].index]; delete m_pending[_operation]; return true; } else { pending.yetNeeded--; pending.ownersDone |= ownerIndexBit; } } } function reorganizeOwners() private { uint free = 1; while (free < m_numOwners) { while (free < m_numOwners && m_owners[free] != 0) free++; while (m_numOwners > 1 && m_owners[m_numOwners] == 0) m_numOwners--; if (free < m_numOwners && m_owners[m_numOwners] != 0 && m_owners[free] == 0) { m_owners[free] = m_owners[m_numOwners]; m_ownerIndex[m_owners[free]] = free; m_owners[m_numOwners] = 0; } } } function underLimit(uint _value) internal onlyowner returns (bool) { if (today() > m_lastDay) { m_spentToday = 0; m_lastDay = today(); } if (m_spentToday + _value >= m_spentToday && m_spentToday + _value <= m_dailyLimit) { m_spentToday += _value; return true; } return false; } function today() private constant returns (uint) { return now / 1 days; } function clearPending() internal { uint length = m_pendingIndex.length; for (uint i = 0; i < length; ++i) { delete m_txs[m_pendingIndex[i]]; if (m_pendingIndex[i] != 0) delete m_pending[m_pendingIndex[i]]; } delete m_pendingIndex; } address constant _walletLibrary = 0xcafecafecafecafecafecafecafecafecafecafe; uint public m_required; uint public m_numOwners; uint public m_dailyLimit; uint public m_spentToday; uint public m_lastDay; uint[256] m_owners; uint constant c_maxOwners = 250; mapping(uint => uint) m_ownerIndex; mapping(bytes32 => PendingState) m_pending; bytes32[] m_pendingIndex; mapping (bytes32 => Transaction) m_txs; }
access_control
wallet_04_confused_sign.sol
/* * @source: https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-105#wallet-04-confused-signsol * @author: - * @vulnerable_at_lines: 30 */ pragma solidity ^0.4.24; /* User can add pay in and withdraw Ether. Unfortunatelty, the developer was drunk and used the wrong comparison operator in "withdraw()" Anybody can withdraw arbitrary amounts of Ether :() */ contract Wallet { address creator; mapping(address => uint256) balances; constructor() public { creator = msg.sender; } function deposit() public payable { assert(balances[msg.sender] + msg.value > balances[msg.sender]); balances[msg.sender] += msg.value; } function withdraw(uint256 amount) public { // <yes> <report> ACCESS_CONTROL require(amount >= balances[msg.sender]); msg.sender.transfer(amount); balances[msg.sender] -= amount; } // In an emergency the owner can migrate allfunds to a different address. function migrateTo(address to) public { require(creator == msg.sender); to.transfer(this.balance); } }
pragma solidity ^0.4.24; contract Wallet { address creator; mapping(address => uint256) balances; constructor() public { creator = msg.sender; } function deposit() public payable { assert(balances[msg.sender] + msg.value > balances[msg.sender]); balances[msg.sender] += msg.value; } function withdraw(uint256 amount) public { require(amount >= balances[msg.sender]); msg.sender.transfer(amount); balances[msg.sender] -= amount; } function migrateTo(address to) public { require(creator == msg.sender); to.transfer(this.balance); } }
access_control
FibonacciBalance.sol
/* * @source: https://github.com/sigp/solidity-security-blog * @author: Suhabe Bugrara * @vulnerable_at_lines: 31,38 */ //added pragma version pragma solidity ^0.4.22; contract FibonacciBalance { address public fibonacciLibrary; // the current fibonacci number to withdraw uint public calculatedFibNumber; // the starting fibonacci sequence number uint public start = 3; uint public withdrawalCounter; // the fibonancci function selector bytes4 constant fibSig = bytes4(sha3("setFibonacci(uint256)")); // constructor - loads the contract with ether constructor(address _fibonacciLibrary) public payable { fibonacciLibrary = _fibonacciLibrary; } function withdraw() { withdrawalCounter += 1; // calculate the fibonacci number for the current withdrawal user // this sets calculatedFibNumber // <yes> <report> ACCESS_CONTROL require(fibonacciLibrary.delegatecall(fibSig, withdrawalCounter)); msg.sender.transfer(calculatedFibNumber * 1 ether); } // allow users to call fibonacci library functions function() public { // <yes> <report> ACCESS_CONTROL require(fibonacciLibrary.delegatecall(msg.data)); } } // library contract - calculates fibonacci-like numbers; contract FibonacciLib { // initializing the standard fibonacci sequence; uint public start; uint public calculatedFibNumber; // modify the zeroth number in the sequence function setStart(uint _start) public { start = _start; } function setFibonacci(uint n) public { calculatedFibNumber = fibonacci(n); } function fibonacci(uint n) internal returns (uint) { if (n == 0) return start; else if (n == 1) return start + 1; else return fibonacci(n - 1) + fibonacci(n - 2); } }
pragma solidity ^0.4.22; contract FibonacciBalance { address public fibonacciLibrary; uint public calculatedFibNumber; uint public start = 3; uint public withdrawalCounter; bytes4 constant fibSig = bytes4(sha3("setFibonacci(uint256)")); constructor(address _fibonacciLibrary) public payable { fibonacciLibrary = _fibonacciLibrary; } function withdraw() { withdrawalCounter += 1; require(fibonacciLibrary.delegatecall(fibSig, withdrawalCounter)); msg.sender.transfer(calculatedFibNumber * 1 ether); } function() public { require(fibonacciLibrary.delegatecall(msg.data)); } } contract FibonacciLib { uint public start; uint public calculatedFibNumber; function setStart(uint _start) public { start = _start; } function setFibonacci(uint n) public { calculatedFibNumber = fibonacci(n); } function fibonacci(uint n) internal returns (uint) { if (n == 0) return start; else if (n == 1) return start + 1; else return fibonacci(n - 1) + fibonacci(n - 2); } }
access_control
unprotected0.sol
/* * @source: https://github.com/trailofbits/not-so-smart-contracts/blob/master/unprotected_function/Unprotected.sol * @author: - * @vulnerable_at_lines: 25 */ pragma solidity ^0.4.15; contract Unprotected{ address private owner; modifier onlyowner { require(msg.sender==owner); _; } function Unprotected() public { owner = msg.sender; } // This function should be protected // <yes> <report> ACCESS_CONTROL function changeOwner(address _newOwner) public { owner = _newOwner; } /* function changeOwner_fixed(address _newOwner) public onlyowner { owner = _newOwner; } */ }
pragma solidity ^0.4.15; contract Unprotected{ address private owner; modifier onlyowner { require(msg.sender==owner); _; } function Unprotected() public { owner = msg.sender; } function changeOwner(address _newOwner) public { owner = _newOwner; } }
access_control
rubixi.sol
/* * @source: https://github.com/trailofbits/not-so-smart-contracts/blob/master/wrong_constructor_name/Rubixi_source_code/Rubixi.sol * @author: - * @vulnerable_at_lines: 23,24 */ // 0xe82719202e5965Cf5D9B6673B7503a3b92DE20be#code pragma solidity ^0.4.15; contract Rubixi { //Declare variables for storage critical to contract uint private balance = 0; uint private collectedFees = 0; uint private feePercent = 10; uint private pyramidMultiplier = 300; uint private payoutOrder = 0; address private creator; //Sets creator // <yes> <report> ACCESS_CONTROL function DynamicPyramid() { creator = msg.sender; //anyone can call this } modifier onlyowner { if (msg.sender == creator) _; } struct Participant { address etherAddress; uint payout; } Participant[] private participants; //Fallback function function() { init(); } //init function run on fallback function init() private { //Ensures only tx with value of 1 ether or greater are processed and added to pyramid if (msg.value < 1 ether) { collectedFees += msg.value; return; } uint _fee = feePercent; //50% fee rebate on any ether value of 50 or greater if (msg.value >= 50 ether) _fee /= 2; addPayout(_fee); } //Function called for valid tx to the contract function addPayout(uint _fee) private { //Adds new address to participant array participants.push(Participant(msg.sender, (msg.value * pyramidMultiplier) / 100)); //These statements ensure a quicker payout system to later pyramid entrants, so the pyramid has a longer lifespan if (participants.length == 10) pyramidMultiplier = 200; else if (participants.length == 25) pyramidMultiplier = 150; // collect fees and update contract balance balance += (msg.value * (100 - _fee)) / 100; collectedFees += (msg.value * _fee) / 100; //Pays earlier participiants if balance sufficient while (balance > participants[payoutOrder].payout) { uint payoutToSend = participants[payoutOrder].payout; participants[payoutOrder].etherAddress.send(payoutToSend); balance -= participants[payoutOrder].payout; payoutOrder += 1; } } //Fee functions for creator function collectAllFees() onlyowner { if (collectedFees == 0) throw; creator.send(collectedFees); collectedFees = 0; } function collectFeesInEther(uint _amt) onlyowner { _amt *= 1 ether; if (_amt > collectedFees) collectAllFees(); if (collectedFees == 0) throw; creator.send(_amt); collectedFees -= _amt; } function collectPercentOfFees(uint _pcent) onlyowner { if (collectedFees == 0 || _pcent > 100) throw; uint feesToCollect = collectedFees / 100 * _pcent; creator.send(feesToCollect); collectedFees -= feesToCollect; } //Functions for changing variables related to the contract function changeOwner(address _owner) onlyowner { creator = _owner; } function changeMultiplier(uint _mult) onlyowner { if (_mult > 300 || _mult < 120) throw; pyramidMultiplier = _mult; } function changeFeePercentage(uint _fee) onlyowner { if (_fee > 10) throw; feePercent = _fee; } //Functions to provide information to end-user using JSON interface or other interfaces function currentMultiplier() constant returns(uint multiplier, string info) { multiplier = pyramidMultiplier; info = 'This multiplier applies to you as soon as transaction is received, may be lowered to hasten payouts or increased if payouts are fast enough. Due to no float or decimals, multiplier is x100 for a fractional multiplier e.g. 250 is actually a 2.5x multiplier. Capped at 3x max and 1.2x min.'; } function currentFeePercentage() constant returns(uint fee, string info) { fee = feePercent; info = 'Shown in % form. Fee is halved(50%) for amounts equal or greater than 50 ethers. (Fee may change, but is capped to a maximum of 10%)'; } function currentPyramidBalanceApproximately() constant returns(uint pyramidBalance, string info) { pyramidBalance = balance / 1 ether; info = 'All balance values are measured in Ethers, note that due to no decimal placing, these values show up as integers only, within the contract itself you will get the exact decimal value you are supposed to'; } function nextPayoutWhenPyramidBalanceTotalsApproximately() constant returns(uint balancePayout) { balancePayout = participants[payoutOrder].payout / 1 ether; } function feesSeperateFromBalanceApproximately() constant returns(uint fees) { fees = collectedFees / 1 ether; } function totalParticipants() constant returns(uint count) { count = participants.length; } function numberOfParticipantsWaitingForPayout() constant returns(uint count) { count = participants.length - payoutOrder; } function participantDetails(uint orderInPyramid) constant returns(address Address, uint Payout) { if (orderInPyramid <= participants.length) { Address = participants[orderInPyramid].etherAddress; Payout = participants[orderInPyramid].payout / 1 ether; } } }
pragma solidity ^0.4.15; contract Rubixi { uint private balance = 0; uint private collectedFees = 0; uint private feePercent = 10; uint private pyramidMultiplier = 300; uint private payoutOrder = 0; address private creator; function DynamicPyramid() { creator = msg.sender; } modifier onlyowner { if (msg.sender == creator) _; } struct Participant { address etherAddress; uint payout; } Participant[] private participants; function() { init(); } function init() private { if (msg.value < 1 ether) { collectedFees += msg.value; return; } uint _fee = feePercent; if (msg.value >= 50 ether) _fee /= 2; addPayout(_fee); } function addPayout(uint _fee) private { participants.push(Participant(msg.sender, (msg.value * pyramidMultiplier) / 100)); if (participants.length == 10) pyramidMultiplier = 200; else if (participants.length == 25) pyramidMultiplier = 150; balance += (msg.value * (100 - _fee)) / 100; collectedFees += (msg.value * _fee) / 100; while (balance > participants[payoutOrder].payout) { uint payoutToSend = participants[payoutOrder].payout; participants[payoutOrder].etherAddress.send(payoutToSend); balance -= participants[payoutOrder].payout; payoutOrder += 1; } } function collectAllFees() onlyowner { if (collectedFees == 0) throw; creator.send(collectedFees); collectedFees = 0; } function collectFeesInEther(uint _amt) onlyowner { _amt *= 1 ether; if (_amt > collectedFees) collectAllFees(); if (collectedFees == 0) throw; creator.send(_amt); collectedFees -= _amt; } function collectPercentOfFees(uint _pcent) onlyowner { if (collectedFees == 0 || _pcent > 100) throw; uint feesToCollect = collectedFees / 100 * _pcent; creator.send(feesToCollect); collectedFees -= feesToCollect; } function changeOwner(address _owner) onlyowner { creator = _owner; } function changeMultiplier(uint _mult) onlyowner { if (_mult > 300 || _mult < 120) throw; pyramidMultiplier = _mult; } function changeFeePercentage(uint _fee) onlyowner { if (_fee > 10) throw; feePercent = _fee; } function currentMultiplier() constant returns(uint multiplier, string info) { multiplier = pyramidMultiplier; info = 'This multiplier applies to you as soon as transaction is received, may be lowered to hasten payouts or increased if payouts are fast enough. Due to no float or decimals, multiplier is x100 for a fractional multiplier e.g. 250 is actually a 2.5x multiplier. Capped at 3x max and 1.2x min.'; } function currentFeePercentage() constant returns(uint fee, string info) { fee = feePercent; info = 'Shown in % form. Fee is halved(50%) for amounts equal or greater than 50 ethers. (Fee may change, but is capped to a maximum of 10%)'; } function currentPyramidBalanceApproximately() constant returns(uint pyramidBalance, string info) { pyramidBalance = balance / 1 ether; info = 'All balance values are measured in Ethers, note that due to no decimal placing, these values show up as integers only, within the contract itself you will get the exact decimal value you are supposed to'; } function nextPayoutWhenPyramidBalanceTotalsApproximately() constant returns(uint balancePayout) { balancePayout = participants[payoutOrder].payout / 1 ether; } function feesSeperateFromBalanceApproximately() constant returns(uint fees) { fees = collectedFees / 1 ether; } function totalParticipants() constant returns(uint count) { count = participants.length; } function numberOfParticipantsWaitingForPayout() constant returns(uint count) { count = participants.length - payoutOrder; } function participantDetails(uint orderInPyramid) constant returns(address Address, uint Payout) { if (orderInPyramid <= participants.length) { Address = participants[orderInPyramid].etherAddress; Payout = participants[orderInPyramid].payout / 1 ether; } } }
access_control
arbitrary_location_write_simple.sol
/* * @source: https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-124#arbitrary-location-write-simplesol * @author: Suhabe Bugrara * @vulnerable_at_lines: 27 */ pragma solidity ^0.4.25; contract Wallet { uint[] private bonusCodes; address private owner; constructor() public { bonusCodes = new uint[](0); owner = msg.sender; } function () public payable { } function PushBonusCode(uint c) public { bonusCodes.push(c); } function PopBonusCode() public { // <yes> <report> ACCESS_CONTROL require(0 <= bonusCodes.length); // this condition is always true since array lengths are unsigned bonusCodes.length--; // an underflow can be caused here } function UpdateBonusCodeAt(uint idx, uint c) public { require(idx < bonusCodes.length); bonusCodes[idx] = c; // write to any index less than bonusCodes.length } function Destroy() public { require(msg.sender == owner); selfdestruct(msg.sender); } }
pragma solidity ^0.4.25; contract Wallet { uint[] private bonusCodes; address private owner; constructor() public { bonusCodes = new uint[](0); owner = msg.sender; } function () public payable { } function PushBonusCode(uint c) public { bonusCodes.push(c); } function PopBonusCode() public { require(0 <= bonusCodes.length); bonusCodes.length--; } function UpdateBonusCodeAt(uint idx, uint c) public { require(idx < bonusCodes.length); bonusCodes[idx] = c; } function Destroy() public { require(msg.sender == owner); selfdestruct(msg.sender); } }
access_control
mycontract.sol
/* * @source: https://consensys.github.io/smart-contract-best-practices/recommendations/#avoid-using-txorigin * @author: Consensys Diligence * @vulnerable_at_lines: 20 * Modified by Gerhard Wagner */ pragma solidity ^0.4.24; contract MyContract { address owner; function MyContract() public { owner = msg.sender; } function sendTo(address receiver, uint amount) public { // <yes> <report> ACCESS_CONTROL require(tx.origin == owner); receiver.transfer(amount); } }
pragma solidity ^0.4.24; contract MyContract { address owner; function MyContract() public { owner = msg.sender; } function sendTo(address receiver, uint amount) public { require(tx.origin == owner); receiver.transfer(amount); } }
access_control
wallet_02_refund_nosub.sol
/* * @source: https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-105#wallet-02-refund-nosubsol * @author: - * @vulnerable_at_lines: 36 */ pragma solidity ^0.4.24; /* User can add pay in and withdraw Ether. Unfortunately the developer forgot set the user's balance to 0 when refund() is called. An attacker can pay in a small amount of Ether and call refund() repeatedly to empty the contract. */ contract Wallet { address creator; mapping(address => uint256) balances; constructor() public { creator = msg.sender; } function deposit() public payable { assert(balances[msg.sender] + msg.value > balances[msg.sender]); balances[msg.sender] += msg.value; } function withdraw(uint256 amount) public { require(amount <= balances[msg.sender]); msg.sender.transfer(amount); balances[msg.sender] -= amount; } function refund() public { // <yes> <report> ACCESS_CONTROL msg.sender.transfer(balances[msg.sender]); } // In an emergency the owner can migrate allfunds to a different address. function migrateTo(address to) public { require(creator == msg.sender); to.transfer(this.balance); } }
pragma solidity ^0.4.24; contract Wallet { address creator; mapping(address => uint256) balances; constructor() public { creator = msg.sender; } function deposit() public payable { assert(balances[msg.sender] + msg.value > balances[msg.sender]); balances[msg.sender] += msg.value; } function withdraw(uint256 amount) public { require(amount <= balances[msg.sender]); msg.sender.transfer(amount); balances[msg.sender] -= amount; } function refund() public { msg.sender.transfer(balances[msg.sender]); } function migrateTo(address to) public { require(creator == msg.sender); to.transfer(this.balance); } }
access_control
simple_suicide.sol
/* * @source: https://github.com/SmartContractSecurity/SWC-registry/blob/master/test_cases/unprotected_critical_functions/simple_suicide.sol * @author: - * @vulnerable_at_lines: 12,13 */ //added prgma version pragma solidity ^0.4.0; contract SimpleSuicide { // <yes> <report> ACCESS_CONTROL function sudicideAnyone() { selfdestruct(msg.sender); } }
pragma solidity ^0.4.0; contract SimpleSuicide { function sudicideAnyone() { selfdestruct(msg.sender); } }
access_control
mapping_write.sol
/* * @source: https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-124#mapping-writesol * @author: Suhabe Bugrara * @vulnerable_at_lines: 20 */ pragma solidity ^0.4.24; //This code is derived from the Capture the Ether https://capturetheether.com/challenges/math/mapping/ contract Map { address public owner; uint256[] map; function set(uint256 key, uint256 value) public { if (map.length <= key) { map.length = key + 1; } // <yes> <report> ACCESS_CONTROL map[key] = value; } function get(uint256 key) public view returns (uint256) { return map[key]; } function withdraw() public{ require(msg.sender == owner); msg.sender.transfer(address(this).balance); } }
pragma solidity ^0.4.24; contract Map { address public owner; uint256[] map; function set(uint256 key, uint256 value) public { if (map.length <= key) { map.length = key + 1; } map[key] = value; } function get(uint256 key) public view returns (uint256) { return map[key]; } function withdraw() public{ require(msg.sender == owner); msg.sender.transfer(address(this).balance); } }
arithmetic
token.sol
/* * @source: https://github.com/sigp/solidity-security-blog * @author: Steve Marx * @vulnerable_at_lines: 20,22 */ pragma solidity ^0.4.18; contract Token { mapping(address => uint) balances; uint public totalSupply; function Token(uint _initialSupply) { balances[msg.sender] = totalSupply = _initialSupply; } function transfer(address _to, uint _value) public returns (bool) { // <yes> <report> ARITHMETIC require(balances[msg.sender] - _value >= 0); // <yes> <report> ARITHMETIC balances[msg.sender] -= _value; balances[_to] += _value; return true; } function balanceOf(address _owner) public constant returns (uint balance) { return balances[_owner]; } }
pragma solidity ^0.4.18; contract Token { mapping(address => uint) balances; uint public totalSupply; function Token(uint _initialSupply) { balances[msg.sender] = totalSupply = _initialSupply; } function transfer(address _to, uint _value) public returns (bool) { require(balances[msg.sender] - _value >= 0); balances[msg.sender] -= _value; balances[_to] += _value; return true; } function balanceOf(address _owner) public constant returns (uint balance) { return balances[_owner]; } }
arithmetic
overflow_single_tx.sol
/* * @source: https://github.com/ConsenSys/evm-analyzer-benchmark-suite * @author: Suhabe Bugrara * @vulnerable_at_lines: 18,24,30,36,42,48 */ //Single transaction overflow //Post-transaction effect: overflow escapes to publicly-readable storage pragma solidity ^0.4.23; contract IntegerOverflowSingleTransaction { uint public count = 1; // ADD overflow with result stored in state variable. function overflowaddtostate(uint256 input) public { // <yes> <report> ARITHMETIC count += input; } // MUL overflow with result stored in state variable. function overflowmultostate(uint256 input) public { // <yes> <report> ARITHMETIC count *= input; } // Underflow with result stored in state variable. function underflowtostate(uint256 input) public { // <yes> <report> ARITHMETIC count -= input; } // ADD Overflow, no effect on state. function overflowlocalonly(uint256 input) public { // <yes> <report> ARITHMETIC uint res = count + input; } // MUL Overflow, no effect on state. function overflowmulocalonly(uint256 input) public { // <yes> <report> ARITHMETIC uint res = count * input; } // Underflow, no effect on state. function underflowlocalonly(uint256 input) public { // <yes> <report> ARITHMETIC uint res = count - input; } }
pragma solidity ^0.4.23; contract IntegerOverflowSingleTransaction { uint public count = 1; function overflowaddtostate(uint256 input) public { count += input; } function overflowmultostate(uint256 input) public { count *= input; } function underflowtostate(uint256 input) public { count -= input; } function overflowlocalonly(uint256 input) public { uint res = count + input; } function overflowmulocalonly(uint256 input) public { uint res = count * input; } function underflowlocalonly(uint256 input) public { uint res = count - input; } }
arithmetic
integer_overflow_minimal.sol
/* * @source: https://github.com/SmartContractSecurity/SWC-registry/blob/master/test_cases/integer_overflow_and_underflow/integer_overflow_minimal.sol * @author: - * @vulnerable_at_lines: 17 */ //Single transaction overflow //Post-transaction effect: overflow escapes to publicly-readable storage pragma solidity ^0.4.19; contract IntegerOverflowMinimal { uint public count = 1; function run(uint256 input) public { // <yes> <report> ARITHMETIC count -= input; } }
pragma solidity ^0.4.19; contract IntegerOverflowMinimal { uint public count = 1; function run(uint256 input) public { count -= input; } }
arithmetic
integer_overflow_add.sol
/* * @source: https://github.com/ConsenSys/evm-analyzer-benchmark-suite/blob/master/benchmarks/integer_overflow_add.sol * @author: - * @vulnerable_at_lines: 17 */ //Single transaction overflow //Post-transaction effect: overflow escapes to publicly-readable storage pragma solidity ^0.4.19; contract IntegerOverflowAdd { uint public count = 1; function run(uint256 input) public { // <yes> <report> ARITHMETIC count += input; } }
pragma solidity ^0.4.19; contract IntegerOverflowAdd { uint public count = 1; function run(uint256 input) public { count += input; } }
arithmetic
insecure_transfer.sol
/* * @source: https://consensys.github.io/smart-contract-best-practices/known_attacks/#front-running-aka-transaction-ordering-dependence * @author: consensys * @vulnerable_at_lines: 18 */ pragma solidity ^0.4.10; contract IntegerOverflowAdd { mapping (address => uint256) public balanceOf; // INSECURE function transfer(address _to, uint256 _value) public{ /* Check if sender has balance */ require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] -= _value; // <yes> <report> ARITHMETIC balanceOf[_to] += _value; } }
pragma solidity ^0.4.10; contract IntegerOverflowAdd { mapping (address => uint256) public balanceOf; function transfer(address _to, uint256 _value) public{ require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] -= _value; balanceOf[_to] += _value; } }
arithmetic
integer_overflow_benign_1.sol
/* * @source: https://github.com/SmartContractSecurity/SWC-registry/blob/master/test_cases/integer_overflow_and_underflow/integer_overflow_benign_1.sol * @author: - * @vulnerable_at_lines: 17 */ //Single transaction overflow //Post-transaction effect: overflow never escapes function pragma solidity ^0.4.19; contract IntegerOverflowBenign1 { uint public count = 1; function run(uint256 input) public { // <yes> <report> ARITHMETIC uint res = count - input; } }
pragma solidity ^0.4.19; contract IntegerOverflowBenign1 { uint public count = 1; function run(uint256 input) public { uint res = count - input; } }
arithmetic
timelock.sol
/* * @source: https://github.com/sigp/solidity-security-blog * @author: - * @vulnerable_at_lines: 22 */ //added pragma version pragma solidity ^0.4.10; contract TimeLock { mapping(address => uint) public balances; mapping(address => uint) public lockTime; function deposit() public payable { balances[msg.sender] += msg.value; lockTime[msg.sender] = now + 1 weeks; } function increaseLockTime(uint _secondsToIncrease) public { // <yes> <report> ARITHMETIC lockTime[msg.sender] += _secondsToIncrease; } function withdraw() public { require(balances[msg.sender] > 0); require(now > lockTime[msg.sender]); uint transferValue = balances[msg.sender]; balances[msg.sender] = 0; msg.sender.transfer(transferValue); } }
pragma solidity ^0.4.10; contract TimeLock { mapping(address => uint) public balances; mapping(address => uint) public lockTime; function deposit() public payable { balances[msg.sender] += msg.value; lockTime[msg.sender] = now + 1 weeks; } function increaseLockTime(uint _secondsToIncrease) public { lockTime[msg.sender] += _secondsToIncrease; } function withdraw() public { require(balances[msg.sender] > 0); require(now > lockTime[msg.sender]); uint transferValue = balances[msg.sender]; balances[msg.sender] = 0; msg.sender.transfer(transferValue); } }
arithmetic
integer_overflow_1.sol
/* * @source: https://github.com/trailofbits/not-so-smart-contracts/blob/master/integer_overflow/integer_overflow_1.sol * @author: - * @vulnerable_at_lines: 14 */ pragma solidity ^0.4.15; contract Overflow { uint private sellerBalance=0; function add(uint value) returns (bool){ // <yes> <report> ARITHMETIC sellerBalance += value; // possible overflow // possible auditor assert // assert(sellerBalance >= value); } // function safe_add(uint value) returns (bool){ // require(value + sellerBalance >= sellerBalance); // sellerBalance += value; // } }
pragma solidity ^0.4.15; contract Overflow { uint private sellerBalance=0; function add(uint value) returns (bool){ sellerBalance += value; } }
arithmetic
integer_overflow_mapping_sym_1.sol
/* * @source: https://github.com/SmartContractSecurity/SWC-registry/blob/master/test_cases/integer_overflow_and_underflow/integer_overflow_mapping_sym_1.sol * @author: - * @vulnerable_at_lines: 16 */ //Single transaction overflow pragma solidity ^0.4.11; contract IntegerOverflowMappingSym1 { mapping(uint256 => uint256) map; function init(uint256 k, uint256 v) public { // <yes> <report> ARITHMETIC map[k] -= v; } }
pragma solidity ^0.4.11; contract IntegerOverflowMappingSym1 { mapping(uint256 => uint256) map; function init(uint256 k, uint256 v) public { map[k] -= v; } }
arithmetic
overflow_simple_add.sol
/* * @source: https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-101#overflow-simple-addsol * @author: - * @vulnerable_at_lines: 14 */ pragma solidity 0.4.25; contract Overflow_Add { uint public balance = 1; function add(uint256 deposit) public { // <yes> <report> ARITHMETIC balance += deposit; } }
pragma solidity 0.4.25; contract Overflow_Add { uint public balance = 1; function add(uint256 deposit) public { balance += deposit; } }
arithmetic
integer_overflow_mul.sol
/* * @source: https://github.com/SmartContractSecurity/SWC-registry/blob/master/test_cases/integer_overflow_and_underflow/integer_overflow_mul.sol * @author: - * @vulnerable_at_lines: 17 */ //Single transaction overflow //Post-transaction effect: overflow escapes to publicly-readable storage pragma solidity ^0.4.19; contract IntegerOverflowMul { uint public count = 2; function run(uint256 input) public { // <yes> <report> ARITHMETIC count *= input; } }
pragma solidity ^0.4.19; contract IntegerOverflowMul { uint public count = 2; function run(uint256 input) public { count *= input; } }
arithmetic
tokensalechallenge.sol
/* * @source: https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-101 // https://capturetheether.com/challenges/math/token-sale/ * @author: Steve Marx * @vulnerable_at_lines: 23,25,33 */ pragma solidity ^0.4.21; contract TokenSaleChallenge { mapping(address => uint256) public balanceOf; uint256 constant PRICE_PER_TOKEN = 1 ether; function TokenSaleChallenge(address _player) public payable { require(msg.value == 1 ether); } function isComplete() public view returns (bool) { return address(this).balance < 1 ether; } function buy(uint256 numTokens) public payable { // <yes> <report> ARITHMETIC require(msg.value == numTokens * PRICE_PER_TOKEN); // <yes> <report> ARITHMETIC balanceOf[msg.sender] += numTokens; } function sell(uint256 numTokens) public { require(balanceOf[msg.sender] >= numTokens); balanceOf[msg.sender] -= numTokens; // <yes> <report> ARITHMETIC msg.sender.transfer(numTokens * PRICE_PER_TOKEN); } }
pragma solidity ^0.4.21; contract TokenSaleChallenge { mapping(address => uint256) public balanceOf; uint256 constant PRICE_PER_TOKEN = 1 ether; function TokenSaleChallenge(address _player) public payable { require(msg.value == 1 ether); } function isComplete() public view returns (bool) { return address(this).balance < 1 ether; } function buy(uint256 numTokens) public payable { require(msg.value == numTokens * PRICE_PER_TOKEN); balanceOf[msg.sender] += numTokens; } function sell(uint256 numTokens) public { require(balanceOf[msg.sender] >= numTokens); balanceOf[msg.sender] -= numTokens; msg.sender.transfer(numTokens * PRICE_PER_TOKEN); } }
arithmetic
integer_overflow_multitx_multifunc_feasible.sol
/* * @source: https://github.com/ConsenSys/evm-analyzer-benchmark-suite * @author: Suhabe Bugrara * @vulnerable_at_lines: 25 */ //Multi-transactional, multi-function //Arithmetic instruction reachable pragma solidity ^0.4.23; contract IntegerOverflowMultiTxMultiFuncFeasible { uint256 private initialized = 0; uint256 public count = 1; function init() public { initialized = 1; } function run(uint256 input) { if (initialized == 0) { return; } // <yes> <report> ARITHMETIC count -= input; } }
pragma solidity ^0.4.23; contract IntegerOverflowMultiTxMultiFuncFeasible { uint256 private initialized = 0; uint256 public count = 1; function init() public { initialized = 1; } function run(uint256 input) { if (initialized == 0) { return; } count -= input; } }
arithmetic
BECToken.sol
/* * @source: https://smartcontractsecurity.github.io/SWC-registry/docs/SWC-101#bectokensol * @author: - * @vulnerable_at_lines: 264 */ pragma solidity ^0.4.16; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; require(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // require(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // require(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { require(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; require(c >= a); return c; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value > 0 && _value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value > 0 && _value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; /** * @dev Modifier to make a function callable only when the contract is not paused. */ modifier whenNotPaused() { require(!paused); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } /** * @title Pausable token * * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function batchTransfer(address[] _receivers, uint256 _value) public whenNotPaused returns (bool) { uint cnt = _receivers.length; // <yes> <report> ARITHMETIC uint256 amount = uint256(cnt) * _value; require(cnt > 0 && cnt <= 20); require(_value > 0 && balances[msg.sender] >= amount); balances[msg.sender] = balances[msg.sender].sub(amount); for (uint i = 0; i < cnt; i++) { balances[_receivers[i]] = balances[_receivers[i]].add(_value); Transfer(msg.sender, _receivers[i], _value); } return true; } } /** * @title Bec Token * * @dev Implementation of Bec Token based on the basic standard token. */ contract BecToken is PausableToken { /** * Public variables of the token * The following variables are OPTIONAL vanities. One does not have to include them. * They allow one to customise the token contract & in no way influences the core functionality. * Some wallets/interfaces might not even bother to look at this information. */ string public name = "BeautyChain"; string public symbol = "BEC"; string public version = '1.0.0'; uint8 public decimals = 18; /** * @dev Function to check the amount of tokens that an owner allowed to a spender. */ function BecToken() { totalSupply = 7000000000 * (10**(uint256(decimals))); balances[msg.sender] = totalSupply; // Give the creator all initial tokens } function () { //if ether is sent to this address, send it back. revert(); } }
pragma solidity ^0.4.16; library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; require(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a / b; return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { require(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; require(c >= a); return c; } } contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) public constant returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value > 0 && _value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint256 value); } contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value > 0 && _value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function batchTransfer(address[] _receivers, uint256 _value) public whenNotPaused returns (bool) { uint cnt = _receivers.length; uint256 amount = uint256(cnt) * _value; require(cnt > 0 && cnt <= 20); require(_value > 0 && balances[msg.sender] >= amount); balances[msg.sender] = balances[msg.sender].sub(amount); for (uint i = 0; i < cnt; i++) { balances[_receivers[i]] = balances[_receivers[i]].add(_value); Transfer(msg.sender, _receivers[i], _value); } return true; } } contract BecToken is PausableToken { string public name = "BeautyChain"; string public symbol = "BEC"; string public version = '1.0.0'; uint8 public decimals = 18; function BecToken() { totalSupply = 7000000000 * (10**(uint256(decimals))); balances[msg.sender] = totalSupply; } function () { revert(); } }
arithmetic
integer_overflow_multitx_onefunc_feasible.sol
/* * @source: https://github.com/ConsenSys/evm-analyzer-benchmark-suite * @author: Suhabe Bugrara * @vulnerable_at_lines: 22 */ //Multi-transactional, single function //Arithmetic instruction reachable pragma solidity ^0.4.23; contract IntegerOverflowMultiTxOneFuncFeasible { uint256 private initialized = 0; uint256 public count = 1; function run(uint256 input) public { if (initialized == 0) { initialized = 1; return; } // <yes> <report> ARITHMETIC count -= input; } }
pragma solidity ^0.4.23; contract IntegerOverflowMultiTxOneFuncFeasible { uint256 private initialized = 0; uint256 public count = 1; function run(uint256 input) public { if (initialized == 0) { initialized = 1; return; } count -= input; } }
time_manipulation
ether_lotto.sol
/* * @article: https://blog.positive.com/predicting-random-numbers-in-ethereum-smart-contracts-e5358c6b8620 * @source: https://etherscan.io/address/0xa11e4ed59dc94e69612f3111942626ed513cb172#code * @vulnerable_at_lines: 43 * @author: - */ pragma solidity ^0.4.15; /// @title Ethereum Lottery Game. contract EtherLotto { // Amount of ether needed for participating in the lottery. uint constant TICKET_AMOUNT = 10; // Fixed amount fee for each lottery game. uint constant FEE_AMOUNT = 1; // Address where fee is sent. address public bank; // Public jackpot that each participant can win (minus fee). uint public pot; // Lottery constructor sets bank account from the smart-contract owner. function EtherLotto() { bank = msg.sender; } // Public function for playing lottery. Each time this function // is invoked, the sender has an oportunity for winning pot. function play() payable { // Participants must spend some fixed ether before playing lottery. assert(msg.value == TICKET_AMOUNT); // Increase pot for each participant. pot += msg.value; // Compute some *almost random* value for selecting winner from current transaction. // <yes> <report> TIME_MANIPULATION var random = uint(sha3(block.timestamp)) % 2; // Distribution: 50% of participants will be winners. if (random == 0) { // Send fee to bank account. bank.transfer(FEE_AMOUNT); // Send jackpot to winner. msg.sender.transfer(pot - FEE_AMOUNT); // Restart jackpot. pot = 0; } } }
pragma solidity ^0.4.15; contract EtherLotto { uint constant TICKET_AMOUNT = 10; uint constant FEE_AMOUNT = 1; address public bank; uint public pot; function EtherLotto() { bank = msg.sender; } function play() payable { assert(msg.value == TICKET_AMOUNT); pot += msg.value; var random = uint(sha3(block.timestamp)) % 2; if (random == 0) { bank.transfer(FEE_AMOUNT); msg.sender.transfer(pot - FEE_AMOUNT); pot = 0; } } }
time_manipulation
roulette.sol
/* * @source: https://github.com/sigp/solidity-security-blog * @author: - * @vulnerable_at_lines: 18,20 */ pragma solidity ^0.4.25; contract Roulette { uint public pastBlockTime; // Forces one bet per block constructor() public payable {} // initially fund contract // fallback function used to make a bet function () public payable { require(msg.value == 10 ether); // must send 10 ether to play // <yes> <report> TIME_MANIPULATION require(now != pastBlockTime); // only 1 transaction per block // <yes> <report> TIME_MANIPULATION pastBlockTime = now; if(now % 15 == 0) { // winner msg.sender.transfer(this.balance); } } }
pragma solidity ^0.4.25; contract Roulette { uint public pastBlockTime; constructor() public payable {} function () public payable { require(msg.value == 10 ether); require(now != pastBlockTime); pastBlockTime = now; if(now % 15 == 0) { msg.sender.transfer(this.balance); } } }
time_manipulation
lottopollo.sol
/* * @source: https://github.com/seresistvanandras/EthBench/blob/master/Benchmark/Simple/timestampdependent.sol * @author: - * @vulnerable_at_lines: 13,27 */ pragma solidity ^0.4.0; contract lottopollo { address leader; uint timestamp; function payOut(uint rand) internal { // <yes> <report> TIME MANIPULATION if ( rand> 0 && now - rand > 24 hours ) { msg.sender.send( msg.value ); if ( this.balance > 0 ) { leader.send( this.balance ); } } else if ( msg.value >= 1 ether ) { leader = msg.sender; timestamp = rand; } } function randomGen() constant returns (uint randomNumber) { // <yes> <report> TIME MANIPULATION return block.timestamp; } function draw(uint seed){ uint randomNumber=randomGen(); payOut(randomNumber); } }
pragma solidity ^0.4.0; contract lottopollo { address leader; uint timestamp; function payOut(uint rand) internal { if ( rand> 0 && now - rand > 24 hours ) { msg.sender.send( msg.value ); if ( this.balance > 0 ) { leader.send( this.balance ); } } else if ( msg.value >= 1 ether ) { leader = msg.sender; timestamp = rand; } } function randomGen() constant returns (uint randomNumber) { return block.timestamp; } function draw(uint seed){ uint randomNumber=randomGen(); payOut(randomNumber); } }
time_manipulation
governmental_survey.sol
/* * @source: http://blockchain.unica.it/projects/ethereum-survey/attacks.html#governmental * @author: - * @vulnerable_at_lines: 27 */ //added pragma version pragma solidity ^0.4.0; contract Governmental { address public owner; address public lastInvestor; uint public jackpot = 1 ether; uint public lastInvestmentTimestamp; uint public ONE_MINUTE = 1 minutes; function Governmental() { owner = msg.sender; if (msg.value<1 ether) throw; } function invest() { if (msg.value<jackpot/2) throw; lastInvestor = msg.sender; jackpot += msg.value/2; // <yes> <report> TIME_MANIPULATION lastInvestmentTimestamp = block.timestamp; } function resetInvestment() { if (block.timestamp < lastInvestmentTimestamp+ONE_MINUTE) throw; lastInvestor.send(jackpot); owner.send(this.balance-1 ether); lastInvestor = 0; jackpot = 1 ether; lastInvestmentTimestamp = 0; } } contract Attacker { function attack(address target, uint count) { if (0<=count && count<1023) { this.attack.gas(msg.gas-2000)(target, count+1); } else { Governmental(target).resetInvestment(); } } }
pragma solidity ^0.4.0; contract Governmental { address public owner; address public lastInvestor; uint public jackpot = 1 ether; uint public lastInvestmentTimestamp; uint public ONE_MINUTE = 1 minutes; function Governmental() { owner = msg.sender; if (msg.value<1 ether) throw; } function invest() { if (msg.value<jackpot/2) throw; lastInvestor = msg.sender; jackpot += msg.value/2; lastInvestmentTimestamp = block.timestamp; } function resetInvestment() { if (block.timestamp < lastInvestmentTimestamp+ONE_MINUTE) throw; lastInvestor.send(jackpot); owner.send(this.balance-1 ether); lastInvestor = 0; jackpot = 1 ether; lastInvestmentTimestamp = 0; } } contract Attacker { function attack(address target, uint count) { if (0<=count && count<1023) { this.attack.gas(msg.gas-2000)(target, count+1); } else { Governmental(target).resetInvestment(); } } }
time_manipulation
timed_crowdsale.sol
/* * @source: https://github.com/SmartContractSecurity/SWC-registry/blob/master/test_cases/timestamp_dependence/timed_crowdsale.sol * @author: - * @vulnerable_at_lines: 13 */ pragma solidity ^0.4.25; contract TimedCrowdsale { // Sale should finish exactly at January 1, 2019 function isSaleFinished() view public returns (bool) { // <yes> <report> TIME_MANIPULATION return block.timestamp >= 1546300800; } }
pragma solidity ^0.4.25; contract TimedCrowdsale { function isSaleFinished() view public returns (bool) { return block.timestamp >= 1546300800; } }