SDU project training -- xss filter function realization

Introduction to XSS attack

What is an XSS attack?

The Chinese name of XSS (Cross Site Scripting) is: Cross Site Scripting attack. The focus of XSS is not on cross site, but on script execution. The principle of XSS is:
A malicious attacker will insert some malicious script code into the web page. When the user browses the page, the script code embedded in the web page will execute, so it will achieve the purpose of malicious attack on the user. The XSS attacks mainly fall into the following categories: reflection type, storage type, and DOM based type. Reflective and DOM based types can be classified as non persistent XSS attacks. Storage type can be classified as persistent XSS attack.

Reflective XSS

The principle of reflective XSS is: reflective XSS generally means that an attacker tempts the victim to visit a URL containing malicious code in a specific way. When the victim clicks the malicious link URL, the malicious code will be directly executed in the browser on the victim's host.
Reflective XSS can also be called non persistent XSS. Why is it called reflective XSS? That is because the injected code of this attack mode is reflected from the target server through error messages, search results, etc. why is it called non persistent XSS? That's because this attack is only one time.
For example, the attacker sends a malicious link containing the injection script to the victim through e-mail. When the victim clicks the link, the injection script is transmitted to the target server, and then the server "reflects" the injection script to the victim's browser, so that the browser executes the script.
Therefore, the attack steps of reflective XSS are as follows:
1. the attacker adds malicious attack code to the parameters after the url.
2. when the user opens a URL with malicious code, the website server takes the malicious code out of the URL, splices it into html and returns it to the browser.
3. the user browser will execute parsing after receiving the response, and the malicious code will also be executed.
4. the attacker steals user data through malicious code and sends it to the attacker's website. An attacker may obtain information such as cookie s, and then use this information to impersonate a legitimate user and call the target website interface to perform attacks and other operations.

Storage XSS

Compared with reflective XSS, storage XSS is more durable and can be stored in the background, which is more harmful. The malicious data input by the attacker is saved in the database, and then the server script program reads the data from the database and displays it on the fixed page of the public display. Then all users browsing the page will be attacked. This type is very aggressive and dangerous. The malicious data entered by the attacker is stored in the database, and then the server script program reads the data from the database. Therefore, most of the stored XSS vulnerabilities occur on form submission.

Attack steps:
1. The attacker's web page post contains JS script
2. After the reply is submitted to the server, it is stored in the database
3. Other netizens view the post, query the reply content of the post in the background, build a complete web page, and return to the browser
4. The net friend's browser rendered the returned web page, and was hit!

Test on the range:

xss attack code demo

<!DOCTYPE html>
  <meta charset=utf-8>
  <meta name="referrer" content="never">
  <title>csrf attack</title>
    <a href="http://Localhost:3001/xss ">xxs attack</a>
    <a href="http://Localhost:3001/testcookie ">testcookie attack</a>
const Koa = require('koa');
const fs = require('fs');
const path = require('path');
const router = require('koa-router')();
const koaBody = require('koa-body');
const static = require('koa-static');

const app = new Koa();

router.get('/', (ctx, next) => {
  // Set the header type. If it is not set, the page will be downloaded directly
  ctx.type = 'html';
  // read file
  const pathUrl = path.join(__dirname, '/static/index.html');
  ctx.body = fs.createReadStream(pathUrl);

router.get('/xss', (ctx, next) => {
  ctx.body = '<script>alert("Reflex type XSS attack")</script>';
router.get('/testcookie', (ctx, next) => {
  ctx.body = '<script>alert("'+ctx.cookies.get('connect.sid')+'")</script>';



app.listen(3001, () => {
  console.log('server is listen in 3001');

XSS prevention methods

Java Web Filter (@WebFilter)

In fact, the filter is to intercept web resources, do some processing, and then hand them over to the next filter or servlet for processing; It is usually used to intercept request s for processing, or intercept the returned response. It is mainly used for automatic login, unified coding format setting, access control, sensitive character filtering, etc.
After creating the default code, you can see that CharsetFilter implements the Filter interface and implements three methods.

package filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
@WebFilter(filterName = "CharsetFilter")
public class CharsetFilter implements Filter {
    public void destroy() {
        /*Called on destroy*/
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        /*Filtering method 
            1.It mainly deals with the request and response, and then passes them to the next filter or Servlet for processing
        chain.doFilter(req, resp);//Leave it to the next filter or servlet
    public void init(FilterConfig config) throws ServletException {
        /*Initialization method:
           1.Execute only once when initialized.  
           2.Receive a parameter of FilterConfig type, which is used to configure filters

be careful:
1. the Filter will be created when the server is started. Only one instance will be created to reside in memory, that is, the init(FilterConfig config) method of the Filter will be executed as soon as the server is started
2. when the Filter is removed or the server is shut down normally, the destroy method will be executed

Multiple filter s:
Multiple filters can be passed between the arrival of our requests to servles. Generally speaking, it is recommended that there should be no association between filters, and that they should handle their own logic. In this way, we don't need to worry about the order of execution. If the execution sequence must be ensured, the configuration must be modified. The execution sequence is as follows

1.stay web.xml Medium, filter Execution sequence follows<filter-mapping>Is related to the order in which the first declaration is executed first
2.Using annotation configuration, filter The execution order of is related to the alphabetical order of names, for example AFilter Will compare BFilter Execute first
3.If the existing web.xml Declared in Filter,Also configured by annotation Filter,Then priority will be given to implementation web.xml Configured in Filter  

xss filter function code

Use escapeHtml4 to fi lt er the input string and convert the three characters' < '>' * 'into HTML encoding format < & > Prevent malicious HTML injection attacks.

  private String clearXss(String html){
    		return html;
    	html = StringEscapeUtils.escapeHtml4(html);//For untrusted input, the
        // apache.commons.lang3.StringEscapeUtils
        // Fi lt er the input string and convert the three characters' < '>' * 'into HTML encoding format < & > Protect against malicious HTML injection attacks:
    	html = StringUtil.escapeHtml(html);
    	return html;

Filter request strings

    public String getQueryString() {  
        return clearXss(super.getQueryString());  

Filter parameters

    public String[] getParameterValues(String name) {  
        String[] values = super.getParameterValues(name);  
        if(values != null) {  
            int length = values.length;  
            String[] escapseValues = new String[length];  
            for(int i = 0; i < length; i++){  
                escapseValues[i] = clearXss(values[i]);  
            return escapseValues;  
        return super.getParameterValues(name);  

XSS filter execution

Put it after the permission filter, so add order (2) before it; Then initialize, execute and destroy the filter. Generally, a filter is a chain, web There are just a few configured in XML. One by one
request -> filter1 -> filter2 ->filter3 -> …. -> request resource; chain. The dofilter forwards the request to the next filter in the filter chain. If there is no filter, it is the resource you requested.

@Order(2)//Load sequence, post load (second)
@WebFilter(urlPatterns = "/*", filterName = "xssFilter")
public class XssFilter implements Filter {
    public void init(FilterConfig filterConfig) {
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        chain.doFilter(new XssHttpServletRequestWrapper((HttpServletRequest) request), response);
    public void destroy() {  

Tags: security Web Security xss

Posted by FrozNic on Sat, 04 Jun 2022 03:16:28 +0530