You are here: Home Blog BreakingPoint Labs Blog

Fighting JavaScript with JavaScript

In response to my previous blog post regarding a new clickjacking technique using link object href target replacement hooked to some of the link object's mouse events, I got a lot of questions asking how this target URL swap technique could be detected short of analyzing all the JavaScript on the page looking for this type of malicious code.  Automated detection through code analysis is a fairly difficult problem for a number of reasons, so I began thinking about this problem from the approach of detecting the result of the malicious code rather than the code itself.  Using that approach I wondered if you could fire potentially unknown event handlers, whatever they may be, without actually causing the event to happen.  Turns out you can:

<html>
   <head>
      <script id="SwapDetetctor" type="text/javascript">
         <!--
         function swapdetect() {
            var tp = window.frames[0];
            var pagelinks = tp.document.links;

            // Preserve the current links array
            var oldlinks = new Array();
            for( i=0; i<pagelinks.length; i++ ) {
            oldlinks[i] = pagelinks[i].href;
}

            // Fire all the links' mousedown and click events
            links = tp.document.getElementsByTagName('a');

            for( i=0; i<links.length; i++ ) {
               clickevent = tp.document.createEvent("MouseEvents");
               clickevent.initEvent("mousedown", true, true);
               links[i].dispatchEvent(clickevent);

               clickevent = tp.document.createEvent("MouseEvents");
               clickevent.initEvent("click", true, true);
               links[i].dispatchEvent(clickevent);
            }

            // Compare old values versus new values
            for( i=0; i<pagelinks.length; i++ ) {
               if( oldlinks[i] != pagelinks[i].href ) {
                    alert("Link target changed due to mouse event:\r\n" +
                    oldlinks[i] + "\r\nis now\r\n" +
                    pagelinks[i].href);
                 }
                }
         }

         setTimeout("swapdetect()", 10000);

         //-->
      </script>
   </head>

   <frameset rows="*" frameborder="no" border="0" framespacing="0">
      <frame name="targetpage" src="targetpage.html" height="100%" width="100%"/>
   </frameset>
</html>

What this bit of HTML and JavaScript does is load a target page into a frame, waits 10 seconds, and then calls the function swapdetect().  I used frames to approach interacting with the page as if it were in a pseudo-sandbox, however you could easily modify the above JavaScript to operate within the current window rather than target a frame or other window, just be sure to call swapdetect() after the page has finished loading and any other handlers for the page's 'onload' events have been called.

The function swapdetect() first creates a backup copy of the page's links array's href targets for later comparison.  It then creates event objects for the 'mousedown' and 'click' events, and uses those artificial events to dispatch the event handlers using the dispatchEvent() function (use fireEvent() on IE) for them (if any) on each link object found in the page's links array.  Due to this approach, only the event handlers are called; the actual event doesn't take effect.  This will cause the link swapping code in my previous blog post to do it's thing, which we can then detect.  The links array is then compared against the backup copy with the original targets to determine if any of the links' targets have changed, and create alert dialogs if so.  If you were so inclined, the same technique used in the link swapping code could be used in place of the alerts to restore the original link's href target value.

Posted by Dustin D. Trammell (2008/11/03 16:51:04.583 US/Central)
0 comments | Tags:

Clickjacking Technique Using the 'onmousedown' Event

A few weeks ago, Tod Beardsley wrote about (not) 'clickjacking' here on the BreakingPoint Systems blog.  He covered a number of techniques to accomplish generating a 'popup' window without triggering any of the traditional popup protections that some browsers feature.  The idea was essentially to cause the user to 'request' the popup, thus making it legitimate in the eyes of the browser.  Later, he covered his speculation on the 'real clickjacking' attack, which didn't use JavaScript at all but rather did some interesting CSS overlay trickery to hijack a link out from under the user as they clicked on it.

