1

This is a very simple contract that I can't hack and I'm stuck, I need some help to get the concepts right.

pragma solidity ^0.4.10;

contract SimpleToken {
    mapping(address => uint) public balances;

    function buyToken() payable {
        balances[msg.sender]+=msg.value / 1 ether;
    }

    function sendToken(address _recipient, uint _amount) {
        require(balances[msg.sender]!=0);

        balances[msg.sender]-=_amount;
        balances[_recipient]+=_amount;
    }
}

I'm using truffle to create the project where this and future contracts will be created, tested, deployed and attacked. I want to create a repository with examples of these hacks while I learn how to do them.

  1. What's the vulnerability and why?

We have sendToken(), to call it you just have to have some balance in your account by first calling buyToken(), but then what? reentrancy, overflow/underflow?

  1. Do I need to create a contract to attack it or just call it from an account via web3js?
pragma solidity ^0.4.10;

import '../SimpleToken.sol';

contract SimpleTokenAttack {
    SimpleToken public victim;

    function SimpleTokenAttack(address _addr) public {
        victim =  SimpleToken(_addr);
    }

    function buy() public returns(bool) {
        // How can I call the function victim.buyToken ?
    }

    function send() public returns(bool) {
        // How can I call the function victim.sendToken ?
    }
}

I plan to create attacks by deloying scripts with truffle exec.

const SimpleTokenContract = artifacts.require('SimpleToken')
const SimpleTokenAttack = artifacts.require('SimpleTokenAttack')

async function execute(callback) {

    let contract = await SimpleTokenContract.deployed()
    console.log(contract.address)

    let attack = await SimpleTokenAttack.deployed()
    console.log(attack.address)

    /*
    - Call buy()
    - Call send()
    */


    callback()
}

module.exports = execute
  • 1
    What would happen if you bought 1 token and then tried to transfer 2 tokens? – user19510 Sep 14 at 18:08
  • 1
    And you should be able to attack this without creating a contract. – user19510 Sep 14 at 18:09
  • 1
    Thanks @smarx, all the exercises don't specify what to do or when you 'won' so I guess I just have to create an underflow and call it a victory. – Ian P. Britto Sep 14 at 22:14
  • Shameless plug for my Capture the Ether. – user19510 Sep 14 at 23:48
  • @smarx haha you are the best, that's what I need. – Ian P. Britto Sep 15 at 13:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.