Attacking Users: Cross-Site Scripting

  • One of the most prevalent web application vulnerabilities.
  • Less useful to lone hackers against an application, compared to injections and other vulnerabilities.
  • All previous attacks were direct and against the server-side app.
  • Some do affect user data, but did not primarily target the users.
  • Companies are shying away from publicly announcing critical security vulnerabilities
  • Key focus recently has been client-side vulnerabilities
    • Examples: Session fixation, Cross-site request forgery
  • Client-side attacks include:
    • Spyware, phishing, Trojans, etc.

Varieties of XSS

  • Reflected XSS (or First-Order XSS)
    • Craft a request with embedded JavaScript that can be reflected to a user who makes the request.
    • It is delivered and executed via a single request and response.
    • Dynamically generated error messages are commonly used for customized error pages that don't need to be hard-coded.
      • Book Example: Error page dynamically generated with a message parameter used to pass the body element text of that error page.
        • Insufficient processing of data and lack of limits on presentation.
    • One can embed JavaScript in a dynamically generated page just by passing a script element to a parameter.
    • Some browsers now will prevent attacks like this by modifying the webpage.
    • Exploiting it:
      • User logs in and application issues a cookie with a session token
      • The attacker feeds a URL with an embedded script to a user.
      • The user requests this URL
      • The server responds to the request, and the response is created
      • The user's browser gets the JavaScript and executes it
      • The JavaScript performs some malicious action.
        • e.g. The code makes a request to a domain, and the request contains the current session token of that user.
      • The attacker monitors requests to that domain, gets the user's request, and uses the captured token to hijack that user's session.
    • Browsers segregate content based on different origins or domains using what is called a "same-origin policy"
      • To capture a session token, a script must be used on that same domain to access cookies issued by them.
  • Stored XSS (second-order XSS)
    • Data submitted by a user is stored in the application and then displayed to other users with no proper filtering or sanitization.
    • Common in social media platforms, forums, blogs, etc.
    • Usually involve at least two requests
      • Post crafted data embedded with malicious code
      • User views the page and the malicious code is executed.
    • Don't need to have the victim visit a specifically crafted URL.
    • More easily executed as the session can be immediately hijacked.
  • DOM-based XSS
    • Process:
      • User requests a crafted URL with embedded JavaScript
      • Server response contains none of the embedded script
        • It simply has the current page source with JavaScript that will load content invoked by parameters.
      • The user's browser processes the response, and the script is executed regardlessly.
        • Processes data from a parameter, and then dynamically inserts into source.
    • The client-side Javascript can access the browser's document object model (DOM) and determine the URL used to load the current page.
      • Might extract data from URL, process it, and then dynamically update the page.

XSS Attacks in Action

  • Real-World XSS Attacks
    • 2010: Apache Foundation compromised via reflected XSS attack in its issue-tracking app.
    • 2005: Myspace vulnerable to stored XSS attack
  • Payloads for XSS Attacks
    • Virtual Defacement
      • Inject malicious data into a page to feed misleading information to users of the application.
    • Injecting Trojan Functionality
      • Inject functionality to the application, whereby that functionality masquerades as a normal component, but performs some malicious actions.
        • False login forms
    • Inducing User Actions
      • Use injected scripts to cause users to perform actions.
      • May automatically force users to attempt to upgrade permissions of an account, brute forcing until an administrator performs the actions via the injected scripts.
    • Exploiting Any Trust Relationships
      • Exploiting trust of content from the same domain
      • Trusting autocomplete enabled forms in an application with previously entered data saved in an autocomplete cache.
      • Some sites recommend adding themselves to a user's browser Trusted Sites zone. Can then perform code execution on the user machine, using things like ActiveXObject('WScript.shell')
    • Escalating the Client-Side Attack
  • Delivery Mechanisms for XSS Attacks
    • Delivering Reflected and DOM-Based XSS Attacks
      • Forged email sent to users. Can say that a URL is causing an error to an admin. Is principally called Spear Phishing.
      • Send using URL in an instant message
      • Can generate requests that trigger XSS flaws by using third-party websites.
      • Malicious banner advertisements
      • "Tell a friend" or feedback functionalities that can be used to send arbitrary content to users.
    • Delivering Stored CSS Attacks
      • In-band
        • Personal information fields, names of documents, feedback or questions, messages, statuses, comments.
        • Application logs and displayed in the browser.
        • Contents of uploaded files.
      • Out-of-band
    • Chaining CSS and Other Attacks
      • Example:
        • Stored XSS vulnerability with username. Can also change display name of other users due to defective access controls. Using this, a user can inject a script into the display name of all users, forcing it to run on display of the name.

