1, Vulnerability name

Storage type XSS Cross site scripting , Reflex type XSS Cross site scripting

2, Vulnerability description

The full name of cross site scripting attack is Cross Site
Script, To differentiate from style sheets , The abbreviation is XSS. The reason for this is that the website outputs the user input to the page , During this process, malicious code may be executed by the browser . Cross site scripting attack, which refers to malicious attackers to Web Insert malicious in the page JavaScript code , When the user browses the page , Embedded in it Web Inside JavaScript The code will be executed , In order to achieve the special purpose of malicious users .XSS It's a passive attack , Because it's passive and hard to use , So many people often call out its harmfulness . But this article mainly talks about the utilization XSS Get the target server's shell. Technology is old technology , But I hope it will help you .

There are three known cross site scripting vulnerabilities :1) Storage type ;2) Reflective ;3) be based on DOM( File object model ).

1, Function points involved in storage cross site scripting attack : The text information entered by the user is saved to the database , And can be displayed in the page function point , For example, users leave messages , Send in station message , Personal information modification and other function points .

2, Function points involved in reflective cross site scripting attack :URL Parameters need to be displayed in the page function points may have reflective cross site scripting attacks , For example, on-site search , Query function point .

3, be based on DOM Function points involved in cross site scripting attack : involve DOM Object's pager , include ( There's no limit to that ):
document.URL document.URLUnencoded document.location document.referrer window
.location
3, Detection conditions

1, Known target URL, Suppose it is http://www.exmaple.com/page.xxx

2, Parameter input of the target to be measured , Or with POST Mode submission parameters , Show as form , Suppose it is name=value

3, In some cases , User input is redisplayed on the web page , Including the name , accounts , Search results and so on ( This indicates that the target website server does not detect the user submitted data )

4, test method

GET Mode cross site script :

1, Add the following statements one by one after the entered parameters , Take article one for example , input
http://www.exmaple.com/page.xxx?name=<script>alert(123456)</script>
Just one of them pops up 123456 Alarm box for , It shows that there are cross site vulnerabilities , Record vulnerabilities , Stop the test .

2, If there is no pop-up display 123456 Alarm box for , Right click the returned page , choice “ view source ”.

3, Find if the web source contains a complete string <script>alert(123456)</script>
, Whether it pops up or not 123456 Alarm box for , Both indicate that there is a cross site scripting vulnerability .

4, Because of some HTML element ( such as <textarea> or ”
) Will affect the execution of the script , So it doesn't have to pop up correctly 123456 alert box , According to the content of the returned web page source file , structure value Value of , such as :
Multiline text input box : </textarea><script>alert(123456)</script> Text input box : </td><script>alert(
123456)</script> '><script>alert(123456)</script> "><script>alert(123456)</
script> </title><script>alert(123456)</script> --><script>alert(123456)</script>
[img]javascript:alert(123456)[/img]<scrip<script>t>alert(123456)</scrip</script
>t> </div><Script>alert(123456)</script>
You need to test all the places on the page where you can submit parameters . The test statements of specific cross site scripts vary according to the actual situation , Self construction , And trigger events , Only some of the most common construction statements are listed here .
Post Mode cross site script :

1, stay POST Enter the following statements one by one in the form , Just one of them pops up 123456 Dialog box for , It shows that there are cross site vulnerabilities , Record vulnerabilities , Stop the test .

2,<script>alert(123456)</script>

3,[img]javascript:alert(123456);[/img]

4, If there is no pop-up display 123456 Alarm box for , Right click the returned page , choice “ view source ”

5, Whether the complete web page string contains a search file <script>alert(123456)</script>
, Whether it pops up or not 123456 Alarm box for , Both indicate that there is a cross site scripting vulnerability