During some research that I was recently performing that I'll likely post about a little later, I discovered another technique that's a bit of a middle-ground between the two methods that Tod was discussing in his blog posts.  He came close to this one with his hooking of the 'onmouseup' event, however he was having it spawn a completely new window (the popup) in addition to following the link rather than 'jacking the click' and sending it somewhere entirely different.  This is essentially the same type of event hooking technique, but it is used to accomplish actual replacement of the link's target URL.

The following JavaScript function accepts as arguments a link object such as you would find in the document object's links array and a URL that you want to override the original link's URL with:

function AddJacker(link, url) {
if ( link.addEventListener ) {
      link.addEventListener("mousedown", function(e){link.href=url;}, false);
  } else if ( link.attachEvent ) {
     link.attachEvent("onmousedown", function(e){link.href=url;});
} else {
var oldhandler = link["onmousedown"];
     if ( oldhandler ) {
        link["onmousedown"] = function(e){oldhandler(e);link.href=url;};
     } else {
        link["onmousedown"] = function(e){link.href=url;};
     }
  }
}

What this essentially does is create an event handler for the 'onmousedown' event for the target link. When the user clicks on the link, the 'onmousedown', 'onclick', and 'onmouseup' events are fired.  Since the 'onmousedown' event happens first, the event handler is called which replaces the link object's href value with the new target URL, which happens before the user is sent on their way to that link's target URL.

The interesting bit about this technique in comparison to the 'onmouseup' technique that Tod was using is that it doesn't result in the user both going to the original target as well as the new target; they are only redirected to the new target, completely overriding the original target.  Like Tod's technique, because the new target URL is hiding in a function that is handling the 'onmousedown' event, a mouseover of the link in the browser indicates that it is still targeting the link's original URL.  The replacement of the URL doesn't happen until the user actually clicks on the link.

Posted by Dustin D. Trammell (2008/10/30 16:22:37.440 GMT-5)
1 comments | Tags:

The Difficulty With Testing Blacklists

I was recently directed to Greg Hoglund's new blog, Fast Horizon.  So far the few posts he's made have been excellent reading, and I generally agree with most of what he's been saying over there.  Just recently he put up a post entitled "Whitelists are the new snake-oil" where he convincingly outlines both why blacklisting is a failing approach to stopping malware (if it ever really worked in the first place), and why the whitelisting approach that many vendors are moving toward is equally doomed to failure.  Blacklisting is the current industry standard approach to stopping malware and is used in technologies such as anti-virus and anti-spyware software.  Blacklisting is also the approach that most network security device vendors take to blocking network attacks and exploits.  While firewalls are the obvious exception to this rule as they are essentially whitelist based, the vast majority of packets that get blocked, filtered, or identified by other network security devices such as IDS and IPS systems are done so via a match against a blacklist of traffic signatures.  These signatures are analogous to fingerprints of the known malicious data that traverses the network.  The following quote from Greg's post nicely sums up the difficulties with this approach:

"Blacklisting sounds ideal, but it doesn’t work. New malware emerges daily that has no corresponding blacklist signature. The malware must first be detected, and then processed. There is always a time window where Enterprises have no defense. Recent figures suggest that the AV vendors are falling so far behind this curve that they will never catch up with the deluge of new malware arriving daily. It can take weeks for a signature to become available.

This deluge of new malware is due to several factors. First, there is more money behind malware development than ever before. Second, we weren’t really that good at capturing malware in the past. Today, new malware can be automatically collected, without human intervention. The slow trickle of malware turned into a flood as honeypot technology emerged. Sensor grids can obtain new malware samples with efficiency - they automatically ‘drive by’ (aka spidering) malicious websites to get infections and leave open ports on the ‘Net so automated scanners will exploit them. In parallel to the automated collection efforts, cybercrime has risen to epic levels. Finally, the barrier to entry has dropped for the cyber criminal. Cyber weapon toolkits have become commonly available. Anti-detection technology is standard fare. New variants of a malware program can be auto-generated. A safe bet is to expect thousands of new malware to hit the Internet per day."

