41.Owner change
2023-06-30 16:17:30 # 00.security

Owner change

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
contract Owned {

address public owner;

modifier onlyOwner() {
require(msg.sender == owner);
_;
}

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

function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != 0);
owner = newOwner;
}

}

The contract above is unsafe: DoS! What if I call transferOwnership() with 0? The owner can no longer change.

Fix it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
contract Owned {

address public owner;
address public ownerTransf; // temporary storage

modifier onlyOwner() {
require(msg.sender == owner);
_;
}

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

function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != 0);
// Instead of swapping owner, we store the 'newOwner' address in the 'ownerTransf' variable.
ownerTransf = newOwner;
}

// New functions

// Cancel any on-going transfer.
function cancelOwnershipTransfer() public onlyOwner {
ownerTransf = 0;
}

// Lets the new owner claim ownership.
function claimOwnership() public {
require(msg.sender == ownerTransf);
owner = ownerTransf;
ownerTransf = 0;
}

}
Prev
2023-06-30 16:17:30 # 00.security
Next