6, Because of some HTML element ( such as <textarea> or ”
) Will affect the execution of the script , So it doesn't have to pop up correctly 123456 alert box , According to the content of the returned web page source file , structure value Value of , such as :
Multiline text input box : </textarea><script>alert(123456)</script> Text input box : </td><script>alert(
123456)</script> '><script>alert(123456)</script> "><script>alert(123456)</
script> </title><script>alert(123456)</script> --><script>alert(123456)</script>
[img]javascript:alert(123456)[/img]<scrip<script>t>alert(123456)</scrip</script
>t> </div><Script>alert(123456)</script>
You need to test all the places on the page where you can submit parameters . The test statements of specific cross site scripts vary according to the actual situation , Self construction , And trigger events , Only some of the most common construction statements are listed here .
If filtered , The following bypass methods can be used :

1, Code bypass . for example HTML code .

2, You can also try other tags , Detect which sensitive keywords are not filtered ( for example <script> Filtered , have access to <img> Wait for the label to test ).

3, Case mix . It's possible that only lowercase is filtered .
“onfocus=” alert(document.cookie) // If the filter < > Symbol <scr<script>ipt>alert(123456)</
script> // You can also nest bypasses <sCrIPt>alert(123456)</ScRiPT> //alert Never use case
5, Restoration plan

It is recommended to verify all input data , Effective detection of attacks ; Code all output data appropriately , To prevent any scripts that have been successfully injected from running on the browser side . The details are as follows :

A, Overall repair mode :

Verify all input data , Effective detection of attacks ; Code all output data appropriately , To prevent any scripts that have been successfully injected from running on the browser side . The details are as follows :

Input validation : Before a data is accepted for display or storage , Use standard input validation mechanism , Verify the length of all input data , type , Syntax and business rules .

Output coding : Before data output , Ensure that the data submitted by the user has been carried out correctly entity code , It is recommended to encode all characters, not just a subset .

Specify the encoding of the output : Don't allow attackers to choose the encoding for your users ( as ISO 8859-1 or UTF-8)

Pay attention to the limitation of blacklist verification method : Just find or replace some characters ( as "<" ">" Or similar "script" Keywords for ), It's easy to be XSS Variant attack bypasses verification mechanism .

Guard against standardization errors :
Before verifying input , Must be decoded and normalized to conform to the current internal representation of the application . Make sure that the application does not decode the same input twice . Filter the data submitted by the client , It is generally recommended to filter out double quotes (”), Angle brackets (<,>) And other special characters , Or entity conversion of special characters contained in the data submitted by the client , Like double quotation marks (”) To its physical form
",< The corresponding entity form is <,< The corresponding entity form is >.
Here are some common characters to filter : [1] |( Vertical bar symbol ) [2] & (& Symbol ) [3] ;( semicolon ) [4] $( Dollar sign ) [5] %( Percentage symbol ) [6]
@(at Symbol ) [7] '( Single quotation mark ) [8] "( Quotation marks ) [9] \'( Backslash escape single quotation mark ) [10] \"( Backslash escape quotation mark ) [11] <>( Angle brackets ) [12
] ()( brackets ) [13] +( plus ) [14] CR( Carriage return ,ASCII 0x0d) [15] LF( Line break ,ASCII 0x0a) [16] ,( comma ) [
17] \( Backslash ) Escape key characters in the request return page . [1] “( Double quotation marks ):" [2] ’ ( Single quotation mark ):&apos [3] &(& Symbol ):& [
4] <( Left angle bracket ):< [5] >( Right angle bracket ):> Without affecting the application , It is suggested that cookie Marked as httpOnly, It is also disabled TRACE method .
B, about java Ongoing web The filters for business development are as follows :


In use java conduct web Business development , For parameters received on the page , Except for a few things that are predictable , A large number of parameter names and values are not triggered Xss Character of vulnerability . And usually to avoid Xss loophole , The developers add various kinds of data to the page output and data storage encode Methods to avoid Xss problem . However, due to the different levels of developers , Plus the difference in security awareness in the process of writing code , It may be careless to miss the user input encode handle . It is impossible for such a large number of parameters to appear Xss and SQL In the business scenario of injecting vulnerabilities , Therefore, you can use a common processing method for most business scenarios , Sacrifice a small amount of user experience , To avoid Xss Loopholes and SQL injection .


