Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

exercises.tex 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. \documentclass [10pt]{article}
  2. \usepackage{latexsym}
  3. \usepackage{amssymb}
  4. \usepackage{epsfig}
  5. \usepackage{fullpage}
  6. \usepackage{enumerate}
  7. \usepackage{xspace}
  8. \usepackage{todonotes}
  9. \usepackage{listings}
  10. \usepackage{url}
  11. \usepackage[ruled,linesnumbered]{algorithm2e} % Enables the writing of pseudo code.
  12. \usepackage{float}% http://ctan.org/pkg/float
  13. \newcommand{\true}{true}
  14. \newcommand{\false}{false}
  15. \pagestyle{plain}
  16. \bibliographystyle{plain}
  17. \title{192.127 Seminar in Software Engineering (Smart Contracts) \\
  18. SWC-124: Write to Arbitrary Storage Location}
  19. \author{Exercises}
  20. \date{WT 2023/24}
  21. \author{\textbf{Ivanov, Ivaylo (11777707) \& Millauer, Peter (01350868)}}
  22. \newtheorem{theorem}{Theorem}
  23. \newtheorem{lemma}[theorem]{Lemma}
  24. \newtheorem{corollary}[theorem]{Corollary}
  25. \newtheorem{proposition}[theorem]{Proposition}
  26. \newtheorem{conjecture}[theorem]{Conjecture}
  27. \newtheorem{definition}[theorem]{Definition}
  28. \newtheorem{example}[theorem]{Example}
  29. \newtheorem{remark}[theorem]{Remark}
  30. \newtheorem{exercise}[theorem]{Exercise}
  31. \renewcommand{\labelenumi}{(\alph{enumi})}
  32. \usepackage{xcolor}
  33. \definecolor{codegreen}{rgb}{0,0.6,0}
  34. \definecolor{codegray}{rgb}{0.5,0.5,0.5}
  35. \definecolor{codepurple}{rgb}{0.58,0,0.82}
  36. \definecolor{backcolour}{rgb}{0.95,0.95,0.92}
  37. \definecolor{verylightgray}{rgb}{.97,.97,.97}
  38. \lstdefinelanguage{Solidity}{
  39. keywords=[1]{anonymous, assembly, assert, balance, break, call, callcode, case, catch, class, constant, continue, constructor, contract, debugger, default, delegatecall, delete, do, else, emit, event, experimental, export, external, false, finally, for, function, gas, if, implements, import, in, indexed, instanceof, interface, internal, is, length, library, log0, log1, log2, log3, log4, memory, modifier, new, payable, pragma, private, protected, public, pure, push, require, return, returns, revert, selfdestruct, send, solidity, storage, struct, suicide, super, switch, then, this, throw, transfer, true, try, typeof, using, value, view, while, with, addmod, ecrecover, keccak256, mulmod, ripemd160, sha256, sha3}, % generic keywords including crypto operations
  40. keywordstyle=[1]\color{blue}\bfseries,
  41. keywords=[2]{address, bool, byte, bytes, bytes1, bytes2, bytes3, bytes4, bytes5, bytes6, bytes7, bytes8, bytes9, bytes10, bytes11, bytes12, bytes13, bytes14, bytes15, bytes16, bytes17, bytes18, bytes19, bytes20, bytes21, bytes22, bytes23, bytes24, bytes25, bytes26, bytes27, bytes28, bytes29, bytes30, bytes31, bytes32, enum, int, int8, int16, int24, int32, int40, int48, int56, int64, int72, int80, int88, int96, int104, int112, int120, int128, int136, int144, int152, int160, int168, int176, int184, int192, int200, int208, int216, int224, int232, int240, int248, int256, mapping, string, uint, uint8, uint16, uint24, uint32, uint40, uint48, uint56, uint64, uint72, uint80, uint88, uint96, uint104, uint112, uint120, uint128, uint136, uint144, uint152, uint160, uint168, uint176, uint184, uint192, uint200, uint208, uint216, uint224, uint232, uint240, uint248, uint256, var, void, ether, finney, szabo, wei, days, hours, minutes, seconds, weeks, years}, % types; money and time units
  42. keywordstyle=[2]\color{teal}\bfseries,
  43. keywords=[3]{block, blockhash, coinbase, difficulty, gaslimit, number, timestamp, msg, data, gas, sender, sig, value, now, tx, gasprice, origin}, % environment variables
  44. keywordstyle=[3]\color{violet}\bfseries,
  45. identifierstyle=\color{black},
  46. sensitive=true,
  47. comment=[l]{//},
  48. morecomment=[s]{/*}{*/},
  49. commentstyle=\color{gray}\ttfamily,
  50. stringstyle=\color{red}\ttfamily,
  51. morestring=[b]',
  52. morestring=[b]"
  53. }
  54. \lstset{
  55. language=Solidity,
  56. backgroundcolor=\color{verylightgray},
  57. extendedchars=true,
  58. basicstyle=\footnotesize\ttfamily,
  59. showstringspaces=false,
  60. showspaces=false,
  61. numbers=left,
  62. numberstyle=\footnotesize,
  63. numbersep=9pt,
  64. tabsize=2,
  65. breaklines=true,
  66. showtabs=false,
  67. captionpos=b
  68. }
  69. \lstdefinestyle{mystyle}{
  70. backgroundcolor=\color{backcolour},
  71. commentstyle=\color{codegreen},
  72. keywordstyle=\color{magenta},
  73. numberstyle=\tiny\color{codegray},
  74. stringstyle=\color{codepurple},
  75. basicstyle=\ttfamily\footnotesize,
  76. breakatwhitespace=false,
  77. breaklines=true,
  78. captionpos=b,
  79. keepspaces=true,
  80. numbers=left,
  81. numbersep=5pt,
  82. showspaces=false,
  83. showstringspaces=false,
  84. showtabs=false,
  85. tabsize=2
  86. }
  87. \begin{document}
  88. \maketitle
  89. \begin{abstract}
  90. This paper outlines different forms of the common smart contract weakness with the SWC number 124, commonly referred to as "Write to Arbitrary Storage Location". While this paper focuses on applications within the context of Ethereum's EVM and higher-level language Solidity, we will also briefly touch on other research that deals with the Hyperledger Fabric environment. We will begin with a gentle introduction to the Solidity storage layout design that allows this weakness to occur, followed by common forms of exploit, alongside their associated consequences. Finally, we will outline the code characteristics that are detectable by automated tools as well as an exploit sketch.
  91. \end{abstract}
  92. \section{Weakness and consequences}
  93. \subsection{Solidity storage layout}
  94. Any contract's storage is a continuous 256-bit address space consisting of 32-bit values. In order to implement dynamically sized data structures like maps and arrays, Solidity distributes their entries in a pseudo-random location. Due to the vast 256-bit range of addresses collisions are statistically extremely improbable and of little practical relevance in safely implemented contracts.
  95. \medspace
  96. In the case of a dynamic array at variable slot $p$, data is written to continuous locations starting at $keccak(p)$. The array itself contains the length information as an $uint256$ value. Even enormous arrays are unlikely to produce collisions due to the vast address space, although an improperly managed array may store data to an unbounded user-controlled offset, thereby allowing arbitrary overwriting of data.
  97. \medspace
  98. For maps stored in variable slot $p$ the data for index $k$ can be found at $keccak(k . p)$ where $.$ is the concatenation operator. This is a statistically safe approach, as the chance of intentionally finding a value for $keccak(k . p)$ s.t. for a known stored variable $x$, $keccak(k . p) == storage\_address(x)$ is about one in $2^{256}$ and $keccak$ is believed to be a cryptographically secure hash function.
  99. \subsection{The Weakness}
  100. Any unchecked array write is potentially dangerous, as the storage-location of all variables is publicly known and an unconstrained array index can be reverse engineered to target them. This can be achieved by using the known array storage location $p$, target-variable $x$, and computing the offset-value $o$ such that $keccac(p) + o == storage\_address(x)$.
  101. \medspace
  102. A trivial example of such a vulnerable write operation is shown in Algorithm~\ref{alg:vuln-write}.
  103. \begin{algorithm}[H]
  104. \begin{lstlisting}[language=Solidity]
  105. pragma solidity 0.4.25;
  106. contract MyContract {
  107. address private owner;
  108. uint[] private arr;
  109. constructor() public {
  110. arr = new uint[](0);
  111. owner = msg.sender;
  112. }
  113. function write(unit index, uint value) {
  114. arr[index] = value;
  115. }
  116. }
  117. \end{lstlisting}
  118. \caption{A completely unchecked array write}
  119. \label{alg:vuln-write}
  120. \end{algorithm}
  121. \medspace
  122. In the following example (Algorithm~\ref{alg:pop-incorrect}) the $pop$ function incorrectly checks for an array $length >= 0$, thereby allowing the $length$ value to underflow when called with an empty array. Once this weakness is triggered, $update$ in Algorithm~\ref{alg:pop-incorrect} behaves just like $write$ did in Algorithm~\ref{alg:pop-incorrect}.
  123. \medspace
  124. \begin{algorithm}[H]
  125. \begin{lstlisting}[language=Solidity]
  126. pragma solidity 0.4.25;
  127. contract MyContract {
  128. address private owner;
  129. uint[] private arr;
  130. constructor() public {
  131. arr = new uint[](0);
  132. owner = msg.sender;
  133. }
  134. function push(value) {
  135. arr[arr.length] = value;
  136. arr.length++;
  137. }
  138. function pop() {
  139. require(arr.length >= 0);
  140. arr.length--;
  141. }
  142. function update(unit index, uint value) {
  143. require(index < arr.length);
  144. arr[index] = value;
  145. }
  146. }
  147. \end{lstlisting}
  148. \caption{An incorrectly managed array length}
  149. \label{alg:pop-incorrect}
  150. \end{algorithm}
  151. \medspace
  152. Another weakness that allows arbitrary storage access is unchecked assembly code. Assembly is a powerful tool that allows the developers to get as close to the EVM as they can, but it may also be very dangerous when not used correctly. As per the documentation\footnote{\url{https://docs.soliditylang.org/en/latest/assembly.html}, accessed: Oct. 30th 2023}: \textit{"this [inline assembly]
  153. bypasses important safety features and checks of Solidity. You should only use it for tasks that need it, and only if you are confident with using it."}
  154. When given access to such low-level instructions, a programmer can construct not only weaknesses similar to the ones described previously, but also others, such as overwriting map locations, contract variables etc.
  155. An example for such a weakness is given in Algorithm~\ref{alg:unchecked-assembly}.
  156. \medspace
  157. \begin{algorithm}[H]
  158. \begin{lstlisting}[language=Solidity]
  159. pragma solidity 0.4.25;
  160. contract MyContract {
  161. address private owner;
  162. mapping(address => bool) public managers;
  163. constructor() public {
  164. owner = msg.sender;
  165. setNextUserRole(msg.sender);
  166. }
  167. function setNextManager(address next) internal {
  168. uint256 slot;
  169. assembly {
  170. slot := managers.slot
  171. sstore(slot, next)
  172. }
  173. bytes32 location = keccak256(abi.encode(160, uint256(slot)));
  174. assembly {
  175. sstore(location, true)
  176. }
  177. }
  178. function registerUser(address user) {
  179. require(msg.sender == owner);
  180. setNextManager(user);
  181. }
  182. function cashout() {
  183. require(managers[msg.sender]);
  184. address payable manager = msg.sender;
  185. manager.transfer(address(this).balance);
  186. }
  187. }
  188. \end{lstlisting}
  189. \caption{An unchecked assembly write to mapping}
  190. \label{alg:unchecked-assembly}
  191. \end{algorithm}
  192. \medspace
  193. The contract has a manager mapping, which is intended to be used as a stack.
  194. The developer has added the \texttt{setNextManager} function, which should set the top of the stack to the latest user as a manager.
  195. The issue is that the function is implemented in such a way, that the stack does not grow, but the first element is always overwritten - this arises from the fact that the memory slot
  196. of the managers mapping does not point to the memory address on the top of the stack, but instead to the base of it.
  197. The function is then using this slot address directly, without calculating any offset, overwriting the base of the stack. If social engineeering is applied, an attacker can persuade the
  198. owner to set them as a manager, which would result in the weakness being exploited directly and the owner giving up their own management rights.
  199. \subsection{Consequences}
  200. The consequences of exploiting an arbitrary storage access weakness can be of different types and severity.
  201. An attacker may gain read-write access to private contract data, which should only be accessible to owners, maintainers etc.
  202. They may also exploit the contract to circumvent authorization checks and drain the contract funds.
  203. According to Li Duan et al.~\cite{multilayer}, an attacker may also be able to destroy the contract storage structure and thus cause
  204. unexpected program flow, abnormal function execution or contract freeze.
  205. \subsection{Similar yet safe code example}
  206. Using dynamic arrays is naturally not inherently dangerous, as long as they're used properly. The following version of Algorithm~\ref{alg:pop-incorrect} correctly checks for array length, and thereby prevents the integer underflow of the length value. This code example is not vulnerable to the techniques shown in this paper.
  207. \medspace
  208. \begin{algorithm}[H]
  209. \begin{lstlisting}[language=Solidity]
  210. pragma solidity 0.4.25;
  211. contract MyContract {
  212. address private owner;
  213. uint[] private arr;
  214. constructor() public {
  215. arr = new uint[](0);
  216. owner = msg.sender;
  217. }
  218. function push(value) {
  219. arr[arr.length] = value;
  220. arr.length++;
  221. }
  222. function pop() {
  223. require(arr.length > 0);
  224. arr.length--;
  225. }
  226. function update(unit index, uint value) {
  227. require(index < arr.length);
  228. arr[index] = value;
  229. }
  230. }
  231. \end{lstlisting}
  232. \caption{Correctly managed array length}
  233. \label{alg:pop-correct}
  234. \end{algorithm}
  235. \section{Vulnerable contracts in literature}
  236. One example for vulnerable contracts, which is similar to Algorithm~\ref{alg:pop-incorrect}, is mentioned in the paper by Li Duan et al.~\cite{multilayer}:
  237. \medspace
  238. \begin{algorithm}[H]
  239. \begin{lstlisting}[language=Solidity]
  240. function PopBonusCode() public {
  241. require(0 <= bonusCodes.length);
  242. bonusCodes.length--;
  243. }
  244. function UpdateBonusCodeAt(uint idx, uint c) public {
  245. require(idx < bonusCodes.length);
  246. bonusCodes[idx] = c;
  247. }
  248. \end{lstlisting}
  249. \caption{Arbitrary write as per Li Duan et al.}
  250. \label{alg:multilayer-example}
  251. \end{algorithm}
  252. \medspace
  253. We will not go into a detailed explanation, as we already did this in the previous section. A more sophisticated example is presented in the paper by Sukrit Kalra et al.~\cite{Kalra2018ZEUSAS}:
  254. \medspace
  255. \begin{algorithm}[H]
  256. \begin{lstlisting}[language=Solidity]
  257. uint payout = balance/participants.length;
  258. for (var i = 0; i < participants.length; i++)
  259. participants[i].send(payout);
  260. \end{lstlisting}
  261. \caption{Arbitrary read as per Sukrit Kalra et al.}
  262. \label{alg:zeus-example}
  263. \end{algorithm}
  264. \medspace
  265. The vulnerability here is an integer overflow - as the variable \texttt{i} is dynamically typed, it will get the smallest possible type that will be able to hold the value 0 - that being \texttt{uint8}, which is able to hold positive integers up to 255.
  266. \medspace
  267. Because of this, if the length of the \texttt{participants} arrays is greater than 255, the integer overflows on the 256th iteration and instead of moving on to \texttt{participants[255]}, it reverts back to the first element in the array. As a result, the first 255 participants will split all the balance of the contract, whereas the rest will get nothing.
  268. \section{Code properties and automatic detection}
  269. Automatic detection tools can be broadly categorized into ones employing static analysis and those who use fuzzing, i.e. application of semi-random inputs. Notable static analysis tools include Securify~\cite{securify} and teEther~\cite{teether} which both function in a similar manner:
  270. \medspace
  271. Initially, the given EVM byte-code is disassembled into a control-flow-graph (CFG). In the second step, the tools identify potentially risky instructions. In the case of arbitrary writes, the instruction of note is $sstore(k,v)$ where both $k$ and $v$ are input-controlled. The tools differ in the way they identify whether or not the values are input-controlled.
  272. \medspace
  273. In the case of Securify~\cite{securify}, the CFG is translated into what the authors call "semantic facts" to which an elaborate set of so-called security patterns is applied. These patterns consist of building blocks in the form of predicates, which allows the tool to simply generate output based on the (transitively) matched patterns.
  274. \medspace
  275. teEther~\cite{teether} employs a similar approach, but instead the authors opt to build a graph of dependent variables. If the graph arrives at a $sstore(k,v)$ instruction and a path can be found leading to user-controlled inputs, the tool infers a set of constraints which are then used to automatically generate an exploit.
  276. \medspace
  277. The fuzz-driven approach to vulnerability detection is more abstract, as general-purpose fuzzing tools generally don't have knowledge of the analysed program. For the tool SmartFuzzDriverGenerator~\cite{fuzzdrivegen}, a multitude of these fuzzing libraries can be used, although its application is limited to the Hyperledger Fabric permissioned blockchain. The problem at hand is, that the technique cannot interface with a smart contract out of the box. The "glue" between fuzzer and program is called a driver, hence the name of "driver-generator".
  278. \medspace
  279. SmartFuzzDriverGenerator aims to automatically generate such a driver by inferring the available APIs from the bytecode. There are multiple approaches to decide the order of available fuzzing steps, including a heuristic based on code complexity (i.e. nested conditions, loops, array operations, etc.), random sequences, and user-generated strategies.
  280. \medspace
  281. The Smartian tool~\cite{smartian} attempts to find a middle-ground between static and dynamic analysis by first transforming the EVM bytecode into control-flow facts. Based on this information, a set of seed-inputs is generated that are expected to have a high probability of yielding useable results. Should no exploit be found, the seed-inputs are then mutated in order to yield a higher code coverage.
  282. \section{Exploit sketch}
  283. An exploitation sketch to Algorithm~\ref{alg:pop-incorrect} and to Algorithm~\ref{alg:multilayer-example} is available from Doughoyte~\cite{doughoyte}.
  284. \textbf{Checkpoint A}
  285. We assume that the following events have occurred:
  286. \begin{enumerate}
  287. \item the contract MerdeToken\footnote{\url{https://github.com/Arachnid/uscc/blob/master/submissions-2017/doughoyte/MerdeToken.sol}, accessed: Oct. 30th 2023} has been created;
  288. \item the investor has set a withdrawal limit of 1 ether, which only they can change;
  289. \item an investor has invested 50 ETH;
  290. \item the owner is malicious.
  291. \end{enumerate}
  292. At this point, an example storage layout as per Doughoyte would be:
  293. \medspace
  294. \lstset{style=mystyle}
  295. \begin{algorithm}[H]
  296. \begin{lstlisting}
  297. "storage": {
  298. // The address of the contract owner:
  299. "0000000000000000000000000000000000000000000000000000000000000000": "94b898c1a30adcff67208fd79b9e5a4d339f3cc6d2",
  300. // The address of the trusted third party:
  301. "0000000000000000000000000000000000000000000000000000000000000001": "948bc7317ad44d6f34f0f0b6e3c8c7bf739ba666fa",
  302. // The amount deposited (50 ETH):
  303. "0000000000000000000000000000000000000000000000000000000000000003": "8902b5e3af16b1880000",
  304. // The withdrawal limit (1 ETH):
  305. "0000000000000000000000000000000000000000000000000000000000000004": "880de0b6b3a7640000",
  306. // the legth of the array would normaly stay here, if it was not zero at init time
  307. // balanceOf[investorAddress] (50 MDT):
  308. "dd87d7653af8fba540ea9ebd2d914ba190d975fcfa4d8d2927126a5decdbff9e": "8902b5e3af16b1880000"
  309. }
  310. \end{lstlisting}
  311. \caption{Exploit - Memory at Checkpoint A}
  312. \label{alg:exploit-checkpoint-a}
  313. \end{algorithm}
  314. \medspace
  315. \textbf{Checkpoint B}
  316. Afterwards, the malicious owner calls the vulnerable function \texttt{popBonusCode()} and the length of the array is set to the max value. This happened, because prior to the underflow, the array length was zero and, to save space, it was omitted from the memory:
  317. \medspace
  318. \lstset{style=mystyle}
  319. \begin{algorithm}[H]
  320. \begin{lstlisting}
  321. "storage": {
  322. "0000000000000000000000000000000000000000000000000000000000000000": "94b898c1a30adcff67208fd79b9e5a4d339f3cc6d2",
  323. "0000000000000000000000000000000000000000000000000000000000000001": "948bc7317ad44d6f34f0f0b6e3c8c7bf739ba666fa",
  324. "0000000000000000000000000000000000000000000000000000000000000003": "8902b5e3af16b1880000",
  325. "0000000000000000000000000000000000000000000000000000000000000004": "880de0b6b3a7640000",
  326. // The array length has underflowed:
  327. "0000000000000000000000000000000000000000000000000000000000000005": "a0ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
  328. "dd87d7653af8fba540ea9ebd2d914ba190d975fcfa4d8d2927126a5decdbff9e": "8902b5e3af16b1880000"
  329. }
  330. \end{lstlisting}
  331. \caption{Exploit - Memory at Checkpoint B}
  332. \label{alg:exploit-checkpoint-b}
  333. \end{algorithm}
  334. \medspace
  335. Increasing the length of the array to the maximum allowed by \texttt{uint256} was important, as this will now allow the owner to pass the requirement set in \texttt{modifyBonusCode} and still
  336. use the function for storage modification.
  337. \medspace
  338. \textbf{Checkpoint C} The owner is then able to use \texttt{modifyBonusCode} to increase the fixed withdraw limit to the max \texttt{uint256} value. Had the contract not have this vulnerability,
  339. this action should only have been possible through the \texttt{setWithdrawLimit}, which is only available to the investor.
  340. \medspace
  341. In order to overwrite the withdrawal limit, the owner must calculate the hex value to use as a first argument (index) to the function.
  342. Since the array \texttt{bonusCodes} underflow is defined in the sixth place in the contract storage, its length is in the fifth storage slot (counting from zero)
  343. \medspace
  344. The limit is defined at the fourth storage slot. Then, in order to manipulate the withdrawal limit, the owner must convert the address of the length to hexadecimal:
  345. \medspace
  346. \lstset{style=mystyle}
  347. \begin{algorithm}[H]
  348. \begin{lstlisting}
  349. $ web3.sha3("0x0000000000000000000000000000000000000000000000000000000000000005", { encoding: 'hex' })
  350. > "0x036b6384b5eca791c62761152d0c79bb0604c104a5fb6f4eb0703f3154bb3db0"
  351. \end{lstlisting}
  352. \caption{Exploit - Convert length address to hex}
  353. \label{alg:exploit-convert-address}
  354. \end{algorithm}
  355. \medspace
  356. and then just calculate the array index that will wrap around using the formula $2^{256} - H + 4$, where $2^{256}$ is the max \texttt{uint256} value, H is the hex obtained from the previous command and 4 is the offset of the withdrawal limit storage slot from the base of the contract. This, converted to hex, will give the owner the address to use with \texttt{modifyBonusCode}. The Perl snippet below does that:
  357. \medspace
  358. \lstset{style=mystyle}
  359. \begin{algorithm}[H]
  360. \begin{lstlisting}[language=Octave]
  361. $ perl -Mbigint -E 'say ((2**256 - 0x036b6384b5eca791c62761152d0c79bb0604c104a5fb6f4eb0703f3154bb3db0 + 4)->as_hex)'
  362. > 0xfc949c7b4a13586e39d89eead2f38644f9fb3efb5a0490b14f8fc0ceab44c254
  363. \end{lstlisting}
  364. \caption{Exploit - Convert limit offset to address}
  365. \label{alg:exploit-convert-offset}
  366. \end{algorithm}
  367. \medspace
  368. As a result, the memory now looks like this:
  369. \medspace
  370. \lstset{style=mystyle}
  371. \begin{algorithm}[H]
  372. \begin{lstlisting}
  373. "storage": {
  374. "0000000000000000000000000000000000000000000000000000000000000000": "94b898c1a30adcff67208fd79b9e5a4d339f3cc6d2",
  375. "0000000000000000000000000000000000000000000000000000000000000001": "948bc7317ad44d6f34f0f0b6e3c8c7bf739ba666fa",
  376. "0000000000000000000000000000000000000000000000000000000000000003": "8902b5e3af16b1880000",
  377. // The withdrawal limit is now really high:
  378. "0000000000000000000000000000000000000000000000000000000000000004": "a0ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
  379. "0000000000000000000000000000000000000000000000000000000000000005": "a0ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
  380. "dd87d7653af8fba540ea9ebd2d914ba190d975fcfa4d8d2927126a5decdbff9e": "8902b5e3af16b1880000"
  381. }
  382. \end{lstlisting}
  383. \caption{Exploit - Memory at Checkpoint C}
  384. \label{alg:exploit-checkpoint-c}
  385. \end{algorithm}
  386. \medspace
  387. \textbf{Checkpoint D} The owner can now call \texttt{withdraw()} with the full amount of ether in the contract and drain it. The investor has not increased the limit at any point.
  388. \section{Conclusion}
  389. We presented different forms of the common weakness SWC-124: Write to Arbitrary Storage Location and how they might be detected using automated tools. We have shown how a possible exploit may be constructed, and how this can lead to the complete compromise of a smart contract's storage and control flow. We have given multiple attackable and benign code examples to illustrate this weakness. We believe this weakness to be of particular practical relevance, as it is very easy to introduce by accident, and hard to for a developer to spot without advanced knowledge of the underlying mechanisms that cause it.
  390. As for preventative measures, we would recommend developers not to interact with low-level building blocks like an array's length value or inline assembly instructions if possible, and instead to employ standard library functions when ever available.
  391. \bibliography{exercise.bib}
  392. \end{document}