<?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 Jacob Thompson on Medium]]></title>
        <description><![CDATA[Stories by Jacob Thompson on Medium]]></description>
        <link>https://medium.com/@jthompson_5338?source=rss-bfc8b10db590------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*OpDhnRD2XAEXzI4WfXMaIg.jpeg</url>
            <title>Stories by Jacob Thompson on Medium</title>
            <link>https://medium.com/@jthompson_5338?source=rss-bfc8b10db590------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 08:29:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jthompson_5338/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[Outsmarting Ransomware]]></title>
            <link>https://medium.com/independent-security-evaluators/outsmarting-ransomware-bb6bded2f68a?source=rss-bfc8b10db590------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb6bded2f68a</guid>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[malware]]></category>
            <category><![CDATA[crypto-ransomware]]></category>
            <category><![CDATA[ransomware]]></category>
            <dc:creator><![CDATA[Jacob Thompson]]></dc:creator>
            <pubDate>Wed, 14 Nov 2018 16:26:01 GMT</pubDate>
            <atom:updated>2018-11-14T16:26:01.306Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Recovering Supposedly-Encrypted Files Without the Key</strong></h4><h4><strong>Introduction</strong></h4><p>Handling incoming email is the scourge of any small business. Often receiving hundreds of messages per day, a business owner must sift through marketing communications, malware, vendor communications, outright spam, and a dismally small portion of legitimate customer inquiries. As large businesses push “paperless” options aggressively, it is no wonder that personnel face a “Catch-22” of ignoring a legitimate email and allowing financial or logistical situations to snowball and harm customer service, versus opening a phishing email containing malware. It follows that a favorite technique of peddlers of ransomware is to warn of an “important delivery” from FedEx, United Parcel Service or the United States Postal Service about a lost package or other problem. It does not help that UPS’s legitimate delivery problem notifications, like phishing emails, urge the user to <a href="https://www.ups.com/us/en/help-center/legal-terms-conditions/fight-fraud/recognize.page">click a suspicious-looking “ePackage” link</a> to find out more about the problem.</p><p>Recently I was helping an acquaintance who fell for such a phishing email and opened a ransomware Windows executable. The ransomware “encrypted” many files in the user’s user profile directory (Desktop, Documents, Pictures, etc.) and renamed them to have a <em>.crypted</em> file extension. As shown below, the ransomware claimed to have encrypted the files using 1024-bit RSA with a unique key pair, and offered to decrypt the files if the user would send 0.42301 Bitcoin (approximately $2,700 as of this writing) to decrypt the files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u622AwMoBh9J7MbaF7UwCA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*1Xf8dfY4cvXdY0OHwrkErA.png" /><figcaption>After “encrypting” the user’s files the ransomware displayed its ransom in Notepad.</figcaption></figure><h4><strong>How Might Ransomware Work?</strong></h4><p>Interestingly, to implement ransomware in this way is actually plausible. If I were a black-hat hacker (and I’m not!) I might <em>correctly</em> implement this ransomware as follows:</p><ol><li>The ransomware would have a <em>public</em> RSA key, preferably 2048 bits or larger and not 1024, baked inside. The ransomware author would hold the corresponding private key.</li><li>Upon opening, the ransomware would generate an AES (symmetric) key. The ransomware would encrypt that key using the RSA public key, and save that (encrypted) key safely to disk. From then on, the AES key would be kept only in memory.</li><li>The ransomware would walk through the file system looking for important files. For each file, it would save an encrypted copy using AES-CBC or another suitable mode, then delete the original (using a secure wipe for good measure). To be extra evil, the ransomware would run multi-threaded to maximize the number of files lost before the user notices it running and stops it.</li><li>If the user attempts to terminate the ransomware, attach a debugger, hibernate the machine, or otherwise interfere, it would immediately wipe the AES key from memory and exit.</li><li>Once the ransomware is done encrypting files, it would wipe the AES key from memory and display the “README” dialog urging the user to send bitcoin.</li><li>The ransomware would allow the user to send the RSA-encrypted AES key to the author, and only if the user pays the Bitcoin would the author decrypt the AES key and send it back.</li></ol><p>Luckily for users, this ransomware was not so well-written, and I suspect the reason is performance. If the user has 100 GB of documents, then ransomware that attempts to encrypt, write, and wipe 100 GB of data is much more likely to be noticed and stopped than ransomware that subtly but reversibly corrupts files.</p><h4><strong>Examining the Encrypted Files</strong></h4><p>Among the “encrypted” documents was one that I will call file1.doc.crypted. First, run the Linux <em>file </em>utility on it and see what it matches:</p><pre>$ file file1.doc.crypted <br>file1.doc.crypted: data</pre><p>Indeed, “data,” which <em>file</em> states when a file does not match any of its known magic numbers, could indicate an encrypted file, which should be indistinguishable from random data. Next, I tried running <em>strings</em> on the file:</p><pre>$ strings file1.doc.crypted <br>...<br>...<br>Microsoft Word 9.0<br>...<br>Title<br>Microsoft Word Document<br>MSWordDoc<br>Word.Document.8</pre><p>Given these strings in the document, it is definitely not (fully) encrypted. Luckily, file1.doc was an old file and the user had a backup copy. Often, file size will “grow” to a multiple of the block size when a file is encrypted. I decided to compare the size of the original and “encrypted” file:</p><pre>$ ls -l file1.doc file1.doc.crypted <br>-rwxr--r-- 1 xxxx xxxx 20992 Oct 15 22:15 file1.doc<br>-rwxr--r-- 1 xxxx xxxx 20992 Oct 15 22:15 file1.doc.crypted</pre><p>The file sizes are identical! That means that should this “encryption” incorporate an initialization vector or nonce, it is either stored elsewhere or somehow reconstructed on the fly given the file name or other metadata. Going further, I decided to perform a byte-by-byte comparison on the two files:</p><pre>$ cmp -l file1.doc file1.doc.crypted<br>    1 320 341<br>    2 317 255<br>    3  21 202<br>    4 340 174<br>    5 241 113<br>...<br> 1021   0  61<br> 1022   0 142<br> 1023   0 223<br> 1024   0 234</pre><p>Only the first 1024 bytes of the two files are different at all! Given that I have worked with “handmade” encryption before, I thought of the most straightforward, easy way to “encrypt” the first 1024 bytes of a file — which is to open the file, exclusive-or (XOR) the first 1024 bytes with a constant key, then overwrite them with these “encrypted” values and close the file. Or symbolically:</p><pre>Plaintext ^ Key = Ciphertext</pre><p>The problem (for the ransomware author) is that if the victim has a backup copy of the plaintext, he or she can recover the key:</p><pre>Key = Ciphertext ^ Plaintext</pre><p>If the same key is reused for different files, this result is devastating to the cryptosystem. If the user has a backup copy of any one file, the user may recover the key and then can use it to decrypt all the files.</p><h4><strong>Testing the Hypothesis</strong></h4><p>If my guess is correct that all this ransomware did was XOR the first 1024 bytes of each file with a constant value, I should be able to quickly write a program <em>to take, file1.doc</em> and <em>file1.doc.crypted</em>, XOR their first 1024 bytes together and recover the key:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0cf79490e1d1128f7d55861c0ddbf9fc/href">https://medium.com/media/0cf79490e1d1128f7d55861c0ddbf9fc/href</a></iframe><p>Next, I run the program and truncate the “decrypted” output (actually the key) to the proper 1024 bytes:</p><pre>$ ./decrypt file1.doc file1.doc.crypted key<br>$ truncate -s 1024 key</pre><p>The real test is to now try decrypting a real “encrypted” file using the obtained key. For testing purposes, I have a PDF:</p><pre>$ ./decrypt key file2.pdf.crypted file2.pdf<br>$ file file2.pdf<br>file2.pdf: PDF document, version 1.3</pre><p>Looking good. How does it look in Adobe Reader?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*mIk1d5FghKqPt0W-6WLEEA.png" /></figure><p>And there we have it: any file “encrypted” by this ransomware (or at least this particular execution of it) can be recovered using the key obtained from the backup copy of an encrypted file. It is straightforward to use the <em>find</em> utility to recursively walk a directory tree and replace <em>.crypted</em> files with their unencrypted equivalents through a shell script made to call the decryption utility appropriately.</p><h4><strong>Lessons Learned</strong></h4><p>First, just as when assessing real software, don’t assume that if malware claims a file is “encrypted” that it is securely encypted in the sense an engineer might assume, e.g. PGP. Perform a security assessment instead!</p><p>Second, after recovering the files, I performed some additional Internet research and found that this was an instance of the “Nemucod” ransomware; a <a href="https://decrypter.emsisoft.com/nemucod">decryption utility is available from Emsisoft</a>. Consider this blog post a writeup of how this ransomware works to complement the publicly-available decryption utilities.</p><p>Jacob Thompson, Principal Security Analyst at <a href="https://securityevaluators.com/">Independent Security Evaluators</a></p><p>Twitter: @<a href="https://twitter.com/isesecurity">ISESecurity</a></p><p><a href="https://securityevaluators.us12.list-manage.com/subscribe?u=27a7f2cf8beb18666f1123d56&amp;id=fb99a93c73"><strong>Sign up to get our latest blogs.</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb6bded2f68a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/independent-security-evaluators/outsmarting-ransomware-bb6bded2f68a">Outsmarting Ransomware</a> was originally published in <a href="https://medium.com/independent-security-evaluators">Independent Security Evaluators</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Binary Patching: Attempting to Restore NPAPI Support to Firefox 60 ESR]]></title>
            <link>https://medium.com/independent-security-evaluators/binary-patching-attempting-to-restore-npapi-support-to-firefox-60-esr-f1b10c804fe7?source=rss-bfc8b10db590------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1b10c804fe7</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[ise-labs]]></category>
            <category><![CDATA[hacking]]></category>
            <dc:creator><![CDATA[Jacob Thompson]]></dc:creator>
            <pubDate>Fri, 12 Oct 2018 16:28:29 GMT</pubDate>
            <atom:updated>2018-10-12T16:28:29.792Z</atom:updated>
            <content:encoded><![CDATA[<p>Abstract.<em> Did you know it is possible to change the behavior of a compiled program by editing the machine code directly rather than recompiling it from source? Though well-known by hackers, firmware engineers, and other low-level types, this can be intriguing to those whose main focus is in other areas of computer science. By focusing on removing a restriction added to Mozilla Firefox between version 52 ESR and 60 ESR, I show from the ground up how to edit a binary to bypass a plugin check, with mixed results. I use only basic GNU binutils tools to focus on the “bits and bytes” and not on how to use a particular tool. If you are interested in brushing up on some x86–64 assembly, basic reverse engineering and hex editing, take a look at this blog.</em></p><p><strong>Introduction. </strong>The Netscape Plugin Application Programming Interface (NPAPI) is a relic of a simpler time on the Internet where programmers focused on just making it work — now — and not on security concerns. Indeed, such basic modern browser features as reading PDF files through the browser and playing sound and video replace old implementations provided using plugins.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oBquWh55AX8-PiS3ri9oUg.jpeg" /></figure><p>The good side of the NPAPI is that it allows third parties to extend web browsers in almost-arbitrary ways. There is no need to get anyone’s permission and no central authority for distributing the plugin. There is no opportunity for web browser vendors to “monetize” the plugin or restrict distribution to an app store in any way, nor any opportunity for the web community to create a controversy over what does or does not belong in web technology; only the end user has any say in the matter. NPAPI plugins were great for niche market products with, perhaps, a few thousand users who needed to quickly develop browser-neutral software to break out of what is available in HTML and JavaScript. A cynical view could include these reasons, in addition to security, for deprecating NPAPI.</p><p>The bad side, of course, is security. The design of NPAPI, in which arbitrary, unsandboxed, unsigned code is loaded directly into the browser’s address space and exposed directly to untrusted inputs from all Internet sites, would never be repeated in today’s threat environment. NPAPI plugins such as Adobe Flash and the Oracle Java applet plugin have well-deserved reputations for endless security advisories. Microsoft’s similar ActiveX technology has an even worse reputation, partly earned due to that technology’s aggressive installation prompts and poor user interface for implementing that feature in early versions of Internet Explorer.</p><p>For this reason, browser vendors are determined to deprecate and remove NPAPI, both to reduce the attack surface it introduces and simplify browser design by removing all the code needed to support plugins. Google set the standard of click-to-run and disabled-by-default features for plugins, followed by <a href="https://en.wikipedia.org/wiki/NPAPI#Support_/_deprecation">removing NPAPI support entirely</a>. Other browser vendors have followed suit. Mozilla Firefox 52 ESR was the last mainstream browser with full support for NPAPI plugins. Version 60 ESR disallows loading all NPAPI plugins except for Adobe Flash, because it is too popular to disable yet. Ignoring the fact that this exemption reeks of “too big to fail,” an interesting question to consider is whether it is possible to take a copy of Firefox 60 ESR with Flash-only NPAPI support and remove the Flash-only restriction, without recompiling it from source code. The practical application of this, if it works, is a temporary workaround to continue to use niche-market NPAPI plugins that still have not migrated to other technologies.</p><p>The remainder of this post focuses on (1) reviewing the Firefox 60 ESR source code to locate the sections of code that implement the restriction of plugins to Flash only, (2) determining where those functions exist in the compiled Firefox binary and libraries, (3) reviewing the assembly code and determining how to modify the instructions to bypass the check, and (4) testing the resulting copy of Firefox to see if NPAPI is working.</p><p><em>Disclaimer:</em> This is not an endorsement of continuing to use NPAPI, or an argument for restoring NPAPI support to browsers. The binary produced is for research purposes only and should be used in production.</p><p><strong>Locating the Plugin Check Source.</strong> Firefox 60 ESR source code is <a href="http://ftp.mozilla.org/pub/firefox/releases/60.2.1esr/source/">available</a>. I downloaded the source archive and searched for references to Adobe Flash’s MIME type, which is <em>application/x-shockwave-flash</em>. This revealed that the relevant code is in <em>dom/plugins/base/nsPluginHost.cpp</em>:</p><pre>$ find . -name &#39;*.cpp&#39; -exec grep -H application/x-shockwave-flash {} +<br>./dom/plugins/base/nsPluginHost.cpp:    &quot;application/x-shockwave-flash&quot;,<br>./dom/plugins/base/nsPluginHost.cpp:  if (aMIMEType.LowerCaseEqualsASCII(&quot;application/x-shockwave-flash&quot;) ||<br>./dom/plugins/base/nsPluginHost.cpp:      aMIMEType.LowerCaseEqualsASCII(&quot;application/x-shockwave-flash-test&quot;)) {<br>./dom/plugins/base/nsPluginHost.cpp:        (!strcmp(info.fMimeTypeArray[i], &quot;application/x-shockwave-flash&quot;) ||<br>./dom/plugins/base/nsPluginHost.cpp:         !strcmp(info.fMimeTypeArray[i], &quot;application/x-shockwave-flash-test&quot;))) {<br>./dom/plugins/test/testplugin/flashplugin/nptest_name.cpp:const char *sMimeDescription = &quot;application/x-shockwave-flash-test:swf:Flash test type&quot;;</pre><p>Looking closer at that file, I found a few places that enforce the restriction to Flash only and that will need to be changed.</p><p><em>ScanPluginsDirectory</em>, <em>WritePluginInfo</em>, and <em>ReadPluginInfo</em> read a <em>plugin.load_flash_only</em> preference (which does not exist as a valid preference in Firefox 60 ESR) and set a boolean <em>flashOnly</em> variable based on its value. I will need to locate each of these functions in the binary and change this boolean to <strong>false</strong>:</p><pre>nsresult nsPluginHost::ScanPluginsDirectory(nsIFile *pluginsDir,<br>                                            bool aCreatePluginList,<br>                                            bool *aPluginsChanged)<br>{<br>//...<br>  bool flashOnly = Preferences::GetBool(&quot;plugin.load_flash_only&quot;, true);<br>//...<br>}<br><br>nsresult<br>nsPluginHost::WritePluginInfo()<br>{<br>//...<br>  bool flashOnly = Preferences::GetBool(&quot;plugin.load_flash_only&quot;, true);<br>//...<br>}<br><br>nsresult<br>nsPluginHost::ReadPluginInfo()<br>{<br>//...<br>  // If we flipped the flash-only pref, ignore it<br>  bool flashOnly = Preferences::GetBool(&quot;plugin.load_flash_only&quot;, true);<br>//...<br>}</pre><p><em>ShouldAddPlugin</em> only returns true for four plugin MIME types on a whitelist. I will need to locate this function and change it so that the final return <strong>false</strong> is return <strong>true</strong>, instead, for plugins that do not match the whitelist:</p><pre>ShouldAddPlugin(const nsPluginInfo&amp; info, bool flashOnly)<br>{<br>  if (!info.fName || (strcmp(info.fName, &quot;Shockwave Flash&quot;) != 0 &amp;&amp; flashOnly)) <br>{<br>    return false;<br>  }<br>  for (uint32_t i = 0; i &lt; info.fVariantCount; ++i) {<br>    if (info.fMimeTypeArray[i] &amp;&amp;<br>        (!strcmp(info.fMimeTypeArray[i], &quot;application/x-shockwave-flash&quot;) ||<br>         !strcmp(info.fMimeTypeArray[i], &quot;application/x-shockwave-flash-test&quot;))) {<br>      return true;<br>    }<br>    if (flashOnly) {<br>      continue;<br>    }<br>    if (info.fMimeTypeArray[i] &amp;&amp;<br>        (!strcmp(info.fMimeTypeArray[i], &quot;application/x-test&quot;) ||<br>         !strcmp(info.fMimeTypeArray[i], &quot;application/x-Second-Test&quot;))) {<br>      return true;<br>    }<br>  }<br>// ...<br>  return false;<br>}</pre><p><em>CanUsePluginForMIMEType</em> implements another whitelist, so I will also need to locate this function and change it so that it returns <strong>true</strong>:</p><pre>bool<br>nsPluginHost::CanUsePluginForMIMEType(const nsACString&amp; aMIMEType)<br>{<br>  // We only support flash as a plugin, so if the mime types don&#39;t match for<br>  // those, exit before we start loading plugins.<br>  //<br>  // XXX: Remove test/java cases when bug 1351885 lands.<br>  if (nsPluginHost::GetSpecialType(aMIMEType) == nsPluginHost::eSpecialType_Flash ||<br>      MimeTypeIsAllowedForFakePlugin(NS_ConvertUTF8toUTF16(aMIMEType)) ||<br>      aMIMEType.LowerCaseEqualsLiteral(&quot;application/x-test&quot;) ||<br>      aMIMEType.LowerCaseEqualsLiteral(&quot;application/x-second-test&quot;) ||<br>      aMIMEType.LowerCaseEqualsLiteral(&quot;application/x-third-test&quot;)) {<br>    return true;<br>  }<br><br>  return false;<br>}</pre><p>After determining how Firefox changed to block non-Flash plugins, the next step is to find the instructions inside the binaries that correspond to that source code in order to change it later.</p><p><strong>Locating the Plugin Check Machine Code.</strong> Next, I needed to locate the machine code implementing the plugin restrictions I found in the source. As each restriction was implemented in the same source file, they should also be implemented in the same binary. Indeed, I found it best to look for the <em>plugin.load_flash_only</em> preference string to find the relevant machine code from the 64-bit Linux version of Firefox 60.2.1esr. I found the checks to be in <em>libxul.so</em>:</p><pre>$ strings -f * | grep plugin.load_flash_only<br>libxul.so: plugin.load_flash_only<br>omni.ja:     if (Preferences.get(&quot;plugin.load_flash_only&quot;, true)) {</pre><p>Now, I need to find the three places in the code that check the <em>load_flash_only</em> preference, and then find <em>ShouldAddPlugin</em> and <em>CanUsePluginForMIMEType</em> and change their return values. Because I am choosing not to use tools such as IDA Pro for the purpose of focusing on the fundamentals, I must use more primitive means:</p><p>(1) locate the file offsets of the strings <em>plugin.load_flash_only</em>, <em>application/x-Second-Test</em>, and <em>application/x-third-test</em> in <em>libxul.so.</em><br>(2) refer to the program headers of <em>libxul.so</em> to determine where the relevant section of the <em>libxul.so</em> binary will be loaded in virtual memory space at runtime, and use that information to convert the string offsets to memory addresses.<br>(3) disassemble <em>libxul.so</em>, and look for instructions that read from the addresses determined in (2), which will pinpoint the machine code corresponding to the source code containing those strings.</p><p>Determining the string file offsets is straightforward:</p><pre>$ strings -t x libxul.so | egrep &#39;plugin.load_flash_only|application/x-Second-Test|application/x-third-test&#39;<br>3edc5ee plugin.load_flash_only<br>3edc661 application/x-Second-Test<br>3edc8d1 application/x-third-test</pre><p>Using <em>readelf</em>, I can determine the conversion factor from disk offsets into <em>libxul.so</em> to virtual memory addresses:</p><pre>$ readelf -l libxul.so<br><br>Elf file type is DYN (Shared object file)<br>Entry point 0x8c60e0<br>There are 9 program headers, starting at offset 64<br><br>Program Headers:<br>  Type           Offset             VirtAddr           PhysAddr<br>                 FileSiz            MemSiz              Flags  Align<br>...<br>  LOAD           0x00000000000eaa68 0x00000000008b9a68 0x00000000008b9a68<br>                 0x0000000004cb15e8 0x0000000004cb15e8  R E    0x1000<br>...</pre><p>To convert, subtract 0xeaa68 from the file offset and add 0x8b9a68:</p><pre>string                    file offset address<br>========================= =========== =========<br>plugin.load_flash_only      0x3edc5ee 0x46ab5ee<br>application/x-Second-Test   0x3edc661 0x46ab661<br>application/x-third-test    0x3edc8d1 0x46ab8d1</pre><p>Now, I need to disassemble <em>libxul.so</em> and search for references to those three addresses. In position independent, x86–64 code, these addresses will not be encoded in the instruction — instead, they are referenced as offsets from the instruction pointer. Luckily, GNU <em>objdump</em> does the conversion for me. First, look for the three references to <em>plugin.load_flash_only’</em>s memory location:</p><pre>$ objdump -D libxul.so &gt; libxul.txt<br>$ grep &#39;# 46ab5ee&#39; libxul.txt<br> 1939848:	48 8d 3d 9f 1d d7 02 	lea    0x2d71d9f(%rip),%rdi        # 46ab5ee &lt;SECKEY_DHPublicKeyTemplate@@xul60+0x91fee&gt;<br> 193bc8b:	48 8d 3d 5c f9 d6 02 	lea    0x2d6f95c(%rip),%rdi        # 46ab5ee &lt;SECKEY_DHPublicKeyTemplate@@xul60+0x91fee&gt;<br> 31ac335:	48 8d 3d b2 f2 4f 01 	lea    0x14ff2b2(%rip),%rdi        # 46ab5ee &lt;SECKEY_DHPublicKeyTemplate@@xul60+0x91fee&gt;</pre><p>Then, locate <em>ShouldAddPlugin</em> by reference to the string <em>application/x-Second-Test’</em>s memory location:</p><pre>$ grep &#39;# 46ab661&#39; libxul.txt 193ab35:	48 8d 35 25 0b d7 02 	lea    0x2d70b25(%rip),%rsi        # 46ab661 &lt;SECKEY_DHPublicKeyTemplate@@xul60+0x92061&gt;</pre><p>Then, locate <em>CanUsePluginForMIMEType</em> by reference to the string <em>application/x-third-test’</em>s memory location:</p><pre>$ grep &#39;# 46ab8d1&#39; libxul.txt<br> 193d735:	48 8d 35 95 e1 d6 02 	lea    0x2d6e195(%rip),%rsi        # 46ab8d1 &lt;SECKEY_DHPublicKeyTemplate@@xul60+0x922d1&gt;</pre><p>Thus, I have located three references to the preference <em>plugin.load_flash_only</em> that all need to be changed to obtain false, plus the two functions that need to be changed to return true.</p><p><strong>Determining How to Patch the Code. </strong>Patching the code that reads the <em>plugin.load_flash_only</em> preference is straightforward. First, take a look at the three places in the code that read that preference:</p><pre>1939848:       48 8d 3d 9f 1d d7 02    lea    0x2d71d9f(%rip),%rdi        # 46ab5ee &lt;SECKEY_DHPublicKeyTemplate@@xul60+0x91fee&gt;<br> 193984f:       ba 01 00 00 00          mov    $0x1,%edx<br> 1939854:       48 89 ee                mov    %rbp,%rsi<br> 1939857:       c6 84 24 c0 01 00 00    movb   $0x1,0x1c0(%rsp)<br> 193985e:       01 <br> 193985f:       4c 8d b4 24 00 01 00    lea    0x100(%rsp),%r14<br> 1939866:       00 <br> 1939867:       e8 c4 ab f0 00          callq  2844430 ...<br>...<br> 193bc8b:       48 8d 3d 5c f9 d6 02    lea    0x2d6f95c(%rip),%rdi        # 46ab5ee &lt;SECKEY_DHPublicKeyTemplate@@xul60+0x91fee&gt;<br> 193bc92:       b2 01                   mov    $0x1,%dl<br> 193bc94:       c6 44 24 50 01          movb   $0x1,0x50(%rsp)<br> 193bc99:       4c 89 ee                mov    %r13,%rsi<br> 193bc9c:       e8 8f 87 f0 00          callq  2844430 ...<br>...<br> 31ac335:       48 8d 3d b2 f2 4f 01    lea    0x14ff2b2(%rip),%rdi        # 46ab5ee &lt;SECKEY_DHPublicKeyTemplate@@xul60+0x91fee&gt;<br> 31ac33c:       48 89 f3                mov    %rsi,%rbx<br> 31ac33f:       c6 01 00                movb   $0x0,(%rcx)<br> 31ac342:       41 89 d5                mov    %edx,%r13d<br> 31ac345:       4c 89 fe                mov    %r15,%rsi<br> 31ac348:       ba 01 00 00 00          mov    $0x1,%edx<br> 31ac34d:       49 89 ce                mov    %rcx,%r14<br> 31ac350:       c6 84 24 80 01 00 00    movb   $0x1,0x180(%rsp)<br> 31ac357:       01 <br> 31ac358:       e8 d3 80 69 ff          callq  2844430 ...</pre><p>I know that 0x46ab5ee is the address of <em>plugin.load_flash_only</em>, and can infer that 0x2844430 must be the address of the function Preferences::GetBool. Ordinarily, I would expect that function to return its <strong>true</strong> or <strong>false</strong> result in %rax, but (although I have not shown the code subsequent to that call) I discovered the call-and-return sequence is not working that way here, possibly due to optimization. Instead, I took a brute force approach: notice that at 0x193984f, 0x193bc92, and 0x31ac348, the code saves a true value into a register. At 0x1939857, 0x193bc94, and 0x31ac350, the code stores a <strong>true</strong> value on the stack. My approach was to simply overwrite all of these instructions so that they store <strong>false</strong> (or zero), instead. For example, to change <em>mov $0x1,%edx</em> to <em>mov $0x0,%edx</em>, all I need to do is change the binary encoding <em>ba 01 00 00 00</em> to <em>ba 00 00 00 00</em>. The process is analogous for all the other instructions.</p><p>Patching the other two functions to accept non-Flash plugins was not as straightforward. Both functions contain a few conditional statements, that bail out and return <strong>false</strong> if some string comparisons all fail. In theory, I should be able to find the <em>ret</em> instruction in both functions and work backward to find a convenient place to overwrite %rax with 1. However, it appears these functions were inlined by the compiler so that they just branch to different locations to depending on whether they would have returned <strong>true</strong> or <strong>false</strong> were they not inlined.</p><p>First, taking a look at the portion of <em>ShouldAddPlugin</em> that checks to see if the plugin’s MIME type is <em>application/x-Second-Test</em>, I see that if <em>strcmp</em> returns zero (the strings are equal), the code jumps to 0x193ab4e, so jumping to 0x193ab4e must be equivalent to returning <strong>true</strong>:</p><pre>193ab35:       48 8d 35 25 0b d7 02    lea    0x2d70b25(%rip),%rsi        # 46a<br>b661 &lt;SECKEY_DHPublicKeyTemplate@@xul60+0x92061&gt;<br> 193ab3c:       48 89 ef                mov    %rbp,%rdi<br> 193ab3f:       e8 8c a2 f8 fe          callq  8c4dd0 &lt;strcmp@plt&gt;<br> 193ab44:       85 c0                   test   %eax,%eax<br> 193ab46:       74 06                   je     193ab4e &lt;_ZNSt3mapIiiSt4lessIiESaISt4pairIKiiEEEixERS3_@@xul60+0xec0e8&gt;</pre><p>To get a better idea of what happens if <em>ShouldAddPlugin</em> returns <strong>false</strong>, I decided to look up the address of the string <em>Shockwave Flash</em> in libxul.so, which I found to be 0x46ab620. Looking around the code that calls <em>strcmp</em> against that string, I can infer that if either the string <em>Shockwave Flash</em> matches or flashOnly is false, the code jumps to 0x193aad1 which must mean branching to the first set of MIME type checks; otherwise the code falls through to 0x193a962. Looking above at 0x193a936, I infer that if the <em>info.fName</em> check fails, the code branches to that same location, confirming my suspicion:</p><pre>193a936:       48 8b bc 24 30 01 00    mov    0x130(%rsp),%rdi<br> 193a93d:       00 <br> 193a93e:       48 85 ff                test   %rdi,%rdi<br> 193a941:       74 1f                   je     193a962 &lt;_ZNSt3mapIiiSt4lessIiESa<br>ISt4pairIKiiEEEixERS3_@@xul60+0xebefc&gt;<br> 193a943:       48 8d 35 d6 0c d7 02    lea    0x2d70cd6(%rip),%rsi        # 46ab620 &lt;SECKEY_DHPublicKeyTemplate@@xul60+0x92020&gt;<br> 193a94a:       e8 81 a4 f8 fe          callq  8c4dd0 &lt;strcmp@plt&gt;<br> 193a94f:       85 c0                   test   %eax,%eax<br> 193a951:       0f 84 7a 01 00 00       je     193aad1 &lt;_ZNSt3mapIiiSt4lessIiESaISt4pairIKiiEEEixERS3_@@xul60+0xec06b&gt;<br> 193a957:       80 7c 24 35 00          cmpb   $0x0,0x35(%rsp)<br> 193a95c:       0f 84 6f 01 00 00       je     193aad1 &lt;_ZNSt3mapIiiSt4lessIiESaISt4pairIKiiEEEixERS3_@@xul60+0xec06b&gt;<br> 193a962:       bf 40 00 00 00          mov    $0x40,%edi</pre><p>Based on that knowledge, I know that to “emulate” having <em>ShouldAddPlugin</em> always return <strong>true</strong>, I must replace the code at offset 0x193a962 with a relative jump to 0x193ab4e. How would such an instruction be encoded? Being restricted to binutils, the quickest way is to write, assemble and disassemble a short executable, determining the encoding as <em>e9 e7 01 00 00</em>:</p><pre>$ cat test.s<br><br>	.global _start<br>	.text<br>_start:<br>	.org 0x193a962-0x400078<br>	jmp 0x193ab4e<br>$ as -o test.o test.s &amp;&amp; ld -o test test.o<br>$ objdump -d test<br><br>test:     file format elf64-x86-64<br><br><br>Disassembly of section .text:<br><br>0000000000400078 &lt;_start&gt;:<br>	...<br> 193a960:	00 00                	add    %al,(%rax)<br> 193a962:	e9 e7 01 00 00       	jmpq   193ab4e &lt;_start+0x153aad6&gt;</pre><p>Next, taking a look at <em>CanUsePluginForMIMEType</em>, since I know that at 0x193d735 begins the check for the <em>application/x-third-test</em> string, I can look backward and infer that at 0x193d71d must begin the check for the <em>application/x-second-test</em> string. Observe that at 0x193d733, the function jumps to 0x193d6f6 if <em>LowerCaseEqualsLiteral</em> returned <strong>true</strong>, but falls through if it returns <strong>false</strong>:</p><pre>193d71d:       48 8d 35 93 e1 d6 02    lea    0x2d6e193(%rip),%rsi        # 46ab8b7 &lt;SECKEY_DHPublicKeyTemplate@@xul60+0x922b7&gt;<br> 193d724:       ba 19 00 00 00          mov    $0x19,%edx<br> 193d729:       48 89 df                mov    %rbx,%rdi<br> 193d72c:       e8 9f 3c ed 00          callq  28113d0 &lt;ffi_closure_unix64_inner@@xul60+0x38b3b&gt;<br> 193d731:       84 c0                   test   %al,%al<br> 193d733:       75 c1                   jne    193d6f6 &lt;_ZNSt3mapIiiSt4lessIiESaISt4pairIKiiEEEixERS3_@@xul60+0xeec90&gt;<br> 193d735:       48 8d 35 95 e1 d6 02    lea    0x2d6e195(%rip),%rsi        # 46ab8d1 &lt;SECKEY_DHPublicKeyTemplate@@xul60+0x922d1&gt;</pre><p>All I need to do here is change the conditional jump <em>jne</em> at 0x193d733 to an unconditional one <em>jmp</em>, which I can accomplish by changing the <em>75</em> opcode to <em>eb</em>.</p><p><strong>Patching the Binary. </strong>Now that I know the code addresses and the changes I need to make, I can use reverse the conversion I initially used to convert these addresses to file offsets. That is, add 0xeaa68 and subtract 0x8b9a68:</p><pre>address   file offset change<br>========= =========== ==================================================<br>0x193984f   0x116a84f ba 01 00 00 00 to ba 00 00 00 00<br>0x1939857   0x116a857 c6 84 24 c0 01 00 00 01 to c6 84 24 c0 01 00 00 00<br>0x193bc92   0x116cc92 b2 01 to b2 00<br>0x193bc94   0x116cc94 c6 44 24 50 01 to c6 44 24 50 00<br>0x31ac348   0x29dd348 ba 01 00 00 00 to ba 00 00 00 00<br>0x31ac350   0x29dd350 c6 84 24 80 01 00 00 01 to c6 84 24 80 01 00 00 00<br>0x193d733   0x116e733 75 c1 to eb c1<br>0x193a962   0x116b962 bf 40 00 00 00 to e9 e7 01 00 00</pre><p>For demonstration purposes, I will show how to make the first change using <em>xxd</em>:</p><pre>$ xxd -g1 libxul.so &gt; libxul.hex<br>$ grep &#39;^0116a840&#39; libxul.hex<br>0116a840: 7c 24 74 e9 47 ff ff ff 48 8d 3d 9f 1d d7 02 ba  |$t.G...H.=.....<br>$ grep &#39;^0116a850&#39; libxul.hex<br>0116a850: 01 00 00 00 48 89 ee c6 84 24 c0 01 00 00 01 4c  ....H....$.....L<br>$ sed -i &#39;s/^0116a850: 01 /0116a850: 00 /&#39; libxul.hex</pre><p>I made the remainder of the changes using <em>vi</em>. Then:</p><pre>$ mv libxul.so libxul.bak<br>$ xxd -r &lt; libxul.hex &gt; libxul.so</pre><p><strong>Testing and Conclusion. </strong>Upon launching Firefox with the modified <em>libxul.so</em>, I was successfully able to launch and connect to a VPN that makes use of a Linux-based NPAPI plugin. I suspect the reason this plugin worked is that it does not have its own graphical user interface. Other plugins, unfortunately, did not work correctly. I was able to load <em>mozplugger</em> with a configuration file set only to support TIFF files, as shown in the <em>about:plugins</em> page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*YXZWZ5Cw_Y_A9tMiqazLtQ.png" /></figure><p>After loading <em>mozplugger</em>, however, upon writing a test HTML page and TIFF file, I could not get the TIFF to display in the web page. Instead, upon visiting the page, the browser wrote the error <em>Connection reset by peer: file /builds/worker/workspace/build/src/ipc/chromium/src/chrome/common/ipc_channel_posix.cc, line 353</em> to the console.</p><p>In the end, this is an interesting exercise (and works for my purposes for the VPN plugin), but clearly is not practical for production use. Every time Firefox updates itself, the <em>libxul.so</em> file will also be updated. In addition, patching this file invalidated any code signatures it may have had. Even if I proceeded further and fixed the <em>mozplugger</em> issues, the full removal of NPAPI from Firefox is inevitable. The <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1269807">bug to disable non-Flash NPAPI plugins</a> was blocking resolution of 23 other bugs. Mozilla has or soon will remove “windowed mode” plugin support, GTK3 plugins, <em>&lt;applet&gt;</em> element support, and special-case code for Windows Media Player, Acrobat Reader, QuickTime, RealPlayer, Google Earth, Silverlight, Unity, and Shockwave plugins. Just as Firefox 52 ESR is now unsupported, Firefox 60 ESR soon will be as well, and the versions that succeed it will have no NPAPI support at all.</p><p><em>Jacob Thompson, Principal Security Analyst at Independent Security Evaluators</em></p><p><em>Twitter: @ISEsecurity</em></p><p><a href="https://securityevaluators.us12.list-manage.com/subscribe?u=27a7f2cf8beb18666f1123d56&amp;id=fb99a93c73"><strong>Sign up to get our latest blogs.</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1b10c804fe7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/independent-security-evaluators/binary-patching-attempting-to-restore-npapi-support-to-firefox-60-esr-f1b10c804fe7">Binary Patching: Attempting to Restore NPAPI Support to Firefox 60 ESR</a> was originally published in <a href="https://medium.com/independent-security-evaluators">Independent Security Evaluators</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Breach in the Same-Origin Policy Induced by Mirroring External Content]]></title>
            <link>https://medium.com/independent-security-evaluators/a-breach-in-the-same-origin-policy-induced-by-mirroring-external-content-f93b17a02ec8?source=rss-bfc8b10db590------2</link>
            <guid isPermaLink="false">https://medium.com/p/f93b17a02ec8</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[hacking]]></category>
            <category><![CDATA[cybersecurity]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Jacob Thompson]]></dc:creator>
            <pubDate>Wed, 19 Oct 2016 12:01:01 GMT</pubDate>
            <atom:updated>2016-10-19T16:50:38.873Z</atom:updated>
            <content:encoded><![CDATA[<p>Authored by <a href="https://medium.com/@jthompson_5338">Jacob Thompson</a>, a Senior Security Analyst <em>at </em><a href="http://www.securityevaluators.com/"><em>Independent Security Evaluators</em></a><em>.</em></p><p>What do Google Translate, the Internet Archive, and the free anonymization proxy Hide.me have in common? Each of these services mirrors web content on a different origin than where it originated — and this could be a threat to your privacy and security. The weakening of the same-origin proxy induced by doing this is an underappreciated attack vector against web users. Under the right conditions, a third-party malicious site could track your browsing history, steal session cookies, and capture data input to web pages that would otherwise be secure under normal conditions. Read along to understand more about the problem, the risks, and how you can protect yourself.</p><p>In certain circumstances developers find the need to write web applications that serve copies of content obtained from other unaffiliated servers. Search engines offer users access to cached versions of web pages accessed by their crawlers. The <a href="https://archive.org/">Internet Archive</a> seeks to preserve copies of web pages even after they are modified or removed. Translation services allow users to submit original and desired languages and an arbitrary URL; the service then fetches the URL at the server-side and returns a translated copy of it to the user’s browser. Proxy services such as <a href="https://hide.me/en/proxy">Hide.me</a> allow users to submit a URL through a web form to view a web page anonymously without special software or configuration as might be required a more robust solution like <a href="https://www.torproject.org/">Tor</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*93UnZr9n-4qx8r4re-tsZQ.jpeg" /><figcaption>cookies on java[script]</figcaption></figure><p>The common thread binding these services is that they provide what I call “mirroring.” That is, they take HTML content (possibly containing JavaScript) from (possibly multiple) external domains, and serve copies of it from a single common origin. Figure 1 shows the request format to a hypothetical but typical mirroring service. Freely available packages such as <a href="https://www.jmarshall.com/tools/cgiproxy/">CGIProxy</a> and <a href="https://sourceforge.net/projects/poxy/">PHProxy</a> make it easy for a server administrator to deploy a mirroring service following this design with minimal work.</p><pre>http://www.example.com/fetch?url=http:%2f%2fwww.example.org%2f</pre><p><em>Figure 1. Web applications provide mirroring if they accept an external URL and return a (possibly modified) copy of its contents to the client.</em></p><p>“Pure” mirroring services aim to serve static content. To service a request, they retrieve a stored copy of the requested URL, possibly modify the page so that any links inside point to the mirroring service, and return the content to the user. A user cannot log in to a web application through such a service, interact with RESTful APIs or other web services, and so on, since these mirrors neither serve dynamic content nor relay requests for such programatically-generated pages to the original server hosting them. The “cached page” services provided by Bing or Google, and the Internet Archive are examples of pure mirroring services.</p><p>Proxies, on the other hand, relay arbitrary HTTP requests between the end user’s browser and upstream servers hosting the pages being accessed, acting as a bare-bones HTTP proxy server or VPN. Clearly, these services <em>must</em> rewrite any references to absolute URLs in the page, lest the user inadvertently “escape” from the proxy by following a link¹. So long as the proxy provides the necessary rewriting, there is no reason why users could not log in to and use an authenticated web application if desired, despite the obvious privacy risks of tunneling all traffic through a third party.</p><p>The problem introduced by mirroring services that operate as shown in Figure 1 is that they cause the browser to treat all pages accessed through the service as if they were being served from the same origin. As a result, the same-origin policy that normally isolates pages served from different servers does not apply. Whether this is of any security consequence depends on the nature of the page being served, the capabilities and configuration of the mirroring service, and hardening techniques in use on the page being accessed (e.g., the <em>HttpOnly</em> cookie flag). Here are two categories of security compromise that could arise when a user accesses pages through a mirroring service:</p><ol><li><strong>Cookie leaks.</strong> Suppose a user visits site <em>A</em> through the mirroring service, that this site sets an HTTP cookie, and that the mirroring service supports cookies and passes the cookie to the user’s browser. If the user later visits a page on unaffiliated site <em>B</em> through the mirroring service, the cookie previously set by site <em>A</em> could be exposed to site <em>B</em>, even though the same-origin policy normally prevents this.</li><li><strong>Total same-origin policy bypass.</strong> In a full proxy scenario, a user may use a mirror service to access an authenticated web application <em>A</em> that relies on the same-origin policy and CSRF protections to protect against unauthorized API calls originating from external sites. If the user later accesses page <em>B</em> through the mirror service, that page could make bidirectional HTTP requests to application <em>A</em> through the proxy, bypassing same-origin protections since the browser sees the two pages as originating from the same server.</li></ol><p>I provide three concrete examples covering both of these scenarios below.</p><h4>A History Leak</h4><p>Suppose that <em>secret.example.com</em> hosts a page that, for social or other reasons, a user would prefer to be able to visit without this fact being exposed. For example, the site might be subversive or considered blasphemous. The page uses the JavaScript <em>document.cookie</em> object to set a session cookie for some legitimate purpose — possibly, to indicate that the user has agreed to a terms of service dialog or has confirmed that he or she is not a minor. Further, the name, format, or other factors with this cookie are unique enough such that it can easily be identified in the browser’s cookie store from its name and value alone, and its presence means it is highly likely that the user visited the <em>secret.example.com</em> site.</p><p>The same-origin policy would normally prevent pages from other servers, such as <em>spy.example.org</em>, from accessing the cookies from other origins. Indeed, as Figure 2 shows, after accessing a page on secret.example.com that sets a cookie using the <em>document.cookie</em> object, viewing a page on <em>spy.example.org</em> that displays all cookies contained in the <em>document.cookie</em> object returns nothing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*pQC3_dDrdUxG-3B93OCf_A.png" /><figcaption>Figure 2. The same-origin policy prevents a page on spy.example.org from reading a cookie set by <em>secret.example.com</em>.</figcaption></figure><p>Now suppose that instead of accessing the two sites directly, the affected user accesses them through a translation service, instead. I’ve moved the two pages to the public-facing domains <em>demo.securityevaluators.com</em> and <em>demo2.securityevaluators.com</em> rather than <em>secret.example.com</em> and <em>spy.example.org</em>, respectively (for testing purposes), but the same-origin policy still applies². Figure 3 shows how, when both sites are accessed through a translation service rather than directly, pages on <em>demo2.securityevaluators.com</em> can access cookies set by <em>demo.securityevaluators.com</em> that would normally be protected by the same origin policy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a5reflqq0OtCEiwZWmo79Q.png" /><figcaption>Figure 3. When both sites are accessed through a typical translation service, a page on demo2.securityevaluators.com can access cookies set by demo.securityevaluators.com even though they would normally be isolated by the same-origin policy.</figcaption></figure><p>Returning to the earlier terminology, in a real-world attack the page on <em>spy.example.org</em> might scan the current cookies for evidence that the user has accessed <em>secret.example.com</em>, and report that fact back to the server if such a cookie is found. Such “history leaks” are considered a violation of the browser security model, and where they have occurred elsewhere, have been treated as security bugs and fixed (e.g., as in <a href="https://blog.mozilla.org/security/2010/03/31/plugging-the-css-history-leak/">CSS selectors</a>). Because the attack shown here relies on JavaScript’s <em>document.cookie</em> object, rather than HTTP headers, this scenario could arise in any mirroring service, not just those that actively proxy traffic in real time.</p><h4>A Session Cookie Leak</h4><p>Now, let’s consider a more consequential attack, in which a user’s (possibly-authenticated) session cookie is leaked between two servers. Unlike the history leak, this attack only works against mirroring services that actively relay traffic between the browser and server, so I concentrate on the Hide.me anonymization service.</p><p>Suppose that a user (directly and not through a mirroring service) visits and logs in to a web application on <em>demo.securityevaluators.com</em>, and then visits two attack pages on <em>demo2.securityevaluators.com</em>. One attack page attempts to read the cookie previously set by the web application in the HTTP request headers, while another attempts to obtain it using JavaScript. As shown in Figure 4, the same-origin policy blocks both attacks when a user accesses these two domains directly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*EFLFX61hNFlK_ijWx9g2hg.png" /><figcaption>Figure 4. The same origin policy blocks pages on demo2.securityevaluators.com from receiving cookies for demo.securityevaluators.com.</figcaption></figure><p>Now suppose that instead of accessing the two sites directly, the affected user accesses them through the Hide.me proxy service, instead. Figure 5 shows three windows, all containing pages accessed through Hide.me. The top window shows an authenticated session in the web application. The middle window shows an attack page (served from a different domain) that gathers cookies from HTTP request headers (i.e., it executes at the server-side). The bottom window shows an attack page that gathers cookies from the JavaScript <em>document.cookie</em> object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*CyMmNGwnLcs4bli6Hj-o6A.png" /><figcaption>Figure 5. When legitimate pages on demo.securityevaluators.com and attack pages on demo2.securityevaluators.com are both accessed through a free proxy service that operates as a mirror, the browser fails to enforce the same-origin policy, allowing the attack page at the bottom of the image to access session cookies for other domains.</figcaption></figure><p>The presence of the <em>PHPSESSID</em> cookie on the latter attack page shows that mirror services can undermine the same-origin policy; a real attack page would send this session cookie to the attacker, who could then impersonate the user in the web application. This example is not intended to pick on Hide.me — the same attack applies to any proxy service that follows this design. In fact, I found a public instance of <a href="https://px.multiscreensite.com/">PHProxy</a> to be susceptible in the same way.</p><p>While the example shown here requires that a user actively authenticate through the proxy service, this is not necessarily a prerequisite for this type of attack to be security-relevant. For example, suppose a web forum application tracks a guest user’s read and unread posts using an anonymous-but-unique session tied to an HTTP cookie. Were this cookie to be exposed to a third party, that adversary could replay it to the server to view the victim’s post reading history.</p><h4><a href="http://eepurl.com/bLc2bf">Sign up to get our latest blogs</a></h4><h4>A Same-Origin Policy Bypass</h4><p>The consequences of a browser’s inability to distinguish pages’ origins when they are accessed through a mirror-based web proxy service are much more than the exposure of user history and even sessions. In fact, because browsers allow bidirectional AJAX requests between resources that fall under the same origin, when both an attack page and the site it targets are accessed through a mirror service that operates as shown in Figure 1, the attack page can interact with its target server in arbitrary ways.</p><p>Here is an example. Suppose a user accesses a web application on <em>demo.securityevaluators.com</em> that, among other things, allows the user to view and modify stored credit card information³. Then, the user accesses an attack page hosted on <em>demo2.securityevaluators.com</em> that attempts to retrieve the page containing the user’s credit card number through an AJAX request and display the retrieved source on the screen. As shown in Figure 6, the same-origin policy prevents this if both sites are accessed directly. In fact, the browser even logs a same-origin-related error to the browser console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*qKTkoi3HQ7GLV7AI4dHjQA.png" /><figcaption>Figure 6. The same-origin policy, by default, blocks an attack site (bottom) from receiving the response to an AJAX request to a different origin (top).</figcaption></figure><p>Now suppose that instead of accessing the two sites directly, the affected user accesses them through the Hide.me proxy service, instead. Figure 7 shows that this time, the attack page can successfully send an AJAX request to the application and receive the user’s credit card number. Because this attack page is specifically written to allow Hide.me to rewrite the URL pointing to the credit card page, Hide.me rewrites it, causing the browser to treat the attack page and credit card page to belong to the same origin (<em>proxy-nl.hide.me</em>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*lZsS1e_3H82zgZ4p2p4dnQ.png" /><figcaption>Figure 7. When accessing sites through a typical mirror-based proxy service, the browser’s same-origin policy fails to protect against cross-domain AJAX requests and responses, since all pages appear to the browser to originate from the same domain.</figcaption></figure><h4>Affected Sites</h4><p>Here is a list of sites where I tested and confirmed that pages hosted on one domain can use JavaScript’s <em>document.cookie</em> to access other cookies set through <em>document.cookie</em> from pages hosted on a different domain.</p><ul><li><a href="http://translate.google.com/">Google Translate</a> translation application.</li><li><a href="http://www.bing.com/">Bing Cache</a>.</li><li><a href="https://www.bing.com/translator/">Microsoft Translator</a> translation application.</li><li><a href="https://www.jmarshall.com/tools/cgiproxy/">CGIProxy</a> anonymization proxy software.</li><li><a href="https://sourceforge.net/projects/poxy/">PHProxy</a> anonymization proxy software.</li><li><a href="http://hide.me/">Hide.me</a> anonymization proxy site.</li><li><a href="http://www.vpnbook.com/">ht anon</a>ymization proxy site.</li><li><a href="https://www.proxysite.com/">ProxySite</a> anonymization proxy site.</li><li><a href="https://hidester.com/proxy/">Hidester</a> anonymization proxy site. Note that this service does disable JavaScript by default.</li><li><a href="https://www.hidemyass.com/proxy#">HideMyAss!</a> anonymization proxy site.</li></ul><h4>Solving the Problem</h4><p>Clearly, mirror-based proxies can undermine a user’s privacy rather than enhancing it. But the designers of these services are not unaware of these risks, and privacy-targeted proxy services including Hide.me include some optional features designed to enhance privacy. In fact, the author of CGIProxy even has a <a href="https://www.jmarshall.com/tools/cgiproxy/security.html">security page</a> listing the software’s limitations and recommending how users should cautiously use a proxy, although that page is silent on the threat that mirror-style proxies present to same-origin-based security. I address some security-enhancing features in typical proxies, their effectiveness, and their limitations below.</p><ol><li><strong>Cookie blocking.</strong> Hide.me supports an “allow cookies” check box that blocks servers from setting cookies using HTTP response headers. Unfortunately, this provides neither usability nor security. First, blocking HTTP cookies prevents users from using web applications through the proxy that depend on cookies to track session state (although accessing security-sensitive pages through such a proxy is unwise anyway). Second, the “allow cookies” option does not affect cookies set using JavaScript’s <em>document.cookie</em> object rather than HTTP headers, and it would be all but impossible to design a proxy that could scan for and remove code that attempts to access the <em>document.cookie</em> object (theoretical computer scientists could prove using <a href="https://en.wikipedia.org/wiki/Rice%27s_theorem">Rice’s theorem</a> that problems like these are undecidable). Therefore, even with cookie blocking in place, history leaks, cookies leaks, and same-origin policy bypasses all remain possible in some instances.</li><li><strong>Script and object removal.</strong> Hide.me has an option to strip JavaScript code and objects (e.g., plugins and Java applets) from pages accessed through the proxy. Unfortunately, JavaScript is all-but-essential to modern websites, as Mozilla’s <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=873709">removal of the option to disable JavaScript</a> in the Firefox user interface attests. To strip JavaScript from pages delivered through a proxy service would render it unusable for most sites.</li><li><strong>Clearing or resetting cookies.</strong> An interesting observation I made observing the Google search engine’s cached page feature is that the server’s response automatically resets to the empty string and clears any cookies sent with the request. This is somewhat similar to the option to block cookies entirely, with the possible advantage that it can also remove cookies set by the JavaScript <em>document.cookie</em> object. Nevertheless, a full proxy service could not do this without breaking legitimate functionality and it is thus not a comprehensive solution.</li><li><strong>One-to-one hostname-to-subdomain mapping.</strong> Another proxy service I tested, Whoer.net, maps hostnames in URLs to unique proxy server subdomains using some form of mapping, (e.g., a hash), rather than servicing all requests from the same domain as shown in Figure 1. This is, perhaps, the most effective way to maintain the same-origin policy while providing a web based proxy, and it does thwart the three specific attacks I show above. Still, serving trusted and untrusted content from the same second-level domain is inherently dangerous — this is why <a href="https://security.googleblog.com/2012/08/content-hosting-for-modern-web.html">Google hosts untrusted content on <em>googleusercontent.com</em></a> to separate it from authenticated and trusted content on <em>google.com</em>. For example, consider JavaScript code that programmatically calculates the <em>document.domain</em> value by stripping all but the top and second-level domains of the current page. Such code would malfunction, and expose cookies to external and untrusted sites, when accessed through the proxy.</li></ol><p>Web developers may wonder if there are any steps they can take to harden their sites from the attacks I have shown in the event that their end users access the site from an affected proxy. Here are some possible mitigations, but their effectiveness varies.</p><ol><li><strong>The <em>HttpOnly</em> cookie flag.</strong> The <em>HttpOnly</em> flag blocks a cookie from being accessed through JavaScript or by plugins, that is, it causes the browser to send the cookie back to the server as part of the headers of any request but otherwise prevents access to the cookie in any way. As part of best practices, all web applications should use the <em>HttpOnly</em> flag wherever possible. This can block some, but not all types of attacks, in particular, it would block the history and cookie leaks I demonstrated, but could not prevent the same-origin policy bypass.</li><li><strong><em>Authorization</em> headers in lieu of cookies.</strong> Many RESTful APIs use a custom <em>Authorization</em> request header rather than cookies for authentication. This is sufficient to mitigate the issues I have shown (since the authorization token does not accidentally “leak” to other pages just by virtue of belonging to the same origin like a cookie would), although the header is not a substitute for cookie-based authentication in all cases for usability reasons.</li><li><strong>Hardening headers.</strong> Correctly deploying HTTP Strict Transport Security and public key pinning headers could block a site from being accessed through a mirror-based proxy service (since the pinned key would necessarily mismatch the mirror’s key), but these would be ineffective against a proxy service that strips these headers for functional reasons.</li><li><strong>Blocking proxy sites.</strong> Highly security-conscious sites may choose to block access through mirror-based proxies as the security of these proxies is dubious even without considering the attacks I have shown.</li></ol><p>Finally, end users may wonder how to defend against these issues. First, they should avoid accessing any authenticated applications or other sensitive material through a proxy that operates as shown in Figure 1. Users who wish to browse anonymously should use Tor or another proxy system that operates at the SOCKS or raw HTTP protocol level, instead. Second, there is not much end users can do about the potential “history leak” problem when accessing static pages through the Internet Archive, translation services, or search engines’ cached page feature — so consider visiting such pages in an isolated private browsing mode session and close it immediately after use to minimize the risk.</p><p>Here I have demonstrated that mirroring external HTML and JavaScript content under a common subdomain is a risky proposition. Given the fact that the risks are to the sites being mirrored and end-users, and not the mirroring services themselves, it is possible that this issue has not received the attention it deserves. Admittedly, the security issues I’ve demonstrated arise only when the exact circumstances are met — not only in how the affected site makes use of web technologies, but also in the requirement that the victim user actually make use of the mirror service in question. Still, in the age of increasing global surveillance and spearphishing (consider the <a href="https://citizenlab.org/2016/08/million-dollar-dissident-iphone-zero-day-nso-group-uae/">use of a one million dollar iOS zero day exploit</a> against a UAE-based human rights activist), even special-case and farfetched violations of web security, at first glance, are worthy of investigation and mitigation.</p><p>¹ Here I ignore the difficulty of applying such rewriting to AJAX requests and other dynamically-generated requests that comprise modern websites.</p><p>² In fact, where two pages share a common parent domain it is possible to relax the same-origin policy via JavaScript’s <em>document.domain</em> or via the <em>domain</em> cookie attribute, but I am not doing that here.</p><p>³ Of course, in the real world this page would be served by HTTPS rather than HTTP, and would not “echo back” a stored credit card number.</p><p>Authored by <a href="https://medium.com/@jthompson_5338">Jacob Thompson</a>, a Senior Security Analyst <em>at </em><a href="http://www.securityevaluators.com/"><em>Independent Security Evaluators</em></a><em>.</em></p><p>Twitter<em>: </em><a href="https://twitter.com/ISEsecurity"><em>@ISESecurity</em></a></p><h4><a href="http://eepurl.com/bLc2bf">Sign up to get our latest blogs</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f93b17a02ec8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/independent-security-evaluators/a-breach-in-the-same-origin-policy-induced-by-mirroring-external-content-f93b17a02ec8">A Breach in the Same-Origin Policy Induced by Mirroring External Content</a> was originally published in <a href="https://medium.com/independent-security-evaluators">Independent Security Evaluators</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>