utilize Servlet Filter mechanism of , Write custom XssFilter, take request Request agent , cover getParameter and getHeader Method to set the specified half width character in the parameter name and parameter value , Force replace with full width characters . So that there will be no need to worry about the abnormal input content when processing in the business layer .
XssFilter.java package filter; import java.io.IOException; import
javax.servlet.Filter; import javax.servlet.FilterChain; import
javax.servlet.FilterConfig; import javax.servlet.ServletException; import
javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import
javax.servlet.http.HttpServletRequest;public class XssFilter implements Filter {
public void init(FilterConfig config) throws ServletException { } public void
doFilter(ServletRequest request, ServletResponse response,FilterChain chain)
throws IOException, ServletException { XssHttpServletRequestWrapper xssRequest =
new XssHttpServletRequestWrapper((HttpServletRequest)
request);chain.doFilter(xssRequest, response); }public void destroy() { }
XssHttpServletRequestWrapper.javapackage filter; import
javax.servlet.http.HttpServletRequest; import
javax.servlet.http.HttpServletRequestWrapper; }public class
XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
HttpServletRequest orgRequest =null; public XssHttpServletRequestWrapper
(HttpServletRequest request) { super(request); orgRequest = request; }
// cover getParameter method , Do both parameter name and parameter value xss filter .<br/>
// If you need to get the original value , Then the super.getParameterValues(name) To get <br/>
//getParameterNames,getParameterValues and getParameterMap It may also need to be covered public String
getParameter(String name) { String value = super.getParameter(xssEncode(name));
if (value != null) { value = xssEncode(value); } return value; }
// cover getHeader method , Do both parameter name and parameter value xss filter .<br/>
// If you need to get the original value , Then the super.getHeaders(name) To get <br/> //getHeaderNames It may also need to be covered public
StringgetHeader(String name) { String value = super.getHeader(xssEncode(name));
if (value != null) { value = xssEncode(value); } return value; }
// Will easily cause xss The half width character of the vulnerability is directly replaced by the full width character private static String xssEncode(String s) { if (s ==
null || s.isEmpty()) { return s; } StringBuilder sb = new
StringBuilder(s.length() +16); for (int i = 0; i < s.length(); i++) { char c =
s.charAt(i);switch (c) { case '>': sb.append('>'); // Full angle greater than sign break; case '<':
sb.append('<'); // Full angle less than sign break; case '\'': sb.append('‘'); // Full width single quotation mark break; case
'\"': sb.append('“'); // Full length double quotation marks break; case '&': sb.append('&'); // Full angle break; case
'\\': sb.append('\'); // Full angle diagonal break; case '#': sb.append('#'); // Full angle well No break;
default: sb.append(c); break; } } return sb.toString(); } // Get the most primitive request public
HttpServletRequestgetOrgRequest() { return orgRequest; } // Get the most primitive request Static method of
public static HttpServletRequest getOrgRequest(HttpServletRequest req) { if(req
instanceof XssHttpServletRequestWrapper){return
((XssHttpServletRequestWrapper)req).getOrgRequest(); }return req; } }
--------------------------------------------------------------------------------
stay web.xml Add : <filter> <filter-name>xssFilter</filter-name>
<filter-class>filter.XssFilter</filter-class> </filter> <filter-mapping>
<filter-name>xssFilter</filter-name> <url-pattern>/*</url-pattern>
</filter-mapping>
C, about PHP Language written by the website system XSS filter :
<?php function RemoveXSS($val) { $val = preg_replace(
'/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val); $search =
'abcdefghijklmnopqrstuvwxyz'; $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; $search
.='[email protected]#$%^&*()'; $search .= '~`";:?+/={}[]-_|\'\\'; for ($i = 0; $i <
strlen($search); $i++) { $val = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search
[$i])).';?)/i', $search[$i], $val); $val = preg_replace('/(�{0,8}'.ord($search
[$i]).';?)/', $search[$i], $val); } $ra1 = Array('javascript', 'vbscript',
'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script',
'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound',
'title', 'base'); $ra2 = Array('onabort', 'onactivate', 'onafterprint',
'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut',
'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint',
'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange',
'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut',
'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick',
'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave',
'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate',
'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp',
'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload',
'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove',
'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend',
'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset',
'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit',
'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange',
'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload'); $ra = array_merge
($ra1, $ra2); $found = true; while ($found == true) { $val_before = $val; for (
$i = 0; $i < sizeof($ra); $i++) { $pattern = '/'; for ($j = 0; $j < strlen($ra[
$i]); $j++) { if ($j > 0) { $pattern .= '('; $pattern .=
'(&#[xX]0{0,8}([9ab]);)'; $pattern .= '|'; $pattern .= '|(�{0,8}([9|10|13]);)'
;$pattern .= ')*'; } $pattern .= $ra[$i][$j]; } $pattern .= '/i'; $replacement
= substr($ra[$i],0,2).'<x>'.substr($ra[$i], 2); $val = preg_replace($pattern,
$replacement, $val); if ($val_before == $val) { $found = false; } } } return
$val; } // Test the effect //echo RemoveXSS("<script language='javascript'>alert('hello
world');</script>") ; ?>
D,asp The program website appears SQL injection , Cross site scripting attack (XSS) It can be used when there are loopholes
The source code is as follows :url=trim(request("url")) It is amended as follows :url=Server.HTMLEncode(trim(request("url")))
use Server.HTMLEncode It solves the script cross site attack vulnerability perhaps :
For user input area, only the required characters required to adapt to the application function are allowed , For legal “>”,“<”“&” These three symbols are replaced :replace(str,"<","<")
replace(str,">",">") replace(str,"&","&")
6,XSS Protection

Spring MVC protect
Project level filtering : <context-param> <param-name>defaultHtmlEscape</param-name> <param-value>
true</param-value> </context-param> Page level filtering : Include in form Of jsp Add <spring:htmlEscape
defaultHtmlEscape="true" /> Form element level filtering : stay form Element <form:form htmlEscape="true"> or <
form:input path="someFormField" htmlEscape="true" />
7,DOM XSS Detailed explanation

Document object model (Document Object
Model), It's famous DOM.DOM It can be thought of as a tree representation of page elements , So that Javascript The realization method of organization processing . be based on DOM The cross site scripting vulnerability of can be executed in many cases , There is no need for the server to determine what needs to be performed . This may lead to many general cross site scripting filtering and detection rules unable to deal with such attacks .

The first hypothetical case uses the following client code :
<script>document.write("Siteisat:"+document.location.href+".");</script>
An attacker may append to the infected page #<script>alert('xss')</script>, Causes a warning box to appear when the script is executed . under these circumstances , Because the browser thinks that #
None of the characters are part of the query , It's just a piece , Therefore, additional code is not sent to the server . In this case , Immediate execution code will be displayed in the web page “ Cross site scripting ” alert . Common cross site scripts ( Persistent and non persistent ) The code for is sent to the server , And redisplay it to the user . Unlike these, this code will only be executed immediately on the user's browser .

be based on DOM Cross site scripting vulnerability testing for

User input comes from two main forms :
1, The server is not allowed to directly XSS The input written to the web page 2, From client JavaScript Object to get the input
The following two examples show how the server inserts data into the JavaScript:
var data = "<escaped data from the server>"; var result = someFunction(
"<escaped data from the server>");
The following is from the client JavaScript Object input :
var data = window.location; var result = someFunction(window.referer);

Because automated testing usually sends specific payloads and attempts to observe them in the server's response , This results in the determination and validation of DOM Of XSS The success rate is very low . It can still play a certain role in the following cases , The information parameters will be fed back to users :
<script> var pos=document.URL.indexOf("message=")+5; document.write(document
.URL.substring(pos,document.URL.length)); </script>
But the following human cases are not detectable :
<script> var navAgt = navigator.userAgent; if (navAgt.indexOf("MSIE")!=-1) {
document.write("You are using IE: " +document.location.href + "."); } else{
document.write("You are using an unknown browser."); } </script>
For this reason , Unless the test tool can perform more analysis on the client code , Otherwise, automated testing cannot detect the DOM Of XSS Sensitive areas .


Therefore, manual testing can be used to detect areas in the code , The parameters in the code can be exploited by attackers . These areas include : Code areas and other modifications that are dynamically written to the page DOM Area of , Or the area where the script is executed directly .