What he describes happening in the malware space is also happening within the attack and exploitation landscape.  Network attacks and exploits are becoming increasingly more dynamic and harder to fingerprint for a number of reasons.  As individual exploits increase the number of targets they can attack, which usually consist of various combinations of target software, the operating system running that software, patch-levels of both the software and operating system, the hardware architecture that both are running on, and any number of other target environmental factors, identifying a single exploit or vulnerability based on it's related network traffic becomes much harder.  When you then factor in all of the evasion techniques such as data massaging, reordering, randomizing, encoding, encrypting, tunneling, and any number of others, many of which have become standard in publicly available tools such as the Metasploit Exploitation Framework, the problem gets exponentially harder and you begin to approach the number of potential variants of a single attack or exploit that the malware folks are seeing in their space.

When faced with an ever-changing hostile network environment of malicious traffic, blacklists of signatures and filters that are developed to detect this data must be equally robust, and must be tested and verified with test cases that approach the dynamic nature and variation that you would see in the wild.

For further reading on dynamic security tests, please see my previous post entitled "File Format Vulnerabilities and Dynamic Exploit Generators" from a few weeks ago.  It helps make Greg's point in that it illustrates how many variants of a malicious file must be properly detected when even only a handful of fields of data within that file can change and it still be a working file format exploit.

Posted by Dustin D. Trammell (2008/07/02 14:09:55.425 GMT-5)
0 comments | Tags:

File Format Vulnerabilities and Dynamic Exploit Generators

File format vulnerabilities make for very interesting network security device test cases.  Due to their nature and how they're transported within network traffic, there are generally multiple layers of data structure, formatting, encoding, and potential obfuscation in play.  Not only must you consider the file format in question's own internal structure, but quite frequently there is further embedded content within that structure.  This entire file object, being it's own self-contained entity, is then potentially being sent over any number of various network transports.  Because the vulnerabilities usually lie in some anomalous use of the file format's internal structure, a bad value contained within that structure, or embedded content within the file, a network security device that intends to detect this maliciousness not only needs to be able to recognize it wherever in the network packet flow it may be, but also be able to reconstruct potentially fragmented data, decode potentially encoded data, and then identify the malicious bit itself.

To better illustrate this dilemma, let's take a look at the recent ms08-033 AVI/MJPG vulnerability.  AVI is essentially a RIFF file with some particular AVI-specific FourCC tagged LISTs and chunks.  The vulnerability here lies in the value of the "biHeight" field within the BITMAPINFOHEADER structure, which is essentially the AVI "stream format" ("strf") chunk.  This chunk is part of a "strl" LIST that describes an individual video stream contained within the file, which, along with other "strl" LISTs generally follow the main AVI header ("strh") chunk.  By populating the "biHeight" field with a negative value (I had success with values -1 through -31), you can trigger the vulnerability described in the advisory and cause Windows Media Player to crash.  Windows Media Player also doesn't seem to care too much about what Codec you indicate that the video stream should be processed with ("fccHandler") in the AVISTREAMHEADER.  Either Windows Media Player defaults unrecognized handlers to the MJPG Codec, or it determines where to send stream data with an unrecognized handler value based on recognizing the encoding method applied to the stream data itself.  Further explanation of the vulnerability can be found in a post by Mark Dowd over at ISS's Frequency X blog.

The strikes that are included in the Security component of the BPS product generally draw upon a back-end code-base that is capable of generating the various bits of data that are used during the strike's attack.  For file format vulnerabilities, this back-end is usually a dynamic file generator that can generate randomized, but still valid, files of the type in question.  This back-end is then coupled with individual strike descriptions which describe the parts of the attack such as various meta-data, the network connections involved, and what actual data is sent across the wire within those connections.  For file format vulnerabilities, the possibilities here are endless.  Due to the file being a self-contained unit, it can be sent from attacker to victim over any number of transports such as HTTP, FTP, POP3, SMTP, IMAP, peer-to-peer applications, tunneled protocols, embedded within other files, and so forth.  Many of these available transports also provide for multiple types of data encoding during transport, such as SMTP's Base64, Quoted-Printable, and UUEncoded variations.

