<?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 polarply on Medium]]></title>
        <description><![CDATA[Stories by polarply on Medium]]></description>
        <link>https://medium.com/@polarply?source=rss-9047f2114317------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*VOfWBIFV3RiL_lJNcqihIg.png</url>
            <title>Stories by polarply on Medium</title>
            <link>https://medium.com/@polarply?source=rss-9047f2114317------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 15:00:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@polarply/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[The GMX Unstaking Leech]]></title>
            <link>https://polarply.medium.com/the-gmx-unstaking-leech-d6c7fdd1459c?source=rss-9047f2114317------2</link>
            <guid isPermaLink="false">https://medium.com/p/d6c7fdd1459c</guid>
            <category><![CDATA[mev]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <dc:creator><![CDATA[polarply]]></dc:creator>
            <pubDate>Wed, 28 Sep 2022 08:05:40 GMT</pubDate>
            <atom:updated>2022-09-28T08:05:40.354Z</atom:updated>
            <content:encoded><![CDATA[<p>GMX is a decentralized perpetual exchange, an important service for crypto trading.</p><p>As part of its platform, GMX allows their native token, GMX, to be staked to receive ETH from a pool consisting of 30% of trading fees generated by the exchange. Currently the default APY is projected at ~18%.</p><p>As part of their tokenomics, staked coins <a href="https://gmxio.gitbook.io/gmx/rewards#multiplier-points">accrue bonus APY</a>:<br>When you stake GMX, you receive Multiplier Points every second at a fixed rate of 100% APR.</p><p>That means 1000 GMX staked for one year would earn 1000 Multiplier Points, so within a year it is as if you would stake 2000 GMX.</p><p>However, to disincentivize unstaking, users that unstake have their bonus burned.</p><p>When a user unstakes they are presented with 3 options: stake again starting with 0 bonus, just hold, or sell their coins. The first option is improbable, and the 2nd option also sounds unlikely. From a naive user’s perspective, why not postpone burning the bonus and stake some more until they really want to sell? <br>Therefore we can deduce that should a user unstake, it is very probable they will proceed to sell their coins.</p><p>I checked the Arbitrum blockchain and analyzed users’ actions after unstaking and found that as burned APY is higher, so is the user’s chance to sell their coins right after:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/0*C9PV_FcOjbeu4hCX" /></figure><p>That is, for a user with burned APY higher than 60%, there’s a &gt;70% chance of selling the coins within 5 minutes of unstaking.</p><p>Using this information one could build a probabilistic sandwich bot.. except I found <a href="https://arbiscan.io/address/0xa2d60b38a6ee00e424a261b87ae220a6168be87f">there already is one</a>!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/0*XhGBZMNKoy7b3xuu" /></figure><p>This MeV strategy sandwiches high volume unstaking actions, selling right after they unstake and buying back after they sell.</p><p>Using this strategy they’ve generated 55 GMX (2270$) in 45 days.</p><p>Example:</p><p>A. User 0xd33 <a href="https://arbiscan.io/tx/0x975626bf62c89c6b02719b424b5a7e7151d8053373502ab19ee09a6f44efb232">unstakes 5,124 GMX</a> ($212,600)<br>B. 1 seconds later: MeV bot <a href="https://arbiscan.io/tx/0xbf3659d7e9df16a12279c5cd822523018e68562ba5f643f67d36a91aabd0ed53">sells 399.00 GMX</a> ($16,550)<br>C. 8 minutes later: User 0xd33 <a href="https://arbiscan.io/tx/0xfb47ae9b98f7d92e48283514cf9a12edbc08cc3b681d5b0d5a21f25ceb866eda">sells their 5,124 GMX</a> on Uniswap<br>D. 15 minutes later: MeV bot <a href="https://arbiscan.io/tx/0x466d9390a625f0b46f1af9132b3422b4fbd4609413845a4f7bee3770c993c7fd">buys back 400.43 GMX</a> for the same price ($16,550)</p><p>This strategy is probabilistically profitable as can be seen by the unstaking probability graph shown above, and is most efficient with large unstakers as they create the largest sandwich opportunity.</p><p>While now this problem is minor, should GMX be more widely adopted these attacks may become more common and extract higher value.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6c7fdd1459c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The False Oracle — Azure Functions Padding Oracle Issue]]></title>
            <link>https://polarply.medium.com/the-false-oracle-azure-functions-padding-oracle-issue-2025e0e6b8a?source=rss-9047f2114317------2</link>
            <guid isPermaLink="false">https://medium.com/p/2025e0e6b8a</guid>
            <category><![CDATA[padding-oracle]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[polarply]]></dc:creator>
            <pubDate>Wed, 28 Apr 2021 15:04:53 GMT</pubDate>
            <atom:updated>2021-04-28T15:04:53.845Z</atom:updated>
            <content:encoded><![CDATA[<h3>The False Oracle — Azure Functions Padding Oracle Issue</h3><h3><strong>Introduction</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/0*blPJYNjsIX9MtAx5" /></figure><p>In this blog I present two vulnerabilities I found in the Azure Functions and another very interesting case of a padding oracle, available as an undocumented HTTP endpoint on every Function instance. Initially I was ecstatic about this finding as theoretically it would have allowed me to achieve remote code execution over arbitrary Azure Functions. However, in a twist of irony, an implementation bug in Microsoft’s Cryptography codebase made this oracle dysfunctional (a false oracle!) and I could not achieve RCE.</p><p>The first vulnerability allowed an attacker with code execution over a Function to escalate privileges by installing a permanent backdoor on the Function. The second bug allowed downloading encrypted Function configurations that did not belong to me. Chaining this bug with a padding oracle would’ve allowed me to decrypt configurations of other users and result in RCE however we shall see why this was not the case.</p><p>Both vulnerabilities were reported to MSRC and are now fixed, and the padding oracle issue was brought to Microsoft’s attention however as it wasn’t functioning they saw no need to fix it.</p><h3><strong>Overview</strong></h3><p>On my <a href="https://www.intezer.com/blog/research/how-we-escaped-docker-in-azure-functions/">previous Function Docker Escape post</a> published in Intezer’s website, I described how I set up Azure Function so I could investigate its environment. In a nutshell, I hosted a reverse shell over the Function environment. After publishing that research, I continued exploring the Function environment and I noticed interesting environment variables such as <em>CONTAINER_START_CONTEXT_SAS_URI</em> which linked to a file in the <em>azcontainers</em> blob storage belonging to <em>wawstorageproddm1157</em> — a storage account belonging to Microsoft.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/0*Hb0vuWFQ0wlQKCrc" /></figure><p>There are two interesting things here:</p><ol><li>An attacker with code execution on an Azure Function is able to escalate privileges using the <em>SCM_RUN_FROM_PACKAGE</em> environment variable. This URL redirected to the Azure Function package but its SAS token had a ‘write’ permission (marked in blue), meaning it can be used to overwrite the Azure Function package. This meant an would have been able to overwrite the Function code package with their own code (Escalation of Privileges). If done thoughtfully, the user would not have noticed this change and the attacker would have been able to plant a backdoor which would have run in every Function invocation. This is the first vulnerability.</li><li>The Azure Function had access to a storage blob belonging to ‘<em>wasstorageproddm1157</em>’ storage account, which belongs to Microsoft (marked in red).</li></ol><p>Accessing this URL showed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/0*m46LfEdnyiJtjUTD" /></figure><p>This was an encrypted version of the configuration file used to initialize the Azure Function.</p><p>The <em>CONTAINER_ENCRYPTION_KEY</em> environment variable was used to decrypt this blob (using AES-256):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/0*zjcReCX86haofliU" /></figure><p>The configuration held many interesting keys, such as <em>SCM_RUN_FROM_PACKAGE</em> that we saw earlier. Furthermore, the configuration file also contained Secrets related to the Function managed identity, allowing to spoof the Function identity outside of that Function.</p><p>I extracted the SAS token from the URL and using the Azure CLI, tried to query the <em>azcontainers </em>blob storage. To my surprise, I was able to list Azure Function’s configurations not belonging to me:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/0*VZdXev43qGocQVdn" /></figure><p>Querying <em>azcontainers</em>, each “name” field is a different configuration file</p><p>The token also enabled me to download these configurations, however they were no use to us in their encrypted form so this had no practical impact.</p><p>However, recall that in the Azure Function Docker Escape blog, while reversing the Init Mesh binary we noticed the Mesh HTTP server was quite verbose. Interacting with this server required to pass an encrypted authentication token under the “<em>x-ms-site-restricted-token</em>” header, and would return a verbose error message when dealing with an invalid token. Specifically, it alerted if the token was malformed — specifically if it had incorrect padding. This behaviour is called a padding oracle, and with this single piece of information an attacker is able to completely decrypt passed encrypted messages.</p><p>Furthermore, we found this HTTP server was accessible from outside the Function via a public endpoint:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/0*V0ZGQ5Qk5RUiqBbe" /></figure><h3>Azure Padding Oracle</h3><p>If you are unfamiliar with Padding Oracle attacks, I suggest going over <a href="https://www.youtube.com/watch?v=aH4DENMN_O4">this</a> video, as it is too bit a lengthy subject for this blog post. However, in a nutshell, a padding oracle enables an attacker to decrypt <strong>any </strong>encrypted message passed to it provided it was encrypted with the matching key in the oracle server.</p><p>Further reversing the Init Mesh binary showed the authentication code tried to decrypt this header using the <em>CONTAINER_ENCRYPTION_KEY</em> env variable, and would authorize the request only if the decryption succeeded.</p><p>So to recap: by downloading an encrypted configuration and finding its matching Azure Function URL, I should be able to achieve remote code execution over it. I would pass the whole encrypted config as <em>x-ms-site-restricted-token </em>and decrypt it bit by bit using the padding oracle. Once I had the configuration, I would use the <em>SCM_RUN_FROM_PACKAGE </em>field to take over the Function similarly as described in the EoP vulnerability, and I would now be in control.</p><p>With a plan at hand, I tried mounting this attack on our own controlled server but the oracle was non-cooperative! It reported no errors when it I passed it a token with invalid padding:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/0*unCPjhNtgIJaukvo" /></figure><p>We were expecting the server to reply “Padding is invalid”</p><p>I checked the Init Mesh binary to explain this behavior and to my dismay I discovered that the unpadding algorithm was flawed and was broken. Reasonably, I initially assumed the padding algorithm was working as intended, and did not spend time reverse engineering it.</p><p>To better understand why it wasn’t working I reconstructed the unpad code:</p><pre>func init_server_pkg_encryption_pkcs7Unpad(data []byte) (byte[], error) {<br>  // Check that last byte isn’t zero<br>  if data[len(data)-1] != 0 {<br>    // Check that last byte is bigger than message total length<br>    data[len(data)-1] &gt; len(data) {<br>    return nil<br>    }<br>  }<br>  return fmt.Errorf(“Padding is invalid”)<br>}</pre><p>Compare this with a <a href="https://raw.githubusercontent.com/paultag/go-pkcs7/master/unpad.go">real unpad algorithm</a>:</p><pre>func Unpad(data []byte, blockSize uint) ([]byte, error) {<br>  if blockSize &lt; 1 {<br>    return nil, fmt.Errorf(“Block size looks wrong”)<br>  }</pre><pre>  if uint(len(data))%blockSize != 0 {<br>    return nil, fmt.Errorf(“Data isn’t aligned to blockSize”)<br>  }</pre><pre>  if len(data) == 0 {<br>    return nil, fmt.Errorf(“Data is empty”)<br>  }</pre><pre>  paddingLength := int(data[len(data)-1])<br>  for _, el := range data[len(data)-paddingLength:] {<br>    if el != byte(paddingLength) {<br>      return nil, fmt.Errorf(“Padding had malformed entries. Have ‘%x’, expected ‘%x’”, paddingLength, el)<br>    }<br>  }</pre><pre>  return data[:len(data)-paddingLength], nil<br>}</pre><p>Ironically, this bug rendered my exploit useless and I could not perform the attack. So in this case, two minuses made a plus.</p><h3><strong>Afterword</strong></h3><p>To summarize my findings, I discovered an escalation of privileges vulnerability in Linux Azure Function instances and information disclosure through being able to download arbitrary Functions’ encrypted configuration. I hoped to use the Padding Oracle to mount a crypto attack and decrypt this configuration, however I soon found out that the padding algorithm was flawed. The attack still required matching the oracle (the Function url) to its configuration which probably would have limited the impact of the attack should I have been successful.</p><p>These findings were reported to MSRC and they changed the scope of the SAS tokens so that apps cannot read encrypted configurations that do not belong to them. Furthermore, the permissive <em>rw</em> storage token (enabling EoP) was also restricted. As for the padding oracle, seeing as how the component was inoperative, the Azure security team decided not to make changes to it.</p><p>I hope you enjoyed the read!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2025e0e6b8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Blockfolio’s Long-Forgotten Github Token Leak]]></title>
            <link>https://polarply.medium.com/blockfolios-long-forgotten-github-token-leak-6cdc09e60929?source=rss-9047f2114317------2</link>
            <guid isPermaLink="false">https://medium.com/p/6cdc09e60929</guid>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[polarply]]></dc:creator>
            <pubDate>Fri, 01 May 2020 21:07:37 GMT</pubDate>
            <atom:updated>2020-05-01T21:07:37.055Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c-Zo_AXkX_Gc1ZUS6y56ew.png" /></figure><p>For more than 2 years, Blockfolio was vulnerable to any attacker stealing their source code and perhaps even injecting his own code into their repositories.<br>This is a quick write-up about how I was able to find a Github token to Blockfolio.</p><p>Blockfolio is the most popular Cryptocurrency price tracking app, with more than 1 million downloads on Android alone. They offer an interface to watch Cryptocurrency prices, set alerts for price movements and even monitor your portfolio (through inputting read-only exchange API keys).</p><p>I’ve been into Crypto coins for a little while now, and its common knowledge that using third party services can expose you to risks. Attackers want your coins and will abuse any attack surface available.</p><p>Very well, I secure my coins in an offline wallet, but my storage isn’t the only attack vector possible to target me.</p><p>I decided to review Cryptocurrency-related tools I use to test the security of these tools which can be used to target me. Blockfolio is the only Android app I am using for Crypto coins so it seemed like a good first target.</p><p>After some time reviewing their app to no avail, I took a look at older versions of the app to see if I can find any long-forgotten secret or hidden web endpoints. Soon I found this version from <a href="https://www.apkmirror.com/apk/blockfolio-inc/blockfolio-bitcoin-altcoin-app/blockfolio-bitcoin-altcoin-app-1-1-4-release/">2017</a> accessing Github’s api.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*waOi-YUkRB8gEGBfwBKQ0g.png" /></figure><p>It’s also appending a token to the authorization header:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*DF2uKhcugR6ETJhgtUudiQ.png" /></figure><p>The app is querying private Github repositories belonging to Blockfolio.<br>This was used to download its <em>frequently asked questions </em>(FAQ) directly from Github and displaying it to the user. A dynamic FAQ.</p><p>This is severe, but maybe it’s just some old token not in use anymore, from back when they launched. Lets verify:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/941/1*eR1u5fx_sTBVlzKQotIoow.png" /></figure><p>Nope, token’s still active, and has a “repo” OAuth Scope. <br>Github.com explains this scope:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*P6tPIjCVT4EGg07vAHZfrw.png" /></figure><p>I stopped digging further since I do not have permission to use the token and reached out to Blockfolio through DMs in social media (they do not have a bug bounty). The company blocked the token within 24 hours and replied that no access to its user data or infrastructure was made.</p><p>My suggestion to cryptocurrency users is to reduce cryptocurrency related third parties as much as possible. Do not install such applications that can execute code on your phone, use web services instead.</p><p>Stay safe everyone, both physically and virtually!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6cdc09e60929" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build your first LLVM Obfuscator]]></title>
            <link>https://polarply.medium.com/build-your-first-llvm-obfuscator-80d16583392b?source=rss-9047f2114317------2</link>
            <guid isPermaLink="false">https://medium.com/p/80d16583392b</guid>
            <category><![CDATA[obfuscation]]></category>
            <category><![CDATA[llvm]]></category>
            <dc:creator><![CDATA[polarply]]></dc:creator>
            <pubDate>Sat, 18 Apr 2020 15:13:29 GMT</pubDate>
            <atom:updated>2020-04-19T19:41:06.101Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to a tutorial on building your first LLVM based obfuscator! <br>In this post we will briefly present LLVM, discuss popular obfuscation approaches and their shortcomings and build our own epic LLVM-based string obfuscator.</p><p>All the code I present in this article is also available in <a href="https://github.com/tsarpaul/llvm-string-obfuscator">Github</a>.</p><p><strong>LLVM</strong></p><p>LLVM is a compiler framework built with the purpose of reducing time and cost of constructing new language compilers. With LLVM, all a language has to do is implement a “front-end” to LLVM. This means it needs to transform its code into LLVM Intermediate Representation (IR) code and LLVM will take care of all the ugly architecture/platform-specific machine code generation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/0*ruIvRn0Eldfontf_" /></figure><p>Popular compilers that are really just LLVM front-ends are Clang, rustc (Rust’s compiler) and Swift’s compiler.</p><p>LLVM offers a system for inserting optimization plugins which review Intermediate Representation and make changes to it.</p><p>This system offers exactly what we need for our purposes. We will register our obfuscator in the optimization pipeline illustrated above and have access to LLVM IR code.</p><p>LLVM’s biggest competitor, GCC also has a plugin system however it seemed less attractive. Modularity is a keystone in LLVM’s architecture, which makes it very convenient for us.</p><p><strong>Why obfuscate through bytecode?</strong></p><p>For the most part open-source obfuscation projects use macro-based techniques, eg:</p><pre>void SampleFiniteStateMachine()<br>{<br>  <strong>using</strong> <strong>namespace</strong> andrivet::ADVobfuscator::Machine1;</pre><pre>  OBFUSCATED_CALL0(FunctionToProtect);<br>  <strong>auto</strong> result = OBFUSCATED_CALL_RET(int, FunctionToProtectWithParameters, OBFUSCATED(“did”), OBFUSCATED(“again”));<br>  cout &lt;&lt; “Result: “ &lt;&lt; result &lt;&lt; endl;<br>}</pre><p><a href="https://github.com/andrivet/ADVobfuscator">https://github.com/andrivet/ADVobfuscator</a></p><p>Where OBFUSCATED_CALL0, OBFUSCATED are macros designed to inject the code obfuscation transformations for the former and string obfuscations for the latter.</p><p>While these projects enable authors to control exactly where their obfuscation schemes will apply, they taint the source-code and for larger projects they can become annoying to manage.</p><p>Another big drawback is that such tools won’t work with other languages since they use language-specific features.</p><p>Another less popular technique manipulates source-code directly before compiling, and while retaining the original source-code’s elegance it still lacks cross-language support.</p><p>Our obfuscator will work on a lower level — the common-ground for many languages, the LLVM bytecode. This will enable us to keep our source code clean while supporting multiple languages, without even being aware of the language we’ll be operating on.</p><p><strong>The Obfuscator</strong></p><p>To demonstrate LLVM’s power, we will implement a string obfuscator, which will encode every string in the binary with ROR-1.</p><p>First we register our plugin with LLVM’s optimizations pipeline:</p><pre><strong>extern</strong> “C” ::llvm::PassPluginLibraryInfo LLVM_ATTRIBUTE_WEAK<br>llvmGetPassPluginInfo() {<br>  <strong>return</strong> {<br>    LLVM_PLUGIN_API_VERSION, “StringObfuscatorPass”, “v0.1”, [](PassBuilder &amp;PB) {<br>      PB.registerPipelineParsingCallback([](StringRef Name, ModulePassManager &amp;MPM,<br>      ArrayRef&lt;PassBuilder::PipelineElement&gt;) {<br>        <strong>if</strong>(Name == “string-obfuscator-pass”){<br>          MPM.addPass(StringObfuscatorModPass());<br>          <strong>return</strong> true;<br>        }<br>        <strong>return</strong> false;<br>        }<br>      );<br>    }<br>  };<br>}</pre><p>LLVM allows registering optimizations (also known as passes) at different stages. You may register your pass to run on every module, function, block or even loop.</p><p>In LLVM, a module is a set of code that is processed together, e.g. a .cpp file. This is where we’ll register our plugin.</p><p>The plugin will activate when the “string-obfuscator-pass” keyword is passed to the optimizer.</p><p>We then define the plugin itself, which inherits the PassInfoMixin class:</p><pre><strong>struct</strong> StringObfuscatorModPass : <strong>public</strong> PassInfoMixin&lt;StringObfuscatorModPass&gt; {<br>  PreservedAnalyses run(Module &amp;M, ModuleAnalysisManager &amp;MAM) {</pre><pre><em>    // Transform the strings<br>    </em><strong>auto</strong> GlobalStrings = encodeGlobalStrings(M);</pre><pre><em>    // Inject functions<br>    </em>Function *DecodeFunc = createDecodeFunc(M);<br>    Function *DecodeStub = createDecodeStubFunc(M, GlobalStrings, DecodeFunc);</pre><pre><em>    // Inject a call to DecodeStub from main<br>    </em>Function *MainFunc = M.getFunction(“main”);<br>    createDecodeStubBlock(MainFunc, DecodeStub);</pre><pre><strong>    return</strong> PreservedAnalyses::all();<br>  };<br>};</pre><p>We only need to implement the <em>run</em> function which is called on every module.</p><p>Formalities aside, we can now dive right into the action.</p><p>We immediately iterate all the global strings and encode them. It’s important to note that all static strings are defined as globals, regardless of their scope (even if they’re confined to just one function).</p><pre>vector&lt;GlobalString*&gt; encodeGlobalStrings(Module&amp; M){<br>  vector&lt;GlobalString*&gt; GlobalStrings;<br>  <strong>for</strong>(GlobalVariable &amp;Glob : M.globals()) {<br>    <em>// Ignore external globals &amp; uninitialized globals.<br>    </em><strong>if</strong> (!Glob.hasInitializer() || Glob.hasExternalLinkage())<br>      <strong>continue</strong>;</pre><pre><em>  // Unwrap the global variable to receive its value<br>  </em><strong>Constant</strong> *Initializer = Glob.getInitializer();<br>  <br>  <em>// Check if its a string<br>  </em><strong>if</strong> (isa&lt;ConstantDataArray&gt;(Initializer)) {<br>    <strong>auto</strong> CDA = cast&lt;ConstantDataArray&gt;(Initializer);<br>    <strong>if</strong> (!CDA-&gt;isString())<br>      <strong>continue</strong>;<br>    <br>    <em>// Extract raw string<br>    </em>StringRef StrVal = CDA-&gt;getAsString();<br>    <strong>const</strong> char *Data = StrVal.begin();<br>    <strong>const</strong> int Size = StrVal.size();</pre><pre><em>    // Create encoded string variable (ROR1)<br>    </em>char *NewData = EncodeString(Data, Size);<br>    <strong>Constant</strong> *NewConst = ConstantDataArray::getString(Ctx, StringRef(NewData, Size), false);</pre><pre><em>    // Overwrite the global value<br>    </em>Glob.setInitializer(NewConst);<br>    GlobalStrings.push_back(<strong>new</strong> GlobalString(&amp;Glob));<br>    Glob.setConstant(false);<br>  }<br>…<br>  <strong>return</strong> GlobalStrings;<br>}</pre><p>Globals are implemented through the GlobalVariable class in LLVM.</p><p>The GlobalVariable class doesn’t actually hold the value of the global itself. You might have uninitialized globals because they point to an external definition, so the value itself is decoupled from the GlobalVariable class and is represented by the Constant class. We grab the value, make sure it’s a string and apply ROR1.</p><p>Now we need to start injecting logic into the binary to decode our strings during runtime.</p><p>To do this we need to implement a decode function and pass those strings we encoded to this function.</p><p>To this end, we’ll need to inject our own LLVM bytecode, but I’m no LLVM assembly expert so we’ll cheat.</p><p>First we build our decode function in C:</p><pre>void Decode(char *String){<br>  <strong>while</strong>(*String != ‘\x00’){<br>    *String -= 1;<br>     String++;<br>  }<br>}</pre><p>We then compile this to LLVM IR through Clang:</p><pre>$ clang -Os -shared -emit-llvm -c decode<strong>.</strong>c -o decode<strong>.</strong>bs &amp;&amp; llvm-dis &lt; decode.bs</pre><p>decode.bs IR disassembly:</p><pre><strong>define</strong> dso_local void @Decode(<strong>i8</strong>* <strong>nocapture</strong> %String) local_unnamed_addr #0 {<br><strong>entry:<br>  </strong>%0 = <strong>load</strong> <strong>i8</strong>, <strong>i8</strong>* %String, <strong>align</strong> 1, !tbaa !2<br>  %cmp6 = <strong>icmp</strong> <strong>eq</strong> <strong>i8</strong> %0, 0<br>  <strong>br</strong> <strong>i1</strong> %cmp6, label %while.end, label %while.body</pre><pre><strong>while.body:</strong> <em>; preds = %entry, %while.body<br>  </em>%1 = <strong>phi</strong> <strong>i8</strong> [ %2, %while.body ], [ %0, %entry ]<br>  %String.addr.07 = <strong>phi</strong> <strong>i8</strong>* [ %incdec.ptr, %while.body ], [ %String, %entry ]<br>  %sub = <strong>add</strong> <strong>i8</strong> %1, -1<br>  <strong>store</strong> <strong>i8</strong> %sub, <strong>i8</strong>* %String.addr.07, <strong>align</strong> 1, !tbaa !2<br>  %incdec.ptr = <strong>getelementptr</strong> <strong>inbounds</strong> <strong>i8</strong>, <strong>i8</strong>* %String.addr.07, <strong>i64</strong> 1<br>  %2 = <strong>load</strong> <strong>i8</strong>, <strong>i8</strong>* %incdec.ptr, <strong>align</strong> 1, !tbaa !2<br>  %cmp = <strong>icmp</strong> <strong>eq</strong> <strong>i8</strong> %2, 0<br>  <strong>br</strong> <strong>i1</strong> %cmp, label %while.end, label %while.body</pre><pre><strong>while.end:</strong> <em>; preds = %while.body, %entry<br>  </em><strong>ret</strong> void<br>}</pre><p>Using this IR dump we build our function manually:</p><pre>Function *createDecodeFunc(Module &amp;M){<br><strong>auto</strong> &amp;Ctx = M.getContext();</pre><pre><em>// Add Decode function<br></em>FunctionCallee DecodeFuncCallee = M.getOrInsertFunction(“decode”, <em>/*ret*/</em> Type::getVoidTy(Ctx), <em>/*args*/</em> Type::getInt8PtrTy(Ctx, 8));<br>Function *DecodeFunc = cast&lt;Function&gt;(DecodeFuncCallee.getCallee());<br>DecodeFunc-&gt;setCallingConv(CallingConv::C);</pre><pre><em>// Name DecodeFunc arguments<br></em>Function::arg_iterator Args = DecodeFunc-&gt;arg_begin();<br>Value *StrPtr = Args++;<br>StrPtr-&gt;setName(“StrPtr”);</pre><pre><em>// Create blocks<br></em>BasicBlock *BEntry = BasicBlock::Create(Ctx, “entry”, DecodeFunc);<br>BasicBlock *BWhileBody = BasicBlock::Create(Ctx, “while.body”, DecodeFunc);<br>BasicBlock *BWhileEnd = BasicBlock::Create(Ctx, “while.end”, DecodeFunc);</pre><pre><em>// Entry block<br></em>IRBuilder&lt;&gt; *Builder = <strong>new</strong> IRBuilder&lt;&gt;(BEntry);<br><strong>auto</strong> *var0 = Builder-&gt;CreateLoad(StrPtr, “var0”);<br><strong>auto</strong> *cmp6 = Builder-&gt;CreateICmpEQ(var0, Constant::getNullValue(Type::getInt8Ty(Ctx)), “cmp6”);<br>Builder-&gt;CreateCondBr(cmp6, BWhileEnd, BWhileBody);</pre><pre><em>// Preheader block<br></em>Builder = <strong>new</strong> IRBuilder&lt;&gt;(BWhileBody);<br>PHINode *var1 = Builder-&gt;CreatePHI(Type::getInt8Ty(Ctx), 2, “var1”);<br>PHINode *stringaddr07 = Builder-&gt;CreatePHI(Type::getInt8PtrTy(Ctx, 8), 2, “stringaddr07”);<br><strong>auto</strong> *sub = Builder-&gt;CreateSub(var1, ConstantInt::get(IntegerType::get(Ctx, 8), 1, true));<br>Builder-&gt;CreateStore(sub, stringaddr07);<br><strong>auto</strong> *incdecptr = Builder-&gt;CreateGEP(stringaddr07, ConstantInt::get(IntegerType::get(Ctx, 64), 1), “incdecptr”);<br><strong>auto</strong> *var2 = Builder-&gt;CreateLoad(incdecptr, “var2”);<br><strong>auto</strong> cmp = Builder-&gt;CreateICmpEQ(var2, ConstantInt::get(IntegerType::get(Ctx, 8), 0), “cmp”);<br>Builder-&gt;CreateCondBr(cmp, BWhileEnd, BWhileBody);<br>…</pre><p>EDIT: It was pointed out to me by <a href="https://twitter.com/0xrepnz">@0xrepnz</a> that you could probably use the llvm::parseIRFile() API to load the IR bytecode for a more elegant solution, thanks 0xrepnz!</p><p>Lets run a quick test and see how our optimization affects the file. We can see our new function, however nobody’s using it yet:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/0*SLoiSgZ6zm6ex1Bj" /></figure><p>Let’s put our new function in use then. We add another function which just calls the decode function on every string we transformed:</p><pre>Function *createDecodeStubFunc(Module &amp;M, vector&lt;GlobalString*&gt; &amp;GlobalStrings, Function *DecodeFunc){<br>  <strong>Context</strong> &amp;Ctx = M.getContext();<br>  <br>  <em>// Add DecodeStub function<br>  </em>FunctionCallee DecodeStubCallee = M.getOrInsertFunction(“decode_stub”, <em>/*ret*/</em> Type::getVoidTy(Ctx));<br>  Function *DecodeStubFunc = cast&lt;Function&gt;(DecodeStubCallee.getCallee());<br>  DecodeStubFunc-&gt;setCallingConv(CallingConv::C);</pre><pre><em>  // Create entry block<br>  </em>BasicBlock *BB = BasicBlock::Create(Ctx, “entry”, DecodeStubFunc);<br>  IRBuilder&lt;&gt; Builder(BB);</pre><pre><em>  // Add calls to decode every encoded global<br>  </em><strong>for</strong>(GlobalString *GlobString : GlobalStrings){<br>    <strong>if</strong>(GlobString-&gt;type == GlobString-&gt;SIMPLE_STRING_TYPE){<br>    <strong>auto</strong> *StrPtr = Builder.CreatePointerCast(GlobString-&gt;Glob, Type::getInt8PtrTy(Ctx, 8));<br>    Builder.CreateCall(DecodeFunc, {StrPtr});<br>  }<br>…<br>  return DecodeStubFunc;<br>}</pre><p>Beautiful:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/0*ymb9btPDbIH66ZQU" /></figure><p>We’re almost done, lets just inject the call to the decode stub in <em>main</em>:</p><pre>void createDecodeStubBlock(Function *F, Function *DecodeStubFunc){<br>  <strong>Context</strong> &amp;Ctx = F-&gt;getContext();<br>  BasicBlock &amp;EntryBlock = F-&gt;getEntryBlock();</pre><pre><em>  // Create new block<br>  </em>BasicBlock *NewBB = BasicBlock::Create(Ctx, “DecodeStub”, EntryBlock.getParent(), &amp;EntryBlock);<br>  IRBuilder&lt;&gt; Builder(NewBB);</pre><pre>  <em>// Call stub func instruction<br>  </em>Builder.CreateCall(DecodeStubFunc);</pre><pre>  <em>// Jump to original entry block<br>  </em>Builder.CreateBr(&amp;EntryBlock);<br>}</pre><pre>run(…){<br>…<br>Function *MainFunc = M.getFunction(“main”);<br>createDecodeStubBlock(MainFunc, DecodeStub);<br>…<br>}</pre><p>We can see that just a small call was added to the original main:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/0*-11Ws7SOttiXBY5b" /></figure><p>Finally, we return a status report to the LLVM Pass Manager:</p><pre>PreservedAnalyses run(Module &amp;M, ModuleAnalysisManager &amp;MAM) {<br>…<br>  <strong>return</strong> PreservedAnalyses::all();<br>}</pre><p>This simply means that we did not taint other passes’ results. This is important information for other passes, so they don’t need to be re-run.</p><p>I left instructions to compile the plugin in my repository. We can run the built plugin with LLVM’s optimizer <strong><em>opt</em></strong>:</p><pre># Create LLVM IR from C<br>$ clang -O3 -emit-llvm hello.c -c -o hello.bc</pre><pre># Run our plugin through the LLVM optimizer on the LLVM IR<br>$ opt -load-pass-plugin=/build/lib/LLVMStringObfuscator.so -passes=”string-obfuscator-pass” &lt; hello.bc -o out.bc</pre><pre># LLVM Static Compiler<br>$ llc out.bc -o out.s</pre><pre># Link with clang<br>$ clang -static out.s -o out</pre><pre># Profit<br>$ ./out</pre><p>We can view our output file’s disassembly to make sure our obfuscator works:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b2ilGXN_VwJ7tKczZKg5Sw.png" /></figure><p><strong>Summary</strong></p><p>This tutorial was an introduction to the potential of running obfuscations through LLVM. As LLVM becomes more mainstream this approach could become more popular.</p><p>You can take a look at a more serious approach for LLVM obfuscation at the link below, where the authors implemented more complex code obfuscation algorithms than our simple string obfuscation:<br>https://github.com/obfuscator-llvm/obfuscator/</p><p>Thanks for reading!</p><p><strong>References</strong></p><p><a href="https://lwn.net/Articles/582697/">https://lwn.net/Articles/582697/</a> — LLVM vs GCC</p><p><a href="https://llvm.org/docs/LangRef.html">https://llvm.org/docs/LangRef.html</a> — LLVM reference</p><p><a href="https://medium.com/@mshockwave/writing-llvm-pass-in-2018-preface-6b90fa67ae82">https://medium.com/@mshockwave/writing-llvm-pass-in-2018-preface-6b90fa67ae82</a> — Modern LLVM passes</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80d16583392b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>