Finding and Exploiting XSS Vulnerabilities

  • Description

    • Often use a proof of concept like:
      • "><script>alert(document.cookie)</script>
    • Many applications employ blacklist filters. Can use any permutation of that same code, which may be able to bypass the filter. Consider encoding, nesting, etc.
  • Finding and Exploiting Reflected XSS Vulnerabilities

    • Process:
      • Input alphabetical string in every entry point
        • Try GET and POST requests.
      • ID locations where string is sent back reflected
      • ID the syntactic context that the reflected data appears
      • Submit modified data to try and induce a script into the response
      • If reflected data is blocked/sanitized, attempt circumventing the controls.
    • Testing Reflections to Introduce Script
      • Example
        • If a response includes:
          • <input type="text" name="andrew" value="testvalue">
        • Attempt injecting some javascript:
          • "><script>alert(1)</script>
        • Or injecting an event handler
          • " onfocus="alert(1)
    • Probing Defensive Filters
      • Three possibilities of server modification of user input:
        • Application or web application firewall identified attack signature and blocked input
        • Application accepted input but performed sanitization or encoding
        • Application truncated attack string to a fixed maximum length
    • Beating Signature-Based Filters
      • Ways to Introduce Script Code
        • Script Tags
        • Event Handlers
          • onreadystatechange=<FUNCTION>
          • onerror=<FUNCTION>
          • onpropertychange=<FUNCTION>
        • Script Pseudo-Protocols
          • Can use VBS protocol or JavaScript pseudo-protocols where inline script is used in an attribute expecting a URL.
          • Examples:
            • <object data=javascript:alert(1)>
            • <iframe src=javascript:alert(1)>
            • <embed src=javascript:alert(1)>
            • form id=test /><button form=test formaction=javascript:alert(1)>
            • <event-source src=javascript:alert(1)>
        • Dynamically Evaluated Styles
          • Some browsers support dynamically evaluated CSS
          • Examples:
            • <x style=x:expression(alert(1))>
            • <x style=behavior:url(#default#time2) onbegin=alert(1)>
      • Bypassing Filters: HTML
        • The Tag Name
          • Capitalization of tags, using NULL bytes at any position
            • NULL bytes work great against web application firewalls.
        • Space Following the Tag Name
          • Use various characters that work fine between the tag name and the first attribute name
            • e.g. /, [%09], [%0d], [%0a], /", /', /COMMENT/
        • Attribute Names
          • Use the same tricks of the tag names for the attribute names
        • Attribute Delimiters
          • Use double/single quotes (or if in IE, backticks) to delimit attributes
        • Attribute Values
          • Same tricks as Attribute Names and Tag Names
        • Tag Brackets
          • Some applications perform URL decoding, but by double encoding, bracket filters can be bypassed.
            • %253cimg%20onerror=alert(1)%20src=a%253e becomes %3cimg onerror=alert(1) src=a%3e which becomes <img onerror=alert(1) src=a>
          • An application may also translate certain Unicode characters to their translations. So, using double-angle quotation marks
        • Character Sets: Use nonstandard encoding for payloads.
          • UTF-7
          • US-ASCII
          • UTF-16
      • Bypassing Filters: Script Code
        • Using Javascript Escaping
          • Use JavaScript escaping
          • \u006 - Unicode Escaping
          • \x6 - Hexadecimal escape
          • \154 - Octal Escapes
        • Dynamically Constructed Strings
          • eval('al' + 'ert(1)')
          • eval(String.fromCharCode(97, 108, 101, 114,.......))
          • eval(atob('.......'))
            • Decode a Base64 encoded command
        • Alternatives to eval
          • 'COMMAND'.replace(/.+/,eval)
          • function::'FUNCTION'
        • Alternatives to Dots
          • <script>alert(document['cookie'])</script>
          • <script>with(document)alert(cookie)</script>
        • Combining Multiple Techniques
        • Using VBScript
          • Can use VBScript in Internet Explorer
            • <script language=vbs>MsgBox 1</script>
            • <img onerror="vbs:MsgBox 1" src=a>
            • <img onerror=MsgBox+1 language=vbs src=a>
        • Combining VBScript and JavaScript
          • Can combine them both, bypassing filters easily by dynamically generated code.
        • Using Encoded Scripts
          • Can use Microsoft's custom script-encoding algorithm to hide VBScript and JScript in an encoded manner.
            • <img onerror="VBScript.Encode:#@~^CAAAAA==\ko$K6,FoQIAAA==^#~@" src=a>
            • <img language="JScript.Encode" onerror="#@~^CAAAAA==C^+.D`8#mgIAAA==^#~@"
            • src=a>
      • Beating Sanitization
        • Determine which characters are being sanitized
        • Nesting, duplication, encoding, NULL bytes, etc
      • Beating Length Limits
        • Shorten the attack payload
          • Remote execution
        • Execute it in parts. Use vulnerable parameters and split amongst them.
        • Convert a reflected XSS flaw into a DOM-based vulnerability.
      • Delivering Working XSS Exploits
        • Escalating an Attack to Other Application Pages
          • Persistance is key. Cause the exploit to persist in the browser.
          • Can create an iframe covering the browser window and reload the current page in the iframe. As they navigate the site, the injected script keeps running and can hook into all navigation events and form submissions.
        • Modifying the Request Method
          • Try different requests to bypass a filter.
        • Exploiting XSS Via Cookies
          • Application may allow using a URL or body parameter with the same name as a cookie to trigger a vulnerability
          • Devise a cross-site request forgery attack setting the required cookie in the user's browser.
        • Exploiting XSS in the Referer Header
          • Use a web-server controlled by the attacker. The attacker's server returns a response to a user's request that includes a payload in the referer header.
            • May need to use it on the same site, so leverage redirect functions on the site.
        • Exploiting XSS in Nonstandard Request and Response Content
          • Requirements:
            • Need to find way of causing user to make a request cross-domain
              • Typically done using XMLHttpRequest
            • Need to find means of manipulating response so it executes script in browser.
              • The browser may have the content-type header changed to whatever the non-standard format it.
          • Sending XML Requests Cross-Domain
            • Send data in an HTTP request using an HTML form with the enctype attribute set to text/plain.
              • Causes browser to:
                • Send parameters on separate lines in the request
                • Use equal signs to separate names and values of parameters
                • Not perform URL encoding of parameter names/values.
          • Executing JavaScript from Within XML Responses
            • May need to inject script by leveraging syntactic features of the format.
        • Attacking Browser XSS Filters
          • IE XSS Filter has these main operations:
            • Cross-domain requests have parameter values inspected for injected JavaScript
            • Checks to see if malicious parameter causes corresponding output in the response
            • If value shows up in response, the response is sanitized to prevent script from running.
          • Bypassing methods:
            • Only parameter values are considered, not parameter names. So, leverage parameter names.
            • Span an attack across multiple parameters since each parameter value is inspected.
            • Cause an "on-site" request for an XSS URL. This is not blocked as only cross-domain requests are inspected.
            • Use unexpected characters, like NULL bytes.
  • Finding and Exploiting Stored XSS Vulnerabilities

    • Process:
      • Submit unique string to all possible locations, and look for corresponding data in the response.
        • Try multiple request methods, principally GET or POST.
      • Inspect all admin accessible areas to ID appearance of data controllable by non-administrators.
      • Test all parameters, HTTP headers, etc.
      • Probe uploaded and downloaded file functionalities for stored XSS attack vulnerabilities.
    • Testing for XSS in Web Mail Applications
      • They include HTML content received from third parties in application pages displayed to users.
      • Send all types of weird HTML using emails.
      • Can use sendmail command on UNIX and pass it crafted emails.
        • Just embed scripts and other input in the email.
    • Testing for XSS in Uploaded Files
      • Considerations:
        • Restrictions on file extensions
        • Inspection of file contents for compliance with format standards
        • May respond with assumed Content-Type header
        • May respond with Content-Disposition header, specifying the browser should save the file to disk.
        • If it accepts a file containing HTML despite having a different file extension, it may be vulnerable.
          • Some browsers may still process it as HTML.
          • Older versions of IE processed things like this as HTML so long as it wasn't requested via img tags.
      • Hybrid File Attacks
        • Can combine multiple formats in the same file.
        • GIFAR files contain data in GIF and JAR format. Metadata fro GIF is at the start and JAR is at the end.
          • Find an application where GIF files are uploaded by one user and can be downloaded by others.
          • Construct a GIFAR file with java code that hijacks the session of a user.
          • Attacker uploaded this file as a picture.
          • Use an external website to deliver attack leveraging the uploaded file.
          • On the external site, use an applet or object tag to load the GIFAR file
          • When user visits the external site, the attacker's java applet executes in his browser.
            • Java applets have a different same-origin policy. They act as if they were loaded from the domain from which it was loaded, not from where it was invoked.
          • NOTE: This is prevented in current versions of Java browser plug-in
      • XSS in Files Loaded Via Ajax
        • Ajax used in some applications for retrieving or rendering URLs specified after the fragment identifier.
        • Uses Ajax to retrieve a file shown after the fragment and sets response within the innerHtml of a div element.
          • May be able to upload a valid image file with embedded HTML markup and construct a URL causing the client-side code to request the image and display as HTML
  • Finding and Exploiting DOM-Based XSS Vulnerabilities
    • Manually walk through an application, modifying URL parameters with
      • "<script>alert(1)</script>
      • ";alert(1)//
      • '-alert(1)-'
    • Display returned pages to see if script is executed.
      • Can be automated with a tool using a Javascript interpreter.
    • Process:
      • Try changing any of the following:
        • document.location
        • document.URL
        • document.URLUnencoded
        • document.referrer
        • Window.location
      • Review all components where data is passed to:
        • document.write()
        • document.writeln()
        • document.body.innerHtml
        • eval()
        • window.execScript()
        • window.setInterval()
        • window.setTimeout()
    • Bypassing defenses:
      • Use a new, random parameter name with a value of the script
      • Use a fragment character (#) to evade the filter

Preventing XSS Attacks

  • Preventing Reflected and Stored XSS
    • Validate Input
      • Not too Long
      • Contains only permitted set of characters
      • Matches a particular regular expression
    • Validate Output
      • HTML encode user originated data
        • Use simple HTML encoding or APIs that with the functionality.
    • Eliminate Dangerous Insertion Points
      • Prevent any insertion of user data into script code
        • Includes script tags and event handlers
      • Avoid embedding user input
      • Explicitly specify encoding types in response headers, prevent modification of this, and ensure XSS filters work with it.
        • Allows for the prevention of manipulating character set.
    • Allowing Limited HTML
      • Prevent user generated embedded scripts where possible
        • Validate normal HTML tags for script methods, like onbegin.
  • Preventing DOM-Based XSS
    • Validate Input
      • Query strings only contain a single parameter
      • Parameter name is message and case sensitive
      • Parameter value only is alphanumeric
    • Validate Output
      • Perform HTML encoding

results matching ""

    No results matching ""