For the ms08-033 example given above, we have developed 8 different transport-and-encoding-based strikes, each of which plug into the RIFF(AVI/MJPG)-generating back-end to dynamically generate the malicious file being transferred.  When you do the math on all of the permutations of the bits of data that a network security device either MUST (to properly detect the badness) or SHOULD (to avoid false positives) be included in a signature or filter for this vulnerability, not including everything else that is randomized by our RIFF-generating back-end, you end up with 1,065,151,889,408 (yes, that's just over one trillion) attack permutations, or malicious, vulnerability-triggering attacks.  These attacks can be produced via the eight ms08-033 strikes that will be included in our next StrikePack.  Any network security device's filters or signatures must be able to match on all of these permutations, do it reliably, and not false positive on legitimate AVI/MJPG files in order to legitimately claim coverage for this vulnerability.  A daunting task indeed.

 

Posted by Dustin D. Trammell (2008/06/17 16:45:04.494 GMT-5)
0 comments | Tags:

ToorCon Seattle 2008

The ToorCon organization puts on some of the best conferences in my opinion, and this last weekend was version 1.0 of their Seattle conference (beta was last year, which I also attended). Friday night was entirely 5-minute lightning talks and then Saturday was entirely 20-minute turbo talks. Sunday was workshops, which unfortunately I could not attend since I had to fly back to Austin mid-day. Last year was invite only and if you were there last year you received a coupon code for a discounted rate this year ($300), otherwise it was a little expensive to attend ($1000). Overall there were a number of excellent speakers with excellent content.

For my thoughts on the various presentations and talks that I saw, please click through to my Personal Blog.

Posted by Dustin D. Trammell (2008/04/22 14:20:00 GMT+0)

CSI-SX 2008

CSI-SX is the new branding for the CSI NetSec conference, which is co-located with Interop Las Vegas, and is essentially the security-focused portion of the overall conference. As with the annual CSI conference, this conference targets a different demographic than I'm used to speaking for as the attendance is usually comprised of very large enterprise and government employees and I usually speak for conferences targeted at the research and hacker communities.

The night before the first day of conference sessions a speaker reception was held which I attended. I met a number of people from the conference staff whom I had not met before as well as a few of the other speakers. Surprisingly I was well-received by this crowd, even with my spiked green hair, which I'm sure they don't see a lot of at this type of conference.

For my thoughts on the various presentations and talks that I saw, please click through to my Personal Blog.

Posted by Dustin D. Trammell (2008/04/30 02:00:00 GMT+0)

RFC-4475: SIP Torture Tests

As of the next upcoming StrikePack, the BPS product will now have test cases from RFC-4475, the SIP Torture Tests, in the form of strikes. The sections of the RFC that are covered by this StrikeSet are Section 3.1.2: Invalid Messages, Section 3.2: Transaction Layer Semantics, and Section 3.3: Application Layer Semantics. The remaining two sections containing test cases, Section 3.1.1: Valid Messages and Section 3.4: Backward Compatibility, are not covered as they are comprised of test cases which are valid SIP messages.

The strikes contained in this StrikeSet are intended to be used as part of a broader RFC-4475 test plan, and should not be used without full understanding of RFC-4475, the sections contained therein, and the individual test cases defined for each section. The strikes for Section 3.1.2: Invalid Messages are likely the only strikes from this test suite for which a pass/fail result in the UI will be valuable, as these are the only test cases from RFC-4475 which should be definitively blocked, rejected, dropped, or otherwise ignored by a SIP-aware Device Under Test (DUT) or a SIP endpoint. The remaining sections' individual test cases each define for themselves how a SIP-aware DUT or SIP endpoint should behave in response to that specific test case, and therefore will likely require external monitoring of either the network traffic or the device itself in order to determine a pass/fail verdict.

The strikes for the BPS RFC-4475 test suite will be available by searching for keyword "torture" in the BPS Attack Manager after applying the next upcoming StrikePack.

Posted by Dustin D. Trammell (2008-02-27 14:04:38)

SMB/CIFS AppSim Update

With the release of StrikePack 21889, the SMB/CIFS AppSim module has been improved from our first version which was released last week. Among the improvements are a number of customization options which are now exposed to the UI. First, the user can now provide their own custom data file to be used as payload data during file transfers, as well as indicate a file chunk size to be used for each request of a portion of the file being transferred. The user can also now configure session parameters for use such as client and server name, domain name, username, and password. If any of the available customization options are not modified by the user, they are randomized to provide each traffic flow with a unique set of session parameters.

Stay tuned for more upcoming improvements and expansions to the SMB/CIFS AppSim as well as the addition of new protocol modules as we continue to improve our Application Simulator component.

Posted by Dustin D. Trammell (2008-02-14 11:23:21)

SMB/CIFS Application Simulator

In our recent StrikePack 21396, SMB/CIFS application traffic simulation has been improved from standard SMB traffic to a more dynamic AppSim module. With the initial release of the new module two SMB flow scenarios have been included; an SMB NULL Session and an SMB/CIFS Client File Download. The former simulates an SMB NULL client connection to the server's IPC$ share. The latter however simulates an authenticated client connection to a shared resource on the server, performs a directory listing, then retrieves information about and downloads a file found there. With the first release of this AppSim module as delivered by the StrikePack mentioned above, these two traffic flows use fairly static data such as the filenames found in the directory listing of the shared resource and the data contained within the target file, although some customizations are exposed to the UI such as client hostname, server hostname, username, etc. In a forthcoming update however, many of the parameters for the Client File Download scenario will be randomized by default, and many more parameters will be exposed to the UI for customization by the user.

Posted by Dustin D. Trammell (2008-02-07 17:26:34)

MS07-061

Another Microsoft Patch Tuesday has arrived with another set of bugs, however this Tuesday we only had one which was ranked critical and as it turns out it's the bug that I was working on last week. The advisory, given the MSB number MS07-061, refers to the issue with the way Windows XP and 2003 improperly handle URIs. The attack vector that was being used to leverage this vulnerability in the wild was a behavioral issue with Adobe Acrobat, which could be made to silently instruct the OS to resolve a "mailto" URI from within a PDF document. Incidentally, resolving a URI this way required no user intervention, which made it a perfect attack vector since many browsers will use the Adobe Reader plug-in to render PDF documents directly in the browser. I began working on reproducing the attack using this pair of bugs last week due to finding out that they were actively being exploited in the wild, thus making them fairly interesting to me. You can read my summary in a previous post of mine, Adobe Acrobat and IE7 are the Best of Friends for the full details. At the time of that analysis, Adobe had patched Acrobat so that it would no longer resolve mailto URIs silently, but of course that was only half of the problem; finding other methods of having the OS resolve malicious URIs was entirely possible. Microsoft, however, has now patched their half of the problem via today's patch.

Posted by Dustin D. Trammell (2007-11-13 13:54:29)

Adobe Acrobat and IE7 Are the Best of Friends

Last week, the body of a SPAM e-mail was fowarded to Full-Disclosure as evidence of a Trojan being spread via a SPAM campaign. It turns out the Trojan being downloaded and installed was the latest Gozi variant (Gozi.F), and the delivery mechanism was a recently patched bug in Adobe Acrobat wherein a PDF could instruct IE7 to resolve a URI which would leverage a bug in Windows XP and Server 2003's URI handler when using IE7 causing it to execute arbitrary commands rather than resolve a legitimate URI. The interesting bit here is that the "bug" in Adobe Acrobat appears to be expected functionality, just with a slightly different behavior for the particular URI being passed.

Within the PDF specification nearly every piece of data is an object. Among other objects such as page tree nodes and catalogs, you have objects which can describe actions to be taken. You also have triggers, which you can think of as analogous to HTML/Javascript functionality such as OnLoad, OnMouseOver, etc. All the Adobe side of this attack does is define a trigger for when a page is opened (usually the first page in the PDF document since it will be opened and displayed first by default), which when triggered calls an action. The action in question is a URI action, which simply tells the OS to resolve a URI. The exploits being found in the wild use a malformed "mailto:" URI, which is passed into Windows to handle it. This causes the URI to get resolved by the system's default "mailto:" URI handler, in this case IE7. What's also interesting about the PDF URI object is that when given a "mailto:" URI, it does not prompt the user in any way prior to attempting to resolve the URI, thus providing a convenient vector for forcing resolution of a URI without user intervention. Other PDF action types, such as "Launch", which simply launches an application, and other URI types when included in a URI action object, generally pass the user a note in class looking something like this:


The user gets no such warning when Acrobat goes to resolve a "mailto:" URI, and it passes it to the Windows shell32 function ShellExecute() to handle it, which causes it to be resolved with the system's default URI handler for the particular type of URI. I'm not going to explain in detail how XP and Server 2003 differ in their handling of URIs from other Windows OSs, as it's already been explained fairly well by Microsoft already. Instead I'll provide a short dramatization (imagine some hand puppets) depicting the exchange between the OS's ShellExecute() function (SE) and IE7 (IE7):

*** SE tries to execute the URI ***

SE: "Hi IE7, this is ShellExecute()... You're the default handler for "mailto:" URI's, so I've got a URI for you today!"

IE7: "Allright! I'll go ahead and resolve that for you. Oh but wait, it looks malformed! That's no good, I can't resolve this..."

SE: "Oh well crap... hrm. Let me try to fix that up for you."

*** SE does some majiks on the URI and tries to execute it again ***

*** SE accidentally executes arbitrary commands ***

As of this posting, the Microsoft side of this attack is currently un-patched. The advisory can be found here.

So, how does this happen you ask? Let's analyze the exploit I created in detail. Due to the way PDFs are structured, this was about the smallest PDF I could create (given some random components) that will exploit the bugs involved:


Toward the end of the file you'll find the EOF marker and just before that the offset for the Cross References table (xrefs), and before that the file trailer which indicates which object is the Root object (Object 1). The Cross References table simply provides offsets to the various objects found in the file. Chaining from the Root object (at offset 0x0013), the Root object indicates the object containing the Page Tree Root Node (Object 2), which in turn indicates that there is 1 page and which object contains that (Object 3). The Page object (offset 0x0097) is essentially a blank page with an "additional action" (the /AA indicator) which indicates the action to take is found in Object 4 and is triggered by a Page Open event (/O). Finally, Object 4 (offset 0x00d2) contains the malicious URI. The badness in this particular URI is the percent sign (%), which is what causes ShellExecture() to execute the commands following it after it tries to clean up the URI and re-resolve it after it was rejected by IE7. In most of the malicious PDF files being found in the wild, rather than just benignly executing calc.exe, they're executing cmd.exe and passing in shell commands to download additional code via FTP and then executing that. In most cases, this second stage of execution installs a Trojan, bot, or rootkit.

pdp from GNUCitizen is credited with originally finding and disclosing these bugs to the appropriate vendors. CVE-2007-5020 and BID 25748 have been assigned for tracking this vulnerability.

[EDIT: Apparently, there may now be a way to automate the opening of the PDF by simply browsing to it in IE.]

Posted by Dustin D. Trammell (2007-11-01 11:25:03)

ToorCon 9 and Context-keys

Late last night I returned from ToorCon 9 in San Diego. I was able to make it out on time without any objections from the raging fires, but others I know were not quite as lucky. Even though the conference was awesome and San Diego, as always, had beautiful weather, it's nice to be back in Austin. This year I spoke at ToorCon on the subject of context-keyed payload encoders. You can view both the slides and video at my personal website if you're so inclined. For an extensive review of ToorCon 9 and all of the talks I attended, please click-through to my personal blog.

Posted by Dustin D. Trammell (2007-10-23 15:31:44)