<?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 Tudor Malene on Medium]]></title>
        <description><![CDATA[Stories by Tudor Malene on Medium]]></description>
        <link>https://medium.com/@tudor.malene?source=rss-960132f36c3d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wOLWqDzoGAgmuRAMuJWJ_g.jpeg</url>
            <title>Stories by Tudor Malene on Medium</title>
            <link>https://medium.com/@tudor.malene?source=rss-960132f36c3d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 05:45:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tudor.malene/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[Why “predict the next word” shouldn’t work this well (but does)]]></title>
            <link>https://medium.com/@tudor.malene/why-predict-the-next-word-shouldnt-work-this-well-but-does-d0333a7a4121?source=rss-960132f36c3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0333a7a4121</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[reinforcement-learning]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Tudor Malene]]></dc:creator>
            <pubDate>Mon, 30 Mar 2026 10:03:25 GMT</pubDate>
            <atom:updated>2026-03-30T10:03:25.766Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O4-K4WffP3GuH3Pfg7ttuw.png" /></figure><p>LLMs are still just predicting the next word.</p><p>Two years ago, that was reason enough to dismiss them — it explained their awkward output. Then they got dramatically better, and scale alone doesn’t explain why.</p><p><em>If you’re new to LLMs, you should watch Karpathy’s </em><a href="https://www.youtube.com/watch?v=7xTGNNLPyMI"><em>“Deep Dive into LLMs” </em></a><em>and read Lee &amp; Trott’s </em><a href="https://www.understandingai.org/p/large-language-models-explained-with"><em>“LLMs Explained with a Minimum of Math and Jargon”</em></a><em>.</em></p><h3>The 2024 mental model of LLMs</h3><p>You probably already know LLMs are stateless <a href="https://poloclub.github.io/transformer-explainer/">next-token predictors</a> trained on lots of text that store information in a weird compressed form.</p><p>Internally, it’s a very complex pattern-matching machine that produces tokens.</p><p>If you asked ChatGPT in 2024:</p><blockquote>Q: Is it cheaper to fly from London to Barcelona or take the train next Friday?</blockquote><p>It would give you a mostly useless answer:</p><blockquote>A: Flying is generally cheaper than taking the train for this route.</blockquote><blockquote>Budget airlines like Ryanair and easyJet often offer flights from London to Barcelona for around £30–£80 if booked in advance. The flight takes about 2 hours.</blockquote><blockquote>By contrast, taking the train usually involves a Eurostar from London to Paris, followed by a high-speed train to Barcelona. This can cost between £120–£200 and takes around 10–12 hours in total.</blockquote><blockquote>So flying is likely the cheaper and faster option, while the train may be more comfortable and environmentally friendly.</blockquote><p>Even though nothing fundamental changed since 2024, we’ll see that the 2026 answer is in a completely different league.</p><h3>Models learning to say “I don’t know”</h3><p>In 2024, one of the most frustrating things about LLMs was that they’d confidently hallucinate.</p><p><strong><em>The simple solution was to teach models to say “I don’t know” — and then give them something to do about it. </em></strong>(This sounds pretty obvious in hindsight)</p><p>They’re trained to recognise patterns that signal uncertainty — like being asked for real-time data — and respond with a refusal. Like this:</p><blockquote>Q: What is the weather in Paris?<br>A: Sorry, I don’t have access to live weather data. You could check weather.com.</blockquote><p>Models are taught humility by example.</p><p><strong><em>This turns out to achieve much more than just not being annoying. Once a model can recognise when it lacks information, it can also learn to do something about it.</em></strong></p><h4>Asking for data (tool use)</h4><p>Instead of refusing, models can be trained to ask for help — by generating a <a href="https://docs.anthropic.com/en/docs/build-with-claude/tool-use/overview">tool call</a> that the system intercepts, executes, and feeds back as context.</p><p>Going back to our weather example. You ask:</p><blockquote>Q: What is the weather in Paris?<br>→ [TOOL_CALL: web_search(“weather Paris”)]<br>→ (result injected into context)<br>A: It’s currently 18°C and partly cloudy in Paris.</blockquote><p>From the user’s perspective, this is all behind the scenes. After you ask a question, you might see a <em>“Searching the web…”</em> indicator, and you get your answer.</p><p>But from the model’s perspective, nothing fundamental changed. It’s still just generating tokens. The trick is that the environment now <em>reacts</em> to certain tokens by fetching real data.</p><p>Instead of relying on its internal compressed knowledge (which is frozen at training time), the model has access to the entire internet, proprietary databases, or any API linked to the system. If it needs to perform some calculations, it can just write a small Python program and ask the host to execute it.</p><h3>Reasoning</h3><p>In 2024, models typically generated answers in a single pass.</p><p>But that’s not required. The human brains that produced the training data don’t work that way. We think through problems, challenge our assumptions, and sometimes spend years on a question.</p><p>The first hint that LLMs could do something similar came in 2022, when researchers showed that simply prompting a model to ‘think step by step’ improved its performance on reasoning tasks. This technique is called <em>“</em><a href="https://arxiv.org/abs/2201.11903"><em>chain-of-thought prompting</em></a><em>”, </em>but the model is still working alone — nobody’s checking its steps<em>.</em></p><h4>Automating thinking</h4><p>For this technique to become useful for real-life research problems, the human can ask <em>“think step by step and ask for feedback after every step,”</em> and then guide the conversation towards the desired result.</p><p>The obvious next step is to remove the human from the loop. Instead of the user guiding the model step by step, another model does it — or the same model plays both roles, challenging its own answers.</p><p>This could work. But something more interesting happened when researchers used “<a href="https://www.understandingai.org/p/reinforcement-learning-explained">Reinforcement Learning</a>”(RL).</p><h3>Reinforcement learning</h3><p>A base model (after pretraining) is given a bunch of tasks, run in a loop. Each time, it responds differently, and each response is evaluated. Over many iterations, through trial and error, the model gets better at producing responses that score well, because those get reinforced in the weights.</p><p><strong><em>This means the model’s internal pattern matching becomes more precise — the next time it encounters a similar problem, the processes that led to the correct answer activate more strongly, making the model more likely to follow that successful approach.</em></strong></p><p><strong><em>The raw information was already there in the base model. RL only makes it overwhelmingly more likely for the model to use it properly. It uses computation to improve the structure; it injects meta-information into the system</em></strong>.</p><p>This is the first way to trade computation for intelligence.</p><p><em>Note: Early LLMs used RL with human raters judging which responses were ‘better’ (</em><a href="https://arxiv.org/abs/2203.02155"><em>RLHF</em></a><em>). This made models polite but was subjective and expensive. The real breakthrough was </em><a href="https://arxiv.org/abs/2501.12948"><em>RLVR</em></a><em> — reinforcement learning with verifiable rewards, using tasks such as maths and code, where correctness can be checked automatically. This scales because </em><a href="https://www.nature.com/articles/s41586-025-09422-z"><em>verification is much easier than solving</em></a><em>.</em></p><h3>Native LLM Reasoning</h3><p>After RL with Verifiable Rewards(RLVR), something unexpected happened: <a href="https://magazine.sebastianraschka.com/p/the-state-of-llm-reasoning-model-training">models started producing reasoning-like s</a>teps. Nobody told them to break problems into steps — the weights shifted that way because methodical approaches produce more correct answers.</p><p>Remember the idea of two models challenging each other? This is that, but happening inside a single model during a single response.</p><p><strong><em>When the generated text looks like a complicated problem, the model writes ‘Let me break this down.’ When it finishes a sub-problem, it writes ‘Let me double-check.’ When it hits a dead end: ‘This doesn’t look right, let me reconsider.’</em></strong></p><p>This is far stronger than prompted chain-of-thought, because the model has learned to recognise patterns of difficulty that no prompt engineer would think to list.</p><p><strong><em>RL is a result-oriented process. Reasoning was an outcome.</em></strong></p><h3>Inference-Time Compute and Reasoning</h3><p>Once a model has learned to reason through RL, you can make it smarter in a surprisingly simple way: <a href="https://openai.com/index/learning-to-reason-with-llms/"><strong>let it think longer</strong></a>.</p><p>At <a href="https://www.gmicloud.ai/blog/inference-time-compute">inference</a> — the moment you actually ask the question — the model can generate more tokens, explore alternatives, and backtrack before committing to an answer. Without the RL training, more tokens would most likely be noise, but with training, the model favours patterns associated with productive thinking.</p><p>LLM Reasoning is searching over possible solution paths, guided by learned heuristics.</p><p>This is the second form of the trade. Intelligence is no longer just what’s baked into the weights during training — it’s also how much computation you’re willing to spend at the moment you ask the question.</p><h3>When it all comes together</h3><p>These capabilities work well together. A model that can reason <strong>and</strong> use tools is fundamentally different from one that can do either alone.</p><p>Let’s go back to the question from the start:</p><blockquote><em>Q: Is it cheaper to fly from London to Barcelona or take the train, if I’m travelling next Friday?</em></blockquote><p>We saw the kind of useless answer the 2024 model would give us.</p><p>A model with tool use alone might search the web and return some results, but struggle to compare them sensibly. A model with reasoning alone might lay out a brilliant analytical framework with made-up numbers.</p><p><strong><em>But a model with both capabilities can reason about what data it needs, make multiple tool calls to look up flight and train prices, write a small program to compare the options accounting for factors like travel time and airport transfers, get the result from the program, recognise when a search result looks outdated, try again — and then present you with a well-reasoned answer grounded in real data.</em></strong></p><p><strong><em>The reasoning drives the tool use, and the tool use grounds the reasoning.</em></strong></p><h3>Conclusion</h3><p>LLMs are still just predicting the next word.</p><p>But you can teach a next-word predictor to admit what it doesn’t know. You can give it access to tools. You can train it to pause and think before answering, or to challenge its own conclusions.</p><p>The result is genuinely useful in practice — even though models still hallucinate sometimes, overthink and overengineer, and get stuck in loops - and the jump from 2024 is enormous.</p><p>That’s the part I didn’t see coming.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0333a7a4121" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing Smart Transparency]]></title>
            <link>https://medium.com/obscuro-labs/web3-needs-access-control-9a80719eec4a?source=rss-960132f36c3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a80719eec4a</guid>
            <category><![CDATA[crypto]]></category>
            <category><![CDATA[web3]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[solidity]]></category>
            <dc:creator><![CDATA[Tudor Malene]]></dc:creator>
            <pubDate>Mon, 16 Sep 2024 16:17:33 GMT</pubDate>
            <atom:updated>2024-09-18T14:59:59.649Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iSvdJv_p5nnGApfhNJCX9g.jpeg" /><figcaption>DALL-E</figcaption></figure><p>Have you ever wondered why, after ten years of massive investments, there are still no decentralized alternatives to mainstream applications?</p><p>I have been in the Blockchain space for a long time and can tell you that it’s not for lack of trying…</p><p>The answer is obvious and has been staring us in the face all this time, yet nobody has been able to pin it down.</p><p>Until now.</p><h3>Access control — the foundation of the Internet</h3><p>If we examine any successful application closely, we will realize it cannot function without restricting access to data.</p><p>Some are obvious, like email, messaging applications, bank accounts, private and shared documents, photos, notes, Amazon purchases, etc. But it goes much, much deeper.</p><p>When you watch Netflix or Amazon Prime, you can only access content included in your subscription or that you purchased. Even though the latest blockbuster is available on the platform, you can’t access it.</p><p>On Spotify, only paid subscribers can choose any song they want, so the entire business model would collapse without data restrictions.</p><p>When you play any mobile (or online) game, some information is inaccessible to your opponents, such as the map you have discovered already, your position on the battlefield, your weapons, or your armour.</p><p>On WhatsApp, when you “share location” with a friend, nobody else will see where you are.</p><p>A Revolut “Joint Account” will notify all owners when a purchase is made, but not anyone else.</p><p>Even traditional passwords or biometrics can only exist with access control.</p><p>Except for Wikipedia, if you analyse any application you use daily, I guarantee it wouldn’t work without access control.</p><h4>“Access Control” &gt; “Privacy”</h4><p>You should realise by now that “Access Control” is much broader than “Privacy”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*Xvllx7gMC_--CDNNWcQs-g.jpeg" /><figcaption><a href="https://imgflip.com/memegenerator">https://imgflip.com/memegenerator</a></figcaption></figure><p>It’s one thing to keep what you watch on Netflix private from your friends, but Netflix itself would not exist if anyone could watch any movie without paying a subscription.</p><p><strong><em>Privacy is desirable and valuable, but, in the grand scheme, it represents a tiny niche, a rounding error. Almost nothing is possible without “Access Control”.</em></strong></p><h3>Yet, there is no access control on the blockchain</h3><p>All the data is fully transparent. Everyone in the world can read everything.</p><p>Open any blockchain explorer, and you can inspect every single piece of data or transaction that has ever been executed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2tYf9rLZihdOAuGyb9tzZg.png" /><figcaption>Twitter</figcaption></figure><p><strong><em>It’s evident that, without access control, Web3 cannot progress beyond a cute experiment with decentralization.</em></strong></p><p>What can we do about it?</p><h3>Smart Transparency</h3><p>Ten years ago, Ethereum introduced “Smart Contracts” and showed how business logic can be transparent, decentralized, auditable, immutable and unstoppable.</p><p>To fix the “Data Access” problem, we’re introducing “Smart Transparency”.</p><p><strong><em>In addition to controlling who can make transactions and how to execute them, the “Smart Contracts” will also be able to control access to data.</em></strong></p><p>In practice, any smart contract has “View Functions,” which return information such as a balance or an NFT. Any Solidity developer will quickly grasp that adding this line of code should prevent anyone but the data owner from successfully calling the view function.</p><blockquote>require(tx.origin == owner, “Access denied”)</blockquote><p>However, the same developer will explain that this control can easily be bypassed and can’t achieve anything besides being a slight annoyance.</p><p><strong><em>Smart Transparency can only be achieved when this check can no longer be bypassed, and all data and computation are encrypted.</em></strong></p><h3>Conclusion</h3><p>The Web3 space is known for radical transparency. While this has been useful as a starting point, any founder will tell you how much they struggle to build truly useful applications. The reason is not that they desire “privacy” but that they can’t implement “access control.”</p><p>“Smart Transparency” is the technology that will power the next generation of “Smart Contracts”.</p><h3>Find out more</h3><p>If you’re interested in learning more about <a href="https://www.ten.xyz/">what we’re building</a>, check out our other blog posts <a href="https://medium.com/obscuro-labs">here</a> or dive into our <a href="https://whitepaper.ten.xyz/">whitepaper</a>. Join the community on <a href="http://discord.gg/tenprotocol">Discord</a> and follow us on <a href="https://www.x.com/tenprotocol">Twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a80719eec4a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/obscuro-labs/web3-needs-access-control-9a80719eec4a">Introducing Smart Transparency</a> was originally published in <a href="https://medium.com/obscuro-labs">TEN Protocol — Privacy on Ethereum</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Account Abstraction Demystified]]></title>
            <link>https://medium.com/obscuro-labs/account-abstraction-demystified-2e85bde4c54d?source=rss-960132f36c3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e85bde4c54d</guid>
            <category><![CDATA[account-abstraction]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[eip-4337]]></category>
            <dc:creator><![CDATA[Tudor Malene]]></dc:creator>
            <pubDate>Fri, 23 Aug 2024 09:56:14 GMT</pubDate>
            <atom:updated>2026-03-30T08:15:20.484Z</atom:updated>
            <content:encoded><![CDATA[<p>Since you clicked on this article, you have likely been on a quest to understand Account Abstraction (EIP-4337). By now, you’re familiar with its <a href="https://www.starknet.io/blog/account-abstraction/">advantages</a> and the <a href="https://www.youtube.com/watch?v=FjK5rYznJjU">five roles</a>, and you’ve probably read <a href="https://medium.com/infinitism/erc-4337-account-abstraction-without-ethereum-protocol-changes-d75c9d94dc4a">Vitalik&#39;s posts</a>. While it all sounds great in theory, you might be feeling confused about how it solves the big UX problems of Web3.</p><p>The main thing to understand is that Account Abstraction(AA) was not created to solve a particular problem but as an exercise to separate transaction verification from execution. In other words, the requirement was to generalise signature verification, hoping the extra flexibility would unlock the creation of better wallets.</p><p>On the other hand, outside the protocol developer circles, everyone expects AA to be the miracle solution that will help onboard the next billion users to Web3. In this article, I will try to bridge this gap.</p><h4>The Web3 Challenge — User Experience</h4><p>The elephant in the room for Web3 adoption is most likely UX: the seed phrases, the unforgiving security, the clicks and the transparency.</p><p>It is not surprising, then, that AA is expected to help developers solve many of these problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*thfO6oAc8daF6CiUcPIsAQ.jpeg" /><figcaption>imgflip.com</figcaption></figure><p>The reality is that EIP-4337 is a standard that can be applied top-of-stack (like ERC-20). It encourages reusable tooling and, possibly, easier solution composition. It does not enable anything that wasn’t possible before.</p><p><strong><em>Any breakthroughs resulting from its widespread adoption will most likely be from various unexpected combinations of solutions and not from a new feature.</em></strong></p><p>This article will discuss UX improvements that seem like a natural fit for AA.</p><h3>The on-chain game</h3><p>All games need a smooth user experience, and having to click a few times in a different window for every move is pretty far from that. The issue is that Ethereum and compatible chains require that every transaction is signed by an &quot;externally owned account&quot; (EOA), and the wallets that control the keys are external to the game.</p><p><strong><em>Our task is to design a secure, decentralised solution for executing the game moves on-chain in real-time without the user having to click to sign each one.</em></strong></p><h4>The simple solution — Session Keys managed by the game</h4><p>The straightforward solution is for the game engine running in the browser or the phone (GE) to generate a volatile key pair behind the scenes and ask the user to transfer some ETH from their main account to this volatile account. We can think about this key pair as a session key (SK) with an on-chain balance.</p><p>While playing, the game engine generates a transaction for every move, signs it with the SK behind the scenes, and submits it to the network.</p><p>When the game ends, the GE will transfer the remaining balance and the winnings to the main account.</p><p>This is a reasonable solution, especially if the game runs on a cheap L2 and the amounts involved are fractions of a dollar. The main disadvantage is that the SK can disappear if the browser crashes, and the ETH it controls can be lost.</p><p>To summarise the User Experience: Alice visits an on-chain game website and registers to play by connecting her wallet and signing a transaction that transfers a small amount of ETH from her account to prepay for moves. Then, she can play the game and make moves as in any Web2 game.</p><h4>Applying EIP-4337</h4><p>In this section, we&#39;ll achieve the same functionality but fix the minor issue of potentially lost funds. You&#39;ll notice how the complexity increases.</p><p>In a nutshell, we keep the Session Key approach but no longer transfer funds to it. The funds and the public key will be submitted to a smart contract. The game moves will not be standalone transactions. Instead, they will be payloads signed with the SK. In EIP-4337 terminology, they will be &quot;User Operations&quot; (UO).</p><p>Since we no longer have transactions but still need to execute the moves on-chain in real-time, we need a &quot;Bundler&quot; to create, submit, and pay for the transactions containing the UOs.</p><p>On-chain, we&#39;ll have three smart contracts: the &quot;Entry point,&quot; the &quot;Smart Wallet,&quot; and the actual &quot;Game Smart Contract.&quot;</p><p>The &quot;Entry Point&quot; is the contract called by the bundler, which unpacks the UOs and authenticates them with the &quot;Smart Wallet.&quot; The &quot;Smart Wallet&quot; can do that because it has the SK&#39;s public key. Afterwards, it submits them to the game for execution. The last step is for the Bundler to reclaim the money it has spent on this UO from the Smart Wallet.</p><p>Assuming all this infrastructure, like the Bundler, Javascript SDKs for UOs, code for the &quot;Entry Point,&quot; and the &quot;Smart Wallet,&quot; already exists, it makes sense for a game developer to use the EIP-4377 standard, as their effort will be similar to the &quot;Simple solution&quot;.</p><p>An extra benefit of the EIP-4377 infrastructure is that the game can now employ a &quot;Paymaster,&quot; another intermediary who can offer to pay for the moves on behalf of the user. This could improve the UX and onboarding of new users and unlock freemium models.</p><p>The User experience is identical to that described in the &quot;Simple solution,&quot; with the difference that even if the browser crashes, the prepaid amount is not lost. Note that using the standard allows for much faster integrations with compatible paymasters.</p><h3>Social Recovery</h3><p>It&#39;s well known that Web3 projects constantly struggle to strike a good balance between usability and security. All solutions, from seed phrases to hardware wallets, trade one for the other. This has been a constant challenge since the early days of Bitcoin.</p><p>Centralised providers, like Apple, <a href="https://medium.com/p/59cd09687d53">give users an excellent user experience with high security</a> because they position themselves at the root of trust and combine many technologies.</p><p>Achieving a similar outcome in a decentralised setup is still a dream, but we can start with the basics.</p><p>The idea behind &quot;Social Recovery Wallets&quot; is to give users a &quot;Forgot Password&quot; recourse. This feature adds a third dimension to the security-balance tradeoff. The user can employ a high-security solution, like a hardware wallet, for everyday operations and still have a way to recover the account in the exceptional situation where she loses the device.</p><p>In the spirit of decentralisation, the role of recoverers is entrusted to &quot;guardians&quot;, who are selected by the user. They can be friends, family, commercial services, or other devices they own. It is critical that no guardian has any power over the assets.</p><p>The implementation is straightforward. The funds are controlled by a &quot;Smart Contract Wallet&quot; (SCW), which will encode all the necessary rules.</p><p>For example:</p><ul><li>KeyA can spend money freely. Where KeyA is the user&#39;s main EOA.</li><li>Any two of KeyB, KeyC and KeyD (the appointed guardians) can replace KeyA for KeyE. Where KeyE is the new key generated by our user.</li></ul><p>With this setup, the user can use KeyA for day-to-day operations but still access a “recovery” mode. This model is superior to a plain “Multi-key” because the guardians are almost never involved.</p><p>Note that KeyA must have some native balance to pay for transactions, but the SCW controls the bulk of the assets.</p><p>Also, note that we haven&#39;t used Account Abstraction for this solution yet, but we have achieved our goal.</p><p>After updating our SCW to be EIP-4377 compatible, all interactions with it will be &quot;User Operations&quot; paid from the balance of the contract. This is a clear improvement, as the user does not need to hold any balance on the EOA, but it does not change the fundamental behaviour.</p><h3>Multi Calls</h3><p>For years, services like Furucombo have allowed users to perform complex arbitrages involving Flash Loans.</p><p>You can start with a flash loan on Aave in CoinA, then buy CoinB on Uniswap, sell it for CoinC on DyDx, then repurchase CoinA on Uniswap, and finally pay back the loan and pocket a small profit.</p><p>All these operations must happen atomically for many reasons, but mainly because the FlashLoan must be paid back in the same invocation.</p><p>There are multiple ways to implement this pattern.</p><p>One option is to write a smart contract that does all this by calling the &quot;lend&quot; and &quot;swap&quot; functions of Aave, Uniswap and DyDx. Services such as Furucombo can generate the code based on the user instructions.</p><p>The code is then deployed to the chain and will execute the arbitrage logic in the constructor. There are some gas inefficiencies, but this is a very flexible solution.</p><p>Another approach is to deploy a general-purpose smart contract that interprets and executes a list of instructions. For example, <em>&quot;Lend 100,000 CoinA from Aaave&quot;</em> — would be the first instruction.</p><p>This is a pretty straightforward &quot;Multi-Call,&quot; and as you can see, it works quite well. This pattern has been used for many years without any standard.</p><p>EIP-4377 fits quite naturally for this problem. The Smart contract is the &quot;Entry Point,&quot; and the instructions are the User Operations.</p><p>Objectively speaking, other than being compatible with a standard, the functional benefits are unclear.</p><h3>Conclusion</h3><p>Account Abstraction (EIP-4377) is hailed as groundbreaking, and the expectations for its impact are sky-high. It is believed that it will solve the UX problems which plague Web3 and hold it back from mainstream adoption.</p><p>However, the reality is more nuanced. Like any standard, the best it can hope to achieve is helping combine existing solutions in unforeseen ways or speeding up new ideas with compatible tooling.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e85bde4c54d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/obscuro-labs/account-abstraction-demystified-2e85bde4c54d">Account Abstraction Demystified</a> was originally published in <a href="https://medium.com/obscuro-labs">TEN Protocol — Privacy on Ethereum</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TEN Introduces Confidential Smart Contracts]]></title>
            <link>https://medium.com/obscuro-labs/encrypting-ethereum-ten-network-introduces-private-smart-contracts-fc71f5949ef6?source=rss-960132f36c3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc71f5949ef6</guid>
            <category><![CDATA[sgx]]></category>
            <category><![CDATA[ethereum]]></category>
            <category><![CDATA[tesnet]]></category>
            <category><![CDATA[layer-2]]></category>
            <dc:creator><![CDATA[Tudor Malene]]></dc:creator>
            <pubDate>Wed, 13 Dec 2023 09:54:46 GMT</pubDate>
            <atom:updated>2025-06-19T08:58:22.955Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vv4sW3ac_bcocjJO8L9hBw.png" /><figcaption>The journey from Bitcoin to Ethereum, to Ten. (Midjourney)</figcaption></figure><p>Two years ago, we embarked on an epic journey to design and build the first Ethereum Layer 2 that goes beyond scalability and introduces EVM <strong>smart contracts with private shared state.</strong></p><p>Today, we&#39;re happy to announce that we hit the first significant milestone, the release of our public Testnet that rolls up to the Ethereum-Sepolia Testnet.</p><p><strong>Smart contracts written for Ethereum will have secrets and free secure randomness for the first time. </strong>Even more remarkable is that developers won&#39;t need to learn anything new to harness these capabilities<strong>.</strong></p><p>This is a big deal because decentralized Ethereum dApps can finally compete in functionality, speed, and cost with their web2 counterparts!</p><h3>First step: Full Data Transparency</h3><p>Blockchain data has always been transparent.</p><p>This was never the explicit goal but a design tradeoff to achieve decentralization. The key property has always been “correctness transparency.” In the Bitcoin whitepaper, Satoshi hoped privacy could be achieved by keeping addresses anonymous.</p><p>A few years later, Ethereum introduced smart contracts with shared state, a feature that unlocked the building of DeFi primitives like decentralized exchanges and lending protocols.</p><p>This massive step forward magnified the importance of the data transparency tradeoff. <strong>It showed that your options are somewhat limited even though you can now build apps with complex functionality that can interoperate on a decentralized platform.</strong> To make it worse, transparency exposes users to predatory practices like sandwich trading.</p><p>This might seem like a surprising statement because Ethereum is extremely successful. But, if you don&#39;t believe me, let&#39;s consider for a minute what it takes to build the on-chain version of a simple card game like Poker. You&#39;ll quickly find that you can&#39;t hide the players&#39; cards since contracts have no secrets.</p><p><strong>Data confidentiality is required by all commercial applications ever built for a good reason.</strong></p><h3>Ten: Removing Data Transparency</h3><p><strong>With the release of the Ten Testnet, the next major innovation in blockchain design has finally arrived.</strong></p><p>Regular web2 applications keep secrets using business logic and physical security (only authorized people can access the physical machines). Replicating this feature on a decentralized architecture requires data encryption during storage, transit, and processing. The trickiest challenge is the latter because it implies keeping the execution hidden even from infrastructure operators.</p><p>Ten uses secure enclaves, cryptography, and cryptoeconomic incentives to achieve all the necessary properties.</p><p>Our approach is to keep the internal state (private variables) of Ten EVM contracts secret by default, the same as the data in any web2 application. It is a matter of smart contract business logic (plain Solidity code) to allow access to information.</p><h3>User and Developer experience</h3><p>We recognize that a new platform with an unfamiliar programming model can face significant adoption challenges, which brings us to another achievement we are immensely proud of. <strong><em>We implemented default data privacy without any EVM or Ethereum RPC interface changes</em></strong>.</p><p><strong>As a </strong><a href="https://docs.ten.xyz/docs/introduction/developer-quickstart"><strong>developer</strong></a><strong>, you don&#39;t have to learn any new language and can continue using all your favorite Ethereum tools. DApps written for Ethereum will just work on Ten.</strong></p><p>More importantly, you don&#39;t have to worry about your users&#39; experience because that is also unchanged.</p><h3>Call to arms</h3><p>The Ten Testnet is open!</p><p>Come and check it out. Deploying dApps will be rewarded as this is an incentivized testnet. The Ten team will help you with every step from conception to production on Mainnet.</p><p>If you are a partner or a developer ready to hack, check out our <a href="https://docs.ten.xyz/">documentation</a>. If you don&#39;t have an immediate idea, you can fork any Ethereum dApp, deploy it, and interact with it.</p><p>If you don&#39;t have time to write a cool dApp yet, check our test application: &quot;<a href="http://guessing.fun/">The Guessing Game</a>,&quot; to experience how onboarding onto Ten is just 3-clicks.</p><p>Not a developer? No worries! Explore exciting ways to join the Ten Testnet through our <a href="https://galxe.com/ten/campaign/GCaCBtUXyk">Galxe Campaign</a>.</p><p>If you need help getting started or want to stay in touch, join our <a href="https://discord.com/invite/7pkKv2Tyfn">Discord</a>.</p><p><em>Note: We recently renamed the protocol from Obscuro to Ten, so you will see both names. At the time of this blog, the renaming is still in progress.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc71f5949ef6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/obscuro-labs/encrypting-ethereum-ten-network-introduces-private-smart-contracts-fc71f5949ef6">TEN Introduces Confidential Smart Contracts</a> was originally published in <a href="https://medium.com/obscuro-labs">TEN Protocol — Privacy on Ethereum</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying SGX part 4— Secure hardware]]></title>
            <link>https://medium.com/@tudor.malene/demystifying-sgx-part-4-secure-hardware-59cd09687d53?source=rss-960132f36c3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/59cd09687d53</guid>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[sgx]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[drm]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Tudor Malene]]></dc:creator>
            <pubDate>Fri, 13 Oct 2023 15:54:15 GMT</pubDate>
            <atom:updated>2026-03-30T08:15:53.738Z</atom:updated>
            <content:encoded><![CDATA[<h3>Demystifying SGX — Part 4— Secure hardware</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*eBgwbjDSxn6CIz9IlREUTw.jpeg" /><figcaption>Secure hardware everywhere</figcaption></figure><p>Secure hardware is all around us, quietly working behind the scenes to protect our digital lives.</p><p>Your laptop, phone, smartwatch, car, TV, game console, Blu-Ray player, Chromecast, home cinema system, crypto wallet, data centres, certificate providers, blockchain nodes, the <a href="https://www.coindesk.com/consensus-magazine/2023/07/24/the-untold-story-of-worldcoins-launch-inside-the-orb/">WorldCoin Orb</a>, and even your PC monitor are all powered by secure hardware. If you look deep enough, you will find it in every device you use.</p><p>In this fourth instalment of the <a href="https://medium.com/obscuro-labs/intel-sgx-demystified-757a242682a3">“Demystifying SGX” series</a>, we’ll focus on everyone’s favourite activities: messing with the iPhone and watching Netflix.</p><h3>iPhone Data Protection</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*7fb2kdRjvlF0G4j2aZyeBQ.png" /><figcaption>Apple security</figcaption></figure><p>In the modern era, smartphones are treasure troves of sensitive information, housing everything from credit card details and passwords to emails, private conversations, documents, and private photos. However, these devices are also susceptible to loss or theft, posing a significant challenge in safeguarding the data they contain. This concern becomes even more pronounced when considering business phones, which often hold closely guarded corporate secrets.</p><p>Early iPhones, until the third generation, had almost no protection. For instance, a thief could remove the storage card, transfer it to another device, and gain unrestricted access to all its contents, including sensitive passwords.</p><p>To mitigate this vulnerability, Apple implemented measures designed to deter non-sophisticated thieves. One such measure involved automatically wiping the data after ten unsuccessful attempts at entering the PIN.</p><p>While this feature offered a degree of protection, it was clear that a more comprehensive solution was urgently needed.</p><h4>Adding encryption</h4><p>In the quest for data security on our devices, it’s tempting to think that encrypting all data with a key derived from the PIN, known only to the user, is a foolproof solution. However, as we’ll explore in this section, this simple approach has significant limitations.</p><p>The fundamental flaw with using a four or six-digit PIN as the sole encryption key is the lack of entropy, which leaves the data vulnerable to attackers armed with modern computing power.</p><p>Requiring users to enter a complex password every time they unlock their device could solve the problem, but it is impractical and burdensome.</p><p>Another critical drawback is that all data is lost if the user forgets the PIN. <em>Note:</em> <em>The good news is that it can be brute-forced back by a “helpful” service because the entropy was low.</em></p><p>The crux of the issue lies in selecting the “root of trust”. This naive approach places the onus solely on users and, using a crypto term, gives them full custody of the data. However, this model is impractical, leading smartphone manufacturers, including Apple, to embrace a different approach.</p><p>They must shift the root of trust to themselves to give users a good experience.</p><h4>The digital fortress</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*a4dSHBYL-kKHWkxk15HFyw.jpeg" /><figcaption><a href="https://www.historyonthenet.com/medieval-castle">https://www.historyonthenet.com/medieval-castle</a></figcaption></figure><p>Apple has taken on the challenge of securing user data, including from themselves, and ensuring a seamless and convenient user experience.</p><p>Their high-level requirement is that the user can access their phone swiftly while keeping thieves and hackers at bay, even when they have physical possession of the device or attempt to deceive the user with malicious apps. Essentially, they aim to offer a user experience akin to using a familiar website like Facebook, with one crucial difference — the “attack surface” they have to defend is significantly larger when data resides on a device controlled by adversaries.</p><p>So, how does Apple meet these ambitious security goals?</p><p>They do so by transforming parts of the device into a digital fortress that can defend itself offline. The attacker should be unable to access data even when removing the storage, placing measurement devices, or replacing various electronic circuits.</p><p>Apple takes responsibility for the security of the fortress as long as the user keeps it up to date and doesn’t unlock the door.</p><h4>Authentication</h4><p>To satisfy the first requirement, the device must have the means to verify the user’s identity instantly and offline. Therefore, the authentication program is the first line of defence, and it must operate securely because compromising it grants full access to the data.</p><p>A typical program is a collection of files that reside in storage and are loaded and executed as needed. Crafty attackers, if they possess the device, could identify the files, replace them with a corrupted version, and subsequently start the device, bypassing authentication.</p><p>The simplest solution is to embed the program into the CPU, but that’s not feasible because it can’t be upgraded. Instead, a more sophisticated approach involves embedding a public key and a mechanism that allows only programs signed by that key to execute.</p><p>This combination of cryptography and hardware protection forms the first link of trust, allowing Apple to improve the software without risking corruption.</p><h4>Encryption</h4><p>We now have a reliable authentication mechanism, so it’s time to consider data encryption.</p><p>If the key is stored in plaintext, the attacker can find it by scanning the storage. It can’t be encrypted itself because then you face the circular problem of where to store this new key, and so on.</p><p>The solution is to embed it in the CPU, accompanied by a mechanism to hand it over only to the authentication program.</p><p>Conceptually, we need a CPU with some basic logic and two &quot; fused &quot; keys to satisfy our requirements. The first key will protect the authentication program, and the second will be used for encryption.</p><p><em>Note: If you read the first parts of this </em><a href="https://medium.com/p/757a242682a3"><em>series</em></a><em>, you might notice the similarity to Intel SGX.</em></p><p>After reading this simplified high-level overview, you should be equipped to understand how Apple achieved this.</p><h4>The Secure Enclave Processor</h4><p>Apple chose a different approach from Intel. Instead of extending the functionality of the main CPU and transforming it into a Trusted Execution Environment (TEE), as Intel has done with the “<strong>S</strong>oftware <strong>G</strong>uard <strong>eXtensions</strong>”, they opted for introducing a dedicated secure co-processor. The iPhone 5S was the first generation to include it.</p><p>Apple is quite <a href="https://support.apple.com/en-gb/guide/security/sec59b0b31ff/web">open about these security aspects</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*bY9JNwv17-C8w237fPMH4Q.png" /><figcaption><a href="https://support.apple.com/en-gb/guide/security/sec59b0b31ff/web">https://support.apple.com/en-gb/guide/security/sec59b0b31ff/web</a></figcaption></figure><p>As you can see from the description above, the Apple Secure Enclave Processor (SEP) only has security responsibilities. It is fused with keys allowing it to establish a hardware root of trust. In other words, this enables it to boot up through a secure process such that only trusted and approved firmware, kernel (SEPOS), and applications are loaded into it. This is a more elaborate way of describing how only signed programs can execute.</p><p>The SEP also has a unique ID (UID) root cryptographic key “fused” into it. The UID is not known to anyone, including Apple*. They only record a derivate of this UID, which they use to authenticate messages from the phones. The UID is used as entropy to generate the encryption key.</p><p><em>Note*: This guarantee cannot be proven since Apple controls the manufacturing process and the software installed on the SEP.</em></p><p>As you can see, this mechanism satisfies all requirements. The SEP runs only verified programs and performs the authentication and encryption in perfect isolation. Hardware security is used both for establishing a root of trust and achieving isolation.</p><p><em>Note 1: To make a parallel with SGX, the main operating system running on the iPhone and all installed applications are considered “untrusted code”.</em></p><p><em>Note 2: Jailbreaking an iPhone generally means that the root-of-trust checks are bypassed, so one can install and run software not signed by Apple.</em></p><p>It’s useful to drill more into the authentication logic performed on a modern iPhone to understand how important hardware security is to all aspects.</p><h4>Face ID authentication</h4><p>From a high level, a user logs into the phone by typing the PIN, pressing their fingerprint, or looking at the camera.</p><p>For the latter, the authentication logic has to compare the images received from the camera against a biometric template recorded when the user created the account.</p><p>There are many attacks to consider and prevent before such a solution is secure, which is why it took so long to roll out. The first iPhone with this feature was the “iPhone X” in 2017.</p><p>For example, the attacker can attempt to trick the mechanism by pointing the camera to an image of the owner. Apple solves this by taking multiple pictures from slightly different angles and creating depth.</p><p>A more sophisticated attacker who gained access to the phone could hook into the circuits and always send the right sequence of images to create the desired depth. These photos of the victim could be taken on the street. This is solved by introducing hardware security elements in all the related circuits, which must authenticate to each other.</p><p><em>Note that if you drop your iPhone and damage the FaceId circuit, it can’t be replaced without replacing the secure enclave processor, which means losing all data. True story.</em></p><h4>Backups</h4><p>You may be wondering by now how backups work since the phone encrypts the data, and Apple doesn’t have the key. How can they help you restore from backup on a different device if you lose your phone?</p><p>To solve this problem, Apple used even more secure hardware. They created a backend infrastructure based on a complex setup of Hardware Security Modules (HSMs) that operate without human access.</p><p>Each phone is assigned a backup key that multiple HSMs can process with redundancy. The key is pushed to the phone with regular software updates and encrypts the data before uploading it to the cloud.</p><p>The HSMs will only process a backup after the user has proven their identity.</p><p>It is truly secure hardware all the way.</p><h3>Digital rights management (DRM)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3MQJRwmi3BSvKIhEVW_5tw.png" /><figcaption>Netflix logo</figcaption></figure><p>While protecting user data on physical devices like iPhones presents formidable challenges, the stakes escalate when a company endeavours to safeguard its premium content, such as high-quality media, across various user devices.</p><p>“Digital rights management”, while contentious, plays a key role in how we consume media, whether distributed on physical discs or streamed via online platforms like Netflix.</p><p>By the end of this section, you will appreciate that it’s not the technical solution that is controversial but the fact that protecting the consumer ownership of media was not a requirement.</p><h4>The AACS standard</h4><p>The Blu-Ray DRM mechanism, which we’ll analyse below, is defined by a standard called “Advanced Access Content System“, or <a href="https://en.wikipedia.org/wiki/Advanced_Access_Content_System">AACS</a>.</p><p>A movie on a Blu-Ray disc is a collection of files containing high-quality video and audio assets. AACS protects them mainly through encryption but with some elements of proprietary formats, like requiring non-standard disc drives.</p><p>The main requirement is pretty obvious: nobody should be able to “rip” the movie. This means creating unencrypted files with high-quality content that can be downloaded and played using a regular media player. The second requirement is preventing cloning a disc bit by bit.</p><p>There are also more subtle requirements. For example, compromised players must be “revoked” and prevented from doing further damage. All this must be achieved without internet access because users should also consume the content offline.</p><p>As you can imagine, the solution is quite complex, so we’ll only cover it from a high level.</p><h4>Playing Blu-Rays on dedicated players</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*T2ab_6buwCXQqkPlDZv91Q.jpeg" /><figcaption>Generic Blu-Ray player</figcaption></figure><p>The “root of trust” in the AACS scheme is the player itself, which reads the content on the disc, decrypts it and then loads the plaintext media content in its internal memory to decode and play it on the TV. If the owner can open it up and connect cables, they could easily rip the movie.</p><p>As a result, a compliant player has to be built like a fortress, so there is no possibility of extracting anything from it besides the output HDMI cable.</p><p><strong><em>Ultimately, the problem that AACS solves is to ensure that the movies can only be played on compliant players.</em></strong></p><p>Let’s get straight to it.</p><p>Every Blu-Ray disc has a <a href="https://en.wikipedia.org/wiki/Advanced_Access_Content_System#Volume_IDs">Volume ID (VID)</a> serial number burnt in, which can only be written and read with special equipment. This mechanism prevents bit-by-bit copying of a disc with standard equipment or even playing the disc on a device that doesn’t have this feature.</p><p>On top of this protection, the VID is encrypted with a key issued by an AACS authority so that only approved manufacturers can decrypt it.</p><p>The VID is used as the first of the inputs to the decryption.</p><p>This might appear to solve the problem, but it’s not fine-grained enough, so the standard defines a second mechanism.</p><p>When manufactured, each compliant playing device is given a set of secret Device Keys. <strong><em>The media files are encrypted with a complex combination of the device keys of all compliant and non-revoked players.</em></strong></p><p>When a particular device is found to be vulnerable, its device keys are revoked, and no future movie will use that key during encryption, so the compromised device will no longer be able to decrypt any new discs, even if it stays offline.</p><p><em>Note: The compromised device can be detected through complex techniques similar to watermarking.</em></p><h4>Playing a Blu-Ray on a PC</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JTJIbAZCVvroC6in1ad09w.png" /><figcaption>Power DVD software</figcaption></figure><p>A more interesting problem to readers of this series is to consider what it takes to play a Blu-Ray disc on a PC equipped with an AACS-compliant disc drive (one that can read the VID).</p><p>The most pressing problem is the management of the “Device Keys” and the VID decryption key.</p><p>If these keys are included with the installer, even if obfuscated, they can be retrieved by reverse engineering. But even if that doesn’t succeed, the program will eventually load the keys in memory, and thus, they will be accessible from programs running at a higher privilege level. Essentially, any computer user following a simple guide could easily retrieve the secret key and thus get closer to ripping the movie.</p><p>We can see that a pure software implementation of the Media Player is impossible to secure against a competent attacker, so the only solution is to add a hardware component and create a trusted “Virtual Blu-Ray player” running on the untrusted computer.</p><h4>Secure Media Player powered by Intel SGX</h4><p>Since this series is focused on SGX, let’s try to use it to secure our media player application for the PC.</p><p>The first problem is to provision the secure keys. They can’t be shipped encrypted with the installer because the sealing key of each CPU is unique.</p><p>As a result, we must introduce an AACS-approved remote service to check the attestations and then send the secrets sealed for each CPU. This also means the computer has to be online during installation.</p><p>The other SGX features described in the previous articles will allow the program to run in perfect isolation to safely decrypt the content and then send it to the display encrypted with the <a href="https://en.wikipedia.org/wiki/High-bandwidth_Digital_Content_Protection">HDCP</a> standard, another protocol to protect media as it travels through connections.</p><p><em>Note: HDCP is also protected by secure hardware and encryption. The monitor creates a secure connection with the media player program.</em></p><p>There is a perception that by doing this, the movie studios are <em>“running programs on my computer outside of my control”</em>, which is inaccurate since the user chooses to run the media player and hit play on the movie. There is not much difference from a regular Blu-Ray player.</p><p>The alternative to this mechanism is for PCs to no longer be able to play high-quality media at all. This is precisely what <a href="https://www.ghacks.net/2022/01/14/intels-dropping-of-sgx-prevents-ultra-hd-blu-ray-playback-on-pcs/">happened</a> when Intel deprecated SGX for consumer CPUs.</p><h4>DRM Controversies</h4><p>DRM is a controversial technology for a good reason. But it is not the technology itself that is the problem, but the media industry, which doesn’t protect consumers when the encoding formats are deprecated.</p><p>As we’ve seen in the Blu-Ray example, you need to buy a special player or install a program that asks permission to play that content. Imagine the AACS format is deprecated in five years, and your player breaks. Buying a new player might not play the movie, and your Blu-ray disc becomes useless.</p><p>To fix the problem, consumers should buy the ownership of a title, which should be portable across providers. Unfortunately, this was not a requirement.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*JfXyOfBWK6ad3PFAf0Bs_Q.png" /><figcaption><a href="https://xkcd.com/488/">https://xkcd.com/488/</a></figcaption></figure><h4>Secure Streaming</h4><p>Have you ever tried watching “Netflix” on your PC and noticed poor quality, even though you had a great internet connection? Or did you have to switch from Chrome to Safari on your Macbook to improve the quality?</p><p>The reason for that is DRM and secure hardware.</p><p>When we looked at the software-only media player, we concluded it was impossible to make it secure. The same problem applies to streaming, except that the content source is not a disc but the network.</p><p>When your device connects to a streaming server and requests to play a movie, it will be asked to prove its security capabilities. The server will decide in real-time the quality of the stream and how it will encrypt it.</p><p>Each manufacturer has a different system.</p><p>Apple uses secure coprocessors, which are present on all of their devices, including Macbooks. Their native Safari browser has direct access to the SEP (the secure enclave processor) and uses it for DRM. Streaming servers, like Netflix, trust the Apple stack to keep their data secure and stream high-quality content.</p><p>When you connect to Netflix from an Apple device, it will prove its identity by signing a message with the UID, which Netflix can check on the Apple servers to understand whether the device is genuine and up-to-date. Then, the stream will be routed through the SEP and then to the monitor.</p><p>Alternative browsers, like Chrome, cannot access native security features on Apple devices, so they must implement a software-only DRM, which explains the poor quality.</p><p>Microsoft has a similar technology based on secure coprocessors called “Pluton”.</p><p>Streaming solves the controversial problem of deprecated formats because users now own the right to view a movie on a service, but it introduces vendor lock-in. For example, the titles you own on “Amazon Video” can’t be transferred to “Disney”.</p><h3>Conclusion</h3><blockquote>Secure hardware is the unsung hero of modern devices.</blockquote><p>It keeps our data safe, gives us the immense convenience of logging in just by looking at the camera, and allows us to watch high-quality movies in our living room or while travelling.</p><p>While emerging technologies like Zero Knowledge Proofs( ZKP) or Fully Homomorphic Encryption (FHE) saw lots of investment and promises, they are still areas of research that will, at best, complement secure hardware to protect us.</p><h3>The “Demystifying SGX” Series</h3><p>In <a href="https://medium.com/obscuro-labs/intel-sgx-demystified-757a242682a3">part 1</a>, we look at the hardware features behind SGX.<br>In <a href="https://medium.com/obscuro-labs/intel-sgx-demystified-part-2-understanding-cpus-and-their-vulnerabilities-cea9754bd755">part 2</a>, we look at the features that make CPUs fast, and how they can be exploited.<br>In <a href="https://medium.com/obscuro-labs/demystifying-sgx-part-3-the-enclave-program-81949a4fe0c6">part 3</a>, we look at the architecture of an SGX enclave, then explore how the program is executed and even build a simple program.<br>In <a href="https://medium.com/obscuro-labs/demystifying-sgx-part-4-secure-hardware-59cd09687d53">part 4</a>, we look at real-life applications of secure hardware.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59cd09687d53" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Demystifying SGX part 3 —The enclave program]]></title>
            <link>https://medium.com/@tudor.malene/demystifying-sgx-part-3-the-enclave-program-81949a4fe0c6?source=rss-960132f36c3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/81949a4fe0c6</guid>
            <category><![CDATA[enclave]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[sgx]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[secure-computing]]></category>
            <dc:creator><![CDATA[Tudor Malene]]></dc:creator>
            <pubDate>Mon, 03 Jul 2023 16:06:24 GMT</pubDate>
            <atom:updated>2026-03-30T08:16:16.463Z</atom:updated>
            <content:encoded><![CDATA[<h3>Demystifying SGX — Part 3 —The enclave program</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*r99-tbIkKiveife9nDlSRQ.png" /><figcaption><a href="https://blog.quarkslab.com/overview-of-intel-sgx-part-1-sgx-internals.html">https://blog.quarkslab.com/overview-of-intel-sgx-part-1-sgx-internals.html</a></figcaption></figure><p>When I first ventured into the realm of <a href="https://en.wikipedia.org/wiki/Software_Guard_Extensions">SGX</a>, the trusted execution environment that ships with almost all Intel server chips, my understanding was muddled with misconceptions. I held inaccurate mental models of its <a href="https://medium.com/obscuro-labs/intel-sgx-demystified-757a242682a3">functioning</a>, and, more significantly, I anticipated a different programming approach. All this made the learning process more difficult than necessary.</p><p>In this article, you’ll find the straightforward overview I wish I had at my fingertips when I began. It’s aimed at sparing you the initial confusion and paving a smoother path into the world of SGX.</p><p>This is part 3 of the “Demystifying SGX” series. I highly recommend starting with <a href="https://medium.com/p/757a242682a3">part 1</a> and <a href="https://medium.com/p/cea9754bd755">part 2</a> for a high-level understanding of the hardware foundations.</p><h3>The architecture</h3><p>Consider the scenario: you have the hardware capability to run code in complete isolation. What should the architecture of an application using this feature look like?</p><p>The root of the main misconception is the mental model people are forming after reading the usual phrases: “running an application in SGX” or “writing an SGX application”. They imagine a standalone program operating in a typical client-server model, where its API consists of a suite of functions accepting arguments and returning results.</p><p>This model is perfectly fine when thinking about the application at the conceptual level. As a matter of fact, this is the model that modern high-level SGX SDKs expose. At this level of abstraction, the concerns are mostly around not revealing any secret information and ensuring the enclave code can protect itself against being fed invalid payloads or various replay attacks.</p><p>But this differs from how an SGX enclave is implemented in the reference Intel SDK. The mismatch between the useful high-level model and the code samples and explanations found in the most popular tutorials causes developers a lot of confusion.</p><p>The rest of the article will bridge the gap between the two models and prepare you to understand the more low-level SGX tutorials and, in a later blog post, the SGX attacks.</p><h4>The adversary</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3GbxQLE4r5LGmRXYRxQfIA.jpeg" /><figcaption><a href="https://thinkwritten.com/antagonist/">https://thinkwritten.com/antagonist/</a></figcaption></figure><p>To quote <a href="https://www.youtube.com/watch?v=VkorEW_eIXg">Martin Scorsese</a>: <em>“We have the protagonist, but where is the antagonist? Where is the drama?”</em></p><p><strong><em>The villain in the SGX story is the “untrusted code”, which includes the Operating System.</em></strong> Their main goal is to extract secrets or to forge computations.</p><p>The untrusted code villain has a wide range of weapons in its arsenal, from controlling the actual OS to calling the various functions with malicious arguments, pausing and inspecting the memory and the registries, and many more.</p><h3>The Intel SGX SDK</h3><p><strong><em>It is crucial to note that Intel designed the SGX enclave not as an independent process but as a library loaded and executed within an untrusted“host” process.</em></strong> The communication between the host and the enclave is bi-directional, allowing them to interchangeably assume the roles of client and server in relation to each other.</p><h4>Security, restrictions and boundaries</h4><p>This design choice becomes intuitive when one appreciates the unique restrictions of an enclave program. Take, for example, the prohibition of “<a href="https://en.wikipedia.org/wiki/System_call">System calls</a>” or syscalls.</p><p>As a reminder, syscalls serve as the means through which an operating system provides various services to programs, facilitating operations like file reading and writing or data transmission over a network.</p><p>Syscalls themselves are <a href="https://git.kernel.org/pub/scm/linux/kernel/git/stable/linux.git/tree/fs/ext4/namei.c">programs that come bundled with the OS kernel</a>. When a process initiates a file read operation, for instance, the corresponding syscall verifies whether the calling program possesses the necessary “read” access rights before retrieving the file’s content from the file system.</p><p>Conceptually, any program that relies upon syscalls will, at some point, give control to the OS to perform certain tasks. This is fine in the traditional model, where the OS is considered trusted, but not for an enclave where it is an adversary.</p><p>We can speculate on the reasons why the engineers at Intel decided to restrict syscalls.</p><p>If the syscalls were executed as part of the enclave, the CPU would need to “measure” the syscall program and include it in the enclave measurement and Attestation quote, which would tether the enclave to a specific OS version.</p><p><em>Note that the measurement would prevent an attacker from running the enclave on a computer initialised with malicious kernel code.</em></p><p>The remaining option is executing syscalls outside the enclave. This comes with different challenges when considering that the CPU already performs complex security logic during syscalls. It is possible that the interactions between the security models were just too complex. Another factor is the burden that this model puts on the enclave developer. When writing programs in a high-level language, one rarely considers which calls actually make a syscall behind the scenes. When writing enclave code, it could be an easy mistake to overlook something and leak secret data to the OS by saving something in a temporary file, for example.</p><p>For these reasons, Intel engineers decided to restrict syscalls but addressed this limitation by enabling the enclave to solicit custom services from the host process. The developer is responsible for explicitly defining these services, which become part of the enclave “untrusted” API.</p><p><strong><em>Essentially, Intel designed the “host” to function as an operating system for the enclave. Mirroring the interaction a typical program has with the OS via syscalls, the enclave program can also call on services exposed by the host.</em></strong></p><h3>The Password Manager example</h3><p>Let’s look at the flow of a typical example: <a href="https://sgx101.gitbook.io/sgx101/sgx-bootstrap/real-world-example">building a secure password manager</a>.</p><p>These are the requirements from the sgx101 website:</p><blockquote>The purpose of this application is to <strong>create a password wallet that can safely store your passwords and display them when requested</strong>. By implementing the wallet with SGX enclave protection, you are guaranteed to be able to securely create a wallet and manage the items inside it. The wallet will be sealed using SGX so that data are protected on disk and unsealed before any operation onto the wallet. Sealed wallet will be saved as filename “wallet.seal”.</blockquote><p>In this case, the attacker is not the local computer but a hacker who gains access to it later.</p><p>You may be curious about the necessity of SGX, considering that, naively, the wallet file could be encrypted directly with the master password. However, it is crucial to understand that without SGX, an attacker who obtains the password-encrypted “wallet.seal” file could potentially employ brute-force techniques to crack it, particularly if the password lacks sufficient entropy.</p><p>An SGX-based password manager can incorporate built-in delay logic to protect against brute-forcing the master password. It also leverages the cryptographic sealing key tied to the processor. This means that attempting to brute-force the sealed wallet file would require brute-forcing the enclave itself in release mode, which is highly impractical.</p><p>The diagram below depicts the “business logic” and the responsibilities of the “untrusted” host and the “trusted secure” enclave.</p><p>As you can see in the diagram, the enclave takes commands from the host (represented with a continuous arrow), like changing the master password, but also sends commands to the host, like storing the wallet on disk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*G6IC2Hmr_3Unao68hBZM4g.png" /></figure><p>All the logic performed over the secret data, like adding an item, is the responsibility of the enclave, while the host performs all the typical OS-specific functions.</p><p>Now that we understand the requirements of the password manager, we’ll build the program using a model more familiar to high-level programmers but which is equivalent to the low-level usage envisioned by Intel.</p><h4>The Enclave as an Object</h4><p>If your background is in OOP languages, the best way to look at an enclave is to consider it an Object.</p><p>The enclave object has a method for each command it takes from the host and a field for each callback function that calls into the host.</p><p>Below is the conceptual API of the “Password Manager” object when expressed as an object in Go.</p><p>First, we define the signatures of the callback functions.</p><pre>type LoadWalletCbType = func() []byte // Returns the sealed wallet<br>type SaveWalletCbType = func(sealedWallet []byte) // Saves the sealed wallet</pre><p>Next, let’s define the “PasswordManager” object.</p><pre>type PasswordManager struct{<br>  sealingKey        []byte <br>  LoadWalletCommand LoadWalletCbType<br>  SaveWalletCommand SaveWalletCbType<br>}<br><br>func (pm *PasswordManager) CreateWallet(masterPwd string){<br>  //... new wallet logic<br>  pm.SaveWalletCommand(sealedWallet)<br>  // ...<br>}<br><br>func (pm *PasswordManager) ShowWallet(masterPwd string) []byte{<br>  sealedWallet := pm.LoadWalletCommand()  <br>  // ... unsealing logic<br>  return plaintextWallet<br>}<br><br>func (pm *PasswordManager) ChangeMasterPassword(oldPwd string, newPwd string){<br>  oldSealedWallet := pm.LoadWalletCommand()  <br>  // ... unsealing and changing password<br>  pm.SaveWalletCommand(newSealedWallet)<br>  // ...<br>}<br><br>func (pm *PasswordManager) AddItem(masterPwd string, item []byte){<br>  oldSealedWallet := pm.LoadWalletCommand()  <br>  // ... unsealing and adding the item<br>  pm.SaveWalletCommand(newSealedWallet)<br>  // ...<br>}</pre><p>Notice how the callback functions pass the control back and forth between the object and the caller.</p><p>Also, notice how the overall API of this “PasswordManager” service consists of the signatures of the methods plus the signatures of the callbacks. In SGX tutorials, these are called the “trusted” and “untrusted” boundaries.</p><h3>Execution of the enclave</h3><p>The final question to answer to complete the picture is how the instructions in this SGX enclave object actually run on the CPU.</p><p>The OOP analogy comes in handy here as well. <strong><em>The best way to think about an SGX enclave is as an encapsulated object with an API and an encrypted internal state that lives inside the “host” process.</em></strong></p><p>To put it differently, the “host” is a typical application with a “main” method that runs as a standalone process. Similar to how it might initialise an embedded SQLite database if it needs to store some structured data, it can also initialise the “PasswordManager” object. <strong><em>Both SQLite and the PasswordManager enclave live inside the space of the main process, and their lifecycles are fully controlled by it.</em></strong></p><p>In practice, the difference is that the embedded SQLite is one of the services a typical program needs to operate, but the “Password manager” enclave is most likely the main reason for the existence of the host program.</p><p>In the rest of this section, we’ll look at what happens under the hood during the host-enclave interactions.</p><h4>Initialisation of the enclave</h4><p>First, the host program has to create the enclave. This step is similar to instantiating an object when the program allocates some memory space and calls the constructor with the supplied arguments. However, for an enclave, there are a few additional steps.</p><p>The entire enclave program must be loaded in memory and “measured”. Based on the measurement, the CPU will create the volatile encryption keys necessary to allocate the encrypted memory space, which is part of the normal memory space of the host process, except that all access to it passes through a dedicated hardware encryption engine.</p><h4>ECALLs</h4><p>Upon successful initialisation, the host has a handle for the enclave, allowing it to invoke specific entry points, like the “CreateWallet” function in our example. Using the official Intel SDK for SGX, this is accomplished using the ECALL (enclave call) function.</p><p>Maybe surprisingly, nothing extraordinary happens on <em>ECALLs</em>. <strong><em>It is similar to calling a regular function because the same CPU core will continue executing the same process.</em></strong></p><p><em>Note: When a normal program calls a function, the Instruction Pointer (IP) will no longer move to the next instruction in the program but will jump to the address where the function starts.</em></p><p>Behind the scenes, an <em>ECALL </em><strong><em>changes the operation mode of the CPU core to “enclave mode”, which enables access to the encrypted memory </em></strong>and loads the IP register with the address of the enclave entry point. After that, the CPU will carry on executing instructions at that address, with the main difference being that memory access is routed through the Memory Encryption Engine. There are other restrictions, of course. For example, as mentioned before, the core cannot execute system calls and the available instruction set is also reduced. Essentially, the CPU is now executing the enclave.</p><p>More concretely, when the host program calls ECALL(enclaveHandle, &quot;CreateWallet&quot;, &quot;strongPassword&quot;), the address of the “strongPassword” value will be loaded in one of the registers, the IP will be loaded with the address of the “CreateWallet” function, and then the enclave mode will be activated. Then the same CPU core will execute the first instruction of “CreateWallet”, but this time it will have transparent access to the contents of the encrypted memory.</p><h4>OCALLs</h4><p>We’ve seen that communication is bidirectional, so at some point, the enclave will call one of the callbacks, or “exit points”, like “SaveWalletCommand”.</p><p>This is done using OCALL (out-call), which is also a normal function call performed after the enclave mode is turned off. For security purposes, the OCALL has to clear the registers and the CPU cache because the exit point callback code is “untrusted&quot;, meaning it could try to access the registers directly or the cache through <a href="https://medium.com/obscuro-labs/intel-sgx-demystified-part-2-understanding-cpus-and-their-vulnerabilities-cea9754bd755">microarchitectural attacks</a>, thus leaking secrets.</p><p>When the callback finishes, the enclave mode is turned back on, and the next instructions from the enclave are executed.</p><p>The back and forth between the “trusted” and the “untrusted” code is relatively lightweight as <strong><em>the CPU will run the same process but in a different mode.</em></strong></p><h4>Threads</h4><p>Another interesting element is multi-threading because, intuitively, the assumption is that you should be able to start a new thread from the enclave code.</p><p>The model chosen by Intel is simpler. Since system calls are disabled from the enclave, so is the possibility of forking. Thus, multi-threading becomes the responsibility of the host, which can start multiple threads executing different enclave entry points.</p><p>One difference from typical execution is that each thread will be executed and bound to a different core.</p><p>Since these threads execute on the same enclave handle and share the encrypted memory space, Intel provides special instructions to synchronise between them.</p><h3>Conclusion</h3><p>Modern SGX SDKs hide a lot of complexity away from developers. For example, you can just write a normal application in languages such as Golang, Rust, or Java, and magically, the code will be executed inside an enclave.</p><p>Behind the scenes, these SDKs employ clever techniques to define the trusted and untrusted boundaries and conduct all the low-level interactions, leaving developers with a much simplified, user-friendly experience.</p><p>While comprehending the intricate backstage operations is no longer essential, having this knowledge can offer considerable advantages when it comes to troubleshooting and auditing security.</p><p>My hope is that this article provides a useful launching pad, propelling you forward in your exploration of SGX. Armed with this foundational understanding, you’re well-equipped to delve deeper into this intriguing realm of confidential computing.</p><h3>The “Demystifying SGX” Series</h3><p>In <a href="https://medium.com/obscuro-labs/intel-sgx-demystified-757a242682a3">part 1</a>, we look at the hardware features behind SGX.<br>In <a href="https://medium.com/obscuro-labs/intel-sgx-demystified-part-2-understanding-cpus-and-their-vulnerabilities-cea9754bd755">part 2</a>, we look at the features that make CPUs fast, and how they can be exploited.<br>In <a href="https://medium.com/obscuro-labs/demystifying-sgx-part-3-the-enclave-program-81949a4fe0c6">part 3</a>, we look at the architecture of an SGX enclave, then explore how the program is executed and even build a simple program.<br>In <a href="https://medium.com/obscuro-labs/demystifying-sgx-part-4-secure-hardware-59cd09687d53">part 4</a>, we look at real-life applications of secure hardware.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81949a4fe0c6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Encrypted Layer 2]]></title>
            <link>https://medium.com/obscuro-labs/the-privacy-transition-4f3f92dec10?source=rss-960132f36c3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f3f92dec10</guid>
            <category><![CDATA[layer-2]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Tudor Malene]]></dc:creator>
            <pubDate>Wed, 14 Jun 2023 14:02:31 GMT</pubDate>
            <atom:updated>2024-12-03T13:17:39.616Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fTkRJxHrZm45t58jYKoWbg.png" /><figcaption><a href="https://www.sofi.com/learn/content/what-is-blockchain-encryption/">https://www.sofi.com/learn/content/what-is-blockchain-encryption/</a></figcaption></figure><p>In his recent blog post, ‘<a href="https://vitalik.ca/general/2023/06/09/three_transitions.html">The Three Transitions</a>’, Vitalik Buterin delineates the key challenges that must be addressed by the Ethereum ecosystem. These issues encompass various user experience (UX) facets, such as cost, confidence to store assets, and the lack of data transparency. Ethereum’s long-term competitiveness against centralised services hinges on the ability to offer a similar UX.</p><p>Vitalik explores the privacy transition with specific applications in mind, like payments and identity. In this article, we’ll build on that foundation and delve deeper into the challenges of achieving <strong>general-purpose privacy</strong>.</p><p><strong>Consider a scenario where an Ethereum Layer 2 (L2) is developed where the entire ledger is encrypted. In such a scenario, users submit encrypted transactions, which are then processed in encrypted form, and the nodes return encrypted payloads, accessible only to designated users.</strong></p><p>Building on this L2 would theoretically enable the development of decentralised applications (Dapps) that function much like typical centralised ones. This is because these Dapps could selectively reveal information only to those who are meant to see it. Whether it’s an online banking customer wanting exclusive access to their account balance or a social media user wishing to share a photo only with select family members.</p><h4>The Developer Experience of an Encrypted L2</h4><p>Developers of Ethereum Dapps, having already adapted to a specific language and environment, should ideally be able to continue with their familiar toolset, even when the ledger is encrypted. Let’s posit that this envisioned encrypted L2 is perfectly EVM-compatible.</p><p>However, requirements need to be identified.</p><p>At a superficial level, one might think that a Turing-complete language should suffice to accommodate any privacy features. Developers could simply append access control logic to the ‘view functions’ exposing user data to execute any access policy. Sounds like a problem solved? Not exactly.</p><p>There are a few nuances that warrant further attention.</p><ul><li>Ethereum-compatible L2s expose the“<a href="https://docs.alchemy.com/reference/eth-getstorageat"><em>eth-getStorageAt</em></a>” RPC call, which enables access to the internal state of any contract, bypassing the “view functions”. This option, naturally, would be nonviable.</li><li>Ethereum RPC calls are not authenticated. For a view function to make access control decisions, it needs to know who is making a call.</li><li>Access to platform-specific resources such as transactions, receipts, and general account data (like native balance, code, and nonce) must also be controlled.</li><li>The most challenging aspect is event logs. These are custom payloads generated by smart contracts, typically used by UIs. Given Ethereum’s data transparency principle, they weren’t designed with access control in mind. However, the objective of our encrypted platform is to ensure data protection by default, providing developers with the tools to establish access control rules, including for events.</li><li>Lastly, the information destined for users needs to be encrypted with “viewing keys” ( or “encrypted keys”)</li></ul><h4>The User Experience</h4><p>A user’s interaction with an encrypted L2 should align with their typical Ethereum experience. This can be realised if the user can access necessary data, such as allowed photos or current balance, but without anyone else viewing their personal balance.</p><p>As Vitalik also pointed out, this experience demands efficient encryption key management. These keys may be, and preferably should be, distinct from the spending keys.</p><h3>Conclusion</h3><p>The realisation of the privacy transition is not only a cryptographic challenge but also an exploration journey of the optimal user and developer experience. At TEN, we align with Vitalik’s vision and have been working tirelessly over the past year and a half to build a platform that embodies this ideal.</p><p>While we wait for technology like <a href="https://en.wikipedia.org/wiki/Homomorphic_encryption">Fully Homomorphic Encryption</a> to become practical, this journey should begin with less than perfect technology, such as <a href="https://medium.com/p/757a242682a3">Trusted Execution Environments </a>(TEEs), and apply to use cases like gaming, or DeFi that doesn’t need perpetual privacy. After all, numerous successful ideas took their first steps in the world of games.</p><p>As we continue to explore these critical themes, your thoughts, ideas, and critiques are invaluable. Head over to our <a href="https://discord.gg/7pkKv2Tyfn">TEN Discord server</a>, where our community is constantly brainstorming and dissecting these complex issues. Your insights could be the key to the next breakthrough. See you there!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f3f92dec10" width="1" height="1" alt=""><hr><p><a href="https://medium.com/obscuro-labs/the-privacy-transition-4f3f92dec10">The Encrypted Layer 2</a> was originally published in <a href="https://medium.com/obscuro-labs">TEN Protocol — Privacy on Ethereum</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a confidential Web Service]]></title>
            <link>https://medium.com/obscuro-labs/building-a-confidential-web-service-983a2a67fc08?source=rss-960132f36c3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/983a2a67fc08</guid>
            <category><![CDATA[obscuro]]></category>
            <category><![CDATA[sgx]]></category>
            <category><![CDATA[crypto]]></category>
            <category><![CDATA[privacy]]></category>
            <category><![CDATA[confidential-computing]]></category>
            <dc:creator><![CDATA[Tudor Malene]]></dc:creator>
            <pubDate>Tue, 02 May 2023 17:38:05 GMT</pubDate>
            <atom:updated>2026-03-30T08:16:49.697Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine your task is to create a web service that keeps all data confidential, even from the team running the infrastructure. For example, the system allows insurance agents to compare their clients in real time against each other to discover fraud. This information is so valuable that nobody is trusted to run this service if a human can access it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o5ru1pFK-Ulg25XO9w8SFA.jpeg" /><figcaption><a href="https://snellingswalters.com/understanding-eap-confidentiality/">https://snellingswalters.com/understanding-eap-confidentiality/</a></figcaption></figure><p>One approach is using traditional checks and balances, like physically guarding the server room, but that&#39;s expensive and not very effective.</p><p>Our goal is to design a system that keeps data confidential and, at the same time, is cheap to run. The solution in this article will leverage the existing HTTPS infrastructure, confidential computing and economic incentives to achieve that. Another way to look at it is that the solution will only require trust in people and systems that don&#39;t have direct access to the data and enough skin in the game to be trustworthy.</p><p>We&#39;ll build the solution step by step by adding elements one at a time, identifying what is missing, and then repeating the process.</p><h3>The connection is secure</h3><p><strong><em>When a user connects to a website like &quot;https://</em></strong><a href="http://www.foo.com/"><strong><em>www.foo.com</em></strong></a><strong><em>&quot;, they have a guarantee that they communicate with a server owned by whoever owns the domain &quot;foo.com&quot;. Users are expected to gain confidence through social means that &quot;foo.com&quot; is owned by the well-known &quot;Foo Corporation&quot;. HTTPS guarantees that nobody else can see the data they exchange. </em></strong>Not the ISP, not the Wifi owner, not the government, and no hacker.</p><p>To support HTTPS, the foo.com administrator owns a key pair and a certificate signed by a trusted authority. All browsers and operating systems contain a hardcoded list of accepted authorities to complete the trust circle. Therefore, if a hacker intercepts the traffic and attempts to impersonate &quot;Foo&quot;, they will fail to present a valid certificate for that name, and the browser will warn the user.</p><p>The image below depicts setting up an HTTPS certificate and how it keeps traffic secure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zXvg5nZqzjYhrlpVDfg-jQ.png" /><figcaption><a href="https://www.hostinger.com/tutorials/what-is-ssl">https://www.hostinger.com/tutorials/what-is-ssl</a></figcaption></figure><h3>Data is secure</h3><p>We&#39;ve seen how HTTPS guarantees that an attacker can&#39;t fake the domain name you connect to. So let&#39;s try to improve that by considering how we could convince users that no human can access the data they submit to the server.</p><p>For example, in our hypothetical fraud detection system, the competing companies do not want the real-time data to be visible to the system administrators because they might be tempted to sell it.</p><p>When a browser tells you that the &quot;Connection is secure&quot;, it doesn&#39;t mean that &quot;foo.com&quot; will not sell your data to advertisers.</p><p>In an ideal world, after typing the URL in the address bar of a browser, a green &quot;Data is secure&quot; tick appears for services that offer this additional guarantee.</p><p>Let&#39;s start by designing a fantasy solution using confidential computing. This solution uses features that are not available yet, but it is useful to understand the problem and the first ingredients of the practical solution.</p><h4>The &quot;Data is secure&quot; certificate</h4><p>A program running in a secure enclave can report a measurement, but that&#39;s not very helpful. For example, the browser displaying: <strong><em>&quot;You&#39;re connected to a server running the program with the hash 0x74d1c…&quot;</em></strong> will not exactly fill a user with confidence that their data is secure.</p><p>We need a way from the statement above to a human-readable <strong><em>&quot;Data is secure&quot;.</em></strong></p><p>Similar to how the Web &quot;Certificate Authorities&quot; (CA) bind a name to a cryptographic key by verifying and attesting identities, we must introduce <strong><em>&quot;Confidential computing security auditors&quot; (CCSA). </em></strong>These are reputable companies that can audit source code and sign a certificate confirming that the program will keep data confidential if run on secure hardware.</p><p><strong><em>A CCSA will bind the data confidentiality guarantee to the measurement of a program.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*91kyxtBGHPJjv-Qz8Mj5nw.png" /><figcaption>Data is secure Cert</figcaption></figure><p>In this ideal model, on top of the trusted CAs, browsers must support a list of trusted CCSAs.</p><h4>HTTPS into the enclave</h4><p>As we&#39;ve seen above, HTTPS already encrypts data between two endpoints and guarantees that nobody in the middle can read it.</p><p><strong><em>To build our confidential solution, we must ensure the browser establishes an HTTPS connection directly with an enclave.</em></strong></p><p>To ensure that an enclave is on the other end, the browser must execute a simple protocol that verifies the Attestation of the counterparty. Then, based on the attestation report and the CCSA certificate, it can confidently display the &quot;Data is secure&quot; tick.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*TYc5QZAAXSX5Shrxm2NMaQ.png" /></figure><p><em>Note that the Attestation verification has to be performed natively by the browser. It can&#39;t rely on downloaded javascript because the javascript file will be served by the service that is under verification.</em></p><p>With this solution, all data is encrypted in transit (HTTPS), during processing (confidential computing) and then at rest if stored in an encrypted database.</p><p>In this ideal solution, the end-user will fully trust the browser to make the best decisions on her behalf. The browser knows which CAs and CCSAs to trust and thus can inform the user that the connection and the data are secure.</p><h4>Web Certificate generated inside the enclave</h4><p>Unfortunately, the design we described above depends on features yet to be implemented by browsers, but we must build this service today.</p><p><em>The insight for the first ingredient of the actual practical solution is that the</em><strong><em> key pair backing the Web Certificate can be generated inside the secure enclave.</em></strong></p><p>This means that any TLS connection using that particular certificate is guaranteed to terminate in the enclave because nobody else will have the corresponding private key.</p><p>The CCSA must audit and attest that this functionality is implemented securely, so the logical output of the CCSA certificate will be: <strong><em>&quot;We guarantee that to the best of our knowledge, if an HTTPS connection is established using the included web certificate, then the data is protected&quot;.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*LuPyFV21QzUYOvYGicAA9g.png" /></figure><p>Since the browser has no native support for secure data, it won&#39;t be able to display &quot;Data is secure&quot;. However, that is not a big problem for the users if they receive the &quot;www.securedataservice.com&quot; URL from a trusted source, like their employer.</p><p>Note that users that want to use a service advertised to them must perform the extra step of visiting a trusted website and checking whether the application they want to use is approved. Only then visit the website safely.</p><p>With this step, we managed to bind a domain name to an enclave. <strong><em>The UX is viable even if the check is not automatic as long as it must be performed only once before using the service the first time.</em></strong></p><h4>&quot;Double-spending&quot; Web certificates</h4><p>A browser connecting to a URL will check that the certificate presented by the server during the TLS handshake is signed by one of the CAs it is configured to trust. However, a website is not required<strong><em> to have a single certificate, so &quot;foo.com&quot; could theoretically use multiple certificates, some with keys generated outside the enclave.</em></strong></p><p>If our hypothetical confidential service provider wants to peek at user data, they can get a second web certificate and present it to some users. If these users do not check the key from the CA certificate against the one found in the CCSA certificate, their data can be submitted to a typical server not running in an enclave, and the users will never know. This is unacceptable, as it violates the trust assumptions we stated for a practical solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*lMhCfZzJFRS3xJpt8pmZyQ.png" /></figure><p>Our task at this step is to remove this last element where users must trust the service provider.</p><p>Decentralised protocols have found clever ways to complement technical solutions with crypto-economic incentives, showing that enormous value can be secured this way.</p><p>This problem is similar to the one solved by the Ethereum proof-of-stake protocol, which prevents validators from double-signing. <strong><em>In both cases, the deviant behaviour can be proven cryptographically</em></strong>.</p><p>In the Ethereum case, the prover presents multiple signatures by the same validator over conflicting blocks. <strong><em>In our case, a verifier can prove the malicious behaviour of the service provider by submitting a second CA certificate for that domain.</em></strong></p><p><em>Note: In the diagram above, if Bob was connected using a special program, he could save the certificate presented during the TLS handshake and claim a reward.</em></p><p>To keep the service honest, verifiers will randomly establish connections with the URL from various IP addresses using a program that checks the certificate. The condition is that the server should be unable to differentiate between a &quot;validity check&quot; call and a normal one to prevent the operator from doing a <a href="https://en.wikipedia.org/wiki/Volkswagen_emissions_scandal">Volkswagen</a>.</p><p>Deviant Ethereum validators are punished by &quot;slashing&quot;, meaning the protocol confiscates their stake. <strong><em>The insight is that bad behaviour can be either prevented in real-time by making it impossible or severely punished if discovered later</em></strong>. Both approaches are practical.</p><p><em>Note: The ideal &quot;Confidential Web Service&quot; solution described originally prevented the service provider from cheating because a browser could detect that immediately when verifying the Attestation.</em></p><p>The key ingredient for the punishment solution is &quot;Skin in the game&quot;.</p><p>Enterprise services, like our hypothetical fraud check example, can be verified by the members. If the provider deviates, they lose their reputation and thus the business.</p><p><strong><em>Public services can stake crypto together with the CCSA in a decentralised smart contract. The contract will pay the stake to anyone with an alternative certificate for the same domain.</em></strong></p><p>With this last ingredient in place, we have a complete solution for our Confidential Web Service. Furthermore, the solution is feasible even without an explicit &quot;Data is secure&quot; tick because crypto has already demonstrated that end-users are happy to use audited programs if they hear about the program from a trusted source.</p><h3>The Real-time fraud checking Service</h3><p>Now we are ready to wrap up our hypothetical fraud checking service.</p><p>A software development company writes a program that performs logic that helps some fierce competitors collaborate. Then, they deploy the program on a secure enclave and instruct the enclave to generate a CA certificate for their brand new &quot;www.live-fraud.com&quot; domain.</p><p>Then they contact &quot;Let&#39;s Encrypt&quot;, where they prove their identity and receive a signed Web CA certificate which they feed back into the enclave.</p><p>Then they hire a reputable security audit firm which will sign over a report confirming two things:</p><ol><li>The Web CA certificate was indeed generated in the enclave.</li><li>The audited program cannot send the data it receives to anyone.</li></ol><p>With this shiny new CCSR certificate, they convince each competitor to use the system.</p><p>These companies know about the multiple certificate attack and ask their security teams to set up a random verification procedure. In case they find a discrepancy, they can sue the software developer.</p><p>When that last piece is in place, they instruct their agents to submit real-time data from their field iPads, safe in the knowledge that &quot;https://www.live-fraud.com&quot; cannot leak their precious data.</p><h3>The Obscuro Gateway</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2mqx3KVAE9hVKvjCscdsSw.png" /></figure><p><a href="https://www.ten.xyz/">Obscuro</a> (now known as Ten) is a decentralised protocol offering private smart contracts. We aim to provide a user experience identical to Ethereum by supporting the same wallets and APIs to interact with the chain.</p><p>To achieve this goal, we faced a dilemma. On the one hand, the transactions and data of the users must be private. Therefore, we designed the Obscuro RPC protocol based on encryption with &quot;viewing keys&quot; (VK). Users can own multiple VKs, register them with a node, and request information encrypted with these keys. However, since ordinary Ethereum wallets do not support VKs, we had to find a way to bridge this gap.</p><p>Our first iteration is a &quot;Wallet Extension&quot; software which acts as an Ethereum node installed on the local computer from the point of view of the wallets and dApps. Behind the scenes, it handles the encrypted communication with an Obscuro node so that no private data leaves the computer unencrypted. While this solution is excellent for tech-savvy users, as it puts them in complete control over privacy, we recognise that there are better ways to onboard users looking for a &quot;one-click&quot; experience.</p><p>This is why we&#39;re introducing &quot;The Obscuro Gateway&quot; (OG). <strong><em>The OG is a hosted &quot;Confidential Web Service&quot; version of the Wallet Extension</em></strong>. We will release an open-source version of this software and expect some node operators to offer this service. As described above, staking will ensure that data remains secure, and all Obscuro nodes will have built-in functionality to act as OG validators.</p><p>The OG will function at a URL like &quot;https://gateway.obscu.ro&quot;. Furthermore, the code will be open source, and a comprehensive security audit will be published. The network of validators will enforce that the gateway keeps the data private.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*UH13hf9AjI3AA6Wg3Z2VFQ.png" /><figcaption>The Obscuro Gateway</figcaption></figure><p>This approach enables us to keep the Obscuro RPC protocol simple and to offer alternatives for the needs of the various Obscuro users. For example, institutional users may want to build their own Obscuro Gateway, where they can introduce advanced features.</p><h3>Conclusion</h3><p>We&#39;ve shown that &quot;Confidential Web Services&quot;, web applications that keep user data private from everyone, can be feasibly built using today&#39;s technology. We at Obscuro will use this technique to build the &quot;Obscuro Gateway&quot; to achieve our ambition of becoming the privacy chain with the best user experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=983a2a67fc08" width="1" height="1" alt=""><hr><p><a href="https://medium.com/obscuro-labs/building-a-confidential-web-service-983a2a67fc08">Building a confidential Web Service</a> was originally published in <a href="https://medium.com/obscuro-labs">TEN Protocol — Privacy on Ethereum</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intel SGX demystified part 2: understanding CPUs and their vulnerabilities]]></title>
            <link>https://medium.com/@tudor.malene/intel-sgx-demystified-part-2-understanding-cpus-and-their-vulnerabilities-cea9754bd755?source=rss-960132f36c3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/cea9754bd755</guid>
            <category><![CDATA[meltdown]]></category>
            <category><![CDATA[sgx]]></category>
            <category><![CDATA[cpu]]></category>
            <category><![CDATA[confidential-computing]]></category>
            <category><![CDATA[computer-security]]></category>
            <dc:creator><![CDATA[Tudor Malene]]></dc:creator>
            <pubDate>Thu, 23 Mar 2023 16:58:11 GMT</pubDate>
            <atom:updated>2026-03-30T08:17:09.694Z</atom:updated>
            <content:encoded><![CDATA[<h3>Demystifying SGX— Part 2 — Understanding CPUs and their vulnerabilities</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*DD8mZBnfC192VmBVsMPNTQ.jpeg" /><figcaption><a href="https://www.eonline.com/news/1271714/these-25-mission-impossible-secrets-are-yours-if-you-choose-to-accept-them">https://www.eonline.com/news/1271714/these-25-mission-impossible-secrets-are-yours-if-you-choose-to-accept-them</a></figcaption></figure><p>When I first heard about researchers &quot;breaking into&quot; secure enclaves, I imagined a &quot;Mission Impossible&quot; style operation where the researcher dodges laser beams, breaks some cryptography, and runs away with the top-secret list of undercover agents.</p><p>It turns out that the researchers are CPU geeks with a deep knowledge of CPU <a href="https://en.wikipedia.org/wiki/Microarchitecture">Microarchitecture</a> (yes, we’ll demystify that as well) who use highly subtle combinations of performance features, or undocumented <a href="https://www.usenix.org/system/files/sec22-borrello.pdf">buffers</a>, to craft scenarios where a bit of data from a program stays residual somewhere in the CPU for a couple of nanoseconds, enough for another program to read it.</p><p>This is the second article in a three-part SGX series. The <a href="https://medium.com/p/757a242682a3">first part</a> describes how SGX works by focusing on the security features of CPUs. In this part, we&#39;ll look at what makes CPUs fast and how those optimisations were used to break the isolation guarantees.</p><h3>The race for performance</h3><p>The main attributes general-purpose CPUs are judged on commercially are cost, speed and power consumption. Since multi-core CPUs became dominant, speed is further broken down into &quot;<a href="https://www.cpubenchmark.net/singleThread.html">single-threaded</a>&quot; and overall speed.</p><p>Based on the use case, each of these attributes will matter more. For example, for a high-end laptop, it will be performance and power consumption. For an industrial server, it will be cost and speed. For some servers, it will be &quot;single-threaded&quot; performance, etc.</p><p>Choosing the balance between these three attributes imposes severe constraints on CPU manufacturers.</p><h4>What makes a CPU fast?</h4><p>Let&#39;s start with the definition of speed. There are various benchmarks out there to measure it. The essence is that the CPU must finish a task, or multiple simultaneous tasks, in the shortest amount of time, at least compared to the competition. This translates into webpages loading faster, games running smoother, code compiling more quickly, etc.</p><p>Early on, the property typically associated with CPU speed was the CPU clock rate. For example, the <a href="https://en.wikipedia.org/wiki/Intel_8086">8086</a> worked at 5–10Mhz. Recent CPUs are working at over <a href="https://www.intel.co.uk/content/www/uk/en/products/sku/230496/intel-core-i913900k-processor-36m-cache-up-to-5-80-ghz/specifications.html">5GHz</a>. The <a href="https://en.wikipedia.org/wiki/Clock_rate">clock rate</a> represents the internal unit of time of the CPU, basically how many &quot;things&quot; it can do in a second. While this is important, the &quot;things&quot; bit is more important. The misconception that CPU clock rate is the only stat that matters even has a name, the &quot;<a href="https://en.wikipedia.org/wiki/Megahertz_myth">Megahertz Myth</a>&quot;.</p><p>&quot;<a href="https://en.wikipedia.org/wiki/Instructions_per_second">Instructions per second</a>&quot; is a better measure of CPU speed. It equates &quot;things&quot; with CPU instructions. Notice in the <a href="https://en.wikipedia.org/wiki/Instructions_per_second#Timeline_of_instructions_per_second">Wikipedia</a> link that the 8086@5Mhz was doing 0.3 MIPS (Million Instructions per Second), while the AMD Ryzen is doing 2,356,230 MIPS at 4.35 GHz. So for a 1000x increase in clock rate, the overall CPU speed went up almost 10 Million times. More relevant to our topic, a better measure is to look at the &quot;<em>instructions per clock cycle per core</em>&quot; metric, which went from 0.066 for the 8086 to 10.96 for the i9.</p><p>CPUs currently execute 160 times more instructions per clock cycle per core than in 1978 (the 8086). This was achieved not only by hardware improvements but primarily by clever optimisations on how data is processed.</p><h4>Tradeoffs</h4><p>Achieving CPU performance is probably one of the most complex tasks in all engineering. So I&#39;ll only mention a few tradeoffs and limitations, primarily due to the limits of materials and physics.</p><p>Increasing the CPU clock rate, which is the internal unit of time of the CPU, is limited mainly by <a href="https://en.wikipedia.org/wiki/Processor_power_dissipation">heat dissipation</a>. The higher the frequency, the more current flows through the internal circuits and the hotter the CPU gets until it can burn. This is the reason why gamers invest so much in <a href="https://techloot.co.uk/gaming/guide-to-overclocking-cool/">special cooling</a>.</p><p>Increasing the circuit size also hits limitations because a lot of information must travel quickly through the CPU. So the &quot;<a href="https://en.wikipedia.org/wiki/Velocity_factor">velocity factor</a>&quot; starts becoming significant because it introduces latency, and information cannot travel between the relevant circuits during a clock tick. That is why &quot;transistor size&quot; has become an important topic, although that is also becoming a myth.</p><p>Another important consideration is that different components have significantly different operating speeds. For example, the CPU works very closely with the memory chip. The issue is that receiving information from memory takes a very long time when measured from the reference frame of the CPU. Imagine sending an email with an urgent information request which you need in 10 minutes and receiving the reply in days. If you don&#39;t have any other tasks, you must stay idle until you receive a response.</p><p>Given all this pain CPU manufacturers have to endure, like fighting the laws of physics, the first directive of CPU design is that &quot;<strong>valuable</strong> <strong>CPU resources should stay idle as little as possible</strong>&quot;.</p><h3>Techniques to reduce idle time</h3><p>After all this context, it&#39;s finally time to introduce the relevant optimisation techniques.</p><p>The 8086 came with &quot;<a href="https://en.wikipedia.org/wiki/Instruction_pipelining">instruction pipelining</a>&quot;, an instruction-level parallelisation technique designed to keep as many of the available circuits busy all the time. Following the same principle as an assembly line, the CPU can execute multiple basic instructions in parallel if they use different circuits. Furthermore, because instructions are sequences of small elementary operations that can be executed in hardware, the CPU can arrange them such that outputs of some operations are available just in time as inputs for others. However, in the case of the 8086, this mechanism was primitive, only splitting up fetching from execution.</p><p>An improvement which came with the NexGen Nx586 is &quot;<a href="https://en.wikipedia.org/wiki/Out-of-order_execution">out-of-order execution</a>&quot; (OOE). The CPU transforms a linear sequence of instructions into multiple sequences that can be executed in parallel by looking at the dependencies between the inputs and outputs. Another way to look at it is that a single-threaded program can be transformed into multiple threads, where each can be scheduled independently. This technique is potent even on a single-core CPU because each sequence typically has idle periods waiting for memory access. Instead of keeping the entire CPU idle, the scheduler can execute the other out-of-order sequence. The &quot;preemptive scheduling&quot; approach comes in very handy.</p><p>An improvement on top of OOE came with the Pentium Pro and is called &quot;<a href="https://en.wikipedia.org/wiki/Speculative_execution">speculative execution</a>&quot;. This is handling the case of an &quot;if&quot; branch in the code or when a function returns. A static analyser of instruction dependency cannot tell which branch will be taken. In this case, the CPU can either idle until it calculates the condition or execute one or both branches speculatively. &quot;Predictive execution&quot; is the technique&#39;s name when it tries to predict which branch is more likely. &quot;Eager execution&quot; is the CPU just executing both branches.</p><p>Speculative execution is also called &quot;transient execution&quot; because the results will be discarded if the predictor is wrong. This feature gave the name to the<a href="https://en.wikipedia.org/wiki/Transient_execution_CPU_vulnerability"> attacks</a> we&#39;ll look at below.</p><p>For general-purpose CPUs, in many cases, it is more efficient overall to calculate potentially unnecessary results and throw them away than to stay idle.</p><h4>Caching</h4><p>The speed of the CPU increased much faster than the access time of the memory chip. This phenomenon is called the &quot;<a href="https://en.wikipedia.org/wiki/Random-access_memory#Memory_wall">Memory Wall</a>&quot;.</p><p>In the 8086 and 80286 days, a CPU requesting some information from memory would receive it with latencies the same order of magnitude as their internal clock.</p><p>Memory access had already become a bottleneck when the 80386 was running at 40 MHz, and this problem has since become exponentially worse as modern CPUs run at 3–5GHz.</p><p>This brings us to the same problem as before, the CPU sitting idle, waiting to receive data or instructions from memory.</p><p>The solution introduced with the <a href="https://en.wikipedia.org/wiki/I486">80486</a> was to include a smaller but much faster memory chip inside the CPU, which can use this &quot;<a href="https://en.wikipedia.org/wiki/CPU_cache">cache</a>&quot; to store data it needs frequently or speculatively request from memory data that it thinks it will need in the future. Assuming that the CPU has only a few cache &quot;misses&quot;, the idle time waiting for memory can be reduced significantly.</p><p>The gap between the CPU speed and the memory latency continued to expand. When the &quot;Pentium Pro&quot; was created, running at 200 Mhz, it was necessary to include another caching layer known as the &quot;L2&quot; cache. The L2 is slower and larger than the L1 cache but still much faster and closer to the core than the memory chip. <a href="https://superuser.com/questions/269080/why-are-multiple-levels-of-caches-used-in-modern-cpus#:~:text=So%2C%20to%20sum%20it%20up,that%20are%20faster%20and%20cheaper.">You may wonder why they didn&#39;t make the existing &quot;L1&quot; cache bigger</a>. There is a massive tradeoff between speed and cost for this type of memory. Increasing its size would make the CPU much larger, which would have other negative side effects. Building a &quot;Level 2&quot; cache that is a bit slower but much smaller in physical size for the same capacity is a pragmatic choice that comes at the cost of increasing the cache management complexity.</p><p>Later a &quot;Layer 3&quot; cache was included, which is even larger.</p><h4>How does caching work?</h4><p>To understand the CPU attacks, we need to peek under the hood.</p><p>During program execution, data blocks are stored in the cache together with metadata. These blocks were either requested directly by the program from memory or can be data that the CPU fetched speculatively.</p><p>Note that they can also be blocks from branches of &quot;speculative execution&quot; that turned out to be wasted.</p><p>Given that the role of the cache is to speed up memory access, each cache entry contains a physical memory address, the memory content, and some metadata. In the literature, this is called a &quot;<a href="https://en.wikipedia.org/wiki/CPU_cache#Cache_entry_structure">cache line</a>&quot;.</p><p>Note that each program has only a view of &quot;virtual addresses&quot;, which are mapped to &quot;physical addresses&quot; by the Memory Management Unit(MMU) circuit that itself uses caching internally.</p><p>All this happens behind the scenes, as programs do not have direct access to the cache. The only operation exposed is flushing the cache or a cache line.</p><p>The essential thing to remember is that caching must be viewed as a side-effect of any execution. Combined with the parallelised and speculative nature of instruction execution, it is critical to most attacks.</p><h4>Multi-Core CPUs</h4><p>By the mid-2000s, making CPUs faster was becoming increasingly challenging, so manufacturers faced a dilemma on how to continue making computers more powerful.</p><p>They could have continued with the regular (single-core) CPUs and made supporting multiple CPUs a problem for the motherboard producers. The disadvantage of that approach is sharing resources between the CPUs.</p><p>For example, cache invalidation is a notoriously hard problem. If the same memory block is cached in multiple CPUs, and the underlying value in memory changes, all the caches must be notified to evict that &quot;stale&quot; value. Doing this over the circuits of the motherboard takes a long time, so this coordination problem could nullify the advantages of having a cache.</p><p>The preferred approach was to include many CPU &quot;cores&quot; in a single circuit to be very close to each other, especially their caches. In the typical setup, each core has its own L1 and L2 caches, and all cores share the L3 cache.</p><h3>Program isolation</h3><p>We can safely assume that CPU engineers are highly competent based on how much they have achieved over the years. They designed all these improvements to maintain the isolation guarantees on which the operating systems and hypervisors rely. The <a href="https://medium.com/obscuro-labs/intel-sgx-demystified-757a242682a3">first article</a> in the series described this concern in detail.</p><p>To summarise, as a computer user, you expect that by loading a web page, there is no way that action allows an attacker to access your banking data that is loaded in excel. Or, as a cloud user, you expect that the client data you have on your server cannot leak to another VM running on the same physical machine. This level of isolation is an essential guarantee of a modern computer.</p><p>This guarantee has come under intense challenge in recent years. By creatively combining the performance features built into the CPU, researchers demonstrated they could bypass the restrictions. This realisation has started a friendly and constructive arms race between researchers and CPU manufacturers that is still ongoing.</p><h3>Meltdown and Spectre attacks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*67I_eizeZ37M3J0-QTlaxg.png" /><figcaption><a href="https://www.malwarebytes.com/blog/news/2018/01/meltdown-and-spectre-what-you-need-to-know">https://www.malwarebytes.com/blog/news/2018/01/meltdown-and-spectre-what-you-need-to-know</a></figcaption></figure><p>These are the original vulnerabilities reported in 2018, triggering a wave of creativity among researchers who discovered many more “Microarchitecture” attacks.</p><p>Note that these attacks are not SGX-related, but understanding them is essential because they represent the template and will give you a good overview of the approach.</p><h4>Microarchitecture</h4><p>When discussing caching, one highlighted aspect was that it is happening behind the scenes, not exposed to the programmer. The same can be said about out-of-order and speculative execution and also about “preemptive multitasking”, which was covered in the previous article.</p><p>What these elements have in common is that they are part of the implementation details of the CPU.</p><p>The API a CPU exposes to programs is called the <a href="https://en.wikipedia.org/wiki/Instruction_set_architecture">“Instruction Set Architecture”(ISA)</a>. To simplify, think of it as the instructions available in the assembly language.</p><p>For example, the multiplication instruction (“MUL”) was introduced with the 8086 CPU. Before that, CPUs could only add and subtract. “MUL” is now part of the API and is a useful abstraction for programs. The <a href="https://www.righto.com/2023/03/8086-multiplication-microcode.html">exact details on how</a> or when the CPU executes the operation are a secret, subject to optimisations.</p><p>The instruction “MOV register, [address]” promises to fetch the data found at an address in memory into the specified register. In the 8086, this was a straightforward operation where the CPU output electrical impulses on some pins, and a few ms later, it received the value. Each of the security and performance features we described so far in these articles, but also many others, have gradually introduced complexity. With the addition of memory isolation, the CPU has to check whether the current process has the right to access that address. This step involves, among others, translating virtual to physical addresses. Once caching was introduced, it must check whether the required data is found in the cache. With caching layers, things became even more complex. For example, in some CPUs, each caching layer can have different entries, while in others, each smaller cache is completely included in the larger one.</p><p>On a modern CPU, when a program requests data from memory, a flurry of activity occurs in many of the CPU circuits. All these operations that go on behind the scenes are executed by internal components of the CPU architecture, which expose private “APIs” to each other. For example, the caching logic of coordinating between multiple cores and multiple layers is a very complex problem. There must be a “microprogram” that calls each of these individual circuits, awaits confirmation from them, handles errors, etc.</p><p>This internal implementation which consists of both the physical circuits, and the programs that operate them, is the “Microarchitecture” of the CPU.</p><p>Unfortunately, even though it is very low level, <strong><em>the Microarchitecture is not immune to the universal “</em></strong><a href="https://www.joelonsoftware.com/2002/11/11/the-law-of-leaky-abstractions/"><strong><em>Law of leaky abstractions</em></strong></a><strong><em>”.</em></strong> The classical example of that law is that an SQL query can run in 10ms or 10 minutes, depending on how much data is in a table and how the database works internally.</p><p>A key element to understanding “Microarchitecture vulnerabilities” is that while the CPU has significant security and isolation responsibilities, at the same time, has reached a level of complexity where some abstractions can leak or behave unexpectedly in certain circumstances. As we’ll see below, researchers devised creative ways to use the implementation details of different instructions or combinations of instructions to access data that should be hidden.</p><h4>The Meltdown Attack</h4><p>The <a href="https://meltdownattack.com/meltdown.pdf">Meltdown</a> attack breaks isolation, allowing a program to read the memory data of other programs running on the same computer.</p><p>Let&#39;s say you log in on your email client. After entering the username and password, their values are stored in memory until submitted to the server for verification. No other program, except the OS kernel, is typically allowed access to that memory entry.</p><p>The &quot;Meltdown attack&quot; managed to melt down that barrier and could read the password just by executing another very clever program.</p><p>There are two significant insights behind it.</p><p>The first insight is that the memory access instruction consists of two steps, which the CPU can execute in parallel as part of the &quot;out of order execution&quot; optimisation. One step is to fetch the actual memory value from the external memory bank and set it into a register. The other step is to check whether the caller can access that address. If it turns out that the access was illegal, the program will stop and roll back the transient execution that might have happened in parallel.</p><p>The critical detail to this attack&#39;s success is that the OOE engine will execute as many instructions in a sequence as possible. For example, suppose another instruction operates on the fetched memory value, like adding something to it. In that case, the CPU can execute it as part of the same out-of-order sequence in parallel with the access check.</p><p>The image below depicts how &quot;Processing of data&quot;, which is the value retrieved from memory, is started eagerly by the CPU when out-of-order execution is enabled.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*fWiqcm4ANiaebuyfq5MpVw.png" /><figcaption><a href="https://www.hitachi.com/hirt/publications/hirt-pub18001/">https://www.hitachi.com/hirt/publications/hirt-pub18001/</a></figcaption></figure><p>To leak the illegal value, the attackers must find an operation that somehow writes the value to a place which is not erased as soon as the CPU finds out about the illegal access. They must leak the data using a &quot;<a href="https://en.wikipedia.org/wiki/Side-channel_attack">side channel</a>&quot; because Intel&#39;s engineers closed all direct avenues.</p><p>The second insight was that if a program accesses an address from its memory space, that value is cached, and the next time the program requests it, it will receive it much quicker. A program can thus infer which addresses were previously cached by requesting various addresses and then measuring how long it takes to receive a response. The side channel is the time it takes to access a memory address, where the address itself must be derived from the value that must be leaked.</p><p><em>Note that the cached value is discarded; what matters is the address and the time it takes to fetch the data at that address</em>. <em>The attackers sneak information out encoded in the address.</em></p><p>This technique is called a &quot;Flush+Reload&quot; cache attack.</p><p>To put it together, the meltdown attack makes a memory request to the physical address where the password is stored. This is illegal, but because of the OOE, the attacker can quickly perform transient actions on the password, racing with the access check.</p><p>The next step in the data-fetching sequence is to immediately take one byte from the password and make a memory request for an element found in a &quot;probe array&quot; at that position. For example, if the first byte of the password is &quot;0x07&quot;, the instruction will request &quot;arr[7]&quot;, which the CPU will fetch and cache.</p><p>When &quot;arr[7]&quot; is returned, the access check will catch up and revert everything. This is ok because the array element was irrelevant.</p><p>Then, in the last part, the program retrieves the leaked byte of the password. For that, it will measure the time it takes to access each of the 256 elements (one byte can encode 256 values) of that &quot;probe&quot; array. Given that this was an array it had just created, and the only access could have been performed during that out-of-order execution, it will find out that the first byte of the password is &quot;0x07&quot; because it received that memory address much quicker than the rest.</p><p>Note that the array has 256 elements, each equal to a page size on that CPU, usually 4 KB. This is needed so that each element is cached independently in a cache line.</p><p>All it has to do now is repeat the same process for every password byte or even for the entire memory space.</p><h4>The Spectre attack</h4><p><a href="https://spectreattack.com/spectre.pdf">Spectre</a> is a more sophisticated attack that exploits &quot;speculative execution&quot;, the other major performance optimisation performed at runtime.</p><p>Speculative execution is implemented by the &quot;<a href="https://en.wikipedia.org/wiki/Branch_predictor">Branch Prediction Unit</a>&quot; (BPU), a hardware unit in the CPU shared by all programs. To simplify, it contains logic that maps source to target addresses based on the likelihood that execution will jump between them. It&#39;s a shortcut for the CPU that says: &quot;when a program reaches address `0x123…`, it usually jumps to address `0xabc…`&quot;.</p><p>Note: &quot;Jumping to an address&quot; is another way of saying that the CPU will continue executing the instructions found at that address.</p><p>If the CPU has spare capacity and reaches address `0x123`, it will carry on and execute the instructions at `0xabc` instead of staying idle. If it turns out the prediction was correct, then by the time it receives the confirmation, it will already have the result. On the other hand, if it turns out it was wrong, then that execution is discarded and rolled back.</p><p>The insight of the attack is that a program on the same computer can &quot;poison&quot; the branch predictor by repeatedly feeding it with carefully chosen addresses.</p><p><strong><em>This gives the attacker the power to transiently execute any snippet of code already existing in the victim program, but with inputs it partially controls.</em></strong></p><p>For this to be useful, the snippet has to perform some side effects that can be exfiltrated via a side channel. For example, if the program contains a sequence of instructions that request memory access based on an input controlled by the attacker, then the Flush+Reload technique can be used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*YxUcWSHtwuuyXOj2l9mhmw.png" /><figcaption>copyright Zecheng He</figcaption></figure><blockquote>The speculative execution window is marked by the red dotted block. “Branch resolution” marks the completion of the delayed authorization, initiated by the conditional or indirect branch instruction. “Load S” (secretaccessing) and “Load R” (secret-sending) are unauthorized memory accesses if they bypass “Branch resolution” (softwaredefined authorization). See <a href="https://www.researchgate.net/publication/344294360_New_Models_for_Understanding_and_Reasoning_about_Speculative_Execution_Attacks">paper</a>.</blockquote><p>With Meltdown, the attacker can write a program that reads another program&#39;s data. Spectre is different because the attacker must find useful code snippets in an existing program (the &quot;gadgets&quot;) and poison the BPU to execute them transiently.</p><p>To recap, the attacker must find a branching instruction in the code where some secret is loaded in a registry and then poison the branch predictor to jump to an address with instructions that make a memory request to an address based on the secret. It doesn&#39;t matter if this access is illegal because it will be cached anyway and can be retrieved using Flush+Reload.</p><h3>Conclusion</h3><p>The commercial pressure to make CPUs faster, cheaper and less power-hungry have determined manufacturers to become more creative and aggressive with performance optimisations. However, these changes have increased complexity, making the attack surface larger, especially when combining these features.</p><p>The first attacks to exploit this complexity, Meltdown and Spectre, have opened up the space for an entire class of similar attacks, which became ever more sophisticated. CPU manufacturers responded with a renewed focus on security but at the expense of performance.</p><p>In the last part of the series, we’ll understand how SGX was affected by this wave of attacks. Spoiler alert, given that SGX programs are just normal programs running with extra restrictions, the attacks had to become even more sophisticated and creative. You will see that “breaking an enclave” is not that different from breaking the isolation between VMs running in the cloud, and CPU manufacturers will immediately address these vulnerabilities.</p><h3>The “Demystifying SGX” Series</h3><p>In <a href="https://medium.com/obscuro-labs/intel-sgx-demystified-757a242682a3">part 1</a>, we look at the hardware features behind SGX.<br>In <a href="https://medium.com/obscuro-labs/intel-sgx-demystified-part-2-understanding-cpus-and-their-vulnerabilities-cea9754bd755">part 2</a>, we look at the features that make CPUs fast, and how they can be exploited.<br>In <a href="https://medium.com/obscuro-labs/demystifying-sgx-part-3-the-enclave-program-81949a4fe0c6">part 3</a>, we look at the architecture of an SGX enclave, then explore how the program is executed and even build a simple program.<br>In <a href="https://medium.com/obscuro-labs/demystifying-sgx-part-4-secure-hardware-59cd09687d53">part 4</a>, we look at real-life applications of secure hardware.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cea9754bd755" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intel SGX demystified]]></title>
            <link>https://medium.com/@tudor.malene/intel-sgx-demystified-757a242682a3?source=rss-960132f36c3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/757a242682a3</guid>
            <category><![CDATA[intel]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[confidential-computing]]></category>
            <category><![CDATA[sgx]]></category>
            <category><![CDATA[trusted-execution]]></category>
            <dc:creator><![CDATA[Tudor Malene]]></dc:creator>
            <pubDate>Mon, 06 Mar 2023 09:38:43 GMT</pubDate>
            <atom:updated>2026-03-30T08:12:16.069Z</atom:updated>
            <content:encoded><![CDATA[<h3>Demystifying SGX — Part 1</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*ZXWfEdiSbn_cU2rW.jpg" /><figcaption>intel.com</figcaption></figure><p>When I started reading about <a href="https://en.wikipedia.org/wiki/Software_Guard_Extensions">Intel SGX</a> a few years ago, I felt intimidated.</p><p>On the one hand, there was a lot of scary-sounding <a href="https://sgx101.gitbook.io/sgx101/sgx-bootstrap/attestation">terminology</a>; on the other hand, the results seemed magic.</p><p>In this article, I will break it down into non-scary concepts, something which would have helped past-me get a head start.</p><p>Before putting it all together, we&#39;ll look at the evolution of the relevant <a href="https://en.wikipedia.org/wiki/Central_processing_unit">CPU </a>features that made SGX possible and how cryptography was added to the mix. The key to the mystery is multitasking.</p><p><em>Note: This article assumes some basic knowledge of computer architecture.</em></p><h3>Multitasking</h3><p>Early CPUs, like the <a href="https://en.wikipedia.org/wiki/Intel_8086">8086</a>, had a simple architecture without built-in support for running multiple programs simultaneously.</p><p>For example, when executing a &quot;.COM&quot; or &quot;.EXE&quot; program, the <a href="https://en.wikipedia.org/wiki/DOS">DOS</a> <a href="https://en.wikipedia.org/wiki/Operating_system">operating system</a>(OS) running on an 8086 gave complete control to the program, which could remove the OS altogether.</p><p><a href="https://en.wikipedia.org/wiki/Windows_3.0">Windows 3.0</a> went a step further and achieved &quot;<a href="https://superuser.com/questions/726348/if-dos-is-single-tasking-how-was-multitasking-possible-in-old-version-of-window">cooperative multitasking</a>&quot;. Programs written this way had to explicitly pause themselves and yield control to the OS, which could run another program. This approach has obvious problems, like one faulty program can cause the entire system to hang. It also places a lot of burden on the application developers.</p><p>The breakthrough for the <a href="https://en.wikipedia.org/wiki/Wintel">PC</a> came with the <a href="https://en.wikipedia.org/wiki/Intel_80286">80286</a>, which added the &quot;<a href="https://en.wikipedia.org/wiki/Protected_mode">Protected mode</a>&quot;, designed to give more control to the OSs over application software. &quot;Protected mode&quot; included &quot;virtual memory&quot; and &quot;safe multitasking&quot;, which enabled OSs to implement &quot;<a href="https://en.wikipedia.org/wiki/Preemption_(computing)">preemptive multitasking</a>&quot;, used to this day by virtually all computer systems. The main difference from &quot;collaborative multitasking&quot; is that the OS can interrupt programs anytime and resume another program without either of them being aware. As a result, multitasking is no longer a concern of the programs.</p><p>To understand SGX, it&#39;s worth zooming in on how programs are executed in this model.</p><h4>Preemptive multitasking</h4><p>Programs start life as a set of instructions loaded in the main memory. <a href="https://en.wikipedia.org/wiki/Instruction_set_architecture">Instructions</a> are either <a href="https://en.wikipedia.org/wiki/Adder_(electronics)">executed directly in hardware</a>, for example, adding the numbers found in two registers, or are &quot;<a href="https://en.wikipedia.org/wiki/Microcode">microcodes</a>&quot;, which translate into a sequence of simpler instructions which eventually end up executed in hardware.</p><p><em>Note: By &quot;addition being executed directly in hardware&quot;, it means that those two registers are literally connected with various electronic circuits, one of them being able to add their values.</em></p><p>As the program executes, the various <a href="https://en.wikipedia.org/wiki/Processor_register">registers</a> in that CPU core will contain the current state. This includes the <a href="https://en.wikipedia.org/wiki/Program_counter">instruction pointer</a> (IP) containing the address to the next instruction. While executing, the program can request to read or write more data from memory or execute I/O operations.</p><p>The &quot;<a href="https://en.wikipedia.org/wiki/Scheduling_(computing)">scheduler</a>&quot; can decide that another program is more important at any point in time, so it wants to use the CPU to execute it. If the current program is not over, it must be resumed later. The solution is to take a snapshot of its state, meaning all registers are saved in a data structure and written to memory. Then, when it&#39;s time to execute the same program again, it just carries on from the snapshot, which loads into all the correct registers.</p><p>To recap, the state of the program at the moment it has been paused consists of all the data in memory plus the execution snapshot, also known as the &quot;<a href="https://en.wikipedia.org/wiki/Task_state_segment">Task State Segment</a>&quot; (TSS).</p><h4>Virtual Memory</h4><p>A prerequisite for &quot;preemptive multitasking&quot; is that each program must have its own &quot;<a href="https://en.wikipedia.org/wiki/Virtual_memory">virtual memory space</a>&quot;, which the OS must keep track of.</p><p>With this feature, each program can assume that it&#39;s running alone on a computer and has all available memory at its disposal. The OS is free to reorganise the physical memory to optimise it for the programs it is running, which includes writing a memory page to a &quot;<a href="https://en.wikipedia.org/wiki/Virtual_memory#Address_space_swapping">swap file</a>&quot; on the disk drive.</p><p>The &quot;protected mode&quot; of the 80286 was the first attempt to achieve this.</p><p>Eventually, the solution settled on using &quot;<a href="https://en.wikipedia.org/wiki/Virtual_memory#Paged_virtual_memory">Paged Virtual Memory</a>&quot;. The component responsible for mapping between the physical and virtual addresses and checking access rights is the &quot;<a href="https://en.wikipedia.org/wiki/Memory_management_unit">Memory Management Unit</a>&quot; (MMU). The first MMU appeared in the 80386 CPU.</p><h4>Access control</h4><p>The other prerequisite for &quot;preemptive multitasking&quot; is controlling access to resources. The OS must be able to efficiently isolate programs from each other and stop them if they are trying to access resources illegally. If a program could remove the OS, multitasking would no longer be possible.</p><p>The &quot;protected mode&quot; of the 80286 introduced four privilege levels or &quot;<a href="https://en.wikipedia.org/wiki/Protection_ring">Rings</a>&quot;. Ring 0 is the most privileged, where the <a href="https://en.wikipedia.org/wiki/Kernel_(operating_system)">OS Kernel</a> runs, also called the &quot;Supervisor mode&quot;. User applications typically run at Ring 3, or &quot;User mode&quot;.</p><p>When the OS crashes, all user programs will stop. When a user program crashes, nothing else should be affected. Also, some instructions can only be called by programs running in Ring 0, and programs with lower privileges cannot access some resources.</p><p>A process can access more privileged resources only through special functions that the OS controls called &quot;<a href="https://en.wikipedia.org/wiki/Call_gate_(Intel)">call gates</a>&quot;. This mechanism has evolved and is now called &quot;system calls&quot; or &quot;<a href="https://en.wikipedia.org/wiki/System_call">syscalls</a>&quot;.</p><p>This Ring based mechanism ultimately gives control to the <a href="https://en.wikipedia.org/wiki/Kernel_(operating_system)">kernel</a> to set up a sandbox for user programs. Everything a &quot;user mode&quot; program does has to go through the kernel and is restricted. It can&#39;t directly perform I/O operations, allocate memory, play sounds, or even display something on the screen. When the program closes, all resources are automatically freed by the kernel.</p><p>In the <a href="https://en.wikipedia.org/wiki/Windows_95">Windows 95</a> days, user programs routinely crashed the entire system. This was because the <a href="https://retrocomputing.stackexchange.com/questions/11878/why-did-windows-95-crash-the-whole-system-but-newer-windows-only-crashed-program">sandboxing was leaky</a> for backwards compatibility reasons.</p><p>To recap, the MMU limits a program to only accessing or modifying its own memory address space. In addition, the &quot;Rings&quot; model, when used properly by the kernel, prevents it from directly manipulating other resources like hardware devices.</p><h4>Virtualisation</h4><p>Years went by, and <a href="https://en.wikipedia.org/wiki/Virtual_machine">virtual machines</a> (VMs) started appearing. VMs are &quot;virtualised&quot; computers which run an OS. This highlights an immediate dilemma. Before VMs, the OS ran at Ring 0, where it could control all resources, which is no longer a valid assumption for a &quot;Guest OS&quot;.</p><p>The initial solution was &quot;Software Virtualisation&quot;, and it used techniques such as &quot;<a href="https://en.wikipedia.org/wiki/Binary_translation">binary translation</a>&quot;, which means that the &quot;Ring 0&quot; instructions were replaced before execution.</p><p>A &quot;Host OS&quot; is running at Ring 0 and is also known as a &quot;<a href="https://en.wikipedia.org/wiki/Hypervisor">Hypervisor</a>&quot; or &quot;Virtual Machine Monitor&quot; (VMM).</p><p>The Pentium 4 CPU saw the introduction of &quot;<a href="https://en.wikipedia.org/wiki/Hardware-assisted_virtualization">Hardware-assisted virtualisation</a>&quot; (Intel VT). This means there are now special instructions supported by the CPU and dedicated circuits that perform these translations more efficiently.</p><h3>Evolution of trust</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ppA1Cu8f-BueYOoV.jpg" /><figcaption><a href="http://www.roffeypark.ac.uk/">www.roffeypark.ac.uk</a></figcaption></figure><p>To finally understand SGX and put all the pieces together, we need to consider how trust evolved.</p><p>In the 8086/DOS days, all the software running on the computer was equally trusted and had full access to all resources.</p><p>Then it became apparent that software like the OS is more likely to be properly tested and behave as a user would expect, compared to random software installed from a floppy disk found in a magazine. So OS developers, in tandem with CPU manufacturers, came up with solutions, and today&#39;s computers are extremely stable.</p><p>Then, with the spread of virtual machines, it turned out that not even OSs are trustworthy and that there should be a trusted &quot;hypervisor&quot; to look after them and ensure they don&#39;t leak data to each other. This enabled cloud providers to service many users on much fewer physical machines. The users, who rent VMs in the cloud, generally trust the cloud providers to keep their data safe and not tamper with the computations.</p><h4>Trust no one (except your own circuits)</h4><p>Let&#39;s consider trust from the point of view of a chip manufacturer like Intel, which is building the CPU, a very complex circuit enclosed in a protective casing. Then we&#39;ll analyse how Intel can export that trust and make it a general-purpose primitive.</p><p>The CPU is added to a computer connected to peripherals where it is running software, all created by third parties. For example, it relies intimately on the &quot;<a href="https://en.wikipedia.org/wiki/Dynamic_random-access_memory">Memory Chip</a>&quot; to store data at an address and make it available for reading later. The CPU cannot calculate correct results if the memory chip malfunctions. In addition, a faulty chip can corrupt the instructions in the program itself, which also live in memory.</p><p>The question is: &quot;<strong><em>What can I do, as a chip manufacturer, to guarantee the correct functioning of my device alone?</em></strong>&quot;.</p><p>Since the early days, CPUs and OSs have steadily descended into paranoia. The CPU has now reached the final stage, where it considers that everything is an adversary that threatens and watches it.</p><p><strong>In this new world, a program running on a CPU cannot be tampered with even when the attacker controls the memory chip. Furthermore, no other process running on that CPU, including the OS, the hypervisor or the physical owner connecting measurement devices to the CPU pins, can read the internal state of that program. And finally, a program can prove to anyone that it is running in this way so that any results are authentic.</strong></p><p>These are the requirements for Intel SGX.</p><h3>Cryptography</h3><p>The last piece of the puzzle is cryptography.</p><p>Let&#39;s rephrase the high-level requirements stated above using cryptographic primitives.</p><h4><a href="https://en.wikipedia.org/wiki/Authenticated_encryption">Authenticated encryption</a> of the memory</h4><p>If the memory chip was part of the CPU enclosing, it could be trusted not to tamper with the data or leak information. However, since it is not, the CPU must encrypt and authenticate the data it sends to the memory chips. This way, it can detect if the data it requests has been tampered with and simultaneously hide the program&#39;s internal state.</p><p>CPUS already have a circuit through which all memory access is performed. Therefore, this requirement can be implemented by extending the MMU with a &quot;<a href="https://eprint.iacr.org/2016/204.pdf">Memory Encryption Engine</a>&quot; (MEE), which can perform real-time authenticated encryption and decryption.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lc1nPHJ8gH2BR_qm5QgvfA.png" /><figcaption><a href="https://eprint.iacr.org/2016/204.pdf">https://eprint.iacr.org/2016/204.pdf</a></figcaption></figure><p><strong>Assuming that each process has some unique encryption key, then the MEE, a trusted circuit in the CPU, can guarantee that any data it loads into the internal circuits is authentic and could not have been read in plaintext form by anyone else. This step is entirely transparent to the rest of the CPU, which can function normally.</strong></p><p>The encryption is quite <a href="https://security.stackexchange.com/questions/136993/intel-sgx-details">complex</a> and is done with volatile keys that are erased once the computer is powered down.</p><p><em>When you read about &quot;encrypted enclaves&quot;, it actually means that there is an encryption layer between the CPU, which functions normally, and the memory chips.</em></p><h4><strong>Authenticating the Microcode</strong></h4><p>Intel can trust the hardware it produces. But, an equally important CPU component is the <a href="https://en.wikipedia.org/wiki/Microcode">Microcode</a>, which implements the complex instructions a CPU executes.</p><p>The microcode must be <a href="https://www.intel.com/content/www/us/en/developer/articles/technical/software-security-guidance/best-practices/microcode-update-guidance.html">upgradeable</a> because, like any software, it can contain bugs. Therefore, for Intel to always be able to trust the hardware plus software package, it needs to ensure that only approved code can be loaded into the CPU.</p><p>To achieve this requirement, each CPU has a <a href="https://www.cisoplatform.com/profiles/blogs/intel-s-secret-key-to-decrypt-microcode-patches-is-exposed">key</a> inside it used to decrypt the update file. Intel owns the corresponding key used for encrypting new versions.</p><p>When researchers recently found <a href="https://aepicleak.com/">vulnerabilities</a> in SGX, Intel was able to fix them by pushing an <a href="https://www.intel.com/content/www/us/en/developer/articles/technical/software-security-guidance/advisory-guidance/stale-data-read-from-xapic.html">update</a>.</p><h4>Attestation</h4><p>The most complex aspect of Intel SGX is the &quot;<a href="https://sgx101.gitbook.io/sgx101/sgx-bootstrap/attestation">Attestation</a>&quot; process, which is the missing ingredient to the problem of proving that a program inside a specific CPU calculated a payload in complete privacy and isolation.</p><p><strong>From a high level, this is a problem of establishing a trust chain from the payload to Intel. As long as the users, or the consumers of the service, trust Intel, they should be convinced of all the guarantees and that the program ran precisely as expected.</strong></p><p>One of Intels&#39; guarantees is that they cannot read or tamper with the data calculated on their CPUs.</p><p><em>Note: If you&#39;re having doubts about trusting a private company, remember that this model is similar to what forms the basis of </em><a href="https://en.wikipedia.org/wiki/HTTPS"><em>HTTPS</em></a><em>, which secures all internet traffic. Web browsers, and implicitly their users, trust private companies known as </em><a href="https://en.wikipedia.org/wiki/Certificate_authority"><em>Certificate authorities</em></a><em> (CA) not to issue certificates for a domain without an explicit request from the owner. For example, a rogue or hacked CA could generate a certificate for &quot;www.mydomain.com&quot;, and then, if they are also able to trick the DNS on the victim&#39;s computer, they can </em><a href="https://en.wikipedia.org/wiki/Man-in-the-middle_attack"><em>man-in-the-middle</em></a><em> (MITM) the </em><a href="https://en.wikipedia.org/wiki/DigiNotar"><em>traffic</em></a><em> to &quot;mydomain.com&quot;. The CAs don’t do this because their reputation is at stake. This practical combination of cryptography and reputation has revolutionised internet security. A corporation like Intel has a </em><a href="https://companiesmarketcap.com/intel/marketcap/"><em>lot of reputation</em></a><em> to defend.</em></p><p>Conceptually, an attested payload must be signed by a key bound to the program and the CPU where it was produced.</p><p>The first step is for the trusted CPU to calculate a cryptographic hash of the program. This is called &quot;<a href="https://www.intel.com/content/www/us/en/developer/articles/technical/introduction-to-intel-sgx-sealing.html">the measurement</a>&quot;, and this value is added to a special register called &quot;MRENCLAVE&quot;, where &quot;MR&quot; stands for &quot;measurement&quot;.</p><p>To prove that a payload originated inside a specific CPU, Intel <a href="https://sgx101.gitbook.io/sgx101/sgx-bootstrap/attestation#root-provisioning-key-rpk">burns</a> private keys into each CPU, which it uses to sign over the &quot;MRENCLAVE&quot; (and the microcode version). This signed report is called &quot;<a href="https://sgx101.gitbook.io/sgx101/sgx-bootstrap/attestation#quoting-enclave-qe">The Quote&quot;</a>.</p><p>This quote is then submitted to an Intel-provided service, the &quot;<a href="https://sgx101.gitbook.io/sgx101/sgx-bootstrap/attestation#there-are-mainly-three-platforms-involved-in-remote-attestation">Intel Attestation Service</a>&quot; (IAS), that checks that the signing key corresponds to a CPU it created. The service can also check whether the CPU and microcode version installed on it is known to have any vulnerabilities. If all checks pass, &quot;the quote&quot; is returned signed by Intels&#39; well-known public key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/0*_U_Oui9I6iPlpPtv" /><figcaption><a href="https://sgx101.gitbook.io/sgx101/sgx-bootstrap/attestation">https://sgx101.gitbook.io/sgx101/sgx-bootstrap/attestation</a></figcaption></figure><p>A person or software inspecting a recently signed quote can assert that a program with the hash &quot;H&quot; (aka &quot;the enclave&quot;) was loaded inside a CPU considered secure by Intel.</p><p>The quote will also contain a key which, by construction, can only be known to the program with the hash &quot;H&quot; running on that CPU. A <a href="https://en.wikipedia.org/wiki/Chain_of_trust">chain of trust</a> all the way to Intel thus guarantees any payload signed by this key.</p><p>The simplified description above shows that this chain of trust has different links like digital signatures, cryptographic hashes, encryption, and physical hardware security.</p><h3>Putting it all together</h3><p>Intel CPUs already had security primitives designed to isolate programs from each other such as the &quot;Ring&quot; model for executing instructions and the Memory Management Unit. These were designed to allow operating systems to execute untrusted programs safely and later to enable hypervisors to run multiple untrusted VMs.</p><p>Adding cryptographic components such as the Memory Encryption Engine enabled a CPU to function as a &quot;Trusted Execution Environment&quot; (TEE). The Attestation protocol designed on top of these primitives creates a trust chain from Intel to virtually any program output. Intel assumes a role similar to a web &quot;Certificate Authority&quot;, with the difference that it certifies computation results and not just identities.</p><p>I hope this perspective shows that &quot;secure enclaves&quot; are not some special magic chip protected by machine guns where data is processed encrypted.<br>It is more boring than that. It is merely another iteration in the decades-long journey to add security features on top of existing processing circuits.</p><h4><em>Final note</em></h4><p><em>To illustrate the main point, I had to simplify severely, like ignoring other CPU manufacturers, sacrificing accuracy, or boiling down extremely complex topics into a short line.</em></p><h3>The “Demystifying SGX” Series</h3><p>In <a href="https://medium.com/obscuro-labs/intel-sgx-demystified-757a242682a3">part 1</a>, we look at the hardware features behind SGX.<br>In <a href="https://medium.com/obscuro-labs/intel-sgx-demystified-part-2-understanding-cpus-and-their-vulnerabilities-cea9754bd755">part 2</a>, we look at the features that make CPUs fast, and how they can be exploited.<br>In <a href="https://medium.com/obscuro-labs/demystifying-sgx-part-3-the-enclave-program-81949a4fe0c6">part 3</a>, we look at the architecture of an SGX enclave, then explore how the program is executed and even build a simple program.<br>In <a href="https://medium.com/obscuro-labs/demystifying-sgx-part-4-secure-hardware-59cd09687d53">part 4</a>, we look at real-life applications of secure hardware.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=757a242682a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>