<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Christian Ruink on Medium]]></title>
        <description><![CDATA[Stories by Christian Ruink on Medium]]></description>
        <link>https://medium.com/@christian.ruink?source=rss-eb8a6e07cf22------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Bh1nxuKXRXU-oe4V.</url>
            <title>Stories by Christian Ruink on Medium</title>
            <link>https://medium.com/@christian.ruink?source=rss-eb8a6e07cf22------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 13:19:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@christian.ruink/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Ethernaut “Privacy” problem]]></title>
            <link>https://medium.com/coinmonks/ethernaut-privacy-problem-7106562caee2?source=rss-eb8a6e07cf22------2</link>
            <guid isPermaLink="false">https://medium.com/p/7106562caee2</guid>
            <category><![CDATA[ethernaut]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Christian Ruink]]></dc:creator>
            <pubDate>Mon, 28 May 2018 06:50:40 GMT</pubDate>
            <atom:updated>2018-05-28T06:52:49.561Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*td8z-tlZSp7tAC5U0gthaA.png" /><figcaption>Bugs…I hate these guys</figcaption></figure><p>Fifth instance in a series of articles breaking down the awesome solidity security coding challenges at <a href="https://ethernaut.zeppelin.solutions/">The Ethernaut</a> by the good folks of Zeppelin Solutions.</p><p>The set of problems available are very fun and illustrative of common security pitfalls in smart contracts so if you’re feeling stuck in a particular challenge and just want a peek into the how and why of the solution this and other articles I’ve published with the same nomenclature are for you.</p><p>This one is going to deal with the following challenge:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I5kA0u7hwc9J02YyQTV4oQ.png" /><figcaption>The “Privacy” Contract</figcaption></figure><blockquote>The creator of this contract was careful enough to protect the sensitive areas of its storage.</blockquote><blockquote>Unlock this contract to beat the level.</blockquote><h3>Let’s examine the contract 🔍</h3><pre>bool public locked = true; <br>uint256 public constant ID = block.timestamp; <br>uint8 private flattening = 10; <br>uint8 private denomination = 255; <br>uint16 private awkwardness = uint16(now); <br>bytes32[3] private data;</pre><p>Firstly, the contract declares a bunch fo storage variables, and some spoilers, only “locked” (what we need to change) and “data” (what we need to read) really matter, the rest are there just to screw with us.</p><pre>function Privacy(bytes32[3] _data) public { <br>   data = _data;<br>}<br>   <br>function unlock(bytes16 _key) public {     <br>    require(_key == bytes16(data[2]));     <br>    locked = false;  <br>}</pre><p>The <em>constructor</em> is where the mystery data was originally passed to the contract, an option to find out more about this information would be to snoop around the <strong>input parameters </strong>for the transaction that created this contract and derive the relevant information from there.</p><p>The <em>unlock</em> function is our only point of interaction with this contract and here we just need to pass the right sequence of bytes16 to unlock the contract and count this as a win.</p><h3>Our approach 🏃</h3><p>The problem and solution is actually quite similar to a previous challenge I’ve covered, <a href="https://medium.com/coinmonks/ethernaut-vault-problem-b2675393650b">the Vault Problem</a>. This is basically a souped version of that challenge were we are forced to know a little bit more about the way storage variables are indexed and how casting works for different types.</p><p>The first thing to know is that nothing is stopping us from snooping around a contracts storage variables (even private ones!) very easily, easing something like web3.eth.getStorageAt(/contract.address/ /var index/)</p><p>Storage variables are indexed as they’re defined, in other words in this particular case the “locked” variable that is first defined in the contract will be available web3.eth.getStorageAt(/contract.address/, 0)</p><p>And while this is true, things can get a little bit more complicated taking storage optimizations into account! The best way to illustrate this is to fetch all the available data and see what we get!</p><pre>let data = []</pre><pre>let callbackFNConstructor = (index) =&gt; (error, contractData) =&gt; {</pre><pre>  data[index] = contractData</pre><pre>}</pre><pre>for(var i = 0; i &lt; 6; i++){</pre><pre>web3.eth.getStorageAt(contract.address, i, callbackFNConstructor(i))</pre><pre>}</pre><p>Running the code in the web console above will fetch us the first 6 storage variables defined in the target contract.</p><p>You should be looking at something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tl-8gWrBSRf4I6o6_Q2SQA.png" /><figcaption>Dat is storage data</figcaption></figure><p>But hey, that’s weird! There are 6 storage variables defined in this contract and our data array only has information for 4. What’s more the first variable defined is a simple boolean so we’d expect the first result to be something like:</p><pre>&quot;0x0000...001&quot;</pre><p>Instead we get way more bits than we bargained for in the first position.</p><p>This all has to do with storage optimization and it follows very simple rules.</p><ol><li>Each index set aside for a storage variable allows 256 bits.</li><li>Variables are indexed in the order they’re defined in contract.</li><li>If a variable takes under &lt; 256 bits to represent, leftover space will be shared with subsequent variables <strong>IF THEY FIT</strong>.</li><li>Constants don’t use this type of storage.</li></ol><p>Looking back at our storage variables we can see the index goes something like this.</p><pre>bool public locked = true;  //rightmost bits of index[0]<br>uint256 public constant ID = block.timestamp; //Not indexed<br>uint8 private flattening = 10; //rightmost bits of index[0] - 2 <br>uint8 private denomination = 255; //rightmost bits of index[0] - 4<br>uint16 private awkwardness = uint16(now); //bits of index[0] -6<br>bytes32[3] private data; //indexes 1,2,3 occupied by each piece</pre><p>With this indexing rules we can actually make sense of our <em>data[0] </em>result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/1*95wruZ4T005mQpZje_vUog.png" /></figure><p>from the hexadecimal</p><p>01 = true</p><p>0a = 10;</p><p>ff = 255;</p><p>c6a6 = “A coerced to 16 bits ‘now’ ”</p><p>Now that we know what represents what in our fished out storage data, it’s easy to grab the relevant information for our hack: <strong><em>data[3] </em></strong>(Which is equivalent to data[2] from the contract)</p><h3>Variable Coercion 🛠</h3><pre>function unlock(bytes16 _key) public {     <br>    require(_key == bytes16(data[2]));     <br>    locked = false;  <br>}</pre><p>The unlock function matches our ‘key’ with a coerced to bytes16 data[2]. Now that we know what data[2] is, it’s going to be peanuts to solve this, we just need to understand how coercion works from bytes32 =&gt;bytes16.</p><p>If you have decent programming experience the concept of type coercion shouldn’t be a strange on but it’s basically like this:</p><pre>int datumA = 5; /This is 5/<br>uint datumB = uint(datumA);  /This is 5/</pre><p>datumB can’t be negative now, and that type is relevant to use for array indexes and a bunch of other useful things. Very simple right? Let’s see another example:</p><pre>int datumA = -5; /This is -5/<br>uint datumB = (datumA);  /This is 115792089237316195423570985008687907853269984665640564039457584007913129639931/</pre><p>WTF right? Well it all has to do with the bit representation of the types you are coercing. In a sense coercion breaks the fundamental rules of a statistically typed language and a sort of meta-rule for dealing with that coercion kicks in. How that plays out can vary from language to language and from type to type (Should you be able to coerce non numerics strings to uints? they’re all bits after all…)</p><p>In any case, the best way to understand the rules reigning over coercion is to <a href="https://solidity.readthedocs.io/">read the documentation</a> or <a href="http://remix.ethereum.org/">play around with coercion till you get it</a> (or do both)</p><p>I’ve digressed, we’re interested in bytes32 =&gt; bytes16 so we can know what bytes16 type key to send as an input parameter, and that particular coercion is pretty straightforward.</p><p>You just take the first half of the bytes32 data and that’s going to be your new bytes16 type data. Calling the unlock method with that as an input parameter should clear up the last hurdle.</p><h3><strong>Conclusion</strong></h3><p>Just like with the vault problem this challenge emphasizes just how not-private are our private variables (or anything really) in the blockchain. The victory screen includes a link to <a href="https://medium.com/aigang-network/how-to-read-ethereum-contract-storage-44252c8af925">Darius’s write up</a> on snooping contract’s storage with more examples for more complex data types which I had linked in the vault problem as well, so be sure to give it a read if you’re still interested in this topic.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7106562caee2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/ethernaut-privacy-problem-7106562caee2">Ethernaut “Privacy” problem</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ethernaut ‘Vault’ Problem]]></title>
            <link>https://medium.com/coinmonks/ethernaut-vault-problem-b2675393650b?source=rss-eb8a6e07cf22------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2675393650b</guid>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[solidity-tutorial]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[Christian Ruink]]></dc:creator>
            <pubDate>Thu, 17 May 2018 04:32:26 GMT</pubDate>
            <atom:updated>2022-06-25T16:30:23.273Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8as3MAB2JYV-sMP5q8fFxg.png" /><figcaption>A soft touch… A quick glance</figcaption></figure><p>This is the fourth time I write about one of the awesome Ethereum security problems at: <a href="https://ethernaut.zeppelin.solutions/level/0x6b7b4a5260b67c1ee9196a42dd1ed8633231ba0a">Ethernaut</a>, and I have become exceedingly efficient at it! Let’s get started.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*R4sDBfFeL_1ehmXS2JBJGg.png" /><figcaption>The “Vault” contract</figcaption></figure><blockquote>Unlock the vault to pass the level!</blockquote><p>This one definitely has a different flavor than other problems we’ve faced so far. There are potentially two routes we can take to open this vault:</p><ol><li>Brute force it somehow, through a vulnerability unlock the vault without knowing the password.</li><li>Use our guile to get our hands on the secret password.</li></ol><p>Honestly, 1 is just a waste of time, this contract is so simple that there’s really not much room for acrobatics, the only way we’re getting through is if we learn the password. So, what do we know about the password at this early stage?</p><h3><strong>Know thy Target 👀</strong></h3><pre>bytes32 private password;</pre><p>Password is a storage variable, type bytes32 with private access. The last point is worth clarifying, as per the docs here’s what the different access types mean:</p><ul><li>external: all, only externally</li><li>public: all (this is the default), externally and internally</li><li>internal: only this contract and contracts deriving from it, only internally</li><li><strong>private: only this contract, only internally</strong></li></ul><p>Basically, that means we can’t just go contract.password() on our console and call it a day. Notably if password had internal visibility we could inherit from this contract and access the password variable through the son!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qkAiVWLv32eeour0Am1X7w.png" /><figcaption>This works</figcaption></figure><p>With the private accessibility though, only internal calls from the very same contract can access them. At this point, you can feel defeated or remember that Ethereum is a public ledger detailing millions of transactions in a completely transparent way for the eyes of the world to see. This means we can just query the contract for it’s <strong>storage. </strong>This fact won’t change, no matter how carefully you encapsulate delicate variables in your contract.</p><h3>Spelunking Storage 🐚</h3><p>So, how do we unofficially inspect a contract? (That is, through the public ledger and not the neat and tidy implementation of the contract itself)</p><p>Enter <strong>web3</strong> the js library for interacting with the Ethereum blockchain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hb_RRuAH4ZuMOgx_kHRe_A.png" /><figcaption>It’s been available for Ethernauts all along…</figcaption></figure><p>The method we’re interested in is the aptly name <strong>web3.eth.getStorage.</strong> Takes a contract address, an integer (index!) and if you’re using Metamask you’re going to also have to pass a callback function to avoid unnecessary freakouts.</p><p>Wait a minute, indexes? Yes! We’re not querying the entire storage, we’re getting it piecemeal and luckily the storage is organized in a pretty straightforward way.</p><p><strong>Each storage element </strong>is indexed accordingly to the order they’re defined in. In the case of the vault contract, the <em>locked </em>storage variable has index 0, and that juicy password has index 1.</p><p>Put it all together and:</p><pre>let contractAddress = //contract Address<br>password = web3.eth.getStorageAt(contractAddress, index))<br>// For Metamask callback whining<br>web3.eth.getStorageAt(contractAddress, 1, <br>function(error, result) {password = result}))</pre><p>You’re going to get a hexadecimal string as a result here, so if you want to make sure you’ve got the right variable why don’t you try converting that result to Ascii?</p><h3>Conclusion</h3><p>This problem is meant to drill home this simple fact: <strong>“Everything is public on a public blockchain”. </strong>The information asymmetry of a client / server application is not present in a client / blockchain environment.</p><p>Think on that before uploading your DNA to the blockchain with a “private” visibility.👩‍🔬</p><p>If you want to know more about inspecting Ethereum smart contracts check out this <a href="https://medium.com/aigang-network/how-to-read-ethereum-contract-storage-44252c8af925">great write-up</a> by <a href="https://medium.com/u/6e8ea834f227">Darius</a>, famous TSM toplaner!</p><blockquote>Join Coinmonks<a href="https://t.me/coincodecap"> Telegram Channel</a> and<a href="https://www.youtube.com/c/coinmonks/videos"> Youtube Channel</a> get daily <a href="http://coincodecap.com/">Crypto News</a></blockquote><h4>Also, Read</h4><ul><li><a href="https://medium.com/coinmonks/top-10-crypto-copy-trading-platforms-for-beginners-d0c37c7d698c">Copy Trading</a> | <a href="https://medium.com/coinmonks/crypto-tax-software-ed4b4810e338">Crypto Tax Software</a></li><li><a href="https://coincodecap.com/grid-trading">Grid Trading</a> | <a href="https://medium.com/coinmonks/the-best-cryptocurrency-hardware-wallets-of-2020-e28b1c124069">Crypto Hardware Wallet</a></li><li><a href="http://Top 4 Telegram Channels for Crypto Traders">Crypto Telegram Signals</a> | <a href="https://medium.com/coinmonks/crypto-trading-bot-c2ffce8acb2a">Crypto Trading Bot</a></li><li><a href="https://medium.com/coinmonks/crypto-exchange-dd2f9d6f3769">Best Crypto Exchange</a> | <a href="https://medium.com/coinmonks/bitcoin-exchange-in-india-7f1fe79715c9">Best Crypto Exchange in India</a></li><li><a href="https://medium.com/coinmonks/best-crypto-apis-for-developers-5efe3a597a9f">Best Crypto APIs</a> for Developers</li><li>Best <a href="https://medium.com/coinmonks/top-5-crypto-lending-platforms-in-2020-that-you-need-to-know-a1b675cec3fa">Crypto Lending Platform</a></li><li>An ultimate guide to <a href="https://medium.com/coinmonks/leveraged-token-3f5257808b22">Leveraged Token</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2675393650b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/ethernaut-vault-problem-b2675393650b">Ethernaut ‘Vault’ Problem</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ethernaut “Telephone” problem.]]></title>
            <link>https://medium.com/coinmonks/ethernaut-telephone-problem-77c574ac8da?source=rss-eb8a6e07cf22------2</link>
            <guid isPermaLink="false">https://medium.com/p/77c574ac8da</guid>
            <category><![CDATA[telephone]]></category>
            <category><![CDATA[ethernaut]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Christian Ruink]]></dc:creator>
            <pubDate>Tue, 08 May 2018 00:16:15 GMT</pubDate>
            <atom:updated>2018-05-08T23:29:57.714Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*_vnnAhVkovM6IdG2p_yYeg.png" /><figcaption><em>Brrbbb… Brbbb…</em></figcaption></figure><p>Third instance of a series covering the <strong>awesome </strong>set of security problems curated by Zeppelin Solutions at: <a href="https://ethernaut.zeppelin.solutions/level/0x6b7b4a5260b67c1ee9196a42dd1ed8633231ba0a">Ethernaut</a>.</p><p>This one is going to be really short, since the problem itself is pretty contrived and there’s not much to look at:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0iU2pyvkmNHzCTnMyvoVdw.png" /><figcaption>The Telephone contract</figcaption></figure><blockquote>Claim ownership of the contract below to complete this level.</blockquote><p>If you’re not completely new to solidity you should be able to read this and think. “Hmmm…How does tx.origin != msg.sender”? A quick google search will answer that question, <strong>tx.origin</strong> will always refer to the original address that made the original transaction (even if the contract you call, calls another, tx.origin will always refer to your address), while <strong>msg.sender </strong>refers to the address of the last caller to the current contract evaluating the transaction.</p><p>Like in most cases, you pwN a smart contract using another:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kHUokWN0iLzAF9a3S-0uBQ.png" /><figcaption>ring ring ring</figcaption></figure><p>Calling Patrick from any Ethereum address with the address your playing the Ethernaut game as a parameter will result in a win!</p><h3>Conclusion</h3><p>Though the exploit was rather obvious, it’s still a very good problem to reflect on the cases where you’d actually <em>want </em>to use <strong>tx.origin</strong> over <strong>msg.sender. </strong>There are some downsides (you can read them on a successful submit!) but it’s a bit hard to think of some upsides. Why don’t you post any you come up with here? I promise I’ll kick the thought back and forth with you : )</p><figure><a href="https://medium.com/coinmonks/smart-contract/home"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t1wllxpa8vlcf9ys0HNYNQ.png" /></a><figcaption><strong>Click to read more about smart contracts</strong></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77c574ac8da" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/ethernaut-telephone-problem-77c574ac8da">Ethernaut “Telephone” problem.</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ethernaut Coin Flip problem]]></title>
            <link>https://medium.com/coinmonks/ethernaut-coin-flip-problem-4f326df872cb?source=rss-eb8a6e07cf22------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f326df872cb</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[blockchain-development]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[solidity]]></category>
            <category><![CDATA[randomness]]></category>
            <dc:creator><![CDATA[Christian Ruink]]></dc:creator>
            <pubDate>Sun, 22 Apr 2018 01:12:09 GMT</pubDate>
            <atom:updated>2018-05-16T10:15:54.431Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5QIx35bAIqMI5LCV3RvI7w.png" /></figure><p>Not sure when it happened but there a handful of new challenges up on OpenZeppelins CTF game; “T<a href="https://ethernaut.zeppelin.solutions/">he Ethernaut</a>”. It’s a great place to start with smart contract development since all of the challenges are perfectly self contained and based on actual vulnerabilities that have lost plenty of people some ETH.</p><p>Right now, I’m gonna be breaking down the challenge titled: “<a href="https://ethernaut.zeppelin.solutions/level/0xd340de695bbc39e72df800dfde78a20d2ed94035"><strong>Coin Flip</strong></a><strong>”.</strong></p><h3>Let’s make our own luck 🍀</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ebs1DqN57kHr-L6DIyqCvA.png" /><figcaption>The CoinFlip contract</figcaption></figure><blockquote>“This is a coin flipping game where you need to build up your winning streak by guessing the outcome of a coin flip. To complete this level you’ll need to use your psychic abilities to guess the correct outcome 10 times in a row.”</blockquote><p>There’s actually no need to hack this contract! We can just flip 10 times and hope for the 0.5¹⁰ probability of guessing right 10 times in a row. It may take a while but there’s nothing like good hard repetitive work to temper the soul.</p><p>Or we can check what the result is going to be before we commit our guess.</p><p>But before that let’s just give the contract one good read through before we look at the solution.</p><pre>function CoinFlip() public {<br>   consecutiveWins = 0;   <br>}</pre><p>The constructor for this contract doesn’t do much, it just sets up the consecutiveWins counter to 0. It actually doesn’t need to do that since every variable defined but not assigned defaults to its null state (0 for uint), but it’s good for clarity anyway.</p><p>Other notable things in contract storage is the lastHash, we don’t really know what’s that for at this point but it’s worth noting it’s not part of public storage. There’s also the FACTOR a BIG ass number! It certainly looks quite ‘magical’ after some looking up it turns out this number is equal to 2²⁵⁵ (curious 🤔)</p><h3>The Flippening 🐬</h3><p>It looks like most of the thinking has to be done in the direction of the <strong>flip() </strong>function.</p><p>Let’s look at that function signature:</p><pre>function flip(bool _guess) public returns (bool) {...</pre><p>“<em>function where I give a bool and get a bool back</em>”</p><p>Moving on.</p><pre>uint256 blockValue = uint256(block.blockhash(block.number-1));</pre><p>block.number and block.blockhash are a globally available variable and function respectively, here’s what they do:</p><p><em>block.number (uint)</em>: current block number</p><p><em>block.blockhash (function(uint) returns (bytes32))</em>: hash of the given block — only for 256 most recent blocks</p><p>In otherwords, whenever a flip transaction is included in a block we look at the number of the previous block, we use that number to look up that previous block’s hash (which is type bytes32) and we cast that to type uint256.</p><p>How does that look like exactly? Let’s fill in the blanks just to get a notion for it:</p><pre>// Current block number 30010 <br>// Network, Ropsten (This matters, naturally)</pre><pre>1. blockValue = uint256(block.blockhash((30010-1));<br>2. blockValue = uint256(block.blockhash((30009));<br>3. blockValue = uint256( 0xf5e22612a5c856807346a40b329664fb393e6ea0e585bd34cffc9f59a50353bd<br>);<br>4. blockValue = 111216218108639340416231065655650431318691078275559772203362371055421202060221</pre><p>Big number is big. Important to note than casting a bytes32 to uint256 covers the same number space. Any valid uint256 can turn up out of casting bytes32.</p><p>Next up:</p><pre>if (lastHash == blockValue) {revert();}<br>lastHash = blockValue;</pre><p>Ok. So that’s what lastHash is for. If there’s a successful transaction then lastHash is going to be set = to this blockValue which is entirely dependant on the block the transaction is being included on, and the only reasonable way for the blockValue to equal the lastHash value is for there to be multiple transactions to this function in the same block. If that’s the case only the first one will go through, that closes one avenue for us. If it weren’t for this right here we could every block with the same guess 10 times, and get the same BlockValue for every transaction.</p><pre>coinFlip = uint256(uint256(blockValue) / FACTOR);<br>bool side = coinFlip == 1 ? true : false;</pre><p>3 / 4 = 0, in solidity. We round down the result of any division and throw away the remainder. Intuition should tell you that <em>(blockValue / Factor) </em>should be equal to 1 or to 0. And it makes sense! Bringing things down to more managable amounts, let’s treat blockValue as an uint8 and Factor as a uint7.</p><pre>//Maxed out!<br>FACTOR = X 1 1 1 1 1 1 1<br>blockValue = ? ? ? ? ? ? ? </pre><p>The important thing is that for blockValue to be greater than FACTOR it only needs the leftmost bit to be equal to 1, otherwise it will be less than FACTOR (or equal).</p><p>Therefor the result of this division (0 or 1) hinges on the single leftmost bit of the blockvalue, which is, ostensibly, randomly determined. Cool.</p><pre>if (side == _guess){ consecutiveWins++; return true; } <br>else { consecutiveWins = 0; return false; }</pre><p>Finally we compare our pseudo random flip result with the user provided guess and adjust the consecutive wins accordingly. So what about, it? Anyway to PwN this contract jump out to you?</p><p>If you consider the necessity for the lastHash clause another vulnerability should become pretty obvious.</p><h3>The Solution! 🏅</h3><blockquote>Every single transaction in the same block can evaluate the “coinflip” result!!</blockquote><p>So, as it’s usually the case, the best way to hack a smart contract is with another:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wa6Kz1xxcc2t3RuzlKP2Ow.png" /><figcaption>Str8 outta Remix</figcaption></figure><p>Here we instantiate define the interface of the CoinFlip contract and instantiate it using the address of our target contract. Then, just calling the cheat function on our devious dirtyRat contract will evaluate the result of the coinflip and pass the “guess” along to the real CoinFlip contract.</p><p>This is done in a single transaction, so our CoinFlip calculations is obviously going to be the same as in the CoinFlip contract since we will necessarily be doing it in the same block.</p><p>Now all that’s left is to spam the cheat function ten times. 😎</p><h3>One more thing…</h3><p>There’s another equally glaring vulnerability here. Miners. Before a block becomes finalized miners build them up with different transactions and compete between themselves to commit their block to the block chain. This means they can exercise their judgment when building up blocks. A miner, given time could try many different guesses and not commit blocks where he was mistaken.</p><p>This property of Proof of Work based consensus is one of the greatest obstacles to achieving truly random outcomes on the blockchain. Think on that before building a decentralized lotto 🤑</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f326df872cb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/ethernaut-coin-flip-problem-4f326df872cb">Ethernaut Coin Flip problem</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ethernaut King Problem]]></title>
            <link>https://medium.com/coinmonks/ethernaut-king-problem-2ccec1ee4190?source=rss-eb8a6e07cf22------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ccec1ee4190</guid>
            <category><![CDATA[ethernaut]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[king]]></category>
            <category><![CDATA[smart-contracts]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[Christian Ruink]]></dc:creator>
            <pubDate>Wed, 27 Dec 2017 19:54:20 GMT</pubDate>
            <atom:updated>2020-10-16T09:25:59.277Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pnCoyKQaCeBHPN8XOvgIdQ.png" /><figcaption>El eternauta original.</figcaption></figure><p>Back in November <a href="https://medium.com/u/4e5199c3ee0a">Zeppelin Solutions</a> invited everybody to participate in their smart contract CTF competition called “<a href="https://ethernaut.zeppelin.solutions/">The Ethernaut</a>”. It was a great way to start Devcon3! It didn’t take long for devs around the world to crush the initial six challenges.</p><p>Most of these puzzles are simplified implementations of real hacks that have occurred in Ethereum’s rocky history. They’re a great entry point for anyone getting started with secure smart contract development and a good site to revisit since the OZ team keeps adding new challenges!</p><p>So, here’s a little write-up on the latest addition (currently) #6 <strong>King.</strong></p><p>If you don’t want to be <strong>spoiled</strong> please stop reading and give it a shot: <a href="https://ethernaut.zeppelin.solutions/level/0x32d25a51c4690960f1d18fadfa98111f71de5fa7">King</a></p><h3><strong>King of the Hill</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*31oScwdHqJK6xmr7YirLWA.png" /><figcaption>The <strong>King</strong> contract</figcaption></figure><p>The objective of the challenge is to prevent the contract from reclaiming kingship once you submit your instance back. Being that the only way to change the kingship in this contract is through the fallback function we can focus exclusively on that.</p><p>First we definitely want to take the kingship from the contract, to do this in the legit way we just need to send the contract address a transaction with a value that is larger than the current prize (1 ETH)</p><p>We can take it easily enough, now the tricky part is retaining when the contract ends up calling the fallback function again. So let’s go line by line and see what we can come up with.</p><pre>require(msg.value &gt;= prize || msg.sender == owner);</pre><p>This looks promising. Put another way the <a href="http://solidity.readthedocs.io/en/develop/contracts.html#fallback-function">fallback function</a> will fail if the msg.value is smaller than the current prize <strong>AND </strong>the message sender is not the owner.</p><p>It’s worth taking a look at <a href="https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/ownership/Ownable.sol">Ownable.sol</a> to see what we’re dealing with. Here I was reminded of the infamous November 2017 Parity Multi-sig wallet hacks, where an alleged beginner locked out over 150 million dollars worth of ETH in hilarious deadpan.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XoXvLzkNZYeFVMEjmmFVQA.png" /><figcaption>Not even the biggest news from that week</figcaption></figure><p>In that instance the “hacker” gained ownership of an uninitialized library that all individual Parity wallet instances utilized. With his new privilege we crashed the library with no survivors.</p><h3><strong>Perhaps we could do the same?</strong></h3><p>Revisiting :</p><pre>require(msg.value &gt;= prize || msg.sender == owner);</pre><p>If we could take ownership of the contract and replace the prize with a value beyond the balance of the current owner we could lock the game out and RULE forever. But we can’t. This case is not like the parity hack, Ownable.sol is pretty solid and there is no way to co-opt such a simple implementation of the contract.</p><p>If we accept that as the reality there is no reason to waste more time in this juicy require, since as long as we can’t take ownership of the contract it will always pass. We can safely move along…</p><pre>king.transfer(msg.value);</pre><p>Good old <strong>PUSH </strong>transactions, without exception handling. Always a treasure trove of issues. This line gets the current king paid right before he’s ousted. There are a ton of ways for transactions to fail, <em>in general</em> now we just need one that suits our needs.</p><ol><li><strong>Out of gas errors. </strong>We’re not making the call here so this is not really something we can control.</li><li><strong>Arbitrary Error from Fallback Function (FF). </strong>If our transaction ends up executing code from a contract that can always fail in some contrived way. That could work. But we can keep it simpler</li><li><strong>Transact with Contract with no FF/ non payable FF. </strong>DING DING DING. As per the docs, when a transaction is made towards a contract address without including any data the fallback function of that contract is called. If a contract doesn’t have one we FAIL, or if we’re including some ETH in the transaction and the fallback function lacks the payable modifier we also FAIL! Hurray!</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NWEstktoG_OcUrOEui8Pdw.png" /></figure><p>We can take the Kingship by proxy with our own contract. Then when the contract attempts to depose us the value transfer will fail. Success!! (We’ll be down 1 ETH for life so this is really a “Let the world burn” kind of hack)</p><h3><strong>Wrapping up</strong></h3><p>This one wasn’t so tricky. When you <strong>KNOW </strong>there is a vulnerability it is relatively simple to go line by line through contract code, until you find a weak spot. But that’s only if you <strong>KNOW.</strong> It’s very hard to apply the same discipline to code you think might be working fine. The hacks will keep piling up, make sure your code is not responsible and be through with your auditing. :P</p><blockquote><a href="https://coincodecap.com/?utm_source=coinmonks">Get Best Software Deals Directly In Your Inbox</a></blockquote><figure><a href="https://coincodecap.com/?utm_source=coinmonks"><img alt="" src="https://cdn-images-1.medium.com/max/584/0*OJ-qb5G6i863msBB.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ccec1ee4190" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coinmonks/ethernaut-king-problem-2ccec1ee4190">Ethernaut King Problem</a> was originally published in <a href="https://medium.com/coinmonks">Coinmonks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>